build_docs.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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():
  65. raise RuntimeError("build_docs.py requires the default locale's encoding to be UTF-8. " +
  66. "Setting environment variable LC_ALL=C.UTF-8 when running build_docs.py may be enough to fix this.")
  67. parser = argparse.ArgumentParser(description='build_docs.py: Build IDF docs', prog='build_docs.py')
  68. parser.add_argument("--language", "-l", choices=LANGUAGES, required=False)
  69. parser.add_argument("--target", "-t", choices=TARGETS, required=False)
  70. parser.add_argument("--build-dir", "-b", type=str, default="_build")
  71. parser.add_argument("--builders", "-bs", nargs='+', type=str, default=["html"],
  72. help="List of builders for Sphinx, e.g. html or latex, for latex a PDF is also generated")
  73. parser.add_argument("--sphinx-parallel-builds", "-p", choices=["auto"] + [str(x) for x in range(8)],
  74. help="Parallel Sphinx builds - number of independent Sphinx builds to run", default="auto")
  75. parser.add_argument("--sphinx-parallel-jobs", "-j", choices=["auto"] + [str(x) for x in range(8)],
  76. help="Sphinx parallel jobs argument - number of threads for each Sphinx build to use", default="1")
  77. action_parsers = parser.add_subparsers(dest='action')
  78. build_parser = action_parsers.add_parser('build', help='Build documentation')
  79. build_parser.add_argument("--check-warnings-only", "-w", action='store_true')
  80. action_parsers.add_parser('linkcheck', help='Check links (a current IDF revision should be uploaded to GitHub)')
  81. action_parsers.add_parser('gh-linkcheck', help='Checking for hardcoded GitHub links')
  82. args = parser.parse_args()
  83. global languages
  84. if args.language is None:
  85. print("Building all languages")
  86. languages = LANGUAGES
  87. else:
  88. languages = [args.language]
  89. global targets
  90. if args.target is None:
  91. print("Building all targets")
  92. targets = TARGETS
  93. else:
  94. targets = [args.target]
  95. if args.action == "build" or args.action is None:
  96. if args.action is None:
  97. args.check_warnings_only = False
  98. sys.exit(action_build(args))
  99. if args.action == "linkcheck":
  100. sys.exit(action_linkcheck(args))
  101. if args.action == "gh-linkcheck":
  102. sys.exit(action_gh_linkcheck(args))
  103. def parallel_call(args, callback):
  104. num_sphinx_builds = len(languages) * len(targets)
  105. num_cpus = multiprocessing.cpu_count()
  106. if args.sphinx_parallel_builds == "auto":
  107. # at most one sphinx build per CPU, up to the number of CPUs
  108. args.sphinx_parallel_builds = min(num_sphinx_builds, num_cpus)
  109. else:
  110. args.sphinx_parallel_builds = int(args.sphinx_parallel_builds)
  111. # Force -j1 because sphinx works incorrectly
  112. args.sphinx_parallel_jobs = 1
  113. if args.sphinx_parallel_jobs == "auto":
  114. # N CPUs per build job, rounded up - (maybe smarter to round down to avoid contention, idk)
  115. args.sphinx_parallel_jobs = int(math.ceil(num_cpus / args.sphinx_parallel_builds))
  116. else:
  117. args.sphinx_parallel_jobs = int(args.sphinx_parallel_jobs)
  118. print("Will use %d parallel builds and %d jobs per build" % (args.sphinx_parallel_builds, args.sphinx_parallel_jobs))
  119. pool = multiprocessing.Pool(args.sphinx_parallel_builds)
  120. if args.sphinx_parallel_jobs > 1:
  121. print("WARNING: Sphinx parallel jobs currently produce incorrect docs output with Sphinx 1.8.5")
  122. # make a list of all combinations of build_docs() args as tuples
  123. #
  124. # there's probably a fancy way to do this with itertools but this way is actually readable
  125. entries = []
  126. for target in targets:
  127. for language in languages:
  128. build_dir = os.path.realpath(os.path.join(args.build_dir, language, target))
  129. entries.append((language, target, build_dir, args.sphinx_parallel_jobs, args.builders))
  130. print(entries)
  131. errcodes = pool.map(callback, entries)
  132. print(errcodes)
  133. is_error = False
  134. for ret in errcodes:
  135. if ret != 0:
  136. print("\nThe following language/target combinations failed to build:")
  137. is_error = True
  138. break
  139. if is_error:
  140. for ret, entry in zip(errcodes, entries):
  141. if ret != 0:
  142. print("language: %s, target: %s, errcode: %d" % (entry[0], entry[1], ret))
  143. # Don't re-throw real error code from each parallel process
  144. return 1
  145. else:
  146. return 0
  147. def sphinx_call(language, target, build_dir, sphinx_parallel_jobs, buildername):
  148. # Note: because this runs in a multiprocessing Process, everything which happens here should be isolated to a single process
  149. # (ie it doesn't matter if Sphinx is using global variables, as they're it's own copy of the global variables)
  150. # wrap stdout & stderr in a way that lets us see which build_docs instance they come from
  151. #
  152. # this doesn't apply to subprocesses, they write to OS stdout & stderr so no prefix appears
  153. prefix = "%s/%s: " % (language, target)
  154. print("Building in build_dir: %s" % (build_dir))
  155. try:
  156. os.makedirs(build_dir)
  157. except OSError:
  158. pass
  159. environ = {}
  160. environ.update(os.environ)
  161. environ['BUILDDIR'] = build_dir
  162. args = [sys.executable, "-u", "-m", "sphinx.cmd.build",
  163. "-j", str(sphinx_parallel_jobs),
  164. "-b", buildername,
  165. "-d", os.path.join(build_dir, "doctrees"),
  166. "-w", SPHINX_WARN_LOG,
  167. "-t", target,
  168. "-D", "idf_target={}".format(target),
  169. os.path.join(os.path.abspath(os.path.dirname(__file__)), language), # srcdir for this language
  170. os.path.join(build_dir, buildername) # build directory
  171. ]
  172. saved_cwd = os.getcwd()
  173. os.chdir(build_dir) # also run sphinx in the build directory
  174. print("Running '%s'" % (" ".join(args)))
  175. ret = 1
  176. try:
  177. # Note: we can't call sphinx.cmd.build.main() here as multiprocessing doesn't est >1 layer deep
  178. # and sphinx.cmd.build() also does a lot of work in the calling thread, especially for j ==1,
  179. # so using a Pyhthon thread for this part is a poor option (GIL)
  180. p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  181. for c in iter(lambda: p.stdout.readline(), b''):
  182. sys.stdout.write(prefix)
  183. sys.stdout.write(c.decode('utf-8'))
  184. ret = p.wait()
  185. assert (ret is not None)
  186. sys.stdout.flush()
  187. except KeyboardInterrupt: # this seems to be the only way to get Ctrl-C to kill everything?
  188. p.kill()
  189. os.chdir(saved_cwd)
  190. return 130 # FIXME It doesn't return this errorcode, why? Just prints stacktrace
  191. os.chdir(saved_cwd)
  192. return ret
  193. def action_build(args):
  194. if not args.check_warnings_only:
  195. ret = parallel_call(args, call_build_docs)
  196. if ret != 0:
  197. return ret
  198. # check Doxygen warnings:
  199. ret = 0
  200. for target in targets:
  201. for language in languages:
  202. build_dir = os.path.realpath(os.path.join(args.build_dir, language, target))
  203. ret += check_docs(language, target,
  204. log_file=os.path.join(build_dir, DXG_WARN_LOG),
  205. known_warnings_file=DXG_KNOWN_WARNINGS,
  206. out_sanitized_log_file=os.path.join(build_dir, DXG_SANITIZED_LOG))
  207. # check Sphinx warnings:
  208. for target in targets:
  209. for language in languages:
  210. build_dir = os.path.realpath(os.path.join(args.build_dir, language, target))
  211. ret += check_docs(language, target,
  212. log_file=os.path.join(build_dir, SPHINX_WARN_LOG),
  213. known_warnings_file=SPHINX_KNOWN_WARNINGS,
  214. out_sanitized_log_file=os.path.join(build_dir, SPHINX_SANITIZED_LOG))
  215. if ret != 0:
  216. return ret
  217. def call_build_docs(entry):
  218. (language, target, build_dir, sphinx_parallel_jobs, builders) = entry
  219. for buildername in builders:
  220. ret = sphinx_call(language, target, build_dir, sphinx_parallel_jobs, buildername)
  221. if ret != 0:
  222. return ret
  223. # Build PDF from tex
  224. if 'latex' in builders:
  225. latex_dir = os.path.join(build_dir, "latex")
  226. ret = build_pdf(language, target, latex_dir)
  227. return ret
  228. def build_pdf(language, target, latex_dir):
  229. # Note: because this runs in a multiprocessing Process, everything which happens here should be isolated to a single process
  230. # wrap stdout & stderr in a way that lets us see which build_docs instance they come from
  231. #
  232. # this doesn't apply to subprocesses, they write to OS stdout & stderr so no prefix appears
  233. prefix = "%s/%s: " % (language, target)
  234. print("Building PDF in latex_dir: %s" % (latex_dir))
  235. saved_cwd = os.getcwd()
  236. os.chdir(latex_dir)
  237. # Based on read the docs PDFBuilder
  238. rcfile = 'latexmkrc'
  239. cmd = [
  240. 'latexmk',
  241. '-r',
  242. rcfile,
  243. '-pdf',
  244. # When ``-f`` is used, latexmk will continue building if it
  245. # encounters errors. We still receive a failure exit code in this
  246. # case, but the correct steps should run.
  247. '-f',
  248. '-dvi-', # dont generate dvi
  249. '-ps-', # dont generate ps
  250. '-interaction=nonstopmode',
  251. '-quiet',
  252. '-outdir=build',
  253. ]
  254. try:
  255. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  256. for c in iter(lambda: p.stdout.readline(), b''):
  257. sys.stdout.write(prefix)
  258. sys.stdout.write(c.decode('utf-8'))
  259. ret = p.wait()
  260. assert (ret is not None)
  261. sys.stdout.flush()
  262. except KeyboardInterrupt: # this seems to be the only way to get Ctrl-C to kill everything?
  263. p.kill()
  264. os.chdir(saved_cwd)
  265. return 130 # FIXME It doesn't return this errorcode, why? Just prints stacktrace
  266. os.chdir(saved_cwd)
  267. return ret
  268. SANITIZE_FILENAME_REGEX = re.compile("[^:]*/([^/:]*)(:.*)")
  269. SANITIZE_LINENUM_REGEX = re.compile("([^:]*)(:[0-9]+:)(.*)")
  270. def sanitize_line(line):
  271. """
  272. Clear a log message from insignificant parts
  273. filter:
  274. - only filename, no path at the beginning
  275. - no line numbers after the filename
  276. """
  277. line = re.sub(SANITIZE_FILENAME_REGEX, r'\1\2', line)
  278. line = re.sub(SANITIZE_LINENUM_REGEX, r'\1:line:\3', line)
  279. return line
  280. def check_docs(language, target, log_file, known_warnings_file, out_sanitized_log_file):
  281. """
  282. Check for Documentation warnings in `log_file`: should only contain (fuzzy) matches to `known_warnings_file`
  283. It prints all unknown messages with `target`/`language` prefix
  284. It leaves `out_sanitized_log_file` file for observe and debug
  285. """
  286. # Sanitize all messages
  287. all_messages = list()
  288. with open(log_file) as f, open(out_sanitized_log_file, 'w') as o:
  289. for line in f:
  290. sanitized_line = sanitize_line(line)
  291. all_messages.append(LogMessage(line, sanitized_line))
  292. o.write(sanitized_line)
  293. known_messages = list()
  294. with open(known_warnings_file) as k:
  295. for known_line in k:
  296. known_messages.append(known_line)
  297. if "doxygen" in known_warnings_file:
  298. # Clean a known Doxygen limitation: it's expected to always document anonymous
  299. # structs/unions but we don't do this in our docs, so filter these all out with a regex
  300. # (this won't match any named field, only anonymous members -
  301. # ie the last part of the field is is just <something>::@NUM not <something>::name)
  302. RE_ANONYMOUS_FIELD = re.compile(r".+:line: warning: parameters of member [^:\s]+(::[^:\s]+)*(::@\d+)+ are not \(all\) documented")
  303. all_messages = [msg for msg in all_messages if not re.match(RE_ANONYMOUS_FIELD, msg.sanitized_text)]
  304. # Collect all new messages that are not match with the known messages.
  305. # The order is an important.
  306. new_messages = list()
  307. known_idx = 0
  308. for msg in all_messages:
  309. try:
  310. known_idx = known_messages.index(msg.sanitized_text, known_idx)
  311. except ValueError:
  312. new_messages.append(msg)
  313. if new_messages:
  314. print("\n%s/%s: Build failed due to new/different warnings (%s):\n" % (language, target, log_file))
  315. for msg in new_messages:
  316. print("%s/%s: %s" % (language, target, msg.original_text), end='')
  317. print("\n%s/%s: (Check files %s and %s for full details.)" % (language, target, known_warnings_file, log_file))
  318. return 1
  319. return 0
  320. def action_linkcheck(args):
  321. return parallel_call(args, call_linkcheck)
  322. def call_linkcheck(entry):
  323. # Remove the last entry which the buildername, since the linkcheck builder is not supplied through the builder list argument
  324. return sphinx_call(*entry[:4], buildername="linkcheck")
  325. # https://github.com/espressif/esp-idf/tree/
  326. # https://github.com/espressif/esp-idf/blob/
  327. # https://github.com/espressif/esp-idf/raw/
  328. GH_LINK_RE = r"https://github.com/espressif/esp-idf/(?:tree|blob|raw)/[^\s]+"
  329. # we allow this one link, because we always want users to see the latest support policy
  330. GH_LINK_ALLOWED = ["https://github.com/espressif/esp-idf/blob/master/SUPPORT_POLICY.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()