Add auto-generated CLI reference documentation from test cases#2673
Add auto-generated CLI reference documentation from test cases#2673
Conversation
|
Warning Rate limit exceeded@koxudaxi has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 4 minutes and 56 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (4)
WalkthroughThis pull request introduces comprehensive CLI documentation infrastructure for the datamodel-codegen tool. It adds automated documentation generation capabilities via a new build script, CLI option metadata structures, supporting GitHub Actions workflow, extensive CLI reference documentation files, and test enhancements with CLI documentation markers to track which options are covered by tests. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Areas requiring extra attention:
Poem
Pre-merge checks and finishing touches✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…o docs/auto-generate-cli-docs
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #2673 +/- ##
==========================================
+ Coverage 99.50% 99.51% +0.01%
==========================================
Files 76 79 +3
Lines 10731 10989 +258
Branches 1316 1318 +2
==========================================
+ Hits 10678 10936 +258
Misses 32 32
Partials 21 21
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
CodSpeed Performance ReportMerging #2673 will not alter performanceComparing Summary
Footnotes
|
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
tests/main/jsonschema/test_main_jsonschema.py (2)
1236-1253: Test for--disable-timestampdoesn't pass the flag it documents
test_main_jsonschema_patternis annotated for--disable-timestamp, and the docstring explains disabling the header timestamp, but the test itself never passes--disable-timestamptorun_main_and_assert. The golden output file also contains a hardcoded timestamp, confirming the test was generated without the flag.Add
extra_args=["--disable-timestamp"]to therun_main_and_assert()call and regenerate the golden file once this change is made:def test_main_jsonschema_pattern(output_file: Path) -> None: run_main_and_assert( input_path=JSON_SCHEMA_DATA_PATH / "pattern.json", output_path=output_file, input_file_type="jsonschema", assert_func=assert_file_content, expected_file="pattern.py", + extra_args=["--disable-timestamp"], )
1671-1689: Align cli_doc CLI arguments with test arguments for prefix-related optionsThe @pytest.mark.cli_doc decorators and test code have misaligned argument values:
test_main_jsonschema_special_enum_special_field_name_prefix: cli_doc specifies["--special-field-name-prefix", "special_"]but test uses["--special-field-name-prefix", "special"]test_main_jsonschema_special_enum_empty_enum_field_name: cli_doc specifies["--empty-enum-field-name", "empty_"]but test uses["--empty-enum-field-name", "empty"]This causes the documented CLI commands to diverge from what the tests actually execute. Align the cli_doc markers to match the test extra_args values, or update both the test arguments and regenerate the golden output files to match the documented cli_args.
Also applies to: lines 1793-1811
tests/main/openapi/test_main_openapi.py (1)
2084-2129: Fix golden_output path format in cli_doc markers for consistency.The two allof tests use
golden_output="main/openapi/..."while all other OpenAPI tests in this file usegolden_output="openapi/...". For example, line 85 uses"openapi/discriminator/enum_use_enum_values.py"and line 327 uses"openapi/base_class.py". The allof tests (lines 2088 and 2112) should follow the same pattern to maintain consistency across the test suite. Change both instances from"main/openapi/..."to"openapi/..."to align with the established convention.
♻️ Duplicate comments (1)
tests/cli_doc/test_cli_doc_coverage.py (1)
103-121: Informational tests contain empty loops with no output.The
test_show_coverage_statsandtest_show_documented_optionsmethods iterate over options but do nothing (justpass). If these are meant to display statistics when run with--no-skip, they need actual print/logging statements. Otherwise, remove the dead code.def test_show_coverage_stats( # noqa: PLR6301 self, collected_options: set[str] ) -> None: """Display documentation coverage statistics.""" all_options = get_all_canonical_options() documentable = all_options - EXCLUDED_FROM_DOCS undocumented = documentable - collected_options for _opt in sorted(undocumented): - pass + print(f" Undocumented: {_opt}") @pytest.mark.skip(reason="Informational: run with -v --no-skip to see stats") def test_show_documented_options( # noqa: PLR6301 self, collected_options: set[str] ) -> None: """Display currently documented options.""" for opt in sorted(collected_options): - CLI_OPTION_META.get(opt) + meta = CLI_OPTION_META.get(opt) + print(f" {opt}: {meta}")This addresses the past review comment about "statement has no effect."
🧹 Nitpick comments (11)
docs/development-contributing.md (1)
105-114: Add guidance on committing generated documentation.After Step 4 verification passes, developers should commit the generated CLI documentation. Consider adding a note clarifying that the auto-generated documentation files should be committed to the repository.
Optionally, you could add to the Step 4 section:
### Step 4: Generate and verify documentation ```bash # Regenerate CLI docs $ pytest --collect-cli-docs -p no:xdist -q $ python scripts/build_cli_docs.py # Verify docs are correct $ tox run -e cli-docs + +# Commit the generated documentation +$ git add docs/cli_reference.md # or the appropriate generated file +$ git commit -m "docs: Update CLI reference for --my-new-option"This clarifies the final step in the workflow. </blockquote></details> <details> <summary>docs/cli-reference/quick-reference.md (1)</summary><blockquote> `1-250`: **Outstanding comprehensive reference documentation!** This quick reference page is exceptionally well-organized with both categorical and alphabetical indexes, making CLI options easy to discover via search (Ctrl+F). The dual organization approach significantly improves user experience. *Optional:* Consider addressing the markdown linting hint on line 238 for style consistency (use underscores instead of asterisks for strong emphasis to match the rest of the file). This is purely cosmetic and can be deferred. </blockquote></details> <details> <summary>tests/cli_doc/test_cli_options_sync.py (1)</summary><blockquote> `23-23`: **Clean up unused `noqa` directives.** Multiple `noqa` directives are unused because the corresponding Ruff rules (`PLR6301`, `PLC0415`) are not enabled in the project configuration. Apply this diff to remove the unused directives: ```diff - def test_all_registered_options_exist_in_argparse(self) -> None: # noqa: PLR6301 + def test_all_registered_options_exist_in_argparse(self) -> None: """Verify that all options in CLI_OPTION_META exist in argparse."""Apply similar changes to lines 36, 48, 58, 68, 75, 94, 101, and 102.
Also applies to: 36-36, 48-48, 58-58, 68-68, 75-75, 94-94, 101-102
docs/cli-reference/template-customization.md (2)
42-57: Input schema code fence language mismatch.The input schema is GraphQL syntax but the code fence specifies
json. Consider using a more appropriate language identifier or a generic fence for accuracy.- ```json + ```graphql scalar Date
204-214: Input schema uses OpenAPI YAML but code fence saysjson.Several input schema examples in this file use YAML/OpenAPI format but are wrapped in
jsoncode fences (lines 207, 619, 885, 1299, etc.). Consider usingyamlfor YAML content for proper syntax highlighting.- ```json + ```yaml openapi: "3.0.0"tests/cli_doc/test_cli_doc_coverage.py (1)
60-70: Remove unusednoqadirectives.Ruff indicates that
PLR6301is not enabled, so thesenoqacomments are unnecessary. This applies to lines 60, 72, 82, 91, 104, and 116.- def test_documented_options_have_cli_doc_markers( # noqa: PLR6301 + def test_documented_options_have_cli_doc_markers( self, collected_options: set[str] ) -> None:tests/conftest.py (3)
46-46: Consider usingstashfor pytest config data.Attaching
_cli_doc_itemsdirectly to the config object works but modern pytest recommends usingconfig.stashwith a typed key for better type safety. This is a minor improvement for maintainability.
49-49: Remove unusednoqadirective.Ruff indicates
PLR0912is not enabled, so thenoqa: ARG001, PLR0912can be simplified to justnoqa: ARG001.-def _validate_cli_doc_marker(node_id: str, kwargs: dict[str, Any]) -> list[str]: # noqa: ARG001, PLR0912 +def _validate_cli_doc_marker(node_id: str, kwargs: dict[str, Any]) -> list[str]: # noqa: ARG001
195-197: RedundantPath()wrapper.
CLI_DOC_COLLECTION_OUTPUTis already aPathobject (line 22), so wrapping it inPath()again on line 196 is unnecessary.CLI_DOC_COLLECTION_OUTPUT.parent.mkdir(parents=True, exist_ok=True) - with Path(CLI_DOC_COLLECTION_OUTPUT).open("w", encoding="utf-8") as f: + with CLI_DOC_COLLECTION_OUTPUT.open("w", encoding="utf-8") as f: json.dump(output, f, indent=2, ensure_ascii=False)src/datamodel_code_generator/cli_options.py (1)
227-230: Remove unusednoqadirectives.Ruff indicates that
PLC0415andSLF001are not enabled, so these directives can be removed.- from datamodel_code_generator.arguments import arg_parser as argument_parser # noqa: PLC0415 + from datamodel_code_generator.arguments import arg_parser as argument_parser alias_map: dict[str, str] = {} - for action in argument_parser._actions: # noqa: SLF001 + for action in argument_parser._actions:scripts/build_cli_docs.py (1)
22-22: Remove unusednoqadirectives.Ruff indicates these directives reference rules that aren't enabled:
- Line 22:
S404- Line 156:
PLR0912,PLR0914,PLR0915- Line 462:
PLR0912,PLR0914,PLR0915Also applies to: 156-156, 462-462
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (55)
.github/workflows/cli-docs.yaml(1 hunks).github/workflows/codespell.yaml(1 hunks).gitignore(1 hunks).pre-commit-config.yaml(1 hunks)README.md(1 hunks)docs/cli-reference/base-options.md(1 hunks)docs/cli-reference/field-customization.md(1 hunks)docs/cli-reference/general-options.md(1 hunks)docs/cli-reference/index.md(1 hunks)docs/cli-reference/openapi-only-options.md(1 hunks)docs/cli-reference/quick-reference.md(1 hunks)docs/cli-reference/template-customization.md(1 hunks)docs/cli-reference/typing-customization.md(1 hunks)docs/development-contributing.md(1 hunks)docs/index.md(2 hunks)mkdocs.yaml(2 hunks)pyproject.toml(1 hunks)scripts/__init__.py(1 hunks)scripts/build_cli_docs.py(1 hunks)scripts/update_command_help_on_markdown.py(1 hunks)src/datamodel_code_generator/cli_options.py(1 hunks)tests/cli_doc/test_cli_doc_coverage.py(1 hunks)tests/cli_doc/test_cli_options_sync.py(1 hunks)tests/conftest.py(3 hunks)tests/data/expected/main/openapi/const_baseline.py(1 hunks)tests/data/expected/main/person.py(1 hunks)tests/data/expected/main_kr/custom_file_header/with_option.py(1 hunks)tests/data/expected/main_kr/custom_file_header/without_option.py(1 hunks)tests/data/expected/main_kr/custom_formatters_kwargs/output.py(1 hunks)tests/data/expected/main_kr/encoding/output.py(1 hunks)tests/data/expected/main_kr/formatters/output.py(1 hunks)tests/data/expected/main_kr/ignore_pyproject/output.py(1 hunks)tests/data/expected/main_kr/include_path_parameters/output.py(1 hunks)tests/data/expected/main_kr/input_output/output.py(1 hunks)tests/data/expected/main_kr/no_alias/with_option.py(1 hunks)tests/data/expected/main_kr/no_alias/without_option.py(1 hunks)tests/data/expected/main_kr/target_python_version/py310.py(1 hunks)tests/data/expected/main_kr/target_python_version/py39.py(1 hunks)tests/data/expected/main_kr/url_with_headers/output.py(1 hunks)tests/data/expected/main_kr/use_non_positive_negative/output.py(1 hunks)tests/data/expected/main_kr/use_pendulum/output.py(1 hunks)tests/data/jsonschema/encoding_test.json(1 hunks)tests/data/jsonschema/no_alias.json(1 hunks)tests/data/jsonschema/pet_simple.json(1 hunks)tests/data/jsonschema/use_non_positive_negative.json(1 hunks)tests/data/jsonschema/use_pendulum.json(1 hunks)tests/data/openapi/include_path_parameters.yaml(1 hunks)tests/main/graphql/test_annotated.py(4 hunks)tests/main/graphql/test_main_graphql.py(10 hunks)tests/main/jsonschema/test_main_jsonschema.py(37 hunks)tests/main/openapi/test_main_openapi.py(27 hunks)tests/main/test_main_general.py(7 hunks)tests/main/test_main_json.py(1 hunks)tests/test_main_kr.py(7 hunks)tox.ini(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (18)
tests/data/jsonschema/use_pendulum.json (4)
tests/data/expected/parser/openapi/openapi_parser_parse_additional_properties/with_import_format_custom_module.Base.py (1)
Event(49-50)tests/data/expected/main_kr/main_use_schema_description/output.py (1)
Event(70-75)tests/data/expected/parser/openapi/openapi_parser_parse_modular/models.py (1)
Event(28-29)tests/data/expected/parser/openapi/openapi_parser_parse_additional_properties/with_import_format.py (1)
Event(47-48)
tests/data/expected/main_kr/custom_formatters_kwargs/output.py (4)
tests/data/expected/main_kr/formatters/output.py (1)
Pet(12-15)tests/data/expected/main_kr/input_output/output.py (1)
Pet(12-15)tests/data/expected/main_kr/url_with_headers/output.py (1)
Pet(12-15)src/datamodel_code_generator/model/base.py (1)
name(599-601)
tests/main/jsonschema/test_main_jsonschema.py (2)
tests/test_main_kr.py (2)
output_file(38-40)output_dir(44-46)tests/main/conftest.py (2)
output_file(94-96)output_dir(100-102)
tests/data/expected/main_kr/input_output/output.py (4)
tests/data/expected/main_kr/custom_formatters_kwargs/output.py (1)
Pet(12-15)tests/data/expected/main_kr/formatters/output.py (1)
Pet(12-15)tests/data/expected/main_kr/url_with_headers/output.py (1)
Pet(12-15)src/datamodel_code_generator/model/base.py (1)
name(599-601)
tests/cli_doc/test_cli_options_sync.py (1)
src/datamodel_code_generator/cli_options.py (2)
get_all_canonical_options(255-257)_canonical_option_key(208-217)
tests/data/expected/main_kr/no_alias/with_option.py (5)
tests/data/expected/main/person.py (1)
Person(11-18)tests/data/expected/main_kr/custom_file_header/with_option.py (1)
Person(10-13)tests/data/expected/main_kr/custom_file_header/without_option.py (1)
Person(12-15)tests/data/expected/main_kr/no_alias/without_option.py (1)
Person(12-15)tests/data/expected/main_kr/target_python_version/py310.py (1)
Person(12-19)
tests/data/expected/main_kr/target_python_version/py39.py (1)
tests/data/expected/main/person.py (1)
Person(11-18)
tests/data/expected/main_kr/custom_file_header/without_option.py (2)
tests/data/expected/main_kr/custom_file_header/with_option.py (1)
Person(10-13)tests/data/expected/main_kr/no_alias/without_option.py (1)
Person(12-15)
tests/data/expected/main_kr/formatters/output.py (4)
tests/data/expected/main_kr/custom_formatters_kwargs/output.py (1)
Pet(12-15)tests/data/expected/main_kr/input_output/output.py (1)
Pet(12-15)tests/data/expected/main_kr/url_with_headers/output.py (1)
Pet(12-15)src/datamodel_code_generator/model/base.py (1)
name(599-601)
tests/data/expected/main_kr/custom_file_header/with_option.py (2)
tests/data/expected/main_kr/custom_file_header/without_option.py (1)
Person(12-15)tests/data/expected/main_kr/no_alias/with_option.py (1)
Person(12-15)
tests/data/expected/main_kr/no_alias/without_option.py (3)
tests/data/expected/main_kr/custom_file_header/with_option.py (1)
Person(10-13)tests/data/expected/main_kr/custom_file_header/without_option.py (1)
Person(12-15)tests/data/expected/main_kr/no_alias/with_option.py (1)
Person(12-15)
tests/main/test_main_json.py (2)
tests/test_main_kr.py (1)
output_file(38-40)tests/main/conftest.py (1)
output_file(94-96)
tests/data/expected/main_kr/target_python_version/py310.py (2)
tests/data/expected/main/person.py (1)
Person(11-18)tests/data/expected/main_kr/target_python_version/py39.py (1)
Person(12-19)
tests/data/expected/main/openapi/const_baseline.py (1)
tests/data/expected/parser/openapi/openapi_parser_parse_modular/bar.py (1)
Field(6-7)
tests/data/expected/main/person.py (1)
tests/data/expected/main_kr/target_python_version/py39.py (1)
Person(12-19)
tests/cli_doc/test_cli_doc_coverage.py (1)
src/datamodel_code_generator/cli_options.py (2)
get_all_canonical_options(255-257)get_canonical_option(240-251)
scripts/build_cli_docs.py (1)
src/datamodel_code_generator/cli_options.py (5)
OptionCategory(18-27)get_all_canonical_options(255-257)get_canonical_option(240-251)get_option_meta(266-278)is_excluded_from_docs(260-263)
tests/main/openapi/test_main_openapi.py (2)
tests/test_main_kr.py (2)
output_file(38-40)test_main_base_class(62-72)tests/main/conftest.py (2)
output_file(94-96)run_main_and_assert(196-352)
🪛 Checkov (3.2.334)
tests/data/openapi/include_path_parameters.yaml
[high] 1-45: Ensure that the global security field has rules defined
(CKV_OPENAPI_4)
[high] 1-45: Ensure that security operations is not empty.
(CKV_OPENAPI_5)
🪛 LanguageTool
docs/cli-reference/openapi-only-options.md
[style] ~928-~928: Using many exclamation marks might seem excessive (in this case: 15 exclamation marks for a text that’s 3514 characters long)
Context: ...ted:** Use --field-constraints instead !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
docs/cli-reference/base-options.md
[style] ~251-~251: Using many exclamation marks might seem excessive (in this case: 15 exclamation marks for a text that’s 2553 characters long)
Context: ...nts. Format: HeaderName:HeaderValue. !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
docs/cli-reference/quick-reference.md
[grammar] ~213-~213: Ensure spelling is correct
Context: ...um member as the default value for enum fiel... - [--shared-module-name](general-o...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
docs/cli-reference/template-customization.md
[style] ~2271-~2271: Using many exclamation marks might seem excessive (in this case: 45 exclamation marks for a text that’s 9401 characters long)
Context: ...le-line strings in the generated code. !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
docs/cli-reference/field-customization.md
[grammar] ~18-~18: Ensure spelling is correct
Context: ...um member as the default value for enum fiel... | | [--snake-case-field](#snake-ca...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
[style] ~2824-~2824: Using many exclamation marks might seem excessive (in this case: 60 exclamation marks for a text that’s 11885 characters long)
Context: ...e`](model-customization.md#class-name) !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
docs/cli-reference/typing-customization.md
[style] ~1437-~1437: Using many exclamation marks might seem excessive (in this case: 48 exclamation marks for a text that’s 9437 characters long)
Context: ...nforcing uniqueness at the type level. !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
docs/cli-reference/general-options.md
[style] ~1677-~1677: Using many exclamation marks might seem excessive (in this case: 33 exclamation marks for a text that’s 7330 characters long)
Context: ...ar output with tree-level model reuse. !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
🪛 markdownlint-cli2 (0.18.1)
docs/cli-reference/quick-reference.md
238-238: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
238-238: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
docs/cli-reference/general-options.md
30-30: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
30-30: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
600-600: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
600-600: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
🪛 Ruff (0.14.8)
tests/cli_doc/test_cli_options_sync.py
23-23: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
36-36: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
48-48: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
58-58: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
68-68: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
75-75: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
94-94: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
101-101: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
102-102: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
tests/test_main_kr.py
1192-1192: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
1199-1199: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
1330-1330: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
1336-1336: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
1369-1369: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
1375-1375: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
tests/conftest.py
49-49: Unused noqa directive (non-enabled: PLR0912)
Remove unused noqa directive
(RUF100)
tests/cli_doc/test_cli_doc_coverage.py
60-60: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
72-72: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
82-82: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
91-91: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
104-104: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
116-116: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
scripts/build_cli_docs.py
22-22: Unused noqa directive (non-enabled: S404)
Remove unused noqa directive
(RUF100)
156-156: Unused noqa directive (non-enabled: PLR0912, PLR0914, PLR0915)
Remove unused noqa directive
(RUF100)
462-462: Unused noqa directive (non-enabled: PLR0912, PLR0914, PLR0915)
Remove unused noqa directive
(RUF100)
src/datamodel_code_generator/cli_options.py
227-227: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
230-230: Unused noqa directive (non-enabled: SLF001)
Remove unused noqa directive
(RUF100)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
- GitHub Check: benchmarks
- GitHub Check: 3.12 on Windows
- GitHub Check: 3.9 on Windows
- GitHub Check: 3.10 on Windows
🔇 Additional comments (63)
tests/data/jsonschema/use_non_positive_negative.json (1)
1-27: LGTM! Well-structured JSON Schema for numeric constraint testing.The schema correctly defines non-negative and non-positive constraints using appropriate
minimumandmaximumproperties. Each field includes clear descriptive metadata, and the constraint mappings (integer/number with min 0 for non-negative, max 0 for non-positive) are accurate.tests/data/expected/main_kr/use_non_positive_negative/output.py (1)
1-31: LGTM! Expected output correctly maps JSON Schema constraints to Pydantic types.The generated model accurately translates the JSON Schema numeric constraints to appropriate Pydantic constrained types (NonNegativeInt, NonPositiveInt, NonNegativeFloat, NonPositiveFloat). Field descriptions are preserved correctly, and the fixed timestamp ensures test stability.
tests/data/jsonschema/use_pendulum.json (1)
1-23: LGTM! Well-formed JSON Schema for testing pendulum types.The schema correctly defines an Event object with appropriate format specifiers for date/time fields. The use of
date-time,date, anddurationformats is ideal for demonstrating pendulum type generation from JSON Schema.tests/data/expected/main_kr/use_pendulum/output.py (1)
1-17: LGTM! Generated output correctly uses pendulum types.The generated Pydantic model accurately reflects the JSON Schema structure with appropriate pendulum types for temporal fields. The mapping is correct:
date-timeformat →DateTimedateformat →Datedurationformat →DurationRequired fields are properly non-Optional, and optional fields correctly use
Optional[T] = None.docs/development-contributing.md (4)
27-48: Clear restructuring of contribution workflow.The reorganization adds explicit steps for verifying documentation (README and CLI docs), which properly integrates the new auto-generation workflow into the contributor process. Step 9 (
tox run -e cli-docs) correctly places the CLI documentation check after code changes.
116-123: Helpful troubleshooting guidance.The troubleshooting section clearly maps common errors to solutions. This will help developers quickly resolve issues when implementing new CLI options.
124-139: Clear and comprehensive marker reference.The reference table effectively documents all marker parameters with clear descriptions and required/optional indicators. The footnote appropriately clarifies the constraint between
golden_outputandmodel_outputs.
50-114: No issues found. All components documented in the guide exist and function as described:
OptionCategoryenum andCLIOptionMetaclass are properly defined incli_options.pypytest.mark.cli_doc()marker is registered with the expected parameters (options,input_schema,cli_args,golden_output, etc.)--collect-cli-docspytest flag is implemented and functionalscripts/build_cli_docs.pyexiststox run -e cli-docstarget is configured intox.inirun_main_and_assert()function signature matches the documented usage pattern- Relative path resolution (e.g.,
jsonschema/example.json) aligns with actual test implementationsThe step-by-step guide accurately reflects the codebase implementation.
pyproject.toml (1)
197-197: LGTM! Appropriate exclusion for generated documentation.Excluding the auto-generated CLI reference docs from spell checking is the correct approach, as these files are programmatically generated and spell-checking them would create unnecessary noise.
tests/data/jsonschema/no_alias.json (1)
1-17: LGTM! Valid test fixture for field naming scenarios.This JSON Schema fixture appropriately tests mixed field naming conventions (hyphens vs underscores), which is valuable for validating the code generator's handling of field aliases and naming transformations.
.pre-commit-config.yaml (1)
34-34: LGTM! Consistent codespell exclusion.The exclusion pattern correctly uses the
^anchor and aligns with the codespell configuration inpyproject.toml..github/workflows/codespell.yaml (1)
30-30: LGTM! Completes the consistent exclusion strategy.This skip directive ensures the CLI reference docs are excluded from spell checking in the GitHub Actions workflow, completing the exclusion strategy across all three spell-check configurations (pyproject.toml, pre-commit, and CI).
tests/data/jsonschema/encoding_test.json (1)
1-15: LGTM! Important test fixture for encoding/i18n scenarios.This schema appropriately tests the code generator's handling of non-ASCII (Japanese) property names and metadata, ensuring proper Unicode support throughout the generation pipeline.
tests/data/expected/main_kr/custom_file_header/with_option.py (1)
1-13: LGTM! Valid expected output with custom header and aliases.The generated model correctly demonstrates:
- Custom copyright header integration
- Field aliases for hyphenated property names
- Proper Pydantic syntax with
Field(..., alias='...')patterntests/data/expected/main_kr/ignore_pyproject/output.py (1)
1-13: LGTM! Valid expected output for pyproject.toml ignore scenario.The model correctly preserves camelCase field naming (not converted to snake_case), which validates the behavior when
pyproject.tomlconfiguration is intentionally ignored.tests/data/expected/main_kr/target_python_version/py310.py (1)
1-19: LGTM! Correct Python 3.10+ syntax.The expected output appropriately uses Python 3.10+ type syntax:
- PEP 604 union syntax (
str | Noneinstead ofOptional[str])- Built-in generic types (
list[Any]instead ofList[Any])This validates proper version-specific code generation.
tests/data/expected/main_kr/target_python_version/py39.py (1)
1-19: LGTM! Correct Python 3.9+ syntax.The use of lowercase
list[Any]instead ofList[Any]is correct for Python 3.9+, which supports subscripting built-in types (PEP 585). This aligns with the target Python version indicated by the filename.docs/cli-reference/typing-customization.md (1)
1-1774: LGTM! Comprehensive typing customization documentation.The documentation is well-structured with clear examples for each CLI option. The static analysis warning about excessive exclamation marks is a false positive caused by Material for MkDocs admonition syntax (
!!! tip), which is intentional.tests/main/graphql/test_annotated.py (1)
43-121: LGTM! Pytest CLI doc markers correctly applied.The
pytest.mark.cli_docdecorators are properly configured with CLI arguments that match the test implementations. The path differences (relative in decorator vs. absolute in test) are intentional and correct for documentation purposes.scripts/__init__.py (1)
1-1: LGTM! Standard package initialization.Simple package docstring for the scripts tooling package.
.gitignore (1)
8-9: LGTM! Appropriate ignore patterns for generated artifacts.The additions correctly exclude:
site/- MkDocs generated documentation outputtests/cli_doc/.cli_doc_collection.json- pytest collection metadatatests/data/jsonschema/pet_simple.json (1)
1-16: LGTM! Valid JSON Schema test fixture.Simple and valid JSON Schema defining a Pet object with three optional properties (id, name, tag). Appropriate for test data.
tests/main/test_main_json.py (1)
31-50: LGTM! CLI documentation marker correctly applied.The test has been enhanced with:
pytest.mark.cli_docdecorator for documentation generation- Updated docstring explaining the
--input-file-typeflag and supported formats- Explicit
input_file_type="json"parameter for clarityThe decorator's
cli_argsand the test's parameters are consistent.docs/cli-reference/field-customization.md (1)
18-18: No action needed – truncation is intentional.Table descriptions use "..." to maintain compact formatting, with full details provided in section definitions. The
--set-default-enum-memberdescription correctly truncates to "enum fiel..." in the table, with the complete text "enum fields" available in the dedicated section below.tests/data/expected/main_kr/no_alias/with_option.py (1)
1-15: LGTM! Well-structured test data.This generated Pydantic model correctly demonstrates the
--no-aliasoption behavior, with direct field names (first_name,last_name,email_address) instead of aliased variants. The model structure and imports are appropriate for the test scenario.scripts/update_command_help_on_markdown.py (1)
1-1: LGTM! Clean docstring formatting.Removing the linting directive improves readability without affecting functionality.
docs/index.md (2)
325-326: Excellent documentation enhancement!The CLI reference link is prominently placed and clearly formatted, making it easy for users to discover the detailed documentation. This addresses the PR objective of documenting features with examples.
587-587: Good cross-reference addition.Linking to the supported data types documentation improves discoverability and user navigation.
README.md (1)
332-333: Great addition to the README!The CLI reference callout with the book emoji (📖) and bold text provides excellent visibility for the new documentation. Users can quickly find detailed examples and usage information.
tests/data/openapi/include_path_parameters.yaml (1)
1-43: LGTM! Well-formed OpenAPI test fixture.This test schema appropriately defines path and query parameters for validating the
--include-path-parametersCLI option. The static analysis warnings about missing security definitions are expected and acceptable for test data fixtures.tests/data/expected/main_kr/custom_formatters_kwargs/output.py (1)
1-15: LGTM! Standard generated test fixture.This Pet model is correctly generated and serves as expected output for the custom formatters kwargs test scenario. The structure matches other Pet model fixtures in the test suite.
tox.ini (1)
17-17: Excellent addition for documentation maintenance!The new
cli-docstest environment provides automated validation to ensure CLI documentation stays synchronized with the codebase. This follows the same pattern as the existingreadmeenvironment and will help prevent documentation drift.Also applies to: 71-77
tests/data/expected/main_kr/encoding/output.py (1)
1-14: LGTM! Generated test fixture for multilingual encoding.This generated model correctly demonstrates Japanese character encoding support with proper Pydantic field definitions and optional typing.
tests/data/expected/main_kr/formatters/output.py (1)
1-15: LGTM! Consistent generated test fixture.This Pet model matches the expected structure across multiple test fixtures in the PR and serves as a baseline for formatter testing.
tests/data/expected/main_kr/input_output/output.py (1)
1-15: LGTM! Consistent test fixture for input/output validation.The Pet model structure is consistent with other test fixtures and correctly serves as expected output for input/output testing scenarios.
tests/data/expected/main_kr/url_with_headers/output.py (1)
1-15: LGTM! Test fixture for URL-based schema input.This Pet model correctly demonstrates generation from a URL source (Line 2), with the expected model structure consistent with other test fixtures.
mkdocs.yaml (2)
5-23: Material theme configuration looks good with modern features enabled.The theme configuration adds useful features like code copying, navigation enhancements, and search improvements. The icon configuration and analytics setup appear correct.
25-43: Markdown extensions appropriately expanded for enhanced documentation.The added extensions (tabbed content, details/summary, emoji support, attributes, and TOC permalinks) align well with the CLI reference documentation needs. The emoji configuration using Material's twemoji is correct.
tests/data/expected/main_kr/no_alias/without_option.py (1)
1-15: LGTM! Test fixture correctly demonstrates default alias behavior.The Person model appropriately uses Field aliases for fields with hyphens (first-name, last-name), which is the expected behavior when the
--no-aliasoption is NOT applied.tests/data/expected/main/openapi/const_baseline.py (2)
10-11: LGTM! Root model with const constraint correctly implements OpenAPI const keyword.The ApiVersion model appropriately uses
__root__withconst=Trueto enforce the constant value 'v1', which is the expected Pydantic pattern for OpenAPI const support.
14-15: LGTM! Api model correctly embeds the const-validated ApiVersion.The Api model structure appropriately composes the const-validated ApiVersion as a field, demonstrating proper model composition for OpenAPI const scenarios.
docs/cli-reference/index.md (2)
9-17: No action needed. The option counts are already consistent across both sections—the category table and alphabetical listing both contain 98 options (5+16+20+26+15+5+11=98). There is no discrepancy to address.
26-177: All linked documentation pages and anchor IDs are correctly configured. All 8 category pages exist and anchor IDs in the target pages match the option references in the index using the extended Markdown syntax (e.g.,## \--option-name` {#option-name}`).tests/main/test_main_general.py (1)
147-187: LGTM! Well-structured CLI documentation markers.The addition of
@pytest.mark.cli_docmarkers and descriptive docstrings enhances test documentation without modifying test logic. The markers properly specify options, input schemas, CLI arguments, and golden outputs, which will enable automated CLI documentation generation.Also applies to: 205-237, 450-470, 473-500, 708-759
tests/main/graphql/test_main_graphql.py (1)
61-81: CLI doc markers and GraphQL option coverage look consistentThe new
@pytest.mark.cli_docannotations and expanded docstrings for the GraphQL tests cleanly document each option and match the actualextra_argsused (--use-default-kwarg,--aliases, specialized-enum toggles, enum subclassing, additional imports, custom formatters, extra-fields handling, type aliases, and dataclass options). Golden outputs and test expectations stay in sync.No changes needed here.
Also applies to: 104-120, 172-185, 200-220, 242-268, 275-297, 332-352, 355-377, 406-438, 469-491
tests/test_main_kr.py (1)
250-272: New CLI doc metadata and tests are well-alignedThe new
@pytest.mark.cli_docannotations in this file (schema/field descriptions, decimal/pendulum behaviors, number constraints, path-parameter inclusion, alias behavior, custom file headers, URL + HTTP options, encoding/formatters, ignore‑pyproject, shared-module-name, exact imports, target-python-version, etc.) all match the underlying tests:
cli_argsmirror theextra_args/invocations.input_schemaandgolden_outputpaths correspond to the schemas and expected files already asserted by the tests.- Docstrings give concise, option-specific explanations.
This structure should work well for the auto-generated CLI docs.
Also applies to: 288-310, 1033-1072, 1075-1098, 1101-1123, 1152-1174, 1177-1213, 1215-1236, 1245-1261, 1264-1286, 1290-1306, 1316-1352, 1354-1396, 1399-1461, 1473-1499, 1502-1530
tests/main/jsonschema/test_main_jsonschema.py (1)
58-80: Broad JSON Schema CLI-doc coverage appears coherent and consistentAcross the many new
@pytest.mark.cli_docannotations in this file (ordering and future-import controls, output model type, defaults, naming/aliasing options, strict/field constraints, collections, titles, string wrapping, enum-as-literal, type-alias/type-mappings, reuse-scope, aliases, collapse-root-models, frozen fields, etc.), the patterns look sound:
optionscorrectly list the primary flag(s) under test.input_schema,cli_args, andgolden_output/expected_fileline up with the existing test behavior and expected outputs in spot checks.- Docstrings give readers enough context to understand each option when consumed in generated CLI docs.
Apart from the few alignment issues already noted in other comments, the overall structure is solid.
Also applies to: 125-151, 225-249, 431-449, 452-470, 508-526, 554-574, 838-858, 861-904, 1056-1099, 1610-1657, 1671-1690, 1705-1722, 1793-1811, 1856-1887, 1925-1943, 1947-1988, 2005-2032, 2082-2100, 2148-2168, 2386-2406, 2560-2593, 2647-2656, 2706-2724, 2757-2767, 2808-2812, 3470-3482, 3513-3527, 3554-3576, 3647-3664, 3803-3820, 3862-3881, 4039-4055, 4059-4072
src/datamodel_code_generator/cli_options.py (1)
266-278: LGTM - Well-designed fallback behavior.The
get_option_metafunction has good defensive design: it canonicalizes the option, checks explicit metadata first, then provides a sensible default for undocumented canonical options. This ensures new options don't break the documentation system.scripts/build_cli_docs.py (1)
66-87: Good security practice with path traversal protection.The
safe_read_filefunction properly validates that resolved paths remain within the base directory, preventing path traversal attacks. This is important since file paths come from test marker data.tests/main/openapi/test_main_openapi.py (14)
81-105: LGTM - CLI documentation marker appropriately documents the feature.The
cli_argsomitting--target-python-versionis acceptable since the marker focuses on documenting--use-enum-values-in-discriminator. The path formats are consistent with the documentation generation convention.
323-342: LGTM - Clean implementation with matching parameters.The
cli_docmarker parameters align correctly with the test'sextra_args, and the docstring clearly documents the--base-classCLI option.
457-494: LGTM - Appropriate use ofmodel_outputsfor parametrized test.The
model_outputsdictionary correctly captures both Pydantic v1 and v2 variants, which is the right approach for documenting a parametrized test without duplicating CLI documentation.
713-738: Potential inconsistency between test execution and documented outputs.The test runs without specifying
--output-model-type, defaulting to Pydantic v1, and validates against"with_field_constraints.py". However, themodel_outputsclaims to document bothpydantic_v1andpydantic_v2outputs.Since the test doesn't actually verify the v2 output, the CLI documentation may be misleading. Consider either:
- Making this test parametrized to actually test both outputs
- Removing
pydantic_v2frommodel_outputssince it's not validated hereIs the
model_outputsfield meant to document outputs that are validated by separate tests, or should it only include outputs validated by this specific test?
688-710: LGTM - Appropriately documents one specific variant from parametrized test.The
cli_docmarker correctly captures the--use-unique-items-as-setflag behavior with a matching golden output file.
782-812: LGTM - Consistent pattern for documenting multi-model parametrized test.The
model_outputsdictionary withprimary=Truecorrectly captures both Pydantic v1 and msgspec variants.
1853-1881: LGTM - Comprehensive documentation of multi-model output types.The
model_outputsdictionary captures all five output model types (Pydantic v1/v2, msgspec, TypedDict, dataclass), providing complete documentation coverage for this feature. Thecomparison_outputappropriately references a baseline for comparison.
3173-3209: LGTM - Well-structured multi-line CLI args for complex example.The
cli_argsis appropriately split across lines for readability. The marker correctly focuses on--parent-scoped-namingas the primary feature being documented.
519-550: LGTM - Custom template directory documentation.The marker and docstring clearly document the
--custom-template-diroption with appropriate context about combining with--extra-template-data.
618-638: LGTM - Validation flag documentation.The docstring appropriately notes that
--validationis deprecated in favor of--field-constraints.
861-880: LGTM - Consistent CLI documentation markers for configuration flags.These markers (
--strip-default-none,--enable-version-header,--allow-population-by-field-name,--allow-extra-fields,--enable-faux-immutability,--force-optional) follow consistent patterns and accurately describe their CLI behavior.Also applies to: 894-913, 933-954, 974-995, 1015-1036, 1051-1069
1193-1215: LGTM - DateTime and nullable handling documentation.The markers for
--output-datetime-class,--use-one-literal-as-default, and--strict-nullableare well-structured with clear docstrings.Also applies to: 1275-1299, 1366-1384
1525-1542: LGTM - OpenAPI scope and naming option documentation.The markers for
--disable-appending-item-suffix,--openapi-scopes, and--use-operation-id-as-nameaccurately reflect the CLI behavior and include appropriate example arguments.Also applies to: 1545-1563, 2473-2491
2616-2636: LGTM - Advanced feature documentation.The markers for
--custom-file-header-path,--use-serialize-as-any, and--read-only-write-only-model-typeprovide clear documentation with accurate examples. The--read-only-write-only-model-typemarker particularly has a helpful docstring explaining the 'request-response' mode behavior.Also applies to: 2769-2789, 3544-3570
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (5)
tests/conftest.py (1)
49-49: Remove unusednoqadirective.The
PLR0912directive (too many branches) is not enabled in your Ruff configuration.Apply this diff:
-def _validate_cli_doc_marker(node_id: str, kwargs: dict[str, Any]) -> list[str]: # noqa: ARG001, PLR0912 # pragma: no cover +def _validate_cli_doc_marker(node_id: str, kwargs: dict[str, Any]) -> list[str]: # noqa: ARG001 # pragma: no covertests/cli_doc/test_cli_options_sync.py (1)
23-23: Remove unusednoqadirectives.Multiple
noqadirectives are not needed as the rules they suppress (PLR6301,PLC0415) are not enabled in your Ruff configuration.Apply this diff to remove all unused directives:
- def test_all_registered_options_exist_in_argparse(self) -> None: # noqa: PLR6301 + def test_all_registered_options_exist_in_argparse(self) -> None: - def test_excluded_options_exist_in_argparse(self) -> None: # noqa: PLR6301 + def test_excluded_options_exist_in_argparse(self) -> None: - def test_no_overlap_between_meta_and_excluded(self) -> None: # noqa: PLR6301 + def test_no_overlap_between_meta_and_excluded(self) -> None: - def test_meta_names_match_keys(self) -> None: # noqa: PLR6301 + def test_meta_names_match_keys(self) -> None: - def test_all_argparse_options_are_documented_or_excluded(self) -> None: # noqa: PLR6301 + def test_all_argparse_options_are_documented_or_excluded(self) -> None: """Verify that all argparse options are either documented or explicitly excluded. This test warns (not fails) when a new CLI option is added to arguments.py but not added to CLI_OPTION_META. Unregistered options are auto-categorized as "General Options" in the documentation. """ - import warnings # noqa: PLC0415 + import warnings - def test_canonical_option_determination_is_stable(self) -> None: # noqa: PLR6301 + def test_canonical_option_determination_is_stable(self) -> None: """Verify that canonical option determination is deterministic. The canonical option should be the longest option string for each action. If multiple options have the same length, the lexicographically last one should be chosen for stability. """ - from datamodel_code_generator.arguments import arg_parser as argument_parser # noqa: PLC0415 - from datamodel_code_generator.cli_options import _canonical_option_key # noqa: PLC0415 + from datamodel_code_generator.arguments import arg_parser as argument_parser + from datamodel_code_generator.cli_options import _canonical_option_keyAlso applies to: 36-36, 48-48, 58-58, 68-68, 75-75, 94-94, 101-102
tests/cli_doc/test_cli_doc_coverage.py (2)
60-60: Remove unusednoqadirectives.The
PLR6301directives are not needed as the rule is not enabled in your Ruff configuration.Apply this diff:
- def test_documented_options_have_cli_doc_markers( # noqa: PLR6301 + def test_documented_options_have_cli_doc_markers( self, collected_options: set[str] ) -> None: - def test_documented_options_have_meta(self) -> None: # noqa: PLR6301 + def test_documented_options_have_meta(self) -> None: - def test_documented_options_not_excluded(self) -> None: # noqa: PLR6301 + def test_documented_options_not_excluded(self) -> None: - def test_collection_schema_version( # noqa: PLR6301 + def test_collection_schema_version( self, collection_data: dict[str, Any] ) -> None:Also applies to: 72-72, 82-82, 91-91
104-104: Remove unusednoqadirectives.Apply this diff:
- def test_show_coverage_stats( # noqa: PLR6301 + def test_show_coverage_stats( self, collected_options: set[str] ) -> None: - def test_show_documented_options( # noqa: PLR6301 + def test_show_documented_options( self, collected_options: set[str] ) -> None:Also applies to: 116-116
src/datamodel_code_generator/cli_options.py (1)
227-227: Remove unusednoqadirectives.The
PLC0415(import-outside-toplevel) andSLF001(private-member-access) directives are not enabled in your Ruff configuration.Apply this diff:
- from datamodel_code_generator.arguments import arg_parser as argument_parser # noqa: PLC0415 + from datamodel_code_generator.arguments import arg_parser as argument_parser alias_map: dict[str, str] = {} - for action in argument_parser._actions: # noqa: SLF001 + for action in argument_parser._actions:Note: While accessing
_actionsis technically a private API, it's the standard way to introspect argparse parsers, so the implementation is correct.Also applies to: 230-230
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/datamodel_code_generator/cli_options.py(1 hunks)tests/cli_doc/test_cli_doc_coverage.py(1 hunks)tests/cli_doc/test_cli_options_sync.py(1 hunks)tests/conftest.py(3 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
tests/cli_doc/test_cli_options_sync.py (1)
src/datamodel_code_generator/cli_options.py (2)
get_all_canonical_options(255-257)_canonical_option_key(208-217)
tests/cli_doc/test_cli_doc_coverage.py (2)
src/datamodel_code_generator/cli_options.py (2)
get_all_canonical_options(255-257)get_canonical_option(240-251)src/datamodel_code_generator/parser/base.py (1)
parent(567-569)
🪛 Ruff (0.14.8)
tests/cli_doc/test_cli_options_sync.py
23-23: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
36-36: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
48-48: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
58-58: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
68-68: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
75-75: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
94-94: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
101-101: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
102-102: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
tests/cli_doc/test_cli_doc_coverage.py
60-60: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
72-72: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
82-82: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
91-91: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
104-104: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
116-116: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
src/datamodel_code_generator/cli_options.py
227-227: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
230-230: Unused noqa directive (non-enabled: SLF001)
Remove unused noqa directive
(RUF100)
tests/conftest.py
49-49: Unused noqa directive (non-enabled: PLR0912)
Remove unused noqa directive
(RUF100)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
- GitHub Check: Analyze (python)
- GitHub Check: 3.10 on Windows
- GitHub Check: 3.11 on Windows
- GitHub Check: 3.12 on macOS
- GitHub Check: 3.14 on Windows
- GitHub Check: 3.12 on Windows
- GitHub Check: 3.13 on Windows
- GitHub Check: benchmarks
🔇 Additional comments (21)
tests/conftest.py (8)
22-24: LGTM!The constants are well-defined. The collection output path is appropriately placed in the
tests/cli_doc/directory, the schema version enables future evolution, and the version pattern correctly validates X.Y format.
27-34: LGTM!The pytest option registration follows standard conventions with a clear help message.
37-46: LGTM!The marker registration is comprehensive and clearly documents all parameters and requirements.
50-132: LGTM!The validation logic is comprehensive and covers all required fields, type checks, and format validations. The version pattern validation and model keys validation are particularly thorough.
135-173: LGTM!The collection logic is well-structured. Validation happens at collection time (preventing invalid markers from proceeding), error reporting is clear, and the use of
pytest.fail(pytrace=False)is appropriate for validation errors.
175-179: LGTM!Correctly skips test execution during CLI doc collection mode by returning
Truefrom thepytest_runtestloophook.
182-197: LGTM!The session finish handler correctly saves the collected metadata with proper directory creation, schema versioning, and JSON formatting.
229-235: LGTM!The terminal summary extension cleanly integrates CLI doc collection reporting with the existing code validation statistics.
tests/cli_doc/test_cli_options_sync.py (2)
1-21: LGTM!The module is well-documented with a clear explanation of its synchronization validation purpose.
23-113: LGTM!All synchronization tests are well-structured with clear, actionable error messages. The use of
warnings.warnfor the documentation coverage test is appropriate for non-critical issues, and the stability test properly validates deterministic canonical option resolution.tests/cli_doc/test_cli_doc_coverage.py (3)
1-35: LGTM!The module is well-structured with a clear purpose. Starting with a single documented option (
--frozen-dataclasses) and allowing gradual expansion is a pragmatic approach.
38-54: LGTM!The fixtures are well-designed with appropriate error handling. The skip message helpfully explains how to generate the collection file.
60-97: LGTM!The coverage tests are comprehensive and ensure that documented options meet all requirements (markers, metadata, not excluded). The schema version validation is crucial for maintaining compatibility.
src/datamodel_code_generator/cli_options.py (8)
1-16: LGTM!The module docstring clearly establishes the design principle that argparse remains the source of truth while this module provides documentation-specific metadata. The reference to synchronization tests is helpful.
18-27: LGTM!The
OptionCategoryenum provides a clear categorization scheme for documentation organization. Inheriting fromstrfacilitates serialization.
30-42: LGTM!The frozen dataclass design ensures immutability of metadata. The fields appropriately cover documentation needs including versioning and deprecation tracking.
45-52: LGTM!The excluded options are appropriate utility and meta options that don't require feature documentation.
54-205: LGTM!The CLI option metadata dictionary is comprehensive and well-organized. The section comments improve readability, and the deprecation handling for
--validationappropriately guides users to the replacement option.
208-217: LGTM!The canonical option key function correctly prioritizes the longest option string and uses lexicographic ordering for deterministic tie-breaking.
220-237: LGTM!The alias map builder correctly uses caching to avoid repeated computation, employs late imports to prevent circular dependencies, and properly selects canonical options using the key function.
240-278: LGTM!The public API functions are well-designed:
- All properly canonicalize input options before processing
get_option_metaincludes a thoughtful fallback to auto-categorize new options as "General" rather than failing- Caching and immutable return types (frozenset) optimize repeated calls
🤖 Generated by GitHub Actions
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (3)
tests/test_main_kr.py (3)
1192-1199: Remove redundant# noqa: PLC0415comments.Ruff reports RUF100 for several
# noqa: PLC0415comments on function-local imports since PLC0415 is not enabled. These can be safely removed.- from unittest.mock import Mock # noqa: PLC0415 + from unittest.mock import Mock ... - from datamodel_code_generator.__main__ import main # noqa: PLC0415 + from datamodel_code_generator.__main__ import main
1353-1359: Remove unused noqa directives in test_http_ignore_tls.Same issue as above - the
# noqa: PLC0415directives are unnecessary.- from unittest.mock import Mock, patch # noqa: PLC0415 + from unittest.mock import Mock, patch ... - from datamodel_code_generator.__main__ import main # noqa: PLC0415 + from datamodel_code_generator.__main__ import main
1392-1398: Remove unused noqa directives in test_http_query_parameters.Same issue - remove the unnecessary
# noqa: PLC0415comments.- from unittest.mock import Mock, patch # noqa: PLC0415 + from unittest.mock import Mock, patch ... - from datamodel_code_generator.__main__ import main # noqa: PLC0415 + from datamodel_code_generator.__main__ import main
🧹 Nitpick comments (7)
docs/cli-reference/quick-reference.md (1)
25-35: Format dunder names as code and avoid mid‑word truncation.Two small polish items here:
- Rows mentioning
__future__and__all__/__init__.pyread more clearly (and avoid markdownlint complaints) if those identifiers are wrapped in backticks, e.g.Generate `__all__` exports for child modules in `__init__.py` files.- The description for
--set-default-enum-memberin the alphabetical index currently ends with “enum fiel...”; consider rephrasing to a full word (“enum fields”) or otherwise avoiding a mid‑word cutoff.Also applies to: 132-140, 213-215
docs/cli-reference/field-customization.md (1)
1694-1701: Fix “presesnt” typo in special-prefix example text.The title/description string “Id must be presesnt and must be a URI” in the input schema and generated model contains a typo. If this wording isn’t constrained by an external spec, consider correcting it to “present” in both places for more polished docs.
Also applies to: 1725-1727
docs/cli-reference/typing-customization.md (1)
552-565: Rephrase--use-annotated/--use-union-operatordescriptions to be user‑facing.Both options are described as “Test GraphQL annotated types…”, which sounds like internal test wording rather than CLI behavior. Consider rephrasing along the lines of:
--use-annotated: “Generate GraphQL (and other) types usingtyping.Annotatedplus modern collection/union syntax.”--use-union-operator: “Use the|union operator (A | B) instead oftyping.Union[A, B]in generated types (especially for GraphQL models).”This keeps the intent clear for end‑users and still matches the examples.
Also applies to: 1363-1376
tests/cli_doc/test_cli_doc_coverage.py (1)
32-35: Consider expanding DOCUMENTED_OPTIONS set.Currently only
--frozen-dataclassesis listed as a documented option, but the tests intest_main_kr.pyadd cli_doc markers to many more options (like--use-schema-description,--use-pendulum,--no-alias, etc.). Consider expanding this set to include all options that now have cli_doc markers, or document why this set intentionally starts small.scripts/build_cli_docs.py (3)
28-29: sys.path manipulation could be fragile.The
sys.path.insert(0, ...)approach works but is fragile. Consider using a package installation approach (e.g.,pip install -e .) in the CI workflow to avoid path manipulation, or document why this is necessary for standalone script execution.
453-464: Subprocess execution looks safe but consider adding timeout.The subprocess call uses a fixed command without shell=True, which is secure. However, consider adding a
timeoutparameter to prevent indefinite hangs if pytest gets stuck.result = subprocess.run( # noqa: S603 [sys.executable, "-m", "pytest", "--collect-cli-docs", "-p", "no:xdist", "-q"], check=False, capture_output=True, text=True, cwd=Path(__file__).parent.parent, + timeout=300, # 5 minute timeout )
542-558: Broad exception handling may hide specific errors.The
except (OSError, ValueError, KeyError)catches a wide range of exceptions. Consider logging the specific exception type and message to aid debugging when errors occur.- except (OSError, ValueError, KeyError): + except (OSError, ValueError, KeyError) as e: + print(f"Error generating {output_path.name}: {e}", file=sys.stderr) errors += 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (10)
docs/cli-reference/base-options.md(1 hunks)docs/cli-reference/field-customization.md(1 hunks)docs/cli-reference/general-options.md(1 hunks)docs/cli-reference/openapi-only-options.md(1 hunks)docs/cli-reference/quick-reference.md(1 hunks)docs/cli-reference/template-customization.md(1 hunks)docs/cli-reference/typing-customization.md(1 hunks)scripts/build_cli_docs.py(1 hunks)tests/cli_doc/test_cli_doc_coverage.py(1 hunks)tests/test_main_kr.py(7 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
tests/cli_doc/test_cli_doc_coverage.py (1)
src/datamodel_code_generator/cli_options.py (2)
get_all_canonical_options(255-257)get_canonical_option(240-251)
scripts/build_cli_docs.py (1)
src/datamodel_code_generator/cli_options.py (4)
OptionCategory(18-27)get_canonical_option(240-251)get_option_meta(266-278)is_excluded_from_docs(260-263)
🪛 LanguageTool
docs/cli-reference/field-customization.md
[grammar] ~18-~18: Ensure spelling is correct
Context: ...um member as the default value for enum fiel... | | [--snake-case-field](#snake-ca...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
[style] ~2824-~2824: Using many exclamation marks might seem excessive (in this case: 60 exclamation marks for a text that’s 11885 characters long)
Context: ...e`](model-customization.md#class-name) !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
docs/cli-reference/template-customization.md
[style] ~2271-~2271: Using many exclamation marks might seem excessive (in this case: 45 exclamation marks for a text that’s 9401 characters long)
Context: ...le-line strings in the generated code. !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
docs/cli-reference/base-options.md
[style] ~250-~250: Using many exclamation marks might seem excessive (in this case: 15 exclamation marks for a text that’s 2469 characters long)
Context: ...nts. Format: HeaderName:HeaderValue. !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
docs/cli-reference/general-options.md
[style] ~1677-~1677: Using many exclamation marks might seem excessive (in this case: 33 exclamation marks for a text that’s 7330 characters long)
Context: ...ar output with tree-level model reuse. !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
docs/cli-reference/openapi-only-options.md
[style] ~928-~928: Using many exclamation marks might seem excessive (in this case: 15 exclamation marks for a text that’s 3514 characters long)
Context: ...ted:** Use --field-constraints instead !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
docs/cli-reference/quick-reference.md
[grammar] ~213-~213: Ensure spelling is correct
Context: ...um member as the default value for enum fiel... - [--shared-module-name](general-o...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
docs/cli-reference/typing-customization.md
[style] ~1437-~1437: Using many exclamation marks might seem excessive (in this case: 48 exclamation marks for a text that’s 9437 characters long)
Context: ...nforcing uniqueness at the type level. !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
🪛 markdownlint-cli2 (0.18.1)
docs/cli-reference/general-options.md
30-30: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
30-30: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
600-600: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
600-600: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
docs/cli-reference/quick-reference.md
30-30: Strong style
Expected: asterisk; Actual: underscore
(MD050, strong-style)
30-30: Strong style
Expected: asterisk; Actual: underscore
(MD050, strong-style)
137-137: Strong style
Expected: asterisk; Actual: underscore
(MD050, strong-style)
137-137: Strong style
Expected: asterisk; Actual: underscore
(MD050, strong-style)
137-137: Strong style
Expected: asterisk; Actual: underscore
(MD050, strong-style)
137-137: Strong style
Expected: asterisk; Actual: underscore
(MD050, strong-style)
157-157: Strong style
Expected: asterisk; Actual: underscore
(MD050, strong-style)
157-157: Strong style
Expected: asterisk; Actual: underscore
(MD050, strong-style)
157-157: Strong style
Expected: asterisk; Actual: underscore
(MD050, strong-style)
157-157: Strong style
Expected: asterisk; Actual: underscore
(MD050, strong-style)
173-173: Strong style
Expected: asterisk; Actual: underscore
(MD050, strong-style)
173-173: Strong style
Expected: asterisk; Actual: underscore
(MD050, strong-style)
🪛 Ruff (0.14.8)
tests/cli_doc/test_cli_doc_coverage.py
60-60: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
72-72: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
82-82: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
91-91: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
104-104: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
112-112: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
114-114: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
117-117: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
121-121: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
125-125: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
tests/test_main_kr.py
1192-1192: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
1199-1199: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
1353-1353: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
1359-1359: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
1392-1392: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
1398-1398: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
scripts/build_cli_docs.py
22-22: Unused noqa directive (non-enabled: S404)
Remove unused noqa directive
(RUF100)
154-154: Unused noqa directive (non-enabled: PLR0912, PLR0914, PLR0915)
Remove unused noqa directive
(RUF100)
467-467: Unused noqa directive (non-enabled: PLR0912, PLR0915)
Remove unused noqa directive
(RUF100)
482-482: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
563-563: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
567-567: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
🔇 Additional comments (7)
docs/cli-reference/base-options.md (1)
5-12: Base options docs look consistent and clear.The table and the detailed
--outputsection now accurately distinguish input vs output behavior and cover file/dir/stdout semantics; examples align with the text.Also applies to: 182-190
docs/cli-reference/openapi-only-options.md (1)
32-49: YAML examples and option sections look good.The OpenAPI‑only option docs are consistent and the YAML examples now use the correct
yamlfences; usage and output snippets match the described behavior.Also applies to: 122-139, 581-590, 657-666, 939-948
docs/cli-reference/template-customization.md (1)
1-22: Well-structured CLI reference documentation.The documentation page provides comprehensive coverage of template customization options with consistent formatting. Each option includes usage examples, input schemas, and output examples using MkDocs Material syntax appropriately.
tests/test_main_kr.py (1)
250-272: Good use of cli_doc markers for documentation generation.The cli_doc markers provide comprehensive metadata including options, input_schema, cli_args, golden_output, and related_options. The docstrings are well-written and will generate useful documentation.
tests/cli_doc/test_cli_doc_coverage.py (1)
60-125: Test class structure is appropriate for coverage verification.The tests properly verify that documented options have cli_doc markers, CLI_OPTION_META entries, and are not in EXCLUDED_FROM_DOCS. The informational stats tests (skipped by default) provide useful debugging capabilities.
Note: The noqa directives (PLR6301, T201) flagged by Ruff are for rules that don't appear to be enabled in this project's configuration, so they're harmless but could be cleaned up for consistency.
scripts/build_cli_docs.py (2)
64-103: Good path traversal protection.The
safe_read_filefunction properly validates that resolved paths don't escape the base directory usingrelative_to(). This prevents path traversal attacks when reading files from collection metadata.
571-595: Main function is well-structured.The CLI interface with
--checkand--collectflags provides good flexibility for both local development and CI usage. The return codes are appropriate for shell scripting.
There was a problem hiding this comment.
Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
.github/workflows/cli-docs.yaml(1 hunks)tests/cli_doc/test_cli_options_sync.py(1 hunks)tests/test_main_kr.py(7 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
tests/cli_doc/test_cli_options_sync.py (1)
src/datamodel_code_generator/cli_options.py (3)
get_all_canonical_options(255-257)get_canonical_option(240-251)_canonical_option_key(208-217)
tests/test_main_kr.py (4)
src/datamodel_code_generator/__init__.py (1)
chdir(153-163)src/datamodel_code_generator/__main__.py (2)
Exit(85-91)main(655-956)tests/conftest.py (1)
freeze_time(276-279)tests/main/conftest.py (1)
output_file(94-96)
🪛 Ruff (0.14.8)
tests/cli_doc/test_cli_options_sync.py
32-32: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
45-45: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
57-57: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
67-67: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
77-77: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
84-84: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
103-103: Unused noqa directive (non-enabled: PLR6301)
Remove unused noqa directive
(RUF100)
110-110: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
111-111: Unused noqa directive (non-enabled: PLC0415)
Remove unused noqa directive
(RUF100)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
- GitHub Check: 3.12 on Windows
- GitHub Check: 3.13 on macOS
- GitHub Check: 3.10 on Windows
- GitHub Check: 3.10 on macOS
- GitHub Check: 3.9 on Windows
- GitHub Check: 3.13 on Windows
- GitHub Check: 3.12 on macOS
- GitHub Check: 3.14 on Windows
- GitHub Check: 3.11 on Windows
- GitHub Check: Analyze (python)
- GitHub Check: benchmarks
🔇 Additional comments (1)
.github/workflows/cli-docs.yaml (1)
1-71: LGTM - Well-structured CLI documentation automation.The workflow correctly separates concerns:
- PR job verifies docs are current without modifying files
- Push job auto-generates and commits doc updates
- Both use consistent tooling (uv, tox, pytest collection)
The conditional job execution (
if: github.event_name == ...) ensures appropriate behavior for each trigger.
fa73bc1 to
41e9831
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
tests/main/jsonschema/test_main_jsonschema.py (3)
1236-1253:--disable-timestampis documented but not exercised in this testThe
cli_docmetadata and docstring describe--disable-timestamp, buttest_main_jsonschema_patterndoes not pass this flag inextra_args. That means:
- The golden output (
jsonschema/pattern.py) is either not actually generated using--disable-timestamp, or- The test isn’t verifying the documented behavior.
Consider aligning these by either:
- Adding
extra_args=["--disable-timestamp"]here and regeneratingpattern.py, or- Adjusting the
cli_docblock (and docstring) if this test is meant to cover the default behavior instead.
1671-1715: Prefix options use different values in docs vs testsFor
--special-field-name-prefixand--empty-enum-field-name:
pytest.mark.cli_docusescli_args=["--special-field-name-prefix", "special_"]andcli_args=["--empty-enum-field-name", "empty_"].- The corresponding tests call
run_main_and_assertwithextra_args=["--special-field-name-prefix", "special"]andextra_args=["--empty-enum-field-name", "empty"].Since these prefixes affect generated identifiers, the CLI examples shown in docs will not reproduce the golden outputs used by the tests.
Recommend making the values consistent (e.g., switch the
cli_doccli_argsto"special"/"empty"or adjust the tests and regenerate the expected files) so that the documented commands match the showcased outputs.Also applies to: 1793-1811
1875-1898:--union-modeexample doesn’t match the showcased output fileThe
cli_docfor--union-modeuses:
cli_args=["--union-mode", "left_to_right"]golden_output="jsonschema/combine_any_of_object.py"But
test_main_jsonschema_combine_any_of_objectparameterization associates:
expected_output="combine_any_of_object.py"with the default union mode (union_mode is None), andexpected_output="combine_any_of_object_left_to_right.py"withunion_mode="left_to_right".So the docs currently show a
left_to_rightcommand but the output snippet comes from the default mode. Please either:
- Point
golden_outputto the left‑to‑right fixture (jsonschema/combine_any_of_object_left_to_right.py), or- Change the
cli_argsin thecli_docto reflect the default behavior if that’s what you want to illustrate.This keeps the CLI example and rendered output in sync.
🧹 Nitpick comments (2)
tests/data/jsonschema/ignore_pyproject_example.json (1)
1-8: LGTM! Clean and appropriate test fixture.The schema is syntactically valid and follows JSON Schema draft-07 correctly. The minimal structure is well-suited for CLI documentation examples, making it easy for users to understand the feature without distraction.
Optionally, you could enhance test coverage by adding validation constraints:
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "firstName": {"type": "string"}, "lastName": {"type": "string"} - } + }, + "required": ["firstName", "lastName"], + "additionalProperties": false }This would demonstrate how the tool handles required fields and strict schemas, but the current minimal version is perfectly fine for documentation purposes.
scripts/build_cli_docs.py (1)
188-197: Refine “Usage” snippet to avoid conflicting--input/--urlexamples
generate_option_sectionalways prefixes the usage withdatamodel-codegen --input schema.jsonunlessconfig_contentis present. For options like--inputand--url, this yields examples such as:
datamodel-codegen --input schema.json --input pet_simple.json ...datamodel-codegen --input schema.json --url https://...which are confusing and may not reflect valid invocations.
Consider making the baseline
--input schema.jsonconditional oncli_argsnot already containing--inputor--url, e.g.:has_input_or_url = any(a in {"--input", "--url"} for a in cli_args) md += " datamodel-codegen " if not has_input_or_url: md += "--input schema.json "This keeps the examples minimal and accurate while still showing the documented option in context.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
scripts/build_cli_docs.py(1 hunks)tests/data/expected/main_kr/ignore_pyproject/without_option.py(1 hunks)tests/data/jsonschema/ignore_pyproject_example.json(1 hunks)tests/main/jsonschema/test_main_jsonschema.py(37 hunks)tests/test_main_kr.py(7 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
scripts/build_cli_docs.py (1)
src/datamodel_code_generator/cli_options.py (4)
OptionCategory(18-27)get_canonical_option(240-251)get_option_meta(266-278)is_excluded_from_docs(260-263)
🪛 Ruff (0.14.8)
scripts/build_cli_docs.py
22-22: Unused noqa directive (non-enabled: S404)
Remove unused noqa directive
(RUF100)
157-157: Unused noqa directive (non-enabled: PLR0912, PLR0914, PLR0915)
Remove unused noqa directive
(RUF100)
470-470: Unused noqa directive (non-enabled: PLR0912, PLR0915)
Remove unused noqa directive
(RUF100)
485-485: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
566-566: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
570-570: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (16)
- GitHub Check: py312-black22 on Ubuntu
- GitHub Check: 3.11 on Ubuntu
- GitHub Check: 3.10 on Windows
- GitHub Check: 3.12 on Ubuntu
- GitHub Check: 3.12 on Windows
- GitHub Check: py312-black24 on Ubuntu
- GitHub Check: 3.11 on macOS
- GitHub Check: 3.9 on Windows
- GitHub Check: 3.10 on Ubuntu
- GitHub Check: 3.13 on Windows
- GitHub Check: py312-black23 on Ubuntu
- GitHub Check: 3.11 on Windows
- GitHub Check: 3.14 on Ubuntu
- GitHub Check: 3.14 on Windows
- GitHub Check: benchmarks
- GitHub Check: Analyze (python)
🔇 Additional comments (3)
tests/data/expected/main_kr/ignore_pyproject/without_option.py (1)
1-13: LGTM! Valid test fixture.This test fixture correctly demonstrates the expected output from datamodel-code-generator. The Pydantic model is properly structured with appropriate use of field aliases to map between Python's snake_case naming convention and JSON's camelCase convention.
tests/main/jsonschema/test_main_jsonschema.py (1)
3803-3819: Nice use of--aliasesCLI doc metadataThe
cli_docblock for--aliasesis consistent with the test: input schema, CLI args, and golden output all align, and the example exercises a realistic scoped aliases configuration. This should generate clear, reproducible docs.tests/test_main_kr.py (1)
1181-1213: HTTP header URL test looks correct and aligned with CLI docs
test_url_with_http_headersnow usesMockerFixturecorrectly, patcheshttpx.get, and asserts both theExitcode and generated output path that matches thecli_docgolden_output. This is a solid example for the--urland--http-headersdocumentation.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
scripts/build_cli_docs.py (1)
22-22: Unused noqa directives flagged by Ruff.Ruff reports that several noqa directives are no longer needed because the suppressed rules (S404, PLR0912, PLR0914, PLR0915, T201) are not enabled in the project's configuration. These can be safely removed.
Note: This issue was previously reported and marked as addressed in past reviews.
Also applies to: 157-157, 470-470, 485-485, 565-565, 569-569, 573-573
🧹 Nitpick comments (7)
docs/cli-reference/base-options.md (1)
244-255: Clarify--urlusage example to avoid implying--inputis requiredThe
--urldescription says it fetches the schema “instead of a local file”, but the usage snippet also passes--input schema.json. That can read as if a local input is still required. Consider simplifying the example to focus on--url(and documenting--inputas optional/alternative separately), e.g.:datamodel-codegen --url https://api.example.com/schema.json --http-headers "Authorization:Bearer token"to match how the tests exercise this flag.
tests/test_main_kr.py (2)
1187-1213: Strengthen--http-headerstest by asserting passed headersThe test already patches
httpx.getand checks the generated file, but it doesn’t assert that theAuthorization:Bearer tokenheader actually reacheshttpx.get. For parity withtest_http_ignore_tls/test_http_query_parameters, consider:httpx_get = mocker.patch("httpx.get", return_value=mock_response) # ... assert return_code == 0 httpx_get.assert_called_once() call_kwargs = httpx_get.call_args[1] assert call_kwargs.get("headers") == {"Authorization": "Bearer token"}This would verify that
--http-headersis wired correctly, not just that generation succeeds.
1519-1546: Aligntest_target_python_version_outputsdocstring with actual CLI argsThe docstring explains differences in both union syntax and container types across Python versions, but the test always passes
--use-standard-collections, so the 3.9 example will already use built-inlist/dict. To keep docs and behavior aligned, either:
- Adjust the docstring to focus on what this test actually demonstrates (e.g. union syntax and any other visible deltas), or
- Drop
--use-standard-collectionshere so the example more clearly shows container-type differences driven solely by--target-python-version.docs/cli-reference/general-options.md (1)
1414-1423: Clarify--http-headersusage so--inputisn’t misread as mandatoryHere the description is about decorating a
--urlfetch with headers, but the example command also includes--input schema.json. Since typical usage (and the tests) work with just--urlplus--http-headers, consider simplifying the snippet to:datamodel-codegen --url https://api.example.com/schema.json --http-headers "Authorization:Bearer token"and, if needed, explaining separately that
--inputcan be combined with--urlwhen both are intentionally used.docs/cli-reference/template-customization.md (1)
1255-1278: Update--disable-timestampexample to actually omit the timestamp lineThe section says
--disable-timestampremoves the timestamp from the generated header for reproducible output, but the example still includes a# timestamp: …line. To make the behavior clear, it would be better to use an output snippet generated with this flag so the header shows only the filename (and optional version header), without a timestamp line.scripts/build_cli_docs.py (2)
237-243: Consider extracting duplicated model configuration to constants.The
model_labelsdictionary andorderlist are defined identically in two places within this function. Extract them as module-level constants to follow DRY principles and simplify future maintenance.Add near the top of the file (after line 47):
+MODEL_LABELS = { + "pydantic_v1": "Pydantic v1", + "pydantic_v2": "Pydantic v2", + "dataclass": "dataclass", + "typeddict": "TypedDict", + "msgspec": "msgspec", +} +MODEL_ORDER = ["pydantic_v1", "pydantic_v2", "dataclass", "typeddict", "msgspec"]Then replace both occurrences in the function:
- model_labels = { - "pydantic_v1": "Pydantic v1", - "pydantic_v2": "Pydantic v2", - "dataclass": "dataclass", - "typeddict": "TypedDict", - "msgspec": "msgspec", - } - order = ["pydantic_v1", "pydantic_v2", "dataclass", "typeddict", "msgspec"] sorted_models = sorted( kwargs["model_outputs"].items(), - key=lambda x: order.index(x[0]) if x[0] in order else len(order), + key=lambda x: MODEL_ORDER.index(x[0]) if x[0] in MODEL_ORDER else len(MODEL_ORDER), ) for model_key, output_file in sorted_models: - label = model_labels.get(model_key, model_key) + label = MODEL_LABELS.get(model_key, model_key)Also applies to: 244-244, 289-295, 296-296
456-467: Consider printing stderr when pytest collection fails.The function captures pytest output but doesn't display it when the command fails. Printing
result.stderrwould help users diagnose collection failures.def collect_cli_docs() -> int: """Run pytest to collect CLI doc metadata.""" result = subprocess.run( # noqa: S603 [sys.executable, "-m", "pytest", "--collect-cli-docs", "-p", "no:xdist", "-q"], check=False, capture_output=True, text=True, cwd=Path(__file__).parent.parent, ) if result.returncode != 0: + if result.stderr: + print(result.stderr, file=sys.stderr) return result.returncode return 0
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
.github/workflows/cli-docs.yaml(1 hunks)docs/cli-reference/base-options.md(1 hunks)docs/cli-reference/field-customization.md(1 hunks)docs/cli-reference/general-options.md(1 hunks)docs/cli-reference/template-customization.md(1 hunks)scripts/build_cli_docs.py(1 hunks)tests/data/jsonschema/formatter_kwargs.json(1 hunks)tests/test_main_kr.py(7 hunks)
✅ Files skipped from review due to trivial changes (1)
- tests/data/jsonschema/formatter_kwargs.json
🚧 Files skipped from review as they are similar to previous changes (1)
- .github/workflows/cli-docs.yaml
🧰 Additional context used
🧬 Code graph analysis (2)
tests/test_main_kr.py (4)
src/datamodel_code_generator/__init__.py (1)
chdir(153-163)src/datamodel_code_generator/__main__.py (3)
Exit(85-91)main(655-956)get(108-110)tests/conftest.py (1)
create_assert_file_content(417-468)src/datamodel_code_generator/reference.py (1)
get(843-845)
scripts/build_cli_docs.py (1)
src/datamodel_code_generator/cli_options.py (4)
OptionCategory(18-27)get_canonical_option(240-251)get_option_meta(266-278)is_excluded_from_docs(260-263)
🪛 LanguageTool
docs/cli-reference/field-customization.md
[grammar] ~18-~18: Ensure spelling is correct
Context: ...um member as the default value for enum fiel... | | [--snake-case-field](#snake-ca...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
[style] ~2824-~2824: Using many exclamation marks might seem excessive (in this case: 60 exclamation marks for a text that’s 11885 characters long)
Context: ...e`](model-customization.md#class-name) !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
docs/cli-reference/base-options.md
[style] ~250-~250: Using many exclamation marks might seem excessive (in this case: 15 exclamation marks for a text that’s 2469 characters long)
Context: ...nts. Format: HeaderName:HeaderValue. !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
docs/cli-reference/general-options.md
[style] ~1669-~1669: Using many exclamation marks might seem excessive (in this case: 33 exclamation marks for a text that’s 7322 characters long)
Context: ...ar output with tree-level model reuse. !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
docs/cli-reference/template-customization.md
[style] ~2271-~2271: Using many exclamation marks might seem excessive (in this case: 45 exclamation marks for a text that’s 9401 characters long)
Context: ...le-line strings in the generated code. !!! tip "Usage" ```bash datamodel-...
(EN_EXCESSIVE_EXCLAMATION)
🪛 markdownlint-cli2 (0.18.1)
docs/cli-reference/general-options.md
30-30: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
30-30: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
600-600: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
600-600: Strong style
Expected: underscore; Actual: asterisk
(MD050, strong-style)
🪛 Ruff (0.14.8)
scripts/build_cli_docs.py
22-22: Unused noqa directive (non-enabled: S404)
Remove unused noqa directive
(RUF100)
157-157: Unused noqa directive (non-enabled: PLR0912, PLR0914, PLR0915)
Remove unused noqa directive
(RUF100)
470-470: Unused noqa directive (non-enabled: PLR0912, PLR0915)
Remove unused noqa directive
(RUF100)
485-485: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
565-565: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
569-569: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
573-573: Unused noqa directive (non-enabled: T201)
Remove unused noqa directive
(RUF100)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
- GitHub Check: 3.10 on Windows
- GitHub Check: 3.9 on Windows
- GitHub Check: 3.14 on Windows
- GitHub Check: 3.12 on Windows
- GitHub Check: 3.11 on Windows
- GitHub Check: 3.13 on Windows
- GitHub Check: 3.13 on macOS
- GitHub Check: 3.12 on macOS
- GitHub Check: Analyze (python)
- GitHub Check: benchmarks
🔇 Additional comments (2)
docs/cli-reference/field-customization.md (1)
5-27: Well-structured field customization options tableThe top-level options table cleanly enumerates all field-related flags with concise, accurate descriptions that match the detailed sections below. This makes the page easy to scan and aligns well with the per-option examples.
tests/test_main_kr.py (1)
7-23: Nice use of TYPE_CHECKING and localized typing for pytest-mockImporting
Mock/patchat runtime and gatingMockerFixturebehindTYPE_CHECKINGkeeps runtime dependencies slim while still providing good type information for static analysis. The imports ofExit,main, andarg_parseralso make later tests more explicit and readable.
Summary
@pytest.mark.cli_doc()markers on test functionsCloses #133
Summary by CodeRabbit
New Features
Documentation
Chores
✏️ Tip: You can customize this high-level summary in your review settings.