koch.nim 31 KB

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