Add pathclass.glob, glob_many.

master
voussoir 2021-09-23 22:36:01 -07:00
parent 85ea9ec660
commit 446626f1ce
No known key found for this signature in database
GPG Key ID: 5F7554F8C26DACCB
1 changed files with 44 additions and 2 deletions

View File

@ -2,6 +2,8 @@ import glob
import os import os
import re import re
_glob = glob
from voussoirkit import winglob from voussoirkit import winglob
WINDOWS_GLOBAL_BADCHARS = {'*', '?', '<', '>', '|', '"'} WINDOWS_GLOBAL_BADCHARS = {'*', '?', '<', '>', '|', '"'}
@ -419,7 +421,7 @@ def get_path_casing(path):
pattern = drive + os.sep + pattern pattern = drive + os.sep + pattern
try: try:
cased = glob.glob(pattern)[0] cased = _glob.glob(pattern)[0]
except IndexError: except IndexError:
return input_path.absolute_path return input_path.absolute_path
@ -432,6 +434,46 @@ def get_path_casing(path):
cased += os.sep cased += os.sep
return cased return cased
def glob(pattern, files=None, directories=None):
'''
Just like regular glob, except it returns Path objects instead of strings.
files, directories:
Pass these arguments to filter the results. Leave both as None to get
all items, set either to True to get just those items.
If you want to recurse, consider using spinal.walk with glob_filenames
instead.
'''
if files is None and directories is None:
files = True
directories = True
if not files and not directories:
raise ValueError('files and directories can\'t both be False.')
paths = (Path(p) for p in winglob.glob(pattern))
if files and directories:
return list(paths)
if files:
return [p for p in paths if p.is_file]
if directories:
return [p for p in paths if p.is_dir]
def glob_many(patterns, files=None, directories=None):
'''
Given many glob patterns, yield the results as a single generator.
Saves you from having to write the nested loop.
If you want to recurse, consider using spinal.walk(glob_filenames=[...])
instead. The important difference between this function and spinal.walk is
that spinal.walk starts from a root directory and looks for descendants
that match the glob. This function can take patterns with no common root.
'''
for pattern in patterns:
yield from glob(pattern, files=files, directories=directories)
def glob_patternize(piece): def glob_patternize(piece):
''' '''
Create a pattern like "[u]ser" from "user", forcing glob to look up the Create a pattern like "[u]ser" from "user", forcing glob to look up the
@ -448,7 +490,7 @@ def glob_patternize(piece):
If the path consists entirely of these special characters, then the If the path consists entirely of these special characters, then the
casing doesn't need to be corrected anyway. casing doesn't need to be corrected anyway.
''' '''
piece = glob.escape(piece) piece = _glob.escape(piece)
for character in piece: for character in piece:
if character not in '![]': if character not in '![]':
replacement = f'[{character}]' replacement = f'[{character}]'