koch.nim 29 KB

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