utils.py 22 KB

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