### Skipping Hidden Files with Walkdir in Rust Source: https://github.com/burntsushi/walkdir/blob/master/README.md This example demonstrates efficient filtering of hidden files and directories (those starting with '.') on Unix-like systems using the `filter_entry` adapter. It defines a helper function `is_hidden` for clarity. Dependencies: `walkdir` crate. ```rust use walkdir::{DirEntry, WalkDir}; fn is_hidden(entry: &DirEntry) -> bool { entry.file_name() .to_str() .map(|s| s.starts_with(".")) .unwrap_or(false) } let walker = WalkDir::new("foo").into_iter(); for entry in walker.filter_entry(|e| !is_hidden(e)) { let entry = entry.unwrap(); println!("{}", entry.path().display()); } ``` -------------------------------- ### Custom Sorting of Directory Entries in Rust Source: https://context7.com/burntsushi/walkdir/llms.txt Applies custom comparison logic to sort directory entries. This example sorts directories before files and then alphabetically within those groups using `sort_by`. ```rust use std::cmp::Ordering; use walkdir::WalkDir; fn main() -> Result<(), Box> { // Sort directories before files, then alphabetically for entry in WalkDir::new("foo").sort_by(|a, b| { match (a.file_type().is_dir(), b.file_type().is_dir()) { (true, false) => Ordering::Less, (false, true) => Ordering::Greater, _ => a.file_name().cmp(b.file_name()), } }) { let entry = entry?; println!("{}", entry.path().display()); } Ok(()) } ``` -------------------------------- ### Error-Tolerant Directory Iteration with Walkdir in Rust Source: https://github.com/burntsushi/walkdir/blob/master/README.md This example shows how to iterate through directory entries using `WalkDir` while gracefully handling potential errors (like permission denied) by using `filter_map` to skip problematic entries. Dependencies: `walkdir` crate. ```rust use walkdir::WalkDir; for entry in WalkDir::new("foo").into_iter().filter_map(|e| e.ok()) { println!("{}", entry.path().display()); } ``` -------------------------------- ### Skipping Directories Dynamically in Rust Traversal Source: https://context7.com/burntsushi/walkdir/llms.txt Demonstrates how to dynamically skip entire directories during iteration based on runtime conditions using `skip_current_dir`. This example skips hidden directories. ```rust use walkdir::{DirEntry, WalkDir}; fn is_hidden(entry: &DirEntry) -> bool { entry.file_name() .to_str() .map(|s| s.starts_with(".")) .unwrap_or(false) } fn main() { let mut it = WalkDir::new("foo").into_iter(); loop { let entry = match it.next() { None => break, Some(Err(err)) => { eprintln!("ERROR: {}", err); continue; } Some(Ok(entry)) => entry, }; if is_hidden(&entry) { if entry.file_type().is_dir() { it.skip_current_dir(); } continue; } println!("{}", entry.path().display()); } } ``` -------------------------------- ### Unix-Specific: Accessing Inode Numbers Source: https://context7.com/burntsushi/walkdir/llms.txt Provides an example of accessing inode numbers for files on Unix-like systems using `DirEntryExt::ino()`. This functionality is conditional and only available when compiled on a Unix platform. ```rust #[cfg(unix)] use walkdir::{DirEntry, DirEntryExt, WalkDir}; #[cfg(unix)] fn main() -> Result<(), Box> { for entry in WalkDir::new("foo") { let entry = entry?; println!("Inode {}: {}", entry.ino(), entry.path().display()); } Ok(()) } #[cfg(not(unix))] fn main() { println!("Inode access is only available on Unix systems"); } ``` -------------------------------- ### Sort Directory Entries by Key Source: https://context7.com/burntsushi/walkdir/llms.txt Sorts directory entries based on a key extracted from each entry. This example sorts by file size, which requires looking up metadata. It handles potential errors during metadata lookup by defaulting to a size of 0. ```rust use walkdir::WalkDir; fn main() -> Result<(), Box> { // Sort by file size (requires metadata lookup) for entry in WalkDir::new("foo").sort_by_key(|e| { e.metadata().map(|m| m.len()).unwrap_or(0) }) { let entry = entry?; if let Ok(metadata) = entry.metadata() { println!("{} bytes: {}", metadata.len(), entry.path().display()); } } Ok(()) } ``` -------------------------------- ### Filtering Hidden Files During Directory Traversal (Rust) Source: https://context7.com/burntsushi/walkdir/llms.txt Efficiently skips hidden files and directories (those starting with '.') during traversal using the `filter_entry` method. A helper function `is_hidden` is provided to determine if an entry is hidden. ```rust use walkdir::{DirEntry, WalkDir}; fn is_hidden(entry: &DirEntry) -> bool { entry.file_name() .to_str() .map(|s| s.starts_with(".")) .unwrap_or(false) } fn main() -> Result<(), Box> { for entry in WalkDir::new("foo") .into_iter() .filter_entry(|e| !is_hidden(e)) { let entry = entry?; println!("{}", entry.path().display()); } Ok(()) } ``` -------------------------------- ### Accessing DirEntry Metadata and Properties Source: https://context7.com/burntsushi/walkdir/llms.txt Illustrates how to use methods on the `DirEntry` struct to retrieve file metadata, type information, path details, and depth. It shows how to access file size, modification times, and permission settings. ```rust use walkdir::WalkDir; fn main() -> Result<(), Box> { for entry in WalkDir::new("foo") { let entry = entry?; println!("Path: {}", entry.path().display()); println!("Filename: {:?}", entry.file_name()); println!("Depth: {}", entry.depth()); println!("Is symlink: {}", entry.path_is_symlink()); println!("File type: {:?}", entry.file_type()); if let Ok(metadata) = entry.metadata() { println!("Size: {} bytes", metadata.len()); println!("Modified: {:?}", metadata.modified()?); println!("Is readonly: {}", metadata.permissions().readonly()); } println!("---"); } Ok(()) } ``` -------------------------------- ### Benchmarking Directory Traversal Tools (Shell) Source: https://github.com/burntsushi/walkdir/blob/master/README.md This shell script provides commands to benchmark the performance of `find`, the `walkdir` Rust crate, and glibc's `nftw` utility. It includes steps for dropping caches and warming them up for consistent testing. Note: Requires `sudo` for cache dropping. ```shell # The directory you want to recursively walk: DIR=$HOME # If you want to observe perf on a cold file cache, run this before *each* command: sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' # To warm the caches find $DIR # Test speed of `find` on warm cache: time find $DIR # Compile and test speed of `walkdir` crate: cargo build --release --example walkdir time ./target/release/examples/walkdir $DIR # Compile and test speed of glibc's `nftw`: gcc -O3 -o nftw ./compare/nftw.c time ./nftw $DIR # For shits and giggles, test speed of Python's (2 or 3) os.walk: time python ./compare/walk.py $DIR ``` -------------------------------- ### Detailed Error Handling with WalkDir Source: https://context7.com/burntsushi/walkdir/llms.txt Demonstrates comprehensive error handling during directory traversal. It shows how to access detailed error information, including the path, depth, loop detection, and specific IO errors like permission denied or not found. ```rust use std::io; use std::path::Path; use walkdir::WalkDir; fn main() { for entry in WalkDir::new("foo").follow_links(true) { match entry { Ok(entry) => println!("{}", entry.path().display()), Err(err) => { eprintln!("Error at depth {}: {}", err.depth(), err); if let Some(path) = err.path() { eprintln!(" Path: {}", path.display()); } if let Some(ancestor) = err.loop_ancestor() { eprintln!(" Loop detected! Ancestor: {}", ancestor.display()); } if let Some(inner) = err.io_error() { match inner.kind() { io::ErrorKind::PermissionDenied => { eprintln!(" Permission denied"); } io::ErrorKind::NotFound => { eprintln!(" Path not found"); } _ => { eprintln!(" IO error: {}", inner); } } } } } } } ``` -------------------------------- ### Following Symbolic Links with Walkdir in Rust Source: https://github.com/burntsushi/walkdir/blob/master/README.md This code snippet extends the basic directory traversal to follow symbolic links. By calling `.follow_links(true)`, the walker will traverse into directories pointed to by symbolic links. Dependencies: `walkdir` crate. ```rust use walkdir::WalkDir; for entry in WalkDir::new("foo").follow_links(true) { let entry = entry.unwrap(); println!("{}", entry.path().display()); } ``` -------------------------------- ### Symbolic Link Following in Directory Traversal (Rust) Source: https://context7.com/burntsushi/walkdir/llms.txt Enables the traversal to follow symbolic links and includes automatic detection to prevent infinite loops. It also demonstrates how to identify and process symlinks versus regular files. ```rust use walkdir::WalkDir; fn main() -> Result<(), Box> { for entry in WalkDir::new("foo").follow_links(true) { let entry = entry?; if entry.path_is_symlink() { println!("Symlink: {} -> {:?}", entry.path().display(), std::fs::read_link(entry.path())?); } else { println!("Regular: {}", entry.path().display()); } } Ok(()) } ``` -------------------------------- ### Customizing Directory Traversal with Walkdir Options in Rust Source: https://context7.com/burntsushi/walkdir/llms.txt Demonstrates chaining multiple configuration options for complex directory traversal requirements using the walkdir crate. It includes filtering hidden files and setting depth limits. Dependencies: walkdir crate. Input: Directory path. Output: Paths of entries matching criteria. ```rust use walkdir::{DirEntry, WalkDir}; fn is_hidden(entry: &DirEntry) -> bool { entry.file_name() .to_str() .map(|s| s.starts_with(".")) .unwrap_or(false) } fn main() -> Result<(), Box> { for entry in WalkDir::new("foo") .follow_links(true) .min_depth(1) .max_depth(5) .max_open(10) .sort_by_file_name() .into_iter() .filter_entry(|e| !is_hidden(e)) .filter_map(|e| e.ok()) { println!("{}", entry.path().display()); } Ok(()) } ``` -------------------------------- ### Basic Recursive Directory Traversal in Rust Source: https://context7.com/burntsushi/walkdir/llms.txt Iterates recursively through all entries in a specified directory and prints the path of each entry. This is the most basic usage of the walkdir library. ```rust use walkdir::WalkDir; fn main() -> Result<(), Box> { for entry in WalkDir::new("foo") { let entry = entry?; println!("{}", entry.path().display()); } Ok(()) } ``` -------------------------------- ### Basic Directory Iteration with Walkdir in Rust Source: https://github.com/burntsushi/walkdir/blob/master/README.md This snippet demonstrates the fundamental usage of the `WalkDir` struct to recursively iterate over entries in a directory. It unwraps each entry, assuming no errors will occur during traversal. Dependencies: `walkdir` crate. ```rust use walkdir::WalkDir; for entry in WalkDir::new("foo") { let entry = entry.unwrap(); println!("{}", entry.path().display()); } ``` -------------------------------- ### Sorting Directory Entries by Filename in Rust Source: https://context7.com/burntsushi/walkdir/llms.txt Sorts the directory entries by their filenames before yielding them, ensuring a deterministic traversal order. This is achieved using the `sort_by_file_name` method. ```rust use walkdir::WalkDir; fn main() -> Result<(), Box> { for entry in WalkDir::new("foo").sort_by_file_name() { let entry = entry?; println!("{}", entry.path().display()); } Ok(()) } ``` -------------------------------- ### Contents-First Traversal Order Source: https://context7.com/burntsushi/walkdir/llms.txt Configures WalkDir to yield directory contents before the directory itself, enabling bottom-up processing. This order is particularly useful for operations like recursive deletion where child items must be processed before their parent directory. ```rust use walkdir::WalkDir; fn main() -> Result<(), Box> { for entry in WalkDir::new("foo").contents_first(true) { let entry = entry?; // This order is useful for recursive deletion if entry.file_type().is_dir() { println!("Directory (after contents): {}", entry.path().display()); } else { println!("File: {}", entry.path().display()); } } Ok(()) } ``` -------------------------------- ### Limit Open File Descriptors Source: https://context7.com/burntsushi/walkdir/llms.txt Controls the maximum number of file descriptors that WalkDir can have open simultaneously. This is crucial for managing system resources and preventing exhaustion, especially when dealing with very large directory structures. ```rust use walkdir::WalkDir; fn main() -> Result<(), Box> { // Limit to 5 open file descriptors at once for entry in WalkDir::new("foo").max_open(5) { let entry = entry?; println!("{}", entry.path().display()); } Ok(()) } ``` -------------------------------- ### Restrict Traversal to Same File System Source: https://context7.com/burntsushi/walkdir/llms.txt Enforces that directory traversal does not cross file system boundaries. This is useful when you want to limit the scope of traversal to a specific mounted volume or partition. ```rust use walkdir::WalkDir; fn main() -> Result<(), Box> { for entry in WalkDir::new("/").same_file_system(true).max_depth(2) { let entry = entry?; println!("{}", entry.path().display()); } Ok(()) } ``` -------------------------------- ### Error-Tolerant Directory Traversal in Rust Source: https://context7.com/burntsushi/walkdir/llms.txt Traverses a directory tree while filtering out and skipping any errors encountered, such as inaccessible directories. This allows the traversal to continue even if some parts of the directory structure cannot be accessed. ```rust use walkdir::WalkDir; fn main() { for entry in WalkDir::new("foo").into_iter().filter_map(|e| e.ok()) { println!("{}", entry.path().display()); } } ``` -------------------------------- ### Directory Traversal with Depth Control in Rust Source: https://context7.com/burntsushi/walkdir/llms.txt Limits the directory traversal to a specified range of depths, excluding the root directory. This is useful for controlling how deep into a directory structure the iteration proceeds. ```rust use walkdir::WalkDir; fn main() -> Result<(), Box> { // Only traverse depths 1, 2, and 3 (skip root at depth 0) for entry in WalkDir::new("foo").min_depth(1).max_depth(3) { let entry = entry?; println!("Depth {}: {}", entry.depth(), entry.path().display()); } Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.