main.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. # -*- coding: utf-8 -*-
  2. import itertools
  3. import argparse
  4. import multiprocessing
  5. import contextlib
  6. import json
  7. import logging
  8. import os
  9. import pathlib
  10. import re
  11. import string
  12. import subprocess
  13. import sys
  14. import tempfile
  15. from sphinx import config as sphinx_config
  16. from sphinx import project as sphinx_project
  17. from . import sphinx
  18. from . import git
  19. @contextlib.contextmanager
  20. def working_dir(path):
  21. prev_cwd = os.getcwd()
  22. os.chdir(path)
  23. try:
  24. yield
  25. finally:
  26. os.chdir(prev_cwd)
  27. def load_sphinx_config_worker(q, confpath, confoverrides, add_defaults):
  28. try:
  29. with working_dir(confpath):
  30. current_config = sphinx_config.Config.read(
  31. confpath, confoverrides,
  32. )
  33. if add_defaults:
  34. current_config.add(
  35. "smv_tag_whitelist", sphinx.DEFAULT_TAG_WHITELIST, "html", str
  36. )
  37. current_config.add(
  38. "smv_branch_whitelist",
  39. sphinx.DEFAULT_TAG_WHITELIST,
  40. "html",
  41. str,
  42. )
  43. current_config.add(
  44. "smv_remote_whitelist",
  45. sphinx.DEFAULT_REMOTE_WHITELIST,
  46. "html",
  47. str,
  48. )
  49. current_config.add(
  50. "smv_released_pattern",
  51. sphinx.DEFAULT_RELEASED_PATTERN,
  52. "html",
  53. str,
  54. )
  55. current_config.add(
  56. "smv_outputdir_format",
  57. sphinx.DEFAULT_OUTPUTDIR_FORMAT,
  58. "html",
  59. str,
  60. )
  61. current_config.add("smv_prefer_remote_refs", False, "html", bool)
  62. current_config.pre_init_values()
  63. current_config.init_values()
  64. except Exception as err:
  65. q.put(err)
  66. return
  67. q.put(current_config)
  68. def load_sphinx_config(confpath, confoverrides, add_defaults=False):
  69. q = multiprocessing.Queue()
  70. proc = multiprocessing.Process(
  71. target=load_sphinx_config_worker,
  72. args=(q, confpath, confoverrides, add_defaults),
  73. )
  74. proc.start()
  75. proc.join()
  76. result = q.get_nowait()
  77. if isinstance(result, Exception):
  78. raise result
  79. return result
  80. def get_python_flags():
  81. if sys.flags.bytes_warning:
  82. yield "-b"
  83. if sys.flags.debug:
  84. yield "-d"
  85. if sys.flags.hash_randomization:
  86. yield "-R"
  87. if sys.flags.ignore_environment:
  88. yield "-E"
  89. if sys.flags.inspect:
  90. yield "-i"
  91. if sys.flags.isolated:
  92. yield "-I"
  93. if sys.flags.no_site:
  94. yield "-S"
  95. if sys.flags.no_user_site:
  96. yield "-s"
  97. if sys.flags.optimize:
  98. yield "-O"
  99. if sys.flags.quiet:
  100. yield "-q"
  101. if sys.flags.verbose:
  102. yield "-v"
  103. for option, value in sys._xoptions.items():
  104. if value is True:
  105. yield from ("-X", option)
  106. else:
  107. yield from ("-X", "{}={}".format(option, value))
  108. def main(argv=None):
  109. if not argv:
  110. argv = sys.argv[1:]
  111. parser = argparse.ArgumentParser()
  112. parser.add_argument("sourcedir", help="path to documentation source files")
  113. parser.add_argument("outputdir", help="path to output directory")
  114. parser.add_argument(
  115. "filenames",
  116. nargs="*",
  117. help="a list of specific files to rebuild. Ignored if -a is specified",
  118. )
  119. parser.add_argument(
  120. "-c",
  121. metavar="PATH",
  122. dest="confdir",
  123. help=(
  124. "path where configuration file (conf.py) is located "
  125. "(default: same as SOURCEDIR)"
  126. ),
  127. )
  128. parser.add_argument(
  129. "-C",
  130. action="store_true",
  131. dest="noconfig",
  132. help="use no config file at all, only -D options",
  133. )
  134. parser.add_argument(
  135. "-D",
  136. metavar="setting=value",
  137. action="append",
  138. dest="define",
  139. default=[],
  140. help="override a setting in configuration file",
  141. )
  142. parser.add_argument(
  143. "--dump-metadata",
  144. action="store_true",
  145. help="dump generated metadata and exit",
  146. )
  147. args, argv = parser.parse_known_args(argv)
  148. if args.noconfig:
  149. return 1
  150. logger = logging.getLogger(__name__)
  151. sourcedir_absolute = os.path.abspath(args.sourcedir)
  152. confdir_absolute = (
  153. os.path.abspath(args.confdir)
  154. if args.confdir is not None
  155. else sourcedir_absolute
  156. )
  157. # Conf-overrides
  158. confoverrides = {}
  159. for d in args.define:
  160. key, _, value = d.partition("=")
  161. confoverrides[key] = value
  162. # Parse config
  163. config = load_sphinx_config(
  164. confdir_absolute, confoverrides, add_defaults=True
  165. )
  166. # Get relative paths to root of git repository
  167. gitroot = pathlib.Path(
  168. git.get_toplevel_path(cwd=sourcedir_absolute)
  169. ).resolve()
  170. cwd_absolute = os.path.abspath(".")
  171. cwd_relative = os.path.relpath(cwd_absolute, str(gitroot))
  172. logger.debug("Git toplevel path: %s", str(gitroot))
  173. sourcedir = os.path.relpath(sourcedir_absolute, str(gitroot))
  174. logger.debug(
  175. "Source dir (relative to git toplevel path): %s", str(sourcedir)
  176. )
  177. if args.confdir:
  178. confdir = os.path.relpath(confdir_absolute, str(gitroot))
  179. else:
  180. confdir = sourcedir
  181. logger.debug("Conf dir (relative to git toplevel path): %s", str(confdir))
  182. conffile = os.path.join(confdir, "conf.py")
  183. # Get git references
  184. gitrefs = git.get_refs(
  185. str(gitroot),
  186. config.smv_tag_whitelist,
  187. config.smv_branch_whitelist,
  188. config.smv_remote_whitelist,
  189. files=(sourcedir, conffile),
  190. )
  191. # Order git refs
  192. if config.smv_prefer_remote_refs:
  193. gitrefs = sorted(gitrefs, key=lambda x: (not x.is_remote, *x))
  194. else:
  195. gitrefs = sorted(gitrefs, key=lambda x: (x.is_remote, *x))
  196. logger = logging.getLogger(__name__)
  197. with tempfile.TemporaryDirectory() as tmp:
  198. # Generate Metadata
  199. metadata = {}
  200. outputdirs = set()
  201. for gitref in gitrefs:
  202. # Clone Git repo
  203. repopath = os.path.join(tmp, gitref.commit)
  204. try:
  205. git.copy_tree(str(gitroot), gitroot.as_uri(), repopath, gitref)
  206. except (OSError, subprocess.CalledProcessError):
  207. logger.error(
  208. "Failed to copy git tree for %s to %s",
  209. gitref.refname,
  210. repopath,
  211. )
  212. continue
  213. # Find config
  214. confpath = os.path.join(repopath, confdir)
  215. try:
  216. current_config = load_sphinx_config(confpath, confoverrides)
  217. except (OSError, sphinx_config.ConfigError):
  218. logger.error(
  219. "Failed load config for %s from %s",
  220. gitref.refname,
  221. confpath,
  222. )
  223. continue
  224. # Ensure that there are not duplicate output dirs
  225. outputdir = config.smv_outputdir_format.format(
  226. ref=gitref, config=current_config,
  227. )
  228. if outputdir in outputdirs:
  229. logger.warning(
  230. "outputdir '%s' for %s conflicts with other versions",
  231. outputdir,
  232. gitref.refname,
  233. )
  234. continue
  235. outputdirs.add(outputdir)
  236. # Get List of files
  237. source_suffixes = current_config.source_suffix
  238. if isinstance(source_suffixes, str):
  239. source_suffixes = [current_config.source_suffix]
  240. current_sourcedir = os.path.join(repopath, sourcedir)
  241. project = sphinx_project.Project(
  242. current_sourcedir, source_suffixes
  243. )
  244. metadata[gitref.name] = {
  245. "name": gitref.name,
  246. "version": current_config.version,
  247. "release": current_config.release,
  248. "is_released": bool(
  249. re.match(config.smv_released_pattern, gitref.refname)
  250. ),
  251. "source": gitref.source,
  252. "creatordate": gitref.creatordate.strftime(sphinx.DATE_FMT),
  253. "basedir": repopath,
  254. "sourcedir": current_sourcedir,
  255. "outputdir": os.path.join(
  256. os.path.abspath(args.outputdir), outputdir
  257. ),
  258. "confdir": confdir_absolute,
  259. "docnames": list(project.discover()),
  260. }
  261. if args.dump_metadata:
  262. print(json.dumps(metadata, indent=2))
  263. return 0
  264. if not metadata:
  265. logger.error("No matching refs found!")
  266. return 2
  267. # Write Metadata
  268. metadata_path = os.path.abspath(os.path.join(tmp, "versions.json"))
  269. with open(metadata_path, mode="w") as fp:
  270. json.dump(metadata, fp, indent=2)
  271. # Run Sphinx
  272. argv.extend(["-D", "smv_metadata_path={}".format(metadata_path)])
  273. for version_name, data in metadata.items():
  274. os.makedirs(data["outputdir"], exist_ok=True)
  275. defines = itertools.chain(
  276. *(
  277. ("-D", string.Template(d).safe_substitute(data))
  278. for d in args.define
  279. )
  280. )
  281. current_argv = argv.copy()
  282. current_argv.extend(
  283. [
  284. *defines,
  285. "-D",
  286. "smv_current_version={}".format(version_name),
  287. "-c",
  288. data["confdir"],
  289. data["sourcedir"],
  290. data["outputdir"],
  291. *args.filenames,
  292. ]
  293. )
  294. logger.debug("Running sphinx-build with args: %r", current_argv)
  295. cmd = (
  296. sys.executable,
  297. *get_python_flags(),
  298. "-m",
  299. "sphinx",
  300. *current_argv,
  301. )
  302. current_cwd = os.path.join(data["basedir"], cwd_relative)
  303. subprocess.check_call(cmd, cwd=current_cwd)
  304. return 0