### Glob Syntax Reference with Examples Source: https://context7.com/burntsushi/globset/llms.txt Provides a reference for the supported glob syntax in the globset library, including examples for metacharacters like ?, *, **, {}, [], and escaping mechanisms. This helps users construct flexible and powerful file path matching patterns. ```Rust use globset::{Glob, GlobBuilder}; fn main() -> Result<(), globset::Error> { // ? - matches any single character let single = Glob::new("file?.txt")?.compile_matcher(); assert!(single.is_match("file1.txt")); assert!(single.is_match("fileA.txt")); assert!(!single.is_match("file10.txt")); // ? matches only one char // * - matches zero or more characters (including path separators by default) let star = Glob::new("*.rs")?.compile_matcher(); assert!(star.is_match("main.rs")); assert!(star.is_match("src/lib.rs")); // * matches / by default assert!(star.is_match(".rs")); // * can match empty string // ** - recursive directory matching (must be path component) let recursive = Glob::new("src/**/*.rs")?.compile_matcher(); assert!(recursive.is_match("src/main.rs")); assert!(recursive.is_match("src/a/b/c/d.rs")); // {a,b} - alternation groups let alt = Glob::new("*.{{rs,toml,json}}")?.compile_matcher(); assert!(alt.is_match("Cargo.toml")); assert!(alt.is_match("config.json")); assert!(alt.is_match("main.rs")); // [abc] - character class let class = Glob::new("file[0-9].txt")?.compile_matcher(); assert!(class.is_match("file0.txt")); assert!(class.is_match("file9.txt")); assert!(!class.is_match("fileA.txt")); // [!abc] or [^abc] - negated character class let neg_class = Glob::new("file[!0-9].txt")?.compile_matcher(); assert!(neg_class.is_match("fileA.txt")); assert!(!neg_class.is_match("file0.txt")); // Escaping metacharacters with [x] syntax let escaped = Glob::new("file[*].txt")?.compile_matcher(); assert!(escaped.is_match("file*.txt")); // Matches literal * // Backslash escaping (platform-dependent, enabled by default on Unix) let backslash = GlobBuilder::new("file\\?.txt") .backslash_escape(true) .build()? .compile_matcher(); assert!(backslash.is_match("file?.txt")); // Matches literal ? Ok(()) } ``` -------------------------------- ### Get All Matching Glob Pattern Indices with GlobSet::matches Source: https://context7.com/burntsushi/globset/llms.txt Illustrates the use of `matches` method on a GlobSet to retrieve a vector containing the sequence numbers of all glob patterns that match a given path. This is useful when the specific matching patterns need to be identified. ```rust use globset::{Glob, GlobSetBuilder}; fn main() -> Result<(), globset::Error> { let mut builder = GlobSetBuilder::new(); builder.add(Glob::new("*.rs")?); // index 0 builder.add(Glob::new("src/lib.rs")?); // index 1 builder.add(Glob::new("src/**/foo.rs")?); // index 2 builder.add(Glob::new("**/*.rs")?); // index 3 let set = builder.build()?; // Get all matching patterns for a path let matches = set.matches("src/bar/baz/foo.rs"); assert_eq!(matches, vec![0, 2, 3]); // Patterns 0, 2, and 3 match // Only one pattern matches let matches = set.matches("src/lib.rs"); assert_eq!(matches, vec![0, 1, 3]); // Patterns 0, 1, and 3 match // Process matched patterns let patterns = ["*.rs", "src/lib.rs", "src/**/foo.rs", "**/*.rs"]; for idx in set.matches("main.rs") { println!("Matched: {}", patterns[idx]); } // Output: "Matched: *.rs" and "Matched: **/*.rs" Ok(()) } ``` -------------------------------- ### GlobSet::matches - Get All Matching Pattern Indices Source: https://context7.com/burntsushi/globset/llms.txt Returns a list of indices for all patterns that match the provided path. ```APIDOC ## GET /globset/{id}/matches ### Description Retrieves the sequence numbers (indices) of all patterns that match the given path. ### Method GET ### Endpoint /globset/{id}/matches ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the GlobSet. #### Query Parameters - **path** (string) - Required - The file path to test. ### Response #### Success Response (200) - **indices** (array of integers) - List of indices corresponding to matching patterns. #### Response Example { "indices": [0, 2, 3] } ``` -------------------------------- ### Amortize Path Preparation Cost with Candidate Source: https://context7.com/burntsushi/globset/llms.txt Demonstrates how to pre-process a path into a `Candidate` for efficient matching against multiple globs or glob sets. This is beneficial when the same path needs to be tested against many matchers, reducing the overhead of repeated path parsing. ```Rust use globset::{Candidate, Glob, GlobSetBuilder}; fn main() -> Result<(), globset::Error> { // Create multiple matchers let rust_matcher = Glob::new("**/*.rs")?.compile_matcher(); let test_matcher = Glob::new("**/test_*.rs")?.compile_matcher(); let mut builder = GlobSetBuilder::new(); builder.add(Glob::new("src/**")?); builder.add(Glob::new("**/*_test.rs")?); let set = builder.build()?; // Pre-process the path once let path = "src/utils/test_helpers.rs"; let candidate = Candidate::new(path); // Use candidate with individual matchers assert!(rust_matcher.is_match_candidate(&candidate)); assert!(test_matcher.is_match_candidate(&candidate)); // Use candidate with glob sets assert!(set.is_match_candidate(&candidate)); let matches = set.matches_candidate(&candidate); assert_eq!(matches, vec![0, 1]); // Both patterns match // Efficient batch processing let paths = ["src/main.rs", "tests/unit.rs", "docs/api.md"]; for path in &paths { let candidate = Candidate::new(path); if set.is_match_candidate(&candidate) { println!("Matched: {}", path); } } Ok(()) } ``` -------------------------------- ### Create and Compile Single Glob Patterns Source: https://context7.com/burntsushi/globset/llms.txt Demonstrates how to instantiate a new glob pattern using Glob::new and compile it into a matcher. This is the standard approach for basic pattern matching against file paths. ```rust use globset::Glob; fn main() -> Result<(), globset::Error> { let rust_files = Glob::new("*.rs")?; let matcher = rust_files.compile_matcher(); assert!(matcher.is_match("main.rs")); assert!(!matcher.is_match("Cargo.toml")); println!("Pattern: {}", rust_files.glob()); Ok(()) } ``` -------------------------------- ### Candidate - Amortize Path Preparation Cost Source: https://context7.com/burntsushi/globset/llms.txt Demonstrates how to use the `Candidate` struct to pre-process a path for efficient matching against multiple globs or glob sets. This is beneficial when the same path needs to be tested against many matchers. ```APIDOC ## Candidate - Amortize Path Preparation Cost A pre-processed path representation that can be reused when matching a single path against multiple globs or glob sets. Constructing a `Candidate` has a small cost, so this is beneficial when the same path needs to be tested against many matchers. ### Method N/A (Struct usage) ### Endpoint N/A (Struct usage) ### Parameters N/A ### Request Example ```rust use globset::{Candidate, Glob, GlobSetBuilder}; fn main() -> Result<(), globset::Error> { // Create multiple matchers let rust_matcher = Glob::new("**/*.rs")?.compile_matcher(); let test_matcher = Glob::new("**/test_*.rs")?.compile_matcher(); let mut builder = GlobSetBuilder::new(); builder.add(Glob::new("src/**")?); builder.add(Glob::new("**/*_test.rs")?); let set = builder.build()?; // Pre-process the path once let path = "src/utils/test_helpers.rs"; let candidate = Candidate::new(path); // Use candidate with individual matchers assert!(rust_matcher.is_match_candidate(&candidate)); assert!(test_matcher.is_match_candidate(&candidate)); // Use candidate with glob sets assert!(set.is_match_candidate(&candidate)); let matches = set.matches_candidate(&candidate); assert_eq!(matches, vec![0, 1]); // Both patterns match // Efficient batch processing let paths = ["src/main.rs", "tests/unit.rs", "docs/api.md"]; for path in &paths { let candidate = Candidate::new(path); if set.is_match_candidate(&candidate) { println!("Matched: {}", path); } } Ok(()) } ``` ### Response N/A (Illustrative example) ``` -------------------------------- ### GlobSet::empty - Create Empty Matcher Source: https://context7.com/burntsushi/globset/llms.txt Explains how to create an empty `GlobSet` which matches nothing. This is useful for default values or conditional building of glob sets. ```APIDOC ## GlobSet::empty - Create Empty Matcher Creates an empty `GlobSet` that matches nothing. This is useful as a default value or when conditionally building a glob set. An empty set is guaranteed to return `false` for all `is_match` calls. ### Method N/A (Function usage) ### Endpoint N/A (Function usage) ### Parameters N/A ### Request Example ```rust use globset::{Glob, GlobSet, GlobSetBuilder}; fn main() -> Result<(), globset::Error> { // Create an empty set directly let empty = GlobSet::empty(); assert!(empty.is_empty()); assert_eq!(empty.len(), 0); // Empty set matches nothing assert!(!empty.is_match("anything.rs")); assert!(!empty.is_match("")); assert!(empty.matches("test.rs").is_empty()); // Conditionally build a set let patterns: Vec<&str> = vec![]; // No patterns provided let set = if patterns.is_empty() { GlobSet::empty() } else { let mut builder = GlobSetBuilder::new(); for pattern in patterns { builder.add(Glob::new(pattern)?); } builder.build()? }; assert!(set.is_empty()); Ok(()) } ``` ### Response N/A (Illustrative example) ``` -------------------------------- ### Build Multiple Glob Patterns with GlobSetBuilder Source: https://context7.com/burntsushi/globset/llms.txt Demonstrates how to use GlobSetBuilder to construct a GlobSet capable of matching multiple glob patterns simultaneously. This is efficient for testing many patterns against a single path. Patterns are assigned sequence numbers upon insertion. ```rust use globset::{Glob, GlobSetBuilder}; fn main() -> Result<(), globset::Error> { let mut builder = GlobSetBuilder::new(); // Add multiple patterns - each gets a sequence number (0, 1, 2, ...) builder.add(Glob::new("*.rs")?); // index 0 builder.add(Glob::new("src/lib.rs")?); // index 1 builder.add(Glob::new("src/**/foo.rs")?); // index 2 builder.add(Glob::new("Cargo.toml")?); // index 3 let set = builder.build()?; // Check set properties println!("Number of patterns: {}", set.len()); // 4 assert!(!set.is_empty()); Ok(()) } ``` -------------------------------- ### Create Empty GlobSet Matcher Source: https://context7.com/burntsushi/globset/llms.txt Shows how to create an empty `GlobSet` which matches nothing. This is useful as a default value or when conditionally building a glob set. An empty set will always return `false` for `is_match` calls and an empty vector for `matches`. ```Rust use globset::{Glob, GlobSet, GlobSetBuilder}; fn main() -> Result<(), globset::Error> { // Create an empty set directly let empty = GlobSet::empty(); assert!(empty.is_empty()); assert_eq!(empty.len(), 0); // Empty set matches nothing assert!(!empty.is_match("anything.rs")); assert!(!empty.is_match("")); assert!(empty.matches("test.rs").is_empty()); // Conditionally build a set let patterns: Vec<&str> = vec![]; // No patterns provided let set = if patterns.is_empty() { GlobSet::empty() } else { let mut builder = GlobSetSetBuilder::new(); for pattern in patterns { builder.add(Glob::new(pattern)?); } builder.build()? }; assert!(set.is_empty()); Ok(()) } ``` -------------------------------- ### Configure Glob Match Semantics with GlobBuilder Source: https://context7.com/burntsushi/globset/llms.txt Shows how to use GlobBuilder to customize matching behavior, including case-insensitivity, literal path separators, and backslash escaping. This is essential for fine-grained control over how patterns interact with file paths. ```rust use globset::GlobBuilder; fn main() -> Result<(), globset::Error> { let case_insensitive = GlobBuilder::new("*.RS") .case_insensitive(true) .build()? .compile_matcher(); assert!(case_insensitive.is_match("main.rs")); let literal_sep = GlobBuilder::new("*.rs") .literal_separator(true) .build()? .compile_matcher(); assert!(!literal_sep.is_match("src/main.rs")); Ok(()) } ``` -------------------------------- ### GlobSetBuilder - Build Multiple Pattern Matcher Source: https://context7.com/burntsushi/globset/llms.txt Initializes a builder to collect multiple glob patterns into a single, optimized matcher. ```APIDOC ## POST /globset/builder ### Description Creates a new GlobSetBuilder instance to aggregate multiple glob patterns for simultaneous matching. ### Method POST ### Endpoint /globset/builder ### Parameters #### Request Body - **patterns** (array of strings) - Required - List of glob patterns to include in the set. ### Request Example { "patterns": ["*.rs", "src/lib.rs", "src/**/*.rs"] } ### Response #### Success Response (200) - **id** (string) - Unique identifier for the built GlobSet instance. #### Response Example { "id": "gs_12345" } ``` -------------------------------- ### GlobSet::is_match - Test If Any Pattern Matches Source: https://context7.com/burntsushi/globset/llms.txt Checks if a given path matches any of the patterns contained within the GlobSet. ```APIDOC ## GET /globset/{id}/is_match ### Description Tests if the provided path matches at least one pattern in the specified GlobSet. ### Method GET ### Endpoint /globset/{id}/is_match ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the GlobSet. #### Query Parameters - **path** (string) - Required - The file path to test against the set. ### Response #### Success Response (200) - **match** (boolean) - Returns true if at least one pattern matches. #### Response Example { "match": true } ``` -------------------------------- ### Glob Syntax Reference Source: https://context7.com/burntsushi/globset/llms.txt Provides a reference for the supported glob syntax, including metacharacters like `?`, `*`, `**`, `{}`, `[]`, and escaping mechanisms. ```APIDOC ## Glob Syntax Reference The library supports standard Unix-style glob syntax with several metacharacters for flexible pattern matching. Here's a comprehensive reference with examples of each syntax element. ### Method N/A (Syntax explanation) ### Endpoint N/A (Syntax explanation) ### Parameters N/A ### Request Example ```rust use globset::{Glob, GlobBuilder}; fn main() -> Result<(), globset::Error> { // ? - matches any single character let single = Glob::new("file?.txt")?.compile_matcher(); assert!(single.is_match("file1.txt")); assert!(single.is_match("fileA.txt")); assert!(!single.is_match("file10.txt")); // ? matches only one char // * - matches zero or more characters (including path separators by default) let star = Glob::new("*.rs")?.compile_matcher(); assert!(star.is_match("main.rs")); assert!(star.is_match("src/lib.rs")); // * matches / by default assert!(star.is_match(".rs")); // * can match empty string // ** - recursive directory matching (must be path component) let recursive = Glob::new("src/**/*.rs")?.compile_matcher(); assert!(recursive.is_match("src/main.rs")); assert!(recursive.is_match("src/a/b/c/d.rs")); // {a,b} - alternation groups let alt = Glob::new("*.{rs,toml,json}")?.compile_matcher(); assert!(alt.is_match("Cargo.toml")); assert!(alt.is_match("config.json")); assert!(alt.is_match("main.rs")); // [abc] - character class let class = Glob::new("file[0-9].txt")?.compile_matcher(); assert!(class.is_match("file0.txt")); assert!(class.is_match("file9.txt")); assert!(!class.is_match("fileA.txt")); // [!abc] or [^abc] - negated character class let neg_class = Glob::new("file[!0-9].txt")?.compile_matcher(); assert!(neg_class.is_match("fileA.txt")); assert!(!neg_class.is_match("file0.txt")); // Escaping metacharacters with [x] syntax let escaped = Glob::new("file[*].txt")?.compile_matcher(); assert!(escaped.is_match("file*.txt")); // Matches literal * // Backslash escaping (platform-dependent, enabled by default on Unix) let backslash = GlobBuilder::new("file\\?.txt") .backslash_escape(true) .build()? .compile_matcher(); assert!(backslash.is_match("file?.txt")); // Matches literal ? Ok(()) } ``` ### Response N/A (Illustrative example) ``` -------------------------------- ### Test Any Glob Pattern Match with GlobSet::is_match Source: https://context7.com/burntsushi/globset/llms.txt Shows how to use the `is_match` method of GlobSet to efficiently check if any of the configured glob patterns match a given path. It returns true if at least one pattern matches, without identifying which specific patterns matched. ```rust use globset::{Glob, GlobSetBuilder}; fn main() -> Result<(), globset::Error> { let mut builder = GlobSetBuilder::new(); builder.add(Glob::new("*.rs")?); builder.add(Glob::new("*.toml")?); builder.add(Glob::new("**/*.md")?); let set = builder.build()?; // Check if any pattern matches assert!(set.is_match("main.rs")); assert!(set.is_match("Cargo.toml")); assert!(set.is_match("docs/README.md")); assert!(set.is_match("deeply/nested/CHANGELOG.md")); // No patterns match these assert!(!set.is_match("main.c")); assert!(!set.is_match("config.json")); Ok(()) } ``` -------------------------------- ### Handling Glob Parsing Errors in Rust Source: https://context7.com/burntsushi/globset/llms.txt Demonstrates how to catch and inspect specific glob parsing errors such as unclosed character classes, invalid ranges, and nested alternations. It also shows a pattern for wrapping glob compilation in a result-based function. ```rust use globset::{Glob, ErrorKind}; fn main() { let err = Glob::new("[a-z").unwrap_err(); assert_eq!(err.glob(), Some("[a-z")); match err.kind() { ErrorKind::UnclosedClass => println!("Missing closing bracket"), _ => {} } let err = Glob::new("[z-a]").unwrap_err(); match err.kind() { ErrorKind::InvalidRange(start, end) => { println!("Invalid range: {} > {}", start, end); } _ => {} } let err = Glob::new("{a,b").unwrap_err(); match err.kind() { ErrorKind::UnclosedAlternates => println!("Missing closing brace"), _ => {} } let err = Glob::new("a,b}").unwrap_err(); match err.kind() { ErrorKind::UnopenedAlternates => println!("Missing opening brace"), _ => {} } let err = Glob::new("{{a,b},{c,d}}").unwrap_err(); match err.kind() { ErrorKind::NestedAlternates => println!("Cannot nest alternation groups"), _ => {} } fn process_pattern(pattern: &str) -> Result<(), String> { match Glob::new(pattern) { Ok(glob) => { let _matcher = glob.compile_matcher(); println!("Pattern '{}' compiled successfully", pattern); Ok(()) } Err(e) => Err(format!("Failed to parse '{}': {}", pattern, e)) } } process_pattern("*.rs").unwrap(); process_pattern("[invalid").unwrap_err(); } ``` -------------------------------- ### Test Paths Against Compiled Glob Matchers Source: https://context7.com/burntsushi/globset/llms.txt Illustrates the use of GlobMatcher::is_match to validate file paths. It supports various input types like string slices and Path objects, returning a boolean result. ```rust use globset::Glob; use std::path::Path; fn main() -> Result<(), globset::Error> { let glob = Glob::new("src/**/*.rs")?.compile_matcher(); assert!(glob.is_match("src/main.rs")); assert!(glob.is_match(Path::new("src/config.rs"))); assert!(!glob.is_match("tests/test.rs")); Ok(()) } ``` -------------------------------- ### Reuse Allocation for Matches with GlobSet::matches_into Source: https://context7.com/burntsushi/globset/llms.txt Explains how to use the `matches_into` method to add matching pattern indices to a pre-allocated vector, clearing it first. This optimizes performance in high-frequency loops by minimizing memory allocations. The resulting vector is sorted and deduplicated. ```rust use globset::{Glob, GlobSetBuilder}; fn main() -> Result<(), globset::Error> { let mut builder = GlobSetBuilder::new(); builder.add(Glob::new("*.rs")?); builder.add(Glob::new("**/*.toml")?); builder.add(Glob::new("src/**")?); let set = builder.build()?; // Reuse this vector for multiple match operations let mut matches = Vec::new(); let paths = ["main.rs", "Cargo.toml", "src/lib.rs", "README.md"]; for path in &paths { set.matches_into(path, &mut matches); if !matches.is_empty() { println!("{}: matched patterns {:?}", path, matches); } } // Output: // main.rs: matched patterns [0] // Cargo.toml: matched patterns [1] // src/lib.rs: matched patterns [0, 2] Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.