build_docs.py 15 KB

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