Keep absolute machine paths out of shareable reports
Direct answer
A shareable report rarely needs the absolute directory where a project happened to be checked out. Path.relative_to(root) expresses a discovered path using the selected project root as its reference. Calling as_posix() then gives the report a consistent slash separator, such as src/x.txt.
The fixture constructs a file under a temporary project and checks the exact report value. Its output does not contain the temporary root. This makes the example reproducible across machines and avoids publishing a home-directory name through this particular path field.
relative_to is a lexical operation; it does not establish that a symlink resolves inside the root. It can also raise ValueError when the path is outside the supplied root. Decide how a scanner should report that case before formatting arbitrary discoveries. Finally, relative names can themselves contain private information. This formatting step removes a machine prefix, but does not redact filenames, exception messages, or any other report fields.
Complete example
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
root = Path(d) / 'project'
p = root / 'src' / 'x.txt'
p.parent.mkdir(parents=True)
p.write_text('x')
assert p.relative_to(root).as_posix() == 'src/x.txt'
result = 'path=src/x.txt'
print(result)
Expected stdout (for a platform supporting the demonstrated operation):
path=src/x.txt
Sources
- pathlib.PurePath.relative_to
Prepared with AI assistance. The example uses synthetic data; its stated limits apply.
Comments
Post a Comment