awstorage 0.1.0__tar.gz

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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.4
2
+ Name: awstorage
3
+ Version: 0.1.0
4
+ Summary: Scan a drive, get a ranked inventory of what fills it, classified re-fetchable or not, diffed against last time -- before you delete anything.
5
+ License: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/Aitherium/awstorage
7
+ Project-URL: Repository, https://github.com/Aitherium/awstorage.git
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: recover
12
+ Requires-Dist: awrecover>=0.1.0; extra == "recover"
13
+ Provides-Extra: yaml
14
+ Requires-Dist: pyyaml>=6.0; extra == "yaml"
15
+ Provides-Extra: dev
16
+ Requires-Dist: pytest>=7.0; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # awstorage
20
+
21
+ **Every drive on every node, indexed, classified and diffed -- so you can see what you own before you delete it.**
22
+
23
+ ```bash
24
+ pip install git+https://github.com/Aitherium/awstorage.git
25
+ awstorage scan E:/ --depth 3 --catalog inventory.db
26
+ awstorage inventory --catalog inventory.db
27
+ awstorage propose --catalog inventory.db --snapshot 1
28
+ awstorage apply --catalog inventory.db --proposal 3 --root E:/ # dry run
29
+ awstorage apply --catalog inventory.db --proposal 3 --root E:/ --yes # quarantine it
30
+ awstorage revert E:/.awstorage-quarantine/3-20260901T230000 # changed your mind
31
+ ```
32
+
33
+ Stdlib only. Works alone, offline, on the box whose disk is full.
34
+
35
+ ## What it does
36
+
37
+ 1. **Scan** a root into a *snapshot*: every directory tree to a bounded depth with
38
+ its bytes, file count and newest mtime, plus the largest files. Bounded by a time
39
+ budget; a scan that runs out marks the snapshot `TRUNCATED` instead of printing a
40
+ total that looks complete and is not.
41
+ 2. **Classify** each tree: `package-cache`, `build-temp`, `model-weights`,
42
+ `container-store`, `dataset`, `backup`, `repo`, `logs`, `service-state`, `media`,
43
+ `vm-disk`, `unknown` -- and whether it is **re-fetchable**. Heuristics offline;
44
+ plug any `complete(prompt) -> str` model callable into `LLMClassifier` and every
45
+ verdict records whether a rule or a model made it, so a wrong call is auditable.
46
+ 3. **Catalog** snapshots in SQLite and **diff** them: what appeared, vanished, grew
47
+ and shrank since last time. "What filled the disk?" becomes a query.
48
+ 4. **Propose** actions under a written policy. Rules pre-approve only re-fetchable
49
+ classes past a size and an age; `service-state`, `dataset`, `vm-disk`, `backup` and
50
+ `unknown` are never auto. Everything else is proposed for a human to approve.
51
+ 5. **Apply** -- dry run by default. A delete is a **quarantine**: the tree is renamed
52
+ onto the same volume under `<root>/.awstorage-quarantine/`, `revert` puts it back
53
+ byte-for-byte, and only `quarantine --purge-older-than N --yes` reclaims the bytes.
54
+ `apply` refuses anything outside the declared roots, anything that changed since the
55
+ scan, and anything neither pre-approved nor approved. Every outcome is ledgered.
56
+
57
+ ## Python
58
+
59
+ ```python
60
+ import awstorage
61
+ from pathlib import Path
62
+
63
+ snap = awstorage.classify_snapshot(awstorage.scan(Path("E:/"), max_depth=3))
64
+ cat = awstorage.Catalog("inventory.db")
65
+ sid = cat.put_snapshot(snap)
66
+ for row in awstorage.rank(snap)[:10]:
67
+ print(row["exclusive_bytes"], row["cls"], row["refetchable"], row["path"])
68
+ props = awstorage.propose(snap, awstorage.default_policy(), snapshot_id=sid)
69
+ awstorage.apply(props[0], roots=[Path("E:/")], dry_run=True)
70
+ ```
71
+
72
+ ## The three rules
73
+
74
+ - **Measure before you delete.** A `du` answers one question once.
75
+ - **Re-fetchable is a property, not a guess.** The classifier says why.
76
+ - **Deleting is a policy, not a mood.** Dry run, roots, fingerprints, quarantine, ledger.
77
+
78
+ ## Composes with
79
+
80
+ - **awrecover** -- `backup_hook=lambda p: awrecover.snapshot(p, store, label)` turns
81
+ `backup-then-delete` into a restorable snapshot first.
82
+ - **awdk / awnode / awsh** -- run the scanner where the disk is, post snapshots to a
83
+ shared catalog, render proposals in a shell or a desktop panel.
84
+ - **awgraph** -- `awstorage graph` emits nodes and typed edges (`contains`,
85
+ `duplicate_of`) any graph store can ingest.
86
+
87
+ `awstorage --self-test` proves the refusals still refuse and the quarantine still reverts.
88
+
89
+ Apache-2.0.
@@ -0,0 +1,71 @@
1
+ # awstorage
2
+
3
+ **Every drive on every node, indexed, classified and diffed -- so you can see what you own before you delete it.**
4
+
5
+ ```bash
6
+ pip install git+https://github.com/Aitherium/awstorage.git
7
+ awstorage scan E:/ --depth 3 --catalog inventory.db
8
+ awstorage inventory --catalog inventory.db
9
+ awstorage propose --catalog inventory.db --snapshot 1
10
+ awstorage apply --catalog inventory.db --proposal 3 --root E:/ # dry run
11
+ awstorage apply --catalog inventory.db --proposal 3 --root E:/ --yes # quarantine it
12
+ awstorage revert E:/.awstorage-quarantine/3-20260901T230000 # changed your mind
13
+ ```
14
+
15
+ Stdlib only. Works alone, offline, on the box whose disk is full.
16
+
17
+ ## What it does
18
+
19
+ 1. **Scan** a root into a *snapshot*: every directory tree to a bounded depth with
20
+ its bytes, file count and newest mtime, plus the largest files. Bounded by a time
21
+ budget; a scan that runs out marks the snapshot `TRUNCATED` instead of printing a
22
+ total that looks complete and is not.
23
+ 2. **Classify** each tree: `package-cache`, `build-temp`, `model-weights`,
24
+ `container-store`, `dataset`, `backup`, `repo`, `logs`, `service-state`, `media`,
25
+ `vm-disk`, `unknown` -- and whether it is **re-fetchable**. Heuristics offline;
26
+ plug any `complete(prompt) -> str` model callable into `LLMClassifier` and every
27
+ verdict records whether a rule or a model made it, so a wrong call is auditable.
28
+ 3. **Catalog** snapshots in SQLite and **diff** them: what appeared, vanished, grew
29
+ and shrank since last time. "What filled the disk?" becomes a query.
30
+ 4. **Propose** actions under a written policy. Rules pre-approve only re-fetchable
31
+ classes past a size and an age; `service-state`, `dataset`, `vm-disk`, `backup` and
32
+ `unknown` are never auto. Everything else is proposed for a human to approve.
33
+ 5. **Apply** -- dry run by default. A delete is a **quarantine**: the tree is renamed
34
+ onto the same volume under `<root>/.awstorage-quarantine/`, `revert` puts it back
35
+ byte-for-byte, and only `quarantine --purge-older-than N --yes` reclaims the bytes.
36
+ `apply` refuses anything outside the declared roots, anything that changed since the
37
+ scan, and anything neither pre-approved nor approved. Every outcome is ledgered.
38
+
39
+ ## Python
40
+
41
+ ```python
42
+ import awstorage
43
+ from pathlib import Path
44
+
45
+ snap = awstorage.classify_snapshot(awstorage.scan(Path("E:/"), max_depth=3))
46
+ cat = awstorage.Catalog("inventory.db")
47
+ sid = cat.put_snapshot(snap)
48
+ for row in awstorage.rank(snap)[:10]:
49
+ print(row["exclusive_bytes"], row["cls"], row["refetchable"], row["path"])
50
+ props = awstorage.propose(snap, awstorage.default_policy(), snapshot_id=sid)
51
+ awstorage.apply(props[0], roots=[Path("E:/")], dry_run=True)
52
+ ```
53
+
54
+ ## The three rules
55
+
56
+ - **Measure before you delete.** A `du` answers one question once.
57
+ - **Re-fetchable is a property, not a guess.** The classifier says why.
58
+ - **Deleting is a policy, not a mood.** Dry run, roots, fingerprints, quarantine, ledger.
59
+
60
+ ## Composes with
61
+
62
+ - **awrecover** -- `backup_hook=lambda p: awrecover.snapshot(p, store, label)` turns
63
+ `backup-then-delete` into a restorable snapshot first.
64
+ - **awdk / awnode / awsh** -- run the scanner where the disk is, post snapshots to a
65
+ shared catalog, render proposals in a shell or a desktop panel.
66
+ - **awgraph** -- `awstorage graph` emits nodes and typed edges (`contains`,
67
+ `duplicate_of`) any graph store can ingest.
68
+
69
+ `awstorage --self-test` proves the refusals still refuse and the quarantine still reverts.
70
+
71
+ Apache-2.0.
@@ -0,0 +1,97 @@
1
+ """awstorage -- every drive on every node, indexed, classified and diffed.
2
+
3
+ Scan a root, get a SNAPSHOT: every directory tree down to a bounded depth with
4
+ its bytes, file count and newest mtime, plus the largest files. Classify each
5
+ tree (cache / build-temp / model-weights / dataset / backup / repo / logs /
6
+ service-state / media / unknown) and mark whether it is RE-FETCHABLE. Store
7
+ snapshots in a catalog and DIFF them, so "what grew since last week" is a
8
+ query rather than a memory. Turn the classification into PROPOSALS under a
9
+ written policy, and APPLY only what the policy pre-approves or a human
10
+ approved -- dry-run by default, ledgered, and never outside a declared root.
11
+
12
+ import awstorage
13
+ from pathlib import Path
14
+
15
+ snap = awstorage.scan(Path("E:/"), max_depth=3, time_budget_s=120)
16
+ awstorage.classify_snapshot(snap) # heuristics, offline
17
+ cat = awstorage.Catalog(Path("inventory.db"))
18
+ sid = cat.put_snapshot(snap)
19
+ for row in awstorage.rank(snap)[:20]:
20
+ print(row["bytes"], row["path"], row["cls"], row["refetchable"])
21
+ props = awstorage.propose(snap, awstorage.default_policy())
22
+ awstorage.apply(props[0], roots=[Path("E:/")], dry_run=True)
23
+
24
+ Three rules it exists to enforce:
25
+
26
+ **Measure before you delete.** A `du` answers one question once. A snapshot
27
+ answers the same question every week, and the diff between two is the
28
+ question you actually had ("what filled the disk?").
29
+
30
+ **Re-fetchable is a property, not a guess.** A tree is re-fetchable when a
31
+ known producer can recreate it (a package cache, a build output, a model
32
+ weight that lives on a mirror). The classifier records WHY it decided that,
33
+ and whether a heuristic or a model decided -- so a wrong call is auditable.
34
+
35
+ **Deleting is a policy, not a mood.** `apply` refuses anything outside the
36
+ declared roots, anything whose fingerprint changed since the scan, and any
37
+ class the policy does not pre-approve unless a human approved that proposal.
38
+ It writes a ledger row either way. A dry run is the default.
39
+
40
+ The package is stdlib-only and speaks to nothing. Fleet integration (a scanner
41
+ per node, a catalog behind an API, a GUI, an autonomous steward, model-backed
42
+ classification) lives in the platform that imports it -- awstorage works alone.
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ from ._fs import SCHEMA_VERSION, ScanError, scan
48
+ from .catalog import Catalog
49
+ from .classify import (
50
+ CLASSES,
51
+ Classifier,
52
+ HeuristicClassifier,
53
+ LLMClassifier,
54
+ classify_snapshot,
55
+ classify_tree,
56
+ )
57
+ from .diff import diff_snapshots
58
+ from .graph import to_graph
59
+ from .policy import (
60
+ ApplyRefused,
61
+ Proposal,
62
+ apply,
63
+ default_policy,
64
+ list_quarantine,
65
+ propose,
66
+ purge_quarantine,
67
+ revert,
68
+ )
69
+ from .report import rank, summarize
70
+
71
+ __version__ = "0.1.0"
72
+
73
+ __all__ = [
74
+ "SCHEMA_VERSION",
75
+ "ScanError",
76
+ "scan",
77
+ "Catalog",
78
+ "CLASSES",
79
+ "Classifier",
80
+ "HeuristicClassifier",
81
+ "LLMClassifier",
82
+ "classify_snapshot",
83
+ "classify_tree",
84
+ "diff_snapshots",
85
+ "to_graph",
86
+ "ApplyRefused",
87
+ "Proposal",
88
+ "apply",
89
+ "default_policy",
90
+ "list_quarantine",
91
+ "propose",
92
+ "purge_quarantine",
93
+ "revert",
94
+ "rank",
95
+ "summarize",
96
+ "__version__",
97
+ ]
@@ -0,0 +1,222 @@
1
+ """Bounded, resumable directory scanning -> a snapshot dict.
2
+
3
+ A snapshot is a plain dict (JSON-serialisable) so it can cross any wire:
4
+
5
+ {"schema": 1, "node": "<hostname>", "root": "E:/", "taken_at": "...",
6
+ "max_depth": 3, "time_budget_s": 120, "truncated": false,
7
+ "trees": [ {"path": "E:/Caches", "depth": 1, "bytes": 157_000_000_000,
8
+ "files": 12000, "dirs": 340, "newest_mtime": 1756000000.0,
9
+ "oldest_mtime": 1700000000.0, "fingerprint": "sha1:..."} ],
10
+ "top_files": [ {"path": ..., "bytes": ..., "mtime": ...} ],
11
+ "errors": ["E:/System Volume Information: PermissionError"],
12
+ "elapsed_s": 41.2}
13
+
14
+ `trees` holds every directory at depth <= max_depth (depth 0 is the root),
15
+ each with the AGGREGATE of everything beneath it -- so a parent's bytes
16
+ already include its children's. Consumers that want exclusive sizes subtract.
17
+
18
+ The fingerprint is sha1 over (bytes, files, newest_mtime): cheap, and enough
19
+ to notice that a tree changed between the scan and an apply. It is NOT a
20
+ content hash; awstorage never reads file contents.
21
+
22
+ Bounded on purpose: a scan that runs forever on a 4 TB drive is one nobody
23
+ runs twice. `time_budget_s` stops the walk and marks the snapshot TRUNCATED
24
+ (a real field, printed by every consumer) rather than returning a total that
25
+ looks complete and is not.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import hashlib
31
+ import os
32
+ import socket
33
+ import time
34
+ from datetime import datetime, timezone
35
+ from pathlib import Path
36
+ from typing import Iterable
37
+
38
+ SCHEMA_VERSION = 1
39
+
40
+ # Directories that are never worth descending into: either they lie about size
41
+ # (reparse/junction targets, /proc) or they are the OS's own business.
42
+ DEFAULT_SKIP_NAMES = frozenset(
43
+ {
44
+ "$recycle.bin",
45
+ "system volume information",
46
+ "proc",
47
+ "sys",
48
+ "dev",
49
+ "run",
50
+ }
51
+ )
52
+
53
+
54
+ class ScanError(Exception):
55
+ """The scan could not run at all (root missing, unreadable, not a dir)."""
56
+
57
+
58
+ def _now_iso() -> str:
59
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
60
+
61
+
62
+ def _norm(p: Path) -> str:
63
+ # Forward slashes everywhere so the same tree has ONE spelling in the
64
+ # catalog whether it was scanned from Windows, WSL, or a Linux node.
65
+ return str(p).replace("\\", "/")
66
+
67
+
68
+ def fingerprint(bytes_: int, files: int, newest_mtime: float) -> str:
69
+ h = hashlib.sha1(f"{bytes_}|{files}|{int(newest_mtime)}".encode())
70
+ return "sha1:" + h.hexdigest()[:16]
71
+
72
+
73
+ def scan(
74
+ root: Path | str,
75
+ *,
76
+ max_depth: int = 3,
77
+ time_budget_s: float = 300.0,
78
+ top_files: int = 50,
79
+ skip_names: Iterable[str] = DEFAULT_SKIP_NAMES,
80
+ node: str | None = None,
81
+ follow_symlinks: bool = False,
82
+ ) -> dict:
83
+ """Walk `root` and return a snapshot dict. Never raises past the root check.
84
+
85
+ Per-entry errors (permission denied, vanished file) are recorded in
86
+ `errors` and the walk continues; only an unusable ROOT raises ScanError.
87
+ """
88
+ root_p = Path(root)
89
+ if not root_p.exists():
90
+ raise ScanError(f"root does not exist: {root}")
91
+ if not root_p.is_dir():
92
+ raise ScanError(f"root is not a directory: {root}")
93
+ skip = {s.lower() for s in skip_names}
94
+ t0 = time.monotonic()
95
+ deadline = t0 + float(time_budget_s)
96
+
97
+ # Aggregates keyed by the directory path (string), for dirs at depth <= max_depth.
98
+ agg: dict[str, dict] = {}
99
+ errors: list[str] = []
100
+ biggest: list[tuple[int, float, str]] = [] # (bytes, mtime, path) kept small
101
+ truncated = False
102
+
103
+ def account(dir_key: str, size: int, mtime: float, is_file: bool) -> None:
104
+ a = agg[dir_key]
105
+ a["bytes"] += size
106
+ if is_file:
107
+ a["files"] += 1
108
+ else:
109
+ a["dirs"] += 1
110
+ if mtime > a["newest_mtime"]:
111
+ a["newest_mtime"] = mtime
112
+ if mtime and (a["oldest_mtime"] == 0.0 or mtime < a["oldest_mtime"]):
113
+ a["oldest_mtime"] = mtime
114
+
115
+ def ensure(path_str: str, depth: int) -> None:
116
+ if path_str not in agg:
117
+ agg[path_str] = {
118
+ "path": path_str,
119
+ "depth": depth,
120
+ "bytes": 0,
121
+ "files": 0,
122
+ "dirs": 0,
123
+ "newest_mtime": 0.0,
124
+ "oldest_mtime": 0.0,
125
+ "git": False,
126
+ }
127
+
128
+ root_key = _norm(root_p)
129
+ ensure(root_key, 0)
130
+ # Stack of (dir path, depth, ancestors-at-or-below-max-depth keys)
131
+ stack: list[tuple[str, int, tuple[str, ...]]] = [(str(root_p), 0, (root_key,))]
132
+
133
+ while stack:
134
+ if time.monotonic() >= deadline:
135
+ truncated = True
136
+ break
137
+ d, depth, owners = stack.pop()
138
+ try:
139
+ it = os.scandir(d)
140
+ except OSError as exc:
141
+ errors.append(f"{_norm(Path(d))}: {type(exc).__name__}")
142
+ continue
143
+ with it:
144
+ for e in it:
145
+ try:
146
+ if e.is_symlink() and not follow_symlinks:
147
+ continue
148
+ if e.is_dir(follow_symlinks=follow_symlinks):
149
+ if e.name == ".git" and owners[-1] in agg:
150
+ # A git working tree: its build outputs may be TRACKED
151
+ # (tenant repos `git add -f` their dist/), so the policy
152
+ # must not auto-delete inside one. Recorded, not decided.
153
+ agg[owners[-1]]["git"] = True
154
+ if e.name.lower() in skip:
155
+ continue
156
+ child_depth = depth + 1
157
+ child_key = _norm(Path(e.path))
158
+ for k in owners:
159
+ account(k, 0, 0.0, is_file=False)
160
+ if child_depth <= max_depth:
161
+ ensure(child_key, child_depth)
162
+ stack.append((e.path, child_depth, owners + (child_key,)))
163
+ else:
164
+ stack.append((e.path, child_depth, owners))
165
+ else:
166
+ st = e.stat(follow_symlinks=follow_symlinks)
167
+ size = int(st.st_size)
168
+ mtime = float(st.st_mtime)
169
+ for k in owners:
170
+ account(k, size, mtime, is_file=True)
171
+ if top_files > 0:
172
+ biggest.append((size, mtime, _norm(Path(e.path))))
173
+ if len(biggest) > top_files * 4:
174
+ biggest.sort(reverse=True)
175
+ del biggest[top_files:]
176
+ except OSError as exc:
177
+ errors.append(f"{_norm(Path(e.path))}: {type(exc).__name__}")
178
+
179
+ biggest.sort(reverse=True)
180
+ trees = []
181
+ for a in sorted(agg.values(), key=lambda x: (x["depth"], x["path"])):
182
+ a = dict(a)
183
+ a["fingerprint"] = fingerprint(a["bytes"], a["files"], a["newest_mtime"])
184
+ trees.append(a)
185
+
186
+ return {
187
+ "schema": SCHEMA_VERSION,
188
+ "node": node or socket.gethostname(),
189
+ "root": root_key,
190
+ "taken_at": _now_iso(),
191
+ "max_depth": int(max_depth),
192
+ "time_budget_s": float(time_budget_s),
193
+ "truncated": truncated,
194
+ "trees": trees,
195
+ "top_files": [
196
+ {"path": p, "bytes": b, "mtime": m} for b, m, p in biggest[:top_files]
197
+ ],
198
+ "errors": errors[:200],
199
+ "error_count": len(errors),
200
+ "elapsed_s": round(time.monotonic() - t0, 2),
201
+ }
202
+
203
+
204
+ def exclusive_bytes(snapshot: dict) -> dict[str, int]:
205
+ """Bytes owned by each tree EXCLUDING its scanned children (depth-aware)."""
206
+ by_depth: dict[int, list[dict]] = {}
207
+ for t in snapshot["trees"]:
208
+ by_depth.setdefault(t["depth"], []).append(t)
209
+ children: dict[str, int] = {}
210
+ for depth, trees in by_depth.items():
211
+ if depth == 0:
212
+ continue
213
+ parents = by_depth.get(depth - 1, [])
214
+ for t in trees:
215
+ # The parent is the depth-1 tree whose path is the longest prefix of ours.
216
+ cand = [p["path"] for p in parents
217
+ if t["path"].startswith(p["path"].rstrip("/") + "/")]
218
+ if cand:
219
+ parent = max(cand, key=len)
220
+ children[parent] = children.get(parent, 0) + t["bytes"]
221
+ return {t["path"]: max(0, t["bytes"] - children.get(t["path"], 0))
222
+ for t in snapshot["trees"]}