test_doc_build.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0
  3. # Copyright(c) 2025: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>
  4. #
  5. # pylint: disable=R0903,R0912,R0913,R0914,R0917,C0301
  6. """
  7. Install minimal supported requirements for different Sphinx versions
  8. and optionally test the build.
  9. """
  10. import argparse
  11. import asyncio
  12. import os.path
  13. import shutil
  14. import sys
  15. import time
  16. import subprocess
  17. # Minimal python version supported by the building system.
  18. PYTHON = os.path.basename(sys.executable)
  19. min_python_bin = None
  20. for i in range(9, 13):
  21. p = f"python3.{i}"
  22. if shutil.which(p):
  23. min_python_bin = p
  24. break
  25. if not min_python_bin:
  26. min_python_bin = PYTHON
  27. # Starting from 8.0, Python 3.9 is not supported anymore.
  28. PYTHON_VER_CHANGES = {(8, 0, 0): PYTHON}
  29. DEFAULT_VERSIONS_TO_TEST = [
  30. (3, 4, 3), # Minimal supported version
  31. (5, 3, 0), # CentOS Stream 9 / AlmaLinux 9
  32. (6, 1, 1), # Debian 12
  33. (7, 2, 1), # openSUSE Leap 15.6
  34. (7, 2, 6), # Ubuntu 24.04 LTS
  35. (7, 4, 7), # Ubuntu 24.10
  36. (7, 3, 0), # openSUSE Tumbleweed
  37. (8, 1, 3), # Fedora 42
  38. (8, 2, 3) # Latest version - covers rolling distros
  39. ]
  40. # Sphinx versions to be installed and their incremental requirements
  41. SPHINX_REQUIREMENTS = {
  42. # Oldest versions we support for each package required by Sphinx 3.4.3
  43. (3, 4, 3): {
  44. "docutils": "0.16",
  45. "alabaster": "0.7.12",
  46. "babel": "2.8.0",
  47. "certifi": "2020.6.20",
  48. "docutils": "0.16",
  49. "idna": "2.10",
  50. "imagesize": "1.2.0",
  51. "Jinja2": "2.11.2",
  52. "MarkupSafe": "1.1.1",
  53. "packaging": "20.4",
  54. "Pygments": "2.6.1",
  55. "PyYAML": "5.1",
  56. "requests": "2.24.0",
  57. "snowballstemmer": "2.0.0",
  58. "sphinxcontrib-applehelp": "1.0.2",
  59. "sphinxcontrib-devhelp": "1.0.2",
  60. "sphinxcontrib-htmlhelp": "1.0.3",
  61. "sphinxcontrib-jsmath": "1.0.1",
  62. "sphinxcontrib-qthelp": "1.0.3",
  63. "sphinxcontrib-serializinghtml": "1.1.4",
  64. "urllib3": "1.25.9",
  65. },
  66. # Update package dependencies to a more modern base. The goal here
  67. # is to avoid to many incremental changes for the next entries
  68. (3, 5, 0): {
  69. "alabaster": "0.7.13",
  70. "babel": "2.17.0",
  71. "certifi": "2025.6.15",
  72. "idna": "3.10",
  73. "imagesize": "1.4.1",
  74. "packaging": "25.0",
  75. "Pygments": "2.8.1",
  76. "requests": "2.32.4",
  77. "snowballstemmer": "3.0.1",
  78. "sphinxcontrib-applehelp": "1.0.4",
  79. "sphinxcontrib-htmlhelp": "2.0.1",
  80. "sphinxcontrib-serializinghtml": "1.1.5",
  81. "urllib3": "2.0.0",
  82. },
  83. # Starting from here, ensure all docutils versions are covered with
  84. # supported Sphinx versions. Other packages are upgraded only when
  85. # required by pip
  86. (4, 0, 0): {
  87. "PyYAML": "5.1",
  88. },
  89. (4, 1, 0): {
  90. "docutils": "0.17",
  91. "Pygments": "2.19.1",
  92. "Jinja2": "3.0.3",
  93. "MarkupSafe": "2.0",
  94. },
  95. (4, 3, 0): {},
  96. (4, 4, 0): {},
  97. (4, 5, 0): {
  98. "docutils": "0.17.1",
  99. },
  100. (5, 0, 0): {},
  101. (5, 1, 0): {},
  102. (5, 2, 0): {
  103. "docutils": "0.18",
  104. "Jinja2": "3.1.2",
  105. "MarkupSafe": "2.0",
  106. "PyYAML": "5.3.1",
  107. },
  108. (5, 3, 0): {
  109. "docutils": "0.18.1",
  110. },
  111. (6, 0, 0): {},
  112. (6, 1, 0): {},
  113. (6, 2, 0): {
  114. "PyYAML": "5.4.1",
  115. },
  116. (7, 0, 0): {},
  117. (7, 1, 0): {},
  118. (7, 2, 0): {
  119. "docutils": "0.19",
  120. "PyYAML": "6.0.1",
  121. "sphinxcontrib-serializinghtml": "1.1.9",
  122. },
  123. (7, 2, 6): {
  124. "docutils": "0.20",
  125. },
  126. (7, 3, 0): {
  127. "alabaster": "0.7.14",
  128. "PyYAML": "6.0.1",
  129. "tomli": "2.0.1",
  130. },
  131. (7, 4, 0): {
  132. "docutils": "0.20.1",
  133. "PyYAML": "6.0.1",
  134. },
  135. (8, 0, 0): {
  136. "docutils": "0.21",
  137. },
  138. (8, 1, 0): {
  139. "docutils": "0.21.1",
  140. "PyYAML": "6.0.1",
  141. "sphinxcontrib-applehelp": "1.0.7",
  142. "sphinxcontrib-devhelp": "1.0.6",
  143. "sphinxcontrib-htmlhelp": "2.0.6",
  144. "sphinxcontrib-qthelp": "1.0.6",
  145. },
  146. (8, 2, 0): {
  147. "docutils": "0.21.2",
  148. "PyYAML": "6.0.1",
  149. "sphinxcontrib-serializinghtml": "1.1.9",
  150. },
  151. }
  152. class AsyncCommands:
  153. """Excecute command synchronously"""
  154. def __init__(self, fp=None):
  155. self.stdout = None
  156. self.stderr = None
  157. self.output = None
  158. self.fp = fp
  159. def log(self, out, verbose, is_info=True):
  160. out = out.removesuffix('\n')
  161. if verbose:
  162. if is_info:
  163. print(out)
  164. else:
  165. print(out, file=sys.stderr)
  166. if self.fp:
  167. self.fp.write(out + "\n")
  168. async def _read(self, stream, verbose, is_info):
  169. """Ancillary routine to capture while displaying"""
  170. while stream is not None:
  171. line = await stream.readline()
  172. if line:
  173. out = line.decode("utf-8", errors="backslashreplace")
  174. self.log(out, verbose, is_info)
  175. if is_info:
  176. self.stdout += out
  177. else:
  178. self.stderr += out
  179. else:
  180. break
  181. async def run(self, cmd, capture_output=False, check=False,
  182. env=None, verbose=True):
  183. """
  184. Execute an arbitrary command, handling errors.
  185. Please notice that this class is not thread safe
  186. """
  187. self.stdout = ""
  188. self.stderr = ""
  189. self.log("$ " + " ".join(cmd), verbose)
  190. proc = await asyncio.create_subprocess_exec(cmd[0],
  191. *cmd[1:],
  192. env=env,
  193. stdout=asyncio.subprocess.PIPE,
  194. stderr=asyncio.subprocess.PIPE)
  195. # Handle input and output in realtime
  196. await asyncio.gather(
  197. self._read(proc.stdout, verbose, True),
  198. self._read(proc.stderr, verbose, False),
  199. )
  200. await proc.wait()
  201. if check and proc.returncode > 0:
  202. raise subprocess.CalledProcessError(returncode=proc.returncode,
  203. cmd=" ".join(cmd),
  204. output=self.stdout,
  205. stderr=self.stderr)
  206. if capture_output:
  207. if proc.returncode > 0:
  208. self.log(f"Error {proc.returncode}", verbose=True, is_info=False)
  209. return ""
  210. return self.output
  211. ret = subprocess.CompletedProcess(args=cmd,
  212. returncode=proc.returncode,
  213. stdout=self.stdout,
  214. stderr=self.stderr)
  215. return ret
  216. class SphinxVenv:
  217. """
  218. Installs Sphinx on one virtual env per Sphinx version with a minimal
  219. set of dependencies, adjusting them to each specific version.
  220. """
  221. def __init__(self):
  222. """Initialize instance variables"""
  223. self.built_time = {}
  224. self.first_run = True
  225. async def _handle_version(self, args, fp,
  226. cur_ver, cur_requirements, python_bin):
  227. """Handle a single Sphinx version"""
  228. cmd = AsyncCommands(fp)
  229. ver = ".".join(map(str, cur_ver))
  230. if not self.first_run and args.wait_input and args.build:
  231. ret = input("Press Enter to continue or 'a' to abort: ").strip().lower()
  232. if ret == "a":
  233. print("Aborted.")
  234. sys.exit()
  235. else:
  236. self.first_run = False
  237. venv_dir = f"Sphinx_{ver}"
  238. req_file = f"requirements_{ver}.txt"
  239. cmd.log(f"\nSphinx {ver} with {python_bin}", verbose=True)
  240. # Create venv
  241. await cmd.run([python_bin, "-m", "venv", venv_dir],
  242. verbose=args.verbose, check=True)
  243. pip = os.path.join(venv_dir, "bin/pip")
  244. # Create install list
  245. reqs = []
  246. for pkg, verstr in cur_requirements.items():
  247. reqs.append(f"{pkg}=={verstr}")
  248. reqs.append(f"Sphinx=={ver}")
  249. await cmd.run([pip, "install"] + reqs, check=True, verbose=args.verbose)
  250. # Freeze environment
  251. result = await cmd.run([pip, "freeze"], verbose=False, check=True)
  252. # Pip install succeeded. Write requirements file
  253. if args.req_file:
  254. with open(req_file, "w", encoding="utf-8") as fp:
  255. fp.write(result.stdout)
  256. if args.build:
  257. start_time = time.time()
  258. # Prepare a venv environment
  259. env = os.environ.copy()
  260. bin_dir = os.path.join(venv_dir, "bin")
  261. env["PATH"] = bin_dir + ":" + env["PATH"]
  262. env["VIRTUAL_ENV"] = venv_dir
  263. if "PYTHONHOME" in env:
  264. del env["PYTHONHOME"]
  265. # Test doc build
  266. await cmd.run(["make", "cleandocs"], env=env, check=True)
  267. make = ["make"]
  268. if args.output:
  269. sphinx_build = os.path.realpath(f"{bin_dir}/sphinx-build")
  270. make += [f"O={args.output}", f"SPHINXBUILD={sphinx_build}"]
  271. if args.make_args:
  272. make += args.make_args
  273. make += args.targets
  274. if args.verbose:
  275. cmd.log(f". {bin_dir}/activate", verbose=True)
  276. await cmd.run(make, env=env, check=True, verbose=True)
  277. if args.verbose:
  278. cmd.log("deactivate", verbose=True)
  279. end_time = time.time()
  280. elapsed_time = end_time - start_time
  281. hours, minutes = divmod(elapsed_time, 3600)
  282. minutes, seconds = divmod(minutes, 60)
  283. hours = int(hours)
  284. minutes = int(minutes)
  285. seconds = int(seconds)
  286. self.built_time[ver] = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
  287. cmd.log(f"Finished doc build for Sphinx {ver}. Elapsed time: {self.built_time[ver]}", verbose=True)
  288. async def run(self, args):
  289. """
  290. Navigate though multiple Sphinx versions, handling each of them
  291. on a loop.
  292. """
  293. if args.log:
  294. fp = open(args.log, "w", encoding="utf-8")
  295. if not args.verbose:
  296. args.verbose = False
  297. else:
  298. fp = None
  299. if not args.verbose:
  300. args.verbose = True
  301. cur_requirements = {}
  302. python_bin = min_python_bin
  303. vers = set(SPHINX_REQUIREMENTS.keys()) | set(args.versions)
  304. for cur_ver in sorted(vers):
  305. if cur_ver in SPHINX_REQUIREMENTS:
  306. new_reqs = SPHINX_REQUIREMENTS[cur_ver]
  307. cur_requirements.update(new_reqs)
  308. if cur_ver in PYTHON_VER_CHANGES: # pylint: disable=R1715
  309. python_bin = PYTHON_VER_CHANGES[cur_ver]
  310. if cur_ver not in args.versions:
  311. continue
  312. if args.min_version:
  313. if cur_ver < args.min_version:
  314. continue
  315. if args.max_version:
  316. if cur_ver > args.max_version:
  317. break
  318. await self._handle_version(args, fp, cur_ver, cur_requirements,
  319. python_bin)
  320. if args.build:
  321. cmd = AsyncCommands(fp)
  322. cmd.log("\nSummary:", verbose=True)
  323. for ver, elapsed_time in sorted(self.built_time.items()):
  324. cmd.log(f"\tSphinx {ver} elapsed time: {elapsed_time}",
  325. verbose=True)
  326. if fp:
  327. fp.close()
  328. def parse_version(ver_str):
  329. """Convert a version string into a tuple."""
  330. return tuple(map(int, ver_str.split(".")))
  331. DEFAULT_VERS = " - "
  332. DEFAULT_VERS += "\n - ".join(map(lambda v: f"{v[0]}.{v[1]}.{v[2]}",
  333. DEFAULT_VERSIONS_TO_TEST))
  334. SCRIPT = os.path.relpath(__file__)
  335. DESCRIPTION = f"""
  336. This tool allows creating Python virtual environments for different
  337. Sphinx versions that are supported by the Linux Kernel build system.
  338. Besides creating the virtual environment, it can also test building
  339. the documentation using "make htmldocs" (and/or other doc targets).
  340. If called without "--versions" argument, it covers the versions shipped
  341. on major distros, plus the lowest supported version:
  342. {DEFAULT_VERS}
  343. A typical usage is to run:
  344. {SCRIPT} -m -l sphinx_builds.log
  345. This will create one virtual env for the default version set and run
  346. "make htmldocs" for each version, creating a log file with the
  347. excecuted commands on it.
  348. NOTE: The build time can be very long, specially on old versions. Also, there
  349. is a known bug with Sphinx version 6.0.x: each subprocess uses a lot of
  350. memory. That, together with "-jauto" may cause OOM killer to cause
  351. failures at the doc generation. To minimize the risk, you may use the
  352. "-a" command line parameter to constrain the built directories and/or
  353. reduce the number of threads from "-jauto" to, for instance, "-j4":
  354. {SCRIPT} -m -V 6.0.1 -a "SPHINXDIRS=process" "SPHINXOPTS='-j4'"
  355. """
  356. MAKE_TARGETS = [
  357. "htmldocs",
  358. "texinfodocs",
  359. "infodocs",
  360. "latexdocs",
  361. "pdfdocs",
  362. "epubdocs",
  363. "xmldocs",
  364. ]
  365. async def main():
  366. """Main program"""
  367. parser = argparse.ArgumentParser(description=DESCRIPTION,
  368. formatter_class=argparse.RawDescriptionHelpFormatter)
  369. ver_group = parser.add_argument_group("Version range options")
  370. ver_group.add_argument('-V', '--versions', nargs="*",
  371. default=DEFAULT_VERSIONS_TO_TEST,type=parse_version,
  372. help='Sphinx versions to test')
  373. ver_group.add_argument('--min-version', "--min", type=parse_version,
  374. help='Sphinx minimal version')
  375. ver_group.add_argument('--max-version', "--max", type=parse_version,
  376. help='Sphinx maximum version')
  377. ver_group.add_argument('-f', '--full', action='store_true',
  378. help='Add all Sphinx (major,minor) supported versions to the version range')
  379. build_group = parser.add_argument_group("Build options")
  380. build_group.add_argument('-b', '--build', action='store_true',
  381. help='Build documentation')
  382. build_group.add_argument('-a', '--make-args', nargs="*",
  383. help='extra arguments for make, like SPHINXDIRS=netlink/specs',
  384. )
  385. build_group.add_argument('-t', '--targets', nargs="+", choices=MAKE_TARGETS,
  386. default=[MAKE_TARGETS[0]],
  387. help="make build targets. Default: htmldocs.")
  388. build_group.add_argument("-o", '--output',
  389. help="output directory for the make O=OUTPUT")
  390. other_group = parser.add_argument_group("Other options")
  391. other_group.add_argument('-r', '--req-file', action='store_true',
  392. help='write a requirements.txt file')
  393. other_group.add_argument('-l', '--log',
  394. help='Log command output on a file')
  395. other_group.add_argument('-v', '--verbose', action='store_true',
  396. help='Verbose all commands')
  397. other_group.add_argument('-i', '--wait-input', action='store_true',
  398. help='Wait for an enter before going to the next version')
  399. args = parser.parse_args()
  400. if not args.make_args:
  401. args.make_args = []
  402. sphinx_versions = sorted(list(SPHINX_REQUIREMENTS.keys()))
  403. if args.full:
  404. args.versions += list(SPHINX_REQUIREMENTS.keys())
  405. venv = SphinxVenv()
  406. await venv.run(args)
  407. # Call main method
  408. if __name__ == "__main__":
  409. asyncio.run(main())