PKכLwwflinx/__init__.py"""Configuration-free Python doc generation via Sphinx.""" __version__ = '0.1.2' from .cli import main # noqa: F401 PK}LK flinx/cli.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 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('.') 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['module'], 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 main(): pass @main.command() def generate(): docs_dir = Path('./docs') write_template_files(docs_dir, verbose=True) @main.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=False, 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 @main.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')) @main.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__': main() PK LĐflinx/project_metadata.pyimport re import subprocess import sys from datetime import datetime 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'): try: project = toml.loads(Path(project_path).read_text()) except FileNotFoundError: return from functools import reduce 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, tuple)): for k in key: try: return self[k] except KeyError: pass return 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 modules_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 def find_module(project_path): """Find the module. Prefer directories over files.""" module_paths = modules_candidates(project_path, 'file') \ or modules_candidates(project_path, 'dir') if not module_paths: raise Exception("Couldn't find a unique module") if len(module_paths) > 2: raise Exception("Too many module candidates") return module_paths[0] class DetectedMetadata(object): """Metadata provider that detects metadata from files in the current directory.""" def __init__(self, project_path='.'): self.project_path = Path(project_path) def module(self): return str(find_module(self.project_path)) 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): for filename in ['README.rst', 'README.md']: path = self.project_path / filename if path.exists(): return str(path) return None def __getitem__(self, key): try: fn = getattr(self, key) except AttributeError: return IndexError(key) return fn() class ProjectMetadata(object): """Return keyed metadata from the first successful provider.""" sources = [] _project_sources = [FlinxMetadata, FlitMetadata, PoetryMetadata] @staticmethod def from_dir(dir): return ProjectMetadata(dir) def __init__(self, project_path='.'): path = Path(project_path) / 'pyproject.toml' if path.exists(): self.sources += [klass(path) for klass in self._project_sources] self.sources.append(DetectedMetadata(project_path)) def version(self): module_path = Path(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): if key == 'version': return self.version() for backer in self.sources: try: return backer[key] except KeyError: pass return KeyError(key) if __name__ == '__main__': for klass in [FlinxMetadata, FlitMetadata, PoetryMetadata, DetectedMetadata, ProjectMetadata]: print(f'{klass.__name__}:') data = klass() for key in ['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!H5"$&flinx-0.1.2.dist-info/entry_points.txtN+I/N.,()J̫Vy\\PKZL0*88flinx-0.1.2.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.2.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,zd&Y)r$[)T&UrPK!HN] flinx-0.1.2.dist-info/METADATAYbj8ǐFB^rvls (6GrݥtJQ Ҿ\R?Swoa^ 1=˞72cZWdOgꦭ*c lx;\xcm\ &tӬ +S_ UMFKW<]5r!SQR|msS|oo~F]kFwOҶSNKUO& ycSueBm#×h86}}R`@zm+Loo&t4ޭM^m$Nn0JwiR1wK/\z"|%Oϳ?nܺ-) GAJ7n72kSfþ}lcKߝ>Dig擧AuݼeM]hQ*/FqeP!ndQ q+)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@c8蘟w~&͆ˉ#vDd @]\*WsC)B{_(2ST`oj [=]6rmY%?Idڦ6249V9䶶ꒊZdua:ONA=%6۪ iQVseLW?;3Pt6attT*F 5R-+z dӲe*r-wΒHxT 1G0G?aq )wTKw'L~Oo__?H :aqr s։~2b݀2m=u+6l͉O]ٹrquZ:pv;As XdЛf:5(OPU9/@ g=l@*t6kTdU%–A`;j~!@`¼tW>OIݡ &2eLt?k]bE^&cMG_OnԫK۷/o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