main.py 7.4 KB

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