attrs.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. # attrs.py -- Git attributes for dulwich
  2. # Copyright (C) 2019-2020 Collabora Ltd
  3. # Copyright (C) 2019-2020 Andrej Shadura <andrew.shadura@collabora.co.uk>
  4. #
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Parse .gitattributes file."""
  22. import os
  23. import re
  24. from collections.abc import Generator, Mapping
  25. from typing import (
  26. IO,
  27. Optional,
  28. Union,
  29. )
  30. AttributeValue = Union[bytes, bool, None]
  31. def _parse_attr(attr: bytes) -> tuple[bytes, AttributeValue]:
  32. """Parse a git attribute into its value.
  33. >>> _parse_attr(b'attr')
  34. (b'attr', True)
  35. >>> _parse_attr(b'-attr')
  36. (b'attr', False)
  37. >>> _parse_attr(b'!attr')
  38. (b'attr', None)
  39. >>> _parse_attr(b'attr=text')
  40. (b'attr', b'text')
  41. """
  42. if attr.startswith(b"!"):
  43. return attr[1:], None
  44. if attr.startswith(b"-"):
  45. return attr[1:], False
  46. if b"=" not in attr:
  47. return attr, True
  48. # Split only on first = to handle values with = in them
  49. name, _, value = attr.partition(b"=")
  50. return name, value
  51. def parse_git_attributes(
  52. f: IO[bytes],
  53. ) -> Generator[tuple[bytes, Mapping[bytes, AttributeValue]], None, None]:
  54. """Parse a Git attributes string.
  55. Args:
  56. f: File-like object to read bytes from
  57. Returns:
  58. List of patterns and corresponding patterns in the order or them being encountered
  59. >>> from io import BytesIO
  60. >>> list(parse_git_attributes(BytesIO(b'''*.tar.* filter=lfs diff=lfs merge=lfs -text
  61. ...
  62. ... # store signatures in Git
  63. ... *.tar.*.asc -filter -diff merge=binary -text
  64. ...
  65. ... # store .dsc verbatim
  66. ... *.dsc -filter !diff merge=binary !text
  67. ... '''))) #doctest: +NORMALIZE_WHITESPACE
  68. [(b'*.tar.*', {'filter': 'lfs', 'diff': 'lfs', 'merge': 'lfs', 'text': False}),
  69. (b'*.tar.*.asc', {'filter': False, 'diff': False, 'merge': 'binary', 'text': False}),
  70. (b'*.dsc', {'filter': False, 'diff': None, 'merge': 'binary', 'text': None})]
  71. """
  72. for line in f:
  73. line = line.strip()
  74. # Ignore blank lines, they're used for readability.
  75. if not line:
  76. continue
  77. if line.startswith(b"#"):
  78. # Comment
  79. continue
  80. pattern, *attrs = line.split()
  81. yield (pattern, {k: v for k, v in (_parse_attr(a) for a in attrs)})
  82. def _translate_pattern(pattern: bytes) -> bytes:
  83. """Translate a gitattributes pattern to a regular expression.
  84. Similar to gitignore patterns, but simpler as gitattributes doesn't support
  85. all the same features (e.g., no directory-only patterns with trailing /).
  86. """
  87. res = b""
  88. i = 0
  89. n = len(pattern)
  90. # If pattern doesn't contain /, it can match at any level
  91. if b"/" not in pattern:
  92. res = b"(?:.*/)??"
  93. elif pattern.startswith(b"/"):
  94. # Leading / means root of repository
  95. pattern = pattern[1:]
  96. n = len(pattern)
  97. while i < n:
  98. c = pattern[i : i + 1]
  99. i += 1
  100. if c == b"*":
  101. if i < n and pattern[i : i + 1] == b"*":
  102. # Double asterisk
  103. i += 1
  104. if i < n and pattern[i : i + 1] == b"/":
  105. # **/ - match zero or more directories
  106. res += b"(?:.*/)??"
  107. i += 1
  108. elif i == n:
  109. # ** at end - match everything
  110. res += b".*"
  111. else:
  112. # ** in middle
  113. res += b".*"
  114. else:
  115. # Single * - match any character except /
  116. res += b"[^/]*"
  117. elif c == b"?":
  118. res += b"[^/]"
  119. elif c == b"[":
  120. # Character class
  121. j = i
  122. if j < n and pattern[j : j + 1] == b"!":
  123. j += 1
  124. if j < n and pattern[j : j + 1] == b"]":
  125. j += 1
  126. while j < n and pattern[j : j + 1] != b"]":
  127. j += 1
  128. if j >= n:
  129. res += b"\\["
  130. else:
  131. stuff = pattern[i:j].replace(b"\\", b"\\\\")
  132. i = j + 1
  133. if stuff.startswith(b"!"):
  134. stuff = b"^" + stuff[1:]
  135. elif stuff.startswith(b"^"):
  136. stuff = b"\\" + stuff
  137. res += b"[" + stuff + b"]"
  138. else:
  139. res += re.escape(c)
  140. return res
  141. class Pattern:
  142. """A single gitattributes pattern."""
  143. def __init__(self, pattern: bytes):
  144. self.pattern = pattern
  145. self._regex: Optional[re.Pattern[bytes]] = None
  146. self._compile()
  147. def _compile(self):
  148. """Compile the pattern to a regular expression."""
  149. regex_pattern = _translate_pattern(self.pattern)
  150. # Add anchors
  151. regex_pattern = b"^" + regex_pattern + b"$"
  152. self._regex = re.compile(regex_pattern)
  153. def match(self, path: bytes) -> bool:
  154. """Check if path matches this pattern.
  155. Args:
  156. path: Path to check (relative to repository root, using / separators)
  157. Returns:
  158. True if path matches this pattern
  159. """
  160. # Normalize path
  161. if path.startswith(b"/"):
  162. path = path[1:]
  163. # Try to match
  164. assert self._regex is not None # Always set by _compile()
  165. return bool(self._regex.match(path))
  166. def match_path(
  167. patterns: list[tuple[Pattern, Mapping[bytes, AttributeValue]]], path: bytes
  168. ) -> dict[bytes, AttributeValue]:
  169. """Get attributes for a path by matching against patterns.
  170. Args:
  171. patterns: List of (Pattern, attributes) tuples
  172. path: Path to match (relative to repository root)
  173. Returns:
  174. Dictionary of attributes that apply to this path
  175. """
  176. attributes: dict[bytes, AttributeValue] = {}
  177. # Later patterns override earlier ones
  178. for pattern, attrs in patterns:
  179. if pattern.match(path):
  180. # Update attributes
  181. for name, value in attrs.items():
  182. if value is None:
  183. # Unspecified - remove the attribute
  184. attributes.pop(name, None)
  185. else:
  186. attributes[name] = value
  187. return attributes
  188. def parse_gitattributes_file(
  189. filename: Union[str, bytes],
  190. ) -> list[tuple[Pattern, Mapping[bytes, AttributeValue]]]:
  191. """Parse a gitattributes file and return compiled patterns.
  192. Args:
  193. filename: Path to the .gitattributes file
  194. Returns:
  195. List of (Pattern, attributes) tuples
  196. """
  197. patterns = []
  198. if isinstance(filename, str):
  199. filename = filename.encode("utf-8")
  200. with open(filename, "rb") as f:
  201. for pattern_bytes, attrs in parse_git_attributes(f):
  202. pattern = Pattern(pattern_bytes)
  203. patterns.append((pattern, attrs))
  204. return patterns
  205. def read_gitattributes(
  206. path: Union[str, bytes],
  207. ) -> list[tuple[Pattern, Mapping[bytes, AttributeValue]]]:
  208. """Read .gitattributes from a directory.
  209. Args:
  210. path: Directory path to check for .gitattributes
  211. Returns:
  212. List of (Pattern, attributes) tuples
  213. """
  214. if isinstance(path, bytes):
  215. path = path.decode("utf-8")
  216. gitattributes_path = os.path.join(path, ".gitattributes")
  217. if os.path.exists(gitattributes_path):
  218. return parse_gitattributes_file(gitattributes_path)
  219. return []
  220. class GitAttributes:
  221. """A collection of gitattributes patterns that can match paths."""
  222. def __init__(
  223. self,
  224. patterns: Optional[list[tuple[Pattern, Mapping[bytes, AttributeValue]]]] = None,
  225. ):
  226. """Initialize GitAttributes.
  227. Args:
  228. patterns: Optional list of (Pattern, attributes) tuples
  229. """
  230. self._patterns = patterns or []
  231. def match_path(self, path: bytes) -> dict[bytes, AttributeValue]:
  232. """Get attributes for a path by matching against patterns.
  233. Args:
  234. path: Path to match (relative to repository root)
  235. Returns:
  236. Dictionary of attributes that apply to this path
  237. """
  238. return match_path(self._patterns, path)
  239. def add_patterns(
  240. self, patterns: list[tuple[Pattern, Mapping[bytes, AttributeValue]]]
  241. ) -> None:
  242. """Add patterns to the collection.
  243. Args:
  244. patterns: List of (Pattern, attributes) tuples to add
  245. """
  246. self._patterns.extend(patterns)
  247. def __len__(self) -> int:
  248. """Return the number of patterns."""
  249. return len(self._patterns)
  250. def __iter__(self):
  251. """Iterate over patterns."""
  252. return iter(self._patterns)
  253. @classmethod
  254. def from_file(cls, filename: Union[str, bytes]) -> "GitAttributes":
  255. """Create GitAttributes from a gitattributes file.
  256. Args:
  257. filename: Path to the .gitattributes file
  258. Returns:
  259. New GitAttributes instance
  260. """
  261. patterns = parse_gitattributes_file(filename)
  262. return cls(patterns)
  263. @classmethod
  264. def from_path(cls, path: Union[str, bytes]) -> "GitAttributes":
  265. """Create GitAttributes from .gitattributes in a directory.
  266. Args:
  267. path: Directory path to check for .gitattributes
  268. Returns:
  269. New GitAttributes instance
  270. """
  271. patterns = read_gitattributes(path)
  272. return cls(patterns)
  273. def set_attribute(self, pattern: bytes, name: bytes, value: AttributeValue) -> None:
  274. """Set an attribute for a pattern.
  275. Args:
  276. pattern: The file pattern
  277. name: Attribute name
  278. value: Attribute value (bytes, True, False, or None)
  279. """
  280. # Find existing pattern
  281. pattern_obj = None
  282. pattern_index = None
  283. for i, (p, attrs) in enumerate(self._patterns):
  284. if p.pattern == pattern:
  285. pattern_obj = p
  286. pattern_index = i
  287. break
  288. if pattern_obj is None:
  289. # Create new pattern
  290. pattern_obj = Pattern(pattern)
  291. attrs_dict: dict[bytes, AttributeValue] = {name: value}
  292. self._patterns.append((pattern_obj, attrs_dict))
  293. else:
  294. # Update existing pattern
  295. # Create a new dict with updated attributes
  296. assert (
  297. pattern_index is not None
  298. ) # pattern_index is set when pattern_obj is found
  299. old_attrs = self._patterns[pattern_index][1]
  300. new_attrs = dict(old_attrs)
  301. new_attrs[name] = value
  302. self._patterns[pattern_index] = (pattern_obj, new_attrs)
  303. def remove_pattern(self, pattern: bytes) -> None:
  304. """Remove all attributes for a pattern.
  305. Args:
  306. pattern: The file pattern to remove
  307. """
  308. self._patterns = [
  309. (p, attrs) for p, attrs in self._patterns if p.pattern != pattern
  310. ]
  311. def to_bytes(self) -> bytes:
  312. """Convert GitAttributes to bytes format suitable for writing to file.
  313. Returns:
  314. Bytes representation of the gitattributes file
  315. """
  316. lines = []
  317. for pattern_obj, attrs in self._patterns:
  318. pattern = pattern_obj.pattern
  319. attr_strs = []
  320. for name, value in sorted(attrs.items()):
  321. if value is True:
  322. attr_strs.append(name)
  323. elif value is False:
  324. attr_strs.append(b"-" + name)
  325. elif value is None:
  326. attr_strs.append(b"!" + name)
  327. else:
  328. # value is bytes
  329. attr_strs.append(name + b"=" + value)
  330. if attr_strs:
  331. line = pattern + b" " + b" ".join(attr_strs)
  332. lines.append(line)
  333. return b"\n".join(lines) + b"\n" if lines else b""
  334. def write_to_file(self, filename: Union[str, bytes]) -> None:
  335. """Write GitAttributes to a file.
  336. Args:
  337. filename: Path to write the .gitattributes file
  338. """
  339. if isinstance(filename, str):
  340. filename = filename.encode("utf-8")
  341. content = self.to_bytes()
  342. with open(filename, "wb") as f:
  343. f.write(content)