diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7fc2bd2..04b694b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,8 @@ jobs: - run: uv run pytest - name: Run the commands shown in lessons run: uv run python tools/test_commands.py + - name: Walk the learner path through the lessons that need a fork + run: uv run python tools/test_learner_path.py windows: # Windows learners use Git Bash (Lesson 03), so the lesson commands run @@ -37,3 +39,5 @@ jobs: - run: uv run pytest - name: Run the commands shown in lessons run: uv run python tools/test_commands.py + - name: Walk the learner path through the lessons that need a fork + run: uv run python tools/test_learner_path.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fdd7937..f2a1dff 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,6 +27,7 @@ uv run ruff check . uv run python tools/check_lessons.py uv run pytest uv run python tools/test_commands.py +uv run python tools/test_learner_path.py ``` **Lesson format:** each lesson is a folder `lessons/NN-slug/` with diff --git a/README.md b/README.md index 4bbc8a1..d6d098c 100644 --- a/README.md +++ b/README.md @@ -32,8 +32,10 @@ your first commit. A bot checks it and, when it's right, merges it. Lessons and video scripts are drafted with AI and **reviewed by a human before anything is published**. Commands shown in lessons are run in CI -(`tools/test_commands.py`); the few that need your own account, like logging -in, are marked and explained. Videos are generated from the scripts in this repo +(`tools/test_commands.py`), on Linux and on Windows in Git Bash. The ones +that need your own fork run there too, against a stand-in fork +(`tools/test_learner_path.py`); only steps that need GitHub itself, like +logging in, are left out, and they are marked and explained. Videos are generated from the scripts in this repo (`tools/render_video.py`), so fixing a mistake means fixing a text file and re-rendering. If you spot something wrong, please [open an issue](https://github.com/thejesh23/first-python-contribution/issues) — that's a contribution too. diff --git a/tools/test_learner_path.py b/tools/test_learner_path.py new file mode 100644 index 0000000..219cb03 --- /dev/null +++ b/tools/test_learner_path.py @@ -0,0 +1,243 @@ +"""Walk the learner's path through the lessons that need a fork, against a stand-in fork. + +tools/test_commands.py runs every lesson command that needs no account. The +commands that need the learner's own fork are marked ```bash norun there. This +script covers those: it makes a local stand-in (a bare "upstream" holding this +checkout, a bare "fork" of it, and a clone with both remotes), then types the +commands of Lessons 03, 05, 07, 10 and 11 in it, in order, in one shell, the +way a learner does: make a venv, activate it, install, test, format, commit, +push, and run the course's checkers. + +Every command is taken from the lesson text and the script stops if a lesson +no longer contains it, so the two can't drift apart. Files the learner writes +in an editor come from the lesson's own code blocks. + +On Windows the commands change exactly as the lessons tell Windows learners: +`py` for `python3`, and `.venv/Scripts/activate` for `.venv/bin/activate`. + +Not covered: logging in, opening the pull request and anything else that needs +GitHub itself, and tools/find_issues.py (it calls the GitHub API). + +Usage:: + + python tools/test_learner_path.py +""" + +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import sys +import tempfile +from dataclasses import dataclass +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +LESSONS = ROOT / "lessons" +# On Windows a bare "bash" finds WSL in System32 before Git Bash; look it up on PATH instead. +BASH = shutil.which("bash") or "bash" +FENCE_RE = re.compile(r"^[ \t]*```[^\n]*\n(?P.*?)^[ \t]*```", re.MULTILINE | re.DOTALL) + + +@dataclass(frozen=True) +class Run: + """A command from a lesson, typed as shown.""" + + lesson: str + command: str + expect_fail: bool = False # the lesson says this one fails + may_fail: bool = False # exit code depends on the machine; check the output instead + must_print: str = "" + env: str = "" # stands in for something the learner does by hand, like typing in an editor + + +@dataclass(frozen=True) +class Write: + """A file the learner creates in an editor: the first code block after `after` in the lesson.""" + + lesson: str + after: str + path: str + + +@dataclass(frozen=True) +class StandIn: + """Not in a lesson: sets the scene, or checks what GitHub would have shown.""" + + command: str + + +L03, L05, L07 = "03-set-up-your-machine", "05-second-pr-from-terminal", "07-set-up-any-project" +L10, L11 = "10-making-the-change", "11-opening-the-pull-request" + +STEPS: list[Run | Write | StandIn] = [ + # Lesson 03, steps 5 and 6: inside the clone, fetch and run the doctor. + Run(L03, "cd first-python-contribution"), + Run(L03, "git remote -v", must_print="upstream"), + Run(L03, "git fetch upstream"), + # gh isn't logged in here, so the doctor reports that and exits 1. It must still print its report. + Run(L03, "python3 tools/doctor.py", may_fail=True, must_print="✔ Python"), + # Lesson 05: the whole second pull request, up to the push. + Run(L05, "python3 -m venv .venv"), + Run(L05, "source .venv/bin/activate"), + Run(L05, "python -m pip install pytest ruff"), + Run(L05, "git switch -c exercise-2 upstream/main"), + Write(L05, "Create `practice/tests/test_ada_lovelace.py`", "practice/tests/test_ada_lovelace.py"), + Run(L05, "python -m pytest practice", expect_fail=True), + Write(L05, "Create `practice/greetings/ada_lovelace.py`", "practice/greetings/ada_lovelace.py"), + Run(L05, "python -m pytest practice"), + Run(L05, "ruff format practice"), + Run(L05, "ruff check practice"), + Run(L05, "git status", must_print="ada_lovelace.py"), + Run(L05, "git add practice/greetings/ada_lovelace.py practice/tests/test_ada_lovelace.py"), + Run(L05, 'git commit -m "Add exercise 2 greeting for ada-lovelace"'), + Run(L05, "git push -u origin exercise-2"), + StandIn("git ls-remote --exit-code origin exercise-2"), + # Lesson 07: the setup detector, pointed at a neighbouring project. + StandIn("mkdir ../requests && touch ../requests/tox.ini ../requests/pyproject.toml"), + Run(L07, "python3 tools/which_setup.py ../requests", must_print="tox"), + # Lesson 10: reproduce the bug, test, fix, changelog, commit, check. + Run(L10, "git switch -c fix-slugify upstream/main"), + Run(L10, "cd practice"), + Run( + L10, + """python -c "from textkit import slugify; print(repr(slugify('Hello World')))\"""", + must_print="hello--world", + ), + Run(L10, "cd .."), + Write(L10, "Add to `practice/tests/test_textkit.py`", "practice/tests/test_textkit.py"), + Run(L10, "python -m pytest practice/tests/test_textkit.py", expect_fail=True), + Write(L10, "## Step 3: The smallest fix that works", "practice/textkit.py"), + Run(L10, "python -m pytest practice/tests/test_textkit.py"), + Run(L10, "python -m pytest practice"), + Run(L10, "ruff format practice"), + Run(L10, "ruff check practice"), + Write(L10, "Add `practice/news/slugify-separators.bugfix.md`", "practice/news/slugify-separators.bugfix.md"), + Run( + L10, + "git add practice/textkit.py practice/tests/test_textkit.py practice/news/slugify-separators.bugfix.md", + ), + # `git commit` opens an editor. This "editor" types the message the lesson shows. + Write(L10, "Without `-m`, git opens your editor", "../commit-message.txt"), + Run(L10, "git commit", env='GIT_EDITOR="cp ../commit-message.txt"'), + Run(L10, "python tools/check_exercise_3.py", must_print="Great fix"), + # Lesson 11: describe the fix and check the description. + Write(L11, "asks for one (Lesson 06).", "pr-description.md"), + Run(L11, "python tools/check_pr_description.py pr-description.md", must_print="✔ Title"), +] + + +def lesson_text(lesson: str) -> str: + return (LESSONS / lesson / "README.md").read_text(encoding="utf-8") + + +def block_after(text: str, marker: str) -> str: + """Return the body of the first fenced block after `marker`.""" + at = text.index(marker) + m = FENCE_RE.search(text, at) + if m is None: + raise ValueError(f"no code block after {marker!r}") + return m.group("body") + + +def as_typed_on_windows(command: str) -> str: + """Lesson 03: `py` for `python3`. Lesson 05: the activate script is under Scripts.""" + command = re.sub(r"\bpython3\b", "py", command) + return command.replace(".venv/bin/activate", ".venv/Scripts/activate") + + +def shell_lines(step: Run | Write | StandIn, windows: bool) -> list[str]: + if isinstance(step, StandIn): + return [step.command] + text = lesson_text(step.lesson) + if isinstance(step, Write): + return [f"cat > {step.path} <<'LESSON_FILE'", block_after(text, step.after).rstrip("\n"), "LESSON_FILE"] + if not any(line.strip() == step.command for line in text.splitlines()): + raise ValueError(f"{step.lesson} no longer shows this command: {step.command}") + command = as_typed_on_windows(step.command) if windows else step.command + if step.env: + command = f"{step.env} {command}" + if step.expect_fail: + return [f'if {command}; then echo "expected to fail: {step.command}" >&2; exit 1; fi'] + if not step.must_print: + return [command] + tail = " || true" if step.may_fail else "" + return [ + f"out=$({command} 2>&1){tail}", + 'echo "$out"', + f"grep -qF -- '{step.must_print}' <<<\"$out\"", + 'if grep -q Traceback <<<"$out"; then exit 1; fi', + ] + + +def script(windows: bool) -> str: + return "\n".join(line for step in STEPS for line in shell_lines(step, windows)) + "\n" + + +def git(*args: str, cwd: Path, env: dict[str, str]) -> None: + subprocess.run(["git", *args], cwd=cwd, env=env, check=True) + + +def make_stand_in(base: Path, env: dict[str, str]) -> None: + """Create upstream.git (this checkout), fork.git and a clone of the fork with both remotes.""" + listed = subprocess.run( + ["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"], + cwd=ROOT, + capture_output=True, + check=True, + ).stdout.decode("utf-8") + seed = base / "seed" + for name in filter(None, listed.split("\0")): + src = ROOT / name + if src.is_file(): + dst = seed / name + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(src, dst) + git("init", "-q", "-b", "main", cwd=seed, env=env) + git("add", "-A", cwd=seed, env=env) + git("commit", "-q", "-m", "Course repo", cwd=seed, env=env) + git("clone", "-q", "--bare", "seed", "upstream.git", cwd=base, env=env) + git("clone", "-q", "--bare", "upstream.git", "fork.git", cwd=base, env=env) + git("clone", "-q", "fork.git", "first-python-contribution", cwd=base, env=env) + clone = base / "first-python-contribution" + # `gh repo clone` adds this remote for a fork (Lesson 03, step 5). + git("remote", "add", "upstream", (base / "upstream.git").as_posix(), cwd=clone, env=env) + + +def main() -> int: + windows = os.name == "nt" + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp).resolve() + home = base / "home" + home.mkdir() + # What Lesson 03 sets, plus the line-ending choice the Git for Windows installer makes by default. + config = "[user]\n\tname = Course CI\n\temail = ci@example.com\n[init]\n\tdefaultBranch = main\n" + if windows: + config += "[core]\n\tautocrlf = true\n" + (home / ".gitconfig").write_text(config, encoding="utf-8") + env = { + **os.environ, + "HOME": str(home), + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": str(home / ".gitconfig"), + "LANG": "C.UTF-8", + "TERM": "dumb", + } + for name in ("VIRTUAL_ENV", "GH_TOKEN", "GITHUB_TOKEN"): # start like a fresh terminal, logged out + env.pop(name, None) + make_stand_in(base, env) + path = base / "learner-path.sh" + path.write_text(script(windows), encoding="utf-8", newline="\n") + proc = subprocess.run([BASH, "-euxo", "pipefail", path.as_posix()], cwd=base, env=env, timeout=900) + if proc.returncode != 0: + print(f"FAIL learner path (exit {proc.returncode})") + return 1 + print("ok learner path: Lessons 03, 05, 07, 10 and 11") + return 0 + + +if __name__ == "__main__": + sys.stdout.reconfigure(encoding="utf-8") # ✔ and ✘ print on Windows too + sys.exit(main())