utils.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. from __future__ import annotations
  2. import contextlib
  3. import logging
  4. import math
  5. import os
  6. import re
  7. import sys
  8. import tempfile
  9. from collections.abc import Callable, Iterable, Iterator, Sequence
  10. from functools import partial
  11. from hashlib import md5
  12. from importlib.metadata import version
  13. from typing import IO, TYPE_CHECKING, Any, TypeVar
  14. from urllib.parse import urlsplit
  15. if TYPE_CHECKING:
  16. import pathlib
  17. from typing import TypeGuard
  18. from fsspec.spec import AbstractFileSystem
  19. DEFAULT_BLOCK_SIZE = 5 * 2**20
  20. T = TypeVar("T")
  21. def infer_storage_options(
  22. urlpath: str, inherit_storage_options: dict[str, Any] | None = None
  23. ) -> dict[str, Any]:
  24. """Infer storage options from URL path and merge it with existing storage
  25. options.
  26. Parameters
  27. ----------
  28. urlpath: str or unicode
  29. Either local absolute file path or URL (hdfs://namenode:8020/file.csv)
  30. inherit_storage_options: dict (optional)
  31. Its contents will get merged with the inferred information from the
  32. given path
  33. Returns
  34. -------
  35. Storage options dict.
  36. Examples
  37. --------
  38. >>> infer_storage_options('/mnt/datasets/test.csv') # doctest: +SKIP
  39. {"protocol": "file", "path", "/mnt/datasets/test.csv"}
  40. >>> infer_storage_options(
  41. ... 'hdfs://username:pwd@node:123/mnt/datasets/test.csv?q=1',
  42. ... inherit_storage_options={'extra': 'value'},
  43. ... ) # doctest: +SKIP
  44. {"protocol": "hdfs", "username": "username", "password": "pwd",
  45. "host": "node", "port": 123, "path": "/mnt/datasets/test.csv",
  46. "url_query": "q=1", "extra": "value"}
  47. """
  48. # Handle Windows paths including disk name in this special case
  49. if (
  50. re.match(r"^[a-zA-Z]:[\\/]", urlpath)
  51. or re.match(r"^[a-zA-Z0-9]+://", urlpath) is None
  52. ):
  53. return {"protocol": "file", "path": urlpath}
  54. parsed_path = urlsplit(urlpath)
  55. protocol = parsed_path.scheme or "file"
  56. if parsed_path.fragment:
  57. path = "#".join([parsed_path.path, parsed_path.fragment])
  58. else:
  59. path = parsed_path.path
  60. if protocol == "file":
  61. # Special case parsing file protocol URL on Windows according to:
  62. # https://msdn.microsoft.com/en-us/library/jj710207.aspx
  63. windows_path = re.match(r"^/([a-zA-Z])[:|]([\\/].*)$", path)
  64. if windows_path:
  65. drive, path = windows_path.groups()
  66. path = f"{drive}:{path}"
  67. if protocol in ["http", "https"]:
  68. # for HTTP, we don't want to parse, as requests will anyway
  69. return {"protocol": protocol, "path": urlpath}
  70. options: dict[str, Any] = {"protocol": protocol, "path": path}
  71. if parsed_path.netloc:
  72. # Parse `hostname` from netloc manually because `parsed_path.hostname`
  73. # lowercases the hostname which is not always desirable (e.g. in S3):
  74. # https://github.com/dask/dask/issues/1417
  75. options["host"] = parsed_path.netloc.rsplit("@", 1)[-1].rsplit(":", 1)[0]
  76. if protocol in ("s3", "s3a", "gcs", "gs"):
  77. options["path"] = options["host"] + options["path"]
  78. else:
  79. options["host"] = options["host"]
  80. if parsed_path.port:
  81. options["port"] = parsed_path.port
  82. if parsed_path.username:
  83. options["username"] = parsed_path.username
  84. if parsed_path.password:
  85. options["password"] = parsed_path.password
  86. if parsed_path.query:
  87. options["url_query"] = parsed_path.query
  88. if parsed_path.fragment:
  89. options["url_fragment"] = parsed_path.fragment
  90. if inherit_storage_options:
  91. update_storage_options(options, inherit_storage_options)
  92. return options
  93. def update_storage_options(
  94. options: dict[str, Any], inherited: dict[str, Any] | None = None
  95. ) -> None:
  96. if not inherited:
  97. inherited = {}
  98. collisions = set(options) & set(inherited)
  99. if collisions:
  100. for collision in collisions:
  101. if options.get(collision) != inherited.get(collision):
  102. raise KeyError(
  103. f"Collision between inferred and specified storage "
  104. f"option:\n{collision}"
  105. )
  106. options.update(inherited)
  107. # Compression extensions registered via fsspec.compression.register_compression
  108. compressions: dict[str, str] = {}
  109. def infer_compression(filename: str) -> str | None:
  110. """Infer compression, if available, from filename.
  111. Infer a named compression type, if registered and available, from filename
  112. extension. This includes builtin (gz, bz2, zip) compressions, as well as
  113. optional compressions. See fsspec.compression.register_compression.
  114. """
  115. extension = os.path.splitext(filename)[-1].strip(".").lower()
  116. if extension in compressions:
  117. return compressions[extension]
  118. return None
  119. def build_name_function(max_int: float) -> Callable[[int], str]:
  120. """Returns a function that receives a single integer
  121. and returns it as a string padded by enough zero characters
  122. to align with maximum possible integer
  123. >>> name_f = build_name_function(57)
  124. >>> name_f(7)
  125. '07'
  126. >>> name_f(31)
  127. '31'
  128. >>> build_name_function(1000)(42)
  129. '0042'
  130. >>> build_name_function(999)(42)
  131. '042'
  132. >>> build_name_function(0)(0)
  133. '0'
  134. """
  135. # handle corner cases max_int is 0 or exact power of 10
  136. max_int += 1e-8
  137. pad_length = int(math.ceil(math.log10(max_int)))
  138. def name_function(i: int) -> str:
  139. return str(i).zfill(pad_length)
  140. return name_function
  141. def seek_delimiter(file: IO[bytes], delimiter: bytes, blocksize: int) -> bool:
  142. r"""Seek current file to file start, file end, or byte after delimiter seq.
  143. Seeks file to next chunk delimiter, where chunks are defined on file start,
  144. a delimiting sequence, and file end. Use file.tell() to see location afterwards.
  145. Note that file start is a valid split, so must be at offset > 0 to seek for
  146. delimiter.
  147. Parameters
  148. ----------
  149. file: a file
  150. delimiter: bytes
  151. a delimiter like ``b'\n'`` or message sentinel, matching file .read() type
  152. blocksize: int
  153. Number of bytes to read from the file at once.
  154. Returns
  155. -------
  156. Returns True if a delimiter was found, False if at file start or end.
  157. """
  158. if file.tell() == 0:
  159. # beginning-of-file, return without seek
  160. return False
  161. # Interface is for binary IO, with delimiter as bytes, but initialize last
  162. # with result of file.read to preserve compatibility with text IO.
  163. last: bytes | None = None
  164. while True:
  165. current = file.read(blocksize)
  166. if not current:
  167. # end-of-file without delimiter
  168. return False
  169. full = last + current if last else current
  170. try:
  171. if delimiter in full:
  172. i = full.index(delimiter)
  173. file.seek(file.tell() - (len(full) - i) + len(delimiter))
  174. return True
  175. elif len(current) < blocksize:
  176. # end-of-file without delimiter
  177. return False
  178. except (OSError, ValueError):
  179. pass
  180. last = full[-len(delimiter) :]
  181. def read_block(
  182. f: IO[bytes],
  183. offset: int,
  184. length: int | None,
  185. delimiter: bytes | None = None,
  186. split_before: bool = False,
  187. ) -> bytes:
  188. """Read a block of bytes from a file
  189. Parameters
  190. ----------
  191. f: File
  192. Open file
  193. offset: int
  194. Byte offset to start read
  195. length: int
  196. Number of bytes to read, read through end of file if None
  197. delimiter: bytes (optional)
  198. Ensure reading starts and stops at delimiter bytestring
  199. split_before: bool (optional)
  200. Start/stop read *before* delimiter bytestring.
  201. If using the ``delimiter=`` keyword argument we ensure that the read
  202. starts and stops at delimiter boundaries that follow the locations
  203. ``offset`` and ``offset + length``. If ``offset`` is zero then we
  204. start at zero, regardless of delimiter. The bytestring returned WILL
  205. include the terminating delimiter string.
  206. Examples
  207. --------
  208. >>> from io import BytesIO # doctest: +SKIP
  209. >>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP
  210. >>> read_block(f, 0, 13) # doctest: +SKIP
  211. b'Alice, 100\\nBo'
  212. >>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP
  213. b'Alice, 100\\nBob, 200\\n'
  214. >>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP
  215. b'Bob, 200\\nCharlie, 300'
  216. """
  217. if delimiter:
  218. f.seek(offset)
  219. found_start_delim = seek_delimiter(f, delimiter, 2**16)
  220. if length is None:
  221. return f.read()
  222. start = f.tell()
  223. length -= start - offset
  224. f.seek(start + length)
  225. found_end_delim = seek_delimiter(f, delimiter, 2**16)
  226. end = f.tell()
  227. # Adjust split location to before delimiter if seek found the
  228. # delimiter sequence, not start or end of file.
  229. if found_start_delim and split_before:
  230. start -= len(delimiter)
  231. if found_end_delim and split_before:
  232. end -= len(delimiter)
  233. offset = start
  234. length = end - start
  235. f.seek(offset)
  236. # TODO: allow length to be None and read to the end of the file?
  237. assert length is not None
  238. b = f.read(length)
  239. return b
  240. def tokenize(*args: Any, **kwargs: Any) -> str:
  241. """Deterministic token
  242. (modified from dask.base)
  243. >>> tokenize([1, 2, '3'])
  244. '9d71491b50023b06fc76928e6eddb952'
  245. >>> tokenize('Hello') == tokenize('Hello')
  246. True
  247. """
  248. if kwargs:
  249. args += (kwargs,)
  250. try:
  251. h = md5(str(args).encode())
  252. except ValueError:
  253. # FIPS systems: https://github.com/fsspec/filesystem_spec/issues/380
  254. h = md5(str(args).encode(), usedforsecurity=False)
  255. return h.hexdigest()
  256. def stringify_path(filepath: str | os.PathLike[str] | pathlib.Path) -> str:
  257. """Attempt to convert a path-like object to a string.
  258. Parameters
  259. ----------
  260. filepath: object to be converted
  261. Returns
  262. -------
  263. filepath_str: maybe a string version of the object
  264. Notes
  265. -----
  266. Objects supporting the fspath protocol are coerced according to its
  267. __fspath__ method.
  268. For backwards compatibility with older Python version, pathlib.Path
  269. objects are specially coerced.
  270. Any other object is passed through unchanged, which includes bytes,
  271. strings, buffers, or anything else that's not even path-like.
  272. """
  273. if isinstance(filepath, str):
  274. return filepath
  275. elif hasattr(filepath, "__fspath__"):
  276. return filepath.__fspath__()
  277. elif hasattr(filepath, "path"):
  278. return filepath.path
  279. else:
  280. return filepath # type: ignore[return-value]
  281. def make_instance(
  282. cls: Callable[..., T], args: Sequence[Any], kwargs: dict[str, Any]
  283. ) -> T:
  284. inst = cls(*args, **kwargs)
  285. inst._determine_worker() # type: ignore[attr-defined]
  286. return inst
  287. def common_prefix(paths: Iterable[str]) -> str:
  288. """For a list of paths, find the shortest prefix common to all"""
  289. parts = [p.split("/") for p in paths]
  290. lmax = min(len(p) for p in parts)
  291. end = 0
  292. for i in range(lmax):
  293. end = all(p[i] == parts[0][i] for p in parts)
  294. if not end:
  295. break
  296. i += end
  297. return "/".join(parts[0][:i])
  298. def other_paths(
  299. paths: list[str],
  300. path2: str | list[str],
  301. exists: bool = False,
  302. flatten: bool = False,
  303. ) -> list[str]:
  304. """In bulk file operations, construct a new file tree from a list of files
  305. Parameters
  306. ----------
  307. paths: list of str
  308. The input file tree
  309. path2: str or list of str
  310. Root to construct the new list in. If this is already a list of str, we just
  311. assert it has the right number of elements.
  312. exists: bool (optional)
  313. For a str destination, it is already exists (and is a dir), files should
  314. end up inside.
  315. flatten: bool (optional)
  316. Whether to flatten the input directory tree structure so that the output files
  317. are in the same directory.
  318. Returns
  319. -------
  320. list of str
  321. """
  322. if isinstance(path2, str):
  323. path2 = path2.rstrip("/")
  324. if flatten:
  325. path2 = ["/".join((path2, p.split("/")[-1])) for p in paths]
  326. else:
  327. cp = common_prefix(paths)
  328. if exists:
  329. cp = cp.rsplit("/", 1)[0]
  330. if not cp and all(not s.startswith("/") for s in paths):
  331. path2 = ["/".join([path2, p]) for p in paths]
  332. else:
  333. path2 = [p.replace(cp, path2, 1) for p in paths]
  334. else:
  335. assert len(paths) == len(path2)
  336. return path2
  337. def is_exception(obj: Any) -> bool:
  338. return isinstance(obj, BaseException)
  339. def isfilelike(f: Any) -> TypeGuard[IO[bytes]]:
  340. return all(hasattr(f, attr) for attr in ["read", "close", "tell"])
  341. def get_protocol(url: str) -> str:
  342. url = stringify_path(url)
  343. parts = re.split(r"(\:\:|\://)", url, maxsplit=1)
  344. if len(parts) > 1:
  345. return parts[0]
  346. return "file"
  347. def get_file_extension(url: str) -> str:
  348. url = stringify_path(url)
  349. ext_parts = url.rsplit(".", 1)
  350. if len(ext_parts) > 1:
  351. return ext_parts[-1]
  352. return ""
  353. def can_be_local(path: str) -> bool:
  354. """Can the given URL be used with open_local?"""
  355. from fsspec import get_filesystem_class
  356. try:
  357. return getattr(get_filesystem_class(get_protocol(path)), "local_file", False)
  358. except (ValueError, ImportError):
  359. # not in registry or import failed
  360. return False
  361. def get_package_version_without_import(name: str) -> str | None:
  362. """For given package name, try to find the version without importing it
  363. Import and package.__version__ is still the backup here, so an import
  364. *might* happen.
  365. Returns either the version string, or None if the package
  366. or the version was not readily found.
  367. """
  368. if name in sys.modules:
  369. mod = sys.modules[name]
  370. if hasattr(mod, "__version__"):
  371. return mod.__version__
  372. try:
  373. return version(name)
  374. except: # noqa: E722
  375. pass
  376. try:
  377. import importlib
  378. mod = importlib.import_module(name)
  379. return mod.__version__
  380. except (ImportError, AttributeError):
  381. return None
  382. def setup_logging(
  383. logger: logging.Logger | None = None,
  384. logger_name: str | None = None,
  385. level: str = "DEBUG",
  386. clear: bool = True,
  387. ) -> logging.Logger:
  388. if logger is None and logger_name is None:
  389. raise ValueError("Provide either logger object or logger name")
  390. logger = logger or logging.getLogger(logger_name)
  391. handle = logging.StreamHandler()
  392. formatter = logging.Formatter(
  393. "%(asctime)s - %(name)s - %(levelname)s - %(funcName)s -- %(message)s"
  394. )
  395. handle.setFormatter(formatter)
  396. if clear:
  397. logger.handlers.clear()
  398. logger.addHandler(handle)
  399. logger.setLevel(level)
  400. return logger
  401. def _unstrip_protocol(name: str, fs: AbstractFileSystem) -> str:
  402. return fs.unstrip_protocol(name)
  403. def mirror_from(
  404. origin_name: str, methods: Iterable[str]
  405. ) -> Callable[[type[T]], type[T]]:
  406. """Mirror attributes and methods from the given
  407. origin_name attribute of the instance to the
  408. decorated class"""
  409. def origin_getter(method: str, self: Any) -> Any:
  410. origin = getattr(self, origin_name)
  411. return getattr(origin, method)
  412. def wrapper(cls: type[T]) -> type[T]:
  413. for method in methods:
  414. wrapped_method = partial(origin_getter, method)
  415. setattr(cls, method, property(wrapped_method))
  416. return cls
  417. return wrapper
  418. @contextlib.contextmanager
  419. def nullcontext(obj: T) -> Iterator[T]:
  420. yield obj
  421. def merge_offset_ranges(
  422. paths: list[str],
  423. starts: list[int] | int,
  424. ends: list[int] | int,
  425. max_gap: int = 0,
  426. max_block: int | None = None,
  427. sort: bool = True,
  428. ) -> tuple[list[str], list[int], list[int]]:
  429. """Merge adjacent byte-offset ranges when the inter-range
  430. gap is <= `max_gap`, and when the merged byte range does not
  431. exceed `max_block` (if specified). By default, this function
  432. will re-order the input paths and byte ranges to ensure sorted
  433. order. If the user can guarantee that the inputs are already
  434. sorted, passing `sort=False` will skip the re-ordering.
  435. """
  436. # Check input
  437. if not isinstance(paths, list):
  438. raise TypeError
  439. if not isinstance(starts, list):
  440. starts = [starts] * len(paths)
  441. if not isinstance(ends, list):
  442. ends = [ends] * len(paths)
  443. if len(starts) != len(paths) or len(ends) != len(paths):
  444. raise ValueError
  445. # Early Return
  446. if len(starts) <= 1:
  447. return paths, starts, ends
  448. starts = [s or 0 for s in starts]
  449. # Sort by paths and then ranges if `sort=True`
  450. if sort:
  451. paths, starts, ends = (
  452. list(v)
  453. for v in zip(
  454. *sorted(
  455. zip(paths, starts, ends),
  456. )
  457. )
  458. )
  459. remove = []
  460. for i, (path, start, end) in enumerate(zip(paths, starts, ends)):
  461. if any(
  462. e is not None and p == path and start >= s and end <= e and i != i2
  463. for i2, (p, s, e) in enumerate(zip(paths, starts, ends))
  464. ):
  465. remove.append(i)
  466. paths = [p for i, p in enumerate(paths) if i not in remove]
  467. starts = [s for i, s in enumerate(starts) if i not in remove]
  468. ends = [e for i, e in enumerate(ends) if i not in remove]
  469. if paths:
  470. # Loop through the coupled `paths`, `starts`, and
  471. # `ends`, and merge adjacent blocks when appropriate
  472. new_paths = paths[:1]
  473. new_starts = starts[:1]
  474. new_ends = ends[:1]
  475. for i in range(1, len(paths)):
  476. if paths[i] == paths[i - 1] and new_ends[-1] is None:
  477. continue
  478. elif (
  479. paths[i] != paths[i - 1]
  480. or ((starts[i] - new_ends[-1]) > max_gap)
  481. or (max_block is not None and (ends[i] - new_starts[-1]) > max_block)
  482. ):
  483. # Cannot merge with previous block.
  484. # Add new `paths`, `starts`, and `ends` elements
  485. new_paths.append(paths[i])
  486. new_starts.append(starts[i])
  487. new_ends.append(ends[i])
  488. else:
  489. # Merge with the previous block by updating the
  490. # last element of `ends`
  491. new_ends[-1] = ends[i]
  492. return new_paths, new_starts, new_ends
  493. # `paths` is empty. Just return input lists
  494. return paths, starts, ends
  495. def file_size(filelike: IO[bytes]) -> int:
  496. """Find length of any open read-mode file-like"""
  497. pos = filelike.tell()
  498. try:
  499. return filelike.seek(0, 2)
  500. finally:
  501. filelike.seek(pos)
  502. @contextlib.contextmanager
  503. def atomic_write(path: str, mode: str = "wb"):
  504. """
  505. A context manager that opens a temporary file next to `path` and, on exit,
  506. replaces `path` with the temporary file, thereby updating `path`
  507. atomically.
  508. """
  509. fd, fn = tempfile.mkstemp(
  510. dir=os.path.dirname(path), prefix=os.path.basename(path) + "-"
  511. )
  512. try:
  513. with open(fd, mode) as fp:
  514. yield fp
  515. except BaseException:
  516. with contextlib.suppress(FileNotFoundError):
  517. os.unlink(fn)
  518. raise
  519. else:
  520. os.replace(fn, path)
  521. def _translate(pat, STAR, QUESTION_MARK):
  522. # Copied from: https://github.com/python/cpython/pull/106703.
  523. res: list[str] = []
  524. add = res.append
  525. i, n = 0, len(pat)
  526. while i < n:
  527. c = pat[i]
  528. i = i + 1
  529. if c == "*":
  530. # compress consecutive `*` into one
  531. if (not res) or res[-1] is not STAR:
  532. add(STAR)
  533. elif c == "?":
  534. add(QUESTION_MARK)
  535. elif c == "[":
  536. j = i
  537. if j < n and pat[j] == "!":
  538. j = j + 1
  539. if j < n and pat[j] == "]":
  540. j = j + 1
  541. while j < n and pat[j] != "]":
  542. j = j + 1
  543. if j >= n:
  544. add("\\[")
  545. else:
  546. stuff = pat[i:j]
  547. if "-" not in stuff:
  548. stuff = stuff.replace("\\", r"\\")
  549. else:
  550. chunks = []
  551. k = i + 2 if pat[i] == "!" else i + 1
  552. while True:
  553. k = pat.find("-", k, j)
  554. if k < 0:
  555. break
  556. chunks.append(pat[i:k])
  557. i = k + 1
  558. k = k + 3
  559. chunk = pat[i:j]
  560. if chunk:
  561. chunks.append(chunk)
  562. else:
  563. chunks[-1] += "-"
  564. # Remove empty ranges -- invalid in RE.
  565. for k in range(len(chunks) - 1, 0, -1):
  566. if chunks[k - 1][-1] > chunks[k][0]:
  567. chunks[k - 1] = chunks[k - 1][:-1] + chunks[k][1:]
  568. del chunks[k]
  569. # Escape backslashes and hyphens for set difference (--).
  570. # Hyphens that create ranges shouldn't be escaped.
  571. stuff = "-".join(
  572. s.replace("\\", r"\\").replace("-", r"\-") for s in chunks
  573. )
  574. # Escape set operations (&&, ~~ and ||).
  575. stuff = re.sub(r"([&~|])", r"\\\1", stuff)
  576. i = j + 1
  577. if not stuff:
  578. # Empty range: never match.
  579. add("(?!)")
  580. elif stuff == "!":
  581. # Negated empty range: match any character.
  582. add(".")
  583. else:
  584. if stuff[0] == "!":
  585. stuff = "^" + stuff[1:]
  586. elif stuff[0] in ("^", "["):
  587. stuff = "\\" + stuff
  588. add(f"[{stuff}]")
  589. else:
  590. add(re.escape(c))
  591. assert i == n
  592. return res
  593. def glob_translate(pat):
  594. # Copied from: https://github.com/python/cpython/pull/106703.
  595. # The keyword parameters' values are fixed to:
  596. # recursive=True, include_hidden=True, seps=None
  597. """Translate a pathname with shell wildcards to a regular expression."""
  598. if os.path.altsep:
  599. seps = os.path.sep + os.path.altsep
  600. else:
  601. seps = os.path.sep
  602. escaped_seps = "".join(map(re.escape, seps))
  603. any_sep = f"[{escaped_seps}]" if len(seps) > 1 else escaped_seps
  604. not_sep = f"[^{escaped_seps}]"
  605. one_last_segment = f"{not_sep}+"
  606. one_segment = f"{one_last_segment}{any_sep}"
  607. any_segments = f"(?:.+{any_sep})?"
  608. any_last_segments = ".*"
  609. results = []
  610. parts = re.split(any_sep, pat)
  611. last_part_idx = len(parts) - 1
  612. for idx, part in enumerate(parts):
  613. if part == "*":
  614. results.append(one_segment if idx < last_part_idx else one_last_segment)
  615. continue
  616. if part == "**":
  617. results.append(any_segments if idx < last_part_idx else any_last_segments)
  618. continue
  619. elif "**" in part:
  620. raise ValueError(
  621. "Invalid pattern: '**' can only be an entire path component"
  622. )
  623. if part:
  624. results.extend(_translate(part, f"{not_sep}*", not_sep))
  625. if idx < last_part_idx:
  626. results.append(any_sep)
  627. res = "".join(results)
  628. return rf"(?s:{res})\Z"