koch.nim 29 KB

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