docstring-generator 2.0.1__tar.gz → 2.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: docstring-generator
3
- Version: 2.0.1
3
+ Version: 2.1.0
4
4
  Summary: Auto generate docstring from type-hints.
5
5
  Author: FelixTheC
6
6
  Project-URL: Repository, https://github.com/FelixTheC/docstring_generator
@@ -12,10 +12,11 @@ Classifier: Typing :: Typed
12
12
  Requires-Python: >=3.13
13
13
  Description-Content-Type: text/markdown
14
14
  Requires-Dist: click==8.4.2
15
- Requires-Dist: docstring-generator-ext==2.0.2
15
+ Requires-Dist: docstring-generator-ext>=2.0.4
16
16
 
17
17
  [![Python 3.10](https://img.shields.io/badge/python-3-blue.svg)](https://www.python.org/downloads/)
18
18
  [![PyPI version](https://badge.fury.io/py/docstring-generator.svg)](https://badge.fury.io/py/docstring-generator)
19
+ ![Actions](https://github.com/FelixTheC/docstring_generator/actions/workflows/python-app.yml/badge.svg)
19
20
  [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
20
21
  [![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json)](https://github.com/astral-sh/uv)
21
22
  [![](https://img.shields.io/pypi/dm/docstring-generator.svg)](https://pypi.org/project/docstring-generator/)
@@ -39,6 +40,9 @@ Good documentation is no longer optional. AI coding assistants, static analysis
39
40
  - ✍️ **Preserving your words** — existing descriptions and custom notes are never overwritten
40
41
  - 🧠 **AI-workflow friendly** — well-structured docstrings improve context quality for LLM-assisted development
41
42
  - 🚨 **Exception-aware** — automatically detects `raise` statements and documents them in a `Raises` section, so failure modes are part of your API contract
43
+ - 🙈 **Convention-correct** — `self` and `cls` are automatically excluded from generated parameter sections, matching every major docstring standard
44
+ - ⚙️ **Async-ready** — handles both `def` and `async def` functions transparently, no extra configuration needed
45
+ - 🎨 **Style-safe** — detects the existing docstring style and refuses to silently mix conventions; explicit opt-in required to convert styles
42
46
  - 🏎️ **Blazing fast** — core engine written in C++ via [pybind11](https://github.com/FelixTheC/docstring_generator_ext)
43
47
 
44
48
  ---
@@ -102,6 +106,81 @@ gendocs_new mydir/ --check --threshold 80
102
106
 
103
107
  Useful in CI pipelines to enforce documentation standards across the codebase.
104
108
 
109
+ ### `--exclude-file` — Skip specific files
110
+
111
+ Exclude one or more files from processing by name. Can be passed multiple times:
112
+
113
+ ```shell
114
+ gendocs_new mydir/ --exclude-file conftest.py --exclude-file settings.py
115
+ ```
116
+
117
+ Files whose name matches any of the provided values are skipped during docstring generation.
118
+
119
+ ### `--exclude-dir` — Skip specific directories
120
+
121
+ Exclude one or more directories from processing. Can be passed multiple times:
122
+
123
+ ```shell
124
+ gendocs_new mydir/ --exclude-dir tests --exclude-dir migrations
125
+ ```
126
+
127
+ Any file whose path contains one of the given directory names is skipped.
128
+
129
+ ### `--dry-run` — Preview changes without modifying any file
130
+
131
+ Run the generator in read-only mode and see exactly what would be added or changed as a unified diff:
132
+
133
+ ```shell
134
+ gendocs_new mydir/ --dry-run
135
+ ```
136
+
137
+ Files that already have complete docstrings print `<file>: no changes`. Files with missing docstrings show a `+`/`-` diff so you can review before committing. Combine with `--style` or `--overwrite-style` to preview a style migration:
138
+
139
+ ```shell
140
+ gendocs_new mydir/ --style google --overwrite-style --dry-run
141
+ ```
142
+
143
+ ### `--changed-only` — Only process git-changed files
144
+
145
+ Restrict processing to files that are modified or staged in git — perfect for large repos where running on the full `src/` directory on every commit would be slow:
146
+
147
+ ```shell
148
+ gendocs_new mydir/ --changed-only
149
+ ```
150
+
151
+ Internally runs `git diff --name-only HEAD` and `git diff --cached --name-only` to collect the list of changed and staged `.py` files, then intersects that list with the paths you provided. If git is not installed or not available on `PATH`, the command aborts immediately with a clear error message rather than silently processing everything.
152
+
153
+ Combines well with `--dry-run` to preview what *would* change for only the files you touched:
154
+
155
+ ```shell
156
+ gendocs_new mydir/ --changed-only --dry-run
157
+ ```
158
+
159
+ ### `--ignore-magic` — Skip dunder / magic methods
160
+
161
+ Exclude dunder methods such as `__init__`, `__str__`, `__repr__`, `__eq__`, etc. from docstring generation. These are often implementation details that add noise rather than value to public documentation:
162
+
163
+ ```shell
164
+ gendocs_new mydir/ --ignore-magic
165
+ ```
166
+
167
+ Can also be enabled permanently via `pyproject.toml` so every invocation skips magic methods without an explicit flag:
168
+
169
+ ```toml
170
+ [tool.docstring_generator]
171
+ ignore_magic = true
172
+ ```
173
+
174
+ ### `--overwrite-style` — Re-format existing docstrings in a different style
175
+
176
+ Force regeneration of existing docstrings using the specified style, even if they already have content:
177
+
178
+ ```shell
179
+ gendocs_new mydir/ --style google --overwrite-style true
180
+ ```
181
+
182
+ Useful when migrating a codebase from one docstring convention to another.
183
+
105
184
  ---
106
185
 
107
186
  ## Configuration via `pyproject.toml`
@@ -112,6 +191,9 @@ Instead of passing flags on every invocation, persist defaults in your project's
112
191
  [tool.docstring_generator]
113
192
  strict = true
114
193
  threshold = 90
194
+ exclude_files = ["conftest.py", "settings.py"]
195
+ exclude_dirs = ["tests", "migrations"]
196
+ ignore_magic = true
115
197
  ```
116
198
 
117
199
  CLI flags always override `pyproject.toml` values. The tool automatically walks up from the target path to find the nearest `pyproject.toml`.
@@ -161,6 +243,37 @@ def foo(val_a: int, val_b: List[int]):
161
243
 
162
244
  ---
163
245
 
246
+ ## Preserve Return Description with `>>` Marker
247
+
248
+ Use `>>` on its own line inside an existing docstring to provide a description for the return value. On the next `gendocs_new` run the marker is consumed and wired into the `Returns` section automatically.
249
+
250
+ ```python
251
+ def square(x: int) -> int:
252
+ """Square a number.
253
+
254
+ >> The squared value of x.
255
+ """
256
+ return x * x
257
+ ```
258
+
259
+ After running `gendocs_new` (Google style):
260
+
261
+ ```python
262
+ def square(x: int) -> int:
263
+ """Square a number.
264
+
265
+ Args:
266
+ x (int):
267
+ Returns:
268
+ int: The squared value of x.
269
+ """
270
+ return x * x
271
+ ```
272
+
273
+ Combine `$N` for parameter descriptions and `>>` for the return description to fully annotate a function before running the generator — no manual editing of the structured sections needed.
274
+
275
+ ---
276
+
164
277
  ## Automatic `Raises` Extraction
165
278
 
166
279
  `docstring_generator` statically analyzes your function body for `raise` statements and adds a `Raises` section describing each exception — including the condition that triggers it. This works seamlessly with frameworks like **Pydantic**, **FastAPI**, or any custom validation logic.
@@ -196,7 +309,6 @@ class PluginConfig(BaseModel):
196
309
  """
197
310
  Parameters
198
311
  ----------
199
- cls : [Argument]
200
312
  values : dict [Argument]
201
313
 
202
314
  Returns
@@ -298,13 +410,13 @@ Ready-to-run examples are available in the [`examples/`](examples/) directory.
298
410
  pip install docstring-generator
299
411
  ```
300
412
 
301
- Requires Python 3.10+.
413
+ Requires Python 3.13+.
302
414
 
303
415
  ---
304
416
 
305
417
  ## How It Works
306
418
 
307
- The core engine is implemented in C++ and exposed to Python via [pybind11](https://github.com/pybind/pybind11), delivering performance that scales to large codebases without slowing down your workflow.
419
+ The core engine is implemented in C++ (C++20) and exposed to Python via [pybind11](https://github.com/pybind/pybind11), delivering performance that scales to large codebases without slowing down your workflow.
308
420
 
309
421
  - **Extension:** [docstring-generator-ext](https://github.com/FelixTheC/docstring_generator_ext) — the high-performance backbone of this project
310
422
 
@@ -314,15 +426,20 @@ The core engine is implemented in C++ and exposed to Python via [pybind11](https
314
426
 
315
427
  Planned features and areas of investment:
316
428
 
317
- - [x] Pre-commit hook integration for automatic docstring enforcement
318
- - [x] Return type documentation generation
319
- - [x] Raises documentation generation
320
- - [x] Docstring coverage reporting (`--check`, `--strict`, `--threshold`)
321
- - [x] `pyproject.toml` configuration support
322
- - [ ] add `>>` as placeholder for additional return description like `$1`
429
+ ### Medium-term
430
+
431
+ - [ ] GitHub Action — publish a ready-to-use Action to the Marketplace so teams can enforce docstring coverage in CI without any local installation
432
+ - [ ] Coverage badge generation (`--badge`) — produce an SVG badge from `--check` results to embed in README, similar to a test-coverage badge
433
+ - [ ] JUnit/SARIF output for `--check` — emit machine-readable results for GitHub, GitLab, and Azure DevOps CI panels; enables PR annotations that highlight undocumented functions inline
323
434
  - [ ] IDE plugin support (JetBrains, VS Code)
435
+
436
+ ### Longer-term
437
+
438
+ - [ ] Watch mode (`--watch`) — monitor the project for file saves and regenerate docstrings automatically in the background
439
+ - [ ] Sphinx / mkdocs bridge (`--export-rst`) — generate `.rst` or `.md` stubs ready for Sphinx/mkdocs autodoc pipelines
440
+ - [ ] Custom docstring templates — let teams define their own format via `pyproject.toml` for internal style guides that extend NumPy or Google
441
+ - [ ] LLM-assisted description generation (opt-in enrichment mode) — use a local or remote LLM to fill in meaningful parameter descriptions beyond the type hint
324
442
  - [ ] CI/CD pipeline gate (fail build below coverage threshold)
325
- - [ ] LLM-assisted description generation (opt-in enrichment mode)
326
443
 
327
444
  Community feedback shapes priorities — open an issue to vote on features or suggest new ones.
328
445
 
@@ -1,5 +1,6 @@
1
1
  [![Python 3.10](https://img.shields.io/badge/python-3-blue.svg)](https://www.python.org/downloads/)
2
2
  [![PyPI version](https://badge.fury.io/py/docstring-generator.svg)](https://badge.fury.io/py/docstring-generator)
3
+ ![Actions](https://github.com/FelixTheC/docstring_generator/actions/workflows/python-app.yml/badge.svg)
3
4
  [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
4
5
  [![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json)](https://github.com/astral-sh/uv)
5
6
  [![](https://img.shields.io/pypi/dm/docstring-generator.svg)](https://pypi.org/project/docstring-generator/)
@@ -23,6 +24,9 @@ Good documentation is no longer optional. AI coding assistants, static analysis
23
24
  - ✍️ **Preserving your words** — existing descriptions and custom notes are never overwritten
24
25
  - 🧠 **AI-workflow friendly** — well-structured docstrings improve context quality for LLM-assisted development
25
26
  - 🚨 **Exception-aware** — automatically detects `raise` statements and documents them in a `Raises` section, so failure modes are part of your API contract
27
+ - 🙈 **Convention-correct** — `self` and `cls` are automatically excluded from generated parameter sections, matching every major docstring standard
28
+ - ⚙️ **Async-ready** — handles both `def` and `async def` functions transparently, no extra configuration needed
29
+ - 🎨 **Style-safe** — detects the existing docstring style and refuses to silently mix conventions; explicit opt-in required to convert styles
26
30
  - 🏎️ **Blazing fast** — core engine written in C++ via [pybind11](https://github.com/FelixTheC/docstring_generator_ext)
27
31
 
28
32
  ---
@@ -86,6 +90,81 @@ gendocs_new mydir/ --check --threshold 80
86
90
 
87
91
  Useful in CI pipelines to enforce documentation standards across the codebase.
88
92
 
93
+ ### `--exclude-file` — Skip specific files
94
+
95
+ Exclude one or more files from processing by name. Can be passed multiple times:
96
+
97
+ ```shell
98
+ gendocs_new mydir/ --exclude-file conftest.py --exclude-file settings.py
99
+ ```
100
+
101
+ Files whose name matches any of the provided values are skipped during docstring generation.
102
+
103
+ ### `--exclude-dir` — Skip specific directories
104
+
105
+ Exclude one or more directories from processing. Can be passed multiple times:
106
+
107
+ ```shell
108
+ gendocs_new mydir/ --exclude-dir tests --exclude-dir migrations
109
+ ```
110
+
111
+ Any file whose path contains one of the given directory names is skipped.
112
+
113
+ ### `--dry-run` — Preview changes without modifying any file
114
+
115
+ Run the generator in read-only mode and see exactly what would be added or changed as a unified diff:
116
+
117
+ ```shell
118
+ gendocs_new mydir/ --dry-run
119
+ ```
120
+
121
+ Files that already have complete docstrings print `<file>: no changes`. Files with missing docstrings show a `+`/`-` diff so you can review before committing. Combine with `--style` or `--overwrite-style` to preview a style migration:
122
+
123
+ ```shell
124
+ gendocs_new mydir/ --style google --overwrite-style --dry-run
125
+ ```
126
+
127
+ ### `--changed-only` — Only process git-changed files
128
+
129
+ Restrict processing to files that are modified or staged in git — perfect for large repos where running on the full `src/` directory on every commit would be slow:
130
+
131
+ ```shell
132
+ gendocs_new mydir/ --changed-only
133
+ ```
134
+
135
+ Internally runs `git diff --name-only HEAD` and `git diff --cached --name-only` to collect the list of changed and staged `.py` files, then intersects that list with the paths you provided. If git is not installed or not available on `PATH`, the command aborts immediately with a clear error message rather than silently processing everything.
136
+
137
+ Combines well with `--dry-run` to preview what *would* change for only the files you touched:
138
+
139
+ ```shell
140
+ gendocs_new mydir/ --changed-only --dry-run
141
+ ```
142
+
143
+ ### `--ignore-magic` — Skip dunder / magic methods
144
+
145
+ Exclude dunder methods such as `__init__`, `__str__`, `__repr__`, `__eq__`, etc. from docstring generation. These are often implementation details that add noise rather than value to public documentation:
146
+
147
+ ```shell
148
+ gendocs_new mydir/ --ignore-magic
149
+ ```
150
+
151
+ Can also be enabled permanently via `pyproject.toml` so every invocation skips magic methods without an explicit flag:
152
+
153
+ ```toml
154
+ [tool.docstring_generator]
155
+ ignore_magic = true
156
+ ```
157
+
158
+ ### `--overwrite-style` — Re-format existing docstrings in a different style
159
+
160
+ Force regeneration of existing docstrings using the specified style, even if they already have content:
161
+
162
+ ```shell
163
+ gendocs_new mydir/ --style google --overwrite-style true
164
+ ```
165
+
166
+ Useful when migrating a codebase from one docstring convention to another.
167
+
89
168
  ---
90
169
 
91
170
  ## Configuration via `pyproject.toml`
@@ -96,6 +175,9 @@ Instead of passing flags on every invocation, persist defaults in your project's
96
175
  [tool.docstring_generator]
97
176
  strict = true
98
177
  threshold = 90
178
+ exclude_files = ["conftest.py", "settings.py"]
179
+ exclude_dirs = ["tests", "migrations"]
180
+ ignore_magic = true
99
181
  ```
100
182
 
101
183
  CLI flags always override `pyproject.toml` values. The tool automatically walks up from the target path to find the nearest `pyproject.toml`.
@@ -145,6 +227,37 @@ def foo(val_a: int, val_b: List[int]):
145
227
 
146
228
  ---
147
229
 
230
+ ## Preserve Return Description with `>>` Marker
231
+
232
+ Use `>>` on its own line inside an existing docstring to provide a description for the return value. On the next `gendocs_new` run the marker is consumed and wired into the `Returns` section automatically.
233
+
234
+ ```python
235
+ def square(x: int) -> int:
236
+ """Square a number.
237
+
238
+ >> The squared value of x.
239
+ """
240
+ return x * x
241
+ ```
242
+
243
+ After running `gendocs_new` (Google style):
244
+
245
+ ```python
246
+ def square(x: int) -> int:
247
+ """Square a number.
248
+
249
+ Args:
250
+ x (int):
251
+ Returns:
252
+ int: The squared value of x.
253
+ """
254
+ return x * x
255
+ ```
256
+
257
+ Combine `$N` for parameter descriptions and `>>` for the return description to fully annotate a function before running the generator — no manual editing of the structured sections needed.
258
+
259
+ ---
260
+
148
261
  ## Automatic `Raises` Extraction
149
262
 
150
263
  `docstring_generator` statically analyzes your function body for `raise` statements and adds a `Raises` section describing each exception — including the condition that triggers it. This works seamlessly with frameworks like **Pydantic**, **FastAPI**, or any custom validation logic.
@@ -180,7 +293,6 @@ class PluginConfig(BaseModel):
180
293
  """
181
294
  Parameters
182
295
  ----------
183
- cls : [Argument]
184
296
  values : dict [Argument]
185
297
 
186
298
  Returns
@@ -282,13 +394,13 @@ Ready-to-run examples are available in the [`examples/`](examples/) directory.
282
394
  pip install docstring-generator
283
395
  ```
284
396
 
285
- Requires Python 3.10+.
397
+ Requires Python 3.13+.
286
398
 
287
399
  ---
288
400
 
289
401
  ## How It Works
290
402
 
291
- The core engine is implemented in C++ and exposed to Python via [pybind11](https://github.com/pybind/pybind11), delivering performance that scales to large codebases without slowing down your workflow.
403
+ The core engine is implemented in C++ (C++20) and exposed to Python via [pybind11](https://github.com/pybind/pybind11), delivering performance that scales to large codebases without slowing down your workflow.
292
404
 
293
405
  - **Extension:** [docstring-generator-ext](https://github.com/FelixTheC/docstring_generator_ext) — the high-performance backbone of this project
294
406
 
@@ -298,15 +410,20 @@ The core engine is implemented in C++ and exposed to Python via [pybind11](https
298
410
 
299
411
  Planned features and areas of investment:
300
412
 
301
- - [x] Pre-commit hook integration for automatic docstring enforcement
302
- - [x] Return type documentation generation
303
- - [x] Raises documentation generation
304
- - [x] Docstring coverage reporting (`--check`, `--strict`, `--threshold`)
305
- - [x] `pyproject.toml` configuration support
306
- - [ ] add `>>` as placeholder for additional return description like `$1`
413
+ ### Medium-term
414
+
415
+ - [ ] GitHub Action — publish a ready-to-use Action to the Marketplace so teams can enforce docstring coverage in CI without any local installation
416
+ - [ ] Coverage badge generation (`--badge`) — produce an SVG badge from `--check` results to embed in README, similar to a test-coverage badge
417
+ - [ ] JUnit/SARIF output for `--check` — emit machine-readable results for GitHub, GitLab, and Azure DevOps CI panels; enables PR annotations that highlight undocumented functions inline
307
418
  - [ ] IDE plugin support (JetBrains, VS Code)
419
+
420
+ ### Longer-term
421
+
422
+ - [ ] Watch mode (`--watch`) — monitor the project for file saves and regenerate docstrings automatically in the background
423
+ - [ ] Sphinx / mkdocs bridge (`--export-rst`) — generate `.rst` or `.md` stubs ready for Sphinx/mkdocs autodoc pipelines
424
+ - [ ] Custom docstring templates — let teams define their own format via `pyproject.toml` for internal style guides that extend NumPy or Google
425
+ - [ ] LLM-assisted description generation (opt-in enrichment mode) — use a local or remote LLM to fill in meaningful parameter descriptions beyond the type hint
308
426
  - [ ] CI/CD pipeline gate (fail build below coverage threshold)
309
- - [ ] LLM-assisted description generation (opt-in enrichment mode)
310
427
 
311
428
  Community feedback shapes priorities — open an issue to vote on features or suggest new ones.
312
429
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "docstring-generator"
3
- version = "2.0.1"
3
+ version = "2.1.0"
4
4
  description = "Auto generate docstring from type-hints."
5
5
  authors = [
6
6
  { name = "FelixTheC" },
@@ -18,7 +18,7 @@ classifiers=[
18
18
 
19
19
  dependencies = [
20
20
  "click == 8.4.2",
21
- "docstring-generator-ext==2.0.2",
21
+ "docstring-generator-ext>=2.0.4",
22
22
  ]
23
23
 
24
24
  [dependency-groups]
@@ -0,0 +1,220 @@
1
+ import difflib
2
+ import pathlib
3
+ import shutil
4
+ import subprocess
5
+ import tempfile
6
+
7
+ import click
8
+ import docstring_generator_ext
9
+ import tomllib # type: ignore
10
+
11
+ from docstring_generator.output import print_results
12
+
13
+ STYLE_MAP = {
14
+ "rest": docstring_generator_ext.DocstringFormatStyle.reST,
15
+ "google": docstring_generator_ext.DocstringFormatStyle.GOOGLE,
16
+ "numpy": docstring_generator_ext.DocstringFormatStyle.NUMPY,
17
+ }
18
+
19
+
20
+ def find_pyproject_toml(start_paths: tuple[str, ...]) -> pathlib.Path | None:
21
+ """
22
+ Walks up parent directories from the target files/directories
23
+ to discover the project root's pyproject.toml.
24
+ """
25
+ # Fallback to current working directory if no paths passed
26
+ base_path = (
27
+ pathlib.Path(start_paths[0]).absolute() if start_paths else pathlib.Path.cwd().absolute()
28
+ )
29
+
30
+ # If the base path is a file, start searching from its parent folder
31
+ search_dir = base_path.parent if base_path.is_file() else base_path
32
+
33
+ for parent in [search_dir] + list(search_dir.parents):
34
+ potential_toml = parent / "pyproject.toml"
35
+ if potential_toml.exists():
36
+ return potential_toml
37
+
38
+ return None
39
+
40
+
41
+ def load_toml_config(config_path: pathlib.Path | None) -> dict:
42
+ """Finds and parses configuration options from pyproject.toml."""
43
+ if not config_path or not config_path.exists():
44
+ return {}
45
+
46
+ with config_path.open("rb") as fp:
47
+ toml_data = tomllib.load(fp)
48
+ # Extract options from your custom namespace: [tool.docstring_generator]
49
+ return toml_data.get("tool", {}).get("docstring_generator", {})
50
+
51
+
52
+ @click.command()
53
+ @click.argument("paths", nargs=-1, required=True)
54
+ @click.option(
55
+ "--style", default="numpy", help="Docstring style [numpy, rest, google].", show_default=True
56
+ )
57
+ @click.option("--check", is_flag=True, help="Get an overview on the docstrings coverage.")
58
+ @click.option(
59
+ "--strict",
60
+ is_flag=True,
61
+ help="Strict mode: Treats partial docstrings as missing/failed documentation.",
62
+ )
63
+ @click.option(
64
+ "--threshold",
65
+ type=click.IntRange(0, 100),
66
+ default=None,
67
+ help="Minimum required coverage percentage (0-100) to pass the check.",
68
+ )
69
+ @click.option("--exclude-file", type=str, multiple=True)
70
+ @click.option("--exclude-dir", type=str, multiple=True)
71
+ @click.option("--overwrite-style", is_flag=True, help="Overwrite existing docstrings.")
72
+ @click.option(
73
+ "--ignore-magic", is_flag=True, help="Ignore dunder methods like `__init__`, `__str__`, etc."
74
+ )
75
+ @click.option(
76
+ "--dry-run",
77
+ is_flag=True,
78
+ help="Preview changes as a unified diff without modifying any file.",
79
+ )
80
+ @click.option(
81
+ "--changed-only",
82
+ is_flag=True,
83
+ help="Only process files changed or staged in git. Aborts if git is not available.",
84
+ )
85
+ def main(
86
+ paths: tuple[str, ...],
87
+ style: str,
88
+ check: bool,
89
+ strict: bool,
90
+ threshold: int | None,
91
+ exclude_file: list[str],
92
+ exclude_dir: list[str],
93
+ overwrite_style: bool,
94
+ dry_run: bool,
95
+ ignore_magic: bool,
96
+ changed_only: bool,
97
+ ) -> None:
98
+ docstring_style = STYLE_MAP[style]
99
+
100
+ config = load_toml_config(find_pyproject_toml(paths))
101
+ _strict = strict or config.get("strict", False)
102
+ _threshold = threshold or config.get("threshold", 100)
103
+ _exclude_files = config.get("exclude_files", [])
104
+ _exclude_dirs = config.get("exclude_dirs", [])
105
+ _ignore_magic = config.get("ignore_magic", [])
106
+
107
+ # CLI args always wins
108
+ if exclude_file:
109
+ _exclude_files = exclude_file
110
+ if exclude_dir:
111
+ _exclude_dirs = exclude_dir
112
+ if ignore_magic:
113
+ _ignore_magic = ignore_magic
114
+
115
+ changed_files: set[str] | None = None
116
+ if changed_only:
117
+ if not shutil.which("git"):
118
+ click.echo(
119
+ "Error: --changed-only requires git, but git was not found on PATH. Aborting.",
120
+ err=True,
121
+ )
122
+ import sys
123
+
124
+ sys.exit(1)
125
+ try:
126
+ result_unstaged = subprocess.run(
127
+ ["git", "diff", "--name-only", "HEAD"],
128
+ capture_output=True,
129
+ text=True,
130
+ check=True,
131
+ )
132
+ result_staged = subprocess.run(
133
+ ["git", "diff", "--cached", "--name-only"],
134
+ capture_output=True,
135
+ text=True,
136
+ check=True,
137
+ )
138
+ raw = result_unstaged.stdout + result_staged.stdout
139
+ changed_files = {
140
+ str(pathlib.Path(line.strip()).absolute())
141
+ for line in raw.splitlines()
142
+ if line.strip().endswith(".py")
143
+ }
144
+ except subprocess.CalledProcessError as e:
145
+ click.echo(f"Error: git command failed: {e.stderr.strip()}", err=True)
146
+ import sys
147
+
148
+ sys.exit(1)
149
+
150
+ files_ = []
151
+
152
+ for path in paths:
153
+ path_ = pathlib.Path(path)
154
+
155
+ if not path_.exists():
156
+ continue
157
+
158
+ if path_.is_dir():
159
+ files_.extend(path_.glob("**/*.py"))
160
+
161
+ if path_.is_file() and path_.name.endswith(".py"):
162
+ files_.append(path_)
163
+
164
+ if changed_files is not None:
165
+ files_ = [f for f in files_ if str(f.absolute()) in changed_files]
166
+
167
+ if check:
168
+ checked_files = {
169
+ file.absolute().as_posix(): docstring_generator_ext.check_docstring(
170
+ file.absolute().as_posix()
171
+ )
172
+ for file in files_
173
+ }
174
+ if print_results(checked_files, _strict, _threshold) != 0:
175
+ import sys
176
+
177
+ return sys.exit(1)
178
+ else:
179
+ for file in files_:
180
+ if file.name in _exclude_files or any(
181
+ str(exclude_dir) in str(file) for exclude_dir in _exclude_dirs
182
+ ):
183
+ continue
184
+ try:
185
+ if dry_run:
186
+ with tempfile.NamedTemporaryFile(suffix=".py", delete=False) as tmp:
187
+ tmp_path = pathlib.Path(tmp.name)
188
+ shutil.copy2(file, tmp_path)
189
+ try:
190
+ docstring_generator_ext.parse_file(
191
+ tmp_path.as_posix(), docstring_style, overwrite_style
192
+ )
193
+ original = file.read_text(encoding="utf-8").splitlines(keepends=True)
194
+ modified = tmp_path.read_text(encoding="utf-8").splitlines(keepends=True)
195
+ diff = list(
196
+ difflib.unified_diff(
197
+ original,
198
+ modified,
199
+ fromfile=f"a/{file}",
200
+ tofile=f"b/{file}",
201
+ )
202
+ )
203
+ if diff:
204
+ print("".join(diff))
205
+ else:
206
+ print(f"{file}: no changes")
207
+ finally:
208
+ tmp_path.unlink(missing_ok=True)
209
+ else:
210
+ docstring_generator_ext.parse_file(
211
+ file.absolute().as_posix(), docstring_style, overwrite_style
212
+ )
213
+ except SyntaxError as e:
214
+ print(f"Error processing file {file}: {e}")
215
+ except Exception as e:
216
+ print(f"Error processing file {file}: {e}")
217
+
218
+
219
+ if __name__ == "__main__":
220
+ main()