From 1bab5cfc54da2dfe38c81b5c592bdf83d39d9ebf Mon Sep 17 00:00:00 2001 From: Rub1kCube Date: Tue, 27 Oct 2026 17:50:46 +0500 Subject: [PATCH] feat: added generate docs and llm friendly --- .gitignore | 22 +++ README.md | 30 ++++- cookiecutter.json | 3 +- pyproject.toml | 1 + uv.lock | 16 +++ .../.github/workflows/docs.yml | 51 +++++++ .../.pre-commit-config.yml | 6 + .../.readthedocs.yml | 17 +++ {{cookiecutter.project_name}}/AGENTS.md | 77 ++++++++++- {{cookiecutter.project_name}}/CONTRIBUTING.md | 125 ++++++++++++++++++ {{cookiecutter.project_name}}/README.md | 54 ++------ {{cookiecutter.project_name}}/context7.json | 16 +++ .../docs/__init__.py | 1 + .../docs/_static/custom.css | 4 + {{cookiecutter.project_name}}/docs/conf.py | 76 +++++++++++ {{cookiecutter.project_name}}/docs/index.rst | 20 +++ {{cookiecutter.project_name}}/docs/justfile | 29 ++++ .../docs/pages/api-reference.rst | 15 +++ .../docs/pages/documentation-guidelines.rst | 107 +++++++++++++++ .../docs/pages/installation.rst | 24 ++++ .../docs/pages/usage.rst | 18 +++ {{cookiecutter.project_name}}/justfile | 28 +++- {{cookiecutter.project_name}}/pyproject.toml | 15 +++ 23 files changed, 699 insertions(+), 56 deletions(-) create mode 100644 {{cookiecutter.project_name}}/.github/workflows/docs.yml create mode 100644 {{cookiecutter.project_name}}/.readthedocs.yml create mode 100644 {{cookiecutter.project_name}}/CONTRIBUTING.md create mode 100644 {{cookiecutter.project_name}}/context7.json create mode 100644 {{cookiecutter.project_name}}/docs/__init__.py create mode 100644 {{cookiecutter.project_name}}/docs/_static/custom.css create mode 100644 {{cookiecutter.project_name}}/docs/conf.py create mode 100644 {{cookiecutter.project_name}}/docs/index.rst create mode 100644 {{cookiecutter.project_name}}/docs/justfile create mode 100644 {{cookiecutter.project_name}}/docs/pages/api-reference.rst create mode 100644 {{cookiecutter.project_name}}/docs/pages/documentation-guidelines.rst create mode 100644 {{cookiecutter.project_name}}/docs/pages/installation.rst create mode 100644 {{cookiecutter.project_name}}/docs/pages/usage.rst diff --git a/.gitignore b/.gitignore index a80c13f..0dfb628 100644 --- a/.gitignore +++ b/.gitignore @@ -30,6 +30,28 @@ htmlcov/ coverage.* setup.py +# AI +.claude +.cursor +.scratch/ +docs/agents/ +docs/adr/ +CONTEXT.md +# locally installed agent skills (project-owned ones are un-ignored below) +.agents/skills/* +skills-lock.json +# local agent config +.mcp.json +mcp.json +# Added by codegraph +.codegraph +codegraph.mdc +# Added by code-review-graph +.code-review-graph/ +# Added by graphify +graphify-out/ +.graphifyignore + # pdm # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. #pdm.lock diff --git a/README.md b/README.md index cab93e2..752b512 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,12 @@ building on the workflow provided by `uv init` or `poetry new`. - [Ruff](https://github.com/astral-sh/ruff) for linting and formatting. - Preconfigured [prek](https://github.com/j178/prek) hooks, a faster alternative to [pre-commit](https://github.com/pre-commit/pre-commit). - MIT, BSD-3-Clause, or Apache-2.0 license generation with [lice2](https://github.com/seapagan/lice2). +- `AGENTS.md` with project commands, verification steps, and documentation rules for coding agents. +- Sphinx documentation with the Shibuya theme, Read the Docs configuration, and a GitHub Actions check. +- `llms.txt` and per-page Markdown generated by + [sphinx-llm-friendly](https://github.com/scrapy/sphinx-llm-friendly) for agents reading the library documentation. +- Optional [Context7](https://context7.com/docs/overview) guidance for looking up dependency documentation + and submitting the generated library's published documentation for indexing. ## Installation @@ -50,11 +56,33 @@ This installs dependencies and Git hooks while preserving the existing environme Use `just reinstall` to recreate the environment and remove generated artifacts. Run `just` to list available commands. `just check-all` checks dependencies, code, formatting, -types, and tests without applying fixes. Use `just format` to format code and `just check` +types, tests, and documentation without applying fixes. Use `just format` to format code and `just check` to run prek hooks with automatic fixes. After changing dependencies, run `just install`: check commands do not synchronize the environment automatically. Use `just upgrade` to update dependency versions and hooks. +## Documentation for agents + +Each generated project includes `AGENTS.md` for agents working on its code. The published documentation +also provides `llms.txt`, an index linking to Markdown versions of its pages for agents using the library. + +Run `just docs` in the generated project to build HTML, `llms.txt`, and the Markdown pages together in +`docs/_build/html/`. Edit the documentation sources and docstrings; these outputs are generated automatically. +`just docs-check` performs a strict build, runs doctests, and checks that `llms.txt` and `index.md` are nonempty. +The existing documentation workflow runs this command, and Read the Docs publishes the generated files +alongside the HTML pages once the repository is connected. + +The generated `AGENTS.md` also guides agents to use Context7, when available, for dependency documentation +matching the versions in `uv.lock`, with a fallback to official documentation or installed sources. +The generated [CONTRIBUTING.md]({{cookiecutter.project_name}}/CONTRIBUTING.md#context7-optional) explains +client setup and submitting the published `llms.txt` to Context7. Maintainers register each library after +publishing its documentation; generation and builds do not register it automatically. +Context7 is optional and requires no additional Python dependency or CI service. + +Each generated library also includes `context7.json` for repository-based indexing. It selects `docs/` +and keeps the root README while excluding build output and contributor instructions. The configuration +applies when the repository is submitted as a Context7 source; it does not change the published `llms.txt`. + ## Library type The `type_lib` prompt offers two options: diff --git a/cookiecutter.json b/cookiecutter.json index 9e75cc7..8be5f14 100644 --- a/cookiecutter.json +++ b/cookiecutter.json @@ -9,6 +9,7 @@ "_extensions": ["jinja2_git.GitExtension"], "_copy_without_render": [ ".venv", - "docs/_build" + "docs/_build", + "docs/justfile" ] } diff --git a/pyproject.toml b/pyproject.toml index cfbf120..522471d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,6 +29,7 @@ test = [ "hatchling>=1.27", "pytest>=9.1.1", "pytest-cookies>=0.7", + "pytest-randomly>=5", "pytest-sugar>=1.1.1", ] lint = [ diff --git a/uv.lock b/uv.lock index 0c42094..7008acf 100644 --- a/uv.lock +++ b/uv.lock @@ -690,6 +690,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5f/f7/438af2f3a6c58f81d22c126707ee5d079f653a76961f4fb7d995e526a9c4/pytest_cookies-0.7.0-py3-none-any.whl", hash = "sha256:52770f090d77b16428f6a24a208e6be76addb2e33458035714087b4de49389ea", size = 6386, upload-time = "2023-03-22T11:07:28.068Z" }, ] +[[package]] +name = "pytest-randomly" +version = "5.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/01/3b/6a40e1b9d925651e601e056a97f60d8a1daeddeac03d5609be60cb4362ce/pytest_randomly-5.0.0.tar.gz", hash = "sha256:e9c575a5873ef168ddbe340ed9e97ce9edb4492ccc821e4b2ac6bb1f0ed515d2", size = 8542, upload-time = "2026-09-01T22:34:20.441Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/b4/47e939285caad9a623d021512912ac08dc92a467ad075d179f43729d2934/pytest_randomly-5.0.0-py3-none-any.whl", hash = "sha256:8a0d4703115c0c25b38b6e129fc16b1947b9643ff26a41bc1d185d7e5a7689c1", size = 8920, upload-time = "2026-09-01T22:34:19.227Z" }, +] + [[package]] name = "pytest-sugar" version = "1.1.1" @@ -746,6 +758,7 @@ dev = [ { name = "pyright", extra = ["nodejs"] }, { name = "pytest" }, { name = "pytest-cookies" }, + { name = "pytest-randomly" }, { name = "pytest-sugar" }, { name = "ruff" }, ] @@ -760,6 +773,7 @@ test = [ { name = "hatchling" }, { name = "pytest" }, { name = "pytest-cookies" }, + { name = "pytest-randomly" }, { name = "pytest-sugar" }, ] @@ -779,6 +793,7 @@ dev = [ { name = "pyright", extras = ["nodejs"], specifier = ">=1.1.414" }, { name = "pytest", specifier = ">=9.1.1" }, { name = "pytest-cookies", specifier = ">=0.7" }, + { name = "pytest-randomly", specifier = ">=5.0.0" }, { name = "pytest-sugar", specifier = ">=1.1.1" }, { name = "ruff", specifier = ">=0.17.2" }, ] @@ -793,6 +808,7 @@ test = [ { name = "hatchling", specifier = ">=1.27" }, { name = "pytest", specifier = ">=9.1.1" }, { name = "pytest-cookies", specifier = ">=0.7" }, + { name = "pytest-randomly", specifier = ">=5.0.0" }, { name = "pytest-sugar", specifier = ">=1.1.1" }, ] diff --git a/{{cookiecutter.project_name}}/.github/workflows/docs.yml b/{{cookiecutter.project_name}}/.github/workflows/docs.yml new file mode 100644 index 0000000..67b45f1 --- /dev/null +++ b/{{cookiecutter.project_name}}/.github/workflows/docs.yml @@ -0,0 +1,51 @@ +name: docs + +on: + push: + branches: + - main + paths: + - "docs/**" + - "**/*.py" + - ".github/workflows/docs.yml" + - ".readthedocs.yml" + - "justfile" + - "pyproject.toml" + - "uv.lock" + pull_request: + paths: + - "docs/**" + - "**/*.py" + - ".github/workflows/docs.yml" + - ".readthedocs.yml" + - "justfile" + - "pyproject.toml" + - "uv.lock" + workflow_dispatch: + +concurrency: + group: "{% raw %}${{ github.workflow }}-${{ github.head_ref || github.run_id }}{% endraw %}" + cancel-in-progress: true + +permissions: + contents: read + +jobs: + docs: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + with: + version: "0.12.3" + python-version: "{{ cookiecutter.min_version_python }}" + enable-cache: true + - name: Install just + run: uv tool install rust-just + - name: Install dependencies + run: uv sync --locked --all-groups --all-extras + - name: Check documentation + run: just docs-check diff --git a/{{cookiecutter.project_name}}/.pre-commit-config.yml b/{{cookiecutter.project_name}}/.pre-commit-config.yml index 5d59735..517f0af 100644 --- a/{{cookiecutter.project_name}}/.pre-commit-config.yml +++ b/{{cookiecutter.project_name}}/.pre-commit-config.yml @@ -23,6 +23,12 @@ repos: - id: ruff-check args: ["--fix"] - id: ruff-format + - repo: https://github.com/sphinx-contrib/sphinx-lint + rev: v1.0.2 + hooks: + - id: sphinx-lint + args: ["--enable=all", "--disable=line-too-long"] + files: ^docs/ - repo: https://github.com/astral-sh/uv-pre-commit rev: 0.13.5 hooks: diff --git a/{{cookiecutter.project_name}}/.readthedocs.yml b/{{cookiecutter.project_name}}/.readthedocs.yml new file mode 100644 index 0000000..446a126 --- /dev/null +++ b/{{cookiecutter.project_name}}/.readthedocs.yml @@ -0,0 +1,17 @@ +version: 2 + +build: + os: ubuntu-lts-latest + tools: + python: "{{ cookiecutter.min_version_python }}" + +python: + install: + - method: uv + command: sync + groups: ["docs"] + path: . + +sphinx: + configuration: docs/conf.py + fail_on_warning: true diff --git a/{{cookiecutter.project_name}}/AGENTS.md b/{{cookiecutter.project_name}}/AGENTS.md index ddc0cfc..12a1119 100644 --- a/{{cookiecutter.project_name}}/AGENTS.md +++ b/{{cookiecutter.project_name}}/AGENTS.md @@ -8,6 +8,7 @@ source of truth for commands; run `just` to list the available recipes. - Python version for development: `{{ cookiecutter.min_version_python }}`. - Library code: `{{ cookiecutter.project_name.lower().replace('-', '_') }}/`. - Tests: `tests/`. +- Documentation: `docs/`. - Dependencies and tool configuration: `pyproject.toml`. - Resolved dependency versions: `uv.lock`. {% if cookiecutter.type_lib == "django" -%} @@ -37,7 +38,10 @@ automatically. There is no need to activate `.venv` manually. | `just type-check` | Run both mypy and Pyright. | | `just mypy` / `just pyright` | Run one type checker. | | `just package` | Check the lockfile, installed environment, and dependency compatibility. | -| `just check-all` | Run `package`, `lint`, `type-check`, and `test`. | +| `just docs` | Build the HTML documentation. | +| `just docs-check` | Build documentation strictly and run its doctests. | +| `just docs-linkcheck` | Check external links in the documentation. | +| `just check-all` | Run `package`, `lint`, `type-check`, `test`, and `docs-check`. | | `just check` | Run prek hooks on all Git-tracked files, with automatic fixes. | `just lint` and `just format` accept file or directory paths and default to the @@ -45,14 +49,75 @@ entire project. `just test`, `just mypy`, and `just pyright` forward extra argum to their tools. The type-checker aliases also have the names `just type-mypy` and `just type-pyright`. -While working, run the checks relevant to the change. Use `just format` when -formatting or lint fixes are needed, then run `just check-all` before handing off -code changes. Report the checks run and any failures or checks you could not run. +## Code verification + +Run verification commands from the repository root: + +- Tests: `just test`. +- Linting and formatting check: `just lint`. +- Formatting and automatic fixes: `just format`. +- Static type analysis: `just type-check`. +- Documentation: `just docs-check`. +- Full verification: `just check-all`. + +After changing code: + +1. Run `just format`. +2. Run the checks relevant to the changed code. +3. Run `just check-all` before committing or handing off the change. +4. Report which checks were run and whether they passed. Include any failures or + checks that could not be run. `just check` may modify files, including `uv.lock`; inspect its changes. Hooks also run when committing. After dependency changes, run `just install` and repeat -the checks. `just package` validates dependencies; use `uv build` when a task -requires building wheel and source distributions, since there is no build recipe. +the checks. Unlike `just format` and `just check`, `just check-all` is intended to +verify the project without applying fixes. `just package` validates dependencies; +use `uv build` when a task requires building wheel and source distributions, since +there is no build recipe. + +## External dependency documentation + +- When a task needs documentation for a dependency's API, behavior, or + configuration, use Context7 if its tools are available. +- Identify the dependency version in `uv.lock` and request documentation for that + version when available. Before the first lockfile is generated, use the + constraints in `pyproject.toml` and state any uncertainty about the exact version. +- Resolve the library's Context7 ID before querying its documentation, unless a + verified ID is already available. Check that examples apply to the project's + dependency version before using them. +- If Context7 is unavailable or lacks the required library or version, consult + official versioned documentation or the installed package's source and + docstrings. Context7 availability must not block development or verification. +- Use this repository's code and documentation to understand the library being + developed; an external index may lag behind local changes. + +See [Context7 setup](CONTRIBUTING.md#context7-optional) for optional client setup +and the separate process for indexing this library's published documentation. + +## Documentation rules + +A change to public behavior is incomplete until its docstrings, guides, and API +reference are updated and `just docs-check` passes. Follow the complete +[documentation guidelines](docs/pages/documentation-guidelines.rst). + +- Document every new or changed public module, class, function, method, and + attribute. Do not document private implementation details unless they explain + an important constraint. +- Use Google-style docstrings. Keep types in Python annotations instead of + repeating them in docstrings. +- Include `Args`, `Returns`, `Yields`, and `Raises` only when applicable. Explain + behavior, constraints, side effects, and exceptions rather than restating names. +- Use Sphinx roles such as `:class:`, `:func:`, `:meth:`, `:attr:`, and `:doc:` + for internal references. Prefer fully qualified targets when a reference could + be ambiguous. +- Put stable, executable examples in `.. doctest::` blocks. Use `.. code-block::` + for illustrative examples that require network access, nondeterministic values, + external services, or extensive setup. +- Add public modules and objects to `docs/pages/api-reference.rst`; add conceptual + or task-oriented documentation to the appropriate guide and to a `toctree`. +- Never edit generated files under `docs/_build/`. +- Run `just docs-check` after changing public APIs or documentation. Run + `just docs-linkcheck` when adding or changing external links. ## Dependency maintenance and cleanup diff --git a/{{cookiecutter.project_name}}/CONTRIBUTING.md b/{{cookiecutter.project_name}}/CONTRIBUTING.md new file mode 100644 index 0000000..799e460 --- /dev/null +++ b/{{cookiecutter.project_name}}/CONTRIBUTING.md @@ -0,0 +1,125 @@ +### Contributing 📦 + +#### Environment setup + +1. Install [just](https://just.systems/man/en/installation.html), + [uv](https://docs.astral.sh/uv/getting-started/installation/), Git, and Bash. +2. Clone the repository and enter its directory. For a newly generated project, run `git init`. +3. Run `just doctor` to check that the required tools are available. +4. Run `just install` to install the project, all dependency groups, and Git hooks + through [`prek`](https://github.com/j178/prek). + +Running `just install` again synchronizes the existing environment. `just reinstall` removes +`.venv`, caches, and build artifacts, then installs the project again. +Check commands do not update the environment automatically: after changing dependencies, +run `just install`. Use `just upgrade` to update dependency versions and hooks. + +Run `just` to list commands by group. + +#### Context7 (optional) + +[Context7](https://context7.com/docs/overview) lets a coding agent retrieve documentation for the project's +dependencies. Connect it in your agent or editor using the [official setup guide](https://context7.com/docs/installation). +For a manual remote MCP connection, use `https://mcp.context7.com/mcp` and follow the +[instructions for your client](https://context7.com/docs/resources/all-clients). +Keep authentication in your client's user settings or credential store. + +After connecting, reload the client or start a new session if required, and check that its Context7 tools +are available. Try a documentation request such as: + +```text +Look up pytest fixture scopes for the pytest version in uv.lock. use context7 +``` + +The project's `AGENTS.md` explains when to consult Context7 and how to fall back to official documentation +or installed sources if the needed documentation is unavailable. Context7 is an optional development aid; +the Python environment, documentation builds, tests, and CI work independently of it. + +To make this library discoverable by other agents, follow the separate +[publication steps](#publishing-documentation-to-context7) below. + +#### Contributing code + +1. Set up the development environment. +2. Create a branch from `main` and make your changes. +3. Run `just format` to apply Ruff fixes and format the code. +4. Run `just check-all` to check dependencies, code, formatting, types, tests, and documentation without + applying fixes. +5. If needed, run `just check`: this runs prek hooks on Git-tracked files and may modify files, + including `uv.lock`. These hooks also run when you commit. + After changing dependencies, repeat `just install` and `just check-all`. +6. Commit your changes and open a pull request. Pull request titles and commit messages should follow + [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/). + For example: `feat: add a model for working with MySQL`. + +Individual checks can be run independently: + +```bash +just test # All tests +just test tests/test_example.py # One test file +just test -k 'example or smoke' # Select tests by expression +just mypy tests/test_example.py # Type-check one file +just type-check # Run mypy and Pyright on the entire project +just lint tests/test_example.py # Check lint and formatting for one file +just package # Check the lockfile and installed environment +just docs # Build the HTML documentation +just docs-serve # Build and serve documentation locally +just docs-check # Build docs strictly and run documentation examples +just docs-linkcheck # Check external links in the documentation +``` + +`just lint` and `just format` accept file and directory paths; without paths they process the entire project. +`just test`, `just mypy`, and `just pyright` forward extra arguments to the corresponding tool. + +#### Documentation + +Documentation sources live in `docs/`. Run `just docs` to rebuild `docs/_build/html` locally. Before opening +a pull request that changes documentation or public APIs, run `just docs-check`. The external link check uses +the network and is intentionally kept separate from `just check-all`. + +Run `just docs-serve` to rebuild the HTML documentation and serve it at . Pass a +different port when needed, for example `just docs-serve 9000`, and press `Ctrl+C` to stop the server. + +The HTML build also generates `llms.txt` and a Markdown version of each documentation page for AI agents. +These files live alongside the HTML pages in `docs/_build/html/`; edit the documentation sources and +docstrings rather than the generated files. `just docs-check` also verifies that `llms.txt` and `index.md` +are nonempty. + +Follow the [documentation guidelines](docs/pages/documentation-guidelines.rst) when writing docstrings, +guides, API references, and executable examples. + +The project includes `.readthedocs.yml` for publishing with Read the Docs. Repository maintainers must connect +the repository to Read the Docs once before the documentation is published. + +#### Publishing documentation to Context7 + +Once the library has public documentation with meaningful usage examples, maintainers can submit it to +Context7. This project uses the published `llms.txt` as the entry point: its Markdown pages contain the +documentation after Sphinx has processed it, including content generated by `autodoc`. + +1. Run `just docs-check`, then publish the documentation with Read the Docs or another static host. +2. Verify that the public `llms.txt` URL and its linked Markdown pages are accessible. A typical Read the Docs + URL is `https://your-project.readthedocs.io/en/latest/llms.txt`; use the actual domain and version path + of your documentation site. +3. Open [Add Library](https://context7.com/add-library?tab=llmstxt), select the `llms.txt` source type, + and submit that public URL. Building or publishing `llms.txt` alone does not register the library. +4. When indexing finishes, use the library ID shown by Context7 to query a documented usage example and + check the returned content. Keep examples and API documentation up to date in the Sphinx sources. +5. After publishing documentation updates, request a refresh from the library's Context7 page when needed. + See [Keeping Libraries Fresh](https://context7.com/docs/library-updates) for refresh behavior. + +For repository-based indexing, the included [`context7.json`](context7.json) selects `docs/` and excludes +`docs/_build/`, `AGENTS.md`, `CONTRIBUTING.md`, and `documentation-guidelines.rst`. Context7 also includes +root-level Markdown files, so the library's `README.md` remains available. Extend the folder list when +adding user guides or examples outside `docs/`; `excludeFiles` entries must be filenames, not paths. +The generated title and description are included when they meet Context7's length limits +(1–100 and 10–500 characters respectively); otherwise Context7 can infer this metadata. + +To use this configuration, commit it to the public repository and submit the repository URL using the +GitHub source type on [Add Library](https://context7.com/add-library). These exclusions apply to repository +indexing; they do not change the published `llms.txt` or its Markdown pages. Prefer the published output +described above when the API reference relies on Sphinx `autodoc`. + +The file does not register the library or connect an MCP client automatically. For ownership verification, +add the actual `url` and `public_key` provided by Context7 when following the +[library owner guide](https://context7.com/docs/library-owners). diff --git a/{{cookiecutter.project_name}}/README.md b/{{cookiecutter.project_name}}/README.md index 16de6c5..ae7ce2a 100644 --- a/{{cookiecutter.project_name}}/README.md +++ b/{{cookiecutter.project_name}}/README.md @@ -13,52 +13,18 @@ print(some_function(3, 4)) # => 7 ``` -## License - -This project is licensed under {{ cookiecutter.license }}. See [LICENSE](LICENSE) for details. - -### Contributing 📦 - -#### Environment setup - -1. Install [just](https://just.systems/man/en/installation.html), - [uv](https://docs.astral.sh/uv/getting-started/installation/), Git, and Bash. -2. Clone the repository and enter its directory. For a newly generated project, run `git init`. -3. Run `just doctor` to check that the required tools are available. -4. Run `just install` to install the project, all dependency groups, and Git hooks - through [`prek`](https://github.com/j178/prek). - -Running `just install` again synchronizes the existing environment. `just reinstall` removes -`.venv`, caches, and build artifacts, then installs the project again. -Check commands do not update the environment automatically: after changing dependencies, -run `just install`. Use `just upgrade` to update dependency versions and hooks. +## Documentation -Run `just` to list commands by group. - -#### Contributing code - -1. Set up the development environment. -2. Create a branch from `main` and make your changes. -3. Run `just format` to apply Ruff fixes and format the code. -4. Run `just check-all` to check dependencies, code, formatting, types, and tests without applying fixes. -5. If needed, run `just check`: this runs prek hooks on Git-tracked files and may modify files, - including `uv.lock`. These hooks also run when you commit. - After changing dependencies, repeat `just install` and `just check-all`. -6. Commit your changes and open a pull request. Pull request titles and commit messages should follow - [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/). - For example: `feat: add a model for working with MySQL`. - -Individual checks can be run independently: +The documentation source is available in [`docs/`](docs/index.rst). Build it locally with: ```bash -just test # All tests -just test tests/test_example.py # One test file -just test -k 'example or smoke' # Select tests by expression -just mypy tests/test_example.py # Type-check one file -just type-check # Run mypy and Pyright on the entire project -just lint tests/test_example.py # Check lint and formatting for one file -just package # Check the lockfile and installed environment +just docs ``` -`just lint` and `just format` accept file and directory paths; without paths they process the entire project. -`just test`, `just mypy`, and `just pyright` forward extra arguments to the corresponding tool. +Run `just docs-check` to perform a clean, strict build and execute documentation examples. +The included `.readthedocs.yml` can be used to publish the documentation on +[Read the Docs](https://readthedocs.org/). + +## License + +This project is licensed under {{ cookiecutter.license }}. See [LICENSE](LICENSE) for details. diff --git a/{{cookiecutter.project_name}}/context7.json b/{{cookiecutter.project_name}}/context7.json new file mode 100644 index 0000000..f540b7c --- /dev/null +++ b/{{cookiecutter.project_name}}/context7.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://context7.com/schema/context7.json", +{%- if 1 <= cookiecutter.project_name|length <= 100 %} + "projectTitle": {{ cookiecutter.project_name | tojson }}, +{%- endif %} +{%- if 10 <= cookiecutter.project_description|length <= 500 %} + "description": {{ cookiecutter.project_description | tojson }}, +{%- endif %} + "folders": ["docs"], + "excludeFolders": ["docs/_build"], + "excludeFiles": [ + "AGENTS.md", + "CONTRIBUTING.md", + "documentation-guidelines.rst" + ] +} diff --git a/{{cookiecutter.project_name}}/docs/__init__.py b/{{cookiecutter.project_name}}/docs/__init__.py new file mode 100644 index 0000000..cf027ec --- /dev/null +++ b/{{cookiecutter.project_name}}/docs/__init__.py @@ -0,0 +1 @@ +"""Documentation configuration package.""" diff --git a/{{cookiecutter.project_name}}/docs/_static/custom.css b/{{cookiecutter.project_name}}/docs/_static/custom.css new file mode 100644 index 0000000..d051b5d --- /dev/null +++ b/{{cookiecutter.project_name}}/docs/_static/custom.css @@ -0,0 +1,4 @@ +html[data-accent-color="blue"] { + --accent-9: #466A91; + --accent-a9: rgb(70 106 145 / 90%); +} diff --git a/{{cookiecutter.project_name}}/docs/conf.py b/{{cookiecutter.project_name}}/docs/conf.py new file mode 100644 index 0000000..082222d --- /dev/null +++ b/{{cookiecutter.project_name}}/docs/conf.py @@ -0,0 +1,76 @@ +"""Sphinx configuration for the project documentation.""" + +from __future__ import annotations + +import doctest +import sys +import tomllib +from pathlib import Path +from typing import TYPE_CHECKING + +from docutils import nodes +from sphinx_iconify.roles import iconify_icon # type: ignore[import-untyped] + + +if TYPE_CHECKING: + from typing import NoReturn + + from sphinx.application import Sphinx + from sphinx.util.docutils import SphinxTranslator + + +_ROOT = Path(__file__).parents[1] +sys.path.insert(0, str(_ROOT)) + +_project_metadata = tomllib.loads((_ROOT / "pyproject.toml").read_text(encoding="utf-8"))["project"] + +project = str(_project_metadata["name"]) +author = "{{ cookiecutter.copyright_holder }}" +copyright = author # noqa: A001 +version = str(_project_metadata["version"]) +release = version + +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.doctest", + "sphinx.ext.napoleon", + "sphinx.ext.viewcode", + "sphinx_autodoc_typehints", + "myst_parser", + "sphinx_design", + "sphinx_copybutton", + "sphinx_contributors", + "sphinx_tabs.tabs", + "sphinx_iconify", + "sphinxcontrib.mermaid", + "sphinx_llm_friendly", +] + +exclude_patterns = ["_build"] +nitpicky = True + +autodoc_typehints = "description" +always_document_param_types = True + +napoleon_google_docstring = True +napoleon_numpy_docstring = False +napoleon_use_param = True +napoleon_use_rtype = True + +doctest_default_flags = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE + +html_theme = "shibuya" +html_theme_options = {"accent_color": "blue"} +html_static_path = ["_static"] +html_css_files = ["custom.css"] + + +def _skip_iconify(_translator: SphinxTranslator, _node: nodes.Node) -> NoReturn: + """Omit decorative icons from the generated Markdown pages.""" + raise nodes.SkipNode + + +def setup(app: Sphinx) -> dict[str, bool]: + """Register Markdown support for third-party documentation nodes.""" + app.add_node(iconify_icon, override=True, llm_markdown=(_skip_iconify, None)) + return {"parallel_read_safe": True, "parallel_write_safe": True} diff --git a/{{cookiecutter.project_name}}/docs/index.rst b/{{cookiecutter.project_name}}/docs/index.rst new file mode 100644 index 0000000..8968cdf --- /dev/null +++ b/{{cookiecutter.project_name}}/docs/index.rst @@ -0,0 +1,20 @@ +{{ cookiecutter.project_name }} +{{ "=" * cookiecutter.project_name|length }} + +{{ cookiecutter.project_description }} + +This documentation covers installation, basic usage, and the public API. + +.. toctree:: + :maxdepth: 2 + :caption: Contents + + pages/installation + pages/usage + pages/api-reference + +.. toctree:: + :maxdepth: 1 + :caption: Contributing + + pages/documentation-guidelines diff --git a/{{cookiecutter.project_name}}/docs/justfile b/{{cookiecutter.project_name}}/docs/justfile new file mode 100644 index 0000000..20c92bc --- /dev/null +++ b/{{cookiecutter.project_name}}/docs/justfile @@ -0,0 +1,29 @@ +# Commands for building and checking the Sphinx documentation + +set positional-arguments + +sphinxopts := env("SPHINXOPTS", "-W --keep-going") +sourcedir := "." +builddir := "_build" + +_default: (build 'html') + +[private] +sphinx +targets: + #!/usr/bin/env bash + set -euo pipefail + for target in {{ targets }}; do + uv run python -m sphinx -M "$target" "{{ sourcedir }}" \ + "{{ builddir }}" {{ sphinxopts }} + done + +# Build one or more Sphinx targets +build +targets='html': (sphinx targets) + +# Build HTML from scratch, run examples, and verify LLM documentation artifacts +check: (sphinx 'clean html doctest') + test -s "{{ builddir }}/html/llms.txt" + test -s "{{ builddir }}/html/index.md" + +# Check links to external resources +linkcheck: (sphinx 'clean linkcheck') diff --git a/{{cookiecutter.project_name}}/docs/pages/api-reference.rst b/{{cookiecutter.project_name}}/docs/pages/api-reference.rst new file mode 100644 index 0000000..4e66c22 --- /dev/null +++ b/{{cookiecutter.project_name}}/docs/pages/api-reference.rst @@ -0,0 +1,15 @@ +API reference +============= + +Package +------- + +.. automodule:: {{ cookiecutter.project_name.lower().replace('-', '_') }} + :members: + :show-inheritance: + +Metadata +-------- + +.. automodule:: {{ cookiecutter.project_name.lower().replace('-', '_') }}.__metadata__ + :members: diff --git a/{{cookiecutter.project_name}}/docs/pages/documentation-guidelines.rst b/{{cookiecutter.project_name}}/docs/pages/documentation-guidelines.rst new file mode 100644 index 0000000..3a2988f --- /dev/null +++ b/{{cookiecutter.project_name}}/docs/pages/documentation-guidelines.rst @@ -0,0 +1,107 @@ +Documentation guidelines +======================== + +Documentation is part of the public API. A change to public behavior is complete +only when the relevant docstrings, guides, API reference, and examples agree with +the implementation and ``just docs-check`` passes. + +Choose the right location +------------------------- + +Use each documentation layer for a distinct purpose: + +* Docstrings define the contract of a module, class, function, method, or + attribute. +* Usage guides explain tasks and connect multiple APIs into practical workflows. +* The API reference lists public objects and their signatures. +* Code comments explain non-obvious implementation decisions and constraints. + +Do not copy the same explanation into several layers. Link to the canonical +explanation instead. + +Public API docstrings +--------------------- + +Use Google-style docstrings. Keep parameter and return types in Python annotations; +Sphinx adds them to the rendered documentation. Start with a short summary, then +describe behavior or constraints that are not obvious from the signature. + +Include ``Args``, ``Returns``, ``Yields``, and ``Raises`` only when applicable. +Document side effects, accepted value ranges, exception conditions, and important +state changes. Avoid descriptions that merely repeat an identifier. + +For example: + +.. code-block:: python + + def load_config(path: Path) -> Config: + """Load configuration from a file. + + Args: + path: Configuration file to read. + + Returns: + Parsed configuration. + + Raises: + ConfigurationError: If the file cannot be read or parsed. + + Examples: + >>> config = load_config(Path("config.toml")) + >>> config.debug + False + """ + +Document every new or changed public object. Private helpers normally need no API +documentation, but their comments should capture important implementation reasons +or invariants. + +References +---------- + +Use Sphinx roles instead of plain text when referring to documented objects or +pages. The most common roles are ``:class:`target```, ``:func:`target```, +``:meth:`target```, ``:attr:`target```, and ``:doc:`target```. Use a fully +qualified target when a short name could be ambiguous. Prefix a Python target with +``~`` when the rendered label should show only its final component, for example +``:class:`~package.module.Type```. + +Keep ``nitpicky`` references valid. Do not suppress a missing-reference warning +unless the referenced object genuinely cannot be linked. + +Examples and doctests +--------------------- + +Use ``.. doctest::`` for small, deterministic examples that should be executed as +part of ``just docs-check``: + +.. doctest:: + + >>> sorted({"beta", "alpha"}) + ['alpha', 'beta'] + +Use ``.. code-block::`` when an example requires network access, external services, +nondeterministic values, secrets, or extensive setup. Keep such examples realistic +and make any omitted setup explicit. + +API and navigation updates +-------------------------- + +When adding a public module, class, or function, update +``docs/pages/api-reference.rst`` so autodoc renders it. Add new guide pages to a +``toctree``; otherwise Sphinx treats them as orphaned documents. Keep guides focused +on user tasks rather than mirroring the source tree. + +Verification +------------ + +Run these commands from the repository root: + +.. code-block:: console + + just docs + just docs-check + +The strict check builds HTML with warnings treated as errors and executes doctests. +Run ``just docs-linkcheck`` after adding or changing external links. Never edit or +commit generated files under ``docs/_build/``. diff --git a/{{cookiecutter.project_name}}/docs/pages/installation.rst b/{{cookiecutter.project_name}}/docs/pages/installation.rst new file mode 100644 index 0000000..e4405d7 --- /dev/null +++ b/{{cookiecutter.project_name}}/docs/pages/installation.rst @@ -0,0 +1,24 @@ +Installation +============ + +Install ``{{ cookiecutter.project_name }}`` from PyPI with your preferred package manager. + +.. tabs:: + + .. tab:: :iconify:`material-icon-theme:uv` uv + + .. code-block:: console + + uv add {{ cookiecutter.project_name }} + + .. tab:: :iconify:`devicon:poetry` Poetry + + .. code-block:: console + + poetry add {{ cookiecutter.project_name }} + + .. tab:: :iconify:`devicon:pypi` pip + + .. code-block:: console + + python -m pip install {{ cookiecutter.project_name }} diff --git a/{{cookiecutter.project_name}}/docs/pages/usage.rst b/{{cookiecutter.project_name}}/docs/pages/usage.rst new file mode 100644 index 0000000..69a5613 --- /dev/null +++ b/{{cookiecutter.project_name}}/docs/pages/usage.rst @@ -0,0 +1,18 @@ +Usage +===== + +Import the package using its Python module name: + +.. code-block:: python + + import {{ cookiecutter.project_name.lower().replace('-', '_') }} + + # Use the library's public API here. + +The installed package exposes its version metadata: + +.. doctest:: + + >>> from {{ cookiecutter.project_name.lower().replace('-', '_') }}.__metadata__ import __version__ + >>> isinstance(__version__, str) + True diff --git a/{{cookiecutter.project_name}}/justfile b/{{cookiecutter.project_name}}/justfile index 3c7dd3b..aae0731 100644 --- a/{{cookiecutter.project_name}}/justfile +++ b/{{cookiecutter.project_name}}/justfile @@ -15,9 +15,12 @@ alias destroy := venv-remove alias mypy := type-mypy alias pyright := type-pyright +# Documentation module +mod _docs 'docs/justfile' + # List available tasks _default: - @"$JUST_BIN" --justfile "$JUST_FILE" --list --unsorted + @"$JUST_BIN" --justfile "$JUST_FILE" --list --unsorted --list-submodules _check-git: @command -v git >/dev/null 2>&1 || { printf 'git was not found in PATH\n' >&2; exit 1; } @@ -68,7 +71,7 @@ clean: rm -rf -- \ .pytest_cache .ruff_cache .mypy_cache .hypothesis .precomcache \ build dist wheelhouse .eggs .egg \ - htmlcov .coverage coverage.xml coverage.json + docs/_build htmlcov .coverage coverage.xml coverage.json # Run mypy [group('typing')] @@ -113,6 +116,23 @@ package: _check-uv uv sync --all-groups --all-extras --locked --check uv pip check -# Check dependencies, code, formatting, types, and tests without applying fixes +# Build the HTML documentation +[group('docs')] +docs +targets='clean html': (_docs::build targets) + +# Build and serve the HTML documentation locally +[group('docs')] +docs-serve port='8000': docs + uv run python -m http.server "{{ '{{port}}' }}" --bind 127.0.0.1 --directory docs/_build/html + +# Build documentation strictly and run its doctests +[group('docs')] +docs-check: _docs::check + +# Check external links in the documentation +[group('docs')] +docs-linkcheck: _docs::linkcheck + +# Check dependencies, code, formatting, types, tests, and docs without applying fixes [group('checks')] -check-all: package lint type-check test +check-all: package lint type-check test docs-check diff --git a/{{cookiecutter.project_name}}/pyproject.toml b/{{cookiecutter.project_name}}/pyproject.toml index 35584e3..f20e2fd 100644 --- a/{{cookiecutter.project_name}}/pyproject.toml +++ b/{{cookiecutter.project_name}}/pyproject.toml @@ -14,11 +14,26 @@ dependencies = [{% if cookiecutter.type_lib == "django" %} "django>=5.2,<5.3" {% [dependency-groups] dev = [ + { include-group = "docs" }, { include-group = "lint" }, { include-group = "release" }, { include-group = "test" }, { include-group = "typing" }, ] +docs = [ + "docutils>=0.22,<0.23", + "myst-parser>=5,<6", + "shibuya>=2026.1,<2027", + "sphinx>=9,<10", + "sphinx-autodoc-typehints>=3,<4", + "sphinx-contributors>=0.2,<0.4", + "sphinx-copybutton>=0.5,<0.6", + "sphinx-design>=0.7,<0.8", + "sphinx-iconify>=0.3,<0.4", + "sphinx-llm-friendly>=0.5,<0.8", + "sphinx-tabs>=3.5,<4", + "sphinxcontrib-mermaid>=2,<3", +] test = [ "pytest>=9.1.1", "pytest-cov>=7",