### PEP440 Versioning Examples Source: https://github.com/facelessuser/wcmatch/blob/main/SECURITY.md Examples of version strings following the major.minor.patch format as defined by PEP440. ```text 8.0 8.1 8.1.3 ``` -------------------------------- ### Minimatch Dot Matching Example Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/about/release.md Demonstrates how minimatch handles matching dot files and directories, including the behavior with '.*'. ```javascript > minimatch("..", ".*") true ``` -------------------------------- ### Example: Translate fnmatch patterns with flags Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/fnmatch.md Demonstrates the usage of the fnmatch.translate function with different flags. The first example uses BRACE expansion, while the second uses BRACE, NEGATE, and SPLIT flags to handle complex pattern matching with exclusions. ```python >>> from wcmatch import fnmatch >>> fnmatch.translate('*.{a,{b,c}}', flags=fnmatch.BRACE) (['^(?s:(?=.)(?![.]).*?\.a)$', '^(?s:(?=.)(?![.]).*?\.b)$', '^(?s:(?=.)(?![.]).*?\.c)$'], []) >>> fnmatch.translate('**|!*.{a,{b,c}}', flags=fnmatch.BRACE | fnmatch.NEGATE | fnmatch.SPLIT) (['^(?s:(?=.)(?![.]).*?)$'], ['^(?s:(?=.).*?\.a)$', '^(?s:(?=.).*?\.b)$', '^(?s:(?=.).*?\.c)$']) ``` -------------------------------- ### Demonstrate Pattern Expansion with BRACE, SPLIT, and EXTMATCH Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/fnmatch.md This example shows how combining BRACE, SPLIT, and EXTMATCH flags can expand a single pattern string into multiple distinct patterns. It highlights the potential for generating redundant patterns when using these features simultaneously. ```python from wcmatch import fnmatch # Expanding a complex pattern using multiple flags patterns = fnmatch.expand('test@(this{|that,|other})|*.py', fnmatch.BRACE | fnmatch.SPLIT | fnmatch.EXTMATCH) print(patterns) # Output: ['test@(this|that)', 'test@(this|other)', '*.py', '*.py'] ``` -------------------------------- ### Pathlib Match Example with '.' Pattern Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/pathlib.md Illustrates the behavior of the match method with a '.' pattern in wcmatch.pathlib, which differs from Python's default pathlib. wcmatch.pathlib returns True for matching the current directory, whereas Python's default raises a ValueError. ```python from wcmatch import pathlib # Example demonstrating match behavior with '.' # wcmatch.pathlib returns True, indicating a successful match for the current directory. # Python's default pathlib raises a ValueError for an empty pattern. print(pathlib.Path('.').match('.')) ``` -------------------------------- ### Path matching methods Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/pathlib.md Provides examples of using match and globmatch to validate paths against patterns. These methods support flags, exclusion patterns, and optional filesystem verification via the REALPATH flag. ```pycon3 from wcmatch import pathlib # Using match (recursive evaluation) p = pathlib.PurePath('docs/src') p.match('src') # Returns True # Using globmatch (non-recursive evaluation) p.globmatch('**/src', flags=pathlib.GLOBSTAR) # Returns True ``` -------------------------------- ### Glob Ignore Patterns Example Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/about/release.md Illustrates how ignore patterns are applied to glob results and are unaffected by underlying directory scanning behavior. ```javascript > glob('..', {}, function (er, files) { ... console.log(files) ... }) > [ '..' ] > glob('..', {ignore: ['.*']}, function (er, files) { ... console.log(files) ... }) > [] ``` -------------------------------- ### WcMatch on_init Method (Python) Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/wcmatch.md Handles custom initialization for WcMatch. It accepts keyword arguments not processed by the main initializer, allowing for extended configuration when deriving from WcMatch. Starting from version 8.0, it strictly requires keyword arguments. ```python def on_init(self, **kwargs): """Handle custom init.""" pass ``` -------------------------------- ### Perform File Searching with wcmatch Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/wcmatch.md Demonstrates basic and recursive file searching using glob-like patterns. Includes examples of excluding directories and using negation logic to filter results. ```python from wcmatch import wcmatch # Basic search wcmatch.WcMatch('.', '*.md|*.txt').match() # Recursive search wcmatch.WcMatch('.', '*.md|*.txt', flags=wcmatch.RECURSIVE).match() # Exclude directory wcmatch.WcMatch('.', '*.md|*.txt', exclude_pattern='docs', flags=wcmatch.RECURSIVE).match() # Using negation wcmatch.WcMatch('.', '*.md|*.txt|!README*', exclude_pattern='docs', flags=wcmatch.RECURSIVE).match() ``` -------------------------------- ### Pathlib Glob Example with './' in Pattern Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/pathlib.md Demonstrates how wcmatch.pathlib handles patterns containing './' in glob searches, contrasting with Python's default behavior. This shows that wcmatch.pathlib correctly matches paths with explicit './' segments. ```python from wcmatch import pathlib # Example demonstrating glob behavior with './' # In this case, both Python's default and wcmatch.pathlib produce the same result. # The path 'docs/src' is matched when the pattern is 'docs/./src'. print(list(pathlib.Path('.').glob('docs/./src'))) ``` -------------------------------- ### Example: Using is_magic to detect magic characters Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/fnmatch.md Illustrates the `fnmatch.is_magic` function. The first example shows that a simple string 'test' is not considered magic. The second example demonstrates that a pattern containing brackets and a question mark, '[test]ing?', is correctly identified as magic. ```python >>> from wcmatch import fnmatch >>> fnmatch.is_magic('test') False >>> fnmatch.is_magic('[test]ing?') True ``` -------------------------------- ### Example: Translate EXTMATCH patterns with capturing groups Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/fnmatch.md Shows how to use fnmatch.translate with the EXTMATCH flag to generate regex patterns that include capturing groups. This allows for extracting specific parts of a matched string, as demonstrated by compiling the pattern and using `match.groups()`. ```python >>> from wcmatch import fnmatch >>> import re >>> gpat = fnmatch.translate("@(file)+([[:digit:]])@(.*)", flags=fnmatch.EXTMATCH) >>> pat = re.compile(gpat[0][0]) >>> pat.match('file33.test.txt').groups() ('file', '33', '.test.txt') ``` -------------------------------- ### Custom File Searcher with WcMatch Subclass Source: https://context7.com/facelessuser/wcmatch/llms.txt Explains how to extend WcMatch by subclassing it and overriding hook methods like `on_init`, `on_validate_file`, `on_match`, and `on_error`. This example creates a `SizedFileMatch` class that filters files based on their size and returns file path with size information. ```python from wcmatch import wcmatch import os class SizedFileMatch(wcmatch.WcMatch): """Custom matcher that filters by file size.""" def on_init(self, *, min_size=0, max_size=float('inf')): """Accept custom size parameters.""" self.min_size = min_size self.max_size = max_size def on_validate_file(self, base, name): """Additional validation based on file size.""" filepath = os.path.join(base, name) try: size = os.path.getsize(filepath) return self.min_size <= size <= self.max_size except OSError: return False def on_match(self, base, name): """Return file path with size info.""" filepath = os.path.join(base, name) size = os.path.getsize(filepath) return {'path': filepath, 'size': size} def on_error(self, base, name): """Handle errors gracefully.""" return {'path': os.path.join(base, name), 'error': True} # Use custom matcher matcher = SizedFileMatch('.', '*.py', flags=wcmatch.RECURSIVE, min_size=100, # At least 100 bytes max_size=10000 # At most 10KB ) for result in matcher.imatch(): if 'error' not in result: print(f"{result['path']}: {result['size']} bytes") ``` -------------------------------- ### Example: Escaping and matching a literal pattern Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/fnmatch.md Demonstrates the `fnmatch.escape` function by escaping a pattern containing special characters. It then uses `fnmatch.fnmatch` to show that the escaped pattern correctly matches the original literal string, confirming the escaping works as intended. ```python >>> from wcmatch import fnmatch >>> fnmatch.escape('**file**{}.txt') '\\*\\*file\\*\\*\\{\\.txt' >>> fnmatch.fnmatch('**file**{}.txt', fnmatch.escape('**file**{}.txt')) True ``` -------------------------------- ### Precompile Glob Pattern with Python Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/glob.md Demonstrates how to precompile a glob pattern using the `wcmatch.glob.compile` function in Python. It shows how to create a `WcMatcher` object and use its `match` and `filter` methods for efficient pattern matching and file filtering. This method is useful for optimizing performance when a pattern is used multiple times. ```python >>> import wcmatch.glob as glob >>> m = glob.compile('**/*.py', flags=glob.GLOBSTAR) >>> m.match('wcmatch/__init__.py') True >>> m.filter(['wcmatch/__init__.py', 'wcmatch/glob.py', 'README.md']) ['wcmatch/__init__.py', 'wcmatch/glob.py'] ``` -------------------------------- ### Handle Cross-Platform Path Separators Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/glob.md Illustrates how to use forward slashes for cross-platform compatibility and how to properly escape backslashes for Windows paths. ```python glob.glob('docs/.*') ``` ```python glob.glob(r'docs\\.*') glob.glob('docs\\\\.*') ``` -------------------------------- ### Globbing with Root Directory and User Path Expansion in Python Source: https://context7.com/facelessuser/wcmatch/llms.txt Demonstrates how to perform glob searches relative to a different directory using `root_dir` and how to expand user home directory paths using `GLOBTILDE`. ```python from wcmatch import glob # Using root_dir to search relative to a different directory glob.glob('*.txt', root_dir='docs/src') # User path expansion glob.glob('~/*.txt', flags=glob.GLOBTILDE) # Expands ~ to user home glob.glob('~root/*.txt', flags=glob.GLOBTILDE) # Specific user ``` -------------------------------- ### Globbing Hidden Files in Node.js Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/about/release.md An example of using node-glob to retrieve hidden files, demonstrating similar behavior to Python's glob implementation regarding directory scanning. ```javascript const glob = require('glob'); glob('.*', {}, function (er, files) { console.log(files); }); ``` -------------------------------- ### Globbing and Matching Special Directories in Python Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/about/release.md Demonstrates how to use pathlib and wcmatch.glob to handle special directory references. Shows that magic patterns like '.*' exclude '.' and '..' while literal patterns include them, and how to use negation flags to filter results. ```pycon3 import pathlib # Globbing hidden files with magic pattern list(pathlib.Path('.').glob('.*')) # Globbing literal directory reference list(pathlib.Path('.').glob('..')) # Matching against special directories pathlib.Path('..').match('.*') from wcmatch import glob glob.glob('.*') glob.glob('..') glob.globmatch('..', '.*') # Using negation flags glob.glob(['..', '!.*'], flags=glob.NEGATE) glob.glob(['..', '!.*'], flags=glob.NEGATE | glob.NODOTDIR) glob.glob(['..', '!..'], flags=glob.NEGATE | glob.NODOTDIR) ``` -------------------------------- ### Deduplicate Pathlib Glob Results Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/about/release.md Demonstrates how wcmatch handles redundant path results caused by pathlib normalization. The example shows default deduplication behavior versus the NOUNIQUE flag which allows duplicate results. ```pycon3 >>> glob.glob(['docs/./src', 'docs/src/.', 'docs/src']) ['docs/./src', 'docs/src/.', 'docs/src'] >>> list(pathlib.Path('.').glob(['docs/./src', 'docs/src/.', 'docs/src'])) [PosixPath('docs/src')] >>> list(pathlib.Path('.').glob(['docs/./src', 'docs/src/.', 'docs/src'], flags=pathlib.NOUNIQUE)) [PosixPath('docs/src'), PosixPath('docs/src'), PosixPath('docs/src')] ``` -------------------------------- ### wcmatch.WcMatch Multi-Pattern Limits Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/wcmatch.md Explains the multi-pattern limits and how to configure them using the `limit` option. ```APIDOC ## Multi-Pattern Limits ### Description The `WcMatch` class allows expanding patterns using `|` and brace expansion. A default limit of 1000 patterns is imposed, which can be adjusted using the `limit` keyword option during initialization. Setting `limit` to `0` removes the restriction. ### Method Applies to `wcmatch.WcMatch` initialization. ### Parameters * **limit** (integer) - Optional - The maximum number of patterns allowed. Defaults to `1000`. Set to `0` for no limit. Introduced in 6.0. ### Request Example ```python from wcmatch import wcmatch # No limit on patterns matcher_unlimited = wcmatch.WcMatch(file_pattern='*.a|*.b|*.c', limit=0) # Custom limit matcher_custom_limit = wcmatch.WcMatch(file_pattern='*.x|*.y', limit=50) ``` ### Response #### Success Response (200) N/A (This describes a configuration option for the constructor.) #### Response Example N/A ``` -------------------------------- ### Compare Dot-file Globbing Behavior Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/glob.md Demonstrates the difference between Python's default glob, WCMatch's default behavior, and Bash-like behavior using the SCANDOTDIR flag. ```pycon3 import glob glob.glob('docs/.*') ``` ```pycon3 from wcmatch import glob glob.glob('docs/.*') ``` ```shell-session $ echo docs/.* ``` ```pycon3 from wcmatch import glob glob.glob('docs/.*', flags=glob.SCANDOTDIR) ``` -------------------------------- ### Expand patterns using BRACE, SPLIT, and EXTMATCH flags Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/wcmatch.md Demonstrates how to use the BRACE, SPLIT, and EXTMATCH flags to expand complex patterns into multiple individual patterns. Note that combining these flags can lead to an exponential increase in generated patterns. ```python >>> expand('test@(this{|that,|other})|*.py', BRACE | SPLIT | EXTMATCH) ['test@(this|that)', 'test@(this|other)', '*.py', '*.py'] ``` -------------------------------- ### wcmatch.WcMatch Initialization Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/wcmatch.md Initializes the WcMatch directory walker object with specified root directory, file patterns, and optional keyword arguments. ```APIDOC ## WcMatch Initialization ### Description Initializes the directory walker object. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **root_dir** (string) - Optional - The root directory to search. Defaults to ".". * **file_pattern** (string) - Optional - One or more patterns separated by `|`. Exceptions can be defined by starting a pattern with `!` (or `-` if `MINUSNEGATE` is set). Defaults to an empty string, which matches all files. * **exclude_pattern** (string) - Optional - Zero or more folder exclude patterns separated by `|`. Exceptions can be defined by starting a pattern with `!` (or `-` if `MINUSNEGATE` is set). * **flags** (integer) - Optional - Flags to alter behavior of folder and file matching. See [Flags](#flags) for more info. Defaults to `0`. * **limit** (integer) - Optional - Allows configuring the max pattern limit. Defaults to `1000`. Set to `0` for no limit. Introduced in 6.0. ### Request Example ```python from wcmatch import wcmatch # Example with basic parameters matcher = wcmatch.WcMatch(root_dir='/path/to/search', file_pattern='*.py|*.txt', exclude_pattern='temp/') # Example with flags and limit matcher_advanced = wcmatch.WcMatch(root_dir='.', file_pattern='**/*.js', flags=wcmatch.WcMatch.HIDDEN, limit=500) ``` ### Response #### Success Response (200) N/A (This is a constructor, it does not return a value directly but initializes an object.) #### Response Example N/A ``` -------------------------------- ### Globbing with Negation and Directory/File Specificity in Python Source: https://context7.com/facelessuser/wcmatch/llms.txt Illustrates advanced globbing techniques including excluding specific patterns using the NEGATE flag, matching only directories, and matching only files using NODIR. ```python from wcmatch import glob # Match all files except certain patterns glob.glob(['**/*.md', '!**/README.md', '!**/_snippets'], flags=glob.NEGATE | glob.GLOBSTAR) # Match directories only (patterns ending with /) glob.glob('**/', flags=glob.GLOBSTAR) # Returns all directories # Match files only with NODIR glob.glob('*', flags=glob.NODIR) # Returns only files, no directories ``` -------------------------------- ### Pathlib.PurePath.match and globmatch - Path Matching Source: https://context7.com/facelessuser/wcmatch/llms.txt Explains the match and globmatch methods for checking if paths conform to specified patterns. Covers right-to-left matching with match(), full path matching with globmatch(), an alias for globmatch() (full_match()), and using REALPATH for filesystem checks. ```python from wcmatch import pathlib path = pathlib.PurePath('project/src/module/file.py') # match() - right-to-left matching (like rglob behavior) path.match('file.py') # True path.match('module/file.py') # True path.match('src/module/file.py') # True path.match('*.py') # True # globmatch() - full path matching path.globmatch('project/**/file.py', flags=pathlib.GLOBSTAR) # True path.globmatch('**/file.py', flags=pathlib.GLOBSTAR) # True path.globmatch('file.py') # False (requires full match) # full_match() - alias for globmatch (Python 3.13+ compatibility) path.full_match('project/**/file.py', flags=pathlib.GLOBSTAR) # True # With REALPATH to check actual filesystem real_path = pathlib.Path('docs') real_path.match('*/', flags=pathlib.REALPATH) # True if 'docs' is a directory ``` -------------------------------- ### Filter Directories with Pattern Matching Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/glob.md Shows how to use globmatch and negation flags to filter directory results, including the use of NODOTDIR for Zsh-like behavior. ```pycon3 from wcmatch import glob glob.globmatch('..', '.*') ``` ```pycon3 from wcmatch import glob glob.glob(['..', '!.*'], flags=glob.NEGATE) ``` ```pycon3 from wcmatch import glob glob.glob(['..', '!.*'], flags=glob.NEGATE | glob.NODOTDIR) glob.glob(['..', '!..'], flags=glob.NEGATE | glob.NODOTDIR) glob.globmatch('..', '.*', flags=glob.NODOTDIR) ``` -------------------------------- ### Instantiate OS-specific Path objects Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/pathlib.md Demonstrates how to use wcmatch.pathlib to create WindowsPath or PosixPath objects. These classes provide path manipulation utilities similar to standard pathlib but integrated with wcmatch's globbing engine. ```pycon3 from wcmatch import pathlib # Example for WindowsPath pathlib.Path('c:/some/path') # Example for PosixPath pathlib.Path('/usr/local/bin') ``` -------------------------------- ### Glob and Path Matching with wcmatch Source: https://context7.com/facelessuser/wcmatch/llms.txt Demonstrates basic glob matching, Windows and Unix path escaping using the glob module. It highlights how to handle special characters and force specific path modes. ```python import wcmatch.glob as glob # Match path with special characters glob.globmatch('some/path?/**file**{}.txt', glob.escape('some/path?/**file**{}.txt')) # True # Windows paths (force Windows mode) glob.escape('C:\\Users\\test?\\file*.txt', unix=False) # Unix paths (force Unix mode) glob.escape('/home/user/test?/*.txt', unix=True) ``` -------------------------------- ### Basic and Recursive Globbing in Python Source: https://context7.com/facelessuser/wcmatch/llms.txt Shows how to use the glob module for finding files. It covers basic wildcard matching and recursive searching using GLOBSTAR and GLOBSTARLONG flags. ```python from wcmatch import glob # Basic globbing - find all markdown files glob.glob('*.md') # ['LICENSE.md', 'README.md'] # Recursive globbing with GLOBSTAR glob.glob('**/*.py', flags=glob.GLOBSTAR) # ['setup.py', 'wcmatch/__init__.py', 'wcmatch/fnmatch.py', ...] # Recursive including symlinks with GLOBSTARLONG glob.glob('***/*.py', flags=glob.GLOBSTARLONG) # Traverses symlinked directories ``` -------------------------------- ### Match, Globmatch, Glob, and RGlob with Path in Python Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/pathlib.md Illustrates various path operations using the Path object, including `match`, `globmatch`, `glob`, and `rglob`. `glob` and `rglob` yield iterators of results from filesystem searches. `match` and `globmatch` on Path objects also do not touch the filesystem by default, but can be forced with the `REALPATH` flag. ```python from wcmatch import pathlib p = pathlib.Path('docs/src') # Check if the path matches a simple pattern print(p.match('src')) # Perform a glob match with recursion enabled print(p.globmatch('**/src', flags=pathlib.GLOBSTAR)) # Recursively find all .txt files print(list(p.glob('**/*.txt', flags=pathlib.GLOBSTAR))) # Recursively find all .txt files (rglob behavior) print(list(p.rglob('*.txt'))) ``` -------------------------------- ### Configure and execute glob matching with WcMatch flags Source: https://context7.com/facelessuser/wcmatch/llms.txt Demonstrates how to combine multiple configuration flags using bitwise OR operators and apply them to a glob search operation. This approach allows for granular control over recursive matching, extended globbing, and dot-file visibility. ```python import wcmatch.glob as glob # Combine flags for recursive, extended, and dot-file matching combined = glob.GLOBSTAR | glob.EXTGLOB | glob.DOTGLOB # Execute the glob search with the configured flags results = glob.glob('**/*.py', flags=combined) ``` -------------------------------- ### Match and Globmatch with PurePath in Python Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/pathlib.md Shows how to use the `match` and `globmatch` methods on a PurePath object. These methods perform pattern matching against the path string without accessing the filesystem. The `globmatch` method supports flags like `GLOBSTAR` for recursive matching. ```python from wcmatch import pathlib p = pathlib.PurePath('docs/src') # Check if the path matches a simple pattern print(p.match('src')) # Perform a glob match with recursion enabled print(p.globmatch('**/src', flags=pathlib.GLOBSTAR)) ``` -------------------------------- ### Expand user paths with GLOBTILDE flag Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/glob.md The GLOBTILDE flag enables tilde expansion for user home directories. It supports both current user expansion and specific user path resolution. ```python from wcmatch import glob glob.glob('~', flags=glob.GLOBTILDE) glob.glob('~root', flags=glob.GLOBTILDE) glob.globmatch('/home/facelessuser/', '~', flags=glob.GLOBTILDE | glob.REALPATH) ``` -------------------------------- ### fnmatch.FORCEWIN (fnmatch.W) and fnmatch.FORCEUNIX (fnmatch.U) Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/fnmatch.md Flags to force cross-platform path matching logic, allowing Windows-style matching on Linux or vice versa. ```APIDOC ## FORCEWIN (W) / FORCEUNIX (U) ### Description - **FORCEWIN**: Forces Windows name and case logic on Linux/Unix systems, including slash normalization. - **FORCEUNIX**: Forces Linux/Unix name and case logic on Windows systems. ### Notes - If both `FORCEWIN` and `FORCEUNIX` are provided, both are ignored. - When using `FORCEUNIX`, case sensitivity is default, but can be overridden with `IGNORECASE`. ### Parameters - **flags** (constant) - Required - `fnmatch.FORCEWIN` (or `W`) / `fnmatch.FORCEUNIX` (or `U`) ``` -------------------------------- ### Precompile and Use a Matcher Object Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/fnmatch.md Demonstrates how to precompile a glob pattern into a WcMatcher object for efficient reuse. The compiled matcher can then be used to match individual strings or filter lists of strings. ```python >>> import wcmatch.fnmatch as fnmatch >>> m = fnmatch.compile('*.md') >>> m.match('README.md') True >>> m.filter(['test.txt', 'file.md', 'README.md']) ['file.md', 'README.md'] ``` -------------------------------- ### Import wcmatch.pathlib Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/pathlib.md Imports the wcmatch.pathlib module, which provides enhanced globbing capabilities for Python's pathlib. ```python from wcmatch import pathlib ``` -------------------------------- ### Create Path Object in Python Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/pathlib.md Shows how to instantiate a Path object from wcmatch's pathlib. This object, unlike PurePath, has access to the filesystem. It is system-dependent, creating either a WindowsPath or PosixPath. ```python from wcmatch import pathlib # Create a Path object (system-dependent) path_obj = pathlib.Path('docs/src') # The output will be system-dependent (PosixPath or WindowsPath) print(path_obj) ``` -------------------------------- ### Expand patterns using BRACE and SPLIT Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/glob.md The BRACE flag enables Bash-style brace expansion, while SPLIT allows splitting patterns. Combining these can lead to significant expansion of patterns, which may impact performance during file system crawling. ```python from wcmatch.glob import expand, BRACE, SPLIT, EXTMATCH expand('test@(this{|that,|other})|*.py', BRACE | SPLIT | EXTMATCH) ``` -------------------------------- ### WcMatch Class Initialization Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/wcmatch.md Initializes the WcMatch class, which is designed for finding files using wildcard patterns. It takes the root directory, file patterns, and other optional keyword arguments to configure the search behavior. The default root directory is the current directory, and file patterns can be specified as a single pattern or multiple patterns separated by '|'. ```python class WcMatch: """Finds files by wildcard.""" def __init__(self, root_dir=".", file_pattern=None, **kwargs): """Initialize the directory walker object.""" ``` -------------------------------- ### Python WcMatch on_init Hook: Accept **kwargs Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/about/release.md Demonstrates how to modify the `on_init` hook in the `WcMatch` class to accept arguments as `**kwargs` for cleaner maintenance and usage. This change affects users overriding the `on_init` hook in versions prior to 8.0. ```python # Excplicitly named def on_init(self, key1=value, key2=value): # Or just use `**kwargs` def on_init(self, **kwargs): ``` ```python CustomWcmatch('.', '*.md|*.txt', flags=wcmatch.RECURSIVE, custom_key=value) ``` -------------------------------- ### WcMatch Pattern Syntax Reference Source: https://context7.com/facelessuser/wcmatch/llms.txt Provides a reference for various pattern syntaxes supported by WcMatch, including basic wildcards, POSIX character classes, extended match patterns (EXTMATCH/EXTGLOB), brace expansion (BRACE), path patterns (GLOBSTAR), pattern splitting (SPLIT), and negation patterns (NEGATE). ```python from wcmatch import fnmatch, glob # Basic wildcards fnmatch.fnmatch('file.txt', '*') # Match everything fnmatch.fnmatch('file.txt', '?ile.txt') # Match single character fnmatch.fnmatch('file.txt', '[ft]ile.txt') # Match character in set fnmatch.fnmatch('file.txt', '[!a-e]ile.txt') # Match character NOT in set # POSIX character classes (inside [...]) fnmatch.fnmatch('file123.txt', 'file[[:digit:]]+.txt') # Digits [0-9] fnmatch.fnmatch('FILE.txt', '[[:upper:]]*.txt') # Uppercase [A-Z] fnmatch.fnmatch('file.txt', '[[:lower:]]*.txt') # Lowercase [a-z] fnmatch.fnmatch('file9.txt', '[[:alnum:]]*.txt') # Alphanumeric [a-zA-Z0-9] fnmatch.fnmatch('file_.txt', '[[:word:]]*.txt') # Word chars [a-zA-Z0-9_] # Extended match patterns (requires EXTMATCH/EXTGLOB flag) fnmatch.fnmatch('file.txt', '?(prefix)file.txt', flags=fnmatch.EXTMATCH) # Zero or one fnmatch.fnmatch('file.txt', '*(pre)file.txt', flags=fnmatch.EXTMATCH) # Zero or more fnmatch.fnmatch('prefile.txt', '+(pre)file.txt', flags=fnmatch.EXTMATCH) # One or more fnmatch.fnmatch('file.txt', '@(file|test).txt', flags=fnmatch.EXTMATCH) # Exactly one fnmatch.fnmatch('file.txt', '!(test).txt', flags=fnmatch.EXTMATCH) # Not matching # Brace expansion (requires BRACE flag) fnmatch.fnmatch('file.md', '*.{txt,md,py}', flags=fnmatch.BRACE) # Alternatives fnmatch.fnmatch('file3.txt', 'file{1..5}.txt', flags=fnmatch.BRACE) # Sequences # Path patterns (glob module) glob.globmatch('a/b/c.txt', '**/c.txt', flags=glob.GLOBSTAR) # ** matches directories glob.globmatch('link/file.txt', '***/file.txt', flags=glob.GLOBSTARLONG) # *** follows symlinks # Pattern splitting (requires SPLIT flag) fnmatch.fnmatch('file.py', '*.txt|*.py|*.md', flags=fnmatch.SPLIT) # Negation patterns (requires NEGATE flag) fnmatch.fnmatch('test.txt', '*|!*.py', flags=fnmatch.NEGATE | fnmatch.SPLIT) # ! excludes # With MINUSNEGATE, use - instead of ! fnmatch.fnmatch('test.txt', '*|-*.py', flags=fnmatch.NEGATE | fnmatch.MINUSNEGATE | fnmatch.SPLIT) # ! excludes # Escape special characters fnmatch.fnmatch('file[1].txt', r'file\[1\].txt') # Backslash escapes ``` -------------------------------- ### Python: Basic Glob Pattern Matching Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/glob.md Finds files matching a given glob pattern. Supports a list of patterns, flags, and an optional root directory. Returns a list of matching file paths. Path-like object input is supported in Python 3.6+. ```python from wcmatch import glob # Example: Find all markdown files matching_files = glob.glob('**/*.md') print(matching_files) # Example: Find all markdown files, excluding README.md and a specific directory matching_files_excluded = glob.glob(['**/*.md', '!README.md', '!**/_snippets'], flags=glob.NEGATE) print(matching_files_excluded) # Example: Return only directories when pattern ends with a slash directories = glob.glob('**/') print(directories) # Example: Handling duplicate results similar to Bash # By default, wcmatch returns unique results. unique_results = glob.glob(['*.md', 'README.md']) print(unique_results) # To get duplicate results like Bash, use the NOUNIQUE flag duplicate_results = glob.glob(['*.md', 'README.md'], flags=glob.NOUNIQUE) print(duplicate_results) # Example: Applying exclusion patterns with duplicate results excluded_duplicate = glob.glob(['*.md', 'README.md', '!README.md'], flags=glob.NEGATE | glob.NOUNIQUE) print(excluded_duplicate) # Example: Using BRACE expansion with NOUNIQUE flag brace_expanded = glob.glob('{*,README}.md', flags=glob.BRACE | glob.NOUNIQUE) print(brace_expanded) # Example: Resolving user paths with GLOBTILDE flag home_dir = glob.glob('~', flags=glob.GLOBTILDE) print(home_dir) root_user_dir = glob.glob('~root', flags=glob.GLOBTILDE) print(root_user_dir) # Example: Using root_dir to change the evaluation path without os.chdir all_files = glob.glob('*') print(all_files) files_in_docs_src = glob.glob('*', root_dir='docs/src') print(files_in_docs_src) ``` -------------------------------- ### Precompiling Glob Patterns in Python Source: https://context7.com/facelessuser/wcmatch/llms.txt Demonstrates the use of `glob.compile` to create reusable matcher objects from glob patterns. This is efficient when applying the same pattern to multiple files or lists of files. ```python from wcmatch import glob # Precompile a recursive Python file pattern matcher = glob.compile('**/*.py', flags=glob.GLOBSTAR) # Reuse for matching multiple paths matcher.match('wcmatch/__init__.py') # True matcher.match('README.md') # False # Reuse for filtering paths = ['wcmatch/__init__.py', 'wcmatch/glob.py', 'README.md'] matcher.filter(paths) # ['wcmatch/__init__.py', 'wcmatch/glob.py'] ``` -------------------------------- ### Validate path matches with glob.globmatch Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/glob.md Demonstrates using globmatch to check if a path matches a pattern. It highlights the use of directory descriptors (dir_fd) for filesystem context. ```python import os import glob dir_fd = os.open('docs/src', os.O_RDONLY | os.O_DIRECTORY) glob.globmatch('markdown', 'markdown', flags=glob.REALPATH) # Returns: False glob.globmatch('markdown', 'markdown', flags=glob.REALPATH, dir_fd=dir_fd) # Returns: True ``` -------------------------------- ### Iterator-Based File Search with WcMatch Source: https://context7.com/facelessuser/wcmatch/llms.txt Demonstrates using the `imatch` method for memory-efficient file searching. It covers basic iteration, graceful aborting with `kill()`, checking abort status with `is_aborted()`, resetting the matcher with `reset()`, and retrieving the count of skipped files using `get_skipped()`. ```python from wcmatch import wcmatch # Iterator-based searching wcm = wcmatch.WcMatch('.', '*.py', flags=wcmatch.RECURSIVE) for filepath in wcm.imatch(): print(f"Found: {filepath}") # Process each file as it's found # Graceful abort with kill() wcm = wcmatch.WcMatch('.', '**/*', flags=wcmatch.RECURSIVE) for i, filepath in enumerate(wcm.imatch()): if i >= 10: # Stop after 10 files wcm.kill() break print(filepath) # Check abort status wcm.is_aborted() # True after kill() # Reset for reuse wcm.reset() list(wcm.imatch()) # Can search again # Get count of skipped files wcm = wcmatch.WcMatch('.', '*.py') list(wcm.imatch()) print(f"Skipped {wcm.get_skipped()} files") ``` -------------------------------- ### Create PurePosixPath Object in Python Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/pathlib.md Demonstrates the creation of a PurePosixPath object, useful for working with Posix-style path strings, particularly on Windows systems. This class, like PurePath, does not access the filesystem. ```python import os from wcmatch import pathlib # Example on a Windows system (os.name might be 'nt') # This will still create a PurePosixPath object print(pathlib.PurePosixPath('/usr/local/bin')) ``` -------------------------------- ### WcMatch Flags Reference Source: https://context7.com/facelessuser/wcmatch/llms.txt Lists and describes the available flags for controlling pattern matching behavior across different WcMatch modules, including case sensitivity, extended matching, brace expansion, path matching, and negation. ```python from wcmatch import fnmatch, glob, pathlib, wcmatch # Case sensitivity flags (all modules) fnmatch.CASE # Force case sensitive (fnmatch.C) fnmatch.IGNORECASE # Force case insensitive (fnmatch.I) # Other flags (examples) # fnmatch.EXTMATCH # fnmatch.BRACE # glob.GLOBSTAR # glob.GLOBSTARLONG # fnmatch.SPLIT # fnmatch.NEGATE # fnmatch.MINUSNEGATE ``` -------------------------------- ### Python: Match file path against glob patterns with globmatch Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/glob.md The globmatch function takes a file name, a pattern or list of patterns, and optional flags. It returns a boolean indicating if the file path matches any of the provided patterns. Supports exclusion patterns and various flags like EXTGLOB, NEGATE, GLOBSTAR, and REALPATH. ```python from wcmatch import glob # Basic usage with extended globbing print(glob.globmatch('some/path/test.txt', '**/*/@(*.txt|*.py)', flags=glob.EXTGLOB)) # Usage with multiple patterns print(glob.globmatch('some/path/test.txt', ['**/*/*.txt', '**/*/*.py'])) # Usage with negation (exclusion) patterns print(glob.globmatch('some/path/test.py', '**|!**/*.txt', flags=glob.NEGATE | glob.GLOBSTAR | glob.SPLIT)) print(glob.globmatch('some/path/test.txt', '**|!**/*.txt', flags=glob.NEGATE | glob.GLOBSTAR | glob.SPLIT)) print(glob.globmatch('some/path/test.txt', ['*/*/*.txt', '!*/*/avoid.txt'], flags=glob.NEGATE)) print(glob.globmatch('some/path/avoid.txt', ['*/*/*.txt', '!*/*/avoid.txt'], flags=glob.NEGATE)) # Usage with NEGATEALL flag print(glob.globmatch('some/path/test.py', '!**/*.txt', flags=glob.NEGATE | glob.GLOBSTAR | glob.NEGATEALL)) print(glob.globmatch('some/path/test.txt', '!**/*.txt', flags=glob.NEGATE | glob.GLOBSTAR | glob.NEGATEALL)) # Default behavior (no filesystem interaction) print(glob.globmatch('docs', '*/')) # Usage with REALPATH flag (filesystem interaction) print(glob.globmatch('docs', '*/', flags=glob.REALPATH)) # REALPATH flag with path context print(glob.globmatch('/usr', '**/', flags=glob.G | glob.REALPATH)) print(glob.globmatch('/usr', '**/', flags=glob.G)) # Using root_dir parameter with REALPATH print(glob.globmatch('markdown', 'markdown', flags=glob.REALPATH)) print(glob.globmatch('markdown', 'markdown', flags=glob.REALPATH, root_dir='docs/src')) ``` -------------------------------- ### WcMatch.match Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/wcmatch.md Performs a file match based on the provided patterns and returns a list of matching files. ```APIDOC ## POST /facelessuser/wcmatch/match ### Description Performs a file match based on the provided patterns and returns a list of matching files. ### Method POST ### Endpoint /facelessuser/wcmatch/match ### Parameters #### Query Parameters - **pattern** (string) - Required - The glob pattern to match files against. - **flags** (integer) - Optional - Flags to modify matching behavior (e.g., RECURSIVE, HIDDEN). - **exclude_pattern** (string) - Optional - Patterns to exclude files or directories. ### Request Body ```json { "directory": ".", "pattern": "*.md|*.txt", "flags": 0, "exclude_pattern": "" } ``` ### Response #### Success Response (200) - **files** (array of strings) - A list of file paths that match the pattern. #### Response Example ```json { "files": [ "./LICENSE.md", "./README.md" ] } ``` ``` -------------------------------- ### Import wcmatch.fnmatch Source: https://github.com/facelessuser/wcmatch/blob/main/docs/src/markdown/fnmatch.md Imports the fnmatch module from the wcmatch library. This is the primary module for performing fnmatch-style pattern matching. ```python from wcmatch import fnmatch ```