main.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 main(argv=None):
  81. if not argv:
  82. argv = sys.argv[1:]
  83. parser = argparse.ArgumentParser()
  84. parser.add_argument("sourcedir", help="path to documentation source files")
  85. parser.add_argument("outputdir", help="path to output directory")
  86. parser.add_argument(
  87. "filenames",
  88. nargs="*",
  89. help="a list of specific files to rebuild. Ignored if -a is specified",
  90. )
  91. parser.add_argument(
  92. "-c",
  93. metavar="PATH",
  94. dest="confdir",
  95. help=(
  96. "path where configuration file (conf.py) is located "
  97. "(default: same as SOURCEDIR)"
  98. ),
  99. )
  100. parser.add_argument(
  101. "-C",
  102. action="store_true",
  103. dest="noconfig",
  104. help="use no config file at all, only -D options",
  105. )
  106. parser.add_argument(
  107. "-D",
  108. metavar="setting=value",
  109. action="append",
  110. dest="define",
  111. default=[],
  112. help="override a setting in configuration file",
  113. )
  114. parser.add_argument(
  115. "--dump-metadata",
  116. action="store_true",
  117. help="dump generated metadata and exit",
  118. )
  119. args, argv = parser.parse_known_args(argv)
  120. if args.noconfig:
  121. return 1
  122. logger = logging.getLogger(__name__)
  123. sourcedir_absolute = os.path.abspath(args.sourcedir)
  124. confdir_absolute = (
  125. os.path.abspath(args.confdir)
  126. if args.confdir is not None
  127. else sourcedir_absolute
  128. )
  129. # Conf-overrides
  130. confoverrides = {}
  131. for d in args.define:
  132. key, _, value = d.partition("=")
  133. confoverrides[key] = value
  134. # Parse config
  135. config = load_sphinx_config(
  136. confdir_absolute, confoverrides, add_defaults=True
  137. )
  138. # Get relative paths to root of git repository
  139. gitroot = pathlib.Path(
  140. git.get_toplevel_path(cwd=sourcedir_absolute)
  141. ).resolve()
  142. cwd_absolute = os.path.abspath(".")
  143. cwd_relative = os.path.relpath(cwd_absolute, str(gitroot))
  144. logger.debug("Git toplevel path: %s", str(gitroot))
  145. sourcedir = os.path.relpath(sourcedir_absolute, str(gitroot))
  146. logger.debug(
  147. "Source dir (relative to git toplevel path): %s", str(sourcedir)
  148. )
  149. if args.confdir:
  150. confdir = os.path.relpath(confdir_absolute, str(gitroot))
  151. else:
  152. confdir = sourcedir
  153. logger.debug("Conf dir (relative to git toplevel path): %s", str(confdir))
  154. conffile = os.path.join(confdir, "conf.py")
  155. # Get git references
  156. gitrefs = git.get_refs(
  157. str(gitroot),
  158. config.smv_tag_whitelist,
  159. config.smv_branch_whitelist,
  160. config.smv_remote_whitelist,
  161. files=(sourcedir, conffile),
  162. )
  163. # Order git refs
  164. if config.smv_prefer_remote_refs:
  165. gitrefs = sorted(gitrefs, key=lambda x: (not x.is_remote, *x))
  166. else:
  167. gitrefs = sorted(gitrefs, key=lambda x: (x.is_remote, *x))
  168. logger = logging.getLogger(__name__)
  169. with tempfile.TemporaryDirectory() as tmp:
  170. # Generate Metadata
  171. metadata = {}
  172. outputdirs = set()
  173. for gitref in gitrefs:
  174. # Clone Git repo
  175. repopath = os.path.join(tmp, gitref.commit)
  176. try:
  177. git.copy_tree(str(gitroot), gitroot.as_uri(), repopath, gitref)
  178. except (OSError, subprocess.CalledProcessError):
  179. logger.error(
  180. "Failed to copy git tree for %s to %s",
  181. gitref.refname,
  182. repopath,
  183. )
  184. continue
  185. # Find config
  186. confpath = os.path.join(repopath, confdir)
  187. try:
  188. current_config = load_sphinx_config(confpath, confoverrides)
  189. except (OSError, sphinx_config.ConfigError):
  190. logger.error(
  191. "Failed load config for %s from %s",
  192. gitref.refname,
  193. confpath,
  194. )
  195. continue
  196. # Ensure that there are not duplicate output dirs
  197. outputdir = config.smv_outputdir_format.format(
  198. ref=gitref, config=current_config,
  199. )
  200. if outputdir in outputdirs:
  201. logger.warning(
  202. "outputdir '%s' for %s conflicts with other versions",
  203. outputdir,
  204. gitref.refname,
  205. )
  206. continue
  207. outputdirs.add(outputdir)
  208. # Get List of files
  209. source_suffixes = current_config.source_suffix
  210. if isinstance(source_suffixes, str):
  211. source_suffixes = [current_config.source_suffix]
  212. current_sourcedir = os.path.join(repopath, sourcedir)
  213. project = sphinx_project.Project(
  214. current_sourcedir, source_suffixes
  215. )
  216. metadata[gitref.name] = {
  217. "name": gitref.name,
  218. "version": current_config.version,
  219. "release": current_config.release,
  220. "is_released": bool(
  221. re.match(config.smv_released_pattern, gitref.refname)
  222. ),
  223. "source": gitref.source,
  224. "creatordate": gitref.creatordate.strftime(sphinx.DATE_FMT),
  225. "basedir": repopath,
  226. "sourcedir": current_sourcedir,
  227. "outputdir": os.path.join(
  228. os.path.abspath(args.outputdir), outputdir
  229. ),
  230. "confdir": confdir_absolute,
  231. "docnames": list(project.discover()),
  232. }
  233. if args.dump_metadata:
  234. print(json.dumps(metadata, indent=2))
  235. return 0
  236. if not metadata:
  237. logger.error("No matching refs found!")
  238. return 2
  239. # Write Metadata
  240. metadata_path = os.path.abspath(os.path.join(tmp, "versions.json"))
  241. with open(metadata_path, mode="w") as fp:
  242. json.dump(metadata, fp, indent=2)
  243. # Run Sphinx
  244. argv.extend(["-D", "smv_metadata_path={}".format(metadata_path)])
  245. for version_name, data in metadata.items():
  246. os.makedirs(data["outputdir"], exist_ok=True)
  247. defines = itertools.chain(
  248. *(
  249. ("-D", string.Template(d).safe_substitute(data))
  250. for d in args.define
  251. )
  252. )
  253. current_argv = argv.copy()
  254. current_argv.extend(
  255. [
  256. *defines,
  257. "-D",
  258. "smv_current_version={}".format(version_name),
  259. "-c",
  260. data["confdir"],
  261. data["sourcedir"],
  262. data["outputdir"],
  263. *args.filenames,
  264. ]
  265. )
  266. logger.debug("Running sphinx-build with args: %r", current_argv)
  267. cmd = (sys.executable, "-m", "sphinx", *current_argv)
  268. current_cwd = os.path.join(data["basedir"], cwd_relative)
  269. subprocess.check_call(cmd, cwd=current_cwd)
  270. return 0