kochdocs.nim 13 KB

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