sphinx-pre-install 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0-or-later
  3. # Copyright (c) 2017-2025 Mauro Carvalho Chehab <mchehab+huawei@kernel.org>
  4. #
  5. # pylint: disable=C0103,C0114,C0115,C0116,C0301,C0302
  6. # pylint: disable=R0902,R0904,R0911,R0912,R0914,R0915,R1705,R1710,E1121
  7. # Note: this script requires at least Python 3.6 to run.
  8. # Don't add changes not compatible with it, it is meant to report
  9. # incompatible python versions.
  10. """
  11. Dependency checker for Sphinx documentation Kernel build.
  12. This module provides tools to check for all required dependencies needed to
  13. build documentation using Sphinx, including system packages, Python modules
  14. and LaTeX packages for PDF generation.
  15. It detect packages for a subset of Linux distributions used by Kernel
  16. maintainers, showing hints and missing dependencies.
  17. The main class SphinxDependencyChecker handles the dependency checking logic
  18. and provides recommendations for installing missing packages. It supports both
  19. system package installations and Python virtual environments. By default,
  20. system pacage install is recommended.
  21. """
  22. import argparse
  23. import locale
  24. import os
  25. import re
  26. import subprocess
  27. import sys
  28. from glob import glob
  29. import os.path
  30. src_dir = os.path.dirname(os.path.realpath(__file__))
  31. sys.path.insert(0, os.path.join(src_dir, '../lib/python'))
  32. from kdoc.python_version import PythonVersion
  33. RECOMMENDED_VERSION = PythonVersion("3.4.3").version
  34. MIN_PYTHON_VERSION = PythonVersion("3.7").version
  35. class DepManager:
  36. """
  37. Manage package dependencies. There are three types of dependencies:
  38. - System: dependencies required for docs build;
  39. - Python: python dependencies for a native distro Sphinx install;
  40. - PDF: dependencies needed by PDF builds.
  41. Each dependency can be mandatory or optional. Not installing an optional
  42. dependency won't break the build, but will cause degradation at the
  43. docs output.
  44. """
  45. # Internal types of dependencies. Don't use them outside DepManager class.
  46. _SYS_TYPE = 0
  47. _PHY_TYPE = 1
  48. _PDF_TYPE = 2
  49. # Dependencies visible outside the class.
  50. # The keys are tuple with: (type, is_mandatory flag).
  51. #
  52. # Currently we're not using all optional dep types. Yet, we'll keep all
  53. # possible combinations here. They're not many, and that makes easier
  54. # if later needed and for the name() method below
  55. SYSTEM_MANDATORY = (_SYS_TYPE, True)
  56. PYTHON_MANDATORY = (_PHY_TYPE, True)
  57. PDF_MANDATORY = (_PDF_TYPE, True)
  58. SYSTEM_OPTIONAL = (_SYS_TYPE, False)
  59. PYTHON_OPTIONAL = (_PHY_TYPE, False)
  60. PDF_OPTIONAL = (_PDF_TYPE, True)
  61. def __init__(self, pdf):
  62. """
  63. Initialize internal vars:
  64. - missing: missing dependencies list, containing a distro-independent
  65. name for a missing dependency and its type.
  66. - missing_pkg: ancillary dict containing missing dependencies in
  67. distro namespace, organized by type.
  68. - need: total number of needed dependencies. Never cleaned.
  69. - optional: total number of optional dependencies. Never cleaned.
  70. - pdf: Is PDF support enabled?
  71. """
  72. self.missing = {}
  73. self.missing_pkg = {}
  74. self.need = 0
  75. self.optional = 0
  76. self.pdf = pdf
  77. @staticmethod
  78. def name(dtype):
  79. """
  80. Ancillary routine to output a warn/error message reporting
  81. missing dependencies.
  82. """
  83. if dtype[0] == DepManager._SYS_TYPE:
  84. msg = "build"
  85. elif dtype[0] == DepManager._PHY_TYPE:
  86. msg = "Python"
  87. else:
  88. msg = "PDF"
  89. if dtype[1]:
  90. return f"ERROR: {msg} mandatory deps missing"
  91. else:
  92. return f"Warning: {msg} optional deps missing"
  93. @staticmethod
  94. def is_optional(dtype):
  95. """Ancillary routine to report if a dependency is optional"""
  96. return not dtype[1]
  97. @staticmethod
  98. def is_pdf(dtype):
  99. """Ancillary routine to report if a dependency is for PDF generation"""
  100. if dtype[0] == DepManager._PDF_TYPE:
  101. return True
  102. return False
  103. def add_package(self, package, dtype):
  104. """
  105. Add a package at the self.missing() dictionary.
  106. Doesn't update missing_pkg.
  107. """
  108. is_optional = DepManager.is_optional(dtype)
  109. self.missing[package] = dtype
  110. if is_optional:
  111. self.optional += 1
  112. else:
  113. self.need += 1
  114. def del_package(self, package):
  115. """
  116. Remove a package at the self.missing() dictionary.
  117. Doesn't update missing_pkg.
  118. """
  119. if package in self.missing:
  120. del self.missing[package]
  121. def clear_deps(self):
  122. """
  123. Clear dependencies without changing needed/optional.
  124. This is an ackward way to have a separate section to recommend
  125. a package after system main dependencies.
  126. TODO: rework the logic to prevent needing it.
  127. """
  128. self.missing = {}
  129. self.missing_pkg = {}
  130. def check_missing(self, progs):
  131. """
  132. Update self.missing_pkg, using progs dict to convert from the
  133. agnostic package name to distro-specific one.
  134. Returns an string with the packages to be installed, sorted and
  135. with eventual duplicates removed.
  136. """
  137. self.missing_pkg = {}
  138. for prog, dtype in sorted(self.missing.items()):
  139. # At least on some LTS distros like CentOS 7, texlive doesn't
  140. # provide all packages we need. When such distros are
  141. # detected, we have to disable PDF output.
  142. #
  143. # So, we need to ignore the packages that distros would
  144. # need for LaTeX to work
  145. if DepManager.is_pdf(dtype) and not self.pdf:
  146. self.optional -= 1
  147. continue
  148. if not dtype in self.missing_pkg:
  149. self.missing_pkg[dtype] = []
  150. self.missing_pkg[dtype].append(progs.get(prog, prog))
  151. install = []
  152. for dtype, pkgs in self.missing_pkg.items():
  153. install += pkgs
  154. return " ".join(sorted(set(install)))
  155. def warn_install(self):
  156. """
  157. Emit warnings/errors related to missing packages.
  158. """
  159. output_msg = ""
  160. for dtype in sorted(self.missing_pkg.keys()):
  161. progs = " ".join(sorted(set(self.missing_pkg[dtype])))
  162. try:
  163. name = DepManager.name(dtype)
  164. output_msg += f'{name}:\t{progs}\n'
  165. except KeyError:
  166. raise KeyError(f"ERROR!!!: invalid dtype for {progs}: {dtype}")
  167. if output_msg:
  168. print(f"\n{output_msg}")
  169. class AncillaryMethods:
  170. """
  171. Ancillary methods that checks for missing dependencies for different
  172. types of types, like binaries, python modules, rpm deps, etc.
  173. """
  174. @staticmethod
  175. def which(prog):
  176. """
  177. Our own implementation of which(). We could instead use
  178. shutil.which(), but this function is simple enough.
  179. Probably faster to use this implementation than to import shutil.
  180. """
  181. for path in os.environ.get("PATH", "").split(":"):
  182. full_path = os.path.join(path, prog)
  183. if os.access(full_path, os.X_OK):
  184. return full_path
  185. return None
  186. @staticmethod
  187. def run(*args, **kwargs):
  188. """
  189. Excecute a command, hiding its output by default.
  190. Preserve compatibility with older Python versions.
  191. """
  192. capture_output = kwargs.pop('capture_output', False)
  193. if capture_output:
  194. if 'stdout' not in kwargs:
  195. kwargs['stdout'] = subprocess.PIPE
  196. if 'stderr' not in kwargs:
  197. kwargs['stderr'] = subprocess.PIPE
  198. else:
  199. if 'stdout' not in kwargs:
  200. kwargs['stdout'] = subprocess.DEVNULL
  201. if 'stderr' not in kwargs:
  202. kwargs['stderr'] = subprocess.DEVNULL
  203. # Don't break with older Python versions
  204. if 'text' in kwargs and sys.version_info < (3, 7):
  205. kwargs['universal_newlines'] = kwargs.pop('text')
  206. return subprocess.run(*args, **kwargs)
  207. class MissingCheckers(AncillaryMethods):
  208. """
  209. Contains some ancillary checkers for different types of binaries and
  210. package managers.
  211. """
  212. def __init__(self, args, texlive):
  213. """
  214. Initialize its internal variables
  215. """
  216. self.pdf = args.pdf
  217. self.virtualenv = args.virtualenv
  218. self.version_check = args.version_check
  219. self.texlive = texlive
  220. self.min_version = (0, 0, 0)
  221. self.cur_version = (0, 0, 0)
  222. self.deps = DepManager(self.pdf)
  223. self.need_symlink = 0
  224. self.need_sphinx = 0
  225. self.verbose_warn_install = 1
  226. self.virtenv_dir = ""
  227. self.install = ""
  228. self.python_cmd = ""
  229. self.virtenv_prefix = ["sphinx_", "Sphinx_" ]
  230. def check_missing_file(self, files, package, dtype):
  231. """
  232. Does the file exists? If not, add it to missing dependencies.
  233. """
  234. for f in files:
  235. if os.path.exists(f):
  236. return
  237. self.deps.add_package(package, dtype)
  238. def check_program(self, prog, dtype):
  239. """
  240. Does the program exists and it is at the PATH?
  241. If not, add it to missing dependencies.
  242. """
  243. found = self.which(prog)
  244. if found:
  245. return found
  246. self.deps.add_package(prog, dtype)
  247. return None
  248. def check_perl_module(self, prog, dtype):
  249. """
  250. Does perl have a dependency? Is it available?
  251. If not, add it to missing dependencies.
  252. Right now, we still need Perl for doc build, as it is required
  253. by some tools called at docs or kernel build time, like:
  254. tools/docs/documentation-file-ref-check
  255. Also, checkpatch is on Perl.
  256. """
  257. # While testing with lxc download template, one of the
  258. # distros (Oracle) didn't have perl - nor even an option to install
  259. # before installing oraclelinux-release-el9 package.
  260. #
  261. # Check it before running an error. If perl is not there,
  262. # add it as a mandatory package, as some parts of the doc builder
  263. # needs it.
  264. if not self.which("perl"):
  265. self.deps.add_package("perl", DepManager.SYSTEM_MANDATORY)
  266. self.deps.add_package(prog, dtype)
  267. return
  268. try:
  269. self.run(["perl", f"-M{prog}", "-e", "1"], check=True)
  270. except subprocess.CalledProcessError:
  271. self.deps.add_package(prog, dtype)
  272. def check_python_module(self, module, is_optional=False):
  273. """
  274. Does a python module exists outside venv? If not, add it to missing
  275. dependencies.
  276. """
  277. if is_optional:
  278. dtype = DepManager.PYTHON_OPTIONAL
  279. else:
  280. dtype = DepManager.PYTHON_MANDATORY
  281. try:
  282. self.run([self.python_cmd, "-c", f"import {module}"], check=True)
  283. except subprocess.CalledProcessError:
  284. self.deps.add_package(module, dtype)
  285. def check_rpm_missing(self, pkgs, dtype):
  286. """
  287. Does a rpm package exists? If not, add it to missing dependencies.
  288. """
  289. for prog in pkgs:
  290. try:
  291. self.run(["rpm", "-q", prog], check=True)
  292. except subprocess.CalledProcessError:
  293. self.deps.add_package(prog, dtype)
  294. def check_pacman_missing(self, pkgs, dtype):
  295. """
  296. Does a pacman package exists? If not, add it to missing dependencies.
  297. """
  298. for prog in pkgs:
  299. try:
  300. self.run(["pacman", "-Q", prog], check=True)
  301. except subprocess.CalledProcessError:
  302. self.deps.add_package(prog, dtype)
  303. def check_missing_tex(self, is_optional=False):
  304. """
  305. Does a LaTeX package exists? If not, add it to missing dependencies.
  306. """
  307. if is_optional:
  308. dtype = DepManager.PDF_OPTIONAL
  309. else:
  310. dtype = DepManager.PDF_MANDATORY
  311. kpsewhich = self.which("kpsewhich")
  312. for prog, package in self.texlive.items():
  313. # If kpsewhich is not there, just add it to deps
  314. if not kpsewhich:
  315. self.deps.add_package(package, dtype)
  316. continue
  317. # Check if the package is needed
  318. try:
  319. result = self.run(
  320. [kpsewhich, prog], stdout=subprocess.PIPE, text=True, check=True
  321. )
  322. # Didn't find. Add it
  323. if not result.stdout.strip():
  324. self.deps.add_package(package, dtype)
  325. except subprocess.CalledProcessError:
  326. # kpsewhich returned an error. Add it, just in case
  327. self.deps.add_package(package, dtype)
  328. def get_sphinx_fname(self):
  329. """
  330. Gets the binary filename for sphinx-build.
  331. """
  332. if "SPHINXBUILD" in os.environ:
  333. return os.environ["SPHINXBUILD"]
  334. fname = "sphinx-build"
  335. if self.which(fname):
  336. return fname
  337. fname = "sphinx-build-3"
  338. if self.which(fname):
  339. self.need_symlink = 1
  340. return fname
  341. return ""
  342. def get_sphinx_version(self, cmd):
  343. """
  344. Gets sphinx-build version.
  345. """
  346. env = os.environ.copy()
  347. # The sphinx-build tool has a bug: internally, it tries to set
  348. # locale with locale.setlocale(locale.LC_ALL, ''). This causes a
  349. # crash if language is not set. Detect and fix it.
  350. try:
  351. locale.setlocale(locale.LC_ALL, '')
  352. except Exception:
  353. env["LC_ALL"] = "C"
  354. env["LANG"] = "C"
  355. try:
  356. result = self.run([cmd, "--version"], env=env,
  357. stdout=subprocess.PIPE,
  358. stderr=subprocess.STDOUT,
  359. text=True, check=True)
  360. except (subprocess.CalledProcessError, FileNotFoundError):
  361. return None
  362. for line in result.stdout.split("\n"):
  363. match = re.match(r"^sphinx-build\s+([\d\.]+)(?:\+(?:/[\da-f]+)|b\d+)?\s*$", line)
  364. if match:
  365. return PythonVersion.parse_version(match.group(1))
  366. match = re.match(r"^Sphinx.*\s+([\d\.]+)\s*$", line)
  367. if match:
  368. return PythonVersion.parse_version(match.group(1))
  369. def check_sphinx(self, conf):
  370. """
  371. Checks Sphinx minimal requirements
  372. """
  373. try:
  374. with open(conf, "r", encoding="utf-8") as f:
  375. for line in f:
  376. match = re.match(r"^\s*needs_sphinx\s*=\s*[\'\"]([\d\.]+)[\'\"]", line)
  377. if match:
  378. self.min_version = PythonVersion.parse_version(match.group(1))
  379. break
  380. except IOError:
  381. sys.exit(f"Can't open {conf}")
  382. if not self.min_version:
  383. sys.exit(f"Can't get needs_sphinx version from {conf}")
  384. self.virtenv_dir = self.virtenv_prefix[0] + "latest"
  385. sphinx = self.get_sphinx_fname()
  386. if not sphinx:
  387. self.need_sphinx = 1
  388. return
  389. self.cur_version = self.get_sphinx_version(sphinx)
  390. if not self.cur_version:
  391. sys.exit(f"{sphinx} didn't return its version")
  392. if self.cur_version < self.min_version:
  393. curver = PythonVersion.ver_str(self.cur_version)
  394. minver = PythonVersion.ver_str(self.min_version)
  395. print(f"ERROR: Sphinx version is {curver}. It should be >= {minver}")
  396. self.need_sphinx = 1
  397. return
  398. # On version check mode, just assume Sphinx has all mandatory deps
  399. if self.version_check and self.cur_version >= RECOMMENDED_VERSION:
  400. sys.exit(0)
  401. def catcheck(self, filename):
  402. """
  403. Reads a file if it exists, returning as string.
  404. If not found, returns an empty string.
  405. """
  406. if os.path.exists(filename):
  407. with open(filename, "r", encoding="utf-8") as f:
  408. return f.read().strip()
  409. return ""
  410. def get_system_release(self):
  411. """
  412. Determine the system type. There's no unique way that would work
  413. with all distros with a minimal package install. So, several
  414. methods are used here.
  415. By default, it will use lsb_release function. If not available, it will
  416. fail back to reading the known different places where the distro name
  417. is stored.
  418. Several modern distros now have /etc/os-release, which usually have
  419. a decent coverage.
  420. """
  421. system_release = ""
  422. if self.which("lsb_release"):
  423. result = self.run(["lsb_release", "-d"], capture_output=True, text=True)
  424. system_release = result.stdout.replace("Description:", "").strip()
  425. release_files = [
  426. "/etc/system-release",
  427. "/etc/redhat-release",
  428. "/etc/lsb-release",
  429. "/etc/gentoo-release",
  430. ]
  431. if not system_release:
  432. for f in release_files:
  433. system_release = self.catcheck(f)
  434. if system_release:
  435. break
  436. # This seems more common than LSB these days
  437. if not system_release:
  438. os_var = {}
  439. try:
  440. with open("/etc/os-release", "r", encoding="utf-8") as f:
  441. for line in f:
  442. match = re.match(r"^([\w\d\_]+)=\"?([^\"]*)\"?\n", line)
  443. if match:
  444. os_var[match.group(1)] = match.group(2)
  445. system_release = os_var.get("NAME", "")
  446. if "VERSION_ID" in os_var:
  447. system_release += " " + os_var["VERSION_ID"]
  448. elif "VERSION" in os_var:
  449. system_release += " " + os_var["VERSION"]
  450. except IOError:
  451. pass
  452. if not system_release:
  453. system_release = self.catcheck("/etc/issue")
  454. system_release = system_release.strip()
  455. return system_release
  456. class SphinxDependencyChecker(MissingCheckers):
  457. """
  458. Main class for checking Sphinx documentation build dependencies.
  459. - Check for missing system packages;
  460. - Check for missing Python modules;
  461. - Check for missing LaTeX packages needed by PDF generation;
  462. - Propose Sphinx install via Python Virtual environment;
  463. - Propose Sphinx install via distro-specific package install.
  464. """
  465. def __init__(self, args):
  466. """Initialize checker variables"""
  467. # List of required texlive packages on Fedora and OpenSuse
  468. texlive = {
  469. "amsfonts.sty": "texlive-amsfonts",
  470. "amsmath.sty": "texlive-amsmath",
  471. "amssymb.sty": "texlive-amsfonts",
  472. "amsthm.sty": "texlive-amscls",
  473. "anyfontsize.sty": "texlive-anyfontsize",
  474. "atbegshi.sty": "texlive-oberdiek",
  475. "bm.sty": "texlive-tools",
  476. "capt-of.sty": "texlive-capt-of",
  477. "cmap.sty": "texlive-cmap",
  478. "ctexhook.sty": "texlive-ctex",
  479. "ecrm1000.tfm": "texlive-ec",
  480. "eqparbox.sty": "texlive-eqparbox",
  481. "eu1enc.def": "texlive-euenc",
  482. "fancybox.sty": "texlive-fancybox",
  483. "fancyvrb.sty": "texlive-fancyvrb",
  484. "float.sty": "texlive-float",
  485. "fncychap.sty": "texlive-fncychap",
  486. "footnote.sty": "texlive-mdwtools",
  487. "framed.sty": "texlive-framed",
  488. "luatex85.sty": "texlive-luatex85",
  489. "multirow.sty": "texlive-multirow",
  490. "needspace.sty": "texlive-needspace",
  491. "palatino.sty": "texlive-psnfss",
  492. "parskip.sty": "texlive-parskip",
  493. "polyglossia.sty": "texlive-polyglossia",
  494. "tabulary.sty": "texlive-tabulary",
  495. "threeparttable.sty": "texlive-threeparttable",
  496. "titlesec.sty": "texlive-titlesec",
  497. "ucs.sty": "texlive-ucs",
  498. "upquote.sty": "texlive-upquote",
  499. "wrapfig.sty": "texlive-wrapfig",
  500. }
  501. super().__init__(args, texlive)
  502. self.need_pip = False
  503. self.rec_sphinx_upgrade = 0
  504. self.system_release = self.get_system_release()
  505. self.activate_cmd = ""
  506. # Some distros may not have a Sphinx shipped package compatible with
  507. # our minimal requirements
  508. self.package_supported = True
  509. # Recommend a new python version
  510. self.recommend_python = None
  511. # Certain hints are meant to be shown only once
  512. self.distro_msg = None
  513. self.latest_avail_ver = (0, 0, 0)
  514. self.venv_ver = (0, 0, 0)
  515. prefix = os.environ.get("srctree", ".") + "/"
  516. self.conf = prefix + "Documentation/conf.py"
  517. self.requirement_file = prefix + "Documentation/sphinx/requirements.txt"
  518. def get_install_progs(self, progs, cmd, extra=None):
  519. """
  520. Check for missing dependencies using the provided program mapping.
  521. The actual distro-specific programs are mapped via progs argument.
  522. """
  523. install = self.deps.check_missing(progs)
  524. if self.verbose_warn_install:
  525. self.deps.warn_install()
  526. if not install:
  527. return
  528. if cmd:
  529. if self.verbose_warn_install:
  530. msg = "You should run:"
  531. else:
  532. msg = ""
  533. if extra:
  534. msg += "\n\t" + extra.replace("\n", "\n\t")
  535. return(msg + "\n\tsudo " + cmd + " " + install)
  536. return None
  537. #
  538. # Distro-specific hints methods
  539. #
  540. def give_debian_hints(self):
  541. """
  542. Provide package installation hints for Debian-based distros.
  543. """
  544. progs = {
  545. "Pod::Usage": "perl-modules",
  546. "convert": "imagemagick",
  547. "dot": "graphviz",
  548. "ensurepip": "python3-venv",
  549. "python-sphinx": "python3-sphinx",
  550. "rsvg-convert": "librsvg2-bin",
  551. "virtualenv": "virtualenv",
  552. "xelatex": "texlive-xetex",
  553. "yaml": "python3-yaml",
  554. }
  555. if self.pdf:
  556. pdf_pkgs = {
  557. "fonts-dejavu": [
  558. "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
  559. ],
  560. "fonts-noto-cjk": [
  561. "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc",
  562. "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
  563. "/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc",
  564. ],
  565. "tex-gyre": [
  566. "/usr/share/texmf/tex/latex/tex-gyre/tgtermes.sty"
  567. ],
  568. "texlive-fonts-recommended": [
  569. "/usr/share/texlive/texmf-dist/fonts/tfm/adobe/zapfding/pzdr.tfm",
  570. ],
  571. "texlive-lang-chinese": [
  572. "/usr/share/texlive/texmf-dist/tex/latex/ctex/ctexhook.sty",
  573. ],
  574. }
  575. for package, files in pdf_pkgs.items():
  576. self.check_missing_file(files, package, DepManager.PDF_MANDATORY)
  577. self.check_program("dvipng", DepManager.PDF_MANDATORY)
  578. if not self.distro_msg:
  579. self.distro_msg = \
  580. "Note: ImageMagick is broken on some distros, affecting PDF output. For more details:\n" \
  581. "\thttps://askubuntu.com/questions/1158894/imagemagick-still-broken-using-with-usr-bin-convert"
  582. return self.get_install_progs(progs, "apt-get install")
  583. def give_redhat_hints(self):
  584. """
  585. Provide package installation hints for RedHat-based distros
  586. (Fedora, RHEL and RHEL-based variants).
  587. """
  588. progs = {
  589. "Pod::Usage": "perl-Pod-Usage",
  590. "convert": "ImageMagick",
  591. "dot": "graphviz",
  592. "python-sphinx": "python3-sphinx",
  593. "rsvg-convert": "librsvg2-tools",
  594. "virtualenv": "python3-virtualenv",
  595. "xelatex": "texlive-xetex-bin",
  596. "yaml": "python3-pyyaml",
  597. }
  598. fedora_tex_pkgs = [
  599. "dejavu-sans-fonts",
  600. "dejavu-sans-mono-fonts",
  601. "dejavu-serif-fonts",
  602. "texlive-collection-fontsrecommended",
  603. "texlive-collection-latex",
  604. "texlive-xecjk",
  605. ]
  606. fedora = False
  607. rel = None
  608. match = re.search(r"(release|Linux)\s+(\d+)", self.system_release)
  609. if match:
  610. rel = int(match.group(2))
  611. if not rel:
  612. print("Couldn't identify release number")
  613. noto_sans_redhat = None
  614. self.pdf = False
  615. elif re.search("Fedora", self.system_release):
  616. # Fedora 38 and upper use this CJK font
  617. noto_sans_redhat = "google-noto-sans-cjk-fonts"
  618. fedora = True
  619. else:
  620. # Almalinux, CentOS, RHEL, ...
  621. # at least up to version 9 (and Fedora < 38), that's the CJK font
  622. noto_sans_redhat = "google-noto-sans-cjk-ttc-fonts"
  623. progs["virtualenv"] = "python-virtualenv"
  624. if not rel or rel < 8:
  625. print("ERROR: Distro not supported. Too old?")
  626. return
  627. # RHEL 8 uses Python 3.6, which is not compatible with
  628. # the build system anymore. Suggest Python 3.11
  629. if rel == 8:
  630. self.check_program("python3.9", DepManager.SYSTEM_MANDATORY)
  631. progs["python3.9"] = "python39"
  632. progs["yaml"] = "python39-pyyaml"
  633. self.recommend_python = True
  634. # There's no python39-sphinx package. Only pip is supported
  635. self.package_supported = False
  636. if not self.distro_msg:
  637. self.distro_msg = \
  638. "Note: RHEL-based distros typically require extra repositories.\n" \
  639. "For most, enabling epel and crb are enough:\n" \
  640. "\tsudo dnf install -y epel-release\n" \
  641. "\tsudo dnf config-manager --set-enabled crb\n" \
  642. "Yet, some may have other required repositories. Those commands could be useful:\n" \
  643. "\tsudo dnf repolist all\n" \
  644. "\tsudo dnf repoquery --available --info <pkgs>\n" \
  645. "\tsudo dnf config-manager --set-enabled '*' # enable all - probably not what you want"
  646. if self.pdf:
  647. pdf_pkgs = [
  648. "/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc",
  649. "/usr/share/fonts/google-noto-sans-cjk-fonts/NotoSansCJK-Regular.ttc",
  650. ]
  651. self.check_missing_file(pdf_pkgs, noto_sans_redhat, DepManager.PDF_MANDATORY)
  652. self.check_rpm_missing(fedora_tex_pkgs, DepManager.PDF_MANDATORY)
  653. self.check_missing_tex(DepManager.PDF_MANDATORY)
  654. # There's no texlive-ctex on RHEL 8 repositories. This will
  655. # likely affect CJK pdf build only.
  656. if not fedora and rel == 8:
  657. self.deps.del_package("texlive-ctex")
  658. return self.get_install_progs(progs, "dnf install")
  659. def give_opensuse_hints(self):
  660. """
  661. Provide package installation hints for openSUSE-based distros
  662. (Leap and Tumbleweed).
  663. """
  664. progs = {
  665. "Pod::Usage": "perl-Pod-Usage",
  666. "convert": "ImageMagick",
  667. "dot": "graphviz",
  668. "python-sphinx": "python3-sphinx",
  669. "virtualenv": "python3-virtualenv",
  670. "xelatex": "texlive-xetex-bin texlive-dejavu",
  671. "yaml": "python3-pyyaml",
  672. }
  673. suse_tex_pkgs = [
  674. "texlive-babel-english",
  675. "texlive-caption",
  676. "texlive-colortbl",
  677. "texlive-courier",
  678. "texlive-dvips",
  679. "texlive-helvetic",
  680. "texlive-makeindex",
  681. "texlive-metafont",
  682. "texlive-metapost",
  683. "texlive-palatino",
  684. "texlive-preview",
  685. "texlive-times",
  686. "texlive-zapfchan",
  687. "texlive-zapfding",
  688. ]
  689. progs["latexmk"] = "texlive-latexmk-bin"
  690. match = re.search(r"(Leap)\s+(\d+).(\d)", self.system_release)
  691. if match:
  692. rel = int(match.group(2))
  693. # Leap 15.x uses Python 3.6, which is not compatible with
  694. # the build system anymore. Suggest Python 3.11
  695. if rel == 15:
  696. if not self.which(self.python_cmd):
  697. self.check_program("python3.11", DepManager.SYSTEM_MANDATORY)
  698. progs["python3.11"] = "python311"
  699. self.recommend_python = True
  700. progs.update({
  701. "python-sphinx": "python311-Sphinx python311-Sphinx-latex",
  702. "virtualenv": "python311-virtualenv",
  703. "yaml": "python311-PyYAML",
  704. })
  705. else:
  706. # Tumbleweed defaults to Python 3.11
  707. progs.update({
  708. "python-sphinx": "python313-Sphinx python313-Sphinx-latex",
  709. "virtualenv": "python313-virtualenv",
  710. "yaml": "python313-PyYAML",
  711. })
  712. # FIXME: add support for installing CJK fonts
  713. #
  714. # I tried hard, but was unable to find a way to install
  715. # "Noto Sans CJK SC" on openSUSE
  716. if self.pdf:
  717. self.check_rpm_missing(suse_tex_pkgs, DepManager.PDF_MANDATORY)
  718. if self.pdf:
  719. self.check_missing_tex()
  720. return self.get_install_progs(progs, "zypper install --no-recommends")
  721. def give_mageia_hints(self):
  722. """
  723. Provide package installation hints for Mageia and OpenMandriva.
  724. """
  725. progs = {
  726. "Pod::Usage": "perl-Pod-Usage",
  727. "convert": "ImageMagick",
  728. "dot": "graphviz",
  729. "python-sphinx": "python3-sphinx",
  730. "rsvg-convert": "librsvg2",
  731. "virtualenv": "python3-virtualenv",
  732. "xelatex": "texlive",
  733. "yaml": "python3-yaml",
  734. }
  735. tex_pkgs = [
  736. "texlive-fontsextra",
  737. "texlive-fonts-asian",
  738. "fonts-ttf-dejavu",
  739. ]
  740. if re.search(r"OpenMandriva", self.system_release):
  741. packager_cmd = "dnf install"
  742. noto_sans = "noto-sans-cjk-fonts"
  743. tex_pkgs = [
  744. "texlive-collection-basic",
  745. "texlive-collection-langcjk",
  746. "texlive-collection-fontsextra",
  747. "texlive-collection-fontsrecommended"
  748. ]
  749. # Tested on OpenMandriva Lx 4.3
  750. progs["convert"] = "imagemagick"
  751. progs["yaml"] = "python-pyyaml"
  752. progs["python-virtualenv"] = "python-virtualenv"
  753. progs["python-sphinx"] = "python-sphinx"
  754. progs["xelatex"] = "texlive"
  755. self.check_program("python-virtualenv", DepManager.PYTHON_MANDATORY)
  756. # On my tests with openMandriva LX 4.0 docker image, upgraded
  757. # to 4.3, python-virtualenv package is broken: it is missing
  758. # ensurepip. Without it, the alternative would be to run:
  759. # python3 -m venv --without-pip ~/sphinx_latest, but running
  760. # pip there won't install sphinx at venv.
  761. #
  762. # Add a note about that.
  763. if not self.distro_msg:
  764. self.distro_msg = \
  765. "Notes:\n"\
  766. "1. for venv, ensurepip could be broken, preventing its install method.\n" \
  767. "2. at least on OpenMandriva LX 4.3, texlive packages seem broken"
  768. else:
  769. packager_cmd = "urpmi"
  770. noto_sans = "google-noto-sans-cjk-ttc-fonts"
  771. progs["latexmk"] = "texlive-collection-basic"
  772. if self.pdf:
  773. pdf_pkgs = [
  774. "/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc",
  775. "/usr/share/fonts/TTF/NotoSans-Regular.ttf",
  776. ]
  777. self.check_missing_file(pdf_pkgs, noto_sans, DepManager.PDF_MANDATORY)
  778. self.check_rpm_missing(tex_pkgs, DepManager.PDF_MANDATORY)
  779. return self.get_install_progs(progs, packager_cmd)
  780. def give_arch_linux_hints(self):
  781. """
  782. Provide package installation hints for ArchLinux.
  783. """
  784. progs = {
  785. "convert": "imagemagick",
  786. "dot": "graphviz",
  787. "latexmk": "texlive-core",
  788. "rsvg-convert": "extra/librsvg",
  789. "virtualenv": "python-virtualenv",
  790. "xelatex": "texlive-xetex",
  791. "yaml": "python-yaml",
  792. }
  793. archlinux_tex_pkgs = [
  794. "texlive-basic",
  795. "texlive-binextra",
  796. "texlive-core",
  797. "texlive-fontsrecommended",
  798. "texlive-langchinese",
  799. "texlive-langcjk",
  800. "texlive-latexextra",
  801. "ttf-dejavu",
  802. ]
  803. if self.pdf:
  804. self.check_pacman_missing(archlinux_tex_pkgs,
  805. DepManager.PDF_MANDATORY)
  806. self.check_missing_file(["/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc"],
  807. "noto-fonts-cjk",
  808. DepManager.PDF_MANDATORY)
  809. return self.get_install_progs(progs, "pacman -S")
  810. def give_gentoo_hints(self):
  811. """
  812. Provide package installation hints for Gentoo.
  813. """
  814. texlive_deps = [
  815. "dev-texlive/texlive-fontsrecommended",
  816. "dev-texlive/texlive-latexextra",
  817. "dev-texlive/texlive-xetex",
  818. "media-fonts/dejavu",
  819. ]
  820. progs = {
  821. "convert": "media-gfx/imagemagick",
  822. "dot": "media-gfx/graphviz",
  823. "rsvg-convert": "gnome-base/librsvg",
  824. "virtualenv": "dev-python/virtualenv",
  825. "xelatex": " ".join(texlive_deps),
  826. "yaml": "dev-python/pyyaml",
  827. "python-sphinx": "dev-python/sphinx",
  828. }
  829. if self.pdf:
  830. pdf_pkgs = {
  831. "media-fonts/dejavu": [
  832. "/usr/share/fonts/dejavu/DejaVuSans.ttf",
  833. ],
  834. "media-fonts/noto-cjk": [
  835. "/usr/share/fonts/noto-cjk/NotoSansCJKsc-Regular.otf",
  836. "/usr/share/fonts/noto-cjk/NotoSerifCJK-Regular.ttc",
  837. ],
  838. }
  839. for package, files in pdf_pkgs.items():
  840. self.check_missing_file(files, package, DepManager.PDF_MANDATORY)
  841. # Handling dependencies is a nightmare, as Gentoo refuses to emerge
  842. # some packages if there's no package.use file describing them.
  843. # To make it worse, compilation flags shall also be present there
  844. # for some packages. If USE is not perfect, error/warning messages
  845. # like those are shown:
  846. #
  847. # !!! The following binary packages have been ignored due to non matching USE:
  848. #
  849. # =media-gfx/graphviz-12.2.1-r1 X pdf -python_single_target_python3_13 qt6 svg
  850. # =media-gfx/graphviz-12.2.1-r1 X pdf python_single_target_python3_12 -python_single_target_python3_13 qt6 svg
  851. # =media-gfx/graphviz-12.2.1-r1 X pdf qt6 svg
  852. # =media-gfx/graphviz-12.2.1-r1 X pdf -python_single_target_python3_10 qt6 svg
  853. # =media-gfx/graphviz-12.2.1-r1 X pdf -python_single_target_python3_10 python_single_target_python3_12 -python_single_target_python3_13 qt6 svg
  854. # =media-fonts/noto-cjk-20190416 X
  855. # =app-text/texlive-core-2024-r1 X cjk -xetex
  856. # =app-text/texlive-core-2024-r1 X -xetex
  857. # =app-text/texlive-core-2024-r1 -xetex
  858. # =dev-libs/zziplib-0.13.79-r1 sdl
  859. #
  860. # And will ignore such packages, installing the remaining ones. That
  861. # affects mostly the image extension and PDF generation.
  862. # Package dependencies and the minimal needed args:
  863. portages = {
  864. "graphviz": "media-gfx/graphviz",
  865. "imagemagick": "media-gfx/imagemagick",
  866. "media-libs": "media-libs/harfbuzz icu",
  867. "media-fonts": "media-fonts/noto-cjk",
  868. "texlive": "app-text/texlive-core xetex",
  869. "zziblib": "dev-libs/zziplib sdl",
  870. }
  871. extra_cmds = ""
  872. if not self.distro_msg:
  873. self.distro_msg = "Note: Gentoo requires package.use to be adjusted before emerging packages"
  874. use_base = "/etc/portage/package.use"
  875. files = glob(f"{use_base}/*")
  876. for fname, portage in portages.items():
  877. install = False
  878. while install is False:
  879. if not files:
  880. # No files under package.usage. Install all
  881. install = True
  882. break
  883. args = portage.split(" ")
  884. name = args.pop(0)
  885. cmd = ["grep", "-l", "-E", rf"^{name}\b" ] + files
  886. result = self.run(cmd, stdout=subprocess.PIPE, text=True)
  887. if result.returncode or not result.stdout.strip():
  888. # File containing portage name not found
  889. install = True
  890. break
  891. # Ensure that needed USE flags are present
  892. if args:
  893. match_fname = result.stdout.strip()
  894. with open(match_fname, 'r', encoding='utf8',
  895. errors='backslashreplace') as fp:
  896. for line in fp:
  897. for arg in args:
  898. if arg.startswith("-"):
  899. continue
  900. if not re.search(rf"\s*{arg}\b", line):
  901. # Needed file argument not found
  902. install = True
  903. break
  904. # Everything looks ok, don't install
  905. break
  906. # emit a code to setup missing USE
  907. if install:
  908. extra_cmds += (f"sudo su -c 'echo \"{portage}\" > {use_base}/{fname}'\n")
  909. # Now, we can use emerge and let it respect USE
  910. return self.get_install_progs(progs,
  911. "emerge --ask --changed-use --binpkg-respect-use=y",
  912. extra_cmds)
  913. def get_install(self):
  914. """
  915. OS-specific hints logic. Seeks for a hinter. If found, use it to
  916. provide package-manager specific install commands.
  917. Otherwise, outputs install instructions for the meta-packages.
  918. Returns a string with the command to be executed to install the
  919. the needed packages, if distro found. Otherwise, return just a
  920. list of packages that require installation.
  921. """
  922. os_hints = {
  923. re.compile("Red Hat Enterprise Linux"): self.give_redhat_hints,
  924. re.compile("Fedora"): self.give_redhat_hints,
  925. re.compile("AlmaLinux"): self.give_redhat_hints,
  926. re.compile("Amazon Linux"): self.give_redhat_hints,
  927. re.compile("CentOS"): self.give_redhat_hints,
  928. re.compile("openEuler"): self.give_redhat_hints,
  929. re.compile("Oracle Linux Server"): self.give_redhat_hints,
  930. re.compile("Rocky Linux"): self.give_redhat_hints,
  931. re.compile("Springdale Open Enterprise"): self.give_redhat_hints,
  932. re.compile("Ubuntu"): self.give_debian_hints,
  933. re.compile("Debian"): self.give_debian_hints,
  934. re.compile("Devuan"): self.give_debian_hints,
  935. re.compile("Kali"): self.give_debian_hints,
  936. re.compile("Mint"): self.give_debian_hints,
  937. re.compile("openSUSE"): self.give_opensuse_hints,
  938. re.compile("Mageia"): self.give_mageia_hints,
  939. re.compile("OpenMandriva"): self.give_mageia_hints,
  940. re.compile("Arch Linux"): self.give_arch_linux_hints,
  941. re.compile("Gentoo"): self.give_gentoo_hints,
  942. }
  943. # If the OS is detected, use per-OS hint logic
  944. for regex, os_hint in os_hints.items():
  945. if regex.search(self.system_release):
  946. return os_hint()
  947. #
  948. # Fall-back to generic hint code for other distros
  949. # That's far from ideal, specially for LaTeX dependencies.
  950. #
  951. progs = {"sphinx-build": "sphinx"}
  952. if self.pdf:
  953. self.check_missing_tex()
  954. self.distro_msg = \
  955. f"I don't know distro {self.system_release}.\n" \
  956. "So, I can't provide you a hint with the install procedure.\n" \
  957. "There are likely missing dependencies."
  958. return self.get_install_progs(progs, None)
  959. #
  960. # Common dependencies
  961. #
  962. def deactivate_help(self):
  963. """
  964. Print a helper message to disable a virtual environment.
  965. """
  966. print("\n If you want to exit the virtualenv, you can use:")
  967. print("\tdeactivate")
  968. def get_virtenv(self):
  969. """
  970. Give a hint about how to activate an already-existing virtual
  971. environment containing sphinx-build.
  972. Returns a tuble with (activate_cmd_path, sphinx_version) with
  973. the newest available virtual env.
  974. """
  975. cwd = os.getcwd()
  976. activates = []
  977. # Add all sphinx prefixes with possible version numbers
  978. for p in self.virtenv_prefix:
  979. activates += glob(f"{cwd}/{p}[0-9]*/bin/activate")
  980. activates.sort(reverse=True, key=str.lower)
  981. # Place sphinx_latest first, if it exists
  982. for p in self.virtenv_prefix:
  983. activates = glob(f"{cwd}/{p}*latest/bin/activate") + activates
  984. ver = (0, 0, 0)
  985. for f in activates:
  986. # Discard too old Sphinx virtual environments
  987. match = re.search(r"(\d+)\.(\d+)\.(\d+)", f)
  988. if match:
  989. ver = (int(match.group(1)), int(match.group(2)), int(match.group(3)))
  990. if ver < self.min_version:
  991. continue
  992. sphinx_cmd = f.replace("activate", "sphinx-build")
  993. if not os.path.isfile(sphinx_cmd):
  994. continue
  995. ver = self.get_sphinx_version(sphinx_cmd)
  996. if not ver:
  997. venv_dir = f.replace("/bin/activate", "")
  998. print(f"Warning: virtual environment {venv_dir} is not working.\n" \
  999. "Python version upgrade? Remove it with:\n\n" \
  1000. "\trm -rf {venv_dir}\n\n")
  1001. else:
  1002. if self.need_sphinx and ver >= self.min_version:
  1003. return (f, ver)
  1004. elif PythonVersion.parse_version(ver) > self.cur_version:
  1005. return (f, ver)
  1006. return ("", ver)
  1007. def recommend_sphinx_upgrade(self):
  1008. """
  1009. Check if Sphinx needs to be upgraded.
  1010. Returns a tuple with the higest available Sphinx version if found.
  1011. Otherwise, returns None to indicate either that no upgrade is needed
  1012. or no venv was found.
  1013. """
  1014. # Avoid running sphinx-builds from venv if cur_version is good
  1015. if self.cur_version and self.cur_version >= RECOMMENDED_VERSION:
  1016. self.latest_avail_ver = self.cur_version
  1017. return None
  1018. # Get the highest version from sphinx_*/bin/sphinx-build and the
  1019. # corresponding command to activate the venv/virtenv
  1020. self.activate_cmd, self.venv_ver = self.get_virtenv()
  1021. # Store the highest version from Sphinx existing virtualenvs
  1022. if self.activate_cmd and self.venv_ver > self.cur_version:
  1023. self.latest_avail_ver = self.venv_ver
  1024. else:
  1025. if self.cur_version:
  1026. self.latest_avail_ver = self.cur_version
  1027. else:
  1028. self.latest_avail_ver = (0, 0, 0)
  1029. # As we don't know package version of Sphinx, and there's no
  1030. # virtual environments, don't check if upgrades are needed
  1031. if not self.virtualenv:
  1032. if not self.latest_avail_ver:
  1033. return None
  1034. return self.latest_avail_ver
  1035. # Either there are already a virtual env or a new one should be created
  1036. self.need_pip = True
  1037. if not self.latest_avail_ver:
  1038. return None
  1039. # Return if the reason is due to an upgrade or not
  1040. if self.latest_avail_ver != (0, 0, 0):
  1041. if self.latest_avail_ver < RECOMMENDED_VERSION:
  1042. self.rec_sphinx_upgrade = 1
  1043. return self.latest_avail_ver
  1044. def recommend_package(self):
  1045. """
  1046. Recommend installing Sphinx as a distro-specific package.
  1047. """
  1048. print("\n2) As a package with:")
  1049. old_need = self.deps.need
  1050. old_optional = self.deps.optional
  1051. self.pdf = False
  1052. self.deps.optional = 0
  1053. old_verbose = self.verbose_warn_install
  1054. self.verbose_warn_install = 0
  1055. self.deps.clear_deps()
  1056. self.deps.add_package("python-sphinx", DepManager.PYTHON_MANDATORY)
  1057. cmd = self.get_install()
  1058. if cmd:
  1059. print(cmd)
  1060. self.deps.need = old_need
  1061. self.deps.optional = old_optional
  1062. self.verbose_warn_install = old_verbose
  1063. def recommend_sphinx_version(self, virtualenv_cmd):
  1064. """
  1065. Provide recommendations for installing or upgrading Sphinx based
  1066. on current version.
  1067. The logic here is complex, as it have to deal with different versions:
  1068. - minimal supported version;
  1069. - minimal PDF version;
  1070. - recommended version.
  1071. It also needs to work fine with both distro's package and
  1072. venv/virtualenv
  1073. """
  1074. if self.recommend_python:
  1075. cur_ver = sys.version_info[:3]
  1076. if cur_ver < MIN_PYTHON_VERSION:
  1077. print(f"\nPython version {cur_ver} is incompatible with doc build.\n" \
  1078. "Please upgrade it and re-run.\n")
  1079. return
  1080. # Version is OK. Nothing to do.
  1081. if self.cur_version != (0, 0, 0) and self.cur_version >= RECOMMENDED_VERSION:
  1082. return
  1083. if self.latest_avail_ver:
  1084. latest_avail_ver = PythonVersion.ver_str(self.latest_avail_ver)
  1085. if not self.need_sphinx:
  1086. # sphinx-build is present and its version is >= $min_version
  1087. # only recommend enabling a newer virtenv version if makes sense.
  1088. if self.latest_avail_ver and self.latest_avail_ver > self.cur_version:
  1089. print(f"\nYou may also use the newer Sphinx version {latest_avail_ver} with:")
  1090. if f"{self.virtenv_prefix}" in os.getcwd():
  1091. print("\tdeactivate")
  1092. print(f"\t. {self.activate_cmd}")
  1093. self.deactivate_help()
  1094. return
  1095. if self.latest_avail_ver and self.latest_avail_ver >= RECOMMENDED_VERSION:
  1096. return
  1097. if not self.virtualenv:
  1098. # No sphinx either via package or via virtenv. As we can't
  1099. # Compare the versions here, just return, recommending the
  1100. # user to install it from the package distro.
  1101. if not self.latest_avail_ver or self.latest_avail_ver == (0, 0, 0):
  1102. return
  1103. # User doesn't want a virtenv recommendation, but he already
  1104. # installed one via virtenv with a newer version.
  1105. # So, print commands to enable it
  1106. if self.latest_avail_ver > self.cur_version:
  1107. print(f"\nYou may also use the Sphinx virtualenv version {latest_avail_ver} with:")
  1108. if f"{self.virtenv_prefix}" in os.getcwd():
  1109. print("\tdeactivate")
  1110. print(f"\t. {self.activate_cmd}")
  1111. self.deactivate_help()
  1112. return
  1113. print("\n")
  1114. else:
  1115. if self.need_sphinx:
  1116. self.deps.need += 1
  1117. # Suggest newer versions if current ones are too old
  1118. if self.latest_avail_ver and self.latest_avail_ver >= self.min_version:
  1119. if self.latest_avail_ver >= RECOMMENDED_VERSION:
  1120. print(f"\nNeed to activate Sphinx (version {latest_avail_ver}) on virtualenv with:")
  1121. print(f"\t. {self.activate_cmd}")
  1122. self.deactivate_help()
  1123. return
  1124. # Version is above the minimal required one, but may be
  1125. # below the recommended one. So, print warnings/notes
  1126. if self.latest_avail_ver < RECOMMENDED_VERSION:
  1127. print(f"Warning: It is recommended at least Sphinx version {RECOMMENDED_VERSION}.")
  1128. # At this point, either it needs Sphinx or upgrade is recommended,
  1129. # both via pip
  1130. if self.rec_sphinx_upgrade:
  1131. if not self.virtualenv:
  1132. print("Instead of install/upgrade Python Sphinx pkg, you could use pip/pypi with:\n\n")
  1133. else:
  1134. print("To upgrade Sphinx, use:\n\n")
  1135. else:
  1136. print("\nSphinx needs to be installed either:\n1) via pip/pypi with:\n")
  1137. if not virtualenv_cmd:
  1138. print(" Currently not possible.\n")
  1139. print(" Please upgrade Python to a newer version and run this script again")
  1140. else:
  1141. print(f"\t{virtualenv_cmd} {self.virtenv_dir}")
  1142. print(f"\t. {self.virtenv_dir}/bin/activate")
  1143. print(f"\tpip install -r {self.requirement_file}")
  1144. self.deactivate_help()
  1145. if self.package_supported:
  1146. self.recommend_package()
  1147. print("\n" \
  1148. " Please note that Sphinx currentlys produce false-positive\n" \
  1149. " warnings when the same name is used for more than one type (functions,\n" \
  1150. " structs, enums,...). This is known Sphinx bug. For more details, see:\n" \
  1151. "\thttps://github.com/sphinx-doc/sphinx/pull/8313")
  1152. def check_needs(self):
  1153. """
  1154. Main method that checks needed dependencies and provides
  1155. recommendations.
  1156. """
  1157. self.python_cmd = sys.executable
  1158. # Check if Sphinx is already accessible from current environment
  1159. self.check_sphinx(self.conf)
  1160. if self.system_release:
  1161. print(f"Detected OS: {self.system_release}.")
  1162. else:
  1163. print("Unknown OS")
  1164. if self.cur_version != (0, 0, 0):
  1165. ver = PythonVersion.ver_str(self.cur_version)
  1166. print(f"Sphinx version: {ver}\n")
  1167. # Check the type of virtual env, depending on Python version
  1168. virtualenv_cmd = None
  1169. if sys.version_info < MIN_PYTHON_VERSION:
  1170. min_ver = ver_str(MIN_PYTHON_VERSION)
  1171. print(f"ERROR: at least python {min_ver} is required to build the kernel docs")
  1172. self.need_sphinx = 1
  1173. self.venv_ver = self.recommend_sphinx_upgrade()
  1174. if self.need_pip:
  1175. if sys.version_info < MIN_PYTHON_VERSION:
  1176. self.need_pip = False
  1177. print("Warning: python version is not supported.")
  1178. else:
  1179. virtualenv_cmd = f"{self.python_cmd} -m venv"
  1180. self.check_python_module("ensurepip")
  1181. # Check for needed programs/tools
  1182. self.check_perl_module("Pod::Usage", DepManager.SYSTEM_MANDATORY)
  1183. self.check_program("make", DepManager.SYSTEM_MANDATORY)
  1184. self.check_program("which", DepManager.SYSTEM_MANDATORY)
  1185. self.check_program("dot", DepManager.SYSTEM_OPTIONAL)
  1186. self.check_program("convert", DepManager.SYSTEM_OPTIONAL)
  1187. self.check_python_module("yaml")
  1188. if self.pdf:
  1189. self.check_program("xelatex", DepManager.PDF_MANDATORY)
  1190. self.check_program("rsvg-convert", DepManager.PDF_MANDATORY)
  1191. self.check_program("latexmk", DepManager.PDF_MANDATORY)
  1192. # Do distro-specific checks and output distro-install commands
  1193. cmd = self.get_install()
  1194. if cmd:
  1195. print(cmd)
  1196. # If distro requires some special instructions, print here.
  1197. # Please notice that get_install() needs to be called first.
  1198. if self.distro_msg:
  1199. print("\n" + self.distro_msg)
  1200. if not self.python_cmd:
  1201. if self.need == 1:
  1202. sys.exit("Can't build as 1 mandatory dependency is missing")
  1203. elif self.need:
  1204. sys.exit(f"Can't build as {self.need} mandatory dependencies are missing")
  1205. # Check if sphinx-build is called sphinx-build-3
  1206. if self.need_symlink:
  1207. sphinx_path = self.which("sphinx-build-3")
  1208. if sphinx_path:
  1209. print(f"\tsudo ln -sf {sphinx_path} /usr/bin/sphinx-build\n")
  1210. self.recommend_sphinx_version(virtualenv_cmd)
  1211. print("")
  1212. if not self.deps.optional:
  1213. print("All optional dependencies are met.")
  1214. if self.deps.need == 1:
  1215. sys.exit("Can't build as 1 mandatory dependency is missing")
  1216. elif self.deps.need:
  1217. sys.exit(f"Can't build as {self.deps.need} mandatory dependencies are missing")
  1218. print("Needed package dependencies are met.")
  1219. DESCRIPTION = """
  1220. Process some flags related to Sphinx installation and documentation build.
  1221. """
  1222. def main():
  1223. """Main function"""
  1224. parser = argparse.ArgumentParser(description=DESCRIPTION)
  1225. parser.add_argument(
  1226. "--no-virtualenv",
  1227. action="store_false",
  1228. dest="virtualenv",
  1229. help="Recommend installing Sphinx instead of using a virtualenv",
  1230. )
  1231. parser.add_argument(
  1232. "--no-pdf",
  1233. action="store_false",
  1234. dest="pdf",
  1235. help="Don't check for dependencies required to build PDF docs",
  1236. )
  1237. parser.add_argument(
  1238. "--version-check",
  1239. action="store_true",
  1240. dest="version_check",
  1241. help="If version is compatible, don't check for missing dependencies",
  1242. )
  1243. args = parser.parse_args()
  1244. checker = SphinxDependencyChecker(args)
  1245. PythonVersion.check_python(MIN_PYTHON_VERSION,
  1246. bail_out=True, success_on_error=True)
  1247. checker.check_needs()
  1248. # Call main if not used as module
  1249. if __name__ == "__main__":
  1250. main()