junk-cleaner 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,148 @@
1
+ # ***************************************************************************
2
+ # junk-cleaner — detect junk and temporary files by name, and remove directory
3
+ # trees that contain nothing else
4
+ #
5
+ # The package root: the documentation of the package, its version and its
6
+ # public interface.
7
+ #
8
+ # Authors: Chris Morrison
9
+ #
10
+ # Copyright (C) 2026 Xanagobe Development Operations
11
+ #
12
+ # This program is free software: you can redistribute it and/or modify
13
+ # it under the terms of the GNU General Public License as published by
14
+ # the Free Software Foundation, either version 3 of the License, or
15
+ # (at your option) any later version.
16
+ #
17
+ # This program is distributed in the hope that it will be useful,
18
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20
+ # GNU General Public License for more details.
21
+ #
22
+ # You should have received a copy of the GNU General Public License
23
+ # along with this program. If not, see https://www.gnu.org/licenses/.
24
+ # ***************************************************************************
25
+
26
+ """junk-cleaner: detect junk files by name and remove directories holding nothing else.
27
+
28
+ The decision rests on one canonical, reviewed data source of junk
29
+ extensions, exact file names, exact directory names and name patterns,
30
+ shared with the Rust crate ``jetsam``. Every rule says whether a match is
31
+ *safe* to delete; a name that matches an unsafe rule is never junk.
32
+
33
+ Questions about names (no file system involved)::
34
+
35
+ >>> from junk_cleaner import classify_name, classify_directory_name, is_junk_name
36
+ >>> is_junk_name("report.TEMP")
37
+ True
38
+ >>> is_junk_name("~WRD0001.tmp") # After a crash, the only copy of a document.
39
+ False
40
+ >>> classify_name("Cargo.lock").verdict.value
41
+ 'unsafe'
42
+ >>> classify_directory_name("@eaDir").verdict.value
43
+ 'describer'
44
+
45
+ Questions about files on disk: :func:`is_junk_file` (a yes or no) and
46
+ :func:`classify` (the verdict and the rule, with errors for paths that do not
47
+ exist or are not regular files). Only regular files are ever junk; symbolic
48
+ links are never followed; a companion such as ``._photo.jpg`` is junk only
49
+ once the file it accompanies is gone or is junk itself, and a describer such
50
+ as ``.DS_Store`` only once nothing it describes is left beside it.
51
+
52
+ Removal: :func:`remove_empty_dir` removes a directory (or, with
53
+ ``recursive``, a tree) that holds nothing but junk, and :func:`check_removable`
54
+ reports what it would remove. Nothing that is not junk is ever removed.
55
+
56
+ The rules themselves: :func:`extensions`, :func:`filenames`,
57
+ :func:`directories`, :func:`patterns`, :func:`find_extension`,
58
+ :func:`find_filename` and :func:`find_directory`.
59
+
60
+ Every exception derives from :class:`JunkCleanerError`.
61
+ """
62
+
63
+ # The rules of the canonical data.
64
+ from ._data import (
65
+ Category,
66
+ Rule,
67
+ RuleKind,
68
+ directories,
69
+ extensions,
70
+ filenames,
71
+ find_directory,
72
+ find_extension,
73
+ find_filename,
74
+ patterns,
75
+ )
76
+
77
+ # The classification of names and files.
78
+ from ._is_junk import (
79
+ FileKind,
80
+ NameVerdict,
81
+ Verdict,
82
+ classify,
83
+ classify_directory_name,
84
+ classify_name,
85
+ is_junk_file,
86
+ is_junk_name,
87
+ )
88
+
89
+ # The removal of directory trees.
90
+ from ._remove_empty import RemoveOutcome, check_removable, remove_empty_dir
91
+
92
+ # The exceptions, all derived from JunkCleanerError.
93
+ from .exceptions import (
94
+ ContainsNonJunkError,
95
+ DataError,
96
+ IncompleteRemovalError,
97
+ JunkCleanerError,
98
+ JunkCleanerIOError,
99
+ NonJunkReason,
100
+ NotAFileError,
101
+ PathNotFoundError,
102
+ )
103
+ from .exceptions import (
104
+ # The brief's name; it also subclasses the built-in, and is left out of
105
+ # __all__ so that "from junk_cleaner import *" never hides the built-in.
106
+ NotADirectoryError as NotADirectoryError,
107
+ )
108
+
109
+ #: The version of the package, the same as the Rust crate's (sync-data checks).
110
+ __version__ = "0.3.0"
111
+
112
+ #: The public interface; everything else is private and may change.
113
+ #: NotADirectoryError is public too, imported by name; it is not listed here
114
+ #: because a star import would then replace the built-in NotADirectoryError
115
+ #: in the importing module, and its ``except NotADirectoryError`` would no
116
+ #: longer catch the built-in that os, pathlib and open raise.
117
+ __all__ = [
118
+ "Category",
119
+ "ContainsNonJunkError",
120
+ "DataError",
121
+ "FileKind",
122
+ "IncompleteRemovalError",
123
+ "JunkCleanerError",
124
+ "JunkCleanerIOError",
125
+ "NameVerdict",
126
+ "NonJunkReason",
127
+ "NotAFileError",
128
+ "PathNotFoundError",
129
+ "RemoveOutcome",
130
+ "Rule",
131
+ "RuleKind",
132
+ "Verdict",
133
+ "__version__",
134
+ "check_removable",
135
+ "classify",
136
+ "classify_directory_name",
137
+ "classify_name",
138
+ "directories",
139
+ "extensions",
140
+ "filenames",
141
+ "find_directory",
142
+ "find_extension",
143
+ "find_filename",
144
+ "is_junk_file",
145
+ "is_junk_name",
146
+ "patterns",
147
+ "remove_empty_dir",
148
+ ]
@@ -0,0 +1,329 @@
1
+ # ***************************************************************************
2
+ # junk-cleaner — detect junk and temporary files by name, and remove directory
3
+ # trees that contain nothing else
4
+ #
5
+ # The file-system operations that the removal algorithm needs, as a protocol,
6
+ # and the metadata it reads: the counterpart of src/remove_empty/backend.rs.
7
+ #
8
+ # Authors: Chris Morrison
9
+ #
10
+ # Copyright (C) 2026 Xanagobe Development Operations
11
+ #
12
+ # This program is free software: you can redistribute it and/or modify
13
+ # it under the terms of the GNU General Public License as published by
14
+ # the Free Software Foundation, either version 3 of the License, or
15
+ # (at your option) any later version.
16
+ #
17
+ # This program is distributed in the hope that it will be useful,
18
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20
+ # GNU General Public License for more details.
21
+ #
22
+ # You should have received a copy of the GNU General Public License
23
+ # along with this program. If not, see https://www.gnu.org/licenses/.
24
+ # ***************************************************************************
25
+
26
+ """The file-system operations of the removal algorithm.
27
+
28
+ The algorithm in :mod:`junk_cleaner._remove_empty` is written once against
29
+ :class:`Backend`. Three backends implement it: two work through open
30
+ directory handles, one for POSIX systems (``FdBackend``, the ``dir_fd``
31
+ functions) and one for Windows (``WindowsBackend`` in
32
+ :mod:`junk_cleaner._windows`, names opened relative to a handle, never
33
+ following a reparse point); the third works through paths
34
+ (``PathBackend``, the tests' second backend everywhere, and the backend of
35
+ any other platform). The tests add a fourth that injects failures and races.
36
+
37
+ They live in a module of their own so that the Windows backend, which needs
38
+ :class:`Meta`, and the algorithm, which needs the Windows backend, do not
39
+ import each other. So do the two errors by which a backend tells the
40
+ algorithm *why* it refuses (:class:`HeldOpenError` and
41
+ :class:`NamedStreamsError`), and the one message that both the algorithm
42
+ and the Windows backend give (:data:`MOVED`), so that each refusal reads
43
+ the same whichever of them notices it, and the same as in the Rust crate.
44
+ """
45
+
46
+ from __future__ import annotations
47
+
48
+ from dataclasses import dataclass
49
+ from typing import Final, Protocol, TypeVar
50
+
51
+ from ._is_junk import FileKind
52
+
53
+ #: The message of a directory, or an entry, that has left the place where
54
+ #: the removal found it, or that something else has taken the place of:
55
+ #: whatever is done next would be done to something that is no longer (or
56
+ #: never was) the thing that was judged, so the removal stops. The same
57
+ #: words as the Rust crate's.
58
+ MOVED: Final = "it was moved or replaced while it was being removed"
59
+
60
+ # --- The reasons of the refusals ----------------------------------------------------
61
+ #
62
+ # Each is the whole reason that a refusal gives, in the same words as the
63
+ # Rust crate's (src/remove_empty/backend.rs), so that the two libraries say
64
+ # the same thing about the same entry; beside each, the errno with which the
65
+ # walk reports it (the Rust crate's ErrorKind in the comment).
66
+
67
+ #: The system denies the deletion: an access control list (macOS, Windows),
68
+ #: or a folder's ``FILE_DELETE_CHILD`` withheld. ``EACCES``
69
+ #: (``PermissionDenied``).
70
+ DENIED: Final = "the system denies its deletion (an access control list, for example)"
71
+ #: A flag forbids the change: a read-only file or folder of Windows, or the
72
+ #: immutable or append-only flags of macOS. ``EACCES`` (``PermissionDenied``).
73
+ READ_ONLY: Final = "it is marked read-only, immutable or append-only"
74
+ #: Another program holds the entry open in a way that the removal's own
75
+ #: open cannot share: with the right to delete it, or without sharing its
76
+ #: deletion (the deletion's open), or without sharing its reading (the
77
+ #: open that holds a folder to list it). A console holds its current
78
+ #: folder without sharing its deletion. ``EBUSY`` (``ResourceBusy``).
79
+ IN_USE: Final = (
80
+ "another program holds it open in a way that the removal cannot share "
81
+ "(a console's current folder, for example)"
82
+ )
83
+ #: Another program holds the entry with an opportunistic lock (or the lease
84
+ #: of a network client) that the deletion had to break, and did not let go
85
+ #: of it within the bound the removal waits for (about a tenth of a
86
+ #: second): the wait was cancelled, and the system confirmed that the entry
87
+ #: was not marked for deletion. ``EBUSY`` (``ResourceBusy``).
88
+ WAITED: Final = (
89
+ "another program holds it open and did not let go of it when asked (an opportunistic lock)"
90
+ )
91
+ #: The system did not answer a request to delete the entry (or to mark it,
92
+ #: in the check) within a second, and its wait could not be cancelled: the
93
+ #: request may yet take effect. A mark of the check that takes effect so is
94
+ #: cleared by the thread that was left with it, before it closes the check's
95
+ #: handle; only if the process ended first would the entry go.
96
+ #: ``ETIMEDOUT`` (``TimedOut``).
97
+ UNANSWERED: Final = (
98
+ "the system did not answer the request to delete it, and its wait could not be "
99
+ "cancelled: it may yet be deleted"
100
+ )
101
+ #: On a volume where a deletion takes effect only once every handle to the
102
+ #: entry has closed (FAT, exFAT, a network share), another program holds the
103
+ #: entry open: deleted, it would stay, marked, until that program closed it,
104
+ #: and its folder could not be removed meanwhile. ``EBUSY``
105
+ #: (``ResourceBusy``).
106
+ LINGERING: Final = (
107
+ "another program holds it open, and on this volume it would stay, marked for "
108
+ "deletion, until that program closed it"
109
+ )
110
+ #: Another program has marked the entry for deletion, and still holds it
111
+ #: open: its name stays, and its folder cannot go until that program closes
112
+ #: it. ``EBUSY`` (``ResourceBusy``) where the check refuses it; everywhere
113
+ #: else the entry has gone (see :class:`BeingDeletedError`).
114
+ BEING_DELETED: Final = "another program is deleting it and still holds it open"
115
+ #: A running program has the file loaded as an image (an executable or a
116
+ #: library that it runs), which Windows never lets anyone delete.
117
+ #: ``ETXTBSY`` (``ExecutableFileBusy``).
118
+ LOADED: Final = "a running program has it loaded"
119
+ #: The medium is write-protected. ``EROFS`` (``ReadOnlyFilesystem``).
120
+ WRITE_PROTECTED: Final = "it lies on a write-protected medium"
121
+ #: The network share denies the deletion. ``EACCES`` (``PermissionDenied``).
122
+ SHARE_DENIED: Final = "the network share denies its deletion (a read-only share, for example)"
123
+
124
+
125
+ class RefusalError(OSError):
126
+ """The system will refuse a deletion, for the reason that ``strerror`` gives.
127
+
128
+ Raised by :meth:`Backend.check_deletable` where the platform says why
129
+ (Windows: a denial, another program's handle, its opportunistic lock, a
130
+ mapped image, a write-protected medium, a read-only share, an entry that
131
+ would linger), with the ``errno`` beside each reason of this module, so
132
+ that the refusal predicted in phase 1 says why in the Rust crate's words.
133
+ The walk reports it with its ``errno`` and ``strerror`` as they are (the
134
+ Rust crate's ``Refusal``).
135
+ """
136
+
137
+ def __init__(self, number: int, reason: str, filename: str | None = None) -> None:
138
+ """The refusal of ``filename`` with the ``errno`` ``number``, for ``reason``."""
139
+ super().__init__(number, reason, filename)
140
+ self.number = number
141
+ """The ``errno`` of the refusal (never None, unlike ``OSError.errno``)."""
142
+ self.reason = reason
143
+ """Its reason (never None, unlike ``OSError.strerror``)."""
144
+
145
+
146
+ class HeldOpenError(RefusalError):
147
+ """The system will refuse a deletion, or a folder's pinning: another program holds the entry.
148
+
149
+ Raised by :meth:`Backend.check_deletable` (Windows: a sharing or a lock
150
+ violation on an open that asks for the right to delete), and by the
151
+ opening of a folder that a backend which pins its folders cannot pin,
152
+ because another program holds it with the right to delete it, or
153
+ without sharing its reading (see :meth:`Backend.pins_folders`). Its
154
+ ``errno`` is ``errno.EBUSY``: the entry is busy, not forbidden (the Rust
155
+ crate reports it as ``ErrorKind::ResourceBusy``), and its ``strerror``
156
+ is :data:`IN_USE`.
157
+ """
158
+
159
+
160
+ class BeingDeletedError(FileNotFoundError):
161
+ """Another program has marked the entry for deletion and still holds it open.
162
+
163
+ A :class:`FileNotFoundError`, so that every operation of the walk takes
164
+ the entry for one that has gone, and never counts it as removed by this
165
+ removal; but the check, which must foresee that its folder cannot go
166
+ while it stays, refuses it, with the reason :data:`BEING_DELETED`
167
+ (finding TP2 of the final review of the Windows engines; the Rust
168
+ crate's ``being_deleted``).
169
+ """
170
+
171
+
172
+ class NamedStreamsError(OSError):
173
+ """A directory about to be removed carries named data streams, so it is kept.
174
+
175
+ Raised by :meth:`Backend.rmdir_at` on Windows, where a folder (not only
176
+ a file) may carry named data streams (``folder:notes.txt``). They are
177
+ not entries, so the walk never sees them, and they may hold data that
178
+ is not junk; removing the folder would remove them with it. The walk
179
+ reports the folder as not junk
180
+ (:attr:`~junk_cleaner.exceptions.NonJunkReason.NAMED_STREAMS`).
181
+ """
182
+
183
+
184
+ @dataclass(frozen=True, slots=True)
185
+ class Meta:
186
+ """What the algorithm needs to know about an object, read without following links."""
187
+
188
+ kind: FileKind
189
+ """The kind of object."""
190
+ device: int | None
191
+ """The device (file system) that holds it, where the platform says: the
192
+ device number on POSIX, the volume serial number on Windows."""
193
+ inode: int | None
194
+ """Its identity on that device, where the platform says (the inode on POSIX,
195
+ the file identifier on Windows): a directory replaced between its status
196
+ and its opening shows up as another inode."""
197
+ mount: int | None
198
+ """The mount that holds it, where the platform says (the mount ID of Linux,
199
+ read from an open directory): a bind mount of the same file system has the
200
+ same device as its parent, but another mount."""
201
+ owner: int | None
202
+ """The user that owns it, where the platform has owners."""
203
+ sticky: bool
204
+ """Whether it is a directory with the sticky bit (as ``/tmp``)."""
205
+ immutable: bool
206
+ """Whether it is marked so that it cannot be removed: the macOS immutable or
207
+ append-only flags, or the read-only attribute of a Windows file or folder."""
208
+
209
+
210
+ #: The type of an open directory, which each backend chooses: a descriptor, a
211
+ #: handle, or a path with what is known about it.
212
+ D = TypeVar("D")
213
+
214
+
215
+ class Backend(Protocol[D]):
216
+ """The file-system operations of the algorithm; names are never followed."""
217
+
218
+ def pins_folders(self) -> bool:
219
+ r"""Whether every directory this backend holds open stays where it is while it is held.
220
+
221
+ True where no other program can rename, move or delete a directory
222
+ while the backend holds it: the Windows backend opens every folder
223
+ without sharing its deletion, and renaming or deleting a folder
224
+ needs an open that asks for exactly that. Windows enforces that
225
+ sharing against every program of the computer, and a Windows server
226
+ against every client of a share (verified through
227
+ ``\\localhost\C$``); a server that enforces the sharing of its own
228
+ clients only (Samba, against the programs of the server itself or
229
+ its NFS clients) pins nothing against those. The walk then looks at
230
+ no chain of directories (see :mod:`junk_cleaner._remove_empty`).
231
+ False for the descriptor backend (no open descriptor stops a
232
+ ``rename``) and the path backend, for which the walk looks at the
233
+ chain before every deletion, relisting and removal. As the Rust
234
+ crate's ``Backend::pins_folders``.
235
+ """
236
+
237
+ def open_dir(self, path: str) -> D:
238
+ """Open a directory by path, following links (for the parent only).
239
+
240
+ A backend that pins its folders raises :class:`HeldOpenError` where
241
+ another program holds the directory in a way that the pinning cannot
242
+ share (with the right to delete it, or without sharing its reading).
243
+ """
244
+
245
+ def open_dir_at(self, directory: D, name: str) -> D:
246
+ """Open the directory ``name`` within ``directory``; fail if it is not one.
247
+
248
+ A backend that pins its folders raises :class:`HeldOpenError` as
249
+ :meth:`open_dir` does.
250
+ """
251
+
252
+ def stat_at(self, directory: D, name: str) -> Meta:
253
+ """Read the metadata of ``name`` within ``directory``."""
254
+
255
+ def stat_dir(self, directory: D) -> Meta:
256
+ """Read the metadata of an open directory."""
257
+
258
+ def stat_path(self, path: str) -> Meta:
259
+ """Read the metadata of what ``path`` names, following links.
260
+
261
+ Only ever asked of a path of the parent of the target: its canonical
262
+ path, whose identity must be that of the parent the removal opened,
263
+ where the parent's own path cannot be read back (see
264
+ :meth:`path_of`), and, on a backend that does not pin its folders,
265
+ the path at which the parent was located, to make sure that it still
266
+ lies there (see :mod:`junk_cleaner._remove_empty`).
267
+ """
268
+
269
+ def path_of(self, directory: D) -> str | None:
270
+ """The path at which the open ``directory`` lies now, as the system reads it back.
271
+
272
+ Read from the open handle or descriptor itself, not by resolving a
273
+ path again, so that it names the very directory that was opened,
274
+ whatever a link on the way to it has become since. None where the
275
+ platform cannot say, never an error; the algorithm then falls back on
276
+ the canonical path, checked by identity, as the Rust crate's
277
+ ``dir_path`` does.
278
+ """
279
+
280
+ def named_streams(self, directory: D) -> bool:
281
+ """Whether the open ``directory`` itself carries named data streams.
282
+
283
+ Only Windows has them on folders; every other backend says False.
284
+ """
285
+
286
+ def list(self, directory: D) -> list[str]:
287
+ """List the names in ``directory``, without ``.`` and ``..``."""
288
+
289
+ def unlink_at(self, directory: D, name: str, expected: Meta | None = None) -> None:
290
+ """Remove the non-directory ``name`` within ``directory``.
291
+
292
+ ``expected`` is the status the algorithm judged: a backend that can
293
+ compare it with what it is about to delete, through the very handle
294
+ that deletes it, refuses another object (the Windows backend).
295
+ """
296
+
297
+ def rmdir_at(self, directory: D, name: str, expected: Meta | None = None) -> None:
298
+ """Remove the empty directory ``name`` within ``directory``.
299
+
300
+ A directory that is not empty must fail with ``errno.ENOTEMPTY`` (or
301
+ ``errno.EEXIST``, which some systems give), on which the walk lists
302
+ it again. ``expected`` is as for :meth:`unlink_at`. A directory that
303
+ carries named data streams fails with :class:`NamedStreamsError`.
304
+ The walk has given up its own handle on the directory first, which a
305
+ backend that pins its folders needs (see :meth:`pins_folders`).
306
+ """
307
+
308
+ def check_writable(self, directory: D) -> None:
309
+ """Raise if entries cannot be added to or removed from ``directory``."""
310
+
311
+ def check_deletable(self, directory: D, name: str) -> None:
312
+ """Raise if the system would refuse to delete ``name``.
313
+
314
+ Only where the platform can say beforehand, beyond what
315
+ :meth:`check_writable` and the flags tell: a
316
+ :class:`PermissionError` where the access control lists of macOS
317
+ deny the deletion of one entry, or of every entry of a directory; a
318
+ :class:`RefusalError` that says why where Windows refuses (a denial,
319
+ another program's handle, its opportunistic lock, a mapped image, a
320
+ write-protected medium, a read-only share, an entry that would
321
+ linger); a :class:`BeingDeletedError` for an entry that another
322
+ program is deleting. Never follows a symbolic link in ``name``.
323
+ """
324
+
325
+ def effective_uid(self) -> int | None:
326
+ """The effective user of this process, where the platform has users."""
327
+
328
+ def close(self, directory: D) -> None:
329
+ """Release an open directory."""