Collections Module

The collections module provides advanced file system operations and enhanced data structures with comprehensive functionality for file management, recycling bin operations, and file system monitoring.

Key Components

  • FileStats: Enhanced data class for file statistics

  • File: Enhanced file class with additional capabilities

  • Directory: Enhanced directory class with advanced operations

  • RecycleBin: Advanced recycling bin implementation

  • OSUtils: Comprehensive OS utility class

  • DummyFile: Template-based dummy file creator

File Management

FileStats

class true.collections.FileStats(size, created, modified, accessed, permissions, is_hidden, mime_type, owner, group, is_symlink, symlink_target, md5_hash=None)[source]

Enhanced data class to hold file statistics

size: int
created: datetime
modified: datetime
accessed: datetime
permissions: str
is_hidden: bool
mime_type: str
owner: str
group: str
md5_hash: Optional[str] = None
to_dict()[source]

Convert stats to dictionary format

Return type:

dict

classmethod from_dict(data)[source]

Create FileStats instance from dictionary

Return type:

FileStats

__init__(size, created, modified, accessed, permissions, is_hidden, mime_type, owner, group, is_symlink, symlink_target, md5_hash=None)

File

class true.collections.File(path, base_path=None)[source]

Enhanced file class with additional capabilities

__init__(path, base_path=None)[source]
property filename: str
property extension: str
property size: int
property md5: str
property mime_type: str

Get file MIME type

get_stats()[source]

Get comprehensive file statistics

Return type:

FileStats

copy_to(destination, overwrite=False)[source]

Copy file to destination with retry mechanism

Return type:

bool

create_backup(suffix='.bak')[source]

Create a backup copy of the file

Return type:

File

is_text_file()[source]

Check if file is a text file

Return type:

bool

read_text(encoding='utf-8')[source]

Read text file content

Return type:

str

write_text(content, encoding='utf-8')[source]

Write text to file

Return type:

int

Directory

class true.collections.Directory(path, base_path=None)[source]

Enhanced directory class with additional capabilities

__init__(path, base_path=None)[source]
property size: int

Get cached directory size with automatic refresh

_calculate_size()[source]

Calculate total directory size

Return type:

int

glob(pattern)[source]
Return type:

Generator[Path, None, None]

rglob(pattern)[source]
Return type:

Generator[Path, None, None]

create(exist_ok=True)[source]

Create directory if it doesn’t exist

Return type:

bool

zip_contents(output_path, compression=8)[source]

Create a zip archive of directory contents

Return type:

bool

get_tree(max_depth=None)[source]

Get directory structure as a nested dictionary

Return type:

Dict[str, Any]

property is_empty: bool

Check if directory is empty

delete()[source]

Delete directory and its contents

Return type:

None

Recycling Bin

RecycleBin

class true.collections.RecycleBin(location, max_size=1073741824)[source]

Advanced RecycleBin implementation with extensive features.

__init__(location, max_size=1073741824)[source]

Initialize RecycleBin.

Parameters:
  • location (str) – Base directory for the recycle bin

  • max_size (int) – Maximum size in bytes (default 1GB)

_setup()[source]

Initialize recycle bin directory structure.

Return type:

None

_load_metadata()[source]

Load metadata from disk.

Return type:

None

_save_metadata()[source]

Save metadata to disk.

Return type:

None

get_total_size()[source]

Get total size of items in recycle bin.

Return type:

int

delete(path)[source]

Move item to recycle bin.

Parameters:

path (str) – Path to item to be deleted

Returns:

Item ID in recycle bin

Return type:

str

Raises:
  • StorageFullError – If recycle bin is full

  • FileNotFoundError – If item doesn’t exist

async async_delete(path)[source]

Asynchronous version of delete operation.

Return type:

str

restore(item_id)[source]

Restore item from recycle bin.

Parameters:

item_id (str) – ID of item to restore

Raises:
  • ItemNotFoundError – If item not found in recycle bin

  • RestoreError – If restoration fails

Return type:

None

async async_restore(item_id)[source]

Asynchronous version of restore operation.

Return type:

None

static _calculate_checksum(path)[source]

Calculate file checksum.

Return type:

str

list_items(pattern=None)[source]

List items in recycle bin with optional pattern matching.

Return type:

Generator[FileMetadata, None, None]

add_tag(item_id, tag)[source]

Add tag to item.

Return type:

None

remove_tag(item_id, tag)[source]

Remove tag from item.

Return type:

None

cleanup(days=30)[source]

Remove items older than specified days.

Return type:

None

_permanent_delete(item_id)[source]

Permanently delete item from recycle bin.

Return type:

None

_start_job_handler()[source]

Start background job handler thread.

Return type:

None

batch_operation()[source]

Context manager for batch operations.

async_batch_operation()[source]

Async context manager for batch operations.

__str__()[source]

String representation.

Return type:

str

__repr__()[source]

Detailed string representation.

Return type:

str

__enter__()[source]

Context manager entry.

__exit__(exc_type, exc_val, exc_tb)[source]

Context manager exit.

async __aenter__()[source]

Async context manager entry.

async __aexit__(exc_type, exc_val, exc_tb)[source]

Async context manager exit.

RecycleBinManager

class true.collections.RecycleBinManager[source]

Singleton manager for recyclebin instances.

__init__()[source]

OS Utilities

OSUtils

class true.collections.OSUtils(base_path=None, max_workers=4)[source]

Enhanced OS utility class with comprehensive file system operations

__init__(base_path=None, max_workers=4)[source]
_setup_logging()[source]

Configure logging with rotation

get_file(path)[source]
Return type:

File

get_directory(path)[source]
Return type:

Directory

safe_move(src, dst, overwrite=False)[source]

Safely move a file or directory with retry mechanism

Return type:

bool

batch_process(file_list, operation, parallel=True)[source]

Process multiple files in parallel or sequentially

Return type:

Dict[str, bool]

watch_directory(directory, callback)[source]

Watch a directory for changes and call callback on file events.

Parameters:
  • directory (str) – Directory path to watch

  • callback (callable) – Function to call when changes occur

Return type:

None

stop_watching(directory=None)[source]

Stop watching a specific directory or all directories

Return type:

None

safe_delete(path, secure=False)[source]

Safely delete a file or directory with optional secure deletion.

Parameters:
  • path (str) – Path to delete

  • secure (bool) – If True, overwrite file contents before deletion

Return type:

bool

force_delete(path)[source]

Forcefully delete a file or directory, using extreme measures for both Unix and Windows.

Parameters:

path (str) – Path to delete

Returns:

True if deletion was successful, False otherwise

Return type:

bool

static _secure_delete_file(path, passes=3)[source]

Securely delete a file by overwriting its contents

Return type:

None

find_files_by_date(directory, start_date=None, end_date=None, modified=True)[source]

Find files within a date range.

Parameters:
  • directory (str) – Directory to search

  • start_date (datetime) – Start date for search

  • end_date (datetime) – End date for search

  • modified (bool) – If True, use modification date, else creation date

Return type:

List[str]

get_directory_stats(directory)[source]

Get comprehensive directory statistics

Return type:

Dict[str, Any]

_log_operation(operation_type, details)[source]

Log operation with timestamp

Return type:

None

export_operation_history(output_file)[source]

Export operation history to JSON file

Return type:

bool

__enter__()[source]

Context manager entry

__exit__(exc_type, exc_val, exc_tb)[source]

Context manager exit with cleanup

__del__()[source]

Cleanup on deletion

File Creation

DummyFile

class true.collections.DummyFile(default_size=1024, default_content=None)[source]

A class to manage the creation out for various types of dummy files using the Template Pattern.

__init__(default_size=1024, default_content=None)[source]
create_file(extension, filename=None, size=None, content=None)[source]

Generic method to create a dummy file based on the extension.

Parameters:
  • extension – File extension (e.g., ‘.pdf’).

  • filename – Name of the file to create.

  • size – Size of the file in bytes.

  • content – Content to fill the file.

custom_file(filename, extension, header=None, size=None, content=None)[source]

Create a custom dummy file.

Parameters:
  • filename – Name of the file.

  • extension – File extension (e.g., ‘.custom’).

  • header – Custom header bytes.

  • size – Size of the file in bytes.

  • content – Custom content to fill the file.

reset()[source]

Reset the list of created files.

static create_image(output_path)[source]
create_video(output_path, sequence_dir=None, codec='libx264', fps=10)[source]
static create_static_video(image_path, output_path, codec='libx264', duration=5, fps=24)[source]
static create_audio(filename, duration=3000, frequency=440)[source]

FileCreator

class true.collections.FileCreator(extension, default_size=1024, default_content=None)[source]

Abstract base class that defines the template for creating a dummy file.

FILE_HEADERS = {'.7z': b"7z\xbc\xaf'\x1c", '.avi': b'RIFF', '.bmp': b'BM', '.docx': b'PK\x03\x04', '.epub': b'PK\x03\x04', '.gif': b'GIF89a', '.jpg': b'\xff\xd8\xff', '.mkv': b'\x1aE\xdf\xa3', '.mp3': b'ID3', '.mp4': b'ftyp', '.pdf': b'%PDF-1.4\n%', '.png': b'\x89PNG\r\n\x1a\n', '.rar': b'Rar!', '.svg': b'<?xml version="1.0"?>', '.tar': b'ustar', '.tiff': b'II*\x00', '.txt': b'', '.wav': b'RIFF', '.xlsx': b'PK\x03\x04', '.zip': b'PK\x03\x04'}
__init__(extension, default_size=1024, default_content=None)[source]

Initialize the FileCreator instance.

Parameters:
  • extension – File extension including dot (e.g., ‘.pdf’)

  • default_size – Default size of the dummy file in bytes.

  • default_content – Default content to fill the dummy file.

create_file(filename=None, size=None, content=None)[source]

Template method to create a dummy file.

Parameters:
  • filename – Name of the file to create.

  • size – Size of the file in bytes.

  • content – Content to fill the file.

property header

Get the header bytes for the file type.

property default_filename

Get the default filename for the file type.

list_created_files()[source]

List all created dummy files.

Returns:

List of filenames.

reset()[source]

Reset the list of created files.

Examples

File Operations

from true.collections import File, Directory, OSUtils

# Enhanced file operations
file = File("example.txt")
print(file.size)  # Get file size
print(file.md5)   # Get MD5 hash
print(file.mime_type)  # Get MIME type

# Copy with retry mechanism
file.copy_to("backup/example.txt")

# Create backup
file.create_backup()  # Creates example.txt.bak

# Directory operations
directory = Directory("my_folder")
directory.create()  # Create if not exists

# Get directory tree
tree = directory.get_tree(max_depth=2)

# Create zip archive
directory.zip_contents("archive.zip")

Recycling Bin Usage

from true.collections import RecycleBin

# Initialize recycle bin
recycle_bin = RecycleBin("./trash", max_size=1024*1024*1024)  # 1GB max

# Delete with move to recycle bin
item_id = recycle_bin.delete("old_file.txt")

# Restore from recycle bin
recycle_bin.restore(item_id)

# List items with pattern
items = recycle_bin.list_items("*.txt")

# Cleanup old items
recycle_bin.cleanup(days=30)

# Use as context manager for batch operations
with recycle_bin:
    recycle_bin.delete("file1.txt")
    recycle_bin.delete("file2.txt")

OS Utilities Usage

from true.collections import OSUtils
from datetime import datetime, timedelta

os_utils = OSUtils()

# Watch directory for changes
def on_change(event):
    print(f"Change detected: {event.src_path}")

os_utils.watch_directory("watched_dir", on_change)

# Find files by date
yesterday = datetime.now() - timedelta(days=1)
files = os_utils.find_files_by_date(
    "search_dir",
    start_date=yesterday,
    modified=True
)

# Safe delete with secure overwrite
os_utils.safe_delete("sensitive.txt", secure=True)

# Batch process files
def process_file(file_path):
    # Process file
    pass

os_utils.batch_process(
    ["file1.txt", "file2.txt"],
    process_file,
    parallel=True
)

Dummy File Creation

from true.collections import DummyFile

# Create dummy files of various types
dummy = DummyFile()

# Create PDF dummy file
dummy.create_file(".pdf", "test.pdf", size=1024*1024)  # 1MB file

# Create image file
dummy.create_image("test.png")

# Create video file
dummy.create_video("output.mp4", fps=30)

# Create audio file
dummy.create_audio("test.wav", duration=5000)