diff --git a/.copier-answers.yml b/.copier-answers.yml index 1515ec2..0990c64 100644 --- a/.copier-answers.yml +++ b/.copier-answers.yml @@ -1,5 +1,5 @@ -# Changes here will be overwritten by Copier -_commit: 1.4.1 +# Changes here will be overwritten by Copier. +_commit: 1.8.4 _src_path: gh:pawamoy/copier-uv author_email: dev@pawamoy.fr author_fullname: Timothée Mazzucotelli @@ -7,7 +7,7 @@ author_username: pawamoy copyright_date: '2021' copyright_holder: Timothée Mazzucotelli copyright_holder_email: dev@pawamoy.fr -copyright_license: ISC License +copyright_license: ISC insiders: false project_description: A legacy Python handler for mkdocstrings. project_name: mkdocstrings-python (legacy) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index a502284..812789e 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,5 +1,2 @@ github: pawamoy -ko_fi: pawamoy polar: pawamoy -custom: -- https://www.paypal.me/pawamoy diff --git a/.github/ISSUE_TEMPLATE/1-bug.md b/.github/ISSUE_TEMPLATE/1-bug.md index 0df6e96..a0e35e0 100644 --- a/.github/ISSUE_TEMPLATE/1-bug.md +++ b/.github/ISSUE_TEMPLATE/1-bug.md @@ -50,7 +50,7 @@ PASTE TRACEBACK HERE redacting sensitive information. --> ```bash -python -m mkdocstrings_handlers.python.debug # | xclip -selection clipboard +python -m mkdocstrings_handlers.python._internal.debug # | xclip -selection clipboard ``` PASTE MARKDOWN OUTPUT HERE diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4675c85..d992137 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,18 +24,21 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 - - - name: Fetch all tags - run: git fetch --depth=1 --tags + uses: actions/checkout@v4 + with: + fetch-depth: 0 + fetch-tags: true - - name: Set up Python + - name: Setup Python uses: actions/setup-python@v5 with: - python-version: "3.11" + python-version: "3.12" - - name: Install uv - run: pip install uv + - name: Setup uv + uses: astral-sh/setup-uv@v5 + with: + enable-cache: true + cache-dependency-glob: pyproject.toml - name: Install dependencies run: make setup @@ -52,8 +55,16 @@ jobs: - name: Check for breaking changes in the API run: make check-api + - name: Store objects inventory for tests + uses: actions/upload-artifact@v4 + with: + name: objects.inv + path: site/objects.inv + tests: + needs: + - quality strategy: matrix: os: @@ -61,12 +72,12 @@ jobs: - macos-latest - windows-latest python-version: - - "3.8" - "3.9" - "3.10" - "3.11" - "3.12" - "3.13" + - "3.14" resolution: - highest - lowest-direct @@ -76,27 +87,38 @@ jobs: - os: windows-latest resolution: lowest-direct runs-on: ${{ matrix.os }} - continue-on-error: ${{ matrix.python-version == '3.13' }} + continue-on-error: ${{ matrix.python-version == '3.14' }} steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 + with: + fetch-depth: 0 + fetch-tags: true - - name: Set up Python + - name: Setup Python uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} allow-prereleases: true - name: Setup uv - uses: astral-sh/setup-uv@v1 + uses: astral-sh/setup-uv@v5 with: enable-cache: true + cache-dependency-glob: pyproject.toml + cache-suffix: ${{ matrix.resolution }} - name: Install dependencies env: UV_RESOLUTION: ${{ matrix.resolution }} run: make setup + - name: Download objects inventory + uses: actions/download-artifact@v4 + with: + name: objects.inv + path: site/ + - name: Run the test suite run: make test diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c1f92ec..3d8190a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -10,16 +10,19 @@ jobs: if: startsWith(github.ref, 'refs/tags/') steps: - name: Checkout - uses: actions/checkout@v3 - - name: Fetch all tags - run: git fetch --depth=1 --tags + uses: actions/checkout@v4 + with: + fetch-depth: 0 + fetch-tags: true - name: Setup Python - uses: actions/setup-python@v4 - - name: Install git-changelog - run: pip install git-changelog + uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Setup uv + uses: astral-sh/setup-uv@v5 - name: Prepare release notes - run: git-changelog --release-notes > release-notes.md + run: uv tool run git-changelog --release-notes > release-notes.md - name: Create release - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v2 with: body_path: release-notes.md diff --git a/.gitpod.dockerfile b/.gitpod.dockerfile deleted file mode 100644 index 1590b41..0000000 --- a/.gitpod.dockerfile +++ /dev/null @@ -1,6 +0,0 @@ -FROM gitpod/workspace-full -USER gitpod -ENV PIP_USER=no -RUN pip3 install pipx; \ - pipx install uv; \ - pipx ensurepath diff --git a/.gitpod.yml b/.gitpod.yml deleted file mode 100644 index 23a3c2b..0000000 --- a/.gitpod.yml +++ /dev/null @@ -1,13 +0,0 @@ -vscode: - extensions: - - ms-python.python - -image: - file: .gitpod.dockerfile - -ports: -- port: 8000 - onOpen: notify - -tasks: -- init: make setup diff --git a/CHANGELOG.md b/CHANGELOG.md index b7e8c8c..f71dd64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,31 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [0.2.7](https://github.com/mkdocstrings/python-legacy/releases/tag/0.2.7) - 2025-05-22 + +[Compare with 0.2.6](https://github.com/mkdocstrings/python-legacy/compare/0.2.6...0.2.7) + +### Bug Fixes + +- Write paths as strings, not Path instances in `sys.path.insert` commands ([d607389](https://github.com/mkdocstrings/python-legacy/commit/d6073891d05d4990f0cd064979e57d03d2de7f97) by Timothée Mazzucotelli). [Issue-mkdocstrings-766](https://github.com/mkdocstrings/mkdocstrings/issues/766) + +## [0.2.6](https://github.com/mkdocstrings/python-legacy/releases/tag/0.2.6) - 2025-03-22 + +[Compare with 0.2.5](https://github.com/mkdocstrings/python-legacy/compare/0.2.5...0.2.6) + +### Build + +- Add back sources to sdist/wheel ([94346e6](https://github.com/mkdocstrings/python-legacy/commit/94346e6a318983431120deb58022fa09d4dda0b8) by Timothée Mazzucotelli). + +## [0.2.5](https://github.com/mkdocstrings/python-legacy/releases/tag/0.2.5) - 2025-03-09 + +[Compare with 0.2.4](https://github.com/mkdocstrings/python-legacy/compare/0.2.4...0.2.5) + +### Build + +- Depend on mkdocstrings 0.28.3 ([a2317df](https://github.com/mkdocstrings/python-legacy/commit/a2317df0e27d9ae600bb04843871e3b2f7763c94) by Timothée Mazzucotelli). +- Drop support for Python 3.8 ([2907379](https://github.com/mkdocstrings/python-legacy/commit/290737942189e5f285f170f2d1bb227f82a6017c) by Timothée Mazzucotelli). + ## [0.2.4](https://github.com/mkdocstrings/python-legacy/releases/tag/0.2.4) - 2024-09-07 [Compare with 0.2.3](https://github.com/mkdocstrings/python-legacy/compare/0.2.3...0.2.4) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 255e0ee..2d46305 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -2,128 +2,79 @@ ## Our Pledge -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, caste, color, religion, or sexual -identity and orientation. +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards -Examples of behavior that contributes to a positive environment for our -community include: +Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the overall - community +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: -* The use of sexualized language or imagery, and sexual attention or advances of - any kind +* The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment -* Publishing others' private information, such as a physical or email address, - without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting +* Publishing others' private information, such as a physical or email address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at -dev@pawamoy.fr. -All complaints will be reviewed and investigated promptly and fairly. +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at dev@pawamoy.fr. All complaints will be reviewed and investigated promptly and fairly. -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. +All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning -**Community Impact**: A violation through a single incident or series of -actions. +**Community Impact**: A violation through a single incident or series of actions. -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or permanent -ban. +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. -**Consequence**: A permanent ban from any sort of public interaction within the -community. +**Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.1, available at -[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. -Community Impact Guidelines were inspired by -[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. -For answers to common questions about this code of conduct, see the FAQ at -[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at -[https://www.contributor-covenant.org/translations][translations]. +For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b85ff46..6a3551c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,7 +1,6 @@ # Contributing -Contributions are welcome, and they are greatly appreciated! -Every little bit helps, and credit will always be given. +Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. ## Environment setup @@ -14,21 +13,15 @@ cd python-legacy make setup ``` -> NOTE: -> If it fails for some reason, -> you'll need to install -> [uv](https://github.com/astral-sh/uv) -> manually. +> NOTE: If it fails for some reason, you'll need to install [uv](https://github.com/astral-sh/uv) manually. > > You can install it with: > > ```bash -> python3 -m pip install --user pipx -> pipx install uv +> curl -LsSf https://astral.sh/uv/install.sh | sh > ``` > -> Now you can try running `make setup` again, -> or simply `uv install`. +> Now you can try running `make setup` again, or simply `uv sync`. You now have the dependencies installed. @@ -36,15 +29,10 @@ Run `make help` to see all the available actions! ## Tasks -The entry-point to run commands and tasks is the `make` Python script, -located in the `scripts` directory. Try running `make` to show the available commands and tasks. -The *commands* do not need the Python dependencies to be installed, -while the *tasks* do. -The cross-platform tasks are written in Python, thanks to [duty](https://github.com/pawamoy/duty). +The entry-point to run commands and tasks is the `make` Python script, located in the `scripts` directory. Try running `make` to show the available commands and tasks. The *commands* do not need the Python dependencies to be installed, +while the *tasks* do. The cross-platform tasks are written in Python, thanks to [duty](https://github.com/pawamoy/duty). -If you work in VSCode, we provide -[an action to configure VSCode](https://pawamoy.github.io/copier-uv/work/#vscode-setup) -for the project. +If you work in VSCode, we provide [an action to configure VSCode](https://pawamoy.github.io/copier-uv/work/#vscode-setup) for the project. ## Development @@ -63,17 +51,13 @@ As usual: 1. go to http://localhost:8000 and check that everything looks good 1. follow our [commit message convention](#commit-message-convention) -If you are unsure about how to fix or ignore a warning, -just let the continuous integration fail, -and we will help you during review. +If you are unsure about how to fix or ignore a warning, just let the continuous integration fail, and we will help you during review. Don't bother updating the changelog, we will take care of this. ## Commit message convention -Commit messages must follow our convention based on the -[Angular style](https://gist.github.com/stephenparish/9941e89d80e2bc58a153#format-of-the-commit-message) -or the [Karma convention](https://karma-runner.github.io/4.0/dev/git-commit-msg.html): +Commit messages must follow our convention based on the [Angular style](https://gist.github.com/stephenparish/9941e89d80e2bc58a153#format-of-the-commit-message) or the [Karma convention](https://karma-runner.github.io/4.0/dev/git-commit-msg.html): ``` [(scope)]: Subject @@ -81,10 +65,7 @@ or the [Karma convention](https://karma-runner.github.io/4.0/dev/git-commit-msg. [Body] ``` -**Subject and body must be valid Markdown.** -Subject must have proper casing (uppercase for first letter -if it makes sense), but no dot at the end, and no punctuation -in general. +**Subject and body must be valid Markdown.** Subject must have proper casing (uppercase for first letter if it makes sense), but no dot at the end, and no punctuation in general. Scope and body are optional. Type can be: @@ -100,9 +81,7 @@ Scope and body are optional. Type can be: - `style`: A change in code style/format. - `tests`: About tests. -If you write a body, please add trailers at the end -(for example issues and PR references, or co-authors), -without relying on GitHub's flavored Markdown: +If you write a body, please add trailers at the end (for example issues and PR references, or co-authors), without relying on GitHub's flavored Markdown: ``` Body. @@ -111,16 +90,9 @@ Issue #10: https://github.com/namespace/project/issues/10 Related to PR namespace/other-project#15: https://github.com/namespace/other-project/pull/15 ``` -These "trailers" must appear at the end of the body, -without any blank lines between them. The trailer title -can contain any character except colons `:`. -We expect a full URI for each trailer, not just GitHub autolinks -(for example, full GitHub URLs for commits and issues, -not the hash or the #issue-number). +These "trailers" must appear at the end of the body, without any blank lines between them. The trailer title can contain any character except colons `:`. We expect a full URI for each trailer, not just GitHub autolinks (for example, full GitHub URLs for commits and issues, not the hash or the #issue-number). -We do not enforce a line length on commit messages summary and body, -but please avoid very long summaries, and very long lines in the body, -unless they are part of code blocks that must not be wrapped. +We do not enforce a line length on commit messages summary and body, but please avoid very long summaries, and very long lines in the body, unless they are part of code blocks that must not be wrapped. ## Pull requests guidelines @@ -145,5 +117,4 @@ And force-push: git push -f ``` -If this seems all too complicated, you can push or force-push each new commit, -and we will squash them ourselves if needed, before merging. +If this seems all too complicated, you can push or force-push each new commit, and we will squash them ourselves if needed, before merging. diff --git a/README.md b/README.md index 45b55f3..b30c8a5 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ dependencies = [ [pytkdocs](https://github.com/mkdocstrings/pytkdocs). - **Support for type annotations:** pytkdocs collects your type annotations and *mkdocstrings* uses them - to display parameters types or return types. + to display parameters types or return types. - **Recursive documentation of Python objects:** just use the module dotted-path as identifier, and you get the full module docs. You don't need to inject documentation for each class, function, etc. diff --git a/config/ruff.toml b/config/ruff.toml index 3c960bf..e2250db 100644 --- a/config/ruff.toml +++ b/config/ruff.toml @@ -1,4 +1,4 @@ -target-version = "py38" +target-version = "py39" line-length = 120 [lint] @@ -47,17 +47,24 @@ ignore = [ ] [lint.per-file-ignores] -"src/*/cli.py" = [ +"src/**/cli.py" = [ "T201", # Print statement ] "src/*/debug.py" = [ "T201", # Print statement ] +"!src/*/*.py" = [ + "D100", # Missing docstring in public module +] +"!src/**.py" = [ + "D101", # Missing docstring in public class + "D103", # Missing docstring in public function +] "scripts/*.py" = [ "INP001", # File is part of an implicit namespace package "T201", # Print statement ] -"tests/*.py" = [ +"tests/**.py" = [ "ARG005", # Unused lambda argument "FBT001", # Boolean positional arg in function definition "PLR2004", # Magic value used in comparison diff --git a/config/vscode/launch.json b/config/vscode/launch.json index b99b643..ef069aa 100644 --- a/config/vscode/launch.json +++ b/config/vscode/launch.json @@ -7,7 +7,17 @@ "request": "launch", "program": "${file}", "console": "integratedTerminal", - "justMyCode": false + "justMyCode": false, + "args": "${command:pickArgs}" + }, + { + "name": "run", + "type": "debugpy", + "request": "launch", + "module": "mkdocstrings_handlers", + "console": "integratedTerminal", + "justMyCode": false, + "args": "${command:pickArgs}" }, { "name": "docs", diff --git a/docs/.overrides/partials/comments.html b/docs/.overrides/partials/comments.html index 77924bc..d002135 100644 --- a/docs/.overrides/partials/comments.html +++ b/docs/.overrides/partials/comments.html @@ -31,7 +31,7 @@

Feedback

: "light" // Instruct Giscus to set theme - giscus.setAttribute("data-theme", theme) + giscus.setAttribute("data-theme", theme) } // Register event handlers after documented loaded diff --git a/docs/.overrides/partials/path-item.html b/docs/.overrides/partials/path-item.html new file mode 100644 index 0000000..a9c9544 --- /dev/null +++ b/docs/.overrides/partials/path-item.html @@ -0,0 +1,22 @@ +{# Fix breadcrumbs for when mkdocs-section-index is used. #} +{# See https://github.com/squidfunk/mkdocs-material/issues/7614. #} + + +{% macro render_content(nav_item) %} + + {{ nav_item.title }} + +{% endmacro %} + + +{% macro render(nav_item, ref=nav_item) %} + {% if nav_item.is_page %} +
  • + + {{ render_content(ref) }} + +
  • + {% elif nav_item.children %} + {{ render(nav_item.children | first, ref) }} + {% endif %} +{% endmacro %} diff --git a/docs/changelog.md b/docs/changelog.md index 786b75d..0536cbb 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -1 +1,5 @@ +--- +title: Changelog +--- + --8<-- "CHANGELOG.md" diff --git a/docs/code_of_conduct.md b/docs/code_of_conduct.md index 01f2ea2..002b2a0 100644 --- a/docs/code_of_conduct.md +++ b/docs/code_of_conduct.md @@ -1 +1,5 @@ +--- +title: Code of Conduct +--- + --8<-- "CODE_OF_CONDUCT.md" diff --git a/docs/contributing.md b/docs/contributing.md index ea38c9b..61935e5 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -1 +1,5 @@ +--- +title: Contributing +--- + --8<-- "CONTRIBUTING.md" diff --git a/docs/credits.md b/docs/credits.md index f758db8..f6ab1aa 100644 --- a/docs/credits.md +++ b/docs/credits.md @@ -1,10 +1,9 @@ --- +title: Credits hide: - toc --- - ```python exec="yes" --8<-- "scripts/gen_credits.py" ``` - diff --git a/docs/css/mkdocstrings.css b/docs/css/mkdocstrings.css index 88c7357..7d66153 100644 --- a/docs/css/mkdocstrings.css +++ b/docs/css/mkdocstrings.css @@ -24,4 +24,49 @@ a.autorefs-external::after { a.external:hover::after, a.autorefs-external:hover::after { background-color: var(--md-accent-fg-color); -} \ No newline at end of file +} + +/* Tree-like output for backlinks. */ +.doc-backlink-list { + --tree-clr: var(--md-default-fg-color); + --tree-font-size: 1rem; + --tree-item-height: 1; + --tree-offset: 1rem; + --tree-thickness: 1px; + --tree-style: solid; + display: grid; + list-style: none !important; +} + +.doc-backlink-list li > span:first-child { + text-indent: .3rem; +} +.doc-backlink-list li { + padding-inline-start: var(--tree-offset); + border-left: var(--tree-thickness) var(--tree-style) var(--tree-clr); + position: relative; + margin-left: 0 !important; + + &:last-child { + border-color: transparent; + } + &::before{ + content: ''; + position: absolute; + top: calc(var(--tree-item-height) / 2 * -1 * var(--tree-font-size) + var(--tree-thickness)); + left: calc(var(--tree-thickness) * -1); + width: calc(var(--tree-offset) + var(--tree-thickness) * 2); + height: calc(var(--tree-item-height) * var(--tree-font-size)); + border-left: var(--tree-thickness) var(--tree-style) var(--tree-clr); + border-bottom: var(--tree-thickness) var(--tree-style) var(--tree-clr); + } + &::after{ + content: ''; + position: absolute; + border-radius: 50%; + background-color: var(--tree-clr); + top: calc(var(--tree-item-height) / 2 * 1rem); + left: var(--tree-offset) ; + translate: calc(var(--tree-thickness) * -1) calc(var(--tree-thickness) * -1); + } +} diff --git a/docs/index.md b/docs/index.md index 8e6f2fb..82377e2 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,4 +1,5 @@ --- +title: Overview hide: - feedback --- diff --git a/docs/license.md b/docs/license.md index e81c0ed..5b25a00 100644 --- a/docs/license.md +++ b/docs/license.md @@ -1,4 +1,5 @@ --- +title: License hide: - feedback --- diff --git a/docs/reference.md b/docs/reference.md deleted file mode 100644 index 56b8add..0000000 --- a/docs/reference.md +++ /dev/null @@ -1,4 +0,0 @@ -::: mkdocstrings_handlers.python - options: - show_root_full_path: true - diff --git a/docs/reference/api.md b/docs/reference/api.md new file mode 100644 index 0000000..79f6b8b --- /dev/null +++ b/docs/reference/api.md @@ -0,0 +1,9 @@ +--- +title: API reference +hide: +- navigation +--- + +# ::: mkdocstrings_handlers.python + options: + show_root_full_path: true diff --git a/duties.py b/duties.py index 77df74e..cd4b8b4 100644 --- a/duties.py +++ b/duties.py @@ -3,15 +3,18 @@ from __future__ import annotations import os +import re import sys from contextlib import contextmanager from importlib.metadata import version as pkgversion from pathlib import Path -from typing import TYPE_CHECKING, Iterator +from typing import TYPE_CHECKING from duty import duty, tools if TYPE_CHECKING: + from collections.abc import Iterator + from duty.context import Context @@ -24,7 +27,7 @@ MULTIRUN = os.environ.get("MULTIRUN", "0") == "1" -def pyprefix(title: str) -> str: # noqa: D103 +def pyprefix(title: str) -> str: if MULTIRUN: prefix = f"(python{sys.version_info.major}.{sys.version_info.minor})" return f"{prefix:14}{title}" @@ -32,7 +35,7 @@ def pyprefix(title: str) -> str: # noqa: D103 @contextmanager -def material_insiders() -> Iterator[bool]: # noqa: D103 +def material_insiders() -> Iterator[bool]: if "+insiders" in pkgversion("mkdocs-material"): os.environ["MATERIAL_INSIDERS"] = "true" try: @@ -43,6 +46,12 @@ def material_insiders() -> Iterator[bool]: # noqa: D103 yield False +def _get_changelog_version() -> str: + changelog_version_re = re.compile(r"^## \[(\d+\.\d+\.\d+)\].*$") + with Path(__file__).parent.joinpath("CHANGELOG.md").open("r", encoding="utf8") as file: + return next(filter(bool, map(changelog_version_re.match, file))).group(1) # type: ignore[union-attr] + + @duty def changelog(ctx: Context, bump: str = "") -> None: """Update the changelog in-place with latest commits. @@ -51,6 +60,7 @@ def changelog(ctx: Context, bump: str = "") -> None: bump: Bump option passed to git-changelog. """ ctx.run(tools.git_changelog(bump=bump or None), title="Updating changelog") + ctx.run(tools.yore.check(bump=bump or _get_changelog_version()), title="Checking legacy code") @duty(pre=["check-quality", "check-types", "check-docs", "check-api"]) @@ -83,6 +93,7 @@ def check_docs(ctx: Context) -> None: def check_types(ctx: Context) -> None: """Check that the code is correctly typed.""" os.environ["MYPYPATH"] = "src" + os.environ["FORCE_COLOR"] = "1" ctx.run( tools.mypy(*PY_SRC_LIST, config_file="config/mypy.ini"), title=pyprefix("Type-checking"), diff --git a/mkdocs.yml b/mkdocs.yml index c7f77d7..f84f95d 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -20,7 +20,7 @@ nav: - Changelog: changelog.md - Credits: credits.md - License: license.md -- API reference: reference.md +- API reference: reference/api.md - Development: - Contributing: contributing.md - Code of Conduct: code_of_conduct.md @@ -40,7 +40,8 @@ theme: - content.code.copy - content.tooltips - navigation.footer - - navigation.indexes + - navigation.instant.preview + - navigation.path - navigation.sections - navigation.tabs - navigation.tabs.sticky @@ -100,7 +101,9 @@ markdown_extensions: plugins: - search +- autorefs - markdown-exec +- section-index - coverage - mkdocstrings: handlers: @@ -111,6 +114,9 @@ plugins: - https://mkdocstrings.github.io/pytkdocs/objects.inv paths: [src, docs] options: + backlinks: tree + docstring_options: + ignore_init_summary: true docstring_section_style: list filters: ["!^_"] group_by_category: true @@ -126,6 +132,13 @@ plugins: show_submodules: false signature_crossrefs: true summary: true +- llmstxt: + full_output: llms-full.txt + sections: + Usage: + - index.md + API: + - reference/api.md - git-revision-date-localized: enabled: !ENV [DEPLOY, false] enable_creation_date: true diff --git a/pyproject.toml b/pyproject.toml index 7143e8c..72197d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,9 +6,10 @@ build-backend = "pdm.backend" name = "mkdocstrings-python-legacy" description = "A legacy Python handler for mkdocstrings." authors = [{name = "Timothée Mazzucotelli", email = "dev@pawamoy.fr"}] -license = {text = "ISC"} +license = "ISC" +license-files = ["LICENSE"] readme = "README.md" -requires-python = ">=3.8" +requires-python = ">=3.9" keywords = [] dynamic = ["version"] classifiers = [ @@ -17,19 +18,19 @@ classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", "Topic :: Documentation", "Topic :: Software Development", "Topic :: Utilities", "Typing :: Typed", ] dependencies = [ - "mkdocstrings>=0.19", + "mkdocstrings>=0.28.3", "mkdocs-autorefs>=1.1", "pytkdocs>=0.14", ] @@ -44,14 +45,14 @@ Discussions = "https://github.com/mkdocstrings/python-legacy/discussions" Gitter = "https://gitter.im/mkdocstrings/python-legacy" Funding = "https://github.com/sponsors/pawamoy" -[tool.pdm] -version = {source = "scm"} +[tool.pdm.version] +source = "call" +getter = "scripts.get_version:get_version" [tool.pdm.build] -package-dir = "src" -editable-backend = "editables" includes = ["src/mkdocstrings_handlers"] -excludes = ["**/.pytest_cache"] +# Include as much as possible in the source distribution, to help redistributors. +excludes = ["**/.pytest_cache", "**/.mypy_cache"] source-includes = [ "config", "docs", @@ -65,23 +66,23 @@ source-includes = [ ] [tool.pdm.build.wheel-data] +# Manual pages can be included in the wheel. +# Depending on the installation tool, they will be accessible to users. +# pipx supports it, uv does not yet, see https://github.com/astral-sh/uv/issues/4731. data = [ {path = "share/**/*", relative-to = "."}, ] -[tool.uv] -dev-dependencies = [ - # dev - "editables>=0.5", - - # maintenance +[dependency-groups] +maintain = [ "build>=1.2", "git-changelog>=2.5", - "twine>=5.0; python_version < '3.13'", - - # ci - "duty>=1.4", - "griffe>=1.2", + "twine>=5.1", + "yore>=0.3.3", +] +ci = [ + "duty>=1.6", + "griffe>=1.6", "ruff>=0.4", "pytest>=8.2", "pytest-cov>=5.0", @@ -90,15 +91,20 @@ dev-dependencies = [ "mypy>=1.10", "types-markdown>=3.6", "types-pyyaml>=6.0", - - # docs - "black>=24.4", +] + docs = [ "markdown-callouts>=0.4", "markdown-exec>=1.8", "mkdocs>=1.6", "mkdocs-coverage>=1.0", "mkdocs-git-revision-date-localized-plugin>=1.2", + "mkdocs-llmstxt>=0.2", "mkdocs-material>=9.5", "mkdocs-minify-plugin>=0.8", + "mkdocs-section-index>=0.3", + # YORE: EOL 3.10: Remove line. "tomli>=2.0; python_version < '3.11'", -] \ No newline at end of file +] + +[tool.uv] +default-groups = ["maintain", "ci", "docs"] diff --git a/scripts/gen_credits.py b/scripts/gen_credits.py index 0e2e165..69c3f2a 100644 --- a/scripts/gen_credits.py +++ b/scripts/gen_credits.py @@ -1,21 +1,22 @@ -"""Script to generate the project's credits.""" +# Script to generate the project's credits. from __future__ import annotations import os import sys from collections import defaultdict +from collections.abc import Iterable from importlib.metadata import distributions from itertools import chain from pathlib import Path from textwrap import dedent -from typing import Dict, Iterable, Union +from typing import Union from jinja2 import StrictUndefined from jinja2.sandbox import SandboxedEnvironment from packaging.requirements import Requirement -# TODO: Remove once support for Python 3.10 is dropped. +# YORE: EOL 3.10: Replace block with line 2. if sys.version_info >= (3, 11): import tomllib else: @@ -26,10 +27,10 @@ pyproject = tomllib.load(pyproject_file) project = pyproject["project"] project_name = project["name"] -devdeps = [dep for dep in pyproject["tool"]["uv"]["dev-dependencies"] if not dep.startswith("-e")] +devdeps = [dep for group in pyproject["dependency-groups"].values() for dep in group if not dep.startswith("-e")] -PackageMetadata = Dict[str, Union[str, Iterable[str]]] -Metadata = Dict[str, PackageMetadata] +PackageMetadata = dict[str, Union[str, Iterable[str]]] +Metadata = dict[str, PackageMetadata] def _merge_fields(metadata: dict) -> PackageMetadata: diff --git a/scripts/get_version.py b/scripts/get_version.py new file mode 100644 index 0000000..6734e5b --- /dev/null +++ b/scripts/get_version.py @@ -0,0 +1,26 @@ +# Get current project version from Git tags or changelog. + +import re +from contextlib import suppress +from pathlib import Path + +from pdm.backend.hooks.version import SCMVersion, Version, default_version_formatter, get_version_from_scm + +_root = Path(__file__).parent.parent +_changelog = _root / "CHANGELOG.md" +_changelog_version_re = re.compile(r"^## \[(\d+\.\d+\.\d+)\].*$") +_default_scm_version = SCMVersion(Version("0.0.0"), None, False, None, None) # noqa: FBT003 + + +def get_version() -> str: + scm_version = get_version_from_scm(_root) or _default_scm_version + if scm_version.version <= Version("0.1"): # Missing Git tags? + with suppress(OSError, StopIteration): # noqa: SIM117 + with _changelog.open("r", encoding="utf8") as file: + match = next(filter(None, map(_changelog_version_re.match, file))) + scm_version = scm_version._replace(version=Version(match.group(1))) + return default_version_formatter(scm_version) + + +if __name__ == "__main__": + print(get_version()) diff --git a/scripts/make b/scripts/make deleted file mode 100755 index c41840f..0000000 --- a/scripts/make +++ /dev/null @@ -1,176 +0,0 @@ -#!/usr/bin/env python3 -"""Management commands.""" - -from __future__ import annotations - -import os -import shutil -import subprocess -import sys -from contextlib import contextmanager -from pathlib import Path -from typing import Any, Iterator - -PYTHON_VERSIONS = os.getenv("PYTHON_VERSIONS", "3.8 3.9 3.10 3.11 3.12 3.13").split() - - -def shell(cmd: str, capture_output: bool = False, **kwargs: Any) -> str | None: - """Run a shell command.""" - if capture_output: - return subprocess.check_output(cmd, shell=True, text=True, **kwargs) # noqa: S602 - subprocess.run(cmd, shell=True, check=True, stderr=subprocess.STDOUT, **kwargs) # noqa: S602 - return None - - -@contextmanager -def environ(**kwargs: str) -> Iterator[None]: - """Temporarily set environment variables.""" - original = dict(os.environ) - os.environ.update(kwargs) - try: - yield - finally: - os.environ.clear() - os.environ.update(original) - - -def uv_install(venv: Path) -> None: - """Install dependencies using uv.""" - with environ(UV_PROJECT_ENVIRONMENT=str(venv)): - shell("uv sync") - - -def setup() -> None: - """Setup the project.""" - if not shutil.which("uv"): - raise ValueError("make: setup: uv must be installed, see https://github.com/astral-sh/uv") - - print("Installing dependencies (default environment)") # noqa: T201 - default_venv = Path(".venv") - if not default_venv.exists(): - shell("uv venv --python python") - uv_install(default_venv) - - if PYTHON_VERSIONS: - for version in PYTHON_VERSIONS: - print(f"\nInstalling dependencies (python{version})") # noqa: T201 - venv_path = Path(f".venvs/{version}") - if not venv_path.exists(): - shell(f"uv venv --python {version} {venv_path}") - with environ(UV_PROJECT_ENVIRONMENT=str(venv_path.resolve())): - uv_install(venv_path) - - -def run(version: str, cmd: str, *args: str, **kwargs: Any) -> None: - """Run a command in a virtual environment.""" - kwargs = {"check": True, **kwargs} - if version == "default": - with environ(UV_PROJECT_ENVIRONMENT=".venv"): - subprocess.run(["uv", "run", cmd, *args], **kwargs) # noqa: S603, PLW1510 - else: - with environ(UV_PROJECT_ENVIRONMENT=f".venvs/{version}", MULTIRUN="1"): - subprocess.run(["uv", "run", cmd, *args], **kwargs) # noqa: S603, PLW1510 - - -def multirun(cmd: str, *args: str, **kwargs: Any) -> None: - """Run a command for all configured Python versions.""" - if PYTHON_VERSIONS: - for version in PYTHON_VERSIONS: - run(version, cmd, *args, **kwargs) - else: - run("default", cmd, *args, **kwargs) - - -def allrun(cmd: str, *args: str, **kwargs: Any) -> None: - """Run a command in all virtual environments.""" - run("default", cmd, *args, **kwargs) - if PYTHON_VERSIONS: - multirun(cmd, *args, **kwargs) - - -def clean() -> None: - """Delete build artifacts and cache files.""" - paths_to_clean = ["build", "dist", "htmlcov", "site", ".coverage*", ".pdm-build"] - for path in paths_to_clean: - shell(f"rm -rf {path}") - - cache_dirs = {".cache", ".pytest_cache", ".mypy_cache", ".ruff_cache", "__pycache__"} - for dirpath in Path(".").rglob("*/"): - if dirpath.parts[0] not in (".venv", ".venvs") and dirpath.name in cache_dirs: - shutil.rmtree(dirpath, ignore_errors=True) - - -def vscode() -> None: - """Configure VSCode to work on this project.""" - Path(".vscode").mkdir(parents=True, exist_ok=True) - shell("cp -v config/vscode/* .vscode") - - -def main() -> int: - """Main entry point.""" - args = list(sys.argv[1:]) - if not args or args[0] == "help": - if len(args) > 1: - run("default", "duty", "--help", args[1]) - else: - print("Available commands") # noqa: T201 - print(" help Print this help. Add task name to print help.") # noqa: T201 - print(" setup Setup all virtual environments (install dependencies).") # noqa: T201 - print(" run Run a command in the default virtual environment.") # noqa: T201 - print(" multirun Run a command for all configured Python versions.") # noqa: T201 - print(" allrun Run a command in all virtual environments.") # noqa: T201 - print(" 3.x Run a command in the virtual environment for Python 3.x.") # noqa: T201 - print(" clean Delete build artifacts and cache files.") # noqa: T201 - print(" vscode Configure VSCode to work on this project.") # noqa: T201 - if os.path.exists(".venv"): - print("\nAvailable tasks") # noqa: T201 - run("default", "duty", "--list") - return 0 - - while args: - cmd = args.pop(0) - - if cmd == "run": - run("default", *args) - return 0 - - if cmd == "multirun": - multirun(*args) - return 0 - - if cmd == "allrun": - allrun(*args) - return 0 - - if cmd.startswith("3."): - run(cmd, *args) - return 0 - - opts = [] - while args and (args[0].startswith("-") or "=" in args[0]): - opts.append(args.pop(0)) - - if cmd == "clean": - clean() - elif cmd == "setup": - setup() - elif cmd == "vscode": - vscode() - elif cmd == "check": - multirun("duty", "check-quality", "check-types", "check-docs") - run("default", "duty", "check-api") - elif cmd in {"check-quality", "check-docs", "check-types", "test"}: - multirun("duty", cmd, *opts) - else: - run("default", "duty", cmd, *opts) - - return 0 - - -if __name__ == "__main__": - try: - sys.exit(main()) - except subprocess.CalledProcessError as process: - if process.output: - print(process.output, file=sys.stderr) # noqa: T201 - sys.exit(process.returncode) diff --git a/scripts/make b/scripts/make new file mode 120000 index 0000000..c2eda0d --- /dev/null +++ b/scripts/make @@ -0,0 +1 @@ +make.py \ No newline at end of file diff --git a/scripts/make.py b/scripts/make.py new file mode 100755 index 0000000..55679ba --- /dev/null +++ b/scripts/make.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +from contextlib import contextmanager +from pathlib import Path +from textwrap import dedent +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Iterator + + +PYTHON_VERSIONS = os.getenv("PYTHON_VERSIONS", "3.9 3.10 3.11 3.12 3.13 3.14").split() + + +def shell(cmd: str, *, capture_output: bool = False, **kwargs: Any) -> str | None: + """Run a shell command.""" + if capture_output: + return subprocess.check_output(cmd, shell=True, text=True, **kwargs) # noqa: S602 + subprocess.run(cmd, shell=True, check=True, stderr=subprocess.STDOUT, **kwargs) # noqa: S602 + return None + + +@contextmanager +def environ(**kwargs: str) -> Iterator[None]: + """Temporarily set environment variables.""" + original = dict(os.environ) + os.environ.update(kwargs) + try: + yield + finally: + os.environ.clear() + os.environ.update(original) + + +def uv_install(venv: Path) -> None: + """Install dependencies using uv.""" + with environ(UV_PROJECT_ENVIRONMENT=str(venv), PYO3_USE_ABI3_FORWARD_COMPATIBILITY="1"): + if "CI" in os.environ: + shell("uv sync --no-editable") + else: + shell("uv sync") + + +def setup() -> None: + """Setup the project.""" + if not shutil.which("uv"): + raise ValueError("make: setup: uv must be installed, see https://github.com/astral-sh/uv") + + print("Installing dependencies (default environment)") + default_venv = Path(".venv") + if not default_venv.exists(): + shell("uv venv") + uv_install(default_venv) + + if PYTHON_VERSIONS: + for version in PYTHON_VERSIONS: + print(f"\nInstalling dependencies (python{version})") + venv_path = Path(f".venvs/{version}") + if not venv_path.exists(): + shell(f"uv venv --python {version} {venv_path}") + with environ(UV_PROJECT_ENVIRONMENT=str(venv_path.resolve())): + uv_install(venv_path) + + +def run(version: str, cmd: str, *args: str, **kwargs: Any) -> None: + """Run a command in a virtual environment.""" + kwargs = {"check": True, **kwargs} + uv_run = ["uv", "run", "--no-sync"] + if version == "default": + with environ(UV_PROJECT_ENVIRONMENT=".venv"): + subprocess.run([*uv_run, cmd, *args], **kwargs) # noqa: S603, PLW1510 + else: + with environ(UV_PROJECT_ENVIRONMENT=f".venvs/{version}", MULTIRUN="1"): + subprocess.run([*uv_run, cmd, *args], **kwargs) # noqa: S603, PLW1510 + + +def multirun(cmd: str, *args: str, **kwargs: Any) -> None: + """Run a command for all configured Python versions.""" + if PYTHON_VERSIONS: + for version in PYTHON_VERSIONS: + run(version, cmd, *args, **kwargs) + else: + run("default", cmd, *args, **kwargs) + + +def allrun(cmd: str, *args: str, **kwargs: Any) -> None: + """Run a command in all virtual environments.""" + run("default", cmd, *args, **kwargs) + if PYTHON_VERSIONS: + multirun(cmd, *args, **kwargs) + + +def clean() -> None: + """Delete build artifacts and cache files.""" + paths_to_clean = ["build", "dist", "htmlcov", "site", ".coverage*", ".pdm-build"] + for path in paths_to_clean: + shutil.rmtree(path, ignore_errors=True) + + cache_dirs = {".cache", ".pytest_cache", ".mypy_cache", ".ruff_cache", "__pycache__"} + for dirpath in Path(".").rglob("*/"): + if dirpath.parts[0] not in (".venv", ".venvs") and dirpath.name in cache_dirs: + shutil.rmtree(dirpath, ignore_errors=True) + + +def vscode() -> None: + """Configure VSCode to work on this project.""" + shutil.copytree("config/vscode", ".vscode", dirs_exist_ok=True) + + +def main() -> int: + """Main entry point.""" + args = list(sys.argv[1:]) + if not args or args[0] == "help": + if len(args) > 1: + run("default", "duty", "--help", args[1]) + else: + print( + dedent( + """ + Available commands + help Print this help. Add task name to print help. + setup Setup all virtual environments (install dependencies). + run Run a command in the default virtual environment. + multirun Run a command for all configured Python versions. + allrun Run a command in all virtual environments. + 3.x Run a command in the virtual environment for Python 3.x. + clean Delete build artifacts and cache files. + vscode Configure VSCode to work on this project. + """, + ), + flush=True, + ) + if os.path.exists(".venv"): + print("\nAvailable tasks", flush=True) + run("default", "duty", "--list") + return 0 + + while args: + cmd = args.pop(0) + + if cmd == "run": + run("default", *args) + return 0 + + if cmd == "multirun": + multirun(*args) + return 0 + + if cmd == "allrun": + allrun(*args) + return 0 + + if cmd.startswith("3."): + run(cmd, *args) + return 0 + + opts = [] + while args and (args[0].startswith("-") or "=" in args[0]): + opts.append(args.pop(0)) + + if cmd == "clean": + clean() + elif cmd == "setup": + setup() + elif cmd == "vscode": + vscode() + elif cmd == "check": + multirun("duty", "check-quality", "check-types", "check-docs") + run("default", "duty", "check-api") + elif cmd in {"check-quality", "check-docs", "check-types", "test"}: + multirun("duty", cmd, *opts) + else: + run("default", "duty", cmd, *opts) + + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main()) + except subprocess.CalledProcessError as process: + if process.output: + print(process.output, file=sys.stderr) + sys.exit(process.returncode) diff --git a/src/mkdocstrings_handlers/_internal/__init__.py b/src/mkdocstrings_handlers/_internal/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/mkdocstrings_handlers/_internal/debug.py b/src/mkdocstrings_handlers/_internal/debug.py new file mode 100644 index 0000000..e6c8834 --- /dev/null +++ b/src/mkdocstrings_handlers/_internal/debug.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import os +import platform +import sys +from dataclasses import dataclass +from importlib import metadata + + +@dataclass +class _Variable: + """Dataclass describing an environment variable.""" + + name: str + """Variable name.""" + value: str + """Variable value.""" + + +@dataclass +class _Package: + """Dataclass describing a Python package.""" + + name: str + """Package name.""" + version: str + """Package version.""" + + +@dataclass +class _Environment: + """Dataclass to store environment information.""" + + interpreter_name: str + """Python interpreter name.""" + interpreter_version: str + """Python interpreter version.""" + interpreter_path: str + """Path to Python executable.""" + platform: str + """Operating System.""" + packages: list[_Package] + """Installed packages.""" + variables: list[_Variable] + """Environment variables.""" + + +def _interpreter_name_version() -> tuple[str, str]: + if hasattr(sys, "implementation"): + impl = sys.implementation.version + version = f"{impl.major}.{impl.minor}.{impl.micro}" + kind = impl.releaselevel + if kind != "final": + version += kind[0] + str(impl.serial) + return sys.implementation.name, version + return "", "0.0.0" + + +def _get_version(dist: str = "mkdocstrings-python-legacy") -> str: + """Get version of the given distribution. + + Parameters: + dist: A distribution name. + + Returns: + A version number. + """ + try: + return metadata.version(dist) + except metadata.PackageNotFoundError: + return "0.0.0" + + +def _get_debug_info() -> _Environment: + """Get debug/environment information. + + Returns: + Environment information. + """ + py_name, py_version = _interpreter_name_version() + packages = ["mkdocstrings-python-legacy"] + variables = ["PYTHONPATH", *[var for var in os.environ if var.startswith("MKDOCSTRINGS_PYTHON_LEGACY")]] + return _Environment( + interpreter_name=py_name, + interpreter_version=py_version, + interpreter_path=sys.executable, + platform=platform.platform(), + variables=[_Variable(var, val) for var in variables if (val := os.getenv(var))], + packages=[_Package(pkg, _get_version(pkg)) for pkg in packages], + ) + + +def _print_debug_info() -> None: + """Print debug/environment information.""" + info = _get_debug_info() + print(f"- __System__: {info.platform}") + print(f"- __Python__: {info.interpreter_name} {info.interpreter_version} ({info.interpreter_path})") + print("- __Environment variables__:") + for var in info.variables: + print(f" - `{var.name}`: `{var.value}`") + print("- __Installed packages__:") + for pkg in info.packages: + print(f" - `{pkg.name}` v{pkg.version}") + + +if __name__ == "__main__": + _print_debug_info() diff --git a/src/mkdocstrings_handlers/python/debug.py b/src/mkdocstrings_handlers/python/debug.py index 81e2e50..f744da6 100644 --- a/src/mkdocstrings_handlers/python/debug.py +++ b/src/mkdocstrings_handlers/python/debug.py @@ -5,7 +5,6 @@ import sys from dataclasses import dataclass from importlib import metadata -from typing import List, Tuple @dataclass @@ -38,13 +37,13 @@ class Environment: """Python interpreter version.""" platform: str """Operating System.""" - packages: List[Package] + packages: list[Package] """Installed packages.""" - variables: List[Variable] + variables: list[Variable] """Environment variables.""" -def _interpreter_name_version() -> Tuple[str, str]: +def _interpreter_name_version() -> tuple[str, str]: if hasattr(sys, "implementation"): impl = sys.implementation.version version = f"{impl.major}.{impl.minor}.{impl.micro}" diff --git a/src/mkdocstrings_handlers/python/handler.py b/src/mkdocstrings_handlers/python/handler.py index 994f4d7..1366894 100644 --- a/src/mkdocstrings_handlers/python/handler.py +++ b/src/mkdocstrings_handlers/python/handler.py @@ -8,15 +8,15 @@ import posixpath import sys import traceback -from collections import ChainMap +from collections.abc import Iterator, Mapping, MutableMapping +from copy import deepcopy +from pathlib import Path from subprocess import PIPE, Popen -from typing import Any, BinaryIO, ClassVar, Iterator, List, Mapping, MutableMapping, Optional, Tuple +from typing import Any, BinaryIO, ClassVar, Optional -from markdown import Markdown -from mkdocstrings.extension import PluginError -from mkdocstrings.handlers.base import BaseHandler, CollectionError, CollectorItem -from mkdocstrings.inventory import Inventory -from mkdocstrings.loggers import get_logger +from mkdocs.config.defaults import MkDocsConfig +from mkdocs.exceptions import PluginError +from mkdocstrings import BaseHandler, CollectionError, CollectorItem, Inventory, get_logger from mkdocstrings_handlers.python.rendering import ( do_brief_xref, @@ -32,22 +32,21 @@ class PythonHandler(BaseHandler): - """The Python handler class. + """The Python handler class.""" - Attributes: - domain: The cross-documentation domain/language for this handler. - enable_inventory: Whether this handler is interested in enabling the creation - of the `objects.inv` Sphinx inventory file. - """ - - domain: str = "py" # to match Sphinx's default domain - enable_inventory: bool = True + name: ClassVar[str] = "python" + """The handler name.""" + domain: ClassVar[str] = "py" # to match Sphinx's default domain + """The domain of the handler.""" + enable_inventory: ClassVar[bool] = True + """Whether the handler supports inventory files.""" - fallback_theme = "material" + fallback_theme: ClassVar[str] = "material" + """The fallback theme to use when the user-selected theme is not supported.""" fallback_config: ClassVar[dict] = {"docstring_style": "markdown", "filters": ["!.*"]} """The configuration used when falling back to re-collecting an object to get its anchor. - This configuration is used in [`Handlers.get_anchors`][mkdocstrings.handlers.base.Handlers.get_anchors]. + This configuration is used in [`Handlers.get_anchors`][mkdocstrings.Handlers.get_anchors]. When trying to fix (optional) cross-references, the autorefs plugin will try to collect an object with every configured handler until one succeeds. It will then try to get @@ -116,14 +115,7 @@ class PythonHandler(BaseHandler): - `show_source` (`bool`): Show the source code of this object. Default: `True`. """ - def __init__( - self, - *args: Any, - setup_commands: Optional[List[str]] = None, - config_file_path: Optional[str] = None, - paths: Optional[List[str]] = None, - **kwargs: Any, - ) -> None: + def __init__(self, config: dict[str, Any], base_dir: Path, **kwargs: Any) -> None: """Initialize the handler. When instantiating a Python handler, we open a `pytkdocs` subprocess in the background with `subprocess.Popen`. @@ -132,24 +124,27 @@ def __init__( too resource intensive, and would slow down `mkdocstrings` a lot. Parameters: - *args: Handler name, theme and custom templates. - setup_commands: A list of python commands as strings to be executed in the subprocess before `pytkdocs`. - config_file_path: The MkDocs configuration file path. - paths: A list of paths to use as search paths. - **kwargs: Same thing, but with keyword arguments. + config: The handler configuration. + base_dir: The base directory of the project. + **kwargs: Arguments passed to the parent constructor. """ + super().__init__(**kwargs) + + self.base_dir = base_dir + self.config = config + self.global_options = config.get("options", {}) + logger.debug("Opening 'pytkdocs' subprocess") env = os.environ.copy() env["PYTHONUNBUFFERED"] = "1" - self._config_file_path = config_file_path - paths = paths or [] - if not paths and config_file_path: - paths.append(os.path.dirname(config_file_path)) + paths = config.get("paths") or [] + if not paths and self.base_dir: + paths.append(self.base_dir) search_paths = [] for path in paths: - if not os.path.isabs(path) and config_file_path: - path = os.path.abspath(os.path.join(os.path.dirname(config_file_path), path)) # noqa: PLW2901 + if not os.path.isabs(path) and self.base_dir: + path = os.path.abspath(os.path.join(self.base_dir, path)) # noqa: PLW2901 if path not in search_paths: search_paths.append(path) self._paths = search_paths @@ -157,9 +152,9 @@ def __init__( commands = [] if search_paths: - commands.extend([f"sys.path.insert(0, {path!r})" for path in reversed(search_paths)]) + commands.extend([f"sys.path.insert(0, {str(path)!r})" for path in reversed(search_paths)]) - if setup_commands: + if setup_commands := config.get("setup_commands"): # prevent the Python interpreter or the setup commands # from writing to stdout as it would break pytkdocs output commands.extend( @@ -191,7 +186,13 @@ def __init__( bufsize=-1, env=env, ) - super().__init__(*args, **kwargs) + + def get_inventory_urls(self) -> list[tuple[str, dict[str, Any]]]: + """Return the URLs of the inventory files to download.""" + return [ + (inv.pop("url"), inv) if isinstance(inv, dict) else (inv, {}) + for inv in deepcopy(self.config.get("import", [])) + ] @classmethod def load_inventory( @@ -200,7 +201,7 @@ def load_inventory( url: str, base_url: Optional[str] = None, **kwargs: Any, # noqa: ARG003 - ) -> Iterator[Tuple[str, str]]: + ) -> Iterator[tuple[str, str]]: """Yield items and their URLs from an inventory file streamed from `in_file`. This implements mkdocstrings' `load_inventory` "protocol" (see plugin.py). @@ -220,7 +221,20 @@ def load_inventory( for item in Inventory.parse_sphinx(in_file, domain_filter=("py",)).values(): yield item.name, posixpath.join(base_url, item.uri) - def collect(self, identifier: str, config: MutableMapping[str, Any]) -> CollectorItem: + def get_options(self, local_options: Mapping[str, Any]) -> MutableMapping[str, Any]: + """Return the options to use to collect an object. + + We merge the global options with the options specific to the object being collected. + + Arguments: + local_options: The selection options. + + Returns: + The options to use to collect an object. + """ + return {**self.default_config, **self.global_options, **local_options} + + def collect(self, identifier: str, options: MutableMapping[str, Any]) -> CollectorItem: """Collect the documentation tree given an identifier and selection options. In this method, we feed one line of JSON to the standard input of the subprocess that was opened @@ -242,7 +256,7 @@ def collect(self, identifier: str, config: MutableMapping[str, Any]) -> Collecto Arguments: identifier: The dotted-path of a Python object available in the Python path. - config: Selection options, used to alter the data collection done by `pytkdocs`. + options: Selection options, used to alter the data collection done by `pytkdocs`. Raises: CollectionError: When there was a problem collecting the object documentation. @@ -250,15 +264,13 @@ def collect(self, identifier: str, config: MutableMapping[str, Any]) -> Collecto Returns: The collected object-tree. """ - final_config = {} + pytkdocs_options = {} for option in ("filters", "members", "docstring_style", "docstring_options"): - if option in config: - final_config[option] = config[option] - elif option in self.default_config: - final_config[option] = self.default_config[option] + if option in options: + pytkdocs_options[option] = options[option] logger.debug("Preparing input") - json_input = json.dumps({"objects": [{"path": identifier, **final_config}]}) + json_input = json.dumps({"objects": [{"path": identifier, **pytkdocs_options}]}) logger.debug("Writing to process' stdin") self.process.stdin.write(json_input + "\n") # type: ignore[union-attr] @@ -300,17 +312,16 @@ def teardown(self) -> None: logger.debug("Tearing process down") self.process.terminate() - def render(self, data: CollectorItem, config: Mapping[str, Any]) -> str: # noqa: D102 (ignore missing docstring) - final_config = ChainMap(config, self.default_config) # type: ignore[arg-type] - + def render(self, data: CollectorItem, options: MutableMapping[str, Any]) -> str: + """Render the collected data into HTML.""" template = self.env.get_template(f"{data['category']}.html") # Heading level is a "state" variable, that will change at each step # of the rendering recursion. Therefore, it's easier to use it as a plain value # than as an item in a dictionary. - heading_level = final_config["heading_level"] - members_order = final_config["members_order"] + heading_level = options["heading_level"] + members_order = options["members_order"] if members_order == "alphabetical": sort_function = sort_key_alphabetical elif members_order == "source": @@ -321,17 +332,18 @@ def render(self, data: CollectorItem, config: Mapping[str, Any]) -> str: # noqa sort_object(data, sort_function=sort_function) return template.render( - **{"config": final_config, data["category"]: data, "heading_level": heading_level, "root": True}, + **{"config": options, data["category"]: data, "heading_level": heading_level, "root": True}, ) - def get_anchors(self, data: CollectorItem) -> Tuple[str, ...]: # noqa: D102 (ignore missing docstring) + def get_aliases(self, identifier: str) -> tuple[str, ...]: + """Return the aliases of an identifier.""" try: + data = self.collect(identifier, self.fallback_config) return (data["path"],) - except KeyError: + except (CollectionError, KeyError): return () - def update_env(self, md: Markdown, config: dict) -> None: # noqa: D102 (ignore missing docstring) - super().update_env(md, config) + def update_env(self, config: dict) -> None: # noqa: ARG002,D102 self.env.trim_blocks = True self.env.lstrip_blocks = True self.env.keep_trailing_newline = False @@ -339,31 +351,18 @@ def update_env(self, md: Markdown, config: dict) -> None: # noqa: D102 (ignore def get_handler( - theme: str, - custom_templates: Optional[str] = None, - setup_commands: Optional[List[str]] = None, - config_file_path: Optional[str] = None, - paths: Optional[List[str]] = None, - **config: Any, # noqa: ARG001 + handler_config: MutableMapping[str, Any], + tool_config: MkDocsConfig, + **kwargs: Any, ) -> PythonHandler: """Simply return an instance of `PythonHandler`. Arguments: - theme: The theme to use when rendering contents. - custom_templates: Directory containing custom templates. - setup_commands: A list of commands as strings to be executed in the subprocess before `pytkdocs`. - config_file_path: The MkDocs configuration file path. - paths: A list of paths to use as search paths. - config: Configuration passed to the handler. + handler_config: The handler configuration. + tool_config: The tool (SSG) configuration. Returns: An instance of `PythonHandler`. """ - return PythonHandler( - handler="python", - theme=theme, - custom_templates=custom_templates, - setup_commands=setup_commands, - config_file_path=config_file_path, - paths=paths, - ) + base_dir = Path(tool_config.config_file_path or "./mkdocs.yml").parent + return PythonHandler(config=dict(handler_config), base_dir=base_dir, **kwargs) diff --git a/src/mkdocstrings_handlers/python/rendering.py b/src/mkdocstrings_handlers/python/rendering.py index 0efef7b..fb9be46 100644 --- a/src/mkdocstrings_handlers/python/rendering.py +++ b/src/mkdocstrings_handlers/python/rendering.py @@ -4,8 +4,7 @@ from typing import Any, Callable from markupsafe import Markup -from mkdocstrings.handlers.base import CollectorItem -from mkdocstrings.loggers import get_logger +from mkdocstrings import CollectorItem, get_logger log = get_logger(__name__) diff --git a/tests/conftest.py b/tests/conftest.py index de476be..6c9ca65 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -3,17 +3,17 @@ from __future__ import annotations from collections import ChainMap -from typing import TYPE_CHECKING, Iterator +from typing import TYPE_CHECKING import pytest from markdown.core import Markdown from mkdocs.config.defaults import MkDocsConfig if TYPE_CHECKING: + from collections.abc import Iterator from pathlib import Path - from mkdocstrings.extension import MkdocstringsExtension - from mkdocstrings.plugin import MkdocstringsPlugin + from mkdocstrings import MkdocstringsExtension, MkdocstringsPlugin @pytest.fixture(name="mkdocs_conf") diff --git a/tests/test_collector.py b/tests/test_collector.py index 012f464..cc7c3c2 100644 --- a/tests/test_collector.py +++ b/tests/test_collector.py @@ -3,11 +3,15 @@ from unittest import mock import pytest -from mkdocstrings.handlers.base import CollectionError +from mkdocstrings import CollectionError from mkdocstrings_handlers.python import get_handler +class _FakeMkDocsConfig: + config_file_path = "mkdocs.yml" + + @pytest.mark.parametrize( ("retval", "exp_res"), [ @@ -26,6 +30,6 @@ def test_collect_result_error(retval: dict, exp_res: str) -> None: with mock.patch("mkdocstrings_handlers.python.handler.json.loads") as m_loads: # noqa: SIM117 with pytest.raises(CollectionError) as excinfo: # noqa: PT012 m_loads.return_value = retval - handler = get_handler("material") + handler = get_handler({}, _FakeMkDocsConfig, theme="material") # type: ignore[arg-type] assert handler.collect("", {}) assert str(excinfo.value) == exp_res diff --git a/tests/test_themes.py b/tests/test_themes.py index b2f7d27..bfd9b78 100644 --- a/tests/test_themes.py +++ b/tests/test_themes.py @@ -7,7 +7,7 @@ import pytest if TYPE_CHECKING: - from mkdocstrings.plugin import MkdocstringsPlugin + from mkdocstrings import MkdocstringsPlugin @pytest.mark.parametrize( @@ -39,6 +39,7 @@ def test_render_themes_templates(module: str, plugin: MkdocstringsPlugin) -> Non plugin: The plugin instance (parametrized fixture). """ handler = plugin.handlers.get_handler("python") - handler._update_env(plugin.md, plugin.handlers._config) # type: ignore[attr-defined] - data = handler.collect(module, {}) - handler.render(data, {}) + handler._update_env(plugin.md, config=plugin.handlers._tool_config) # type: ignore[attr-defined] + options = handler.get_options({}) + data = handler.collect(module, options) + handler.render(data, options)