コード例 #1
0
ファイル: __main__.py プロジェクト: repo-helper/mkrecipe
def main(
    project: "PathLike" = '.',
    outfile: str = "conda/meta.yaml",
    artifact_type: "Literal['sdist', 'wheel']" = "sdist",
    show_traceback: bool = False,
):
    """
	Make a conda recipe for the given project.
	"""

    # 3rd party
    from domdf_python_tools.paths import PathPlus
    from pyproject_parser.cli import ConfigTracebackHandler

    # this package
    from mkrecipe import MaryBerry

    with handle_tracebacks(show_traceback, ConfigTracebackHandler):
        recipe_file = PathPlus(outfile)
        recipe_file.parent.maybe_make(parents=True)

        if artifact_type == "sdist":
            recipe = MaryBerry(project).make()
        elif artifact_type == "wheel":
            recipe = MaryBerry(project).make_for_wheel()
        else:  # pragma: no cover
            # Click should handle this case for us
            raise click.BadOptionUsage(
                "type", f"Unknown value for '--type': {artifact_type}")

        recipe_file.write_clean(recipe)
        click.echo(f"Recipe written to {recipe_file.as_posix()!r}")
コード例 #2
0
ファイル: docs.py プロジェクト: repo-helper/repo_helper
def make_docutils_conf(repo_path: pathlib.Path,
                       templates: Environment) -> List[str]:
    """
	Add configuration for ``Docutils``.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    file = PathPlus(repo_path / templates.globals["docs_dir"] /
                    "docutils.conf")
    file.parent.maybe_make(parents=True)

    if not file.is_file():
        file.write_text('\n'.join([
            "[restructuredtext parser]",
            "tab_width = 4",
            '',
            '',
        ]))

    conf = ConfigUpdater()
    conf.read(str(file))
    required_sections = ["restructuredtext parser"]

    for section in required_sections:
        if section not in conf.sections():
            conf.add_section(section)

    conf["restructuredtext parser"]["tab_width"] = 4

    file.write_clean(str(conf))

    return [file.relative_to(repo_path).as_posix()]
コード例 #3
0
def make_pkginfo(repo_path: pathlib.Path, templates: Environment) -> List[str]:
    """
	Update the ``__pkginfo__.py`` file.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    pkginfo_file = PathPlus(repo_path / "__pkginfo__.py")

    if templates.globals["extras_require"]:

        __pkginfo__ = templates.get_template("__pkginfo__._py")

        pkginfo_file.write_clean(__pkginfo__.render())

        with resource(repo_helper.files, "isort.cfg") as isort_config:
            yapf_style = PathPlus(
                isort_config).parent.parent / "templates" / "style.yapf"
            reformat_file(pkginfo_file,
                          yapf_style=str(yapf_style),
                          isort_config_file=str(isort_config))

    else:
        pkginfo_file.unlink(missing_ok=True)

    return [pkginfo_file.name]
コード例 #4
0
def replace_emoji(app: Sphinx, exception: Optional[Exception] = None):
    if exception:
        return

    if app.builder.name.lower() != "latex":
        return

    output_file = PathPlus(
        app.builder.outdir) / f"{app.builder.titles[0][1]}.tex"

    output_content = output_file.read_text()

    # Documentation summary emoji
    output_content = output_content.replace(" 🐍 🛠️", '')
    output_content = output_content.replace('🐍', '')
    output_content = output_content.replace('🛠', '')
    output_content = output_content.replace('️', '')  # Variation Selector-16

    output_content = output_content.replace(
        '≈', r" $\approx$ ")  # coming in sphinx-toolbox 2.12
    output_content = output_content.replace(
        'μ', r"\textmu ")  # fixed in sphinx-toolbox 2.12
    output_content = output_content.replace(
        r"\textmum", r"\textmu m")  # fixed in sphinx-toolbox 2.12
    output_content = output_content.replace(
        '\u205f', r"\medspace ")  # medium mathematical space

    # in words.py
    output_content = output_content.replace(r'A\sphinxhyphen{}Ω',
                                            r"A\sphinxhyphen{}\textOmega")
    output_content = output_content.replace(
        r'α\sphinxhyphen{}ϖ', r"\textalpha\sphinxhyphen{}\textomega")

    output_file.write_clean(output_content)
コード例 #5
0
ファイル: ci_cd.py プロジェクト: repo-helper/repo_helper
def make_github_docs_test(repo_path: pathlib.Path,
                          templates: Environment) -> List[str]:
    """
	Add configuration for GitHub Actions documentation check to the desired repo.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    file = PathPlus(repo_path / ".github" / "workflows" /
                    "docs_test_action.yml")
    file.parent.maybe_make(parents=True)

    if templates.globals["enable_docs"]:

        if templates.globals["docs_fail_on_warning"]:
            build_command = "tox -e docs -- -W "
        else:
            build_command = "tox -e docs -- "

        file.write_clean(
            templates.get_template(
                file.name).render(build_command=build_command))

    else:
        file.unlink(missing_ok=True)

    return [file.relative_to(repo_path).as_posix()]
コード例 #6
0
ファイル: ci_cd.py プロジェクト: repo-helper/repo_helper
def make_actions_deploy_conda(repo_path: pathlib.Path,
                              templates: Environment) -> List[str]:
    """
	Add script to build Conda package and deploy to Anaconda.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    old_deploy_file = PathPlus(repo_path / ".ci" / "actions_deploy_conda.sh")
    old_build_file = PathPlus(repo_path / ".ci" / "actions_build_conda.sh")
    old_deploy_file.unlink(missing_ok=True)
    old_build_file.unlink(missing_ok=True)

    deploy_file = PathPlus(repo_path / ".github" / "actions_deploy_conda.sh")
    build_file = PathPlus(repo_path / ".github" / "actions_build_conda.sh")
    deploy_file.parent.maybe_make()

    build_file.write_clean(templates.get_template(build_file.name).render())
    build_file.make_executable()
    deploy_file.write_clean(templates.get_template(deploy_file.name).render())
    deploy_file.make_executable()

    return [
        build_file.relative_to(repo_path).as_posix(),
        old_build_file.relative_to(repo_path).as_posix(),
        deploy_file.relative_to(repo_path).as_posix(),
        old_deploy_file.relative_to(repo_path).as_posix(),
    ]
コード例 #7
0
def rewrite_readme(repo_path: pathlib.Path,
                   templates: Environment) -> List[str]:
    """
	Update blocks in the ``README.rst`` file.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    # TODO: link to documentation below installation

    readme_file = PathPlus(repo_path / "README.rst")

    shields_block = ShieldsBlock(
        username=templates.globals["username"],
        repo_name=templates.globals["repo_name"],
        version=templates.globals["version"],
        conda=templates.globals["enable_conda"],
        tests=templates.globals["enable_tests"]
        and not templates.globals["stubs_package"],
        docs=templates.globals["enable_docs"],
        pypi_name=templates.globals["pypi_name"],
        docker_shields=templates.globals["docker_shields"],
        docker_name=templates.globals["docker_name"],
        platforms=templates.globals["platforms"],
        pre_commit=templates.globals["enable_pre_commit"],
        on_pypi=templates.globals["on_pypi"],
        docs_url=templates.globals["docs_url"],
        primary_conda_channel=templates.globals["primary_conda_channel"],
    ).make()

    if templates.globals["on_pypi"]:
        install_block = create_readme_install_block(
            templates.globals["modname"],
            templates.globals["username"],
            templates.globals["enable_conda"],
            templates.globals["on_pypi"],
            templates.globals["pypi_name"],
            templates.globals["conda_channels"],
        )
    else:
        install_block = get_readme_installation_block_no_pypi_template(
        ).render(
            modname=templates.globals["modname"],
            username=templates.globals["username"],
            repo_name=templates.globals["repo_name"],
        )

    readme = readme_file.read_text(encoding="UTF-8")
    readme = shields_regex.sub(str(shields_block), readme)
    readme = installation_regex.sub(install_block + '\n', readme)
    short_desc_block = create_short_desc_block(
        templates.globals["short_desc"], )
    readme = short_desc_regex.sub(short_desc_block, readme)

    readme_file.write_clean(readme)

    return [readme_file.name]
コード例 #8
0
def replace_unknown_unicode(app: Sphinx,
                            exception: Optional[Exception] = None):
    r"""
	Replaces certain unknown unicode characters in the Sphinx LaTeX output with the best equivalents.

	.. only:: html

		The mapping is as follows:

		* ♠ -- \spadesuit
		* ♥ -- \heartsuit
		* ♦ -- \diamondsuit
		* ♣ -- \clubsuit
		* Zero width space -- \hspace{0pt}
		* μ -- \textmu
		* ≡ -- \equiv (new in version 2.11.0)
		* ≈ -- \approx (new in version 2.12.0)
		* ≥ -- \geq (new in version 2.13.0)
		* ≤ -- \leq (new in version 2.13.0)

	This function can be hooked into the :event:`build-finished` event as follows:

	.. code-block:: python

		app.connect("build-finished", replace_unknown_unicode)

	.. versionadded:: 2.9.0

	:param app: The Sphinx application.
	:param exception: Any exception which occurred and caused Sphinx to abort.
	"""

    if exception:  # pragma: no cover
        return

    if app.builder is None or app.builder.name.lower() != "latex":
        return

    builder = cast(LaTeXBuilder, app.builder)
    output_file = PathPlus(
        builder.outdir) / f"{builder.titles[0][1].lower()}.tex"

    output_content = output_file.read_text()

    output_content = output_content.replace('♠', r' $\spadesuit$ ')
    output_content = output_content.replace('♥', r' $\heartsuit$ ')
    output_content = output_content.replace('♦', r' $\diamondsuit$ ')
    output_content = output_content.replace('♣', r' $\clubsuit$ ')
    output_content = output_content.replace(
        '\u200b', r'\hspace{0pt}')  # Zero width space
    output_content = output_content.replace('μ', r"\textmu{}")
    output_content = output_content.replace('≡', r" $\equiv$ ")
    output_content = output_content.replace('≈', r" $\approx$ ")
    output_content = output_content.replace('≥', r" $\geq$ ")
    output_content = output_content.replace('≤', r" $\leq$ ")

    output_file.write_clean(output_content)
コード例 #9
0
def replace_geq(app: Sphinx, exception: Optional[Exception] = None):
    if exception:
        return

    if app.builder.name.lower() != "latex":
        return

    output_file = PathPlus(
        app.builder.outdir) / f"{app.builder.titles[0][1]}.tex"
    output_content = output_file.read_text()
    output_content = output_content.replace('≥', r" $\geq$ ")
    output_file.write_clean(output_content)
コード例 #10
0
ファイル: linting.py プロジェクト: repo-helper/repo_helper
def make_pylintrc(repo_path: pathlib.Path,
                  templates: Environment) -> List[str]:
    """
	Copy ``.pylintrc`` into the desired repository.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    file = PathPlus(repo_path / ".pylintrc")
    file.write_clean(PathPlus(template_dir / "pylintrc").read_text())
    return [file.name]
コード例 #11
0
ファイル: testing.py プロジェクト: repo-helper/repo_helper
def make_yapf(repo_path: pathlib.Path, templates: Environment) -> List[str]:
	"""
	Add configuration for ``yapf``.

	https://github.com/google/yapf

	:param repo_path: Path to the repository root.
	:param templates:
	"""

	file = PathPlus(repo_path) / ".style.yapf"
	file.write_clean(templates.get_template("style.yapf").render())
	return [file.name]
コード例 #12
0
def replace_unicode(app, exception):
    if exception:
        return

    if app.builder.name.lower() != "latex":
        return

    output_file = PathPlus(
        app.builder.outdir) / f"{app.builder.titles[0][1]}.tex"

    output_content = output_file.read_text()
    output_content = output_content.replace('➞', r" $\rightarrow$ ")
    output_file.write_clean(output_content)
コード例 #13
0
def make_stale_bot(repo_path: pathlib.Path, templates: Environment) -> List[str]:
	"""
	Add configuration for ``stale`` to the desired repo.

	https://probot.github.io/apps/stale/

	:param repo_path: Path to the repository root.
	:param templates:
	"""

	stale_file = PathPlus(repo_path) / ".github" / "stale.yml"
	stale_file.parent.maybe_make()
	stale_file.write_clean(templates.get_template("stale_bot.yaml").render())
	return [stale_file.relative_to(repo_path).as_posix()]
コード例 #14
0
ファイル: old.py プロジェクト: repo-helper/repo_helper
def make_lint_roller(repo_path: pathlib.Path,
                     templates: Environment) -> List[str]:
    """
	Add the lint_roller.sh script to the desired repo.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    lint_roller = templates.get_template("lint_roller._sh")
    lint_file = PathPlus(repo_path / "lint_roller.sh")

    lint_file.write_clean(lint_roller.render())
    lint_file.make_executable()

    return [lint_file.name]
コード例 #15
0
def make_setup(repo_path: pathlib.Path, templates: Environment) -> List[str]:
    """
	Update the ``setup.py`` script.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    setup_file = PathPlus(repo_path / "setup.py")

    if templates.globals["use_whey"]:
        setup_file.unlink(missing_ok=True)

    else:
        setup = templates.get_template("setup._py")

        data = dict(
            extras_require="extras_require",
            install_requires="install_requires",
            description=repr(templates.globals["short_desc"]),
            py_modules=templates.globals["py_modules"],
            name=f"{normalize(templates.globals['modname'])!r}",
        )
        # TODO: remove name once GitHub dependency graph fixed

        if templates.globals["desktopfile"]:
            data[
                "data_files"] = "[('share/applications', ['{modname}.desktop'])]".format_map(
                    templates.globals)

        setup_args = sorted({
            **data,
            **templates.globals["additional_setup_args"]
        }.items())

        setup_file.write_clean(
            setup.render(additional_setup_args='\n'.join(
                f"\t\t{k}={v}," for k, v in setup_args)))

        with resource(repo_helper.files, "isort.cfg") as isort_config:
            yapf_style = PathPlus(
                isort_config).parent.parent / "templates" / "style.yapf"
            reformat_file(setup_file,
                          yapf_style=str(yapf_style),
                          isort_config_file=str(isort_config))

    return [setup_file.name]
コード例 #16
0
def make_contributing(repo_path: pathlib.Path, templates: Environment) -> List[str]:
	"""
	Add ``CONTRIBUTING.rst`` to the desired repo.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

	file = PathPlus(repo_path / "CONTRIBUTING.rst")
	old_file = repo_path / "CONTRIBUTING.md"

	file.write_clean(templates.get_template(file.name).render(bash_block=github_bash_block))

	if old_file.is_file():
		old_file.unlink()

	return [file.name, old_file.name]
コード例 #17
0
def replace_environment_variables_header(app: Sphinx, exception: Optional[Exception] = None):
	if exception:
		return

	if app.builder.name.lower() != "latex":
		return

	output_file = PathPlus(app.builder.outdir) / f"{app.builder.titles[0][1]}.tex"

	output_content = output_file.read_text()

	output_content = output_content.replace(
			r"\subsubsection*{Environment variables}",
			r"\vspace{20px}{\textcolor{TitleColor}{\sffamily\bfseries Environment variables}}",
			)

	output_file.write_clean(output_content)
コード例 #18
0
ファイル: ci_cd.py プロジェクト: repo-helper/repo_helper
def make_github_octocheese(repo_path: pathlib.Path,
                           templates: Environment) -> List[str]:
    """
	Add configuration for the OctoCheese GitHub Action.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    file = PathPlus(repo_path / ".github" / "workflows" / "octocheese.yml")
    file.parent.maybe_make(parents=True)

    if templates.globals["on_pypi"]:
        file.write_clean(templates.get_template(file.name).render())
    elif file.is_file():
        file.unlink()

    return [file.relative_to(repo_path).as_posix()]
コード例 #19
0
def replace_latex(app: Sphinx, exception: Optional[Exception] = None):
	if exception:
		return

	if app.builder.name.lower() != "latex":
		return

	output_file = PathPlus(app.builder.outdir) / f"{app.builder.titles[0][1]}.tex"

	output_content = output_file.read_text()

	output_content = output_content.replace('≡', r"$\equiv$")
	output_content = output_content.replace(
			r"@\spxentry{verify}\spxextra{SlumberURL attribute}}\needspace{5\baselineskip}",
			r"@\spxentry{verify}\spxextra{SlumberURL attribute}}",
			)

	output_file.write_clean(output_content)
コード例 #20
0
def make_manifest(repo_path: pathlib.Path,
                  templates: Environment) -> List[str]:
    """
	Update the ``MANIFEST.in`` file for ``setuptools``.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    file = PathPlus(repo_path / "MANIFEST.in")

    if templates.globals["use_whey"]:
        file.unlink(missing_ok=True)

    else:
        manifest_entries = [
            "include LICENSE",
            "include requirements.txt",
            "prune **/__pycache__",
            *templates.globals["manifest_additional"],
        ]

        if templates.globals["extras_require"]:
            manifest_entries.insert(0, "include __pkginfo__.py")

        for item in templates.globals["additional_requirements_files"]:
            manifest_entries.append(f"include {pathlib.PurePosixPath(item)}")

        if templates.globals["stubs_package"]:
            import_name = f"{templates.globals['import_name']}-stubs"
        else:
            import_name = templates.globals["import_name"].replace('.', '/')

        pkg_dir = pathlib.PurePosixPath(
            templates.globals["source_dir"]) / import_name

        manifest_entries.extend([
            f"recursive-include {pkg_dir} *.pyi",
            f"include {pkg_dir / 'py.typed'}",
        ])

        file.write_clean('\n'.join(manifest_entries))

    return [file.name]
コード例 #21
0
def replace_emoji(app: Sphinx, exception: Optional[Exception] = None):
    if exception:
        return

    if app.builder.name.lower() != "latex":
        return

    output_file = PathPlus(
        app.builder.outdir) / f"{app.builder.titles[0][1]}.tex"

    output_content = output_file.read_text()

    output_content = output_content.replace('🧰', '')
    output_content = output_content.replace('📔', '')
    output_content = output_content.replace(
        r"\sphinxcode{\sphinxupquote{\textbackslash{}vspace\{\}}}",
        r"\mbox{\sphinxcode{\sphinxupquote{\textbackslash{}vspace\{\}}}}",
    )

    output_file.write_clean(output_content)
コード例 #22
0
def make_imgbot(repo_path: pathlib.Path, templates: Environment) -> List[str]:
	"""
	Add configuration for ``imgbot`` to the desired repo.

	https://imgbot.net/

	:param repo_path: Path to the repository root.
	:param templates:
	"""

	imgbot_file = PathPlus(repo_path / ".imgbotconfig")

	imgbot_config = {
			"schedule": "weekly",
			"ignoredFiles": ["**/*.svg"] + templates.globals["imgbot_ignore"],
			}

	imgbot_file.write_clean(json.dumps(imgbot_config, indent=4))

	return [imgbot_file.name]
コード例 #23
0
ファイル: ci_cd.py プロジェクト: repo-helper/repo_helper
def make_github_manylinux(repo_path: pathlib.Path,
                          templates: Environment) -> List[str]:
    """
	Add configuration for `GitHub Actions` manylinux wheel builds the desired repo.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    # TODO: deploys from other supported platforms for not pure python

    file = PathPlus(repo_path / ".github" / "workflows" /
                    "manylinux_build.yml")
    file.parent.maybe_make(parents=True)

    if not templates.globals["pure_python"] and "Linux" in templates.globals[
            "platforms"]:
        actions = templates.get_template(file.name)
        wheel_py_versions = []
        PYVERSIONS = []

        for pyver in range(6, 8):
            if f"3.{pyver}" in templates.globals["python_versions"]:
                wheel_py_versions.append(f"cp3{pyver}-cp3{pyver}m")
                PYVERSIONS.append(f'"3{pyver}"')

        for pyver in range(8, 10):
            if f"3.{pyver}" in templates.globals["python_versions"]:
                wheel_py_versions.append(f"cp3{pyver}-cp3{pyver}")
                PYVERSIONS.append(f'"3{pyver}"')

        file.write_clean(
            actions.render(
                wheel_py_versions=wheel_py_versions,
                PYVERSIONS=' '.join(PYVERSIONS),
            ))
    elif file.is_file():
        file.unlink()

    return [file.relative_to(repo_path).as_posix()]
コード例 #24
0
def make_docs_contributing(repo_path: pathlib.Path, templates: Environment) -> List[str]:
	"""
	Add CONTRIBUTING.rst to the documentation directory of the repo.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

	file = PathPlus(repo_path / templates.globals["docs_dir"] / "contributing.rst")
	file.parent.maybe_make(parents=True)

	contributing = templates.get_template("CONTRIBUTING.rst")

	if templates.globals["standalone_contrib_guide"]:
		file.write_clean(contributing.render(bash_block=sphinx_bash_block))

	else:
		file.write_lines([
				"Overview",
				"---------",
				*contributing.render(bash_block=sphinx_bash_block).splitlines()[3:],
				])

	return [file.relative_to(repo_path).as_posix()]
コード例 #25
0
ファイル: ci_cd.py プロジェクト: repo-helper/repo_helper
def ensure_bumpversion(repo_path: pathlib.Path,
                       templates: Environment) -> List[str]:
    """
	Add configuration for ``bumpversion`` to the desired repo.

	https://pypi.org/project/bumpversion/

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    bumpversion_file = PathPlus(repo_path / ".bumpversion.cfg")

    if not bumpversion_file.is_file():
        bumpversion_file.write_lines([
            "[bumpversion]",
            f"current_version = {templates.globals['version']}",
            "commit = True",
            "tag = True",
        ])

    bv = ConfigUpdater()
    bv.read(str(bumpversion_file))

    old_sections = [
        "bumpversion:file:git_helper.yml", "bumpversion:file:__pkginfo__.py"
    ]
    required_sections = {
        f"bumpversion:file:{filename}"
        for filename in get_bumpversion_filenames(templates)
    }

    if not templates.globals["enable_docs"]:
        old_sections.append(
            f"bumpversion:file:{templates.globals['docs_dir']}/index.rst")

    if not templates.globals["enable_conda"]:
        old_sections.append(f"bumpversion:file:.github/workflows/conda_ci.yml")

    if templates.globals["use_whey"]:
        old_sections.append("bumpversion:file:setup.cfg")

    for section in old_sections:
        if section in bv.sections():
            bv.remove_section(section)
        if section in required_sections:
            required_sections.remove(section)

    for section in sorted(required_sections):
        if section not in bv.sections():
            bv.add_section(section)

    init_filename = get_init_filename(templates)
    if init_filename is not None:
        init_section = bv[f"bumpversion:file:{init_filename}"]
        if "search" not in init_section:
            init_section["search"] = ': str = "{current_version}"'
            init_section["replace"] = ': str = "{new_version}"'

    if "bumpversion:file:setup.cfg" in bv.sections():
        setup_cfg_section = bv["bumpversion:file:setup.cfg"]
        if ("search" not in setup_cfg_section or
            ("search" in setup_cfg_section and
             setup_cfg_section["search"].value == "name = {current_version}")):
            setup_cfg_section["search"] = "version = {current_version}"
            setup_cfg_section["replace"] = "version = {new_version}"

    if "bumpversion:file:pyproject.toml" in bv.sections():
        pp_toml_section = bv["bumpversion:file:pyproject.toml"]
        if "search" not in pp_toml_section:
            pp_toml_section["search"] = 'version = "{current_version}"'
            pp_toml_section["replace"] = 'version = "{new_version}"'

    bv["bumpversion"]["current_version"] = templates.globals["version"]
    bv["bumpversion"]["commit"] = "True"
    bv["bumpversion"]["tag"] = "True"

    bumpversion_file.write_clean(str(bv))

    return [bumpversion_file.name]
コード例 #26
0
ファイル: docs.py プロジェクト: repo-helper/repo_helper
def rewrite_docs_index(repo_path: pathlib.Path,
                       templates: Environment) -> List[str]:
    """
	Update blocks in the documentation ``index.rst`` file.

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    index_rst_file = PathPlus(repo_path / templates.globals["docs_dir"] /
                              "index.rst")
    index_rst_file.parent.maybe_make()

    # Set up the blocks
    sb = ShieldsBlock(
        username=templates.globals["username"],
        repo_name=templates.globals["repo_name"],
        version=templates.globals["version"],
        conda=templates.globals["enable_conda"],
        tests=templates.globals["enable_tests"]
        and not templates.globals["stubs_package"],
        docs=templates.globals["enable_docs"],
        pypi_name=templates.globals["pypi_name"],
        docker_shields=templates.globals["docker_shields"],
        docker_name=templates.globals["docker_name"],
        platforms=templates.globals["platforms"],
        pre_commit=templates.globals["enable_pre_commit"],
        on_pypi=templates.globals["on_pypi"],
        primary_conda_channel=templates.globals["primary_conda_channel"],
    )

    sb.set_docs_mode()
    make_out = sb.make()

    shield_block_list = StringList([*make_out[0:2], ".. only:: html"])

    with shield_block_list.with_indent_size(1):
        shield_block_list.extend(make_out[1:-1])

    shield_block_list.append(make_out[-1])

    shields_block = str(shield_block_list)

    if templates.globals["license"] == "GNU General Public License v2 (GPLv2)":
        source = f"https://img.shields.io/github/license/{templates.globals['username']}/{templates.globals['repo_name']}"
        shields_block.replace(
            source, "https://img.shields.io/badge/license-GPLv2-orange")

    # .. image:: https://img.shields.io/badge/License-LGPL%20v3-blue.svg

    install_block = create_docs_install_block(
        templates.globals["repo_name"],
        templates.globals["username"],
        templates.globals["enable_conda"],
        templates.globals["on_pypi"],
        templates.globals["pypi_name"],
        templates.globals["conda_channels"],
    ) + '\n'

    links_block = create_docs_links_block(
        templates.globals["username"],
        templates.globals["repo_name"],
    )

    # Do the replacement
    index_rst = index_rst_file.read_text(encoding="UTF-8")
    index_rst = shields_regex.sub(shields_block, index_rst)
    index_rst = installation_regex.sub(install_block, index_rst)
    index_rst = links_regex.sub(links_block, index_rst)
    index_rst = short_desc_regex.sub(
        ".. start short_desc\n\n.. documentation-summary::\n\t:meta:\n\n.. end short_desc",
        index_rst,
    )

    if ":caption: Links" not in index_rst and not templates.globals[
            "preserve_custom_theme"]:
        index_rst = index_rst.replace(
            ".. start links", '\n'.join([
                ".. sidebar-links::",
                "\t:caption: Links",
                "\t:github:",
                (f"	:pypi: {templates.globals['pypi_name']}"
                 if templates.globals["on_pypi"] else ''),
                '',
                '',
                ".. start links",
            ]))

    index_rst_file.write_clean(index_rst)

    return [index_rst_file.relative_to(repo_path).as_posix()]
コード例 #27
0
ファイル: docs.py プロジェクト: repo-helper/repo_helper
def make_conf(repo_path: pathlib.Path, templates: Environment) -> List[str]:
    """
	Add ``conf.py`` configuration file for ``Sphinx``.

	https://www.sphinx-doc.org/en/master/index.html

	:param repo_path: Path to the repository root.
	:param templates:
	"""

    conf = templates.get_template("conf._py")
    file = PathPlus(repo_path / templates.globals["docs_dir"] / "conf.py")
    file.parent.maybe_make(parents=True)

    username = templates.globals["username"]
    repo_name = templates.globals["repo_name"]

    if templates.globals["sphinx_html_theme"] in {
            "sphinx-rtd-theme", "domdf-sphinx-theme"
    }:
        style = {
            "display_github": True,  # Integrate GitHub
            "github_user": username,  # Username
            "github_repo": repo_name,  # Repo name
            "github_version": "master",  # Version
            "conf_py_path":
            f"/{templates.globals['docs_dir']}/",  # Path in the checkout to the docs root
        }

        for key, val in style.items():
            if key not in templates.globals["html_context"]:
                templates.globals["html_context"][key] = val

        options = {
            # 'logo': 'logo.png',
            "logo_only": False,  # True will show just the logo
        }

        for key, val in options.items():
            if key not in templates.globals["html_theme_options"]:
                templates.globals["html_theme_options"][key] = val

    elif templates.globals["sphinx_html_theme"] in {
            "alabaster", "repo-helper-sphinx-theme"
    }:
        # See https://github.com/bitprophet/alabaster/blob/master/alabaster/theme.conf
        # and https://alabaster.readthedocs.io/en/latest/customization.html

        style = {
            # 'logo': 'logo.png',
            "page_width": "1200px",
            "logo_name": "true",
            "github_user": username,  # Username
            "github_repo": repo_name,  # Repo name
            "description": templates.globals["short_desc"],
            "github_banner": "true",
            "github_type": "star",
            "badge_branch": "master",
            "fixed_sidebar": "true",
        }

        for key, val in style.items():
            if key not in templates.globals["html_theme_options"]:
                templates.globals["html_theme_options"][key] = val

    elif templates.globals["sphinx_html_theme"] in {"furo"}:
        # See https://github.com/bitprophet/alabaster/blob/master/alabaster/theme.conf
        # and https://alabaster.readthedocs.io/en/latest/customization.html

        style = {
            "toc-title-font-size": "12pt",
            "toc-font-size": "12pt",
            "admonition-font-size": "12pt",
        }

        for key in ["light_css_variables", "dark_css_variables"]:
            if key not in templates.globals["html_theme_options"]:
                templates.globals["html_theme_options"][key] = style
            else:
                templates.globals["html_theme_options"][key] = {
                    **style,
                    **templates.globals["html_theme_options"][key],
                }

    file.write_clean(
        conf.render(pformat=pformat_tabs, enquote_value=enquote_value))

    with resource(repo_helper.files, "isort.cfg") as isort_config:
        yapf_style = PathPlus(
            isort_config).parent.parent / "templates" / "style.yapf"
        reformat_file(file,
                      yapf_style=str(yapf_style),
                      isort_config_file=str(isort_config))

    return [file.relative_to(repo_path).as_posix()]