koch.nim 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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 = "afd03bc000f4013c48f52381728327dabfccfc4c" # 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. # Nim versions < (1, 1) expect Nim's exception type to have a 'raiseId' field for
  252. # C++ interop. Later Nim versions do this differently and removed the 'raiseId' field.
  253. # Thus we always bootstrap the first iteration with "c" and not with "cpp" as
  254. # a workaround.
  255. let defaultCommand = if useCpp and i > 0: "cpp" else: "c"
  256. let bootOptions = if args.len == 0 or args.startsWith("-"): defaultCommand else: ""
  257. echo "iteration: ", i+1
  258. var extraOption = ""
  259. var nimi = i.thVersion
  260. if i == 0:
  261. nimi = nimStart
  262. extraOption.add " --skipUserCfg --skipParentCfg -d:nimKochBootstrap"
  263. # The configs are skipped for bootstrap
  264. # (1st iteration) to prevent newer flags from breaking bootstrap phase.
  265. let ret = execCmdEx(nimStart & " --version")
  266. doAssert ret.exitCode == 0
  267. let version = ret.output.splitLines[0]
  268. if version.startsWith "Nim Compiler Version 0.20.0":
  269. extraOption.add " --lib:lib" # see https://github.com/nim-lang/Nim/pull/14291
  270. # in order to use less memory, we split the build into two steps:
  271. # --compileOnly produces a $project.json file and does not run GCC/Clang.
  272. # jsonbuild then uses the $project.json file to build the Nim binary.
  273. exec "$# $# $# --nimcache:$# $# --noNimblePath --compileOnly compiler" / "nim.nim" %
  274. [nimi, bootOptions, extraOption, smartNimcache, args]
  275. exec "$# jsonscript --noNimblePath --nimcache:$# $# compiler" / "nim.nim" %
  276. [nimi, smartNimcache, args]
  277. if sameFileContent(output, i.thVersion):
  278. copyExe(output, finalDest)
  279. echo "executables are equal: SUCCESS!"
  280. return
  281. copyExe(output, (i+1).thVersion)
  282. copyExe(output, finalDest)
  283. when not defined(windows): echo "[Warning] executables are still not equal"
  284. # -------------- clean --------------------------------------------------------
  285. const
  286. cleanExt = [
  287. ".ppu", ".o", ".obj", ".dcu", ".~pas", ".~inc", ".~dsk", ".~dpr",
  288. ".map", ".tds", ".err", ".bak", ".pyc", ".exe", ".rod", ".pdb", ".idb",
  289. ".idx", ".ilk"
  290. ]
  291. ignore = [
  292. ".bzrignore", "nim", "nim.exe", "koch", "koch.exe", ".gitignore"
  293. ]
  294. proc cleanAux(dir: string) =
  295. for kind, path in walkDir(dir):
  296. case kind
  297. of pcFile:
  298. var (_, name, ext) = splitFile(path)
  299. if ext == "" or cleanExt.contains(ext):
  300. if not ignore.contains(name):
  301. echo "removing: ", path
  302. removeFile(path)
  303. of pcDir:
  304. case splitPath(path).tail
  305. of "nimcache":
  306. echo "removing dir: ", path
  307. removeDir(path)
  308. of "dist", ".git", "icons": discard
  309. else: cleanAux(path)
  310. else: discard
  311. proc removePattern(pattern: string) =
  312. for f in walkFiles(pattern):
  313. echo "removing: ", f
  314. removeFile(f)
  315. proc clean(args: string) =
  316. removePattern("web/*.html")
  317. removePattern("doc/*.html")
  318. cleanAux(getCurrentDir())
  319. for kind, path in walkDir(getCurrentDir() / "build"):
  320. if kind == pcDir:
  321. echo "removing dir: ", path
  322. removeDir(path)
  323. # -------------- builds a release ---------------------------------------------
  324. proc winReleaseArch(arch: string) =
  325. doAssert arch in ["32", "64"]
  326. let cpu = if arch == "32": "i386" else: "amd64"
  327. template withMingw(path, body) =
  328. let prevPath = getEnv("PATH")
  329. putEnv("PATH", (if path.len > 0: path & PathSep else: "") & prevPath)
  330. try:
  331. body
  332. finally:
  333. putEnv("PATH", prevPath)
  334. withMingw r"..\mingw" & arch & r"\bin":
  335. # Rebuilding koch is necessary because it uses its pointer size to
  336. # determine which mingw link to put in the NSIS installer.
  337. inFold "winrelease koch":
  338. nimexec "c --cpu:$# koch" % cpu
  339. kochExecFold("winrelease boot", "boot -d:release --cpu:$#" % cpu)
  340. kochExecFold("winrelease zip", "zip -d:release")
  341. overwriteFile r"build\nim-$#.zip" % VersionAsString,
  342. r"web\upload\download\nim-$#_x$#.zip" % [VersionAsString, arch]
  343. proc winRelease*() =
  344. # Now used from "tools/winrelease" and not directly supported by koch
  345. # anymore!
  346. # Build -docs file:
  347. when true:
  348. inFold "winrelease buildDocs":
  349. buildDocs(gaCode)
  350. withDir "web/upload/" & VersionAsString:
  351. inFold "winrelease zipdocs":
  352. exec "7z a -tzip docs-$#.zip *.html" % VersionAsString
  353. overwriteFile "web/upload/$1/docs-$1.zip" % VersionAsString,
  354. "web/upload/download/docs-$1.zip" % VersionAsString
  355. when true:
  356. inFold "winrelease csource":
  357. csource("-d:danger")
  358. when sizeof(pointer) == 4:
  359. winReleaseArch "32"
  360. when sizeof(pointer) == 8:
  361. winReleaseArch "64"
  362. # -------------- tests --------------------------------------------------------
  363. template `|`(a, b): string = (if a.len > 0: a else: b)
  364. proc tests(args: string) =
  365. nimexec "cc --opt:speed testament/testament"
  366. var testCmd = quoteShell(getCurrentDir() / "testament/testament".exe)
  367. testCmd.add " " & quoteShell("--nim:" & findNim())
  368. testCmd.add " " & (args|"all")
  369. let success = tryExec testCmd
  370. if not success:
  371. quit("tests failed", QuitFailure)
  372. proc temp(args: string) =
  373. proc splitArgs(a: string): (string, string) =
  374. # every --options before the command (indicated by starting
  375. # with not a dash) is part of the bootArgs, the rest is part
  376. # of the programArgs:
  377. let args = os.parseCmdLine a
  378. result = ("", "")
  379. var i = 0
  380. while i < args.len and args[i][0] == '-':
  381. result[0].add " " & quoteShell(args[i])
  382. inc i
  383. while i < args.len:
  384. result[1].add " " & quoteShell(args[i])
  385. inc i
  386. let d = getAppDir()
  387. let output = d / "compiler" / "nim".exe
  388. let finalDest = d / "bin" / "nim_temp".exe
  389. # 125 is the magic number to tell git bisect to skip the current commit.
  390. var (bootArgs, programArgs) = splitArgs(args)
  391. if "doc" notin programArgs and
  392. "threads" notin programArgs and
  393. "js" notin programArgs and "rst2html" notin programArgs:
  394. bootArgs = " -d:leanCompiler" & bootArgs
  395. let nimexec = findNim().quoteShell()
  396. exec(nimexec & " c -d:debug --debugger:native -d:nimBetterRun " & bootArgs & " " & (d / "compiler" / "nim"), 125)
  397. copyExe(output, finalDest)
  398. setCurrentDir(origDir)
  399. if programArgs.len > 0: exec(finalDest & " " & programArgs)
  400. proc xtemp(cmd: string) =
  401. let d = getAppDir()
  402. copyExe(d / "bin" / "nim".exe, d / "bin" / "nim_backup".exe)
  403. try:
  404. withDir(d):
  405. temp""
  406. copyExe(d / "bin" / "nim_temp".exe, d / "bin" / "nim".exe)
  407. exec(cmd)
  408. finally:
  409. copyExe(d / "bin" / "nim_backup".exe, d / "bin" / "nim".exe)
  410. proc icTest(args: string) =
  411. temp("")
  412. let inp = os.parseCmdLine(args)[0]
  413. let content = readFile(inp)
  414. let nimExe = getAppDir() / "bin" / "nim_temp".exe
  415. var i = 0
  416. for fragment in content.split("#!EDIT!#"):
  417. let file = inp.replace(".nim", "_temp.nim")
  418. writeFile(file, fragment)
  419. var cmd = nimExe & " cpp --ic:on -d:nimIcIntegrityChecks --listcmd "
  420. if i == 0:
  421. cmd.add "-f "
  422. cmd.add quoteShell(file)
  423. exec(cmd)
  424. inc i
  425. proc buildDrNim(args: string) =
  426. if not dirExists("dist/nimz3"):
  427. exec("git clone https://github.com/zevv/nimz3.git dist/nimz3")
  428. when defined(windows):
  429. if not dirExists("dist/dlls"):
  430. exec("git clone -q https://github.com/nim-lang/dlls.git dist/dlls")
  431. copyExe("dist/dlls/libz3.dll", "bin/libz3.dll")
  432. execFold("build drnim", "nim c -o:$1 $2 drnim/drnim" % ["bin/drnim".exe, args])
  433. else:
  434. if not dirExists("dist/z3"):
  435. exec("git clone -q https://github.com/Z3Prover/z3.git dist/z3")
  436. withDir("dist/z3"):
  437. exec("git fetch")
  438. exec("git checkout " & Z3StableCommit)
  439. createDir("build")
  440. withDir("build"):
  441. exec("""cmake -DZ3_BUILD_LIBZ3_SHARED=FALSE -G "Unix Makefiles" ../""")
  442. exec("make -j4")
  443. execFold("build drnim", "nim cpp --dynlibOverride=libz3 -o:$1 $2 drnim/drnim" % ["bin/drnim".exe, args])
  444. # always run the tests for now:
  445. exec("testament/testament".exe & " --nim:" & "drnim".exe & " pat drnim/tests")
  446. proc hostInfo(): string =
  447. "hostOS: $1, hostCPU: $2, int: $3, float: $4, cpuEndian: $5, cwd: $6" %
  448. [hostOS, hostCPU, $int.sizeof, $float.sizeof, $cpuEndian, getCurrentDir()]
  449. proc installDeps(dep: string, commit = "") =
  450. # the hashes/urls are version controlled here, so can be changed seamlessly
  451. # and tied to a nim release (mimicking git submodules)
  452. var commit = commit
  453. case dep
  454. of "tinyc":
  455. if commit.len == 0: commit = "916cc2f94818a8a382dd8d4b8420978816c1dfb3"
  456. cloneDependency(distDir, "https://github.com/timotheecour/nim-tinyc-archive", commit)
  457. else: doAssert false, "unsupported: " & dep
  458. # xxx: also add linenoise, niminst etc, refs https://github.com/nim-lang/RFCs/issues/206
  459. proc runCI(cmd: string) =
  460. doAssert cmd.len == 0, cmd # avoid silently ignoring
  461. echo "runCI: ", cmd
  462. echo hostInfo()
  463. # boot without -d:nimHasLibFFI to make sure this still works
  464. # `--lib:lib` is needed for bootstrap on openbsd, for reasons described in
  465. # https://github.com/nim-lang/Nim/pull/14291 (`getAppFilename` bugsfor older nim on openbsd).
  466. kochExecFold("Boot in release mode", "boot -d:release --gc:refc -d:nimStrictMode --lib:lib")
  467. kochExecFold("Boot Nim ORC", "boot -d:release --lib:lib")
  468. when false: # debugging: when you need to run only 1 test in CI, use something like this:
  469. execFold("debugging test", "nim r tests/stdlib/tosproc.nim")
  470. doAssert false, "debugging only"
  471. ## build nimble early on to enable remainder to depend on it if needed
  472. kochExecFold("Build Nimble", "nimble")
  473. execFold("Install smtp", "nimble install smtp -y")
  474. let batchParam = "--batch:$1" % "NIM_TESTAMENT_BATCH".getEnv("_")
  475. if getEnv("NIM_TEST_PACKAGES", "0") == "1":
  476. nimCompileFold("Compile testament", "testament/testament.nim", options = "-d:release")
  477. execFold("Test selected Nimble packages", "testament $# pcat nimble-packages" % batchParam)
  478. else:
  479. buildTools()
  480. for a in "zip opengl sdl1 jester@#head".split:
  481. let buildDeps = "build"/"deps" # xxx factor pending https://github.com/timotheecour/Nim/issues/616
  482. # if this gives `Additional info: "build/deps" [OSError]`, make sure nimble is >= v0.12.0,
  483. # otherwise `absolutePath` is needed, refs https://github.com/nim-lang/nimble/issues/901
  484. execFold("", "nimble install -y --nimbleDir:$# $#" % [buildDeps.quoteShell, a])
  485. ## run tests
  486. execFold("Test nimscript", "nim e tests/test_nimscript.nims")
  487. when defined(windows):
  488. execFold("Compile tester", "nim c --usenimcache -d:nimCoroutines --os:genode -d:posix --compileOnly testament/testament")
  489. # main bottleneck here
  490. # xxx: even though this is the main bottleneck, we could speedup the rest via batching with `--batch`.
  491. # BUG: with initOptParser, `--batch:'' all` interprets `all` as the argument of --batch, pending bug #14343
  492. execFold("Run tester", "nim c -r --putenv:NIM_TESTAMENT_REMOTE_NETWORKING:1 -d:nimStrictMode testament/testament $# all -d:nimCoroutines" % batchParam)
  493. block: # nimHasLibFFI:
  494. when defined(posix): # windows can be handled in future PR's
  495. execFold("nimble install -y libffi", "nimble install -y libffi")
  496. const nimFFI = "bin/nim.ctffi"
  497. # no need to bootstrap with koch boot (would be slower)
  498. let backend = if doUseCpp(): "cpp" else: "c"
  499. execFold("build with -d:nimHasLibFFI", "nim $1 -d:release -d:nimHasLibFFI -o:$2 compiler/nim.nim" % [backend, nimFFI])
  500. execFold("test with -d:nimHasLibFFI", "$1 $2 -r testament/testament --nim:$1 r tests/misc/trunner.nim -d:nimTrunnerFfi" % [nimFFI, backend])
  501. execFold("Run nimdoc tests", "nim r nimdoc/tester")
  502. execFold("Run rst2html tests", "nim r nimdoc/rsttester")
  503. execFold("Run nimpretty tests", "nim r nimpretty/tester.nim")
  504. when defined(posix):
  505. # refs #18385, build with -d:release instead of -d:danger for testing
  506. # We could also skip building nimsuggest in buildTools, or build it with -d:release
  507. # in bundleNimsuggest depending on some environment variable when we are in CI. One advantage
  508. # of rebuilding is this won't affect bin/nimsuggest when running runCI locally
  509. execFold("build nimsuggest_testing", "nim c -o:bin/nimsuggest_testing -d:release nimsuggest/nimsuggest")
  510. execFold("Run nimsuggest tests", "nim r nimsuggest/tester")
  511. execFold("Run atlas tests", "nim c -r -d:atlasTests tools/atlas/atlas.nim clone https://github.com/disruptek/balls")
  512. proc testUnixInstall(cmdLineRest: string) =
  513. csource("-d:danger" & cmdLineRest)
  514. xz(false, cmdLineRest)
  515. let oldCurrentDir = getCurrentDir()
  516. try:
  517. let destDir = getTempDir()
  518. copyFile("build/nim-$1.tar.xz" % VersionAsString,
  519. destDir / "nim-$1.tar.xz" % VersionAsString)
  520. setCurrentDir(destDir)
  521. execCleanPath("tar -xJf nim-$1.tar.xz" % VersionAsString)
  522. setCurrentDir("nim-$1" % VersionAsString)
  523. execCleanPath("sh build.sh")
  524. # first test: try if './bin/nim --version' outputs something sane:
  525. let output = execProcess("./bin/nim --version").splitLines
  526. if output.len > 0 and output[0].contains(VersionAsString):
  527. echo "Version check: success"
  528. execCleanPath("./bin/nim c koch.nim")
  529. execCleanPath("./koch boot -d:release", destDir / "bin")
  530. # check the docs build:
  531. execCleanPath("./koch docs", destDir / "bin")
  532. # check nimble builds:
  533. execCleanPath("./koch tools")
  534. # check the tests work:
  535. putEnv("NIM_EXE_NOT_IN_PATH", "NOT_IN_PATH")
  536. execCleanPath("./koch tests --nim:bin/nim cat megatest", destDir / "bin")
  537. else:
  538. echo "Version check: failure"
  539. finally:
  540. setCurrentDir oldCurrentDir
  541. proc valgrind(cmd: string) =
  542. # somewhat hacky: '=' sign means "pass to valgrind" else "pass to Nim"
  543. let args = parseCmdLine(cmd)
  544. var nimcmd = ""
  545. var valcmd = ""
  546. for i, a in args:
  547. if i == args.len-1:
  548. # last element is the filename:
  549. valcmd.add ' '
  550. valcmd.add changeFileExt(a, ExeExt)
  551. nimcmd.add ' '
  552. nimcmd.add a
  553. elif '=' in a:
  554. valcmd.add ' '
  555. valcmd.add a
  556. else:
  557. nimcmd.add ' '
  558. nimcmd.add a
  559. exec("nim c" & nimcmd)
  560. let supp = getAppDir() / "tools" / "nimgrind.supp"
  561. exec("valgrind --suppressions=" & supp & valcmd)
  562. proc showHelp(success: bool) =
  563. quit(HelpText % [VersionAsString & spaces(44-len(VersionAsString)),
  564. CompileDate, CompileTime], if success: QuitSuccess else: QuitFailure)
  565. proc branchDone() =
  566. let thisBranch = execProcess("git symbolic-ref --short HEAD").strip()
  567. if thisBranch != "devel" and thisBranch != "":
  568. exec("git checkout devel")
  569. exec("git branch -D " & thisBranch)
  570. exec("git pull --rebase")
  571. when isMainModule:
  572. var op = initOptParser()
  573. var
  574. latest = false
  575. localDocsOnly = false
  576. localDocsOut = ""
  577. while true:
  578. op.next()
  579. case op.kind
  580. of cmdLongOption, cmdShortOption:
  581. case normalize(op.key)
  582. of "help", "h": showHelp(success = true)
  583. of "latest": latest = true
  584. of "stable": latest = false
  585. of "nim": nimExe = op.val.absolutePath # absolute so still works with changeDir
  586. of "localdocs":
  587. localDocsOnly = true
  588. if op.val.len > 0:
  589. localDocsOut = op.val.absolutePath
  590. else: showHelp(success = false)
  591. of cmdArgument:
  592. case normalize(op.key)
  593. of "boot": boot(op.cmdLineRest)
  594. of "clean": clean(op.cmdLineRest)
  595. of "doc", "docs": buildDocs(op.cmdLineRest & " --d:nimPreviewSlimSystem " & paCode, localDocsOnly, localDocsOut)
  596. of "doc0", "docs0":
  597. # undocumented command for Araq-the-merciful:
  598. buildDocs(op.cmdLineRest & gaCode)
  599. of "pdf": buildPdfDoc(op.cmdLineRest, "doc/pdf")
  600. of "csource", "csources": csource(op.cmdLineRest)
  601. of "zip": zip(latest, op.cmdLineRest)
  602. of "xz": xz(latest, op.cmdLineRest)
  603. of "nsis": nsis(latest, op.cmdLineRest)
  604. of "geninstall": geninstall(op.cmdLineRest)
  605. of "distrohelper": geninstall()
  606. of "install": install(op.cmdLineRest)
  607. of "testinstall": testUnixInstall(op.cmdLineRest)
  608. of "installdeps": installDeps(op.cmdLineRest)
  609. of "runci": runCI(op.cmdLineRest)
  610. of "test", "tests": tests(op.cmdLineRest)
  611. of "temp": temp(op.cmdLineRest)
  612. of "xtemp": xtemp(op.cmdLineRest)
  613. of "wintools": bundleWinTools(op.cmdLineRest)
  614. of "nimble": bundleNimbleExe(latest, op.cmdLineRest)
  615. of "nimsuggest": bundleNimsuggest(op.cmdLineRest)
  616. # toolsNoNimble is kept for backward compatibility with build scripts
  617. of "toolsnonimble", "toolsnoexternal":
  618. buildTools(op.cmdLineRest)
  619. of "tools":
  620. buildTools(op.cmdLineRest)
  621. bundleNimbleExe(latest, op.cmdLineRest)
  622. of "pushcsource":
  623. quit "use this instead: https://github.com/nim-lang/csources_v1/blob/master/push_c_code.nim"
  624. of "valgrind": valgrind(op.cmdLineRest)
  625. of "c2nim": bundleC2nim(op.cmdLineRest)
  626. of "drnim": buildDrNim(op.cmdLineRest)
  627. of "fusion":
  628. let suffix = if latest: HeadHash else: FusionStableHash
  629. exec("nimble install -y fusion@$#" % suffix)
  630. of "ic": icTest(op.cmdLineRest)
  631. of "branchdone": branchDone()
  632. else: showHelp(success = false)
  633. break
  634. of cmdEnd:
  635. showHelp(success = false)