kochdocs.nim 12 KB

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