Skip to content

Make RequirementsFile a tree that knows itself - #377

Merged
Paebbels merged 9 commits into
claude/dependency-tablefrom
claude/requirements-file-tree
Sep 5, 2026
Merged

Paebbels merged 9 commits into
claude/dependency-tablefrom
claude/requirements-file-tree

Conversation

@pytooling-claude

Copy link
Copy Markdown

Summary

The twelve review points on pyTooling/Dependency/Python.py, which turn out to be one change: RequirementsFile kept a list of includes and threaded a _visited set through its recursion, and knew nothing else about the shape it was building.

Stacked on #364. Base is claude/dependency-table, so the diff shows only this change.

Every file knows where it sits

_parent is the file whose -r line referenced it, _root the entrypoint the tree was read from, and IterateToRoot() walks the chain upwards — which is what lets a requirement name the entrypoint that pulled it in.

The root keeps the mapping, and it replaces _visited entirely

_analyzedRequirementFiles holds every file of the tree by resolved path. The same mapping that detects a cycle while reading answers, afterwards, which files the tree was read from.

That second use had a duplicate: the Sphinx directive carried its own _Walk generator to re-derive exactly that list for env.note_dependency. It's deleted — two answers to one question is one too many.

Only the root's mapping is filled. A referenced file carries an empty one it never reads, because the alternative is a Nullable that every lookup has to test for a case that cannot happen.

A cycle raises

CircularRequirementsFileError, with the chain in a note:

Requirements file '…/requirements.txt' referenced in '…/other.txt' line 1 is already being read.
Chain: …/requirements.txt -> …/other.txt -> …/requirements.txt

Read-once-and-continue was the old behaviour, and it hid the problem. Nobody writes a cycle of -r lines on purpose.

One _entries list

A file states requirements and -r lines interleaved, and two separate lists lost that order. Entries is the ordered union; Requirements and ReferencedFiles are generator views filtering it by type — which also answers the two comments asking for generators.

The smaller ones

review point done
raise a DependencyError, FileNotFoundError as cause RequirementsFileNotFoundError(...) from FileNotFoundError(path) — the pattern CLIAbstraction, Configuration.YAML/.JSON and Filesystem already use
hand ex to WarningCollector.Raise it takes a cause parameter; it's passed now
raise ex, not a bare raise done
"the files it references" renamed throughout — Includes is ReferencedFiles, because -r references a file rather than including its text
doc-string wording, field alignment done

Tests

Six new testcases: entry order, parent/root/IterateToRoot, the root's mapping, a cycle, a self-reference, and the cause on a missing file. Four existing ones changed — test_Includes_Cycle now asserts the raise instead of the read-once behaviour it was written for.

1929 passed, 30 skipped, 3 xfailed. CheckDocstrings, CheckProperties, CheckFieldComments, CheckAlignment, CheckAnnotations, CheckDiff at zero; CheckRaises unchanged at its 5-problem baseline (extra 110 → 112, both the advisory kind: __init__ documents what _ReadReferencedFile raises, and that documents what the recursive constructor raises).

Not in this PR

Three more PRs follow, stacked in this order — the directive's configuration and naming, its code-quality points, and the two new format options.

Answers the review's twelve points on 'pyTooling/Dependency/Python.py',
which together are one change: the class kept a list of includes and a
'_visited' set threaded through the recursion, and knew nothing else
about the shape it was building.

**Every file knows where it sits.** '_parent' is the file whose '-r'
line referenced it, '_root' the entrypoint the tree was read from, and
'IterateToRoot()' walks the chain - which is what lets a requirement
name the entrypoint that pulled it in.

**The root keeps '_analyzedRequirementFiles'**, every file of the tree by
resolved path. That replaces '_visited' entirely: the same mapping that
detects a cycle while reading answers afterwards which files the tree was
read from. The Sphinx directive had its own '_Walk' generator to
re-derive that list; it is deleted, because two answers to one question
is one too many.

**A cycle raises** 'CircularRequirementsFileError' with the chain in a
note, instead of being read once and passed over. A file referencing
itself is not something anyone writes on purpose, and continuing hides
it.

**One '_entries' list**, not a list of requirements beside a list of
includes. A file states the two interleaved, and splitting them lost
that order; 'Requirements' and 'ReferencedFiles' are generator views
filtering it by type.

Also from the review: 'RequirementsFileNotFoundError' with the
'FileNotFoundError' as its cause, which is how CLIAbstraction,
Configuration and Filesystem already report a missing file; the
'InvalidRequirement' handed to 'WarningCollector.Raise' as the cause it
takes a parameter for; 'raise ex' rather than a bare re-raise; and
'includes' renamed to 'references' throughout, because '-r' references a
file rather than including its text.

Six new testcases: entry order, parent/root/IterateToRoot, the root's
mapping, a cycle, a self-reference, and the cause on a missing file.

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
@pytooling-claude
pytooling-claude Bot requested a review from Paebbels as a code owner September 4, 2026 21:28
@codacy-production

codacy-production Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 29 complexity · 2 duplication

Metric Results
Complexity 29
Duplication 2

View in Codacy

🟢 Coverage 94.74% diff coverage · +0.05% coverage variation

Metric Results
Coverage variation ✅ +0.05% coverage variation
Diff coverage ✅ 94.74% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (ec27a48) 12648 10697 84.57%
Head commit (5c154d8) 12696 (+48) 10744 (+47) 84.63% (+0.05%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#377) 95 90 94.74%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@codecov

codecov Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.73684% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.52%. Comparing base (ec27a48) to head (5c154d8).
⚠️ Report is 1 commits behind head on claude/dependency-table.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
pyTooling/Dependency/Python.py 96.42% 3 Missing ⚠️
pyTooling/Documentation/Sphinx/DependencyTable.py 71.42% 2 Missing ⚠️
Additional details and impacted files
@@                     Coverage Diff                     @@
##           claude/dependency-table     #377      +/-   ##
===========================================================
+ Coverage                    81.45%   81.52%   +0.07%     
===========================================================
  Files                           56       56              
  Lines                        12648    12696      +48     
  Branches                      1929     1933       +4     
===========================================================
+ Hits                         10303    10351      +48     
- Misses                        1951     1952       +1     
+ Partials                       394      393       -1     
Flag Coverage Δ
unittests 81.52% <94.73%> (+0.07%) ⬆️

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.

Comment thread pyTooling/Dependency/Python.py Resolved
Comment thread pyTooling/Dependency/Python.py Resolved
Comment thread pyTooling/Dependency/Python.py Resolved
Comment thread pyTooling/Dependency/Python.py Resolved
Comment thread pyTooling/Dependency/Python.py Resolved
Comment thread pyTooling/Dependency/Python.py Resolved
Comment thread pyTooling/Dependency/Python.py Resolved
Comment thread pyTooling/Dependency/Python.py Resolved
Seven of the eight comments are applied; the eighth is answered in its
thread.

**'Flatten()' is 'AllRequirements' and keeps the file's order.** It
merged every referenced file first and appended this file's own
requirements after, so a '-r' line that is not the first line came out
before the requirements written above it. It walks '_entries' now - the
one list that already holds requirements and references in the order
written - so a reference contributes where its line stands. It is a
'@readonly' generator, like 'Requirements' and 'ReferencedFiles' beside
it, rather than a method returning a dict.

The nearer statement still wins, and now wherever the two stand: this
file's own requirements are collected a second time and re-applied at
the end. A dict key keeps the position of its first insertion, so
overriding a package's version does not move the package.

**'Hierarchy' is the path from the root down to this file**, as a tuple,
built with a deque the way 'pyTooling.Tree.Node.Path' builds its own.
That is what the cycle message wanted: 'reversed(tuple(IterateToRoot()))'
is 'self.Hierarchy' now. 'Path' was not available for it - it is the
file's own path on disk - and of the two names offered, 'Hierarchy' says
what the tuple is, where 'PathToNode' would be a second kind of path in
a class that already has one.

**Alignment** of the field block and of the constructor's assignments.
The field names cannot share one column with their comments once
'_analyzedRequirementFiles' is among them, so the two fields whose
comment does not fit take a '#:' line above them - the pattern this file
already uses for 'LicenseOverrides'.

Also: 'does not exist' rather than 'not found' in
'RequirementsFileNotFoundError'.

Three new testcases: the file's order across a reference, an overriding
statement keeping its position, and 'Hierarchy' from a leaf and from a
root.

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
Comment thread pyTooling/Dependency/Python.py Resolved
Comment thread pyTooling/Dependency/Python.py Resolved
Comment thread pyTooling/Dependency/Python.py Resolved
Comment thread pyTooling/Dependency/Python.py Resolved
Comment thread pyTooling/Dependency/Python.py Resolved
Comment thread pyTooling/Dependency/Python.py Resolved
Comment thread pyTooling/Dependency/Python.py Resolved
**'_parent' is 'parent'.** All parameters are real parameters, so the
underscore is gone from the signature, the doc-string and the two
assignments - and 'parent' is type-checked the way 'path' already was,
with a testcase for it.

**'IterateFromRoot()' is the method 'Hierarchy' is built from**, so the
property and its generator no longer name opposite directions.
'pyTooling.LinkedList' already had this family - 'IterateToFirst' beside
'IterateFromFirst' - and this is the same pair around the root:
'IterateToRoot()' walks up, 'IterateFromRoot()' walks down, and
'Hierarchy' is 'tuple(self.IterateFromRoot())'.

**The cycle chain reads with arrows**, in both the message and its note.

**'AllRequirements' shows its example** rather than describing it. Three
columns - what the referenced file states, what the entrypoint states,
what comes out - say in four lines what the prose needed a paragraph
for, and the two rules stay as one sentence above it.

**Both 'canonicalize_name' imports are guarded.** The one added in the
previous commit was worse than unguarded: it stood *before* the
'pyTooling.Dependency.Python' import that raises
'MissingDependencyError', so a build without the 'pypi' extra got a bare
"No module named 'packaging'" instead of the message naming the extra to
install. Both sites now carry the same 'try'/'except ImportError' ->
'MissingDependencyError' the model's own imports use, so neither depends
on import order.

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
Comment thread pyTooling/Dependency/Python.py Resolved
Paebbels and others added 2 commits September 5, 2026 21:42
'PythonCoding.md' has one form for this - "Optional, " opening the
':param:' description, plus what the default is - and 'parent' has a
default, so it takes it:

  :param parent: Optional, the file referencing this one. Default: ``None``, a root.

The rule's own test is the default, not the annotation: a 'Nullable[...]'
parameter *without* one is required and does not open with "Optional".

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
Comment thread pyTooling/Dependency/Python.py Resolved
Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
@Paebbels
Paebbels force-pushed the claude/requirements-file-tree branch from 083a42c to 613540d Compare September 5, 2026 21:49
claude-code and others added 3 commits September 5, 2026 21:56
The tests were fragile and the resolve in them is right: 'Path(directory)' from 'TemporaryDirectory()' is '/var/...'
on macOS while its resolution is '/private/var/...', so comparing library output against the unresolved spelling
fails there and passes here. That fix stays.

Dropping 'path.resolve()' from '__init__' is a second, independent change, and it is a regression:
'Entrypoints::test_TheWholeTreeIsSpelledOneWay' fails. It builds a symlinked directory on purpose - it is not about
temporary directories - and asserts the tree spells one directory one way. Without the resolve the root is keyed in
'_analyzedRequirementFiles' by the caller's spelling while every '-r' reference is keyed by a resolved one, so the
same file enters the tree twice and a cycle is reported one level later than it happens. Three doc-strings still
promise a resolved path.

Resolved once in '__init__' now, before the existence check, so the "does not exist" message names the file the
library actually looked for. A referenced file is already resolved, so it is a no-op there.

Also:
- the two field comments overflowed 120 columns in the one-line form; shortened rather than moved back onto own
  '#:' lines
- 'AnalyzedRequirementFiles' returns 'None' for a referenced file now, so the return type is 'Nullable'

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
You are right that a path handed in must come back out of the 'Path' property unchanged - and there is a precedent
for it: 'pyEDAA.ProjectModel.File' keeps '_path' as given and exposes the resolution separately as 'ResolvedPath'.
Overwriting '_path' was the wrong place to put this.

The resolve is not about opening a file - 'open()' never needs one, the kernel walks the symlinks itself. It is
about the one place a path is used as an *identity*: '_analyzedRequirementFiles' is a dict keyed by path, and its
keys are compared against a '-r' reference, which is resolved. If the root is inserted under the caller's spelling
and every reference under a resolved one, the two are not comparable.

So the key is resolved and '_path' is not. 'Path' returns what was handed in, the mapping still holds one entry per
file, and 'Entrypoints::test_TheWholeTreeIsSpelledOneWay' passes.

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
They were needed while '_path' was compared directly. Now that only the mapping's key is resolved they are dead in
two tests and harmful in the third:

- 'test_Includes_Cycle' and 'test_Includes_SelfReference' compare no path at all, only the exception.
- 'test_TheRootKnowsEveryFileOfItsTree' resolves every element of its expected set already, so resolving 'root' on
  top of that changes nothing on Linux - and on macOS it removes the only thing the test could catch. Handing in
  '/var/folders/...' when the resolution is '/private/var/folders/...' is exactly the case the resolved key exists
  for, and pre-resolving 'root' makes macOS test the same trivial case Linux does. On '613540d' that test fails on
  macOS with 'root' unresolved, which is the point.

Left unresolved with a comment saying why, so it doesn't look like an oversight.

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
@Paebbels
Paebbels merged commit 51de083 into claude/dependency-table Sep 5, 2026
61 checks passed
@Paebbels
Paebbels deleted the claude/requirements-file-tree branch September 5, 2026 22:34
@pytooling-claude pytooling-claude Bot mentioned this pull request Sep 6, 2026
@pytooling-claude pytooling-claude Bot added Dependency pyTooling.Dependency - Generic dependency graph and package resolutions. Documentation Improvements or additions to documentation Unit Tests labels Sep 6, 2026
@pytooling-claude pytooling-claude Bot added this to the v10.0 milestone Sep 6, 2026
This was referenced Oct 12, 2026
This was referenced Oct 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Dependency pyTooling.Dependency - Generic dependency graph and package resolutions. Documentation Improvements or additions to documentation Unit Tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants