kochdocs.nim 14 KB

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