-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.py
More file actions
398 lines (331 loc) · 13.4 KB
/
setup.py
File metadata and controls
398 lines (331 loc) · 13.4 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#!/usr/bin/env python3
# SPDX-FileCopyrightText: [year] Author Name <author@example.com>
#
# SPDX-License-Identifier: ISC
"""Interactive setup script for the Python package template."""
import json
import re
import shutil
import subprocess
import sys
import urllib.error
import urllib.request
from datetime import datetime
from pathlib import Path
SCRIPT_DIR = Path(__file__).parent.resolve()
def _require_uv() -> None:
if shutil.which("uv"):
return
print("UV is required to run this setup.", file=sys.stderr)
print("Install it from: https://docs.astral.sh/uv/getting-started/installation/", file=sys.stderr)
sys.exit(1)
def _install_rich() -> None:
result = subprocess.run(
["uv", "pip", "install", "-q", "rich"],
capture_output=True,
)
if result.returncode != 0:
print("Failed to install rich. Run this script with:", file=sys.stderr)
print(" uv run python setup.py", file=sys.stderr)
sys.exit(1)
def _uninstall_rich() -> None:
subprocess.run(
["uv", "pip", "uninstall", "-y", "rich"],
capture_output=True,
)
def validate_package_name(name: str) -> bool:
pattern = r"^[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)*$"
return bool(re.match(pattern, name))
def to_underscore(name: str) -> str:
return name.replace("-", "_")
def replace_in_file(filepath: Path, replacements: dict[str, str]) -> None:
content = filepath.read_text()
for old, new in replacements.items():
content = content.replace(old, new)
filepath.write_text(content)
def run_command(args: list[str], cwd: Path | None = None) -> tuple[bool, str]:
result = subprocess.run(args, cwd=cwd, capture_output=True, text=True)
output = result.stdout + result.stderr
return result.returncode == 0, output
def _git_config(key: str) -> str | None:
result = subprocess.run(
["git", "config", key], capture_output=True, text=True
)
value = result.stdout.strip()
return value if result.returncode == 0 and value else None
def _parse_github_remote() -> tuple[str | None, str | None]:
result = subprocess.run(
["git", "remote", "get-url", "origin"], capture_output=True, text=True
)
if result.returncode != 0:
return None, None
url = result.stdout.strip()
match = re.search(r"github\.com[:/]([^/]+)/([^/.]+)", url)
if not match:
return None, None
return match.group(1), match.group(2)
def _fetch_github_description(owner: str, repo: str) -> str | None:
url = f"https://api.github.com/repos/{owner}/{repo}"
req = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json"})
try:
with urllib.request.urlopen(req, timeout=5) as resp:
data = json.loads(resp.read())
desc = data["description"]
return desc if desc else None
except (urllib.error.URLError, OSError, json.JSONDecodeError, KeyError):
return None
def main() -> int: # pragma: no cover
_require_uv()
_install_rich()
# Imported after runtime installation (rich is not a project dependency)
from rich.console import Console # type: ignore[reportMissingImports]
from rich.prompt import Confirm, Prompt # type: ignore[reportMissingImports]
from rich.table import Table # type: ignore[reportMissingImports]
console = Console()
def print_header(text: str) -> None:
console.print()
console.rule(f"[bold]{text}[/bold]", style="cyan")
console.print()
def print_step(text: str) -> None:
console.print(f" [cyan]->[/cyan] {text}")
def print_success(text: str) -> None:
console.print(f" [green]\\[OK][/green] {text}")
def print_error(text: str) -> None:
console.print(f" [red]\\[ERROR][/red] {text}", stderr=True)
def ask_required(label: str) -> str:
while True:
value = Prompt.ask(f"[bold]{label}[/bold]").strip()
if value:
return value
console.print(" [yellow]This field is required.[/yellow]")
print_header("Python package template setup")
console.print("This script will configure the template for your project.\n")
gh_owner, gh_repo = _parse_github_remote()
default_name = SCRIPT_DIR.name
while True:
package_name = Prompt.ask(
"[bold]Package name[/bold]",
default=default_name,
).strip()
if not package_name:
console.print(" [yellow]This field is required.[/yellow]")
continue
if validate_package_name(package_name):
break
console.print(
" [yellow]Invalid name. Use letters, numbers, and hyphens"
" (e.g., my-package).[/yellow]"
)
package_underscore = to_underscore(package_name)
package_title = package_name.replace("-", " ").title()
default_description = None
if gh_owner and gh_repo:
default_description = _fetch_github_description(gh_owner, gh_repo)
if default_description:
description = Prompt.ask(
"[bold]Package description[/bold]", default=default_description
).strip()
else:
description = ask_required("Package description")
default_author = _git_config("user.name")
default_email = _git_config("user.email")
if default_author:
author_name = Prompt.ask(
"[bold]Author name[/bold]", default=default_author
).strip()
else:
author_name = ask_required("Author name")
if default_email:
author_email = Prompt.ask(
"[bold]Author email[/bold]", default=default_email
).strip()
else:
author_email = ask_required("Author email")
if gh_owner:
github_username = Prompt.ask(
"[bold]GitHub username or organization[/bold]", default=gh_owner
).strip()
else:
github_username = ask_required("GitHub username or organization")
include_docs = Confirm.ask(
"[bold]Include Starlight documentation site?[/bold]", default=True
)
current_year = str(datetime.now().year)
print_header("Configuration summary")
table = Table(show_header=False, box=None, padding=(0, 2))
table.add_column(style="bold")
table.add_column()
table.add_row("Package name", package_name)
table.add_row("Python import", package_underscore)
table.add_row("Description", description)
table.add_row("Author", f"{author_name} <{author_email}>")
table.add_row("GitHub", f"{github_username}/{package_name}")
table.add_row("Documentation", "Yes (Starlight)" if include_docs else "No")
console.print(table)
console.print()
if not Confirm.ask("Proceed with setup?", default=True):
console.print("\n[yellow]Setup cancelled.[/yellow]")
_uninstall_rich()
return 1
print_header("Configuring project")
src_old = SCRIPT_DIR / "src" / "package_name"
src_new = SCRIPT_DIR / "src" / package_underscore
if src_old.exists():
print_step(f"Renaming src/package_name/ to src/{package_underscore}/")
shutil.move(str(src_old), str(src_new))
print_success("Package directory renamed")
replacements = {
"opencitations/python-package-template": f"{github_username}/{package_name}",
"python-package-template": package_name,
"package-name": package_name,
"package_name": package_underscore,
"Package Name": package_title,
"Python Package Template": package_title,
"Package description": description,
"A template for creating Python packages with UV, pytest, and Starlight documentation": description,
"Author Name": author_name,
"author@example.com": author_email,
"opencitations": github_username,
"[year]": current_year,
"[author]": author_name,
}
files_to_update = [
SCRIPT_DIR / "pyproject.toml",
SCRIPT_DIR / "LICENSE.md",
SCRIPT_DIR / "REUSE.toml",
SCRIPT_DIR / "src" / package_underscore / "__init__.py",
SCRIPT_DIR / "tests" / "__init__.py",
SCRIPT_DIR / "tests" / "test_example.py",
SCRIPT_DIR / ".github" / "workflows" / "tests.yml",
SCRIPT_DIR / ".github" / "workflows" / "release.yml",
SCRIPT_DIR / ".github" / "workflows" / "deploy-docs.yml",
SCRIPT_DIR / ".github" / "workflows" / "reuse.yml",
]
for filepath in files_to_update:
if filepath.exists():
print_step(f"Updating {filepath.relative_to(SCRIPT_DIR)}")
replace_in_file(filepath, replacements)
print_success(f"{filepath.name} updated")
readme_template = SCRIPT_DIR / "README_TEMPLATE.md"
readme_path = SCRIPT_DIR / "README.md"
if readme_template.exists():
print_step("Generating README.md from template...")
content = readme_template.read_text()
for old, new in replacements.items():
content = content.replace(old, new)
readme_path.write_text(content)
print_success("README.md generated")
docs_dir = SCRIPT_DIR / "docs"
if include_docs:
if docs_dir.exists():
print_step("Updating documentation files...")
docs_files = [
docs_dir / "astro.config.mjs",
docs_dir / "src" / "content.config.ts",
docs_dir / "src" / "content" / "docs" / "index.mdx",
docs_dir / "src" / "content" / "docs" / "getting_started.md",
]
for filepath in docs_files:
if filepath.exists():
replace_in_file(filepath, replacements)
print_success("Documentation files updated")
else:
if docs_dir.exists():
print_step("Removing documentation directory...")
shutil.rmtree(docs_dir)
print_success("docs/ removed")
deploy_docs_workflow = SCRIPT_DIR / ".github" / "workflows" / "deploy-docs.yml"
if deploy_docs_workflow.exists():
print_step("Removing documentation workflow...")
deploy_docs_workflow.unlink()
print_success("deploy-docs.yml removed")
reuse_toml = SCRIPT_DIR / "REUSE.toml"
if reuse_toml.exists():
print_step("Removing docs entries from REUSE.toml...")
content = reuse_toml.read_text()
content = re.sub(r' "docs/[^\n]+\n', "", content)
reuse_toml.write_text(content)
print_success("REUSE.toml updated")
if readme_path.exists():
print_step("Updating README.md (removing docs section)...")
content = readme_path.read_text()
content = re.sub(
r"\n## Documentation\n.*?(?=\n## |\Z)",
"",
content,
flags=re.DOTALL,
)
content = re.sub(
r"\n### Building documentation locally\n.*?(?=\n## |\n### |\Z)",
"",
content,
flags=re.DOTALL,
)
readme_path.write_text(content)
print_success("README.md updated")
print_step("Running uv sync --all-extras --dev")
success, output = run_command(
["uv", "sync", "--all-extras", "--dev"],
cwd=SCRIPT_DIR,
)
if success:
print_success("Dependencies installed")
else:
print_error("uv sync failed. Run it manually after setup.")
console.print(output)
print_step("Removing setup files")
setup_files = [
SCRIPT_DIR / "setup.py",
SCRIPT_DIR / "README_TEMPLATE.md",
]
for filepath in setup_files:
if filepath.exists():
filepath.unlink()
images_dir = SCRIPT_DIR / ".github" / "images"
if images_dir.exists():
shutil.rmtree(images_dir)
reuse_toml = SCRIPT_DIR / "REUSE.toml"
if reuse_toml.exists():
content = reuse_toml.read_text()
content = re.sub(r' "README_TEMPLATE\.md",\n', "", content)
content = re.sub(r' "\.github/images/\*\*",\n', "", content)
reuse_toml.write_text(content)
print_success("Setup files removed")
_uninstall_rich()
print_header("Setup complete")
console.print("Your project is ready. Next steps:\n")
console.print("[bold]1. Configure GitHub repository:[/bold]")
console.print(" - Create PyPI token: https://pypi.org/manage/account/token/")
console.print(
f" - Add as secret: https://github.com/{github_username}/{package_name}"
"/settings/secrets/actions/new"
)
console.print(" Name: PYPI_TOKEN")
if include_docs:
console.print(
f" - Enable GitHub Pages: https://github.com/{github_username}"
f"/{package_name}/settings/pages"
)
console.print(" Source: GitHub Actions")
console.print()
console.print("[bold]2. Commit and push:[/bold]")
console.print(' git add .')
console.print(' git commit -m "feat: initial project setup"')
console.print(" git push")
if include_docs:
console.print()
console.print(
" [yellow]Warning: if GitHub Pages is not configured with"
" 'GitHub Actions' as source, the documentation deployment"
" will fail.[/yellow]"
)
console.print()
console.print("[bold]3. Start developing:[/bold]")
console.print(f" - Edit src/{package_underscore}/__init__.py")
console.print(" - Add tests in tests/")
if include_docs:
console.print(" - Update documentation in docs/src/content/docs/")
console.print()
return 0
if __name__ == "__main__":
sys.exit(main())