Option C Tools
Loading...
Searching...
No Matches
paths.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# oct/core/paths.py
4
5"""
6Purpose
7-------
8Provide a single canonical helper for rendering filesystem paths in
9user-facing output. OCT commands (``oct lint``, ``oct health``, ``oct
10git check``, ...) must present paths as project-relative POSIX strings
11so findings are portable across machines, cross-platform, and safe to
12paste into tickets, CI logs, and patch files.
13
14Responsibilities
15----------------
16- Convert an absolute :class:`pathlib.Path` into a project-relative
17 POSIX string when the path is inside *project_root*.
18- Fall back to an absolute POSIX string when *path* is outside the
19 project (e.g. a stdlib file surfaced by a traceback, a user-supplied
20 lint target under ``C:\\`` or ``/tmp``).
21
22Diagnostics
23-----------
24Domain: OCT-CORE
25Levels:
26 L2 — lifecycle
27 L3 — semantic details
28
29Contracts
30---------
31- Never raises on valid ``Path`` input.
32- Always returns forward slashes (POSIX), even on Windows.
33- ``project_root`` must be an absolute, resolved path for the relative
34 calculation to be correct; callers typically hand it straight from
35 :class:`LinterContext.project_root` (already resolved at context
36 construction).
37"""
38
39from __future__ import annotations
40
41from pathlib import Path
42
43
44def to_project_relative(path: Path, project_root: Path) -> str:
45 """Render *path* as a project-relative POSIX string.
46
47 OI-533: standardises path output across linter, health, and git
48 commands so findings never leak absolute machine paths into CI
49 artifacts or pasted error reports.
50
51 Parameters
52 ----------
53 path
54 The file or directory to render. May be absolute or relative.
55 project_root
56 The project root; typically ``ctx.project_root``. Should be
57 absolute and resolved so :meth:`~pathlib.Path.relative_to`
58 computes the expected relative.
59
60 Returns
61 -------
62 Project-relative POSIX string when *path* lives inside
63 *project_root*; otherwise the absolute POSIX form of *path* (so
64 out-of-tree paths remain unambiguous).
65 """
66 try:
67 return path.relative_to(project_root).as_posix()
68 except ValueError:
69 return path.as_posix()
str to_project_relative(Path path, Path project_root)
Definition paths.py:44