Amar-Aly commited on
Commit
a68bc02
·
verified ·
1 Parent(s): 2d34725

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .cache/pip/http-v2/5/5/9/a/2/559a28d2d50a6d0988e3c56e5d0d411789da84005e4420f1a26bb23e +0 -0
  2. .cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/_monitor.py +104 -0
  3. .cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/_tqdm_pandas.py +24 -0
  4. .cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/contrib/concurrent.py +105 -0
  5. .cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/contrib/utils_worker.py +38 -0
  6. .cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/std.py +1525 -0
  7. .cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/utils.py +325 -0
  8. .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock-3.29.1.dist-info/METADATA +38 -0
  9. .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock-3.29.1.dist-info/RECORD +19 -0
  10. .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock-3.29.1.dist-info/licenses/LICENSE +21 -0
  11. .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_async_read_write.py +207 -0
  12. .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_error.py +28 -0
  13. .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft.py +227 -0
  14. .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft_rw/__init__.py +12 -0
  15. .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft_rw/_async.py +213 -0
  16. .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft_rw/_sync.py +849 -0
  17. .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_unix.py +116 -0
  18. .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_windows.py +111 -0
  19. .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/py.typed +0 -0
  20. .cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/version.py +24 -0
  21. .cache/uv/archive-v0/Qs_dcKhIt99HrPiFoiNRv/typing_extensions-4.15.0.dist-info/METADATA +72 -0
  22. .cache/uv/archive-v0/Qs_dcKhIt99HrPiFoiNRv/typing_extensions-4.15.0.dist-info/WHEEL +4 -0
  23. .cache/uv/archive-v0/Qs_dcKhIt99HrPiFoiNRv/typing_extensions.py +0 -0
  24. .cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc-0.0.4.dist-info/RECORD +8 -0
  25. .cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc-0.0.4.dist-info/WHEEL +4 -0
  26. .cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc/__init__.py +3 -0
  27. .cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc/main.py +36 -0
  28. .cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11-0.16.0.dist-info/METADATA +202 -0
  29. .cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11-0.16.0.dist-info/RECORD +17 -0
  30. .cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11-0.16.0.dist-info/top_level.txt +1 -0
  31. .cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11/_abnf.py +132 -0
  32. .cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11/_state.py +365 -0
  33. .cache/uv/archive-v0/YlYoCgs7J-Rpy5AtSN3P_/httpcore/_exceptions.py +81 -0
  34. .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/LICENSE +13 -0
  35. .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/RECORD +13 -0
  36. .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/WHEEL +6 -0
  37. .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/top_level.txt +1 -0
  38. .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/zip-safe +1 -0
  39. .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/__init__.py +23 -0
  40. .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/_core.py +11 -0
  41. .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/nt.py +163 -0
  42. .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/posix/_core.py +3 -0
  43. .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/posix/proc.py +83 -0
  44. .cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/posix/ps.py +51 -0
  45. .cache/uv/archive-v0/mZts5W47V4a3dXgJR251L/idna/uts46data.py +0 -0
  46. .cache/uv/simple-v18/pypi/certifi.rkyv +0 -0
  47. .cache/uv/simple-v18/pypi/h11.rkyv +0 -0
  48. .cache/uv/simple-v18/pypi/httpcore.rkyv +0 -0
  49. .cache/uv/simple-v18/pypi/markdown-it-py.rkyv +0 -0
  50. .cache/uv/simple-v18/pypi/mdurl.rkyv +0 -0
.cache/pip/http-v2/5/5/9/a/2/559a28d2d50a6d0988e3c56e5d0d411789da84005e4420f1a26bb23e ADDED
Binary file (1.26 kB). View file
 
.cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/_monitor.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ from threading import Event, Thread, current_thread
3
+ from time import time
4
+ from warnings import warn
5
+
6
+ __all__ = ["TMonitor", "TqdmSynchronisationWarning"]
7
+
8
+
9
+ class TqdmSynchronisationWarning(RuntimeWarning):
10
+ """
11
+ tqdm multi-thread/-process errors which may cause incorrect nesting
12
+ but otherwise no adverse effects
13
+ """
14
+
15
+
16
+ class TMonitor(Thread):
17
+ """
18
+ Monitoring thread for tqdm bars.
19
+ Monitors if tqdm bars are taking too much time to display
20
+ and readjusts miniters automatically if necessary.
21
+
22
+ Parameters
23
+ ----------
24
+ tqdm_cls : class
25
+ tqdm class to use (can be core tqdm or a submodule).
26
+ sleep_interval : float
27
+ Time to sleep between monitoring checks.
28
+ """
29
+ _test = {} # internal vars for unit testing
30
+
31
+ def __init__(self, tqdm_cls, sleep_interval):
32
+ Thread.__init__(self, name="tqdm_monitor")
33
+ self.daemon = True # kill thread when main killed (KeyboardInterrupt)
34
+ self.woken = 0 # last time woken up, to sync with monitor
35
+ self.tqdm_cls = tqdm_cls
36
+ self.sleep_interval = sleep_interval
37
+ self._time = self._test.get("time", time)
38
+ self.was_killed = self._test.get("Event", Event)()
39
+ atexit.register(self._atexit_signal)
40
+ self.start()
41
+
42
+ def _atexit_signal(self):
43
+ """
44
+ Non-joining shutdown signal.
45
+ Avoids deadlocks at interpreter exit from other threads, dead forks, etc.
46
+ This daemon thread is auto-reaped on shutdown without needing a join.
47
+ """
48
+ self.was_killed.set()
49
+
50
+ def exit(self):
51
+ self.was_killed.set()
52
+ if self is not current_thread():
53
+ self.join()
54
+ return self.report()
55
+
56
+ def get_instances(self):
57
+ # returns a copy of started `tqdm_cls` instances
58
+ return [i for i in self.tqdm_cls._instances.copy()
59
+ # Avoid race by checking that the instance started
60
+ if hasattr(i, 'start_t')]
61
+
62
+ def run(self):
63
+ cur_t = self._time()
64
+ while True:
65
+ # After processing and before sleeping, notify that we woke
66
+ # Need to be done just before sleeping
67
+ self.woken = cur_t
68
+ # Sleep some time...
69
+ self.was_killed.wait(self.sleep_interval)
70
+ # Quit if killed
71
+ if self.was_killed.is_set():
72
+ return
73
+ # Then monitor!
74
+ # Acquire lock (to access _instances)
75
+ with self.tqdm_cls.get_lock():
76
+ cur_t = self._time()
77
+ # Check tqdm instances are waiting too long to print
78
+ instances = self.get_instances()
79
+ for instance in instances:
80
+ # Check event in loop to reduce blocking time on exit
81
+ if self.was_killed.is_set():
82
+ return
83
+ # Only if mininterval > 1 (else iterations are just slow)
84
+ # and last refresh exceeded maxinterval
85
+ if (
86
+ instance.miniters > 1
87
+ and (cur_t - instance.last_print_t) >= instance.maxinterval
88
+ ):
89
+ # force bypassing miniters on next iteration
90
+ # (dynamic_miniters adjusts mininterval automatically)
91
+ instance.miniters = 1
92
+ # Refresh now! (works only for manual tqdm)
93
+ instance.refresh(nolock=True)
94
+ # Remove accidental long-lived strong reference
95
+ del instance
96
+ if instances != self.get_instances(): # pragma: nocover
97
+ warn("Set changed size during iteration" +
98
+ " (see https://github.com/tqdm/tqdm/issues/481)",
99
+ TqdmSynchronisationWarning, stacklevel=2)
100
+ # Remove accidental long-lived strong references
101
+ del instances
102
+
103
+ def report(self):
104
+ return not self.was_killed.is_set()
.cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/_tqdm_pandas.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ __author__ = "github.com/casperdcl"
4
+ __all__ = ['tqdm_pandas']
5
+
6
+
7
+ def tqdm_pandas(tclass, **tqdm_kwargs):
8
+ """
9
+ Registers the given `tqdm` instance with
10
+ `pandas.core.groupby.DataFrameGroupBy.progress_apply`.
11
+ """
12
+ from tqdm import TqdmDeprecationWarning
13
+
14
+ if isinstance(tclass, type) or (getattr(tclass, '__name__', '').startswith(
15
+ 'tqdm_')): # delayed adapter case
16
+ TqdmDeprecationWarning(
17
+ "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm, ...)`.",
18
+ fp_write=getattr(tqdm_kwargs.get('file', None), 'write', sys.stderr.write))
19
+ tclass.pandas(**tqdm_kwargs)
20
+ else:
21
+ TqdmDeprecationWarning(
22
+ "Please use `tqdm.pandas(...)` instead of `tqdm_pandas(tqdm(...))`.",
23
+ fp_write=getattr(tclass.fp, 'write', sys.stderr.write))
24
+ type(tclass).pandas(deprecated_t=tclass)
.cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/contrib/concurrent.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Thin wrappers around `concurrent.futures`.
3
+ """
4
+ from contextlib import contextmanager
5
+ from operator import length_hint
6
+ from os import cpu_count
7
+
8
+ from ..auto import tqdm as tqdm_auto
9
+ from ..std import TqdmWarning
10
+
11
+ __author__ = {"github.com/": ["casperdcl"]}
12
+ __all__ = ['thread_map', 'process_map']
13
+
14
+
15
+ @contextmanager
16
+ def ensure_lock(tqdm_class, lock_name=""):
17
+ """get (create if necessary) and then restore `tqdm_class`'s lock"""
18
+ old_lock = getattr(tqdm_class, '_lock', None) # don't create a new lock
19
+ lock = old_lock or tqdm_class.get_lock() # maybe create a new lock
20
+ lock = getattr(lock, lock_name, lock) # maybe subtype
21
+ tqdm_class.set_lock(lock)
22
+ yield lock
23
+ if old_lock is None:
24
+ del tqdm_class._lock
25
+ else:
26
+ tqdm_class.set_lock(old_lock)
27
+
28
+
29
+ def _executor_map(PoolExecutor, fn, *iterables, **tqdm_kwargs):
30
+ """
31
+ Implementation of `thread_map` and `process_map`.
32
+
33
+ Parameters
34
+ ----------
35
+ tqdm_class : [default: tqdm.auto.tqdm].
36
+ max_workers : [default: min(32, cpu_count() + 4)].
37
+ chunksize : [default: 1].
38
+ lock_name : [default: "":str].
39
+ """
40
+ kwargs = tqdm_kwargs.copy()
41
+ if "total" not in kwargs:
42
+ kwargs["total"] = length_hint(iterables[0])
43
+ tqdm_class = kwargs.pop("tqdm_class", tqdm_auto)
44
+ max_workers = kwargs.pop("max_workers", min(32, cpu_count() + 4))
45
+ chunksize = kwargs.pop("chunksize", 1)
46
+ lock_name = kwargs.pop("lock_name", "")
47
+ with ensure_lock(tqdm_class, lock_name=lock_name) as lk:
48
+ # share lock in case workers are already using `tqdm`
49
+ with PoolExecutor(max_workers=max_workers, initializer=tqdm_class.set_lock,
50
+ initargs=(lk,)) as ex:
51
+ return list(tqdm_class(ex.map(fn, *iterables, chunksize=chunksize), **kwargs))
52
+
53
+
54
+ def thread_map(fn, *iterables, **tqdm_kwargs):
55
+ """
56
+ Equivalent of `list(map(fn, *iterables))`
57
+ driven by `concurrent.futures.ThreadPoolExecutor`.
58
+
59
+ Parameters
60
+ ----------
61
+ tqdm_class : optional
62
+ `tqdm` class to use for bars [default: tqdm.auto.tqdm].
63
+ max_workers : int, optional
64
+ Maximum number of workers to spawn; passed to
65
+ `concurrent.futures.ThreadPoolExecutor.__init__`.
66
+ [default: max(32, cpu_count() + 4)].
67
+ """
68
+ from concurrent.futures import ThreadPoolExecutor
69
+ return _executor_map(ThreadPoolExecutor, fn, *iterables, **tqdm_kwargs)
70
+
71
+
72
+ def process_map(fn, *iterables, **tqdm_kwargs):
73
+ """
74
+ Equivalent of `list(map(fn, *iterables))`
75
+ driven by `concurrent.futures.ProcessPoolExecutor`.
76
+
77
+ Parameters
78
+ ----------
79
+ tqdm_class : optional
80
+ `tqdm` class to use for bars [default: tqdm.auto.tqdm].
81
+ max_workers : int, optional
82
+ Maximum number of workers to spawn; passed to
83
+ `concurrent.futures.ProcessPoolExecutor.__init__`.
84
+ [default: min(32, cpu_count() + 4)].
85
+ chunksize : int, optional
86
+ Size of chunks sent to worker processes; passed to
87
+ `concurrent.futures.ProcessPoolExecutor.map`. [default: 1].
88
+ lock_name : str, optional
89
+ Member of `tqdm_class.get_lock()` to use [default: mp_lock].
90
+ """
91
+ from concurrent.futures import ProcessPoolExecutor
92
+ if iterables and "chunksize" not in tqdm_kwargs:
93
+ # default `chunksize=1` has poor performance for large iterables
94
+ # (most time spent dispatching items to workers).
95
+ longest_iterable_len = max(map(length_hint, iterables))
96
+ if longest_iterable_len > 1000:
97
+ from warnings import warn
98
+ warn("Iterable length %d > 1000 but `chunksize` is not set."
99
+ " This may seriously degrade multiprocess performance."
100
+ " Set `chunksize=1` or more." % longest_iterable_len,
101
+ TqdmWarning, stacklevel=2)
102
+ if "lock_name" not in tqdm_kwargs:
103
+ tqdm_kwargs = tqdm_kwargs.copy()
104
+ tqdm_kwargs["lock_name"] = "mp_lock"
105
+ return _executor_map(ProcessPoolExecutor, fn, *iterables, **tqdm_kwargs)
.cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/contrib/utils_worker.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ IO/concurrency helpers for `tqdm.contrib`.
3
+ """
4
+ from collections import deque
5
+ from concurrent.futures import ThreadPoolExecutor
6
+
7
+ from ..auto import tqdm as tqdm_auto
8
+
9
+ __author__ = {"github.com/": ["casperdcl"]}
10
+ __all__ = ['MonoWorker']
11
+
12
+
13
+ class MonoWorker:
14
+ """
15
+ Supports one running task and one waiting task.
16
+ The waiting task is the most recent submitted (others are discarded).
17
+ """
18
+ def __init__(self):
19
+ self.pool = ThreadPoolExecutor(max_workers=1)
20
+ self.futures = deque([], 2)
21
+
22
+ def submit(self, func, *args, **kwargs):
23
+ """`func(*args, **kwargs)` may replace currently waiting task."""
24
+ futures = self.futures
25
+ if len(futures) == futures.maxlen:
26
+ running = futures.popleft()
27
+ if not running.done():
28
+ if len(futures): # clear waiting
29
+ waiting = futures.pop()
30
+ waiting.cancel()
31
+ futures.appendleft(running) # re-insert running
32
+ try:
33
+ waiting = self.pool.submit(func, *args, **kwargs)
34
+ except Exception as e:
35
+ tqdm_auto.write(str(e))
36
+ else:
37
+ futures.append(waiting)
38
+ return waiting
.cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/std.py ADDED
@@ -0,0 +1,1525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Customisable progressbar decorator for iterators.
3
+ Includes a default `range` iterator printing to `stderr`.
4
+
5
+ Usage:
6
+ >>> from tqdm import trange, tqdm
7
+ >>> for i in trange(10):
8
+ ... ...
9
+ """
10
+ import sys
11
+ from collections import OrderedDict, defaultdict
12
+ from contextlib import contextmanager
13
+ from datetime import datetime, timedelta, timezone
14
+ from numbers import Number
15
+ from time import time
16
+ from warnings import warn
17
+ from weakref import WeakSet
18
+
19
+ from ._monitor import TMonitor
20
+ from .utils import (
21
+ CallbackIOWrapper, Comparable, DisableOnWriteError, FormatReplace, SimpleTextIOWrapper,
22
+ _is_ascii, _screen_shape_wrapper, _supports_unicode, _term_move_up, disp_len, disp_trim,
23
+ envwrap)
24
+
25
+ __author__ = "https://github.com/tqdm/tqdm#contributions"
26
+ __all__ = ['tqdm', 'trange',
27
+ 'TqdmTypeError', 'TqdmKeyError', 'TqdmWarning',
28
+ 'TqdmExperimentalWarning', 'TqdmDeprecationWarning',
29
+ 'TqdmMonitorWarning']
30
+
31
+
32
+ class TqdmTypeError(TypeError):
33
+ pass
34
+
35
+
36
+ class TqdmKeyError(KeyError):
37
+ pass
38
+
39
+
40
+ class TqdmWarning(Warning):
41
+ """base class for all tqdm warnings.
42
+
43
+ Used for non-external-code-breaking errors, such as garbled printing.
44
+ """
45
+ def __init__(self, msg, fp_write=None): # noqa: B042
46
+ if fp_write is not None:
47
+ fp_write("\n" + self.__class__.__name__ + ": " + str(msg).rstrip() + '\n')
48
+ else:
49
+ super().__init__(msg)
50
+
51
+
52
+ class TqdmExperimentalWarning(TqdmWarning, FutureWarning):
53
+ """beta feature, unstable API and behaviour"""
54
+
55
+
56
+ class TqdmDeprecationWarning(TqdmWarning, DeprecationWarning):
57
+ """may be removed in a future release"""
58
+ # not suppressed if raised
59
+
60
+
61
+ class TqdmMonitorWarning(TqdmWarning, RuntimeWarning):
62
+ """tqdm monitor errors which do not affect external functionality"""
63
+
64
+
65
+ def TRLock(*args, **kwargs):
66
+ """threading RLock"""
67
+ try:
68
+ from threading import RLock
69
+ return RLock(*args, **kwargs)
70
+ except (ImportError, OSError): # pragma: no cover
71
+ pass
72
+
73
+
74
+ class TqdmDefaultWriteLock:
75
+ """
76
+ Provide a default write lock for thread and multiprocessing safety.
77
+ Works only on platforms supporting `fork` (so Windows is excluded).
78
+ You must initialise a `tqdm` or `TqdmDefaultWriteLock` instance
79
+ before forking in order for the write lock to work.
80
+ On Windows, you need to supply the lock from the parent to the children as
81
+ an argument to joblib or the parallelism lib you use.
82
+ """
83
+ # global thread lock so no setup required for multithreading.
84
+ # NB: Do not create multiprocessing lock as it sets the multiprocessing
85
+ # context, disallowing `spawn()`/`forkserver()`
86
+ th_lock = TRLock()
87
+
88
+ def __init__(self):
89
+ # Create global parallelism locks to avoid racing issues with parallel
90
+ # bars works only if fork available (Linux/MacOSX, but not Windows)
91
+ cls = type(self)
92
+ root_lock = cls.th_lock
93
+ if root_lock is not None:
94
+ root_lock.acquire()
95
+ cls.create_mp_lock()
96
+ self.locks = [lk for lk in [cls.mp_lock, cls.th_lock] if lk is not None]
97
+ if root_lock is not None:
98
+ root_lock.release()
99
+
100
+ def acquire(self, *a, **k):
101
+ for lock in self.locks:
102
+ lock.acquire(*a, **k)
103
+
104
+ def release(self):
105
+ for lock in self.locks[::-1]: # Release in inverse order of acquisition
106
+ lock.release()
107
+
108
+ def __enter__(self):
109
+ self.acquire()
110
+
111
+ def __exit__(self, *exc):
112
+ self.release()
113
+
114
+ @classmethod
115
+ def create_mp_lock(cls):
116
+ if not hasattr(cls, 'mp_lock'):
117
+ try:
118
+ from multiprocessing import RLock
119
+ cls.mp_lock = RLock()
120
+ except (ImportError, OSError): # pragma: no cover
121
+ cls.mp_lock = None
122
+
123
+ @classmethod
124
+ def create_th_lock(cls):
125
+ assert hasattr(cls, 'th_lock')
126
+ warn("create_th_lock not needed anymore", TqdmDeprecationWarning, stacklevel=2)
127
+
128
+
129
+ class Bar:
130
+ """
131
+ `str.format`-able bar with format specifiers: `[width][type]`
132
+
133
+ - `width`
134
+ + unspecified (default): use `self.default_len`
135
+ + `int >= 0`: overrides `self.default_len`
136
+ + `int < 0`: subtract from `self.default_len`
137
+ - `type`
138
+ + `a`: ascii (`charset=self.ASCII` override)
139
+ + `u`: unicode (`charset=self.UTF` override)
140
+ + `b`: blank (`charset=" "` override)
141
+ """
142
+ ASCII = " 123456789#"
143
+ UTF = " " + ''.join(map(chr, range(0x258F, 0x2587, -1)))
144
+ BLANK = " "
145
+ COLOUR_RESET = '\x1b[0m'
146
+ COLOUR_RGB = '\x1b[38;2;%d;%d;%dm'
147
+ COLOURS = {'BLACK': '\x1b[30m', 'RED': '\x1b[31m', 'GREEN': '\x1b[32m',
148
+ 'YELLOW': '\x1b[33m', 'BLUE': '\x1b[34m', 'MAGENTA': '\x1b[35m',
149
+ 'CYAN': '\x1b[36m', 'WHITE': '\x1b[37m'}
150
+
151
+ def __init__(self, frac, default_len=10, charset=UTF, colour=None):
152
+ if not 0 <= frac <= 1:
153
+ warn("clamping frac to range [0, 1]", TqdmWarning, stacklevel=2)
154
+ frac = max(0, min(1, frac))
155
+ assert default_len > 0
156
+ self.frac = frac
157
+ self.default_len = default_len
158
+ self.charset = charset
159
+ self.colour = colour
160
+
161
+ @property
162
+ def colour(self):
163
+ return self._colour
164
+
165
+ @colour.setter
166
+ def colour(self, value):
167
+ if not value:
168
+ self._colour = None
169
+ return
170
+ try:
171
+ if value.upper() in self.COLOURS:
172
+ self._colour = self.COLOURS[value.upper()]
173
+ elif value[0] == '#' and len(value) == 7:
174
+ self._colour = self.COLOUR_RGB % tuple(
175
+ int(i, 16) for i in (value[1:3], value[3:5], value[5:7]))
176
+ else:
177
+ raise KeyError
178
+ except (KeyError, AttributeError):
179
+ warn(f"Unknown colour ({value}); valid choices:"
180
+ f" [hex (#00ff00), {', '.join(self.COLOURS)}]", TqdmWarning, stacklevel=2)
181
+ self._colour = None
182
+
183
+ def __format__(self, format_spec):
184
+ if format_spec:
185
+ _type = format_spec[-1].lower()
186
+ try:
187
+ charset = {'a': self.ASCII, 'u': self.UTF, 'b': self.BLANK}[_type]
188
+ except KeyError:
189
+ charset = self.charset
190
+ else:
191
+ format_spec = format_spec[:-1]
192
+ if format_spec:
193
+ N_BARS = int(format_spec)
194
+ if N_BARS < 0:
195
+ N_BARS += self.default_len
196
+ else:
197
+ N_BARS = self.default_len
198
+ else:
199
+ charset = self.charset
200
+ N_BARS = self.default_len
201
+
202
+ nsyms = len(charset) - 1
203
+ bar_length, frac_bar_length = divmod(int(self.frac * N_BARS * nsyms), nsyms)
204
+
205
+ res = charset[-1] * bar_length
206
+ if bar_length < N_BARS: # whitespace padding
207
+ res = res + charset[frac_bar_length] + charset[0] * (N_BARS - bar_length - 1)
208
+ return self.colour + res + self.COLOUR_RESET if self.colour else res
209
+
210
+
211
+ class EMA:
212
+ """
213
+ Exponential moving average: smoothing to give progressively lower
214
+ weights to older values.
215
+
216
+ Parameters
217
+ ----------
218
+ smoothing : float, optional
219
+ Smoothing factor in range [0, 1], [default: 0.3].
220
+ Increase to give more weight to recent values.
221
+ Ranges from 0 (yields old value) to 1 (yields new value).
222
+ """
223
+ def __init__(self, smoothing=0.3):
224
+ self.alpha = smoothing
225
+ self.last = 0
226
+ self.calls = 0
227
+
228
+ def __call__(self, x=None):
229
+ """
230
+ Parameters
231
+ ----------
232
+ x : float
233
+ New value to include in EMA.
234
+ """
235
+ beta = 1 - self.alpha
236
+ if x is not None:
237
+ self.last = self.alpha * x + beta * self.last
238
+ self.calls += 1
239
+ return self.last / (1 - beta ** self.calls) if self.calls else self.last
240
+
241
+
242
+ class tqdm(Comparable):
243
+ """
244
+ Decorate an iterable object, returning an iterator which acts exactly
245
+ like the original iterable, but prints a dynamically updating
246
+ progressbar every time a value is requested.
247
+
248
+ Parameters
249
+ ----------
250
+ iterable : iterable, optional
251
+ Iterable to decorate with a progressbar.
252
+ Leave blank to manually manage the updates.
253
+ desc : str, optional
254
+ Prefix for the progressbar.
255
+ total : int or float, optional
256
+ The number of expected iterations. If unspecified,
257
+ len(iterable) is used if possible. If float("inf") or as a last
258
+ resort, only basic progress statistics are displayed
259
+ (no ETA, no progressbar).
260
+ If `gui` is True and this parameter needs subsequent updating,
261
+ specify an initial arbitrary large positive number,
262
+ e.g. 9e9.
263
+ leave : bool, optional
264
+ If [default: True], keeps all traces of the progressbar
265
+ upon termination of iteration.
266
+ If `None`, will leave only if `position` is `0`.
267
+ file : `io.TextIOWrapper` or `io.StringIO`, optional
268
+ Specifies where to output the progress messages
269
+ (default: sys.stderr). Uses `file.write(str)` and `file.flush()`
270
+ methods. For encoding, see `write_bytes`.
271
+ ncols : int, optional
272
+ The width of the entire output message. If specified,
273
+ dynamically resizes the progressbar to stay within this bound.
274
+ If unspecified, attempts to use environment width. The
275
+ fallback is a meter width of 10 and no limit for the counter and
276
+ statistics. If 0, will not print any meter (only stats).
277
+ mininterval : float, optional
278
+ Minimum progress display update interval [default: 0.1] seconds.
279
+ maxinterval : float, optional
280
+ Maximum progress display update interval [default: 10] seconds.
281
+ Automatically adjusts `miniters` to correspond to `mininterval`
282
+ after long display update lag. Only works if `dynamic_miniters`
283
+ or monitor thread is enabled.
284
+ miniters : int or float, optional
285
+ Minimum progress display update interval, in iterations.
286
+ If 0 and `dynamic_miniters`, will automatically adjust to equal
287
+ `mininterval` (more CPU efficient, good for tight loops).
288
+ If > 0, will skip display of specified number of iterations.
289
+ Tweak this and `mininterval` to get very efficient loops.
290
+ If your progress is erratic with both fast and slow iterations
291
+ (network, skipping items, etc) you should set miniters=1.
292
+ ascii : bool or str, optional
293
+ If unspecified or False, use unicode (smooth blocks) to fill
294
+ the meter. The fallback is to use ASCII characters " 123456789#".
295
+ disable : bool, optional
296
+ Whether to disable the entire progressbar wrapper
297
+ [default: False]. If set to None, disable on non-TTY.
298
+ unit : str, optional
299
+ String that will be used to define the unit of each iteration
300
+ [default: it].
301
+ unit_scale : bool or int or float, optional
302
+ If 1 or True, the number of iterations will be reduced/scaled
303
+ automatically and a metric prefix following the
304
+ International System of Units standard will be added
305
+ (kilo, mega, etc.) [default: False]. If any other non-zero
306
+ number, will scale `total` and `n`.
307
+ dynamic_ncols : bool, optional
308
+ If set, constantly alters `ncols` and `nrows` to the
309
+ environment (allowing for window resizes) [default: False].
310
+ smoothing : float, optional
311
+ Exponential moving average smoothing factor for speed estimates
312
+ (ignored in GUI mode). Ranges from 0 (average speed) to 1
313
+ (current/instantaneous speed) [default: 0.3].
314
+ bar_format : str, optional
315
+ Specify a custom bar string formatting. May impact performance.
316
+ [default: '{l_bar}{bar}{r_bar}'], where
317
+ l_bar='{desc}: {percentage:3.0f}%|' and
318
+ r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
319
+ '{rate_fmt}{postfix}]'
320
+ Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
321
+ percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
322
+ rate, rate_fmt, rate_noinv, rate_noinv_fmt,
323
+ rate_inv, rate_inv_fmt, postfix, unit_divisor,
324
+ remaining, remaining_s, eta.
325
+ Note that a trailing ": " is automatically removed after {desc}
326
+ if the latter is empty.
327
+ initial : int or float, optional
328
+ The initial counter value. Useful when restarting a progress
329
+ bar [default: 0]. If using float, consider specifying `{n:.3f}`
330
+ or similar in `bar_format`, or specifying `unit_scale`.
331
+ position : int, optional
332
+ Specify the line offset to print this bar (starting from 0)
333
+ Automatic if unspecified.
334
+ Useful to manage multiple bars at once (eg, from threads).
335
+ postfix : dict or *, optional
336
+ Specify additional stats to display at the end of the bar.
337
+ Calls `set_postfix(**postfix)` if possible (dict).
338
+ unit_divisor : float, optional
339
+ [default: 1000], ignored unless `unit_scale` is True.
340
+ write_bytes : bool, optional
341
+ Whether to write bytes. If (default: False) will write unicode.
342
+ lock_args : tuple, optional
343
+ Passed to `refresh` for intermediate output
344
+ (initialisation, iterating, and updating).
345
+ nrows : int, optional
346
+ The screen height. If specified, hides nested bars outside this
347
+ bound. If unspecified, attempts to use environment height.
348
+ The fallback is 20.
349
+ colour : str, optional
350
+ Bar colour (e.g. 'green', '#00ff00').
351
+ delay : float, optional
352
+ Don't display until [default: 0] seconds have elapsed.
353
+ gui : bool, optional
354
+ WARNING: internal parameter - do not use.
355
+ Use tqdm.gui.tqdm(...) instead. If set, will attempt to use
356
+ matplotlib animations for a graphical output [default: False].
357
+
358
+ Returns
359
+ -------
360
+ out : decorated iterator.
361
+ """
362
+
363
+ monitor_interval = 10 # set to 0 to disable the thread
364
+ monitor = None
365
+ _instances = WeakSet()
366
+
367
+ @staticmethod
368
+ def format_sizeof(num, suffix='', divisor=1000):
369
+ """
370
+ Formats a number (greater than unity) with SI Order of Magnitude
371
+ prefixes.
372
+
373
+ Parameters
374
+ ----------
375
+ num : float
376
+ Number ( >= 1) to format.
377
+ suffix : str, optional
378
+ Post-postfix [default: ''].
379
+ divisor : float, optional
380
+ Divisor between prefixes [default: 1000].
381
+
382
+ Returns
383
+ -------
384
+ out : str
385
+ Number with Order of Magnitude SI unit postfix.
386
+ """
387
+ for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
388
+ if abs(num) < 999.5:
389
+ if abs(num) < 99.95:
390
+ if abs(num) < 9.995:
391
+ return f'{num:1.2f}{unit}{suffix}'
392
+ return f'{num:2.1f}{unit}{suffix}'
393
+ return f'{num:3.0f}{unit}{suffix}'
394
+ num /= divisor
395
+ return f'{num:3.1f}Y{suffix}'
396
+
397
+ @staticmethod
398
+ def format_interval(t):
399
+ """
400
+ Formats a number of seconds as a clock time, [H:]MM:SS
401
+
402
+ Parameters
403
+ ----------
404
+ t : int
405
+ Number of seconds.
406
+
407
+ Returns
408
+ -------
409
+ out : str
410
+ [H:]MM:SS
411
+ """
412
+ sign = '-' if t < 0 else ''
413
+ mins, s = divmod(abs(int(t)), 60)
414
+ h, m = divmod(mins, 60)
415
+ return f'{sign}{h:d}:{m:02d}:{s:02d}' if h else f'{sign}{m:02d}:{s:02d}'
416
+
417
+ @staticmethod
418
+ def format_num(n):
419
+ """
420
+ Intelligent scientific notation (.3g).
421
+
422
+ Parameters
423
+ ----------
424
+ n : int or float or Numeric
425
+ A Number.
426
+
427
+ Returns
428
+ -------
429
+ out : str
430
+ Formatted number.
431
+ """
432
+ f = f'{n:.3g}'.replace('e+0', 'e+').replace('e-0', 'e-')
433
+ n = str(n)
434
+ return f if len(f) < len(n) else n
435
+
436
+ @staticmethod
437
+ def status_printer(file):
438
+ """
439
+ Manage the printing and in-place updating of a line of characters.
440
+ Note that if the string is longer than a line, then in-place
441
+ updating may not work (it will print a new line at each refresh).
442
+ """
443
+ fp = file
444
+ fp_flush = getattr(fp, 'flush', lambda: None) # pragma: no cover
445
+ if fp in (sys.stderr, sys.stdout):
446
+ getattr(sys.stderr, 'flush', lambda: None)()
447
+ getattr(sys.stdout, 'flush', lambda: None)()
448
+
449
+ def fp_write(s):
450
+ fp.write(str(s))
451
+ fp_flush()
452
+
453
+ last_len = [0]
454
+
455
+ def print_status(s):
456
+ len_s = disp_len(s)
457
+ fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0)))
458
+ last_len[0] = len_s
459
+
460
+ return print_status
461
+
462
+ @staticmethod
463
+ def format_meter(n, total, elapsed, ncols=None, prefix='',
464
+ ascii=False, # pylint: disable=redefined-builtin
465
+ unit='it', unit_scale=False, rate=None, bar_format=None, postfix=None,
466
+ unit_divisor=1000, initial=0, colour=None, **extra_kwargs):
467
+ """
468
+ Return a string-based progress bar given some parameters
469
+
470
+ Parameters
471
+ ----------
472
+ n : int or float
473
+ Number of finished iterations.
474
+ total : int or float
475
+ The expected total number of iterations. If meaningless (None),
476
+ only basic progress statistics are displayed (no ETA).
477
+ elapsed : float
478
+ Number of seconds passed since start.
479
+ ncols : int, optional
480
+ The width of the entire output message. If specified,
481
+ dynamically resizes `{bar}` to stay within this bound
482
+ [default: None]. If `0`, will not print any bar (only stats).
483
+ The fallback is `{bar:10}`.
484
+ prefix : str, optional
485
+ Prefix message (included in total width) [default: ''].
486
+ Use as {desc} in bar_format string.
487
+ ascii : bool, optional or str, optional
488
+ If not set, use unicode (smooth blocks) to fill the meter
489
+ [default: False]. The fallback is to use ASCII characters
490
+ " 123456789#".
491
+ unit : str, optional
492
+ The iteration unit [default: 'it'].
493
+ unit_scale : bool or int or float, optional
494
+ If 1 or True, the number of iterations will be printed with an
495
+ appropriate SI metric prefix (k = 10^3, M = 10^6, etc.)
496
+ [default: False]. If any other non-zero number, will scale
497
+ `total` and `n`.
498
+ rate : float, optional
499
+ Manual override for iteration rate.
500
+ If [default: None], uses n/elapsed.
501
+ bar_format : str, optional
502
+ Specify a custom bar string formatting. May impact performance.
503
+ [default: '{l_bar}{bar}{r_bar}'], where
504
+ l_bar='{desc}: {percentage:3.0f}%|' and
505
+ r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
506
+ '{rate_fmt}{postfix}]'
507
+ Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
508
+ percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
509
+ rate, rate_fmt, rate_noinv, rate_noinv_fmt,
510
+ rate_inv, rate_inv_fmt, postfix, unit_divisor,
511
+ remaining, remaining_s, eta.
512
+ Note that a trailing ": " is automatically removed after {desc}
513
+ if the latter is empty.
514
+ postfix : *, optional
515
+ Similar to `prefix`, but placed at the end
516
+ (e.g. for additional stats).
517
+ Note: postfix is usually a string (not a dict) for this method,
518
+ and will if possible be set to postfix = ', ' + postfix.
519
+ However other types are supported (#382).
520
+ unit_divisor : float, optional
521
+ [default: 1000], ignored unless `unit_scale` is True.
522
+ initial : int or float, optional
523
+ The initial counter value [default: 0].
524
+ colour : str, optional
525
+ Bar colour (e.g. 'green', '#00ff00').
526
+
527
+ Returns
528
+ -------
529
+ out : Formatted meter and stats, ready to display.
530
+ """
531
+
532
+ # sanity check: total
533
+ if total and n >= (total + 0.5): # allow float imprecision (#849)
534
+ total = None
535
+
536
+ # apply custom scale if necessary
537
+ if unit_scale and unit_scale not in (True, 1):
538
+ if total:
539
+ total *= unit_scale
540
+ n *= unit_scale
541
+ if rate:
542
+ rate *= unit_scale # by default rate = self.avg_dn / self.avg_dt
543
+ unit_scale = False
544
+
545
+ elapsed_str = tqdm.format_interval(elapsed)
546
+
547
+ # if unspecified, attempt to use rate = average speed
548
+ # (we allow manual override since predicting time is an arcane art)
549
+ if rate is None and elapsed:
550
+ rate = (n - initial) / elapsed
551
+ inv_rate = 1 / rate if rate else None
552
+ format_sizeof = tqdm.format_sizeof
553
+ rate_noinv_fmt = ((format_sizeof(rate) if unit_scale else f'{rate:5.2f}')
554
+ if rate else '?') + unit + '/s'
555
+ rate_inv_fmt = (
556
+ (format_sizeof(inv_rate) if unit_scale else f'{inv_rate:5.2f}')
557
+ if inv_rate else '?') + 's/' + unit
558
+ rate_fmt = rate_inv_fmt if inv_rate and inv_rate > 1 else rate_noinv_fmt
559
+
560
+ if unit_scale:
561
+ n_fmt = format_sizeof(n, divisor=unit_divisor)
562
+ total_fmt = format_sizeof(total, divisor=unit_divisor) if total is not None else '?'
563
+ else:
564
+ n_fmt = str(n)
565
+ total_fmt = str(total) if total is not None else '?'
566
+
567
+ try:
568
+ postfix = ', ' + postfix if postfix else ''
569
+ except TypeError:
570
+ pass
571
+
572
+ remaining = (total - n) / rate if rate and total else 0
573
+ remaining_str = tqdm.format_interval(remaining) if rate else '?'
574
+ try:
575
+ eta_dt = (datetime.now() + timedelta(seconds=remaining)
576
+ if rate and total else datetime.fromtimestamp(0, timezone.utc))
577
+ except OverflowError:
578
+ eta_dt = datetime.max
579
+
580
+ # format the stats displayed to the left and right sides of the bar
581
+ if prefix:
582
+ # old prefix setup work around
583
+ bool_prefix_colon_already = (prefix[-2:] == ": ")
584
+ l_bar = prefix if bool_prefix_colon_already else prefix + ": "
585
+ else:
586
+ l_bar = ''
587
+
588
+ r_bar = f'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}{postfix}]'
589
+
590
+ # Custom bar formatting
591
+ # Populate a dict with all available progress indicators
592
+ format_dict = {
593
+ # slight extension of self.format_dict
594
+ 'n': n, 'n_fmt': n_fmt, 'total': total, 'total_fmt': total_fmt,
595
+ 'elapsed': elapsed_str, 'elapsed_s': elapsed,
596
+ 'ncols': ncols, 'desc': prefix or '', 'unit': unit,
597
+ 'rate': inv_rate if inv_rate and inv_rate > 1 else rate,
598
+ 'rate_fmt': rate_fmt, 'rate_noinv': rate,
599
+ 'rate_noinv_fmt': rate_noinv_fmt, 'rate_inv': inv_rate,
600
+ 'rate_inv_fmt': rate_inv_fmt,
601
+ 'postfix': postfix, 'unit_divisor': unit_divisor,
602
+ 'colour': colour,
603
+ # plus more useful definitions
604
+ 'remaining': remaining_str, 'remaining_s': remaining,
605
+ 'l_bar': l_bar, 'r_bar': r_bar, 'eta': eta_dt,
606
+ **extra_kwargs}
607
+
608
+ # total is known: we can predict some stats
609
+ if total:
610
+ # fractional and percentage progress
611
+ frac = n / total
612
+ percentage = frac * 100
613
+
614
+ l_bar += f'{percentage:3.0f}%|'
615
+
616
+ if ncols == 0:
617
+ return l_bar[:-1] + r_bar[1:]
618
+
619
+ format_dict.update(l_bar=l_bar)
620
+ if bar_format:
621
+ format_dict.update(percentage=percentage)
622
+
623
+ # auto-remove colon for empty `{desc}`
624
+ if not prefix:
625
+ bar_format = bar_format.replace("{desc}: ", '')
626
+ else:
627
+ bar_format = "{l_bar}{bar}{r_bar}"
628
+
629
+ full_bar = FormatReplace()
630
+ nobar = bar_format.format(bar=full_bar, **format_dict)
631
+ if not full_bar.format_called:
632
+ return nobar # no `{bar}`; nothing else to do
633
+
634
+ # Formatting progress bar space available for bar's display
635
+ full_bar = Bar(frac,
636
+ max(1, ncols - disp_len(nobar)) if ncols else 10,
637
+ charset=Bar.ASCII if ascii is True else ascii or Bar.UTF,
638
+ colour=colour)
639
+ if not _is_ascii(full_bar.charset) and _is_ascii(bar_format):
640
+ bar_format = str(bar_format)
641
+ res = bar_format.format(bar=full_bar, **format_dict)
642
+ return disp_trim(res, ncols) if ncols else res
643
+
644
+ elif bar_format:
645
+ # user-specified bar_format but no total
646
+ l_bar += '|'
647
+ format_dict.update(l_bar=l_bar, percentage=0)
648
+ full_bar = FormatReplace()
649
+ nobar = bar_format.format(bar=full_bar, **format_dict)
650
+ if not full_bar.format_called:
651
+ return nobar
652
+ full_bar = Bar(0,
653
+ max(1, ncols - disp_len(nobar)) if ncols else 10,
654
+ charset=Bar.BLANK, colour=colour)
655
+ res = bar_format.format(bar=full_bar, **format_dict)
656
+ return disp_trim(res, ncols) if ncols else res
657
+ else:
658
+ # no total: no progressbar, ETA, just progress stats
659
+ return (f'{(prefix + ": ") if prefix else ""}'
660
+ f'{n_fmt}{unit} [{elapsed_str}, {rate_fmt}{postfix}]')
661
+
662
+ def __new__(cls, *_, **__):
663
+ instance = object.__new__(cls)
664
+ with cls.get_lock(): # also constructs lock if non-existent
665
+ cls._instances.add(instance)
666
+ # create monitoring thread
667
+ if cls.monitor_interval and (cls.monitor is None
668
+ or not cls.monitor.report()):
669
+ try:
670
+ cls.monitor = TMonitor(cls, cls.monitor_interval)
671
+ except Exception as e: # pragma: nocover
672
+ warn("tqdm:disabling monitor support"
673
+ " (monitor_interval = 0) due to:\n" + str(e),
674
+ TqdmMonitorWarning, stacklevel=2)
675
+ cls.monitor_interval = 0
676
+ return instance
677
+
678
+ @classmethod
679
+ def _get_free_pos(cls, instance=None):
680
+ """Skips specified instance."""
681
+ positions = {abs(inst.pos) for inst in cls._instances
682
+ if inst is not instance and hasattr(inst, "pos")}
683
+ return min(set(range(len(positions) + 1)).difference(positions))
684
+
685
+ @classmethod
686
+ def _decr_instances(cls, instance):
687
+ """
688
+ Remove from list and reposition another unfixed bar
689
+ to fill the new gap.
690
+
691
+ This means that by default (where all nested bars are unfixed),
692
+ order is not maintained but screen flicker/blank space is minimised.
693
+ (tqdm<=4.44.1 moved ALL subsequent unfixed bars up.)
694
+ """
695
+ with cls._lock:
696
+ try:
697
+ cls._instances.remove(instance)
698
+ except KeyError:
699
+ # if not instance.gui: # pragma: no cover
700
+ # raise
701
+ pass # py2: maybe magically removed already
702
+ # else:
703
+ if not instance.gui:
704
+ last = (instance.nrows or 20) - 1
705
+ # find unfixed (`pos >= 0`) overflow (`pos >= nrows - 1`)
706
+ instances = list(filter(
707
+ lambda i: hasattr(i, "pos") and last <= i.pos,
708
+ cls._instances))
709
+ # set first found to current `pos`
710
+ if instances:
711
+ inst = min(instances, key=lambda i: i.pos)
712
+ inst.clear(nolock=True)
713
+ inst.pos = abs(instance.pos)
714
+
715
+ @classmethod
716
+ def write(cls, s, file=None, end="\n", nolock=False):
717
+ """Print a message via tqdm (without overlap with bars)."""
718
+ fp = file if file is not None else sys.stdout
719
+ with cls.external_write_mode(file=file, nolock=nolock):
720
+ # Write the message
721
+ fp.write(s)
722
+ fp.write(end)
723
+
724
+ @classmethod
725
+ @contextmanager
726
+ def external_write_mode(cls, file=None, nolock=False):
727
+ """
728
+ Disable tqdm within context and refresh tqdm when exits.
729
+ Useful when writing to standard output stream
730
+ """
731
+ fp = file if file is not None else sys.stdout
732
+
733
+ try:
734
+ if not nolock:
735
+ cls.get_lock().acquire()
736
+ # Clear all bars
737
+ inst_cleared = []
738
+ for inst in getattr(cls, '_instances', []):
739
+ # Clear instance if in the target output file
740
+ # or if write output + tqdm output are both either
741
+ # sys.stdout or sys.stderr (because both are mixed in terminal)
742
+ if hasattr(inst, "start_t") and (inst.fp == fp or all(
743
+ f in (sys.stdout, sys.stderr) for f in (fp, inst.fp))):
744
+ inst.clear(nolock=True)
745
+ inst_cleared.append(inst)
746
+ yield
747
+ # Force refresh display of bars we cleared
748
+ for inst in inst_cleared:
749
+ inst.refresh(nolock=True)
750
+ finally:
751
+ if not nolock:
752
+ cls._lock.release()
753
+
754
+ @classmethod
755
+ def set_lock(cls, lock):
756
+ """Set the global lock."""
757
+ cls._lock = lock
758
+
759
+ @classmethod
760
+ def get_lock(cls):
761
+ """Get the global lock. Construct it if it does not exist."""
762
+ if not hasattr(cls, '_lock'):
763
+ cls._lock = TqdmDefaultWriteLock()
764
+ return cls._lock
765
+
766
+ @classmethod
767
+ def pandas(cls, **tqdm_kwargs):
768
+ """
769
+ Registers the current `tqdm` class with
770
+ pandas.core.
771
+ ( frame.DataFrame
772
+ | series.Series
773
+ | groupby.(generic.)DataFrameGroupBy
774
+ | groupby.(generic.)SeriesGroupBy
775
+ ).progress_apply
776
+
777
+ A new instance will be created every time `progress_apply` is called,
778
+ and each instance will automatically `close()` upon completion.
779
+
780
+ Parameters
781
+ ----------
782
+ tqdm_kwargs : arguments for the tqdm instance
783
+
784
+ Examples
785
+ --------
786
+ >>> import pandas as pd
787
+ >>> import numpy as np
788
+ >>> from tqdm import tqdm
789
+ >>> from tqdm.gui import tqdm as tqdm_gui
790
+ >>>
791
+ >>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
792
+ >>> tqdm.pandas(ncols=50) # can use tqdm_gui, optional kwargs, etc
793
+ >>> # Now you can use `progress_apply` instead of `apply`
794
+ >>> df.groupby(0).progress_apply(lambda x: x**2)
795
+
796
+ References
797
+ ----------
798
+ <https://stackoverflow.com/questions/18603270/\
799
+ progress-indicator-during-pandas-operations-python>
800
+ """
801
+ from warnings import catch_warnings, simplefilter
802
+
803
+ from pandas.core.frame import DataFrame
804
+ from pandas.core.series import Series
805
+ try:
806
+ with catch_warnings():
807
+ simplefilter("ignore", category=FutureWarning)
808
+ from pandas import Panel
809
+ except ImportError: # pandas>=1.2.0
810
+ Panel = None
811
+ Rolling, Expanding = None, None
812
+ try: # pandas>=1.0.0
813
+ from pandas.core.window.rolling import _Rolling_and_Expanding
814
+ except ImportError:
815
+ try: # pandas>=0.18.0
816
+ from pandas.core.window import _Rolling_and_Expanding
817
+ except ImportError: # pandas>=1.2.0
818
+ try: # pandas>=1.2.0
819
+ from pandas.core.window.expanding import Expanding
820
+ from pandas.core.window.rolling import Rolling
821
+ _Rolling_and_Expanding = Rolling, Expanding
822
+ except ImportError: # pragma: no cover
823
+ _Rolling_and_Expanding = None
824
+ try: # pandas>=0.25.0
825
+ from pandas.core.groupby.generic import SeriesGroupBy # , NDFrameGroupBy
826
+ from pandas.core.groupby.generic import DataFrameGroupBy
827
+ except ImportError: # pragma: no cover
828
+ try: # pandas>=0.23.0
829
+ from pandas.core.groupby.groupby import DataFrameGroupBy, SeriesGroupBy
830
+ except ImportError:
831
+ from pandas.core.groupby import DataFrameGroupBy, SeriesGroupBy
832
+ try: # pandas>=0.23.0
833
+ from pandas.core.groupby.groupby import GroupBy
834
+ except ImportError: # pragma: no cover
835
+ from pandas.core.groupby import GroupBy
836
+
837
+ try: # pandas>=0.23.0
838
+ from pandas.core.groupby.groupby import PanelGroupBy
839
+ except ImportError:
840
+ try:
841
+ from pandas.core.groupby import PanelGroupBy
842
+ except ImportError: # pandas>=0.25.0
843
+ PanelGroupBy = None
844
+
845
+ tqdm_kwargs = tqdm_kwargs.copy()
846
+ deprecated_t = [tqdm_kwargs.pop('deprecated_t', None)]
847
+
848
+ def inner_generator(df_function='apply'):
849
+ def inner(df, func, *args, **kwargs):
850
+ """
851
+ Parameters
852
+ ----------
853
+ df : (DataFrame|Series)[GroupBy]
854
+ Data (may be grouped).
855
+ func : function
856
+ To be applied on the (grouped) data.
857
+ **kwargs : optional
858
+ Transmitted to `df.apply()`.
859
+ """
860
+
861
+ # Precompute total iterations
862
+ total = tqdm_kwargs.pop("total", getattr(df, 'ngroups', None))
863
+ if total is None: # not grouped
864
+ if df_function == 'applymap':
865
+ total = df.size
866
+ elif isinstance(df, Series):
867
+ total = len(df)
868
+ elif (_Rolling_and_Expanding is None or
869
+ not isinstance(df, _Rolling_and_Expanding)):
870
+ # DataFrame or Panel
871
+ axis = kwargs.get('axis', 0)
872
+ if axis == 'index':
873
+ axis = 0
874
+ elif axis == 'columns':
875
+ axis = 1
876
+ # when axis=0, total is shape[axis1]
877
+ total = df.size // df.shape[axis]
878
+
879
+ # Init bar
880
+ if deprecated_t[0] is not None:
881
+ t = deprecated_t[0]
882
+ deprecated_t[0] = None
883
+ else:
884
+ t = cls(total=total, **tqdm_kwargs)
885
+
886
+ if len(args) > 0:
887
+ # *args intentionally not supported (see #244, #299)
888
+ TqdmDeprecationWarning(
889
+ "Except func, normal arguments are intentionally" +
890
+ " not supported by" +
891
+ " `(DataFrame|Series|GroupBy).progress_apply`." +
892
+ " Use keyword arguments instead.",
893
+ fp_write=getattr(t.fp, 'write', sys.stderr.write))
894
+
895
+ try: # pandas>=1.3.0,<3.0
896
+ from pandas.core.common import is_builtin_func
897
+ except ImportError: # pandas<1.3.0
898
+ is_builtin_func = getattr(df, '_is_builtin_func', lambda f: f)
899
+ try:
900
+ func = is_builtin_func(func)
901
+ except TypeError:
902
+ pass
903
+
904
+ # Define bar updating wrapper
905
+ def wrapper(*args, **kwargs):
906
+ # update tbar correctly
907
+ # it seems `pandas apply` calls `func` twice
908
+ # on the first column/row to decide whether it can
909
+ # take a fast or slow code path; so stop when t.total==t.n
910
+ t.update(n=1 if not t.total or t.n < t.total else 0)
911
+ return func(*args, **kwargs)
912
+
913
+ # Apply the provided function (in **kwargs)
914
+ # on the df using our wrapper (which provides bar updating)
915
+ try:
916
+ return getattr(df, df_function)(wrapper, **kwargs)
917
+ finally:
918
+ t.close()
919
+
920
+ return inner
921
+
922
+ # Monkeypatch pandas to provide easy methods
923
+ # Enable custom tqdm progress in pandas!
924
+ Series.progress_apply = inner_generator()
925
+ SeriesGroupBy.progress_apply = inner_generator()
926
+ Series.progress_map = inner_generator('map')
927
+ SeriesGroupBy.progress_map = inner_generator('map')
928
+
929
+ DataFrame.progress_apply = inner_generator()
930
+ DataFrameGroupBy.progress_apply = inner_generator()
931
+ DataFrame.progress_applymap = inner_generator('applymap')
932
+ DataFrame.progress_map = inner_generator('map')
933
+ DataFrameGroupBy.progress_map = inner_generator('map')
934
+
935
+ if Panel is not None:
936
+ Panel.progress_apply = inner_generator()
937
+ if PanelGroupBy is not None:
938
+ PanelGroupBy.progress_apply = inner_generator()
939
+
940
+ GroupBy.progress_apply = inner_generator()
941
+ GroupBy.progress_aggregate = inner_generator('aggregate')
942
+ GroupBy.progress_transform = inner_generator('transform')
943
+
944
+ if Rolling is not None and Expanding is not None:
945
+ Rolling.progress_apply = inner_generator()
946
+ Expanding.progress_apply = inner_generator()
947
+ elif _Rolling_and_Expanding is not None:
948
+ _Rolling_and_Expanding.progress_apply = inner_generator()
949
+
950
+ # override defaults via env vars
951
+ @envwrap("tqdm", is_method=True, types={'total': float, 'ncols': int, 'miniters': float,
952
+ 'position': int, 'nrows': int})
953
+ def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None,
954
+ ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None,
955
+ ascii=False, # pylint: disable=redefined-builtin
956
+ disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3,
957
+ bar_format=None, initial=0, position=None, postfix=None, unit_divisor=1000,
958
+ write_bytes=False, lock_args=None, nrows=None, colour=None, delay=0.0, gui=False,
959
+ **kwargs):
960
+ """see tqdm.tqdm for arguments"""
961
+ if file is None:
962
+ file = sys.stderr
963
+
964
+ if write_bytes:
965
+ # Despite coercing unicode into bytes, py2 sys.std* streams
966
+ # should have bytes written to them.
967
+ file = SimpleTextIOWrapper(
968
+ file, encoding=getattr(file, 'encoding', None) or 'utf-8')
969
+
970
+ file = DisableOnWriteError(file, tqdm_instance=self)
971
+
972
+ if disable is None and hasattr(file, "isatty") and not file.isatty():
973
+ disable = True
974
+
975
+ if total is None and iterable is not None:
976
+ try:
977
+ total = len(iterable)
978
+ except (TypeError, AttributeError):
979
+ total = None
980
+ if total == float("inf"):
981
+ # Infinite iterations, behave same as unknown
982
+ total = None
983
+
984
+ if disable:
985
+ self.iterable = iterable
986
+ self.disable = disable
987
+ with self._lock:
988
+ self.pos = self._get_free_pos(self)
989
+ self._instances.remove(self)
990
+ self.n = initial
991
+ self.total = total
992
+ self.leave = leave
993
+ return
994
+
995
+ if kwargs:
996
+ self.disable = True
997
+ with self._lock:
998
+ self.pos = self._get_free_pos(self)
999
+ self._instances.remove(self)
1000
+ raise (
1001
+ TqdmDeprecationWarning(
1002
+ "`nested` is deprecated and automated.\n"
1003
+ "Use `position` instead for manual control.\n",
1004
+ fp_write=getattr(file, 'write', sys.stderr.write))
1005
+ if "nested" in kwargs else
1006
+ TqdmKeyError("Unknown argument(s): " + str(kwargs)))
1007
+
1008
+ # Preprocess the arguments
1009
+ if (
1010
+ (ncols is None or nrows is None) and (file in (sys.stderr, sys.stdout))
1011
+ ) or dynamic_ncols: # pragma: no cover
1012
+ if dynamic_ncols:
1013
+ dynamic_ncols = _screen_shape_wrapper()
1014
+ if dynamic_ncols:
1015
+ ncols, nrows = dynamic_ncols(file)
1016
+ else:
1017
+ _dynamic_ncols = _screen_shape_wrapper()
1018
+ if _dynamic_ncols:
1019
+ _ncols, _nrows = _dynamic_ncols(file)
1020
+ if ncols is None:
1021
+ ncols = _ncols
1022
+ if nrows is None:
1023
+ nrows = _nrows
1024
+
1025
+ if miniters is None:
1026
+ miniters = 0
1027
+ dynamic_miniters = True
1028
+ else:
1029
+ dynamic_miniters = False
1030
+
1031
+ if mininterval is None:
1032
+ mininterval = 0
1033
+
1034
+ if maxinterval is None:
1035
+ maxinterval = 0
1036
+
1037
+ if ascii is None:
1038
+ ascii = not _supports_unicode(file)
1039
+
1040
+ if bar_format and ascii is not True and not _is_ascii(ascii):
1041
+ # Convert bar format into unicode since terminal uses unicode
1042
+ bar_format = str(bar_format)
1043
+
1044
+ if smoothing is None:
1045
+ smoothing = 0
1046
+
1047
+ # Store the arguments
1048
+ self.iterable = iterable
1049
+ self.desc = desc or ''
1050
+ self.total = total
1051
+ self.leave = leave
1052
+ self.fp = file
1053
+ self.ncols = ncols
1054
+ self.nrows = nrows
1055
+ self.mininterval = mininterval
1056
+ self.maxinterval = maxinterval
1057
+ self.miniters = miniters
1058
+ self.dynamic_miniters = dynamic_miniters
1059
+ self.ascii = ascii
1060
+ self.disable = disable
1061
+ self.unit = unit
1062
+ self.unit_scale = unit_scale
1063
+ self.unit_divisor = unit_divisor
1064
+ self.initial = initial
1065
+ self.lock_args = lock_args
1066
+ self.delay = delay
1067
+ self.gui = gui
1068
+ self.dynamic_ncols = dynamic_ncols
1069
+ self.smoothing = smoothing
1070
+ self._ema_dn = EMA(smoothing)
1071
+ self._ema_dt = EMA(smoothing)
1072
+ self._ema_miniters = EMA(smoothing)
1073
+ self.bar_format = bar_format
1074
+ self.postfix = None
1075
+ self.colour = colour
1076
+ self._time = time
1077
+ if postfix:
1078
+ try:
1079
+ self.set_postfix(refresh=False, **postfix)
1080
+ except TypeError:
1081
+ self.postfix = postfix
1082
+
1083
+ # Init the iterations counters
1084
+ self.last_print_n = initial
1085
+ self.n = initial
1086
+
1087
+ # if nested, at initial sp() call we replace '\r' by '\n' to
1088
+ # not overwrite the outer progress bar
1089
+ with self._lock:
1090
+ # mark fixed positions as negative
1091
+ self.pos = self._get_free_pos(self) if position is None else -position
1092
+
1093
+ if not gui:
1094
+ # Initialize the screen printer
1095
+ self.sp = self.status_printer(self.fp)
1096
+ if delay <= 0:
1097
+ self.refresh(lock_args=self.lock_args)
1098
+
1099
+ # Init the time counter
1100
+ self.last_print_t = self._time()
1101
+ # NB: Avoid race conditions by setting start_t at the very end of init
1102
+ self.start_t = self.last_print_t
1103
+
1104
+ def __bool__(self):
1105
+ if self.total is not None:
1106
+ return self.total > 0
1107
+ if self.iterable is None:
1108
+ raise TypeError('bool() undefined when iterable == total == None')
1109
+ return bool(self.iterable)
1110
+
1111
+ def __len__(self):
1112
+ return (
1113
+ self.total if self.iterable is None
1114
+ else self.iterable.shape[0] if hasattr(self.iterable, "shape")
1115
+ else len(self.iterable) if hasattr(self.iterable, "__len__")
1116
+ else self.iterable.__length_hint__() if hasattr(self.iterable, "__length_hint__")
1117
+ else getattr(self, "total", None))
1118
+
1119
+ def __reversed__(self):
1120
+ try:
1121
+ orig = self.iterable
1122
+ except AttributeError:
1123
+ raise TypeError("'tqdm' object is not reversible")
1124
+ else:
1125
+ self.iterable = reversed(self.iterable)
1126
+ return self.__iter__()
1127
+ finally:
1128
+ self.iterable = orig
1129
+
1130
+ def __contains__(self, item):
1131
+ contains = getattr(self.iterable, '__contains__', None)
1132
+ return (contains(item) if contains is not None # pylint: disable=not-callable
1133
+ else item in self.__iter__())
1134
+
1135
+ def __enter__(self):
1136
+ return self
1137
+
1138
+ def __exit__(self, exc_type, exc_value, traceback):
1139
+ try:
1140
+ self.close()
1141
+ except AttributeError:
1142
+ # maybe eager thread cleanup upon external error
1143
+ if (exc_type, exc_value, traceback) == (None, None, None):
1144
+ raise
1145
+ warn("AttributeError ignored", TqdmWarning, stacklevel=2)
1146
+
1147
+ def __del__(self):
1148
+ self.close()
1149
+
1150
+ def __str__(self):
1151
+ return self.format_meter(**self.format_dict)
1152
+
1153
+ @property
1154
+ def _comparable(self):
1155
+ return abs(getattr(self, "pos", 1 << 31))
1156
+
1157
+ def __hash__(self):
1158
+ return id(self)
1159
+
1160
+ def __iter__(self):
1161
+ """Backward-compatibility to use: for x in tqdm(iterable)"""
1162
+
1163
+ # Inlining instance variables as locals (speed optimisation)
1164
+ iterable = self.iterable
1165
+
1166
+ # If the bar is disabled, then just walk the iterable
1167
+ # (note: keep this check outside the loop for performance)
1168
+ if self.disable:
1169
+ for obj in iterable:
1170
+ yield obj
1171
+ return
1172
+
1173
+ mininterval = self.mininterval
1174
+ last_print_t = self.last_print_t
1175
+ last_print_n = self.last_print_n
1176
+ min_start_t = self.start_t + self.delay
1177
+ n = self.n
1178
+ time = self._time
1179
+
1180
+ try:
1181
+ for obj in iterable:
1182
+ yield obj
1183
+ # Update and possibly print the progressbar.
1184
+ # Note: does not call self.update(1) for speed optimisation.
1185
+ n += 1
1186
+
1187
+ if n - last_print_n >= self.miniters:
1188
+ cur_t = time()
1189
+ dt = cur_t - last_print_t
1190
+ if dt >= mininterval and cur_t >= min_start_t:
1191
+ self.update(n - last_print_n)
1192
+ last_print_n = self.last_print_n
1193
+ last_print_t = self.last_print_t
1194
+ finally:
1195
+ self.n = n
1196
+ self.close()
1197
+
1198
+ def update(self, n=1):
1199
+ """
1200
+ Manually update the progress bar, useful for streams
1201
+ such as reading files.
1202
+ E.g.:
1203
+ >>> t = tqdm(total=filesize) # Initialise
1204
+ >>> for current_buffer in stream:
1205
+ ... ...
1206
+ ... t.update(len(current_buffer))
1207
+ >>> t.close()
1208
+ The last line is highly recommended, but possibly not necessary if
1209
+ `t.update()` will be called in such a way that `filesize` will be
1210
+ exactly reached and printed.
1211
+
1212
+ Parameters
1213
+ ----------
1214
+ n : int or float, optional
1215
+ Increment to add to the internal counter of iterations
1216
+ [default: 1]. If using float, consider specifying `{n:.3f}`
1217
+ or similar in `bar_format`, or specifying `unit_scale`.
1218
+
1219
+ Returns
1220
+ -------
1221
+ out : bool or None
1222
+ True if a `display()` was triggered.
1223
+ """
1224
+ if self.disable:
1225
+ return
1226
+
1227
+ if n < 0:
1228
+ self.last_print_n += n # for auto-refresh logic to work
1229
+ self.n += n
1230
+
1231
+ # check counter first to reduce calls to time()
1232
+ if self.n - self.last_print_n >= self.miniters:
1233
+ cur_t = self._time()
1234
+ dt = cur_t - self.last_print_t
1235
+ if dt >= self.mininterval and cur_t >= self.start_t + self.delay:
1236
+ cur_t = self._time()
1237
+ dn = self.n - self.last_print_n # >= n
1238
+ if self.smoothing and dt and dn:
1239
+ # EMA (not just overall average)
1240
+ self._ema_dn(dn)
1241
+ self._ema_dt(dt)
1242
+ self.refresh(lock_args=self.lock_args)
1243
+ if self.dynamic_miniters:
1244
+ # If no `miniters` was specified, adjust automatically to the
1245
+ # maximum iteration rate seen so far between two prints.
1246
+ # e.g.: After running `tqdm.update(5)`, subsequent
1247
+ # calls to `tqdm.update()` will only cause an update after
1248
+ # at least 5 more iterations.
1249
+ if self.maxinterval and dt >= self.maxinterval:
1250
+ self.miniters = dn * (self.mininterval or self.maxinterval) / dt
1251
+ elif self.smoothing:
1252
+ # EMA miniters update
1253
+ self.miniters = self._ema_miniters(
1254
+ dn * (self.mininterval / dt if self.mininterval and dt
1255
+ else 1))
1256
+ else:
1257
+ # max iters between two prints
1258
+ self.miniters = max(self.miniters, dn)
1259
+
1260
+ # Store old values for next call
1261
+ self.last_print_n = self.n
1262
+ self.last_print_t = cur_t
1263
+ return True
1264
+
1265
+ def close(self):
1266
+ """Cleanup and (if leave=False) close the progressbar."""
1267
+ if self.disable:
1268
+ return
1269
+
1270
+ # Prevent multiple closures
1271
+ self.disable = True
1272
+
1273
+ # decrement instance pos and remove from internal set
1274
+ pos = abs(self.pos)
1275
+ self._decr_instances(self)
1276
+
1277
+ if self.last_print_t < self.start_t + self.delay:
1278
+ # haven't ever displayed; nothing to clear
1279
+ return
1280
+
1281
+ # GUI mode
1282
+ if getattr(self, 'sp', None) is None:
1283
+ return
1284
+
1285
+ # annoyingly, _supports_unicode isn't good enough
1286
+ def fp_write(s):
1287
+ self.fp.write(str(s))
1288
+
1289
+ try:
1290
+ fp_write('')
1291
+ except ValueError as e:
1292
+ if 'closed' in str(e):
1293
+ return
1294
+ raise # pragma: no cover
1295
+
1296
+ leave = pos == 0 if self.leave is None else self.leave
1297
+
1298
+ with self._lock:
1299
+ if leave:
1300
+ # stats for overall rate (no weighted average)
1301
+ self._ema_dt = lambda: None
1302
+ self.display(pos=0)
1303
+ fp_write('\n')
1304
+ else:
1305
+ # clear previous display
1306
+ if self.display(msg='', pos=pos) and not pos:
1307
+ fp_write('\r')
1308
+
1309
+ def clear(self, nolock=False):
1310
+ """Clear current bar display."""
1311
+ if self.disable:
1312
+ return
1313
+
1314
+ if not nolock:
1315
+ self._lock.acquire()
1316
+ pos = abs(self.pos)
1317
+ if pos < (self.nrows or 20):
1318
+ self.moveto(pos)
1319
+ self.sp('')
1320
+ self.fp.write('\r') # place cursor back at the beginning of line
1321
+ self.moveto(-pos)
1322
+ if not nolock:
1323
+ self._lock.release()
1324
+
1325
+ def refresh(self, nolock=False, lock_args=None):
1326
+ """
1327
+ Force refresh the display of this bar.
1328
+
1329
+ Parameters
1330
+ ----------
1331
+ nolock : bool, optional
1332
+ If `True`, does not lock.
1333
+ If [default: `False`]: calls `acquire()` on internal lock.
1334
+ lock_args : tuple, optional
1335
+ Passed to internal lock's `acquire()`.
1336
+ If specified, will only `display()` if `acquire()` returns `True`.
1337
+ """
1338
+ if self.disable:
1339
+ return
1340
+
1341
+ if not nolock:
1342
+ if lock_args:
1343
+ if not self._lock.acquire(*lock_args):
1344
+ return False
1345
+ else:
1346
+ self._lock.acquire()
1347
+ self.display()
1348
+ if not nolock:
1349
+ self._lock.release()
1350
+ return True
1351
+
1352
+ def unpause(self):
1353
+ """Restart tqdm timer from last print time."""
1354
+ if self.disable:
1355
+ return
1356
+ cur_t = self._time()
1357
+ self.start_t += cur_t - self.last_print_t
1358
+ self.last_print_t = cur_t
1359
+
1360
+ def reset(self, total=None):
1361
+ """
1362
+ Resets to 0 iterations for repeated use.
1363
+
1364
+ Consider combining with `leave=True`.
1365
+
1366
+ Parameters
1367
+ ----------
1368
+ total : int or float, optional. Total to use for the new bar.
1369
+ """
1370
+ self.n = 0
1371
+ if total is not None:
1372
+ self.total = total
1373
+ if self.disable:
1374
+ return
1375
+ self.last_print_n = 0
1376
+ self.last_print_t = self.start_t = self._time()
1377
+ self._ema_dn = EMA(self.smoothing)
1378
+ self._ema_dt = EMA(self.smoothing)
1379
+ self._ema_miniters = EMA(self.smoothing)
1380
+ self.refresh()
1381
+
1382
+ def set_description(self, desc=None, refresh=True):
1383
+ """
1384
+ Set/modify description of the progress bar.
1385
+
1386
+ Parameters
1387
+ ----------
1388
+ desc : str, optional
1389
+ refresh : bool, optional
1390
+ Forces refresh [default: True].
1391
+ """
1392
+ self.desc = desc + ': ' if desc else ''
1393
+ if refresh:
1394
+ self.refresh()
1395
+
1396
+ def set_description_str(self, desc=None, refresh=True):
1397
+ """Set/modify description without ': ' appended."""
1398
+ self.desc = desc or ''
1399
+ if refresh:
1400
+ self.refresh()
1401
+
1402
+ def set_postfix(self, ordered_dict=None, refresh=True, **kwargs):
1403
+ """
1404
+ Set/modify postfix (additional stats)
1405
+ with automatic formatting based on datatype.
1406
+
1407
+ Parameters
1408
+ ----------
1409
+ ordered_dict : dict or OrderedDict, optional
1410
+ refresh : bool, optional
1411
+ Forces refresh [default: True].
1412
+ kwargs : dict, optional
1413
+ """
1414
+ # Sort in alphabetical order to be more deterministic
1415
+ postfix = OrderedDict([] if ordered_dict is None else ordered_dict)
1416
+ for key in sorted(kwargs.keys()):
1417
+ postfix[key] = kwargs[key]
1418
+ # Preprocess stats according to datatype
1419
+ for key in postfix.keys():
1420
+ # Number: limit the length of the string
1421
+ if isinstance(postfix[key], Number):
1422
+ postfix[key] = self.format_num(postfix[key])
1423
+ # Else for any other type, try to get the string conversion
1424
+ elif not isinstance(postfix[key], str):
1425
+ postfix[key] = str(postfix[key])
1426
+ # Else if it's a string, don't need to preprocess anything
1427
+ # Stitch together to get the final postfix
1428
+ self.postfix = ', '.join(key + '=' + postfix[key].strip()
1429
+ for key in postfix.keys())
1430
+ if refresh:
1431
+ self.refresh()
1432
+
1433
+ def set_postfix_str(self, s='', refresh=True):
1434
+ """
1435
+ Postfix without dictionary expansion, similar to prefix handling.
1436
+ """
1437
+ self.postfix = str(s)
1438
+ if refresh:
1439
+ self.refresh()
1440
+
1441
+ def moveto(self, n):
1442
+ # TODO: private method
1443
+ self.fp.write('\n' * n + _term_move_up() * -n)
1444
+ getattr(self.fp, 'flush', lambda: None)()
1445
+
1446
+ @property
1447
+ def format_dict(self):
1448
+ """Public API for read-only member access."""
1449
+ if self.disable and not hasattr(self, 'unit'):
1450
+ return defaultdict(lambda: None, {
1451
+ 'n': self.n, 'total': self.total, 'elapsed': 0, 'unit': 'it'})
1452
+ if self.dynamic_ncols:
1453
+ self.ncols, self.nrows = self.dynamic_ncols(self.fp)
1454
+ return {
1455
+ 'n': self.n, 'total': self.total,
1456
+ 'elapsed': self._time() - self.start_t if hasattr(self, 'start_t') else 0,
1457
+ 'ncols': self.ncols, 'nrows': self.nrows, 'prefix': self.desc,
1458
+ 'ascii': self.ascii, 'unit': self.unit, 'unit_scale': self.unit_scale,
1459
+ 'rate': self._ema_dn() / self._ema_dt() if self._ema_dt() else None,
1460
+ 'bar_format': self.bar_format, 'postfix': self.postfix,
1461
+ 'unit_divisor': self.unit_divisor, 'initial': self.initial,
1462
+ 'colour': self.colour}
1463
+
1464
+ def display(self, msg=None, pos=None):
1465
+ """
1466
+ Use `self.sp` to display `msg` in the specified `pos`.
1467
+
1468
+ Consider overloading this function when inheriting to use e.g.:
1469
+ `self.some_frontend(**self.format_dict)` instead of `self.sp`.
1470
+
1471
+ Parameters
1472
+ ----------
1473
+ msg : str, optional. What to display (default: `repr(self)`).
1474
+ pos : int, optional. Position to `moveto`
1475
+ (default: `abs(self.pos)`).
1476
+ """
1477
+ if pos is None:
1478
+ pos = abs(self.pos)
1479
+
1480
+ nrows = self.nrows or 20
1481
+ if pos >= nrows - 1:
1482
+ if pos >= nrows:
1483
+ return False
1484
+ if msg or msg is None: # override at `nrows - 1`
1485
+ msg = " ... (more hidden) ..."
1486
+
1487
+ if not hasattr(self, "sp"):
1488
+ raise TqdmDeprecationWarning(
1489
+ "Please use `tqdm.gui.tqdm(...)`"
1490
+ " instead of `tqdm(..., gui=True)`\n",
1491
+ fp_write=getattr(self.fp, 'write', sys.stderr.write))
1492
+
1493
+ if pos:
1494
+ self.moveto(pos)
1495
+ self.sp(self.__str__() if msg is None else msg)
1496
+ if pos:
1497
+ self.moveto(-pos)
1498
+ return True
1499
+
1500
+ @classmethod
1501
+ @contextmanager
1502
+ def wrapattr(cls, stream, method, total=None, bytes=True, # pylint: disable=redefined-builtin
1503
+ **tqdm_kwargs):
1504
+ """
1505
+ stream : file-like object.
1506
+ method : str, "read" or "write". The result of `read()` and
1507
+ the first argument of `write()` should have a `len()`.
1508
+
1509
+ >>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
1510
+ ... while True:
1511
+ ... chunk = fobj.read(chunk_size)
1512
+ ... if not chunk:
1513
+ ... break
1514
+ """
1515
+ with cls(total=total, **tqdm_kwargs) as t:
1516
+ if bytes:
1517
+ t.unit = "B"
1518
+ t.unit_scale = True
1519
+ t.unit_divisor = 1024
1520
+ yield CallbackIOWrapper(t.update, stream, method)
1521
+
1522
+
1523
+ def trange(*args, **kwargs):
1524
+ """Shortcut for tqdm(range(*args), **kwargs)."""
1525
+ return tqdm(range(*args), **kwargs)
.cache/uv/archive-v0/9FjNv3LgiVy99xT4t-wKg/tqdm/utils.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ General helpers required for `tqdm.std`.
3
+ """
4
+ import os
5
+ import re
6
+ import sys
7
+ from functools import partial, partialmethod, wraps
8
+ from inspect import signature
9
+ # TODO consider using wcswidth third-party package for 0-width characters
10
+ from unicodedata import east_asian_width
11
+ from warnings import warn
12
+ from weakref import proxy
13
+
14
+ _range, _unich, _unicode, _basestring = range, chr, str, str
15
+ CUR_OS = sys.platform
16
+ IS_WIN = any(CUR_OS.startswith(i) for i in ['win32', 'cygwin'])
17
+ IS_NIX = any(CUR_OS.startswith(i) for i in ['aix', 'linux', 'darwin', 'freebsd'])
18
+ RE_ANSI = re.compile(r"\x1b\[[;\d]*[A-Za-z]")
19
+
20
+ try:
21
+ if IS_WIN:
22
+ import colorama
23
+ else:
24
+ raise ImportError
25
+ except ImportError:
26
+ colorama = None
27
+ else:
28
+ try:
29
+ colorama.init(strip=False)
30
+ except TypeError:
31
+ colorama.init()
32
+
33
+ try:
34
+ from envwrap import envwrap # pylint: disable=unused-import
35
+ except ModuleNotFoundError:
36
+ def envwrap(name, app="", types=None, is_method=False):
37
+ """
38
+ Basic (env-var-only) version of `envwrap <https://github.com/tqdm/envwrap>`_.
39
+ Install ``envwrap`` for config file support.
40
+ """
41
+ if types is None:
42
+ types = {}
43
+ if name[-1] == "_":
44
+ name = name[:-1]
45
+ warn("Trailing underscore in `name` is automatic", DeprecationWarning, stacklevel=2)
46
+ prefixes = (name, f"{name}_{app}") if app else (name,)
47
+ env_overrides = {}
48
+ for prefix in prefixes:
49
+ prefix = prefix.upper() + "_"
50
+ i = len(prefix)
51
+ env_overrides.update(
52
+ (k[i:].lower(), v) for k, v in os.environ.items() if k.startswith(prefix))
53
+ part = partialmethod if is_method else partial
54
+
55
+ def wrap(func):
56
+ params = signature(func).parameters
57
+ # ignore unknown env vars
58
+ overrides = {k: v for k, v in env_overrides.items() if k in params}
59
+ # infer overrides' `type`s
60
+ for k in overrides:
61
+ param = params[k]
62
+ if param.annotation is not param.empty: # typehints
63
+ for typ in getattr(param.annotation, '__args__', (param.annotation,)):
64
+ try:
65
+ overrides[k] = typ(overrides[k])
66
+ except Exception:
67
+ pass
68
+ else:
69
+ break
70
+ elif param.default is not None: # type of default value
71
+ overrides[k] = type(param.default)(overrides[k])
72
+ else:
73
+ try: # `types` fallback
74
+ overrides[k] = types[k](overrides[k])
75
+ except KeyError: # keep unconverted (`str`)
76
+ pass
77
+ return part(func, **overrides)
78
+ return wrap
79
+
80
+
81
+ class FormatReplace:
82
+ """
83
+ >>> a = FormatReplace('something')
84
+ >>> f"{a:5d}"
85
+ 'something'
86
+ """ # NOQA: P102
87
+ def __init__(self, replace=''):
88
+ self.replace = replace
89
+ self.format_called = 0
90
+
91
+ def __format__(self, _):
92
+ self.format_called += 1
93
+ return self.replace
94
+
95
+
96
+ class Comparable:
97
+ """Assumes child has self._comparable attr/@property"""
98
+ def __lt__(self, other):
99
+ return self._comparable < other._comparable
100
+
101
+ def __le__(self, other):
102
+ return (self < other) or (self == other)
103
+
104
+ def __eq__(self, other):
105
+ return self._comparable == other._comparable
106
+
107
+ def __ne__(self, other):
108
+ return not self == other
109
+
110
+ def __gt__(self, other):
111
+ return not self <= other
112
+
113
+ def __ge__(self, other):
114
+ return not self < other
115
+
116
+
117
+ class ObjectWrapper:
118
+ def __getattr__(self, name):
119
+ return getattr(self._wrapped, name)
120
+
121
+ def __setattr__(self, name, value):
122
+ return setattr(self._wrapped, name, value)
123
+
124
+ def wrapper_getattr(self, name):
125
+ """Actual `self.getattr` rather than self._wrapped.getattr"""
126
+ try:
127
+ return object.__getattr__(self, name)
128
+ except AttributeError: # py2
129
+ return getattr(self, name)
130
+
131
+ def wrapper_setattr(self, name, value):
132
+ """Actual `self.setattr` rather than self._wrapped.setattr"""
133
+ return object.__setattr__(self, name, value)
134
+
135
+ def __init__(self, wrapped):
136
+ """
137
+ Thin wrapper around a given object
138
+ """
139
+ self.wrapper_setattr('_wrapped', wrapped)
140
+
141
+
142
+ class SimpleTextIOWrapper(ObjectWrapper):
143
+ """
144
+ Change only `.write()` of the wrapped object by encoding the passed
145
+ value and passing the result to the wrapped object's `.write()` method.
146
+ """
147
+ # pylint: disable=too-few-public-methods
148
+ def __init__(self, wrapped, encoding):
149
+ super().__init__(wrapped)
150
+ self.wrapper_setattr('encoding', encoding)
151
+
152
+ def write(self, s):
153
+ """
154
+ Encode `s` and pass to the wrapped object's `.write()` method.
155
+ """
156
+ return self._wrapped.write(s.encode(self.wrapper_getattr('encoding')))
157
+
158
+ def __eq__(self, other):
159
+ return self._wrapped == getattr(other, '_wrapped', other)
160
+
161
+
162
+ class DisableOnWriteError(ObjectWrapper):
163
+ """
164
+ Disable the given `tqdm_instance` upon `write()` or `flush()` errors.
165
+ """
166
+ @staticmethod
167
+ def disable_on_exception(tqdm_instance, func):
168
+ """
169
+ Quietly set `tqdm_instance.miniters=inf` if `func` raises `errno=5`.
170
+ """
171
+ tqdm_instance = proxy(tqdm_instance)
172
+
173
+ def inner(*args, **kwargs):
174
+ try:
175
+ return func(*args, **kwargs)
176
+ except OSError as e:
177
+ if e.errno != 5:
178
+ raise
179
+ try:
180
+ tqdm_instance.miniters = float('inf')
181
+ except ReferenceError:
182
+ pass
183
+ except ValueError as e:
184
+ if 'closed' not in str(e):
185
+ raise
186
+ try:
187
+ tqdm_instance.miniters = float('inf')
188
+ except ReferenceError:
189
+ pass
190
+ return inner
191
+
192
+ def __init__(self, wrapped, tqdm_instance): # noqa: B042
193
+ super().__init__(wrapped)
194
+ if hasattr(wrapped, 'write'):
195
+ self.wrapper_setattr(
196
+ 'write', self.disable_on_exception(tqdm_instance, wrapped.write))
197
+ if hasattr(wrapped, 'flush'):
198
+ self.wrapper_setattr(
199
+ 'flush', self.disable_on_exception(tqdm_instance, wrapped.flush))
200
+
201
+ def __eq__(self, other):
202
+ return self._wrapped == getattr(other, '_wrapped', other)
203
+
204
+
205
+ class CallbackIOWrapper(ObjectWrapper):
206
+ def __init__(self, callback, stream, method="read"):
207
+ """
208
+ Wrap a given `file`-like object's `read()` or `write()` to report
209
+ lengths to the given `callback`
210
+ """
211
+ super().__init__(stream)
212
+ func = getattr(stream, method)
213
+ if method == "write":
214
+ @wraps(func)
215
+ def write(data, *args, **kwargs):
216
+ res = func(data, *args, **kwargs)
217
+ callback(len(data))
218
+ return res
219
+ self.wrapper_setattr('write', write)
220
+ elif method == "read":
221
+ @wraps(func)
222
+ def read(*args, **kwargs):
223
+ data = func(*args, **kwargs)
224
+ callback(len(data))
225
+ return data
226
+ self.wrapper_setattr('read', read)
227
+ else:
228
+ raise KeyError("Can only wrap read/write methods")
229
+
230
+
231
+ def _is_utf(encoding):
232
+ try:
233
+ '\u2588\u2589'.encode(encoding)
234
+ except UnicodeEncodeError:
235
+ return False
236
+ except Exception:
237
+ try:
238
+ return encoding.lower().startswith('utf-') or ('U8' == encoding)
239
+ except Exception:
240
+ return False
241
+ else:
242
+ return True
243
+
244
+
245
+ def _supports_unicode(fp):
246
+ try:
247
+ return _is_utf(fp.encoding)
248
+ except AttributeError:
249
+ return False
250
+
251
+
252
+ def _is_ascii(s):
253
+ if isinstance(s, str):
254
+ for c in s:
255
+ if ord(c) > 255:
256
+ return False
257
+ return True
258
+ return _supports_unicode(s)
259
+
260
+
261
+ def _screen_shape_wrapper(): # pragma: no cover
262
+ """
263
+ Return a function which returns console dimensions (width, height).
264
+ Supported: linux, osx, windows, cygwin.
265
+ """
266
+ from os import get_terminal_size
267
+
268
+ def inner(fp):
269
+ try:
270
+ cols, lines = get_terminal_size(getattr(fp, 'fileno', lambda: None)())
271
+ return cols - 1, lines - 1
272
+ except Exception:
273
+ return None, None
274
+
275
+ return inner
276
+
277
+
278
+ def _environ_cols_wrapper(): # pragma: no cover
279
+ """
280
+ Return a function which returns console width.
281
+ Supported: linux, osx, windows, cygwin.
282
+ """
283
+ warn("Use `_screen_shape_wrapper()(file)[0]` instead of"
284
+ " `_environ_cols_wrapper()(file)`", DeprecationWarning, stacklevel=2)
285
+ shape = _screen_shape_wrapper()
286
+ if not shape:
287
+ return None
288
+
289
+ @wraps(shape)
290
+ def inner(fp):
291
+ return shape(fp)[0]
292
+
293
+ return inner
294
+
295
+
296
+ def _term_move_up(): # pragma: no cover
297
+ return '' if (os.name == 'nt') and (colorama is None) else '\x1b[A'
298
+
299
+
300
+ def _text_width(s):
301
+ return sum(2 if east_asian_width(ch) in 'FW' else 1 for ch in str(s))
302
+
303
+
304
+ def disp_len(data):
305
+ """
306
+ Returns the real on-screen length of a string which may contain
307
+ ANSI control codes and wide chars.
308
+ """
309
+ return _text_width(RE_ANSI.sub('', data))
310
+
311
+
312
+ def disp_trim(data, length):
313
+ """
314
+ Trim a string which may contain ANSI control characters.
315
+ """
316
+ if len(data) == disp_len(data):
317
+ return data[:length]
318
+
319
+ ansi_present = bool(RE_ANSI.search(data))
320
+ while disp_len(data) > length: # carefully delete one char at a time
321
+ data = data[:-1]
322
+ if ansi_present and bool(RE_ANSI.search(data)):
323
+ # assume ANSI reset is required
324
+ return data if data.endswith("\033[0m") else data + "\033[0m"
325
+ return data
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock-3.29.1.dist-info/METADATA ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: filelock
3
+ Version: 3.29.1
4
+ Summary: A platform independent file lock.
5
+ Project-URL: Documentation, https://py-filelock.readthedocs.io
6
+ Project-URL: Homepage, https://github.com/tox-dev/py-filelock
7
+ Project-URL: Source, https://github.com/tox-dev/py-filelock
8
+ Project-URL: Tracker, https://github.com/tox-dev/py-filelock/issues
9
+ Maintainer-email: Bernát Gábor <gaborjbernat@gmail.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: application,cache,directory,log,user
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: Internet
25
+ Classifier: Topic :: Software Development :: Libraries
26
+ Classifier: Topic :: System
27
+ Requires-Python: >=3.10
28
+ Description-Content-Type: text/markdown
29
+
30
+ # filelock
31
+
32
+ [![PyPI](https://img.shields.io/pypi/v/filelock)](https://pypi.org/project/filelock/)
33
+ [![Supported Python versions](https://img.shields.io/pypi/pyversions/filelock.svg)](https://pypi.org/project/filelock/)
34
+ [![Documentation status](https://readthedocs.org/projects/py-filelock/badge/?version=latest)](https://py-filelock.readthedocs.io/en/latest/?badge=latest)
35
+ [![Downloads](https://static.pepy.tech/badge/filelock/month)](https://pepy.tech/project/filelock)
36
+ [![check](https://github.com/tox-dev/py-filelock/actions/workflows/check.yaml/badge.svg)](https://github.com/tox-dev/py-filelock/actions/workflows/check.yaml)
37
+
38
+ For more information checkout the [official documentation](https://py-filelock.readthedocs.io/en/latest/index.html).
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock-3.29.1.dist-info/RECORD ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ filelock/__init__.py,sha256=Ig_QNvsAVtctz2-fkq9EUCgXmW6M5PDudiOC85szmis,2612
2
+ filelock/_api.py,sha256=mgN9X_i6b3bDG9gd8qxwrrRnwU5FeBSJw78jTTvU7ZI,22377
3
+ filelock/_async_read_write.py,sha256=C_cRi4sZ7_CWcqdEf0pcA5sdJ2m3EI_2tAW6kS_5P6I,7759
4
+ filelock/_error.py,sha256=amqJaDkEv4DhjelOhJ3xm12kVtgakSZLnVAyzAL2IYU,775
5
+ filelock/_read_write.py,sha256=TjTDsYO0Lwe6yVb7oCiWHmNRc0MiJHWwKHUpYeafmlA,15693
6
+ filelock/_soft.py,sha256=kllCdsXp2Su5n7D71wKeUxIxNqrDqKqdZyNffIX7EF0,8683
7
+ filelock/_unix.py,sha256=pbTsIi29Qv8zBtLsXqc3PzlS3wz2db53M1MIqVo9790,4579
8
+ filelock/_util.py,sha256=wPf-LvzmdHWHw4DinDeVJlB0GNVOYGNUeNKSnHBQuUU,1716
9
+ filelock/_windows.py,sha256=kJFOenaffOP6Qza2b3-yxgiPiDcyroWnzz9STGkCrgM,3943
10
+ filelock/asyncio.py,sha256=z6yRl3od9BLEvtwXqvPLzaamoliXL-onelc7rmKGUlA,15558
11
+ filelock/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ filelock/version.py,sha256=C4a-gV3Z3ywHMJ4kTeBPRZksDETbu7qRoFc4RK8KzkY,522
13
+ filelock/_soft_rw/__init__.py,sha256=_ktpGmVObzrvL0K1_EAV3LF7B9JarYxW-mx_eyGPhT0,370
14
+ filelock/_soft_rw/_async.py,sha256=3MdgJN0SBM-9-Msslt4HeikJtz2cc1tbeN1sWK9NV60,8704
15
+ filelock/_soft_rw/_sync.py,sha256=jhCNoZ18umc4UId4YtzGD-qv3oWaVWjPpA1xfbSd--o,34976
16
+ filelock-3.29.1.dist-info/METADATA,sha256=p3_JjhhlHGrca1NbxoftieI5aUQzuYYPDazMzQWBdYM,1977
17
+ filelock-3.29.1.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
18
+ filelock-3.29.1.dist-info/licenses/LICENSE,sha256=YIyJ1QYK6ZIa3M8yNmlbxlSplG4SMj72wCHfoE4pTUg,1088
19
+ filelock-3.29.1.dist-info/RECORD,,
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock-3.29.1.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Bernát Gábor and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_async_read_write.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async wrapper around :class:`ReadWriteLock` for use with ``asyncio``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import functools
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from contextlib import asynccontextmanager
9
+ from typing import TYPE_CHECKING
10
+
11
+ from ._read_write import ReadWriteLock
12
+
13
+ if TYPE_CHECKING:
14
+ import os
15
+ from collections.abc import AsyncGenerator, Callable
16
+ from concurrent import futures
17
+ from types import TracebackType
18
+
19
+
20
+ class AsyncAcquireReadWriteReturnProxy:
21
+ """Context-aware object that releases the async read/write lock on exit."""
22
+
23
+ def __init__(self, lock: AsyncReadWriteLock) -> None:
24
+ self.lock = lock
25
+
26
+ async def __aenter__(self) -> AsyncReadWriteLock:
27
+ return self.lock
28
+
29
+ async def __aexit__(
30
+ self,
31
+ exc_type: type[BaseException] | None,
32
+ exc_value: BaseException | None,
33
+ traceback: TracebackType | None,
34
+ ) -> None:
35
+ await self.lock.release()
36
+
37
+
38
+ class AsyncReadWriteLock:
39
+ """
40
+ Async wrapper around :class:`ReadWriteLock` for use in ``asyncio`` applications.
41
+
42
+ Because Python's :mod:`sqlite3` module has no async API, all blocking SQLite operations are dispatched to a thread
43
+ pool via ``loop.run_in_executor()``. Reentrancy, upgrade/downgrade rules, and singleton behavior are delegated
44
+ to the underlying :class:`ReadWriteLock`.
45
+
46
+ :param lock_file: path to the SQLite database file used as the lock
47
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
48
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
49
+ :param is_singleton: if ``True``, reuse existing :class:`ReadWriteLock` instances for the same resolved path
50
+ :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop
51
+ :param executor: executor for ``run_in_executor``; ``None`` uses the default executor
52
+
53
+ .. versionadded:: 3.21.0
54
+
55
+ """
56
+
57
+ def __init__( # noqa: PLR0913
58
+ self,
59
+ lock_file: str | os.PathLike[str],
60
+ timeout: float = -1,
61
+ *,
62
+ blocking: bool = True,
63
+ is_singleton: bool = True,
64
+ loop: asyncio.AbstractEventLoop | None = None,
65
+ executor: futures.Executor | None = None,
66
+ ) -> None:
67
+ self._lock = ReadWriteLock(lock_file, timeout, blocking=blocking, is_singleton=is_singleton)
68
+ self._loop = loop
69
+ self._owns_executor = executor is None
70
+ self._executor = executor or ThreadPoolExecutor(max_workers=1)
71
+
72
+ @property
73
+ def lock_file(self) -> str:
74
+ """:returns: the path to the lock file."""
75
+ return self._lock.lock_file
76
+
77
+ @property
78
+ def timeout(self) -> float:
79
+ """:returns: the default timeout."""
80
+ return self._lock.timeout
81
+
82
+ @property
83
+ def blocking(self) -> bool:
84
+ """:returns: whether blocking is enabled by default."""
85
+ return self._lock.blocking
86
+
87
+ @property
88
+ def loop(self) -> asyncio.AbstractEventLoop | None:
89
+ """:returns: the event loop (or ``None`` for the running loop)."""
90
+ return self._loop
91
+
92
+ @property
93
+ def executor(self) -> futures.Executor | None:
94
+ """:returns: the executor (or ``None`` for the default)."""
95
+ return self._executor
96
+
97
+ async def _run(self, func: Callable[..., object], *args: object, **kwargs: object) -> object:
98
+ loop = self._loop or asyncio.get_running_loop()
99
+ return await loop.run_in_executor(self._executor, functools.partial(func, *args, **kwargs))
100
+
101
+ async def acquire_read(self, timeout: float = -1, *, blocking: bool = True) -> AsyncAcquireReadWriteReturnProxy:
102
+ """
103
+ Acquire a shared read lock.
104
+
105
+ See :meth:`ReadWriteLock.acquire_read` for full semantics.
106
+
107
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
108
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
109
+
110
+ :returns: a proxy that can be used as an async context manager to release the lock
111
+
112
+ :raises RuntimeError: if a write lock is already held on this instance
113
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
114
+
115
+ """
116
+ await self._run(self._lock.acquire_read, timeout, blocking=blocking)
117
+ return AsyncAcquireReadWriteReturnProxy(lock=self)
118
+
119
+ async def acquire_write(self, timeout: float = -1, *, blocking: bool = True) -> AsyncAcquireReadWriteReturnProxy:
120
+ """
121
+ Acquire an exclusive write lock.
122
+
123
+ See :meth:`ReadWriteLock.acquire_write` for full semantics.
124
+
125
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
126
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
127
+
128
+ :returns: a proxy that can be used as an async context manager to release the lock
129
+
130
+ :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread
131
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
132
+
133
+ """
134
+ await self._run(self._lock.acquire_write, timeout, blocking=blocking)
135
+ return AsyncAcquireReadWriteReturnProxy(lock=self)
136
+
137
+ async def release(self, *, force: bool = False) -> None:
138
+ """
139
+ Release one level of the current lock.
140
+
141
+ See :meth:`ReadWriteLock.release` for full semantics.
142
+
143
+ :param force: if ``True``, release the lock completely regardless of the current lock level
144
+
145
+ :raises RuntimeError: if no lock is currently held and *force* is ``False``
146
+
147
+ """
148
+ await self._run(self._lock.release, force=force)
149
+
150
+ @asynccontextmanager
151
+ async def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]:
152
+ """
153
+ Async context manager that acquires and releases a shared read lock.
154
+
155
+ Falls back to instance defaults for *timeout* and *blocking* when ``None``.
156
+
157
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
158
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
159
+
160
+ """
161
+ if timeout is None:
162
+ timeout = self._lock.timeout
163
+ if blocking is None:
164
+ blocking = self._lock.blocking
165
+ await self.acquire_read(timeout, blocking=blocking)
166
+ try:
167
+ yield
168
+ finally:
169
+ await self.release()
170
+
171
+ @asynccontextmanager
172
+ async def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]:
173
+ """
174
+ Async context manager that acquires and releases an exclusive write lock.
175
+
176
+ Falls back to instance defaults for *timeout* and *blocking* when ``None``.
177
+
178
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
179
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
180
+
181
+ """
182
+ if timeout is None:
183
+ timeout = self._lock.timeout
184
+ if blocking is None:
185
+ blocking = self._lock.blocking
186
+ await self.acquire_write(timeout, blocking=blocking)
187
+ try:
188
+ yield
189
+ finally:
190
+ await self.release()
191
+
192
+ async def close(self) -> None:
193
+ """
194
+ Release the lock (if held) and close the underlying SQLite connection.
195
+
196
+ After calling this method, the lock instance is no longer usable.
197
+
198
+ """
199
+ await self._run(self._lock.close)
200
+ if self._owns_executor:
201
+ self._executor.shutdown(wait=False)
202
+
203
+
204
+ __all__ = [
205
+ "AsyncAcquireReadWriteReturnProxy",
206
+ "AsyncReadWriteLock",
207
+ ]
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_error.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+
4
+ class Timeout(TimeoutError): # noqa: N818
5
+ """Raised when the lock could not be acquired in *timeout* seconds."""
6
+
7
+ def __init__(self, lock_file: str) -> None:
8
+ super().__init__()
9
+ self._lock_file = lock_file
10
+
11
+ def __reduce__(self) -> tuple[type[Timeout], tuple[str]]:
12
+ return self.__class__, (self._lock_file,) # Properly pickle the exception
13
+
14
+ def __str__(self) -> str:
15
+ return f"The file lock '{self._lock_file}' could not be acquired."
16
+
17
+ def __repr__(self) -> str:
18
+ return f"{self.__class__.__name__}({self.lock_file!r})"
19
+
20
+ @property
21
+ def lock_file(self) -> str:
22
+ """:returns: The path of the file lock."""
23
+ return self._lock_file
24
+
25
+
26
+ __all__ = [
27
+ "Timeout",
28
+ ]
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import socket
5
+ import sys
6
+ import time
7
+ from contextlib import suppress
8
+ from errno import EACCES, EEXIST, EPERM, ESRCH
9
+ from pathlib import Path
10
+
11
+ from ._api import BaseFileLock
12
+ from ._util import ensure_directory_exists, raise_on_not_writable_file
13
+
14
+ _WIN_SYNCHRONIZE = 0x100000
15
+ _WIN_ERROR_INVALID_PARAMETER = 87
16
+ _WIN_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
17
+ _MALFORMED_LOCK_AGE_THRESHOLD = 2.0
18
+ _MAX_LOCK_FILE_SIZE = 1024
19
+
20
+
21
+ class SoftFileLock(BaseFileLock):
22
+ """
23
+ Portable file lock based on file existence.
24
+
25
+ Unlike :class:`UnixFileLock <filelock.UnixFileLock>` and :class:`WindowsFileLock <filelock.WindowsFileLock>`, this
26
+ lock does not use OS-level locking primitives. Instead, it creates the lock file with ``O_CREAT | O_EXCL`` and
27
+ treats its existence as the lock indicator. This makes it work on any filesystem but leaves stale lock files behind
28
+ if the process crashes without releasing the lock.
29
+
30
+ To mitigate stale locks, the lock file contains the PID and hostname of the holding process. On contention, if the
31
+ holder is on the same host and its PID no longer exists, the stale lock is broken automatically.
32
+
33
+ """
34
+
35
+ def _acquire(self) -> None:
36
+ raise_on_not_writable_file(self.lock_file)
37
+ ensure_directory_exists(self.lock_file)
38
+ flags = (
39
+ os.O_WRONLY # open for writing only
40
+ | os.O_CREAT
41
+ | os.O_EXCL # together with above raise EEXIST if the file specified by filename exists
42
+ | os.O_TRUNC # truncate the file to zero byte
43
+ )
44
+ if (o_nofollow := getattr(os, "O_NOFOLLOW", None)) is not None:
45
+ flags |= o_nofollow
46
+ try:
47
+ file_handler = os.open(self.lock_file, flags, self._open_mode())
48
+ except OSError as exception:
49
+ if not (
50
+ exception.errno == EEXIST or (exception.errno == EACCES and sys.platform == "win32")
51
+ ): # pragma: win32 no cover
52
+ raise
53
+ self._try_break_stale_lock()
54
+ else:
55
+ self._write_lock_info(file_handler)
56
+ self._context.lock_file_fd = file_handler
57
+
58
+ def _try_break_stale_lock(self) -> None:
59
+ with suppress(OSError, ValueError):
60
+ content, mtime = _read_lock_file(self.lock_file)
61
+ lines = content.strip().splitlines() if content else []
62
+
63
+ if len(lines) not in {2, 3}:
64
+ if time.time() - mtime >= _MALFORMED_LOCK_AGE_THRESHOLD:
65
+ self._evict_lock_file()
66
+ return
67
+
68
+ pid_str, hostname = lines[0], lines[1]
69
+ creation_time_str = lines[2] if len(lines) == 3 else None # noqa: PLR2004
70
+
71
+ if hostname != socket.gethostname():
72
+ return
73
+
74
+ pid = int(pid_str)
75
+
76
+ if self._is_process_alive(pid):
77
+ if sys.platform == "win32" and creation_time_str is not None: # pragma: win32 cover
78
+ stored = int(creation_time_str)
79
+ actual = self._get_process_creation_time(pid)
80
+ if actual is not None and actual != stored:
81
+ pass # PID recycled, fall through to evict
82
+ else:
83
+ return # same process or can't verify — don't evict
84
+ else:
85
+ return
86
+
87
+ self._evict_lock_file()
88
+
89
+ def _evict_lock_file(self) -> None:
90
+ break_path = f"{self.lock_file}.break.{os.getpid()}"
91
+ Path(self.lock_file).rename(break_path)
92
+ Path(break_path).unlink()
93
+
94
+ @staticmethod
95
+ def _is_process_alive(pid: int) -> bool:
96
+ if sys.platform == "win32": # pragma: win32 cover
97
+ import ctypes # noqa: PLC0415
98
+
99
+ kernel32 = ctypes.windll.kernel32
100
+ handle = kernel32.OpenProcess(_WIN_SYNCHRONIZE, 0, pid)
101
+ if handle:
102
+ kernel32.CloseHandle(handle)
103
+ return True
104
+ return kernel32.GetLastError() != _WIN_ERROR_INVALID_PARAMETER
105
+ try:
106
+ os.kill(pid, 0)
107
+ except OSError as exc:
108
+ if exc.errno == ESRCH:
109
+ return False
110
+ if exc.errno == EPERM:
111
+ return True
112
+ raise
113
+ return True
114
+
115
+ @staticmethod
116
+ def _get_process_creation_time(pid: int) -> int | None:
117
+ """Return the process creation FILETIME as an integer on Windows, ``None`` otherwise."""
118
+ if sys.platform != "win32": # pragma: win32 no cover
119
+ return None
120
+ import ctypes # pragma: win32 cover # noqa: PLC0415
121
+ from ctypes import wintypes # noqa: PLC0415
122
+
123
+ kernel32 = ctypes.windll.kernel32
124
+ handle = kernel32.OpenProcess(_WIN_PROCESS_QUERY_LIMITED_INFORMATION, 0, pid)
125
+ if not handle:
126
+ return None
127
+ try:
128
+ creation = wintypes.FILETIME()
129
+ exit_time = wintypes.FILETIME()
130
+ kernel_time = wintypes.FILETIME()
131
+ user_time = wintypes.FILETIME()
132
+ if not kernel32.GetProcessTimes(
133
+ handle,
134
+ ctypes.byref(creation),
135
+ ctypes.byref(exit_time),
136
+ ctypes.byref(kernel_time),
137
+ ctypes.byref(user_time),
138
+ ):
139
+ return None
140
+ finally:
141
+ kernel32.CloseHandle(handle)
142
+ return (creation.dwHighDateTime << 32) | creation.dwLowDateTime
143
+
144
+ @staticmethod
145
+ def _write_lock_info(fd: int) -> None:
146
+ with suppress(OSError):
147
+ info = f"{os.getpid()}\n{socket.gethostname()}\n"
148
+ if sys.platform == "win32" and (ct := SoftFileLock._get_process_creation_time(os.getpid())) is not None:
149
+ info += f"{ct}\n"
150
+ os.write(fd, info.encode())
151
+
152
+ @property
153
+ def pid(self) -> int | None:
154
+ """
155
+ The PID of the process holding this lock, read from the lock file.
156
+
157
+ :returns: the PID as an integer, or ``None`` if the lock file does not exist or cannot be parsed
158
+
159
+ """
160
+ with suppress(OSError, ValueError):
161
+ content, _ = _read_lock_file(self.lock_file)
162
+ if content and (lines := content.strip().splitlines()):
163
+ return int(lines[0])
164
+ return None
165
+
166
+ @property
167
+ def is_lock_held_by_us(self) -> bool:
168
+ """
169
+ Whether this lock is held by the current process.
170
+
171
+ :returns: ``True`` if the lock file exists and contains the current process's PID
172
+
173
+ """
174
+ return self.pid == os.getpid()
175
+
176
+ def break_lock(self) -> None:
177
+ """Forcibly break the lock by removing the lock file, regardless of who holds it."""
178
+ with suppress(OSError):
179
+ Path(self.lock_file).unlink()
180
+
181
+ def _release(self) -> None:
182
+ assert self._context.lock_file_fd is not None # noqa: S101
183
+ os.close(self._context.lock_file_fd)
184
+ self._context.lock_file_fd = None
185
+ if sys.platform == "win32":
186
+ self._windows_unlink_with_retry()
187
+ else:
188
+ with suppress(OSError):
189
+ Path(self.lock_file).unlink()
190
+
191
+ def _windows_unlink_with_retry(self) -> None:
192
+ max_retries = 10
193
+ retry_delay = 0.001
194
+ for attempt in range(max_retries):
195
+ # Windows doesn't immediately release file handles after close, causing EACCES/EPERM on unlink
196
+ try:
197
+ Path(self.lock_file).unlink()
198
+ except OSError as exc: # noqa: PERF203
199
+ if exc.errno not in {EACCES, EPERM}:
200
+ return
201
+ if attempt < max_retries - 1:
202
+ time.sleep(retry_delay)
203
+ retry_delay *= 2
204
+ else:
205
+ return
206
+
207
+
208
+ def _read_lock_file(path: str) -> tuple[str | None, float]:
209
+ # The lock file is created with O_EXCL | O_NOFOLLOW, so a symlink here is a hostile replacement and must
210
+ # not be followed. O_NONBLOCK keeps an attacker-placed FIFO from stalling the open (O_NOFOLLOW alone only
211
+ # rejects a symlink, not a real FIFO at the path), and the capped read stops a huge file (e.g. /dev/zero)
212
+ # from exhausting memory. Content is None when the file is too large or not UTF-8, but the mtime still
213
+ # flows back so the caller can evict it as a stale, malformed lock.
214
+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
215
+ try:
216
+ mtime, data = os.fstat(fd).st_mtime, os.read(fd, _MAX_LOCK_FILE_SIZE + 1)
217
+ finally:
218
+ os.close(fd)
219
+ if len(data) <= _MAX_LOCK_FILE_SIZE:
220
+ with suppress(UnicodeDecodeError):
221
+ return data.decode("utf-8"), mtime
222
+ return None, mtime
223
+
224
+
225
+ __all__ = [
226
+ "SoftFileLock",
227
+ ]
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft_rw/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cross-process and cross-host reader/writer lock on :class:`~filelock.SoftFileLock` primitives."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ._async import AsyncAcquireSoftReadWriteReturnProxy, AsyncSoftReadWriteLock
6
+ from ._sync import SoftReadWriteLock
7
+
8
+ __all__ = [
9
+ "AsyncAcquireSoftReadWriteReturnProxy",
10
+ "AsyncSoftReadWriteLock",
11
+ "SoftReadWriteLock",
12
+ ]
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft_rw/_async.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async wrapper around :class:`SoftReadWriteLock` for use with ``asyncio``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import functools
7
+ from contextlib import asynccontextmanager
8
+ from typing import TYPE_CHECKING
9
+
10
+ from ._sync import SoftReadWriteLock
11
+
12
+ if TYPE_CHECKING:
13
+ import os
14
+ from collections.abc import AsyncGenerator, Callable
15
+ from concurrent import futures
16
+ from types import TracebackType
17
+
18
+
19
+ class AsyncAcquireSoftReadWriteReturnProxy:
20
+ """Async context-aware object that releases an :class:`AsyncSoftReadWriteLock` on exit."""
21
+
22
+ def __init__(self, lock: AsyncSoftReadWriteLock) -> None:
23
+ self.lock = lock
24
+
25
+ async def __aenter__(self) -> AsyncSoftReadWriteLock:
26
+ return self.lock
27
+
28
+ async def __aexit__(
29
+ self,
30
+ exc_type: type[BaseException] | None,
31
+ exc_value: BaseException | None,
32
+ traceback: TracebackType | None,
33
+ ) -> None:
34
+ await self.lock.release()
35
+
36
+
37
+ class AsyncSoftReadWriteLock:
38
+ """
39
+ Async wrapper around :class:`SoftReadWriteLock` for ``asyncio`` applications.
40
+
41
+ The sync class's blocking filesystem operations run on a thread pool via ``loop.run_in_executor()``.
42
+ Reentrancy, upgrade/downgrade rules, fork handling, heartbeat and TTL stale detection, and singleton
43
+ behavior are delegated to the underlying :class:`SoftReadWriteLock`.
44
+
45
+ :param lock_file: path to the lock file; sidecar state/write/readers live next to it
46
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
47
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately on contention
48
+ :param is_singleton: if ``True``, reuse existing :class:`SoftReadWriteLock` instances per resolved path
49
+ :param heartbeat_interval: seconds between heartbeat refreshes; default 30 s
50
+ :param stale_threshold: seconds of mtime inactivity before a marker is stale; defaults to ``3 * heartbeat_interval``
51
+ :param poll_interval: seconds between acquire retries under contention; default 0.25 s
52
+ :param loop: event loop for ``run_in_executor``; ``None`` uses the running loop
53
+ :param executor: executor for ``run_in_executor``; ``None`` uses the default executor
54
+
55
+ .. versionadded:: 3.27.0
56
+
57
+ """
58
+
59
+ def __init__( # noqa: PLR0913
60
+ self,
61
+ lock_file: str | os.PathLike[str],
62
+ timeout: float = -1,
63
+ *,
64
+ blocking: bool = True,
65
+ is_singleton: bool = True,
66
+ heartbeat_interval: float = 30.0,
67
+ stale_threshold: float | None = None,
68
+ poll_interval: float = 0.25,
69
+ loop: asyncio.AbstractEventLoop | None = None,
70
+ executor: futures.Executor | None = None,
71
+ ) -> None:
72
+ self._lock = SoftReadWriteLock(
73
+ lock_file,
74
+ timeout,
75
+ blocking=blocking,
76
+ is_singleton=is_singleton,
77
+ heartbeat_interval=heartbeat_interval,
78
+ stale_threshold=stale_threshold,
79
+ poll_interval=poll_interval,
80
+ )
81
+ self._loop = loop
82
+ self._executor = executor
83
+
84
+ @property
85
+ def lock_file(self) -> str:
86
+ """:returns: the path to the lock file passed to the constructor."""
87
+ return self._lock.lock_file
88
+
89
+ @property
90
+ def timeout(self) -> float:
91
+ """:returns: the default timeout applied when ``acquire_read`` / ``acquire_write`` is called without one."""
92
+ return self._lock.timeout
93
+
94
+ @property
95
+ def blocking(self) -> bool:
96
+ """:returns: whether ``acquire_*`` defaults to blocking; ``False`` makes contention raise immediately."""
97
+ return self._lock.blocking
98
+
99
+ @property
100
+ def loop(self) -> asyncio.AbstractEventLoop | None:
101
+ """:returns: the event loop used for ``run_in_executor``, or ``None`` for the running loop."""
102
+ return self._loop
103
+
104
+ @property
105
+ def executor(self) -> futures.Executor | None:
106
+ """:returns: the executor used for ``run_in_executor``, or ``None`` for the default executor."""
107
+ return self._executor
108
+
109
+ async def acquire_read(
110
+ self, timeout: float | None = None, *, blocking: bool | None = None
111
+ ) -> AsyncAcquireSoftReadWriteReturnProxy:
112
+ """
113
+ Acquire a shared read lock.
114
+
115
+ See :meth:`SoftReadWriteLock.acquire_read` for the full reentrancy / upgrade / fork semantics. The blocking
116
+ work runs inside ``run_in_executor`` so other coroutines on the same loop continue to progress while this
117
+ call waits.
118
+
119
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
120
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
121
+
122
+ :returns: a proxy usable as an async context manager to release the lock
123
+
124
+ :raises RuntimeError: if a write lock is already held, if this instance was invalidated by
125
+ :func:`os.fork`, or if :meth:`close` was called
126
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
127
+
128
+ """
129
+ await self._run(self._lock.acquire_read, timeout, blocking=blocking)
130
+ return AsyncAcquireSoftReadWriteReturnProxy(lock=self)
131
+
132
+ async def acquire_write(
133
+ self, timeout: float | None = None, *, blocking: bool | None = None
134
+ ) -> AsyncAcquireSoftReadWriteReturnProxy:
135
+ """
136
+ Acquire an exclusive write lock.
137
+
138
+ See :meth:`SoftReadWriteLock.acquire_write` for the two-phase writer-preferring semantics. The blocking
139
+ work runs inside ``run_in_executor``.
140
+
141
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
142
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
143
+
144
+ :returns: a proxy usable as an async context manager to release the lock
145
+
146
+ :raises RuntimeError: if a read lock is already held, if a write lock is held by a different thread, if
147
+ this instance was invalidated by :func:`os.fork`, or if :meth:`close` was called
148
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
149
+
150
+ """
151
+ await self._run(self._lock.acquire_write, timeout, blocking=blocking)
152
+ return AsyncAcquireSoftReadWriteReturnProxy(lock=self)
153
+
154
+ async def release(self, *, force: bool = False) -> None:
155
+ """
156
+ Release one level of the current lock.
157
+
158
+ :param force: if ``True``, release the lock completely regardless of the current lock level
159
+
160
+ :raises RuntimeError: if no lock is currently held and *force* is ``False``
161
+
162
+ """
163
+ await self._run(self._lock.release, force=force)
164
+
165
+ @asynccontextmanager
166
+ async def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]:
167
+ """
168
+ Async context manager that acquires and releases a shared read lock.
169
+
170
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
171
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
172
+
173
+ :raises RuntimeError: if a write lock is already held on this instance
174
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
175
+
176
+ """
177
+ await self.acquire_read(timeout, blocking=blocking)
178
+ try:
179
+ yield
180
+ finally:
181
+ await self.release()
182
+
183
+ @asynccontextmanager
184
+ async def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> AsyncGenerator[None]:
185
+ """
186
+ Async context manager that acquires and releases an exclusive write lock.
187
+
188
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
189
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
190
+
191
+ :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread
192
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
193
+
194
+ """
195
+ await self.acquire_write(timeout, blocking=blocking)
196
+ try:
197
+ yield
198
+ finally:
199
+ await self.release()
200
+
201
+ async def close(self) -> None:
202
+ """Release any held lock and release the underlying filesystem resources. Idempotent."""
203
+ await self._run(self._lock.close)
204
+
205
+ async def _run(self, func: Callable[..., object], *args: object, **kwargs: object) -> object:
206
+ loop = self._loop or asyncio.get_running_loop()
207
+ return await loop.run_in_executor(self._executor, functools.partial(func, *args, **kwargs))
208
+
209
+
210
+ __all__ = [
211
+ "AsyncAcquireSoftReadWriteReturnProxy",
212
+ "AsyncSoftReadWriteLock",
213
+ ]
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_soft_rw/_sync.py ADDED
@@ -0,0 +1,849 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cross-process and cross-host reader/writer lock built on :class:`SoftFileLock` primitives."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import atexit
6
+ import hmac
7
+ import os
8
+ import re
9
+ import secrets
10
+ import socket
11
+ import stat
12
+ import sys
13
+ import threading
14
+ import time
15
+ import uuid
16
+ from contextlib import contextmanager, suppress
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import TYPE_CHECKING, Literal
20
+ from weakref import WeakValueDictionary
21
+
22
+ from filelock._api import AcquireReturnProxy
23
+ from filelock._error import Timeout
24
+ from filelock._soft import SoftFileLock
25
+ from filelock._util import ensure_directory_exists
26
+
27
+ if TYPE_CHECKING:
28
+ from collections.abc import Callable, Generator
29
+
30
+
31
+ _Mode = Literal["read", "write"]
32
+ _BREAK_SUFFIX = ".break"
33
+ _MAX_MARKER_SIZE = 1024
34
+ _O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
35
+ # dirfd-relative I/O is a Unix-only optimization; Windows cannot ``os.open()`` a directory at all, and
36
+ # its ``os`` module skips dir_fd support entirely. When disabled, callers fall back to full-path ops.
37
+ _SUPPORTS_DIR_FD = sys.platform != "win32" and os.open in os.supports_dir_fd
38
+
39
+ _all_instances: WeakValueDictionary[Path, SoftReadWriteLock] = WeakValueDictionary()
40
+ _all_instances_lock = threading.Lock()
41
+ _atexit_registered = False
42
+ _fork_registered = False
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class _Paths:
47
+ state: str
48
+ write: str
49
+ readers: str
50
+
51
+
52
+ @dataclass
53
+ class _Locks:
54
+ internal: threading.Lock
55
+ transaction: threading.Lock
56
+ state: SoftFileLock
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class _MarkerInfo:
61
+ token: str
62
+ pid: int
63
+ hostname: str
64
+
65
+
66
+ @dataclass
67
+ class _Hold:
68
+ """Everything that exists only while a lock is held; ``None`` when the instance has no lock."""
69
+
70
+ level: int
71
+ mode: _Mode
72
+ write_thread_id: int | None
73
+ marker_name: str
74
+ is_reader: bool
75
+ token: str
76
+ heartbeat_thread: _HeartbeatThread
77
+ heartbeat_stop: threading.Event
78
+
79
+
80
+ class _SoftRWMeta(type):
81
+ _instances: WeakValueDictionary[Path, SoftReadWriteLock]
82
+ _instances_lock: threading.Lock
83
+
84
+ def __call__( # noqa: PLR0913
85
+ cls,
86
+ lock_file: str | os.PathLike[str],
87
+ timeout: float = -1,
88
+ *,
89
+ blocking: bool = True,
90
+ is_singleton: bool = True,
91
+ heartbeat_interval: float = 30.0,
92
+ stale_threshold: float | None = None,
93
+ poll_interval: float = 0.25,
94
+ ) -> SoftReadWriteLock:
95
+ if not is_singleton:
96
+ return super().__call__(
97
+ lock_file,
98
+ timeout,
99
+ blocking=blocking,
100
+ is_singleton=is_singleton,
101
+ heartbeat_interval=heartbeat_interval,
102
+ stale_threshold=stale_threshold,
103
+ poll_interval=poll_interval,
104
+ )
105
+
106
+ normalized = Path(lock_file).resolve()
107
+ with cls._instances_lock:
108
+ instance = cls._instances.get(normalized)
109
+ if instance is None:
110
+ instance = super().__call__(
111
+ lock_file,
112
+ timeout,
113
+ blocking=blocking,
114
+ is_singleton=is_singleton,
115
+ heartbeat_interval=heartbeat_interval,
116
+ stale_threshold=stale_threshold,
117
+ poll_interval=poll_interval,
118
+ )
119
+ cls._instances[normalized] = instance
120
+ elif instance.timeout != timeout or instance.blocking != blocking:
121
+ msg = (
122
+ f"Singleton lock created with timeout={instance.timeout}, blocking={instance.blocking},"
123
+ f" cannot be changed to timeout={timeout}, blocking={blocking}"
124
+ )
125
+ raise ValueError(msg)
126
+ return instance
127
+
128
+
129
+ class SoftReadWriteLock(metaclass=_SoftRWMeta):
130
+ """
131
+ Cross-process and cross-host reader/writer lock built on :class:`SoftFileLock` primitives.
132
+
133
+ Use this class instead of :class:`~filelock.ReadWriteLock` when the lock file lives on a network
134
+ filesystem (NFS, Lustre with ``-o flock``, HPC cluster shared storage). ``ReadWriteLock`` is backed
135
+ by SQLite and cannot run on NFS because SQLite's ``fcntl`` locking is unreliable there.
136
+
137
+ Layout on disk for a lock at ``foo.lock``:
138
+
139
+ - ``foo.lock.state`` — a :class:`SoftFileLock` taken only during state transitions (microseconds).
140
+ - ``foo.lock.write`` — writer marker; its presence means a writer is claiming or holding the lock.
141
+ - ``foo.lock.readers/<host>.<pid>.<uuid>`` — one file per reader.
142
+
143
+ Each marker stores a random token (``secrets.token_hex(16)``), the holder's pid, and the holder's
144
+ hostname. A daemon heartbeat thread refreshes ``mtime`` on every held marker. A marker whose mtime
145
+ has not advanced in ``stale_threshold`` seconds may be evicted by any process on any host, giving
146
+ correct behavior when a compute node crashes with a lock held.
147
+
148
+ Writer acquire is two-phase and writer-preferring: phase 1 claims ``.write`` (blocking any new
149
+ reader), phase 2 waits for existing readers to drain. Writer starvation is impossible.
150
+
151
+ Reentrancy, upgrade/downgrade rules, thread pinning, and singleton caching by resolved path match
152
+ :class:`~filelock.ReadWriteLock`.
153
+
154
+ Forking while holding a lock invalidates the inherited instance in the child so the child cannot
155
+ double-own the lock with its parent; ``release()`` on a fork-invalidated instance is a no-op, and
156
+ the child must re-acquire if it needs a lock.
157
+
158
+ Trust boundary: protects against same-UID non-cooperating processes (one host or cross-host) and
159
+ same-host different-UID users via ``0o600`` / ``0o700`` permissions. Does not protect against root
160
+ compromise, NTP tampering on same-UID cross-host nodes, or multi-tenant mounts where hostile
161
+ co-tenants share the UID.
162
+
163
+ :param lock_file: path to the lock file; sidecar state/write/readers live next to it
164
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
165
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately on contention
166
+ :param is_singleton: if ``True``, reuse existing instances for the same resolved path
167
+ :param heartbeat_interval: seconds between heartbeat refreshes; default 30 s
168
+ :param stale_threshold: seconds of ``mtime`` inactivity before a marker is stale; defaults to
169
+ ``3 * heartbeat_interval``, matching etcd's ``LeaseKeepAlive`` convention
170
+ :param poll_interval: seconds between acquire retries under contention; default 0.25 s
171
+
172
+ .. versionadded:: 3.27.0
173
+
174
+ """
175
+
176
+ _instances: WeakValueDictionary[Path, SoftReadWriteLock] = WeakValueDictionary()
177
+ _instances_lock = threading.Lock()
178
+
179
+ def __init__( # noqa: PLR0913
180
+ self,
181
+ lock_file: str | os.PathLike[str],
182
+ timeout: float = -1,
183
+ *,
184
+ blocking: bool = True,
185
+ is_singleton: bool = True, # noqa: ARG002
186
+ heartbeat_interval: float = 30.0,
187
+ stale_threshold: float | None = None,
188
+ poll_interval: float = 0.25,
189
+ ) -> None:
190
+ if heartbeat_interval <= 0:
191
+ msg = f"heartbeat_interval must be positive, got {heartbeat_interval}"
192
+ raise ValueError(msg)
193
+ if stale_threshold is None:
194
+ stale_threshold = heartbeat_interval * 3
195
+ if stale_threshold <= heartbeat_interval:
196
+ msg = f"stale_threshold must exceed heartbeat_interval ({stale_threshold} <= {heartbeat_interval})"
197
+ raise ValueError(msg)
198
+ if poll_interval <= 0:
199
+ msg = f"poll_interval must be positive, got {poll_interval}"
200
+ raise ValueError(msg)
201
+
202
+ self.lock_file: str = os.fspath(lock_file)
203
+ self.timeout: float = timeout
204
+ self.blocking: bool = blocking
205
+ self.heartbeat_interval: float = heartbeat_interval
206
+ self.stale_threshold: float = stale_threshold
207
+ self.poll_interval: float = poll_interval
208
+
209
+ self._paths = _Paths(
210
+ state=f"{self.lock_file}.state",
211
+ write=f"{self.lock_file}.write",
212
+ readers=f"{self.lock_file}.readers",
213
+ )
214
+ ensure_directory_exists(self.lock_file)
215
+ self._locks = _Locks(
216
+ internal=threading.Lock(),
217
+ transaction=threading.Lock(),
218
+ state=SoftFileLock(self._paths.state, timeout=-1),
219
+ )
220
+ self._readers_dir_fd: int | None = None
221
+ self._hold: _Hold | None = None
222
+ self._fork_invalidated: bool = False
223
+ self._closed: bool = False
224
+
225
+ with _all_instances_lock:
226
+ _all_instances[Path(self.lock_file).resolve()] = self
227
+ _register_hooks()
228
+
229
+ @contextmanager
230
+ def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]:
231
+ """
232
+ Context manager that acquires and releases a shared read lock.
233
+
234
+ Falls back to instance defaults for *timeout* and *blocking* when ``None``.
235
+
236
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
237
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
238
+
239
+ :raises RuntimeError: if a write lock is already held on this instance
240
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
241
+
242
+ """
243
+ self.acquire_read(timeout, blocking=blocking)
244
+ try:
245
+ yield
246
+ finally:
247
+ self.release()
248
+
249
+ @contextmanager
250
+ def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]:
251
+ """
252
+ Context manager that acquires and releases an exclusive write lock.
253
+
254
+ Falls back to instance defaults for *timeout* and *blocking* when ``None``.
255
+
256
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default
257
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default
258
+
259
+ :raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread
260
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
261
+
262
+ """
263
+ self.acquire_write(timeout, blocking=blocking)
264
+ try:
265
+ yield
266
+ finally:
267
+ self.release()
268
+
269
+ def acquire_read(self, timeout: float | None = None, *, blocking: bool | None = None) -> AcquireReturnProxy:
270
+ """
271
+ Acquire a shared read lock.
272
+
273
+ If this instance already holds a read lock, the lock level is incremented (reentrant). Attempting to acquire a
274
+ read lock while holding a write lock raises :class:`RuntimeError` (downgrade not allowed). On the 0→1
275
+ transition a daemon heartbeat thread is started that refreshes the reader marker's ``mtime`` every
276
+ ``heartbeat_interval`` seconds so peers on other hosts do not evict the marker as stale.
277
+
278
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default; ``-1`` means block
279
+ indefinitely
280
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable;
281
+ ``None`` uses the instance default
282
+
283
+ :returns: a proxy that can be used as a context manager to release the lock
284
+
285
+ :raises RuntimeError: if a write lock is already held on this instance, if this instance was invalidated by
286
+ :func:`os.fork`, or if :meth:`close` was called
287
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
288
+
289
+ """
290
+ return self._acquire("read", timeout, blocking=blocking)
291
+
292
+ def acquire_write(self, timeout: float | None = None, *, blocking: bool | None = None) -> AcquireReturnProxy:
293
+ """
294
+ Acquire an exclusive write lock.
295
+
296
+ If this instance already holds a write lock from the same thread, the lock level is incremented (reentrant).
297
+ Attempting to acquire a write lock while holding a read lock raises :class:`RuntimeError` (upgrade not
298
+ allowed). Write locks are pinned to the acquiring thread: a different thread trying to re-enter also raises
299
+ :class:`RuntimeError`.
300
+
301
+ Writer acquisition runs in two phases. Phase 1 atomically claims ``<path>.write`` via ``O_CREAT | O_EXCL``,
302
+ which immediately blocks any new reader on any host. Phase 2 waits for existing readers to drain. Writer
303
+ starvation is impossible: new readers see ``<path>.write`` during phase 2 and wait behind the pending writer.
304
+
305
+ :param timeout: maximum wait time in seconds, or ``None`` to use the instance default; ``-1`` means block
306
+ indefinitely
307
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable;
308
+ ``None`` uses the instance default
309
+
310
+ :returns: a proxy that can be used as a context manager to release the lock
311
+
312
+ :raises RuntimeError: if a read lock is already held, if a write lock is held by a different thread, if this
313
+ instance was invalidated by :func:`os.fork`, or if :meth:`close` was called
314
+ :raises Timeout: if the lock cannot be acquired within *timeout* seconds
315
+
316
+ """
317
+ return self._acquire("write", timeout, blocking=blocking)
318
+
319
+ def close(self) -> None:
320
+ """
321
+ Release any held lock and release internal filesystem resources.
322
+
323
+ Idempotent. After calling this method the instance can no longer acquire locks — subsequent acquires raise
324
+ :class:`RuntimeError`. A fork-invalidated instance is closed without raising.
325
+ """
326
+ self.release(force=True)
327
+ with self._locks.internal:
328
+ if self._closed:
329
+ return
330
+ self._closed = True
331
+ if self._readers_dir_fd is not None:
332
+ with suppress(OSError):
333
+ os.close(self._readers_dir_fd)
334
+ self._readers_dir_fd = None
335
+
336
+ def release(self, *, force: bool = False) -> None:
337
+ """
338
+ Release one level of the current lock.
339
+
340
+ When the lock level reaches zero the heartbeat thread is stopped and the held marker file is unlinked. On a
341
+ fork-invalidated instance (that is, the child of a :func:`os.fork` call made while the parent held a lock)
342
+ this method is a no-op so inherited ``with`` blocks can unwind cleanly in the child.
343
+
344
+ :param force: if ``True``, release the lock completely regardless of the current lock level
345
+
346
+ :raises RuntimeError: if no lock is currently held and *force* is ``False``
347
+
348
+ """
349
+ with self._locks.internal:
350
+ if self._fork_invalidated:
351
+ # Inherited state from the parent is meaningless in the child; clear any counters and return.
352
+ self._hold = None
353
+ return
354
+ hold = self._hold
355
+ if hold is None:
356
+ if force:
357
+ return
358
+ msg = f"Cannot release a lock on {self.lock_file} (lock id: {id(self)}) that is not held"
359
+ raise RuntimeError(msg)
360
+ if force:
361
+ hold.level = 0
362
+ else:
363
+ hold.level -= 1
364
+ if hold.level > 0:
365
+ return
366
+ self._hold = None
367
+
368
+ # Order matters: signal → join → unlink. A late tick on a deleted marker is harmless, and the
369
+ # token check in the heartbeat callback would catch any re-acquisition race, but joining first
370
+ # removes even that theoretical race.
371
+ hold.heartbeat_stop.set()
372
+ hold.heartbeat_thread.join(timeout=self.heartbeat_interval + 1.0)
373
+ if hold.is_reader:
374
+ _unlink(hold.marker_name, dir_fd=self._readers_dir_fd)
375
+ else:
376
+ _unlink(hold.marker_name)
377
+
378
+ @classmethod
379
+ def get_lock(
380
+ cls,
381
+ lock_file: str | os.PathLike[str],
382
+ timeout: float = -1,
383
+ *,
384
+ blocking: bool = True,
385
+ ) -> SoftReadWriteLock:
386
+ """
387
+ Return the singleton :class:`SoftReadWriteLock` for *lock_file*.
388
+
389
+ :param lock_file: path to the lock file; sidecar state/write/readers live next to it
390
+ :param timeout: maximum wait time in seconds; ``-1`` means block indefinitely
391
+ :param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable
392
+
393
+ :returns: the singleton lock instance
394
+
395
+ :raises ValueError: if an instance already exists for this path with different *timeout* or *blocking* values
396
+
397
+ """
398
+ return cls(lock_file, timeout, blocking=blocking)
399
+
400
+ def _acquire(
401
+ self,
402
+ mode: _Mode,
403
+ timeout: float | None,
404
+ *,
405
+ blocking: bool | None,
406
+ ) -> AcquireReturnProxy:
407
+ effective_timeout = self.timeout if timeout is None else timeout
408
+ blocking = self.blocking if blocking is None else blocking
409
+
410
+ with self._locks.internal:
411
+ if self._fork_invalidated:
412
+ msg = f"SoftReadWriteLock on {self.lock_file} was invalidated by fork(); construct a new instance"
413
+ raise RuntimeError(msg)
414
+ if self._closed:
415
+ msg = f"SoftReadWriteLock on {self.lock_file} has been closed"
416
+ raise RuntimeError(msg)
417
+ if self._hold is not None:
418
+ return self._validate_reentrant(mode)
419
+
420
+ start = time.perf_counter()
421
+ if not blocking:
422
+ acquired = self._locks.transaction.acquire(blocking=False)
423
+ elif effective_timeout == -1:
424
+ acquired = self._locks.transaction.acquire(blocking=True)
425
+ else:
426
+ acquired = self._locks.transaction.acquire(blocking=True, timeout=effective_timeout)
427
+ if not acquired:
428
+ raise Timeout(self.lock_file) from None
429
+ try:
430
+ return self._do_acquire_inner(mode, effective_timeout, start, blocking=blocking)
431
+ finally:
432
+ self._locks.transaction.release()
433
+
434
+ def _do_acquire_inner(
435
+ self,
436
+ mode: _Mode,
437
+ effective_timeout: float,
438
+ start: float,
439
+ *,
440
+ blocking: bool,
441
+ ) -> AcquireReturnProxy:
442
+ with self._locks.internal:
443
+ if self._hold is not None:
444
+ return self._validate_reentrant(mode)
445
+ deadline = None if effective_timeout == -1 else start + effective_timeout
446
+ token = secrets.token_hex(16)
447
+ if mode == "write":
448
+ marker_name, is_reader = self._acquire_writer_slot(token, deadline=deadline, blocking=blocking)
449
+ else:
450
+ marker_name, is_reader = self._acquire_reader_slot(token, deadline=deadline, blocking=blocking)
451
+ stop_event = threading.Event()
452
+ heartbeat = _HeartbeatThread(
453
+ refresh=self._refresh_marker,
454
+ interval=self.heartbeat_interval,
455
+ stop_event=stop_event,
456
+ name=f"filelock-heartbeat-{id(self):x}",
457
+ )
458
+ with self._locks.internal:
459
+ self._hold = _Hold(
460
+ level=1,
461
+ mode=mode,
462
+ write_thread_id=threading.get_ident() if mode == "write" else None,
463
+ marker_name=marker_name,
464
+ is_reader=is_reader,
465
+ token=token,
466
+ heartbeat_thread=heartbeat,
467
+ heartbeat_stop=stop_event,
468
+ )
469
+ heartbeat.start()
470
+ return AcquireReturnProxy(lock=self)
471
+
472
+ def _validate_reentrant(self, mode: _Mode) -> AcquireReturnProxy:
473
+ hold = self._hold
474
+ assert hold is not None # noqa: S101
475
+ if hold.mode != mode:
476
+ opposite = "write" if mode == "read" else "read"
477
+ direction = "downgrade" if mode == "read" else "upgrade"
478
+ msg = (
479
+ f"Cannot acquire {mode} lock on {self.lock_file} (lock id: {id(self)}): "
480
+ f"already holding a {opposite} lock ({direction} not allowed)"
481
+ )
482
+ raise RuntimeError(msg)
483
+ if mode == "write" and (cur := threading.get_ident()) != hold.write_thread_id:
484
+ msg = (
485
+ f"Cannot acquire write lock on {self.lock_file} (lock id: {id(self)}) "
486
+ f"from thread {cur} while it is held by thread {hold.write_thread_id}"
487
+ )
488
+ raise RuntimeError(msg)
489
+ hold.level += 1
490
+ return AcquireReturnProxy(lock=self)
491
+
492
+ def _acquire_writer_slot(
493
+ self,
494
+ token: str,
495
+ *,
496
+ deadline: float | None,
497
+ blocking: bool,
498
+ ) -> tuple[str, bool]:
499
+ # Phase 2 scans readers/ via dirfd (where supported), so we need it open even though writers never
500
+ # create files inside.
501
+ self._open_readers_dir()
502
+
503
+ def try_claim_writer() -> bool:
504
+ with self._locks.state:
505
+ _break_stale_marker(self._paths.write, stale_threshold=self.stale_threshold, now=time.time())
506
+ if _file_exists(self._paths.write):
507
+ return False
508
+ try:
509
+ _atomic_create_marker(self._paths.write, token)
510
+ except FileExistsError:
511
+ return False
512
+ return True
513
+
514
+ def readers_drained_touching() -> bool:
515
+ with self._locks.state:
516
+ # Refresh our writer marker on every scan iteration. Otherwise phase 2 can exceed
517
+ # ``stale_threshold`` under contention and a peer would treat us as stale and evict us.
518
+ with suppress(OSError):
519
+ _touch(self._paths.write)
520
+ self._break_stale_readers(time.time())
521
+ return not self._any_readers()
522
+
523
+ self._wait_for(try_claim_writer, deadline=deadline, blocking=blocking)
524
+ try:
525
+ self._wait_for(readers_drained_touching, deadline=deadline, blocking=blocking)
526
+ except Timeout:
527
+ # Give up our writer claim so readers can make progress again.
528
+ _unlink(self._paths.write)
529
+ raise
530
+ return self._paths.write, False
531
+
532
+ def _acquire_reader_slot(
533
+ self,
534
+ token: str,
535
+ *,
536
+ deadline: float | None,
537
+ blocking: bool,
538
+ ) -> tuple[str, bool]:
539
+ self._open_readers_dir()
540
+ reader_name = f"{uuid.uuid4().hex}.{os.getpid()}"
541
+ dir_fd = self._readers_dir_fd
542
+ full_reader_path = str(Path(self._paths.readers) / reader_name)
543
+
544
+ def try_claim_reader() -> bool:
545
+ with self._locks.state:
546
+ _break_stale_marker(self._paths.write, stale_threshold=self.stale_threshold, now=time.time())
547
+ if _file_exists(self._paths.write):
548
+ return False
549
+ if dir_fd is not None:
550
+ _atomic_create_marker(reader_name, token, dir_fd=dir_fd)
551
+ else: # pragma: win32 cover
552
+ _atomic_create_marker(full_reader_path, token)
553
+ return True
554
+
555
+ self._wait_for(try_claim_reader, deadline=deadline, blocking=blocking)
556
+ return (reader_name if dir_fd is not None else full_reader_path), True
557
+
558
+ def _wait_for(
559
+ self,
560
+ predicate: Callable[[], bool],
561
+ *,
562
+ deadline: float | None,
563
+ blocking: bool,
564
+ ) -> None:
565
+ while True:
566
+ if predicate():
567
+ return
568
+ now = time.perf_counter()
569
+ if not blocking:
570
+ raise Timeout(self.lock_file)
571
+ if deadline is not None and now >= deadline:
572
+ raise Timeout(self.lock_file)
573
+ sleep_for = self.poll_interval
574
+ if deadline is not None:
575
+ sleep_for = min(sleep_for, max(deadline - now, 0.0))
576
+ time.sleep(sleep_for)
577
+
578
+ def _open_readers_dir(self) -> None:
579
+ readers_path = Path(self._paths.readers)
580
+ with suppress(FileExistsError):
581
+ readers_path.mkdir(mode=0o700)
582
+ # mkdir has no O_NOFOLLOW, so verify via lstat that we did not land on an attacker-placed symlink
583
+ # or a regular file before we open or scan inside.
584
+ st = os.lstat(self._paths.readers)
585
+ if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
586
+ msg = f"{self._paths.readers} exists but is not a directory or is a symlink; refusing to use it"
587
+ raise RuntimeError(msg)
588
+ if self._readers_dir_fd is None and _SUPPORTS_DIR_FD:
589
+ flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | _O_NOFOLLOW
590
+ self._readers_dir_fd = os.open(self._paths.readers, flags)
591
+
592
+ def _any_readers(self) -> bool:
593
+ for _ in self._iter_reader_entries():
594
+ return True
595
+ return False
596
+
597
+ def _iter_reader_entries(self) -> Generator[tuple[str, bool]]:
598
+ """
599
+ Yield ``(name, dirfd_relative)`` pairs for every live reader marker.
600
+
601
+ ``dirfd_relative`` is ``True`` when *name* should be passed to ``dir_fd=``-aware syscalls; ``False``
602
+ when *name* is a full path because dirfd-relative I/O is unavailable on this platform.
603
+ """
604
+ if self._readers_dir_fd is not None:
605
+ with os.scandir(self._readers_dir_fd) as it:
606
+ for entry in it:
607
+ if not _is_housekeeping_name(entry.name):
608
+ yield entry.name, True
609
+ return
610
+ readers_path = Path(self._paths.readers) # pragma: win32 cover
611
+ with os.scandir(readers_path) as it: # pragma: win32 cover
612
+ for entry in it: # pragma: win32 cover
613
+ if not _is_housekeeping_name(entry.name): # pragma: win32 cover
614
+ yield str(readers_path / entry.name), False # pragma: win32 cover
615
+
616
+ def _break_stale_readers(self, now: float) -> None:
617
+ names: list[tuple[str, int | None]] = []
618
+ try:
619
+ for name, dirfd_relative in self._iter_reader_entries():
620
+ names.append((name, self._readers_dir_fd if dirfd_relative else None))
621
+ except OSError: # pragma: no cover - transient NFS scandir hiccup
622
+ return
623
+ for name, fd in names:
624
+ _break_stale_marker(name, stale_threshold=self.stale_threshold, now=now, dir_fd=fd)
625
+
626
+ def _refresh_marker(self) -> bool:
627
+ with self._locks.internal:
628
+ hold = self._hold
629
+ if hold is None: # pragma: no cover - race between stop_event.set and join
630
+ return False
631
+ marker_name = hold.marker_name
632
+ token = hold.token
633
+ dir_fd = self._readers_dir_fd if hold.is_reader else None
634
+
635
+ read_result = _read_marker(marker_name, dir_fd=dir_fd)
636
+ if read_result is None:
637
+ return False
638
+ info, _mtime = read_result
639
+ # Token mismatch means another process already evicted our marker and created its own; stop the
640
+ # thread so it does not touch a stranger's file.
641
+ if info is None or not hmac.compare_digest(info.token, token):
642
+ return False
643
+ try:
644
+ _touch(marker_name, dir_fd=dir_fd)
645
+ except FileNotFoundError: # pragma: no cover - race between successful read and touch
646
+ return False
647
+ return True
648
+
649
+ def _reset_after_fork_in_child(self) -> None: # pragma: no cover - fork child not tracked
650
+ # Replace every lock this instance owns with a fresh one; the inherited locks may still be held
651
+ # by threads that no longer exist in the child. The readers dirfd and the SoftFileLock state
652
+ # mutex both get dropped for the same reason — the child re-creates them on its next acquire.
653
+ self._locks = _Locks(
654
+ internal=threading.Lock(),
655
+ transaction=threading.Lock(),
656
+ state=SoftFileLock(self._paths.state, timeout=-1),
657
+ )
658
+ self._hold = None
659
+ self._readers_dir_fd = None
660
+ self._fork_invalidated = True
661
+
662
+
663
+ class _HeartbeatThread(threading.Thread):
664
+ def __init__(
665
+ self,
666
+ refresh: Callable[[], bool],
667
+ interval: float,
668
+ stop_event: threading.Event,
669
+ name: str,
670
+ ) -> None:
671
+ super().__init__(name=name, daemon=True)
672
+ self._refresh = refresh
673
+ self._interval = interval
674
+ self._stop_event = stop_event
675
+
676
+ def run(self) -> None:
677
+ while not self._stop_event.wait(self._interval):
678
+ if not self._refresh():
679
+ self._stop_event.set()
680
+ return
681
+
682
+
683
+ def _atomic_create_marker(name: str, token: str, *, dir_fd: int | None = None) -> None:
684
+ # O_NOFOLLOW blocks the symlink-overwrite attack where an attacker pre-creates the marker path as a
685
+ # symlink pointing at a victim file. Mode 0o600 keeps the token unreadable to other users.
686
+ flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY | _O_NOFOLLOW
687
+ if _SUPPORTS_DIR_FD and dir_fd is not None:
688
+ fd = os.open(name, flags, 0o600, dir_fd=dir_fd)
689
+ else:
690
+ fd = os.open(name, flags, 0o600)
691
+ try:
692
+ content = f"{token}\n{os.getpid()}\n{socket.gethostname()}\n".encode("ascii")
693
+ os.write(fd, content)
694
+ finally:
695
+ os.close(fd)
696
+
697
+
698
+ def _read_marker(name: str, *, dir_fd: int | None = None) -> tuple[_MarkerInfo | None, float] | None:
699
+ # O_NOFOLLOW is defense in depth: we already created this file, but a hostile replacement by symlink
700
+ # between create and read would be caught here.
701
+ flags = os.O_RDONLY | _O_NOFOLLOW
702
+ try:
703
+ fd = os.open(name, flags, dir_fd=dir_fd) if _SUPPORTS_DIR_FD and dir_fd is not None else os.open(name, flags)
704
+ except OSError:
705
+ return None
706
+ try:
707
+ try:
708
+ st = os.fstat(fd)
709
+ data = os.read(fd, _MAX_MARKER_SIZE + 1)
710
+ except OSError: # pragma: no cover - fstat/read after a successful open is hard to provoke
711
+ return None
712
+ finally:
713
+ os.close(fd)
714
+ return _parse_marker_bytes(data), st.st_mtime
715
+
716
+
717
+ def _parse_marker_bytes(data: bytes) -> _MarkerInfo | None:
718
+ # Trust nothing about attacker-controlled markers; any deviation returns None so callers fall through
719
+ # to stale cleanup. ``re.match`` caches compiled patterns internally, so the regex is built only once
720
+ # despite being defined inline.
721
+ if not data or len(data) > _MAX_MARKER_SIZE:
722
+ return None
723
+ try:
724
+ text = data.decode("ascii")
725
+ except UnicodeDecodeError:
726
+ return None
727
+ match = re.match(
728
+ r"""
729
+ \A # start of string
730
+ (?P<token> [0-9a-f]{32} ) \n # 128-bit hex token
731
+ (?P<pid> [1-9][0-9]{0,9} ) \n # decimal pid: no leading zero, ≤ 10 digits
732
+ (?P<hostname> [\x21-\x7e]{1,253}) # printable non-whitespace ASCII (RFC 1123 hostname limit)
733
+ \n* # tolerate sloppy writers that append extra newlines
734
+ \Z # end of string
735
+ """,
736
+ text,
737
+ re.VERBOSE,
738
+ )
739
+ if match is None:
740
+ return None
741
+ pid = int(match["pid"], 10)
742
+ if pid > 2**31 - 1:
743
+ return None
744
+ return _MarkerInfo(token=match["token"], pid=pid, hostname=match["hostname"])
745
+
746
+
747
+ def _break_stale_marker( # noqa: PLR0911
748
+ name: str,
749
+ *,
750
+ stale_threshold: float,
751
+ now: float,
752
+ dir_fd: int | None = None,
753
+ ) -> bool:
754
+ # Atomic break pattern: read → rename to unique break-name → re-verify → unlink. The rename gives us a
755
+ # private name nobody else can touch; if the re-verify sees a newer mtime or a different token, the
756
+ # legitimate holder's heartbeat fired between read and rename and we must abort (leaving the .break.*
757
+ # file behind rather than rollback-renaming, because rollback is itself racy).
758
+ read_result = _read_marker(name, dir_fd=dir_fd)
759
+ if read_result is None:
760
+ return False
761
+ info_before, mtime_before = read_result
762
+ if now - mtime_before <= stale_threshold:
763
+ return False
764
+ if info_before is None:
765
+ _unlink(name, dir_fd=dir_fd)
766
+ return True
767
+
768
+ break_name = f"{name}{_BREAK_SUFFIX}.{os.getpid()}.{secrets.token_hex(16)}"
769
+ try:
770
+ if _SUPPORTS_DIR_FD and dir_fd is not None:
771
+ os.rename(name, break_name, src_dir_fd=dir_fd, dst_dir_fd=dir_fd)
772
+ else:
773
+ Path(name).rename(break_name)
774
+ except OSError: # pragma: no cover - race where the marker vanishes between read and rename
775
+ return False
776
+
777
+ read_after = _read_marker(break_name, dir_fd=dir_fd)
778
+ if read_after is None: # pragma: no cover - race where a peer unlinks the break-name file
779
+ return False
780
+ info_after, mtime_after = read_after
781
+ if info_after is None: # pragma: no cover - content replaced post-rename by a racing peer
782
+ _unlink(break_name, dir_fd=dir_fd)
783
+ return True
784
+ if not hmac.compare_digest(info_before.token, info_after.token): # pragma: no cover - race only
785
+ return False
786
+ if mtime_after > mtime_before: # pragma: no cover - heartbeat raced our rename
787
+ return False
788
+ _unlink(break_name, dir_fd=dir_fd)
789
+ return True
790
+
791
+
792
+ def _unlink(name: str, *, dir_fd: int | None = None) -> None:
793
+ with suppress(FileNotFoundError):
794
+ if _SUPPORTS_DIR_FD and dir_fd is not None:
795
+ # Path.unlink has no dir_fd support, so we stay on os.unlink for the dirfd path.
796
+ os.unlink(name, dir_fd=dir_fd)
797
+ else:
798
+ Path(name).unlink()
799
+
800
+
801
+ def _touch(name: str, *, dir_fd: int | None = None) -> None:
802
+ if _SUPPORTS_DIR_FD and dir_fd is not None:
803
+ os.utime(name, None, dir_fd=dir_fd)
804
+ else:
805
+ os.utime(name, None)
806
+
807
+
808
+ def _file_exists(path: str) -> bool:
809
+ try:
810
+ st = os.lstat(path)
811
+ except FileNotFoundError:
812
+ return False
813
+ return stat.S_ISREG(st.st_mode)
814
+
815
+
816
+ def _is_housekeeping_name(name: str) -> bool:
817
+ return name.startswith(".") or _BREAK_SUFFIX in name
818
+
819
+
820
+ def _reset_all_after_fork() -> None: # pragma: no cover - fork child, not tracked by coverage
821
+ global _all_instances_lock # noqa: PLW0603
822
+ # User-created threading locks do not auto-reset across fork: any lock held by a parent thread stays
823
+ # locked in the child with no owner to release it. Replace the module-level lock and every instance's
824
+ # locks with fresh ones; the child is single-threaded at this point so no synchronization is needed.
825
+ _all_instances_lock = threading.Lock()
826
+ for instance in list(_all_instances.values()):
827
+ instance._reset_after_fork_in_child() # noqa: SLF001
828
+
829
+
830
+ def _cleanup_all_instances() -> None: # pragma: no cover - runs from atexit at interpreter shutdown
831
+ for instance in list(_all_instances.values()):
832
+ with suppress(Exception):
833
+ instance.release(force=True)
834
+
835
+
836
+ def _register_hooks() -> None:
837
+ global _atexit_registered, _fork_registered # noqa: PLW0603
838
+ if not _atexit_registered:
839
+ atexit.register(_cleanup_all_instances)
840
+ _atexit_registered = True
841
+ # after_in_child replaces inherited state so the child cannot double-own any lock the parent held.
842
+ if not _fork_registered and hasattr(os, "register_at_fork"):
843
+ os.register_at_fork(after_in_child=_reset_all_after_fork)
844
+ _fork_registered = True
845
+
846
+
847
+ __all__ = [
848
+ "SoftReadWriteLock",
849
+ ]
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_unix.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ import warnings
6
+ from contextlib import suppress
7
+ from errno import EAGAIN, ENOSYS, EWOULDBLOCK
8
+ from pathlib import Path
9
+ from typing import cast
10
+
11
+ from ._api import BaseFileLock
12
+ from ._util import ensure_directory_exists
13
+
14
+ #: a flag to indicate if the fcntl API is available
15
+ has_fcntl = False
16
+ if sys.platform == "win32": # pragma: win32 cover
17
+
18
+ class UnixFileLock(BaseFileLock):
19
+ """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
20
+
21
+ def _acquire(self) -> None:
22
+ raise NotImplementedError
23
+
24
+ def _release(self) -> None:
25
+ raise NotImplementedError
26
+
27
+ else: # pragma: win32 no cover
28
+ try:
29
+ import fcntl
30
+
31
+ _ = (fcntl.flock, fcntl.LOCK_EX, fcntl.LOCK_NB, fcntl.LOCK_UN)
32
+ except (ImportError, AttributeError):
33
+ pass
34
+ else:
35
+ has_fcntl = True
36
+
37
+ class UnixFileLock(BaseFileLock):
38
+ """
39
+ Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems.
40
+
41
+ Lock file cleanup: Unix and macOS delete the lock file reliably after release, even in
42
+ multi-threaded scenarios. Unlike Windows, Unix allows unlinking files that other processes
43
+ have open.
44
+ """
45
+
46
+ def _acquire(self) -> None: # noqa: C901, PLR0912
47
+ ensure_directory_exists(self.lock_file)
48
+ open_flags = os.O_RDWR | os.O_TRUNC
49
+ o_nofollow = getattr(os, "O_NOFOLLOW", None)
50
+ if o_nofollow is not None:
51
+ open_flags |= o_nofollow
52
+ open_flags |= os.O_CREAT
53
+ open_mode = self._open_mode()
54
+ try:
55
+ fd = os.open(self.lock_file, open_flags, open_mode)
56
+ except FileNotFoundError:
57
+ # On FUSE/NFS, os.open(O_CREAT) is not atomic: LOOKUP + CREATE can be split, allowing a concurrent
58
+ # unlink() to delete the file between them. For valid paths, treat ENOENT as transient contention.
59
+ # For invalid paths (e.g., empty string), re-raise to avoid infinite retry loops.
60
+ if self.lock_file and Path(self.lock_file).parent.exists():
61
+ return
62
+ raise
63
+ except PermissionError:
64
+ # Sticky-bit dirs (e.g. /tmp): O_CREAT fails if the file is owned by another user (#317).
65
+ # Fall back to opening the existing file without O_CREAT.
66
+ if not Path(self.lock_file).exists():
67
+ raise
68
+ try:
69
+ fd = os.open(self.lock_file, open_flags & ~os.O_CREAT, open_mode)
70
+ except FileNotFoundError:
71
+ return
72
+ if self.has_explicit_mode:
73
+ with suppress(PermissionError):
74
+ os.fchmod(fd, self._context.mode)
75
+ try:
76
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
77
+ except OSError as exception:
78
+ os.close(fd)
79
+ if exception.errno == ENOSYS:
80
+ with suppress(OSError):
81
+ Path(self.lock_file).unlink()
82
+ self._fallback_to_soft_lock()
83
+ self._acquire()
84
+ return
85
+ if exception.errno not in {EAGAIN, EWOULDBLOCK}:
86
+ raise
87
+ else:
88
+ # The file may have been unlinked by a concurrent _release() between our open() and flock().
89
+ # A lock on an unlinked inode is useless — discard and let the retry loop start fresh.
90
+ if os.fstat(fd).st_nlink == 0:
91
+ os.close(fd)
92
+ else:
93
+ self._context.lock_file_fd = fd
94
+
95
+ def _fallback_to_soft_lock(self) -> None:
96
+ from ._soft import SoftFileLock # noqa: PLC0415
97
+
98
+ warnings.warn("flock not supported on this filesystem, falling back to SoftFileLock", stacklevel=2)
99
+ from .asyncio import AsyncSoftFileLock, BaseAsyncFileLock # noqa: PLC0415
100
+
101
+ self.__class__ = AsyncSoftFileLock if isinstance(self, BaseAsyncFileLock) else SoftFileLock
102
+
103
+ def _release(self) -> None:
104
+ fd = cast("int", self._context.lock_file_fd)
105
+ self._context.lock_file_fd = None
106
+ with suppress(OSError):
107
+ Path(self.lock_file).unlink()
108
+ fcntl.flock(fd, fcntl.LOCK_UN)
109
+ with suppress(OSError): # close can raise EIO on FUSE/Docker bind-mount filesystems after unlink
110
+ os.close(fd)
111
+
112
+
113
+ __all__ = [
114
+ "UnixFileLock",
115
+ "has_fcntl",
116
+ ]
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/_windows.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from contextlib import suppress
6
+ from errno import EACCES
7
+ from pathlib import Path
8
+ from typing import cast
9
+
10
+ from ._api import BaseFileLock
11
+ from ._util import ensure_directory_exists, raise_on_not_writable_file
12
+
13
+ if sys.platform == "win32": # pragma: win32 cover
14
+ import ctypes
15
+ import msvcrt
16
+ from ctypes import wintypes
17
+
18
+ # Windows API constants for reparse point detection
19
+ FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400
20
+ INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF
21
+
22
+ # Load kernel32.dll
23
+ _kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
24
+ _kernel32.GetFileAttributesW.argtypes = [wintypes.LPCWSTR]
25
+ _kernel32.GetFileAttributesW.restype = wintypes.DWORD
26
+
27
+ def _is_reparse_point(path: str) -> bool:
28
+ """
29
+ Check if a path is a reparse point (symlink, junction, etc.) on Windows.
30
+
31
+ :param path: Path to check
32
+
33
+ :returns: True if path is a reparse point, False otherwise
34
+
35
+ :raises OSError: If GetFileAttributesW fails for reasons other than file-not-found
36
+
37
+ """
38
+ attrs = _kernel32.GetFileAttributesW(path)
39
+ if attrs == INVALID_FILE_ATTRIBUTES:
40
+ # File doesn't exist yet - that's fine, we'll create it
41
+ err = ctypes.get_last_error()
42
+ if err == 2: # noqa: PLR2004 # ERROR_FILE_NOT_FOUND
43
+ return False
44
+ if err == 3: # noqa: PLR2004 # ERROR_PATH_NOT_FOUND
45
+ return False
46
+ # Some other error - let caller handle it
47
+ return False
48
+ return bool(attrs & FILE_ATTRIBUTE_REPARSE_POINT)
49
+
50
+ class WindowsFileLock(BaseFileLock):
51
+ """
52
+ Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems.
53
+
54
+ Lock file cleanup: Windows attempts to delete the lock file after release, but deletion is
55
+ not guaranteed in multi-threaded scenarios where another thread holds an open handle. The lock
56
+ file may persist on disk, which does not affect lock correctness.
57
+ """
58
+
59
+ def _acquire(self) -> None:
60
+ raise_on_not_writable_file(self.lock_file)
61
+ ensure_directory_exists(self.lock_file)
62
+
63
+ # Security check: Refuse to open reparse points (symlinks, junctions)
64
+ # This prevents TOCTOU symlink attacks (CVE-TBD)
65
+ if _is_reparse_point(self.lock_file):
66
+ msg = f"Lock file is a reparse point (symlink/junction): {self.lock_file}"
67
+ raise OSError(msg)
68
+
69
+ flags = (
70
+ os.O_RDWR # open for read and write
71
+ | os.O_CREAT # create file if not exists
72
+ )
73
+ try:
74
+ fd = os.open(self.lock_file, flags, self._open_mode())
75
+ except OSError as exception:
76
+ if exception.errno != EACCES: # has no access to this lock
77
+ raise
78
+ else:
79
+ try:
80
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
81
+ except OSError as exception:
82
+ os.close(fd) # close file first
83
+ if exception.errno != EACCES: # file is already locked
84
+ raise
85
+ else:
86
+ self._context.lock_file_fd = fd
87
+
88
+ def _release(self) -> None:
89
+ fd = cast("int", self._context.lock_file_fd)
90
+ self._context.lock_file_fd = None
91
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
92
+ os.close(fd)
93
+
94
+ with suppress(OSError):
95
+ Path(self.lock_file).unlink()
96
+
97
+ else: # pragma: win32 no cover
98
+
99
+ class WindowsFileLock(BaseFileLock):
100
+ """Uses the :func:`msvcrt.locking` function to hard lock the lock file on Windows systems."""
101
+
102
+ def _acquire(self) -> None:
103
+ raise NotImplementedError
104
+
105
+ def _release(self) -> None:
106
+ raise NotImplementedError
107
+
108
+
109
+ __all__ = [
110
+ "WindowsFileLock",
111
+ ]
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/py.typed ADDED
File without changes
.cache/uv/archive-v0/Ih3Q1P8ipe5TvNEUWdwAa/filelock/version.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '3.29.1'
22
+ __version_tuple__ = version_tuple = (3, 29, 1)
23
+
24
+ __commit_id__ = commit_id = None
.cache/uv/archive-v0/Qs_dcKhIt99HrPiFoiNRv/typing_extensions-4.15.0.dist-info/METADATA ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: typing_extensions
3
+ Version: 4.15.0
4
+ Summary: Backported and Experimental Type Hints for Python 3.9+
5
+ Keywords: annotations,backport,checker,checking,function,hinting,hints,type,typechecking,typehinting,typehints,typing
6
+ Author-email: "Guido van Rossum, Jukka Lehtosalo, Łukasz Langa, Michael Lee" <levkivskyi@gmail.com>
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-Expression: PSF-2.0
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Software Development
23
+ License-File: LICENSE
24
+ Project-URL: Bug Tracker, https://github.com/python/typing_extensions/issues
25
+ Project-URL: Changes, https://github.com/python/typing_extensions/blob/main/CHANGELOG.md
26
+ Project-URL: Documentation, https://typing-extensions.readthedocs.io/
27
+ Project-URL: Home, https://github.com/python/typing_extensions
28
+ Project-URL: Q & A, https://github.com/python/typing/discussions
29
+ Project-URL: Repository, https://github.com/python/typing_extensions
30
+
31
+ # Typing Extensions
32
+
33
+ [![Chat at https://gitter.im/python/typing](https://badges.gitter.im/python/typing.svg)](https://gitter.im/python/typing)
34
+
35
+ [Documentation](https://typing-extensions.readthedocs.io/en/latest/#) –
36
+ [PyPI](https://pypi.org/project/typing-extensions/)
37
+
38
+ ## Overview
39
+
40
+ The `typing_extensions` module serves two related purposes:
41
+
42
+ - Enable use of new type system features on older Python versions. For example,
43
+ `typing.TypeGuard` is new in Python 3.10, but `typing_extensions` allows
44
+ users on previous Python versions to use it too.
45
+ - Enable experimentation with new type system PEPs before they are accepted and
46
+ added to the `typing` module.
47
+
48
+ `typing_extensions` is treated specially by static type checkers such as
49
+ mypy and pyright. Objects defined in `typing_extensions` are treated the same
50
+ way as equivalent forms in `typing`.
51
+
52
+ `typing_extensions` uses
53
+ [Semantic Versioning](https://semver.org/). The
54
+ major version will be incremented only for backwards-incompatible changes.
55
+ Therefore, it's safe to depend
56
+ on `typing_extensions` like this: `typing_extensions ~=x.y`,
57
+ where `x.y` is the first version that includes all features you need.
58
+ [This](https://packaging.python.org/en/latest/specifications/version-specifiers/#compatible-release)
59
+ is equivalent to `typing_extensions >=x.y, <(x+1)`. Do not depend on `~= x.y.z`
60
+ unless you really know what you're doing; that defeats the purpose of
61
+ semantic versioning.
62
+
63
+ ## Included items
64
+
65
+ See [the documentation](https://typing-extensions.readthedocs.io/en/latest/#) for a
66
+ complete listing of module contents.
67
+
68
+ ## Contributing
69
+
70
+ See [CONTRIBUTING.md](https://github.com/python/typing_extensions/blob/main/CONTRIBUTING.md)
71
+ for how to contribute to `typing_extensions`.
72
+
.cache/uv/archive-v0/Qs_dcKhIt99HrPiFoiNRv/typing_extensions-4.15.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.12.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.cache/uv/archive-v0/Qs_dcKhIt99HrPiFoiNRv/typing_extensions.py ADDED
The diff for this file is too large to render. See raw diff
 
.cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc-0.0.4.dist-info/RECORD ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ annotated_doc-0.0.4.dist-info/METADATA,sha256=Irm5KJua33dY2qKKAjJ-OhKaVBVIfwFGej_dSe3Z1TU,6566
2
+ annotated_doc-0.0.4.dist-info/WHEEL,sha256=9P2ygRxDrTJz3gsagc0Z96ukrxjr-LFBGOgv3AuKlCA,90
3
+ annotated_doc-0.0.4.dist-info/entry_points.txt,sha256=6OYgBcLyFCUgeqLgnvMyOJxPCWzgy7se4rLPKtNonMs,34
4
+ annotated_doc-0.0.4.dist-info/licenses/LICENSE,sha256=__Fwd5pqy_ZavbQFwIfxzuF4ZpHkqWpANFF-SlBKDN8,1086
5
+ annotated_doc/__init__.py,sha256=VuyxxUe80kfEyWnOrCx_Bk8hybo3aKo6RYBlkBBYW8k,52
6
+ annotated_doc/main.py,sha256=5Zfvxv80SwwLqpRW73AZyZyiM4bWma9QWRbp_cgD20s,1075
7
+ annotated_doc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ annotated_doc-0.0.4.dist-info/RECORD,,
.cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc-0.0.4.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: pdm-backend (2.4.5)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .main import Doc as Doc
2
+
3
+ __version__ = "0.0.4"
.cache/uv/archive-v0/SAOyCfPGdxpvjuy5LHTZY/annotated_doc/main.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Doc:
2
+ """Define the documentation of a type annotation using `Annotated`, to be
3
+ used in class attributes, function and method parameters, return values,
4
+ and variables.
5
+
6
+ The value should be a positional-only string literal to allow static tools
7
+ like editors and documentation generators to use it.
8
+
9
+ This complements docstrings.
10
+
11
+ The string value passed is available in the attribute `documentation`.
12
+
13
+ Example:
14
+
15
+ ```Python
16
+ from typing import Annotated
17
+ from annotated_doc import Doc
18
+
19
+ def hi(name: Annotated[str, Doc("Who to say hi to")]) -> None:
20
+ print(f"Hi, {name}!")
21
+ ```
22
+ """
23
+
24
+ def __init__(self, documentation: str, /) -> None:
25
+ self.documentation = documentation
26
+
27
+ def __repr__(self) -> str:
28
+ return f"Doc({self.documentation!r})"
29
+
30
+ def __hash__(self) -> int:
31
+ return hash(self.documentation)
32
+
33
+ def __eq__(self, other: object) -> bool:
34
+ if not isinstance(other, Doc):
35
+ return NotImplemented
36
+ return self.documentation == other.documentation
.cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11-0.16.0.dist-info/METADATA ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: h11
3
+ Version: 0.16.0
4
+ Summary: A pure-Python, bring-your-own-I/O implementation of HTTP/1.1
5
+ Home-page: https://github.com/python-hyper/h11
6
+ Author: Nathaniel J. Smith
7
+ Author-email: njs@pobox.com
8
+ License: MIT
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: Implementation :: CPython
13
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Internet :: WWW/HTTP
22
+ Classifier: Topic :: System :: Networking
23
+ Requires-Python: >=3.8
24
+ License-File: LICENSE.txt
25
+ Dynamic: author
26
+ Dynamic: author-email
27
+ Dynamic: classifier
28
+ Dynamic: description
29
+ Dynamic: home-page
30
+ Dynamic: license
31
+ Dynamic: license-file
32
+ Dynamic: requires-python
33
+ Dynamic: summary
34
+
35
+ h11
36
+ ===
37
+
38
+ .. image:: https://travis-ci.org/python-hyper/h11.svg?branch=master
39
+ :target: https://travis-ci.org/python-hyper/h11
40
+ :alt: Automated test status
41
+
42
+ .. image:: https://codecov.io/gh/python-hyper/h11/branch/master/graph/badge.svg
43
+ :target: https://codecov.io/gh/python-hyper/h11
44
+ :alt: Test coverage
45
+
46
+ .. image:: https://readthedocs.org/projects/h11/badge/?version=latest
47
+ :target: http://h11.readthedocs.io/en/latest/?badge=latest
48
+ :alt: Documentation Status
49
+
50
+ This is a little HTTP/1.1 library written from scratch in Python,
51
+ heavily inspired by `hyper-h2 <https://hyper-h2.readthedocs.io/>`_.
52
+
53
+ It's a "bring-your-own-I/O" library; h11 contains no IO code
54
+ whatsoever. This means you can hook h11 up to your favorite network
55
+ API, and that could be anything you want: synchronous, threaded,
56
+ asynchronous, or your own implementation of `RFC 6214
57
+ <https://tools.ietf.org/html/rfc6214>`_ -- h11 won't judge you.
58
+ (Compare this to the current state of the art, where every time a `new
59
+ network API <https://trio.readthedocs.io/>`_ comes along then someone
60
+ gets to start over reimplementing the entire HTTP protocol from
61
+ scratch.) Cory Benfield made an `excellent blog post describing the
62
+ benefits of this approach
63
+ <https://lukasa.co.uk/2015/10/The_New_Hyper/>`_, or if you like video
64
+ then here's his `PyCon 2016 talk on the same theme
65
+ <https://www.youtube.com/watch?v=7cC3_jGwl_U>`_.
66
+
67
+ This also means that h11 is not immediately useful out of the box:
68
+ it's a toolkit for building programs that speak HTTP, not something
69
+ that could directly replace ``requests`` or ``twisted.web`` or
70
+ whatever. But h11 makes it much easier to implement something like
71
+ ``requests`` or ``twisted.web``.
72
+
73
+ At a high level, working with h11 goes like this:
74
+
75
+ 1) First, create an ``h11.Connection`` object to track the state of a
76
+ single HTTP/1.1 connection.
77
+
78
+ 2) When you read data off the network, pass it to
79
+ ``conn.receive_data(...)``; you'll get back a list of objects
80
+ representing high-level HTTP "events".
81
+
82
+ 3) When you want to send a high-level HTTP event, create the
83
+ corresponding "event" object and pass it to ``conn.send(...)``;
84
+ this will give you back some bytes that you can then push out
85
+ through the network.
86
+
87
+ For example, a client might instantiate and then send a
88
+ ``h11.Request`` object, then zero or more ``h11.Data`` objects for the
89
+ request body (e.g., if this is a POST), and then a
90
+ ``h11.EndOfMessage`` to indicate the end of the message. Then the
91
+ server would then send back a ``h11.Response``, some ``h11.Data``, and
92
+ its own ``h11.EndOfMessage``. If either side violates the protocol,
93
+ you'll get a ``h11.ProtocolError`` exception.
94
+
95
+ h11 is suitable for implementing both servers and clients, and has a
96
+ pleasantly symmetric API: the events you send as a client are exactly
97
+ the ones that you receive as a server and vice-versa.
98
+
99
+ `Here's an example of a tiny HTTP client
100
+ <https://github.com/python-hyper/h11/blob/master/examples/basic-client.py>`_
101
+
102
+ It also has `a fine manual <https://h11.readthedocs.io/>`_.
103
+
104
+ FAQ
105
+ ---
106
+
107
+ *Whyyyyy?*
108
+
109
+ I wanted to play with HTTP in `Curio
110
+ <https://curio.readthedocs.io/en/latest/tutorial.html>`__ and `Trio
111
+ <https://trio.readthedocs.io>`__, which at the time didn't have any
112
+ HTTP libraries. So I thought, no big deal, Python has, like, a dozen
113
+ different implementations of HTTP, surely I can find one that's
114
+ reusable. I didn't find one, but I did find Cory's call-to-arms
115
+ blog-post. So I figured, well, fine, if I have to implement HTTP from
116
+ scratch, at least I can make sure no-one *else* has to ever again.
117
+
118
+ *Should I use it?*
119
+
120
+ Maybe. You should be aware that it's a very young project. But, it's
121
+ feature complete and has an exhaustive test-suite and complete docs,
122
+ so the next step is for people to try using it and see how it goes
123
+ :-). If you do then please let us know -- if nothing else we'll want
124
+ to talk to you before making any incompatible changes!
125
+
126
+ *What are the features/limitations?*
127
+
128
+ Roughly speaking, it's trying to be a robust, complete, and non-hacky
129
+ implementation of the first "chapter" of the HTTP/1.1 spec: `RFC 7230:
130
+ HTTP/1.1 Message Syntax and Routing
131
+ <https://tools.ietf.org/html/rfc7230>`_. That is, it mostly focuses on
132
+ implementing HTTP at the level of taking bytes on and off the wire,
133
+ and the headers related to that, and tries to be anal about spec
134
+ conformance. It doesn't know about higher-level concerns like URL
135
+ routing, conditional GETs, cross-origin cookie policies, or content
136
+ negotiation. But it does know how to take care of framing,
137
+ cross-version differences in keep-alive handling, and the "obsolete
138
+ line folding" rule, so you can focus your energies on the hard /
139
+ interesting parts for your application, and it tries to support the
140
+ full specification in the sense that any useful HTTP/1.1 conformant
141
+ application should be able to use h11.
142
+
143
+ It's pure Python, and has no dependencies outside of the standard
144
+ library.
145
+
146
+ It has a test suite with 100.0% coverage for both statements and
147
+ branches.
148
+
149
+ Currently it supports Python 3 (testing on 3.8-3.12) and PyPy 3.
150
+ The last Python 2-compatible version was h11 0.11.x.
151
+ (Originally it had a Cython wrapper for `http-parser
152
+ <https://github.com/nodejs/http-parser>`_ and a beautiful nested state
153
+ machine implemented with ``yield from`` to postprocess the output. But
154
+ I had to take these out -- the new *parser* needs fewer lines-of-code
155
+ than the old *parser wrapper*, is written in pure Python, uses no
156
+ exotic language syntax, and has more features. It's sad, really; that
157
+ old state machine was really slick. I just need a few sentences here
158
+ to mourn that.)
159
+
160
+ I don't know how fast it is. I haven't benchmarked or profiled it yet,
161
+ so it's probably got a few pointless hot spots, and I've been trying
162
+ to err on the side of simplicity and robustness instead of
163
+ micro-optimization. But at the architectural level I tried hard to
164
+ avoid fundamentally bad decisions, e.g., I believe that all the
165
+ parsing algorithms remain linear-time even in the face of pathological
166
+ input like slowloris, and there are no byte-by-byte loops. (I also
167
+ believe that it maintains bounded memory usage in the face of
168
+ arbitrary/pathological input.)
169
+
170
+ The whole library is ~800 lines-of-code. You can read and understand
171
+ the whole thing in less than an hour. Most of the energy invested in
172
+ this so far has been spent on trying to keep things simple by
173
+ minimizing special-cases and ad hoc state manipulation; even though it
174
+ is now quite small and simple, I'm still annoyed that I haven't
175
+ figured out how to make it even smaller and simpler. (Unfortunately,
176
+ HTTP does not lend itself to simplicity.)
177
+
178
+ The API is ~feature complete and I don't expect the general outlines
179
+ to change much, but you can't judge an API's ergonomics until you
180
+ actually document and use it, so I'd expect some changes in the
181
+ details.
182
+
183
+ *How do I try it?*
184
+
185
+ .. code-block:: sh
186
+
187
+ $ pip install h11
188
+ $ git clone git@github.com:python-hyper/h11
189
+ $ cd h11/examples
190
+ $ python basic-client.py
191
+
192
+ and go from there.
193
+
194
+ *License?*
195
+
196
+ MIT
197
+
198
+ *Code of conduct?*
199
+
200
+ Contributors are requested to follow our `code of conduct
201
+ <https://github.com/python-hyper/h11/blob/master/CODE_OF_CONDUCT.md>`_ in
202
+ all project spaces.
.cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11-0.16.0.dist-info/RECORD ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ h11/__init__.py,sha256=iO1KzkSO42yZ6ffg-VMgbx_ZVTWGUY00nRYEWn-s3kY,1507
2
+ h11/_abnf.py,sha256=ybixr0xsupnkA6GFAyMubuXF6Tc1lb_hF890NgCsfNc,4815
3
+ h11/_connection.py,sha256=k9YRVf6koZqbttBW36xSWaJpWdZwa-xQVU9AHEo9DuI,26863
4
+ h11/_events.py,sha256=I97aXoal1Wu7dkL548BANBUCkOIbe-x5CioYA9IBY14,11792
5
+ h11/_headers.py,sha256=P7D-lBNxHwdLZPLimmYwrPG-9ZkjElvvJZJdZAgSP-4,10412
6
+ h11/_readers.py,sha256=a4RypORUCC3d0q_kxPuBIM7jTD8iLt5X91TH0FsduN4,8590
7
+ h11/_receivebuffer.py,sha256=xrspsdsNgWFxRfQcTXxR8RrdjRXXTK0Io5cQYWpJ1Ws,5252
8
+ h11/_state.py,sha256=_5LG_BGR8FCcFQeBPH-TMHgm_-B-EUcWCnQof_9XjFE,13231
9
+ h11/_util.py,sha256=LWkkjXyJaFlAy6Lt39w73UStklFT5ovcvo0TkY7RYuk,4888
10
+ h11/_version.py,sha256=GVSsbPSPDcOuF6ptfIiXnVJoaEm3ygXbMnqlr_Giahw,686
11
+ h11/_writers.py,sha256=oFKm6PtjeHfbj4RLX7VB7KDc1gIY53gXG3_HR9ltmTA,5081
12
+ h11/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7
13
+ h11-0.16.0.dist-info/licenses/LICENSE.txt,sha256=N9tbuFkm2yikJ6JYZ_ELEjIAOuob5pzLhRE4rbjm82E,1124
14
+ h11-0.16.0.dist-info/METADATA,sha256=KPMmCYrAn8unm48YD5YIfIQf4kViFct7hyqcfVzRnWQ,8348
15
+ h11-0.16.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
16
+ h11-0.16.0.dist-info/top_level.txt,sha256=F7dC4jl3zeh8TGHEPaWJrMbeuoWbS379Gwdi-Yvdcis,4
17
+ h11-0.16.0.dist-info/RECORD,,
.cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11-0.16.0.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ h11
.cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11/_abnf.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # We use native strings for all the re patterns, to take advantage of string
2
+ # formatting, and then convert to bytestrings when compiling the final re
3
+ # objects.
4
+
5
+ # https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#whitespace
6
+ # OWS = *( SP / HTAB )
7
+ # ; optional whitespace
8
+ OWS = r"[ \t]*"
9
+
10
+ # https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.token.separators
11
+ # token = 1*tchar
12
+ #
13
+ # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
14
+ # / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
15
+ # / DIGIT / ALPHA
16
+ # ; any VCHAR, except delimiters
17
+ token = r"[-!#$%&'*+.^_`|~0-9a-zA-Z]+"
18
+
19
+ # https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#header.fields
20
+ # field-name = token
21
+ field_name = token
22
+
23
+ # The standard says:
24
+ #
25
+ # field-value = *( field-content / obs-fold )
26
+ # field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
27
+ # field-vchar = VCHAR / obs-text
28
+ # obs-fold = CRLF 1*( SP / HTAB )
29
+ # ; obsolete line folding
30
+ # ; see Section 3.2.4
31
+ #
32
+ # https://tools.ietf.org/html/rfc5234#appendix-B.1
33
+ #
34
+ # VCHAR = %x21-7E
35
+ # ; visible (printing) characters
36
+ #
37
+ # https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.quoted-string
38
+ # obs-text = %x80-FF
39
+ #
40
+ # However, the standard definition of field-content is WRONG! It disallows
41
+ # fields containing a single visible character surrounded by whitespace,
42
+ # e.g. "foo a bar".
43
+ #
44
+ # See: https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189
45
+ #
46
+ # So our definition of field_content attempts to fix it up...
47
+ #
48
+ # Also, we allow lots of control characters, because apparently people assume
49
+ # that they're legal in practice (e.g., google analytics makes cookies with
50
+ # \x01 in them!):
51
+ # https://github.com/python-hyper/h11/issues/57
52
+ # We still don't allow NUL or whitespace, because those are often treated as
53
+ # meta-characters and letting them through can lead to nasty issues like SSRF.
54
+ vchar = r"[\x21-\x7e]"
55
+ vchar_or_obs_text = r"[^\x00\s]"
56
+ field_vchar = vchar_or_obs_text
57
+ field_content = r"{field_vchar}+(?:[ \t]+{field_vchar}+)*".format(**globals())
58
+
59
+ # We handle obs-fold at a different level, and our fixed-up field_content
60
+ # already grows to swallow the whole value, so ? instead of *
61
+ field_value = r"({field_content})?".format(**globals())
62
+
63
+ # header-field = field-name ":" OWS field-value OWS
64
+ header_field = (
65
+ r"(?P<field_name>{field_name})"
66
+ r":"
67
+ r"{OWS}"
68
+ r"(?P<field_value>{field_value})"
69
+ r"{OWS}".format(**globals())
70
+ )
71
+
72
+ # https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#request.line
73
+ #
74
+ # request-line = method SP request-target SP HTTP-version CRLF
75
+ # method = token
76
+ # HTTP-version = HTTP-name "/" DIGIT "." DIGIT
77
+ # HTTP-name = %x48.54.54.50 ; "HTTP", case-sensitive
78
+ #
79
+ # request-target is complicated (see RFC 7230 sec 5.3) -- could be path, full
80
+ # URL, host+port (for connect), or even "*", but in any case we are guaranteed
81
+ # that it contists of the visible printing characters.
82
+ method = token
83
+ request_target = r"{vchar}+".format(**globals())
84
+ http_version = r"HTTP/(?P<http_version>[0-9]\.[0-9])"
85
+ request_line = (
86
+ r"(?P<method>{method})"
87
+ r" "
88
+ r"(?P<target>{request_target})"
89
+ r" "
90
+ r"{http_version}".format(**globals())
91
+ )
92
+
93
+ # https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#status.line
94
+ #
95
+ # status-line = HTTP-version SP status-code SP reason-phrase CRLF
96
+ # status-code = 3DIGIT
97
+ # reason-phrase = *( HTAB / SP / VCHAR / obs-text )
98
+ status_code = r"[0-9]{3}"
99
+ reason_phrase = r"([ \t]|{vchar_or_obs_text})*".format(**globals())
100
+ status_line = (
101
+ r"{http_version}"
102
+ r" "
103
+ r"(?P<status_code>{status_code})"
104
+ # However, there are apparently a few too many servers out there that just
105
+ # leave out the reason phrase:
106
+ # https://github.com/scrapy/scrapy/issues/345#issuecomment-281756036
107
+ # https://github.com/seanmonstar/httparse/issues/29
108
+ # so make it optional. ?: is a non-capturing group.
109
+ r"(?: (?P<reason>{reason_phrase}))?".format(**globals())
110
+ )
111
+
112
+ HEXDIG = r"[0-9A-Fa-f]"
113
+ # Actually
114
+ #
115
+ # chunk-size = 1*HEXDIG
116
+ #
117
+ # but we impose an upper-limit to avoid ridiculosity. len(str(2**64)) == 20
118
+ chunk_size = r"({HEXDIG}){{1,20}}".format(**globals())
119
+ # Actually
120
+ #
121
+ # chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
122
+ #
123
+ # but we aren't parsing the things so we don't really care.
124
+ chunk_ext = r";.*"
125
+ chunk_header = (
126
+ r"(?P<chunk_size>{chunk_size})"
127
+ r"(?P<chunk_ext>{chunk_ext})?"
128
+ r"{OWS}\r\n".format(
129
+ **globals()
130
+ ) # Even though the specification does not allow for extra whitespaces,
131
+ # we are lenient with trailing whitespaces because some servers on the wild use it.
132
+ )
.cache/uv/archive-v0/V_EJpQdJR3Hb5Ox_13302/h11/_state.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ################################################################
2
+ # The core state machine
3
+ ################################################################
4
+ #
5
+ # Rule 1: everything that affects the state machine and state transitions must
6
+ # live here in this file. As much as possible goes into the table-based
7
+ # representation, but for the bits that don't quite fit, the actual code and
8
+ # state must nonetheless live here.
9
+ #
10
+ # Rule 2: this file does not know about what role we're playing; it only knows
11
+ # about HTTP request/response cycles in the abstract. This ensures that we
12
+ # don't cheat and apply different rules to local and remote parties.
13
+ #
14
+ #
15
+ # Theory of operation
16
+ # ===================
17
+ #
18
+ # Possibly the simplest way to think about this is that we actually have 5
19
+ # different state machines here. Yes, 5. These are:
20
+ #
21
+ # 1) The client state, with its complicated automaton (see the docs)
22
+ # 2) The server state, with its complicated automaton (see the docs)
23
+ # 3) The keep-alive state, with possible states {True, False}
24
+ # 4) The SWITCH_CONNECT state, with possible states {False, True}
25
+ # 5) The SWITCH_UPGRADE state, with possible states {False, True}
26
+ #
27
+ # For (3)-(5), the first state listed is the initial state.
28
+ #
29
+ # (1)-(3) are stored explicitly in member variables. The last
30
+ # two are stored implicitly in the pending_switch_proposals set as:
31
+ # (state of 4) == (_SWITCH_CONNECT in pending_switch_proposals)
32
+ # (state of 5) == (_SWITCH_UPGRADE in pending_switch_proposals)
33
+ #
34
+ # And each of these machines has two different kinds of transitions:
35
+ #
36
+ # a) Event-triggered
37
+ # b) State-triggered
38
+ #
39
+ # Event triggered is the obvious thing that you'd think it is: some event
40
+ # happens, and if it's the right event at the right time then a transition
41
+ # happens. But there are somewhat complicated rules for which machines can
42
+ # "see" which events. (As a rule of thumb, if a machine "sees" an event, this
43
+ # means two things: the event can affect the machine, and if the machine is
44
+ # not in a state where it expects that event then it's an error.) These rules
45
+ # are:
46
+ #
47
+ # 1) The client machine sees all h11.events objects emitted by the client.
48
+ #
49
+ # 2) The server machine sees all h11.events objects emitted by the server.
50
+ #
51
+ # It also sees the client's Request event.
52
+ #
53
+ # And sometimes, server events are annotated with a _SWITCH_* event. For
54
+ # example, we can have a (Response, _SWITCH_CONNECT) event, which is
55
+ # different from a regular Response event.
56
+ #
57
+ # 3) The keep-alive machine sees the process_keep_alive_disabled() event
58
+ # (which is derived from Request/Response events), and this event
59
+ # transitions it from True -> False, or from False -> False. There's no way
60
+ # to transition back.
61
+ #
62
+ # 4&5) The _SWITCH_* machines transition from False->True when we get a
63
+ # Request that proposes the relevant type of switch (via
64
+ # process_client_switch_proposals), and they go from True->False when we
65
+ # get a Response that has no _SWITCH_* annotation.
66
+ #
67
+ # So that's event-triggered transitions.
68
+ #
69
+ # State-triggered transitions are less standard. What they do here is couple
70
+ # the machines together. The way this works is, when certain *joint*
71
+ # configurations of states are achieved, then we automatically transition to a
72
+ # new *joint* state. So, for example, if we're ever in a joint state with
73
+ #
74
+ # client: DONE
75
+ # keep-alive: False
76
+ #
77
+ # then the client state immediately transitions to:
78
+ #
79
+ # client: MUST_CLOSE
80
+ #
81
+ # This is fundamentally different from an event-based transition, because it
82
+ # doesn't matter how we arrived at the {client: DONE, keep-alive: False} state
83
+ # -- maybe the client transitioned SEND_BODY -> DONE, or keep-alive
84
+ # transitioned True -> False. Either way, once this precondition is satisfied,
85
+ # this transition is immediately triggered.
86
+ #
87
+ # What if two conflicting state-based transitions get enabled at the same
88
+ # time? In practice there's only one case where this arises (client DONE ->
89
+ # MIGHT_SWITCH_PROTOCOL versus DONE -> MUST_CLOSE), and we resolve it by
90
+ # explicitly prioritizing the DONE -> MIGHT_SWITCH_PROTOCOL transition.
91
+ #
92
+ # Implementation
93
+ # --------------
94
+ #
95
+ # The event-triggered transitions for the server and client machines are all
96
+ # stored explicitly in a table. Ditto for the state-triggered transitions that
97
+ # involve just the server and client state.
98
+ #
99
+ # The transitions for the other machines, and the state-triggered transitions
100
+ # that involve the other machines, are written out as explicit Python code.
101
+ #
102
+ # It'd be nice if there were some cleaner way to do all this. This isn't
103
+ # *too* terrible, but I feel like it could probably be better.
104
+ #
105
+ # WARNING
106
+ # -------
107
+ #
108
+ # The script that generates the state machine diagrams for the docs knows how
109
+ # to read out the EVENT_TRIGGERED_TRANSITIONS and STATE_TRIGGERED_TRANSITIONS
110
+ # tables. But it can't automatically read the transitions that are written
111
+ # directly in Python code. So if you touch those, you need to also update the
112
+ # script to keep it in sync!
113
+ from typing import cast, Dict, Optional, Set, Tuple, Type, Union
114
+
115
+ from ._events import *
116
+ from ._util import LocalProtocolError, Sentinel
117
+
118
+ # Everything in __all__ gets re-exported as part of the h11 public API.
119
+ __all__ = [
120
+ "CLIENT",
121
+ "SERVER",
122
+ "IDLE",
123
+ "SEND_RESPONSE",
124
+ "SEND_BODY",
125
+ "DONE",
126
+ "MUST_CLOSE",
127
+ "CLOSED",
128
+ "MIGHT_SWITCH_PROTOCOL",
129
+ "SWITCHED_PROTOCOL",
130
+ "ERROR",
131
+ ]
132
+
133
+
134
+ class CLIENT(Sentinel, metaclass=Sentinel):
135
+ pass
136
+
137
+
138
+ class SERVER(Sentinel, metaclass=Sentinel):
139
+ pass
140
+
141
+
142
+ # States
143
+ class IDLE(Sentinel, metaclass=Sentinel):
144
+ pass
145
+
146
+
147
+ class SEND_RESPONSE(Sentinel, metaclass=Sentinel):
148
+ pass
149
+
150
+
151
+ class SEND_BODY(Sentinel, metaclass=Sentinel):
152
+ pass
153
+
154
+
155
+ class DONE(Sentinel, metaclass=Sentinel):
156
+ pass
157
+
158
+
159
+ class MUST_CLOSE(Sentinel, metaclass=Sentinel):
160
+ pass
161
+
162
+
163
+ class CLOSED(Sentinel, metaclass=Sentinel):
164
+ pass
165
+
166
+
167
+ class ERROR(Sentinel, metaclass=Sentinel):
168
+ pass
169
+
170
+
171
+ # Switch types
172
+ class MIGHT_SWITCH_PROTOCOL(Sentinel, metaclass=Sentinel):
173
+ pass
174
+
175
+
176
+ class SWITCHED_PROTOCOL(Sentinel, metaclass=Sentinel):
177
+ pass
178
+
179
+
180
+ class _SWITCH_UPGRADE(Sentinel, metaclass=Sentinel):
181
+ pass
182
+
183
+
184
+ class _SWITCH_CONNECT(Sentinel, metaclass=Sentinel):
185
+ pass
186
+
187
+
188
+ EventTransitionType = Dict[
189
+ Type[Sentinel],
190
+ Dict[
191
+ Type[Sentinel],
192
+ Dict[Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], Type[Sentinel]],
193
+ ],
194
+ ]
195
+
196
+ EVENT_TRIGGERED_TRANSITIONS: EventTransitionType = {
197
+ CLIENT: {
198
+ IDLE: {Request: SEND_BODY, ConnectionClosed: CLOSED},
199
+ SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE},
200
+ DONE: {ConnectionClosed: CLOSED},
201
+ MUST_CLOSE: {ConnectionClosed: CLOSED},
202
+ CLOSED: {ConnectionClosed: CLOSED},
203
+ MIGHT_SWITCH_PROTOCOL: {},
204
+ SWITCHED_PROTOCOL: {},
205
+ ERROR: {},
206
+ },
207
+ SERVER: {
208
+ IDLE: {
209
+ ConnectionClosed: CLOSED,
210
+ Response: SEND_BODY,
211
+ # Special case: server sees client Request events, in this form
212
+ (Request, CLIENT): SEND_RESPONSE,
213
+ },
214
+ SEND_RESPONSE: {
215
+ InformationalResponse: SEND_RESPONSE,
216
+ Response: SEND_BODY,
217
+ (InformationalResponse, _SWITCH_UPGRADE): SWITCHED_PROTOCOL,
218
+ (Response, _SWITCH_CONNECT): SWITCHED_PROTOCOL,
219
+ },
220
+ SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE},
221
+ DONE: {ConnectionClosed: CLOSED},
222
+ MUST_CLOSE: {ConnectionClosed: CLOSED},
223
+ CLOSED: {ConnectionClosed: CLOSED},
224
+ SWITCHED_PROTOCOL: {},
225
+ ERROR: {},
226
+ },
227
+ }
228
+
229
+ StateTransitionType = Dict[
230
+ Tuple[Type[Sentinel], Type[Sentinel]], Dict[Type[Sentinel], Type[Sentinel]]
231
+ ]
232
+
233
+ # NB: there are also some special-case state-triggered transitions hard-coded
234
+ # into _fire_state_triggered_transitions below.
235
+ STATE_TRIGGERED_TRANSITIONS: StateTransitionType = {
236
+ # (Client state, Server state) -> new states
237
+ # Protocol negotiation
238
+ (MIGHT_SWITCH_PROTOCOL, SWITCHED_PROTOCOL): {CLIENT: SWITCHED_PROTOCOL},
239
+ # Socket shutdown
240
+ (CLOSED, DONE): {SERVER: MUST_CLOSE},
241
+ (CLOSED, IDLE): {SERVER: MUST_CLOSE},
242
+ (ERROR, DONE): {SERVER: MUST_CLOSE},
243
+ (DONE, CLOSED): {CLIENT: MUST_CLOSE},
244
+ (IDLE, CLOSED): {CLIENT: MUST_CLOSE},
245
+ (DONE, ERROR): {CLIENT: MUST_CLOSE},
246
+ }
247
+
248
+
249
+ class ConnectionState:
250
+ def __init__(self) -> None:
251
+ # Extra bits of state that don't quite fit into the state model.
252
+
253
+ # If this is False then it enables the automatic DONE -> MUST_CLOSE
254
+ # transition. Don't set this directly; call .keep_alive_disabled()
255
+ self.keep_alive = True
256
+
257
+ # This is a subset of {UPGRADE, CONNECT}, containing the proposals
258
+ # made by the client for switching protocols.
259
+ self.pending_switch_proposals: Set[Type[Sentinel]] = set()
260
+
261
+ self.states: Dict[Type[Sentinel], Type[Sentinel]] = {CLIENT: IDLE, SERVER: IDLE}
262
+
263
+ def process_error(self, role: Type[Sentinel]) -> None:
264
+ self.states[role] = ERROR
265
+ self._fire_state_triggered_transitions()
266
+
267
+ def process_keep_alive_disabled(self) -> None:
268
+ self.keep_alive = False
269
+ self._fire_state_triggered_transitions()
270
+
271
+ def process_client_switch_proposal(self, switch_event: Type[Sentinel]) -> None:
272
+ self.pending_switch_proposals.add(switch_event)
273
+ self._fire_state_triggered_transitions()
274
+
275
+ def process_event(
276
+ self,
277
+ role: Type[Sentinel],
278
+ event_type: Type[Event],
279
+ server_switch_event: Optional[Type[Sentinel]] = None,
280
+ ) -> None:
281
+ _event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type
282
+ if server_switch_event is not None:
283
+ assert role is SERVER
284
+ if server_switch_event not in self.pending_switch_proposals:
285
+ raise LocalProtocolError(
286
+ "Received server _SWITCH_UPGRADE event without a pending proposal"
287
+ )
288
+ _event_type = (event_type, server_switch_event)
289
+ if server_switch_event is None and _event_type is Response:
290
+ self.pending_switch_proposals = set()
291
+ self._fire_event_triggered_transitions(role, _event_type)
292
+ # Special case: the server state does get to see Request
293
+ # events.
294
+ if _event_type is Request:
295
+ assert role is CLIENT
296
+ self._fire_event_triggered_transitions(SERVER, (Request, CLIENT))
297
+ self._fire_state_triggered_transitions()
298
+
299
+ def _fire_event_triggered_transitions(
300
+ self,
301
+ role: Type[Sentinel],
302
+ event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]],
303
+ ) -> None:
304
+ state = self.states[role]
305
+ try:
306
+ new_state = EVENT_TRIGGERED_TRANSITIONS[role][state][event_type]
307
+ except KeyError:
308
+ event_type = cast(Type[Event], event_type)
309
+ raise LocalProtocolError(
310
+ "can't handle event type {} when role={} and state={}".format(
311
+ event_type.__name__, role, self.states[role]
312
+ )
313
+ ) from None
314
+ self.states[role] = new_state
315
+
316
+ def _fire_state_triggered_transitions(self) -> None:
317
+ # We apply these rules repeatedly until converging on a fixed point
318
+ while True:
319
+ start_states = dict(self.states)
320
+
321
+ # It could happen that both these special-case transitions are
322
+ # enabled at the same time:
323
+ #
324
+ # DONE -> MIGHT_SWITCH_PROTOCOL
325
+ # DONE -> MUST_CLOSE
326
+ #
327
+ # For example, this will always be true of a HTTP/1.0 client
328
+ # requesting CONNECT. If this happens, the protocol switch takes
329
+ # priority. From there the client will either go to
330
+ # SWITCHED_PROTOCOL, in which case it's none of our business when
331
+ # they close the connection, or else the server will deny the
332
+ # request, in which case the client will go back to DONE and then
333
+ # from there to MUST_CLOSE.
334
+ if self.pending_switch_proposals:
335
+ if self.states[CLIENT] is DONE:
336
+ self.states[CLIENT] = MIGHT_SWITCH_PROTOCOL
337
+
338
+ if not self.pending_switch_proposals:
339
+ if self.states[CLIENT] is MIGHT_SWITCH_PROTOCOL:
340
+ self.states[CLIENT] = DONE
341
+
342
+ if not self.keep_alive:
343
+ for role in (CLIENT, SERVER):
344
+ if self.states[role] is DONE:
345
+ self.states[role] = MUST_CLOSE
346
+
347
+ # Tabular state-triggered transitions
348
+ joint_state = (self.states[CLIENT], self.states[SERVER])
349
+ changes = STATE_TRIGGERED_TRANSITIONS.get(joint_state, {})
350
+ self.states.update(changes)
351
+
352
+ if self.states == start_states:
353
+ # Fixed point reached
354
+ return
355
+
356
+ def start_next_cycle(self) -> None:
357
+ if self.states != {CLIENT: DONE, SERVER: DONE}:
358
+ raise LocalProtocolError(
359
+ f"not in a reusable state. self.states={self.states}"
360
+ )
361
+ # Can't reach DONE/DONE with any of these active, but still, let's be
362
+ # sure.
363
+ assert self.keep_alive
364
+ assert not self.pending_switch_proposals
365
+ self.states = {CLIENT: IDLE, SERVER: IDLE}
.cache/uv/archive-v0/YlYoCgs7J-Rpy5AtSN3P_/httpcore/_exceptions.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import typing
3
+
4
+ ExceptionMapping = typing.Mapping[typing.Type[Exception], typing.Type[Exception]]
5
+
6
+
7
+ @contextlib.contextmanager
8
+ def map_exceptions(map: ExceptionMapping) -> typing.Iterator[None]:
9
+ try:
10
+ yield
11
+ except Exception as exc: # noqa: PIE786
12
+ for from_exc, to_exc in map.items():
13
+ if isinstance(exc, from_exc):
14
+ raise to_exc(exc) from exc
15
+ raise # pragma: nocover
16
+
17
+
18
+ class ConnectionNotAvailable(Exception):
19
+ pass
20
+
21
+
22
+ class ProxyError(Exception):
23
+ pass
24
+
25
+
26
+ class UnsupportedProtocol(Exception):
27
+ pass
28
+
29
+
30
+ class ProtocolError(Exception):
31
+ pass
32
+
33
+
34
+ class RemoteProtocolError(ProtocolError):
35
+ pass
36
+
37
+
38
+ class LocalProtocolError(ProtocolError):
39
+ pass
40
+
41
+
42
+ # Timeout errors
43
+
44
+
45
+ class TimeoutException(Exception):
46
+ pass
47
+
48
+
49
+ class PoolTimeout(TimeoutException):
50
+ pass
51
+
52
+
53
+ class ConnectTimeout(TimeoutException):
54
+ pass
55
+
56
+
57
+ class ReadTimeout(TimeoutException):
58
+ pass
59
+
60
+
61
+ class WriteTimeout(TimeoutException):
62
+ pass
63
+
64
+
65
+ # Network errors
66
+
67
+
68
+ class NetworkError(Exception):
69
+ pass
70
+
71
+
72
+ class ConnectError(NetworkError):
73
+ pass
74
+
75
+
76
+ class ReadError(NetworkError):
77
+ pass
78
+
79
+
80
+ class WriteError(NetworkError):
81
+ pass
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/LICENSE ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2018, Tzu-ping Chung <uranusjr@gmail.com>
2
+
3
+ Permission to use, copy, modify, and distribute this software for any
4
+ purpose with or without fee is hereby granted, provided that the above
5
+ copyright notice and this permission notice appear in all copies.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
10
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/RECORD ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ shellingham/__init__.py,sha256=pAKXUPKUdwyErC0ZjS-5w-fRdSbmdcfvnpt_x1yWqtA,635
2
+ shellingham/_core.py,sha256=v-CTr_7F7cJAtNnzpa1N_Hl8afkY5yiDA4joGmsUBu0,300
3
+ shellingham/nt.py,sha256=m6J6SuwyqVVlxXT9Bc-9F_1x-T5u0gCFFrRAF2LIkeg,4516
4
+ shellingham/posix/__init__.py,sha256=pB69qtvZJ_yIf48nl4-ZfS3wLwwuXuknXOZhBnC2T1o,3129
5
+ shellingham/posix/_core.py,sha256=_v18UaXbzr4muNhr3-mH1FdSdjZ_dOXQrtUyomIbKYQ,81
6
+ shellingham/posix/proc.py,sha256=nSUxIuQSotvaDW76i0oTQAM9aZ9PXBLFAEktWljSKCo,2659
7
+ shellingham/posix/ps.py,sha256=NGmDKCukhNp0lahwYCaMXphBYaVbhbiR9BtE0OkT8qU,1770
8
+ shellingham-1.5.4.dist-info/LICENSE,sha256=84j9OMrRMRLB3A9mm76A5_hFQe26-3LzAw0sp2QsPJ0,751
9
+ shellingham-1.5.4.dist-info/METADATA,sha256=GD2AIgo3STJieVc53TV8xbs_Sb05DMkZjVGA5UUaB_o,3461
10
+ shellingham-1.5.4.dist-info/WHEEL,sha256=iYlv5fX357PQyRT2o6tw1bN-YcKFFHKqB_LwHO5wP-g,110
11
+ shellingham-1.5.4.dist-info/top_level.txt,sha256=uKMQL5AKxPi4O9_Rbd838QeEs4ImpGQKNbEDZYqgBgk,12
12
+ shellingham-1.5.4.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
13
+ shellingham-1.5.4.dist-info/RECORD,,
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.41.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
6
+
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ shellingham
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham-1.5.4.dist-info/zip-safe ADDED
@@ -0,0 +1 @@
 
 
1
+
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import os
3
+
4
+ from ._core import ShellDetectionFailure
5
+
6
+ __version__ = "1.5.4"
7
+
8
+
9
+ def detect_shell(pid=None, max_depth=10):
10
+ name = os.name
11
+ try:
12
+ impl = importlib.import_module(".{}".format(name), __name__)
13
+ except ImportError:
14
+ message = "Shell detection not implemented for {0!r}".format(name)
15
+ raise RuntimeError(message)
16
+ try:
17
+ get_shell = impl.get_shell
18
+ except AttributeError:
19
+ raise RuntimeError("get_shell not implemented for {0!r}".format(name))
20
+ shell = get_shell(pid, max_depth=max_depth)
21
+ if shell:
22
+ return shell
23
+ raise ShellDetectionFailure()
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/_core.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SHELL_NAMES = (
2
+ {"sh", "bash", "dash", "ash"} # Bourne.
3
+ | {"csh", "tcsh"} # C.
4
+ | {"ksh", "zsh", "fish"} # Common alternatives.
5
+ | {"cmd", "powershell", "pwsh"} # Microsoft.
6
+ | {"elvish", "xonsh", "nu"} # More exotic.
7
+ )
8
+
9
+
10
+ class ShellDetectionFailure(EnvironmentError):
11
+ pass
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/nt.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import ctypes
3
+ import os
4
+
5
+ from ctypes.wintypes import (
6
+ BOOL,
7
+ CHAR,
8
+ DWORD,
9
+ HANDLE,
10
+ LONG,
11
+ LPWSTR,
12
+ MAX_PATH,
13
+ PDWORD,
14
+ ULONG,
15
+ )
16
+
17
+ from shellingham._core import SHELL_NAMES
18
+
19
+
20
+ INVALID_HANDLE_VALUE = HANDLE(-1).value
21
+ ERROR_NO_MORE_FILES = 18
22
+ ERROR_INSUFFICIENT_BUFFER = 122
23
+ TH32CS_SNAPPROCESS = 2
24
+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
25
+
26
+
27
+ kernel32 = ctypes.windll.kernel32
28
+
29
+
30
+ def _check_handle(error_val=0):
31
+ def check(ret, func, args):
32
+ if ret == error_val:
33
+ raise ctypes.WinError()
34
+ return ret
35
+
36
+ return check
37
+
38
+
39
+ def _check_expected(expected):
40
+ def check(ret, func, args):
41
+ if ret:
42
+ return True
43
+ code = ctypes.GetLastError()
44
+ if code == expected:
45
+ return False
46
+ raise ctypes.WinError(code)
47
+
48
+ return check
49
+
50
+
51
+ class ProcessEntry32(ctypes.Structure):
52
+ _fields_ = (
53
+ ("dwSize", DWORD),
54
+ ("cntUsage", DWORD),
55
+ ("th32ProcessID", DWORD),
56
+ ("th32DefaultHeapID", ctypes.POINTER(ULONG)),
57
+ ("th32ModuleID", DWORD),
58
+ ("cntThreads", DWORD),
59
+ ("th32ParentProcessID", DWORD),
60
+ ("pcPriClassBase", LONG),
61
+ ("dwFlags", DWORD),
62
+ ("szExeFile", CHAR * MAX_PATH),
63
+ )
64
+
65
+
66
+ kernel32.CloseHandle.argtypes = [HANDLE]
67
+ kernel32.CloseHandle.restype = BOOL
68
+
69
+ kernel32.CreateToolhelp32Snapshot.argtypes = [DWORD, DWORD]
70
+ kernel32.CreateToolhelp32Snapshot.restype = HANDLE
71
+ kernel32.CreateToolhelp32Snapshot.errcheck = _check_handle( # type: ignore
72
+ INVALID_HANDLE_VALUE,
73
+ )
74
+
75
+ kernel32.Process32First.argtypes = [HANDLE, ctypes.POINTER(ProcessEntry32)]
76
+ kernel32.Process32First.restype = BOOL
77
+ kernel32.Process32First.errcheck = _check_expected( # type: ignore
78
+ ERROR_NO_MORE_FILES,
79
+ )
80
+
81
+ kernel32.Process32Next.argtypes = [HANDLE, ctypes.POINTER(ProcessEntry32)]
82
+ kernel32.Process32Next.restype = BOOL
83
+ kernel32.Process32Next.errcheck = _check_expected( # type: ignore
84
+ ERROR_NO_MORE_FILES,
85
+ )
86
+
87
+ kernel32.GetCurrentProcessId.argtypes = []
88
+ kernel32.GetCurrentProcessId.restype = DWORD
89
+
90
+ kernel32.OpenProcess.argtypes = [DWORD, BOOL, DWORD]
91
+ kernel32.OpenProcess.restype = HANDLE
92
+ kernel32.OpenProcess.errcheck = _check_handle( # type: ignore
93
+ INVALID_HANDLE_VALUE,
94
+ )
95
+
96
+ kernel32.QueryFullProcessImageNameW.argtypes = [HANDLE, DWORD, LPWSTR, PDWORD]
97
+ kernel32.QueryFullProcessImageNameW.restype = BOOL
98
+ kernel32.QueryFullProcessImageNameW.errcheck = _check_expected( # type: ignore
99
+ ERROR_INSUFFICIENT_BUFFER,
100
+ )
101
+
102
+
103
+ @contextlib.contextmanager
104
+ def _handle(f, *args, **kwargs):
105
+ handle = f(*args, **kwargs)
106
+ try:
107
+ yield handle
108
+ finally:
109
+ kernel32.CloseHandle(handle)
110
+
111
+
112
+ def _iter_processes():
113
+ f = kernel32.CreateToolhelp32Snapshot
114
+ with _handle(f, TH32CS_SNAPPROCESS, 0) as snap:
115
+ entry = ProcessEntry32()
116
+ entry.dwSize = ctypes.sizeof(entry)
117
+ ret = kernel32.Process32First(snap, entry)
118
+ while ret:
119
+ yield entry
120
+ ret = kernel32.Process32Next(snap, entry)
121
+
122
+
123
+ def _get_full_path(proch):
124
+ size = DWORD(MAX_PATH)
125
+ while True:
126
+ path_buff = ctypes.create_unicode_buffer("", size.value)
127
+ if kernel32.QueryFullProcessImageNameW(proch, 0, path_buff, size):
128
+ return path_buff.value
129
+ size.value *= 2
130
+
131
+
132
+ def get_shell(pid=None, max_depth=10):
133
+ proc_map = {
134
+ proc.th32ProcessID: (proc.th32ParentProcessID, proc.szExeFile)
135
+ for proc in _iter_processes()
136
+ }
137
+ pid = pid or os.getpid()
138
+
139
+ for _ in range(0, max_depth + 1):
140
+ try:
141
+ ppid, executable = proc_map[pid]
142
+ except KeyError: # No such process? Give up.
143
+ break
144
+
145
+ # The executable name would be encoded with the current code page if
146
+ # we're in ANSI mode (usually). Try to decode it into str/unicode,
147
+ # replacing invalid characters to be safe (not thoeratically necessary,
148
+ # I think). Note that we need to use 'mbcs' instead of encoding
149
+ # settings from sys because this is from the Windows API, not Python
150
+ # internals (which those settings reflect). (pypa/pipenv#3382)
151
+ if isinstance(executable, bytes):
152
+ executable = executable.decode("mbcs", "replace")
153
+
154
+ name = executable.rpartition(".")[0].lower()
155
+ if name not in SHELL_NAMES:
156
+ pid = ppid
157
+ continue
158
+
159
+ key = PROCESS_QUERY_LIMITED_INFORMATION
160
+ with _handle(kernel32.OpenProcess, key, 0, pid) as proch:
161
+ return (name, _get_full_path(proch))
162
+
163
+ return None
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/posix/_core.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ import collections
2
+
3
+ Process = collections.namedtuple("Process", "args pid ppid")
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/posix/proc.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import os
3
+ import re
4
+ import sys
5
+
6
+ from ._core import Process
7
+
8
+ # FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=procfs
9
+ # NetBSD: https://man.netbsd.org/NetBSD-9.3-STABLE/mount_procfs.8
10
+ # DragonFlyBSD: https://www.dragonflybsd.org/cgi/web-man?command=procfs
11
+ BSD_STAT_PPID = 2
12
+
13
+ # See https://docs.kernel.org/filesystems/proc.html
14
+ LINUX_STAT_PPID = 3
15
+
16
+ STAT_PATTERN = re.compile(r"\(.+\)|\S+")
17
+
18
+
19
+ def detect_proc():
20
+ """Detect /proc filesystem style.
21
+
22
+ This checks the /proc/{pid} directory for possible formats. Returns one of
23
+ the following as str:
24
+
25
+ * `stat`: Linux-style, i.e. ``/proc/{pid}/stat``.
26
+ * `status`: BSD-style, i.e. ``/proc/{pid}/status``.
27
+ """
28
+ pid = os.getpid()
29
+ for name in ("stat", "status"):
30
+ if os.path.exists(os.path.join("/proc", str(pid), name)):
31
+ return name
32
+ raise ProcFormatError("unsupported proc format")
33
+
34
+
35
+ def _use_bsd_stat_format():
36
+ try:
37
+ return os.uname().sysname.lower() in ("freebsd", "netbsd", "dragonfly")
38
+ except Exception:
39
+ return False
40
+
41
+
42
+ def _get_ppid(pid, name):
43
+ path = os.path.join("/proc", str(pid), name)
44
+ with io.open(path, encoding="ascii", errors="replace") as f:
45
+ parts = STAT_PATTERN.findall(f.read())
46
+ # We only care about TTY and PPID -- both are numbers.
47
+ if _use_bsd_stat_format():
48
+ return parts[BSD_STAT_PPID]
49
+ return parts[LINUX_STAT_PPID]
50
+
51
+
52
+ def _get_cmdline(pid):
53
+ path = os.path.join("/proc", str(pid), "cmdline")
54
+ encoding = sys.getfilesystemencoding() or "utf-8"
55
+ with io.open(path, encoding=encoding, errors="replace") as f:
56
+ # XXX: Command line arguments can be arbitrary byte sequences, not
57
+ # necessarily decodable. For Shellingham's purpose, however, we don't
58
+ # care. (pypa/pipenv#2820)
59
+ # cmdline appends an extra NULL at the end, hence the [:-1].
60
+ return tuple(f.read().split("\0")[:-1])
61
+
62
+
63
+ class ProcFormatError(EnvironmentError):
64
+ pass
65
+
66
+
67
+ def iter_process_parents(pid, max_depth=10):
68
+ """Try to look up the process tree via the /proc interface."""
69
+ stat_name = detect_proc()
70
+
71
+ # Inner generator function so we correctly throw an error eagerly if proc
72
+ # is not supported, rather than on the first call to the iterator. This
73
+ # allows the call site detects the correct implementation.
74
+ def _iter_process_parents(pid, max_depth):
75
+ for _ in range(max_depth):
76
+ ppid = _get_ppid(pid, stat_name)
77
+ args = _get_cmdline(pid)
78
+ yield Process(args=args, pid=pid, ppid=ppid)
79
+ if ppid == "0":
80
+ break
81
+ pid = ppid
82
+
83
+ return _iter_process_parents(pid, max_depth)
.cache/uv/archive-v0/_cd0yf9FPcanqQcbDtZSW/shellingham/posix/ps.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import errno
2
+ import subprocess
3
+ import sys
4
+
5
+ from ._core import Process
6
+
7
+
8
+ class PsNotAvailable(EnvironmentError):
9
+ pass
10
+
11
+
12
+ def iter_process_parents(pid, max_depth=10):
13
+ """Try to look up the process tree via the output of `ps`."""
14
+ try:
15
+ cmd = ["ps", "-ww", "-o", "pid=", "-o", "ppid=", "-o", "args="]
16
+ output = subprocess.check_output(cmd)
17
+ except OSError as e: # Python 2-compatible FileNotFoundError.
18
+ if e.errno != errno.ENOENT:
19
+ raise
20
+ raise PsNotAvailable("ps not found")
21
+ except subprocess.CalledProcessError as e:
22
+ # `ps` can return 1 if the process list is completely empty.
23
+ # (sarugaku/shellingham#15)
24
+ if not e.output.strip():
25
+ return
26
+ raise
27
+ if not isinstance(output, str):
28
+ encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
29
+ output = output.decode(encoding)
30
+
31
+ processes_mapping = {}
32
+ for line in output.split("\n"):
33
+ try:
34
+ _pid, ppid, args = line.strip().split(None, 2)
35
+ # XXX: This is not right, but we are really out of options.
36
+ # ps does not offer a sane way to decode the argument display,
37
+ # and this is "Good Enough" for obtaining shell names. Hopefully
38
+ # people don't name their shell with a space, or have something
39
+ # like "/usr/bin/xonsh is uber". (sarugaku/shellingham#14)
40
+ args = tuple(a.strip() for a in args.split(" "))
41
+ except ValueError:
42
+ continue
43
+ processes_mapping[_pid] = Process(args=args, pid=_pid, ppid=ppid)
44
+
45
+ for _ in range(max_depth):
46
+ try:
47
+ process = processes_mapping[pid]
48
+ except KeyError:
49
+ return
50
+ yield process
51
+ pid = process.ppid
.cache/uv/archive-v0/mZts5W47V4a3dXgJR251L/idna/uts46data.py ADDED
The diff for this file is too large to render. See raw diff
 
.cache/uv/simple-v18/pypi/certifi.rkyv ADDED
Binary file (73.7 kB). View file
 
.cache/uv/simple-v18/pypi/h11.rkyv ADDED
Binary file (14.2 kB). View file
 
.cache/uv/simple-v18/pypi/httpcore.rkyv ADDED
Binary file (63.3 kB). View file
 
.cache/uv/simple-v18/pypi/markdown-it-py.rkyv ADDED
Binary file (50 kB). View file
 
.cache/uv/simple-v18/pypi/mdurl.rkyv ADDED
Binary file (4.68 kB). View file