فهرست منبع

Fix various code style issues

Jan Holthuis 5 سال پیش
والد
کامیت
5d709d35b3
6فایلهای تغییر یافته به همراه189 افزوده شده و 106 حذف شده
  1. 5 5
      docs/conf.py
  2. 11 13
      setup.py
  3. 1 0
      sphinx_multiversion/__main__.py
  4. 37 20
      sphinx_multiversion/git.py
  5. 80 33
      sphinx_multiversion/main.py
  6. 55 35
      sphinx_multiversion/sphinx.py

+ 5 - 5
docs/conf.py

@@ -6,10 +6,10 @@ author = "Jan Holthuis"
 project = "sphinx-multiversion"
 release = "1.0.0"
 version = "1.0"
-copyright = '{}, {}'.format(time.strftime('%Y'), author)
+copyright = "{}, {}".format(time.strftime("%Y"), author)
 
-html_last_updated_fmt = '%c'
-master_doc = 'index'
-pygments_style = 'friendly'
-templates_path = ['_templates']
+html_last_updated_fmt = "%c"
+master_doc = "index"
+pygments_style = "friendly"
+templates_path = ["_templates"]
 extensions = []

+ 11 - 13
setup.py

@@ -3,21 +3,19 @@
 from setuptools import setup
 
 setup(
-    name='sphinx-multiversion',
-    description='Add support for multiple versions to sphinx',
+    name="sphinx-multiversion",
+    description="Add support for multiple versions to sphinx",
     classifiers=[
-        'License :: OSI Approved :: BSD License',
+        "License :: OSI Approved :: BSD License",
         "Programming Language :: Python :: 3",
-      ],
-    author='Jan Holthuis',
-    author_email='holthuis.jan@googlemail.com',
+    ],
+    author="Jan Holthuis",
+    author_email="holthuis.jan@googlemail.com",
     version="1.0.0",
-    install_requires=['sphinx >= 2.1'],
-    license='BSD',
-    packages=['sphinx_multiversion'],
+    install_requires=["sphinx >= 2.1"],
+    license="BSD",
+    packages=["sphinx_multiversion"],
     entry_points={
-        'console_scripts': [
-            'sphinx-multiversion=sphinx_multiversion:main',
-        ],
+        "console_scripts": ["sphinx-multiversion=sphinx_multiversion:main",],
     },
- )
+)

+ 1 - 0
sphinx_multiversion/__main__.py

@@ -2,4 +2,5 @@
 # -*- coding: utf-8 -*-
 import sys
 from sphinx.ext.multiversion import main
+
 sys.exit(main())

+ 37 - 20
sphinx_multiversion/git.py

@@ -6,19 +6,20 @@ import subprocess
 import re
 import tarfile
 
-GitRef = collections.namedtuple('VersionRef', [
-    'name',
-    'commit',
-    'source',
-    'is_remote',
-    'refname',
-    'creatordate',
-])
+GitRef = collections.namedtuple(
+    "VersionRef",
+    ["name", "commit", "source", "is_remote", "refname", "creatordate",],
+)
 
 
 def get_all_refs(gitroot):
-    cmd = ("git", "for-each-ref", "--format",
-           "%(objectname)\t%(refname)\t%(creatordate:iso)", "refs")
+    cmd = (
+        "git",
+        "for-each-ref",
+        "--format",
+        "%(objectname)\t%(refname)\t%(creatordate:iso)",
+        "refs",
+    )
     output = subprocess.check_output(cmd, cwd=gitroot).decode()
     for line in output.splitlines():
         is_remote = False
@@ -28,16 +29,20 @@ def get_all_refs(gitroot):
 
         commit = fields[0]
         refname = fields[1]
-        creatordate = datetime.datetime.strptime(fields[2], "%Y-%m-%d %H:%M:%S %z")
+        creatordate = datetime.datetime.strptime(
+            fields[2], "%Y-%m-%d %H:%M:%S %z"
+        )
 
         # Parse refname
-        matchobj = re.match(r"^refs/(heads|tags|remotes/[^/]+)/(\S+)$", refname)
+        matchobj = re.match(
+            r"^refs/(heads|tags|remotes/[^/]+)/(\S+)$", refname
+        )
         if not matchobj:
             continue
         source = matchobj.group(1)
         name = matchobj.group(2)
 
-        if source.startswith('remotes/'):
+        if source.startswith("remotes/"):
             is_remote = True
 
         yield GitRef(name, commit, source, is_remote, refname, creatordate)
@@ -45,17 +50,21 @@ def get_all_refs(gitroot):
 
 def get_refs(gitroot, tag_whitelist, branch_whitelist, remote_whitelist):
     for ref in get_all_refs(gitroot):
-        if ref.source == 'tags':
+        if ref.source == "tags":
             if tag_whitelist is None or not re.match(tag_whitelist, ref.name):
                 continue
-        elif ref.source == 'heads':
-            if branch_whitelist is None or not re.match(branch_whitelist, ref.name):
+        elif ref.source == "heads":
+            if branch_whitelist is None or not re.match(
+                branch_whitelist, ref.name
+            ):
                 continue
         elif ref.is_remote and remote_whitelist is not None:
-            remote_name = ref.source.partition('/')[2]
+            remote_name = ref.source.partition("/")[2]
             if not re.match(remote_whitelist, remote_name):
                 continue
-            if branch_whitelist is None or not re.match(branch_whitelist, ref.name):
+            if branch_whitelist is None or not re.match(
+                branch_whitelist, ref.name
+            ):
                 continue
         else:
             continue
@@ -63,9 +72,17 @@ def get_refs(gitroot, tag_whitelist, branch_whitelist, remote_whitelist):
         yield ref
 
 
-def copy_tree(src, dst, reference, sourcepath='.'):
+def copy_tree(src, dst, reference, sourcepath="."):
     with tempfile.SpooledTemporaryFile() as fp:
-        cmd = ("git", "archive", "--format", "tar", reference.commit, "--", sourcepath)
+        cmd = (
+            "git",
+            "archive",
+            "--format",
+            "tar",
+            reference.commit,
+            "--",
+            sourcepath,
+        )
         subprocess.check_call(cmd, stdout=fp)
         fp.seek(0)
         with tarfile.TarFile(fileobj=fp) as tarfp:

+ 80 - 33
sphinx_multiversion/main.py

@@ -23,13 +23,41 @@ def main(argv=None):
         argv = sys.argv[1:]
 
     parser = argparse.ArgumentParser()
-    parser.add_argument('sourcedir', help='path to documentation source files')
-    parser.add_argument('outputdir', help='path to output directory')
-    parser.add_argument('filenames', nargs='*', help='a list of specific files to rebuild. Ignored if -a is specified')
-    parser.add_argument('-c', metavar='PATH', dest='confdir', help='path where configuration file (conf.py) is located (default: same as SOURCEDIR)')
-    parser.add_argument('-C', action='store_true', dest='noconfig', help='use no config file at all, only -D options')
-    parser.add_argument('-D', metavar='setting=value', action='append', dest='define', default=[], help='override a setting in configuration file')
-    parser.add_argument('--dump-metadata', action='store_true', help='dump generated metadata and exit')
+    parser.add_argument("sourcedir", help="path to documentation source files")
+    parser.add_argument("outputdir", help="path to output directory")
+    parser.add_argument(
+        "filenames",
+        nargs="*",
+        help="a list of specific files to rebuild. Ignored if -a is specified",
+    )
+    parser.add_argument(
+        "-c",
+        metavar="PATH",
+        dest="confdir",
+        help=(
+            "path where configuration file (conf.py) is located "
+            "(default: same as SOURCEDIR)"
+        ),
+    )
+    parser.add_argument(
+        "-C",
+        action="store_true",
+        dest="noconfig",
+        help="use no config file at all, only -D options",
+    )
+    parser.add_argument(
+        "-D",
+        metavar="setting=value",
+        action="append",
+        dest="define",
+        default=[],
+        help="override a setting in configuration file",
+    )
+    parser.add_argument(
+        "--dump-metadata",
+        action="store_true",
+        help="dump generated metadata and exit",
+    )
     args, argv = parser.parse_known_args(argv)
     if args.noconfig:
         return 1
@@ -37,7 +65,7 @@ def main(argv=None):
     # Conf-overrides
     confoverrides = {}
     for d in args.define:
-        key, _, value = d.partition('=')
+        key, _, value = d.partition("=")
         confoverrides[key] = value
 
     # Parse config
@@ -46,16 +74,24 @@ def main(argv=None):
         confoverrides,
     )
     config.add("smv_tag_whitelist", sphinx.DEFAULT_TAG_WHITELIST, "html", str)
-    config.add("smv_branch_whitelist", sphinx.DEFAULT_TAG_WHITELIST, "html", str)
-    config.add("smv_remote_whitelist", sphinx.DEFAULT_REMOTE_WHITELIST, "html", str)
-    config.add("smv_released_pattern", sphinx.DEFAULT_RELEASED_PATTERN, "html", str)
-    config.add("smv_outputdir_format", sphinx.DEFAULT_OUTPUTDIR_FORMAT, "html", str)
+    config.add(
+        "smv_branch_whitelist", sphinx.DEFAULT_TAG_WHITELIST, "html", str
+    )
+    config.add(
+        "smv_remote_whitelist", sphinx.DEFAULT_REMOTE_WHITELIST, "html", str
+    )
+    config.add(
+        "smv_released_pattern", sphinx.DEFAULT_RELEASED_PATTERN, "html", str
+    )
+    config.add(
+        "smv_outputdir_format", sphinx.DEFAULT_OUTPUTDIR_FORMAT, "html", str
+    )
     config.add("smv_prefer_remote_refs", False, "html", bool)
     config.pre_init_values()
     config.init_values()
 
     # Get git references
-    gitroot = pathlib.Path('.').resolve()
+    gitroot = pathlib.Path(".").resolve()
     gitrefs = git.get_refs(
         str(gitroot),
         config.smv_tag_whitelist,
@@ -90,33 +126,37 @@ def main(argv=None):
             except (OSError, subprocess.CalledProcessError):
                 logger.error(
                     "Failed to copy git tree for %s to %s",
-                    gitref.refname, repopath)
+                    gitref.refname,
+                    repopath,
+                )
                 continue
 
             # Find config
             confpath = os.path.join(repopath, confdir)
             try:
                 current_config = sphinx_config.Config.read(
-                    confpath,
-                    confoverrides,
+                    confpath, confoverrides,
                 )
             except (OSError, sphinx_config.ConfigError):
                 logger.error(
                     "Failed load config for %s from %s",
-                    gitref.refname, confpath)
+                    gitref.refname,
+                    confpath,
+                )
                 continue
             current_config.pre_init_values()
             current_config.init_values()
 
             # Ensure that there are not duplicate output dirs
             outputdir = config.smv_outputdir_format.format(
-                ref=gitref,
-                config=current_config,
+                ref=gitref, config=current_config,
             )
             if outputdir in outputdirs:
                 logger.warning(
                     "outputdir '%s' for %s conflicts with other versions",
-                    outputdir, gitref.refname)
+                    outputdir,
+                    gitref.refname,
+                )
                 continue
             outputdirs.add(outputdir)
 
@@ -126,18 +166,21 @@ def main(argv=None):
                 source_suffixes = [current_config.source_suffix]
 
             current_sourcedir = os.path.join(repopath, sourcedir)
-            project = sphinx_project.Project(current_sourcedir, source_suffixes)
+            project = sphinx_project.Project(
+                current_sourcedir, source_suffixes
+            )
             metadata[gitref.name] = {
                 "name": gitref.name,
                 "version": current_config.version,
                 "release": current_config.release,
                 "is_released": bool(
-                    re.match(config.smv_released_pattern, gitref.refname)),
+                    re.match(config.smv_released_pattern, gitref.refname)
+                ),
                 "source": gitref.source,
-                "creatordate": gitref.creatordate.strftime("%Y-%m-%d %H:%M:%S %z"),
+                "creatordate": gitref.creatordate.strftime(sphinx.DATE_FMT),
                 "sourcedir": current_sourcedir,
                 "outputdir": outputdir,
-                "docnames": list(project.discover())
+                "docnames": list(project.discover()),
             }
 
         if args.dump_metadata:
@@ -150,7 +193,7 @@ def main(argv=None):
 
         # Write Metadata
         metadata_path = os.path.abspath(os.path.join(tmp, "versions.json"))
-        with open(metadata_path, mode='w') as fp:
+        with open(metadata_path, mode="w") as fp:
             json.dump(metadata, fp, indent=2)
 
         # Run Sphinx
@@ -160,14 +203,18 @@ def main(argv=None):
             os.makedirs(outdir, exist_ok=True)
 
             current_argv = argv.copy()
-            current_argv.extend([
-                *itertools.chain(*(('-D', d) for d in args.define)),
-                "-D", "smv_current_version={}".format(version_name),
-                "-c", args.confdir,
-                data["sourcedir"],
-                outdir,
-                *args.filenames,
-            ])
+            current_argv.extend(
+                [
+                    *itertools.chain(*(("-D", d) for d in args.define)),
+                    "-D",
+                    "smv_current_version={}".format(version_name),
+                    "-c",
+                    args.confdir,
+                    data["sourcedir"],
+                    outdir,
+                    *args.filenames,
+                ]
+            )
             status = sphinx_build.build_main(current_argv)
             if status not in (0, None):
                 break

+ 55 - 35
sphinx_multiversion/sphinx.py

@@ -13,19 +13,16 @@ from sphinx.locale import _
 
 logger = logging.getLogger(__name__)
 
-DEFAULT_TAG_WHITELIST = r'^.*$'
-DEFAULT_BRANCH_WHITELIST = r'^.*$'
+DATE_FMT = "%Y-%m-%d %H:%M:%S %z"
+DEFAULT_TAG_WHITELIST = r"^.*$"
+DEFAULT_BRANCH_WHITELIST = r"^.*$"
 DEFAULT_REMOTE_WHITELIST = None
-DEFAULT_RELEASED_PATTERN = r'^tags/.*$'
-DEFAULT_OUTPUTDIR_FORMAT = r'{ref.name}'
+DEFAULT_RELEASED_PATTERN = r"^tags/.*$"
+DEFAULT_OUTPUTDIR_FORMAT = r"{ref.name}"
 
-Version = collections.namedtuple('Version', [
-    'name',
-    'url',
-    'version',
-    'release',
-    'is_released',
-])
+Version = collections.namedtuple(
+    "Version", ["name", "url", "version", "release", "is_released",]
+)
 
 
 class VersionInfo:
@@ -46,23 +43,35 @@ class VersionInfo:
 
     @property
     def tags(self):
-        return [self._dict_to_versionobj(v) for v in self.metadata.values()
-                if v["source"] == "tags"]
+        return [
+            self._dict_to_versionobj(v)
+            for v in self.metadata.values()
+            if v["source"] == "tags"
+        ]
 
     @property
     def branches(self):
-        return [self._dict_to_versionobj(v) for v in self.metadata.values()
-                if v["source"] != "tags"]
+        return [
+            self._dict_to_versionobj(v)
+            for v in self.metadata.values()
+            if v["source"] != "tags"
+        ]
 
     @property
     def releases(self):
-        return [self._dict_to_versionobj(v) for v in self.metadata.values()
-                if v["is_released"]]
+        return [
+            self._dict_to_versionobj(v)
+            for v in self.metadata.values()
+            if v["is_released"]
+        ]
 
     @property
     def in_development(self):
-        return [self._dict_to_versionobj(v) for v in self.metadata.values()
-                if not v["is_released"]]
+        return [
+            self._dict_to_versionobj(v)
+            for v in self.metadata.values()
+            if not v["is_released"]
+        ]
 
     def __iter__(self):
         for item in self.tags:
@@ -84,29 +93,32 @@ class VersionInfo:
 
     def vpathto(self, other_version_name):
         if self.current_version_name == other_version_name:
-            return '{}.html'.format(
-                posixpath.split(self.context["pagename"])[-1])
+            return "{}.html".format(
+                posixpath.split(self.context["pagename"])[-1]
+            )
 
         # Find output root
         current_version = self.metadata[self.current_version_name]
         relpath = pathlib.PurePath(current_version["outputdir"])
-        outputroot = os.path.join(
-            *('..' for x in relpath.joinpath(self.context["pagename"]).parent.parts)
-        )
+        relpath_dir = relpath.joinpath(self.context["pagename"]).parent
+        outputroot = os.path.join(*(".." for x in relpath_dir.parts))
 
         # Find output dir of other version
         other_version = self.metadata[other_version_name]
         outputdir = posixpath.join(outputroot, other_version["outputdir"])
 
         if not self.vhasdoc(other_version_name):
-            return posixpath.join(outputdir, 'index.html')
+            return posixpath.join(outputdir, "index.html")
 
-        return posixpath.join(outputdir, '{}.html'.format(self.context["pagename"]))
+        return posixpath.join(
+            outputdir, "{}.html".format(self.context["pagename"])
+        )
 
 
 def html_page_context(app, pagename, templatename, context, doctree):
     versioninfo = VersionInfo(
-        app, context, app.config.smv_metadata, app.config.smv_current_version)
+        app, context, app.config.smv_metadata, app.config.smv_current_version
+    )
     context["versions"] = versioninfo
     context["vhasdoc"] = versioninfo.vhasdoc
     context["vpathto"] = versioninfo.vpathto
@@ -116,7 +128,6 @@ def html_page_context(app, pagename, templatename, context, doctree):
     context["html_theme"] = app.config.html_theme
 
 
-
 def config_inited(app, config):
     """Update the Sphinx builder.
     :param sphinx.application.Sphinx app: Sphinx application object.
@@ -150,9 +161,10 @@ def config_inited(app, config):
     config.today = old_config.today
     if not config.today:
         config.today = sphinx_i18n.format_date(
-            format=config.today_fmt or _('%b %d, %Y'),
-            date=datetime.datetime.strptime(data["creatordate"], "%Y-%m-%d %H:%M:%S %z"),
-            language=config.language)
+            format=config.today_fmt or _("%b %d, %Y"),
+            date=datetime.datetime.strptime(data["creatordate"], DATE_FMT),
+            language=config.language,
+        )
 
 
 def setup(app):
@@ -161,10 +173,18 @@ def setup(app):
     app.add_config_value("smv_current_version", "", "html")
     app.add_config_value("smv_latest_version", "master", "html")
     app.add_config_value("smv_tag_whitelist", DEFAULT_TAG_WHITELIST, "html")
-    app.add_config_value("smv_branch_whitelist", DEFAULT_BRANCH_WHITELIST, "html")
-    app.add_config_value("smv_remote_whitelist", DEFAULT_REMOTE_WHITELIST, "html")
-    app.add_config_value("smv_released_pattern", DEFAULT_RELEASED_PATTERN, "html")
-    app.add_config_value("smv_outputdir_format", DEFAULT_OUTPUTDIR_FORMAT, "html")
+    app.add_config_value(
+        "smv_branch_whitelist", DEFAULT_BRANCH_WHITELIST, "html"
+    )
+    app.add_config_value(
+        "smv_remote_whitelist", DEFAULT_REMOTE_WHITELIST, "html"
+    )
+    app.add_config_value(
+        "smv_released_pattern", DEFAULT_RELEASED_PATTERN, "html"
+    )
+    app.add_config_value(
+        "smv_outputdir_format", DEFAULT_OUTPUTDIR_FORMAT, "html"
+    )
     app.connect("config-inited", config_inited)
 
     return {