common.cleanups
Overview
common.cleanups contains filesystem cleanup functionality for removing unwanted files and directories from a target directory while retaining explicitly selected entries.
The module currently provides:
- the
SFTP_HISTORY_FILEconstant, - the
purge_directory()helper.
Dependencies
The module uses only Python standard library functionality:
osshutilpathlib.Path
Constants
SFTP_HISTORY_FILE
SFTP_HISTORY_FILE = "sftp_history.txt"
Filename constant for an SFTP history file.
The constant is defined in this module but is not referenced by purge_directory().
API Reference
common.cleanups.purge_directory(directory, retain: list)
Removes files and directories from directory unless their names are contained in retain.
Only the direct children of the supplied directory are inspected. Directories selected for deletion are removed recursively.
Parameters
directory
Path of the directory whose contents should be inspected.
The value is passed directly to os.scandir().
retain: list
List of entry names that must be preserved.
Comparison is performed against entry.name, not against the full path.
Returns
None
The function performs filesystem side effects and does not explicitly return a value.
Raises
The function does not catch filesystem exceptions. Errors raised by operations such as the following propagate to the caller:
os.scandir()shutil.rmtree()Path.unlink()
Processing
- Open the supplied directory using
os.scandir(). - Iterate through every direct child entry.
- Check whether
entry.nameis present inretain. - Leave retained entries unchanged.
- Remove non-retained directories recursively with
shutil.rmtree(). - Remove non-retained files with
Path.unlink().
Directory Handling
A non-retained directory is removed using:
shutil.rmtree(entry)
This removes the directory and all nested contents.
File Handling
A non-retained file is removed using:
Path(entry).unlink()
Side Effects
The function permanently deletes filesystem content.
Example
from common.cleanups import purge_directory
purge_directory(
"/data/article",
retain=[
"processing",
"metadata.json",
],
)
This preserves direct child entries named processing and metadata.json and removes the other direct children.
Operational Considerations
Name-Based Retention
Retention is based only on the filename or directory name:
entry.name
Full paths are not compared.
Recursive Deletion
If a top-level directory is not retained, its entire directory tree is removed. Nested items are not independently checked against retain.
Other Filesystem Entry Types
The implementation explicitly handles entries for which entry.is_dir() or entry.is_file() is true. No separate behavior is defined for other entry types.
Error Recovery
No retry, rollback, or recovery mechanism is implemented. If an exception occurs after some entries have already been deleted, those earlier deletions are not reversed.