Repository navigation
Make RequirementsFile a tree that knows itself - #377
Conversation
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>
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 29 |
| Duplication | 2 |
🟢 Coverage 94.74% diff coverage · +0.05% coverage variation
Metric Results Coverage variation ✅ +0.05% coverage variation Diff coverage ✅ 94.74% diff coverage 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 Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
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>
**'_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>
'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>
Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
083a42c to
613540d
Compare
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>
Summary
The twelve review points on
pyTooling/Dependency/Python.py, which turn out to be one change:RequirementsFilekept a list of includes and threaded a_visitedset through its recursion, and knew nothing else about the shape it was building.Every file knows where it sits
_parentis the file whose-rline referenced it,_rootthe entrypoint the tree was read from, andIterateToRoot()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
_visitedentirely_analyzedRequirementFilesholds 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
_Walkgenerator to re-derive exactly that list forenv.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
Nullablethat every lookup has to test for a case that cannot happen.A cycle raises
CircularRequirementsFileError, with the chain in a note:Read-once-and-continue was the old behaviour, and it hid the problem. Nobody writes a cycle of
-rlines on purpose.One
_entrieslistA file states requirements and
-rlines interleaved, and two separate lists lost that order.Entriesis the ordered union;RequirementsandReferencedFilesare generator views filtering it by type — which also answers the two comments asking for generators.The smaller ones
DependencyError,FileNotFoundErroras causeRequirementsFileNotFoundError(...) from FileNotFoundError(path)— the patternCLIAbstraction,Configuration.YAML/.JSONandFilesystemalready useextoWarningCollector.Raisecauseparameter; it's passed nowraise ex, not a bareraiseIncludesisReferencedFiles, because-rreferences a file rather than including its textTests
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_Cyclenow asserts the raise instead of the read-once behaviour it was written for.1929 passed, 30 skipped, 3 xfailed.
CheckDocstrings,CheckProperties,CheckFieldComments,CheckAlignment,CheckAnnotations,CheckDiffat zero;CheckRaisesunchanged at its 5-problem baseline (extra110 → 112, both the advisory kind:__init__documents what_ReadReferencedFileraises, 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.