build_docs.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #!/usr/bin/env python3
  2. # coding=utf-8
  3. #
  4. # Top-level docs builder
  5. #
  6. # This is just a front-end to sphinx-build that can call it multiple times for different language/target combinations
  7. #
  8. # Will build out to _build/LANG/TARGET by default
  9. #
  10. # Specific custom docs functionality should be added in conf_common.py or in a Sphinx extension, not here.
  11. #
  12. # Copyright 2020 Espressif Systems (Shanghai) PTE LTD
  13. #
  14. # Licensed under the Apache License, Version 2.0 (the "License");
  15. # you may not use this file except in compliance with the License.
  16. # You may obtain a copy of the License at
  17. #
  18. # http://www.apache.org/licenses/LICENSE-2.0
  19. #
  20. # Unless required by applicable law or agreed to in writing, software
  21. # distributed under the License is distributed on an "AS IS" BASIS,
  22. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. # See the License for the specific language governing permissions and
  24. # limitations under the License.
  25. #
  26. from __future__ import print_function
  27. import argparse
  28. import locale
  29. import math
  30. import multiprocessing
  31. import os
  32. import os.path
  33. import subprocess
  34. import sys
  35. import re
  36. from collections import namedtuple
  37. LANGUAGES = ["en", "zh_CN"]
  38. TARGETS = ["esp32", "esp32s2"]
  39. SPHINX_WARN_LOG = "sphinx-warning-log.txt"
  40. SPHINX_SANITIZED_LOG = "sphinx-warning-log-sanitized.txt"
  41. SPHINX_KNOWN_WARNINGS = os.path.join(os.environ["IDF_PATH"], "docs", "sphinx-known-warnings.txt")
  42. DXG_WARN_LOG = "doxygen-warning-log.txt"
  43. DXG_SANITIZED_LOG = "doxygen-warning-log-sanitized.txt"
  44. DXG_KNOWN_WARNINGS = os.path.join(os.environ["IDF_PATH"], "docs", "doxygen-known-warnings.txt")
  45. LogMessage = namedtuple("LogMessage", "original_text sanitized_text")
  46. languages = LANGUAGES
  47. targets = TARGETS
  48. def main():
  49. # check Python dependencies for docs
  50. try:
  51. subprocess.check_call([sys.executable,
  52. os.path.join(os.environ["IDF_PATH"],
  53. "tools",
  54. "check_python_dependencies.py"),
  55. "-r",
  56. "{}/docs/requirements.txt".format(os.environ["IDF_PATH"])
  57. ])
  58. except subprocess.CalledProcessError:
  59. raise SystemExit(2) # stdout will already have these errors
  60. # This is not the only way to make sure that all files opened by Python are treated as UTF-8, but the other way is passing encoding='utf-8' to all open()
  61. # functions and this way makes Python 2 compatibility really tough if there is any code that assumes text files contain strings (kconfiglib assumes this).
  62. # The reason for that is that you need to import io.open() to support the encoding argument on Python 2, and this function always uses Py2's unicode
  63. # type not the str type.
  64. if ('UTF-8' not in locale.getlocale()) and ('utf8' not in locale.getlocale()):
  65. raise RuntimeError("build_docs.py requires the default locale's encoding to be UTF-8.\n" +
  66. " - Linux. Setting environment variable LC_ALL=C.UTF-8 when running build_docs.py may be " +
  67. "enough to fix this.\n"
  68. " - Windows. Possible solution for the Windows 10 starting version 1803. Go to " +
  69. "Control Panel->Clock and Region->Region->Administrative->Change system locale...; " +
  70. "Check `Beta: Use Unicode UTF-8 for worldwide language support` and reboot")
  71. parser = argparse.ArgumentParser(description='build_docs.py: Build IDF docs', prog='build_docs.py')
  72. parser.add_argument("--language", "-l", choices=LANGUAGES, required=False)
  73. parser.add_argument("--target", "-t", choices=TARGETS, required=False)
  74. parser.add_argument("--build-dir", "-b", type=str, default="_build")
  75. parser.add_argument("--builders", "-bs", nargs='+', type=str, default=["html"],
  76. help="List of builders for Sphinx, e.g. html or latex, for latex a PDF is also generated")
  77. parser.add_argument("--sphinx-parallel-builds", "-p", choices=["auto"] + [str(x) for x in range(8)],
  78. help="Parallel Sphinx builds - number of independent Sphinx builds to run", default="auto")
  79. parser.add_argument("--sphinx-parallel-jobs", "-j", choices=["auto"] + [str(x) for x in range(8)],
  80. help="Sphinx parallel jobs argument - number of threads for each Sphinx build to use", default="1")
  81. parser.add_argument("--input-docs", "-i", nargs='+', default=[""],
  82. help="List of documents to build relative to the doc base folder, i.e. the language folder. Defaults to all documents")
  83. action_parsers = parser.add_subparsers(dest='action')
  84. build_parser = action_parsers.add_parser('build', help='Build documentation')
  85. build_parser.add_argument("--check-warnings-only", "-w", action='store_true')
  86. action_parsers.add_parser('linkcheck', help='Check links (a current IDF revision should be uploaded to GitHub)')
  87. action_parsers.add_parser('gh-linkcheck', help='Checking for hardcoded GitHub links')
  88. args = parser.parse_args()
  89. global languages
  90. if args.language is None:
  91. print("Building all languages")
  92. languages = LANGUAGES
  93. else:
  94. languages = [args.language]
  95. global targets
  96. if args.target is None:
  97. print("Building all targets")
  98. targets = TARGETS
  99. else:
  100. targets = [args.target]
  101. if args.action == "build" or args.action is None:
  102. if args.action is None:
  103. args.check_warnings_only = False
  104. sys.exit(action_build(args))
  105. if args.action == "linkcheck":
  106. sys.exit(action_linkcheck(args))
  107. if args.action == "gh-linkcheck":
  108. sys.exit(action_gh_linkcheck(args))
  109. def parallel_call(args, callback):
  110. num_sphinx_builds = len(languages) * len(targets)
  111. num_cpus = multiprocessing.cpu_count()
  112. if args.sphinx_parallel_builds == "auto":
  113. # at most one sphinx build per CPU, up to the number of CPUs
  114. args.sphinx_parallel_builds = min(num_sphinx_builds, num_cpus)
  115. else:
  116. args.sphinx_parallel_builds = int(args.sphinx_parallel_builds)
  117. # Force -j1 because sphinx works incorrectly
  118. args.sphinx_parallel_jobs = 1
  119. if args.sphinx_parallel_jobs == "auto":
  120. # N CPUs per build job, rounded up - (maybe smarter to round down to avoid contention, idk)
  121. args.sphinx_parallel_jobs = int(math.ceil(num_cpus / args.sphinx_parallel_builds))
  122. else:
  123. args.sphinx_parallel_jobs = int(args.sphinx_parallel_jobs)
  124. print("Will use %d parallel builds and %d jobs per build" % (args.sphinx_parallel_builds, args.sphinx_parallel_jobs))
  125. pool = multiprocessing.Pool(args.sphinx_parallel_builds)
  126. if args.sphinx_parallel_jobs > 1:
  127. print("WARNING: Sphinx parallel jobs currently produce incorrect docs output with Sphinx 1.8.5")
  128. # make a list of all combinations of build_docs() args as tuples
  129. #
  130. # there's probably a fancy way to do this with itertools but this way is actually readable
  131. entries = []
  132. for target in targets:
  133. for language in languages:
  134. build_dir = os.path.realpath(os.path.join(args.build_dir, language, target))
  135. entries.append((language, target, build_dir, args.sphinx_parallel_jobs, args.builders, args.input_docs))
  136. print(entries)
  137. errcodes = pool.map(callback, entries)
  138. print(errcodes)
  139. is_error = False
  140. for ret in errcodes:
  141. if ret != 0:
  142. print("\nThe following language/target combinations failed to build:")
  143. is_error = True
  144. break
  145. if is_error:
  146. for ret, entry in zip(errcodes, entries):
  147. if ret != 0:
  148. print("language: %s, target: %s, errcode: %d" % (entry[0], entry[1], ret))
  149. # Don't re-throw real error code from each parallel process
  150. return 1
  151. else:
  152. return 0
  153. def sphinx_call(language, target, build_dir, sphinx_parallel_jobs, buildername, input_docs):
  154. # Note: because this runs in a multiprocessing Process, everything which happens here should be isolated to a single process
  155. # (ie it doesn't matter if Sphinx is using global variables, as they're it's own copy of the global variables)
  156. # wrap stdout & stderr in a way that lets us see which build_docs instance they come from
  157. #
  158. # this doesn't apply to subprocesses, they write to OS stdout & stderr so no prefix appears
  159. prefix = "%s/%s: " % (language, target)
  160. print("Building in build_dir: %s" % (build_dir))
  161. try:
  162. os.makedirs(build_dir)
  163. except OSError:
  164. pass
  165. environ = {}
  166. environ.update(os.environ)
  167. environ['BUILDDIR'] = build_dir
  168. args = [sys.executable, "-u", "-m", "sphinx.cmd.build",
  169. "-j", str(sphinx_parallel_jobs),
  170. "-b", buildername,
  171. "-d", os.path.join(build_dir, "doctrees"),
  172. "-w", SPHINX_WARN_LOG,
  173. "-t", target,
  174. "-D", "idf_target={}".format(target),
  175. "-D", "docs_to_build={}".format(",". join(input_docs)),
  176. os.path.join(os.path.abspath(os.path.dirname(__file__)), language), # srcdir for this language
  177. os.path.join(build_dir, buildername) # build directory
  178. ]
  179. saved_cwd = os.getcwd()
  180. os.chdir(build_dir) # also run sphinx in the build directory
  181. print("Running '%s'" % (" ".join(args)))
  182. ret = 1
  183. try:
  184. # Note: we can't call sphinx.cmd.build.main() here as multiprocessing doesn't est >1 layer deep
  185. # and sphinx.cmd.build() also does a lot of work in the calling thread, especially for j ==1,
  186. # so using a Pyhthon thread for this part is a poor option (GIL)
  187. p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  188. for c in iter(lambda: p.stdout.readline(), b''):
  189. sys.stdout.write(prefix)
  190. sys.stdout.write(c.decode('utf-8'))
  191. ret = p.wait()
  192. assert (ret is not None)
  193. sys.stdout.flush()
  194. except KeyboardInterrupt: # this seems to be the only way to get Ctrl-C to kill everything?
  195. p.kill()
  196. os.chdir(saved_cwd)
  197. return 130 # FIXME It doesn't return this errorcode, why? Just prints stacktrace
  198. os.chdir(saved_cwd)
  199. return ret
  200. def action_build(args):
  201. if not args.check_warnings_only:
  202. ret = parallel_call(args, call_build_docs)
  203. if ret != 0:
  204. return ret
  205. def call_build_docs(entry):
  206. (language, target, build_dir, sphinx_parallel_jobs, builders, input_docs) = entry
  207. for buildername in builders:
  208. ret = sphinx_call(language, target, build_dir, sphinx_parallel_jobs, buildername, input_docs)
  209. # Warnings are checked after each builder as logs are overwritten
  210. # check Doxygen warnings:
  211. ret += check_docs(language, target,
  212. log_file=os.path.join(build_dir, DXG_WARN_LOG),
  213. known_warnings_file=DXG_KNOWN_WARNINGS,
  214. out_sanitized_log_file=os.path.join(build_dir, DXG_SANITIZED_LOG))
  215. # check Sphinx warnings:
  216. ret += check_docs(language, target,
  217. log_file=os.path.join(build_dir, SPHINX_WARN_LOG),
  218. known_warnings_file=SPHINX_KNOWN_WARNINGS,
  219. out_sanitized_log_file=os.path.join(build_dir, SPHINX_SANITIZED_LOG))
  220. if ret != 0:
  221. return ret
  222. # Build PDF from tex
  223. if 'latex' in builders:
  224. latex_dir = os.path.join(build_dir, "latex")
  225. ret = build_pdf(language, target, latex_dir)
  226. return ret
  227. def build_pdf(language, target, latex_dir):
  228. # Note: because this runs in a multiprocessing Process, everything which happens here should be isolated to a single process
  229. # wrap stdout & stderr in a way that lets us see which build_docs instance they come from
  230. #
  231. # this doesn't apply to subprocesses, they write to OS stdout & stderr so no prefix appears
  232. prefix = "%s/%s: " % (language, target)
  233. print("Building PDF in latex_dir: %s" % (latex_dir))
  234. saved_cwd = os.getcwd()
  235. os.chdir(latex_dir)
  236. # Based on read the docs PDFBuilder
  237. rcfile = 'latexmkrc'
  238. cmd = [
  239. 'latexmk',
  240. '-r',
  241. rcfile,
  242. '-pdf',
  243. # When ``-f`` is used, latexmk will continue building if it
  244. # encounters errors. We still receive a failure exit code in this
  245. # case, but the correct steps should run.
  246. '-f',
  247. '-dvi-', # dont generate dvi
  248. '-ps-', # dont generate ps
  249. '-interaction=nonstopmode',
  250. '-quiet',
  251. '-outdir=build',
  252. ]
  253. try:
  254. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  255. for c in iter(lambda: p.stdout.readline(), b''):
  256. sys.stdout.write(prefix)
  257. sys.stdout.write(c.decode('utf-8'))
  258. ret = p.wait()
  259. assert (ret is not None)
  260. sys.stdout.flush()
  261. except KeyboardInterrupt: # this seems to be the only way to get Ctrl-C to kill everything?
  262. p.kill()
  263. os.chdir(saved_cwd)
  264. return 130 # FIXME It doesn't return this errorcode, why? Just prints stacktrace
  265. os.chdir(saved_cwd)
  266. return ret
  267. SANITIZE_FILENAME_REGEX = re.compile("[^:]*/([^/:]*)(:.*)")
  268. SANITIZE_LINENUM_REGEX = re.compile("([^:]*)(:[0-9]+:)(.*)")
  269. def sanitize_line(line):
  270. """
  271. Clear a log message from insignificant parts
  272. filter:
  273. - only filename, no path at the beginning
  274. - no line numbers after the filename
  275. """
  276. line = re.sub(SANITIZE_FILENAME_REGEX, r'\1\2', line)
  277. line = re.sub(SANITIZE_LINENUM_REGEX, r'\1:line:\3', line)
  278. return line
  279. def check_docs(language, target, log_file, known_warnings_file, out_sanitized_log_file):
  280. """
  281. Check for Documentation warnings in `log_file`: should only contain (fuzzy) matches to `known_warnings_file`
  282. It prints all unknown messages with `target`/`language` prefix
  283. It leaves `out_sanitized_log_file` file for observe and debug
  284. """
  285. # Sanitize all messages
  286. all_messages = list()
  287. with open(log_file) as f, open(out_sanitized_log_file, 'w') as o:
  288. for line in f:
  289. sanitized_line = sanitize_line(line)
  290. all_messages.append(LogMessage(line, sanitized_line))
  291. o.write(sanitized_line)
  292. known_messages = list()
  293. with open(known_warnings_file) as k:
  294. for known_line in k:
  295. known_messages.append(known_line)
  296. if "doxygen" in known_warnings_file:
  297. # Clean a known Doxygen limitation: it's expected to always document anonymous
  298. # structs/unions but we don't do this in our docs, so filter these all out with a regex
  299. # (this won't match any named field, only anonymous members -
  300. # ie the last part of the field is is just <something>::@NUM not <something>::name)
  301. RE_ANONYMOUS_FIELD = re.compile(r".+:line: warning: parameters of member [^:\s]+(::[^:\s]+)*(::@\d+)+ are not \(all\) documented")
  302. all_messages = [msg for msg in all_messages if not re.match(RE_ANONYMOUS_FIELD, msg.sanitized_text)]
  303. # Collect all new messages that are not match with the known messages.
  304. # The order is an important.
  305. new_messages = list()
  306. known_idx = 0
  307. for msg in all_messages:
  308. try:
  309. known_idx = known_messages.index(msg.sanitized_text, known_idx)
  310. except ValueError:
  311. new_messages.append(msg)
  312. if new_messages:
  313. print("\n%s/%s: Build failed due to new/different warnings (%s):\n" % (language, target, log_file))
  314. for msg in new_messages:
  315. print("%s/%s: %s" % (language, target, msg.original_text), end='')
  316. print("\n%s/%s: (Check files %s and %s for full details.)" % (language, target, known_warnings_file, log_file))
  317. return 1
  318. return 0
  319. def action_linkcheck(args):
  320. args.builders = "linkcheck"
  321. return parallel_call(args, call_linkcheck)
  322. def call_linkcheck(entry):
  323. return sphinx_call(*entry)
  324. # https://github.com/espressif/esp-idf/tree/
  325. # https://github.com/espressif/esp-idf/blob/
  326. # https://github.com/espressif/esp-idf/raw/
  327. GH_LINK_RE = r"https://github.com/espressif/esp-idf/(?:tree|blob|raw)/[^\s]+"
  328. # we allow this one doc, because we always want users to see the latest support policy
  329. GH_LINK_ALLOWED = ["https://github.com/espressif/esp-idf/blob/master/SUPPORT_POLICY.md",
  330. "https://github.com/espressif/esp-idf/blob/master/SUPPORT_POLICY_CN.md"]
  331. def action_gh_linkcheck(args):
  332. print("Checking for hardcoded GitHub links\n")
  333. github_links = []
  334. docs_dir = os.path.relpath(os.path.dirname(__file__))
  335. for root, _, files in os.walk(docs_dir):
  336. if "_build" in root:
  337. continue
  338. files = [os.path.join(root, f) for f in files if f.endswith(".rst")]
  339. for path in files:
  340. with open(path, "r") as f:
  341. for link in re.findall(GH_LINK_RE, f.read()):
  342. if link not in GH_LINK_ALLOWED:
  343. github_links.append((path, link))
  344. if github_links:
  345. for path, link in github_links:
  346. print("%s: %s" % (path, link))
  347. print("WARNING: Some .rst files contain hardcoded Github links.")
  348. print("Please check above output and replace links with one of the following:")
  349. print("- :idf:`dir` - points to directory inside ESP-IDF")
  350. print("- :idf_file:`file` - points to file inside ESP-IDF")
  351. print("- :idf_raw:`file` - points to raw view of the file inside ESP-IDF")
  352. print("- :component:`dir` - points to directory inside ESP-IDF components dir")
  353. print("- :component_file:`file` - points to file inside ESP-IDF components dir")
  354. print("- :component_raw:`file` - points to raw view of the file inside ESP-IDF components dir")
  355. print("- :example:`dir` - points to directory inside ESP-IDF examples dir")
  356. print("- :example_file:`file` - points to file inside ESP-IDF examples dir")
  357. print("- :example_raw:`file` - points to raw view of the file inside ESP-IDF examples dir")
  358. print("These link types will point to the correct GitHub version automatically")
  359. return 1
  360. else:
  361. print("No hardcoded links found")
  362. return 0
  363. if __name__ == "__main__":
  364. main()