Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make glob consistent with glob.glob #1382

Merged
merged 9 commits into from
Oct 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 18 additions & 38 deletions fsspec/asyn.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from .exceptions import FSTimeoutError
from .implementations.local import LocalFileSystem, make_path_posix, trailing_sep
from .spec import AbstractBufferedFile, AbstractFileSystem
from .utils import is_exception, other_paths
from .utils import glob_translate, is_exception, other_paths

private = re.compile("_[^_]")
iothread = [None] # dedicated fsspec IO thread
Expand Down Expand Up @@ -735,8 +735,12 @@ async def _glob(self, path, maxdepth=None, **kwargs):

import re

ends = path.endswith("/")
seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,)
ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash
path = self._strip_protocol(path)
append_slash_to_dirname = ends_with_sep or path.endswith(
tuple(sep + "**" for sep in seps)
)
idx_star = path.find("*") if path.find("*") >= 0 else len(path)
idx_qmark = path.find("?") if path.find("?") >= 0 else len(path)
idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
Expand Down Expand Up @@ -775,46 +779,22 @@ async def _glob(self, path, maxdepth=None, **kwargs):
allpaths = await self._find(
root, maxdepth=depth, withdirs=True, detail=True, **kwargs
)
# Escape characters special to python regex, leaving our supported
# special characters in place.
# See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html
# for shell globbing details.
pattern = (
"^"
+ (
path.replace("\\", r"\\")
.replace(".", r"\.")
.replace("+", r"\+")
.replace("//", "/")
.replace("(", r"\(")
.replace(")", r"\)")
.replace("|", r"\|")
.replace("^", r"\^")
.replace("$", r"\$")
.replace("{", r"\{")
.replace("}", r"\}")
.rstrip("/")
.replace("?", ".")
)
+ "$"
)
pattern = re.sub("/[*]{2}", "=SLASH_DOUBLE_STARS=", pattern)
pattern = re.sub("[*]{2}/?", "=DOUBLE_STARS=", pattern)
pattern = re.sub("[*]", "[^/]*", pattern)
pattern = re.sub("=SLASH_DOUBLE_STARS=", "(|/.*)", pattern)
pattern = re.sub("=DOUBLE_STARS=", ".*", pattern)

pattern = glob_translate(path + ("/" if ends_with_sep else ""))
pattern = re.compile(pattern)

out = {
p: allpaths[p]
for p in sorted(allpaths)
if pattern.match(p.replace("//", "/").rstrip("/"))
p: info
for p, info in sorted(allpaths.items())
if pattern.match(
(
p + "/"
if append_slash_to_dirname and info["type"] == "directory"
else p
)
)
}

# Return directories only when the glob end by a slash
# This is needed for posix glob compliance
if ends:
out = {k: v for k, v in out.items() if v["type"] == "directory"}

if detail:
return out
else:
Expand Down
58 changes: 21 additions & 37 deletions fsspec/implementations/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@
from fsspec.callbacks import _DEFAULT_CALLBACK
from fsspec.exceptions import FSTimeoutError
from fsspec.spec import AbstractBufferedFile
from fsspec.utils import DEFAULT_BLOCK_SIZE, isfilelike, nullcontext, tokenize
from fsspec.utils import (
DEFAULT_BLOCK_SIZE,
glob_translate,
isfilelike,
nullcontext,
tokenize,
)

from ..caching import AllBytes

Expand Down Expand Up @@ -441,8 +447,9 @@ async def _glob(self, path, maxdepth=None, **kwargs):
raise ValueError("maxdepth must be at least 1")
import re

ends = path.endswith("/")
ends_with_slash = path.endswith("/") # _strip_protocol strips trailing slash
path = self._strip_protocol(path)
append_slash_to_dirname = ends_with_slash or path.endswith("/**")
idx_star = path.find("*") if path.find("*") >= 0 else len(path)
idx_brace = path.find("[") if path.find("[") >= 0 else len(path)

Expand Down Expand Up @@ -480,45 +487,22 @@ async def _glob(self, path, maxdepth=None, **kwargs):
allpaths = await self._find(
root, maxdepth=depth, withdirs=True, detail=True, **kwargs
)
# Escape characters special to python regex, leaving our supported
# special characters in place.
# See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html
# for shell globbing details.
pattern = (
"^"
+ (
path.replace("\\", r"\\")
.replace(".", r"\.")
.replace("+", r"\+")
.replace("//", "/")
.replace("(", r"\(")
.replace(")", r"\)")
.replace("|", r"\|")
.replace("^", r"\^")
.replace("$", r"\$")
.replace("{", r"\{")
.replace("}", r"\}")
.rstrip("/")
)
+ "$"
)
pattern = re.sub("/[*]{2}", "=SLASH_DOUBLE_STARS=", pattern)
pattern = re.sub("[*]{2}/?", "=DOUBLE_STARS=", pattern)
pattern = re.sub("[*]", "[^/]*", pattern)
pattern = re.sub("=SLASH_DOUBLE_STARS=", "(|/.*)", pattern)
pattern = re.sub("=DOUBLE_STARS=", ".*", pattern)

pattern = glob_translate(path + ("/" if ends_with_slash else ""))
pattern = re.compile(pattern)

out = {
p: allpaths[p]
for p in sorted(allpaths)
if pattern.match(p.replace("//", "/").rstrip("/"))
p: info
for p, info in sorted(allpaths.items())
if pattern.match(
(
p + "/"
if append_slash_to_dirname and info["type"] == "directory"
else p
)
)
}

# Return directories only when the glob end by a slash
# This is needed for posix glob compliance
if ends:
out = {k: v for k, v in out.items() if v["type"] == "directory"}

if detail:
return out
else:
Expand Down
58 changes: 17 additions & 41 deletions fsspec/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from .transaction import Transaction
from .utils import (
_unstrip_protocol,
glob_translate,
isfilelike,
other_paths,
read_block,
Expand Down Expand Up @@ -551,19 +552,19 @@ def glob(self, path, maxdepth=None, **kwargs):

The `maxdepth` option is applied on the first `**` found in the path.

Search path names that contain embedded characters special to this
implementation of glob may not produce expected results;
e.g., ``foo/bar/*starredfilename*``.

kwargs are passed to ``ls``.
"""
if maxdepth is not None and maxdepth < 1:
raise ValueError("maxdepth must be at least 1")

import re

ends = path.endswith("/")
seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,)
ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash
path = self._strip_protocol(path)
append_slash_to_dirname = ends_with_sep or path.endswith(
tuple(sep + "**" for sep in seps)
)
idx_star = path.find("*") if path.find("*") >= 0 else len(path)
idx_qmark = path.find("?") if path.find("?") >= 0 else len(path)
idx_brace = path.find("[") if path.find("[") >= 0 else len(path)
Expand Down Expand Up @@ -600,47 +601,22 @@ def glob(self, path, maxdepth=None, **kwargs):
depth = None

allpaths = self.find(root, maxdepth=depth, withdirs=True, detail=True, **kwargs)
# Escape characters special to python regex, leaving our supported
# special characters in place.
# See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html
# for shell globbing details.
pattern = (
"^"
+ (
path.replace("\\", r"\\")
.replace(".", r"\.")
.replace("+", r"\+")
.replace("//", "/")
.replace("(", r"\(")
.replace(")", r"\)")
.replace("|", r"\|")
.replace("^", r"\^")
.replace("$", r"\$")
.replace("{", r"\{")
.replace("}", r"\}")
.rstrip("/")
.replace("?", ".")
)
+ "$"
)
pattern = re.sub("/[*]{2}", "=SLASH_DOUBLE_STARS=", pattern)
pattern = re.sub("[*]{2}/?", "=DOUBLE_STARS=", pattern)
pattern = re.sub("[*]", "[^/]*", pattern)
pattern = re.sub("=SLASH_DOUBLE_STARS=", "(|/.*)", pattern)
pattern = re.sub("=DOUBLE_STARS=", ".*", pattern)

pattern = glob_translate(path + ("/" if ends_with_sep else ""))
pattern = re.compile(pattern)

out = {
p: allpaths[p]
for p in sorted(allpaths)
if pattern.match(p.replace("//", "/").rstrip("/"))
p: info
for p, info in sorted(allpaths.items())
if pattern.match(
(
p + "/"
if append_slash_to_dirname and info["type"] == "directory"
else p
)
)
}

# Return directories only when the glob end by a slash
# This is needed for posix glob compliance
if ends:
out = {k: v for k, v in out.items() if v["type"] == "directory"}

if detail:
return out
else:
Expand Down
10 changes: 5 additions & 5 deletions fsspec/tests/abstract/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,9 @@
"subdir1/subfile2",
],
),
("**1", False, None, ["file1", "subdir0/subfile1", "subdir1/subfile1"]),
("**/*1", False, None, ["file1", "subdir0/subfile1", "subdir1/subfile1"]),
(
"**1",
"**/*1",
True,
None,
[
Expand All @@ -120,14 +120,14 @@
"subdir1/nesteddir/nestedfile",
],
),
("**1", True, 1, ["file1"]),
("**/*1", True, 1, ["file1"]),
(
"**1",
"**/*1",
True,
2,
["file1", "subdir0/subfile1", "subdir1/subfile1", "subdir1/subfile2"],
),
("**1", False, 2, ["file1", "subdir0/subfile1", "subdir1/subfile1"]),
("**/*1", False, 2, ["file1", "subdir0/subfile1", "subdir1/subfile1"]),
("**/subdir0", False, None, []),
("**/subdir0", True, None, ["subfile1", "subfile2", "nesteddir/nestedfile"]),
("**/subdir0/nested*", False, 2, []),
Expand Down
Loading
Loading