main.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. # -*- coding: utf-8 -*-
  2. import itertools
  3. import argparse
  4. import json
  5. import logging
  6. import os
  7. import pathlib
  8. import re
  9. import string
  10. import subprocess
  11. import sys
  12. import tempfile
  13. from sphinx import config as sphinx_config
  14. from sphinx import project as sphinx_project
  15. from . import sphinx
  16. from . import git
  17. def main(argv=None):
  18. if not argv:
  19. argv = sys.argv[1:]
  20. parser = argparse.ArgumentParser()
  21. parser.add_argument("sourcedir", help="path to documentation source files")
  22. parser.add_argument("outputdir", help="path to output directory")
  23. parser.add_argument(
  24. "filenames",
  25. nargs="*",
  26. help="a list of specific files to rebuild. Ignored if -a is specified",
  27. )
  28. parser.add_argument(
  29. "-c",
  30. metavar="PATH",
  31. dest="confdir",
  32. help=(
  33. "path where configuration file (conf.py) is located "
  34. "(default: same as SOURCEDIR)"
  35. ),
  36. )
  37. parser.add_argument(
  38. "-C",
  39. action="store_true",
  40. dest="noconfig",
  41. help="use no config file at all, only -D options",
  42. )
  43. parser.add_argument(
  44. "-D",
  45. metavar="setting=value",
  46. action="append",
  47. dest="define",
  48. default=[],
  49. help="override a setting in configuration file",
  50. )
  51. parser.add_argument(
  52. "--dump-metadata",
  53. action="store_true",
  54. help="dump generated metadata and exit",
  55. )
  56. args, argv = parser.parse_known_args(argv)
  57. if args.noconfig:
  58. return 1
  59. logger = logging.getLogger(__name__)
  60. sourcedir_absolute = os.path.abspath(args.sourcedir)
  61. confdir_absolute = (
  62. os.path.abspath(args.confdir)
  63. if args.confdir is not None
  64. else sourcedir_absolute
  65. )
  66. # Conf-overrides
  67. confoverrides = {}
  68. for d in args.define:
  69. key, _, value = d.partition("=")
  70. confoverrides[key] = value
  71. # Parse config
  72. config = sphinx_config.Config.read(confdir_absolute, confoverrides)
  73. config.add("smv_tag_whitelist", sphinx.DEFAULT_TAG_WHITELIST, "html", str)
  74. config.add(
  75. "smv_branch_whitelist", sphinx.DEFAULT_TAG_WHITELIST, "html", str
  76. )
  77. config.add(
  78. "smv_remote_whitelist", sphinx.DEFAULT_REMOTE_WHITELIST, "html", str
  79. )
  80. config.add(
  81. "smv_released_pattern", sphinx.DEFAULT_RELEASED_PATTERN, "html", str
  82. )
  83. config.add(
  84. "smv_outputdir_format", sphinx.DEFAULT_OUTPUTDIR_FORMAT, "html", str
  85. )
  86. config.add("smv_prefer_remote_refs", False, "html", bool)
  87. config.pre_init_values()
  88. config.init_values()
  89. # Get relative paths to root of git repository
  90. gitroot = pathlib.Path(
  91. git.get_toplevel_path(cwd=sourcedir_absolute)
  92. ).resolve()
  93. logger.debug("Git toplevel path: %s", str(gitroot))
  94. sourcedir = os.path.relpath(sourcedir_absolute, str(gitroot))
  95. logger.debug(
  96. "Source dir (relative to git toplevel path): %s", str(sourcedir)
  97. )
  98. if args.confdir:
  99. confdir = os.path.relpath(confdir_absolute, str(gitroot))
  100. else:
  101. confdir = sourcedir
  102. logger.debug("Conf dir (relative to git toplevel path): %s", str(confdir))
  103. conffile = os.path.join(confdir, "conf.py")
  104. # Get git references
  105. gitrefs = git.get_refs(
  106. str(gitroot),
  107. config.smv_tag_whitelist,
  108. config.smv_branch_whitelist,
  109. config.smv_remote_whitelist,
  110. files=(sourcedir, conffile),
  111. )
  112. # Order git refs
  113. if config.smv_prefer_remote_refs:
  114. gitrefs = sorted(gitrefs, key=lambda x: (not x.is_remote, *x))
  115. else:
  116. gitrefs = sorted(gitrefs, key=lambda x: (x.is_remote, *x))
  117. logger = logging.getLogger(__name__)
  118. with tempfile.TemporaryDirectory() as tmp:
  119. # Generate Metadata
  120. metadata = {}
  121. outputdirs = set()
  122. for gitref in gitrefs:
  123. # Clone Git repo
  124. repopath = os.path.join(tmp, gitref.commit)
  125. try:
  126. git.copy_tree(str(gitroot), gitroot.as_uri(), repopath, gitref)
  127. except (OSError, subprocess.CalledProcessError):
  128. logger.error(
  129. "Failed to copy git tree for %s to %s",
  130. gitref.refname,
  131. repopath,
  132. )
  133. continue
  134. # Find config
  135. confpath = os.path.join(repopath, confdir)
  136. try:
  137. current_config = sphinx_config.Config.read(
  138. confpath, confoverrides,
  139. )
  140. except (OSError, sphinx_config.ConfigError):
  141. logger.error(
  142. "Failed load config for %s from %s",
  143. gitref.refname,
  144. confpath,
  145. )
  146. continue
  147. current_config.pre_init_values()
  148. current_config.init_values()
  149. # Ensure that there are not duplicate output dirs
  150. outputdir = config.smv_outputdir_format.format(
  151. ref=gitref, config=current_config,
  152. )
  153. if outputdir in outputdirs:
  154. logger.warning(
  155. "outputdir '%s' for %s conflicts with other versions",
  156. outputdir,
  157. gitref.refname,
  158. )
  159. continue
  160. outputdirs.add(outputdir)
  161. # Get List of files
  162. source_suffixes = current_config.source_suffix
  163. if isinstance(source_suffixes, str):
  164. source_suffixes = [current_config.source_suffix]
  165. current_sourcedir = os.path.join(repopath, sourcedir)
  166. project = sphinx_project.Project(
  167. current_sourcedir, source_suffixes
  168. )
  169. metadata[gitref.name] = {
  170. "name": gitref.name,
  171. "version": current_config.version,
  172. "release": current_config.release,
  173. "is_released": bool(
  174. re.match(config.smv_released_pattern, gitref.refname)
  175. ),
  176. "source": gitref.source,
  177. "creatordate": gitref.creatordate.strftime(sphinx.DATE_FMT),
  178. "sourcedir": current_sourcedir,
  179. "outputdir": os.path.join(
  180. os.path.abspath(args.outputdir), outputdir
  181. ),
  182. "confdir": confdir_absolute,
  183. "docnames": list(project.discover()),
  184. }
  185. if args.dump_metadata:
  186. print(json.dumps(metadata, indent=2))
  187. return 0
  188. if not metadata:
  189. logger.error("No matching refs found!")
  190. return 2
  191. # Write Metadata
  192. metadata_path = os.path.abspath(os.path.join(tmp, "versions.json"))
  193. with open(metadata_path, mode="w") as fp:
  194. json.dump(metadata, fp, indent=2)
  195. # Run Sphinx
  196. argv.extend(["-D", "smv_metadata_path={}".format(metadata_path)])
  197. for version_name, data in metadata.items():
  198. os.makedirs(data["outputdir"], exist_ok=True)
  199. defines = itertools.chain(
  200. *(
  201. ("-D", string.Template(d).safe_substitute(data))
  202. for d in args.define
  203. )
  204. )
  205. current_argv = argv.copy()
  206. current_argv.extend(
  207. [
  208. *defines,
  209. "-D",
  210. "smv_current_version={}".format(version_name),
  211. "-c",
  212. data["confdir"],
  213. data["sourcedir"],
  214. data["outputdir"],
  215. *args.filenames,
  216. ]
  217. )
  218. logger.debug("Running sphinx-build with args: %r", current_argv)
  219. cmd = (sys.executable, "-m", "sphinx", *current_argv)
  220. subprocess.check_call(cmd)
  221. return 0