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.
drift/models.py ADDED
@@ -0,0 +1,231 @@
1
+ """Validated version-one snapshot records."""
2
+
3
+ import re
4
+ import unicodedata
5
+ from datetime import datetime
6
+ from typing import Annotated, Literal, Self
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
9
+
10
+ from drift.collectors import dependency, docker, git, runtime, system
11
+ from drift.collectors.base import (
12
+ COLLECTOR_IDS,
13
+ CollectorId,
14
+ CollectorStatus,
15
+ DiagnosticCode,
16
+ Observation,
17
+ ProbeIssue,
18
+ ProbeValue,
19
+ )
20
+ from drift.collectors.engine import collector_status
21
+ from drift.paths import project_path_parts
22
+
23
+ _ID_PATTERN = r"^[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15}$"
24
+ _ID = re.compile(_ID_PATTERN)
25
+ _PREFIX = re.compile(r"[0-9a-f]{6,32}")
26
+ _UTC = re.compile(
27
+ r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?Z"
28
+ )
29
+ _CHECKSUM = re.compile(r"[0-9a-f]{64}")
30
+ _DECLARED_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
31
+ _SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*")
32
+ _STATES = {"created", "running", "paused", "restarting", "removing", "exited", "dead"}
33
+ _FIXED_PROBES = {
34
+ "dependency": dependency.PROBE_IDS,
35
+ "docker": docker.PROBE_IDS,
36
+ "git": git.PROBE_IDS,
37
+ "runtime": runtime.PROBE_IDS,
38
+ "system": system.PROBE_IDS,
39
+ }
40
+ _BOOLEAN_PROBES = {
41
+ ("docker", "installed"),
42
+ ("docker", "compose_installed"),
43
+ ("docker", "daemon_reachable"),
44
+ ("git", "repository"),
45
+ }
46
+
47
+ type SnapshotId = Annotated[str, Field(pattern=_ID_PATTERN)]
48
+
49
+
50
+ def is_snapshot_id(value: str) -> bool:
51
+ return _ID.fullmatch(value) is not None
52
+
53
+
54
+ def is_snapshot_reference(value: str) -> bool:
55
+ return _PREFIX.fullmatch(value) is not None and (
56
+ len(value) < 32 or is_snapshot_id(value)
57
+ )
58
+
59
+
60
+ def valid_message(value: str) -> bool:
61
+ return 1 <= len(value) <= 256 and not any(
62
+ unicodedata.category(character) in {"Cc", "Cs"} for character in value
63
+ )
64
+
65
+
66
+ def _valid_names(names: list[str], *, declared: bool = False) -> bool:
67
+ return names == sorted(set(names)) and all(
68
+ name
69
+ and "=" not in name
70
+ and "\0" not in name
71
+ and (not declared or _DECLARED_NAME.fullmatch(name))
72
+ for name in names
73
+ )
74
+
75
+
76
+ class StrictRecord(BaseModel):
77
+ model_config = ConfigDict(strict=True, extra="forbid", hide_input_in_errors=True)
78
+
79
+
80
+ class Observed(StrictRecord):
81
+ status: Literal["ok"]
82
+ value: ProbeValue
83
+
84
+
85
+ class Issue(StrictRecord):
86
+ status: Literal["unavailable", "unsupported", "failed", "not_applicable"]
87
+ code: DiagnosticCode
88
+
89
+
90
+ type ProbeRecord = Annotated[Observed | Issue, Field(discriminator="status")]
91
+
92
+
93
+ class CollectorRecord(StrictRecord):
94
+ status: CollectorStatus
95
+ probes: dict[str, ProbeRecord]
96
+
97
+
98
+ class Scope(StrictRecord):
99
+ active_allowlist: list[str] | None
100
+ active_name_case: Literal["preserve", "uppercase"]
101
+ compose_project: Annotated[str, Field(pattern=r"^[a-z0-9][a-z0-9_-]*$")] | None
102
+
103
+ @model_validator(mode="after")
104
+ def _check_allowlist(self) -> Self:
105
+ if self.active_allowlist is not None and (
106
+ not _valid_names(self.active_allowlist)
107
+ or (
108
+ self.active_name_case == "uppercase"
109
+ and any(name != name.upper() for name in self.active_allowlist)
110
+ )
111
+ ):
112
+ raise ValueError("Invalid active name scope.")
113
+ return self
114
+
115
+
116
+ def _valid_value(
117
+ collector: CollectorId, probe: str, value: ProbeValue, scope: Scope
118
+ ) -> bool:
119
+ if (collector, probe) in _BOOLEAN_PROBES:
120
+ return isinstance(value, bool)
121
+ if collector == "environment":
122
+ if not isinstance(value, list) or not _valid_names(
123
+ value, declared=probe != "active"
124
+ ):
125
+ return False
126
+ if probe != "active":
127
+ return True
128
+ if scope.active_name_case == "uppercase" and any(
129
+ name != name.upper() for name in value
130
+ ):
131
+ return False
132
+ return scope.active_allowlist is None or set(value) <= set(
133
+ scope.active_allowlist
134
+ )
135
+ if collector == "docker" and probe == "services":
136
+ return (
137
+ scope.compose_project is not None
138
+ and isinstance(value, dict)
139
+ and all(
140
+ _SERVICE.fullmatch(service)
141
+ and counts
142
+ and set(counts) <= _STATES
143
+ and all(count > 0 for count in counts.values())
144
+ for service, counts in value.items()
145
+ )
146
+ )
147
+ if not isinstance(value, str) or not value:
148
+ return False
149
+ if collector == "dependency":
150
+ return _CHECKSUM.fullmatch(value) is not None
151
+ if collector == "git" and probe == "commit":
152
+ return len(value) in {40, 64} and all(
153
+ character in "0123456789abcdef" for character in value
154
+ )
155
+ if collector == "git" and probe == "worktree":
156
+ return value in {"clean", "dirty"}
157
+ return True
158
+
159
+
160
+ class CapturedEnvironment(StrictRecord):
161
+ scope: Scope
162
+ collectors: dict[CollectorId, CollectorRecord]
163
+
164
+ @model_validator(mode="after")
165
+ def _check_collectors(self) -> Self:
166
+ if self.collectors.keys() != set(COLLECTOR_IDS):
167
+ raise ValueError("Invalid collector set.")
168
+ for key, record in self.collectors.items():
169
+ probes = record.probes
170
+ if record.status == "disabled" and not probes:
171
+ continue
172
+ if key == "environment":
173
+ files = set(probes) - {"active"}
174
+ if "active" not in probes or any(
175
+ not item.startswith("file:") for item in files
176
+ ):
177
+ raise ValueError("Invalid environment probe set.")
178
+ for item in files:
179
+ project_path_parts(item.removeprefix("file:"))
180
+ if self.scope.active_name_case == "uppercase" and len(
181
+ {item.upper() for item in files}
182
+ ) != len(files):
183
+ raise ValueError("Duplicate environment probe paths.")
184
+ elif probes.keys() != set(_FIXED_PROBES[key]):
185
+ raise ValueError("Invalid collector probe set.")
186
+ for probe, result in probes.items():
187
+ if isinstance(result, Observed) and not _valid_value(
188
+ key, probe, result.value, self.scope
189
+ ):
190
+ raise ValueError("Invalid probe value.")
191
+ if (
192
+ collector_status(
193
+ key,
194
+ {
195
+ probe: Observation(result.value)
196
+ if isinstance(result, Observed)
197
+ else ProbeIssue(result.status, result.code)
198
+ for probe, result in probes.items()
199
+ },
200
+ )
201
+ != record.status
202
+ ):
203
+ raise ValueError("Invalid aggregate collector status.")
204
+ return self
205
+
206
+
207
+ class Snapshot(CapturedEnvironment):
208
+ schema_version: Annotated[int, Field(ge=1, le=1)]
209
+ id: SnapshotId
210
+ created_at: str
211
+ message: str | None
212
+
213
+ @field_validator("created_at")
214
+ @classmethod
215
+ def _check_timestamp(cls, value: str) -> str:
216
+ if not _UTC.fullmatch(value):
217
+ raise ValueError("Expected a UTC timestamp.")
218
+ datetime.fromisoformat(value)
219
+ return value
220
+
221
+ @field_validator("message")
222
+ @classmethod
223
+ def _check_message(cls, value: str | None) -> str | None:
224
+ if value is not None and not valid_message(value):
225
+ raise ValueError("Invalid snapshot message.")
226
+ return value
227
+
228
+
229
+ class Metadata(StrictRecord):
230
+ schema_version: Annotated[int, Field(ge=1, le=1)]
231
+ baseline_id: SnapshotId | None
drift/output.py ADDED
@@ -0,0 +1,54 @@
1
+ """Shared CLI reports and stream handling."""
2
+
3
+ import json
4
+ import unicodedata
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass
7
+
8
+ import typer
9
+
10
+ from drift.exceptions import DriftError
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Report:
15
+ result: dict[str, object]
16
+ text: str
17
+ exit_code: int = 0
18
+
19
+
20
+ def literal(value: str) -> str:
21
+ return "".join(
22
+ ascii(character)[1:-1]
23
+ if unicodedata.category(character) in {"Cc", "Cf", "Cs"}
24
+ else character
25
+ for character in value
26
+ )
27
+
28
+
29
+ def _json(command: str, key: str, value: dict[str, object]) -> None:
30
+ typer.echo(json.dumps({"schema_version": 1, "command": command, key: value}))
31
+
32
+
33
+ def emit(command: str, as_json: bool, operation: Callable[[], Report]) -> None:
34
+ try:
35
+ report = operation()
36
+ except DriftError as error:
37
+ if as_json:
38
+ _json(command, "error", {"code": error.code, "message": str(error)})
39
+ else:
40
+ typer.echo(f"{error.code}: {literal(str(error))}", err=True)
41
+ raise typer.Exit(1) from None
42
+ except Exception:
43
+ message = "An unexpected error prevented Drift from completing the command."
44
+ if as_json:
45
+ _json(command, "error", {"code": "internal_error", "message": message})
46
+ else:
47
+ typer.echo(f"internal_error: {message}", err=True)
48
+ raise typer.Exit(1) from None
49
+ if as_json:
50
+ _json(command, "result", report.result)
51
+ else:
52
+ typer.echo(report.text)
53
+ if report.exit_code:
54
+ raise typer.Exit(report.exit_code)
drift/paths.py ADDED
@@ -0,0 +1,143 @@
1
+ """Read regular files beneath a resolved project root."""
2
+
3
+ import errno
4
+ import os
5
+ import re
6
+ import stat
7
+ from collections.abc import Iterator
8
+ from contextlib import ExitStack, contextmanager
9
+ from pathlib import Path
10
+ from typing import BinaryIO
11
+
12
+ from drift.exceptions import PathChangedError, UnsafePathError
13
+
14
+ _INVALID_CHARACTER = re.compile(r'[<>:"\\|?*\x00-\x1f\x7f\ud800-\udfff]')
15
+ _RESERVED_NAME = re.compile(r"(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|(?:COM|LPT)[0-9¹²³])")
16
+ _NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
17
+ _DIRECTORY = getattr(os, "O_DIRECTORY", 0)
18
+ _NONBLOCK = getattr(os, "O_NONBLOCK", 0)
19
+ _DESCRIPTOR_READS = (
20
+ os.open in os.supports_dir_fd
21
+ and os.stat in os.supports_dir_fd
22
+ and os.stat in os.supports_follow_symlinks
23
+ and bool(_NOFOLLOW and _DIRECTORY and _NONBLOCK)
24
+ )
25
+
26
+
27
+ def project_path_parts(relative_path: str) -> tuple[str, ...]:
28
+ """Validate portable relative syntax before a path can be normalized."""
29
+ parts = tuple(relative_path.split("/"))
30
+ for part in parts:
31
+ stem = part.partition(".")[0].rstrip(" ").upper()
32
+ if (
33
+ not part
34
+ or part.endswith((" ", "."))
35
+ or _INVALID_CHARACTER.search(part)
36
+ or _RESERVED_NAME.fullmatch(stem)
37
+ ):
38
+ raise UnsafePathError("Use a safe, slash-separated project-relative path.")
39
+ return parts
40
+
41
+
42
+ def require_kind(info: os.stat_result, *, directory: bool) -> None:
43
+ kind = stat.S_ISDIR if directory else stat.S_ISREG
44
+ reparse_point = (
45
+ getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT
46
+ )
47
+ if reparse_point or not kind(info.st_mode):
48
+ raise UnsafePathError(
49
+ "Project paths must use real directories and regular files."
50
+ )
51
+
52
+
53
+ @contextmanager
54
+ def project_directory(
55
+ root: Path, parts: tuple[str, ...] = ()
56
+ ) -> Iterator[tuple[Path, int | None]]:
57
+ """Hold a checked project directory, using a descriptor where supported."""
58
+ if parts and project_path_parts("/".join(parts)) != parts:
59
+ raise UnsafePathError("Use a safe, slash-separated project-relative path.")
60
+ path = root.joinpath(*parts)
61
+ if not _DESCRIPTOR_READS:
62
+ current = root
63
+ require_kind(current.lstat(), directory=True)
64
+ for part in parts:
65
+ current /= part
66
+ require_kind(current.lstat(), directory=True)
67
+ yield path, None
68
+ return
69
+
70
+ directory_flags = os.O_RDONLY | _DIRECTORY | _NOFOLLOW
71
+ with ExitStack() as directories:
72
+ try:
73
+ directory_fd = os.open(root, directory_flags)
74
+ directories.callback(os.close, directory_fd)
75
+ for part in parts:
76
+ directory_fd = os.open(part, directory_flags, dir_fd=directory_fd)
77
+ directories.callback(os.close, directory_fd)
78
+ except OSError as error:
79
+ if error.errno in {errno.ELOOP, errno.ENOTDIR}:
80
+ raise UnsafePathError(
81
+ "Project paths must use real directories."
82
+ ) from None
83
+ raise
84
+ yield path, directory_fd
85
+
86
+
87
+ @contextmanager
88
+ def _open_relative(root: Path, parts: tuple[str, ...]) -> Iterator[BinaryIO]:
89
+ try:
90
+ with project_directory(root, parts[:-1]) as (_, directory_fd):
91
+ name = parts[-1]
92
+ require_kind(
93
+ os.stat(name, dir_fd=directory_fd, follow_symlinks=False),
94
+ directory=False,
95
+ )
96
+ descriptor = os.open(
97
+ name,
98
+ os.O_RDONLY | _NOFOLLOW | _NONBLOCK,
99
+ dir_fd=directory_fd,
100
+ )
101
+ except OSError as error:
102
+ if error.errno in {errno.ELOOP, errno.ENOTDIR}:
103
+ raise UnsafePathError(
104
+ "Project paths must use real directories and regular files."
105
+ ) from None
106
+ raise
107
+
108
+ with os.fdopen(descriptor, "rb") as stream:
109
+ require_kind(os.fstat(stream.fileno()), directory=False)
110
+ yield stream
111
+
112
+
113
+ def _checked_file(root: Path, parts: tuple[str, ...]) -> tuple[Path, os.stat_result]:
114
+ require_kind(root.lstat(), directory=True)
115
+ path = root
116
+ for part in parts[:-1]:
117
+ path = path / part
118
+ require_kind(path.lstat(), directory=True)
119
+ path = path / parts[-1]
120
+ info = path.lstat()
121
+ require_kind(info, directory=False)
122
+ return path, info
123
+
124
+
125
+ @contextmanager
126
+ def open_project_file(root: Path, relative_path: str) -> Iterator[BinaryIO]:
127
+ """Open a read-only binary stream, rejecting links and special files."""
128
+ parts = project_path_parts(relative_path)
129
+ if _DESCRIPTOR_READS:
130
+ with _open_relative(root, parts) as stream:
131
+ yield stream
132
+ return
133
+
134
+ path, before = _checked_file(root, parts)
135
+ with path.open("rb") as stream:
136
+ opened = os.fstat(stream.fileno())
137
+ require_kind(opened, directory=False)
138
+ _, after = _checked_file(root, parts)
139
+ if not (os.path.samestat(before, opened) and os.path.samestat(opened, after)):
140
+ raise PathChangedError(
141
+ "The project file changed while it was being opened."
142
+ )
143
+ yield stream
drift/project.py ADDED
@@ -0,0 +1,72 @@
1
+ """Prepare and resolve project-local Drift state."""
2
+
3
+ from pathlib import Path
4
+
5
+ from drift.config import CONFIG_NAME, ProjectConfig, load_config, resolve_project_root
6
+ from drift.exceptions import ProjectNotInitializedError, StorageError
7
+ from drift.models import Metadata
8
+ from drift.paths import project_directory
9
+ from drift.storage import (
10
+ SNAPSHOTS,
11
+ STATE,
12
+ ensure_directory,
13
+ publish_file,
14
+ publish_metadata,
15
+ read_metadata,
16
+ snapshot_ids,
17
+ )
18
+
19
+ _DEFAULT_CONFIG = b"schema_version = 1\n"
20
+ _IGNORE = b"/*\n!/.gitignore\n"
21
+
22
+
23
+ def _ensure_metadata(root: Path) -> bool:
24
+ try:
25
+ read_metadata(root)
26
+ except FileNotFoundError:
27
+ if snapshot_ids(root):
28
+ try:
29
+ read_metadata(root) # A concurrent initializer may have completed.
30
+ except FileNotFoundError:
31
+ raise StorageError(
32
+ "Snapshot history exists without metadata. Recover metadata before initializing."
33
+ ) from None
34
+ return False
35
+ if publish_metadata(root, Metadata(schema_version=1, baseline_id=None)):
36
+ return True
37
+ read_metadata(root)
38
+ return False
39
+
40
+
41
+ def initialize(project: Path | None) -> bool:
42
+ root = resolve_project_root(project, search_parents=False)
43
+ try:
44
+ load_config(root)
45
+ except ProjectNotInitializedError:
46
+ config_missing = True
47
+ else:
48
+ config_missing = False
49
+
50
+ created = ensure_directory(root, STATE)
51
+ created |= ensure_directory(root, "/".join(SNAPSHOTS))
52
+ created |= _ensure_metadata(root)
53
+ created |= publish_file(root, f"{STATE}/.gitignore", _IGNORE)
54
+ if config_missing:
55
+ published = publish_file(root, CONFIG_NAME, _DEFAULT_CONFIG)
56
+ if not published:
57
+ load_config(root)
58
+ created |= published
59
+ return created
60
+
61
+
62
+ def initialized_project(project: Path | None) -> tuple[Path, ProjectConfig]:
63
+ root = resolve_project_root(project)
64
+ config = load_config(root)
65
+ try:
66
+ with project_directory(root, SNAPSHOTS):
67
+ pass
68
+ except OSError:
69
+ raise StorageError(
70
+ "Drift project state is incomplete. Run drift init."
71
+ ) from None
72
+ return root, config
drift/snapshots.py ADDED
@@ -0,0 +1,109 @@
1
+ """Capture and describe environment snapshots."""
2
+
3
+ import os
4
+ from dataclasses import asdict, dataclass
5
+ from datetime import UTC, datetime
6
+ from pathlib import Path
7
+ from uuid import uuid4
8
+
9
+ from drift.collectors.engine import run_collectors
10
+ from drift.collectors.registry import build_registry
11
+ from drift.config import ProjectConfig
12
+ from drift.exceptions import (
13
+ HistoryEmptyError,
14
+ HistoryIncompleteError,
15
+ InvalidSnapshotError,
16
+ SnapshotNotFoundError,
17
+ StorageError,
18
+ UnsafePathError,
19
+ UnsupportedSchemaError,
20
+ )
21
+ from drift.models import CapturedEnvironment, Scope, Snapshot
22
+ from drift.storage import publish_snapshot, read_snapshot, snapshot_ids
23
+
24
+
25
+ def capture(root: Path, config: ProjectConfig) -> CapturedEnvironment:
26
+ allowlist = config.environment.active_allowlist
27
+ scope = Scope(
28
+ active_allowlist=None if allowlist is None else sorted(allowlist),
29
+ active_name_case="uppercase" if os.name == "nt" else "preserve",
30
+ compose_project=config.docker.compose_project,
31
+ )
32
+ results = run_collectors(root, config, build_registry(config))
33
+ return CapturedEnvironment.model_validate(
34
+ {
35
+ "scope": scope,
36
+ "collectors": {name: asdict(result) for name, result in results.items()},
37
+ }
38
+ )
39
+
40
+
41
+ def capture_snapshot(
42
+ root: Path, config: ProjectConfig, message: str | None
43
+ ) -> Snapshot:
44
+ current = capture(root, config)
45
+ timestamp = datetime.now(UTC).isoformat().replace("+00:00", "Z")
46
+ for _ in range(8):
47
+ snapshot = Snapshot(
48
+ schema_version=1,
49
+ id=uuid4().hex,
50
+ created_at=timestamp,
51
+ message=message,
52
+ scope=current.scope,
53
+ collectors=current.collectors,
54
+ )
55
+ if publish_snapshot(root, snapshot):
56
+ return snapshot
57
+ raise StorageError("Could not allocate a unique snapshot ID.")
58
+
59
+
60
+ def summary(snapshot: Snapshot) -> dict[str, object]:
61
+ return {
62
+ "id": snapshot.id,
63
+ "created_at": snapshot.created_at,
64
+ "message": snapshot.message,
65
+ "collector_statuses": {
66
+ name: result.status for name, result in snapshot.collectors.items()
67
+ },
68
+ }
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class History:
73
+ snapshots: list[Snapshot]
74
+ damaged: list[dict[str, str]]
75
+
76
+
77
+ def _chronological(snapshot: Snapshot) -> tuple[datetime, str, str]:
78
+ timestamp = datetime.fromisoformat(snapshot.created_at).replace(microsecond=0)
79
+ fraction = snapshot.created_at.removesuffix("Z").partition(".")[2].rstrip("0")
80
+ return timestamp, fraction, snapshot.id
81
+
82
+
83
+ def list_history(root: Path) -> History:
84
+ readable: list[Snapshot] = []
85
+ damaged: list[dict[str, str]] = []
86
+ for snapshot_id in snapshot_ids(root):
87
+ try:
88
+ readable.append(read_snapshot(root, snapshot_id))
89
+ except SnapshotNotFoundError:
90
+ damaged.append({"id": snapshot_id, "code": "storage_error"})
91
+ except (
92
+ InvalidSnapshotError,
93
+ UnsupportedSchemaError,
94
+ UnsafePathError,
95
+ StorageError,
96
+ ) as error:
97
+ damaged.append({"id": snapshot_id, "code": error.code})
98
+ return History(sorted(readable, key=_chronological), damaged)
99
+
100
+
101
+ def latest_snapshot(root: Path) -> Snapshot:
102
+ history = list_history(root)
103
+ if history.damaged:
104
+ raise HistoryIncompleteError(
105
+ "History contains damaged entries. Run drift history or select a snapshot explicitly."
106
+ )
107
+ if not history.snapshots:
108
+ raise HistoryEmptyError("There are no snapshots. Run drift snapshot first.")
109
+ return history.snapshots[-1]