diff --git a/AGENTS.md b/AGENTS.md index 14d0ae9..52e2ee9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -129,6 +129,12 @@ human approval. - Keep production code, tests, package configuration, and documentation aligned. - Add tests for new library behavior under `tests/`. +- Write Google-style docstrings for every function, including private ones. + Ruff checks the style and requires `Returns` and `Raises` sections when the + code returns or raises. Also list every argument under `Args` and add an + `Examples` section. Ruff cannot require `Examples`, but pytest runs them as + doctests, so write them to pass (mark ones that cannot run with + `# doctest: +SKIP`). - Use the configured Ruff and ty checks; do not introduce duplicate tooling without a project need. - Copy `.env.example` to `.env` or use `make bootstrap` in a linked worktree. diff --git a/pyproject.toml b/pyproject.toml index e90a598..1d95b09 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -94,8 +94,11 @@ notebooks = [ [tool.ruff] target-version = "py311" +# pydoclint (DOC) rules are still in preview, so opt in to them by name only. +preview = true [tool.ruff.lint] +explicit-preview-rules = true select = [ "E", # pycodestyle "F", # pyflakes @@ -127,6 +130,12 @@ select = [ "FLY", # flynt - f-string conversion "PERF", # perflint - performance improvements "RUF", # ruff-specific rules + "D", # pydocstyle - docstring style + "DOC201", # pydoclint - document return values + "DOC402", # pydoclint - document yielded values + "DOC403", # pydoclint - no Yields section without yield + "DOC501", # pydoclint - document raised exceptions + "DOC502", # pydoclint - no Raises section for exceptions not raised ] ignore = [ "E501", # Line length @@ -140,8 +149,13 @@ ignore = [ "RUF005", # Allow for adding lists ] +[tool.ruff.lint.pydocstyle] +convention = "google" + [tool.ruff.lint.per-file-ignores] "tests/*" = [ + "D", # Docstrings + "DOC", # Docstring sections "ANN", # Annotations "S105", # Possible hardcoded password "S108", # Temp directory @@ -153,11 +167,12 @@ docstring-code-format = true [tool.pytest.ini_options] addopts = [ "--strict-config", + "--doctest-modules", "--strict-markers", "--durations=10", "--durations-min=1.0", ] -testpaths = ["tests"] +testpaths = ["tests", "scripts"] python_files = "test_*.py" timeout = 60 xfail_strict = true diff --git a/scripts/worktree_bootstrap.py b/scripts/worktree_bootstrap.py index 540d0da..4f06b55 100644 --- a/scripts/worktree_bootstrap.py +++ b/scripts/worktree_bootstrap.py @@ -21,17 +21,49 @@ class Runner(Protocol): """Run commands needed by the bootstrap.""" def capture(self, command: Sequence[str], cwd: Path) -> str: - """Run a command and return its standard output.""" + """Run a command and return its standard output. + + Args: + command: The program and its arguments. + cwd: The directory to run the command in. + + Returns: + The text the command printed to standard output. + + Examples: + >>> runner.capture(("git", "status", "-sb"), Path(".")) # doctest: +SKIP + 'On branch main' + """ def execute(self, command: Sequence[str], cwd: Path) -> None: - """Run a command with output attached to the terminal.""" + """Run a command with output attached to the terminal. + + Args: + command: The program and its arguments. + cwd: The directory to run the command in. + + Examples: + >>> runner.execute(("uv", "sync"), Path(".")) # doctest: +SKIP + """ class SubprocessRunner: """Run bootstrap commands in subprocesses.""" def capture(self, command: Sequence[str], cwd: Path) -> str: - """Run a command and return its standard output.""" + """Run a command and return its standard output. + + Args: + command: The program and its arguments. + cwd: The directory to run the command in. + + Returns: + The text the command printed to standard output. + + Examples: + >>> SubprocessRunner().capture(("echo", "-n", "hi"), Path(".")) + 'hi' + """ result = subprocess.run( # noqa: S603 - Commands are never shell strings. command, cwd=cwd, @@ -42,7 +74,15 @@ def capture(self, command: Sequence[str], cwd: Path) -> str: return result.stdout def execute(self, command: Sequence[str], cwd: Path) -> None: - """Run a command with output attached to the terminal.""" + """Run a command with output attached to the terminal. + + Args: + command: The program and its arguments. + cwd: The directory to run the command in. + + Examples: + >>> SubprocessRunner().execute(("true",), Path(".")) + """ subprocess.run( # noqa: S603 - Commands are never shell strings. command, cwd=cwd, @@ -59,7 +99,19 @@ class GitCheckout: @classmethod def discover(cls, runner: Runner, cwd: Path) -> GitCheckout: - """Discover checkout paths from Git metadata.""" + """Discover checkout paths from Git metadata. + + Args: + runner: Runs the Git commands. + cwd: A directory inside the checkout. + + Returns: + The current and primary checkout paths. + + Examples: + >>> GitCheckout.discover(SubprocessRunner(), Path(".")) # doctest: +SKIP + GitCheckout(current=PosixPath('/code/app'), primary=PosixPath('/code/app')) + """ current_output = runner.capture( ("git", "rev-parse", "--show-toplevel"), cwd, @@ -74,12 +126,36 @@ def discover(cls, runner: Runner, cwd: Path) -> GitCheckout: @property def is_linked_worktree(self) -> bool: - """Return whether the current checkout is not the primary checkout.""" + """Report whether the current checkout is a linked worktree. + + Returns: + True if the current checkout is not the primary checkout. + + Examples: + >>> GitCheckout( + ... current=Path("/a-feature"), primary=Path("/a") + ... ).is_linked_worktree + True + """ return self.current != self.primary def parse_primary_checkout(output: str) -> Path: - """Return the primary checkout from Git's porcelain worktree listing.""" + """Find the primary checkout in Git's porcelain worktree listing. + + Args: + output: The text printed by `git worktree list --porcelain`. + + Returns: + The path of the first listed worktree, which is the primary checkout. + + Raises: + ValueError: If the listing contains no worktree. + + Examples: + >>> parse_primary_checkout("worktree /tmp/primary").name + 'primary' + """ for line in output.splitlines(): if line.startswith("worktree "): return Path(line.removeprefix("worktree ")).resolve() @@ -88,7 +164,18 @@ def parse_primary_checkout(output: str) -> Path: def worktree_identifier(checkout: Path) -> str: - """Build a stable, environment-safe identifier for a checkout.""" + """Build a stable, environment-safe identifier for a checkout. + + Args: + checkout: The path of the checkout. + + Returns: + The lowercase folder name with a short hash of the full path. + + Examples: + >>> worktree_identifier(Path("/tmp/My App")).startswith("my-app-") + True + """ resolved = checkout.resolve() slug = re.sub(r"[^a-z0-9]+", "-", resolved.name.lower()).strip("-") safe_slug = slug or "worktree" @@ -97,7 +184,17 @@ def worktree_identifier(checkout: Path) -> str: def ensure_shared_env(checkout: GitCheckout) -> None: - """Link the primary .env into a linked worktree without overwriting files.""" + """Link the primary .env into a linked worktree without overwriting files. + + Args: + checkout: The current and primary checkout paths. + + Raises: + FileExistsError: If the worktree already has a different `.env`. + + Examples: + >>> ensure_shared_env(GitCheckout(current=Path("."), primary=Path("."))) + """ if not checkout.is_linked_worktree: return @@ -116,7 +213,22 @@ def ensure_shared_env(checkout: GitCheckout) -> None: def ensure_worktree_override(checkout: Path, identifier: str) -> None: - """Create or update the managed identifier while preserving local settings.""" + """Create or update the managed identifier while preserving local settings. + + Args: + checkout: The checkout folder that holds `.env.worktree`. + identifier: The value to store as the worktree identifier. + + Raises: + ValueError: If the file assigns the identifier more than once. + + Examples: + >>> import tempfile + >>> with tempfile.TemporaryDirectory() as folder: + ... ensure_worktree_override(Path(folder), "demo-1234") + ... (Path(folder) / ".env.worktree").read_text().splitlines()[-1] + 'WORKTREE_ID=demo-1234' + """ override = checkout / ".env.worktree" assignment = f"{WORKTREE_ID_VARIABLE}={identifier}" if not override.exists(): @@ -151,7 +263,20 @@ def ensure_worktree_override(checkout: Path, identifier: str) -> None: def bootstrap(cwd: Path, uv: str, runner: Runner) -> GitCheckout: - """Prepare local environment files and install locked dependencies.""" + """Prepare local environment files and install locked dependencies. + + Args: + cwd: A directory inside the checkout. + uv: The uv program to run. + runner: Runs the Git and uv commands. + + Returns: + The checkout that was prepared. + + Examples: + >>> bootstrap(Path("."), "uv", SubprocessRunner()) # doctest: +SKIP + GitCheckout(current=PosixPath('/code/app'), primary=PosixPath('/code/app')) + """ checkout = GitCheckout.discover(runner, cwd) ensure_shared_env(checkout) ensure_worktree_override( @@ -166,7 +291,11 @@ def bootstrap(cwd: Path, uv: str, runner: Runner) -> GitCheckout: def main() -> None: - """Run the worktree bootstrap.""" + """Run the worktree bootstrap from the command line. + + Examples: + >>> main() # doctest: +SKIP + """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--uv", default=os.environ.get("UV", "uv")) args = parser.parse_args()