koch.nim 28 KB

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