Last active
December 18, 2023 18:20
-
-
Save jepler/7a09f9672b06851a00eec018bccb7175 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import re | |
S_IFDIR = 16384 | |
def exists(arg): | |
try: | |
os.stat(arg) | |
return True | |
except OSError: | |
return False | |
def isdir(arg): | |
try: | |
return os.stat(arg)[0] & S_IFDIR | |
except OSError: | |
return False | |
_glob_rx = re.compile(r'\[\]?.*?]|\\.|.') | |
def glob_to_re(expr): | |
def replacer(m): | |
if m.group(0) == '*': | |
return '.*' | |
return m.group(0) | |
return re.compile(_glob_rx.sub(replacer, expr) + "$") | |
def glob1(partial, parts, i): | |
if i == len(parts): | |
if exists(partial): | |
yield partial | |
else: | |
part = parts[i] | |
# if not any_special(part): | |
# yield from glob1(partial + "/" + part, parts, i+1) | |
# elif os.isdir(partial): | |
partial_or_root = partial or '/' | |
if isdir(partial_or_root): | |
rx = glob_to_re(part) | |
for name in os.listdir(partial_or_root): | |
if rx.match(name): | |
yield from glob1(partial + "/" + name, parts, i+1) | |
def glob(pattern): | |
rooted = pattern.startswith('/') | |
if rooted: pattern = pattern[1:] | |
parts = pattern.split('/') | |
return glob1('' if rooted else '.', parts, 0) | |
if __name__ == '__main__': | |
for g in glob("/e*"): | |
print("*", g) | |
print() | |
for g in glob("/e*/m*"): | |
print("*", g) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment