Exemple #1
0
def test_unlink(BASE):
    p = PathPlus(BASE) / "fileA"
    p.unlink()
    with pytest.raises(FileNotFoundError):
        p.stat()
    with pytest.raises(FileNotFoundError):
        p.unlink()
Exemple #2
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]
Exemple #3
0
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(),
    ]
Exemple #4
0
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()]
Exemple #5
0
def test_rmdir(BASE):
    p = PathPlus(BASE) / "dirA"
    for q in p.iterdir():
        q.unlink()
    p.rmdir()
    with pytest.raises(FileNotFoundError):
        p.stat()
    with pytest.raises(FileNotFoundError):
        p.unlink()
Exemple #6
0
def remove_make_conda_recipe(repo_path: pathlib.Path,
                             templates: Environment) -> List[str]:
    """
	Remove the old script to create a Conda recipe.

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

    file = PathPlus(repo_path / "make_conda_recipe.py")
    file.unlink(missing_ok=True)
    return [file.name]
Exemple #7
0
def remove_lint_roller(repo_path: pathlib.Path,
                       templates: Environment) -> List[str]:
    """
	Remove the old lint_roller.sh script to the desired repo.

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

    lint_file = PathPlus(repo_path / "lint_roller.sh")
    if lint_file.is_file():
        lint_file.unlink()

    return [lint_file.name]
Exemple #8
0
def make_isort(repo_path: pathlib.Path, templates: Environment) -> List[str]:
	"""
	Remove the ``isort`` configuration file.

	https://github.com/timothycrosley/isort

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

	isort_file = PathPlus(repo_path / ".isort.cfg")
	isort_file.unlink(missing_ok=True)
	assert not isort_file.is_file()
	return [isort_file.name]
Exemple #9
0
def travis_bad(repo_path: pathlib.Path, templates: Environment) -> List[str]:
    """
	Removes Travis CI configuration.

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

    if PathPlus(repo_path / ".travis.yml").is_file():
        PathPlus(repo_path / ".travis.yml").unlink()

    conda_file = PathPlus(repo_path / ".ci" / "travis_deploy_conda.sh")
    if conda_file.is_file():
        conda_file.unlink()

    return [".travis.yml", conda_file.relative_to(repo_path).as_posix()]
Exemple #10
0
def remove_autodoc_augment_defaults(repo_path: pathlib.Path,
                                    templates: Environment) -> List[str]:
    """
	Remove the redundant "autodoc_augment_defaults" extension.

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

    target_file = PathPlus(repo_path / templates.globals["docs_dir"] /
                           "autodoc_augment_defaults.py")

    if target_file.is_file():
        target_file.unlink()

    return [target_file.relative_to(repo_path).as_posix()]
Exemple #11
0
def remove_copy_pypi_2_github(repo_path: pathlib.Path,
                              templates: Environment) -> List[str]:
    """
	Remove deprecated copy_pypi_2_github.py script.

	Uue octocheese and its GitHub Action instead.

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

    copier = PathPlus(repo_path / ".ci" / "copy_pypi_2_github.py")
    if copier.is_file():
        copier.unlink()

    return [copier.relative_to(repo_path).as_posix()]
Exemple #12
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]
Exemple #13
0
    def write_out(self):
        """
		Write out to the ``.ini`` file.
		"""

        ini_file = PathPlus(self.base_path / self.filename)

        for section_name in self.managed_sections:
            getattr(self, re.sub("[:.-]", '_', section_name))()

        self.merge_existing(ini_file)

        if not self._ini.sections():
            ini_file.unlink(missing_ok=True)
        else:
            self._output.append(str(self._ini))
            ini_file.write_lines(self._output)
Exemple #14
0
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()]
Exemple #15
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]
Exemple #16
0
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()]
Exemple #17
0
def make_formate_toml(repo_path: pathlib.Path, templates: Environment) -> List[str]:
	"""
	Add configuration for ``formate``.

	https://formate.readthedocs.io

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

	known_third_party = set()

	isort_file = PathPlus(repo_path / ".isort.cfg")
	formate_file = PathPlus(repo_path / "formate.toml")

	isort_config = get_isort_config(repo_path, templates)
	known_third_party.update(isort_config["known_third_party"])

	if formate_file.is_file():
		formate_config = dom_toml.load(formate_file)
	else:
		formate_config = {}

	# Read the isort config file and get "known_third_party" from there
	if isort_file.is_file():
		isort = ConfigUpdater()
		isort.read(str(isort_file))

		if "settings" in isort.sections() and "known_third_party" in isort["settings"]:
			known_third_party.update(re.split(r"(\n|,\s*)", isort["settings"]["known_third_party"].value))

	isort_file.unlink(missing_ok=True)

	if "hooks" in formate_config and "isort" in formate_config["hooks"]:
		if "kwargs" in formate_config["hooks"]["isort"]:
			known_third_party.update(formate_config["hooks"]["isort"]["kwargs"].get("known_third_party", ()))

			for existing_key, value in formate_config["hooks"]["isort"]["kwargs"].items():
				if existing_key not in isort_config:
					isort_config[existing_key] = value

	def normalise_underscore(name: str) -> str:
		return normalize(name.strip()).replace('-', '_')

	isort_config["known_third_party"] = sorted(set(filter(bool, map(normalise_underscore, known_third_party))))

	hooks = {
			"dynamic_quotes": 10,
			"collections-import-rewrite": 20,
			"yapf": {"priority": 30, "kwargs": {"yapf_style": ".style.yapf"}},
			"reformat-generics": 40,
			"isort": {"priority": 50, "kwargs": isort_config},
			"noqa-reformat": 60,
			"ellipsis-reformat": 70,
			"squish_stubs": 80,
			}

	config = {"indent": '\t', "line_length": 115}

	formate_config["hooks"] = hooks
	formate_config["config"] = config

	formate_file = PathPlus(repo_path / "formate.toml")
	dom_toml.dump(formate_config, formate_file, encoder=dom_toml.TomlEncoder)

	return [formate_file.name, isort_file.name]
Exemple #18
0
 def test_append_pathplus(self):
     file = PathPlus("paths_append_test_file.txt")
     file.write_text("initial content\n")
     file.append_text("appended content")
     assert file.read_text() == "initial content\nappended content"
     file.unlink()
Exemple #19
0
def test_unlink_missing_ok(BASE):
    p = PathPlus(BASE) / "fileAAA"
    with pytest.raises(FileNotFoundError):
        p.unlink()
    p.unlink(missing_ok=True)