kochdocs.nim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. ## Part of 'koch' responsible for the documentation generation.
  2. import os, strutils, osproc, sets, pathnorm, sequtils
  3. # XXX: Remove this feature check once the csources supports it.
  4. when defined(nimHasCastPragmaBlocks):
  5. import std/pegs
  6. from std/private/globs import nativeToUnixPath, walkDirRecFilter, PathEntry
  7. import "../compiler/nimpaths"
  8. const
  9. gaCode* = " --doc.googleAnalytics:UA-48159761-1"
  10. paCode* = " --doc.plausibleAnalytics:nim-lang.org"
  11. # errormax: subsequent errors are probably consequences of 1st one; a simple
  12. # bug could cause unlimited number of errors otherwise, hard to debug in CI.
  13. docDefines = "-d:nimExperimentalAsyncjsThen -d:nimExperimentalLinenoiseExtra"
  14. nimArgs = "--errormax:3 --hint:Conf:off --hint:Path:off --hint:Processing:off --hint:XDeclaredButNotUsed:off --warning:UnusedImport:off -d:boot --putenv:nimversion=$# $#" % [system.NimVersion, docDefines]
  15. gitUrl = "https://github.com/nim-lang/Nim"
  16. docHtmlOutput = "doc/html"
  17. webUploadOutput = "web/upload"
  18. var nimExe*: string
  19. const allowList = ["jsbigints.nim", "jsheaders.nim", "jsformdata.nim", "jsfetch.nim", "jsutils.nim"]
  20. template isJsOnly(file: string): bool =
  21. file.isRelativeTo("lib/js") or
  22. file.extractFilename in allowList
  23. proc exe*(f: string): string =
  24. result = addFileExt(f, ExeExt)
  25. when defined(windows):
  26. result = result.replace('/','\\')
  27. proc findNimImpl*(): tuple[path: string, ok: bool] =
  28. if nimExe.len > 0: return (nimExe, true)
  29. let nim = "nim".exe
  30. result.path = "bin" / nim
  31. result.ok = true
  32. if fileExists(result.path): return
  33. for dir in split(getEnv("PATH"), PathSep):
  34. result.path = dir / nim
  35. if fileExists(result.path): return
  36. # assume there is a symlink to the exe or something:
  37. return (nim, false)
  38. proc findNim*(): string = findNimImpl().path
  39. proc exec*(cmd: string, errorcode: int = QuitFailure, additionalPath = "") =
  40. let prevPath = getEnv("PATH")
  41. if additionalPath.len > 0:
  42. var absolute = additionalPath
  43. if not absolute.isAbsolute:
  44. absolute = getCurrentDir() / absolute
  45. echo("Adding to $PATH: ", absolute)
  46. putEnv("PATH", (if prevPath.len > 0: prevPath & PathSep else: "") & absolute)
  47. echo(cmd)
  48. if execShellCmd(cmd) != 0: quit("FAILURE", errorcode)
  49. putEnv("PATH", prevPath)
  50. template inFold*(desc, body) =
  51. if existsEnv("TRAVIS"):
  52. echo "travis_fold:start:" & desc.replace(" ", "_")
  53. elif existsEnv("GITHUB_ACTIONS"):
  54. echo "::group::" & desc
  55. elif existsEnv("TF_BUILD"):
  56. echo "##[group]" & desc
  57. body
  58. if existsEnv("TRAVIS"):
  59. echo "travis_fold:end:" & desc.replace(" ", "_")
  60. elif existsEnv("GITHUB_ACTIONS"):
  61. echo "::endgroup::"
  62. elif existsEnv("TF_BUILD"):
  63. echo "##[endgroup]"
  64. proc execFold*(desc, cmd: string, errorcode: int = QuitFailure, additionalPath = "") =
  65. ## Execute shell command. Add log folding for various CI services.
  66. # https://github.com/travis-ci/travis-ci/issues/2285#issuecomment-42724719
  67. let desc = if desc.len == 0: cmd else: desc
  68. inFold(desc):
  69. exec(cmd, errorcode, additionalPath)
  70. proc execCleanPath*(cmd: string,
  71. additionalPath = ""; errorcode: int = QuitFailure) =
  72. # simulate a poor man's virtual environment
  73. let prevPath = getEnv("PATH")
  74. when defined(windows):
  75. let cleanPath = r"$1\system32;$1;$1\System32\Wbem" % getEnv"SYSTEMROOT"
  76. else:
  77. const cleanPath = r"/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin"
  78. putEnv("PATH", cleanPath & PathSep & additionalPath)
  79. echo(cmd)
  80. if execShellCmd(cmd) != 0: quit("FAILURE", errorcode)
  81. putEnv("PATH", prevPath)
  82. proc nimexec*(cmd: string) =
  83. # Consider using `nimCompile` instead
  84. exec findNim().quoteShell() & " " & cmd
  85. proc nimCompile*(input: string, outputDir = "bin", mode = "c", options = "") =
  86. let output = outputDir / input.splitFile.name.exe
  87. let cmd = findNim().quoteShell() & " " & mode & " -o:" & output & " " & options & " " & input
  88. exec cmd
  89. proc nimCompileFold*(desc, input: string, outputDir = "bin", mode = "c", options = "", outputName = "") =
  90. let outputName2 = if outputName.len == 0: input.splitFile.name.exe else: outputName.exe
  91. let output = outputDir / outputName2
  92. let cmd = findNim().quoteShell() & " " & mode & " -o:" & output & " " & options & " " & input
  93. execFold(desc, cmd)
  94. proc getRst2html(): seq[string] =
  95. for a in walkDirRecFilter("doc"):
  96. let path = a.path
  97. if a.kind == pcFile and path.splitFile.ext == ".rst" and path.lastPathPart notin
  98. ["docs.rst", "nimfix.rst"]:
  99. # maybe we should still show nimfix, could help reviving it
  100. # `docs` is redundant with `overview`, might as well remove that file?
  101. result.add path
  102. doAssert "doc/manual/var_t_return.rst".unixToNativePath in result # sanity check
  103. const
  104. rstPdfList = """
  105. manual.rst
  106. lib.rst
  107. tut1.rst
  108. tut2.rst
  109. tut3.rst
  110. nimc.rst
  111. niminst.rst
  112. mm.rst
  113. """.splitWhitespace().mapIt("doc" / it)
  114. doc0 = """
  115. lib/system/threads.nim
  116. lib/system/channels_builtin.nim
  117. """.splitWhitespace() # ran by `nim doc0` instead of `nim doc`
  118. withoutIndex = """
  119. lib/wrappers/mysql.nim
  120. lib/wrappers/sqlite3.nim
  121. lib/wrappers/postgres.nim
  122. lib/wrappers/tinyc.nim
  123. lib/wrappers/odbcsql.nim
  124. lib/wrappers/pcre.nim
  125. lib/wrappers/openssl.nim
  126. lib/posix/posix.nim
  127. lib/posix/linux.nim
  128. lib/posix/termios.nim
  129. """.splitWhitespace()
  130. # some of these are include files so shouldn't be docgen'd
  131. ignoredModules = """
  132. lib/pure/future.nim
  133. lib/pure/collections/hashcommon.nim
  134. lib/pure/collections/tableimpl.nim
  135. lib/pure/collections/setimpl.nim
  136. lib/pure/ioselects/ioselectors_kqueue.nim
  137. lib/pure/ioselects/ioselectors_select.nim
  138. lib/pure/ioselects/ioselectors_poll.nim
  139. lib/pure/ioselects/ioselectors_epoll.nim
  140. lib/posix/posix_macos_amd64.nim
  141. lib/posix/posix_other.nim
  142. lib/posix/posix_nintendoswitch.nim
  143. lib/posix/posix_nintendoswitch_consts.nim
  144. lib/posix/posix_linux_amd64.nim
  145. lib/posix/posix_linux_amd64_consts.nim
  146. lib/posix/posix_other_consts.nim
  147. lib/posix/posix_freertos_consts.nim
  148. lib/posix/posix_openbsd_amd64.nim
  149. lib/posix/posix_haiku.nim
  150. """.splitWhitespace()
  151. when (NimMajor, NimMinor) < (1, 1) or not declared(isRelativeTo):
  152. proc isRelativeTo(path, base: string): bool =
  153. let path = path.normalizedPath
  154. let base = base.normalizedPath
  155. let ret = relativePath(path, base)
  156. result = path.len > 0 and not ret.startsWith ".."
  157. proc getDocList(): seq[string] =
  158. var docIgnore: HashSet[string]
  159. for a in doc0: docIgnore.incl a
  160. for a in withoutIndex: docIgnore.incl a
  161. for a in ignoredModules: docIgnore.incl a
  162. # don't ignore these even though in lib/system (not include files)
  163. const goodSystem = """
  164. lib/system/io.nim
  165. lib/system/nimscript.nim
  166. lib/system/assertions.nim
  167. lib/system/iterators.nim
  168. lib/system/dollars.nim
  169. lib/system/widestrs.nim
  170. """.splitWhitespace()
  171. proc follow(a: PathEntry): bool =
  172. result = a.path.lastPathPart notin ["nimcache", htmldocsDirname,
  173. "includes", "deprecated", "genode"] and
  174. not a.path.isRelativeTo("lib/fusion") # fusion was un-bundled but we need to keep this in case user has it installed
  175. for entry in walkDirRecFilter("lib", follow = follow):
  176. let a = entry.path
  177. if entry.kind != pcFile or a.splitFile.ext != ".nim" or
  178. (a.isRelativeTo("lib/system") and a.nativeToUnixPath notin goodSystem) or
  179. a.nativeToUnixPath in docIgnore:
  180. continue
  181. result.add a
  182. result.add normalizePath("nimsuggest/sexp.nim")
  183. let doc = getDocList()
  184. proc sexec(cmds: openArray[string]) =
  185. ## Serial queue wrapper around exec.
  186. for cmd in cmds:
  187. echo(cmd)
  188. let (outp, exitCode) = osproc.execCmdEx(cmd)
  189. if exitCode != 0: quit outp
  190. proc mexec(cmds: openArray[string]) =
  191. ## Multiprocessor version of exec
  192. let r = execProcesses(cmds, {poStdErrToStdOut, poParentStreams, poEchoCmd})
  193. if r != 0:
  194. echo "external program failed, retrying serial work queue for logs!"
  195. sexec(cmds)
  196. proc buildDocSamples(nimArgs, destPath: string) =
  197. ## Special case documentation sample proc.
  198. ##
  199. ## TODO: consider integrating into the existing generic documentation builders
  200. ## now that we have a single `doc` command.
  201. exec(findNim().quoteShell() & " doc $# -o:$# $#" %
  202. [nimArgs, destPath / "docgen_sample.html", "doc" / "docgen_sample.nim"])
  203. proc buildDocPackages(nimArgs, destPath: string) =
  204. # compiler docs; later, other packages (perhaps tools, testament etc)
  205. let nim = findNim().quoteShell()
  206. # to avoid broken links to manual from compiler dir, but a multi-package
  207. # structure could be supported later
  208. proc docProject(outdir, options, mainproj: string) =
  209. exec("$nim doc --project --outdir:$outdir $nimArgs --git.url:$gitUrl $options $mainproj" % [
  210. "nim", nim,
  211. "outdir", outdir,
  212. "nimArgs", nimArgs,
  213. "gitUrl", gitUrl,
  214. "options", options,
  215. "mainproj", mainproj,
  216. ])
  217. let extra = "-u:boot"
  218. # xxx keep in sync with what's in $nim_prs_D/config/nimdoc.cfg, or, rather,
  219. # start using nims instead of nimdoc.cfg
  220. docProject(destPath/"compiler", extra, "compiler/index.nim")
  221. proc buildDoc(nimArgs, destPath: string) =
  222. # call nim for the documentation:
  223. let rst2html = getRst2html()
  224. var
  225. commands = newSeq[string](rst2html.len + len(doc0) + len(doc) + withoutIndex.len)
  226. i = 0
  227. let nim = findNim().quoteShell()
  228. for d in items(rst2html):
  229. commands[i] = nim & " rst2html $# --git.url:$# -o:$# --index:on $#" %
  230. [nimArgs, gitUrl,
  231. destPath / changeFileExt(splitFile(d).name, "html"), d]
  232. i.inc
  233. for d in items(doc0):
  234. commands[i] = nim & " doc0 $# --git.url:$# -o:$# --index:on $#" %
  235. [nimArgs, gitUrl,
  236. destPath / changeFileExt(splitFile(d).name, "html"), d]
  237. i.inc
  238. for d in items(doc):
  239. let extra = if isJsOnly(d): "--backend:js" else: ""
  240. var nimArgs2 = nimArgs
  241. if d.isRelativeTo("compiler"): doAssert false
  242. commands[i] = nim & " doc $# $# --git.url:$# --outdir:$# --index:on $#" %
  243. [extra, nimArgs2, gitUrl, destPath, d]
  244. i.inc
  245. for d in items(withoutIndex):
  246. commands[i] = nim & " doc $# --git.url:$# -o:$# $#" %
  247. [nimArgs, gitUrl,
  248. destPath / changeFileExt(splitFile(d).name, "html"), d]
  249. i.inc
  250. mexec(commands)
  251. exec(nim & " buildIndex -o:$1/theindex.html $1" % [destPath])
  252. # caveat: this works so long it's called before `buildDocPackages` which
  253. # populates `compiler/` with unrelated idx files that shouldn't be in index,
  254. # so should work in CI but you may need to remove your generated html files
  255. # locally after calling `./koch docs`. The clean fix would be for `idx` files
  256. # to be transient with `--project` (eg all in memory).
  257. proc nim2pdf(src: string, dst: string, nimArgs: string) =
  258. # xxx expose as a `nim` command or in some other reusable way.
  259. let outDir = "build" / "xelatextmp" # xxx factor pending https://github.com/timotheecour/Nim/issues/616
  260. # note: this will generate temporary files in gitignored `outDir`: aux toc log out tex
  261. exec("$# rst2tex $# --outdir:$# $#" % [findNim().quoteShell(), nimArgs, outDir.quoteShell, src.quoteShell])
  262. let texFile = outDir / src.lastPathPart.changeFileExt("tex")
  263. for i in 0..<3: # call LaTeX three times to get cross references right:
  264. let xelatexLog = outDir / "xelatex.log"
  265. # `>` should work on windows, if not, we can use `execCmdEx`
  266. let cmd = "xelatex -interaction=nonstopmode -output-directory=$# $# > $#" % [outDir.quoteShell, texFile.quoteShell, xelatexLog.quoteShell]
  267. exec(cmd) # on error, user can inspect `xelatexLog`
  268. if i == 1: # build .ind file
  269. var texFileBase = texFile
  270. texFileBase.removeSuffix(".tex")
  271. let cmd = "makeindex $# > $#" % [
  272. texFileBase.quoteShell, xelatexLog.quoteShell]
  273. exec(cmd)
  274. moveFile(texFile.changeFileExt("pdf"), dst)
  275. proc buildPdfDoc*(nimArgs, destPath: string) =
  276. var pdfList: seq[string]
  277. createDir(destPath)
  278. if os.execShellCmd("xelatex -version") != 0:
  279. doAssert false, "xelatex not found" # or, raise an exception
  280. else:
  281. for src in items(rstPdfList):
  282. let dst = destPath / src.lastPathPart.changeFileExt("pdf")
  283. pdfList.add dst
  284. nim2pdf(src, dst, nimArgs)
  285. echo "\nOutput PDF files: \n ", pdfList.join(" ") # because `nim2pdf` is a bit verbose
  286. proc buildJS(): string =
  287. let nim = findNim()
  288. exec("$# js -d:release --out:$# tools/nimblepkglist.nim" %
  289. [nim.quoteShell(), webUploadOutput / "nimblepkglist.js"])
  290. # xxx deadcode? and why is it only for webUploadOutput, not for local docs?
  291. result = getDocHacksJs(nimr = getCurrentDir(), nim)
  292. proc buildDocsDir*(args: string, dir: string) =
  293. let args = nimArgs & " " & args
  294. let docHackJsSource = buildJS()
  295. createDir(dir)
  296. buildDocSamples(args, dir)
  297. buildDoc(args, dir) # bottleneck
  298. copyFile(dir / "overview.html", dir / "index.html")
  299. buildDocPackages(args, dir)
  300. copyFile(docHackJsSource, dir / docHackJsSource.lastPathPart)
  301. proc buildDocs*(args: string, localOnly = false, localOutDir = "") =
  302. let localOutDir =
  303. if localOutDir.len == 0:
  304. docHtmlOutput
  305. else:
  306. localOutDir
  307. var args = args
  308. if not localOnly:
  309. buildDocsDir(args, webUploadOutput / NimVersion)
  310. # XXX: Remove this feature check once the csources supports it.
  311. when defined(nimHasCastPragmaBlocks):
  312. let gaFilter = peg"@( y'--doc.googleAnalytics:' @(\s / $) )"
  313. args = args.replace(gaFilter)
  314. buildDocsDir(args, localOutDir)