koch.nim 28 KB

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