PKvLm{{flinx/__init__.py"""Configuration-free Python doc generation via Sphinx.""" __version__ = '0.1.4' from .commands import cli # noqa: F401 PK|vLX`((flinx/commands.py"""Flinx CLI.""" import inspect import subprocess import sys import webbrowser from functools import reduce, wraps from pathlib import Path import click import pytoml as toml from jinja2 import Environment from sphinx.cmd.build import main as sphinx_build from .project_metadata import NoUniqueModuleError, ProjectMetadata GENERATED_TEXT = "THIS FILE IS AUTOMATICALLY GENERATED BY FLINX. " "MANUAL CHANGES WILL BE LOST." # Allow these names as shortcuts for sphinx.ext.*. sphinx_builtin_extensions = ['autodoc', 'autosectionlabel', 'autosummary', 'coverage', 'doctest', 'extlinks', 'githubpages', 'graphviz', 'ifconfig', 'imgconverter', 'imgmath', 'mathjax', 'jsmith', 'inheritance_diagram', 'intersphinx', 'linkcode', 'napoleon', 'todo', 'viewcode'] # Configuration variables that start with image_ imply the imgconverter (not image) # extension, etc. config_var_ext_prefixes = {'image': 'imgconverter', 'inheritance': 'inheritance_graph'} # Use this, if the user doesn't specify extensions. default_extensions = ['autodoc'] env = Environment() env.filters['repr'] = repr poject_relpath = Path('..') env.filters['project_rel'] = lambda s: str(poject_relpath / s) TEMPLATE_DIR = Path(__file__).parent / 'templates' conf_tpl = env.from_string((TEMPLATE_DIR / 'conf.py.tpl').read_text()) index_tpl = env.from_string((TEMPLATE_DIR / 'index.rst.tpl').read_text()) def write_template_files(output_dir, include_generated_warning=True, verbose=True): """Generate the ``conf.py`` and ``README.rst`` files.""" # TODO: refuse to overwrite non-generated files? metadata = ProjectMetadata.from_dir('.') config = get_sphinx_configuration('.') try: metadata['name'] # for effect except NoUniqueModuleError as e: sys.stderr.write("{}\n".format(e)) sys.exit(1) generated_text = GENERATED_TEXT if include_generated_warning else None index_text = index_tpl.render( readme=metadata['readme'], module_name=metadata['module'], generated_text=generated_text, ) index_path = output_dir / 'index.rst' index_path.write_text(index_text) if verbose: print('wrote', index_path) author = metadata['author'] copyright_year = metadata['date'] config['extensions'] = get_extensions(config) conf_text = conf_tpl.render( module_path='..', project=metadata['name'], copyright=f'{copyright_year}, {author}', author=author, version=metadata['version'], source_suffix=['.rst'], master_basename='index', generated_text=generated_text, config=config.items(), ) conf_path = output_dir / 'conf.py' conf_path.write_text(conf_text) if verbose: print('wrote', conf_path) return conf_path def get_extensions(config_vars): """Infer the extensions from the Sphinx configuration variables.""" # expand shortcut names extensions = ['sphinx.ext.' + ext if ext in sphinx_builtin_extensions else ext for ext in config_vars.get('extensions', default_extensions)] # add extensions implied by configuration value names prefixes = {k.split('_', 1)[0] for k in config_vars.keys() if '_' in k} detected_exts = (config_var_ext_prefixes.get(prefix, prefix) for prefix in prefixes) auto_exts = sorted('sphinx.ext.' + ext for ext in detected_exts if ext in sphinx_builtin_extensions) for ext in auto_exts: if ext not in extensions: extensions.append(ext) return extensions def get_sphinx_configuration(project_dir): """Read the Sphinx configuration from ``pyproject.toml```.""" try: project = toml.loads((Path(project_dir) / 'pyproject.toml').read_text()) return reduce(lambda a, b: a[b], 'tool.flinx.configuration'.split('.'), project) except (FileNotFoundError, KeyError): return {} @click.group() def cli(): """Configuration-free Sphinx builder.""" pass @cli.command() def generate(): """Write the generated files.""" docs_dir = Path('./docs') write_template_files(docs_dir, verbose=True) @cli.command() def eject(): """Write the generated files, without header warnings.""" docs_dir = Path('./docs') write_template_files(docs_dir, include_generated_warning=False, verbose=True) def build_sphinx_args(all_files=False, formatting='html', verbose=False, **args): """Translate shared options into a new set of options, and write templates.""" docs_dir = Path('./docs') build_dir = docs_dir / '_build' / formatting docs_dir.mkdir(exist_ok=True) conf_path = write_template_files(docs_dir, verbose=verbose) args = [ '-b', formatting, '-c', str(conf_path.parent), # config file '-j', 'auto', # processors '-q', # quiet str(docs_dir), str(build_dir) ] if all_files: args += ['-a'] return dict(build_args=args, build_dir=build_dir, docs_dir=docs_dir) def with_sphinx_build_args(f): """Decorate a function to consume a common set of options.""" @click.option('-a', '--all-files', is_flag=True, help='Rebuild all the docs, regardless of what has changed.') @click.option('-o', '--open-url', is_flag=True, help='Open the HTML index in a browser.') @click.option('--format', 'formatting', default='html', type=click.Choice(['html']), help='The output format.') @click.option('--verbose', is_flag=True) @wraps(f) def wrapper(**kwargs): # build_args, build_dir, docs_dir = build_sphinx_args(**kwargs) build_args = build_sphinx_args(**kwargs) kwargs = {k: v for k, v in kwargs.items() if k not in consumed_args} for k, v in build_args.items(): if k in wrapped_args: kwargs[k] = v return f(**kwargs) def position_param_names(f): var_parameter_kinds = \ (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD) return {p.name for p in inspect.signature(f).parameters.values() if p.kind not in var_parameter_kinds} wrapped_args = position_param_names(f) consumed_args = position_param_names(build_sphinx_args) - wrapped_args return wrapper @cli.command() @with_sphinx_build_args def build(build_args=None, docs_dir=None, build_dir=None, format=None, open_url=False): """Use sphinx-build to build the documentation.""" status = sphinx_build(build_args) if status: sys.exit(sys.exit) if open_url and format == 'html': webbrowser.open(str(build_dir / 'index.html')) @cli.command() @with_sphinx_build_args def serve(build_args=None, open_url=False): """Use sphinx-autobuild to build and serve the documentation.""" if open_url: build_args += ['-B'] process = subprocess.run(['sphinx-autobuild'] + build_args) if process.returncode: sys.exit(1) if __name__ == '__main__': sys.exit(cli() or 0) PKvL{flinx/project_metadata.py"""Read the project metadata from a variety of sources.""" import re import subprocess import sys from datetime import datetime from functools import reduce from pathlib import Path import pytoml as toml test_filename_re = re.compile(r'^(test_|_test)$') version_re = re.compile(r'^\s*__version__\s*=\s*(\'.*?\'|".*?")', re.M) class CombinedMetadata(object): """Combine metadata from multiple sources.""" def __init__(self, sources): self.sources = sources def __getitem__(self, key): """Return a project metadata value.""" for source in self.sources: try: return source[key] except KeyError: pass raise KeyError(key) class PyProjectMetadataProviderABC(object): """Abstract base class for metadata sources that read ``pyproject.toml``.""" _metadata = {} _translations = {} def __init__(self, project_path='pyproject.toml'): project = toml.loads(Path(project_path).read_text()) try: dotpath = self._toml_path.split('.') self._metadata = reduce(lambda a, b: a[b], dotpath, project) except KeyError: pass def __getitem__(self, key): """Return a project metadata value.""" translation = self._translations.get(key, key) if isinstance(translation, list): for k in translation: try: return self[k] except KeyError: pass raise KeyError(key) getter = getattr(self, '_get_' + translation.replace('-', '_'), None) if callable(getter): return getter() return self._metadata[translation] class FlinxMetadata(PyProjectMetadataProviderABC): """Provide project metadata from the Flinx section of ``pyproject.toml``.""" _toml_path = 'tool.flinx.metadata' class FlitMetadata(PyProjectMetadataProviderABC): """Metadata provider that reads the Flit data from ``pyproject.toml``.""" _toml_path = 'tool.flit.metadata' _translations = { 'name': ['dist-name', 'module'], 'readme': 'description-file', } class PoetryMetadata(PyProjectMetadataProviderABC): """Provide project metadata from the Poetry section of ``pyproject.toml``.""" _toml_path = 'tool.poetry' def _get_author(self): authors = self['authors'] if not authors: raise KeyError('author') authors = [(author + '<').split('<')[0].strip() for author in authors] if len(authors) > 1: authors[-1] = 'and ' + authors[-1] return (', ' if len(authors) > 2 else ' ').join(authors) def read_version_def(path): """Return the version string from a module.""" match = version_re.search(path.read_text()) return match.group(1).strip('"\'') if match else None def module_candidates(project_path='.', search='file'): """Yield the candidate modules in the current directory. A candidate file module is a non-test file that contains the string ``__version = …``, according to grep. A candidate directory module is a non-test directory that contains an ``__init__`` file that contains this string. ``search`` should be one of "file" and "dir". """ root = Path(project_path) if search == 'file': paths = [p for p in root.glob('*.py') if p.is_file()] paths = [p for p in paths if not test_filename_re.match(str(p.stem))] else: paths = [p for p in root.glob('*') if p.is_dir()] paths = [p / '__init__.py' for p in paths if not test_filename_re.match(str(p))] paths = [p for p in paths if p.is_file()] paths = [p for p in paths if read_version_def(p)] if search == 'file': paths = [p.stem for p in paths] else: paths = [p.parent for p in paths] return paths class NoUniqueModuleError(Exception): """No module found.""" pass def find_module(project_home): """Find the module. Prefer directories over files.""" module_paths = module_candidates(project_home, 'file') \ or module_candidates(project_home, 'dir') if not module_paths: raise NoUniqueModuleError("Couldn't find module") if len(module_paths) > 1: raise NoUniqueModuleError("Too many module candidates") return Path(module_paths[0]) class InferredProjectMetadata(object): """Metadata provider that detects metadata from files in the current directory.""" readme_re = re.compile(r'^README.(md|rst)$', re.I) def __init__(self, project_path='.'): self.project_path = Path(project_path) def _get_module(self): return str(find_module(self.project_path).name) def _get_name(self): return str(self.project_path.name) def _get_author(self): process = subprocess.run(["git", "config", "user.name"], stdout=subprocess.PIPE) if process.returncode: sys.exit(1) if not process.stdout: raise Exception("Couldn't detect user name") return process.stdout.decode().strip() def _get_date(self): return datetime.now().strftime('%Y') def _get_readme(self): paths = [path for path in self.project_path.glob("*") if self.readme_re.match(str(path.name))] return str(paths[0].name) if paths else None def __getitem__(self, key): """Return a project metadata value.""" fn = getattr(self, '_get_' + key, None) if not fn: raise KeyError(key) return fn() class ProjectMetadata(CombinedMetadata): """Combine metadata from ``pyproject.toml`` and the directory structure.""" _project_source_classes = [FlinxMetadata, FlitMetadata, PoetryMetadata] sources = [] @classmethod def from_dir(cls, project_home): """Construct a ProjectMetadata that reads from the specified directory.""" return cls(project_home) def __init__(self, project_home='.'): self._project_home = Path(project_home) project_file_path = self._project_home / 'pyproject.toml' sources = [] if project_file_path.exists(): sources += [cls(project_file_path) for cls in self._project_source_classes] sources.append(InferredProjectMetadata(self._project_home)) super().__init__(sources) def _get_version(self): module_path = self._project_home / self['module'] init_path = module_path / '__init__.py' path = init_path if module_path.is_dir() else Path(str(module_path) + '.py') return read_version_def(path) def __getitem__(self, key): """Return a project metadata value.""" try: return super().__getitem__(key) except KeyError: if key == 'version': return self._get_version() raise if __name__ == '__main__': for klass in [FlinxMetadata, FlitMetadata, PoetryMetadata, InferredProjectMetadata, ProjectMetadata]: print(f'{klass.__name__}:') data = klass() for key in ['name', 'module', 'version', 'author', 'date', 'readme']: try: value = data[key] print("{:>8}: {}".format(key, value)) except KeyError: pass PK bLU  flinx/templates/conf.py.tpl# Configuration file for the Sphinx documentation builder. # {% if generated_text -%} # {{ generated_text }} # Make changes to ``project.toml``, and run ``flinx generate``. {%- else -%} # This file contains only the most common options. For a full list # see the `Sphinx documentation `. {%- endif %} import sys {% if '.md' in source_suffix %} from recommonmark.parser import CommonMarkParser {% endif %} sys.path.insert(0, '{{ module_path }}') project = '{{ project }}' copyright = {{ copyright | repr }} author = '{{ author }}' version = '{{ version }}' release = '{{ version }}' master_doc = '{{ master_basename }}' exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] source_suffix = {{ source_suffix }} {% if '.md' in source_suffix %} source_parsers = { '.md': CommonMarkParser } {% endif %} {%- if 'sphinx.ext.intersphinx' in extensions %} intersphinx_mapping = {'https://docs.python.org/': None} {%- endif %} {% for k, v in config %} {{ k }} = {{ v | repr }} {% endfor %} PKVL(AAflinx/templates/index.rst.tpl{%- if generated_text -%} .. {{ generated_text }} Make changes to ``project.toml``, and run ``flinx generate``, instead. {% endif -%} {% if readme %} .. include:: {{ readme | project_rel }} {% endif -%} .. toctree:: :maxdepth: 2 :caption: Contents: API --- .. automodule:: {{ module_name }} :members: PK!H{*,&flinx-0.1.4.dist-info/entry_points.txtN+I/N.,()J̫zy)V9\\PKZL0*88flinx-0.1.4.dist-info/LICENSEThe MIT License (MIT) Copyright (c) 2018 Oliver Steele Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECT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xɋh? EBA%MFe[)!5Naco4l/Gf%(s~9" Ou$yč| iٔUnpANt#.P"AID?jy3.f\J][WyT쾀p +vg?\R5a2zm}s&Y)D/C*h% ?z؅3l}SN ѲP&JPK!H^(? flinx-0.1.4.dist-info/RECORDuَ@~-Yb.KD!,BPӏN&?uE(HEPKQR r)*er $A*zH; cˀ%Ҷib ?nvз)ÿHvHˁ Ni`g1{妜8yMt;}v ҬSer$hk ׫*S$s:X |mw[gRvP @㹬,BֺVceB=ZO 1$QHZuC`#[`lFx!ԃD)Y,T^CqRbx=}AG@-#Cٯ7PKvLm{{flinx/__init__.pyPK|vLX`((flinx/commands.pyPKvL{flinx/project_metadata.pyPK bLU   :flinx/templates/conf.py.tplPKVL(AAL>flinx/templates/index.rst.tplPK!H{*,&?flinx-0.1.4.dist-info/entry_points.txtPKZL0*886@flinx-0.1.4.dist-info/LICENSEPK!HNODflinx-0.1.4.dist-info/WHEELPK!Hb>] 0Eflinx-0.1.4.dist-info/METADATAPK!H^(? Oflinx-0.1.4.dist-info/RECORDPK Q