Skip to content

feat: add python_dep for Python version constraints - #202

Merged
stanislavlevin merged 1 commit into
mainfrom
issue_201
Nov 20, 2026
Merged

stanislavlevin merged 1 commit into
mainfrom
issue_201

Conversation

@stanislavlevin

@stanislavlevin stanislavlevin commented Nov 17, 2026 •

Copy link
Copy Markdown
Owner

Add python_dep to collect the project's Requires-Python, detect upstream changes, and generate interpreter dependencies.

  • sync stores the normalized constraint in pyproject_deps.json, creating a missing config or removing the constraint when metadata omits it.
  • sync --verify saves changes, prints an old/new JSON diff, and exits with code 4 if the constraint changed. Equivalent parsed specifiers compare equal.
  • print emits the stored constraint, or nothing if absent. --format supports $specifier for the full constraint or $rpmlowver for the RPM lower version limit.

The config is shared with deps; each command validates its own fields and preserves the other's data. Collection reuses the existing metadata build and cache handling. --depsconfig PATH selects another config file.

For Requires-Python: >=3.12,<4:

$ python -m pyproject_installer python_dep sync
$ python -m pyproject_installer python_dep print --format='python3$rpmlowver'
python3 >= 3.12

Fixes: #201

Summary by Sourcery

Add Python version constraint management from Requires-Python, including shared configuration storage, drift verification, and downstream dependency output.

New Features:

  • Add a python_dep command to collect and store normalized Python version constraints from project metadata.
  • Support printing stored constraints as normalized specifiers or RPM-compatible lower version dependencies.

Bug Fixes:

  • Detect Python constraint drift during verification, including additions and removals, with the appropriate exit status.

Enhancements:

  • Share dependency configuration handling between deps and python_dep while allowing each command to validate and preserve its own data.
  • Reuse metadata collection and caching for Python version constraint discovery.
  • Document shared configuration and metadata-cache concurrency requirements.

Documentation:

  • Document the python_dep command, synchronization and verification behavior, output formats, and configuration semantics.
  • Add design documentation for Python dependency collection and metadata-cache concurrency.

Tests:

  • Add CLI, metadata collection, configuration synchronization, verification, validation, and output-format coverage for python_dep.
  • Add tests ensuring existing dependency configuration data is preserved by both dependency commands.

@sourcery-ai

sourcery-ai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 50a1601

#201 Python version requirements must be tracked manually · 2 of 2 met

# Requirement Status Notes
1 Track the project's Requires-Python constraint for use when writing interpreter dependencies. ✅ Met python_dep sync collects and stores the normalized constraint, and print makes it available in PEP 440 or RPM lower-limit format.
2 Make upstream changes to the Python version constraint detectable. ✅ Met sync --verify compares parsed constraints, saves changes, and reports an old/new diff when the constraint changes.

@sourcery-ai sourcery-ai 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.

Hey - I've found 7 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/pyproject_installer/deps_cmd/deps_config_base.py" line_range="82" />
<code_context>
-        self.validate_config(self.config)
-        # first parse the whole config
-        json_config = self._to_json(self.config)
-        self.file.write_text(json_config, encoding="utf-8")
-        logger.debug("Saved config file %s", self.file)
+    def validate_collector(
</code_context>
<issue_to_address>
**Concurrent sync loses config data**

When both commands load the shared config before either saves, `deps sync` and `python_dep sync` each save a full in-memory config snapshot, so the later save overwrites the earlier command's fields and the caller finds dependency sources or `requires_python` missing.

Reload and merge each command's changes under a shared lock before saving.

Also at `src/pyproject_installer/python_dep_cmd/deps_config.py:55-71`.
</issue_to_address>

### Comment 2
<location path="src/pyproject_installer/deps_cmd/deps_config_base.py" line_range="82" />
<code_context>
-        self.validate_config(self.config)
-        # first parse the whole config
-        json_config = self._to_json(self.config)
-        self.file.write_text(json_config, encoding="utf-8")
-        logger.debug("Saved config file %s", self.file)
+    def validate_collector(
</code_context>
<issue_to_address>
**Interrupted save corrupts config**

When the process stops or a write error occurs during a config save, `Path.write_text` truncates the existing config before completing the JSON write, leaving invalid or partial JSON that prevents both commands from loading the shared data.

Write the complete JSON to a temporary file and atomically replace the config.
</issue_to_address>

### Comment 3
<location path="src/pyproject_installer/python_dep_cmd/collector.py" line_range="15" />
<code_context>
+
+    def collect(self) -> Iterator[str]:
+        """Yield normalized Requires-Python when present."""
+        requires_python = self.parsed_metadata().requires_python
+        yield from [str(requires_python)] if requires_python is not None else []
</code_context>
<issue_to_address>
**Older metadata replaces fresh cache**

When two callers miss the cache, the project metadata changes between their builds, and the older build finishes last, the slower build can write its older metadata after a second build has cached newer metadata; subsequent `deps` and `python_dep` commands then read the stale cache and store outdated requirements or Python constraints.

Coordinate cache population so a build cannot overwrite metadata produced from a newer project state.
</issue_to_address>

### Comment 4
<location path="src/pyproject_installer/python_dep_cmd/deps_config.py" line_range="108" />
<code_context>
+                constraint is not None
+                and "rpmlowver" in template.get_identifiers()
+            ):
+                lower_limit = rpm_lower_limit(constraint)
+            output = template.safe_substitute(
+                specifier=output,
</code_context>
<issue_to_address>
**Epoch bounds are weakened**

When `Requires-Python` contains an epoch lower bound and the caller prints `$rpmlowver`, `rpm_lower_limit` derives the RPM lower bound from `Version.release`, which drops the PEP 440 epoch. A constraint such as `>=1!3.12` is therefore printed as `>= 3.12`, allowing an interpreter version that does not satisfy the stored constraint to meet the generated dependency.

Preserve the epoch in the RPM version requirement when supported, or avoid emitting a lower bound that does not enforce the declared epoch.
</issue_to_address>

### Comment 5
<location path="src/pyproject_installer/python_dep_cmd/deps_config.py" line_range="71-79" />
<code_context>
-    @config.setter
-    def config(self, value: DepsConfigType) -> None:
-        self._config = deepcopy(value)
-        self.save()
-
-    def set_default(self) -> None:
</code_context>
<issue_to_address>
**Verification retry hides drift**

When A `sync --verify` process stops after saving a change but before printing the diff and exiting with code 4, `sync` saves the new constraint before printing the diff or raising `DepsUnsyncedError`; a retry then sees equal specifiers and returns successfully, so the caller receives no indication that the original verification found drift.

Persist enough verification state to report the drift if the command is retried after saving.
</issue_to_address>

### Comment 6
<location path="src/pyproject_installer/python_dep_cmd/collector.py" line_range="16" />
<code_context>
+    def collect(self) -> Iterator[str]:
+        """Yield normalized Requires-Python when present."""
+        requires_python = self.parsed_metadata().requires_python
+        yield from [str(requires_python)] if requires_python is not None else []
</code_context>
<issue_to_address>
**Empty constraints appear absent**

When metadata contains a blank `Requires-Python` field or the config contains `"requires_python": ""`, `SpecifierSet("")` is accepted and stringifies to `""`, so a blank metadata field is stored as `requires_python: ""` and an empty string in an existing config passes validation. `print` then emits nothing, making that stored value indistinguishable from an absent constraint to callers.

Reject empty specifier sets as invalid constraints, or consistently treat them as absent before syncing and printing.

Also at `src/pyproject_installer/python_dep_cmd/deps_config.py:38`.
</issue_to_address>

### Comment 7
<location path="README.md" line_range="740-815" />
<code_context>
+python -m pyproject_installer python_dep sync
</code_context>
<issue_to_address>
**Examples use the real project name**

When readers consult the newly added command examples, the new README and design examples invoke `python -m pyproject_installer`, so the usage material violates the requirement to use fictional or generic names.

Use a generic or fictional module name in illustrative examples, clearly marking them as placeholders.

Also at `docs/designs/python_dep.md:88-105`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 6 findings to address first, and sync writes or removes requires_python in the shared JSON config, and print can expose that constraint to downstream packaging. A wrong value remains after reverting the code, but it is bounded and can be corrected by syncing again or editing the config.

Blocking findings: src/pyproject_installer/deps_cmd/deps_config_base.py:82, src/pyproject_installer/deps_cmd/deps_config_base.py:82, src/pyproject_installer/python_dep_cmd/collector.py:15, src/pyproject_installer/python_dep_cmd/deps_config.py:108, src/pyproject_installer/python_dep_cmd/deps_config.py:79, and 1 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread README.md Resolved
Collect Requires-Python from core metadata so package maintainers can
generate interpreter dependencies and detect upstream changes.

Add sync with optional verification and print with PEP 440 or RPM
lower-limit formats. Store the constraint alongside dependency sources
in pyproject_deps.json, preserving each command's data and sharing the
validated metadata cache.

Fixes: #201
Assisted-by: Codex:gpt-6.1-sol
Signed-off-by: Stanislav Levin <slev@altlinux.org>
@stanislavlevin
stanislavlevin merged commit 754d61d into main Nov 20, 2026
22 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Python version requirements must be tracked manually

1 participant