fonttools 4.55.4__cp313-cp313-musllinux_1_2_aarch64.whl → 4.61.1__cp313-cp313-musllinux_1_2_aarch64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. fontTools/__init__.py +1 -1
  2. fontTools/annotations.py +30 -0
  3. fontTools/cffLib/CFF2ToCFF.py +65 -10
  4. fontTools/cffLib/__init__.py +61 -26
  5. fontTools/cffLib/specializer.py +4 -1
  6. fontTools/cffLib/transforms.py +11 -6
  7. fontTools/config/__init__.py +15 -0
  8. fontTools/cu2qu/cu2qu.c +6567 -5579
  9. fontTools/cu2qu/cu2qu.cpython-313-aarch64-linux-musl.so +0 -0
  10. fontTools/cu2qu/cu2qu.py +36 -4
  11. fontTools/cu2qu/ufo.py +14 -0
  12. fontTools/designspaceLib/__init__.py +8 -3
  13. fontTools/designspaceLib/statNames.py +14 -7
  14. fontTools/feaLib/ast.py +24 -15
  15. fontTools/feaLib/builder.py +139 -66
  16. fontTools/feaLib/error.py +1 -1
  17. fontTools/feaLib/lexer.c +7038 -7995
  18. fontTools/feaLib/lexer.cpython-313-aarch64-linux-musl.so +0 -0
  19. fontTools/feaLib/parser.py +75 -40
  20. fontTools/feaLib/variableScalar.py +6 -1
  21. fontTools/fontBuilder.py +50 -44
  22. fontTools/merge/__init__.py +1 -1
  23. fontTools/merge/cmap.py +33 -1
  24. fontTools/merge/tables.py +12 -1
  25. fontTools/misc/bezierTools.c +14913 -17013
  26. fontTools/misc/bezierTools.cpython-313-aarch64-linux-musl.so +0 -0
  27. fontTools/misc/bezierTools.py +4 -1
  28. fontTools/misc/configTools.py +3 -1
  29. fontTools/misc/enumTools.py +23 -0
  30. fontTools/misc/etree.py +4 -27
  31. fontTools/misc/filesystem/__init__.py +68 -0
  32. fontTools/misc/filesystem/_base.py +134 -0
  33. fontTools/misc/filesystem/_copy.py +45 -0
  34. fontTools/misc/filesystem/_errors.py +54 -0
  35. fontTools/misc/filesystem/_info.py +75 -0
  36. fontTools/misc/filesystem/_osfs.py +164 -0
  37. fontTools/misc/filesystem/_path.py +67 -0
  38. fontTools/misc/filesystem/_subfs.py +92 -0
  39. fontTools/misc/filesystem/_tempfs.py +34 -0
  40. fontTools/misc/filesystem/_tools.py +34 -0
  41. fontTools/misc/filesystem/_walk.py +55 -0
  42. fontTools/misc/filesystem/_zipfs.py +204 -0
  43. fontTools/misc/fixedTools.py +1 -1
  44. fontTools/misc/loggingTools.py +1 -1
  45. fontTools/misc/psCharStrings.py +17 -2
  46. fontTools/misc/sstruct.py +2 -6
  47. fontTools/misc/symfont.py +6 -8
  48. fontTools/misc/testTools.py +5 -1
  49. fontTools/misc/textTools.py +4 -2
  50. fontTools/misc/visitor.py +32 -16
  51. fontTools/misc/xmlWriter.py +44 -8
  52. fontTools/mtiLib/__init__.py +1 -3
  53. fontTools/otlLib/builder.py +402 -155
  54. fontTools/otlLib/optimize/gpos.py +49 -63
  55. fontTools/pens/filterPen.py +218 -26
  56. fontTools/pens/momentsPen.c +5514 -5584
  57. fontTools/pens/momentsPen.cpython-313-aarch64-linux-musl.so +0 -0
  58. fontTools/pens/pointPen.py +61 -18
  59. fontTools/pens/roundingPen.py +2 -2
  60. fontTools/pens/t2CharStringPen.py +31 -11
  61. fontTools/qu2cu/qu2cu.c +6581 -6168
  62. fontTools/qu2cu/qu2cu.cpython-313-aarch64-linux-musl.so +0 -0
  63. fontTools/subset/__init__.py +283 -25
  64. fontTools/subset/svg.py +2 -3
  65. fontTools/ttLib/__init__.py +4 -0
  66. fontTools/ttLib/__main__.py +47 -8
  67. fontTools/ttLib/removeOverlaps.py +7 -5
  68. fontTools/ttLib/reorderGlyphs.py +8 -7
  69. fontTools/ttLib/sfnt.py +11 -9
  70. fontTools/ttLib/tables/D__e_b_g.py +20 -2
  71. fontTools/ttLib/tables/G_V_A_R_.py +5 -0
  72. fontTools/ttLib/tables/S__i_l_f.py +2 -2
  73. fontTools/ttLib/tables/T_S_I__0.py +14 -3
  74. fontTools/ttLib/tables/T_S_I__1.py +2 -5
  75. fontTools/ttLib/tables/T_S_I__5.py +18 -7
  76. fontTools/ttLib/tables/__init__.py +1 -0
  77. fontTools/ttLib/tables/_a_v_a_r.py +12 -3
  78. fontTools/ttLib/tables/_c_m_a_p.py +20 -7
  79. fontTools/ttLib/tables/_c_v_t.py +3 -2
  80. fontTools/ttLib/tables/_f_p_g_m.py +3 -1
  81. fontTools/ttLib/tables/_g_l_y_f.py +45 -21
  82. fontTools/ttLib/tables/_g_v_a_r.py +67 -19
  83. fontTools/ttLib/tables/_h_d_m_x.py +4 -4
  84. fontTools/ttLib/tables/_h_m_t_x.py +7 -3
  85. fontTools/ttLib/tables/_l_o_c_a.py +2 -2
  86. fontTools/ttLib/tables/_n_a_m_e.py +11 -6
  87. fontTools/ttLib/tables/_p_o_s_t.py +9 -7
  88. fontTools/ttLib/tables/otBase.py +5 -12
  89. fontTools/ttLib/tables/otConverters.py +5 -2
  90. fontTools/ttLib/tables/otData.py +1 -1
  91. fontTools/ttLib/tables/otTables.py +33 -30
  92. fontTools/ttLib/tables/otTraverse.py +2 -1
  93. fontTools/ttLib/tables/sbixStrike.py +3 -3
  94. fontTools/ttLib/ttFont.py +666 -120
  95. fontTools/ttLib/ttGlyphSet.py +0 -10
  96. fontTools/ttLib/woff2.py +10 -13
  97. fontTools/ttx.py +13 -1
  98. fontTools/ufoLib/__init__.py +300 -202
  99. fontTools/ufoLib/converters.py +103 -30
  100. fontTools/ufoLib/errors.py +8 -0
  101. fontTools/ufoLib/etree.py +1 -1
  102. fontTools/ufoLib/filenames.py +171 -106
  103. fontTools/ufoLib/glifLib.py +303 -205
  104. fontTools/ufoLib/kerning.py +98 -48
  105. fontTools/ufoLib/utils.py +46 -15
  106. fontTools/ufoLib/validators.py +121 -99
  107. fontTools/unicodedata/Blocks.py +35 -20
  108. fontTools/unicodedata/Mirrored.py +446 -0
  109. fontTools/unicodedata/ScriptExtensions.py +63 -37
  110. fontTools/unicodedata/Scripts.py +173 -152
  111. fontTools/unicodedata/__init__.py +10 -2
  112. fontTools/varLib/__init__.py +198 -109
  113. fontTools/varLib/avar/__init__.py +0 -0
  114. fontTools/varLib/avar/__main__.py +72 -0
  115. fontTools/varLib/avar/build.py +79 -0
  116. fontTools/varLib/avar/map.py +108 -0
  117. fontTools/varLib/avar/plan.py +1004 -0
  118. fontTools/varLib/{avar.py → avar/unbuild.py} +70 -59
  119. fontTools/varLib/avarPlanner.py +3 -999
  120. fontTools/varLib/featureVars.py +21 -7
  121. fontTools/varLib/hvar.py +113 -0
  122. fontTools/varLib/instancer/__init__.py +180 -65
  123. fontTools/varLib/interpolatableHelpers.py +3 -0
  124. fontTools/varLib/iup.c +7564 -6903
  125. fontTools/varLib/iup.cpython-313-aarch64-linux-musl.so +0 -0
  126. fontTools/varLib/models.py +17 -2
  127. fontTools/varLib/mutator.py +11 -0
  128. fontTools/varLib/varStore.py +10 -38
  129. fontTools/voltLib/__main__.py +206 -0
  130. fontTools/voltLib/ast.py +4 -0
  131. fontTools/voltLib/parser.py +16 -8
  132. fontTools/voltLib/voltToFea.py +347 -166
  133. {fonttools-4.55.4.dist-info → fonttools-4.61.1.dist-info}/METADATA +269 -1410
  134. {fonttools-4.55.4.dist-info → fonttools-4.61.1.dist-info}/RECORD +318 -294
  135. {fonttools-4.55.4.dist-info → fonttools-4.61.1.dist-info}/WHEEL +1 -1
  136. fonttools-4.61.1.dist-info/licenses/LICENSE.external +388 -0
  137. {fonttools-4.55.4.data → fonttools-4.61.1.data}/data/share/man/man1/ttx.1 +0 -0
  138. {fonttools-4.55.4.dist-info → fonttools-4.61.1.dist-info}/entry_points.txt +0 -0
  139. {fonttools-4.55.4.dist-info → fonttools-4.61.1.dist-info/licenses}/LICENSE +0 -0
  140. {fonttools-4.55.4.dist-info → fonttools-4.61.1.dist-info}/top_level.txt +0 -0
@@ -1409,7 +1409,10 @@ def curveCurveIntersections(curve1, curve2):
1409
1409
  line2 = curve2[0], curve2[-1]
1410
1410
  return lineLineIntersections(*line1, *line2)
1411
1411
  else:
1412
- return curveLineIntersections(curve2, line1)
1412
+ hits = curveLineIntersections(curve2, line1)
1413
+ # curve is passed first to this fn but is the second segment, so
1414
+ # we need to swap t1/t2 in the result
1415
+ return [Intersection(pt=x.pt, t1=x.t2, t2=x.t1) for x in hits]
1413
1416
  elif _is_linelike(curve2):
1414
1417
  line2 = curve2[0], curve2[-1]
1415
1418
  return curveLineIntersections(curve1, line2)
@@ -224,7 +224,9 @@ class AbstractConfig(MutableMapping):
224
224
 
225
225
  def __init__(
226
226
  self,
227
- values: Union[AbstractConfig, Dict[Union[Option, str], Any]] = {},
227
+ values: Union[
228
+ AbstractConfig, Dict[Union[Option, str], Any], Mapping[str, Any]
229
+ ] = {},
228
230
  parse_values: bool = False,
229
231
  skip_unknown: bool = False,
230
232
  ):
@@ -0,0 +1,23 @@
1
+ """Enum-related utilities, including backports for older Python versions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import Enum
6
+
7
+
8
+ __all__ = ["StrEnum"]
9
+
10
+ # StrEnum is only available in Python 3.11+
11
+ try:
12
+ from enum import StrEnum
13
+ except ImportError:
14
+
15
+ class StrEnum(str, Enum):
16
+ """
17
+ Minimal backport of Python 3.11's StrEnum for older versions.
18
+
19
+ An Enum where all members are also strings.
20
+ """
21
+
22
+ def __str__(self) -> str:
23
+ return self.value
fontTools/misc/etree.py CHANGED
@@ -56,21 +56,7 @@ except ImportError:
56
56
  from xml.etree.ElementTree import *
57
57
  _have_lxml = False
58
58
 
59
- import sys
60
-
61
- # dict is always ordered in python >= 3.6 and on pypy
62
- PY36 = sys.version_info >= (3, 6)
63
- try:
64
- import __pypy__
65
- except ImportError:
66
- __pypy__ = None
67
- _dict_is_ordered = bool(PY36 or __pypy__)
68
- del PY36, __pypy__
69
-
70
- if _dict_is_ordered:
71
- _Attrib = dict
72
- else:
73
- from collections import OrderedDict as _Attrib
59
+ _Attrib = dict
74
60
 
75
61
  if isinstance(Element, type):
76
62
  _Element = Element
@@ -221,18 +207,9 @@ except ImportError:
221
207
  # characters, the surrogate blocks, FFFE, and FFFF:
222
208
  # Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
223
209
  # Here we reversed the pattern to match only the invalid characters.
224
- # For the 'narrow' python builds supporting only UCS-2, which represent
225
- # characters beyond BMP as UTF-16 surrogate pairs, we need to pass through
226
- # the surrogate block. I haven't found a more elegant solution...
227
- UCS2 = sys.maxunicode < 0x10FFFF
228
- if UCS2:
229
- _invalid_xml_string = re.compile(
230
- "[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uFFFE-\uFFFF]"
231
- )
232
- else:
233
- _invalid_xml_string = re.compile(
234
- "[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]"
235
- )
210
+ _invalid_xml_string = re.compile(
211
+ "[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]"
212
+ )
236
213
 
237
214
  def _tounicode(s):
238
215
  """Test if a string is valid user input and decode it to unicode string
@@ -0,0 +1,68 @@
1
+ """Minimal, stdlib-only replacement for [`pyfilesystem2`][1] API for use by `fontTools.ufoLib`.
2
+
3
+ This package is a partial reimplementation of the `fs` package by Will McGugan, used under the
4
+ MIT license. See LICENSE.external for details.
5
+
6
+ Note this only exports a **subset** of the `pyfilesystem2` API, in particular the modules,
7
+ classes and functions that are currently used directly by `fontTools.ufoLib`.
8
+
9
+ It opportunistically tries to import the relevant modules from the upstream `fs` package
10
+ when this is available. Otherwise it falls back to the replacement modules within this package.
11
+
12
+ As of version 4.59.0, the `fonttools[ufo]` extra no longer requires the `fs` package, thus
13
+ this `fontTools.misc.filesystem` package is used by default.
14
+
15
+ Client code can either replace `import fs` with `from fontTools.misc import filesystem as fs`
16
+ if that happens to work (no guarantee), or they can continue to use `fs` but they will have
17
+ to specify it as an explicit dependency of their project.
18
+
19
+ [1]: https://github.com/PyFilesystem/pyfilesystem2
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ try:
25
+ __import__("fs")
26
+ except ImportError:
27
+ from . import _base as base
28
+ from . import _copy as copy
29
+ from . import _errors as errors
30
+ from . import _info as info
31
+ from . import _osfs as osfs
32
+ from . import _path as path
33
+ from . import _subfs as subfs
34
+ from . import _tempfs as tempfs
35
+ from . import _tools as tools
36
+ from . import _walk as walk
37
+ from . import _zipfs as zipfs
38
+
39
+ _haveFS = False
40
+ else:
41
+ import fs.base as base
42
+ import fs.copy as copy
43
+ import fs.errors as errors
44
+ import fs.info as info
45
+ import fs.osfs as osfs
46
+ import fs.path as path
47
+ import fs.subfs as subfs
48
+ import fs.tempfs as tempfs
49
+ import fs.tools as tools
50
+ import fs.walk as walk
51
+ import fs.zipfs as zipfs
52
+
53
+ _haveFS = True
54
+
55
+
56
+ __all__ = [
57
+ "base",
58
+ "copy",
59
+ "errors",
60
+ "info",
61
+ "osfs",
62
+ "path",
63
+ "subfs",
64
+ "tempfs",
65
+ "tools",
66
+ "walk",
67
+ "zipfs",
68
+ ]
@@ -0,0 +1,134 @@
1
+ from __future__ import annotations
2
+
3
+ import typing
4
+ from abc import ABC, abstractmethod
5
+
6
+ from ._copy import copy_dir, copy_file
7
+ from ._errors import (
8
+ DestinationExists,
9
+ DirectoryExpected,
10
+ FileExpected,
11
+ FilesystemClosed,
12
+ NoSysPath,
13
+ ResourceNotFound,
14
+ )
15
+ from ._path import dirname
16
+ from ._walk import BoundWalker
17
+
18
+ if typing.TYPE_CHECKING:
19
+ from typing import IO, Any, Collection, Iterator, Self, Type
20
+
21
+ from ._info import Info
22
+ from ._subfs import SubFS
23
+
24
+
25
+ class FS(ABC):
26
+ """Abstract base class for custom filesystems."""
27
+
28
+ _closed: bool = False
29
+
30
+ @abstractmethod
31
+ def open(self, path: str, mode: str = "rb", **kwargs) -> IO[Any]: ...
32
+
33
+ @abstractmethod
34
+ def exists(self, path: str) -> bool: ...
35
+
36
+ @abstractmethod
37
+ def isdir(self, path: str) -> bool: ...
38
+
39
+ @abstractmethod
40
+ def isfile(self, path: str) -> bool: ...
41
+
42
+ @abstractmethod
43
+ def listdir(self, path: str) -> list[str]: ...
44
+
45
+ @abstractmethod
46
+ def makedir(self, path: str, recreate: bool = False) -> SubFS: ...
47
+
48
+ @abstractmethod
49
+ def makedirs(self, path: str, recreate: bool = False) -> SubFS: ...
50
+
51
+ @abstractmethod
52
+ def getinfo(self, path: str, namespaces: Collection[str] | None = None) -> Info: ...
53
+
54
+ @abstractmethod
55
+ def remove(self, path: str) -> None: ...
56
+
57
+ @abstractmethod
58
+ def removedir(self, path: str) -> None: ...
59
+
60
+ @abstractmethod
61
+ def removetree(self, path: str) -> None: ...
62
+
63
+ @abstractmethod
64
+ def movedir(self, src: str, dst: str, create: bool = False) -> None: ...
65
+
66
+ def getsyspath(self, path: str) -> str:
67
+ raise NoSysPath(f"the filesystem {self!r} has no system path")
68
+
69
+ def close(self):
70
+ self._closed = True
71
+
72
+ def isclosed(self) -> bool:
73
+ return self._closed
74
+
75
+ def __enter__(self) -> Self:
76
+ return self
77
+
78
+ def __exit__(self, exc_type, exc, tb):
79
+ self.close()
80
+ return False # never swallow exceptions
81
+
82
+ def check(self):
83
+ if self._closed:
84
+ raise FilesystemClosed(f"the filesystem {self!r} is closed")
85
+
86
+ def opendir(self, path: str, *, factory: Type[SubFS] | None = None) -> SubFS:
87
+ """Return a sub‑filesystem rooted at `path`."""
88
+ if factory is None:
89
+ from ._subfs import SubFS
90
+
91
+ factory = SubFS
92
+ return factory(self, path)
93
+
94
+ def scandir(
95
+ self, path: str, namespaces: Collection[str] | None = None
96
+ ) -> Iterator[Info]:
97
+ return (self.getinfo(f"{path}/{p}", namespaces) for p in self.listdir(path))
98
+
99
+ @property
100
+ def walk(self) -> BoundWalker:
101
+ return BoundWalker(self)
102
+
103
+ def readbytes(self, path: str) -> bytes:
104
+ with self.open(path, "rb") as f:
105
+ return f.read()
106
+
107
+ def writebytes(self, path: str, data: bytes):
108
+ with self.open(path, "wb") as f:
109
+ f.write(data)
110
+
111
+ def create(self, path: str, wipe: bool = False):
112
+ if not wipe and self.exists(path):
113
+ return False
114
+ with self.open(path, "wb"):
115
+ pass # 'touch' empty file
116
+ return True
117
+
118
+ def copy(self, src_path: str, dst_path: str, overwrite=False):
119
+ if not self.exists(src_path):
120
+ raise ResourceNotFound(f"{src_path!r} does not exist")
121
+ elif not self.isfile(src_path):
122
+ raise FileExpected(f"path {src_path!r} should be a file")
123
+ if not overwrite and self.exists(dst_path):
124
+ raise DestinationExists(f"destination {dst_path!r} already exists")
125
+ if not self.isdir(dirname(dst_path)):
126
+ raise DirectoryExpected(f"path {dirname(dst_path)!r} should be a directory")
127
+ copy_file(self, src_path, self, dst_path)
128
+
129
+ def copydir(self, src_path: str, dst_path: str, create=False):
130
+ if not create and not self.exists(dst_path):
131
+ raise ResourceNotFound(f"{dst_path!r} does not exist")
132
+ if not self.isdir(src_path):
133
+ raise DirectoryExpected(f"path {src_path!r} should be a directory")
134
+ copy_dir(self, src_path, self, dst_path)
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ import typing
4
+
5
+ from ._errors import IllegalDestination
6
+ from ._path import combine, frombase, isbase
7
+ from ._tools import copy_file_data
8
+
9
+ if typing.TYPE_CHECKING:
10
+ from ._base import FS
11
+
12
+
13
+ def copy_file(src_fs: FS, src_path: str, dst_fs: FS, dst_path: str):
14
+ if src_fs is dst_fs and src_path == dst_path:
15
+ raise IllegalDestination(f"cannot copy {src_path!r} to itself")
16
+
17
+ with src_fs.open(src_path, "rb") as src_file:
18
+ with dst_fs.open(dst_path, "wb") as dst_file:
19
+ copy_file_data(src_file, dst_file)
20
+
21
+
22
+ def copy_structure(
23
+ src_fs: FS,
24
+ dst_fs: FS,
25
+ src_root: str = "/",
26
+ dst_root: str = "/",
27
+ ):
28
+ if src_fs is dst_fs and isbase(src_root, dst_root):
29
+ raise IllegalDestination(f"cannot copy {src_fs!r} to itself")
30
+
31
+ dst_fs.makedirs(dst_root, recreate=True)
32
+ for dir_path in src_fs.walk.dirs(src_root):
33
+ dst_fs.makedir(combine(dst_root, frombase(src_root, dir_path)), recreate=True)
34
+
35
+
36
+ def copy_dir(src_fs: FS, src_path: str, dst_fs: FS, dst_path: str):
37
+ copy_structure(src_fs, dst_fs, src_path, dst_path)
38
+
39
+ for file_path in src_fs.walk.files(src_path):
40
+ copy_path = combine(dst_path, frombase(src_path, file_path))
41
+ copy_file(src_fs, file_path, dst_fs, copy_path)
42
+
43
+
44
+ def copy_fs(src_fs: FS, dst_fs: FS):
45
+ copy_dir(src_fs, "/", dst_fs, "/")
@@ -0,0 +1,54 @@
1
+ class FSError(Exception):
2
+ pass
3
+
4
+
5
+ class CreateFailed(FSError):
6
+ pass
7
+
8
+
9
+ class FilesystemClosed(FSError):
10
+ pass
11
+
12
+
13
+ class MissingInfoNamespace(FSError):
14
+ pass
15
+
16
+
17
+ class NoSysPath(FSError):
18
+ pass
19
+
20
+
21
+ class OperationFailed(FSError):
22
+ pass
23
+
24
+
25
+ class IllegalDestination(OperationFailed):
26
+ pass
27
+
28
+
29
+ class ResourceError(FSError):
30
+ pass
31
+
32
+
33
+ class ResourceNotFound(ResourceError):
34
+ pass
35
+
36
+
37
+ class DirectoryExpected(ResourceError):
38
+ pass
39
+
40
+
41
+ class DirectoryNotEmpty(ResourceError):
42
+ pass
43
+
44
+
45
+ class FileExpected(ResourceError):
46
+ pass
47
+
48
+
49
+ class DestinationExists(ResourceError):
50
+ pass
51
+
52
+
53
+ class ResourceReadOnly(ResourceError):
54
+ pass
@@ -0,0 +1,75 @@
1
+ from __future__ import annotations
2
+
3
+ import typing
4
+ from datetime import datetime, timezone
5
+
6
+ from ._errors import MissingInfoNamespace
7
+
8
+ if typing.TYPE_CHECKING:
9
+ from collections.abc import Mapping
10
+ from typing import Any
11
+
12
+
13
+ def epoch_to_datetime(t: int | None) -> datetime | None:
14
+ """Convert epoch time to a UTC datetime."""
15
+ if t is None:
16
+ return None
17
+ return datetime.fromtimestamp(t, tz=timezone.utc)
18
+
19
+
20
+ class Info:
21
+ __slots__ = ["raw", "namespaces"]
22
+
23
+ def __init__(self, raw_info: Mapping[str, Any]):
24
+ self.raw = raw_info
25
+ self.namespaces = frozenset(raw_info.keys())
26
+
27
+ def get(self, namespace: str, key: str, default: Any | None = None) -> Any | None:
28
+ try:
29
+ return self.raw[namespace].get(key, default)
30
+ except KeyError:
31
+ raise MissingInfoNamespace(f"Namespace {namespace!r} does not exist")
32
+
33
+ @property
34
+ def name(self) -> str:
35
+ return self.get("basic", "name")
36
+
37
+ @property
38
+ def is_dir(self) -> bool:
39
+ return self.get("basic", "is_dir")
40
+
41
+ @property
42
+ def is_file(self) -> bool:
43
+ return not self.is_dir
44
+
45
+ @property
46
+ def accessed(self) -> datetime | None:
47
+ return epoch_to_datetime(self.get("details", "accessed"))
48
+
49
+ @property
50
+ def modified(self) -> datetime | None:
51
+ return epoch_to_datetime(self.get("details", "modified"))
52
+
53
+ @property
54
+ def size(self) -> int | None:
55
+ return self.get("details", "size")
56
+
57
+ @property
58
+ def type(self) -> int | None:
59
+ return self.get("details", "type")
60
+
61
+ @property
62
+ def created(self) -> datetime | None:
63
+ return epoch_to_datetime(self.get("details", "created"))
64
+
65
+ @property
66
+ def metadata_changed(self) -> datetime | None:
67
+ return epoch_to_datetime(self.get("details", "metadata_changed"))
68
+
69
+ def __str__(self) -> str:
70
+ if self.is_dir:
71
+ return "<dir '{}'>".format(self.name)
72
+ else:
73
+ return "<file '{}'>".format(self.name)
74
+
75
+ __repr__ = __str__
@@ -0,0 +1,164 @@
1
+ from __future__ import annotations
2
+
3
+ import errno
4
+ import platform
5
+ import shutil
6
+ import stat
7
+ import typing
8
+ from os import PathLike
9
+ from pathlib import Path
10
+
11
+ from ._base import FS
12
+ from ._errors import (
13
+ CreateFailed,
14
+ DirectoryExpected,
15
+ DirectoryNotEmpty,
16
+ FileExpected,
17
+ IllegalDestination,
18
+ ResourceError,
19
+ ResourceNotFound,
20
+ )
21
+ from ._info import Info
22
+ from ._path import isbase
23
+
24
+ if typing.TYPE_CHECKING:
25
+ from collections.abc import Collection
26
+ from typing import IO, Any
27
+
28
+ from ._subfs import SubFS
29
+
30
+
31
+ _WINDOWS_PLATFORM = platform.system() == "Windows"
32
+
33
+
34
+ class OSFS(FS):
35
+ """Filesystem for a directory on the local disk.
36
+
37
+ A thin layer on top of `pathlib.Path`.
38
+ """
39
+
40
+ def __init__(self, root: str | PathLike, create: bool = False):
41
+ super().__init__()
42
+ self._root = Path(root).resolve()
43
+ if create:
44
+ self._root.mkdir(parents=True, exist_ok=True)
45
+ else:
46
+ if not self._root.is_dir():
47
+ raise CreateFailed(
48
+ f"unable to create OSFS: {root!r} does not exist or is not a directory"
49
+ )
50
+
51
+ def _abs(self, rel_path: str) -> Path:
52
+ self.check()
53
+ return (self._root / rel_path.strip("/")).resolve()
54
+
55
+ def open(self, path: str, mode: str = "rb", **kwargs) -> IO[Any]:
56
+ try:
57
+ return self._abs(path).open(mode, **kwargs)
58
+ except FileNotFoundError:
59
+ raise ResourceNotFound(f"No such file or directory: {path!r}")
60
+
61
+ def exists(self, path: str) -> bool:
62
+ return self._abs(path).exists()
63
+
64
+ def isdir(self, path: str) -> bool:
65
+ return self._abs(path).is_dir()
66
+
67
+ def isfile(self, path: str) -> bool:
68
+ return self._abs(path).is_file()
69
+
70
+ def listdir(self, path: str) -> list[str]:
71
+ return [p.name for p in self._abs(path).iterdir()]
72
+
73
+ def _mkdir(self, path: str, parents: bool = False, exist_ok: bool = False) -> SubFS:
74
+ self._abs(path).mkdir(parents=parents, exist_ok=exist_ok)
75
+ return self.opendir(path)
76
+
77
+ def makedir(self, path: str, recreate: bool = False) -> SubFS:
78
+ return self._mkdir(path, parents=False, exist_ok=recreate)
79
+
80
+ def makedirs(self, path: str, recreate: bool = False) -> SubFS:
81
+ return self._mkdir(path, parents=True, exist_ok=recreate)
82
+
83
+ def getinfo(self, path: str, namespaces: Collection[str] | None = None) -> Info:
84
+ path = self._abs(path)
85
+ if not path.exists():
86
+ raise ResourceNotFound(f"No such file or directory: {str(path)!r}")
87
+ info = {
88
+ "basic": {
89
+ "name": path.name,
90
+ "is_dir": path.is_dir(),
91
+ }
92
+ }
93
+ namespaces = namespaces or ()
94
+ if "details" in namespaces:
95
+ stat_result = path.stat()
96
+ details = info["details"] = {
97
+ "accessed": stat_result.st_atime,
98
+ "modified": stat_result.st_mtime,
99
+ "size": stat_result.st_size,
100
+ "type": stat.S_IFMT(stat_result.st_mode),
101
+ "created": getattr(stat_result, "st_birthtime", None),
102
+ }
103
+ ctime_key = "created" if _WINDOWS_PLATFORM else "metadata_changed"
104
+ details[ctime_key] = stat_result.st_ctime
105
+ return Info(info)
106
+
107
+ def remove(self, path: str):
108
+ path = self._abs(path)
109
+ try:
110
+ path.unlink()
111
+ except FileNotFoundError:
112
+ raise ResourceNotFound(f"No such file or directory: {str(path)!r}")
113
+ except OSError as e:
114
+ if path.is_dir():
115
+ raise FileExpected(f"path {str(path)!r} should be a file")
116
+ else:
117
+ raise ResourceError(f"unable to remove {str(path)!r}: {e}")
118
+
119
+ def removedir(self, path: str):
120
+ try:
121
+ self._abs(path).rmdir()
122
+ except NotADirectoryError:
123
+ raise DirectoryExpected(f"path {path!r} should be a directory")
124
+ except OSError as e:
125
+ if e.errno == errno.ENOTEMPTY:
126
+ raise DirectoryNotEmpty(f"Directory not empty: {path!r}")
127
+ else:
128
+ raise ResourceError(f"unable to remove {path!r}: {e}")
129
+
130
+ def removetree(self, path: str):
131
+ shutil.rmtree(self._abs(path))
132
+
133
+ def movedir(self, src_dir: str, dst_dir: str, create: bool = False):
134
+ if isbase(src_dir, dst_dir):
135
+ raise IllegalDestination(f"cannot move {src_dir!r} to {dst_dir!r}")
136
+ src_path = self._abs(src_dir)
137
+ if not src_path.exists():
138
+ raise ResourceNotFound(f"Source {src_dir!r} does not exist")
139
+ elif not src_path.is_dir():
140
+ raise DirectoryExpected(f"Source {src_dir!r} should be a directory")
141
+ dst_path = self._abs(dst_dir)
142
+ if not create and not dst_path.exists():
143
+ raise ResourceNotFound(f"Destination {dst_dir!r} does not exist")
144
+ if dst_path.is_file():
145
+ raise DirectoryExpected(f"Destination {dst_dir!r} should be a directory")
146
+ if create:
147
+ dst_path.parent.mkdir(parents=True, exist_ok=True)
148
+ if dst_path.exists():
149
+ if list(dst_path.iterdir()):
150
+ raise DirectoryNotEmpty(f"Destination {dst_dir!r} is not empty")
151
+ elif _WINDOWS_PLATFORM:
152
+ # on Unix os.rename silently replaces an empty dst_dir whereas on
153
+ # Windows it always raises FileExistsError, empty or not.
154
+ dst_path.rmdir()
155
+ src_path.rename(dst_path)
156
+
157
+ def getsyspath(self, path: str) -> str:
158
+ return str(self._abs(path))
159
+
160
+ def __repr__(self) -> str:
161
+ return f"{self.__class__.__name__}({str(self._root)!r})"
162
+
163
+ def __str__(self) -> str:
164
+ return f"<{self.__class__.__name__.lower()} '{self._root}'>"