File Operations
Relevant source files
The following files were used as context for generating this wiki page:
- src/flext_cli/services/file_tools.py
- src/flext_cli/_utilities/_files_parts/flextcliutilitiesfiles_part_01.py
- src/flext_cli/_utilities/_files_parts/flextcliutilitiesfiles_part_04.py
- examples/ex_04_file_operations.py
- src/flext_cli/_utilities/_file_test_helper_parts/flextcliutilitiesfiletesthelpersmixin_part_03.py
- examples/ex_11_complete_integration.py
- tests/unit/_cases/test_files_cov/testsflextclifilescov_part_01.py
File Operations within flext-cli provide a robust, typed, and railway-oriented interface for interacting with the filesystem. The system is designed to handle common developer tasks such as reading and writing structured data (JSON, YAML, CSV), managing directory structures, and performing atomic file updates. By utilizing the p.Result pattern, the library ensures that file I/O operations are fallible but manageable without excessive try/except blocks in application logic.
Sources: src/flext_cli/services/file_tools.py:11-15, examples/ex_04_file_operations.py:18-22, examples/README.md:14-16
Architecture and Design
The file operations architecture follows a tiered approach. The public cli facade delegates to the FlextCliFileTools service, which in turn utilizes low-level utilities located in the u.Cli namespace (specifically FlextCliUtilitiesFiles). This separation ensures that the public API remains stable while the underlying implementation can be optimized or extended.
Component Relationship
The following diagram illustrates how an application interacts with the file system through the flext-cli layers.
This flow ensures consistent error handling and type validation across all file-related tasks.
Sources: src/flext_cli/services/file_tools.py:16-120, src/flext_cli/_utilities/_files_parts/flextcliutilitiesfiles_part_01.py:18-25
Core File Operations
The system supports a variety of formats and operation types, summarized in the table below:
| Feature | Description | Supported Formats |
|---|---|---|
| Structured I/O | Reading/Writing data directly to mappings or models. | JSON, YAML, CSV |
| Atomic Writes | Ensuring files are written completely or not at all. | Text |
| Path Management | Creating directories, deleting paths, and copying files. | All |
| Format Detection | Identifying file types based on extension or content. | .json, .yaml, .csv, .txt, .bin |
| Binary Access | Raw byte access for non-textual data. | Binary (.bin) |
Sources: src/flext_cli/services/file_tools.py:20-110, src/flext_cli/_utilities/_files_parts/flextcliutilitiesfiles_part_01.py:27-35
Structured Data Handling
A key strength of the module is its ability to handle structured data with built-in validation. For instance, read_json_model allows direct loading of JSON content into Pydantic models.
# Example: Reading a JSON file into a Pydantic model
from flext_cli import cli
from my_models import ConfigModel
result = cli.read_json_model("config.json", ConfigModel)
if result.success:
config = result.value
Sources: src/flext_cli/services/file_tools.py:44-48, src/flext_cli/_utilities/_files_parts/flextcliutilitiesfiles_part_01.py:82-90
Implementation Details
Format Detection Logic
The utility layer uses a mapping of suffixes to determine the appropriate handler for a file.
Format detection is critical for the load_file_auto_dict method, which automatically chooses between JSON and YAML parsers based on the file extension.
Sources: src/flext_cli/_utilities/_files_parts/flextcliutilitiesfiles_part_01.py:27-35, src/flext_cli/_utilities/_files_parts/flextcliutilitiesfiles_part_04.py:23-32
Utility Methods Summary
The FlextCliUtilitiesFiles class (accessible via u.Cli) implements the heavy lifting:
files_read_json(file_path): Reads UTF-8 text and validates it against theJSON_VALUE_ADAPTER.files_write_csv(file_path, rows): Handles the creation of CSV files using the standardcsv.writerwith proper newline handling.files_delete(file_path): An idempotent operation that removes files or directory trees (usingshutil.rmtree).ensure_dir(file_path): Recursively creates parent directories if they do not exist.
Sources: src/flext_cli/_utilities/_files_parts/flextcliutilitiesfiles_part_01.py:37-118, src/flext_cli/services/file_tools.py:20-23
Advanced Metadata and Comparison
For testing and maintenance scenarios, the module provides advanced helpers through the FlextCliUtilitiesFileTestHelpersMixin.
File Comparison Modes
The files_compare utility supports multiple comparison strategies:
content: Compares the full text content of two files.size: Efficiently compares files based on theirstat().st_size.hash: Compares SHA-256 digests of file contents.lines: Compares files line-by-line, with options toignore_ws(whitespace) orignore_case.
Information Extraction
The files_info method returns a comprehensive mapping of file attributes:
# Example info mapping keys
{
"exists": True,
"path": "/path/to/file",
"size": 1024,
"is_file": True,
"format": "json",
"hash": "...", # Optional
"parsed": {...} # Optional parsed content
}
Conclusion
The File Operations module in flext-cli provides a centralized, safe, and typed approach to filesystem interactions. By abstracting the complexities of encoding, atomic updates, and format-specific parsing into a clean service layer, it allows developers to focus on application logic while maintaining high reliability and consistent error handling across the CLI ecosystem.