cli-svckit 0.1.2__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.
cli_svckit/procs.py ADDED
@@ -0,0 +1,139 @@
1
+ """Process helpers: liveness, start time, and the process table (parent/group relations).
2
+
3
+ Everything here returns ``None`` or an empty list instead of raising when the platform tool (``ps``) is missing
4
+ or fails. ``psutil`` is used when it can be imported, otherwise ``ps`` output is parsed.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import subprocess
11
+ import time
12
+ from dataclasses import dataclass
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class ProcInfo:
17
+ """One row of the process table."""
18
+
19
+ pid: int
20
+ ppid: int
21
+ pgid: int
22
+ command: str
23
+
24
+
25
+ def _ps_field(pid: int, field: str) -> str | None:
26
+ try:
27
+ out = subprocess.run(
28
+ ["ps", "-o", f"{field}=", "-p", str(pid)], capture_output=True, text=True, timeout=5, check=False,
29
+ env={**os.environ, "LC_ALL": "C"},
30
+ )
31
+ except (OSError, subprocess.SubprocessError):
32
+ return None
33
+ text = out.stdout.strip()
34
+ return text if out.returncode == 0 and text else None
35
+
36
+
37
+ def pid_alive(pid: int) -> bool:
38
+ """Return True when a process with this pid exists (a zombie counts as gone when ``ps`` can tell)."""
39
+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
40
+ return False
41
+ try:
42
+ os.kill(pid, 0)
43
+ except ProcessLookupError:
44
+ return False
45
+ except PermissionError:
46
+ return True
47
+ except OSError:
48
+ return False
49
+ state = _ps_field(pid, "stat")
50
+ return not (state is not None and state.startswith("Z"))
51
+
52
+
53
+ def process_start_time(pid: int) -> float | None:
54
+ """Return the process start time as a UNIX timestamp, or None when unknown or the process is gone."""
55
+ try:
56
+ import psutil # type: ignore[import-not-found,unused-ignore]
57
+ except ImportError:
58
+ psutil = None
59
+ if psutil is not None:
60
+ try:
61
+ return float(psutil.Process(pid).create_time())
62
+ except Exception:
63
+ return None
64
+ text = _ps_field(pid, "lstart")
65
+ if text is None:
66
+ return None
67
+ try:
68
+ # lstart looks like "Mon Jan 2 15:04:05 2006" in the local time zone.
69
+ return float(time.mktime(time.strptime(text, "%a %b %d %H:%M:%S %Y")))
70
+ except (ValueError, OverflowError):
71
+ return None
72
+
73
+
74
+ def parse_ps(text: str) -> list[ProcInfo]:
75
+ """Parse ``ps -axo pid=,ppid=,pgid=,command=`` output; malformed lines are skipped."""
76
+ rows: list[ProcInfo] = []
77
+ for line in text.splitlines():
78
+ parts = line.split(None, 3)
79
+ if len(parts) < 3:
80
+ continue
81
+ try:
82
+ pid, ppid, pgid = int(parts[0]), int(parts[1]), int(parts[2])
83
+ except ValueError:
84
+ continue
85
+ rows.append(ProcInfo(pid, ppid, pgid, parts[3].strip() if len(parts) > 3 else ""))
86
+ return rows
87
+
88
+
89
+ def process_table() -> list[ProcInfo]:
90
+ """Return all visible processes, or an empty list when they cannot be listed."""
91
+ try:
92
+ import psutil # type: ignore[import-not-found,unused-ignore]
93
+ except ImportError:
94
+ psutil = None
95
+ if psutil is not None:
96
+ try:
97
+ rows = []
98
+ for p in psutil.process_iter(["pid", "ppid", "cmdline"]):
99
+ info = p.info
100
+ try:
101
+ pgid = os.getpgid(info["pid"])
102
+ except OSError:
103
+ continue
104
+ rows.append(ProcInfo(info["pid"], info["ppid"] or 0, pgid, " ".join(info.get("cmdline") or [])))
105
+ if rows:
106
+ return rows
107
+ except Exception:
108
+ pass
109
+ try:
110
+ out = subprocess.run(
111
+ ["ps", "-axo", "pid=,ppid=,pgid=,command="], capture_output=True, text=True, timeout=10, check=False
112
+ )
113
+ except (OSError, subprocess.SubprocessError):
114
+ return []
115
+ return parse_ps(out.stdout) if out.returncode == 0 else []
116
+
117
+
118
+ def descendants(pid: int, table: list[ProcInfo] | None = None) -> list[ProcInfo]:
119
+ """Return every child, grandchild, ... of ``pid`` (not ``pid`` itself), breadth first."""
120
+ rows = process_table() if table is None else table
121
+ children: dict[int, list[ProcInfo]] = {}
122
+ for row in rows:
123
+ children.setdefault(row.ppid, []).append(row)
124
+ found: list[ProcInfo] = []
125
+ seen = {pid}
126
+ queue = [pid]
127
+ while queue:
128
+ for child in children.get(queue.pop(0), []):
129
+ if child.pid not in seen:
130
+ seen.add(child.pid)
131
+ found.append(child)
132
+ queue.append(child.pid)
133
+ return found
134
+
135
+
136
+ def group_members(pgid: int, table: list[ProcInfo] | None = None) -> list[ProcInfo]:
137
+ """Return every process in the process group ``pgid``."""
138
+ rows = process_table() if table is None else table
139
+ return [row for row in rows if row.pgid == pgid]
cli_svckit/py.typed ADDED
File without changes
cli_svckit/rcfile.py ADDED
@@ -0,0 +1,336 @@
1
+ """Put a tool's command on PATH (rc-file line or symlink) and remove exactly what was installed.
2
+
3
+ Install records a receipt; uninstall only removes the line/link the receipt vouches for and refuses
4
+ (``SvcError("forbidden")``) when it was edited, duplicated or has no receipt. All rc-file work is done on
5
+ bytes so every other byte of the file is left untouched.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import difflib
11
+ import os
12
+ import tempfile
13
+ import time
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from cli_svckit.contract.envelope import SvcError
20
+ from cli_svckit.receipts import Receipts, sha256_text
21
+
22
+
23
+ @dataclass
24
+ class Action:
25
+ """One change made (or planned) by an install helper; ``op`` is rc_line, link, remove or write."""
26
+
27
+ op: str
28
+ path: str
29
+ line: str | None = None
30
+ target: str | None = None
31
+ sha256: str | None = None
32
+
33
+ def to_dict(self) -> dict[str, Any]:
34
+ """Return the install-result ``actions`` item (unset fields omitted)."""
35
+ d: dict[str, Any] = {"op": self.op, "path": self.path}
36
+ for key in ("line", "target", "sha256"):
37
+ value = getattr(self, key)
38
+ if value is not None:
39
+ d[key] = value
40
+ return d
41
+
42
+
43
+ # ---------------------------------------------------------------- helpers
44
+
45
+
46
+ def _managed(line: str, marker: str) -> str:
47
+ return f"{line} # {marker}"
48
+
49
+
50
+ def _split(data: bytes) -> list[bytes]:
51
+ """Split on newline keeping line endings; the last item has none when the file lacks a final newline."""
52
+ parts = data.split(b"\n")
53
+ out = [p + b"\n" for p in parts[:-1]]
54
+ if parts[-1]:
55
+ out.append(parts[-1])
56
+ return out
57
+
58
+
59
+ def _content(raw: bytes) -> str:
60
+ return raw.removesuffix(b"\n").removesuffix(b"\r").decode("utf-8", "surrogateescape")
61
+
62
+
63
+ def _eol_of(data: bytes) -> bytes:
64
+ i = data.find(b"\n")
65
+ return b"\r\n" if i > 0 and data[i - 1 : i] == b"\r" else b"\n"
66
+
67
+
68
+ def _marked(lines: list[bytes], marker: str) -> list[int]:
69
+ suffix = f" # {marker}"
70
+ return [i for i, raw in enumerate(lines) if _content(raw).endswith(suffix)]
71
+
72
+
73
+ def _read(path: Path) -> bytes | None:
74
+ try:
75
+ return path.read_bytes()
76
+ except FileNotFoundError:
77
+ return None
78
+
79
+
80
+ def _write_atomic(path: Path, data: bytes) -> None:
81
+ real = Path(os.path.realpath(path))
82
+ real.parent.mkdir(parents=True, exist_ok=True)
83
+ mode = real.stat().st_mode & 0o7777 if real.exists() else 0o644
84
+ # mkstemp creates the file 0600 with a unique name, so it is never wider than the source
85
+ fd, tmp_name = tempfile.mkstemp(prefix=real.name + ".svckit-tmp-", dir=real.parent)
86
+ try:
87
+ with os.fdopen(fd, "wb") as fh:
88
+ fh.write(data)
89
+ os.chmod(tmp_name, mode)
90
+ os.replace(tmp_name, real)
91
+ except BaseException:
92
+ Path(tmp_name).unlink(missing_ok=True)
93
+ raise
94
+
95
+
96
+ def _backup(path: Path, clock: Callable[[], float]) -> Path:
97
+ stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime(clock()))
98
+ mode = path.stat().st_mode & 0o7777
99
+ data = path.read_bytes()
100
+ n = 0
101
+ while True:
102
+ suffix = f"-{n}" if n else ""
103
+ dest = path.with_name(f"{path.name}.svckit-backup-{stamp}{suffix}")
104
+ try:
105
+ fd = os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
106
+ except FileExistsError:
107
+ n += 1
108
+ continue
109
+ break
110
+ with os.fdopen(fd, "wb") as fh:
111
+ fh.write(data)
112
+ os.chmod(dest, mode)
113
+ return dest
114
+
115
+
116
+ def _key(path: str | os.PathLike[str]) -> str:
117
+ """Receipt key for a path: ``~`` expanded and made absolute, so every spelling finds the same entry."""
118
+ return os.path.abspath(os.path.expanduser(path))
119
+
120
+
121
+ def _entries(receipts: Receipts, name: str) -> list[dict[str, Any]]:
122
+ doc = receipts.read(name)
123
+ return list(doc["entries"]) if doc else []
124
+
125
+
126
+ def _store(receipts: Receipts, name: str, entries: list[dict[str, Any]]) -> None:
127
+ if entries:
128
+ receipts.write(name, entries)
129
+ else:
130
+ receipts.remove(name)
131
+
132
+
133
+ def _refuse(message: str, path: Path, found: str) -> SvcError:
134
+ return SvcError("forbidden", message, data={"path": str(path), "found": found})
135
+
136
+
137
+ # ---------------------------------------------------------------- rc line
138
+
139
+
140
+ def install_rc_line(
141
+ rc_path: str | os.PathLike[str],
142
+ line: str,
143
+ marker: str,
144
+ *,
145
+ receipts: Receipts,
146
+ name: str,
147
+ dry_run: bool = False,
148
+ backup: bool = True,
149
+ clock: Callable[[], float] = time.time,
150
+ ) -> list[Action]:
151
+ """Append ``<line> # <marker>`` to the rc file (creating it) unless it is already there.
152
+
153
+ Idempotent: an identical managed line means no action. A marked line that differs raises ``forbidden``.
154
+ A CRLF file gets a CRLF line; a file without a final newline gets one added first (recorded in the
155
+ receipt so uninstall can restore the exact original bytes). Returns the actions (same on dry run).
156
+ """
157
+ path = Path(os.path.expanduser(rc_path))
158
+ text = _managed(line, marker)
159
+ data = _read(path)
160
+ existing = _marked(_split(data), marker) if data is not None else []
161
+ if existing:
162
+ lines = _split(data or b"")
163
+ if len(existing) == 1 and _content(lines[existing[0]]) == text:
164
+ return []
165
+ if len(existing) > 1:
166
+ raise _refuse("the marker appears more than once", path, "duplicate")
167
+ raise _refuse("a line with this marker already exists and differs", path, "edited")
168
+ action = Action("rc_line", str(path), line=text, sha256=sha256_text(text))
169
+ if dry_run:
170
+ return [action]
171
+ old = data or b""
172
+ eol = _eol_of(old)
173
+ prefix = bool(old) and not old.endswith(b"\n")
174
+ new = old + (eol if prefix else b"") + text.encode("utf-8", "surrogateescape") + eol
175
+ if data is not None and backup:
176
+ _backup(path, clock)
177
+ _write_atomic(path, new)
178
+ entries = [e for e in _entries(receipts, name) if not (e.get("kind") == "rc_line" and e.get("path") == _key(path))]
179
+ entries.append(
180
+ {
181
+ "kind": "rc_line",
182
+ "path": _key(path),
183
+ "sha256": action.sha256,
184
+ "line": text,
185
+ "prefix_eol": prefix,
186
+ "created": data is None,
187
+ }
188
+ )
189
+ receipts.write(name, entries)
190
+ return [action]
191
+
192
+
193
+ def uninstall_rc_line(
194
+ rc_path: str | os.PathLike[str],
195
+ marker: str,
196
+ *,
197
+ receipts: Receipts,
198
+ name: str,
199
+ dry_run: bool = False,
200
+ force: bool = False,
201
+ clock: Callable[[], float] = time.time,
202
+ ) -> list[Action]:
203
+ """Remove only the line carrying ``marker``, after backing the file up.
204
+
205
+ Refuses with ``SvcError("forbidden", data={"path", "found"})`` when the receipt is missing, the line
206
+ differs from the receipt's hash (``edited``), or the marker appears more than once (``duplicate``);
207
+ ``force`` overrides this. Nothing else in the file changes. Nothing to remove returns ``[]``.
208
+ """
209
+ path = Path(os.path.expanduser(rc_path))
210
+ entries = _entries(receipts, name)
211
+ entry = next((e for e in entries if e.get("kind") == "rc_line" and e.get("path") == _key(path)), None)
212
+ data = _read(path)
213
+ lines = _split(data) if data is not None else []
214
+ idx = _marked(lines, marker)
215
+ if not idx:
216
+ if entry is None:
217
+ return []
218
+ if not force:
219
+ raise _refuse("the managed line is not in the file", path, "missing")
220
+ if not dry_run:
221
+ _store(receipts, name, [e for e in entries if e is not entry])
222
+ return []
223
+ if not force:
224
+ if len(idx) > 1:
225
+ raise _refuse("the marker appears more than once", path, "duplicate")
226
+ if entry is None:
227
+ raise _refuse("no receipt for this line", path, "missing")
228
+ if sha256_text(_content(lines[idx[0]])) != entry.get("sha256"):
229
+ raise _refuse("the managed line was edited", path, "edited")
230
+ texts = [_content(lines[i]) for i in idx]
231
+ actions = [Action("remove", str(path), line=t, sha256=sha256_text(t)) for t in texts]
232
+ if dry_run:
233
+ return actions
234
+ drop = set(idx)
235
+ if entry and entry.get("prefix_eol") and drop == {len(lines) - 1} and len(lines) > 1:
236
+ # the install added a newline after the previous (unterminated) last line: take it back
237
+ lines[-2] = lines[-2].removesuffix(b"\n").removesuffix(b"\r")
238
+ new = b"".join(raw for i, raw in enumerate(lines) if i not in drop)
239
+ _backup(path, clock)
240
+ if entry and entry.get("created") and not new:
241
+ Path(os.path.realpath(path)).unlink()
242
+ else:
243
+ _write_atomic(path, new)
244
+ _store(receipts, name, [e for e in entries if e is not entry])
245
+ return actions
246
+
247
+
248
+ # ---------------------------------------------------------------- symlinks
249
+
250
+
251
+ def _link_path(target: str | os.PathLike[str], link_dir: str | os.PathLike[str]) -> Path:
252
+ return Path(os.path.expanduser(link_dir)) / Path(target).name
253
+
254
+
255
+ def install_link(
256
+ target: str | os.PathLike[str],
257
+ link_dir: str | os.PathLike[str],
258
+ *,
259
+ receipts: Receipts,
260
+ name: str,
261
+ dry_run: bool = False,
262
+ ) -> list[Action]:
263
+ """Symlink ``link_dir/<basename of target>`` to ``target`` and record it.
264
+
265
+ An identical existing link is a no-op; anything else already at that path raises ``forbidden``.
266
+ """
267
+ link = _link_path(target, link_dir)
268
+ tgt = str(target)
269
+ if link.is_symlink() and os.readlink(link) == tgt:
270
+ return []
271
+ if link.is_symlink() or link.exists():
272
+ raise _refuse("something that was not installed here already exists", link, "edited")
273
+ action = Action("link", str(link), target=tgt, sha256=sha256_text(tgt))
274
+ if dry_run:
275
+ return [action]
276
+ link.parent.mkdir(parents=True, exist_ok=True)
277
+ os.symlink(tgt, link)
278
+ entries = [e for e in _entries(receipts, name) if not (e.get("kind") == "link" and e.get("path") == _key(link))]
279
+ entries.append({"kind": "link", "path": _key(link), "sha256": action.sha256, "target": tgt})
280
+ receipts.write(name, entries)
281
+ return [action]
282
+
283
+
284
+ def uninstall_link(
285
+ target: str | os.PathLike[str],
286
+ link_dir: str | os.PathLike[str],
287
+ *,
288
+ receipts: Receipts,
289
+ name: str,
290
+ dry_run: bool = False,
291
+ force: bool = False,
292
+ ) -> list[Action]:
293
+ """Remove the link this tool created; refuse (``forbidden``) if it is not a receipted symlink to ``target``."""
294
+ link = _link_path(target, link_dir)
295
+ entries = _entries(receipts, name)
296
+ entry = next((e for e in entries if e.get("kind") == "link" and e.get("path") == _key(link)), None)
297
+ if not (link.is_symlink() or link.exists()):
298
+ if entry is not None and not dry_run:
299
+ _store(receipts, name, [e for e in entries if e is not entry])
300
+ return []
301
+ if not force:
302
+ if entry is None:
303
+ raise _refuse("no receipt for this link", link, "missing")
304
+ if not link.is_symlink() or os.readlink(link) != entry.get("target"):
305
+ raise _refuse("the link was replaced or edited", link, "edited")
306
+ action = Action("remove", str(link), target=str(target))
307
+ if dry_run:
308
+ return [action]
309
+ link.unlink()
310
+ _store(receipts, name, [e for e in entries if e is not entry])
311
+ return [action]
312
+
313
+
314
+ # ---------------------------------------------------------------- diff
315
+
316
+
317
+ def plan_diff(rc_path: str | os.PathLike[str], actions: list[Action]) -> str:
318
+ """Return a unified diff of what ``actions`` (rc_line / remove) would do to ``rc_path`` (for ``--dry-run``)."""
319
+ path = Path(os.path.expanduser(rc_path))
320
+ data = _read(path) or b""
321
+ old = _split(data)
322
+ eol = _eol_of(data)
323
+ new = list(old)
324
+ for a in actions:
325
+ if a.path != str(path) or a.line is None:
326
+ continue
327
+ raw = a.line.encode("utf-8", "surrogateescape")
328
+ if a.op == "rc_line":
329
+ if new and not new[-1].endswith(b"\n"):
330
+ new[-1] += eol
331
+ new.append(raw + eol)
332
+ elif a.op == "remove":
333
+ new = [r for r in new if _content(r) != a.line]
334
+ old_t = [r.decode("utf-8", "replace") for r in old]
335
+ new_t = [r.decode("utf-8", "replace") for r in new]
336
+ return "".join(difflib.unified_diff(old_t, new_t, f"a/{path.name}", f"b/{path.name}"))
cli_svckit/receipts.py ADDED
@@ -0,0 +1,59 @@
1
+ """Install receipts: a small record of exactly what an install changed, so uninstall removes only that."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import tempfile
9
+ import time
10
+ from collections.abc import Callable
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+
15
+ def sha256_text(s: str) -> str:
16
+ """Return the hex SHA-256 of ``s`` encoded as UTF-8 (lone surrogates from undecodable bytes are preserved)."""
17
+ return hashlib.sha256(s.encode("utf-8", "surrogateescape")).hexdigest()
18
+
19
+
20
+ class Receipts:
21
+ """Receipt store: one ``<dir>/<name>.json`` per installed tool, files mode 0600, directory 0700."""
22
+
23
+ def __init__(self, dir: str | os.PathLike[str], *, clock: Callable[[], float] = time.time) -> None:
24
+ self.dir = Path(dir)
25
+ self._clock = clock
26
+
27
+ def _path(self, name: str) -> Path:
28
+ if not name or "/" in name or "\\" in name or name.startswith("."):
29
+ raise ValueError(f"invalid receipt name: {name!r}")
30
+ return self.dir / f"{name}.json"
31
+
32
+ def write(self, name: str, entries: list[dict[str, Any]]) -> Path:
33
+ """Store ``entries`` for ``name`` (replacing any earlier receipt) and return the file path."""
34
+ path = self._path(name)
35
+ self.dir.mkdir(parents=True, exist_ok=True)
36
+ os.chmod(self.dir, 0o700)
37
+ doc = {"v": 1, "name": name, "entries": entries, "written_at": self._clock()}
38
+ fd, tmp = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=self.dir)
39
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
40
+ fh.write(json.dumps(doc, indent=2, sort_keys=True) + "\n")
41
+ os.chmod(tmp, 0o600)
42
+ os.replace(tmp, path)
43
+ return path
44
+
45
+ def read(self, name: str) -> dict[str, Any] | None:
46
+ """Return the receipt document for ``name``, or None when absent or unreadable."""
47
+ try:
48
+ doc = json.loads(self._path(name).read_text(encoding="utf-8"))
49
+ except (OSError, ValueError):
50
+ return None
51
+ return doc if isinstance(doc, dict) and isinstance(doc.get("entries"), list) else None
52
+
53
+ def remove(self, name: str) -> bool:
54
+ """Delete the receipt for ``name``; return whether one existed."""
55
+ try:
56
+ self._path(name).unlink()
57
+ except FileNotFoundError:
58
+ return False
59
+ return True