Repository navigation
Expand file tree
/
Copy pathinit_project.py
More file actions
208 lines (186 loc) · 6.43 KB
/
Copy pathinit_project.py
File metadata and controls
208 lines (186 loc) · 6.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import keyword
import re
import shutil
import subprocess
import sys
from pathlib import Path
_VALID_PROJECT_RE = re.compile(r"^[a-z][a-z0-9_-]*$")
_VALID_PACKAGE_RE = re.compile(r"^[a-z][a-z0-9_]*$")
_VALID_OWNER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$")
_SKIP_DIRS = frozenset(
{".git", ".venv", "__pycache__", ".mypy_cache", ".pytest_cache", ".ruff_cache", "dist"}
)
def _starter_readme(project_name: str, description: str, owner: str) -> str:
return (
f"# {project_name}\n\n"
f"{description}\n\n"
f"This repository is hosted on [Codeberg](https://codeberg.org/{owner}/{project_name}) "
f"and mirrored on [GitHub](https://github.com/{owner}/{project_name}).\n\n"
"## Features\n\n"
"- Feature one\n"
"- Feature two\n\n"
"## Usage\n\n"
"```sh\n"
f"uv tool install {project_name}\n"
"# or\n"
f"pip install {project_name}\n\n"
f"{project_name} --version\n"
"```\n\n"
"## Development\n\n"
"Requires Python 3.11+ and uv.\n\n"
"```sh\n"
"uv sync\n"
"uv run ruff format --check .\n"
"uv run ruff check .\n"
"uv run mypy src tests\n"
"uv run pytest\n"
"```\n\n"
"See [SECURITY.md](SECURITY.md) if you find a security issue.\n\n"
"## Licence\n\n"
"Source code is licensed under the [MIT License](LICENSE).\n"
)
def validate_package_name(name: str) -> str | None:
if not name.isascii() or not _VALID_PACKAGE_RE.match(name) or not name.isidentifier():
return (
f"Invalid Python package name {name!r}; use lowercase ASCII letters, digits, "
"and underscores starting with a letter."
)
if keyword.iskeyword(name) or keyword.issoftkeyword(name):
return f"Invalid Python package name {name!r}; cannot be a Python keyword."
return None
def _replace_in_tree(
root: Path,
*,
project_name: str,
package_name: str,
description: str,
owner: str,
author: str,
email: str,
) -> None:
for path in sorted(root.rglob("*")):
if not path.is_file():
continue
if any(part in _SKIP_DIRS for part in path.parts):
continue
if path.name in ("init_project.py", "test_init_project.py", "uv.lock", "README.md"):
continue
try:
text = path.read_text(encoding="utf-8")
except UnicodeDecodeError:
continue
updated = (
text.replace("Short description of my-package.", description)
.replace("my-package", project_name)
.replace("my_package", package_name)
)
if owner != "0jar":
updated = (
updated.replace("/0jar/", f"/{owner}/")
.replace("UV_PUBLISH_USERNAME: 0jar", f"UV_PUBLISH_USERNAME: {owner}")
.replace("owner: 0jar", f"owner: {owner}")
)
if author != "Jarema":
updated = updated.replace('name = "Jarema"', f'name = "{author}"').replace(
"Copyright (c) 2026 Jarema", f"Copyright (c) 2026 {author}"
)
if email != "git@jarema.me":
updated = updated.replace('email = "git@jarema.me"', f'email = "{email}"')
if updated != text:
path.write_text(updated, encoding="utf-8")
def main(argv: list[str] | None = None, *, root: Path | None = None) -> int:
parser = argparse.ArgumentParser(
description="Rename template placeholders and initialise a new Python project."
)
parser.add_argument(
"project_name",
help="Distribution and repository name (lowercase ASCII letters, digits, hyphens).",
)
parser.add_argument(
"-p",
"--package-name",
default=None,
help="Python import package name (defaults to project_name with '-' replaced by '_').",
)
parser.add_argument(
"-d",
"--description",
default=None,
help="One-line project description for pyproject.toml, README.md, and CLI help.",
)
parser.add_argument(
"--owner",
default="0jar",
help="Codeberg and GitHub repository owner (default: 0jar).",
)
parser.add_argument(
"--author",
default="Jarema",
help="Package author and LICENSE copyright holder (default: Jarema).",
)
parser.add_argument(
"--email",
default="git@jarema.me",
help="Package author email in pyproject.toml (default: git@jarema.me).",
)
parser.add_argument(
"--no-sync",
action="store_true",
help="Skip running 'uv lock' and 'uv sync' after renaming.",
)
parser.add_argument(
"--keep-script",
action="store_true",
help="Keep init_project.py and tests/test_init_project.py instead of deleting them.",
)
args = parser.parse_args(argv)
project_name: str = args.project_name.strip()
if not project_name.isascii() or not _VALID_PROJECT_RE.match(project_name):
print(
f"Error: Invalid project name {project_name!r}; use lowercase ASCII letters, digits, "
"hyphens or underscores starting with a letter.",
file=sys.stderr,
)
return 2
package_name: str = (args.package_name or project_name.replace("-", "_")).strip()
if pkg_err := validate_package_name(package_name):
print(f"Error: {pkg_err}", file=sys.stderr)
return 2
owner: str = args.owner.strip()
if not owner.isascii() or not _VALID_OWNER_RE.match(owner):
print(f"Error: Invalid repository owner {owner!r}.", file=sys.stderr)
return 2
description: str = args.description or f"Short description of {project_name}."
target_root = (root or Path(__file__).resolve().parent).resolve()
src_old = target_root / "src" / "my_package"
src_new = target_root / "src" / package_name
if src_old.is_dir() and src_old != src_new:
if src_new.exists():
print(f"Error: Target package directory already exists: {src_new}", file=sys.stderr)
return 2
src_old.rename(src_new)
_replace_in_tree(
target_root,
project_name=project_name,
package_name=package_name,
description=description,
owner=owner,
author=args.author.strip(),
email=args.email.strip(),
)
(target_root / "README.md").write_text(
_starter_readme(project_name, description, owner), encoding="utf-8"
)
if not args.no_sync and shutil.which("uv"):
subprocess.run(["uv", "lock"], cwd=target_root, check=True) # noqa: S603, S607
subprocess.run(["uv", "sync"], cwd=target_root, check=True) # noqa: S603, S607
if not args.keep_script:
(target_root / "init_project.py").unlink(missing_ok=True)
(target_root / "tests" / "test_init_project.py").unlink(missing_ok=True)
print(f"Initialised {project_name} (package: {package_name}) in {target_root}")
return 0
if __name__ == "__main__":
raise SystemExit(main())