python-corekit 0.4.1__py3-none-any.whl → 0.6.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.
Files changed (41) hide show
  1. corekit/connections/sql/connection.py +6 -2
  2. corekit/docker/__init__.py +4 -2
  3. corekit/docker/client.py +48 -0
  4. corekit/docker/constants.py +19 -0
  5. corekit/docker/disk/__init__.py +8 -0
  6. corekit/docker/disk/constants.py +14 -0
  7. corekit/docker/disk/inspector.py +217 -0
  8. corekit/docker/disk/models.py +44 -0
  9. corekit/docker/watchdog.py +10 -8
  10. corekit/exceptions/__init__.py +2 -0
  11. corekit/exceptions/base.py +19 -0
  12. corekit/files/__init__.py +3 -0
  13. corekit/files/disk.py +123 -0
  14. corekit/html/__init__.py +22 -0
  15. corekit/html/client.py +22 -0
  16. corekit/html/models.py +20 -0
  17. corekit/html/parser.py +272 -0
  18. corekit/html/scraper.py +127 -0
  19. corekit/html/settings.py +197 -0
  20. corekit/html/state.py +56 -0
  21. corekit/http/__init__.py +2 -1
  22. corekit/http/api.py +71 -3
  23. corekit/http/client.py +24 -54
  24. corekit/http/response.py +38 -5
  25. corekit/llm/client.py +3 -2
  26. corekit/llm/tools/loop.py +5 -2
  27. corekit/llm/wire.py +11 -5
  28. corekit/process/__init__.py +7 -0
  29. corekit/process/runner.py +47 -0
  30. corekit/schemas/__init__.py +10 -1
  31. corekit/schemas/models/arbitrary.py +49 -5
  32. corekit/schemas/size.py +85 -0
  33. corekit/utils/__init__.py +62 -7
  34. corekit/utils/coercion.py +59 -73
  35. corekit/utils/collections.py +242 -4
  36. corekit/utils/parsers.py +205 -0
  37. {python_corekit-0.4.1.dist-info → python_corekit-0.6.0.dist-info}/METADATA +10 -8
  38. {python_corekit-0.4.1.dist-info → python_corekit-0.6.0.dist-info}/RECORD +41 -23
  39. {python_corekit-0.4.1.dist-info → python_corekit-0.6.0.dist-info}/WHEEL +1 -1
  40. {python_corekit-0.4.1.dist-info → python_corekit-0.6.0.dist-info}/licenses/LICENSE +0 -0
  41. {python_corekit-0.4.1.dist-info → python_corekit-0.6.0.dist-info}/top_level.txt +0 -0
@@ -330,15 +330,19 @@ class SQLConnection(Connectable):
330
330
  """
331
331
  return list(self._exec(query.build()))
332
332
 
333
- def delete_many_by_query(self, query: Query) -> None:
333
+ def delete_many_by_query(self, query: Query) -> int:
334
334
  """
335
335
  Delete every row matching a Query.
336
+
337
+ Returns the number of rows deleted.
336
338
  """
337
339
  self.require_writable()
338
340
  self._start_session()
339
- for item in self.fetch_many_by_query(query):
341
+ items = self.fetch_many_by_query(query)
342
+ for item in items:
340
343
  self.session.delete(item)
341
344
  self.session.commit()
345
+ return len(items)
342
346
 
343
347
  def execute(self, operation: Operation) -> Any:
344
348
  """
@@ -1,7 +1,9 @@
1
1
  """
2
- Docker container control.
2
+ Docker container control and disk inspection.
3
3
  """
4
4
 
5
+ from corekit.docker.client import DockerClientProvider
6
+ from corekit.docker.disk import ContainerLog, DfCategory, DockerDiskInspector, ImageSize
5
7
  from corekit.docker.watchdog import Watchdog
6
8
 
7
- __all__ = ["Watchdog"]
9
+ __all__ = ["ContainerLog", "DfCategory", "DockerClientProvider", "DockerDiskInspector", "ImageSize", "Watchdog"]
@@ -0,0 +1,48 @@
1
+ """
2
+ Getting a Docker SDK client without assuming where the daemon lives.
3
+
4
+ ``DockerClientProvider`` is the one place that resolves the endpoint:
5
+ an explicit host wins, then ``$DOCKER_HOST``, then the first socket that
6
+ actually exists among the usual locations (including snap's), and only
7
+ then the classic default. ``Watchdog`` and ``DockerDiskInspector`` both
8
+ build their clients through here, so a daemon that moves (classic install
9
+ to snap, say) is found by both.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+
16
+ from docker import DockerClient
17
+
18
+ from corekit.docker.constants import DEFAULT_DOCKER_HOST, DOCKER_SOCKET_CANDIDATES
19
+
20
+ __all__ = ["DockerClientProvider"]
21
+
22
+
23
+ class DockerClientProvider:
24
+ """
25
+ Resolves Docker endpoints and builds SDK clients for them.
26
+ """
27
+
28
+ @staticmethod
29
+ def resolve_host(docker_host: str | None = None) -> str:
30
+ """
31
+ Resolve the endpoint to use, without connecting to it.
32
+ """
33
+ if docker_host:
34
+ return docker_host
35
+ from_env = os.environ.get("DOCKER_HOST")
36
+ if from_env:
37
+ return from_env
38
+ for candidate in DOCKER_SOCKET_CANDIDATES:
39
+ if candidate.exists():
40
+ return f"unix://{candidate}"
41
+ return DEFAULT_DOCKER_HOST
42
+
43
+ @staticmethod
44
+ def create_client(docker_host: str | None = None) -> DockerClient:
45
+ """
46
+ Build an SDK client for the resolved endpoint.
47
+ """
48
+ return DockerClient(base_url=DockerClientProvider.resolve_host(docker_host))
@@ -0,0 +1,19 @@
1
+ """
2
+ Shared Docker daemon constants.
3
+ """
4
+
5
+ from pathlib import Path
6
+
7
+ DEFAULT_DOCKER_HOST = "unix:///var/run/docker.sock"
8
+
9
+ # Candidate sockets in preference order. Snap Docker does not use
10
+ # /var/run/docker.sock, which is the single most common reason an SDK
11
+ # client "cannot connect" on an Ubuntu host.
12
+ DOCKER_SOCKET_CANDIDATES: tuple[Path, ...] = (
13
+ Path("/var/run/docker.sock"),
14
+ Path("/run/docker.sock"),
15
+ Path("/var/snap/docker/current/run/docker.sock"),
16
+ )
17
+
18
+ WATCHDOG_LABEL = "watchdog"
19
+ WATCHDOG_MANAGED = "true"
@@ -0,0 +1,8 @@
1
+ """
2
+ Docker disk inspection: what is using the space under the Docker root.
3
+ """
4
+
5
+ from corekit.docker.disk.inspector import DockerDiskInspector
6
+ from corekit.docker.disk.models import ContainerLog, DfCategory, ImageSize
7
+
8
+ __all__ = ["ContainerLog", "DfCategory", "DockerDiskInspector", "ImageSize"]
@@ -0,0 +1,14 @@
1
+ """
2
+ Constants for Docker disk inspection.
3
+ """
4
+
5
+ # (display name, key in the daemon's df report, dot-path to the entry's size)
6
+ # Volumes nest their size under UsageData; everything else is a top-level field.
7
+ DF_CATEGORIES: tuple[tuple[str, str, str], ...] = (
8
+ ("Images", "Images", "Size"),
9
+ ("Containers", "Containers", "SizeRw"),
10
+ ("Volumes", "Volumes", "UsageData.Size"),
11
+ ("Build Cache", "BuildCache", "Size"),
12
+ )
13
+
14
+ UNREFERENCED_IMAGE = "<none>:<none>"
@@ -0,0 +1,217 @@
1
+ """
2
+ Where Docker's disk went.
3
+
4
+ ``DockerDiskInspector`` is the read-side counterpart to ``Watchdog``:
5
+ Watchdog changes container state, the inspector measures it -- Docker root
6
+ usage, per-container log sizes, largest volumes and images, and a
7
+ ``docker system df``-style summary. It can also truncate container logs,
8
+ which is a measurement remedy rather than lifecycle control, and safe:
9
+ truncating in place reclaims space immediately, deleting would not.
10
+
11
+ Daemon data comes from the Docker SDK (built by ``DockerClientProvider``,
12
+ so snap and classic installs are both found); on-disk sizes come from
13
+ ``corekit.files.DiskScanner``, because the daemon does not report log-file
14
+ sizes and its volume accounting does not match ``du``. Filesystem access
15
+ under the Docker root typically needs elevation, which the scanner handles.
16
+
17
+ Daemon payloads are untrusted-shaped: every field is extracted through the
18
+ ``parse_*``/``safe_*`` utilities and ``getval`` rather than raw indexing.
19
+
20
+ inspector = DockerDiskInspector()
21
+ inspector.root_dir() # snap-aware: the socket is discovered
22
+ inspector.container_logs() # every log, biggest first
23
+ inspector.truncate_log("api") # after you have looked at it
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from pathlib import Path
29
+
30
+ from docker import DockerClient
31
+ from docker.errors import APIError, NotFound
32
+
33
+ from corekit.docker.client import DockerClientProvider
34
+ from corekit.docker.disk import constants as disk_constants
35
+ from corekit.docker.disk.models import ContainerLog, DfCategory, ImageSize
36
+ from corekit.files.disk import DiskScanner, PathSize
37
+ from corekit.observability.benchmarkable import Benchmarkable
38
+ from corekit.utils import first_string, getval, parse_dict, safe_dict, safe_int, safe_list, safe_string
39
+
40
+ __all__ = ["DockerDiskInspector"]
41
+
42
+
43
+ class DockerDiskInspector(Benchmarkable):
44
+ """
45
+ Measures Docker disk usage via the SDK plus filesystem scans.
46
+
47
+ Unlike Watchdog there is no label enforcement: measuring is read-only,
48
+ and the one mutating operation (log truncation) is addressed by exact
49
+ container name or ID, never by pattern.
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ docker_host: str | None = None,
55
+ scanner: DiskScanner | None = None,
56
+ ) -> None:
57
+ """
58
+ :param docker_host: Docker endpoint; resolved by
59
+ ``DockerClientProvider`` (``$DOCKER_HOST``, existing sockets
60
+ including snap's, then the classic default) when omitted.
61
+ :param scanner: filesystem scanner for on-disk sizes; one with
62
+ elevation enabled by default.
63
+ """
64
+ super().__init__()
65
+ self.docker_host = DockerClientProvider.resolve_host(docker_host)
66
+ self._scanner = scanner or DiskScanner()
67
+ self._client_instance: DockerClient | None = None
68
+
69
+ @property
70
+ def _client(self) -> DockerClient:
71
+ """
72
+ The Docker client, connected on first use.
73
+ """
74
+ if self._client_instance is None:
75
+ self._client_instance = DockerClientProvider.create_client(self.docker_host)
76
+ return self._client_instance
77
+
78
+ # =============
79
+ # Daemon-level queries
80
+ # =============
81
+
82
+ def root_dir(self) -> Path:
83
+ """
84
+ The daemon's DockerRootDir (e.g. /var/snap/docker/common/var-lib-docker).
85
+ """
86
+ root = safe_string(getval(safe_dict(self._client.info()), "DockerRootDir"))
87
+ if not root:
88
+ raise RuntimeError("Daemon did not report a DockerRootDir (is docker running?)")
89
+ return Path(root)
90
+
91
+ def df_summary(self) -> list[DfCategory]:
92
+ """
93
+ Aggregate the daemon's df report into per-category counts and sizes.
94
+ """
95
+ report = parse_dict(self._client.df()).value
96
+ categories: list[DfCategory] = []
97
+ for display_name, report_key, size_path in disk_constants.DF_CATEGORIES:
98
+ entries = safe_list(getval(report, report_key, default=[]))
99
+ total = sum(safe_int(getval(entry, size_path, default=0)) for entry in entries)
100
+ categories.append(DfCategory(name=display_name, count=len(entries), size_bytes=total))
101
+ return categories
102
+
103
+ def images(self) -> list[ImageSize]:
104
+ """
105
+ Every image with its daemon-reported size, biggest first.
106
+ """
107
+ images = [
108
+ ImageSize(
109
+ reference=first_string(safe_list(image.tags), disk_constants.UNREFERENCED_IMAGE),
110
+ image_id=safe_string(image.short_id),
111
+ size_bytes=safe_int(getval(parse_dict(image.attrs).value, "Size")),
112
+ )
113
+ for image in self._client.images.list()
114
+ ]
115
+ return sorted(images, key=lambda img: img.size_bytes, reverse=True)
116
+
117
+ # =============
118
+ # Filesystem-backed queries
119
+ # =============
120
+
121
+ def root_children(self, root: Path | None = None) -> list[PathSize]:
122
+ """
123
+ Largest directories directly under the Docker root.
124
+ """
125
+ return self._scanner.child_sizes(root or self.root_dir())
126
+
127
+ def volumes(self, root: Path | None = None) -> list[PathSize]:
128
+ """
129
+ Largest Docker volumes (by on-disk size), biggest first.
130
+ """
131
+ return self._scanner.child_sizes((root or self.root_dir()) / "volumes")
132
+
133
+ def container_logs(self) -> list[ContainerLog]:
134
+ """
135
+ Every container's log with its size, biggest first.
136
+
137
+ Containers without a log path (non json-file drivers) or with an
138
+ unmeasurable log file are skipped.
139
+ """
140
+ logs: list[ContainerLog] = []
141
+ try:
142
+ containers = self._client.containers.list(all=True)
143
+ except APIError as exc:
144
+ self.error(f"Docker API error listing containers: {exc}")
145
+ return []
146
+ for container in containers:
147
+ log = self._measure_container_log(container)
148
+ if log is not None:
149
+ logs.append(log)
150
+ return sorted(logs, key=lambda x: x.size_bytes, reverse=True)
151
+
152
+ def logs_above(self, threshold_bytes: int) -> list[ContainerLog]:
153
+ """
154
+ Container logs strictly larger than the threshold, biggest first.
155
+ """
156
+ return [log for log in self.container_logs() if log.size_bytes > threshold_bytes]
157
+
158
+ def log_for(self, identifier: str) -> ContainerLog:
159
+ """
160
+ Resolve one container by name or ID and measure its log.
161
+
162
+ Raises LookupError if the container does not exist or has no log.
163
+ """
164
+ try:
165
+ container = self._client.containers.get(identifier)
166
+ except NotFound as exc:
167
+ raise LookupError(f"Container not found: {identifier}") from exc
168
+
169
+ log = self._measure_container_log(container)
170
+ if log is None:
171
+ raise LookupError(f"Container has no measurable log file (non json-file driver?): {identifier}")
172
+ return log
173
+
174
+ # =============
175
+ # Truncation
176
+ # =============
177
+
178
+ def truncate_log(self, identifier: str) -> ContainerLog:
179
+ """
180
+ Truncate one container's log; returns its pre-truncate measurement.
181
+ """
182
+ log = self.log_for(identifier)
183
+ self._scanner.truncate(log.log_path)
184
+ return log
185
+
186
+ def truncate_logs(self, logs: list[ContainerLog]) -> None:
187
+ """
188
+ Truncate each given container log.
189
+ """
190
+ for log in logs:
191
+ self._scanner.truncate(log.log_path)
192
+
193
+ # =============
194
+ # Private Methods
195
+ # =============
196
+
197
+ def _measure_container_log(self, container: object) -> ContainerLog | None:
198
+ """
199
+ Build a ContainerLog for one SDK container, or None when it has no
200
+ log path or the file cannot be measured.
201
+ """
202
+
203
+ log_path_text = safe_string(getval(container, "attrs.LogPath", default=""))
204
+ if not log_path_text:
205
+ return None
206
+
207
+ log_path = Path(log_path_text)
208
+ size = self._scanner.file_size(log_path)
209
+ if size is None:
210
+ return None
211
+
212
+ return ContainerLog(
213
+ container_id=safe_string(getval(container, "id")),
214
+ name=safe_string(getval(container, "name")).lstrip("/"),
215
+ log_path=log_path,
216
+ size_bytes=size,
217
+ )
@@ -0,0 +1,44 @@
1
+ """
2
+ Data shapes returned by DockerDiskInspector.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ __all__ = ["ContainerLog", "DfCategory", "ImageSize"]
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class ContainerLog:
15
+ """
16
+ One container's json-file log and its measured size.
17
+ """
18
+
19
+ container_id: str
20
+ name: str
21
+ log_path: Path
22
+ size_bytes: int
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class ImageSize:
27
+ """
28
+ One image and its size as reported by the daemon.
29
+ """
30
+
31
+ reference: str
32
+ image_id: str
33
+ size_bytes: int
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class DfCategory:
38
+ """
39
+ One row of a ``docker system df``-style summary.
40
+ """
41
+
42
+ name: str
43
+ count: int
44
+ size_bytes: int
@@ -18,13 +18,13 @@ from docker import DockerClient
18
18
  from docker.errors import APIError, NotFound
19
19
  from docker.models.containers import Container
20
20
 
21
+ from corekit.docker.client import DockerClientProvider
22
+ from corekit.docker.constants import DEFAULT_DOCKER_HOST, WATCHDOG_LABEL, WATCHDOG_MANAGED
21
23
  from corekit.observability.benchmarkable import Benchmarkable
22
24
 
23
- __all__ = ["Watchdog"]
24
-
25
- DEFAULT_DOCKER_HOST = "unix:///var/run/docker.sock"
26
- WATCHDOG_LABEL = "watchdog"
27
- WATCHDOG_MANAGED = "true"
25
+ # DEFAULT_DOCKER_HOST / WATCHDOG_* are re-exported for backwards
26
+ # compatibility; the canonical definitions live in corekit.docker.constants.
27
+ __all__ = ["DEFAULT_DOCKER_HOST", "WATCHDOG_LABEL", "WATCHDOG_MANAGED", "Watchdog"]
28
28
 
29
29
 
30
30
  def _accept_all(*args: Any, **kwargs: Any) -> bool:
@@ -44,13 +44,15 @@ class Watchdog(Benchmarkable):
44
44
 
45
45
  def __init__(self, docker_host: str | None = None, enforce_label: bool = True) -> None:
46
46
  """
47
- :param docker_host: Docker endpoint. Defaults to the local socket.
47
+ :param docker_host: Docker endpoint. Defaults to the endpoint
48
+ resolved by ``DockerClientProvider`` (``$DOCKER_HOST``, then an
49
+ existing socket -- snap included -- then the classic default).
48
50
  :param enforce_label: restrict actions to containers carrying the
49
51
  managed label. On by default; turn it off only when this watchdog
50
52
  is meant to control every container on the host.
51
53
  """
52
54
  super().__init__()
53
- self.docker_host = docker_host or DEFAULT_DOCKER_HOST
55
+ self.docker_host = DockerClientProvider.resolve_host(docker_host)
54
56
  self.enforce_label = enforce_label
55
57
  self._client_instance: DockerClient | None = None
56
58
 
@@ -63,7 +65,7 @@ class Watchdog(Benchmarkable):
63
65
  and inspected on a machine where Docker is not running.
64
66
  """
65
67
  if self._client_instance is None:
66
- self._client_instance = DockerClient(base_url=self.docker_host)
68
+ self._client_instance = DockerClientProvider.create_client(self.docker_host)
67
69
  return self._client_instance
68
70
 
69
71
  @staticmethod
@@ -7,6 +7,7 @@ a user. ``CoreHTTPException`` is the FastAPI-facing public exception.
7
7
  """
8
8
 
9
9
  from corekit.exceptions.base import (
10
+ CommandFailedError,
10
11
  CoreException,
11
12
  CoreHTTPException,
12
13
  ExponentialBackoffTimeoutException,
@@ -20,6 +21,7 @@ from corekit.exceptions.types import ArbitraryCoreExceptionType, CoreExceptionTy
20
21
 
21
22
  __all__ = [
22
23
  "ArbitraryCoreExceptionType",
24
+ "CommandFailedError",
23
25
  "CoreException",
24
26
  "CoreExceptionType",
25
27
  "CoreHTTPException",
@@ -27,6 +27,7 @@ from fastapi import HTTPException
27
27
  from corekit.exceptions.enum import Retryability
28
28
 
29
29
  __all__ = [
30
+ "CommandFailedError",
30
31
  "CoreException",
31
32
  "CoreHTTPException",
32
33
  "RetryableCoreHTTPException",
@@ -112,6 +113,24 @@ class ExponentialBackoffTimeoutException(InternalCoreException):
112
113
  self.attempts = attempts
113
114
 
114
115
 
116
+ class CommandFailedError(InternalCoreException):
117
+ """
118
+ An external command exited non-zero, timed out, or could not be started.
119
+
120
+ ``command`` is the argv that was run; ``detail`` (also carried as the
121
+ shared ``error`` field) is stderr text or the OS-level reason.
122
+ """
123
+
124
+ def __init__(self, command: list[str], detail: str) -> None:
125
+ super().__init__(
126
+ message=f"Command failed: {' '.join(command)}",
127
+ retryable=Retryability.NON_RETRYABLE,
128
+ error=detail,
129
+ )
130
+ self.command = command
131
+ self.detail = detail
132
+
133
+
115
134
  class CoreHTTPException(HTTPException, PublicCoreException):
116
135
  """
117
136
  FastAPI HTTPException that is also a PublicCoreException.
corekit/files/__init__.py CHANGED
@@ -9,15 +9,18 @@ File reading and writing, with format handled by the manager.
9
9
  """
10
10
 
11
11
  from corekit.files.base import FileContent, FileError, FileManager
12
+ from corekit.files.disk import DiskScanner, PathSize
12
13
  from corekit.files.enum import FileMode
13
14
  from corekit.files.json import JsonFileManager
14
15
  from corekit.files.toml import TomlFileManager
15
16
 
16
17
  __all__ = [
18
+ "DiskScanner",
17
19
  "FileContent",
18
20
  "FileError",
19
21
  "FileManager",
20
22
  "FileMode",
21
23
  "JsonFileManager",
24
+ "PathSize",
22
25
  "TomlFileManager",
23
26
  ]
corekit/files/disk.py ADDED
@@ -0,0 +1,123 @@
1
+ """
2
+ Measuring and truncating files on disk.
3
+
4
+ ``DiskScanner`` answers "how big is this path?" for files and directory
5
+ trees, and truncates files in place. Every operation tries direct access
6
+ first and, on failure, retries elevated through the ``CommandRunner``
7
+ (log files and layer directories under a Docker root are root-owned, so an
8
+ unprivileged process typically cannot stat them). Pass ``elevate=False``
9
+ to disable the retry; unmeasurable paths then report ``None`` instead of
10
+ prompting for a password.
11
+
12
+ Sizes for single files are apparent sizes (``stat``); directory sizes are
13
+ ``du -sb`` totals. Both are byte counts and directly comparable.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+
21
+ from corekit.exceptions import CommandFailedError
22
+ from corekit.process import CommandRunner
23
+
24
+ __all__ = ["DiskScanner", "PathSize"]
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class PathSize:
29
+ """
30
+ A filesystem path with its measured size in bytes.
31
+ """
32
+
33
+ path: Path
34
+ size_bytes: int
35
+
36
+
37
+ class DiskScanner:
38
+ """
39
+ Filesystem sizing and in-place truncation, with optional elevation.
40
+ """
41
+
42
+ def __init__(self, runner: CommandRunner | None = None, *, elevate: bool = True) -> None:
43
+ """
44
+ :param runner: command executor for the elevated fallbacks and for
45
+ ``du``/``find``; a plain ``CommandRunner`` by default.
46
+ :param elevate: allow sudo retries when direct access fails.
47
+ """
48
+ self._runner = runner or CommandRunner()
49
+ self._elevate = elevate
50
+
51
+ def file_size(self, path: Path) -> int | None:
52
+ """
53
+ Size of a single file, or None if it cannot be measured.
54
+ """
55
+ try:
56
+ return path.stat().st_size
57
+ except OSError:
58
+ pass
59
+ if not self._elevate:
60
+ return None
61
+ try:
62
+ output = self._runner.run(["stat", "-c", "%s", str(path)], elevate=True)
63
+ return int(output.strip())
64
+ except (CommandFailedError, ValueError):
65
+ return None
66
+
67
+ def dir_size(self, path: Path) -> int | None:
68
+ """
69
+ Recursive size of a path (``du -sb``), or None if unmeasurable.
70
+ """
71
+ for elevate in (False, True):
72
+ if elevate and not self._elevate:
73
+ break
74
+ try:
75
+ output = self._runner.run(["du", "-sb", "--", str(path)], elevate=elevate)
76
+ return int(output.split()[0])
77
+ except (CommandFailedError, ValueError, IndexError):
78
+ continue
79
+ return None
80
+
81
+ def child_sizes(self, parent: Path) -> list[PathSize]:
82
+ """
83
+ Recursive sizes of every direct child of ``parent``, biggest first.
84
+ """
85
+ sizes: list[PathSize] = []
86
+ for child in self._children(parent):
87
+ size = self.dir_size(child)
88
+ if size is not None:
89
+ sizes.append(PathSize(path=child, size_bytes=size))
90
+ return sorted(sizes, key=lambda entry: entry.size_bytes, reverse=True)
91
+
92
+ def truncate(self, path: Path) -> None:
93
+ """
94
+ Truncate a file to zero bytes in place.
95
+
96
+ In place matters: deleting a file another process holds open does
97
+ not reclaim its space, truncating it does.
98
+ """
99
+ try:
100
+ with path.open("r+b") as handle:
101
+ handle.truncate(0)
102
+ return
103
+ except OSError:
104
+ pass
105
+ if not self._elevate:
106
+ raise PermissionError(f"Cannot truncate {path} (elevation disabled)")
107
+ self._runner.run(["truncate", "-s", "0", str(path)], elevate=True)
108
+
109
+ def _children(self, parent: Path) -> list[Path]:
110
+ """
111
+ Direct children of ``parent``, via elevated find if listing is denied.
112
+ """
113
+ try:
114
+ return sorted(parent.iterdir())
115
+ except OSError:
116
+ pass
117
+ if not self._elevate:
118
+ return []
119
+ try:
120
+ output = self._runner.run(["find", str(parent), "-mindepth", "1", "-maxdepth", "1"], elevate=True)
121
+ except CommandFailedError:
122
+ return []
123
+ return sorted(Path(line) for line in output.splitlines() if line.strip())
@@ -0,0 +1,22 @@
1
+ """
2
+ HTML parsing and crawling helpers.
3
+ """
4
+
5
+ from corekit.html.client import WebscrapeClient
6
+ from corekit.html.models import LinkItem, Page, PageMetadata
7
+ from corekit.html.parser import HtmlParser
8
+ from corekit.html.scraper import Scraper
9
+ from corekit.html.settings import CleanSettings, LinkFilterSettings
10
+ from corekit.html.state import ScraperState
11
+
12
+ __all__ = [
13
+ "CleanSettings",
14
+ "HtmlParser",
15
+ "LinkFilterSettings",
16
+ "LinkItem",
17
+ "Page",
18
+ "PageMetadata",
19
+ "Scraper",
20
+ "ScraperState",
21
+ "WebscrapeClient",
22
+ ]
corekit/html/client.py ADDED
@@ -0,0 +1,22 @@
1
+ from typing import Any
2
+
3
+ from corekit.http import BaseHttpClient
4
+
5
+
6
+ class WebscrapeClient(BaseHttpClient):
7
+ """
8
+ HTTP client with browser-like default headers for scraping.
9
+
10
+ Inherits GET-only ``supported_methods`` from ``BaseHttpClient``.
11
+ """
12
+
13
+ def __init__(self, **kwargs: Any) -> None:
14
+ kwargs.setdefault("strict", False)
15
+ super().__init__(**kwargs)
16
+
17
+ @property
18
+ def headers(self) -> dict[str, str]:
19
+ return {
20
+ "Accept": "text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8",
21
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:156.0) Gecko/20100101 Firefox/156.0",
22
+ }