build_docs.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. #!/usr/bin/env python
  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. from __future__ import print_function
  13. import argparse
  14. import math
  15. import multiprocessing
  16. import os
  17. import os.path
  18. import subprocess
  19. import sys
  20. import re
  21. from collections import namedtuple
  22. LANGUAGES = ["en", "zh_CN"]
  23. TARGETS = ["esp32", "esp32s2"]
  24. SPHINX_WARN_LOG = "sphinx-warning-log.txt"
  25. SPHINX_SANITIZED_LOG = "sphinx-warning-log-sanitized.txt"
  26. SPHINX_KNOWN_WARNINGS = os.path.join(os.environ["IDF_PATH"], "docs", "sphinx-known-warnings.txt")
  27. DXG_WARN_LOG = "doxygen-warning-log.txt"
  28. DXG_SANITIZED_LOG = "doxygen-warning-log-sanitized.txt"
  29. DXG_KNOWN_WARNINGS = os.path.join(os.environ["IDF_PATH"], "docs", "doxygen-known-warnings.txt")
  30. LogMessage = namedtuple("LogMessage", "original_text sanitized_text")
  31. languages = LANGUAGES
  32. targets = TARGETS
  33. def main():
  34. # check Python dependencies for docs
  35. try:
  36. subprocess.check_call([sys.executable,
  37. os.path.join(os.environ["IDF_PATH"],
  38. "tools",
  39. "check_python_dependencies.py"),
  40. "-r",
  41. "{}/docs/requirements.txt".format(os.environ["IDF_PATH"])
  42. ])
  43. except subprocess.CalledProcessError:
  44. raise SystemExit(2) # stdout will already have these errors
  45. parser = argparse.ArgumentParser(description='build_docs.py: Build IDF docs', prog='build_docs.py')
  46. parser.add_argument("--language", "-l", choices=LANGUAGES, required=False)
  47. parser.add_argument("--target", "-t", choices=TARGETS, required=False)
  48. parser.add_argument("--build-dir", "-b", type=str, default="_build")
  49. parser.add_argument("--sphinx-parallel-builds", "-p", choices=["auto"] + [str(x) for x in range(8)],
  50. help="Parallel Sphinx builds - number of independent Sphinx builds to run", default="auto")
  51. parser.add_argument("--sphinx-parallel-jobs", "-j", choices=["auto"] + [str(x) for x in range(8)],
  52. help="Sphinx parallel jobs argument - number of threads for each Sphinx build to use", default="1")
  53. action_parsers = parser.add_subparsers(dest='action')
  54. build_parser = action_parsers.add_parser('build', help='Build documentation')
  55. build_parser.add_argument("--check-warnings-only", "-w", action='store_true')
  56. action_parsers.add_parser('linkcheck', help='Check links (a current IDF revision should be uploaded to GitHub)')
  57. action_parsers.add_parser('gh-linkcheck', help='Checking for hardcoded GitHub links')
  58. args = parser.parse_args()
  59. global languages
  60. if args.language is None:
  61. print("Building all languages")
  62. languages = LANGUAGES
  63. else:
  64. languages = [args.language]
  65. global targets
  66. if args.target is None:
  67. print("Building all targets")
  68. targets = TARGETS
  69. else:
  70. targets = [args.target]
  71. if args.action == "build" or args.action is None:
  72. sys.exit(action_build(args))
  73. if args.action == "linkcheck":
  74. sys.exit(action_linkcheck(args))
  75. if args.action == "gh-linkcheck":
  76. sys.exit(action_gh_linkcheck(args))
  77. def parallel_call(args, callback):
  78. num_sphinx_builds = len(languages) * len(targets)
  79. num_cpus = multiprocessing.cpu_count()
  80. if args.sphinx_parallel_builds == "auto":
  81. # at most one sphinx build per CPU, up to the number of CPUs
  82. args.sphinx_parallel_builds = min(num_sphinx_builds, num_cpus)
  83. else:
  84. args.sphinx_parallel_builds = int(args.sphinx_parallel_builds)
  85. # Force -j1 because sphinx works incorrectly
  86. args.sphinx_parallel_jobs = 1
  87. if args.sphinx_parallel_jobs == "auto":
  88. # N CPUs per build job, rounded up - (maybe smarter to round down to avoid contention, idk)
  89. args.sphinx_parallel_jobs = int(math.ceil(num_cpus / args.sphinx_parallel_builds))
  90. else:
  91. args.sphinx_parallel_jobs = int(args.sphinx_parallel_jobs)
  92. print("Will use %d parallel builds and %d jobs per build" % (args.sphinx_parallel_builds, args.sphinx_parallel_jobs))
  93. pool = multiprocessing.Pool(args.sphinx_parallel_builds)
  94. if args.sphinx_parallel_jobs > 1:
  95. print("WARNING: Sphinx parallel jobs currently produce incorrect docs output with Sphinx 1.8.5")
  96. # make a list of all combinations of build_docs() args as tuples
  97. #
  98. # there's probably a fancy way to do this with itertools but this way is actually readable
  99. entries = []
  100. for target in targets:
  101. for language in languages:
  102. build_dir = os.path.realpath(os.path.join(args.build_dir, language, target))
  103. entries.append((language, target, build_dir, args.sphinx_parallel_jobs))
  104. print(entries)
  105. errcodes = pool.map(callback, entries)
  106. print(errcodes)
  107. is_error = False
  108. for ret in errcodes:
  109. if ret != 0:
  110. print("\nThe following language/target combinations failed to build:")
  111. is_error = True
  112. break
  113. if is_error:
  114. for ret, entry in zip(errcodes, entries):
  115. if ret != 0:
  116. print("language: %s, target: %s, errcode: %d" % (entry[0], entry[1], ret))
  117. # Don't re-throw real error code from each parallel process
  118. return 1
  119. else:
  120. return 0
  121. def sphinx_call(language, target, build_dir, sphinx_parallel_jobs, buildername):
  122. # Note: because this runs in a multiprocessing Process, everything which happens here should be isolated to a single process
  123. # (ie it doesn't matter if Sphinx is using global variables, as they're it's own copy of the global variables)
  124. # wrap stdout & stderr in a way that lets us see which build_docs instance they come from
  125. #
  126. # this doesn't apply to subprocesses, they write to OS stdout & stderr so no prefix appears
  127. prefix = "%s/%s: " % (language, target)
  128. print("Building in build_dir: %s" % (build_dir))
  129. try:
  130. os.makedirs(build_dir)
  131. except OSError:
  132. pass
  133. environ = {}
  134. environ.update(os.environ)
  135. environ['BUILDDIR'] = build_dir
  136. args = [sys.executable, "-u", "-m", "sphinx.cmd.build",
  137. "-j", str(sphinx_parallel_jobs),
  138. "-b", buildername,
  139. "-d", os.path.join(build_dir, "doctrees"),
  140. "-w", SPHINX_WARN_LOG,
  141. "-t", target,
  142. "-D", "idf_target={}".format(target),
  143. os.path.join(os.path.abspath(os.path.dirname(__file__)), language), # srcdir for this language
  144. os.path.join(build_dir, buildername) # build directory
  145. ]
  146. saved_cwd = os.getcwd()
  147. os.chdir(build_dir) # also run sphinx in the build directory
  148. print("Running '%s'" % (" ".join(args)))
  149. ret = 1
  150. try:
  151. # Note: we can't call sphinx.cmd.build.main() here as multiprocessing doesn't est >1 layer deep
  152. # and sphinx.cmd.build() also does a lot of work in the calling thread, especially for j ==1,
  153. # so using a Pyhthon thread for this part is a poor option (GIL)
  154. p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  155. for c in iter(lambda: p.stdout.readline(), b''):
  156. sys.stdout.write(prefix)
  157. sys.stdout.write(c.decode('utf-8'))
  158. ret = p.wait()
  159. assert (ret is not None)
  160. sys.stdout.flush()
  161. except KeyboardInterrupt: # this seems to be the only way to get Ctrl-C to kill everything?
  162. p.kill()
  163. os.chdir(saved_cwd)
  164. return 130 # FIXME It doesn't return this errorcode, why? Just prints stacktrace
  165. os.chdir(saved_cwd)
  166. return ret
  167. def action_build(args):
  168. if not args.check_warnings_only:
  169. ret = parallel_call(args, call_build_docs)
  170. if ret != 0:
  171. return ret
  172. # check Doxygen warnings:
  173. ret = 0
  174. for target in targets:
  175. for language in languages:
  176. build_dir = os.path.realpath(os.path.join(args.build_dir, language, target))
  177. ret += check_docs(language, target,
  178. log_file=os.path.join(build_dir, DXG_WARN_LOG),
  179. known_warnings_file=DXG_KNOWN_WARNINGS,
  180. out_sanitized_log_file=os.path.join(build_dir, DXG_SANITIZED_LOG))
  181. # check Sphinx warnings:
  182. for target in targets:
  183. for language in languages:
  184. build_dir = os.path.realpath(os.path.join(args.build_dir, language, target))
  185. ret += check_docs(language, target,
  186. log_file=os.path.join(build_dir, SPHINX_WARN_LOG),
  187. known_warnings_file=SPHINX_KNOWN_WARNINGS,
  188. out_sanitized_log_file=os.path.join(build_dir, SPHINX_SANITIZED_LOG))
  189. if ret != 0:
  190. return ret
  191. def call_build_docs(entry):
  192. return sphinx_call(*entry, buildername="html")
  193. SANITIZE_FILENAME_REGEX = re.compile("[^:]*/([^/:]*)(:.*)")
  194. SANITIZE_LINENUM_REGEX = re.compile("([^:]*)(:[0-9]+:)(.*)")
  195. def sanitize_line(line):
  196. """
  197. Clear a log message from insignificant parts
  198. filter:
  199. - only filename, no path at the beginning
  200. - no line numbers after the filename
  201. """
  202. line = re.sub(SANITIZE_FILENAME_REGEX, r'\1\2', line)
  203. line = re.sub(SANITIZE_LINENUM_REGEX, r'\1:line:\3', line)
  204. return line
  205. def check_docs(language, target, log_file, known_warnings_file, out_sanitized_log_file):
  206. """
  207. Check for Documentation warnings in `log_file`: should only contain (fuzzy) matches to `known_warnings_file`
  208. It prints all unknown messages with `target`/`language` prefix
  209. It leaves `out_sanitized_log_file` file for observe and debug
  210. """
  211. # Sanitize all messages
  212. all_messages = list()
  213. with open(log_file) as f, open(out_sanitized_log_file, 'w') as o:
  214. for line in f:
  215. sanitized_line = sanitize_line(line)
  216. all_messages.append(LogMessage(line, sanitized_line))
  217. o.write(sanitized_line)
  218. known_messages = list()
  219. with open(known_warnings_file) as k:
  220. for known_line in k:
  221. known_messages.append(known_line)
  222. if "doxygen" in known_warnings_file:
  223. # Clean a known Doxygen limitation: it's expected to always document anonymous
  224. # structs/unions but we don't do this in our docs, so filter these all out with a regex
  225. # (this won't match any named field, only anonymous members -
  226. # ie the last part of the field is is just <something>::@NUM not <something>::name)
  227. RE_ANONYMOUS_FIELD = re.compile(r".+:line: warning: parameters of member [^:\s]+(::[^:\s]+)*(::@\d+)+ are not \(all\) documented")
  228. all_messages = [msg for msg in all_messages if not re.match(RE_ANONYMOUS_FIELD, msg.sanitized_text)]
  229. # Collect all new messages that are not match with the known messages.
  230. # The order is an important.
  231. new_messages = list()
  232. known_idx = 0
  233. for msg in all_messages:
  234. try:
  235. known_idx = known_messages.index(msg.sanitized_text, known_idx)
  236. except ValueError:
  237. new_messages.append(msg)
  238. if new_messages:
  239. print("\n%s/%s: Build failed due to new/different warnings (%s):\n" % (language, target, log_file))
  240. for msg in new_messages:
  241. print("%s/%s: %s" % (language, target, msg.original_text), end='')
  242. print("\n%s/%s: (Check files %s and %s for full details.)" % (language, target, known_warnings_file, log_file))
  243. return 1
  244. return 0
  245. def action_linkcheck(args):
  246. return parallel_call(args, call_linkcheck)
  247. def call_linkcheck(entry):
  248. return sphinx_call(*entry, buildername="linkcheck")
  249. # https://github.com/espressif/esp-idf/tree/
  250. # https://github.com/espressif/esp-idf/blob/
  251. # https://github.com/espressif/esp-idf/raw/
  252. GH_LINK_RE = r"https://github.com/espressif/esp-idf/(?:tree|blob|raw)/[^\s]+"
  253. # we allow this one link, because we always want users to see the latest support policy
  254. GH_LINK_ALLOWED = ["https://github.com/espressif/esp-idf/blob/master/SUPPORT_POLICY.md"]
  255. def action_gh_linkcheck(args):
  256. print("Checking for hardcoded GitHub links\n")
  257. github_links = []
  258. docs_dir = os.path.relpath(os.path.dirname(__file__))
  259. for root, _, files in os.walk(docs_dir):
  260. if "_build" in root:
  261. continue
  262. files = [os.path.join(root, f) for f in files if f.endswith(".rst")]
  263. for path in files:
  264. with open(path, "r") as f:
  265. for link in re.findall(GH_LINK_RE, f.read()):
  266. if link not in GH_LINK_ALLOWED:
  267. github_links.append((path, link))
  268. if github_links:
  269. for path, link in github_links:
  270. print("%s: %s" % (path, link))
  271. print("WARNING: Some .rst files contain hardcoded Github links.")
  272. print("Please check above output and replace links with one of the following:")
  273. print("- :idf:`dir` - points to directory inside ESP-IDF")
  274. print("- :idf_file:`file` - points to file inside ESP-IDF")
  275. print("- :idf_raw:`file` - points to raw view of the file inside ESP-IDF")
  276. print("- :component:`dir` - points to directory inside ESP-IDF components dir")
  277. print("- :component_file:`file` - points to file inside ESP-IDF components dir")
  278. print("- :component_raw:`file` - points to raw view of the file inside ESP-IDF components dir")
  279. print("- :example:`dir` - points to directory inside ESP-IDF examples dir")
  280. print("- :example_file:`file` - points to file inside ESP-IDF examples dir")
  281. print("- :example_raw:`file` - points to raw view of the file inside ESP-IDF examples dir")
  282. print("These link types will point to the correct GitHub version automatically")
  283. return 1
  284. else:
  285. print("No hardcoded links found")
  286. return 0
  287. if __name__ == "__main__":
  288. main()