koch.nim 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. #
  2. #
  3. # Maintenance program for Nim
  4. # (c) Copyright 2017 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # See doc/koch.txt for documentation.
  10. #
  11. const
  12. # examples of possible values for repos: Head, ea82b54
  13. NimbleStableCommit = "168416290e49023894fc26106799d6f1fc964a2d" # master
  14. AtlasStableCommit = "7b780811a168f3f32bff4822369dda46a7f87f9a"
  15. ChecksumsStableCommit = "b4c73320253f78e3a265aec6d9e8feb83f97c77b"
  16. # examples of possible values for fusion: #head, #ea82b54, 1.2.3
  17. FusionStableHash = "#372ee4313827ef9f2ea388840f7d6b46c2b1b014"
  18. HeadHash = "#head"
  19. when not defined(windows):
  20. const
  21. Z3StableCommit = "65de3f748a6812eecd7db7c478d5fc54424d368b" # the version of Z3 that DrNim uses
  22. when defined(gcc) and defined(windows):
  23. when defined(x86):
  24. {.link: "icons/koch.res".}
  25. else:
  26. {.link: "icons/koch_icon.o".}
  27. when defined(amd64) and defined(windows) and defined(vcc):
  28. {.link: "icons/koch-amd64-windows-vcc.res".}
  29. when defined(i386) and defined(windows) and defined(vcc):
  30. {.link: "icons/koch-i386-windows-vcc.res".}
  31. import std/[os, strutils, parseopt, osproc]
  32. # Using `std/os` instead of `os` to fail early if config isn't set up properly.
  33. # If this fails with: `Error: cannot open file: std/os`, see
  34. # https://github.com/nim-lang/Nim/pull/14291 for explanation + how to fix.
  35. when defined(nimPreviewSlimSystem):
  36. import std/[assertions, syncio]
  37. import tools / kochdocs
  38. import tools / deps
  39. const VersionAsString = system.NimVersion
  40. const
  41. HelpText = """
  42. +-----------------------------------------------------------------+
  43. | Maintenance program for Nim |
  44. | Version $1|
  45. | (c) 2017 Andreas Rumpf |
  46. +-----------------------------------------------------------------+
  47. Build time: $2, $3
  48. Usage:
  49. koch [options] command [options for command]
  50. Options:
  51. --help, -h shows this help and quits
  52. --latest bundle the installers with bleeding edge versions of
  53. external components.
  54. --stable bundle the installers with stable versions of
  55. external components (default).
  56. --nim:path use specified path for nim binary
  57. --localdocs[:path] only build local documentations. If a path is not
  58. specified (or empty), the default is used.
  59. --skipIntegrityCheck skips integrity check when booting the compiler
  60. Possible Commands:
  61. boot [options] bootstraps with given command line options
  62. distrohelper [bindir] helper for distro packagers
  63. tools builds Nim related tools
  64. toolsNoExternal builds Nim related tools (except external tools,
  65. e.g. nimble)
  66. doesn't require network connectivity
  67. nimble builds the Nimble tool
  68. atlas builds the Atlas tool
  69. fusion installs fusion via Nimble
  70. Boot options:
  71. -d:release produce a release version of the compiler
  72. -d:nimUseLinenoise use the linenoise library for interactive mode
  73. `nim secret` (not needed on Windows)
  74. -d:leanCompiler produce a compiler without JS codegen or
  75. documentation generator in order to use less RAM
  76. for bootstrapping
  77. Commands for core developers:
  78. runCI runs continuous integration (CI), e.g. from Github Actions
  79. docs [options] generates the full documentation
  80. csource -d:danger builds the C sources for installation
  81. pdf builds the PDF documentation
  82. zip builds the installation zip package
  83. xz builds the installation tar.xz package
  84. testinstall test tar.xz package; Unix only!
  85. installdeps [options] installs external dependency (e.g. tinyc) to dist/
  86. tests [options] run the testsuite (run a subset of tests by
  87. specifying a category, e.g. `tests cat async`)
  88. temp options creates a temporary compiler for testing
  89. """
  90. let kochExe* = when isMainModule: os.getAppFilename() # always correct when koch is main program, even if `koch` exe renamed e.g.: `nim c -o:koch_debug koch.nim`
  91. else: getAppDir() / "koch".exe # works for winrelease
  92. proc kochExec*(cmd: string) =
  93. exec kochExe.quoteShell & " " & cmd
  94. proc kochExecFold*(desc, cmd: string) =
  95. execFold(desc, kochExe.quoteShell & " " & cmd)
  96. template withDir(dir, body) =
  97. let old = getCurrentDir()
  98. try:
  99. setCurrentDir(dir)
  100. body
  101. finally:
  102. setCurrentDir(old)
  103. let origDir = getCurrentDir()
  104. setCurrentDir(getAppDir())
  105. proc tryExec(cmd: string): bool =
  106. echo(cmd)
  107. result = execShellCmd(cmd) == 0
  108. proc safeRemove(filename: string) =
  109. if fileExists(filename): removeFile(filename)
  110. proc overwriteFile(source, dest: string) =
  111. safeRemove(dest)
  112. moveFile(source, dest)
  113. proc copyExe(source, dest: string) =
  114. safeRemove(dest)
  115. copyFile(dest=dest, source=source)
  116. inclFilePermissions(dest, {fpUserExec, fpGroupExec, fpOthersExec})
  117. const
  118. compileNimInst = "tools/niminst/niminst"
  119. distDir = "dist"
  120. proc csource(args: string) =
  121. nimexec(("cc $1 -r $3 --var:version=$2 --var:mingw=none csource " &
  122. "--main:compiler/nim.nim compiler/installer.ini $1") %
  123. [args, VersionAsString, compileNimInst])
  124. proc bundleC2nim(args: string) =
  125. cloneDependency(distDir, "https://github.com/nim-lang/c2nim.git")
  126. nimCompile("dist/c2nim/c2nim",
  127. options = "--noNimblePath --path:. " & args)
  128. proc bundleNimbleExe(latest: bool, args: string) =
  129. let commit = if latest: "HEAD" else: NimbleStableCommit
  130. cloneDependency(distDir, "https://github.com/nim-lang/nimble.git",
  131. commit = commit, allowBundled = true)
  132. cloneDependency(distDir / "nimble" / distDir, "https://github.com/nim-lang/checksums.git",
  133. commit = ChecksumsStableCommit, allowBundled = true) # or copy it from dist?
  134. # installer.ini expects it under $nim/bin
  135. nimCompile("dist/nimble/src/nimble.nim",
  136. options = "-d:release --mm:refc --noNimblePath " & args)
  137. proc bundleAtlasExe(latest: bool, args: string) =
  138. let commit = if latest: "HEAD" else: AtlasStableCommit
  139. cloneDependency(distDir, "https://github.com/nim-lang/atlas.git",
  140. commit = commit, allowBundled = true)
  141. # installer.ini expects it under $nim/bin
  142. nimCompile("dist/atlas/src/atlas.nim",
  143. options = "-d:release --noNimblePath " & args)
  144. proc bundleNimsuggest(args: string) =
  145. nimCompileFold("Compile nimsuggest", "nimsuggest/nimsuggest.nim",
  146. options = "-d:danger " & args)
  147. proc buildVccTool(args: string) =
  148. let input = "tools/vccexe/vccexe.nim"
  149. if contains(args, "--cc:vcc"):
  150. nimCompileFold("Compile Vcc", input, "build", options = args)
  151. let fileName = input.splitFile.name
  152. moveFile(exe("build" / fileName), exe("bin" / fileName))
  153. else:
  154. nimCompileFold("Compile Vcc", input, options = args)
  155. proc bundleNimpretty(args: string) =
  156. nimCompileFold("Compile nimpretty", "nimpretty/nimpretty.nim",
  157. options = "-d:release " & args)
  158. proc bundleWinTools(args: string) =
  159. nimCompile("tools/finish.nim", outputDir = "", options = args)
  160. buildVccTool(args)
  161. nimCompile("tools/nimgrab.nim", options = "-d:ssl " & args)
  162. nimCompile("tools/nimgrep.nim", options = args)
  163. nimCompile("testament/testament.nim", options = args)
  164. when false:
  165. # not yet a tool worth including
  166. nimCompile(r"tools\downloader.nim",
  167. options = r"--cc:vcc --app:gui -d:ssl --noNimblePath --path:..\ui " & args)
  168. proc bundleChecksums(latest: bool) =
  169. let commit = if latest: "HEAD" else: ChecksumsStableCommit
  170. cloneDependency(distDir, "https://github.com/nim-lang/checksums.git", commit, allowBundled = true)
  171. proc zip(latest: bool; args: string) =
  172. bundleChecksums(latest)
  173. bundleNimbleExe(latest, args)
  174. bundleAtlasExe(latest, args)
  175. bundleNimsuggest(args)
  176. bundleNimpretty(args)
  177. bundleWinTools(args)
  178. nimexec("cc -r $2 --var:version=$1 --var:mingw=none --main:compiler/nim.nim scripts compiler/installer.ini" %
  179. [VersionAsString, compileNimInst])
  180. exec("$# --var:version=$# --var:mingw=none --main:compiler/nim.nim zip compiler/installer.ini" %
  181. ["tools/niminst/niminst".exe, VersionAsString])
  182. proc ensureCleanGit() =
  183. let (outp, status) = osproc.execCmdEx("git diff")
  184. if outp.len != 0:
  185. quit "Not a clean git repository; 'git diff' not empty!"
  186. if status != 0:
  187. quit "Not a clean git repository; 'git diff' returned non-zero!"
  188. proc xz(latest: bool; args: string) =
  189. ensureCleanGit()
  190. nimexec("cc -r $2 --var:version=$1 --var:mingw=none --main:compiler/nim.nim scripts compiler/installer.ini" %
  191. [VersionAsString, compileNimInst])
  192. exec("$# --var:version=$# --var:mingw=none --main:compiler/nim.nim xz compiler/installer.ini" %
  193. ["tools" / "niminst" / "niminst".exe, VersionAsString])
  194. proc buildTool(toolname, args: string) =
  195. nimexec("cc $# $#" % [args, toolname])
  196. copyFile(dest="bin" / splitFile(toolname).name.exe, source=toolname.exe)
  197. proc buildTools(args: string = "") =
  198. bundleNimsuggest(args)
  199. nimCompileFold("Compile nimgrep", "tools/nimgrep.nim",
  200. options = "-d:release " & args)
  201. when defined(windows): buildVccTool(args)
  202. bundleNimpretty(args)
  203. nimCompileFold("Compile testament", "testament/testament.nim", options = "-d:release " & args)
  204. # pre-packages a debug version of nim which can help in many cases investigate issuses
  205. # withouth having to rebuild compiler.
  206. # `-d:nimDebugUtils` only makes sense when temporarily editing/debugging compiler
  207. # `-d:debug` should be changed to a flag that doesn't require re-compiling nim
  208. # `--opt:speed` is a sensible default even for a debug build, it doesn't affect nim stacktraces
  209. nimCompileFold("Compile nim_dbg", "compiler/nim.nim", options =
  210. "--opt:speed --stacktrace -d:debug --stacktraceMsgs -d:nimCompilerStacktraceHints " & args,
  211. outputName = "nim_dbg")
  212. proc testTools(args: string = "") =
  213. nimCompileFold("Compile nimgrep", "tools/nimgrep.nim",
  214. options = "-d:release " & args)
  215. when defined(windows): buildVccTool(args)
  216. bundleNimpretty(args)
  217. nimCompileFold("Compile testament", "testament/testament.nim", options = "-d:release " & args)
  218. proc nsis(latest: bool; args: string) =
  219. bundleChecksums(latest)
  220. bundleNimbleExe(latest, args)
  221. bundleAtlasExe(latest, args)
  222. bundleNimsuggest(args)
  223. bundleWinTools(args)
  224. # make sure we have generated the niminst executables:
  225. buildTool("tools/niminst/niminst", args)
  226. #buildTool("tools/nimgrep", args)
  227. # produce 'nim_debug.exe':
  228. #exec "nim c compiler" / "nim.nim"
  229. #copyExe("compiler/nim".exe, "bin/nim_debug".exe)
  230. exec(("tools" / "niminst" / "niminst --var:version=$# --var:mingw=mingw$#" &
  231. " nsis compiler/installer.ini") % [VersionAsString, $(sizeof(pointer)*8)])
  232. proc geninstall(args="") =
  233. nimexec("cc -r $# --var:version=$# --var:mingw=none --main:compiler/nim.nim scripts compiler/installer.ini $#" %
  234. [compileNimInst, VersionAsString, args])
  235. proc install(args: string) =
  236. geninstall()
  237. exec("sh ./install.sh $#" % args)
  238. # -------------- boot ---------------------------------------------------------
  239. proc findStartNim: string =
  240. # we try several things before giving up:
  241. # * nimExe
  242. # * bin/nim
  243. # * $PATH/nim
  244. # If these fail, we try to build nim with the "build.(sh|bat)" script.
  245. let (nim, ok) = findNimImpl()
  246. if ok: return nim
  247. when defined(posix):
  248. const buildScript = "build.sh"
  249. if fileExists(buildScript):
  250. if tryExec("./" & buildScript): return "bin" / nim
  251. else:
  252. const buildScript = "build.bat"
  253. if fileExists(buildScript):
  254. if tryExec(buildScript): return "bin" / nim
  255. echo("Found no nim compiler and every attempt to build one failed!")
  256. quit("FAILURE")
  257. proc thVersion(i: int): string =
  258. result = ("compiler" / "nim" & $i).exe
  259. template doUseCpp(): bool = getEnv("NIM_COMPILE_TO_CPP", "false") == "true"
  260. proc boot(args: string, skipIntegrityCheck: bool) =
  261. ## bootstrapping is a process that involves 3 steps:
  262. ## 1. use csourcesAny to produce nim1.exe. This nim1.exe is buggy but
  263. ## rock solid for building a Nim compiler. It shouldn't be used for anything else.
  264. ## 2. use nim1.exe to produce nim2.exe. nim2.exe is the one you really need.
  265. ## 3. We use nim2.exe to build nim3.exe. nim3.exe is equal to nim2.exe except for timestamps.
  266. ## This step ensures a minimum amount of quality. We know that nim2.exe can be used
  267. ## for Nim compiler development.
  268. var output = "compiler" / "nim".exe
  269. var finalDest = "bin" / "nim".exe
  270. # default to use the 'c' command:
  271. let useCpp = doUseCpp()
  272. let smartNimcache = (if "release" in args or "danger" in args: "nimcache/r_" else: "nimcache/d_") &
  273. hostOS & "_" & hostCPU
  274. if not dirExists("dist/checksums"):
  275. bundleChecksums(false)
  276. let nimStart = findStartNim().quoteShell()
  277. let times = 2 - ord(skipIntegrityCheck)
  278. for i in 0..times:
  279. let defaultCommand = if useCpp: "cpp" else: "c"
  280. let bootOptions = if args.len == 0 or args.startsWith("-"): defaultCommand else: ""
  281. echo "iteration: ", i+1
  282. var extraOption = ""
  283. var nimi = i.thVersion
  284. if i == 0:
  285. nimi = nimStart
  286. extraOption.add " --skipUserCfg --skipParentCfg -d:nimKochBootstrap"
  287. # The configs are skipped for bootstrap
  288. # (1st iteration) to prevent newer flags from breaking bootstrap phase.
  289. let ret = execCmdEx(nimStart & " --version")
  290. doAssert ret.exitCode == 0
  291. let version = ret.output.splitLines[0]
  292. if version.startsWith "Nim Compiler Version 0.20.0":
  293. extraOption.add " --lib:lib" # see https://github.com/nim-lang/Nim/pull/14291
  294. # in order to use less memory, we split the build into two steps:
  295. # --compileOnly produces a $project.json file and does not run GCC/Clang.
  296. # jsonbuild then uses the $project.json file to build the Nim binary.
  297. exec "$# $# $# --nimcache:$# $# --noNimblePath --compileOnly compiler" / "nim.nim" %
  298. [nimi, bootOptions, extraOption, smartNimcache, args]
  299. exec "$# jsonscript --noNimblePath --nimcache:$# $# compiler" / "nim.nim" %
  300. [nimi, smartNimcache, args]
  301. if sameFileContent(output, i.thVersion):
  302. copyExe(output, finalDest)
  303. echo "executables are equal: SUCCESS!"
  304. return
  305. copyExe(output, (i+1).thVersion)
  306. copyExe(output, finalDest)
  307. when not defined(windows):
  308. if not skipIntegrityCheck:
  309. echo "[Warning] executables are still not equal"
  310. # -------------- clean --------------------------------------------------------
  311. const
  312. cleanExt = [
  313. ".ppu", ".o", ".obj", ".dcu", ".~pas", ".~inc", ".~dsk", ".~dpr",
  314. ".map", ".tds", ".err", ".bak", ".pyc", ".exe", ".rod", ".pdb", ".idb",
  315. ".idx", ".ilk"
  316. ]
  317. ignore = [
  318. ".bzrignore", "nim", "nim.exe", "koch", "koch.exe", ".gitignore"
  319. ]
  320. proc cleanAux(dir: string) =
  321. for kind, path in walkDir(dir):
  322. case kind
  323. of pcFile:
  324. var (_, name, ext) = splitFile(path)
  325. if ext == "" or cleanExt.contains(ext):
  326. if not ignore.contains(name):
  327. echo "removing: ", path
  328. removeFile(path)
  329. of pcDir:
  330. case splitPath(path).tail
  331. of "nimcache":
  332. echo "removing dir: ", path
  333. removeDir(path)
  334. of "dist", ".git", "icons": discard
  335. else: cleanAux(path)
  336. else: discard
  337. proc removePattern(pattern: string) =
  338. for f in walkFiles(pattern):
  339. echo "removing: ", f
  340. removeFile(f)
  341. proc clean(args: string) =
  342. removePattern("web/*.html")
  343. removePattern("doc/*.html")
  344. cleanAux(getCurrentDir())
  345. for kind, path in walkDir(getCurrentDir() / "build"):
  346. if kind == pcDir:
  347. echo "removing dir: ", path
  348. removeDir(path)
  349. # -------------- builds a release ---------------------------------------------
  350. proc winReleaseArch(arch: string) =
  351. doAssert arch in ["32", "64"]
  352. let cpu = if arch == "32": "i386" else: "amd64"
  353. template withMingw(path, body) =
  354. let prevPath = getEnv("PATH")
  355. putEnv("PATH", (if path.len > 0: path & PathSep else: "") & prevPath)
  356. try:
  357. body
  358. finally:
  359. putEnv("PATH", prevPath)
  360. withMingw r"..\mingw" & arch & r"\bin":
  361. # Rebuilding koch is necessary because it uses its pointer size to
  362. # determine which mingw link to put in the NSIS installer.
  363. inFold "winrelease koch":
  364. nimexec "c --cpu:$# koch" % cpu
  365. kochExecFold("winrelease boot", "boot -d:release --cpu:$#" % cpu)
  366. kochExecFold("winrelease zip", "zip -d:release")
  367. overwriteFile r"build\nim-$#.zip" % VersionAsString,
  368. r"web\upload\download\nim-$#_x$#.zip" % [VersionAsString, arch]
  369. proc winRelease*() =
  370. # Now used from "tools/winrelease" and not directly supported by koch
  371. # anymore!
  372. # Build -docs file:
  373. when true:
  374. inFold "winrelease buildDocs":
  375. buildDocs(gaCode)
  376. withDir "web/upload/" & VersionAsString:
  377. inFold "winrelease zipdocs":
  378. exec "7z a -tzip docs-$#.zip *.html" % VersionAsString
  379. overwriteFile "web/upload/$1/docs-$1.zip" % VersionAsString,
  380. "web/upload/download/docs-$1.zip" % VersionAsString
  381. when true:
  382. inFold "winrelease csource":
  383. csource("-d:danger")
  384. when sizeof(pointer) == 4:
  385. winReleaseArch "32"
  386. when sizeof(pointer) == 8:
  387. winReleaseArch "64"
  388. # -------------- tests --------------------------------------------------------
  389. template `|`(a, b): string = (if a.len > 0: a else: b)
  390. proc tests(args: string) =
  391. nimexec "cc --opt:speed testament/testament"
  392. var testCmd = quoteShell(getCurrentDir() / "testament/testament".exe)
  393. testCmd.add " " & quoteShell("--nim:" & findNim())
  394. testCmd.add " " & (args|"all")
  395. let success = tryExec testCmd
  396. if not success:
  397. quit("tests failed", QuitFailure)
  398. proc temp(args: string) =
  399. proc splitArgs(a: string): (string, string) =
  400. # every --options before the command (indicated by starting
  401. # with not a dash) is part of the bootArgs, the rest is part
  402. # of the programArgs:
  403. let args = os.parseCmdLine a
  404. result = ("", "")
  405. var i = 0
  406. while i < args.len and args[i][0] == '-':
  407. result[0].add " " & quoteShell(args[i])
  408. inc i
  409. while i < args.len:
  410. result[1].add " " & quoteShell(args[i])
  411. inc i
  412. if not dirExists("dist/checksums"):
  413. bundleChecksums(false)
  414. let d = getAppDir()
  415. let output = d / "compiler" / "nim".exe
  416. let finalDest = d / "bin" / "nim_temp".exe
  417. # 125 is the magic number to tell git bisect to skip the current commit.
  418. var (bootArgs, programArgs) = splitArgs(args)
  419. if "doc" notin programArgs and
  420. "threads" notin programArgs and
  421. "js" notin programArgs and "rst2html" notin programArgs:
  422. bootArgs = " -d:leanCompiler" & bootArgs
  423. let nimexec = findNim().quoteShell()
  424. exec(nimexec & " c -d:debug --debugger:native -d:nimBetterRun " & bootArgs & " " & (d / "compiler" / "nim"), 125)
  425. copyExe(output, finalDest)
  426. setCurrentDir(origDir)
  427. if programArgs.len > 0: exec(finalDest & " " & programArgs)
  428. proc xtemp(cmd: string) =
  429. let d = getAppDir()
  430. copyExe(d / "bin" / "nim".exe, d / "bin" / "nim_backup".exe)
  431. try:
  432. withDir(d):
  433. temp""
  434. copyExe(d / "bin" / "nim_temp".exe, d / "bin" / "nim".exe)
  435. exec(cmd)
  436. finally:
  437. copyExe(d / "bin" / "nim_backup".exe, d / "bin" / "nim".exe)
  438. proc icTest(args: string) =
  439. temp("")
  440. let inp = os.parseCmdLine(args)[0]
  441. let content = readFile(inp)
  442. let nimExe = getAppDir() / "bin" / "nim_temp".exe
  443. var i = 0
  444. for fragment in content.split("#!EDIT!#"):
  445. let file = inp.replace(".nim", "_temp.nim")
  446. writeFile(file, fragment)
  447. var cmd = nimExe & " cpp --ic:on -d:nimIcIntegrityChecks --listcmd "
  448. if i == 0:
  449. cmd.add "-f "
  450. cmd.add quoteShell(file)
  451. exec(cmd)
  452. inc i
  453. proc buildDrNim(args: string) =
  454. if not dirExists("dist/nimz3"):
  455. exec("git clone https://github.com/zevv/nimz3.git dist/nimz3")
  456. when defined(windows):
  457. if not dirExists("dist/dlls"):
  458. exec("git clone -q https://github.com/nim-lang/dlls.git dist/dlls")
  459. copyExe("dist/dlls/libz3.dll", "bin/libz3.dll")
  460. execFold("build drnim", "nim c -o:$1 $2 drnim/drnim" % ["bin/drnim".exe, args])
  461. else:
  462. if not dirExists("dist/z3"):
  463. exec("git clone -q https://github.com/Z3Prover/z3.git dist/z3")
  464. withDir("dist/z3"):
  465. exec("git fetch")
  466. exec("git checkout " & Z3StableCommit)
  467. createDir("build")
  468. withDir("build"):
  469. exec("""cmake -DZ3_BUILD_LIBZ3_SHARED=FALSE -G "Unix Makefiles" ../""")
  470. exec("make -j4")
  471. execFold("build drnim", "nim cpp --dynlibOverride=libz3 -o:$1 $2 drnim/drnim" % ["bin/drnim".exe, args])
  472. # always run the tests for now:
  473. exec("testament/testament".exe & " --nim:" & "drnim".exe & " pat drnim/tests")
  474. proc hostInfo(): string =
  475. "hostOS: $1, hostCPU: $2, int: $3, float: $4, cpuEndian: $5, cwd: $6" %
  476. [hostOS, hostCPU, $int.sizeof, $float.sizeof, $cpuEndian, getCurrentDir()]
  477. proc installDeps(dep: string, commit = "") =
  478. # the hashes/urls are version controlled here, so can be changed seamlessly
  479. # and tied to a nim release (mimicking git submodules)
  480. var commit = commit
  481. case dep
  482. of "tinyc":
  483. if commit.len == 0: commit = "916cc2f94818a8a382dd8d4b8420978816c1dfb3"
  484. cloneDependency(distDir, "https://github.com/timotheecour/nim-tinyc-archive", commit)
  485. else: doAssert false, "unsupported: " & dep
  486. # xxx: also add linenoise, niminst etc, refs https://github.com/nim-lang/RFCs/issues/206
  487. proc runCI(cmd: string) =
  488. doAssert cmd.len == 0, cmd # avoid silently ignoring
  489. echo "runCI: ", cmd
  490. echo hostInfo()
  491. # boot without -d:nimHasLibFFI to make sure this still works
  492. # `--lib:lib` is needed for bootstrap on openbsd, for reasons described in
  493. # https://github.com/nim-lang/Nim/pull/14291 (`getAppFilename` bugsfor older nim on openbsd).
  494. kochExecFold("Boot Nim ORC", "boot -d:release -d:nimStrictMode --lib:lib")
  495. when false: # debugging: when you need to run only 1 test in CI, use something like this:
  496. execFold("debugging test", "nim r tests/stdlib/tosproc.nim")
  497. doAssert false, "debugging only"
  498. ## build nimble early on to enable remainder to depend on it if needed
  499. kochExecFold("Build Nimble", "nimble")
  500. execFold("Install smtp", "nimble install smtp -y")
  501. let batchParam = "--batch:$1" % "NIM_TESTAMENT_BATCH".getEnv("_")
  502. if getEnv("NIM_TEST_PACKAGES", "0") == "1":
  503. nimCompileFold("Compile testament", "testament/testament.nim", options = "-d:release")
  504. execFold("Test selected Nimble packages", "testament $# pcat nimble-packages" % batchParam)
  505. else:
  506. testTools()
  507. for a in "zip opengl sdl1 jester@#head".split:
  508. let buildDeps = "build"/"deps" # xxx factor pending https://github.com/timotheecour/Nim/issues/616
  509. # if this gives `Additional info: "build/deps" [OSError]`, make sure nimble is >= v0.12.0,
  510. # otherwise `absolutePath` is needed, refs https://github.com/nim-lang/nimble/issues/901
  511. execFold("", "nimble install -y --nimbleDir:$# $#" % [buildDeps.quoteShell, a])
  512. ## run tests
  513. execFold("Test nimscript", "nim e tests/test_nimscript.nims")
  514. when defined(windows):
  515. execFold("Compile tester", "nim c --usenimcache -d:nimCoroutines --os:genode -d:posix --compileOnly testament/testament")
  516. # main bottleneck here
  517. # xxx: even though this is the main bottleneck, we could speedup the rest via batching with `--batch`.
  518. # BUG: with initOptParser, `--batch:'' all` interprets `all` as the argument of --batch, pending bug #14343
  519. execFold("Run tester", "nim c -r --putenv:NIM_TESTAMENT_REMOTE_NETWORKING:1 -d:nimStrictMode testament/testament $# all -d:nimCoroutines" % batchParam)
  520. block: # nimHasLibFFI:
  521. when defined(posix): # windows can be handled in future PR's
  522. execFold("nimble install -y libffi", "nimble install -y libffi")
  523. const nimFFI = "bin/nim.ctffi"
  524. # no need to bootstrap with koch boot (would be slower)
  525. let backend = if doUseCpp(): "cpp" else: "c"
  526. execFold("build with -d:nimHasLibFFI", "nim $1 -d:release -d:nimHasLibFFI -o:$2 compiler/nim.nim" % [backend, nimFFI])
  527. execFold("test with -d:nimHasLibFFI", "$1 $2 -r testament/testament --nim:$1 r tests/misc/trunner.nim -d:nimTrunnerFfi" % [nimFFI, backend])
  528. execFold("Run nimdoc tests", "nim r nimdoc/tester")
  529. execFold("Run rst2html tests", "nim r nimdoc/rsttester")
  530. execFold("Run nimpretty tests", "nim r nimpretty/tester.nim")
  531. when defined(posix):
  532. # refs #18385, build with -d:release instead of -d:danger for testing
  533. # We could also skip building nimsuggest in buildTools, or build it with -d:release
  534. # in bundleNimsuggest depending on some environment variable when we are in CI. One advantage
  535. # of rebuilding is this won't affect bin/nimsuggest when running runCI locally
  536. execFold("build nimsuggest_testing", "nim c -o:bin/nimsuggest_testing -d:release nimsuggest/nimsuggest")
  537. execFold("Run nimsuggest tests", "nim r nimsuggest/tester")
  538. kochExecFold("Testing booting in refc", "boot -d:release --mm:refc -d:nimStrictMode --lib:lib")
  539. proc testUnixInstall(cmdLineRest: string) =
  540. csource("-d:danger" & cmdLineRest)
  541. xz(false, cmdLineRest)
  542. let oldCurrentDir = getCurrentDir()
  543. try:
  544. let destDir = getTempDir()
  545. copyFile("build/nim-$1.tar.xz" % VersionAsString,
  546. destDir / "nim-$1.tar.xz" % VersionAsString)
  547. setCurrentDir(destDir)
  548. execCleanPath("tar -xJf nim-$1.tar.xz" % VersionAsString)
  549. setCurrentDir("nim-$1" % VersionAsString)
  550. execCleanPath("sh build.sh")
  551. # first test: try if './bin/nim --version' outputs something sane:
  552. let output = execProcess("./bin/nim --version").splitLines
  553. if output.len > 0 and output[0].contains(VersionAsString):
  554. echo "Version check: success"
  555. execCleanPath("./bin/nim c koch.nim")
  556. execCleanPath("./koch boot -d:release", destDir / "bin")
  557. # check the docs build:
  558. execCleanPath("./koch docs", destDir / "bin")
  559. # check nimble builds:
  560. execCleanPath("./koch tools")
  561. # check the tests work:
  562. putEnv("NIM_EXE_NOT_IN_PATH", "NOT_IN_PATH")
  563. execCleanPath("./koch tests --nim:bin/nim cat megatest", destDir / "bin")
  564. else:
  565. echo "Version check: failure"
  566. finally:
  567. setCurrentDir oldCurrentDir
  568. proc valgrind(cmd: string) =
  569. # somewhat hacky: '=' sign means "pass to valgrind" else "pass to Nim"
  570. let args = parseCmdLine(cmd)
  571. var nimcmd = ""
  572. var valcmd = ""
  573. for i, a in args:
  574. if i == args.len-1:
  575. # last element is the filename:
  576. valcmd.add ' '
  577. valcmd.add changeFileExt(a, ExeExt)
  578. nimcmd.add ' '
  579. nimcmd.add a
  580. elif '=' in a:
  581. valcmd.add ' '
  582. valcmd.add a
  583. else:
  584. nimcmd.add ' '
  585. nimcmd.add a
  586. exec("nim c" & nimcmd)
  587. let supp = getAppDir() / "tools" / "nimgrind.supp"
  588. exec("valgrind --suppressions=" & supp & valcmd)
  589. proc showHelp(success: bool) =
  590. quit(HelpText % [VersionAsString & spaces(44-len(VersionAsString)),
  591. CompileDate, CompileTime], if success: QuitSuccess else: QuitFailure)
  592. proc branchDone() =
  593. let thisBranch = execProcess("git symbolic-ref --short HEAD").strip()
  594. if thisBranch != "devel" and thisBranch != "":
  595. exec("git checkout devel")
  596. exec("git branch -D " & thisBranch)
  597. exec("git pull --rebase")
  598. when isMainModule:
  599. var op = initOptParser()
  600. var
  601. latest = false
  602. localDocsOnly = false
  603. localDocsOut = ""
  604. skipIntegrityCheck = false
  605. while true:
  606. op.next()
  607. case op.kind
  608. of cmdLongOption, cmdShortOption:
  609. case normalize(op.key)
  610. of "help", "h": showHelp(success = true)
  611. of "latest": latest = true
  612. of "stable": latest = false
  613. of "nim": nimExe = op.val.absolutePath # absolute so still works with changeDir
  614. of "localdocs":
  615. localDocsOnly = true
  616. if op.val.len > 0:
  617. localDocsOut = op.val.absolutePath
  618. of "skipintegritycheck":
  619. skipIntegrityCheck = true
  620. else: showHelp(success = false)
  621. of cmdArgument:
  622. case normalize(op.key)
  623. of "boot": boot(op.cmdLineRest, skipIntegrityCheck)
  624. of "clean": clean(op.cmdLineRest)
  625. of "doc", "docs": buildDocs(op.cmdLineRest & " --d:nimPreviewSlimSystem " & paCode, localDocsOnly, localDocsOut)
  626. of "doc0", "docs0":
  627. # undocumented command for Araq-the-merciful:
  628. buildDocs(op.cmdLineRest & gaCode)
  629. of "pdf": buildPdfDoc(op.cmdLineRest, "doc/pdf")
  630. of "csource", "csources": csource(op.cmdLineRest)
  631. of "zip": zip(latest, op.cmdLineRest)
  632. of "xz": xz(latest, op.cmdLineRest)
  633. of "nsis": nsis(latest, op.cmdLineRest)
  634. of "geninstall": geninstall(op.cmdLineRest)
  635. of "distrohelper": geninstall()
  636. of "install": install(op.cmdLineRest)
  637. of "testinstall": testUnixInstall(op.cmdLineRest)
  638. of "installdeps": installDeps(op.cmdLineRest)
  639. of "runci": runCI(op.cmdLineRest)
  640. of "test", "tests": tests(op.cmdLineRest)
  641. of "temp": temp(op.cmdLineRest)
  642. of "xtemp": xtemp(op.cmdLineRest)
  643. of "wintools": bundleWinTools(op.cmdLineRest)
  644. of "nimble": bundleNimbleExe(latest, op.cmdLineRest)
  645. of "atlas": bundleAtlasExe(latest, op.cmdLineRest)
  646. of "nimsuggest": bundleNimsuggest(op.cmdLineRest)
  647. # toolsNoNimble is kept for backward compatibility with build scripts
  648. of "toolsnonimble", "toolsnoexternal":
  649. buildTools(op.cmdLineRest)
  650. of "tools":
  651. buildTools(op.cmdLineRest)
  652. bundleNimbleExe(latest, op.cmdLineRest)
  653. bundleAtlasExe(latest, op.cmdLineRest)
  654. of "checksums":
  655. bundleChecksums(latest)
  656. of "pushcsource":
  657. quit "use this instead: https://github.com/nim-lang/csources_v1/blob/master/push_c_code.nim"
  658. of "valgrind": valgrind(op.cmdLineRest)
  659. of "c2nim": bundleC2nim(op.cmdLineRest)
  660. of "drnim": buildDrNim(op.cmdLineRest)
  661. of "fusion":
  662. let suffix = if latest: HeadHash else: FusionStableHash
  663. exec("nimble install -y fusion@$#" % suffix)
  664. of "ic": icTest(op.cmdLineRest)
  665. of "branchdone": branchDone()
  666. else: showHelp(success = false)
  667. break
  668. of cmdEnd:
  669. showHelp(success = false)