Utils Layer¶
Utility functions, file operations, and validation modules for EzCompiler.
The utils layer provides reusable utilities for file management, configuration parsing, template processing, ZIP operations, and comprehensive validation.
File Utilities¶
Utilities for file and directory operations.
file_utils
¶
File utilities - File and directory operation utilities for EzCompiler.
This module provides utility functions for common file operations including path validation, directory creation, file copying, and path manipulation.
FileUtils
¶
File and directory operations utility class.
Provides static methods for common file and directory operations used throughout the EzCompiler project, including validation, creation, copying, moving, and listing operations.
Example
FileUtils.create_directory_if_not_exists("./output") file_size = FileUtils.get_file_size("path/to/file.txt")
validate_file_exists
staticmethod
¶
Validate that a file exists and is accessible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the file to validate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if file exists and is accessible, False otherwise |
validate_directory_exists
staticmethod
¶
Validate that a directory exists and is accessible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the directory to validate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if directory exists and is accessible, False otherwise |
create_directory_if_not_exists
staticmethod
¶
Create a directory if it doesn't exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the directory to create |
required |
Raises:
| Type | Description |
|---|---|
DirectoryCreationError
|
If directory creation fails |
ensure_parent_directory_exists
staticmethod
¶
Ensure that the parent directory of a file exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str | Path
|
Path to the file |
required |
Raises:
| Type | Description |
|---|---|
DirectoryCreationError
|
If parent directory creation fails |
get_file_size
staticmethod
¶
Get the size of a file in bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
File size in bytes |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file doesn't exist |
FileAccessError
|
If file is not accessible |
copy_file
staticmethod
¶
Copy a file from source to destination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path
|
Source file path |
required |
destination
|
str | Path
|
Destination file path |
required |
preserve_metadata
|
bool
|
Whether to preserve file metadata (default: True) |
True
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If source file doesn't exist |
FileCopyError
|
If copy operation fails |
move_file
staticmethod
¶
Move a file from source to destination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path
|
Source file path |
required |
destination
|
str | Path
|
Destination file path |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If source file doesn't exist |
FileMoveError
|
If move operation fails |
delete_file
staticmethod
¶
Delete a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the file to delete |
required |
Raises:
| Type | Description |
|---|---|
FileDeleteError
|
If deletion fails |
list_files
staticmethod
¶
List all files in a directory matching a pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | Path
|
Directory to search in |
required |
pattern
|
str
|
File pattern to match (default: "*") |
'*'
|
Returns:
| Type | Description |
|---|---|
list[Path]
|
list[Path]: List of matching file paths |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If directory doesn't exist |
DirectoryListError
|
If directory access fails |
get_file_extension
staticmethod
¶
Get the file extension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
File extension (including the dot) |
get_file_name_without_extension
staticmethod
¶
Get the file name without extension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
File name without extension |
is_hidden_file
staticmethod
¶
Check if a file is hidden.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if file is hidden, False otherwise |
get_relative_path
staticmethod
¶
Get the relative path from base_path to target_path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_path
|
str | Path
|
Base directory path |
required |
target_path
|
str | Path
|
Target file/directory path |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Relative path from base to target |
Note
If target is not relative to base, returns the absolute path.
normalize_path
staticmethod
¶
Normalize a path (resolve symlinks, make absolute).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to normalize |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
Normalized absolute path |
ensure_unique_filename
staticmethod
¶
Ensure a filename is unique by adding a number suffix if necessary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Original file path |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
Unique file path, with numeric suffix added if original exists |
Example
If "output.txt" exists, returns "output_1.txt"¶
unique_path = FileUtils.ensure_unique_filename("output.txt")
Configuration Utilities¶
Utilities for parsing and validating configuration files (YAML/JSON).
config_utils
¶
Configuration utilities - Configuration-specific utility functions for EzCompiler.
This module provides specialized utility functions for configuration validation and processing. Uses thematic utils (ValidationUtils, FileUtils) internally.
Note: These utilities are intended for use by services and other layers that need to validate or process CompilerConfig instances. The CompilerConfig class itself performs its own validation during initialization.
Utils layer can only use DEBUG and ERROR log levels.
ConfigUtils
¶
Utility class for configuration-specific operations.
Provides static methods for configuration validation and processing. Uses thematic utils (ValidationUtils, FileUtils) internally.
Example
config = CompilerConfig(...) ConfigUtils.validate_required_config_fields(config) ConfigUtils.validate_config_paths(config) ConfigUtils.validate_compiler_option(config.compiler)
validate_required_config_fields
staticmethod
¶
validate_required_config_fields(config: CompilerConfig) -> None
Validate required configuration fields are not empty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
CompilerConfig
|
CompilerConfig instance to validate |
required |
Raises:
| Type | Description |
|---|---|
ConfigurationError
|
If any required field is empty |
Note
Uses ValidationUtils for string validation.
Example
config = CompilerConfig(...) ConfigUtils.validate_required_config_fields(config)
validate_config_paths
staticmethod
¶
validate_config_paths(config: CompilerConfig) -> None
Validate file and folder paths in configuration.
Ensures main file exists and normalizes output_folder to Path. Does not create the output folder (that's done during compilation).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
CompilerConfig
|
CompilerConfig instance to validate |
required |
Raises:
| Type | Description |
|---|---|
ConfigurationError
|
If main file doesn't exist |
Note
Uses FileUtils for file existence checks.
Example
config = CompilerConfig(..., main_file="main.py", output_folder="dist") ConfigUtils.validate_config_paths(config)
validate_compiler_option
staticmethod
¶
Validate compiler option value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compiler
|
str
|
Compiler name to validate |
required |
Raises:
| Type | Description |
|---|---|
ConfigurationError
|
If compiler is not valid |
Example
ConfigUtils.validate_compiler_option("PyInstaller") ConfigUtils.validate_compiler_option("invalid") ConfigurationError: Invalid compiler: invalid
normalize_output_folder
staticmethod
¶
Normalize output folder path to Path object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_folder
|
str | Path
|
Output folder as string or Path |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
Normalized Path object |
Example
folder = ConfigUtils.normalize_output_folder("dist") print(type(folder))
load_yaml_config
staticmethod
¶
Load configuration from a YAML file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Path to the YAML file |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Parsed configuration dictionary |
Raises:
| Type | Description |
|---|---|
ConfigFileNotFoundError
|
If the file does not exist |
ConfigFileParseError
|
If the file cannot be parsed |
load_json_config
staticmethod
¶
Load configuration from a JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Path to the JSON file |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Parsed configuration dictionary |
Raises:
| Type | Description |
|---|---|
ConfigFileNotFoundError
|
If the file does not exist |
ConfigFileParseError
|
If the file cannot be parsed |
load_toml_config
staticmethod
¶
Load and return the full parsed TOML dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Path to the TOML file |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Parsed TOML dictionary |
Raises:
| Type | Description |
|---|---|
ConfigFileNotFoundError
|
If the file does not exist |
ConfigFileParseError
|
If the file cannot be parsed |
extract_pyproject_config
staticmethod
¶
Extract ezcompiler configuration from pyproject.toml structure.
Maps [project] fields (name, version, description, authors) and [tool.ezcompiler] fields into the flat config dict format expected by CompilerConfig.from_dict().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
toml_data
|
dict[str, Any]
|
Full parsed pyproject.toml dictionary |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Extracted configuration dictionary (may be empty) |
discover_config_file
staticmethod
¶
Auto-discover configuration file in the given directory.
Priority order: 1. ezcompiler.yaml 2. ezcompiler.json 3. pyproject.toml (only if [tool.ezcompiler] section exists)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
search_dir
|
Path
|
Directory to search in |
required |
Returns:
| Type | Description |
|---|---|
Path | None
|
Path | None: Path to discovered config file, or None if not found |
merge_config_dicts
staticmethod
¶
Merge two configuration dictionaries.
Override replaces base values. For known nested sections (compilation, upload, advanced), keys are merged within the section. All other values (including include_files, lists) are replaced entirely.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
dict[str, Any]
|
Base configuration dictionary |
required |
override
|
dict[str, Any]
|
Override configuration dictionary |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Merged configuration dictionary |
Template Utilities¶
Utilities for template processing and variable substitution.
template_utils
¶
Template processor - Variable substitution processor for EzCompiler templates.
This module provides utilities for processing templates with variable substitution, including methods for config, version, and setup template processing with placeholder replacement.
Utils layer can only use DEBUG and ERROR log levels.
TemplateProcessor
¶
Utility class for processing templates with variable substitution.
Provides static methods to replace placeholders in templates with actual values from configuration dictionaries. Supports multiple template types and formats.
Example
processor = TemplateProcessor() config = {"version": "1.0.0", "project_name": "MyApp"} result = processor.process_config_template(template, config)
create_mockup_config
staticmethod
¶
Create a mockup configuration dictionary with default values.
Provides realistic default values that can be used to generate valid JSON/YAML templates without placeholders.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Dictionary with mockup configuration values |
Example
mockup = TemplateProcessor.create_mockup_config() print(mockup["version"]) '1.0.0'
process_template_with_mockup
staticmethod
¶
Process a template using mockup values to create a valid file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
str
|
The template string with placeholders |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Processed template string with mockup values |
Raises:
| Type | Description |
|---|---|
TemplateSubstitutionError
|
If substitution fails |
Example
template = "version: #VERSION#\nproject: #PROJECT_NAME#" result = TemplateProcessor.process_template_with_mockup(template)
process_version_template
staticmethod
¶
process_version_template(template: str, version: str, company_name: str, project_description: str, project_name: str) -> str
Process version info template with project-specific values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
str
|
The version template string |
required |
version
|
str
|
Project version (e.g., "1.0.0") |
required |
company_name
|
str
|
Company name |
required |
project_description
|
str
|
Project description |
required |
project_name
|
str
|
Project name |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Processed template string |
Raises:
| Type | Description |
|---|---|
TemplateSubstitutionError
|
If version substitution fails |
Note
Converts version string to tuple format (e.g., "1.0.0" -> "(1, 0, 0, 0)") and automatically includes current year for copyright.
process_config_template
staticmethod
¶
Process configuration template with project configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
str
|
The configuration template string |
required |
config
|
dict[str, Any]
|
Project configuration dictionary |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Processed template string |
Raises:
| Type | Description |
|---|---|
TemplateSubstitutionError
|
If config substitution fails |
Note
Handles nested dictionaries for include_files, compilation, upload, and advanced settings. Converts Python booleans to JSON-compatible lowercase strings.
process_setup_template
staticmethod
¶
Process setup template with project configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
str
|
The setup template string |
required |
config
|
dict[str, Any]
|
Project configuration dictionary |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Processed template string |
Raises:
| Type | Description |
|---|---|
TemplateSubstitutionError
|
If setup substitution fails |
Note
Formats include_files as Python dict string representation for setup.py compatibility.
validate_template
staticmethod
¶
Validate template syntax.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
str
|
Template string to validate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if template is valid |
Raises:
| Type | Description |
|---|---|
TemplateValidationError
|
If template syntax is invalid |
Note
Performs basic validation: checks for balanced braces and quotes.
Compiler Utilities¶
Utilities for compiler-specific operations.
compiler_utils
¶
Compiler utilities - Compiler-specific utility functions for EzCompiler.
This module provides specialized utility functions for compiler operations, including configuration validation, output directory preparation, and include files formatting. Uses thematic utils (FileUtils, ValidationUtils) internally.
Utils layer can only use DEBUG and ERROR log levels.
CompilerUtils
¶
Utility class for compiler-specific operations.
Provides static methods for compiler-related tasks such as configuration validation, output directory preparation, and include files formatting. Uses thematic utils (FileUtils, ValidationUtils) internally.
Example
config = CompilerConfig(...) CompilerUtils.validate_compiler_config(config) CompilerUtils.prepare_compiler_output_directory(config) files = CompilerUtils.format_include_files_data(config)
validate_compiler_config
staticmethod
¶
validate_compiler_config(config: CompilerConfig) -> None
Validate configuration for compilation.
Checks that all required configuration fields are present and valid (main file exists, output folder is set).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
CompilerConfig
|
CompilerConfig instance to validate |
required |
Raises:
| Type | Description |
|---|---|
MainFileNotFoundError
|
If main file doesn't exist or is required but missing |
OutputDirectoryError
|
If output folder is not set |
Note
Uses FileUtils for file existence checks.
Example
config = CompilerConfig(...) CompilerUtils.validate_compiler_config(config)
prepare_compiler_output_directory
staticmethod
¶
prepare_compiler_output_directory(config: CompilerConfig) -> None
Prepare the output directory for compilation.
Creates the output directory if it doesn't exist, including any parent directories as needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
CompilerConfig
|
CompilerConfig instance with output_folder path |
required |
Note
Uses FileUtils.create_directory_if_not_exists() internally.
Example
config = CompilerConfig(..., output_folder=Path("dist")) CompilerUtils.prepare_compiler_output_directory(config)
format_include_files_data
staticmethod
¶
format_include_files_data(config: CompilerConfig) -> list[str]
Format include files data for compilation.
Combines individual files and folders from configuration, formatting folders with trailing slashes for compatibility with different compilers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
CompilerConfig
|
CompilerConfig instance with include_files |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: List of formatted include paths |
Note
Files are included as-is, folders are formatted with trailing slashes for Cx_Freeze compatibility.
Example
config.include_files = { ... "files": ["config.yaml"], ... "folders": ["lib", "assets"] ... } files = CompilerUtils.format_include_files_data(config) print(files) ['config.yaml', 'lib/', 'assets/']
get_windows_base_for_console
staticmethod
¶
Get Windows base executable type based on console setting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
console
|
bool
|
Whether to show console window |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: "Win32GUI" if console=False on Windows, None otherwise |
Note
Used by Cx_Freeze to determine executable base type.
Example
base = CompilerUtils.get_windows_base_for_console(False) print(base) 'Win32GUI' # On Windows
check_onefile_mode
staticmethod
¶
Check if onefile mode is requested via command-line arguments.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if --onefile is in sys.argv, False otherwise |
Note
Used by PyInstaller and Nuitka to determine output format.
Example
When run with: python script.py --onefile¶
is_onefile = CompilerUtils.check_onefile_mode() print(is_onefile) True
Uploader Utilities¶
Utilities for upload operations.
uploader_utils
¶
Uploader utilities - Uploader-specific utility functions for EzCompiler.
This module provides specialized utility functions for uploader operations, including source path validation, configuration validation, and backup operations. Uses thematic utils (FileUtils, ValidationUtils) internally.
Utils layer can only use DEBUG and ERROR log levels.
UploaderUtils
¶
Utility class for uploader-specific operations.
Provides static methods for uploader-related tasks such as source path validation, configuration validation, and backup operations. Uses thematic utils (FileUtils) internally.
Example
UploaderUtils.validate_source_path(Path("file.zip")) UploaderUtils.validate_upload_type("disk") backup_path = UploaderUtils.generate_backup_path(Path("file.zip"))
validate_source_path
staticmethod
¶
Validate that the source path exists and is accessible.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_path
|
Path
|
Path to validate |
required |
Raises:
| Type | Description |
|---|---|
SourcePathError
|
If source path is invalid or inaccessible |
Note
Uses FileUtils for file/directory existence checks.
Example
UploaderUtils.validate_source_path(Path("file.zip"))
validate_upload_type
staticmethod
¶
Validate upload type string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upload_type
|
str
|
Upload type to validate |
required |
Raises:
| Type | Description |
|---|---|
UploaderTypeError
|
If upload type is not supported |
Example
UploaderUtils.validate_upload_type("disk") UploaderUtils.validate_upload_type("invalid") UploaderTypeError: Unsupported upload type: invalid
validate_server_url
staticmethod
¶
Validate server URL format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
server_url
|
str
|
Server URL to validate |
required |
Raises:
| Type | Description |
|---|---|
ServerConfigError
|
If server URL is invalid |
Example
UploaderUtils.validate_server_url("https://example.com") UploaderUtils.validate_server_url("invalid") ServerConfigError: server_url must start with http:// or https://
generate_backup_path
staticmethod
¶
Generate a unique backup path for a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to file that needs backup |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
Unique backup path (with .backup suffix and counter if needed) |
Example
backup = UploaderUtils.generate_backup_path(Path("file.zip")) print(backup) file.zip.backup
get_default_disk_config
staticmethod
¶
Get default configuration for disk uploader.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Default disk uploader configuration |
Example
config = UploaderUtils.get_default_disk_config() print(config)
get_default_server_config
staticmethod
¶
Get default configuration for server uploader.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Default server uploader configuration |
Example
config = UploaderUtils.get_default_server_config() print(config)
ZIP Utilities¶
Utilities for creating and managing ZIP archives.
zip_utils
¶
ZIP utilities - ZIP archive operation utilities for EzCompiler.
This module provides utility functions for creating, extracting, and managing ZIP archives used in the EzCompiler project, with support for progress tracking and logging.
ZipUtils
¶
ZIP archive operations utility class.
Provides static methods for creating, extracting, and managing ZIP archives used in the EzCompiler project. Supports compression, progress tracking, and detailed logging.
Class Variables
_ezpl: Cached Ezpl instance for logging _logger: Cached logger instance _printer: Cached printer instance
Example
ZipUtils.create_zip_archive("./source", "./output.zip") ZipUtils.extract_zip_archive("./output.zip", "./extracted")
create_zip_archive
staticmethod
¶
create_zip_archive(source_path: str | Path, output_path: str | Path, compression: int = ZIP_DEFLATED, include_hidden: bool = False, progress_callback: Callable[[str, int], None] | None = None) -> None
Create a ZIP archive from a file or directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_path
|
str | Path
|
Path to the source file or directory |
required |
output_path
|
str | Path
|
Path where the ZIP file will be created |
required |
compression
|
int
|
Compression method (default: ZIP_DEFLATED) |
ZIP_DEFLATED
|
include_hidden
|
bool
|
Whether to include hidden files (default: False) |
False
|
progress_callback
|
Callable[[str, int], None] | None
|
Optional callback for progress updates (file, progress) |
None
|
Raises:
| Type | Description |
|---|---|
FileOperationError
|
If ZIP creation fails |
Note
Progress callback receives (filename: str, progress: int) where progress is a percentage from 0 to 100.
extract_zip_archive
staticmethod
¶
extract_zip_archive(zip_path: str | Path, extract_path: str | Path, password: str | None = None, progress_callback: Callable[[str, int], None] | None = None) -> None
Extract a ZIP archive to a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zip_path
|
str | Path
|
Path to the ZIP file |
required |
extract_path
|
str | Path
|
Directory where files will be extracted |
required |
password
|
str | None
|
Optional password for encrypted archives (default: None) |
None
|
progress_callback
|
Callable[[str, int], None] | None
|
Optional callback for progress updates (file, progress) |
None
|
Raises:
| Type | Description |
|---|---|
FileOperationError
|
If extraction fails |
Note
Progress callback receives (filename: str, progress: int) where progress is a percentage from 0 to 100.
list_zip_contents
staticmethod
¶
List the contents of a ZIP archive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zip_path
|
str | Path
|
Path to the ZIP file |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: List of file names in the archive |
Raises:
| Type | Description |
|---|---|
ZipFileCorruptedError
|
If listing fails |
get_zip_info
staticmethod
¶
Get information about a ZIP archive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zip_path
|
str | Path
|
Path to the ZIP file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Dictionary with ZIP information including: - file_count: Number of files in the archive - total_size: Total uncompressed size in bytes - compressed_size: Total compressed size in bytes - compression_ratio: Compression ratio as percentage - files: List of file names in the archive |
Raises:
| Type | Description |
|---|---|
ZipFileCorruptedError
|
If getting info fails |
is_valid_zip
staticmethod
¶
Check if a file is a valid ZIP archive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zip_path
|
str | Path
|
Path to the file to check |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if file is a valid ZIP archive, False otherwise |
add_file_to_zip
staticmethod
¶
Add a single file to an existing ZIP archive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zip_path
|
str | Path
|
Path to the ZIP file |
required |
file_path
|
str | Path
|
Path to the file to add |
required |
arcname
|
str | None
|
Name of the file in the archive (default: file name) |
None
|
Raises:
| Type | Description |
|---|---|
ZipCreationError
|
If adding file fails |
remove_file_from_zip
staticmethod
¶
Remove a file from a ZIP archive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zip_path
|
str | Path
|
Path to the ZIP file |
required |
file_name
|
str
|
Name of the file to remove from the archive |
required |
Raises:
| Type | Description |
|---|---|
ZipCreationError
|
If removal fails |
Note
Creates a temporary file during removal process.
Validators¶
Comprehensive validation package with 9 specialized modules.
Domain Validators¶
Validators for domain-specific entities (URLs, emails, etc.).
domain_validators
¶
Domain validators - Validation utilities for project-specific domains.
This module provides validation functions for project-specific data types like compiler names and upload structures.
validate_compiler_name
¶
Validate a compiler name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
compiler
|
str
|
Compiler name to validate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if compiler name is valid, False otherwise |
Note
Valid compilers: "auto", "Cx_Freeze", "PyInstaller", "Nuitka"
Example
validate_compiler_name("PyInstaller") True validate_compiler_name("auto") True validate_compiler_name("InvalidCompiler") False
validate_upload_structure
¶
Validate an upload structure type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
str
|
Upload structure to validate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if upload structure is valid, False otherwise |
Note
Valid structures: "disk", "server"
Example
validate_upload_structure("disk") True validate_upload_structure("server") True validate_upload_structure("cloud") False
Format Validators¶
Validators for data format validation.
format_validators
¶
Format validators - Validation utilities for common data formats.
This module provides validation functions for common data formats like version strings, email addresses, and URLs.
validate_version_string
¶
Validate a version string format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
version
|
str
|
Version string to validate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if version format is valid (e.g., 1.0.0), False otherwise |
Note
Accepts common version formats: x.y.z, x.y.z.w, x.y, etc.
Example
validate_version_string("1.0.0") True validate_version_string("1.0") True validate_version_string("invalid") False
validate_email
¶
Validate an email address format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
email
|
str
|
Email address to validate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if email format is valid, False otherwise |
Note
Uses basic regex pattern validation. Not a strict RFC 5322 validator.
Example
validate_email("user@example.com") True validate_email("invalid-email") False
validate_url
¶
Validate a URL format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to validate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if URL format is valid, False otherwise |
Note
Validates basic HTTP/HTTPS URL structure.
Example
validate_url("https://example.com") True validate_url("http://example.com/path") True validate_url("invalid-url") False
Meta Validators¶
Meta-validators for composite and conditional validation.
meta_validators
¶
Meta validators - Validation utilities for batch validation operations.
This module provides validation functions for performing multiple validations at once using a declarative approach.
validate_multiple
¶
Perform multiple validations at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
validations
|
list[tuple[Any, str, str]]
|
List of (value, validator_name, field_name) tuples |
required |
validators
|
dict[str, Callable]
|
Dict of validator_name -> validator_function |
required |
Raises:
| Type | Description |
|---|---|
SchemaValidationError
|
If any validation fails |
Example
validations = [ ... ("1.0.0", "version_string", "version"), ... ("user@example.com", "email", "contact_email"), ... ("https://example.com", "url", "server_url"), ... ] validators = { ... "version_string": ValidationUtils.validate_version_string, ... "email": ValidationUtils.validate_email, ... "url": ValidationUtils.validate_url, ... } validate_multiple(validations, validators)
Raises:
| Type | Description |
|---|---|
SchemaValidationError
|
If any validation fails |
Path Validators¶
Validators for file and directory paths.
path_validators
¶
Path validators - Validation utilities for file and directory paths.
This module provides validation functions for validating file and directory paths, checking for valid characters and structure.
validate_file_path
¶
Validate a file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File path to validate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if path format is valid, False otherwise |
Note
Checks for valid characters and structure, not existence.
Example
validate_file_path("path/to/file.txt") True validate_file_path("invalid
") False
validate_directory_path
¶
Validate a directory path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Directory path to validate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if path format is valid, False otherwise |
Note
Uses same validation as file path validation.
Example
validate_directory_path("path/to/directory") True validate_directory_path("invalid
") False
Schema Validators¶
Validators for structured data schemas.
schema_validators
¶
Schema validators - Validation utilities for dictionary schemas and structures.
This module provides validation functions for validating dictionary structures, required fields, field types, and complex schema validation.
validate_required_fields
¶
Validate that required fields are present in a dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dictionary to validate |
required |
required_fields
|
list[str]
|
List of required field names |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If data is not a dict |
RequiredFieldError
|
If required fields are missing |
Example
validate_required_fields({"name": "test", "age": 25}, ["name", "age"]) validate_required_fields({"name": "test"}, ["name", "age"]) Traceback (most recent call last): ... RequiredFieldError: Missing required fields: age
validate_field_types
¶
Validate that fields have the correct types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dictionary to validate |
required |
field_types
|
dict[str, type]
|
Dictionary mapping field names to expected types |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If data is not a dict |
TypeValidationError
|
If field types are incorrect |
Example
validate_field_types({"name": "test", "age": 25}, {"name": str, "age": int}) validate_field_types({"name": "test", "age": "25"}, {"name": str, "age": int}) Traceback (most recent call last): ... TypeValidationError: Field 'age' must be of type int, got str
validate_config_dict
¶
Validate a configuration dictionary structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any]
|
Configuration dictionary to validate |
required |
Raises:
| Type | Description |
|---|---|
SchemaValidationError
|
If configuration is invalid |
Note
Validates required top-level sections and their formats.
Example
config = { ... "version": "1.0.0", ... "project_name": "MyProject", ... "main_file": "main.py" ... } validate_config_dict(config)
validate_dict_schema
¶
Validate a dictionary against a schema.
Schema format: { "field_name": { "type": (str, int, ...), # Required type(s) "required": True/False, # Is field required "empty": True/False, # Allow empty values "choices": [...] # Valid choices "min_length": int, # Min length (str/list) "max_length": int, # Max length (str/list) "min_value": int/float, # Min value (numeric) "max_value": int/float, # Max value (numeric) "pattern": "regex", # Regex pattern (str) } }
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dictionary to validate |
required |
schema
|
dict[str, dict[str, Any]]
|
Validation schema |
required |
Raises:
| Type | Description |
|---|---|
SchemaValidationError
|
If validation fails |
Example
schema = { # noqa: W605 ... "version": {"type": str, "required": True, "pattern": r"^\d+.\d+.\d+$"}, # noqa: W605 ... "port": {"type": int, "required": False, "min_value": 1, "max_value": 65535}, ... } validate_dict_schema(data, schema)
String Validators¶
Validators for string format and content.
string_validators
¶
String validators - Validation utilities for string manipulation and validation.
This module provides validation functions for sanitizing filenames and validating string patterns.
sanitize_filename
¶
Sanitize a filename by removing invalid characters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Original filename |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Sanitized filename with invalid characters removed |
Note
Returns "unnamed_file" if filename becomes empty after sanitization.
Example
sanitize_filename("my_file.txt") 'my_file.txt' sanitize_filename("invalid<>file.txt") 'invalid__file.txt' sanitize_filename(">>>") 'unnamed_file'
validate_pattern
¶
validate_pattern(value: str, pattern: str, field_name: str = 'Value', error_msg: str | None = None) -> None
Validate that a string matches a regex pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
String to validate |
required |
pattern
|
str
|
Regex pattern to match |
required |
field_name
|
str
|
Name of field for error messages |
'Value'
|
error_msg
|
str | None
|
Custom error message |
None
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If value is not a string |
PatternValidationError
|
If value doesn't match pattern |
Example
validate_pattern("hello123", r"^[a-z]+\d+$") validate_pattern("hello", r"^\d+$") Traceback (most recent call last): ... PatternValidationError: Value does not match required pattern
Type Validators¶
Validators for Python type checking and validation.
type_validators
¶
Type validators - Validation utilities for type checking.
This module provides validation functions for checking data types and validating integer values.
validate_positive_integer
¶
Validate that a value is a positive integer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Value to validate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if value is a positive integer, False otherwise |
Example
validate_positive_integer(5) True validate_positive_integer(0) False validate_positive_integer(-1) False
validate_non_negative_integer
¶
Validate that a value is a non-negative integer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Value to validate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if value is a non-negative integer, False otherwise |
Example
validate_non_negative_integer(0) True validate_non_negative_integer(5) True validate_non_negative_integer(-1) False
validate_boolean
¶
Validate that a value is a boolean.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Value to validate |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if value is a boolean, False otherwise |
Example
validate_boolean(True) True validate_boolean(False) True validate_boolean(1) False
validate_type
¶
validate_type(value: Any, expected_type: type | tuple[type, ...], field_name: str = 'Value') -> None
Validate that a value is of the expected type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Value to validate |
required |
expected_type
|
type | tuple[type, ...]
|
Expected type or tuple of types |
required |
field_name
|
str
|
Name of field for error messages |
'Value'
|
Raises:
| Type | Description |
|---|---|
TypeValidationError
|
If value is not of expected type |
Example
validate_type("hello", str) validate_type(42, int) validate_type("hello", int) Traceback (most recent call last): ... TypeValidationError: Value must be of type int, got str
Value Validators¶
Validators for value ranges and constraints.
value_validators
¶
Value validators - Validation utilities for value ranges and constraints.
This module provides validation functions for checking string lengths, numeric ranges, list lengths, choices, and other value constraints.
validate_string_length
¶
Validate string length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
String to validate |
required |
min_length
|
int
|
Minimum allowed length (default: 0) |
0
|
max_length
|
int | None
|
Maximum allowed length, None for no limit (default: None) |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if string length is valid, False otherwise |
Example
validate_string_length("hello", min_length=3) True validate_string_length("hi", min_length=3) False validate_string_length("toolong", max_length=5) False
validate_numeric_range
¶
validate_numeric_range(value: int | float, min_value: int | float | None = None, max_value: int | float | None = None) -> bool
Validate numeric value range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
int | float
|
Numeric value to validate |
required |
min_value
|
int | float | None
|
Minimum allowed value, None for no limit (default: None) |
None
|
max_value
|
int | float | None
|
Maximum allowed value, None for no limit (default: None) |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if value is within range, False otherwise |
Example
validate_numeric_range(5, min_value=0, max_value=10) True validate_numeric_range(-1, min_value=0) False validate_numeric_range(15, max_value=10) False
validate_list_length
¶
Validate list length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
list[Any]
|
List to validate |
required |
min_length
|
int
|
Minimum allowed length (default: 0) |
0
|
max_length
|
int | None
|
Maximum allowed length, None for no limit (default: None) |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if list length is valid, False otherwise |
Example
validate_list_length([1, 2, 3], min_length=2) True validate_list_length([1], min_length=2) False validate_list_length([1, 2, 3, 4], max_length=3) False
validate_choice
¶
Validate that a value is one of the valid choices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Value to validate |
required |
valid_choices
|
list[Any]
|
List of valid choices |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if value is a valid choice, False otherwise |
Example
validate_choice("red", ["red", "green", "blue"]) True validate_choice("yellow", ["red", "green", "blue"]) False
validate_not_empty
¶
Validate that a value is not empty (string, list, dict, etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Value to validate |
required |
field_name
|
str
|
Name of field for error messages |
'Value'
|
Raises:
| Type | Description |
|---|---|
RequiredFieldError
|
If value is empty |
Example
validate_not_empty("hello") validate_not_empty([1, 2, 3]) validate_not_empty("") Traceback (most recent call last): ... RequiredFieldError: Value cannot be empty
validate_one_of
¶
Validate that a value is one of the valid options.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Value to validate |
required |
valid_values
|
list[Any]
|
List of valid values |
required |
field_name
|
str
|
Name of field for error messages |
'Value'
|
Raises:
| Type | Description |
|---|---|
ChoiceValidationError
|
If value is not in valid values |
Example
validate_one_of("red", ["red", "green", "blue"]) validate_one_of("yellow", ["red", "green", "blue"]) Traceback (most recent call last): ... ChoiceValidationError: Value must be one of: red, green, blue, got yellow
validate_value_in_range
¶
validate_value_in_range(value: int | float, min_value: int | float | None = None, max_value: int | float | None = None, field_name: str = 'Value') -> None
Validate that a numeric value is within a range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
int | float
|
Numeric value to validate |
required |
min_value
|
int | float | None
|
Minimum allowed value (None for no limit) |
None
|
max_value
|
int | float | None
|
Maximum allowed value (None for no limit) |
None
|
field_name
|
str
|
Name of field for error messages |
'Value'
|
Raises:
| Type | Description |
|---|---|
RangeValidationError
|
If value is out of range |
Example
validate_value_in_range(5, min_value=0, max_value=10) validate_value_in_range(-1, min_value=0) Traceback (most recent call last): ... RangeValidationError: Value must be >= 0, got -1
validate_length
¶
validate_length(value: str | list[Any], min_length: int | None = None, max_length: int | None = None, field_name: str = 'Value') -> None
Validate the length of a string or list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str | list[Any]
|
String or list to validate |
required |
min_length
|
int | None
|
Minimum allowed length (None for no limit) |
None
|
max_length
|
int | None
|
Maximum allowed length (None for no limit) |
None
|
field_name
|
str
|
Name of field for error messages |
'Value'
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If value is not string or list |
LengthValidationError
|
If length is out of range |
Example
validate_length("hello", min_length=3, max_length=10) validate_length("hi", min_length=3) Traceback (most recent call last): ... LengthValidationError: Value must have length >= 3, got 2