koch.nim 30 KB

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