Skip to content

Commit

Permalink
Switch to pyproject and ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
Frank Odom committed Jul 19, 2023
1 parent 9125bf2 commit 0fa8b93
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 52 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# {{REPO_NAME}}


## Install

```bash
Expand Down
49 changes: 49 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
[tool.black]
line-length = 88

[tool.mypy]
files = "{{REPO_NAME_SNAKECASE}}/"
check_untyped_defs = "true"
ignore_missing_imports = "true"

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "--cov --cov-report term-missing --cov-fail-under 80"
filterwarnings = "ignore:.*.:DeprecationWarning"

[tool.ruff]
ignore = ["B905", "E501"]
line-length = 88
select = [
"B",
"C",
"E",
"F",
"I",
"W"
]
# Exclude a variety of commonly ignored directories.
exclude = [
".bzr",
".direnv",
".eggs",
".git",
".hg",
".mypy_cache",
".nox",
".pants.d",
".ruff_cache",
".svn",
".tox",
".venv",
"__pypackages__",
"_build",
"buck-out",
"build",
"dist",
"node_modules",
"venv",
]

[tool.ruff.mccabe]
max-complexity = 18
14 changes: 0 additions & 14 deletions setup.cfg

This file was deleted.

4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def get_version_tag() -> str:
return version


extras_require = {"test": ["black", "flake8", "isort", "mypy", "pytest", "pytest-cov"]}
extras_require = {"test": ["black", "ruff", "mypy", "pytest", "pytest-cov"]}
extras_require["dev"] = ["pre-commit", *extras_require["test"]]
all_require = [r for reqs in extras_require.values() for r in reqs]
extras_require["all"] = all_require
Expand All @@ -40,5 +40,5 @@ def get_version_tag() -> str:
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
],
python_requires=">=3.7",
python_requires=">=3.8",
)
80 changes: 44 additions & 36 deletions templatize
Original file line number Diff line number Diff line change
@@ -1,73 +1,81 @@
#!/usr/bin/env python3

import subprocess
import shutil
from pathlib import Path
from typing import Dict, List, Optional, Union
from subprocess import getoutput
from typing import Dict, List, Sequence, Tuple, Union

THIS_FILE = Path(__file__).expanduser().absolute()
REPO_DIR = THIS_FILE.parent


def get_git_info(key: str, repo_path: Path) -> str:
cmd = ["git", "config", key]
output = subprocess.run(cmd, capture_output=True, check=True, cwd=repo_path)
return output.stdout.decode().strip()
def get_git_info(key: str) -> str:
return getoutput(f"git config {key}").strip()


def get_repo_owner_and_name() -> Tuple[str, str]:
owner, name = (
get_git_info("remote.origin.url")
.removeprefix("https://github.com/")
.removeprefix("git@github.com:")
.removesuffix(".git")
.split("/", maxsplit=1)
)
return owner, name


def recursive_get_files(
root_dir: Union[Path, str], excepted_files: Optional[List[str]] = None
root_dir: Union[Path, str], excepted_files: Sequence[Union[str, Path]] = ()
) -> List[Path]:
if isinstance(root_dir, str):
root_dir = Path(root_dir)
if excepted_files is None:
excepted_files = []
return [x for x in root_dir.glob("**/*") if x not in excepted_files and x.is_file()]


REPO_OWNER, REPO_NAME = get_repo_owner_and_name()
PLACEHOLDERS = {
"{{REPO_NAME}}": REPO_DIR.name,
"{{REPO_NAME_ALLCAPS}}": REPO_DIR.name.upper().replace("-", "_"),
"{{GIT_USER_NAME}}": get_git_info("user.name", REPO_DIR),
"{{GIT_USER_EMAIL}}": get_git_info("user.email", REPO_DIR),
"{{REPO_OWNER}}": get_git_info("remote.origin.url", REPO_DIR)
.replace("https://github.com/", "")
.replace("git@github.com:", "")
.split("/")[0],
"{{REPO_NAME}}": REPO_NAME,
"{{REPO_OWNER}}": REPO_OWNER,
"{{REPO_NAME_SNAKECASE}}": REPO_NAME.replace("-", "_"),
"{{REPO_NAME_ALLCAPS}}": REPO_NAME.upper().replace("-", "_"),
"{{GIT_USER_NAME}}": get_git_info("user.name"),
"{{GIT_USER_EMAIL}}": get_git_info("user.email"),
}

EXCEPTED_FILES = [THIS_FILE] + recursive_get_files(REPO_DIR / ".git")

def substitute_placeholders(path: Union[str, Path], placeholder_map: Dict[str, str]):
# Replace placeholders in file names
for placeholder, value in placeholder_map.items():
if placeholder in str(path):
dest = Path(str(path).replace(placeholder, value))
dest.parent.mkdir(exist_ok=True)
path = shutil.move(path, dest)

def substitute_placeholders(
filename: Union[str, Path], placeholder_map: Dict[str, str]
):
if isinstance(filename, str):
filename = Path(filename)
# Attempt to read *text* contents from file
try:
with filename.open("r") as fh:
content = fh.read()
with open(path, "r") as f:
content = f.read()
except UnicodeDecodeError:
# file is binary
return
changed = False

# Replace placeholders in file contents
for placeholder, value in placeholder_map.items():
if placeholder in content:
content = content.replace(placeholder, value)
changed = True
if changed:
with filename.open("w") as fh:
fh.write(content)


def cleanup():
THIS_FILE.unlink()
# Write modified contents back to file
with open(path, "w") as f:
f.write(content)


def main():
files = recursive_get_files(REPO_DIR, EXCEPTED_FILES)
for filename in files:
git_files = recursive_get_files(REPO_DIR / ".git")
for filename in recursive_get_files(REPO_DIR, excepted_files=git_files):
substitute_placeholders(filename, placeholder_map=PLACEHOLDERS)
cleanup()

THIS_FILE.unlink()
Path("{{REPO_NAME_SNAKECASE}}").rmdir()


if __name__ == "__main__":
Expand Down
Empty file.

0 comments on commit 0fa8b93

Please sign in to comment.