Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions .github/scripts/gen_directory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""Regenerate DIRECTORY.md; with --check, fail if it is out of date."""

import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
SKIP = {".git", ".github", ".venv", "venv", "__pycache__"}

HEADER = """# Directory

Every `.py` file in this repo, grouped by category. Any file can be run with `python3 <path>`.
Packages (folders with a `__main__.py`) are run with `python3 -m <dotted.path>`.
"""


def is_package(path: Path) -> bool:
return path.is_dir() and (path / "__main__.py").exists()


def groups() -> dict[str, list[Path]]:
found: dict[str, list[Path]] = {}
for directory in sorted(p for p in ROOT.rglob("*") if p.is_dir()):
rel = directory.relative_to(ROOT)
if any(part in SKIP or part.startswith(".") for part in rel.parts):
continue
if any(is_package(ROOT / Path(*rel.parts[:i])) for i in range(1, len(rel.parts) + 1)):
continue # inside a package
entries = [f for f in sorted(directory.glob("*.py"))]
entries += [d for d in sorted(directory.iterdir()) if is_package(d)]
if entries:
found[rel.as_posix()] = sorted(entries, key=lambda p: p.name)
return found


def render() -> str:
data = groups()
total = sum(len(v) for v in data.values())
lines = [HEADER, f"_{total} runnable samples across {len(data)} directories._\n"]
for name, entries in data.items():
lines.append(f"## {name}")
for entry in entries:
rel = entry.relative_to(ROOT).as_posix()
if entry.is_dir():
lines.append(f"- [{entry.name}]({rel}/) (package)")
else:
lines.append(f"- [{entry.stem}]({rel})")
lines.append("")
return "\n".join(lines)


def main() -> int:
text = render()
target = ROOT / "DIRECTORY.md"
if "--check" in sys.argv:
if target.read_text() != text:
print("DIRECTORY.md is out of date: run python3 .github/scripts/gen_directory.py")
return 1
print("DIRECTORY.md is up to date")
return 0
target.write_text(text)
return 0


if __name__ == "__main__":
sys.exit(main())
53 changes: 53 additions & 0 deletions .github/scripts/run_all.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""Run every sample and report failures.

Single files run as scripts; a package directory (one containing __main__.py)
runs as ``python -m <dotted.path>`` from the repo root.
"""

import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
TIMEOUT = 60


def targets() -> list[tuple[str, list[str]]]:
found: list[tuple[str, list[str]]] = []
for path in sorted(ROOT.rglob("*.py")):
rel = path.relative_to(ROOT)
if rel.parts[0] in {".git", ".github", ".venv", "venv"}:
continue
if path.name == "__main__.py":
module = ".".join(rel.parent.parts)
found.append((str(rel.parent), [sys.executable, "-m", module]))
elif any((ROOT / Path(*rel.parts[:i]) / "__main__.py").exists()
for i in range(1, len(rel.parts))):
continue # internal module of a package; covered by its __main__
else:
found.append((str(rel), [sys.executable, str(rel)]))
return found


def main() -> int:
failures = 0
items = targets()
for name, cmd in items:
try:
result = subprocess.run(
cmd, cwd=ROOT, capture_output=True, text=True,
timeout=TIMEOUT, stdin=subprocess.DEVNULL,
)
ok = result.returncode == 0 and result.stdout.strip() != ""
detail = (result.stderr.strip().splitlines() or ["no output"])[-1]
except subprocess.TimeoutExpired:
ok, detail = False, f"timeout after {TIMEOUT}s"
if not ok:
failures += 1
print(f"FAIL {name}: {detail}")
print(f"{len(items) - failures}/{len(items)} passed")
return 1 if failures else 0


if __name__ == "__main__":
sys.exit(main())
31 changes: 31 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: CI

on:
push:
branches: [main]
pull_request:

jobs:
samples:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.12", "3.13"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Run every sample
run: python .github/scripts/run_all.py

directory:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: DIRECTORY.md is up to date
run: python .github/scripts/gen_directory.py --check
2 changes: 1 addition & 1 deletion DIRECTORY.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Directory

Every `.py` file in this repo, grouped by category. Any file can be run with `python3 <path>`.
Packages (folders with a `__main__.py`) are run with `python3 -m <dotted.path>`.

_318 runnable samples across 39 directories._

Expand Down Expand Up @@ -399,4 +400,3 @@ _318 runnable samples across 39 directories._
- [valid_parentheses](strings/valid_parentheses.py)
- [wildcard_and_regex_matching](strings/wildcard_and_regex_matching.py)
- [z_algorithm](strings/z_algorithm.py)

Loading