Upload folder using huggingface_hub (part 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +5 -0
- .venv/lib/python3.11/site-packages/dateutil/tz/__pycache__/_common.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/dateutil/tz/__pycache__/_factories.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/dateutil/tz/__pycache__/tz.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/dateutil/tz/__pycache__/win.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/dateutil/tz/_common.py +419 -0
- .venv/lib/python3.11/site-packages/dateutil/tz/_factories.py +80 -0
- .venv/lib/python3.11/site-packages/dateutil/tz/tz.py +1849 -0
- .venv/lib/python3.11/site-packages/dateutil/tz/win.py +370 -0
- .venv/lib/python3.11/site-packages/dateutil/tzwin.py +2 -0
- .venv/lib/python3.11/site-packages/dateutil/utils.py +71 -0
- .venv/lib/python3.11/site-packages/dateutil/zoneinfo/__init__.py +167 -0
- .venv/lib/python3.11/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz +3 -0
- .venv/lib/python3.11/site-packages/dateutil/zoneinfo/rebuild.py +75 -0
- .venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/AUTHORS.md +14 -0
- .venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/INSTALLER +1 -0
- .venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/LICENSE.txt +20 -0
- .venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/METADATA +165 -0
- .venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/RECORD +16 -0
- .venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/REQUESTED +0 -0
- .venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/WHEEL +5 -0
- .venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/top_level.txt +1 -0
- .venv/lib/python3.11/site-packages/donfig/__init__.py +4 -0
- .venv/lib/python3.11/site-packages/donfig/__pycache__/__init__.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/donfig/__pycache__/_lock.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/donfig/__pycache__/config_obj.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/donfig/__pycache__/version.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/donfig/_lock.py +98 -0
- .venv/lib/python3.11/site-packages/donfig/config_obj.py +794 -0
- .venv/lib/python3.11/site-packages/donfig/tests/__init__.py +0 -0
- .venv/lib/python3.11/site-packages/donfig/tests/test_config.py +649 -0
- .venv/lib/python3.11/site-packages/donfig/tests/test_lock.py +87 -0
- .venv/lib/python3.11/site-packages/donfig/utils.py +44 -0
- .venv/lib/python3.11/site-packages/donfig/version.py +21 -0
- .venv/lib/python3.11/site-packages/filelock-3.29.6.dist-info/INSTALLER +1 -0
- .venv/lib/python3.11/site-packages/filelock-3.29.6.dist-info/METADATA +38 -0
- .venv/lib/python3.11/site-packages/filelock-3.29.6.dist-info/RECORD +21 -0
- .venv/lib/python3.11/site-packages/filelock-3.29.6.dist-info/REQUESTED +0 -0
- .venv/lib/python3.11/site-packages/filelock-3.29.6.dist-info/WHEEL +4 -0
- .venv/lib/python3.11/site-packages/filelock-3.29.6.dist-info/licenses/LICENSE +21 -0
- .venv/lib/python3.11/site-packages/filelock/__init__.py +93 -0
- .venv/lib/python3.11/site-packages/filelock/__pycache__/__init__.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/filelock/__pycache__/_api.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/filelock/__pycache__/_async_read_write.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/filelock/__pycache__/_error.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/filelock/__pycache__/_read_write.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/filelock/__pycache__/_soft.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/filelock/__pycache__/_unix.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/filelock/__pycache__/_util.cpython-311.pyc +0 -0
- .venv/lib/python3.11/site-packages/filelock/__pycache__/_windows.cpython-311.pyc +0 -0
.gitattributes
CHANGED
|
@@ -42,3 +42,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 42 |
.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/merge.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 43 |
.venv/lib/python3.11/site-packages/click/__pycache__/core.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 44 |
.venv/lib/python3.11/site-packages/contourpy/_contourpy.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
.venv/lib/python3.11/site-packages/anndata/_core/__pycache__/merge.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 43 |
.venv/lib/python3.11/site-packages/click/__pycache__/core.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 44 |
.venv/lib/python3.11/site-packages/contourpy/_contourpy.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
.venv/lib/python3.11/site-packages/fontTools/cu2qu/cu2qu.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
.venv/lib/python3.11/site-packages/fontTools/feaLib/lexer.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
.venv/lib/python3.11/site-packages/fontTools/misc/bezierTools.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
.venv/lib/python3.11/site-packages/fontTools/pens/momentsPen.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
.venv/lib/python3.11/site-packages/fontTools/qu2cu/qu2cu.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
.venv/lib/python3.11/site-packages/dateutil/tz/__pycache__/_common.cpython-311.pyc
ADDED
|
Binary file (15.3 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/dateutil/tz/__pycache__/_factories.cpython-311.pyc
ADDED
|
Binary file (5.23 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/dateutil/tz/__pycache__/tz.cpython-311.pyc
ADDED
|
Binary file (70.5 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/dateutil/tz/__pycache__/win.cpython-311.pyc
ADDED
|
Binary file (18.4 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/dateutil/tz/_common.py
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def tzname_in_python2(namefunc):
|
| 14 |
+
"""Change unicode output into bytestrings in Python 2
|
| 15 |
+
|
| 16 |
+
tzname() API changed in Python 3. It used to return bytes, but was changed
|
| 17 |
+
to unicode strings
|
| 18 |
+
"""
|
| 19 |
+
if PY2:
|
| 20 |
+
@wraps(namefunc)
|
| 21 |
+
def adjust_encoding(*args, **kwargs):
|
| 22 |
+
name = namefunc(*args, **kwargs)
|
| 23 |
+
if name is not None:
|
| 24 |
+
name = name.encode()
|
| 25 |
+
|
| 26 |
+
return name
|
| 27 |
+
|
| 28 |
+
return adjust_encoding
|
| 29 |
+
else:
|
| 30 |
+
return namefunc
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# The following is adapted from Alexander Belopolsky's tz library
|
| 34 |
+
# https://github.com/abalkin/tz
|
| 35 |
+
if hasattr(datetime, 'fold'):
|
| 36 |
+
# This is the pre-python 3.6 fold situation
|
| 37 |
+
def enfold(dt, fold=1):
|
| 38 |
+
"""
|
| 39 |
+
Provides a unified interface for assigning the ``fold`` attribute to
|
| 40 |
+
datetimes both before and after the implementation of PEP-495.
|
| 41 |
+
|
| 42 |
+
:param fold:
|
| 43 |
+
The value for the ``fold`` attribute in the returned datetime. This
|
| 44 |
+
should be either 0 or 1.
|
| 45 |
+
|
| 46 |
+
:return:
|
| 47 |
+
Returns an object for which ``getattr(dt, 'fold', 0)`` returns
|
| 48 |
+
``fold`` for all versions of Python. In versions prior to
|
| 49 |
+
Python 3.6, this is a ``_DatetimeWithFold`` object, which is a
|
| 50 |
+
subclass of :py:class:`datetime.datetime` with the ``fold``
|
| 51 |
+
attribute added, if ``fold`` is 1.
|
| 52 |
+
|
| 53 |
+
.. versionadded:: 2.6.0
|
| 54 |
+
"""
|
| 55 |
+
return dt.replace(fold=fold)
|
| 56 |
+
|
| 57 |
+
else:
|
| 58 |
+
class _DatetimeWithFold(datetime):
|
| 59 |
+
"""
|
| 60 |
+
This is a class designed to provide a PEP 495-compliant interface for
|
| 61 |
+
Python versions before 3.6. It is used only for dates in a fold, so
|
| 62 |
+
the ``fold`` attribute is fixed at ``1``.
|
| 63 |
+
|
| 64 |
+
.. versionadded:: 2.6.0
|
| 65 |
+
"""
|
| 66 |
+
__slots__ = ()
|
| 67 |
+
|
| 68 |
+
def replace(self, *args, **kwargs):
|
| 69 |
+
"""
|
| 70 |
+
Return a datetime with the same attributes, except for those
|
| 71 |
+
attributes given new values by whichever keyword arguments are
|
| 72 |
+
specified. Note that tzinfo=None can be specified to create a naive
|
| 73 |
+
datetime from an aware datetime with no conversion of date and time
|
| 74 |
+
data.
|
| 75 |
+
|
| 76 |
+
This is reimplemented in ``_DatetimeWithFold`` because pypy3 will
|
| 77 |
+
return a ``datetime.datetime`` even if ``fold`` is unchanged.
|
| 78 |
+
"""
|
| 79 |
+
argnames = (
|
| 80 |
+
'year', 'month', 'day', 'hour', 'minute', 'second',
|
| 81 |
+
'microsecond', 'tzinfo'
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
for arg, argname in zip(args, argnames):
|
| 85 |
+
if argname in kwargs:
|
| 86 |
+
raise TypeError('Duplicate argument: {}'.format(argname))
|
| 87 |
+
|
| 88 |
+
kwargs[argname] = arg
|
| 89 |
+
|
| 90 |
+
for argname in argnames:
|
| 91 |
+
if argname not in kwargs:
|
| 92 |
+
kwargs[argname] = getattr(self, argname)
|
| 93 |
+
|
| 94 |
+
dt_class = self.__class__ if kwargs.get('fold', 1) else datetime
|
| 95 |
+
|
| 96 |
+
return dt_class(**kwargs)
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def fold(self):
|
| 100 |
+
return 1
|
| 101 |
+
|
| 102 |
+
def enfold(dt, fold=1):
|
| 103 |
+
"""
|
| 104 |
+
Provides a unified interface for assigning the ``fold`` attribute to
|
| 105 |
+
datetimes both before and after the implementation of PEP-495.
|
| 106 |
+
|
| 107 |
+
:param fold:
|
| 108 |
+
The value for the ``fold`` attribute in the returned datetime. This
|
| 109 |
+
should be either 0 or 1.
|
| 110 |
+
|
| 111 |
+
:return:
|
| 112 |
+
Returns an object for which ``getattr(dt, 'fold', 0)`` returns
|
| 113 |
+
``fold`` for all versions of Python. In versions prior to
|
| 114 |
+
Python 3.6, this is a ``_DatetimeWithFold`` object, which is a
|
| 115 |
+
subclass of :py:class:`datetime.datetime` with the ``fold``
|
| 116 |
+
attribute added, if ``fold`` is 1.
|
| 117 |
+
|
| 118 |
+
.. versionadded:: 2.6.0
|
| 119 |
+
"""
|
| 120 |
+
if getattr(dt, 'fold', 0) == fold:
|
| 121 |
+
return dt
|
| 122 |
+
|
| 123 |
+
args = dt.timetuple()[:6]
|
| 124 |
+
args += (dt.microsecond, dt.tzinfo)
|
| 125 |
+
|
| 126 |
+
if fold:
|
| 127 |
+
return _DatetimeWithFold(*args)
|
| 128 |
+
else:
|
| 129 |
+
return datetime(*args)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _validate_fromutc_inputs(f):
|
| 133 |
+
"""
|
| 134 |
+
The CPython version of ``fromutc`` checks that the input is a ``datetime``
|
| 135 |
+
object and that ``self`` is attached as its ``tzinfo``.
|
| 136 |
+
"""
|
| 137 |
+
@wraps(f)
|
| 138 |
+
def fromutc(self, dt):
|
| 139 |
+
if not isinstance(dt, datetime):
|
| 140 |
+
raise TypeError("fromutc() requires a datetime argument")
|
| 141 |
+
if dt.tzinfo is not self:
|
| 142 |
+
raise ValueError("dt.tzinfo is not self")
|
| 143 |
+
|
| 144 |
+
return f(self, dt)
|
| 145 |
+
|
| 146 |
+
return fromutc
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class _tzinfo(tzinfo):
|
| 150 |
+
"""
|
| 151 |
+
Base class for all ``dateutil`` ``tzinfo`` objects.
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
def is_ambiguous(self, dt):
|
| 155 |
+
"""
|
| 156 |
+
Whether or not the "wall time" of a given datetime is ambiguous in this
|
| 157 |
+
zone.
|
| 158 |
+
|
| 159 |
+
:param dt:
|
| 160 |
+
A :py:class:`datetime.datetime`, naive or time zone aware.
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
:return:
|
| 164 |
+
Returns ``True`` if ambiguous, ``False`` otherwise.
|
| 165 |
+
|
| 166 |
+
.. versionadded:: 2.6.0
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
dt = dt.replace(tzinfo=self)
|
| 170 |
+
|
| 171 |
+
wall_0 = enfold(dt, fold=0)
|
| 172 |
+
wall_1 = enfold(dt, fold=1)
|
| 173 |
+
|
| 174 |
+
same_offset = wall_0.utcoffset() == wall_1.utcoffset()
|
| 175 |
+
same_dt = wall_0.replace(tzinfo=None) == wall_1.replace(tzinfo=None)
|
| 176 |
+
|
| 177 |
+
return same_dt and not same_offset
|
| 178 |
+
|
| 179 |
+
def _fold_status(self, dt_utc, dt_wall):
|
| 180 |
+
"""
|
| 181 |
+
Determine the fold status of a "wall" datetime, given a representation
|
| 182 |
+
of the same datetime as a (naive) UTC datetime. This is calculated based
|
| 183 |
+
on the assumption that ``dt.utcoffset() - dt.dst()`` is constant for all
|
| 184 |
+
datetimes, and that this offset is the actual number of hours separating
|
| 185 |
+
``dt_utc`` and ``dt_wall``.
|
| 186 |
+
|
| 187 |
+
:param dt_utc:
|
| 188 |
+
Representation of the datetime as UTC
|
| 189 |
+
|
| 190 |
+
:param dt_wall:
|
| 191 |
+
Representation of the datetime as "wall time". This parameter must
|
| 192 |
+
either have a `fold` attribute or have a fold-naive
|
| 193 |
+
:class:`datetime.tzinfo` attached, otherwise the calculation may
|
| 194 |
+
fail.
|
| 195 |
+
"""
|
| 196 |
+
if self.is_ambiguous(dt_wall):
|
| 197 |
+
delta_wall = dt_wall - dt_utc
|
| 198 |
+
_fold = int(delta_wall == (dt_utc.utcoffset() - dt_utc.dst()))
|
| 199 |
+
else:
|
| 200 |
+
_fold = 0
|
| 201 |
+
|
| 202 |
+
return _fold
|
| 203 |
+
|
| 204 |
+
def _fold(self, dt):
|
| 205 |
+
return getattr(dt, 'fold', 0)
|
| 206 |
+
|
| 207 |
+
def _fromutc(self, dt):
|
| 208 |
+
"""
|
| 209 |
+
Given a timezone-aware datetime in a given timezone, calculates a
|
| 210 |
+
timezone-aware datetime in a new timezone.
|
| 211 |
+
|
| 212 |
+
Since this is the one time that we *know* we have an unambiguous
|
| 213 |
+
datetime object, we take this opportunity to determine whether the
|
| 214 |
+
datetime is ambiguous and in a "fold" state (e.g. if it's the first
|
| 215 |
+
occurrence, chronologically, of the ambiguous datetime).
|
| 216 |
+
|
| 217 |
+
:param dt:
|
| 218 |
+
A timezone-aware :class:`datetime.datetime` object.
|
| 219 |
+
"""
|
| 220 |
+
|
| 221 |
+
# Re-implement the algorithm from Python's datetime.py
|
| 222 |
+
dtoff = dt.utcoffset()
|
| 223 |
+
if dtoff is None:
|
| 224 |
+
raise ValueError("fromutc() requires a non-None utcoffset() "
|
| 225 |
+
"result")
|
| 226 |
+
|
| 227 |
+
# The original datetime.py code assumes that `dst()` defaults to
|
| 228 |
+
# zero during ambiguous times. PEP 495 inverts this presumption, so
|
| 229 |
+
# for pre-PEP 495 versions of python, we need to tweak the algorithm.
|
| 230 |
+
dtdst = dt.dst()
|
| 231 |
+
if dtdst is None:
|
| 232 |
+
raise ValueError("fromutc() requires a non-None dst() result")
|
| 233 |
+
delta = dtoff - dtdst
|
| 234 |
+
|
| 235 |
+
dt += delta
|
| 236 |
+
# Set fold=1 so we can default to being in the fold for
|
| 237 |
+
# ambiguous dates.
|
| 238 |
+
dtdst = enfold(dt, fold=1).dst()
|
| 239 |
+
if dtdst is None:
|
| 240 |
+
raise ValueError("fromutc(): dt.dst gave inconsistent "
|
| 241 |
+
"results; cannot convert")
|
| 242 |
+
return dt + dtdst
|
| 243 |
+
|
| 244 |
+
@_validate_fromutc_inputs
|
| 245 |
+
def fromutc(self, dt):
|
| 246 |
+
"""
|
| 247 |
+
Given a timezone-aware datetime in a given timezone, calculates a
|
| 248 |
+
timezone-aware datetime in a new timezone.
|
| 249 |
+
|
| 250 |
+
Since this is the one time that we *know* we have an unambiguous
|
| 251 |
+
datetime object, we take this opportunity to determine whether the
|
| 252 |
+
datetime is ambiguous and in a "fold" state (e.g. if it's the first
|
| 253 |
+
occurrence, chronologically, of the ambiguous datetime).
|
| 254 |
+
|
| 255 |
+
:param dt:
|
| 256 |
+
A timezone-aware :class:`datetime.datetime` object.
|
| 257 |
+
"""
|
| 258 |
+
dt_wall = self._fromutc(dt)
|
| 259 |
+
|
| 260 |
+
# Calculate the fold status given the two datetimes.
|
| 261 |
+
_fold = self._fold_status(dt, dt_wall)
|
| 262 |
+
|
| 263 |
+
# Set the default fold value for ambiguous dates
|
| 264 |
+
return enfold(dt_wall, fold=_fold)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class tzrangebase(_tzinfo):
|
| 268 |
+
"""
|
| 269 |
+
This is an abstract base class for time zones represented by an annual
|
| 270 |
+
transition into and out of DST. Child classes should implement the following
|
| 271 |
+
methods:
|
| 272 |
+
|
| 273 |
+
* ``__init__(self, *args, **kwargs)``
|
| 274 |
+
* ``transitions(self, year)`` - this is expected to return a tuple of
|
| 275 |
+
datetimes representing the DST on and off transitions in standard
|
| 276 |
+
time.
|
| 277 |
+
|
| 278 |
+
A fully initialized ``tzrangebase`` subclass should also provide the
|
| 279 |
+
following attributes:
|
| 280 |
+
* ``hasdst``: Boolean whether or not the zone uses DST.
|
| 281 |
+
* ``_dst_offset`` / ``_std_offset``: :class:`datetime.timedelta` objects
|
| 282 |
+
representing the respective UTC offsets.
|
| 283 |
+
* ``_dst_abbr`` / ``_std_abbr``: Strings representing the timezone short
|
| 284 |
+
abbreviations in DST and STD, respectively.
|
| 285 |
+
* ``_hasdst``: Whether or not the zone has DST.
|
| 286 |
+
|
| 287 |
+
.. versionadded:: 2.6.0
|
| 288 |
+
"""
|
| 289 |
+
def __init__(self):
|
| 290 |
+
raise NotImplementedError('tzrangebase is an abstract base class')
|
| 291 |
+
|
| 292 |
+
def utcoffset(self, dt):
|
| 293 |
+
isdst = self._isdst(dt)
|
| 294 |
+
|
| 295 |
+
if isdst is None:
|
| 296 |
+
return None
|
| 297 |
+
elif isdst:
|
| 298 |
+
return self._dst_offset
|
| 299 |
+
else:
|
| 300 |
+
return self._std_offset
|
| 301 |
+
|
| 302 |
+
def dst(self, dt):
|
| 303 |
+
isdst = self._isdst(dt)
|
| 304 |
+
|
| 305 |
+
if isdst is None:
|
| 306 |
+
return None
|
| 307 |
+
elif isdst:
|
| 308 |
+
return self._dst_base_offset
|
| 309 |
+
else:
|
| 310 |
+
return ZERO
|
| 311 |
+
|
| 312 |
+
@tzname_in_python2
|
| 313 |
+
def tzname(self, dt):
|
| 314 |
+
if self._isdst(dt):
|
| 315 |
+
return self._dst_abbr
|
| 316 |
+
else:
|
| 317 |
+
return self._std_abbr
|
| 318 |
+
|
| 319 |
+
def fromutc(self, dt):
|
| 320 |
+
""" Given a datetime in UTC, return local time """
|
| 321 |
+
if not isinstance(dt, datetime):
|
| 322 |
+
raise TypeError("fromutc() requires a datetime argument")
|
| 323 |
+
|
| 324 |
+
if dt.tzinfo is not self:
|
| 325 |
+
raise ValueError("dt.tzinfo is not self")
|
| 326 |
+
|
| 327 |
+
# Get transitions - if there are none, fixed offset
|
| 328 |
+
transitions = self.transitions(dt.year)
|
| 329 |
+
if transitions is None:
|
| 330 |
+
return dt + self.utcoffset(dt)
|
| 331 |
+
|
| 332 |
+
# Get the transition times in UTC
|
| 333 |
+
dston, dstoff = transitions
|
| 334 |
+
|
| 335 |
+
dston -= self._std_offset
|
| 336 |
+
dstoff -= self._std_offset
|
| 337 |
+
|
| 338 |
+
utc_transitions = (dston, dstoff)
|
| 339 |
+
dt_utc = dt.replace(tzinfo=None)
|
| 340 |
+
|
| 341 |
+
isdst = self._naive_isdst(dt_utc, utc_transitions)
|
| 342 |
+
|
| 343 |
+
if isdst:
|
| 344 |
+
dt_wall = dt + self._dst_offset
|
| 345 |
+
else:
|
| 346 |
+
dt_wall = dt + self._std_offset
|
| 347 |
+
|
| 348 |
+
_fold = int(not isdst and self.is_ambiguous(dt_wall))
|
| 349 |
+
|
| 350 |
+
return enfold(dt_wall, fold=_fold)
|
| 351 |
+
|
| 352 |
+
def is_ambiguous(self, dt):
|
| 353 |
+
"""
|
| 354 |
+
Whether or not the "wall time" of a given datetime is ambiguous in this
|
| 355 |
+
zone.
|
| 356 |
+
|
| 357 |
+
:param dt:
|
| 358 |
+
A :py:class:`datetime.datetime`, naive or time zone aware.
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
:return:
|
| 362 |
+
Returns ``True`` if ambiguous, ``False`` otherwise.
|
| 363 |
+
|
| 364 |
+
.. versionadded:: 2.6.0
|
| 365 |
+
"""
|
| 366 |
+
if not self.hasdst:
|
| 367 |
+
return False
|
| 368 |
+
|
| 369 |
+
start, end = self.transitions(dt.year)
|
| 370 |
+
|
| 371 |
+
dt = dt.replace(tzinfo=None)
|
| 372 |
+
return (end <= dt < end + self._dst_base_offset)
|
| 373 |
+
|
| 374 |
+
def _isdst(self, dt):
|
| 375 |
+
if not self.hasdst:
|
| 376 |
+
return False
|
| 377 |
+
elif dt is None:
|
| 378 |
+
return None
|
| 379 |
+
|
| 380 |
+
transitions = self.transitions(dt.year)
|
| 381 |
+
|
| 382 |
+
if transitions is None:
|
| 383 |
+
return False
|
| 384 |
+
|
| 385 |
+
dt = dt.replace(tzinfo=None)
|
| 386 |
+
|
| 387 |
+
isdst = self._naive_isdst(dt, transitions)
|
| 388 |
+
|
| 389 |
+
# Handle ambiguous dates
|
| 390 |
+
if not isdst and self.is_ambiguous(dt):
|
| 391 |
+
return not self._fold(dt)
|
| 392 |
+
else:
|
| 393 |
+
return isdst
|
| 394 |
+
|
| 395 |
+
def _naive_isdst(self, dt, transitions):
|
| 396 |
+
dston, dstoff = transitions
|
| 397 |
+
|
| 398 |
+
dt = dt.replace(tzinfo=None)
|
| 399 |
+
|
| 400 |
+
if dston < dstoff:
|
| 401 |
+
isdst = dston <= dt < dstoff
|
| 402 |
+
else:
|
| 403 |
+
isdst = not dstoff <= dt < dston
|
| 404 |
+
|
| 405 |
+
return isdst
|
| 406 |
+
|
| 407 |
+
@property
|
| 408 |
+
def _dst_base_offset(self):
|
| 409 |
+
return self._dst_offset - self._std_offset
|
| 410 |
+
|
| 411 |
+
__hash__ = None
|
| 412 |
+
|
| 413 |
+
def __ne__(self, other):
|
| 414 |
+
return not (self == other)
|
| 415 |
+
|
| 416 |
+
def __repr__(self):
|
| 417 |
+
return "%s(...)" % self.__class__.__name__
|
| 418 |
+
|
| 419 |
+
__reduce__ = object.__reduce__
|
.venv/lib/python3.11/site-packages/dateutil/tz/_factories.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import timedelta
|
| 2 |
+
import weakref
|
| 3 |
+
from collections import OrderedDict
|
| 4 |
+
|
| 5 |
+
from six.moves import _thread
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class _TzSingleton(type):
|
| 9 |
+
def __init__(cls, *args, **kwargs):
|
| 10 |
+
cls.__instance = None
|
| 11 |
+
super(_TzSingleton, cls).__init__(*args, **kwargs)
|
| 12 |
+
|
| 13 |
+
def __call__(cls):
|
| 14 |
+
if cls.__instance is None:
|
| 15 |
+
cls.__instance = super(_TzSingleton, cls).__call__()
|
| 16 |
+
return cls.__instance
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class _TzFactory(type):
|
| 20 |
+
def instance(cls, *args, **kwargs):
|
| 21 |
+
"""Alternate constructor that returns a fresh instance"""
|
| 22 |
+
return type.__call__(cls, *args, **kwargs)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class _TzOffsetFactory(_TzFactory):
|
| 26 |
+
def __init__(cls, *args, **kwargs):
|
| 27 |
+
cls.__instances = weakref.WeakValueDictionary()
|
| 28 |
+
cls.__strong_cache = OrderedDict()
|
| 29 |
+
cls.__strong_cache_size = 8
|
| 30 |
+
|
| 31 |
+
cls._cache_lock = _thread.allocate_lock()
|
| 32 |
+
|
| 33 |
+
def __call__(cls, name, offset):
|
| 34 |
+
if isinstance(offset, timedelta):
|
| 35 |
+
key = (name, offset.total_seconds())
|
| 36 |
+
else:
|
| 37 |
+
key = (name, offset)
|
| 38 |
+
|
| 39 |
+
instance = cls.__instances.get(key, None)
|
| 40 |
+
if instance is None:
|
| 41 |
+
instance = cls.__instances.setdefault(key,
|
| 42 |
+
cls.instance(name, offset))
|
| 43 |
+
|
| 44 |
+
# This lock may not be necessary in Python 3. See GH issue #901
|
| 45 |
+
with cls._cache_lock:
|
| 46 |
+
cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance)
|
| 47 |
+
|
| 48 |
+
# Remove an item if the strong cache is overpopulated
|
| 49 |
+
if len(cls.__strong_cache) > cls.__strong_cache_size:
|
| 50 |
+
cls.__strong_cache.popitem(last=False)
|
| 51 |
+
|
| 52 |
+
return instance
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class _TzStrFactory(_TzFactory):
|
| 56 |
+
def __init__(cls, *args, **kwargs):
|
| 57 |
+
cls.__instances = weakref.WeakValueDictionary()
|
| 58 |
+
cls.__strong_cache = OrderedDict()
|
| 59 |
+
cls.__strong_cache_size = 8
|
| 60 |
+
|
| 61 |
+
cls.__cache_lock = _thread.allocate_lock()
|
| 62 |
+
|
| 63 |
+
def __call__(cls, s, posix_offset=False):
|
| 64 |
+
key = (s, posix_offset)
|
| 65 |
+
instance = cls.__instances.get(key, None)
|
| 66 |
+
|
| 67 |
+
if instance is None:
|
| 68 |
+
instance = cls.__instances.setdefault(key,
|
| 69 |
+
cls.instance(s, posix_offset))
|
| 70 |
+
|
| 71 |
+
# This lock may not be necessary in Python 3. See GH issue #901
|
| 72 |
+
with cls.__cache_lock:
|
| 73 |
+
cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance)
|
| 74 |
+
|
| 75 |
+
# Remove an item if the strong cache is overpopulated
|
| 76 |
+
if len(cls.__strong_cache) > cls.__strong_cache_size:
|
| 77 |
+
cls.__strong_cache.popitem(last=False)
|
| 78 |
+
|
| 79 |
+
return instance
|
| 80 |
+
|
.venv/lib/python3.11/site-packages/dateutil/tz/tz.py
ADDED
|
@@ -0,0 +1,1849 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
This module offers timezone implementations subclassing the abstract
|
| 4 |
+
:py:class:`datetime.tzinfo` type. There are classes to handle tzfile format
|
| 5 |
+
files (usually are in :file:`/etc/localtime`, :file:`/usr/share/zoneinfo`,
|
| 6 |
+
etc), TZ environment string (in all known formats), given ranges (with help
|
| 7 |
+
from relative deltas), local machine timezone, fixed offset timezone, and UTC
|
| 8 |
+
timezone.
|
| 9 |
+
"""
|
| 10 |
+
import datetime
|
| 11 |
+
import struct
|
| 12 |
+
import time
|
| 13 |
+
import sys
|
| 14 |
+
import os
|
| 15 |
+
import bisect
|
| 16 |
+
import weakref
|
| 17 |
+
from collections import OrderedDict
|
| 18 |
+
|
| 19 |
+
import six
|
| 20 |
+
from six import string_types
|
| 21 |
+
from six.moves import _thread
|
| 22 |
+
from ._common import tzname_in_python2, _tzinfo
|
| 23 |
+
from ._common import tzrangebase, enfold
|
| 24 |
+
from ._common import _validate_fromutc_inputs
|
| 25 |
+
|
| 26 |
+
from ._factories import _TzSingleton, _TzOffsetFactory
|
| 27 |
+
from ._factories import _TzStrFactory
|
| 28 |
+
try:
|
| 29 |
+
from .win import tzwin, tzwinlocal
|
| 30 |
+
except ImportError:
|
| 31 |
+
tzwin = tzwinlocal = None
|
| 32 |
+
|
| 33 |
+
# For warning about rounding tzinfo
|
| 34 |
+
from warnings import warn
|
| 35 |
+
|
| 36 |
+
ZERO = datetime.timedelta(0)
|
| 37 |
+
EPOCH = datetime.datetime(1970, 1, 1, 0, 0)
|
| 38 |
+
EPOCHORDINAL = EPOCH.toordinal()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@six.add_metaclass(_TzSingleton)
|
| 42 |
+
class tzutc(datetime.tzinfo):
|
| 43 |
+
"""
|
| 44 |
+
This is a tzinfo object that represents the UTC time zone.
|
| 45 |
+
|
| 46 |
+
**Examples:**
|
| 47 |
+
|
| 48 |
+
.. doctest::
|
| 49 |
+
|
| 50 |
+
>>> from datetime import *
|
| 51 |
+
>>> from dateutil.tz import *
|
| 52 |
+
|
| 53 |
+
>>> datetime.now()
|
| 54 |
+
datetime.datetime(2003, 9, 27, 9, 40, 1, 521290)
|
| 55 |
+
|
| 56 |
+
>>> datetime.now(tzutc())
|
| 57 |
+
datetime.datetime(2003, 9, 27, 12, 40, 12, 156379, tzinfo=tzutc())
|
| 58 |
+
|
| 59 |
+
>>> datetime.now(tzutc()).tzname()
|
| 60 |
+
'UTC'
|
| 61 |
+
|
| 62 |
+
.. versionchanged:: 2.7.0
|
| 63 |
+
``tzutc()`` is now a singleton, so the result of ``tzutc()`` will
|
| 64 |
+
always return the same object.
|
| 65 |
+
|
| 66 |
+
.. doctest::
|
| 67 |
+
|
| 68 |
+
>>> from dateutil.tz import tzutc, UTC
|
| 69 |
+
>>> tzutc() is tzutc()
|
| 70 |
+
True
|
| 71 |
+
>>> tzutc() is UTC
|
| 72 |
+
True
|
| 73 |
+
"""
|
| 74 |
+
def utcoffset(self, dt):
|
| 75 |
+
return ZERO
|
| 76 |
+
|
| 77 |
+
def dst(self, dt):
|
| 78 |
+
return ZERO
|
| 79 |
+
|
| 80 |
+
@tzname_in_python2
|
| 81 |
+
def tzname(self, dt):
|
| 82 |
+
return "UTC"
|
| 83 |
+
|
| 84 |
+
def is_ambiguous(self, dt):
|
| 85 |
+
"""
|
| 86 |
+
Whether or not the "wall time" of a given datetime is ambiguous in this
|
| 87 |
+
zone.
|
| 88 |
+
|
| 89 |
+
:param dt:
|
| 90 |
+
A :py:class:`datetime.datetime`, naive or time zone aware.
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
:return:
|
| 94 |
+
Returns ``True`` if ambiguous, ``False`` otherwise.
|
| 95 |
+
|
| 96 |
+
.. versionadded:: 2.6.0
|
| 97 |
+
"""
|
| 98 |
+
return False
|
| 99 |
+
|
| 100 |
+
@_validate_fromutc_inputs
|
| 101 |
+
def fromutc(self, dt):
|
| 102 |
+
"""
|
| 103 |
+
Fast track version of fromutc() returns the original ``dt`` object for
|
| 104 |
+
any valid :py:class:`datetime.datetime` object.
|
| 105 |
+
"""
|
| 106 |
+
return dt
|
| 107 |
+
|
| 108 |
+
def __eq__(self, other):
|
| 109 |
+
if not isinstance(other, (tzutc, tzoffset)):
|
| 110 |
+
return NotImplemented
|
| 111 |
+
|
| 112 |
+
return (isinstance(other, tzutc) or
|
| 113 |
+
(isinstance(other, tzoffset) and other._offset == ZERO))
|
| 114 |
+
|
| 115 |
+
__hash__ = None
|
| 116 |
+
|
| 117 |
+
def __ne__(self, other):
|
| 118 |
+
return not (self == other)
|
| 119 |
+
|
| 120 |
+
def __repr__(self):
|
| 121 |
+
return "%s()" % self.__class__.__name__
|
| 122 |
+
|
| 123 |
+
__reduce__ = object.__reduce__
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
#: Convenience constant providing a :class:`tzutc()` instance
|
| 127 |
+
#:
|
| 128 |
+
#: .. versionadded:: 2.7.0
|
| 129 |
+
UTC = tzutc()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@six.add_metaclass(_TzOffsetFactory)
|
| 133 |
+
class tzoffset(datetime.tzinfo):
|
| 134 |
+
"""
|
| 135 |
+
A simple class for representing a fixed offset from UTC.
|
| 136 |
+
|
| 137 |
+
:param name:
|
| 138 |
+
The timezone name, to be returned when ``tzname()`` is called.
|
| 139 |
+
:param offset:
|
| 140 |
+
The time zone offset in seconds, or (since version 2.6.0, represented
|
| 141 |
+
as a :py:class:`datetime.timedelta` object).
|
| 142 |
+
"""
|
| 143 |
+
def __init__(self, name, offset):
|
| 144 |
+
self._name = name
|
| 145 |
+
|
| 146 |
+
try:
|
| 147 |
+
# Allow a timedelta
|
| 148 |
+
offset = offset.total_seconds()
|
| 149 |
+
except (TypeError, AttributeError):
|
| 150 |
+
pass
|
| 151 |
+
|
| 152 |
+
self._offset = datetime.timedelta(seconds=_get_supported_offset(offset))
|
| 153 |
+
|
| 154 |
+
def utcoffset(self, dt):
|
| 155 |
+
return self._offset
|
| 156 |
+
|
| 157 |
+
def dst(self, dt):
|
| 158 |
+
return ZERO
|
| 159 |
+
|
| 160 |
+
@tzname_in_python2
|
| 161 |
+
def tzname(self, dt):
|
| 162 |
+
return self._name
|
| 163 |
+
|
| 164 |
+
@_validate_fromutc_inputs
|
| 165 |
+
def fromutc(self, dt):
|
| 166 |
+
return dt + self._offset
|
| 167 |
+
|
| 168 |
+
def is_ambiguous(self, dt):
|
| 169 |
+
"""
|
| 170 |
+
Whether or not the "wall time" of a given datetime is ambiguous in this
|
| 171 |
+
zone.
|
| 172 |
+
|
| 173 |
+
:param dt:
|
| 174 |
+
A :py:class:`datetime.datetime`, naive or time zone aware.
|
| 175 |
+
:return:
|
| 176 |
+
Returns ``True`` if ambiguous, ``False`` otherwise.
|
| 177 |
+
|
| 178 |
+
.. versionadded:: 2.6.0
|
| 179 |
+
"""
|
| 180 |
+
return False
|
| 181 |
+
|
| 182 |
+
def __eq__(self, other):
|
| 183 |
+
if not isinstance(other, tzoffset):
|
| 184 |
+
return NotImplemented
|
| 185 |
+
|
| 186 |
+
return self._offset == other._offset
|
| 187 |
+
|
| 188 |
+
__hash__ = None
|
| 189 |
+
|
| 190 |
+
def __ne__(self, other):
|
| 191 |
+
return not (self == other)
|
| 192 |
+
|
| 193 |
+
def __repr__(self):
|
| 194 |
+
return "%s(%s, %s)" % (self.__class__.__name__,
|
| 195 |
+
repr(self._name),
|
| 196 |
+
int(self._offset.total_seconds()))
|
| 197 |
+
|
| 198 |
+
__reduce__ = object.__reduce__
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
class tzlocal(_tzinfo):
|
| 202 |
+
"""
|
| 203 |
+
A :class:`tzinfo` subclass built around the ``time`` timezone functions.
|
| 204 |
+
"""
|
| 205 |
+
def __init__(self):
|
| 206 |
+
super(tzlocal, self).__init__()
|
| 207 |
+
|
| 208 |
+
self._std_offset = datetime.timedelta(seconds=-time.timezone)
|
| 209 |
+
if time.daylight:
|
| 210 |
+
self._dst_offset = datetime.timedelta(seconds=-time.altzone)
|
| 211 |
+
else:
|
| 212 |
+
self._dst_offset = self._std_offset
|
| 213 |
+
|
| 214 |
+
self._dst_saved = self._dst_offset - self._std_offset
|
| 215 |
+
self._hasdst = bool(self._dst_saved)
|
| 216 |
+
self._tznames = tuple(time.tzname)
|
| 217 |
+
|
| 218 |
+
def utcoffset(self, dt):
|
| 219 |
+
if dt is None and self._hasdst:
|
| 220 |
+
return None
|
| 221 |
+
|
| 222 |
+
if self._isdst(dt):
|
| 223 |
+
return self._dst_offset
|
| 224 |
+
else:
|
| 225 |
+
return self._std_offset
|
| 226 |
+
|
| 227 |
+
def dst(self, dt):
|
| 228 |
+
if dt is None and self._hasdst:
|
| 229 |
+
return None
|
| 230 |
+
|
| 231 |
+
if self._isdst(dt):
|
| 232 |
+
return self._dst_offset - self._std_offset
|
| 233 |
+
else:
|
| 234 |
+
return ZERO
|
| 235 |
+
|
| 236 |
+
@tzname_in_python2
|
| 237 |
+
def tzname(self, dt):
|
| 238 |
+
return self._tznames[self._isdst(dt)]
|
| 239 |
+
|
| 240 |
+
def is_ambiguous(self, dt):
|
| 241 |
+
"""
|
| 242 |
+
Whether or not the "wall time" of a given datetime is ambiguous in this
|
| 243 |
+
zone.
|
| 244 |
+
|
| 245 |
+
:param dt:
|
| 246 |
+
A :py:class:`datetime.datetime`, naive or time zone aware.
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
:return:
|
| 250 |
+
Returns ``True`` if ambiguous, ``False`` otherwise.
|
| 251 |
+
|
| 252 |
+
.. versionadded:: 2.6.0
|
| 253 |
+
"""
|
| 254 |
+
naive_dst = self._naive_is_dst(dt)
|
| 255 |
+
return (not naive_dst and
|
| 256 |
+
(naive_dst != self._naive_is_dst(dt - self._dst_saved)))
|
| 257 |
+
|
| 258 |
+
def _naive_is_dst(self, dt):
|
| 259 |
+
timestamp = _datetime_to_timestamp(dt)
|
| 260 |
+
return time.localtime(timestamp + time.timezone).tm_isdst
|
| 261 |
+
|
| 262 |
+
def _isdst(self, dt, fold_naive=True):
|
| 263 |
+
# We can't use mktime here. It is unstable when deciding if
|
| 264 |
+
# the hour near to a change is DST or not.
|
| 265 |
+
#
|
| 266 |
+
# timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour,
|
| 267 |
+
# dt.minute, dt.second, dt.weekday(), 0, -1))
|
| 268 |
+
# return time.localtime(timestamp).tm_isdst
|
| 269 |
+
#
|
| 270 |
+
# The code above yields the following result:
|
| 271 |
+
#
|
| 272 |
+
# >>> import tz, datetime
|
| 273 |
+
# >>> t = tz.tzlocal()
|
| 274 |
+
# >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
|
| 275 |
+
# 'BRDT'
|
| 276 |
+
# >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()
|
| 277 |
+
# 'BRST'
|
| 278 |
+
# >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
|
| 279 |
+
# 'BRST'
|
| 280 |
+
# >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()
|
| 281 |
+
# 'BRDT'
|
| 282 |
+
# >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
|
| 283 |
+
# 'BRDT'
|
| 284 |
+
#
|
| 285 |
+
# Here is a more stable implementation:
|
| 286 |
+
#
|
| 287 |
+
if not self._hasdst:
|
| 288 |
+
return False
|
| 289 |
+
|
| 290 |
+
# Check for ambiguous times:
|
| 291 |
+
dstval = self._naive_is_dst(dt)
|
| 292 |
+
fold = getattr(dt, 'fold', None)
|
| 293 |
+
|
| 294 |
+
if self.is_ambiguous(dt):
|
| 295 |
+
if fold is not None:
|
| 296 |
+
return not self._fold(dt)
|
| 297 |
+
else:
|
| 298 |
+
return True
|
| 299 |
+
|
| 300 |
+
return dstval
|
| 301 |
+
|
| 302 |
+
def __eq__(self, other):
|
| 303 |
+
if isinstance(other, tzlocal):
|
| 304 |
+
return (self._std_offset == other._std_offset and
|
| 305 |
+
self._dst_offset == other._dst_offset)
|
| 306 |
+
elif isinstance(other, tzutc):
|
| 307 |
+
return (not self._hasdst and
|
| 308 |
+
self._tznames[0] in {'UTC', 'GMT'} and
|
| 309 |
+
self._std_offset == ZERO)
|
| 310 |
+
elif isinstance(other, tzoffset):
|
| 311 |
+
return (not self._hasdst and
|
| 312 |
+
self._tznames[0] == other._name and
|
| 313 |
+
self._std_offset == other._offset)
|
| 314 |
+
else:
|
| 315 |
+
return NotImplemented
|
| 316 |
+
|
| 317 |
+
__hash__ = None
|
| 318 |
+
|
| 319 |
+
def __ne__(self, other):
|
| 320 |
+
return not (self == other)
|
| 321 |
+
|
| 322 |
+
def __repr__(self):
|
| 323 |
+
return "%s()" % self.__class__.__name__
|
| 324 |
+
|
| 325 |
+
__reduce__ = object.__reduce__
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class _ttinfo(object):
|
| 329 |
+
__slots__ = ["offset", "delta", "isdst", "abbr",
|
| 330 |
+
"isstd", "isgmt", "dstoffset"]
|
| 331 |
+
|
| 332 |
+
def __init__(self):
|
| 333 |
+
for attr in self.__slots__:
|
| 334 |
+
setattr(self, attr, None)
|
| 335 |
+
|
| 336 |
+
def __repr__(self):
|
| 337 |
+
l = []
|
| 338 |
+
for attr in self.__slots__:
|
| 339 |
+
value = getattr(self, attr)
|
| 340 |
+
if value is not None:
|
| 341 |
+
l.append("%s=%s" % (attr, repr(value)))
|
| 342 |
+
return "%s(%s)" % (self.__class__.__name__, ", ".join(l))
|
| 343 |
+
|
| 344 |
+
def __eq__(self, other):
|
| 345 |
+
if not isinstance(other, _ttinfo):
|
| 346 |
+
return NotImplemented
|
| 347 |
+
|
| 348 |
+
return (self.offset == other.offset and
|
| 349 |
+
self.delta == other.delta and
|
| 350 |
+
self.isdst == other.isdst and
|
| 351 |
+
self.abbr == other.abbr and
|
| 352 |
+
self.isstd == other.isstd and
|
| 353 |
+
self.isgmt == other.isgmt and
|
| 354 |
+
self.dstoffset == other.dstoffset)
|
| 355 |
+
|
| 356 |
+
__hash__ = None
|
| 357 |
+
|
| 358 |
+
def __ne__(self, other):
|
| 359 |
+
return not (self == other)
|
| 360 |
+
|
| 361 |
+
def __getstate__(self):
|
| 362 |
+
state = {}
|
| 363 |
+
for name in self.__slots__:
|
| 364 |
+
state[name] = getattr(self, name, None)
|
| 365 |
+
return state
|
| 366 |
+
|
| 367 |
+
def __setstate__(self, state):
|
| 368 |
+
for name in self.__slots__:
|
| 369 |
+
if name in state:
|
| 370 |
+
setattr(self, name, state[name])
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
class _tzfile(object):
|
| 374 |
+
"""
|
| 375 |
+
Lightweight class for holding the relevant transition and time zone
|
| 376 |
+
information read from binary tzfiles.
|
| 377 |
+
"""
|
| 378 |
+
attrs = ['trans_list', 'trans_list_utc', 'trans_idx', 'ttinfo_list',
|
| 379 |
+
'ttinfo_std', 'ttinfo_dst', 'ttinfo_before', 'ttinfo_first']
|
| 380 |
+
|
| 381 |
+
def __init__(self, **kwargs):
|
| 382 |
+
for attr in self.attrs:
|
| 383 |
+
setattr(self, attr, kwargs.get(attr, None))
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
class tzfile(_tzinfo):
|
| 387 |
+
"""
|
| 388 |
+
This is a ``tzinfo`` subclass that allows one to use the ``tzfile(5)``
|
| 389 |
+
format timezone files to extract current and historical zone information.
|
| 390 |
+
|
| 391 |
+
:param fileobj:
|
| 392 |
+
This can be an opened file stream or a file name that the time zone
|
| 393 |
+
information can be read from.
|
| 394 |
+
|
| 395 |
+
:param filename:
|
| 396 |
+
This is an optional parameter specifying the source of the time zone
|
| 397 |
+
information in the event that ``fileobj`` is a file object. If omitted
|
| 398 |
+
and ``fileobj`` is a file stream, this parameter will be set either to
|
| 399 |
+
``fileobj``'s ``name`` attribute or to ``repr(fileobj)``.
|
| 400 |
+
|
| 401 |
+
See `Sources for Time Zone and Daylight Saving Time Data
|
| 402 |
+
<https://data.iana.org/time-zones/tz-link.html>`_ for more information.
|
| 403 |
+
Time zone files can be compiled from the `IANA Time Zone database files
|
| 404 |
+
<https://www.iana.org/time-zones>`_ with the `zic time zone compiler
|
| 405 |
+
<https://www.freebsd.org/cgi/man.cgi?query=zic&sektion=8>`_
|
| 406 |
+
|
| 407 |
+
.. note::
|
| 408 |
+
|
| 409 |
+
Only construct a ``tzfile`` directly if you have a specific timezone
|
| 410 |
+
file on disk that you want to read into a Python ``tzinfo`` object.
|
| 411 |
+
If you want to get a ``tzfile`` representing a specific IANA zone,
|
| 412 |
+
(e.g. ``'America/New_York'``), you should call
|
| 413 |
+
:func:`dateutil.tz.gettz` with the zone identifier.
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
**Examples:**
|
| 417 |
+
|
| 418 |
+
Using the US Eastern time zone as an example, we can see that a ``tzfile``
|
| 419 |
+
provides time zone information for the standard Daylight Saving offsets:
|
| 420 |
+
|
| 421 |
+
.. testsetup:: tzfile
|
| 422 |
+
|
| 423 |
+
from dateutil.tz import gettz
|
| 424 |
+
from datetime import datetime
|
| 425 |
+
|
| 426 |
+
.. doctest:: tzfile
|
| 427 |
+
|
| 428 |
+
>>> NYC = gettz('America/New_York')
|
| 429 |
+
>>> NYC
|
| 430 |
+
tzfile('/usr/share/zoneinfo/America/New_York')
|
| 431 |
+
|
| 432 |
+
>>> print(datetime(2016, 1, 3, tzinfo=NYC)) # EST
|
| 433 |
+
2016-01-03 00:00:00-05:00
|
| 434 |
+
|
| 435 |
+
>>> print(datetime(2016, 7, 7, tzinfo=NYC)) # EDT
|
| 436 |
+
2016-07-07 00:00:00-04:00
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
The ``tzfile`` structure contains a fully history of the time zone,
|
| 440 |
+
so historical dates will also have the right offsets. For example, before
|
| 441 |
+
the adoption of the UTC standards, New York used local solar mean time:
|
| 442 |
+
|
| 443 |
+
.. doctest:: tzfile
|
| 444 |
+
|
| 445 |
+
>>> print(datetime(1901, 4, 12, tzinfo=NYC)) # LMT
|
| 446 |
+
1901-04-12 00:00:00-04:56
|
| 447 |
+
|
| 448 |
+
And during World War II, New York was on "Eastern War Time", which was a
|
| 449 |
+
state of permanent daylight saving time:
|
| 450 |
+
|
| 451 |
+
.. doctest:: tzfile
|
| 452 |
+
|
| 453 |
+
>>> print(datetime(1944, 2, 7, tzinfo=NYC)) # EWT
|
| 454 |
+
1944-02-07 00:00:00-04:00
|
| 455 |
+
|
| 456 |
+
"""
|
| 457 |
+
|
| 458 |
+
def __init__(self, fileobj, filename=None):
|
| 459 |
+
super(tzfile, self).__init__()
|
| 460 |
+
|
| 461 |
+
file_opened_here = False
|
| 462 |
+
if isinstance(fileobj, string_types):
|
| 463 |
+
self._filename = fileobj
|
| 464 |
+
fileobj = open(fileobj, 'rb')
|
| 465 |
+
file_opened_here = True
|
| 466 |
+
elif filename is not None:
|
| 467 |
+
self._filename = filename
|
| 468 |
+
elif hasattr(fileobj, "name"):
|
| 469 |
+
self._filename = fileobj.name
|
| 470 |
+
else:
|
| 471 |
+
self._filename = repr(fileobj)
|
| 472 |
+
|
| 473 |
+
if fileobj is not None:
|
| 474 |
+
if not file_opened_here:
|
| 475 |
+
fileobj = _nullcontext(fileobj)
|
| 476 |
+
|
| 477 |
+
with fileobj as file_stream:
|
| 478 |
+
tzobj = self._read_tzfile(file_stream)
|
| 479 |
+
|
| 480 |
+
self._set_tzdata(tzobj)
|
| 481 |
+
|
| 482 |
+
def _set_tzdata(self, tzobj):
|
| 483 |
+
""" Set the time zone data of this object from a _tzfile object """
|
| 484 |
+
# Copy the relevant attributes over as private attributes
|
| 485 |
+
for attr in _tzfile.attrs:
|
| 486 |
+
setattr(self, '_' + attr, getattr(tzobj, attr))
|
| 487 |
+
|
| 488 |
+
def _read_tzfile(self, fileobj):
|
| 489 |
+
out = _tzfile()
|
| 490 |
+
|
| 491 |
+
# From tzfile(5):
|
| 492 |
+
#
|
| 493 |
+
# The time zone information files used by tzset(3)
|
| 494 |
+
# begin with the magic characters "TZif" to identify
|
| 495 |
+
# them as time zone information files, followed by
|
| 496 |
+
# sixteen bytes reserved for future use, followed by
|
| 497 |
+
# six four-byte values of type long, written in a
|
| 498 |
+
# ``standard'' byte order (the high-order byte
|
| 499 |
+
# of the value is written first).
|
| 500 |
+
if fileobj.read(4).decode() != "TZif":
|
| 501 |
+
raise ValueError("magic not found")
|
| 502 |
+
|
| 503 |
+
fileobj.read(16)
|
| 504 |
+
|
| 505 |
+
(
|
| 506 |
+
# The number of UTC/local indicators stored in the file.
|
| 507 |
+
ttisgmtcnt,
|
| 508 |
+
|
| 509 |
+
# The number of standard/wall indicators stored in the file.
|
| 510 |
+
ttisstdcnt,
|
| 511 |
+
|
| 512 |
+
# The number of leap seconds for which data is
|
| 513 |
+
# stored in the file.
|
| 514 |
+
leapcnt,
|
| 515 |
+
|
| 516 |
+
# The number of "transition times" for which data
|
| 517 |
+
# is stored in the file.
|
| 518 |
+
timecnt,
|
| 519 |
+
|
| 520 |
+
# The number of "local time types" for which data
|
| 521 |
+
# is stored in the file (must not be zero).
|
| 522 |
+
typecnt,
|
| 523 |
+
|
| 524 |
+
# The number of characters of "time zone
|
| 525 |
+
# abbreviation strings" stored in the file.
|
| 526 |
+
charcnt,
|
| 527 |
+
|
| 528 |
+
) = struct.unpack(">6l", fileobj.read(24))
|
| 529 |
+
|
| 530 |
+
# The above header is followed by tzh_timecnt four-byte
|
| 531 |
+
# values of type long, sorted in ascending order.
|
| 532 |
+
# These values are written in ``standard'' byte order.
|
| 533 |
+
# Each is used as a transition time (as returned by
|
| 534 |
+
# time(2)) at which the rules for computing local time
|
| 535 |
+
# change.
|
| 536 |
+
|
| 537 |
+
if timecnt:
|
| 538 |
+
out.trans_list_utc = list(struct.unpack(">%dl" % timecnt,
|
| 539 |
+
fileobj.read(timecnt*4)))
|
| 540 |
+
else:
|
| 541 |
+
out.trans_list_utc = []
|
| 542 |
+
|
| 543 |
+
# Next come tzh_timecnt one-byte values of type unsigned
|
| 544 |
+
# char; each one tells which of the different types of
|
| 545 |
+
# ``local time'' types described in the file is associated
|
| 546 |
+
# with the same-indexed transition time. These values
|
| 547 |
+
# serve as indices into an array of ttinfo structures that
|
| 548 |
+
# appears next in the file.
|
| 549 |
+
|
| 550 |
+
if timecnt:
|
| 551 |
+
out.trans_idx = struct.unpack(">%dB" % timecnt,
|
| 552 |
+
fileobj.read(timecnt))
|
| 553 |
+
else:
|
| 554 |
+
out.trans_idx = []
|
| 555 |
+
|
| 556 |
+
# Each ttinfo structure is written as a four-byte value
|
| 557 |
+
# for tt_gmtoff of type long, in a standard byte
|
| 558 |
+
# order, followed by a one-byte value for tt_isdst
|
| 559 |
+
# and a one-byte value for tt_abbrind. In each
|
| 560 |
+
# structure, tt_gmtoff gives the number of
|
| 561 |
+
# seconds to be added to UTC, tt_isdst tells whether
|
| 562 |
+
# tm_isdst should be set by localtime(3), and
|
| 563 |
+
# tt_abbrind serves as an index into the array of
|
| 564 |
+
# time zone abbreviation characters that follow the
|
| 565 |
+
# ttinfo structure(s) in the file.
|
| 566 |
+
|
| 567 |
+
ttinfo = []
|
| 568 |
+
|
| 569 |
+
for i in range(typecnt):
|
| 570 |
+
ttinfo.append(struct.unpack(">lbb", fileobj.read(6)))
|
| 571 |
+
|
| 572 |
+
abbr = fileobj.read(charcnt).decode()
|
| 573 |
+
|
| 574 |
+
# Then there are tzh_leapcnt pairs of four-byte
|
| 575 |
+
# values, written in standard byte order; the
|
| 576 |
+
# first value of each pair gives the time (as
|
| 577 |
+
# returned by time(2)) at which a leap second
|
| 578 |
+
# occurs; the second gives the total number of
|
| 579 |
+
# leap seconds to be applied after the given time.
|
| 580 |
+
# The pairs of values are sorted in ascending order
|
| 581 |
+
# by time.
|
| 582 |
+
|
| 583 |
+
# Not used, for now (but seek for correct file position)
|
| 584 |
+
if leapcnt:
|
| 585 |
+
fileobj.seek(leapcnt * 8, os.SEEK_CUR)
|
| 586 |
+
|
| 587 |
+
# Then there are tzh_ttisstdcnt standard/wall
|
| 588 |
+
# indicators, each stored as a one-byte value;
|
| 589 |
+
# they tell whether the transition times associated
|
| 590 |
+
# with local time types were specified as standard
|
| 591 |
+
# time or wall clock time, and are used when
|
| 592 |
+
# a time zone file is used in handling POSIX-style
|
| 593 |
+
# time zone environment variables.
|
| 594 |
+
|
| 595 |
+
if ttisstdcnt:
|
| 596 |
+
isstd = struct.unpack(">%db" % ttisstdcnt,
|
| 597 |
+
fileobj.read(ttisstdcnt))
|
| 598 |
+
|
| 599 |
+
# Finally, there are tzh_ttisgmtcnt UTC/local
|
| 600 |
+
# indicators, each stored as a one-byte value;
|
| 601 |
+
# they tell whether the transition times associated
|
| 602 |
+
# with local time types were specified as UTC or
|
| 603 |
+
# local time, and are used when a time zone file
|
| 604 |
+
# is used in handling POSIX-style time zone envi-
|
| 605 |
+
# ronment variables.
|
| 606 |
+
|
| 607 |
+
if ttisgmtcnt:
|
| 608 |
+
isgmt = struct.unpack(">%db" % ttisgmtcnt,
|
| 609 |
+
fileobj.read(ttisgmtcnt))
|
| 610 |
+
|
| 611 |
+
# Build ttinfo list
|
| 612 |
+
out.ttinfo_list = []
|
| 613 |
+
for i in range(typecnt):
|
| 614 |
+
gmtoff, isdst, abbrind = ttinfo[i]
|
| 615 |
+
gmtoff = _get_supported_offset(gmtoff)
|
| 616 |
+
tti = _ttinfo()
|
| 617 |
+
tti.offset = gmtoff
|
| 618 |
+
tti.dstoffset = datetime.timedelta(0)
|
| 619 |
+
tti.delta = datetime.timedelta(seconds=gmtoff)
|
| 620 |
+
tti.isdst = isdst
|
| 621 |
+
tti.abbr = abbr[abbrind:abbr.find('\x00', abbrind)]
|
| 622 |
+
tti.isstd = (ttisstdcnt > i and isstd[i] != 0)
|
| 623 |
+
tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0)
|
| 624 |
+
out.ttinfo_list.append(tti)
|
| 625 |
+
|
| 626 |
+
# Replace ttinfo indexes for ttinfo objects.
|
| 627 |
+
out.trans_idx = [out.ttinfo_list[idx] for idx in out.trans_idx]
|
| 628 |
+
|
| 629 |
+
# Set standard, dst, and before ttinfos. before will be
|
| 630 |
+
# used when a given time is before any transitions,
|
| 631 |
+
# and will be set to the first non-dst ttinfo, or to
|
| 632 |
+
# the first dst, if all of them are dst.
|
| 633 |
+
out.ttinfo_std = None
|
| 634 |
+
out.ttinfo_dst = None
|
| 635 |
+
out.ttinfo_before = None
|
| 636 |
+
if out.ttinfo_list:
|
| 637 |
+
if not out.trans_list_utc:
|
| 638 |
+
out.ttinfo_std = out.ttinfo_first = out.ttinfo_list[0]
|
| 639 |
+
else:
|
| 640 |
+
for i in range(timecnt-1, -1, -1):
|
| 641 |
+
tti = out.trans_idx[i]
|
| 642 |
+
if not out.ttinfo_std and not tti.isdst:
|
| 643 |
+
out.ttinfo_std = tti
|
| 644 |
+
elif not out.ttinfo_dst and tti.isdst:
|
| 645 |
+
out.ttinfo_dst = tti
|
| 646 |
+
|
| 647 |
+
if out.ttinfo_std and out.ttinfo_dst:
|
| 648 |
+
break
|
| 649 |
+
else:
|
| 650 |
+
if out.ttinfo_dst and not out.ttinfo_std:
|
| 651 |
+
out.ttinfo_std = out.ttinfo_dst
|
| 652 |
+
|
| 653 |
+
for tti in out.ttinfo_list:
|
| 654 |
+
if not tti.isdst:
|
| 655 |
+
out.ttinfo_before = tti
|
| 656 |
+
break
|
| 657 |
+
else:
|
| 658 |
+
out.ttinfo_before = out.ttinfo_list[0]
|
| 659 |
+
|
| 660 |
+
# Now fix transition times to become relative to wall time.
|
| 661 |
+
#
|
| 662 |
+
# I'm not sure about this. In my tests, the tz source file
|
| 663 |
+
# is setup to wall time, and in the binary file isstd and
|
| 664 |
+
# isgmt are off, so it should be in wall time. OTOH, it's
|
| 665 |
+
# always in gmt time. Let me know if you have comments
|
| 666 |
+
# about this.
|
| 667 |
+
lastdst = None
|
| 668 |
+
lastoffset = None
|
| 669 |
+
lastdstoffset = None
|
| 670 |
+
lastbaseoffset = None
|
| 671 |
+
out.trans_list = []
|
| 672 |
+
|
| 673 |
+
for i, tti in enumerate(out.trans_idx):
|
| 674 |
+
offset = tti.offset
|
| 675 |
+
dstoffset = 0
|
| 676 |
+
|
| 677 |
+
if lastdst is not None:
|
| 678 |
+
if tti.isdst:
|
| 679 |
+
if not lastdst:
|
| 680 |
+
dstoffset = offset - lastoffset
|
| 681 |
+
|
| 682 |
+
if not dstoffset and lastdstoffset:
|
| 683 |
+
dstoffset = lastdstoffset
|
| 684 |
+
|
| 685 |
+
tti.dstoffset = datetime.timedelta(seconds=dstoffset)
|
| 686 |
+
lastdstoffset = dstoffset
|
| 687 |
+
|
| 688 |
+
# If a time zone changes its base offset during a DST transition,
|
| 689 |
+
# then you need to adjust by the previous base offset to get the
|
| 690 |
+
# transition time in local time. Otherwise you use the current
|
| 691 |
+
# base offset. Ideally, I would have some mathematical proof of
|
| 692 |
+
# why this is true, but I haven't really thought about it enough.
|
| 693 |
+
baseoffset = offset - dstoffset
|
| 694 |
+
adjustment = baseoffset
|
| 695 |
+
if (lastbaseoffset is not None and baseoffset != lastbaseoffset
|
| 696 |
+
and tti.isdst != lastdst):
|
| 697 |
+
# The base DST has changed
|
| 698 |
+
adjustment = lastbaseoffset
|
| 699 |
+
|
| 700 |
+
lastdst = tti.isdst
|
| 701 |
+
lastoffset = offset
|
| 702 |
+
lastbaseoffset = baseoffset
|
| 703 |
+
|
| 704 |
+
out.trans_list.append(out.trans_list_utc[i] + adjustment)
|
| 705 |
+
|
| 706 |
+
out.trans_idx = tuple(out.trans_idx)
|
| 707 |
+
out.trans_list = tuple(out.trans_list)
|
| 708 |
+
out.trans_list_utc = tuple(out.trans_list_utc)
|
| 709 |
+
|
| 710 |
+
return out
|
| 711 |
+
|
| 712 |
+
def _find_last_transition(self, dt, in_utc=False):
|
| 713 |
+
# If there's no list, there are no transitions to find
|
| 714 |
+
if not self._trans_list:
|
| 715 |
+
return None
|
| 716 |
+
|
| 717 |
+
timestamp = _datetime_to_timestamp(dt)
|
| 718 |
+
|
| 719 |
+
# Find where the timestamp fits in the transition list - if the
|
| 720 |
+
# timestamp is a transition time, it's part of the "after" period.
|
| 721 |
+
trans_list = self._trans_list_utc if in_utc else self._trans_list
|
| 722 |
+
idx = bisect.bisect_right(trans_list, timestamp)
|
| 723 |
+
|
| 724 |
+
# We want to know when the previous transition was, so subtract off 1
|
| 725 |
+
return idx - 1
|
| 726 |
+
|
| 727 |
+
def _get_ttinfo(self, idx):
|
| 728 |
+
# For no list or after the last transition, default to _ttinfo_std
|
| 729 |
+
if idx is None or (idx + 1) >= len(self._trans_list):
|
| 730 |
+
return self._ttinfo_std
|
| 731 |
+
|
| 732 |
+
# If there is a list and the time is before it, return _ttinfo_before
|
| 733 |
+
if idx < 0:
|
| 734 |
+
return self._ttinfo_before
|
| 735 |
+
|
| 736 |
+
return self._trans_idx[idx]
|
| 737 |
+
|
| 738 |
+
def _find_ttinfo(self, dt):
|
| 739 |
+
idx = self._resolve_ambiguous_time(dt)
|
| 740 |
+
|
| 741 |
+
return self._get_ttinfo(idx)
|
| 742 |
+
|
| 743 |
+
def fromutc(self, dt):
|
| 744 |
+
"""
|
| 745 |
+
The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`.
|
| 746 |
+
|
| 747 |
+
:param dt:
|
| 748 |
+
A :py:class:`datetime.datetime` object.
|
| 749 |
+
|
| 750 |
+
:raises TypeError:
|
| 751 |
+
Raised if ``dt`` is not a :py:class:`datetime.datetime` object.
|
| 752 |
+
|
| 753 |
+
:raises ValueError:
|
| 754 |
+
Raised if this is called with a ``dt`` which does not have this
|
| 755 |
+
``tzinfo`` attached.
|
| 756 |
+
|
| 757 |
+
:return:
|
| 758 |
+
Returns a :py:class:`datetime.datetime` object representing the
|
| 759 |
+
wall time in ``self``'s time zone.
|
| 760 |
+
"""
|
| 761 |
+
# These isinstance checks are in datetime.tzinfo, so we'll preserve
|
| 762 |
+
# them, even if we don't care about duck typing.
|
| 763 |
+
if not isinstance(dt, datetime.datetime):
|
| 764 |
+
raise TypeError("fromutc() requires a datetime argument")
|
| 765 |
+
|
| 766 |
+
if dt.tzinfo is not self:
|
| 767 |
+
raise ValueError("dt.tzinfo is not self")
|
| 768 |
+
|
| 769 |
+
# First treat UTC as wall time and get the transition we're in.
|
| 770 |
+
idx = self._find_last_transition(dt, in_utc=True)
|
| 771 |
+
tti = self._get_ttinfo(idx)
|
| 772 |
+
|
| 773 |
+
dt_out = dt + datetime.timedelta(seconds=tti.offset)
|
| 774 |
+
|
| 775 |
+
fold = self.is_ambiguous(dt_out, idx=idx)
|
| 776 |
+
|
| 777 |
+
return enfold(dt_out, fold=int(fold))
|
| 778 |
+
|
| 779 |
+
def is_ambiguous(self, dt, idx=None):
|
| 780 |
+
"""
|
| 781 |
+
Whether or not the "wall time" of a given datetime is ambiguous in this
|
| 782 |
+
zone.
|
| 783 |
+
|
| 784 |
+
:param dt:
|
| 785 |
+
A :py:class:`datetime.datetime`, naive or time zone aware.
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
:return:
|
| 789 |
+
Returns ``True`` if ambiguous, ``False`` otherwise.
|
| 790 |
+
|
| 791 |
+
.. versionadded:: 2.6.0
|
| 792 |
+
"""
|
| 793 |
+
if idx is None:
|
| 794 |
+
idx = self._find_last_transition(dt)
|
| 795 |
+
|
| 796 |
+
# Calculate the difference in offsets from current to previous
|
| 797 |
+
timestamp = _datetime_to_timestamp(dt)
|
| 798 |
+
tti = self._get_ttinfo(idx)
|
| 799 |
+
|
| 800 |
+
if idx is None or idx <= 0:
|
| 801 |
+
return False
|
| 802 |
+
|
| 803 |
+
od = self._get_ttinfo(idx - 1).offset - tti.offset
|
| 804 |
+
tt = self._trans_list[idx] # Transition time
|
| 805 |
+
|
| 806 |
+
return timestamp < tt + od
|
| 807 |
+
|
| 808 |
+
def _resolve_ambiguous_time(self, dt):
|
| 809 |
+
idx = self._find_last_transition(dt)
|
| 810 |
+
|
| 811 |
+
# If we have no transitions, return the index
|
| 812 |
+
_fold = self._fold(dt)
|
| 813 |
+
if idx is None or idx == 0:
|
| 814 |
+
return idx
|
| 815 |
+
|
| 816 |
+
# If it's ambiguous and we're in a fold, shift to a different index.
|
| 817 |
+
idx_offset = int(not _fold and self.is_ambiguous(dt, idx))
|
| 818 |
+
|
| 819 |
+
return idx - idx_offset
|
| 820 |
+
|
| 821 |
+
def utcoffset(self, dt):
|
| 822 |
+
if dt is None:
|
| 823 |
+
return None
|
| 824 |
+
|
| 825 |
+
if not self._ttinfo_std:
|
| 826 |
+
return ZERO
|
| 827 |
+
|
| 828 |
+
return self._find_ttinfo(dt).delta
|
| 829 |
+
|
| 830 |
+
def dst(self, dt):
|
| 831 |
+
if dt is None:
|
| 832 |
+
return None
|
| 833 |
+
|
| 834 |
+
if not self._ttinfo_dst:
|
| 835 |
+
return ZERO
|
| 836 |
+
|
| 837 |
+
tti = self._find_ttinfo(dt)
|
| 838 |
+
|
| 839 |
+
if not tti.isdst:
|
| 840 |
+
return ZERO
|
| 841 |
+
|
| 842 |
+
# The documentation says that utcoffset()-dst() must
|
| 843 |
+
# be constant for every dt.
|
| 844 |
+
return tti.dstoffset
|
| 845 |
+
|
| 846 |
+
@tzname_in_python2
|
| 847 |
+
def tzname(self, dt):
|
| 848 |
+
if not self._ttinfo_std or dt is None:
|
| 849 |
+
return None
|
| 850 |
+
return self._find_ttinfo(dt).abbr
|
| 851 |
+
|
| 852 |
+
def __eq__(self, other):
|
| 853 |
+
if not isinstance(other, tzfile):
|
| 854 |
+
return NotImplemented
|
| 855 |
+
return (self._trans_list == other._trans_list and
|
| 856 |
+
self._trans_idx == other._trans_idx and
|
| 857 |
+
self._ttinfo_list == other._ttinfo_list)
|
| 858 |
+
|
| 859 |
+
__hash__ = None
|
| 860 |
+
|
| 861 |
+
def __ne__(self, other):
|
| 862 |
+
return not (self == other)
|
| 863 |
+
|
| 864 |
+
def __repr__(self):
|
| 865 |
+
return "%s(%s)" % (self.__class__.__name__, repr(self._filename))
|
| 866 |
+
|
| 867 |
+
def __reduce__(self):
|
| 868 |
+
return self.__reduce_ex__(None)
|
| 869 |
+
|
| 870 |
+
def __reduce_ex__(self, protocol):
|
| 871 |
+
return (self.__class__, (None, self._filename), self.__dict__)
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
class tzrange(tzrangebase):
|
| 875 |
+
"""
|
| 876 |
+
The ``tzrange`` object is a time zone specified by a set of offsets and
|
| 877 |
+
abbreviations, equivalent to the way the ``TZ`` variable can be specified
|
| 878 |
+
in POSIX-like systems, but using Python delta objects to specify DST
|
| 879 |
+
start, end and offsets.
|
| 880 |
+
|
| 881 |
+
:param stdabbr:
|
| 882 |
+
The abbreviation for standard time (e.g. ``'EST'``).
|
| 883 |
+
|
| 884 |
+
:param stdoffset:
|
| 885 |
+
An integer or :class:`datetime.timedelta` object or equivalent
|
| 886 |
+
specifying the base offset from UTC.
|
| 887 |
+
|
| 888 |
+
If unspecified, +00:00 is used.
|
| 889 |
+
|
| 890 |
+
:param dstabbr:
|
| 891 |
+
The abbreviation for DST / "Summer" time (e.g. ``'EDT'``).
|
| 892 |
+
|
| 893 |
+
If specified, with no other DST information, DST is assumed to occur
|
| 894 |
+
and the default behavior or ``dstoffset``, ``start`` and ``end`` is
|
| 895 |
+
used. If unspecified and no other DST information is specified, it
|
| 896 |
+
is assumed that this zone has no DST.
|
| 897 |
+
|
| 898 |
+
If this is unspecified and other DST information is *is* specified,
|
| 899 |
+
DST occurs in the zone but the time zone abbreviation is left
|
| 900 |
+
unchanged.
|
| 901 |
+
|
| 902 |
+
:param dstoffset:
|
| 903 |
+
A an integer or :class:`datetime.timedelta` object or equivalent
|
| 904 |
+
specifying the UTC offset during DST. If unspecified and any other DST
|
| 905 |
+
information is specified, it is assumed to be the STD offset +1 hour.
|
| 906 |
+
|
| 907 |
+
:param start:
|
| 908 |
+
A :class:`relativedelta.relativedelta` object or equivalent specifying
|
| 909 |
+
the time and time of year that daylight savings time starts. To
|
| 910 |
+
specify, for example, that DST starts at 2AM on the 2nd Sunday in
|
| 911 |
+
March, pass:
|
| 912 |
+
|
| 913 |
+
``relativedelta(hours=2, month=3, day=1, weekday=SU(+2))``
|
| 914 |
+
|
| 915 |
+
If unspecified and any other DST information is specified, the default
|
| 916 |
+
value is 2 AM on the first Sunday in April.
|
| 917 |
+
|
| 918 |
+
:param end:
|
| 919 |
+
A :class:`relativedelta.relativedelta` object or equivalent
|
| 920 |
+
representing the time and time of year that daylight savings time
|
| 921 |
+
ends, with the same specification method as in ``start``. One note is
|
| 922 |
+
that this should point to the first time in the *standard* zone, so if
|
| 923 |
+
a transition occurs at 2AM in the DST zone and the clocks are set back
|
| 924 |
+
1 hour to 1AM, set the ``hours`` parameter to +1.
|
| 925 |
+
|
| 926 |
+
|
| 927 |
+
**Examples:**
|
| 928 |
+
|
| 929 |
+
.. testsetup:: tzrange
|
| 930 |
+
|
| 931 |
+
from dateutil.tz import tzrange, tzstr
|
| 932 |
+
|
| 933 |
+
.. doctest:: tzrange
|
| 934 |
+
|
| 935 |
+
>>> tzstr('EST5EDT') == tzrange("EST", -18000, "EDT")
|
| 936 |
+
True
|
| 937 |
+
|
| 938 |
+
>>> from dateutil.relativedelta import *
|
| 939 |
+
>>> range1 = tzrange("EST", -18000, "EDT")
|
| 940 |
+
>>> range2 = tzrange("EST", -18000, "EDT", -14400,
|
| 941 |
+
... relativedelta(hours=+2, month=4, day=1,
|
| 942 |
+
... weekday=SU(+1)),
|
| 943 |
+
... relativedelta(hours=+1, month=10, day=31,
|
| 944 |
+
... weekday=SU(-1)))
|
| 945 |
+
>>> tzstr('EST5EDT') == range1 == range2
|
| 946 |
+
True
|
| 947 |
+
|
| 948 |
+
"""
|
| 949 |
+
def __init__(self, stdabbr, stdoffset=None,
|
| 950 |
+
dstabbr=None, dstoffset=None,
|
| 951 |
+
start=None, end=None):
|
| 952 |
+
|
| 953 |
+
global relativedelta
|
| 954 |
+
from dateutil import relativedelta
|
| 955 |
+
|
| 956 |
+
self._std_abbr = stdabbr
|
| 957 |
+
self._dst_abbr = dstabbr
|
| 958 |
+
|
| 959 |
+
try:
|
| 960 |
+
stdoffset = stdoffset.total_seconds()
|
| 961 |
+
except (TypeError, AttributeError):
|
| 962 |
+
pass
|
| 963 |
+
|
| 964 |
+
try:
|
| 965 |
+
dstoffset = dstoffset.total_seconds()
|
| 966 |
+
except (TypeError, AttributeError):
|
| 967 |
+
pass
|
| 968 |
+
|
| 969 |
+
if stdoffset is not None:
|
| 970 |
+
self._std_offset = datetime.timedelta(seconds=stdoffset)
|
| 971 |
+
else:
|
| 972 |
+
self._std_offset = ZERO
|
| 973 |
+
|
| 974 |
+
if dstoffset is not None:
|
| 975 |
+
self._dst_offset = datetime.timedelta(seconds=dstoffset)
|
| 976 |
+
elif dstabbr and stdoffset is not None:
|
| 977 |
+
self._dst_offset = self._std_offset + datetime.timedelta(hours=+1)
|
| 978 |
+
else:
|
| 979 |
+
self._dst_offset = ZERO
|
| 980 |
+
|
| 981 |
+
if dstabbr and start is None:
|
| 982 |
+
self._start_delta = relativedelta.relativedelta(
|
| 983 |
+
hours=+2, month=4, day=1, weekday=relativedelta.SU(+1))
|
| 984 |
+
else:
|
| 985 |
+
self._start_delta = start
|
| 986 |
+
|
| 987 |
+
if dstabbr and end is None:
|
| 988 |
+
self._end_delta = relativedelta.relativedelta(
|
| 989 |
+
hours=+1, month=10, day=31, weekday=relativedelta.SU(-1))
|
| 990 |
+
else:
|
| 991 |
+
self._end_delta = end
|
| 992 |
+
|
| 993 |
+
self._dst_base_offset_ = self._dst_offset - self._std_offset
|
| 994 |
+
self.hasdst = bool(self._start_delta)
|
| 995 |
+
|
| 996 |
+
def transitions(self, year):
|
| 997 |
+
"""
|
| 998 |
+
For a given year, get the DST on and off transition times, expressed
|
| 999 |
+
always on the standard time side. For zones with no transitions, this
|
| 1000 |
+
function returns ``None``.
|
| 1001 |
+
|
| 1002 |
+
:param year:
|
| 1003 |
+
The year whose transitions you would like to query.
|
| 1004 |
+
|
| 1005 |
+
:return:
|
| 1006 |
+
Returns a :class:`tuple` of :class:`datetime.datetime` objects,
|
| 1007 |
+
``(dston, dstoff)`` for zones with an annual DST transition, or
|
| 1008 |
+
``None`` for fixed offset zones.
|
| 1009 |
+
"""
|
| 1010 |
+
if not self.hasdst:
|
| 1011 |
+
return None
|
| 1012 |
+
|
| 1013 |
+
base_year = datetime.datetime(year, 1, 1)
|
| 1014 |
+
|
| 1015 |
+
start = base_year + self._start_delta
|
| 1016 |
+
end = base_year + self._end_delta
|
| 1017 |
+
|
| 1018 |
+
return (start, end)
|
| 1019 |
+
|
| 1020 |
+
def __eq__(self, other):
|
| 1021 |
+
if not isinstance(other, tzrange):
|
| 1022 |
+
return NotImplemented
|
| 1023 |
+
|
| 1024 |
+
return (self._std_abbr == other._std_abbr and
|
| 1025 |
+
self._dst_abbr == other._dst_abbr and
|
| 1026 |
+
self._std_offset == other._std_offset and
|
| 1027 |
+
self._dst_offset == other._dst_offset and
|
| 1028 |
+
self._start_delta == other._start_delta and
|
| 1029 |
+
self._end_delta == other._end_delta)
|
| 1030 |
+
|
| 1031 |
+
@property
|
| 1032 |
+
def _dst_base_offset(self):
|
| 1033 |
+
return self._dst_base_offset_
|
| 1034 |
+
|
| 1035 |
+
|
| 1036 |
+
@six.add_metaclass(_TzStrFactory)
|
| 1037 |
+
class tzstr(tzrange):
|
| 1038 |
+
"""
|
| 1039 |
+
``tzstr`` objects are time zone objects specified by a time-zone string as
|
| 1040 |
+
it would be passed to a ``TZ`` variable on POSIX-style systems (see
|
| 1041 |
+
the `GNU C Library: TZ Variable`_ for more details).
|
| 1042 |
+
|
| 1043 |
+
There is one notable exception, which is that POSIX-style time zones use an
|
| 1044 |
+
inverted offset format, so normally ``GMT+3`` would be parsed as an offset
|
| 1045 |
+
3 hours *behind* GMT. The ``tzstr`` time zone object will parse this as an
|
| 1046 |
+
offset 3 hours *ahead* of GMT. If you would like to maintain the POSIX
|
| 1047 |
+
behavior, pass a ``True`` value to ``posix_offset``.
|
| 1048 |
+
|
| 1049 |
+
The :class:`tzrange` object provides the same functionality, but is
|
| 1050 |
+
specified using :class:`relativedelta.relativedelta` objects. rather than
|
| 1051 |
+
strings.
|
| 1052 |
+
|
| 1053 |
+
:param s:
|
| 1054 |
+
A time zone string in ``TZ`` variable format. This can be a
|
| 1055 |
+
:class:`bytes` (2.x: :class:`str`), :class:`str` (2.x:
|
| 1056 |
+
:class:`unicode`) or a stream emitting unicode characters
|
| 1057 |
+
(e.g. :class:`StringIO`).
|
| 1058 |
+
|
| 1059 |
+
:param posix_offset:
|
| 1060 |
+
Optional. If set to ``True``, interpret strings such as ``GMT+3`` or
|
| 1061 |
+
``UTC+3`` as being 3 hours *behind* UTC rather than ahead, per the
|
| 1062 |
+
POSIX standard.
|
| 1063 |
+
|
| 1064 |
+
.. caution::
|
| 1065 |
+
|
| 1066 |
+
Prior to version 2.7.0, this function also supported time zones
|
| 1067 |
+
in the format:
|
| 1068 |
+
|
| 1069 |
+
* ``EST5EDT,4,0,6,7200,10,0,26,7200,3600``
|
| 1070 |
+
* ``EST5EDT,4,1,0,7200,10,-1,0,7200,3600``
|
| 1071 |
+
|
| 1072 |
+
This format is non-standard and has been deprecated; this function
|
| 1073 |
+
will raise a :class:`DeprecatedTZFormatWarning` until
|
| 1074 |
+
support is removed in a future version.
|
| 1075 |
+
|
| 1076 |
+
.. _`GNU C Library: TZ Variable`:
|
| 1077 |
+
https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
|
| 1078 |
+
"""
|
| 1079 |
+
def __init__(self, s, posix_offset=False):
|
| 1080 |
+
global parser
|
| 1081 |
+
from dateutil.parser import _parser as parser
|
| 1082 |
+
|
| 1083 |
+
self._s = s
|
| 1084 |
+
|
| 1085 |
+
res = parser._parsetz(s)
|
| 1086 |
+
if res is None or res.any_unused_tokens:
|
| 1087 |
+
raise ValueError("unknown string format")
|
| 1088 |
+
|
| 1089 |
+
# Here we break the compatibility with the TZ variable handling.
|
| 1090 |
+
# GMT-3 actually *means* the timezone -3.
|
| 1091 |
+
if res.stdabbr in ("GMT", "UTC") and not posix_offset:
|
| 1092 |
+
res.stdoffset *= -1
|
| 1093 |
+
|
| 1094 |
+
# We must initialize it first, since _delta() needs
|
| 1095 |
+
# _std_offset and _dst_offset set. Use False in start/end
|
| 1096 |
+
# to avoid building it two times.
|
| 1097 |
+
tzrange.__init__(self, res.stdabbr, res.stdoffset,
|
| 1098 |
+
res.dstabbr, res.dstoffset,
|
| 1099 |
+
start=False, end=False)
|
| 1100 |
+
|
| 1101 |
+
if not res.dstabbr:
|
| 1102 |
+
self._start_delta = None
|
| 1103 |
+
self._end_delta = None
|
| 1104 |
+
else:
|
| 1105 |
+
self._start_delta = self._delta(res.start)
|
| 1106 |
+
if self._start_delta:
|
| 1107 |
+
self._end_delta = self._delta(res.end, isend=1)
|
| 1108 |
+
|
| 1109 |
+
self.hasdst = bool(self._start_delta)
|
| 1110 |
+
|
| 1111 |
+
def _delta(self, x, isend=0):
|
| 1112 |
+
from dateutil import relativedelta
|
| 1113 |
+
kwargs = {}
|
| 1114 |
+
if x.month is not None:
|
| 1115 |
+
kwargs["month"] = x.month
|
| 1116 |
+
if x.weekday is not None:
|
| 1117 |
+
kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week)
|
| 1118 |
+
if x.week > 0:
|
| 1119 |
+
kwargs["day"] = 1
|
| 1120 |
+
else:
|
| 1121 |
+
kwargs["day"] = 31
|
| 1122 |
+
elif x.day:
|
| 1123 |
+
kwargs["day"] = x.day
|
| 1124 |
+
elif x.yday is not None:
|
| 1125 |
+
kwargs["yearday"] = x.yday
|
| 1126 |
+
elif x.jyday is not None:
|
| 1127 |
+
kwargs["nlyearday"] = x.jyday
|
| 1128 |
+
if not kwargs:
|
| 1129 |
+
# Default is to start on first sunday of april, and end
|
| 1130 |
+
# on last sunday of october.
|
| 1131 |
+
if not isend:
|
| 1132 |
+
kwargs["month"] = 4
|
| 1133 |
+
kwargs["day"] = 1
|
| 1134 |
+
kwargs["weekday"] = relativedelta.SU(+1)
|
| 1135 |
+
else:
|
| 1136 |
+
kwargs["month"] = 10
|
| 1137 |
+
kwargs["day"] = 31
|
| 1138 |
+
kwargs["weekday"] = relativedelta.SU(-1)
|
| 1139 |
+
if x.time is not None:
|
| 1140 |
+
kwargs["seconds"] = x.time
|
| 1141 |
+
else:
|
| 1142 |
+
# Default is 2AM.
|
| 1143 |
+
kwargs["seconds"] = 7200
|
| 1144 |
+
if isend:
|
| 1145 |
+
# Convert to standard time, to follow the documented way
|
| 1146 |
+
# of working with the extra hour. See the documentation
|
| 1147 |
+
# of the tzinfo class.
|
| 1148 |
+
delta = self._dst_offset - self._std_offset
|
| 1149 |
+
kwargs["seconds"] -= delta.seconds + delta.days * 86400
|
| 1150 |
+
return relativedelta.relativedelta(**kwargs)
|
| 1151 |
+
|
| 1152 |
+
def __repr__(self):
|
| 1153 |
+
return "%s(%s)" % (self.__class__.__name__, repr(self._s))
|
| 1154 |
+
|
| 1155 |
+
|
| 1156 |
+
class _tzicalvtzcomp(object):
|
| 1157 |
+
def __init__(self, tzoffsetfrom, tzoffsetto, isdst,
|
| 1158 |
+
tzname=None, rrule=None):
|
| 1159 |
+
self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom)
|
| 1160 |
+
self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto)
|
| 1161 |
+
self.tzoffsetdiff = self.tzoffsetto - self.tzoffsetfrom
|
| 1162 |
+
self.isdst = isdst
|
| 1163 |
+
self.tzname = tzname
|
| 1164 |
+
self.rrule = rrule
|
| 1165 |
+
|
| 1166 |
+
|
| 1167 |
+
class _tzicalvtz(_tzinfo):
|
| 1168 |
+
def __init__(self, tzid, comps=[]):
|
| 1169 |
+
super(_tzicalvtz, self).__init__()
|
| 1170 |
+
|
| 1171 |
+
self._tzid = tzid
|
| 1172 |
+
self._comps = comps
|
| 1173 |
+
self._cachedate = []
|
| 1174 |
+
self._cachecomp = []
|
| 1175 |
+
self._cache_lock = _thread.allocate_lock()
|
| 1176 |
+
|
| 1177 |
+
def _find_comp(self, dt):
|
| 1178 |
+
if len(self._comps) == 1:
|
| 1179 |
+
return self._comps[0]
|
| 1180 |
+
|
| 1181 |
+
dt = dt.replace(tzinfo=None)
|
| 1182 |
+
|
| 1183 |
+
try:
|
| 1184 |
+
with self._cache_lock:
|
| 1185 |
+
return self._cachecomp[self._cachedate.index(
|
| 1186 |
+
(dt, self._fold(dt)))]
|
| 1187 |
+
except ValueError:
|
| 1188 |
+
pass
|
| 1189 |
+
|
| 1190 |
+
lastcompdt = None
|
| 1191 |
+
lastcomp = None
|
| 1192 |
+
|
| 1193 |
+
for comp in self._comps:
|
| 1194 |
+
compdt = self._find_compdt(comp, dt)
|
| 1195 |
+
|
| 1196 |
+
if compdt and (not lastcompdt or lastcompdt < compdt):
|
| 1197 |
+
lastcompdt = compdt
|
| 1198 |
+
lastcomp = comp
|
| 1199 |
+
|
| 1200 |
+
if not lastcomp:
|
| 1201 |
+
# RFC says nothing about what to do when a given
|
| 1202 |
+
# time is before the first onset date. We'll look for the
|
| 1203 |
+
# first standard component, or the first component, if
|
| 1204 |
+
# none is found.
|
| 1205 |
+
for comp in self._comps:
|
| 1206 |
+
if not comp.isdst:
|
| 1207 |
+
lastcomp = comp
|
| 1208 |
+
break
|
| 1209 |
+
else:
|
| 1210 |
+
lastcomp = comp[0]
|
| 1211 |
+
|
| 1212 |
+
with self._cache_lock:
|
| 1213 |
+
self._cachedate.insert(0, (dt, self._fold(dt)))
|
| 1214 |
+
self._cachecomp.insert(0, lastcomp)
|
| 1215 |
+
|
| 1216 |
+
if len(self._cachedate) > 10:
|
| 1217 |
+
self._cachedate.pop()
|
| 1218 |
+
self._cachecomp.pop()
|
| 1219 |
+
|
| 1220 |
+
return lastcomp
|
| 1221 |
+
|
| 1222 |
+
def _find_compdt(self, comp, dt):
|
| 1223 |
+
if comp.tzoffsetdiff < ZERO and self._fold(dt):
|
| 1224 |
+
dt -= comp.tzoffsetdiff
|
| 1225 |
+
|
| 1226 |
+
compdt = comp.rrule.before(dt, inc=True)
|
| 1227 |
+
|
| 1228 |
+
return compdt
|
| 1229 |
+
|
| 1230 |
+
def utcoffset(self, dt):
|
| 1231 |
+
if dt is None:
|
| 1232 |
+
return None
|
| 1233 |
+
|
| 1234 |
+
return self._find_comp(dt).tzoffsetto
|
| 1235 |
+
|
| 1236 |
+
def dst(self, dt):
|
| 1237 |
+
comp = self._find_comp(dt)
|
| 1238 |
+
if comp.isdst:
|
| 1239 |
+
return comp.tzoffsetdiff
|
| 1240 |
+
else:
|
| 1241 |
+
return ZERO
|
| 1242 |
+
|
| 1243 |
+
@tzname_in_python2
|
| 1244 |
+
def tzname(self, dt):
|
| 1245 |
+
return self._find_comp(dt).tzname
|
| 1246 |
+
|
| 1247 |
+
def __repr__(self):
|
| 1248 |
+
return "<tzicalvtz %s>" % repr(self._tzid)
|
| 1249 |
+
|
| 1250 |
+
__reduce__ = object.__reduce__
|
| 1251 |
+
|
| 1252 |
+
|
| 1253 |
+
class tzical(object):
|
| 1254 |
+
"""
|
| 1255 |
+
This object is designed to parse an iCalendar-style ``VTIMEZONE`` structure
|
| 1256 |
+
as set out in `RFC 5545`_ Section 4.6.5 into one or more `tzinfo` objects.
|
| 1257 |
+
|
| 1258 |
+
:param `fileobj`:
|
| 1259 |
+
A file or stream in iCalendar format, which should be UTF-8 encoded
|
| 1260 |
+
with CRLF endings.
|
| 1261 |
+
|
| 1262 |
+
.. _`RFC 5545`: https://tools.ietf.org/html/rfc5545
|
| 1263 |
+
"""
|
| 1264 |
+
def __init__(self, fileobj):
|
| 1265 |
+
global rrule
|
| 1266 |
+
from dateutil import rrule
|
| 1267 |
+
|
| 1268 |
+
if isinstance(fileobj, string_types):
|
| 1269 |
+
self._s = fileobj
|
| 1270 |
+
# ical should be encoded in UTF-8 with CRLF
|
| 1271 |
+
fileobj = open(fileobj, 'r')
|
| 1272 |
+
else:
|
| 1273 |
+
self._s = getattr(fileobj, 'name', repr(fileobj))
|
| 1274 |
+
fileobj = _nullcontext(fileobj)
|
| 1275 |
+
|
| 1276 |
+
self._vtz = {}
|
| 1277 |
+
|
| 1278 |
+
with fileobj as fobj:
|
| 1279 |
+
self._parse_rfc(fobj.read())
|
| 1280 |
+
|
| 1281 |
+
def keys(self):
|
| 1282 |
+
"""
|
| 1283 |
+
Retrieves the available time zones as a list.
|
| 1284 |
+
"""
|
| 1285 |
+
return list(self._vtz.keys())
|
| 1286 |
+
|
| 1287 |
+
def get(self, tzid=None):
|
| 1288 |
+
"""
|
| 1289 |
+
Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``.
|
| 1290 |
+
|
| 1291 |
+
:param tzid:
|
| 1292 |
+
If there is exactly one time zone available, omitting ``tzid``
|
| 1293 |
+
or passing :py:const:`None` value returns it. Otherwise a valid
|
| 1294 |
+
key (which can be retrieved from :func:`keys`) is required.
|
| 1295 |
+
|
| 1296 |
+
:raises ValueError:
|
| 1297 |
+
Raised if ``tzid`` is not specified but there are either more
|
| 1298 |
+
or fewer than 1 zone defined.
|
| 1299 |
+
|
| 1300 |
+
:returns:
|
| 1301 |
+
Returns either a :py:class:`datetime.tzinfo` object representing
|
| 1302 |
+
the relevant time zone or :py:const:`None` if the ``tzid`` was
|
| 1303 |
+
not found.
|
| 1304 |
+
"""
|
| 1305 |
+
if tzid is None:
|
| 1306 |
+
if len(self._vtz) == 0:
|
| 1307 |
+
raise ValueError("no timezones defined")
|
| 1308 |
+
elif len(self._vtz) > 1:
|
| 1309 |
+
raise ValueError("more than one timezone available")
|
| 1310 |
+
tzid = next(iter(self._vtz))
|
| 1311 |
+
|
| 1312 |
+
return self._vtz.get(tzid)
|
| 1313 |
+
|
| 1314 |
+
def _parse_offset(self, s):
|
| 1315 |
+
s = s.strip()
|
| 1316 |
+
if not s:
|
| 1317 |
+
raise ValueError("empty offset")
|
| 1318 |
+
if s[0] in ('+', '-'):
|
| 1319 |
+
signal = (-1, +1)[s[0] == '+']
|
| 1320 |
+
s = s[1:]
|
| 1321 |
+
else:
|
| 1322 |
+
signal = +1
|
| 1323 |
+
if len(s) == 4:
|
| 1324 |
+
return (int(s[:2]) * 3600 + int(s[2:]) * 60) * signal
|
| 1325 |
+
elif len(s) == 6:
|
| 1326 |
+
return (int(s[:2]) * 3600 + int(s[2:4]) * 60 + int(s[4:])) * signal
|
| 1327 |
+
else:
|
| 1328 |
+
raise ValueError("invalid offset: " + s)
|
| 1329 |
+
|
| 1330 |
+
def _parse_rfc(self, s):
|
| 1331 |
+
lines = s.splitlines()
|
| 1332 |
+
if not lines:
|
| 1333 |
+
raise ValueError("empty string")
|
| 1334 |
+
|
| 1335 |
+
# Unfold
|
| 1336 |
+
i = 0
|
| 1337 |
+
while i < len(lines):
|
| 1338 |
+
line = lines[i].rstrip()
|
| 1339 |
+
if not line:
|
| 1340 |
+
del lines[i]
|
| 1341 |
+
elif i > 0 and line[0] == " ":
|
| 1342 |
+
lines[i-1] += line[1:]
|
| 1343 |
+
del lines[i]
|
| 1344 |
+
else:
|
| 1345 |
+
i += 1
|
| 1346 |
+
|
| 1347 |
+
tzid = None
|
| 1348 |
+
comps = []
|
| 1349 |
+
invtz = False
|
| 1350 |
+
comptype = None
|
| 1351 |
+
for line in lines:
|
| 1352 |
+
if not line:
|
| 1353 |
+
continue
|
| 1354 |
+
name, value = line.split(':', 1)
|
| 1355 |
+
parms = name.split(';')
|
| 1356 |
+
if not parms:
|
| 1357 |
+
raise ValueError("empty property name")
|
| 1358 |
+
name = parms[0].upper()
|
| 1359 |
+
parms = parms[1:]
|
| 1360 |
+
if invtz:
|
| 1361 |
+
if name == "BEGIN":
|
| 1362 |
+
if value in ("STANDARD", "DAYLIGHT"):
|
| 1363 |
+
# Process component
|
| 1364 |
+
pass
|
| 1365 |
+
else:
|
| 1366 |
+
raise ValueError("unknown component: "+value)
|
| 1367 |
+
comptype = value
|
| 1368 |
+
founddtstart = False
|
| 1369 |
+
tzoffsetfrom = None
|
| 1370 |
+
tzoffsetto = None
|
| 1371 |
+
rrulelines = []
|
| 1372 |
+
tzname = None
|
| 1373 |
+
elif name == "END":
|
| 1374 |
+
if value == "VTIMEZONE":
|
| 1375 |
+
if comptype:
|
| 1376 |
+
raise ValueError("component not closed: "+comptype)
|
| 1377 |
+
if not tzid:
|
| 1378 |
+
raise ValueError("mandatory TZID not found")
|
| 1379 |
+
if not comps:
|
| 1380 |
+
raise ValueError(
|
| 1381 |
+
"at least one component is needed")
|
| 1382 |
+
# Process vtimezone
|
| 1383 |
+
self._vtz[tzid] = _tzicalvtz(tzid, comps)
|
| 1384 |
+
invtz = False
|
| 1385 |
+
elif value == comptype:
|
| 1386 |
+
if not founddtstart:
|
| 1387 |
+
raise ValueError("mandatory DTSTART not found")
|
| 1388 |
+
if tzoffsetfrom is None:
|
| 1389 |
+
raise ValueError(
|
| 1390 |
+
"mandatory TZOFFSETFROM not found")
|
| 1391 |
+
if tzoffsetto is None:
|
| 1392 |
+
raise ValueError(
|
| 1393 |
+
"mandatory TZOFFSETFROM not found")
|
| 1394 |
+
# Process component
|
| 1395 |
+
rr = None
|
| 1396 |
+
if rrulelines:
|
| 1397 |
+
rr = rrule.rrulestr("\n".join(rrulelines),
|
| 1398 |
+
compatible=True,
|
| 1399 |
+
ignoretz=True,
|
| 1400 |
+
cache=True)
|
| 1401 |
+
comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto,
|
| 1402 |
+
(comptype == "DAYLIGHT"),
|
| 1403 |
+
tzname, rr)
|
| 1404 |
+
comps.append(comp)
|
| 1405 |
+
comptype = None
|
| 1406 |
+
else:
|
| 1407 |
+
raise ValueError("invalid component end: "+value)
|
| 1408 |
+
elif comptype:
|
| 1409 |
+
if name == "DTSTART":
|
| 1410 |
+
# DTSTART in VTIMEZONE takes a subset of valid RRULE
|
| 1411 |
+
# values under RFC 5545.
|
| 1412 |
+
for parm in parms:
|
| 1413 |
+
if parm != 'VALUE=DATE-TIME':
|
| 1414 |
+
msg = ('Unsupported DTSTART param in ' +
|
| 1415 |
+
'VTIMEZONE: ' + parm)
|
| 1416 |
+
raise ValueError(msg)
|
| 1417 |
+
rrulelines.append(line)
|
| 1418 |
+
founddtstart = True
|
| 1419 |
+
elif name in ("RRULE", "RDATE", "EXRULE", "EXDATE"):
|
| 1420 |
+
rrulelines.append(line)
|
| 1421 |
+
elif name == "TZOFFSETFROM":
|
| 1422 |
+
if parms:
|
| 1423 |
+
raise ValueError(
|
| 1424 |
+
"unsupported %s parm: %s " % (name, parms[0]))
|
| 1425 |
+
tzoffsetfrom = self._parse_offset(value)
|
| 1426 |
+
elif name == "TZOFFSETTO":
|
| 1427 |
+
if parms:
|
| 1428 |
+
raise ValueError(
|
| 1429 |
+
"unsupported TZOFFSETTO parm: "+parms[0])
|
| 1430 |
+
tzoffsetto = self._parse_offset(value)
|
| 1431 |
+
elif name == "TZNAME":
|
| 1432 |
+
if parms:
|
| 1433 |
+
raise ValueError(
|
| 1434 |
+
"unsupported TZNAME parm: "+parms[0])
|
| 1435 |
+
tzname = value
|
| 1436 |
+
elif name == "COMMENT":
|
| 1437 |
+
pass
|
| 1438 |
+
else:
|
| 1439 |
+
raise ValueError("unsupported property: "+name)
|
| 1440 |
+
else:
|
| 1441 |
+
if name == "TZID":
|
| 1442 |
+
if parms:
|
| 1443 |
+
raise ValueError(
|
| 1444 |
+
"unsupported TZID parm: "+parms[0])
|
| 1445 |
+
tzid = value
|
| 1446 |
+
elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"):
|
| 1447 |
+
pass
|
| 1448 |
+
else:
|
| 1449 |
+
raise ValueError("unsupported property: "+name)
|
| 1450 |
+
elif name == "BEGIN" and value == "VTIMEZONE":
|
| 1451 |
+
tzid = None
|
| 1452 |
+
comps = []
|
| 1453 |
+
invtz = True
|
| 1454 |
+
|
| 1455 |
+
def __repr__(self):
|
| 1456 |
+
return "%s(%s)" % (self.__class__.__name__, repr(self._s))
|
| 1457 |
+
|
| 1458 |
+
|
| 1459 |
+
if sys.platform != "win32":
|
| 1460 |
+
TZFILES = ["/etc/localtime", "localtime"]
|
| 1461 |
+
TZPATHS = ["/usr/share/zoneinfo",
|
| 1462 |
+
"/usr/lib/zoneinfo",
|
| 1463 |
+
"/usr/share/lib/zoneinfo",
|
| 1464 |
+
"/etc/zoneinfo"]
|
| 1465 |
+
else:
|
| 1466 |
+
TZFILES = []
|
| 1467 |
+
TZPATHS = []
|
| 1468 |
+
|
| 1469 |
+
|
| 1470 |
+
def __get_gettz():
|
| 1471 |
+
tzlocal_classes = (tzlocal,)
|
| 1472 |
+
if tzwinlocal is not None:
|
| 1473 |
+
tzlocal_classes += (tzwinlocal,)
|
| 1474 |
+
|
| 1475 |
+
class GettzFunc(object):
|
| 1476 |
+
"""
|
| 1477 |
+
Retrieve a time zone object from a string representation
|
| 1478 |
+
|
| 1479 |
+
This function is intended to retrieve the :py:class:`tzinfo` subclass
|
| 1480 |
+
that best represents the time zone that would be used if a POSIX
|
| 1481 |
+
`TZ variable`_ were set to the same value.
|
| 1482 |
+
|
| 1483 |
+
If no argument or an empty string is passed to ``gettz``, local time
|
| 1484 |
+
is returned:
|
| 1485 |
+
|
| 1486 |
+
.. code-block:: python3
|
| 1487 |
+
|
| 1488 |
+
>>> gettz()
|
| 1489 |
+
tzfile('/etc/localtime')
|
| 1490 |
+
|
| 1491 |
+
This function is also the preferred way to map IANA tz database keys
|
| 1492 |
+
to :class:`tzfile` objects:
|
| 1493 |
+
|
| 1494 |
+
.. code-block:: python3
|
| 1495 |
+
|
| 1496 |
+
>>> gettz('Pacific/Kiritimati')
|
| 1497 |
+
tzfile('/usr/share/zoneinfo/Pacific/Kiritimati')
|
| 1498 |
+
|
| 1499 |
+
On Windows, the standard is extended to include the Windows-specific
|
| 1500 |
+
zone names provided by the operating system:
|
| 1501 |
+
|
| 1502 |
+
.. code-block:: python3
|
| 1503 |
+
|
| 1504 |
+
>>> gettz('Egypt Standard Time')
|
| 1505 |
+
tzwin('Egypt Standard Time')
|
| 1506 |
+
|
| 1507 |
+
Passing a GNU ``TZ`` style string time zone specification returns a
|
| 1508 |
+
:class:`tzstr` object:
|
| 1509 |
+
|
| 1510 |
+
.. code-block:: python3
|
| 1511 |
+
|
| 1512 |
+
>>> gettz('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3')
|
| 1513 |
+
tzstr('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3')
|
| 1514 |
+
|
| 1515 |
+
:param name:
|
| 1516 |
+
A time zone name (IANA, or, on Windows, Windows keys), location of
|
| 1517 |
+
a ``tzfile(5)`` zoneinfo file or ``TZ`` variable style time zone
|
| 1518 |
+
specifier. An empty string, no argument or ``None`` is interpreted
|
| 1519 |
+
as local time.
|
| 1520 |
+
|
| 1521 |
+
:return:
|
| 1522 |
+
Returns an instance of one of ``dateutil``'s :py:class:`tzinfo`
|
| 1523 |
+
subclasses.
|
| 1524 |
+
|
| 1525 |
+
.. versionchanged:: 2.7.0
|
| 1526 |
+
|
| 1527 |
+
After version 2.7.0, any two calls to ``gettz`` using the same
|
| 1528 |
+
input strings will return the same object:
|
| 1529 |
+
|
| 1530 |
+
.. code-block:: python3
|
| 1531 |
+
|
| 1532 |
+
>>> tz.gettz('America/Chicago') is tz.gettz('America/Chicago')
|
| 1533 |
+
True
|
| 1534 |
+
|
| 1535 |
+
In addition to improving performance, this ensures that
|
| 1536 |
+
`"same zone" semantics`_ are used for datetimes in the same zone.
|
| 1537 |
+
|
| 1538 |
+
|
| 1539 |
+
.. _`TZ variable`:
|
| 1540 |
+
https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
|
| 1541 |
+
|
| 1542 |
+
.. _`"same zone" semantics`:
|
| 1543 |
+
https://blog.ganssle.io/articles/2018/02/aware-datetime-arithmetic.html
|
| 1544 |
+
"""
|
| 1545 |
+
def __init__(self):
|
| 1546 |
+
|
| 1547 |
+
self.__instances = weakref.WeakValueDictionary()
|
| 1548 |
+
self.__strong_cache_size = 8
|
| 1549 |
+
self.__strong_cache = OrderedDict()
|
| 1550 |
+
self._cache_lock = _thread.allocate_lock()
|
| 1551 |
+
|
| 1552 |
+
def __call__(self, name=None):
|
| 1553 |
+
with self._cache_lock:
|
| 1554 |
+
rv = self.__instances.get(name, None)
|
| 1555 |
+
|
| 1556 |
+
if rv is None:
|
| 1557 |
+
rv = self.nocache(name=name)
|
| 1558 |
+
if not (name is None
|
| 1559 |
+
or isinstance(rv, tzlocal_classes)
|
| 1560 |
+
or rv is None):
|
| 1561 |
+
# tzlocal is slightly more complicated than the other
|
| 1562 |
+
# time zone providers because it depends on environment
|
| 1563 |
+
# at construction time, so don't cache that.
|
| 1564 |
+
#
|
| 1565 |
+
# We also cannot store weak references to None, so we
|
| 1566 |
+
# will also not store that.
|
| 1567 |
+
self.__instances[name] = rv
|
| 1568 |
+
else:
|
| 1569 |
+
# No need for strong caching, return immediately
|
| 1570 |
+
return rv
|
| 1571 |
+
|
| 1572 |
+
self.__strong_cache[name] = self.__strong_cache.pop(name, rv)
|
| 1573 |
+
|
| 1574 |
+
if len(self.__strong_cache) > self.__strong_cache_size:
|
| 1575 |
+
self.__strong_cache.popitem(last=False)
|
| 1576 |
+
|
| 1577 |
+
return rv
|
| 1578 |
+
|
| 1579 |
+
def set_cache_size(self, size):
|
| 1580 |
+
with self._cache_lock:
|
| 1581 |
+
self.__strong_cache_size = size
|
| 1582 |
+
while len(self.__strong_cache) > size:
|
| 1583 |
+
self.__strong_cache.popitem(last=False)
|
| 1584 |
+
|
| 1585 |
+
def cache_clear(self):
|
| 1586 |
+
with self._cache_lock:
|
| 1587 |
+
self.__instances = weakref.WeakValueDictionary()
|
| 1588 |
+
self.__strong_cache.clear()
|
| 1589 |
+
|
| 1590 |
+
@staticmethod
|
| 1591 |
+
def nocache(name=None):
|
| 1592 |
+
"""A non-cached version of gettz"""
|
| 1593 |
+
tz = None
|
| 1594 |
+
if not name:
|
| 1595 |
+
try:
|
| 1596 |
+
name = os.environ["TZ"]
|
| 1597 |
+
except KeyError:
|
| 1598 |
+
pass
|
| 1599 |
+
if name is None or name in ("", ":"):
|
| 1600 |
+
for filepath in TZFILES:
|
| 1601 |
+
if not os.path.isabs(filepath):
|
| 1602 |
+
filename = filepath
|
| 1603 |
+
for path in TZPATHS:
|
| 1604 |
+
filepath = os.path.join(path, filename)
|
| 1605 |
+
if os.path.isfile(filepath):
|
| 1606 |
+
break
|
| 1607 |
+
else:
|
| 1608 |
+
continue
|
| 1609 |
+
if os.path.isfile(filepath):
|
| 1610 |
+
try:
|
| 1611 |
+
tz = tzfile(filepath)
|
| 1612 |
+
break
|
| 1613 |
+
except (IOError, OSError, ValueError):
|
| 1614 |
+
pass
|
| 1615 |
+
else:
|
| 1616 |
+
tz = tzlocal()
|
| 1617 |
+
else:
|
| 1618 |
+
try:
|
| 1619 |
+
if name.startswith(":"):
|
| 1620 |
+
name = name[1:]
|
| 1621 |
+
except TypeError as e:
|
| 1622 |
+
if isinstance(name, bytes):
|
| 1623 |
+
new_msg = "gettz argument should be str, not bytes"
|
| 1624 |
+
six.raise_from(TypeError(new_msg), e)
|
| 1625 |
+
else:
|
| 1626 |
+
raise
|
| 1627 |
+
if os.path.isabs(name):
|
| 1628 |
+
if os.path.isfile(name):
|
| 1629 |
+
tz = tzfile(name)
|
| 1630 |
+
else:
|
| 1631 |
+
tz = None
|
| 1632 |
+
else:
|
| 1633 |
+
for path in TZPATHS:
|
| 1634 |
+
filepath = os.path.join(path, name)
|
| 1635 |
+
if not os.path.isfile(filepath):
|
| 1636 |
+
filepath = filepath.replace(' ', '_')
|
| 1637 |
+
if not os.path.isfile(filepath):
|
| 1638 |
+
continue
|
| 1639 |
+
try:
|
| 1640 |
+
tz = tzfile(filepath)
|
| 1641 |
+
break
|
| 1642 |
+
except (IOError, OSError, ValueError):
|
| 1643 |
+
pass
|
| 1644 |
+
else:
|
| 1645 |
+
tz = None
|
| 1646 |
+
if tzwin is not None:
|
| 1647 |
+
try:
|
| 1648 |
+
tz = tzwin(name)
|
| 1649 |
+
except (WindowsError, UnicodeEncodeError):
|
| 1650 |
+
# UnicodeEncodeError is for Python 2.7 compat
|
| 1651 |
+
tz = None
|
| 1652 |
+
|
| 1653 |
+
if not tz:
|
| 1654 |
+
from dateutil.zoneinfo import get_zonefile_instance
|
| 1655 |
+
tz = get_zonefile_instance().get(name)
|
| 1656 |
+
|
| 1657 |
+
if not tz:
|
| 1658 |
+
for c in name:
|
| 1659 |
+
# name is not a tzstr unless it has at least
|
| 1660 |
+
# one offset. For short values of "name", an
|
| 1661 |
+
# explicit for loop seems to be the fastest way
|
| 1662 |
+
# To determine if a string contains a digit
|
| 1663 |
+
if c in "0123456789":
|
| 1664 |
+
try:
|
| 1665 |
+
tz = tzstr(name)
|
| 1666 |
+
except ValueError:
|
| 1667 |
+
pass
|
| 1668 |
+
break
|
| 1669 |
+
else:
|
| 1670 |
+
if name in ("GMT", "UTC"):
|
| 1671 |
+
tz = UTC
|
| 1672 |
+
elif name in time.tzname:
|
| 1673 |
+
tz = tzlocal()
|
| 1674 |
+
return tz
|
| 1675 |
+
|
| 1676 |
+
return GettzFunc()
|
| 1677 |
+
|
| 1678 |
+
|
| 1679 |
+
gettz = __get_gettz()
|
| 1680 |
+
del __get_gettz
|
| 1681 |
+
|
| 1682 |
+
|
| 1683 |
+
def datetime_exists(dt, tz=None):
|
| 1684 |
+
"""
|
| 1685 |
+
Given a datetime and a time zone, determine whether or not a given datetime
|
| 1686 |
+
would fall in a gap.
|
| 1687 |
+
|
| 1688 |
+
:param dt:
|
| 1689 |
+
A :class:`datetime.datetime` (whose time zone will be ignored if ``tz``
|
| 1690 |
+
is provided.)
|
| 1691 |
+
|
| 1692 |
+
:param tz:
|
| 1693 |
+
A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If
|
| 1694 |
+
``None`` or not provided, the datetime's own time zone will be used.
|
| 1695 |
+
|
| 1696 |
+
:return:
|
| 1697 |
+
Returns a boolean value whether or not the "wall time" exists in
|
| 1698 |
+
``tz``.
|
| 1699 |
+
|
| 1700 |
+
.. versionadded:: 2.7.0
|
| 1701 |
+
"""
|
| 1702 |
+
if tz is None:
|
| 1703 |
+
if dt.tzinfo is None:
|
| 1704 |
+
raise ValueError('Datetime is naive and no time zone provided.')
|
| 1705 |
+
tz = dt.tzinfo
|
| 1706 |
+
|
| 1707 |
+
dt = dt.replace(tzinfo=None)
|
| 1708 |
+
|
| 1709 |
+
# This is essentially a test of whether or not the datetime can survive
|
| 1710 |
+
# a round trip to UTC.
|
| 1711 |
+
dt_rt = dt.replace(tzinfo=tz).astimezone(UTC).astimezone(tz)
|
| 1712 |
+
dt_rt = dt_rt.replace(tzinfo=None)
|
| 1713 |
+
|
| 1714 |
+
return dt == dt_rt
|
| 1715 |
+
|
| 1716 |
+
|
| 1717 |
+
def datetime_ambiguous(dt, tz=None):
|
| 1718 |
+
"""
|
| 1719 |
+
Given a datetime and a time zone, determine whether or not a given datetime
|
| 1720 |
+
is ambiguous (i.e if there are two times differentiated only by their DST
|
| 1721 |
+
status).
|
| 1722 |
+
|
| 1723 |
+
:param dt:
|
| 1724 |
+
A :class:`datetime.datetime` (whose time zone will be ignored if ``tz``
|
| 1725 |
+
is provided.)
|
| 1726 |
+
|
| 1727 |
+
:param tz:
|
| 1728 |
+
A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If
|
| 1729 |
+
``None`` or not provided, the datetime's own time zone will be used.
|
| 1730 |
+
|
| 1731 |
+
:return:
|
| 1732 |
+
Returns a boolean value whether or not the "wall time" is ambiguous in
|
| 1733 |
+
``tz``.
|
| 1734 |
+
|
| 1735 |
+
.. versionadded:: 2.6.0
|
| 1736 |
+
"""
|
| 1737 |
+
if tz is None:
|
| 1738 |
+
if dt.tzinfo is None:
|
| 1739 |
+
raise ValueError('Datetime is naive and no time zone provided.')
|
| 1740 |
+
|
| 1741 |
+
tz = dt.tzinfo
|
| 1742 |
+
|
| 1743 |
+
# If a time zone defines its own "is_ambiguous" function, we'll use that.
|
| 1744 |
+
is_ambiguous_fn = getattr(tz, 'is_ambiguous', None)
|
| 1745 |
+
if is_ambiguous_fn is not None:
|
| 1746 |
+
try:
|
| 1747 |
+
return tz.is_ambiguous(dt)
|
| 1748 |
+
except Exception:
|
| 1749 |
+
pass
|
| 1750 |
+
|
| 1751 |
+
# If it doesn't come out and tell us it's ambiguous, we'll just check if
|
| 1752 |
+
# the fold attribute has any effect on this particular date and time.
|
| 1753 |
+
dt = dt.replace(tzinfo=tz)
|
| 1754 |
+
wall_0 = enfold(dt, fold=0)
|
| 1755 |
+
wall_1 = enfold(dt, fold=1)
|
| 1756 |
+
|
| 1757 |
+
same_offset = wall_0.utcoffset() == wall_1.utcoffset()
|
| 1758 |
+
same_dst = wall_0.dst() == wall_1.dst()
|
| 1759 |
+
|
| 1760 |
+
return not (same_offset and same_dst)
|
| 1761 |
+
|
| 1762 |
+
|
| 1763 |
+
def resolve_imaginary(dt):
|
| 1764 |
+
"""
|
| 1765 |
+
Given a datetime that may be imaginary, return an existing datetime.
|
| 1766 |
+
|
| 1767 |
+
This function assumes that an imaginary datetime represents what the
|
| 1768 |
+
wall time would be in a zone had the offset transition not occurred, so
|
| 1769 |
+
it will always fall forward by the transition's change in offset.
|
| 1770 |
+
|
| 1771 |
+
.. doctest::
|
| 1772 |
+
|
| 1773 |
+
>>> from dateutil import tz
|
| 1774 |
+
>>> from datetime import datetime
|
| 1775 |
+
>>> NYC = tz.gettz('America/New_York')
|
| 1776 |
+
>>> print(tz.resolve_imaginary(datetime(2017, 3, 12, 2, 30, tzinfo=NYC)))
|
| 1777 |
+
2017-03-12 03:30:00-04:00
|
| 1778 |
+
|
| 1779 |
+
>>> KIR = tz.gettz('Pacific/Kiritimati')
|
| 1780 |
+
>>> print(tz.resolve_imaginary(datetime(1995, 1, 1, 12, 30, tzinfo=KIR)))
|
| 1781 |
+
1995-01-02 12:30:00+14:00
|
| 1782 |
+
|
| 1783 |
+
As a note, :func:`datetime.astimezone` is guaranteed to produce a valid,
|
| 1784 |
+
existing datetime, so a round-trip to and from UTC is sufficient to get
|
| 1785 |
+
an extant datetime, however, this generally "falls back" to an earlier time
|
| 1786 |
+
rather than falling forward to the STD side (though no guarantees are made
|
| 1787 |
+
about this behavior).
|
| 1788 |
+
|
| 1789 |
+
:param dt:
|
| 1790 |
+
A :class:`datetime.datetime` which may or may not exist.
|
| 1791 |
+
|
| 1792 |
+
:return:
|
| 1793 |
+
Returns an existing :class:`datetime.datetime`. If ``dt`` was not
|
| 1794 |
+
imaginary, the datetime returned is guaranteed to be the same object
|
| 1795 |
+
passed to the function.
|
| 1796 |
+
|
| 1797 |
+
.. versionadded:: 2.7.0
|
| 1798 |
+
"""
|
| 1799 |
+
if dt.tzinfo is not None and not datetime_exists(dt):
|
| 1800 |
+
|
| 1801 |
+
curr_offset = (dt + datetime.timedelta(hours=24)).utcoffset()
|
| 1802 |
+
old_offset = (dt - datetime.timedelta(hours=24)).utcoffset()
|
| 1803 |
+
|
| 1804 |
+
dt += curr_offset - old_offset
|
| 1805 |
+
|
| 1806 |
+
return dt
|
| 1807 |
+
|
| 1808 |
+
|
| 1809 |
+
def _datetime_to_timestamp(dt):
|
| 1810 |
+
"""
|
| 1811 |
+
Convert a :class:`datetime.datetime` object to an epoch timestamp in
|
| 1812 |
+
seconds since January 1, 1970, ignoring the time zone.
|
| 1813 |
+
"""
|
| 1814 |
+
return (dt.replace(tzinfo=None) - EPOCH).total_seconds()
|
| 1815 |
+
|
| 1816 |
+
|
| 1817 |
+
if sys.version_info >= (3, 6):
|
| 1818 |
+
def _get_supported_offset(second_offset):
|
| 1819 |
+
return second_offset
|
| 1820 |
+
else:
|
| 1821 |
+
def _get_supported_offset(second_offset):
|
| 1822 |
+
# For python pre-3.6, round to full-minutes if that's not the case.
|
| 1823 |
+
# Python's datetime doesn't accept sub-minute timezones. Check
|
| 1824 |
+
# http://python.org/sf/1447945 or https://bugs.python.org/issue5288
|
| 1825 |
+
# for some information.
|
| 1826 |
+
old_offset = second_offset
|
| 1827 |
+
calculated_offset = 60 * ((second_offset + 30) // 60)
|
| 1828 |
+
return calculated_offset
|
| 1829 |
+
|
| 1830 |
+
|
| 1831 |
+
try:
|
| 1832 |
+
# Python 3.7 feature
|
| 1833 |
+
from contextlib import nullcontext as _nullcontext
|
| 1834 |
+
except ImportError:
|
| 1835 |
+
class _nullcontext(object):
|
| 1836 |
+
"""
|
| 1837 |
+
Class for wrapping contexts so that they are passed through in a
|
| 1838 |
+
with statement.
|
| 1839 |
+
"""
|
| 1840 |
+
def __init__(self, context):
|
| 1841 |
+
self.context = context
|
| 1842 |
+
|
| 1843 |
+
def __enter__(self):
|
| 1844 |
+
return self.context
|
| 1845 |
+
|
| 1846 |
+
def __exit__(*args, **kwargs):
|
| 1847 |
+
pass
|
| 1848 |
+
|
| 1849 |
+
# vim:ts=4:sw=4:et
|
.venv/lib/python3.11/site-packages/dateutil/tz/win.py
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 6 |
+
Attempting to import this module on a non-Windows platform will raise an
|
| 7 |
+
:py:obj:`ImportError`.
|
| 8 |
+
"""
|
| 9 |
+
# This code was originally contributed by Jeffrey Harris.
|
| 10 |
+
import datetime
|
| 11 |
+
import struct
|
| 12 |
+
|
| 13 |
+
from six.moves import winreg
|
| 14 |
+
from six import text_type
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
import ctypes
|
| 18 |
+
from ctypes import wintypes
|
| 19 |
+
except ValueError:
|
| 20 |
+
# ValueError is raised on non-Windows systems for some horrible reason.
|
| 21 |
+
raise ImportError("Running tzwin on non-Windows system")
|
| 22 |
+
|
| 23 |
+
from ._common import tzrangebase
|
| 24 |
+
|
| 25 |
+
__all__ = ["tzwin", "tzwinlocal", "tzres"]
|
| 26 |
+
|
| 27 |
+
ONEWEEK = datetime.timedelta(7)
|
| 28 |
+
|
| 29 |
+
TZKEYNAMENT = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"
|
| 30 |
+
TZKEYNAME9X = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones"
|
| 31 |
+
TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _settzkeyname():
|
| 35 |
+
handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
|
| 36 |
+
try:
|
| 37 |
+
winreg.OpenKey(handle, TZKEYNAMENT).Close()
|
| 38 |
+
TZKEYNAME = TZKEYNAMENT
|
| 39 |
+
except WindowsError:
|
| 40 |
+
TZKEYNAME = TZKEYNAME9X
|
| 41 |
+
handle.Close()
|
| 42 |
+
return TZKEYNAME
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
TZKEYNAME = _settzkeyname()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class tzres(object):
|
| 49 |
+
"""
|
| 50 |
+
Class for accessing ``tzres.dll``, which contains timezone name related
|
| 51 |
+
resources.
|
| 52 |
+
|
| 53 |
+
.. versionadded:: 2.5.0
|
| 54 |
+
"""
|
| 55 |
+
p_wchar = ctypes.POINTER(wintypes.WCHAR) # Pointer to a wide char
|
| 56 |
+
|
| 57 |
+
def __init__(self, tzres_loc='tzres.dll'):
|
| 58 |
+
# Load the user32 DLL so we can load strings from tzres
|
| 59 |
+
user32 = ctypes.WinDLL('user32')
|
| 60 |
+
|
| 61 |
+
# Specify the LoadStringW function
|
| 62 |
+
user32.LoadStringW.argtypes = (wintypes.HINSTANCE,
|
| 63 |
+
wintypes.UINT,
|
| 64 |
+
wintypes.LPWSTR,
|
| 65 |
+
ctypes.c_int)
|
| 66 |
+
|
| 67 |
+
self.LoadStringW = user32.LoadStringW
|
| 68 |
+
self._tzres = ctypes.WinDLL(tzres_loc)
|
| 69 |
+
self.tzres_loc = tzres_loc
|
| 70 |
+
|
| 71 |
+
def load_name(self, offset):
|
| 72 |
+
"""
|
| 73 |
+
Load a timezone name from a DLL offset (integer).
|
| 74 |
+
|
| 75 |
+
>>> from dateutil.tzwin import tzres
|
| 76 |
+
>>> tzr = tzres()
|
| 77 |
+
>>> print(tzr.load_name(112))
|
| 78 |
+
'Eastern Standard Time'
|
| 79 |
+
|
| 80 |
+
:param offset:
|
| 81 |
+
A positive integer value referring to a string from the tzres dll.
|
| 82 |
+
|
| 83 |
+
.. note::
|
| 84 |
+
|
| 85 |
+
Offsets found in the registry are generally of the form
|
| 86 |
+
``@tzres.dll,-114``. The offset in this case is 114, not -114.
|
| 87 |
+
|
| 88 |
+
"""
|
| 89 |
+
resource = self.p_wchar()
|
| 90 |
+
lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR)
|
| 91 |
+
nchar = self.LoadStringW(self._tzres._handle, offset, lpBuffer, 0)
|
| 92 |
+
return resource[:nchar]
|
| 93 |
+
|
| 94 |
+
def name_from_string(self, tzname_str):
|
| 95 |
+
"""
|
| 96 |
+
Parse strings as returned from the Windows registry into the time zone
|
| 97 |
+
name as defined in the registry.
|
| 98 |
+
|
| 99 |
+
>>> from dateutil.tzwin import tzres
|
| 100 |
+
>>> tzr = tzres()
|
| 101 |
+
>>> print(tzr.name_from_string('@tzres.dll,-251'))
|
| 102 |
+
'Dateline Daylight Time'
|
| 103 |
+
>>> print(tzr.name_from_string('Eastern Standard Time'))
|
| 104 |
+
'Eastern Standard Time'
|
| 105 |
+
|
| 106 |
+
:param tzname_str:
|
| 107 |
+
A timezone name string as returned from a Windows registry key.
|
| 108 |
+
|
| 109 |
+
:return:
|
| 110 |
+
Returns the localized timezone string from tzres.dll if the string
|
| 111 |
+
is of the form `@tzres.dll,-offset`, else returns the input string.
|
| 112 |
+
"""
|
| 113 |
+
if not tzname_str.startswith('@'):
|
| 114 |
+
return tzname_str
|
| 115 |
+
|
| 116 |
+
name_splt = tzname_str.split(',-')
|
| 117 |
+
try:
|
| 118 |
+
offset = int(name_splt[1])
|
| 119 |
+
except:
|
| 120 |
+
raise ValueError("Malformed timezone string.")
|
| 121 |
+
|
| 122 |
+
return self.load_name(offset)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class tzwinbase(tzrangebase):
|
| 126 |
+
"""tzinfo class based on win32's timezones available in the registry."""
|
| 127 |
+
def __init__(self):
|
| 128 |
+
raise NotImplementedError('tzwinbase is an abstract base class')
|
| 129 |
+
|
| 130 |
+
def __eq__(self, other):
|
| 131 |
+
# Compare on all relevant dimensions, including name.
|
| 132 |
+
if not isinstance(other, tzwinbase):
|
| 133 |
+
return NotImplemented
|
| 134 |
+
|
| 135 |
+
return (self._std_offset == other._std_offset and
|
| 136 |
+
self._dst_offset == other._dst_offset and
|
| 137 |
+
self._stddayofweek == other._stddayofweek and
|
| 138 |
+
self._dstdayofweek == other._dstdayofweek and
|
| 139 |
+
self._stdweeknumber == other._stdweeknumber and
|
| 140 |
+
self._dstweeknumber == other._dstweeknumber and
|
| 141 |
+
self._stdhour == other._stdhour and
|
| 142 |
+
self._dsthour == other._dsthour and
|
| 143 |
+
self._stdminute == other._stdminute and
|
| 144 |
+
self._dstminute == other._dstminute and
|
| 145 |
+
self._std_abbr == other._std_abbr and
|
| 146 |
+
self._dst_abbr == other._dst_abbr)
|
| 147 |
+
|
| 148 |
+
@staticmethod
|
| 149 |
+
def list():
|
| 150 |
+
"""Return a list of all time zones known to the system."""
|
| 151 |
+
with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle:
|
| 152 |
+
with winreg.OpenKey(handle, TZKEYNAME) as tzkey:
|
| 153 |
+
result = [winreg.EnumKey(tzkey, i)
|
| 154 |
+
for i in range(winreg.QueryInfoKey(tzkey)[0])]
|
| 155 |
+
return result
|
| 156 |
+
|
| 157 |
+
def display(self):
|
| 158 |
+
"""
|
| 159 |
+
Return the display name of the time zone.
|
| 160 |
+
"""
|
| 161 |
+
return self._display
|
| 162 |
+
|
| 163 |
+
def transitions(self, year):
|
| 164 |
+
"""
|
| 165 |
+
For a given year, get the DST on and off transition times, expressed
|
| 166 |
+
always on the standard time side. For zones with no transitions, this
|
| 167 |
+
function returns ``None``.
|
| 168 |
+
|
| 169 |
+
:param year:
|
| 170 |
+
The year whose transitions you would like to query.
|
| 171 |
+
|
| 172 |
+
:return:
|
| 173 |
+
Returns a :class:`tuple` of :class:`datetime.datetime` objects,
|
| 174 |
+
``(dston, dstoff)`` for zones with an annual DST transition, or
|
| 175 |
+
``None`` for fixed offset zones.
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
if not self.hasdst:
|
| 179 |
+
return None
|
| 180 |
+
|
| 181 |
+
dston = picknthweekday(year, self._dstmonth, self._dstdayofweek,
|
| 182 |
+
self._dsthour, self._dstminute,
|
| 183 |
+
self._dstweeknumber)
|
| 184 |
+
|
| 185 |
+
dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek,
|
| 186 |
+
self._stdhour, self._stdminute,
|
| 187 |
+
self._stdweeknumber)
|
| 188 |
+
|
| 189 |
+
# Ambiguous dates default to the STD side
|
| 190 |
+
dstoff -= self._dst_base_offset
|
| 191 |
+
|
| 192 |
+
return dston, dstoff
|
| 193 |
+
|
| 194 |
+
def _get_hasdst(self):
|
| 195 |
+
return self._dstmonth != 0
|
| 196 |
+
|
| 197 |
+
@property
|
| 198 |
+
def _dst_base_offset(self):
|
| 199 |
+
return self._dst_base_offset_
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class tzwin(tzwinbase):
|
| 203 |
+
"""
|
| 204 |
+
Time zone object created from the zone info in the Windows registry
|
| 205 |
+
|
| 206 |
+
These are similar to :py:class:`dateutil.tz.tzrange` objects in that
|
| 207 |
+
the time zone data is provided in the format of a single offset rule
|
| 208 |
+
for either 0 or 2 time zone transitions per year.
|
| 209 |
+
|
| 210 |
+
:param: name
|
| 211 |
+
The name of a Windows time zone key, e.g. "Eastern Standard Time".
|
| 212 |
+
The full list of keys can be retrieved with :func:`tzwin.list`.
|
| 213 |
+
"""
|
| 214 |
+
|
| 215 |
+
def __init__(self, name):
|
| 216 |
+
self._name = name
|
| 217 |
+
|
| 218 |
+
with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle:
|
| 219 |
+
tzkeyname = text_type("{kn}\\{name}").format(kn=TZKEYNAME, name=name)
|
| 220 |
+
with winreg.OpenKey(handle, tzkeyname) as tzkey:
|
| 221 |
+
keydict = valuestodict(tzkey)
|
| 222 |
+
|
| 223 |
+
self._std_abbr = keydict["Std"]
|
| 224 |
+
self._dst_abbr = keydict["Dlt"]
|
| 225 |
+
|
| 226 |
+
self._display = keydict["Display"]
|
| 227 |
+
|
| 228 |
+
# See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm
|
| 229 |
+
tup = struct.unpack("=3l16h", keydict["TZI"])
|
| 230 |
+
stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1
|
| 231 |
+
dstoffset = stdoffset-tup[2] # + DaylightBias * -1
|
| 232 |
+
self._std_offset = datetime.timedelta(minutes=stdoffset)
|
| 233 |
+
self._dst_offset = datetime.timedelta(minutes=dstoffset)
|
| 234 |
+
|
| 235 |
+
# for the meaning see the win32 TIME_ZONE_INFORMATION structure docs
|
| 236 |
+
# http://msdn.microsoft.com/en-us/library/windows/desktop/ms725481(v=vs.85).aspx
|
| 237 |
+
(self._stdmonth,
|
| 238 |
+
self._stddayofweek, # Sunday = 0
|
| 239 |
+
self._stdweeknumber, # Last = 5
|
| 240 |
+
self._stdhour,
|
| 241 |
+
self._stdminute) = tup[4:9]
|
| 242 |
+
|
| 243 |
+
(self._dstmonth,
|
| 244 |
+
self._dstdayofweek, # Sunday = 0
|
| 245 |
+
self._dstweeknumber, # Last = 5
|
| 246 |
+
self._dsthour,
|
| 247 |
+
self._dstminute) = tup[12:17]
|
| 248 |
+
|
| 249 |
+
self._dst_base_offset_ = self._dst_offset - self._std_offset
|
| 250 |
+
self.hasdst = self._get_hasdst()
|
| 251 |
+
|
| 252 |
+
def __repr__(self):
|
| 253 |
+
return "tzwin(%s)" % repr(self._name)
|
| 254 |
+
|
| 255 |
+
def __reduce__(self):
|
| 256 |
+
return (self.__class__, (self._name,))
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class tzwinlocal(tzwinbase):
|
| 260 |
+
"""
|
| 261 |
+
Class representing the local time zone information in the Windows registry
|
| 262 |
+
|
| 263 |
+
While :class:`dateutil.tz.tzlocal` makes system calls (via the :mod:`time`
|
| 264 |
+
module) to retrieve time zone information, ``tzwinlocal`` retrieves the
|
| 265 |
+
rules directly from the Windows registry and creates an object like
|
| 266 |
+
:class:`dateutil.tz.tzwin`.
|
| 267 |
+
|
| 268 |
+
Because Windows does not have an equivalent of :func:`time.tzset`, on
|
| 269 |
+
Windows, :class:`dateutil.tz.tzlocal` instances will always reflect the
|
| 270 |
+
time zone settings *at the time that the process was started*, meaning
|
| 271 |
+
changes to the machine's time zone settings during the run of a program
|
| 272 |
+
on Windows will **not** be reflected by :class:`dateutil.tz.tzlocal`.
|
| 273 |
+
Because ``tzwinlocal`` reads the registry directly, it is unaffected by
|
| 274 |
+
this issue.
|
| 275 |
+
"""
|
| 276 |
+
def __init__(self):
|
| 277 |
+
with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle:
|
| 278 |
+
with winreg.OpenKey(handle, TZLOCALKEYNAME) as tzlocalkey:
|
| 279 |
+
keydict = valuestodict(tzlocalkey)
|
| 280 |
+
|
| 281 |
+
self._std_abbr = keydict["StandardName"]
|
| 282 |
+
self._dst_abbr = keydict["DaylightName"]
|
| 283 |
+
|
| 284 |
+
try:
|
| 285 |
+
tzkeyname = text_type('{kn}\\{sn}').format(kn=TZKEYNAME,
|
| 286 |
+
sn=self._std_abbr)
|
| 287 |
+
with winreg.OpenKey(handle, tzkeyname) as tzkey:
|
| 288 |
+
_keydict = valuestodict(tzkey)
|
| 289 |
+
self._display = _keydict["Display"]
|
| 290 |
+
except OSError:
|
| 291 |
+
self._display = None
|
| 292 |
+
|
| 293 |
+
stdoffset = -keydict["Bias"]-keydict["StandardBias"]
|
| 294 |
+
dstoffset = stdoffset-keydict["DaylightBias"]
|
| 295 |
+
|
| 296 |
+
self._std_offset = datetime.timedelta(minutes=stdoffset)
|
| 297 |
+
self._dst_offset = datetime.timedelta(minutes=dstoffset)
|
| 298 |
+
|
| 299 |
+
# For reasons unclear, in this particular key, the day of week has been
|
| 300 |
+
# moved to the END of the SYSTEMTIME structure.
|
| 301 |
+
tup = struct.unpack("=8h", keydict["StandardStart"])
|
| 302 |
+
|
| 303 |
+
(self._stdmonth,
|
| 304 |
+
self._stdweeknumber, # Last = 5
|
| 305 |
+
self._stdhour,
|
| 306 |
+
self._stdminute) = tup[1:5]
|
| 307 |
+
|
| 308 |
+
self._stddayofweek = tup[7]
|
| 309 |
+
|
| 310 |
+
tup = struct.unpack("=8h", keydict["DaylightStart"])
|
| 311 |
+
|
| 312 |
+
(self._dstmonth,
|
| 313 |
+
self._dstweeknumber, # Last = 5
|
| 314 |
+
self._dsthour,
|
| 315 |
+
self._dstminute) = tup[1:5]
|
| 316 |
+
|
| 317 |
+
self._dstdayofweek = tup[7]
|
| 318 |
+
|
| 319 |
+
self._dst_base_offset_ = self._dst_offset - self._std_offset
|
| 320 |
+
self.hasdst = self._get_hasdst()
|
| 321 |
+
|
| 322 |
+
def __repr__(self):
|
| 323 |
+
return "tzwinlocal()"
|
| 324 |
+
|
| 325 |
+
def __str__(self):
|
| 326 |
+
# str will return the standard name, not the daylight name.
|
| 327 |
+
return "tzwinlocal(%s)" % repr(self._std_abbr)
|
| 328 |
+
|
| 329 |
+
def __reduce__(self):
|
| 330 |
+
return (self.__class__, ())
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def picknthweekday(year, month, dayofweek, hour, minute, whichweek):
|
| 334 |
+
""" dayofweek == 0 means Sunday, whichweek 5 means last instance """
|
| 335 |
+
first = datetime.datetime(year, month, 1, hour, minute)
|
| 336 |
+
|
| 337 |
+
# This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6),
|
| 338 |
+
# Because 7 % 7 = 0
|
| 339 |
+
weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1)
|
| 340 |
+
wd = weekdayone + ((whichweek - 1) * ONEWEEK)
|
| 341 |
+
if (wd.month != month):
|
| 342 |
+
wd -= ONEWEEK
|
| 343 |
+
|
| 344 |
+
return wd
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def valuestodict(key):
|
| 348 |
+
"""Convert a registry key's values to a dictionary."""
|
| 349 |
+
dout = {}
|
| 350 |
+
size = winreg.QueryInfoKey(key)[1]
|
| 351 |
+
tz_res = None
|
| 352 |
+
|
| 353 |
+
for i in range(size):
|
| 354 |
+
key_name, value, dtype = winreg.EnumValue(key, i)
|
| 355 |
+
if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN:
|
| 356 |
+
# If it's a DWORD (32-bit integer), it's stored as unsigned - convert
|
| 357 |
+
# that to a proper signed integer
|
| 358 |
+
if value & (1 << 31):
|
| 359 |
+
value = value - (1 << 32)
|
| 360 |
+
elif dtype == winreg.REG_SZ:
|
| 361 |
+
# If it's a reference to the tzres DLL, load the actual string
|
| 362 |
+
if value.startswith('@tzres'):
|
| 363 |
+
tz_res = tz_res or tzres()
|
| 364 |
+
value = tz_res.name_from_string(value)
|
| 365 |
+
|
| 366 |
+
value = value.rstrip('\x00') # Remove trailing nulls
|
| 367 |
+
|
| 368 |
+
dout[key_name] = value
|
| 369 |
+
|
| 370 |
+
return dout
|
.venv/lib/python3.11/site-packages/dateutil/tzwin.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# tzwin has moved to dateutil.tz.win
|
| 2 |
+
from .tz.win import *
|
.venv/lib/python3.11/site-packages/dateutil/utils.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
This module offers general convenience and utility functions for dealing with
|
| 4 |
+
datetimes.
|
| 5 |
+
|
| 6 |
+
.. versionadded:: 2.7.0
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import unicode_literals
|
| 9 |
+
|
| 10 |
+
from datetime import datetime, time
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def today(tzinfo=None):
|
| 14 |
+
"""
|
| 15 |
+
Returns a :py:class:`datetime` representing the current day at midnight
|
| 16 |
+
|
| 17 |
+
:param tzinfo:
|
| 18 |
+
The time zone to attach (also used to determine the current day).
|
| 19 |
+
|
| 20 |
+
:return:
|
| 21 |
+
A :py:class:`datetime.datetime` object representing the current day
|
| 22 |
+
at midnight.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
dt = datetime.now(tzinfo)
|
| 26 |
+
return datetime.combine(dt.date(), time(0, tzinfo=tzinfo))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def default_tzinfo(dt, tzinfo):
|
| 30 |
+
"""
|
| 31 |
+
Sets the ``tzinfo`` parameter on naive datetimes only
|
| 32 |
+
|
| 33 |
+
This is useful for example when you are provided a datetime that may have
|
| 34 |
+
either an implicit or explicit time zone, such as when parsing a time zone
|
| 35 |
+
string.
|
| 36 |
+
|
| 37 |
+
.. doctest::
|
| 38 |
+
|
| 39 |
+
>>> from dateutil.tz import tzoffset
|
| 40 |
+
>>> from dateutil.parser import parse
|
| 41 |
+
>>> from dateutil.utils import default_tzinfo
|
| 42 |
+
>>> dflt_tz = tzoffset("EST", -18000)
|
| 43 |
+
>>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz))
|
| 44 |
+
2014-01-01 12:30:00+00:00
|
| 45 |
+
>>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz))
|
| 46 |
+
2014-01-01 12:30:00-05:00
|
| 47 |
+
|
| 48 |
+
:param dt:
|
| 49 |
+
The datetime on which to replace the time zone
|
| 50 |
+
|
| 51 |
+
:param tzinfo:
|
| 52 |
+
The :py:class:`datetime.tzinfo` subclass instance to assign to
|
| 53 |
+
``dt`` if (and only if) it is naive.
|
| 54 |
+
|
| 55 |
+
:return:
|
| 56 |
+
Returns an aware :py:class:`datetime.datetime`.
|
| 57 |
+
"""
|
| 58 |
+
if dt.tzinfo is not None:
|
| 59 |
+
return dt
|
| 60 |
+
else:
|
| 61 |
+
return dt.replace(tzinfo=tzinfo)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def within_delta(dt1, dt2, delta):
|
| 65 |
+
"""
|
| 66 |
+
Useful for comparing two datetimes that may have a negligible difference
|
| 67 |
+
to be considered equal.
|
| 68 |
+
"""
|
| 69 |
+
delta = abs(delta)
|
| 70 |
+
difference = dt1 - dt2
|
| 71 |
+
return -delta <= difference <= delta
|
.venv/lib/python3.11/site-packages/dateutil/zoneinfo/__init__.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import warnings
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
from tarfile import TarFile
|
| 6 |
+
from pkgutil import get_data
|
| 7 |
+
from io import BytesIO
|
| 8 |
+
|
| 9 |
+
from dateutil.tz import tzfile as _tzfile
|
| 10 |
+
|
| 11 |
+
__all__ = ["get_zonefile_instance", "gettz", "gettz_db_metadata"]
|
| 12 |
+
|
| 13 |
+
ZONEFILENAME = "dateutil-zoneinfo.tar.gz"
|
| 14 |
+
METADATA_FN = 'METADATA'
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class tzfile(_tzfile):
|
| 18 |
+
def __reduce__(self):
|
| 19 |
+
return (gettz, (self._filename,))
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def getzoneinfofile_stream():
|
| 23 |
+
try:
|
| 24 |
+
return BytesIO(get_data(__name__, ZONEFILENAME))
|
| 25 |
+
except IOError as e: # TODO switch to FileNotFoundError?
|
| 26 |
+
warnings.warn("I/O error({0}): {1}".format(e.errno, e.strerror))
|
| 27 |
+
return None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ZoneInfoFile(object):
|
| 31 |
+
def __init__(self, zonefile_stream=None):
|
| 32 |
+
if zonefile_stream is not None:
|
| 33 |
+
with TarFile.open(fileobj=zonefile_stream) as tf:
|
| 34 |
+
self.zones = {zf.name: tzfile(tf.extractfile(zf), filename=zf.name)
|
| 35 |
+
for zf in tf.getmembers()
|
| 36 |
+
if zf.isfile() and zf.name != METADATA_FN}
|
| 37 |
+
# deal with links: They'll point to their parent object. Less
|
| 38 |
+
# waste of memory
|
| 39 |
+
links = {zl.name: self.zones[zl.linkname]
|
| 40 |
+
for zl in tf.getmembers() if
|
| 41 |
+
zl.islnk() or zl.issym()}
|
| 42 |
+
self.zones.update(links)
|
| 43 |
+
try:
|
| 44 |
+
metadata_json = tf.extractfile(tf.getmember(METADATA_FN))
|
| 45 |
+
metadata_str = metadata_json.read().decode('UTF-8')
|
| 46 |
+
self.metadata = json.loads(metadata_str)
|
| 47 |
+
except KeyError:
|
| 48 |
+
# no metadata in tar file
|
| 49 |
+
self.metadata = None
|
| 50 |
+
else:
|
| 51 |
+
self.zones = {}
|
| 52 |
+
self.metadata = None
|
| 53 |
+
|
| 54 |
+
def get(self, name, default=None):
|
| 55 |
+
"""
|
| 56 |
+
Wrapper for :func:`ZoneInfoFile.zones.get`. This is a convenience method
|
| 57 |
+
for retrieving zones from the zone dictionary.
|
| 58 |
+
|
| 59 |
+
:param name:
|
| 60 |
+
The name of the zone to retrieve. (Generally IANA zone names)
|
| 61 |
+
|
| 62 |
+
:param default:
|
| 63 |
+
The value to return in the event of a missing key.
|
| 64 |
+
|
| 65 |
+
.. versionadded:: 2.6.0
|
| 66 |
+
|
| 67 |
+
"""
|
| 68 |
+
return self.zones.get(name, default)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# The current API has gettz as a module function, although in fact it taps into
|
| 72 |
+
# a stateful class. So as a workaround for now, without changing the API, we
|
| 73 |
+
# will create a new "global" class instance the first time a user requests a
|
| 74 |
+
# timezone. Ugly, but adheres to the api.
|
| 75 |
+
#
|
| 76 |
+
# TODO: Remove after deprecation period.
|
| 77 |
+
_CLASS_ZONE_INSTANCE = []
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def get_zonefile_instance(new_instance=False):
|
| 81 |
+
"""
|
| 82 |
+
This is a convenience function which provides a :class:`ZoneInfoFile`
|
| 83 |
+
instance using the data provided by the ``dateutil`` package. By default, it
|
| 84 |
+
caches a single instance of the ZoneInfoFile object and returns that.
|
| 85 |
+
|
| 86 |
+
:param new_instance:
|
| 87 |
+
If ``True``, a new instance of :class:`ZoneInfoFile` is instantiated and
|
| 88 |
+
used as the cached instance for the next call. Otherwise, new instances
|
| 89 |
+
are created only as necessary.
|
| 90 |
+
|
| 91 |
+
:return:
|
| 92 |
+
Returns a :class:`ZoneInfoFile` object.
|
| 93 |
+
|
| 94 |
+
.. versionadded:: 2.6
|
| 95 |
+
"""
|
| 96 |
+
if new_instance:
|
| 97 |
+
zif = None
|
| 98 |
+
else:
|
| 99 |
+
zif = getattr(get_zonefile_instance, '_cached_instance', None)
|
| 100 |
+
|
| 101 |
+
if zif is None:
|
| 102 |
+
zif = ZoneInfoFile(getzoneinfofile_stream())
|
| 103 |
+
|
| 104 |
+
get_zonefile_instance._cached_instance = zif
|
| 105 |
+
|
| 106 |
+
return zif
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def gettz(name):
|
| 110 |
+
"""
|
| 111 |
+
This retrieves a time zone from the local zoneinfo tarball that is packaged
|
| 112 |
+
with dateutil.
|
| 113 |
+
|
| 114 |
+
:param name:
|
| 115 |
+
An IANA-style time zone name, as found in the zoneinfo file.
|
| 116 |
+
|
| 117 |
+
:return:
|
| 118 |
+
Returns a :class:`dateutil.tz.tzfile` time zone object.
|
| 119 |
+
|
| 120 |
+
.. warning::
|
| 121 |
+
It is generally inadvisable to use this function, and it is only
|
| 122 |
+
provided for API compatibility with earlier versions. This is *not*
|
| 123 |
+
equivalent to ``dateutil.tz.gettz()``, which selects an appropriate
|
| 124 |
+
time zone based on the inputs, favoring system zoneinfo. This is ONLY
|
| 125 |
+
for accessing the dateutil-specific zoneinfo (which may be out of
|
| 126 |
+
date compared to the system zoneinfo).
|
| 127 |
+
|
| 128 |
+
.. deprecated:: 2.6
|
| 129 |
+
If you need to use a specific zoneinfofile over the system zoneinfo,
|
| 130 |
+
instantiate a :class:`dateutil.zoneinfo.ZoneInfoFile` object and call
|
| 131 |
+
:func:`dateutil.zoneinfo.ZoneInfoFile.get(name)` instead.
|
| 132 |
+
|
| 133 |
+
Use :func:`get_zonefile_instance` to retrieve an instance of the
|
| 134 |
+
dateutil-provided zoneinfo.
|
| 135 |
+
"""
|
| 136 |
+
warnings.warn("zoneinfo.gettz() will be removed in future versions, "
|
| 137 |
+
"to use the dateutil-provided zoneinfo files, instantiate a "
|
| 138 |
+
"ZoneInfoFile object and use ZoneInfoFile.zones.get() "
|
| 139 |
+
"instead. See the documentation for details.",
|
| 140 |
+
DeprecationWarning)
|
| 141 |
+
|
| 142 |
+
if len(_CLASS_ZONE_INSTANCE) == 0:
|
| 143 |
+
_CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream()))
|
| 144 |
+
return _CLASS_ZONE_INSTANCE[0].zones.get(name)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def gettz_db_metadata():
|
| 148 |
+
""" Get the zonefile metadata
|
| 149 |
+
|
| 150 |
+
See `zonefile_metadata`_
|
| 151 |
+
|
| 152 |
+
:returns:
|
| 153 |
+
A dictionary with the database metadata
|
| 154 |
+
|
| 155 |
+
.. deprecated:: 2.6
|
| 156 |
+
See deprecation warning in :func:`zoneinfo.gettz`. To get metadata,
|
| 157 |
+
query the attribute ``zoneinfo.ZoneInfoFile.metadata``.
|
| 158 |
+
"""
|
| 159 |
+
warnings.warn("zoneinfo.gettz_db_metadata() will be removed in future "
|
| 160 |
+
"versions, to use the dateutil-provided zoneinfo files, "
|
| 161 |
+
"ZoneInfoFile object and query the 'metadata' attribute "
|
| 162 |
+
"instead. See the documentation for details.",
|
| 163 |
+
DeprecationWarning)
|
| 164 |
+
|
| 165 |
+
if len(_CLASS_ZONE_INSTANCE) == 0:
|
| 166 |
+
_CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream()))
|
| 167 |
+
return _CLASS_ZONE_INSTANCE[0].metadata
|
.venv/lib/python3.11/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d3ea52e7b6e968de0d884df1288193596fa95b803db4f92a18279a7398004475
|
| 3 |
+
size 156400
|
.venv/lib/python3.11/site-packages/dateutil/zoneinfo/rebuild.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
import tempfile
|
| 4 |
+
import shutil
|
| 5 |
+
import json
|
| 6 |
+
from subprocess import check_call, check_output
|
| 7 |
+
from tarfile import TarFile
|
| 8 |
+
|
| 9 |
+
from dateutil.zoneinfo import METADATA_FN, ZONEFILENAME
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None):
|
| 13 |
+
"""Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar*
|
| 14 |
+
|
| 15 |
+
filename is the timezone tarball from ``ftp.iana.org/tz``.
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
tmpdir = tempfile.mkdtemp()
|
| 19 |
+
zonedir = os.path.join(tmpdir, "zoneinfo")
|
| 20 |
+
moduledir = os.path.dirname(__file__)
|
| 21 |
+
try:
|
| 22 |
+
with TarFile.open(filename) as tf:
|
| 23 |
+
for name in zonegroups:
|
| 24 |
+
tf.extract(name, tmpdir)
|
| 25 |
+
filepaths = [os.path.join(tmpdir, n) for n in zonegroups]
|
| 26 |
+
|
| 27 |
+
_run_zic(zonedir, filepaths)
|
| 28 |
+
|
| 29 |
+
# write metadata file
|
| 30 |
+
with open(os.path.join(zonedir, METADATA_FN), 'w') as f:
|
| 31 |
+
json.dump(metadata, f, indent=4, sort_keys=True)
|
| 32 |
+
target = os.path.join(moduledir, ZONEFILENAME)
|
| 33 |
+
with TarFile.open(target, "w:%s" % format) as tf:
|
| 34 |
+
for entry in os.listdir(zonedir):
|
| 35 |
+
entrypath = os.path.join(zonedir, entry)
|
| 36 |
+
tf.add(entrypath, entry)
|
| 37 |
+
finally:
|
| 38 |
+
shutil.rmtree(tmpdir)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _run_zic(zonedir, filepaths):
|
| 42 |
+
"""Calls the ``zic`` compiler in a compatible way to get a "fat" binary.
|
| 43 |
+
|
| 44 |
+
Recent versions of ``zic`` default to ``-b slim``, while older versions
|
| 45 |
+
don't even have the ``-b`` option (but default to "fat" binaries). The
|
| 46 |
+
current version of dateutil does not support Version 2+ TZif files, which
|
| 47 |
+
causes problems when used in conjunction with "slim" binaries, so this
|
| 48 |
+
function is used to ensure that we always get a "fat" binary.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
help_text = check_output(["zic", "--help"])
|
| 53 |
+
except OSError as e:
|
| 54 |
+
_print_on_nosuchfile(e)
|
| 55 |
+
raise
|
| 56 |
+
|
| 57 |
+
if b"-b " in help_text:
|
| 58 |
+
bloat_args = ["-b", "fat"]
|
| 59 |
+
else:
|
| 60 |
+
bloat_args = []
|
| 61 |
+
|
| 62 |
+
check_call(["zic"] + bloat_args + ["-d", zonedir] + filepaths)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _print_on_nosuchfile(e):
|
| 66 |
+
"""Print helpful troubleshooting message
|
| 67 |
+
|
| 68 |
+
e is an exception raised by subprocess.check_call()
|
| 69 |
+
|
| 70 |
+
"""
|
| 71 |
+
if e.errno == 2:
|
| 72 |
+
logging.error(
|
| 73 |
+
"Could not find zic. Perhaps you need to install "
|
| 74 |
+
"libc-bin or some other package that provides it, "
|
| 75 |
+
"or it's not in your PATH?")
|
.venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/AUTHORS.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Project Contributors
|
| 2 |
+
|
| 3 |
+
The following people have made contributions to this project either directly
|
| 4 |
+
or in the original `dask.config` module:
|
| 5 |
+
|
| 6 |
+
<!--- Use your GitHub account or any other personal reference URL --->
|
| 7 |
+
<!--- See https://gist.github.com/djhoese/52220272ec73b12eb8f4a29709be110d for auto-generating parts of this list --->
|
| 8 |
+
|
| 9 |
+
- [David Hoese (djhoese)](https://github.com/djhoese)
|
| 10 |
+
- [James Bourbeau (jrbourbeau)](https://github.com/jrbourbeau)
|
| 11 |
+
- [Jim Crist (jcrist)](https://github.com/jcrist)
|
| 12 |
+
- [Joe Hamman (jhamman)](https://github.com/jhamman)
|
| 13 |
+
- [Matt Rocklin (mrocklin)](https://github.com/mrocklin)
|
| 14 |
+
- [Simon Perkins (sjperkins)](https://github.com/sjperkins)
|
.venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
uv
|
.venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/LICENSE.txt
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Copyright (c) 2018- Donfig Developers
|
| 2 |
+
Copyright (c) 2014-2018, Anaconda, Inc. and contributors
|
| 3 |
+
|
| 4 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 5 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 6 |
+
in the Software without restriction, including without limitation the rights
|
| 7 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 8 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 9 |
+
furnished to do so, subject to the following conditions:
|
| 10 |
+
|
| 11 |
+
The above copyright notice and this permission notice shall be included in all
|
| 12 |
+
copies or substantial portions of the Software.
|
| 13 |
+
|
| 14 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 15 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 16 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 17 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 18 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 19 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 20 |
+
SOFTWARE.
|
.venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/METADATA
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|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
Version: 0.8.1.post1
|
| 4 |
+
Summary: Python package for configuring a python package
|
| 5 |
+
Maintainer-email: David Hoese <david.hoese@ssec.wisc.edu>
|
| 6 |
+
License: MIT
|
| 7 |
+
Project-URL: Homepage, https://github.com/pytroll/donfig
|
| 8 |
+
Keywords: task-scheduling parallel numpy pandas pydata
|
| 9 |
+
Classifier: Development Status :: 3 - Alpha
|
| 10 |
+
Classifier: Intended Audience :: Developers
|
| 11 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 12 |
+
Classifier: Operating System :: OS Independent
|
| 13 |
+
Classifier: Programming Language :: Python
|
| 14 |
+
Classifier: Topic :: Scientific/Engineering
|
| 15 |
+
Requires-Python: >=3.8
|
| 16 |
+
Description-Content-Type: text/x-rst
|
| 17 |
+
License-File: LICENSE.txt
|
| 18 |
+
License-File: AUTHORS.md
|
| 19 |
+
Requires-Dist: pyyaml
|
| 20 |
+
Provides-Extra: docs
|
| 21 |
+
Requires-Dist: sphinx >=4.0.0 ; extra == 'docs'
|
| 22 |
+
Requires-Dist: numpydoc ; extra == 'docs'
|
| 23 |
+
Requires-Dist: pytest ; extra == 'docs'
|
| 24 |
+
Requires-Dist: cloudpickle ; extra == 'docs'
|
| 25 |
+
Provides-Extra: test
|
| 26 |
+
Requires-Dist: pytest ; extra == 'test'
|
| 27 |
+
Requires-Dist: cloudpickle ; extra == 'test'
|
| 28 |
+
|
| 29 |
+
Donfig
|
| 30 |
+
======
|
| 31 |
+
|
| 32 |
+
.. image:: https://github.com/pytroll/donfig/workflows/CI/badge.svg?branch=main
|
| 33 |
+
:target: https://github.com/pytroll/donfig/actions?query=workflow%3A%22CI%22
|
| 34 |
+
|
| 35 |
+
.. image:: https://codecov.io/gh/pytroll/donfig/branch/main/graph/badge.svg?token=xmvNtxzdoB
|
| 36 |
+
:target: https://codecov.io/gh/pytroll/donfig
|
| 37 |
+
|
| 38 |
+
.. image:: https://anaconda.org/conda-forge/donfig/badges/version.svg
|
| 39 |
+
:target: https://anaconda.org/conda-forge/donfig/
|
| 40 |
+
|
| 41 |
+
.. image:: https://results.pre-commit.ci/badge/github/pytroll/donfig/main.svg
|
| 42 |
+
:target: https://results.pre-commit.ci/latest/github/pytroll/donfig/main
|
| 43 |
+
:alt: pre-commit.ci status
|
| 44 |
+
|
| 45 |
+
Donfig is a python library meant to make configuration easier for other
|
| 46 |
+
python packages. Donfig can be configured programmatically, by
|
| 47 |
+
environment variables, or from YAML files in standard locations. The
|
| 48 |
+
below examples show the basics of using donfig. For more details see the
|
| 49 |
+
official `documentation <https://donfig.readthedocs.io/en/latest/>`_.
|
| 50 |
+
|
| 51 |
+
Installation
|
| 52 |
+
------------
|
| 53 |
+
|
| 54 |
+
Donfig can be installed from PyPI using pip:
|
| 55 |
+
|
| 56 |
+
.. code-block:: bash
|
| 57 |
+
|
| 58 |
+
pip install donfig
|
| 59 |
+
|
| 60 |
+
Or with conda using the conda-forge channel:
|
| 61 |
+
|
| 62 |
+
.. code-block:: bash
|
| 63 |
+
|
| 64 |
+
conda install -c conda-forge donfig
|
| 65 |
+
|
| 66 |
+
Using Donfig
|
| 67 |
+
------------
|
| 68 |
+
|
| 69 |
+
Create the package-wide configuration object for your package named `mypkg`:
|
| 70 |
+
|
| 71 |
+
.. code-block:: python
|
| 72 |
+
|
| 73 |
+
# mypkg/__init__.py
|
| 74 |
+
from donfig import Config
|
| 75 |
+
config = Config('mypkg')
|
| 76 |
+
|
| 77 |
+
Use the configuration object:
|
| 78 |
+
|
| 79 |
+
.. code-block:: python
|
| 80 |
+
|
| 81 |
+
from mypkg import config
|
| 82 |
+
important_val = config.get('important_key')
|
| 83 |
+
if important_val:
|
| 84 |
+
# do something
|
| 85 |
+
else:
|
| 86 |
+
# something else
|
| 87 |
+
|
| 88 |
+
Set configuration in Python
|
| 89 |
+
---------------------------
|
| 90 |
+
|
| 91 |
+
Configuration can be modified in python before code using it is called:
|
| 92 |
+
|
| 93 |
+
.. code-block:: python
|
| 94 |
+
|
| 95 |
+
# mypkg/work.py
|
| 96 |
+
from mypkg import config
|
| 97 |
+
config.set(important_key=5)
|
| 98 |
+
|
| 99 |
+
# use the configuration
|
| 100 |
+
|
| 101 |
+
Donfig configurations can also be changed as a context manager:
|
| 102 |
+
|
| 103 |
+
.. code-block:: python
|
| 104 |
+
|
| 105 |
+
config.set(other_key=True)
|
| 106 |
+
|
| 107 |
+
with config.set(other_key=False):
|
| 108 |
+
print(config.get('other_key')) # False
|
| 109 |
+
|
| 110 |
+
print(config.get('other_key')) # True
|
| 111 |
+
|
| 112 |
+
Configure from environment variables
|
| 113 |
+
------------------------------------
|
| 114 |
+
|
| 115 |
+
Environment variables are automatically loaded when the Config object is
|
| 116 |
+
created. Any environment variable starting with the name of the config
|
| 117 |
+
object in all capital letters and an underscore will be loaded in to
|
| 118 |
+
the config object:
|
| 119 |
+
|
| 120 |
+
.. code-block:: bash
|
| 121 |
+
|
| 122 |
+
export MYPKG_MY_KEY="a value"
|
| 123 |
+
|
| 124 |
+
And can be accessed in python:
|
| 125 |
+
|
| 126 |
+
.. code-block:: python
|
| 127 |
+
|
| 128 |
+
from mypkg import config
|
| 129 |
+
print(config.get('my_key'))
|
| 130 |
+
|
| 131 |
+
Configure from YAML file
|
| 132 |
+
------------------------
|
| 133 |
+
|
| 134 |
+
Donfig will also automatically load any YAML configuration files found in
|
| 135 |
+
specific paths. The default paths:
|
| 136 |
+
|
| 137 |
+
- ~/.config/<config name>/
|
| 138 |
+
- /etc/<config name>/
|
| 139 |
+
- <sys.prefix>/etc/<config name>/
|
| 140 |
+
|
| 141 |
+
Note the `/etc/<config name>/` directory can also be specified with the
|
| 142 |
+
environment variable `DASK_ROOT_CONFIG`. Also note that
|
| 143 |
+
`~/.config/<package name>` (or other location specified with `DASK_CONFIG`)
|
| 144 |
+
can be created as a custom user configuration file for easier user
|
| 145 |
+
customization (see documentation for details).
|
| 146 |
+
|
| 147 |
+
History
|
| 148 |
+
-------
|
| 149 |
+
|
| 150 |
+
Donfig is based on the original configuration logic of the `dask` library.
|
| 151 |
+
The code has been modified to use a config object instead of a global
|
| 152 |
+
configuration dictionary. This makes the configuration logic of dask available
|
| 153 |
+
to everyone. The name "donfig" is a shortening of "dask.config", the original
|
| 154 |
+
dask module that implemented this functionality.
|
| 155 |
+
|
| 156 |
+
License
|
| 157 |
+
-------
|
| 158 |
+
|
| 159 |
+
Original code from the dask library was distributed under the license
|
| 160 |
+
specified in `DASK_LICENSE.txt`. In November 2018 this code was migrated to
|
| 161 |
+
the Donfig project under the MIT license described in `LICENSE.txt`. The full
|
| 162 |
+
copyright for this project is therefore::
|
| 163 |
+
|
| 164 |
+
Copyright (c) 2018 Donfig Developers
|
| 165 |
+
Copyright (c) 2014-2018, Anaconda, Inc. and contributors
|
.venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/RECORD
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
donfig-0.8.1.post1.dist-info/AUTHORS.md,sha256=mp1PfyBVoP3pgaDXX-AjG_fDHFZSVBdZRs3slpUV8_Y,671
|
| 2 |
+
donfig-0.8.1.post1.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
|
| 3 |
+
donfig-0.8.1.post1.dist-info/LICENSE.txt,sha256=wpcwsj3cPi58xvGB3ftW54HRHoVsINY1pfAdyL22Q8Y,1119
|
| 4 |
+
donfig-0.8.1.post1.dist-info/METADATA,sha256=MLya3HI_njJ6LRqoMCsxA2XV6Wt-RJPHLJppzezed0g,4955
|
| 5 |
+
donfig-0.8.1.post1.dist-info/RECORD,,
|
| 6 |
+
donfig-0.8.1.post1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 7 |
+
donfig-0.8.1.post1.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
|
| 8 |
+
donfig-0.8.1.post1.dist-info/top_level.txt,sha256=i48N4rDEfZzJ51PkFvZ4qud3H1AFoCnN8BI2H9uDg64,7
|
| 9 |
+
donfig/__init__.py,sha256=r11sMeyl9pAnSMeBdsS6pNLku_VgwgWBFwhpHMWPtho,142
|
| 10 |
+
donfig/_lock.py,sha256=nVtKd1W9GMmTtrnw-wQguM1R3K0znlK5Uu-pCUp5ulY,3425
|
| 11 |
+
donfig/config_obj.py,sha256=PCIND5O33fVC6Vdd-59Z2EI2r2DMlM-aN0cgdB_pNBA,24644
|
| 12 |
+
donfig/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 13 |
+
donfig/tests/test_config.py,sha256=6Jq2TWgi0SpYqhHoc_1HcWAYnDwnd2b-1QCsrPCZmPQ,19003
|
| 14 |
+
donfig/tests/test_lock.py,sha256=oQKwtLP5gm6I8rRZTA2HB1L2adc1Oky-ay34gQ3UCuM,2567
|
| 15 |
+
donfig/utils.py,sha256=yV5D1eqHMV50CbwgN9A0HljNWghVZnjT1w4pEh12i-w,1732
|
| 16 |
+
donfig/version.py,sha256=5ahCPOK0MzoeH6n2ePA0U6CVtQm3O9vAUKL7my0GubM,503
|
.venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/REQUESTED
ADDED
|
File without changes
|
.venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: bdist_wheel (0.43.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
.venv/lib/python3.11/site-packages/donfig-0.8.1.post1.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
donfig
|
.venv/lib/python3.11/site-packages/donfig/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import version # noqa
|
| 2 |
+
from .config_obj import Config, deserialize, serialize # noqa
|
| 3 |
+
|
| 4 |
+
__version__ = version.get_versions()["version"]
|
.venv/lib/python3.11/site-packages/donfig/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (460 Bytes). View file
|
|
|
.venv/lib/python3.11/site-packages/donfig/__pycache__/_lock.cpython-311.pyc
ADDED
|
Binary file (4.13 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/donfig/__pycache__/config_obj.cpython-311.pyc
ADDED
|
Binary file (32.7 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/donfig/__pycache__/version.cpython-311.pyc
ADDED
|
Binary file (620 Bytes). View file
|
|
|
.venv/lib/python3.11/site-packages/donfig/_lock.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2022 Donfig Developers
|
| 4 |
+
# Copyright (c) 2014-2022, Anaconda, Inc. and contributors
|
| 5 |
+
#
|
| 6 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 7 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 8 |
+
# in the Software without restriction, including without limitation the rights
|
| 9 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 10 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 11 |
+
# furnished to do so, subject to the following conditions:
|
| 12 |
+
#
|
| 13 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 14 |
+
# copies or substantial portions of the Software.
|
| 15 |
+
#
|
| 16 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 17 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 18 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 19 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 20 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 21 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 22 |
+
# SOFTWARE.
|
| 23 |
+
"""Config synchronization locks ported from upstream dask.
|
| 24 |
+
|
| 25 |
+
Originally part of Dask and stored in the dask/utils.py module. This module
|
| 26 |
+
should be considered private and should not be imported directly by users.
|
| 27 |
+
There are no guarantees that this module will exist in the future.
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
import uuid
|
| 32 |
+
from threading import Lock
|
| 33 |
+
from weakref import WeakValueDictionary
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class SerializableLock:
|
| 37 |
+
"""A Serializable per-process Lock.
|
| 38 |
+
|
| 39 |
+
This wraps a normal ``threading.Lock`` object and satisfies the same
|
| 40 |
+
interface. However, this lock can also be serialized and sent to different
|
| 41 |
+
processes. It will not block concurrent operations between processes (for
|
| 42 |
+
this you should look at ``multiprocessing.Lock`` or ``locket.lock_file``
|
| 43 |
+
but will consistently deserialize into the same lock.
|
| 44 |
+
|
| 45 |
+
So if we make a lock in one process::
|
| 46 |
+
|
| 47 |
+
lock = SerializableLock()
|
| 48 |
+
|
| 49 |
+
And then send it over to another process multiple times::
|
| 50 |
+
|
| 51 |
+
bytes = pickle.dumps(lock)
|
| 52 |
+
a = pickle.loads(bytes)
|
| 53 |
+
b = pickle.loads(bytes)
|
| 54 |
+
|
| 55 |
+
Then the deserialized objects will operate as though they were the same
|
| 56 |
+
lock, and collide as appropriate.
|
| 57 |
+
|
| 58 |
+
This is useful for consistently protecting resources on a per-process
|
| 59 |
+
level.
|
| 60 |
+
|
| 61 |
+
The creation of locks is itself not threadsafe.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
_locks: WeakValueDictionary = WeakValueDictionary()
|
| 65 |
+
|
| 66 |
+
def __init__(self, token=None):
|
| 67 |
+
self.token = token or str(uuid.uuid4())
|
| 68 |
+
if self.token in SerializableLock._locks:
|
| 69 |
+
self.lock = SerializableLock._locks[self.token]
|
| 70 |
+
else:
|
| 71 |
+
self.lock = Lock()
|
| 72 |
+
SerializableLock._locks[self.token] = self.lock
|
| 73 |
+
|
| 74 |
+
def acquire(self, *args, **kwargs):
|
| 75 |
+
return self.lock.acquire(*args, **kwargs)
|
| 76 |
+
|
| 77 |
+
def release(self, *args, **kwargs):
|
| 78 |
+
return self.lock.release(*args, **kwargs)
|
| 79 |
+
|
| 80 |
+
def __enter__(self):
|
| 81 |
+
self.lock.__enter__()
|
| 82 |
+
|
| 83 |
+
def __exit__(self, *args):
|
| 84 |
+
self.lock.__exit__(*args)
|
| 85 |
+
|
| 86 |
+
def locked(self):
|
| 87 |
+
return self.lock.locked()
|
| 88 |
+
|
| 89 |
+
def __getstate__(self):
|
| 90 |
+
return self.token
|
| 91 |
+
|
| 92 |
+
def __setstate__(self, token):
|
| 93 |
+
self.__init__(token)
|
| 94 |
+
|
| 95 |
+
def __str__(self):
|
| 96 |
+
return f"<{self.__class__.__name__}: {self.token}>"
|
| 97 |
+
|
| 98 |
+
__repr__ = __str__
|
.venv/lib/python3.11/site-packages/donfig/config_obj.py
ADDED
|
@@ -0,0 +1,794 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2018-2019 Donfig Developers
|
| 4 |
+
# Copyright (c) 2014-2018, Anaconda, Inc. and contributors
|
| 5 |
+
#
|
| 6 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 7 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 8 |
+
# in the Software without restriction, including without limitation the rights
|
| 9 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 10 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 11 |
+
# furnished to do so, subject to the following conditions:
|
| 12 |
+
#
|
| 13 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 14 |
+
# copies or substantial portions of the Software.
|
| 15 |
+
#
|
| 16 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 17 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 18 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 19 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 20 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 21 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 22 |
+
# SOFTWARE.
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import ast
|
| 26 |
+
import base64
|
| 27 |
+
import contextlib
|
| 28 |
+
import json
|
| 29 |
+
import os
|
| 30 |
+
import pprint
|
| 31 |
+
import site
|
| 32 |
+
import sys
|
| 33 |
+
import warnings
|
| 34 |
+
from collections.abc import Mapping, Sequence
|
| 35 |
+
from contextlib import nullcontext
|
| 36 |
+
from copy import deepcopy
|
| 37 |
+
from typing import Any, Literal, MutableMapping
|
| 38 |
+
|
| 39 |
+
import yaml
|
| 40 |
+
|
| 41 |
+
from ._lock import SerializableLock
|
| 42 |
+
|
| 43 |
+
no_default = "__no_default__"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def canonical_name(k: str, config: Mapping[str, Any]) -> str:
|
| 47 |
+
"""Return the canonical name for a key.
|
| 48 |
+
|
| 49 |
+
Handles user choice of '-' or '_' conventions by standardizing on whichever
|
| 50 |
+
version was set first. If a key already exists in either hyphen or
|
| 51 |
+
underscore form, the existing version is the canonical name. If neither
|
| 52 |
+
version exists the original key is used as is.
|
| 53 |
+
"""
|
| 54 |
+
try:
|
| 55 |
+
if k in config:
|
| 56 |
+
return k
|
| 57 |
+
except TypeError:
|
| 58 |
+
# config is not a mapping, return the same name as provided
|
| 59 |
+
return k
|
| 60 |
+
|
| 61 |
+
altk = k.replace("_", "-") if "_" in k else k.replace("-", "_")
|
| 62 |
+
|
| 63 |
+
if altk in config:
|
| 64 |
+
return altk
|
| 65 |
+
|
| 66 |
+
return k
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def update(
|
| 70 |
+
old: MutableMapping[str, Any],
|
| 71 |
+
new: Mapping[str, Any],
|
| 72 |
+
priority: Literal["old", "new", "new-defaults"] = "new",
|
| 73 |
+
defaults: Mapping | None = None,
|
| 74 |
+
) -> Mapping[str, Any]:
|
| 75 |
+
"""Update a nested dictionary with values from another
|
| 76 |
+
|
| 77 |
+
This is like dict.update except that it smoothly merges nested values
|
| 78 |
+
|
| 79 |
+
This operates in-place and modifies old
|
| 80 |
+
|
| 81 |
+
Parameters
|
| 82 |
+
----------
|
| 83 |
+
priority: string {'old', 'new', 'new-defaults'}
|
| 84 |
+
If new (default) then the new dictionary has preference.
|
| 85 |
+
Otherwise the old dictionary does.
|
| 86 |
+
If 'new-defaults', a mapping should be given of the current defaults.
|
| 87 |
+
Only if a value in ``old`` matches the current default, it will be
|
| 88 |
+
updated with ``new``.
|
| 89 |
+
|
| 90 |
+
Examples
|
| 91 |
+
--------
|
| 92 |
+
>>> a = {'x': 1, 'y': {'a': 2}}
|
| 93 |
+
>>> b = {'x': 2, 'y': {'b': 3}}
|
| 94 |
+
>>> update(a, b) # doctest: +SKIP
|
| 95 |
+
{'x': 2, 'y': {'a': 2, 'b': 3}}
|
| 96 |
+
|
| 97 |
+
>>> a = {'x': 1, 'y': {'a': 2}}
|
| 98 |
+
>>> b = {'x': 2, 'y': {'b': 3}}
|
| 99 |
+
>>> update(a, b, priority='old') # doctest: +SKIP
|
| 100 |
+
{'x': 1, 'y': {'a': 2, 'b': 3}}
|
| 101 |
+
|
| 102 |
+
>>> d = {'x': 0, 'y': {'a': 2}}
|
| 103 |
+
>>> a = {'x': 1, 'y': {'a': 2}}
|
| 104 |
+
>>> b = {'x': 2, 'y': {'a': 3, 'b': 3}}
|
| 105 |
+
>>> update(a, b, priority='new-defaults', defaults=d) # doctest: +SKIP
|
| 106 |
+
{'x': 1, 'y': {'a': 3, 'b': 3}}
|
| 107 |
+
|
| 108 |
+
See Also
|
| 109 |
+
--------
|
| 110 |
+
donfig.config_obj.merge
|
| 111 |
+
|
| 112 |
+
"""
|
| 113 |
+
for k, v in new.items():
|
| 114 |
+
k = canonical_name(k, old)
|
| 115 |
+
|
| 116 |
+
if isinstance(v, Mapping):
|
| 117 |
+
if k not in old or old[k] is None:
|
| 118 |
+
old[k] = {}
|
| 119 |
+
update(
|
| 120 |
+
old[k],
|
| 121 |
+
v,
|
| 122 |
+
priority=priority,
|
| 123 |
+
defaults=defaults.get(k) if defaults else None,
|
| 124 |
+
)
|
| 125 |
+
else:
|
| 126 |
+
if (
|
| 127 |
+
priority == "new"
|
| 128 |
+
or k not in old
|
| 129 |
+
or (priority == "new-defaults" and defaults and k in defaults and defaults[k] == old[k])
|
| 130 |
+
):
|
| 131 |
+
old[k] = v
|
| 132 |
+
|
| 133 |
+
return old
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def merge(*dicts: Mapping) -> dict:
|
| 137 |
+
"""Update a sequence of nested dictionaries
|
| 138 |
+
|
| 139 |
+
This prefers the values in the latter dictionaries to those in the former
|
| 140 |
+
|
| 141 |
+
Examples
|
| 142 |
+
--------
|
| 143 |
+
>>> a = {'x': 1, 'y': {'a': 2}}
|
| 144 |
+
>>> b = {'y': {'b': 3}}
|
| 145 |
+
>>> merge(a, b) # doctest: +SKIP
|
| 146 |
+
{'x': 1, 'y': {'a': 2, 'b': 3}}
|
| 147 |
+
|
| 148 |
+
See Also
|
| 149 |
+
--------
|
| 150 |
+
donfig.config_obj.update
|
| 151 |
+
|
| 152 |
+
"""
|
| 153 |
+
result: dict = {}
|
| 154 |
+
for d in dicts:
|
| 155 |
+
update(result, d)
|
| 156 |
+
return result
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def collect_yaml(paths: Sequence[str]) -> list[dict]:
|
| 160 |
+
"""Collect configuration from yaml files
|
| 161 |
+
|
| 162 |
+
This searches through a list of paths, expands to find all yaml or json
|
| 163 |
+
files, and then parses each file.
|
| 164 |
+
|
| 165 |
+
"""
|
| 166 |
+
# Find all paths
|
| 167 |
+
file_paths = []
|
| 168 |
+
for path in paths:
|
| 169 |
+
if os.path.exists(path):
|
| 170 |
+
if os.path.isdir(path):
|
| 171 |
+
try:
|
| 172 |
+
file_paths.extend(
|
| 173 |
+
sorted(
|
| 174 |
+
os.path.join(path, p)
|
| 175 |
+
for p in os.listdir(path)
|
| 176 |
+
if os.path.splitext(p)[1].lower() in (".json", ".yaml", ".yml")
|
| 177 |
+
)
|
| 178 |
+
)
|
| 179 |
+
except OSError:
|
| 180 |
+
# Ignore permission errors
|
| 181 |
+
pass
|
| 182 |
+
else:
|
| 183 |
+
file_paths.append(path)
|
| 184 |
+
|
| 185 |
+
configs = []
|
| 186 |
+
|
| 187 |
+
# Parse yaml files
|
| 188 |
+
for path in file_paths:
|
| 189 |
+
config = _load_config_file(path)
|
| 190 |
+
if config is not None:
|
| 191 |
+
configs.append(config)
|
| 192 |
+
|
| 193 |
+
return configs
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _load_config_file(path: str) -> dict | None:
|
| 197 |
+
try:
|
| 198 |
+
with open(path) as f:
|
| 199 |
+
config = yaml.safe_load(f.read())
|
| 200 |
+
except OSError:
|
| 201 |
+
# Ignore permission errors
|
| 202 |
+
return None
|
| 203 |
+
except Exception as exc:
|
| 204 |
+
raise ValueError(f"A config file at {path!r} is malformed, original error " f"message:\n\n{exc}") from None
|
| 205 |
+
if config is not None and not isinstance(config, dict):
|
| 206 |
+
raise ValueError(
|
| 207 |
+
f"A config file at {path!r} is malformed - config files must have "
|
| 208 |
+
f"a dict as the top level object, got a {type(config).__name__} instead"
|
| 209 |
+
)
|
| 210 |
+
return config
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def collect_env(
|
| 214 |
+
prefix: str, env: Mapping[str, str] | None = None, deprecations: MutableMapping[str, str | None] | None = None
|
| 215 |
+
) -> dict:
|
| 216 |
+
"""Collect config from environment variables
|
| 217 |
+
|
| 218 |
+
This grabs environment variables of the form "DASK_FOO__BAR_BAZ=123" and
|
| 219 |
+
turns these into config variables of the form ``{"foo": {"bar-baz": 123}}``
|
| 220 |
+
It transforms the key and value in the following way:
|
| 221 |
+
|
| 222 |
+
- Lower-cases the key text
|
| 223 |
+
- Treats ``__`` (double-underscore) as nested access
|
| 224 |
+
- Calls ``ast.literal_eval`` on the value
|
| 225 |
+
|
| 226 |
+
"""
|
| 227 |
+
if env is None:
|
| 228 |
+
env = os.environ
|
| 229 |
+
|
| 230 |
+
serial_env = f"{prefix}_INTERNAL_INHERIT_CONFIG"
|
| 231 |
+
if serial_env in env:
|
| 232 |
+
d = deserialize(env[serial_env])
|
| 233 |
+
else:
|
| 234 |
+
d = {}
|
| 235 |
+
|
| 236 |
+
prefix_len = len(prefix)
|
| 237 |
+
for name, value in env.items():
|
| 238 |
+
if name.startswith(prefix):
|
| 239 |
+
varname = name[prefix_len:].lower().replace("__", ".")
|
| 240 |
+
try:
|
| 241 |
+
d[varname] = ast.literal_eval(value)
|
| 242 |
+
except (SyntaxError, ValueError):
|
| 243 |
+
d[varname] = value
|
| 244 |
+
|
| 245 |
+
result: dict = {}
|
| 246 |
+
# fake thread lock to use set functionality
|
| 247 |
+
lock = nullcontext()
|
| 248 |
+
ConfigSet(result, lock, deprecations or {}, d)
|
| 249 |
+
return result
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class ConfigSet:
|
| 253 |
+
"""Temporarily set configuration values within a context manager
|
| 254 |
+
|
| 255 |
+
Note, this class should be used directly from the `Config`
|
| 256 |
+
object via the :meth:`donfig.Config.set` method.
|
| 257 |
+
|
| 258 |
+
Examples
|
| 259 |
+
--------
|
| 260 |
+
>>> from donfig.config_obj import ConfigSet
|
| 261 |
+
>>> import mypkg
|
| 262 |
+
>>> with ConfigSet(mypkg.config, {'foo': 123}):
|
| 263 |
+
... pass
|
| 264 |
+
|
| 265 |
+
See Also
|
| 266 |
+
--------
|
| 267 |
+
donfig.Config.set
|
| 268 |
+
donfig.Config.get
|
| 269 |
+
|
| 270 |
+
"""
|
| 271 |
+
|
| 272 |
+
def __init__(
|
| 273 |
+
self,
|
| 274 |
+
config: MutableMapping,
|
| 275 |
+
lock: SerializableLock | contextlib.AbstractContextManager,
|
| 276 |
+
deprecations: MutableMapping[str, str | None],
|
| 277 |
+
arg: Mapping | None = None,
|
| 278 |
+
**kwargs,
|
| 279 |
+
):
|
| 280 |
+
with lock:
|
| 281 |
+
self.config = config
|
| 282 |
+
self.deprecations = deprecations
|
| 283 |
+
self._record: list[tuple[str, tuple, Any]] = []
|
| 284 |
+
|
| 285 |
+
if arg is not None:
|
| 286 |
+
for key, value in arg.items():
|
| 287 |
+
key = self._check_deprecations(key)
|
| 288 |
+
self._assign(key.split("."), value, config)
|
| 289 |
+
if kwargs:
|
| 290 |
+
for key, value in kwargs.items():
|
| 291 |
+
key = key.replace("__", ".")
|
| 292 |
+
key = self._check_deprecations(key)
|
| 293 |
+
self._assign(key.split("."), value, config)
|
| 294 |
+
|
| 295 |
+
def _check_deprecations(self, key: str):
|
| 296 |
+
"""Check if the provided value has been renamed or removed.
|
| 297 |
+
|
| 298 |
+
Parameters
|
| 299 |
+
----------
|
| 300 |
+
key : str
|
| 301 |
+
The configuration key to check
|
| 302 |
+
|
| 303 |
+
Returns
|
| 304 |
+
-------
|
| 305 |
+
new: str
|
| 306 |
+
The proper key, whether the original (if no deprecation) or the aliased
|
| 307 |
+
value
|
| 308 |
+
|
| 309 |
+
"""
|
| 310 |
+
if key in self.deprecations:
|
| 311 |
+
new = self.deprecations[key]
|
| 312 |
+
if new:
|
| 313 |
+
warnings.warn(f"Configuration key {key!r} has been deprecated. " f"Please use {new!r} instead")
|
| 314 |
+
return new
|
| 315 |
+
else:
|
| 316 |
+
raise ValueError(f"Configuration value {key!r} has been removed")
|
| 317 |
+
else:
|
| 318 |
+
return key
|
| 319 |
+
|
| 320 |
+
def __enter__(self):
|
| 321 |
+
return self.config
|
| 322 |
+
|
| 323 |
+
def __exit__(self, type, value, traceback):
|
| 324 |
+
for op, path, value in reversed(self._record):
|
| 325 |
+
d = self.config
|
| 326 |
+
if op == "replace":
|
| 327 |
+
for key in path[:-1]:
|
| 328 |
+
d = d.setdefault(key, {})
|
| 329 |
+
d[path[-1]] = value
|
| 330 |
+
else: # insert
|
| 331 |
+
for key in path[:-1]:
|
| 332 |
+
try:
|
| 333 |
+
d = d[key]
|
| 334 |
+
except KeyError:
|
| 335 |
+
break
|
| 336 |
+
else:
|
| 337 |
+
d.pop(path[-1], None)
|
| 338 |
+
|
| 339 |
+
def _assign(
|
| 340 |
+
self,
|
| 341 |
+
keys: Sequence[str],
|
| 342 |
+
value: Any,
|
| 343 |
+
d: MutableMapping,
|
| 344 |
+
path: tuple[str, ...] = (),
|
| 345 |
+
record: bool = True,
|
| 346 |
+
) -> None:
|
| 347 |
+
"""Assign value into a nested configuration dictionary
|
| 348 |
+
|
| 349 |
+
Parameters
|
| 350 |
+
----------
|
| 351 |
+
keys : Sequence[str]
|
| 352 |
+
The nested path of keys to assign the value, similar to toolz.put_in
|
| 353 |
+
value: object
|
| 354 |
+
d : dict
|
| 355 |
+
The part of the nested dictionary into which we want to assign the
|
| 356 |
+
value
|
| 357 |
+
path : tuple[str], optional
|
| 358 |
+
Used internally to hold the path of old values
|
| 359 |
+
record : bool, optional
|
| 360 |
+
Whether this operation needs to be recorded to allow for rollback.
|
| 361 |
+
|
| 362 |
+
"""
|
| 363 |
+
key = canonical_name(keys[0], d)
|
| 364 |
+
path = path + (key,)
|
| 365 |
+
|
| 366 |
+
if len(keys) == 1:
|
| 367 |
+
if record:
|
| 368 |
+
if key in d:
|
| 369 |
+
self._record.append(("replace", path, d[key]))
|
| 370 |
+
else:
|
| 371 |
+
self._record.append(("insert", path, None))
|
| 372 |
+
d[key] = value
|
| 373 |
+
else:
|
| 374 |
+
if key not in d:
|
| 375 |
+
if record:
|
| 376 |
+
self._record.append(("insert", path, None))
|
| 377 |
+
d[key] = {}
|
| 378 |
+
# No need to record subsequent operations after an insert
|
| 379 |
+
record = False
|
| 380 |
+
self._assign(keys[1:], value, d[key], path, record=record)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def expand_environment_variables(config):
|
| 384 |
+
"""Expand environment variables in a nested config dictionary
|
| 385 |
+
|
| 386 |
+
This function will recursively search through any nested dictionaries
|
| 387 |
+
and/or lists.
|
| 388 |
+
|
| 389 |
+
Parameters
|
| 390 |
+
----------
|
| 391 |
+
config : dict, iterable, or str
|
| 392 |
+
Input object to search for environment variables
|
| 393 |
+
|
| 394 |
+
Returns
|
| 395 |
+
-------
|
| 396 |
+
config : same type as input
|
| 397 |
+
|
| 398 |
+
Examples
|
| 399 |
+
--------
|
| 400 |
+
>>> expand_environment_variables({'x': [1, 2, '$USER']}) # doctest: +SKIP
|
| 401 |
+
{'x': [1, 2, 'my-username']}
|
| 402 |
+
|
| 403 |
+
"""
|
| 404 |
+
if isinstance(config, Mapping):
|
| 405 |
+
return {k: expand_environment_variables(v) for k, v in config.items()}
|
| 406 |
+
elif isinstance(config, str):
|
| 407 |
+
return os.path.expandvars(config)
|
| 408 |
+
elif isinstance(config, (list, tuple, set)):
|
| 409 |
+
return type(config)([expand_environment_variables(v) for v in config])
|
| 410 |
+
else:
|
| 411 |
+
return config
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
class Config:
|
| 415 |
+
def __init__(
|
| 416 |
+
self,
|
| 417 |
+
name: str,
|
| 418 |
+
defaults: list[Mapping[str, Any]] | None = None,
|
| 419 |
+
paths: list[str] | None = None,
|
| 420 |
+
env: Mapping[str, str] | None = None,
|
| 421 |
+
env_var: str | None = None,
|
| 422 |
+
root_env_var: str | None = None,
|
| 423 |
+
env_prefix: str | None = None,
|
| 424 |
+
deprecations: Mapping[str, str | None] | None = None,
|
| 425 |
+
):
|
| 426 |
+
if root_env_var is None:
|
| 427 |
+
root_env_var = f"{name.upper()}_ROOT_CONFIG"
|
| 428 |
+
if paths is None:
|
| 429 |
+
paths = [
|
| 430 |
+
os.getenv(root_env_var, f"/etc/{name}"),
|
| 431 |
+
os.path.join(sys.prefix, "etc", name),
|
| 432 |
+
*[os.path.join(prefix, "etc", name) for prefix in site.PREFIXES],
|
| 433 |
+
os.path.join(os.path.expanduser("~"), ".config", name),
|
| 434 |
+
]
|
| 435 |
+
|
| 436 |
+
if env_prefix is None:
|
| 437 |
+
env_prefix = f"{name.upper()}_"
|
| 438 |
+
if env is None:
|
| 439 |
+
env = os.environ
|
| 440 |
+
if env_var is None:
|
| 441 |
+
env_var = f"{name.upper()}_CONFIG"
|
| 442 |
+
if env_var in os.environ:
|
| 443 |
+
main_path = os.environ[env_var]
|
| 444 |
+
paths.append(main_path)
|
| 445 |
+
else:
|
| 446 |
+
main_path = os.path.join(os.path.expanduser("~"), ".config", name)
|
| 447 |
+
if deprecations is None:
|
| 448 |
+
deprecations = {}
|
| 449 |
+
|
| 450 |
+
# Remove duplicate paths while preserving ordering
|
| 451 |
+
paths = list(reversed(list(dict.fromkeys(reversed(paths)))))
|
| 452 |
+
|
| 453 |
+
self.name = name
|
| 454 |
+
self.env_prefix = env_prefix
|
| 455 |
+
self.env = env
|
| 456 |
+
self.main_path = main_path
|
| 457 |
+
self.paths = paths
|
| 458 |
+
self.defaults = defaults or []
|
| 459 |
+
self.deprecations = deprecations
|
| 460 |
+
|
| 461 |
+
self.config: MutableMapping[str, Any] = {}
|
| 462 |
+
self.config_lock = SerializableLock()
|
| 463 |
+
self.refresh()
|
| 464 |
+
|
| 465 |
+
def __contains__(self, item):
|
| 466 |
+
try:
|
| 467 |
+
self[item]
|
| 468 |
+
return True
|
| 469 |
+
except (TypeError, IndexError, KeyError):
|
| 470 |
+
return False
|
| 471 |
+
|
| 472 |
+
def __getitem__(self, item):
|
| 473 |
+
return self.get(item)
|
| 474 |
+
|
| 475 |
+
def pprint(self, **kwargs):
|
| 476 |
+
return pprint.pprint(self.config, **kwargs)
|
| 477 |
+
|
| 478 |
+
def collect(self, paths: list[str] | None = None, env: Mapping[str, str] | None = None) -> dict:
|
| 479 |
+
"""Collect configuration from paths and environment variables
|
| 480 |
+
|
| 481 |
+
Parameters
|
| 482 |
+
----------
|
| 483 |
+
paths : list[str]
|
| 484 |
+
A list of paths to search for yaml config files. Defaults to the
|
| 485 |
+
paths passed when creating this object.
|
| 486 |
+
|
| 487 |
+
env : Mapping[str, str]
|
| 488 |
+
The system environment variables to search through. Defaults to
|
| 489 |
+
the environment dictionary passed when creating this object.
|
| 490 |
+
|
| 491 |
+
Returns
|
| 492 |
+
-------
|
| 493 |
+
config: dict
|
| 494 |
+
|
| 495 |
+
See Also
|
| 496 |
+
--------
|
| 497 |
+
donfig.Config.refresh: collect configuration and update into primary config
|
| 498 |
+
|
| 499 |
+
"""
|
| 500 |
+
if paths is None:
|
| 501 |
+
paths = self.paths
|
| 502 |
+
if env is None:
|
| 503 |
+
env = self.env
|
| 504 |
+
configs = []
|
| 505 |
+
|
| 506 |
+
if yaml:
|
| 507 |
+
configs.extend(collect_yaml(paths=paths))
|
| 508 |
+
|
| 509 |
+
configs.append(collect_env(self.env_prefix, env=env))
|
| 510 |
+
|
| 511 |
+
return merge(*configs)
|
| 512 |
+
|
| 513 |
+
def refresh(self, **kwargs) -> None:
|
| 514 |
+
"""Update configuration by re-reading yaml files and env variables.
|
| 515 |
+
|
| 516 |
+
This goes through the following stages:
|
| 517 |
+
|
| 518 |
+
1. Clearing out all old configuration
|
| 519 |
+
2. Updating from the stored defaults from downstream libraries
|
| 520 |
+
(see update_defaults)
|
| 521 |
+
3. Updating from yaml files and environment variables
|
| 522 |
+
|
| 523 |
+
Note that some functionality only checks configuration once at startup and
|
| 524 |
+
may not change behavior, even if configuration changes. It is recommended
|
| 525 |
+
to restart your python process if convenient to ensure that new
|
| 526 |
+
configuration changes take place.
|
| 527 |
+
|
| 528 |
+
See Also
|
| 529 |
+
--------
|
| 530 |
+
donfig.Config.collect: for parameters
|
| 531 |
+
donfig.Config.update_defaults
|
| 532 |
+
|
| 533 |
+
"""
|
| 534 |
+
self.clear()
|
| 535 |
+
|
| 536 |
+
for d in self.defaults:
|
| 537 |
+
update(self.config, d, priority="old")
|
| 538 |
+
|
| 539 |
+
update(self.config, self.collect(**kwargs))
|
| 540 |
+
|
| 541 |
+
def get(self, key: str, default: Any = no_default) -> Any:
|
| 542 |
+
"""Get elements from global config
|
| 543 |
+
|
| 544 |
+
Use '.' for nested access
|
| 545 |
+
|
| 546 |
+
Examples
|
| 547 |
+
--------
|
| 548 |
+
>>> from donfig import Config
|
| 549 |
+
>>> config = Config('mypkg')
|
| 550 |
+
>>> config.get('foo') # doctest: +SKIP
|
| 551 |
+
{'x': 1, 'y': 2}
|
| 552 |
+
|
| 553 |
+
>>> config.get('foo.x') # doctest: +SKIP
|
| 554 |
+
1
|
| 555 |
+
|
| 556 |
+
>>> config.get('foo.x.y', default=123) # doctest: +SKIP
|
| 557 |
+
123
|
| 558 |
+
|
| 559 |
+
See Also
|
| 560 |
+
--------
|
| 561 |
+
donfig.Config.set
|
| 562 |
+
|
| 563 |
+
"""
|
| 564 |
+
keys = key.split(".")
|
| 565 |
+
result = self.config
|
| 566 |
+
for k in keys:
|
| 567 |
+
k = canonical_name(k, result)
|
| 568 |
+
try:
|
| 569 |
+
result = result[k]
|
| 570 |
+
except (TypeError, IndexError, KeyError):
|
| 571 |
+
if default is not no_default:
|
| 572 |
+
return default
|
| 573 |
+
else:
|
| 574 |
+
raise
|
| 575 |
+
return result
|
| 576 |
+
|
| 577 |
+
def update_defaults(self, new: Mapping) -> None:
|
| 578 |
+
"""Add a new set of defaults to the configuration
|
| 579 |
+
|
| 580 |
+
It does two things:
|
| 581 |
+
|
| 582 |
+
1. Add the defaults to a collection to be used by refresh() later
|
| 583 |
+
2. Updates the global config with the new configuration.
|
| 584 |
+
Old values are prioritized over new ones, unless the current value
|
| 585 |
+
is the old default, in which case it's updated to the new default.
|
| 586 |
+
|
| 587 |
+
"""
|
| 588 |
+
current_defaults = merge(*self.defaults)
|
| 589 |
+
self.defaults.append(new)
|
| 590 |
+
update(self.config, new, priority="new-defaults", defaults=current_defaults)
|
| 591 |
+
|
| 592 |
+
def to_dict(self):
|
| 593 |
+
"""Return dictionary copy of configuration.
|
| 594 |
+
|
| 595 |
+
.. warning::
|
| 596 |
+
|
| 597 |
+
This will copy all keys and values. This includes values that
|
| 598 |
+
may cause unwanted side effects depending on what values exist
|
| 599 |
+
in the current configuration.
|
| 600 |
+
|
| 601 |
+
"""
|
| 602 |
+
return deepcopy(self.config)
|
| 603 |
+
|
| 604 |
+
def clear(self):
|
| 605 |
+
"""Clear all existing configuration."""
|
| 606 |
+
self.config.clear()
|
| 607 |
+
|
| 608 |
+
def merge(self, *dicts):
|
| 609 |
+
"""Merge this configuration with multiple dictionaries.
|
| 610 |
+
|
| 611 |
+
See :func:`~donfig.config_obj.merge` for more information.
|
| 612 |
+
|
| 613 |
+
"""
|
| 614 |
+
self.config = merge(self.config, dicts)
|
| 615 |
+
|
| 616 |
+
def update(self, new, priority="new"):
|
| 617 |
+
"""Update the internal configuration dictionary with `new`.
|
| 618 |
+
|
| 619 |
+
See :func:`~donfig.config_obj.update` for more information.
|
| 620 |
+
|
| 621 |
+
"""
|
| 622 |
+
self.config = update(self.config, new, priority=priority)
|
| 623 |
+
|
| 624 |
+
def expand_environment_variables(self) -> None:
|
| 625 |
+
"""Expand any environment variables in this configuration in-place.
|
| 626 |
+
|
| 627 |
+
See :func:`~donfig.config_obj.expand_environment_variables` for more information.
|
| 628 |
+
|
| 629 |
+
"""
|
| 630 |
+
self.config = expand_environment_variables(self.config)
|
| 631 |
+
|
| 632 |
+
def rename(self, aliases: Mapping) -> None:
|
| 633 |
+
"""Rename old keys to new keys
|
| 634 |
+
|
| 635 |
+
This helps migrate older configuration versions over time
|
| 636 |
+
|
| 637 |
+
"""
|
| 638 |
+
old = []
|
| 639 |
+
new = {}
|
| 640 |
+
for o, n in aliases.items():
|
| 641 |
+
value = self.get(o, None)
|
| 642 |
+
if value is not None:
|
| 643 |
+
old.append(o)
|
| 644 |
+
new[n] = value
|
| 645 |
+
|
| 646 |
+
for k in old:
|
| 647 |
+
del self.config[canonical_name(k, self.config)] # TODO: support nested keys
|
| 648 |
+
|
| 649 |
+
self.set(new)
|
| 650 |
+
|
| 651 |
+
def set(self, arg=None, **kwargs):
|
| 652 |
+
"""Set configuration values within a context manager.
|
| 653 |
+
|
| 654 |
+
Parameters
|
| 655 |
+
----------
|
| 656 |
+
arg : mapping or None, optional
|
| 657 |
+
A mapping of configuration key-value pairs to set.
|
| 658 |
+
**kwargs :
|
| 659 |
+
Additional key-value pairs to set. If ``arg`` is provided, values set
|
| 660 |
+
in ``arg`` will be applied before those in ``kwargs``.
|
| 661 |
+
Double-underscores (``__``) in keyword arguments will be replaced with
|
| 662 |
+
``.``, allowing nested values to be easily set.
|
| 663 |
+
|
| 664 |
+
Examples
|
| 665 |
+
--------
|
| 666 |
+
>>> from donfig import Config
|
| 667 |
+
>>> config = Config('mypkg')
|
| 668 |
+
|
| 669 |
+
Set ``'foo.bar'`` in a context, by providing a mapping.
|
| 670 |
+
|
| 671 |
+
>>> with config.set({'foo.bar': 123}):
|
| 672 |
+
... pass
|
| 673 |
+
|
| 674 |
+
Set ``'foo.bar'`` in a context, by providing a keyword argument.
|
| 675 |
+
|
| 676 |
+
>>> with config.set(foo__bar=123):
|
| 677 |
+
... pass
|
| 678 |
+
|
| 679 |
+
Set ``'foo.bar'`` globally.
|
| 680 |
+
|
| 681 |
+
>>> config.set(foo__bar=123) # doctest: +SKIP
|
| 682 |
+
|
| 683 |
+
See Also
|
| 684 |
+
--------
|
| 685 |
+
donfig.Config.get
|
| 686 |
+
|
| 687 |
+
"""
|
| 688 |
+
return ConfigSet(self.config, self.config_lock, self.deprecations, arg=arg, **kwargs)
|
| 689 |
+
|
| 690 |
+
def ensure_file(self, source: str, destination: str | None = None, comment: bool = True) -> None:
|
| 691 |
+
"""Copy file to default location if it does not already exist
|
| 692 |
+
|
| 693 |
+
This tries to move a default configuration file to a default location if
|
| 694 |
+
if does not already exist. It also comments out that file by default.
|
| 695 |
+
|
| 696 |
+
This is to be used by downstream modules that may
|
| 697 |
+
have default configuration files that they wish to include in the default
|
| 698 |
+
configuration path.
|
| 699 |
+
|
| 700 |
+
Parameters
|
| 701 |
+
----------
|
| 702 |
+
source : string, filename
|
| 703 |
+
Source configuration file, typically within a source directory.
|
| 704 |
+
destination : string, directory
|
| 705 |
+
Destination directory. Configurable by ``<CONFIG NAME>_CONFIG``
|
| 706 |
+
environment variable, falling back to ~/.config/<config name>.
|
| 707 |
+
comment : bool, True by default
|
| 708 |
+
Whether or not to comment out the config file when copying.
|
| 709 |
+
|
| 710 |
+
"""
|
| 711 |
+
if destination is None:
|
| 712 |
+
destination = self.main_path
|
| 713 |
+
|
| 714 |
+
# destination is a file and already exists, never overwrite
|
| 715 |
+
if os.path.isfile(destination):
|
| 716 |
+
return
|
| 717 |
+
|
| 718 |
+
# If destination is not an existing file, interpret as a directory,
|
| 719 |
+
# use the source basename as the filename
|
| 720 |
+
directory = destination
|
| 721 |
+
destination = os.path.join(directory, os.path.basename(source))
|
| 722 |
+
|
| 723 |
+
try:
|
| 724 |
+
if not os.path.exists(destination):
|
| 725 |
+
os.makedirs(directory, exist_ok=True)
|
| 726 |
+
|
| 727 |
+
# Atomically create destination. Parallel testing discovered
|
| 728 |
+
# a race condition where a process can be busy creating the
|
| 729 |
+
# destination while another process reads an empty config file.
|
| 730 |
+
tmp = "%s.tmp.%d" % (destination, os.getpid())
|
| 731 |
+
with open(source) as f:
|
| 732 |
+
lines = list(f)
|
| 733 |
+
|
| 734 |
+
if comment:
|
| 735 |
+
lines = ["# " + line if line.strip() and not line.startswith("#") else line for line in lines]
|
| 736 |
+
|
| 737 |
+
with open(tmp, "w") as f:
|
| 738 |
+
f.write("".join(lines))
|
| 739 |
+
|
| 740 |
+
try:
|
| 741 |
+
os.rename(tmp, destination)
|
| 742 |
+
except OSError:
|
| 743 |
+
os.remove(tmp)
|
| 744 |
+
except OSError:
|
| 745 |
+
pass
|
| 746 |
+
|
| 747 |
+
def serialize(self) -> str:
|
| 748 |
+
"""Serialize conifg data into a string.
|
| 749 |
+
|
| 750 |
+
See :func:`serialize` for more information.
|
| 751 |
+
|
| 752 |
+
"""
|
| 753 |
+
return serialize(self.config)
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def serialize(data: Any) -> str:
|
| 757 |
+
"""Serialize config data into a string.
|
| 758 |
+
|
| 759 |
+
Typically used to pass config via the ``MYPKG_INTERNAL_INHERIT_CONFIG`` environment variable.
|
| 760 |
+
|
| 761 |
+
Parameters
|
| 762 |
+
----------
|
| 763 |
+
data: json-serializable object
|
| 764 |
+
The data to serialize
|
| 765 |
+
|
| 766 |
+
Returns
|
| 767 |
+
-------
|
| 768 |
+
serialized_data: str
|
| 769 |
+
The serialized data as a string
|
| 770 |
+
|
| 771 |
+
"""
|
| 772 |
+
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
| 773 |
+
|
| 774 |
+
|
| 775 |
+
def deserialize(data: str) -> Any:
|
| 776 |
+
"""De-serialize config data into the original object.
|
| 777 |
+
|
| 778 |
+
Typically used when receiving config via the
|
| 779 |
+
``MYPKG_INTERNAL_INHERIT_CONFIG`` environment variable. This is
|
| 780 |
+
automatically called when a :class:`Config` is created and environment
|
| 781 |
+
variables are loaded.
|
| 782 |
+
|
| 783 |
+
Parameters
|
| 784 |
+
----------
|
| 785 |
+
data: str
|
| 786 |
+
String serialized by :func:`donfig.serialize`
|
| 787 |
+
|
| 788 |
+
Returns
|
| 789 |
+
-------
|
| 790 |
+
deserialized_data: obj
|
| 791 |
+
The de-serialized data
|
| 792 |
+
|
| 793 |
+
"""
|
| 794 |
+
return json.loads(base64.urlsafe_b64decode(data.encode()).decode())
|
.venv/lib/python3.11/site-packages/donfig/tests/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.11/site-packages/donfig/tests/test_config.py
ADDED
|
@@ -0,0 +1,649 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2018 Donfig Developers
|
| 4 |
+
# Copyright (c) 2014-2018, Anaconda, Inc. and contributors
|
| 5 |
+
#
|
| 6 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 7 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 8 |
+
# in the Software without restriction, including without limitation the rights
|
| 9 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 10 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 11 |
+
# furnished to do so, subject to the following conditions:
|
| 12 |
+
#
|
| 13 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 14 |
+
# copies or substantial portions of the Software.
|
| 15 |
+
#
|
| 16 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 17 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 18 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 19 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 20 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 21 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 22 |
+
# SOFTWARE.
|
| 23 |
+
import os
|
| 24 |
+
import site
|
| 25 |
+
import stat
|
| 26 |
+
import subprocess
|
| 27 |
+
import sys
|
| 28 |
+
from collections import OrderedDict
|
| 29 |
+
from contextlib import contextmanager
|
| 30 |
+
|
| 31 |
+
import cloudpickle
|
| 32 |
+
import pytest
|
| 33 |
+
import yaml
|
| 34 |
+
|
| 35 |
+
from donfig.config_obj import (
|
| 36 |
+
Config,
|
| 37 |
+
canonical_name,
|
| 38 |
+
collect_env,
|
| 39 |
+
collect_yaml,
|
| 40 |
+
deserialize,
|
| 41 |
+
expand_environment_variables,
|
| 42 |
+
merge,
|
| 43 |
+
serialize,
|
| 44 |
+
update,
|
| 45 |
+
)
|
| 46 |
+
from donfig.utils import tmpfile
|
| 47 |
+
|
| 48 |
+
CONFIG_NAME = "mytest"
|
| 49 |
+
ENV_PREFIX = CONFIG_NAME.upper() + "_"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_canonical_name():
|
| 53 |
+
c = {"foo-bar": 1, "fizz_buzz": 2}
|
| 54 |
+
assert canonical_name("foo-bar", c) == "foo-bar"
|
| 55 |
+
assert canonical_name("foo_bar", c) == "foo-bar"
|
| 56 |
+
assert canonical_name("fizz-buzz", c) == "fizz_buzz"
|
| 57 |
+
assert canonical_name("fizz_buzz", c) == "fizz_buzz"
|
| 58 |
+
assert canonical_name("new-key", c) == "new-key"
|
| 59 |
+
assert canonical_name("new_key", c) == "new_key"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_update():
|
| 63 |
+
a = {"x": 1, "y": {"a": 1}}
|
| 64 |
+
b = {"x": 2, "z": 3, "y": OrderedDict({"b": 2})}
|
| 65 |
+
update(b, a)
|
| 66 |
+
assert b == {"x": 1, "y": {"a": 1, "b": 2}, "z": 3}
|
| 67 |
+
|
| 68 |
+
a = {"x": 1, "y": {"a": 1}}
|
| 69 |
+
b = {"x": 2, "z": 3, "y": {"a": 3, "b": 2}}
|
| 70 |
+
update(b, a, priority="old")
|
| 71 |
+
assert b == {"x": 2, "y": {"a": 3, "b": 2}, "z": 3}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_update_new_defaults():
|
| 75 |
+
d = {"x": 1, "y": 1, "z": {"a": 1, "b": 1}}
|
| 76 |
+
o = {"x": 1, "y": 2, "z": {"a": 1, "b": 2}, "c": 2, "c2": {"d": 2}}
|
| 77 |
+
n = {"x": 3, "y": 3, "z": OrderedDict({"a": 3, "b": 3}), "c": 3, "c2": {"d": 3}}
|
| 78 |
+
assert update(o, n, priority="new-defaults", defaults=d) == {
|
| 79 |
+
"x": 3,
|
| 80 |
+
"y": 2,
|
| 81 |
+
"z": {"a": 3, "b": 2},
|
| 82 |
+
"c": 2,
|
| 83 |
+
"c2": {"d": 2},
|
| 84 |
+
}
|
| 85 |
+
assert update(o, n, priority="new-defaults", defaults=o) == update(o, n, priority="new")
|
| 86 |
+
assert update(o, n, priority="new-defaults", defaults=None) == update(o, n, priority="old")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_update_defaults():
|
| 90 |
+
defaults = [
|
| 91 |
+
{"a": 1, "b": {"c": 1}},
|
| 92 |
+
{"a": 2, "b": {"d": 2}},
|
| 93 |
+
]
|
| 94 |
+
config = Config(CONFIG_NAME, defaults=defaults)
|
| 95 |
+
current = {"a": 2, "b": {"c": 1, "d": 3}, "extra": 0}
|
| 96 |
+
config.update(current)
|
| 97 |
+
new = {"a": 0, "b": {"c": 0, "d": 0}, "new-extra": 0}
|
| 98 |
+
config.update_defaults(new)
|
| 99 |
+
|
| 100 |
+
assert defaults == [
|
| 101 |
+
{"a": 1, "b": {"c": 1}},
|
| 102 |
+
{"a": 2, "b": {"d": 2}},
|
| 103 |
+
{"a": 0, "b": {"c": 0, "d": 0}, "new-extra": 0},
|
| 104 |
+
]
|
| 105 |
+
assert config.to_dict() == {"a": 0, "b": {"c": 0, "d": 3}, "extra": 0, "new-extra": 0}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_merge():
|
| 109 |
+
a = {"x": 1, "y": {"a": 1}}
|
| 110 |
+
b = {"x": 2, "z": 3, "y": {"b": 2}}
|
| 111 |
+
|
| 112 |
+
expected = {"x": 2, "y": {"a": 1, "b": 2}, "z": 3}
|
| 113 |
+
|
| 114 |
+
c = merge(a, b)
|
| 115 |
+
assert c == expected
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def test_collect_yaml_paths():
|
| 119 |
+
a = {"x": 1, "y": {"a": 1}}
|
| 120 |
+
b = {"x": 2, "z": 3, "y": {"b": 2}}
|
| 121 |
+
|
| 122 |
+
expected = {
|
| 123 |
+
"x": 2,
|
| 124 |
+
"y": {"a": 1, "b": 2},
|
| 125 |
+
"z": 3,
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
with tmpfile(extension="yaml") as fn1:
|
| 129 |
+
with tmpfile(extension="yaml") as fn2:
|
| 130 |
+
with open(fn1, "w") as f:
|
| 131 |
+
yaml.dump(a, f)
|
| 132 |
+
with open(fn2, "w") as f:
|
| 133 |
+
yaml.dump(b, f)
|
| 134 |
+
|
| 135 |
+
config = merge(*collect_yaml(paths=[fn1, fn2]))
|
| 136 |
+
assert config == expected
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def test_collect_yaml_dir():
|
| 140 |
+
a = {"x": 1, "y": {"a": 1}}
|
| 141 |
+
b = {"x": 2, "z": 3, "y": {"b": 2}}
|
| 142 |
+
|
| 143 |
+
expected = {
|
| 144 |
+
"x": 2,
|
| 145 |
+
"y": {"a": 1, "b": 2},
|
| 146 |
+
"z": 3,
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
with tmpfile() as dirname:
|
| 150 |
+
os.mkdir(dirname)
|
| 151 |
+
with open(os.path.join(dirname, "a.yaml"), mode="w") as f:
|
| 152 |
+
yaml.dump(a, f)
|
| 153 |
+
with open(os.path.join(dirname, "b.yaml"), mode="w") as f:
|
| 154 |
+
yaml.dump(b, f)
|
| 155 |
+
|
| 156 |
+
config = merge(*collect_yaml(paths=[dirname]))
|
| 157 |
+
assert config == expected
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
@contextmanager
|
| 161 |
+
def no_read_permissions(path):
|
| 162 |
+
perm_orig = stat.S_IMODE(os.stat(path).st_mode)
|
| 163 |
+
perm_new = perm_orig ^ stat.S_IREAD
|
| 164 |
+
try:
|
| 165 |
+
os.chmod(path, perm_new)
|
| 166 |
+
yield
|
| 167 |
+
finally:
|
| 168 |
+
os.chmod(path, perm_orig)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@pytest.mark.skipif(sys.platform == "win32", reason="Can't make writeonly file on windows")
|
| 172 |
+
@pytest.mark.parametrize("kind", ["directory", "file"])
|
| 173 |
+
def test_collect_yaml_permission_errors(tmpdir, kind):
|
| 174 |
+
a = {"x": 1, "y": 2}
|
| 175 |
+
b = {"y": 3, "z": 4}
|
| 176 |
+
|
| 177 |
+
dir_path = str(tmpdir)
|
| 178 |
+
a_path = os.path.join(dir_path, "a.yaml")
|
| 179 |
+
b_path = os.path.join(dir_path, "b.yaml")
|
| 180 |
+
|
| 181 |
+
with open(a_path, mode="w") as f:
|
| 182 |
+
yaml.dump(a, f)
|
| 183 |
+
with open(b_path, mode="w") as f:
|
| 184 |
+
yaml.dump(b, f)
|
| 185 |
+
|
| 186 |
+
if kind == "directory":
|
| 187 |
+
cant_read = dir_path
|
| 188 |
+
expected = {}
|
| 189 |
+
else:
|
| 190 |
+
cant_read = a_path
|
| 191 |
+
expected = b
|
| 192 |
+
|
| 193 |
+
with no_read_permissions(cant_read):
|
| 194 |
+
config = merge(*collect_yaml(paths=[dir_path]))
|
| 195 |
+
assert config == expected
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def test_collect_yaml_malformed_file(tmpdir):
|
| 199 |
+
dir_path = str(tmpdir)
|
| 200 |
+
fil_path = os.path.join(dir_path, "a.yaml")
|
| 201 |
+
|
| 202 |
+
with open(fil_path, mode="wb") as f:
|
| 203 |
+
f.write(b"{")
|
| 204 |
+
|
| 205 |
+
with pytest.raises(ValueError) as rec:
|
| 206 |
+
collect_yaml(paths=[dir_path])
|
| 207 |
+
assert repr(fil_path) in str(rec.value)
|
| 208 |
+
assert "is malformed" in str(rec.value)
|
| 209 |
+
assert "original error message" in str(rec.value)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def test_collect_yaml_no_top_level_dict(tmpdir):
|
| 213 |
+
dir_path = str(tmpdir)
|
| 214 |
+
fil_path = os.path.join(dir_path, "a.yaml")
|
| 215 |
+
|
| 216 |
+
with open(fil_path, mode="wb") as f:
|
| 217 |
+
f.write(b"[1234]")
|
| 218 |
+
|
| 219 |
+
with pytest.raises(ValueError) as rec:
|
| 220 |
+
collect_yaml(paths=[dir_path])
|
| 221 |
+
assert repr(fil_path) in str(rec.value)
|
| 222 |
+
assert "is malformed" in str(rec.value)
|
| 223 |
+
assert "must have a dict" in str(rec.value)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def test_env():
|
| 227 |
+
env = {
|
| 228 |
+
ENV_PREFIX + "A_B": "123",
|
| 229 |
+
ENV_PREFIX + "C": "True",
|
| 230 |
+
ENV_PREFIX + "D": "hello",
|
| 231 |
+
ENV_PREFIX + "E__X": "123",
|
| 232 |
+
ENV_PREFIX + "E__Y": "456",
|
| 233 |
+
ENV_PREFIX + "F": '[1, 2, "3"]',
|
| 234 |
+
ENV_PREFIX + "G": "/not/parsable/as/literal",
|
| 235 |
+
"FOO": "not included",
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
expected = {
|
| 239 |
+
"a_b": 123,
|
| 240 |
+
"c": True,
|
| 241 |
+
"d": "hello",
|
| 242 |
+
"e": {"x": 123, "y": 456},
|
| 243 |
+
"f": [1, 2, "3"],
|
| 244 |
+
"g": "/not/parsable/as/literal",
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
res = collect_env(CONFIG_NAME.upper() + "_", env)
|
| 248 |
+
assert res == expected
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def test_collect():
|
| 252 |
+
a = {"x": 1, "y": {"a": 1}}
|
| 253 |
+
b = {"x": 2, "z": 3, "y": {"b": 2}}
|
| 254 |
+
env = {ENV_PREFIX + "W": 4}
|
| 255 |
+
|
| 256 |
+
expected = {
|
| 257 |
+
"w": 4,
|
| 258 |
+
"x": 2,
|
| 259 |
+
"y": {"a": 1, "b": 2},
|
| 260 |
+
"z": 3,
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
config = Config(CONFIG_NAME)
|
| 264 |
+
with tmpfile(extension="yaml") as fn1:
|
| 265 |
+
with tmpfile(extension="yaml") as fn2:
|
| 266 |
+
with open(fn1, "w") as f:
|
| 267 |
+
yaml.dump(a, f)
|
| 268 |
+
with open(fn2, "w") as f:
|
| 269 |
+
yaml.dump(b, f)
|
| 270 |
+
|
| 271 |
+
config = config.collect([fn1, fn2], env=env)
|
| 272 |
+
assert config == expected
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def test_collect_env_none():
|
| 276 |
+
os.environ[ENV_PREFIX + "FOO"] = "bar"
|
| 277 |
+
config = Config(CONFIG_NAME)
|
| 278 |
+
try:
|
| 279 |
+
config = config.collect([])
|
| 280 |
+
assert config == {"foo": "bar"}
|
| 281 |
+
finally:
|
| 282 |
+
del os.environ[ENV_PREFIX + "FOO"]
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def test_get():
|
| 286 |
+
test_config = Config(CONFIG_NAME)
|
| 287 |
+
test_config.config = {"x": 1, "y": {"a": 2}}
|
| 288 |
+
|
| 289 |
+
assert test_config.get("x") == 1
|
| 290 |
+
assert test_config["x"] == 1
|
| 291 |
+
assert test_config.get("y.a") == 2
|
| 292 |
+
assert test_config["y.a"] == 2
|
| 293 |
+
assert test_config.get("y.b", 123) == 123
|
| 294 |
+
with pytest.raises(KeyError):
|
| 295 |
+
test_config.get("y.b")
|
| 296 |
+
with pytest.raises(KeyError):
|
| 297 |
+
test_config["y.b"]
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def test_contains():
|
| 301 |
+
test_config = Config(CONFIG_NAME)
|
| 302 |
+
test_config.config = {"x": 1, "y": {"a": 2}}
|
| 303 |
+
|
| 304 |
+
assert "x" in test_config
|
| 305 |
+
assert "y.a" in test_config
|
| 306 |
+
assert "y.b" not in test_config
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def test_ensure_file(tmpdir):
|
| 310 |
+
a = {"x": 1, "y": {"a": 1}}
|
| 311 |
+
b = {"x": 123}
|
| 312 |
+
|
| 313 |
+
source = os.path.join(str(tmpdir), "source.yaml")
|
| 314 |
+
dest = os.path.join(str(tmpdir), "dest")
|
| 315 |
+
destination = os.path.join(dest, "source.yaml")
|
| 316 |
+
|
| 317 |
+
with open(source, "w") as f:
|
| 318 |
+
yaml.dump(a, f)
|
| 319 |
+
|
| 320 |
+
config = Config(CONFIG_NAME)
|
| 321 |
+
config.ensure_file(source=source, destination=dest, comment=False)
|
| 322 |
+
|
| 323 |
+
with open(destination) as f:
|
| 324 |
+
result = yaml.safe_load(f)
|
| 325 |
+
assert result == a
|
| 326 |
+
|
| 327 |
+
# don't overwrite old config files
|
| 328 |
+
with open(source, "w") as f:
|
| 329 |
+
yaml.dump(b, f)
|
| 330 |
+
|
| 331 |
+
config.ensure_file(source=source, destination=dest, comment=False)
|
| 332 |
+
|
| 333 |
+
with open(destination) as f:
|
| 334 |
+
result = yaml.safe_load(f)
|
| 335 |
+
assert result == a
|
| 336 |
+
|
| 337 |
+
os.remove(destination)
|
| 338 |
+
|
| 339 |
+
# Write again, now with comments
|
| 340 |
+
config.ensure_file(source=source, destination=dest, comment=True)
|
| 341 |
+
|
| 342 |
+
with open(destination) as f:
|
| 343 |
+
text = f.read()
|
| 344 |
+
assert "123" in text
|
| 345 |
+
|
| 346 |
+
with open(destination) as f:
|
| 347 |
+
result = yaml.safe_load(f)
|
| 348 |
+
assert not result
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def test_set():
|
| 352 |
+
config = Config(CONFIG_NAME)
|
| 353 |
+
with config.set(abc=123):
|
| 354 |
+
assert config.config["abc"] == 123
|
| 355 |
+
with config.set(abc=456):
|
| 356 |
+
assert config.config["abc"] == 456
|
| 357 |
+
assert config.config["abc"] == 123
|
| 358 |
+
|
| 359 |
+
assert "abc" not in config.config
|
| 360 |
+
|
| 361 |
+
with config.set({"abc": 123}):
|
| 362 |
+
assert config.config["abc"] == 123
|
| 363 |
+
assert "abc" not in config.config
|
| 364 |
+
|
| 365 |
+
with config.set({"abc.x": 1, "abc.y": 2, "abc.z.a": 3}):
|
| 366 |
+
assert config.config["abc"] == {"x": 1, "y": 2, "z": {"a": 3}}
|
| 367 |
+
assert "abc" not in config.config
|
| 368 |
+
|
| 369 |
+
config.config = {}
|
| 370 |
+
config.set({"abc.x": 123})
|
| 371 |
+
assert config.config["abc"]["x"] == 123
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def test_set_kwargs():
|
| 375 |
+
config = Config(CONFIG_NAME)
|
| 376 |
+
with config.set(foo__bar=1, foo__baz=2):
|
| 377 |
+
assert config.config["foo"] == {"bar": 1, "baz": 2}
|
| 378 |
+
assert "foo" not in config.config
|
| 379 |
+
|
| 380 |
+
# Mix kwargs and dict, kwargs override
|
| 381 |
+
with config.set({"foo.bar": 1, "foo.baz": 2}, foo__buzz=3, foo__bar=4):
|
| 382 |
+
assert config.config["foo"] == {"bar": 4, "baz": 2, "buzz": 3}
|
| 383 |
+
assert "foo" not in config.config
|
| 384 |
+
|
| 385 |
+
# Mix kwargs and nested dict, kwargs override
|
| 386 |
+
with config.set({"foo": {"bar": 1, "baz": 2}}, foo__buzz=3, foo__bar=4):
|
| 387 |
+
assert config.config["foo"] == {"bar": 4, "baz": 2, "buzz": 3}
|
| 388 |
+
assert "foo" not in config.config
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def test_set_nested():
|
| 392 |
+
config = Config(CONFIG_NAME)
|
| 393 |
+
with config.set({"abc": {"x": 123}}):
|
| 394 |
+
assert config.config["abc"] == {"x": 123}
|
| 395 |
+
with config.set({"abc.y": 456}):
|
| 396 |
+
assert config.config["abc"] == {"x": 123, "y": 456}
|
| 397 |
+
assert config.config["abc"] == {"x": 123}
|
| 398 |
+
assert "abc" not in config.config
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def test_set_hard_to_copyables():
|
| 402 |
+
import threading
|
| 403 |
+
|
| 404 |
+
config = Config(CONFIG_NAME)
|
| 405 |
+
with config.set(x=threading.Lock()):
|
| 406 |
+
with config.set(y=1):
|
| 407 |
+
pass
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
@pytest.mark.parametrize("mkdir", [True, False])
|
| 411 |
+
def test_ensure_file_directory(mkdir, tmpdir):
|
| 412 |
+
a = {"x": 1, "y": {"a": 1}}
|
| 413 |
+
|
| 414 |
+
source = os.path.join(str(tmpdir), "source.yaml")
|
| 415 |
+
dest = os.path.join(str(tmpdir), "dest")
|
| 416 |
+
|
| 417 |
+
with open(source, "w") as f:
|
| 418 |
+
yaml.dump(a, f)
|
| 419 |
+
|
| 420 |
+
if mkdir:
|
| 421 |
+
os.mkdir(dest)
|
| 422 |
+
|
| 423 |
+
config = Config(CONFIG_NAME)
|
| 424 |
+
config.ensure_file(source=source, destination=dest)
|
| 425 |
+
|
| 426 |
+
assert os.path.isdir(dest)
|
| 427 |
+
assert os.path.exists(os.path.join(dest, "source.yaml"))
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def test_ensure_file_defaults_to_TEST_CONFIG_directory(tmpdir):
|
| 431 |
+
a = {"x": 1, "y": {"a": 1}}
|
| 432 |
+
source = os.path.join(str(tmpdir), "source.yaml")
|
| 433 |
+
with open(source, "w") as f:
|
| 434 |
+
yaml.dump(a, f)
|
| 435 |
+
|
| 436 |
+
config = Config("test")
|
| 437 |
+
destination = os.path.join(str(tmpdir), "test")
|
| 438 |
+
PATH = config.main_path
|
| 439 |
+
try:
|
| 440 |
+
config.main_path = destination
|
| 441 |
+
config.ensure_file(source=source)
|
| 442 |
+
finally:
|
| 443 |
+
config.main_path = PATH
|
| 444 |
+
|
| 445 |
+
assert os.path.isdir(destination)
|
| 446 |
+
[fn] = os.listdir(destination)
|
| 447 |
+
assert os.path.split(fn)[1] == os.path.split(source)[1]
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def test_rename():
|
| 451 |
+
config = Config(CONFIG_NAME)
|
| 452 |
+
aliases = {"foo_bar": "foo.bar"}
|
| 453 |
+
config.config = {"foo-bar": 123}
|
| 454 |
+
config.rename(aliases)
|
| 455 |
+
assert config.config == {"foo": {"bar": 123}}
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def test_refresh():
|
| 459 |
+
defaults = []
|
| 460 |
+
config = Config(CONFIG_NAME, defaults=defaults)
|
| 461 |
+
|
| 462 |
+
config.update_defaults({"a": 1})
|
| 463 |
+
assert config.config == {"a": 1}
|
| 464 |
+
|
| 465 |
+
config.refresh(paths=[], env={ENV_PREFIX + "B": "2"})
|
| 466 |
+
assert config.config == {"a": 1, "b": 2}
|
| 467 |
+
|
| 468 |
+
config.refresh(paths=[], env={ENV_PREFIX + "C": "3"})
|
| 469 |
+
assert config.config == {"a": 1, "c": 3}
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
@pytest.mark.parametrize(
|
| 473 |
+
"inp,out",
|
| 474 |
+
[
|
| 475 |
+
("1", "1"),
|
| 476 |
+
(1, 1),
|
| 477 |
+
("$FOO", "foo"),
|
| 478 |
+
([1, "$FOO"], [1, "foo"]),
|
| 479 |
+
((1, "$FOO"), (1, "foo")),
|
| 480 |
+
({1, "$FOO"}, {1, "foo"}),
|
| 481 |
+
({"a": "$FOO"}, {"a": "foo"}),
|
| 482 |
+
({"a": "A", "b": [1, "2", "$FOO"]}, {"a": "A", "b": [1, "2", "foo"]}),
|
| 483 |
+
],
|
| 484 |
+
)
|
| 485 |
+
def test_expand_environment_variables(inp, out):
|
| 486 |
+
try:
|
| 487 |
+
os.environ["FOO"] = "foo"
|
| 488 |
+
assert expand_environment_variables(inp) == out
|
| 489 |
+
finally:
|
| 490 |
+
del os.environ["FOO"]
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def test_env_var_canonical_name(monkeypatch):
|
| 494 |
+
value = 3
|
| 495 |
+
monkeypatch.setenv(ENV_PREFIX + "A_B", str(value))
|
| 496 |
+
config = Config(CONFIG_NAME)
|
| 497 |
+
|
| 498 |
+
assert config.get("a_b") == value
|
| 499 |
+
assert config.get("a-b") == value
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def test_get_set_canonical_name():
|
| 503 |
+
c = {"x-y": {"a_b": 123}}
|
| 504 |
+
config = Config(CONFIG_NAME)
|
| 505 |
+
config.update(c)
|
| 506 |
+
|
| 507 |
+
keys = ["x_y.a_b", "x-y.a-b", "x_y.a-b"]
|
| 508 |
+
for k in keys:
|
| 509 |
+
assert config.get(k) == 123
|
| 510 |
+
|
| 511 |
+
with config.set({"x_y": {"a-b": 456}}):
|
| 512 |
+
for k in keys:
|
| 513 |
+
assert config.get(k) == 456
|
| 514 |
+
|
| 515 |
+
# No change to new keys in sub dicts
|
| 516 |
+
with config.set({"x_y": {"a-b": {"c_d": 1}, "e-f": 2}}):
|
| 517 |
+
assert config.get("x_y.a-b") == {"c_d": 1}
|
| 518 |
+
assert config.get("x_y.e_f") == 2
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
@pytest.mark.parametrize("key", ["custom_key", "custom-key"])
|
| 522 |
+
def test_get_set_roundtrip(key):
|
| 523 |
+
value = 123
|
| 524 |
+
config = Config(CONFIG_NAME)
|
| 525 |
+
with config.set({key: value}):
|
| 526 |
+
assert config.get("custom_key") == value
|
| 527 |
+
assert config.get("custom-key") == value
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def test_merge_none_to_dict():
|
| 531 |
+
assert merge({"a": None, "c": 0}, {"a": {"b": 1}}) == {"a": {"b": 1}, "c": 0}
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def test_pprint(capsys):
|
| 535 |
+
test_config = Config(CONFIG_NAME)
|
| 536 |
+
test_config.config = {"x": 1, "y": {"a": 2}}
|
| 537 |
+
test_config.pprint()
|
| 538 |
+
cap_out = capsys.readouterr()[0]
|
| 539 |
+
assert cap_out == """{'x': 1, 'y': {'a': 2}}\n"""
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def test_to_dict():
|
| 543 |
+
test_config = Config(CONFIG_NAME)
|
| 544 |
+
test_config.config = {"x": 1, "y": {"a": 2}}
|
| 545 |
+
d = test_config.to_dict()
|
| 546 |
+
assert d == test_config.config
|
| 547 |
+
# make sure we copied
|
| 548 |
+
d["z"] = 3
|
| 549 |
+
d["y"]["b"] = 4
|
| 550 |
+
assert d != test_config.config
|
| 551 |
+
assert d["y"] != test_config.config["y"]
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
def test_path_includes_site_prefix():
|
| 555 |
+
command = (
|
| 556 |
+
"import site, os; "
|
| 557 |
+
'prefix = os.path.join("include", "this", "path"); '
|
| 558 |
+
"site.PREFIXES.append(prefix); "
|
| 559 |
+
"from donfig import Config; "
|
| 560 |
+
f"config = Config('{CONFIG_NAME}'); "
|
| 561 |
+
"print(config.paths); "
|
| 562 |
+
f'assert os.path.join(prefix, "etc", "{CONFIG_NAME}") in config.paths'
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
subprocess.check_call([sys.executable, "-c", command])
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def test__get_paths(monkeypatch):
|
| 569 |
+
# These settings, if present, would interfere with these tests
|
| 570 |
+
# We temporarily remove them to avoid interference from the
|
| 571 |
+
# machine where tests are being run.
|
| 572 |
+
monkeypatch.delenv("MYPKG_CONFIG", raising=False)
|
| 573 |
+
monkeypatch.delenv("MYPKG_ROOT_CONFIG", raising=False)
|
| 574 |
+
monkeypatch.setattr(site, "PREFIXES", [])
|
| 575 |
+
|
| 576 |
+
expected = [
|
| 577 |
+
"/etc/mypkg",
|
| 578 |
+
os.path.join(sys.prefix, "etc", "mypkg"),
|
| 579 |
+
os.path.join(os.path.expanduser("~"), ".config", "mypkg"),
|
| 580 |
+
]
|
| 581 |
+
config = Config("mypkg")
|
| 582 |
+
assert config.paths == expected
|
| 583 |
+
assert len(config.paths) == len(set(config.paths)) # No duplicate paths
|
| 584 |
+
|
| 585 |
+
with monkeypatch.context() as m:
|
| 586 |
+
m.setenv("MYPKG_CONFIG", "foo-bar")
|
| 587 |
+
config = Config("mypkg")
|
| 588 |
+
paths = config.paths
|
| 589 |
+
assert paths == expected + ["foo-bar"]
|
| 590 |
+
assert len(paths) == len(set(paths))
|
| 591 |
+
|
| 592 |
+
with monkeypatch.context() as m:
|
| 593 |
+
m.setenv("MYPKG_ROOT_CONFIG", "foo-bar")
|
| 594 |
+
config = Config("mypkg")
|
| 595 |
+
paths = config.paths
|
| 596 |
+
assert paths == ["foo-bar"] + expected[1:]
|
| 597 |
+
assert len(paths) == len(set(paths))
|
| 598 |
+
|
| 599 |
+
with monkeypatch.context() as m:
|
| 600 |
+
prefix = os.path.join("include", "this", "path")
|
| 601 |
+
m.setattr(site, "PREFIXES", site.PREFIXES + [prefix])
|
| 602 |
+
config = Config("mypkg")
|
| 603 |
+
paths = config.paths
|
| 604 |
+
assert os.path.join(prefix, "etc", "mypkg") in paths
|
| 605 |
+
assert len(paths) == len(set(paths))
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def test_serialization():
|
| 609 |
+
config = Config(CONFIG_NAME)
|
| 610 |
+
config.set(one_key="one_value")
|
| 611 |
+
new_config = cloudpickle.loads(cloudpickle.dumps(config))
|
| 612 |
+
assert new_config.get("one_key") == "one_value"
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def test_deprecations_rename():
|
| 616 |
+
config = Config(CONFIG_NAME, deprecations={"fuse_ave_width": "optimization.fuse.ave-width"})
|
| 617 |
+
with pytest.warns(Warning) as info, config.set(fuse_ave_width=123):
|
| 618 |
+
assert config.get("optimization.fuse.ave-width") == 123
|
| 619 |
+
|
| 620 |
+
assert "optimization.fuse.ave-width" in str(info[0].message)
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
def test_deprecations_removed():
|
| 624 |
+
config = Config(CONFIG_NAME, deprecations={"fuse_ave_width": None})
|
| 625 |
+
with pytest.raises(ValueError):
|
| 626 |
+
config.set(fuse_ave_width=123)
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def test_config_serialization_functions():
|
| 630 |
+
serialized = serialize({"array": {"svg": {"size": 150}}})
|
| 631 |
+
config_dict = deserialize(serialized)
|
| 632 |
+
assert config_dict["array"]["svg"]["size"] == 150
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def test_config_object_serialization():
|
| 636 |
+
config = Config(CONFIG_NAME)
|
| 637 |
+
config.set({"array.svg.size": 150})
|
| 638 |
+
ser_config = config.serialize()
|
| 639 |
+
deser_dict = deserialize(ser_config)
|
| 640 |
+
deser_config = Config(CONFIG_NAME)
|
| 641 |
+
deser_config.update(deser_dict)
|
| 642 |
+
assert deser_config.get("array.svg.size") == 150
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
def test_config_inheritance(monkeypatch):
|
| 646 |
+
ser_dict = serialize({"array": {"svg": {"size": 150}}})
|
| 647 |
+
monkeypatch.setenv(f"{ENV_PREFIX}_INTERNAL_INHERIT_CONFIG", ser_dict)
|
| 648 |
+
config = Config(CONFIG_NAME)
|
| 649 |
+
assert config.get("array.svg.size") == 150
|
.venv/lib/python3.11/site-packages/donfig/tests/test_lock.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2022 Donfig Developers
|
| 4 |
+
# Copyright (c) 2014-2018, Anaconda, Inc. and contributors
|
| 5 |
+
#
|
| 6 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 7 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 8 |
+
# in the Software without restriction, including without limitation the rights
|
| 9 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 10 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 11 |
+
# furnished to do so, subject to the following conditions:
|
| 12 |
+
#
|
| 13 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 14 |
+
# copies or substantial portions of the Software.
|
| 15 |
+
#
|
| 16 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 17 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 18 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 19 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 20 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 21 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 22 |
+
# SOFTWARE.
|
| 23 |
+
|
| 24 |
+
import pickle
|
| 25 |
+
|
| 26 |
+
from .._lock import SerializableLock
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_SerializableLock():
|
| 30 |
+
a = SerializableLock()
|
| 31 |
+
b = SerializableLock()
|
| 32 |
+
with a:
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
with a:
|
| 36 |
+
with b:
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
with a:
|
| 40 |
+
assert not a.acquire(False)
|
| 41 |
+
|
| 42 |
+
a2 = pickle.loads(pickle.dumps(a))
|
| 43 |
+
a3 = pickle.loads(pickle.dumps(a))
|
| 44 |
+
a4 = pickle.loads(pickle.dumps(a2))
|
| 45 |
+
|
| 46 |
+
for x in [a, a2, a3, a4]:
|
| 47 |
+
for y in [a, a2, a3, a4]:
|
| 48 |
+
with x:
|
| 49 |
+
assert not y.acquire(False)
|
| 50 |
+
|
| 51 |
+
b2 = pickle.loads(pickle.dumps(b))
|
| 52 |
+
b3 = pickle.loads(pickle.dumps(b2))
|
| 53 |
+
|
| 54 |
+
for x in [a, a2, a3, a4]:
|
| 55 |
+
for y in [b, b2, b3]:
|
| 56 |
+
with x:
|
| 57 |
+
with y:
|
| 58 |
+
pass
|
| 59 |
+
with y:
|
| 60 |
+
with x:
|
| 61 |
+
pass
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_SerializableLock_name_collision():
|
| 65 |
+
a = SerializableLock("a")
|
| 66 |
+
b = SerializableLock("b")
|
| 67 |
+
c = SerializableLock("a")
|
| 68 |
+
d = SerializableLock()
|
| 69 |
+
|
| 70 |
+
assert a.lock is not b.lock
|
| 71 |
+
assert a.lock is c.lock
|
| 72 |
+
assert d.lock not in (a.lock, b.lock, c.lock)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_SerializableLock_locked():
|
| 76 |
+
a = SerializableLock("a")
|
| 77 |
+
assert not a.locked()
|
| 78 |
+
with a:
|
| 79 |
+
assert a.locked()
|
| 80 |
+
assert not a.locked()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def test_SerializableLock_acquire_blocking():
|
| 84 |
+
a = SerializableLock("a")
|
| 85 |
+
assert a.acquire(blocking=True)
|
| 86 |
+
assert not a.acquire(blocking=False)
|
| 87 |
+
a.release()
|
.venv/lib/python3.11/site-packages/donfig/utils.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) 2018 Donfig Developers
|
| 4 |
+
# Copyright (c) 2014-2018, Anaconda, Inc. and contributors
|
| 5 |
+
#
|
| 6 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 7 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 8 |
+
# in the Software without restriction, including without limitation the rights
|
| 9 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 10 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 11 |
+
# furnished to do so, subject to the following conditions:
|
| 12 |
+
#
|
| 13 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 14 |
+
# copies or substantial portions of the Software.
|
| 15 |
+
#
|
| 16 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 17 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 18 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 19 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 20 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 21 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 22 |
+
# SOFTWARE.
|
| 23 |
+
import os
|
| 24 |
+
import shutil
|
| 25 |
+
import tempfile
|
| 26 |
+
from contextlib import contextmanager, suppress
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@contextmanager
|
| 30 |
+
def tmpfile(extension="", dir=None):
|
| 31 |
+
extension = "." + extension.lstrip(".")
|
| 32 |
+
handle, filename = tempfile.mkstemp(extension, dir=dir)
|
| 33 |
+
os.close(handle)
|
| 34 |
+
os.remove(filename)
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
yield filename
|
| 38 |
+
finally:
|
| 39 |
+
if os.path.exists(filename):
|
| 40 |
+
if os.path.isdir(filename):
|
| 41 |
+
shutil.rmtree(filename)
|
| 42 |
+
else:
|
| 43 |
+
with suppress(OSError):
|
| 44 |
+
os.remove(filename)
|
.venv/lib/python3.11/site-packages/donfig/version.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# This file was generated by 'versioneer.py' (0.28) from
|
| 3 |
+
# revision-control system data, or from the parent directory name of an
|
| 4 |
+
# unpacked source archive. Distribution tarballs contain a pre-generated copy
|
| 5 |
+
# of this file.
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
|
| 9 |
+
version_json = '''
|
| 10 |
+
{
|
| 11 |
+
"date": "2024-05-23T09:11:29-0500",
|
| 12 |
+
"dirty": false,
|
| 13 |
+
"error": null,
|
| 14 |
+
"full-revisionid": "9669a064dc7bbbd1af83fad548608a00cf101f94",
|
| 15 |
+
"version": "0.8.1.post1"
|
| 16 |
+
}
|
| 17 |
+
''' # END VERSION_JSON
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_versions():
|
| 21 |
+
return json.loads(version_json)
|
.venv/lib/python3.11/site-packages/filelock-3.29.6.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
uv
|
.venv/lib/python3.11/site-packages/filelock-3.29.6.dist-info/METADATA
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: filelock
|
| 3 |
+
Version: 3.29.6
|
| 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 |
+
[](https://pypi.org/project/filelock/)
|
| 33 |
+
[](https://pypi.org/project/filelock/)
|
| 34 |
+
[](https://py-filelock.readthedocs.io/en/latest/?badge=latest)
|
| 35 |
+
[](https://pepy.tech/project/filelock)
|
| 36 |
+
[](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).
|
.venv/lib/python3.11/site-packages/filelock-3.29.6.dist-info/RECORD
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
filelock-3.29.6.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
|
| 2 |
+
filelock-3.29.6.dist-info/METADATA,sha256=QQLJgG-XjFHvnILkEsyh2OoQ9OhbkyouosqAs_9wIdU,1977
|
| 3 |
+
filelock-3.29.6.dist-info/RECORD,,
|
| 4 |
+
filelock-3.29.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
filelock-3.29.6.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
| 6 |
+
filelock-3.29.6.dist-info/licenses/LICENSE,sha256=YIyJ1QYK6ZIa3M8yNmlbxlSplG4SMj72wCHfoE4pTUg,1088
|
| 7 |
+
filelock/__init__.py,sha256=Ig_QNvsAVtctz2-fkq9EUCgXmW6M5PDudiOC85szmis,2612
|
| 8 |
+
filelock/_api.py,sha256=CeNvmIUi-vj3DmGkrNyhAVuLVAyiJE71Th8BVZPIoBg,23802
|
| 9 |
+
filelock/_async_read_write.py,sha256=cI59FlQ1BaebdmoG77OVcTKYaDVabPJOjh5xsOGYC8c,8457
|
| 10 |
+
filelock/_error.py,sha256=IytAfHRl_zagaLkbto73QkiWni0KfTzq-6Xgc1v6450,765
|
| 11 |
+
filelock/_read_write.py,sha256=f6oAIkzwX2cEI_8Y2haeo49yL79gZ1Y3vLpNRGTiHcg,17030
|
| 12 |
+
filelock/_soft.py,sha256=z7I5KJFNZewCZdVQS8Ploq80tKKurLtxCQxPptRbzQA,10329
|
| 13 |
+
filelock/_soft_rw/__init__.py,sha256=_ktpGmVObzrvL0K1_EAV3LF7B9JarYxW-mx_eyGPhT0,370
|
| 14 |
+
filelock/_soft_rw/_async.py,sha256=Hu7e8epFROEzkEGW1Qq-oe25O0fxl6lVilMM6ORkSFE,8654
|
| 15 |
+
filelock/_soft_rw/_sync.py,sha256=pX9ABKeUXQF8ltpxJO3d2zuigdHZnh1ewVOJOWb5eCc,40371
|
| 16 |
+
filelock/_unix.py,sha256=zNmZv3F3Qqkl_r9rxI2S5s5eKdh3y6G1rHFb0a5G-Zc,4505
|
| 17 |
+
filelock/_util.py,sha256=hOUcnuJ0hsM9tcsk_hHXwnfmfkxAf0USVqkjSiOBBes,4841
|
| 18 |
+
filelock/_windows.py,sha256=kJFOenaffOP6Qza2b3-yxgiPiDcyroWnzz9STGkCrgM,3943
|
| 19 |
+
filelock/asyncio.py,sha256=4HPfzyibgUK7AmBb7WJKA-MGX8y_ya8AXK5btwcaEfc,15528
|
| 20 |
+
filelock/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 21 |
+
filelock/version.py,sha256=q5EyvwTL7rzuAFheFgy-DSW_f6bMEEFIeRloPAvCMAo,522
|
.venv/lib/python3.11/site-packages/filelock-3.29.6.dist-info/REQUESTED
ADDED
|
File without changes
|
.venv/lib/python3.11/site-packages/filelock-3.29.6.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.30.1
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
.venv/lib/python3.11/site-packages/filelock-3.29.6.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.
|
.venv/lib/python3.11/site-packages/filelock/__init__.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A platform independent file lock that supports the with-statement.
|
| 3 |
+
|
| 4 |
+
.. autodata:: filelock.__version__
|
| 5 |
+
:no-value:
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
import warnings
|
| 13 |
+
from typing import TYPE_CHECKING
|
| 14 |
+
|
| 15 |
+
from ._api import AcquireReturnProxy, BaseFileLock
|
| 16 |
+
from ._error import Timeout
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from ._async_read_write import (
|
| 20 |
+
AsyncAcquireReadWriteReturnProxy,
|
| 21 |
+
AsyncReadWriteLock,
|
| 22 |
+
)
|
| 23 |
+
from ._read_write import ReadWriteLock
|
| 24 |
+
else:
|
| 25 |
+
try:
|
| 26 |
+
from ._async_read_write import AsyncAcquireReadWriteReturnProxy, AsyncReadWriteLock
|
| 27 |
+
from ._read_write import ReadWriteLock
|
| 28 |
+
except ImportError: # sqlite3 may be unavailable if Python was built without it or the C library is missing
|
| 29 |
+
AsyncAcquireReadWriteReturnProxy = None
|
| 30 |
+
AsyncReadWriteLock = None
|
| 31 |
+
ReadWriteLock = None
|
| 32 |
+
|
| 33 |
+
from ._soft import SoftFileLock
|
| 34 |
+
from ._soft_rw import AsyncAcquireSoftReadWriteReturnProxy, AsyncSoftReadWriteLock, SoftReadWriteLock
|
| 35 |
+
from ._unix import UnixFileLock, has_fcntl
|
| 36 |
+
from ._windows import WindowsFileLock
|
| 37 |
+
from .asyncio import (
|
| 38 |
+
AsyncAcquireReturnProxy,
|
| 39 |
+
AsyncSoftFileLock,
|
| 40 |
+
AsyncUnixFileLock,
|
| 41 |
+
AsyncWindowsFileLock,
|
| 42 |
+
BaseAsyncFileLock,
|
| 43 |
+
)
|
| 44 |
+
from .version import version
|
| 45 |
+
|
| 46 |
+
#: version of the project as a string
|
| 47 |
+
__version__: str = version
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if sys.platform == "win32": # pragma: win32 cover
|
| 51 |
+
_FileLock: type[BaseFileLock] = WindowsFileLock
|
| 52 |
+
_AsyncFileLock: type[BaseAsyncFileLock] = AsyncWindowsFileLock
|
| 53 |
+
else: # pragma: win32 no cover # noqa: PLR5501
|
| 54 |
+
if has_fcntl:
|
| 55 |
+
_FileLock: type[BaseFileLock] = UnixFileLock
|
| 56 |
+
_AsyncFileLock: type[BaseAsyncFileLock] = AsyncUnixFileLock
|
| 57 |
+
else:
|
| 58 |
+
_FileLock = SoftFileLock
|
| 59 |
+
_AsyncFileLock = AsyncSoftFileLock
|
| 60 |
+
if warnings is not None:
|
| 61 |
+
warnings.warn("only soft file lock is available", stacklevel=2)
|
| 62 |
+
|
| 63 |
+
if TYPE_CHECKING:
|
| 64 |
+
FileLock = SoftFileLock
|
| 65 |
+
AsyncFileLock = AsyncSoftFileLock
|
| 66 |
+
else:
|
| 67 |
+
#: Alias for the lock, which should be used for the current platform.
|
| 68 |
+
FileLock = _FileLock
|
| 69 |
+
AsyncFileLock = _AsyncFileLock
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
__all__ = [
|
| 73 |
+
"AcquireReturnProxy",
|
| 74 |
+
"AsyncAcquireReadWriteReturnProxy",
|
| 75 |
+
"AsyncAcquireReturnProxy",
|
| 76 |
+
"AsyncAcquireSoftReadWriteReturnProxy",
|
| 77 |
+
"AsyncFileLock",
|
| 78 |
+
"AsyncReadWriteLock",
|
| 79 |
+
"AsyncSoftFileLock",
|
| 80 |
+
"AsyncSoftReadWriteLock",
|
| 81 |
+
"AsyncUnixFileLock",
|
| 82 |
+
"AsyncWindowsFileLock",
|
| 83 |
+
"BaseAsyncFileLock",
|
| 84 |
+
"BaseFileLock",
|
| 85 |
+
"FileLock",
|
| 86 |
+
"ReadWriteLock",
|
| 87 |
+
"SoftFileLock",
|
| 88 |
+
"SoftReadWriteLock",
|
| 89 |
+
"Timeout",
|
| 90 |
+
"UnixFileLock",
|
| 91 |
+
"WindowsFileLock",
|
| 92 |
+
"__version__",
|
| 93 |
+
]
|
.venv/lib/python3.11/site-packages/filelock/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (2.47 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/filelock/__pycache__/_api.cpython-311.pyc
ADDED
|
Binary file (28.1 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/filelock/__pycache__/_async_read_write.cpython-311.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/filelock/__pycache__/_error.cpython-311.pyc
ADDED
|
Binary file (1.92 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/filelock/__pycache__/_read_write.cpython-311.pyc
ADDED
|
Binary file (21.2 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/filelock/__pycache__/_soft.cpython-311.pyc
ADDED
|
Binary file (14.6 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/filelock/__pycache__/_unix.cpython-311.pyc
ADDED
|
Binary file (6.54 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/filelock/__pycache__/_util.cpython-311.pyc
ADDED
|
Binary file (5.05 kB). View file
|
|
|
.venv/lib/python3.11/site-packages/filelock/__pycache__/_windows.cpython-311.pyc
ADDED
|
Binary file (5.5 kB). View file
|
|
|