Visitar URL original
Deduplicate module content builder by koxudaxi · Pull Request #3346 · datamodel-code-generator/datamodel-code-generator · GitHub
Skip to content

Deduplicate module content builder - #3346

Merged
Koudai Aono (koxudaxi) merged 1 commit into
mainfrom
refactor/module-content-builder
Jun 12, 2026
Merged

Koudai Aono (koxudaxi) merged 1 commit into
mainfrom
refactor/module-content-builder

Conversation

@koxudaxi

@koxudaxi Koudai Aono (koxudaxi) commented Jun 12, 2026 •

Copy link
Copy Markdown
Member

No description provided.

@coderabbitai

coderabbitai Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors future-import handling in module content generation. _build_module_content now accepts a future_imports parameter that takes precedence over extraction from body when a custom file header is used. The multi-file output path is simplified by delegating all content assembly to _build_module_content rather than using conditional print-based branching.

Changes

Future imports parameter propagation

Layer / File(s) Summary
Module content building with future imports parameter
src/datamodel_code_generator/__init__.py
_build_module_content signature extended with future_imports keyword parameter; extraction logic updated to use pre-supplied imports first; multi-module output writing refactored to pass module-specific future_imports through unified _build_module_content call instead of conditional re-extraction.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A rabbit hops through import lines,
Future calls now well-aligned,
No more branching paths to chase,
One function sets the proper place!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main refactoring change: consolidating and reusing module content builder logic across multiple code paths.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/module-content-builder

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codspeed

codspeed Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 10.76%

⚠️ Unknown Walltime execution environment detected

Using the Walltime instrument on standard Hosted Runners will lead to inconsistent data.

For the most accurate results, we recommend using CodSpeed Macro Runners: bare-metal machines fine-tuned for performance measurement consistency.

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

❌ 5 regressed benchmarks
✅ 6 untouched benchmarks
⏩ 98 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Mode Benchmark BASE HEAD Efficiency
❌ WallTime test_perf_deep_nested 4.8 s 5.5 s -12.31%
❌ WallTime test_perf_complex_refs 1.9 s 2.1 s -10.67%
❌ WallTime test_perf_large_models_pydantic_v2 3.4 s 3.8 s -10.64%
❌ WallTime test_perf_kubernetes_style_pydantic_v2 2.5 s 2.8 s -10.17%
❌ WallTime test_perf_duplicate_names 1 s 1.1 s -10%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing refactor/module-content-builder (52a77f5) with main (a1252a2)

Open in CodSpeed

Footnotes

  1. 98 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@github-actions

github-actions Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

📚 Docs Preview: https://pr-3346.datamodel-code-generator.pages.dev

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/datamodel_code_generator/__init__.py`:
- Around line 981-984: The code always forwards future_imports into
_build_module_content which can reintroduce from __future__ lines even when
imports are intentionally omitted (with_import=False) or when a
custom_file_header is used; modify the write call to conditionally pass
future_imports only when imports are being emitted (e.g., compute an
effective_future_imports = future_imports if with_import (or if result.body
contains imports) else None/[] and pass that into _build_module_content),
referencing the variables/_function names file, _build_module_content,
effective_header, custom_file_header, and future_imports so the future imports
are not re-inserted when with_import is False.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9a18bd4a-8a2d-4957-9c1c-233bde082695

📥 Commits

Reviewing files that changed from the base of the PR and between a1252a2 and 9298b2f.

📒 Files selected for processing (1)
  • src/datamodel_code_generator/__init__.py

Comment thread src/datamodel_code_generator/__init__.py Outdated
@codecov

codecov Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (a1252a2) to head (52a77f5).

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #3346   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          125       125           
  Lines        28265     28246   -19     
  Branches      3452      3449    -3     
=========================================
- Hits         28265     28246   -19     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@koxudaxi
Koudai Aono (koxudaxi) force-pushed the refactor/module-content-builder branch from 9298b2f to 52a77f5 Compare June 12, 2026 07:26

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/datamodel_code_generator/__init__.py (1)

946-952: 💤 Low value

Consider passing future_imports for consistency with the file-writing path.

The multi-module string-return path doesn't pass result.future_imports to _build_module_content, relying on extraction from body instead. While functionally correct (extraction fallback works), it's inconsistent with the file-writing path (line 968) which does pass it.

♻️ Suggested change for consistency
         for name, result in sorted(results.items()):
             source_filename = str(result.source.as_posix() if result.source else input_filename)
             safe_filename = source_filename.replace("\n", " ").replace("\r", " ") if source_filename else ""
             effective_header = custom_file_header or header.format(safe_filename)
-            generated[name] = _build_module_content(result.body, effective_header, custom_file_header)
+            generated[name] = _build_module_content(
+                result.body, effective_header, custom_file_header, future_imports=result.future_imports
+            )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/datamodel_code_generator/__init__.py` around lines 946 - 952, The loop
that builds the in-memory multi-module output should pass the module's explicit
future imports to _build_module_content for consistency with the file-writing
path; update the call in the for loop (where variables name, result are iterated
and safe_filename/effective_header are computed) to pass result.future_imports
as the future_imports argument to _build_module_content alongside result.body
and effective_header so it no longer relies on extracting them from the body.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/datamodel_code_generator/__init__.py`:
- Around line 946-952: The loop that builds the in-memory multi-module output
should pass the module's explicit future imports to _build_module_content for
consistency with the file-writing path; update the call in the for loop (where
variables name, result are iterated and safe_filename/effective_header are
computed) to pass result.future_imports as the future_imports argument to
_build_module_content alongside result.body and effective_header so it no longer
relies on extracting them from the body.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8d1b1886-6159-439a-a146-3a1890fade00

📥 Commits

Reviewing files that changed from the base of the PR and between 9298b2f and 52a77f5.

📒 Files selected for processing (1)
  • src/datamodel_code_generator/__init__.py

@koxudaxi
Koudai Aono (koxudaxi) merged commit 2d379eb into main Jun 12, 2026
51 of 52 checks passed
@koxudaxi
Koudai Aono (koxudaxi) deleted the refactor/module-content-builder branch June 12, 2026 08:25
@github-actions

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: The prepared analysis files (analysis-context.md, pr.diff, deleted-lines.txt) live under /home/runner/work/_temp/release-draft-pr/, which is outside this session's sandboxed working directory. Every access method was blocked: the Read tool reported permission not granted; Bash cat/grep/cp/ln/python3 were hard-blocked by the sandbox; a subagent hit the same boundary; and git-based reconstruction is impossible because the checkout is a shallow depth-1 clone (only the squash-merge commit 2d379eb exists, so git show/diff render the whole tree as added) with network fetch of the parent commit blocked. The ground rules designate the prepared diff as the only valid source of truth and forbid reporting any option/parameter/class/enum/function as removed unless it appears as a removed line in that diff. Since I could not read the diff, I have no verifiable evidence of any removed item, changed default, template change, or altered generated output. The PR title ("Deduplicate module content builder") indicates a behavior-preserving internal refactor, and no entry for #3346 exists in the current CHANGELOG. Fabricating breaking-change entries without evidence would be incorrect, so the faithful determination is that no breaking change can be substantiated.


This analysis was performed by Claude Code Action

@github-actions

Copy link
Copy Markdown
Contributor

🎉 Released in 0.64.0

This PR is now available in the latest release. See the release notes for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant