PK}L {{flinx/__init__.py"""Configuration-free Python doc generation via Sphinx.""" __version__ = '0.2.0' from .commands import cli # noqa: F401 PK}LͰflinx/commands.pyimport inspect import subprocess import sys import webbrowser from functools import wraps from pathlib import Path import click from sphinx.cmd.build import main as sphinx_build from .generation import write_template_files def generation_options(verbose=True): """Add generation options.""" def inner(f): @click.option('--force', is_flag=True, help="Overwrite conf.py and index.rst") @click.option('--unless-exists', is_flag=True, help="Skip conf.py and index.rst generation without error, " "if non-generated files exists.") @click.option('--verbose', is_flag=True, default=verbose) @wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) return wrapper return inner @click.group() def cli(): """Configuration-free Sphinx builder.""" pass @cli.command() @generation_options(verbose=True) def generate(force=False, unless_exists=False, verbose=False): """Write the generated files.""" docs_dir = Path('./docs') write_template_files(docs_dir, force=force, unless_exists=unless_exists, verbose=verbose) @cli.command() @generation_options(verbose=True) def eject(force=False, unless_exists=False, verbose=False): """Write the generated files, without header warnings.""" docs_dir = Path('./docs') write_template_files(docs_dir, force=force, include_generated_warning=False, unless_exists=unless_exists, verbose=verbose) def build_sphinx_args(all_files=False, force=False, fmt='html', unless_exists=False, verbose=False, **args): """Translate shared options into a new set of options, and write templates.""" docs_dir = Path('./docs') build_dir = docs_dir / '_build' / fmt write_template_files(docs_dir, force=force, unless_exists=unless_exists, verbose=verbose) args = [ '-b', fmt, '-c', str(docs_dir), # config file directory '-j', 'auto', # processors ] if not verbose: args += ['-q'] if all_files: args += ['-a'] args += [str(docs_dir), str(build_dir), ] 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', 'fmt', default='html', help='The output format.') @generation_options(verbose=False) @wraps(f) def wrapper(**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 non_variadic_param_names(f): """Return a set of names of f's non-variadic parameters.""" 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} # names of parameters to the wrapped function wrapped_args = non_variadic_param_names(f) # names of parameters that shouldn't be passed to the wrapped function consumed_args = non_variadic_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, fmt=None, open_url=False): """Use sphinx-build to build the documentation.""" status = sphinx_build(build_args) if status: sys.exit(status) if open_url and fmt == '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(process.returncode) if __name__ == '__main__': sys.exit(cli() or 0) PK=rL-flinx/configuration.pyfrom functools import reduce from pathlib import Path import pytoml as toml 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 {} PKrL88flinx/extensions.py# 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 = { 'autoclass': 'autodoc', 'image': 'imgconverter', 'inheritance': 'inheritance_diagram', } # Use this, if the user doesn't specify extensions. default_extensions = ['autodoc'] 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 PK}Ls  flinx/generation.pyimport sys from pathlib import Path from click import ClickException from jinja2 import Environment from .configuration import get_sphinx_configuration from .extensions import get_extensions from .project_metadata import NoUniqueModuleError, ProjectMetadata GENERATED_TEXT = "THIS FILE IS AUTOMATICALLY GENERATED BY FLINX. " "MANUAL CHANGES WILL BE LOST." 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()) class NonGeneratedFileExists(ClickException): """An exception that indicates a non-generate file exists. An exception for ``write_template_files`` to raise when a writing a file would replace a non - generated file. """ @property def path(self): """Return the pathname of the file, as a Path.""" return self.args[0] def format_message(self): """Return the message for click to display.""" return "won't overwrite {}; aborting. " \ "Use --force to overwrite.".format(str(self.path)) def write_template_files(output_dir, force=True, include_generated_warning=True, unless_exists=False, verbose=True): """Generate the ``conf.py`` and ``README.rst`` files.""" index_path = output_dir / 'index.rst' conf_path = output_dir / 'conf.py' overwritten_files = [path for path in (conf_path, index_path) if path.exists() and GENERATED_TEXT not in path.read_text()] if overwritten_files and not force: if unless_exists: return raise NonGeneratedFileExists(overwritten_files[0]) output_dir.mkdir(parents=True, exist_ok=True) 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.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.write_text(conf_text) if verbose: print('Wrote', conf_path) return conf_path 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.2.0.dist-info/entry_points.txtN+I/N.,()J̫zy)V9\\PKZL0*88flinx-0.2.0.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 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!HNOflinx-0.2.0.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,zd&Y)r$[)T&UrPK!HSB flinx-0.2.0.dist-info/METADATAYnba-G EAAUKJa  wKrKQ Ҿ\#y@C"c73T];ol9ϓg*X.sSދyTE\3l4کi-7amKTt%o5h%-R+P_Ph2a]/#ֹE&եɏooE n,fPc)DTsm(X~E>ubKeN Aʕfi4^lYނVd~w;UFgf2{WUlr%o]ĻrRfUxʩ ת\հ%]}Q"SV&K֤';Ӈo2lRotnΆ}>;G]2Mzwk-UϫCUM 'G`KV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ates/index.rst.tplPK!H{*,&Iflinx-0.2.0.dist-info/entry_points.txtPKZL0*88EJflinx-0.2.0.dist-info/LICENSEPK!HNONflinx-0.2.0.dist-info/WHEELPK!HSB ?Oflinx-0.2.0.dist-info/METADATAPK!H XDYflinx-0.2.0.dist-info/RECORDPK x\