koch.nim 31 KB

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