attrs.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 published 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, Iterator, Mapping, Sequence
  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. """Initialize GitAttributesPattern.
  145. Args:
  146. pattern: Attribute pattern as bytes
  147. """
  148. self.pattern = pattern
  149. self._regex: Optional[re.Pattern[bytes]] = None
  150. self._compile()
  151. def _compile(self) -> None:
  152. """Compile the pattern to a regular expression."""
  153. regex_pattern = _translate_pattern(self.pattern)
  154. # Add anchors
  155. regex_pattern = b"^" + regex_pattern + b"$"
  156. self._regex = re.compile(regex_pattern)
  157. def match(self, path: bytes) -> bool:
  158. """Check if path matches this pattern.
  159. Args:
  160. path: Path to check (relative to repository root, using / separators)
  161. Returns:
  162. True if path matches this pattern
  163. """
  164. # Normalize path
  165. if path.startswith(b"/"):
  166. path = path[1:]
  167. # Try to match
  168. assert self._regex is not None # Always set by _compile()
  169. return bool(self._regex.match(path))
  170. def match_path(
  171. patterns: Sequence[tuple[Pattern, Mapping[bytes, AttributeValue]]], path: bytes
  172. ) -> dict[bytes, AttributeValue]:
  173. """Get attributes for a path by matching against patterns.
  174. Args:
  175. patterns: List of (Pattern, attributes) tuples
  176. path: Path to match (relative to repository root)
  177. Returns:
  178. Dictionary of attributes that apply to this path
  179. """
  180. attributes: dict[bytes, AttributeValue] = {}
  181. # Later patterns override earlier ones
  182. for pattern, attrs in patterns:
  183. if pattern.match(path):
  184. # Update attributes
  185. for name, value in attrs.items():
  186. if value is None:
  187. # Unspecified - remove the attribute
  188. attributes.pop(name, None)
  189. else:
  190. attributes[name] = value
  191. return attributes
  192. def parse_gitattributes_file(
  193. filename: Union[str, bytes],
  194. ) -> list[tuple[Pattern, Mapping[bytes, AttributeValue]]]:
  195. """Parse a gitattributes file and return compiled patterns.
  196. Args:
  197. filename: Path to the .gitattributes file
  198. Returns:
  199. List of (Pattern, attributes) tuples
  200. """
  201. patterns = []
  202. if isinstance(filename, str):
  203. filename = filename.encode("utf-8")
  204. with open(filename, "rb") as f:
  205. for pattern_bytes, attrs in parse_git_attributes(f):
  206. pattern = Pattern(pattern_bytes)
  207. patterns.append((pattern, attrs))
  208. return patterns
  209. def read_gitattributes(
  210. path: Union[str, bytes],
  211. ) -> list[tuple[Pattern, Mapping[bytes, AttributeValue]]]:
  212. """Read .gitattributes from a directory.
  213. Args:
  214. path: Directory path to check for .gitattributes
  215. Returns:
  216. List of (Pattern, attributes) tuples
  217. """
  218. if isinstance(path, bytes):
  219. path = path.decode("utf-8")
  220. gitattributes_path = os.path.join(path, ".gitattributes")
  221. if os.path.exists(gitattributes_path):
  222. return parse_gitattributes_file(gitattributes_path)
  223. return []
  224. class GitAttributes:
  225. """A collection of gitattributes patterns that can match paths."""
  226. def __init__(
  227. self,
  228. patterns: Optional[list[tuple[Pattern, Mapping[bytes, AttributeValue]]]] = None,
  229. ):
  230. """Initialize GitAttributes.
  231. Args:
  232. patterns: Optional list of (Pattern, attributes) tuples
  233. """
  234. self._patterns = patterns or []
  235. def match_path(self, path: bytes) -> dict[bytes, AttributeValue]:
  236. """Get attributes for a path by matching against patterns.
  237. Args:
  238. path: Path to match (relative to repository root)
  239. Returns:
  240. Dictionary of attributes that apply to this path
  241. """
  242. return match_path(self._patterns, path)
  243. def add_patterns(
  244. self, patterns: Sequence[tuple[Pattern, Mapping[bytes, AttributeValue]]]
  245. ) -> None:
  246. """Add patterns to the collection.
  247. Args:
  248. patterns: List of (Pattern, attributes) tuples to add
  249. """
  250. self._patterns.extend(patterns)
  251. def __len__(self) -> int:
  252. """Return the number of patterns."""
  253. return len(self._patterns)
  254. def __iter__(self) -> Iterator[tuple["Pattern", Mapping[bytes, AttributeValue]]]:
  255. """Iterate over patterns."""
  256. return iter(self._patterns)
  257. @classmethod
  258. def from_file(cls, filename: Union[str, bytes]) -> "GitAttributes":
  259. """Create GitAttributes from a gitattributes file.
  260. Args:
  261. filename: Path to the .gitattributes file
  262. Returns:
  263. New GitAttributes instance
  264. """
  265. patterns = parse_gitattributes_file(filename)
  266. return cls(patterns)
  267. @classmethod
  268. def from_path(cls, path: Union[str, bytes]) -> "GitAttributes":
  269. """Create GitAttributes from .gitattributes in a directory.
  270. Args:
  271. path: Directory path to check for .gitattributes
  272. Returns:
  273. New GitAttributes instance
  274. """
  275. patterns = read_gitattributes(path)
  276. return cls(patterns)
  277. def set_attribute(self, pattern: bytes, name: bytes, value: AttributeValue) -> None:
  278. """Set an attribute for a pattern.
  279. Args:
  280. pattern: The file pattern
  281. name: Attribute name
  282. value: Attribute value (bytes, True, False, or None)
  283. """
  284. # Find existing pattern
  285. pattern_obj = None
  286. attrs_dict: Optional[dict[bytes, AttributeValue]] = None
  287. pattern_index = -1
  288. for i, (p, attrs) in enumerate(self._patterns):
  289. if p.pattern == pattern:
  290. pattern_obj = p
  291. # Convert to mutable dict
  292. attrs_dict = dict(attrs)
  293. pattern_index = i
  294. break
  295. if pattern_obj is None:
  296. # Create new pattern
  297. pattern_obj = Pattern(pattern)
  298. attrs_dict = {name: value}
  299. self._patterns.append((pattern_obj, attrs_dict))
  300. else:
  301. # Update the existing pattern in the list
  302. assert pattern_index >= 0
  303. assert attrs_dict is not None
  304. self._patterns[pattern_index] = (pattern_obj, attrs_dict)
  305. # Update the attribute
  306. if attrs_dict is None:
  307. raise AssertionError("attrs_dict should not be None at this point")
  308. attrs_dict[name] = value
  309. def remove_pattern(self, pattern: bytes) -> None:
  310. """Remove all attributes for a pattern.
  311. Args:
  312. pattern: The file pattern to remove
  313. """
  314. self._patterns = [
  315. (p, attrs) for p, attrs in self._patterns if p.pattern != pattern
  316. ]
  317. def to_bytes(self) -> bytes:
  318. """Convert GitAttributes to bytes format suitable for writing to file.
  319. Returns:
  320. Bytes representation of the gitattributes file
  321. """
  322. lines = []
  323. for pattern_obj, attrs in self._patterns:
  324. pattern = pattern_obj.pattern
  325. attr_strs = []
  326. for name, value in sorted(attrs.items()):
  327. if value is True:
  328. attr_strs.append(name)
  329. elif value is False:
  330. attr_strs.append(b"-" + name)
  331. elif value is None:
  332. attr_strs.append(b"!" + name)
  333. else:
  334. # value is bytes
  335. attr_strs.append(name + b"=" + value)
  336. if attr_strs:
  337. line = pattern + b" " + b" ".join(attr_strs)
  338. lines.append(line)
  339. return b"\n".join(lines) + b"\n" if lines else b""
  340. def write_to_file(self, filename: Union[str, bytes]) -> None:
  341. """Write GitAttributes to a file.
  342. Args:
  343. filename: Path to write the .gitattributes file
  344. """
  345. if isinstance(filename, str):
  346. filename = filename.encode("utf-8")
  347. content = self.to_bytes()
  348. with open(filename, "wb") as f:
  349. f.write(content)