PKՀLW{{flinx/__init__.py"""Configuration-free Python doc generation via Sphinx.""" __version__ = '0.1.3' from .commands import cli # noqa: F401 PKYL1▪flinx/commands.pyimport inspect import subprocess import sys import webbrowser from functools import reduce, wraps from pathlib import Path import click from jinja2 import Environment import pytoml as toml from sphinx.cmd.build import main as sphinx_build from .project_metadata import NoModuleException, 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 NoModuleException 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): # 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): try: project = toml.loads(Path('pyproject.toml').read_text()) return reduce(lambda a, b: a[b], 'tool.flinx.configuration'.split('.'), project) except (FileNotFoundError, KeyError): return {} @click.group() def cli(): pass @cli.command() def generate(): docs_dir = Path('./docs') write_template_files(docs_dir, verbose=True) @cli.command() def eject(): docs_dir = Path('./docs') write_template_files(docs_dir, include_generated_warning=False, verbose=True) def build_sphinx_args(all=False, format='html', verbose=False, **args): docs_dir = Path('./docs') build_dir = docs_dir / '_build' / format docs_dir.mkdir(exist_ok=True) conf_path = write_template_files(docs_dir, verbose=verbose) args = [ '-b', format, '-c', str(conf_path.parent), # config file '-j', 'auto', # processors '-q', # quiet str(docs_dir), str(build_dir) ] if all: args += ['-a'] return dict(build_args=args, build_dir=build_dir, docs_dir=docs_dir) def with_sphinx_build_args(f): @click.option('-a', '--all', is_flag=True, help='Rebuild all the docs, regardless of what has changed.') @click.option('-o', '--open', is_flag=True, help='Open the HTML index in a browser.') @click.option('--format', 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=False): """Build the documentation.""" status = sphinx_build(build_args) if status: sys.exit(sys.exit) if open and format == 'html': webbrowser.open(str(build_dir / 'index.html')) @cli.command() @with_sphinx_build_args def serve(build_args=None, open=False): if open: build_args += ['-B'] process = subprocess.run(['sphinx-autobuild'] + build_args) if process.returncode: sys.exit(1) if __name__ == '__main__': sys.exit(cli() or 0) PK[uLZ--flinx/project_metadata.pyimport 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 PyProjectMetadataProviderABC(object): _metadata = dict() _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): if key in self._translations: key = self._translations[key] if isinstance(key, list): for k in key: try: return self[k] except KeyError: pass raise KeyError(key) if callable(getattr(self, key, None)): return getattr(self, key)() return self._metadata[key] class FlinxMetadata(PyProjectMetadataProviderABC): _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): _toml_path = 'tool.poetry' def 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): match = version_re.search(path.read_text()) return match.group(1).strip('"\'') if match else None def module_candidates(project_path='.', search='file'): """Yields 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 NoModuleException(Exception): pass def find_module(project_path): """Find the module. Prefer directories over files.""" module_paths = module_candidates(project_path, 'file') \ or module_candidates(project_path, 'dir') if not module_paths: raise NoModuleException("Couldn't find module") if len(module_paths) > 2: raise NoModuleException("Too many module candidates") return module_paths[0] class InspectedMetadata(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 module(self): return str(find_module(self.project_path)) def name(self): return str(self.project_path.name) def 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 date(self): return datetime.now().strftime('%Y') def readme(self): paths = [path.name for path in self.project_path.glob("*") if self.readme_re.match(str(path.name))] return str(paths[0]) if paths else None def __getitem__(self, key): try: fn = getattr(self, key) except AttributeError: raise KeyError(key) return fn() class CombinedMetadata(object): """Return keyed metadata from the first successful source.""" def __init__(self, sources): self.sources = sources def __getitem__(self, key): for source in self.sources: try: return source[key] except KeyError: pass raise KeyError(key) class ProjectMetadata(CombinedMetadata): _project_sources = [FlinxMetadata, FlitMetadata, PoetryMetadata] sources = [] @classmethod def from_dir(klass, dir): return klass(dir) def __init__(self, dir='.'): self._dir = Path(dir) project_path = self._dir / 'pyproject.toml' sources = [] if project_path.exists(): sources += [klass(project_path) for klass in self._project_sources] sources.append(InspectedMetadata(dir)) super().__init__(sources) def _get_version(self): module_path = self._dir / self['module'] path = module_path / '__init__.py' \ if module_path.is_dir() else Path(str(module_path)+'.py') return read_version_def(path) def __getitem__(self, key): try: return super().__getitem__(key) except KeyError: if key == 'version': return self._get_version() raise if __name__ == '__main__': for klass in [FlinxMetadata, FlitMetadata, PoetryMetadata, InspectedMetadata, 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{Lfflinx/templates/conf.py.tpl{%- if generated_text -%} # {{ generated_text }} # # Make changes to ``project.toml``, and run ``flinx generate``, instead. {% else %} # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config {%- 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.3.dist-info/entry_points.txtN+I/N.,()J̫zy)V9\\PKZL0*88flinx-0.1.3.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.1.3.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,zd&Y)r$[)T&UrPK!HC] flinx-0.1.3.dist-info/METADATAYbj8ǐ8FB^rvls (6GrݥtJQ Ҿ\R?Swoa^ 1}=Uoteƴ(m}/>ɞfM[Uovzvз۸r5.MzEkYAV^ UMFKW<]5r!SQR|msS|oo~F]kFwOҶSNKUO& yc3ueBm#×h86}}R`@zm+Loo&t4ޭM^m$Nn0JwiR1wK/\z"|%Oϲ?nܺ-) GAJ7n72kSfþ}lcKߝ>Dig擧AuݼeM]hQ*/FqeP!ndQ qK)G3-lFwXMTP#%"#[Sù2!d@DV}yYH8yԲt*hFoYD4 1,K׀t].0B].mFH 0y64hnH *B(,uuMo $=kCA Dve9E7QD~ju-@4iZHͺ* ͔>~/ ~,ذ "riK \ #Alg31 xIhwLg _e!Ylpm^Je}eș@dlW@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ǥZa1J <%5,Oop1Uh̺ZxZ1KZ=M6 Eoƫ?F=ڦLu\˧d?H%_ ޞΒ)7o/mP3 e7DŌ8tؕVa+Vu?ݚzqPKՀLW{{flinx/__init__.pyPKYL1▪flinx/commands.pyPK[uLZ--flinx/project_metadata.pyPK{Lf3flinx/templates/conf.py.tplPKVL(AA<8flinx/templates/index.rst.tplPK!H{*,&9flinx-0.1.3.dist-info/entry_points.txtPKZL0*88&:flinx-0.1.3.dist-info/LICENSEPK!HNO>flinx-0.1.3.dist-info/WHEELPK!HC]  ?flinx-0.1.3.dist-info/METADATAPK!Hpn Iflinx-0.1.3.dist-info/RECORDPK K