drift-dev-env 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,85 @@
1
+ """Report versions from fixed probes for supported runtimes."""
2
+
3
+ import os
4
+ import re
5
+
6
+ from drift.collectors.base import CollectorContext, Observation, ProbeIssue, ProbeResult
7
+ from drift.collectors.runner import CommandOutput, launcher_paths, run_probe
8
+
9
+ _COMMANDS = {
10
+ "python": ("-I", "-S", "--version"),
11
+ "node": ("--version",),
12
+ "npm": ("--version",),
13
+ "php": ("-n", "-v"),
14
+ "java": ("-version",),
15
+ "go": ("version",),
16
+ }
17
+ PROBE_IDS = tuple(_COMMANDS)
18
+ _VERSION = rb"([0-9]+(?:\.[0-9]+)+(?:[A-Za-z0-9_.+\-]*))"
19
+ _PATTERNS = {
20
+ "python": re.compile(rb"Python " + _VERSION),
21
+ "node": re.compile(rb"v" + _VERSION),
22
+ "npm": re.compile(_VERSION),
23
+ "php": re.compile(rb"PHP " + _VERSION + rb"(?: \(.*\))?"),
24
+ "java": re.compile(rb'(?:openjdk|java) version "' + _VERSION + rb'"(?: .*)?'),
25
+ "go": re.compile(rb"go version go" + _VERSION + rb" [a-z0-9]+/[a-z0-9]+"),
26
+ }
27
+
28
+
29
+ def _windows_npm(context: CollectorContext) -> CommandOutput | ProbeIssue:
30
+ for directory in launcher_paths():
31
+ if not any(
32
+ (directory / f"npm{suffix}").is_file()
33
+ for suffix in (".cmd", ".bat", ".ps1")
34
+ ):
35
+ continue
36
+ try:
37
+ installation = directory.resolve(strict=True)
38
+ node = (installation / "node.exe").resolve(strict=True)
39
+ script = (installation / "node_modules/npm/bin/npm-cli.js").resolve(
40
+ strict=True
41
+ )
42
+ if (
43
+ node.parent == installation
44
+ and script.is_relative_to(installation)
45
+ and script.is_file()
46
+ ):
47
+ return run_probe(
48
+ node,
49
+ (str(script), "--version"),
50
+ cwd=context.root,
51
+ deadline=context.deadline,
52
+ )
53
+ except (OSError, RuntimeError):
54
+ break
55
+ break
56
+ return ProbeIssue("unsupported", "unsupported_launcher")
57
+
58
+
59
+ def _probe(name: str, args: tuple[str, ...], context: CollectorContext) -> ProbeResult:
60
+ output = run_probe(
61
+ name,
62
+ args,
63
+ cwd=context.root,
64
+ deadline=context.deadline,
65
+ profile="go" if name == "go" else "default",
66
+ )
67
+ if name == "python" and output == ProbeIssue("unavailable", "executable_missing"):
68
+ output = run_probe("python3", args, cwd=context.root, deadline=context.deadline)
69
+ if (
70
+ name == "npm"
71
+ and os.name == "nt"
72
+ and output == ProbeIssue("unsupported", "unsupported_launcher")
73
+ ):
74
+ output = _windows_npm(context)
75
+ if isinstance(output, ProbeIssue):
76
+ return output
77
+ for stream in (output.stdout, output.stderr):
78
+ for line in stream.splitlines():
79
+ if match := _PATTERNS[name].fullmatch(line.strip()):
80
+ return Observation(match[1].decode("ascii"))
81
+ return ProbeIssue("failed", "invalid_output")
82
+
83
+
84
+ def collect(context: CollectorContext) -> dict[str, ProbeResult]:
85
+ return {name: _probe(name, args, context) for name, args in _COMMANDS.items()}
@@ -0,0 +1,20 @@
1
+ """Collect product and architecture information from the current system."""
2
+
3
+ import platform
4
+
5
+ from drift.collectors.base import CollectorContext, Observation, ProbeIssue, ProbeResult
6
+
7
+ PROBE_IDS = ("os", "os_version", "architecture")
8
+
9
+
10
+ def collect(_context: CollectorContext) -> dict[str, ProbeResult]:
11
+ name = platform.system()
12
+ version = platform.mac_ver()[0] if name == "Darwin" else ""
13
+ return {
14
+ key: Observation(value) if value else ProbeIssue("failed", "invalid_output")
15
+ for key, value in zip(
16
+ PROBE_IDS,
17
+ (name, version or platform.release(), platform.machine()),
18
+ strict=True,
19
+ )
20
+ }
drift/comparison.py ADDED
@@ -0,0 +1,207 @@
1
+ """Deterministic comparison of two validated environment captures."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Literal
5
+
6
+ from drift.collectors.base import (
7
+ COLLECTOR_IDS,
8
+ CollectorId,
9
+ DiagnosticCode,
10
+ ProbeValue,
11
+ known_absence,
12
+ )
13
+ from drift.models import CapturedEnvironment, Issue, Observed, ProbeRecord, Scope
14
+
15
+ type ChangeValue = bool | str | dict[str, int] | None
16
+ type Side = Literal["reference", "current", "both"]
17
+ type GapCode = DiagnosticCode | Literal["scope_changed"]
18
+
19
+ _DOCKER_PREREQUISITES = {
20
+ "client_version": ("installed",),
21
+ "compose_installed": ("installed",),
22
+ "compose_version": ("installed", "compose_installed"),
23
+ "daemon_reachable": ("installed",),
24
+ }
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Change:
29
+ collector: CollectorId
30
+ probe: str
31
+ subject: str | None
32
+ kind: Literal["added", "removed", "modified"]
33
+ before: ChangeValue
34
+ after: ChangeValue
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Gap:
39
+ collector: CollectorId
40
+ probe: str | None
41
+ side: Side
42
+ code: GapCode
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Comparison:
47
+ changes: list[Change]
48
+ gaps: list[Gap]
49
+ comparable: int
50
+
51
+ @property
52
+ def warnings(self) -> list[str]:
53
+ return [] if self.comparable else ["no_comparable_observations"]
54
+
55
+ @property
56
+ def outcome(self) -> Literal["match", "drift", "incomplete"]:
57
+ if self.changes:
58
+ return "drift"
59
+ return "incomplete" if self.gaps or self.warnings else "match"
60
+
61
+ @property
62
+ def exit_code(self) -> Literal[0, 3, 4]:
63
+ if self.outcome == "drift":
64
+ return 3
65
+ return 4 if self.outcome == "incomplete" else 0
66
+
67
+
68
+ def _change(
69
+ collector: CollectorId,
70
+ probe: str,
71
+ subject: str | None,
72
+ before: ChangeValue,
73
+ after: ChangeValue,
74
+ ) -> Change:
75
+ kind: Literal["added", "removed", "modified"]
76
+ kind = "added" if before is None else "removed" if after is None else "modified"
77
+ return Change(collector, probe, subject, kind, before, after)
78
+
79
+
80
+ def _members(value: ProbeValue | None) -> dict[str, ChangeValue]:
81
+ if isinstance(value, list):
82
+ return dict.fromkeys(value, True)
83
+ if isinstance(value, dict):
84
+ return dict(value)
85
+ return {}
86
+
87
+
88
+ def _changes(
89
+ collector: CollectorId, probe: str, old: ProbeRecord, new: ProbeRecord
90
+ ) -> list[Change]:
91
+ before = old.value if isinstance(old, Observed) else None
92
+ after = new.value if isinstance(new, Observed) else None
93
+ if before == after:
94
+ return []
95
+ if isinstance(before, (list, dict)) or isinstance(after, (list, dict)):
96
+ original, current = _members(before), _members(after)
97
+ return [
98
+ _change(collector, probe, name, original.get(name), current.get(name))
99
+ for name in sorted(original.keys() | current.keys())
100
+ if original.get(name) != current.get(name)
101
+ ]
102
+ return [_change(collector, probe, None, before, after)]
103
+
104
+
105
+ def _scope_changed(collector: CollectorId, probe: str, old: Scope, new: Scope) -> bool:
106
+ if collector == "environment" and probe == "active":
107
+ return (
108
+ old.active_allowlist != new.active_allowlist
109
+ or old.active_name_case != new.active_name_case
110
+ )
111
+ return (
112
+ collector == "docker"
113
+ and probe == "services"
114
+ and old.compose_project != new.compose_project
115
+ )
116
+
117
+
118
+ def _issue_code(collector: CollectorId, result: ProbeRecord) -> DiagnosticCode | None:
119
+ if isinstance(result, Observed):
120
+ return None
121
+ if result.status == "unavailable" and known_absence(collector, result.code):
122
+ return None
123
+ return result.code
124
+
125
+
126
+ def _explained(
127
+ probe: str,
128
+ issue: ProbeRecord,
129
+ absent: dict[str, ProbeRecord],
130
+ present: dict[str, ProbeRecord],
131
+ ) -> bool:
132
+ if (
133
+ not isinstance(issue, Issue)
134
+ or issue.status != "not_applicable"
135
+ or issue.code != "prerequisite_missing"
136
+ ):
137
+ return False
138
+ return any(
139
+ absent.get(key) == Observed(status="ok", value=False)
140
+ and present.get(key) == Observed(status="ok", value=True)
141
+ for key in _DOCKER_PREREQUISITES.get(probe, ())
142
+ )
143
+
144
+
145
+ def compare(reference: CapturedEnvironment, current: CapturedEnvironment) -> Comparison:
146
+ changes: list[Change] = []
147
+ gaps: list[Gap] = []
148
+ comparable = 0
149
+ for collector in COLLECTOR_IDS:
150
+ if collector == "git":
151
+ continue
152
+ old, new = reference.collectors[collector], current.collectors[collector]
153
+ if old.status == "disabled" or new.status == "disabled":
154
+ if old.status != new.status:
155
+ gaps.append(
156
+ Gap(
157
+ collector,
158
+ None,
159
+ "reference" if old.status == "disabled" else "current",
160
+ "scope_changed",
161
+ )
162
+ )
163
+ continue
164
+ for probe in sorted(old.probes.keys() | new.probes.keys()):
165
+ if _scope_changed(collector, probe, reference.scope, current.scope):
166
+ gaps.append(Gap(collector, probe, "both", "scope_changed"))
167
+ continue
168
+ if probe not in old.probes or probe not in new.probes:
169
+ gaps.append(
170
+ Gap(
171
+ collector,
172
+ probe,
173
+ "reference" if probe not in old.probes else "current",
174
+ "scope_changed",
175
+ )
176
+ )
177
+ continue
178
+ before, after = old.probes[probe], new.probes[probe]
179
+ services = collector == "docker" and probe == "services"
180
+ if services and reference.scope.compose_project is None:
181
+ continue
182
+ if not services and before.status == after.status == "not_applicable":
183
+ continue
184
+ left, right = _issue_code(collector, before), _issue_code(collector, after)
185
+ if left is None and right is None:
186
+ comparable += 1
187
+ changes.extend(_changes(collector, probe, before, after))
188
+ continue
189
+ if collector == "docker":
190
+ if _explained(probe, before, old.probes, new.probes):
191
+ left = None
192
+ if _explained(probe, after, new.probes, old.probes):
193
+ right = None
194
+ if left is not None and left == right:
195
+ gaps.append(Gap(collector, probe, "both", left))
196
+ else:
197
+ if left is not None:
198
+ gaps.append(Gap(collector, probe, "reference", left))
199
+ if right is not None:
200
+ gaps.append(Gap(collector, probe, "current", right))
201
+ return Comparison(
202
+ changes,
203
+ sorted(
204
+ gaps, key=lambda gap: (gap.collector, gap.probe or "", gap.side, gap.code)
205
+ ),
206
+ comparable,
207
+ )
drift/config.py ADDED
@@ -0,0 +1,118 @@
1
+ """Project discovery and validation of the v1 TOML configuration."""
2
+
3
+ import os
4
+ import tomllib
5
+ from pathlib import Path
6
+ from typing import Annotated
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
9
+
10
+ from drift.exceptions import (
11
+ InvalidConfigError,
12
+ InvalidProjectError,
13
+ ProjectNotInitializedError,
14
+ UnsupportedSchemaError,
15
+ )
16
+ from drift.paths import open_project_file, project_path_parts
17
+
18
+ CONFIG_NAME = "drift.toml"
19
+
20
+
21
+ class _Settings(BaseModel):
22
+ model_config = ConfigDict(extra="forbid", strict=True, hide_input_in_errors=True)
23
+
24
+
25
+ class CollectorSettings(_Settings):
26
+ system: bool = True
27
+ runtime: bool = True
28
+ docker: bool = True
29
+ environment: bool = True
30
+ dependency: bool = True
31
+ git: bool = True
32
+
33
+
34
+ class EnvironmentSettings(_Settings):
35
+ files: list[str] = Field(default_factory=list)
36
+ active_allowlist: list[str] | None = None
37
+
38
+ @field_validator("files")
39
+ @classmethod
40
+ def _validate_files(cls, files: list[str]) -> list[str]:
41
+ for path in files:
42
+ project_path_parts(path)
43
+ if len({os.path.normcase(path) for path in files}) != len(files):
44
+ raise ValueError("Configured environment files must be unique.")
45
+ return files
46
+
47
+ @field_validator("active_allowlist")
48
+ @classmethod
49
+ def _validate_allowlist(cls, names: list[str] | None) -> list[str] | None:
50
+ if names is None:
51
+ return None
52
+ if any(not name or "\0" in name or "=" in name for name in names):
53
+ raise ValueError("The active allowlist must contain valid variable names.")
54
+ normalized = [name.upper() for name in names] if os.name == "nt" else names
55
+ if len(set(normalized)) != len(names):
56
+ raise ValueError("Active environment variable names must be unique.")
57
+ return normalized
58
+
59
+
60
+ class DockerSettings(_Settings):
61
+ compose_project: Annotated[str, Field(pattern=r"^[a-z0-9][a-z0-9_-]*$")] | None = (
62
+ None
63
+ )
64
+
65
+
66
+ class ProjectConfig(_Settings):
67
+ schema_version: int = Field(ge=1, le=1)
68
+ collectors: CollectorSettings = Field(default_factory=CollectorSettings)
69
+ environment: EnvironmentSettings = Field(default_factory=EnvironmentSettings)
70
+ docker: DockerSettings = Field(default_factory=DockerSettings)
71
+
72
+
73
+ def resolve_project_root(
74
+ project: Path | None = None, *, search_parents: bool = True
75
+ ) -> Path:
76
+ """Select an explicit directory or discover the nearest configuration."""
77
+ try:
78
+ start = (Path.cwd() if project is None else project).resolve(strict=True)
79
+ if not start.is_dir():
80
+ raise InvalidProjectError("Select an existing project directory.")
81
+ except (OSError, RuntimeError, ValueError):
82
+ raise InvalidProjectError("Select an existing project directory.") from None
83
+
84
+ if project is not None or not search_parents:
85
+ return start
86
+
87
+ for directory in (start, *start.parents):
88
+ try:
89
+ (directory / CONFIG_NAME).lstat()
90
+ except FileNotFoundError:
91
+ continue
92
+ except OSError:
93
+ raise InvalidConfigError("Could not access drift.toml.") from None
94
+ return directory
95
+ raise ProjectNotInitializedError("No drift.toml was found. Run drift init first.")
96
+
97
+
98
+ def load_config(root: Path) -> ProjectConfig:
99
+ """Read and validate configuration without accessing configured inputs."""
100
+ try:
101
+ with open_project_file(root, CONFIG_NAME) as stream:
102
+ settings = tomllib.load(stream)
103
+ except FileNotFoundError:
104
+ raise ProjectNotInitializedError(
105
+ "No drift.toml was found. Run drift init first."
106
+ ) from None
107
+ except (OSError, ValueError, RecursionError):
108
+ raise InvalidConfigError("Could not read drift.toml as valid TOML.") from None
109
+
110
+ schema_version = settings.get("schema_version")
111
+ if type(schema_version) is int and schema_version != 1:
112
+ raise UnsupportedSchemaError("The drift.toml schema version is unsupported.")
113
+ try:
114
+ return ProjectConfig.model_validate(settings)
115
+ except ValidationError:
116
+ raise InvalidConfigError(
117
+ "drift.toml settings do not match the v1 schema."
118
+ ) from None
drift/exceptions.py ADDED
@@ -0,0 +1,65 @@
1
+ """Errors with stable codes and safe user-facing messages."""
2
+
3
+ from typing import ClassVar
4
+
5
+
6
+ class DriftError(Exception):
7
+ """An expected Drift error."""
8
+
9
+ code: ClassVar[str]
10
+
11
+
12
+ class InvalidProjectError(DriftError):
13
+ code = "invalid_project"
14
+
15
+
16
+ class ProjectNotInitializedError(DriftError):
17
+ code = "project_not_initialized"
18
+
19
+
20
+ class InvalidConfigError(DriftError):
21
+ code = "invalid_config"
22
+
23
+
24
+ class UnsupportedSchemaError(DriftError):
25
+ code = "unsupported_schema"
26
+
27
+
28
+ class UnsafePathError(DriftError):
29
+ code = "unsafe_path"
30
+
31
+
32
+ class PathChangedError(UnsafePathError):
33
+ """A checked path was replaced while opening it."""
34
+
35
+
36
+ class StorageError(DriftError):
37
+ code = "storage_error"
38
+
39
+
40
+ class InvalidSnapshotError(DriftError):
41
+ code = "invalid_snapshot"
42
+
43
+
44
+ class SnapshotNotFoundError(DriftError):
45
+ code = "snapshot_not_found"
46
+
47
+
48
+ class AmbiguousSnapshotError(DriftError):
49
+ code = "ambiguous_snapshot"
50
+
51
+
52
+ class HistoryEmptyError(DriftError):
53
+ code = "history_empty"
54
+
55
+
56
+ class HistoryIncompleteError(DriftError):
57
+ code = "history_incomplete"
58
+
59
+
60
+ class BaselineMissingError(DriftError):
61
+ code = "baseline_missing"
62
+
63
+
64
+ class InvalidBaselineError(DriftError):
65
+ code = "invalid_baseline"
@@ -0,0 +1,68 @@
1
+ """Capture and report a live comparison without modifying project state."""
2
+
3
+ import json
4
+ from dataclasses import asdict
5
+ from pathlib import Path
6
+
7
+ from drift.comparison import ChangeValue, compare
8
+ from drift.config import ProjectConfig
9
+ from drift.models import CollectorRecord, Observed, Snapshot
10
+ from drift.output import Report, literal
11
+ from drift.snapshots import capture
12
+
13
+
14
+ def _label(value: ChangeValue) -> str:
15
+ if value is None:
16
+ return "(absent)"
17
+ return literal(value) if isinstance(value, str) else json.dumps(value)
18
+
19
+
20
+ def _git_line(label: str, context: CollectorRecord) -> str:
21
+ values = [
22
+ f"{probe}={_label(result.value)}"
23
+ for probe in ("branch", "commit", "worktree")
24
+ if isinstance(result := context.probes.get(probe), Observed)
25
+ and isinstance(result.value, str)
26
+ ]
27
+ return f"Git {label} ({context.status})" + (
28
+ f" · {', '.join(values)}" if values else ""
29
+ )
30
+
31
+
32
+ def compare_live(root: Path, config: ProjectConfig, reference: Snapshot) -> Report:
33
+ current = capture(root, config)
34
+ result = compare(reference, current)
35
+ heading = {
36
+ "match": "Environment matches",
37
+ "drift": "Drift detected against",
38
+ "incomplete": "Comparison incomplete against",
39
+ }[result.outcome]
40
+ lines = [f"{heading} {reference.id}"]
41
+ for change in result.changes:
42
+ subject = f" [{literal(change.subject)}]" if change.subject is not None else ""
43
+ lines.append(
44
+ f"{change.kind.capitalize()} {change.collector}.{literal(change.probe)}{subject}"
45
+ f" {_label(change.before)} → {_label(change.after)}"
46
+ )
47
+ for gap in result.gaps:
48
+ probe = f".{literal(gap.probe)}" if gap.probe is not None else ""
49
+ lines.append(f"Coverage gap {gap.collector}{probe} {gap.side}: {gap.code}")
50
+ if result.warnings:
51
+ lines.append("No comparable environment observations.")
52
+ before_git, after_git = reference.collectors["git"], current.collectors["git"]
53
+ lines.extend((_git_line("reference", before_git), _git_line("current", after_git)))
54
+ return Report(
55
+ {
56
+ "reference_id": reference.id,
57
+ "outcome": result.outcome,
58
+ "changes": [asdict(change) for change in result.changes],
59
+ "gaps": [asdict(gap) for gap in result.gaps],
60
+ "warnings": result.warnings,
61
+ "git": {
62
+ "reference": before_git.model_dump(),
63
+ "current": after_git.model_dump(),
64
+ },
65
+ },
66
+ "\n".join(lines),
67
+ result.exit_code,
68
+ )