### CLI Usage Examples (Shell) Source: https://github.com/peteretelej/tree/blob/main/_autodocs/OVERVIEW.md Provides examples of how to use the Rust-Tree CLI binary with various flags and arguments for directory traversal and filtering. ```sh tree -L 2 -a -s --color . ``` ```sh tree --pattern="*.rs" --exclude="target" --prune src/ ``` -------------------------------- ### CLI Usage Examples with Short Flags Source: https://github.com/peteretelej/tree/blob/main/README.md Demonstrates common command-line usage patterns for the tree CLI using short flag notations. These examples show filtering by level, including all files, and applying include/exclude patterns. ```sh # Using short flags ./tree -L 2 . ./tree -a -f -s . ./tree -P "*.txt" -I "*.log" . ``` -------------------------------- ### Rust Icon Management Source: https://github.com/peteretelej/tree/blob/main/_autodocs/MANIFEST.txt Examples of initializing and using the IconManager for file path icon lookups. ```Rust use rust_tree::icons::IconManager; let icon_manager = IconManager::new().unwrap(); let icon = icon_manager.get_icon_for_path("/path/to/file.txt"); println!("{:?}", icon); ``` ```Rust use rust_tree::icons::IconManager; let icon_manager = IconManager::from_file("custom_theme.json").unwrap(); let icon = icon_manager.get_icon_for_path("/path/to/directory"); println!("{:?}", icon); ``` -------------------------------- ### Rust Display Formatting Source: https://github.com/peteretelej/tree/blob/main/_autodocs/MANIFEST.txt Examples of formatting file permissions and colorizing output. ```Rust use rust_tree::display::format_permissions_unix; let permissions = 0o755; let formatted = format_permissions_unix(permissions); println!("{}", formatted); ``` ```Rust use rust_tree::display::colorize; let text = "Hello, world!"; let colored_text = colorize(text, "blue"); println!("{}", colored_text); ``` -------------------------------- ### Rust Library Usage Examples Source: https://github.com/peteretelej/tree/blob/main/_autodocs/MANIFEST.txt Demonstrates various ways to use the Rust Tree library for file system traversal and manipulation. ```Rust use rust_tree::tree::TreeOptions; let options = TreeOptions::default(); let tree = rust_tree::tree::build_virtual_tree(".", &options).unwrap(); println!("{}", tree); ``` ```Rust use rust_tree::tree::TreeOptions; let options = TreeOptions::default(); let entries = rust_tree::traversal::list_directory(".", &options).unwrap(); for entry in entries { println!("{:?}", entry); } ``` ```Rust use rust_tree::tree::TreeOptions; let options = TreeOptions::default(); let output = rust_tree::traversal::list_directory_as_string(".", &options).unwrap(); println!("{}", output); ``` ```Rust use rust_tree::tree::TreeOptions; let options = TreeOptions::default(); let tree = rust_tree::fromfile::build_virtual_tree("archive.tar.gz", &options).unwrap(); println!("{}", tree); ``` ```Rust use rust_tree::tree::TreeOptions; let options = TreeOptions::default(); let tree = rust_tree::fromfile::build_virtual_tree("archive.zip", &options).unwrap(); println!("{}", tree); ``` ```Rust use rust_tree::tree::TreeOptions; let options = TreeOptions::default(); let tree = rust_tree::fromfile::build_virtual_tree("archive.7z", &options).unwrap(); println!("{}", tree); ``` ```Rust use rust_tree::tree::TreeOptions; let options = TreeOptions::default(); let tree = rust_tree::fromfile::build_virtual_tree("archive.rar", &options).unwrap(); println!("{}", tree); ``` ```Rust use rust_tree::tree::TreeOptions; let options = TreeOptions::default(); let tree = rust_tree::fromfile::build_virtual_tree("input.txt", &options).unwrap(); println!("{}", tree); ``` ```Rust use rust_tree::tree::TreeOptions; let options = TreeOptions::default(); let tree = rust_tree::fromfile::build_virtual_tree("-", &options).unwrap(); println!("{}", tree); ``` ```Rust use rust_tree::tree::TreeOptions; let options = TreeOptions::default(); let tree = rust_tree::fromfile::build_virtual_tree("path/to/dir", &options).unwrap(); println!("{}", tree); ``` ```Rust use rust_tree::tree::TreeOptions; let options = TreeOptions::default(); let tree = rust_tree::fromfile::build_virtual_tree("path/to/file.txt", &options).unwrap(); println!("{}", tree); ``` ```Rust use rust_tree::tree::TreeOptions; let options = TreeOptions::default(); let tree = rust_tree::fromfile::build_virtual_tree("path/to/archive.tar.gz", &options).unwrap(); println!("{}", tree); ``` -------------------------------- ### Configuration-Driven Architecture Example Source: https://github.com/peteretelej/tree/blob/main/_autodocs/architecture.md Demonstrates how to initialize `TreeOptions` and pass them to a function for directory listing. This pattern centralizes behavior control within the `TreeOptions` struct. ```rust let options = TreeOptions { /* 25 fields */ }; list_directory(".", &options)?; ``` -------------------------------- ### Install Rust Tree CLI from GitHub Source: https://github.com/peteretelej/tree/blob/main/README.md Install the latest development version of the Rust Tree CLI directly from its GitHub repository using Cargo. This requires Git to be installed. ```sh cargo install --git https://github.com/peteretelej/tree.git --locked ``` -------------------------------- ### CLI Usage Examples with Long Flags Source: https://github.com/peteretelej/tree/blob/main/README.md Demonstrates common command-line usage patterns for the tree CLI using long flag notations. These examples mirror the short flag examples but use descriptive names for clarity. ```sh # Using long flags ./tree --level=2 . ./tree --all --full-path --size . ./tree --pattern="*.txt" --exclude="*.log" . ``` -------------------------------- ### Rust Path Normalization Source: https://github.com/peteretelej/tree/blob/main/_autodocs/MANIFEST.txt Example of normalizing file paths for consistent handling. ```Rust use rust_tree::fromfile::normalize_path; let path = "./path/to/../file.txt"; let normalized = normalize_path(path); println!("{}", normalized); ``` -------------------------------- ### Install Rust Tree CLI with Cargo Source: https://github.com/peteretelej/tree/blob/main/README.md Install the stable release of the Rust Tree CLI from crates.io using Cargo. Ensure you have Rust and Cargo installed. ```sh cargo install rust_tree --locked ``` -------------------------------- ### CLI Usage Example with Prune Option Source: https://github.com/peteretelej/tree/blob/main/README.md Shows how to use the --prune flag in conjunction with pattern matching to hide directories that do not contain any matching files. This helps in cleaning up the output. ```sh # Hide directories that have no matching files ./tree --pattern="*.txt" --exclude="*.log" --prune . ``` -------------------------------- ### Rust Error Handling Examples Source: https://github.com/peteretelej/tree/blob/main/_autodocs/MANIFEST.txt Illustrates how to detect and handle specific error types like broken pipes. ```Rust use rust_tree::errors::ErrorKind; use std::io::{self, ErrorKind as IoErrorKind}; fn handle_error(e: io::Error) { match e.kind() { IoErrorKind::PermissionDenied => println!("Permission denied."), IoErrorKind::NotFound => println!("Not found."), _ => println!("An unexpected error occurred."), } } ``` ```Rust use rust_tree::utils::is_broken_pipe_error; use std::io::Error; let err = Error::new(std::io::ErrorKind::Other, "some error"); if is_broken_pipe_error(&err) { println!("This is a broken pipe."); } else { println!("This is not a broken pipe."); } ``` -------------------------------- ### Multi-Pattern Parsing Example Source: https://github.com/peteretelej/tree/blob/main/_autodocs/cli.md Demonstrates how multiple patterns for `-P` and `-I` arguments are parsed using pipe separation. Each pattern is trimmed and filtered before parsing. ```sh tree -P "*.rs|*.toml" src/ ``` -------------------------------- ### Use Rust Tree as a Crate - Basic Directory Listing Source: https://github.com/peteretelej/tree/blob/main/README.md Example of using the `rust_tree` crate in a Rust project to list directory contents. It demonstrates setting basic options like `full_path` and `no_indent`. ```rust use rust_tree::tree::{list_directory, options::TreeOptions}; fn main() { let path = "."; let options = TreeOptions { full_path: true, no_indent: true, ..Default::default() }; list_directory(path, &options).unwrap(); } ``` -------------------------------- ### IconManager::new Source: https://github.com/peteretelej/tree/blob/main/_autodocs/icons.md Creates a new IconManager instance with the embedded default icon theme. This is the primary way to get started with icon management. ```APIDOC ## IconManager::new ### Description Creates an IconManager with the embedded default icon theme. This method loads the default icon mappings from the binary. ### Method `new()` ### Returns - `IconManager` - An instance of `IconManager` with the default theme loaded. ### Behavior Loads embedded `DEFAULT_ICON_THEME` JSON from the binary, parses it, and wraps it in an `IconManager`. ### Example ```rust use rust_tree::rust_tree::icons::IconManager; use std::path::Path; let manager = IconManager::new(); let icon = manager.get_icon_for_path(Path::new("Cargo.toml")); println!("{}", icon); // Prints: "📦" ``` ``` -------------------------------- ### Use Rust Tree as a Crate - Get Output as String Source: https://github.com/peteretelej/tree/blob/main/README.md Demonstrates using the `list_directory_as_string` function from the `rust_tree` crate to capture the tree output as a String. This is useful for further processing or logging. ```rust use rust_tree::tree::list_directory_as_string; fn main() { let path = "."; let tree_output = list_directory_as_string(path, &Default::default()).unwrap(); println!("{}", tree_output); } ``` -------------------------------- ### Create an empty GitignoreRules set Source: https://github.com/peteretelej/tree/blob/main/_autodocs/gitignore.md Use `GitignoreRules::new()` to create an empty rule set. This is useful for starting with no exclusions. ```rust use rust_tree::rust_tree::gitignore::GitignoreRules; let rules = GitignoreRules::new(); assert!(rules.is_empty()); ``` -------------------------------- ### Build Rust Tree CLI from Source Source: https://github.com/peteretelej/tree/blob/main/README.md Compile the Rust Tree CLI from its source code. This method requires Git, Rust, and Cargo to be installed. The compiled binary will be in the target/release directory. ```sh git clone https://github.com/peteretelej/tree.git cd tree cargo build --release ./target/release/tree -L 2 . # or use --level=2 # copy tree binary to a PATH directory ``` -------------------------------- ### Create IconManager with Default Theme Source: https://github.com/peteretelej/tree/blob/main/_autodocs/icons.md Instantiates an IconManager using the embedded default icon theme. This is useful for quick setup without needing a custom theme file. ```rust use rust_tree::rust_tree::icons::IconManager; let manager = IconManager::new(); let icon = manager.get_icon_for_path(Path::new("Cargo.toml")); println!("{}", icon); // Prints: "📦" ``` -------------------------------- ### Analyze Directory Structure with Rust Tree Source: https://github.com/peteretelej/tree/blob/main/_autodocs/examples.md Employ `list_directory_as_string` to obtain directory structure information, then parse the output to identify specific file patterns. This example filters for lines containing file size information. ```rust use rust_tree::rust_tree::traversal::list_directory_as_string; use rust_tree::rust_tree::options::TreeOptions; fn analyze_structure(path: &str) -> std::io::Result<()> { let options = TreeOptions { human_readable: true, ..Default::default() }; let output = list_directory_as_string(path, &options)?; for line in output.lines() { if line.contains("[") && line.contains("]") { println!("File with size: {}", line); } } Ok(()) } ``` -------------------------------- ### Archive Listing via Stdin Source: https://github.com/peteretelej/tree/blob/main/_autodocs/examples.md Parses and displays tar archive contents piped via standard input. This is a shell command example. ```sh tar -tvf archive.tar | tree --fromfile . ``` -------------------------------- ### Custom Icon Theme Support in Rust Source: https://github.com/peteretelej/tree/blob/main/_autodocs/examples.md Enables icon display, though custom icon themes require deeper integration beyond this example. Set the `icons` option. ```rust use rust_tree::rust_tree::traversal::list_directory; use rust_tree::rust_tree::options::TreeOptions; use rust_tree::rust_tree::icons::IconManager; fn main() -> std::io::Result<()> { // In a real app, you'd replace IconManager usage // (requires code integration, no CLI flag for this) let options = TreeOptions { icons: true, ..Default::default() }; list_directory(".", &options)?; Ok(()) } ``` -------------------------------- ### Use Rust Tree as a Crate - Human Readable File Size Source: https://github.com/peteretelej/tree/blob/main/README.md Example of using the `bytes_to_human_readable` utility function from the `rust_tree` crate to format file sizes into a human-readable string. This requires standard file system operations. ```rust use rust_tree::utils::bytes_to_human_readable; use std::fs; fn main() { let metadata = fs::metadata("my_file.txt").unwrap(); let size = metadata.len(); let size_str = bytes_to_human_readable(size); println!("File size: {}", size_str); } ``` -------------------------------- ### Graceful Handling of BrokenPipe Error in Piped Output Source: https://github.com/peteretelej/tree/blob/main/_autodocs/errors.md This example demonstrates special handling for `io::ErrorKind::BrokenPipe` errors, which can occur when piping output to another command that closes the pipe early. It ensures the program exits with a success code (0) in such cases, adhering to Unix conventions. ```rust match run_cli() { Ok(()) => {} Err(err) => { if is_broken_pipe_error(&err) { std::process::exit(0); // Success exit code } else { eprintln!("Error: {err}"); std::process::exit(1); // Failure exit code } } } ``` -------------------------------- ### Handle Traversal Errors in Application Code Source: https://github.com/peteretelej/tree/blob/main/_autodocs/errors.md In application code, handle errors during directory traversal. This example demonstrates checking for specific errors like broken pipes to exit gracefully, or printing a general error message and exiting with a non-zero status for other errors. ```rust match list_directory(".", &options) { Ok(()) => println!("Success"), Err(e) => { if is_broken_pipe_error(&e) { std::process::exit(0); } else { eprintln!("Error: {}", e); std::process::exit(1); } } } ``` -------------------------------- ### List Directory with Options (Rust Library) Source: https://github.com/peteretelej/tree/blob/main/_autodocs/OVERVIEW.md Demonstrates how to use the `list_directory` function from the Rust-Tree library with custom `TreeOptions`. Ensure necessary imports are present. ```rust use rust_tree::rust_tree::traversal::list_directory; use rust_tree::rust_tree::options::TreeOptions; let options = TreeOptions { full_path: true, human_readable: true, ..Default::default() }; list_directory(".", &options)?; ``` -------------------------------- ### Rust Gitignore Rule Handling Source: https://github.com/peteretelej/tree/blob/main/_autodocs/MANIFEST.txt Demonstrates creating, loading, and checking paths against gitignore rules. ```Rust use rust_tree::gitignore::GitignoreRules; let mut rules = GitignoreRules::new(); rules.load_for_root(".gitignore").unwrap(); rules.extend_with_dir("subdir/.gitignore").unwrap(); let is_ignored = rules.is_ignored("path/to/file"); println!("Is ignored: {}", is_ignored); ``` ```Rust use rust_tree::gitignore::GitignoreRules; let mut rules = GitignoreRules::new(); rules.load_for_root(".gitignore").unwrap(); let is_ignored = rules.is_ignored("some/file.txt"); println!("Is ignored: {}", is_ignored); ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/peteretelej/tree/blob/main/README.md Execute the tree command-line tool. The basic syntax includes optional flags and options, followed by the target path. Use --help for a full list of options. ```sh ./tree [FLAGS] [OPTIONS] [PATH] # Get help and see all available options ./tree --help ``` -------------------------------- ### Main CLI Entry Point Source: https://github.com/peteretelej/tree/blob/main/_autodocs/cli.md The main entry point for the CLI application. It parses command-line arguments, converts them to `TreeOptions`, and then calls `list_directory()`. Any errors encountered during parsing or execution are propagated as `io::Error`. ```rust pub fn run_cli() -> io::Result<()> ``` -------------------------------- ### Build Directory Browser with Rust Tree Source: https://github.com/peteretelej/tree/blob/main/_autodocs/examples.md Use `list_directory_as_string` with `TreeOptions` to generate a string representation of a directory's structure. Configure options like traversal depth and whether to include all files. ```rust use rust_tree::rust_tree::traversal::list_directory_as_string; use rust_tree::rust_tree::options::TreeOptions; fn get_tree(path: &str, level: u32) -> std::io::Result { let options = TreeOptions { level: Some(level), full_path: true, all_files: true, ..Default::default() }; list_directory_as_string(path, &options) } fn main() -> std::io::Result<()> { let tree = get_tree(".", 3)?; println!("{}", tree); Ok(()) } ``` -------------------------------- ### Basic Directory Listing in Rust Source: https://github.com/peteretelej/tree/blob/main/_autodocs/examples.md Lists the current directory using default options. Requires importing `list_directory` and `TreeOptions`. ```rust use rust_tree::rust_tree::traversal::list_directory; use rust_tree::rust_tree::options::TreeOptions; fn main() -> std::io::Result<()> { let options = TreeOptions::default(); list_directory(".", &options)?; Ok(()) } ``` -------------------------------- ### Rust CLI Pattern Parsing Source: https://github.com/peteretelej/tree/blob/main/_autodocs/MANIFEST.txt Demonstrates parsing glob patterns for file selection in the CLI. ```Rust use rust_tree::cli::parse_glob_pattern; let pattern = parse_glob_pattern("*.rs").unwrap(); println!("{:?}", pattern); ``` ```Rust use rust_tree::cli::parse_glob_pattern; let pattern = parse_glob_pattern("src/**/*.rs").unwrap(); println!("{:?}", pattern); ``` ```Rust use rust_tree::cli::parse_glob_pattern; let pattern = parse_glob_pattern("!*.lock").unwrap(); println!("{:?}", pattern); ``` ```Rust use rust_tree::cli::parse_glob_pattern; let pattern = parse_glob_pattern("*.rs").unwrap(); let pattern2 = parse_glob_pattern("!*.rs.bak").unwrap(); println!("{:?}", vec![pattern, pattern2]); ``` -------------------------------- ### Create IconManager Instance Source: https://github.com/peteretelej/tree/blob/main/_autodocs/types.md Instantiate IconManager with either the default theme or a custom theme loaded from a file. ```rust let mgr = IconManager::new(); // Default theme ``` ```rust let mgr = IconManager::from_file(path)?; // Custom theme ``` -------------------------------- ### Handle Pattern Validation Errors in Application Code Source: https://github.com/peteretelej/tree/blob/main/_autodocs/errors.md In application code, validate patterns using a match statement. This example shows how to handle a successful pattern parse or log an error message if the pattern is invalid. ```rust match parse_glob_pattern("*.rs") { Ok(p) => { /* use pattern */ }, Err(e) => eprintln!("Invalid pattern: {}", e), } ``` -------------------------------- ### Load and Check Gitignore Rules Source: https://github.com/peteretelej/tree/blob/main/_autodocs/gitignore.md Demonstrates how to load gitignore rules for a given root path and check if a specific path is ignored. This is useful for custom logic outside of direct directory traversal. ```rust use std::path::Path; use rust_tree::rust_tree::gitignore::GitignoreRules; let rules = GitignoreRules::load_for_root(Path::new(".")); let ignored = rules.is_ignored(Path::new("target"), true); if ignored { println!("target/ is ignored"); } ``` -------------------------------- ### Check Metadata Error Before Use in Library Code Source: https://github.com/peteretelej/tree/blob/main/_autodocs/errors.md In library code, check for errors when accessing file metadata before proceeding. This example logs a warning and allows the program to continue with a default or missing value if metadata cannot be read. ```rust if let Err(e) = fs::metadata(&path) { eprintln!("Warning: Could not read metadata for {:?}: {}", path, e); // Continue with default/missing value } ``` -------------------------------- ### Run Pre-Push Script Source: https://github.com/peteretelej/tree/blob/main/README.md Execute the `./scripts/pre-push` script to ensure code quality and adherence to project standards before pushing changes. Consider copying this script to your local Git hooks directory for automatic execution. ```bash ./scripts/pre-push ``` -------------------------------- ### Create GitignoreRules Instance Source: https://github.com/peteretelej/tree/blob/main/_autodocs/types.md Instantiate GitignoreRules either with default settings or by loading rules for a specific root path. ```rust let rules = GitignoreRules::new(); ``` ```rust let rules = GitignoreRules::load_for_root(path); ``` -------------------------------- ### Get Icon for a Specific File Path Source: https://github.com/peteretelej/tree/blob/main/_autodocs/icons.md Retrieves the appropriate icon for a given file or directory path. The lookup follows a specific order: well-known names, directory check, file extension, and finally a fallback generic icon. ```rust use std::path::Path; let icon1 = manager.get_icon_for_path(Path::new("Cargo.toml")); // Returns: "📦" let icon2 = manager.get_icon_for_path(Path::new("src")); // Returns: "📁" let icon3 = manager.get_icon_for_path(Path::new("main.rs")); // Returns: "🦀" let icon4 = manager.get_icon_for_path(Path::new("unknown.xyz")); // Returns: "📄" ``` -------------------------------- ### TreeOptions Construction with Defaults Source: https://github.com/peteretelej/tree/blob/main/_autodocs/options.md Demonstrates how to construct a TreeOptions struct, utilizing default values for unspecified fields. This is useful for setting up custom configurations while relying on sensible defaults for most options. ```rust let options = TreeOptions { all_files: true, level: Some(3), full_path: false, print_size: true, ..Default::default() // Use default for remaining fields }; ``` -------------------------------- ### Copy Pre-Push Script to Git Hooks Source: https://github.com/peteretelej/tree/blob/main/README.md Copy the project's `pre-push` script to the local `.git/hooks/` directory to enable it as a pre-push Git hook. ```bash cp scripts/pre-push .git/hooks/pre-push ``` -------------------------------- ### Icon Manager Methods Source: https://github.com/peteretelej/tree/blob/main/_autodocs/MANIFEST.txt Methods for initializing and using the IconManager to retrieve icons for file paths. ```APIDOC ## IconManager::new() ### Description Creates a new `IconManager` with the default icon theme. ### Method (Not specified, likely a Rust function call) ### Endpoint (Not applicable, Rust function) ### Parameters (Details not provided in source) ### Request Example (Not applicable) ### Response (Details not provided in source) ## IconManager::from_file() ### Description Creates a new `IconManager` by loading a custom icon theme from a file. ### Method (Not specified, likely a Rust function call) ### Endpoint (Not applicable, Rust function) ### Parameters (Details not provided in source) ### Request Example (Not applicable) ### Response (Details not provided in source) ## IconManager::get_icon_for_path() ### Description Retrieves the appropriate icon for a given file path based on the loaded theme. ### Method (Not specified, likely a Rust function call) ### Endpoint (Not applicable, Rust function) ### Parameters (Details not provided in source) ### Request Example (Not applicable) ### Response (Details not provided in source) ``` -------------------------------- ### Directory Traversal with Gitignore Enabled Source: https://github.com/peteretelej/tree/blob/main/_autodocs/gitignore.md Shows how to perform directory traversal while respecting .gitignore rules. This is typically enabled by setting the `gitignore` option to true in `TreeOptions`. ```rust use rust_tree::rust_tree::traversal::list_directory; use rust_tree::rust_tree::options::TreeOptions; let options = TreeOptions { gitignore: true, ..Default::default() }; list_directory(".", &options)?; // Will respect .gitignore rules ``` -------------------------------- ### Rust: Format Entry Line Source: https://github.com/peteretelej/tree/blob/main/_autodocs/traversal.md Formats a single file or directory entry into a string suitable for tree output. Includes options for permissions, icons, size, and modification date. ```rust fn format_entry_line( writer: &mut W, root_path: P, current_path: &Path, options: &TreeOptions, depth: usize, stats: &mut (u64, u64), indent_state: &[bool], icon_manager: &IconManager, parent_matched: bool, gitignore_rules: &GitignoreRules, ) -> io::Result ``` -------------------------------- ### Build Rust Tree CLI for Windows 7 Source: https://github.com/peteretelej/tree/blob/main/README.md Build the Rust Tree CLI with specific Rust version (1.75.0) and a provided lockfile for Windows 7 compatibility. This requires rustup to manage toolchains. ```sh rustup install 1.75.0 cp Cargo-win7.lock Cargo.lock rustup run 1.75.0 cargo build --release # restore default rust toolchain version rustup default stable ``` -------------------------------- ### Full Path and Human-Readable Sizes in Rust Source: https://github.com/peteretelej/tree/blob/main/_autodocs/examples.md Displays full paths and formats file sizes in a human-readable way. Set `full_path`, `print_size`, and `human_readable` options. ```rust use rust_tree::rust_tree::traversal::list_directory; use rust_tree::rust_tree::options::TreeOptions; fn main() -> std::io::Result<()> { let options = TreeOptions { full_path: true, print_size: true, human_readable: true, ..Default::default() }; list_directory("src", &options)?; Ok(()) } ``` -------------------------------- ### Write Directory Listing to File Source: https://github.com/peteretelej/tree/blob/main/_autodocs/examples.md Saves the output of a directory listing to a specified file. Configure options like output file path, full path inclusion, and human-readable sizes. ```rust use rust_tree::rust_tree::traversal::list_directory; use rust_tree::rust_tree::options::TreeOptions; fn main() -> std::io::Result<()> { let options = TreeOptions { output_file: Some("tree_output.txt".to_string()), full_path: true, human_readable: true, ..Default::default() }; list_directory(".", &options)?; println!("Output written to tree_output.txt"); Ok(()) } ``` -------------------------------- ### Run CLI with Provided Arguments Source: https://github.com/peteretelej/tree/blob/main/_autodocs/cli.md Executes the CLI functionality with a provided vector of string arguments, useful for testing. It uses `Cli::try_parse_from()` to parse the arguments instead of reading from the environment. ```rust pub fn run_with_args(args: Vec) -> io::Result<()> ``` ```rust let args = vec![ "tree".to_string(), "-L".to_string(), "2".to_string(), ".".to_string(), ]; run_with_args(args)?; ``` -------------------------------- ### ANSI Color Formatting with ansi_term Source: https://github.com/peteretelej/tree/blob/main/_autodocs/display.md Demonstrates how to apply various ANSI color and style combinations to text using the `ansi_term` crate. Ensure the `ansi_term` crate is added as a dependency. ```rust use ansi_term::Colour::{Blue, Cyan, Green, Red, Yellow}; Blue.bold().paint(text).to_string() // Blue bold Cyan.paint(text).to_string() // Cyan Green.paint(text).to_string() // Green Red.paint(text).to_string() // Red Yellow.paint(text).to_string() // Yellow ``` -------------------------------- ### Cli Structure Source: https://github.com/peteretelej/tree/blob/main/_autodocs/types.md Represents command-line arguments parsed using clap. ```APIDOC ## Cli ### Description Parses command-line arguments using the clap library. ### Fields - `path` (String): The path to process. - `all_files` (bool): Whether to include all files. - `level` (Option): Optional recursion level. ``` -------------------------------- ### Define Custom Theme Format Source: https://github.com/peteretelej/tree/blob/main/_autodocs/icons.md Illustrates the JSON structure for a custom icon theme. This format includes mappings for well-known filenames, file extensions, and generic directory/file icons. ```json { "well_known": { "cargo.toml": "📦", "dockerfile": "🐳" }, "extensions": { "rs": "🦀", "py": "🐍" }, "icons": { "dir": "📁", "file": "📄" } } ``` -------------------------------- ### run_cli Source: https://github.com/peteretelej/tree/blob/main/_autodocs/cli.md The main entry point for the CLI application. It parses command-line arguments, converts them into `TreeOptions`, and initiates the directory traversal. ```APIDOC ## run_cli ### Description Main CLI entry point. This function orchestrates the entire command-line interface operation, from argument parsing to executing the core tree listing logic. ### Parameters None. This function reads command-line arguments directly from the environment using `std::env::args()`. ### Returns - **io::Result<()>** - Returns `Ok(())` upon successful execution, or an `io::Error` if any part of the process fails, such as argument parsing or file system operations. ### Behavior 1. Parses command-line arguments using `Cli::parse()`. 2. Converts the parsed arguments into `TreeOptions` via `cli_to_options()`. 3. Calls `list_directory()` with the parsed path and options. 4. Propagates any encountered errors, wrapping them in `io::Error`. ### Used by This function serves as the binary's entry point, typically called from `src/main.rs`. ``` -------------------------------- ### Format and Check Code with Cargo Source: https://github.com/peteretelej/tree/blob/main/README.md Use `cargo fmt` to format your Rust code according to project standards and `cargo fmt --check` to verify that the formatting is correct before committing. ```bash cargo fmt cargo fmt --check ``` -------------------------------- ### run_with_args Source: https://github.com/peteretelej/tree/blob/main/_autodocs/cli.md Executes the CLI logic with a provided vector of arguments, making it suitable for testing and programmatic invocation. It mirrors `run_cli` but allows explicit argument passing. ```APIDOC ## run_with_args ### Description Execute the CLI functionality with a specific set of arguments provided as a vector of strings. This is particularly useful for automated testing scenarios or when programmatically controlling the CLI behavior. ### Parameters #### Path Parameters - **args** (Vec) - Required - A vector of strings representing the command-line arguments, similar to `std::env::args()`. The first element should be the program name. ### Returns - **io::Result<()>** - Returns `Ok(())` on successful execution, or an `io::Error` if any errors occur during argument parsing or execution. ### Behavior - Functionally identical to `run_cli()` but bypasses reading from `std::env::args()`. - Uses `Cli::try_parse_from(args)` for argument parsing instead of `Cli::parse()`. ### Example ```rust let args = vec![ "tree".to_string(), "-L".to_string(), "2".to_string(), ".".to_string(), ]; run_with_args(args)?; ``` ``` -------------------------------- ### IconManager::from_file Source: https://github.com/peteretelej/tree/blob/main/_autodocs/icons.md Loads a custom icon theme from a JSON file. Allows for user-defined icon mappings. ```APIDOC ## IconManager::from_file ### Description Loads an icon theme from a JSON file on disk, allowing for custom icon mappings. This method is useful for users who want to define their own icons. ### Method `from_file(path: &str) -> Result>` ### Parameters #### Path Parameters - **path** (`&str`) - Required - File path to custom icon theme JSON ### Returns - `Result>` - Returns `Ok(IconManager)` on success, or `Err(Box)` if the file is not found or the JSON is invalid. ### Behavior 1. Reads file contents as UTF-8 string. 2. Deserializes JSON into `IconTheme` struct. 3. Returns wrapped in `IconManager` if successful. ### Custom Theme Format ```json { "well_known": { "cargo.toml": "📦", "dockerfile": "🐳" }, "extensions": { "rs": "🦀", "py": "🐍" }, "icons": { "dir": "📁", "file": "📄" } } ``` ### Error Handling - File not found → `io::Error` - Invalid JSON → `serde_json::Error` - Both wrapped in `Box` ### Example ```rust // Assuming the file exists and is valid JSON let manager = IconManager::from_file("/path/to/custom_theme.json")?; ``` ``` -------------------------------- ### Filesystem Traversal Data Flow Source: https://github.com/peteretelej/tree/blob/main/_autodocs/architecture.md Detailed data flow for the standard filesystem traversal path, from command parsing to directory listing and formatting. ```tree user command │ ├─→ Cli::parse() [cli module] │ (parse command-line args) │ ├─→ cli_to_options() [cli module] │ (validate patterns, convert to TreeOptions) │ └─→ list_directory(path, opts) [traversal module] │ ├─→ create_writer() [traversal module] │ (open file or use stdout) │ ├─→ traverse_directory() [traversal module (recursive)] │ ├─→ fs::read_dir(current_path) │ ├─→ should_skip_entry() [traversal module] │ │ ├─→ Check hidden files (all_files flag) │ │ ├─→ Check gitignore rules │ │ ├─→ Check exclude patterns │ │ ├─→ Check include patterns │ │ └─→ Check dir_only flag │ │ │ ├─→ Sort entries (alphabetical or by mtime) │ │ │ ├─→ format_entry_line() [traversal module] │ │ ├─→ colorize() [display module] │ │ ├─→ get_icon_for_path() [icons module] │ │ ├─→ bytes_to_human_readable() [utils module] │ │ └─→ format_permissions_unix() [display module] │ │ │ ├─→ writeln!(writer, line) │ │ │ └─→ traverse_directory() (recursive) [depth+1] │ ├─→ Write summary (if !no_report) │ └─→ writer.flush() ``` -------------------------------- ### Handle NotFound Error for Nonexistent Paths Source: https://github.com/peteretelej/tree/blob/main/_autodocs/errors.md This code shows how to specifically catch and handle `io::ErrorKind::NotFound` when a specified path does not exist. This is common when listing directories or reading files. ```rust match list_directory("nonexistent/path", &options) { Err(e) if e.kind() == io::ErrorKind::NotFound => { eprintln!("Path not found: {}", e); } Err(e) => { /* other errors */ } Ok(()) => {} } ``` -------------------------------- ### Traverse Directory and Write Output Source: https://github.com/peteretelej/tree/blob/main/_autodocs/traversal.md Use `list_directory` to traverse a directory and write the formatted tree to stdout or a file. Configure output format and filtering using `TreeOptions`. This function is suitable for direct output to the console or files. ```rust use rust_tree::rust_tree::traversal::list_directory; use rust_tree::rust_tree::options::TreeOptions; let options = TreeOptions { all_files: true, level: Some(2), print_size: true, ..Default::default() }; list_directory(".", &options)?; ``` -------------------------------- ### Traverse Directory and Return as String Source: https://github.com/peteretelej/tree/blob/main/_autodocs/traversal.md Use `list_directory_as_string` to traverse a directory and capture the formatted tree output as a `String`. This is useful for further processing or analysis of the tree data in memory. Be mindful of potential memory overhead for large trees. ```rust use rust_tree::rust_tree::traversal::list_directory_as_string; use rust_tree::rust_tree::options::TreeOptions; let options = TreeOptions { full_path: true, ..Default::default() }; let output = list_directory_as_string(".", &options)?; println!("Tree output:\n{}", output); ``` -------------------------------- ### IconManager Methods Source: https://github.com/peteretelej/tree/blob/main/_autodocs/types.md Provides methods for managing and looking up file type icons. ```APIDOC ## IconManager ### Description Manages file type icons using themes. ### Methods - `new()`: Create with default embedded theme. - `from_file(path)`: Load custom theme from JSON. - `get_icon_for_path(path)`: Look up icon for file path. ``` -------------------------------- ### Project Module Organization Source: https://github.com/peteretelej/tree/blob/main/_autodocs/architecture.md Overview of the project's directory structure and the responsibilities of each module. ```tree rust_tree/ ├── cli — Argument parsing, validation, CLI execution entry point ├── options — TreeOptions configuration struct ├── traversal — Core directory walking and tree formatting ├── display — Colorization and permissions formatting ├── utils — Size formatting and error diagnosis utilities ├── icons — File type icon lookup and management ├── fromfile — Archive listing parsing and virtual tree rendering └── gitignore — .gitignore pattern matching and rule application ``` -------------------------------- ### GitignoreRules::new Source: https://github.com/peteretelej/tree/blob/main/_autodocs/gitignore.md Creates an empty rule set for gitignore patterns. This is useful for initializing a new set of rules before loading any from files. ```APIDOC ## GitignoreRules::new ### Description Create an empty rule set with no exclusions. ### Method `GitignoreRules::new()` ### Returns `GitignoreRules` with empty rules vector. ### Example ```rust use rust_tree::rust_tree::gitignore::GitignoreRules; let rules = GitignoreRules::new(); assert!(rules.is_empty()); ``` ``` -------------------------------- ### Load IconManager from Custom JSON File Source: https://github.com/peteretelej/tree/blob/main/_autodocs/icons.md Loads a custom icon theme from a specified JSON file path. This allows for flexible customization of file type icons. ```rust let manager = IconManager::from_file("/path/to/custom_theme.json")?; ``` -------------------------------- ### Load Gitignore Rules from Root Directory Source: https://github.com/peteretelej/tree/blob/main/_autodocs/gitignore.md Use `GitignoreRules::load_for_root` to load rules from `.gitignore` and `.ignore` files in the specified root directory and its ancestors. This method handles precedence between the two file types. ```rust use std::path::Path; let rules = GitignoreRules::load_for_root(Path::new(".")); // Loads rules from ./.gitignore and ./.ignore ``` -------------------------------- ### Capture Tree Output as String in Rust Source: https://github.com/peteretelej/tree/blob/main/_autodocs/examples.md Retrieves the tree directory listing as a string for further processing. Use `list_directory_as_string`. ```rust use rust_tree::rust_tree::traversal::list_directory_as_string; use rust_tree::rust_tree::options::TreeOptions; fn main() -> std::io::Result<()> { let options = TreeOptions { all_files: true, ..Default::default() }; let output = list_directory_as_string(".", &options)?; println!("Tree output:\n{}", output); // Process output further let lines: Vec<&str> = output.lines().collect(); println!("Total lines: {}", lines.len()); Ok(()) } ``` -------------------------------- ### Release New Version: Update Cargo.toml, Commit, and Tag Source: https://github.com/peteretelej/tree/blob/main/README.md Steps to release a new version: update the version number in `Cargo.toml`, commit the change, and create an annotated Git tag for the new version. Pushing the tag triggers automated builds and releases. ```bash # Update version in Cargo.toml to 1.2.3 git add Cargo.toml git commit -m "version 1.2.3" git tag -a v1.2.3 -m "tree v1.2.3" git push origin v1.2.3 ``` -------------------------------- ### Read File Listing from Path or Stdin Source: https://github.com/peteretelej/tree/blob/main/_autodocs/fromfile.md Reads lines from a specified file or standard input. Trims whitespace and removes empty lines. ```rust use rust_tree::rust_tree::fromfile::read_file_listing; let lines = read_file_listing("archive_listing.txt")?; // Lines: ["file1.txt", "dir1/", "dir1/file2.txt"] ``` -------------------------------- ### CLI Argument Structure Source: https://github.com/peteretelej/tree/blob/main/_autodocs/cli.md Defines the command-line interface structure using `clap` derive API. Includes fields for path, hidden files, and other tree options. ```rust #[derive(Parser, Debug)] pub struct Cli { #[arg(default_value = ".", help = "The path to the directory to list.")] pub path: String, #[arg(short = 'a', long = "all", help = "Include hidden files.")] pub all_files: bool, // ... (29 more fields covering all tree options) } ``` -------------------------------- ### list_directory_as_string Source: https://github.com/peteretelej/tree/blob/main/_autodocs/traversal.md Traverse a directory and return the formatted tree as a String. This is useful for capturing tree output for further processing. ```APIDOC ## list_directory_as_string ### Description Traverse a directory and return the formatted tree as a `String`. This function is functionally identical to `list_directory()` but buffers output to memory instead of writing to a file or stdout. It is useful for capturing tree output for further processing or analysis, but has increased memory overhead for very large trees. ### Method ```rust pub fn list_directory_as_string>( path: P, options: &TreeOptions ) -> io::Result ``` ### Parameters #### Path Parameters - **path** (`P: AsRef`) - Required - Root directory path to traverse. - **options** (`&TreeOptions`) - Required - Configuration controlling output format and filtering. ### Request Example ```rust use rust_tree::rust_tree::traversal::list_directory_as_string; use rust_tree::rust_tree::options::TreeOptions; let options = TreeOptions { full_path: true, ..Default::default() }; let output = list_directory_as_string(".", &options)?; println!("Tree output:\n{}", output); ``` ### Response #### Success Response (io::Result) - The complete tree output as a UTF-8 string. #### Error Response (io::Result) - Error if traversal fails. ``` -------------------------------- ### Rust CLI Argument Conversion Source: https://github.com/peteretelej/tree/blob/main/_autodocs/MANIFEST.txt Shows the conversion of command-line arguments into TreeOptions. ```Rust use rust_tree::cli::cli_to_options; let args = vec!["--all", "--depth", "3"]; let options = cli_to_options(&args).unwrap(); println!("{:?}", options); ```