Prepend
A command-line utility for prepending text to files. Uses buffered I/O and atomic file operations.
Installation
From Source
cd prepend
cargo build --release
Install Globally
Usage
Interactive Mode
Run without text argument to enter interactive mode:
Type or paste your text, then press Ctrl+D (Unix) or Ctrl+Z (Windows) on a new line to finish.
Command-Line Mode
Provide text directly as an argument:
Dry-Run Mode
Preview changes without modifying the file:
Examples
Add a comment header to a source file:
Add multiple lines interactively:
# Type your text
# Press Ctrl+D when done
Prepend to a log file:
Project Structure
prepend/
+-- src/
| +-- main.rs # Binary entry point
| +-- lib.rs # Core library implementation
| +-- constants.rs # Shared constants (ANSI colors, allowed extensions)
| +-- error.rs # Custom error types
+-- tests/
| +-- cli_tests.rs # End-to-end CLI tests (12 tests)
| +-- integration_tests.rs # Library integration tests (15 tests)
+-- Cargo.toml
The project is structured as both a binary and library crate. Core functionality is exposed through lib.rs for testing and potential reuse.
Library API
The library provides a well-documented public API with rustdoc comments:
Config- Configuration struct for prepend operationsparse_arguments()- Parse command-line arguments into a Configvalidate_file()- Validate file exists, is writable, and is a regular fileperform_prepend()- Safely prepend text to a file using atomic operationsprint_help()- Display help information
Error Handling
The library uses a custom PrependError type instead of strings for better error handling:
FileNotFound(String),
NotAFile(String),
NotWritable(String),
EmptyInput,
Io(io::Error),
}
This provides type-safe error handling with automatic conversion from io::Error.
Constants Module
Shared constants are centralized in constants.rs:
- ANSI color codes for terminal output
- Allowed file extensions list
- Buffer size configuration
Supported File Types
The tool validates file extensions and supports common text file types:
- Text files: txt, log, md
- Config files: conf, yaml, json, cfg, ini, csv
- Scripts: sh, py, js
- Source code: c, cpp, h, rs
Files with uncommon extensions will show a warning but can still be processed.
Technical Details
Performance
- Uses 64KB buffered I/O for efficient processing
- Handles large files without memory issues
- Atomic file replacement prevents corruption
Safety
- Validates file existence and permissions before modification
- Creates temporary file in same directory as target
- Atomic rename operation ensures data integrity
- Automatic cleanup on failure
Testing
Run the test suite:
Run tests with output:
Run specific test:
Check code quality:
cargo fmt
Test Coverage
- 12 CLI tests covering command-line interface behavior
- 15 integration tests covering core library functionality
- Tests include edge cases: empty files, large files, binary files, special characters
License
MIT License. See LICENSE file for details.