sparse_patterns.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. # sparse_patterns.py -- Sparse checkout pattern handling.
  2. # Copyright (C) 2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  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. """Sparse checkout pattern handling."""
  22. __all__ = [
  23. "BlobNotFoundError",
  24. "SparseCheckoutConflictError",
  25. "apply_included_paths",
  26. "compute_included_paths_cone",
  27. "compute_included_paths_full",
  28. "determine_included_paths",
  29. "match_gitignore_patterns",
  30. "parse_sparse_patterns",
  31. ]
  32. import os
  33. from collections.abc import Sequence, Set
  34. from fnmatch import fnmatch
  35. from .file import ensure_dir_exists
  36. from .index import Index, IndexEntry
  37. from .objects import Blob
  38. from .repo import Repo
  39. class SparseCheckoutConflictError(Exception):
  40. """Raised when local modifications would be overwritten by a sparse checkout operation."""
  41. class BlobNotFoundError(Exception):
  42. """Raised when a requested blob is not found in the repository's object store."""
  43. def determine_included_paths(
  44. index: Index, lines: Sequence[str], cone: bool
  45. ) -> set[str]:
  46. """Determine which paths in the index should be included based on either a full-pattern match or a cone-mode approach.
  47. Args:
  48. index: An Index object containing the repository's index.
  49. lines: A list of pattern lines (strings) from sparse-checkout config.
  50. cone: A bool indicating cone mode.
  51. Returns:
  52. A set of included path strings.
  53. """
  54. if cone:
  55. return compute_included_paths_cone(index, lines)
  56. else:
  57. return compute_included_paths_full(index, lines)
  58. def compute_included_paths_full(index: Index, lines: Sequence[str]) -> set[str]:
  59. """Use .gitignore-style parsing and matching to determine included paths.
  60. Each file path in the index is tested against the parsed sparse patterns.
  61. If it matches the final (most recently applied) positive pattern, it is included.
  62. Args:
  63. index: An Index object containing the repository's index.
  64. lines: A list of pattern lines (strings) from sparse-checkout config.
  65. Returns:
  66. A set of included path strings.
  67. """
  68. parsed = parse_sparse_patterns(lines)
  69. included = set()
  70. for path_bytes, entry in index.items():
  71. path_str = path_bytes.decode("utf-8")
  72. # For .gitignore logic, match_gitignore_patterns returns True if 'included'
  73. if match_gitignore_patterns(path_str, parsed, path_is_dir=False):
  74. included.add(path_str)
  75. return included
  76. def compute_included_paths_cone(index: Index, lines: Sequence[str]) -> set[str]:
  77. """Implement a simplified 'cone' approach for sparse-checkout.
  78. By default, this can include top-level files, exclude all subdirectories,
  79. and re-include specified directories. The logic is less comprehensive than
  80. Git's built-in cone mode (recursive vs parent) and is essentially an implementation
  81. of the recursive cone mode.
  82. Args:
  83. index: An Index object containing the repository's index.
  84. lines: A list of pattern lines (strings), typically including entries like
  85. "/*", "!/*/", or "/mydir/".
  86. Returns:
  87. A set of included path strings.
  88. """
  89. include_top_level = False
  90. exclude_subdirs = False
  91. reinclude_dirs = set()
  92. for pat in lines:
  93. if pat == "/*":
  94. include_top_level = True
  95. elif pat == "!/*/":
  96. exclude_subdirs = True
  97. elif pat.startswith("/"):
  98. # strip leading '/' and trailing '/'
  99. d = pat.strip("/")
  100. if d:
  101. reinclude_dirs.add(d)
  102. included = set()
  103. for path_bytes, entry in index.items():
  104. path_str = path_bytes.decode("utf-8")
  105. # Check if this is top-level (no slash) or which top_dir it belongs to
  106. if "/" not in path_str:
  107. # top-level file
  108. if include_top_level:
  109. included.add(path_str)
  110. continue
  111. top_dir = path_str.split("/", 1)[0]
  112. if exclude_subdirs:
  113. # subdirs are excluded unless they appear in reinclude_dirs
  114. if top_dir in reinclude_dirs:
  115. included.add(path_str)
  116. else:
  117. # if we never set exclude_subdirs, we might include everything by default
  118. # or handle partial subdir logic. For now, let's assume everything is included
  119. included.add(path_str)
  120. return included
  121. def apply_included_paths(
  122. repo: Repo, included_paths: Set[str], force: bool = False
  123. ) -> None:
  124. """Apply the sparse-checkout inclusion set to the index and working tree.
  125. This function updates skip-worktree bits in the index based on whether each
  126. path is included or not. It then adds or removes files in the working tree
  127. accordingly. If ``force=False``, files that have local modifications
  128. will cause an error instead of being removed.
  129. Args:
  130. repo: A path to the repository or a Repo object.
  131. included_paths: A set of paths (strings) that should remain included.
  132. force: Whether to forcibly remove locally modified files (default False).
  133. Returns:
  134. None
  135. """
  136. index = repo.open_index()
  137. normalizer = repo.get_blob_normalizer()
  138. def local_modifications_exist(full_path: str, index_entry: IndexEntry) -> bool:
  139. if not os.path.exists(full_path):
  140. return False
  141. with open(full_path, "rb") as f:
  142. disk_data = f.read()
  143. try:
  144. blob_obj = repo.object_store[index_entry.sha]
  145. except KeyError:
  146. return True
  147. disk_blob = Blob.from_string(disk_data)
  148. norm_blob = normalizer.checkin_normalize(disk_blob, full_path.encode("utf-8"))
  149. norm_data = norm_blob.data
  150. if not isinstance(blob_obj, Blob):
  151. return True
  152. return bool(norm_data != blob_obj.data)
  153. # 1) Update skip-worktree bits
  154. for path_bytes, entry in list(index.items()):
  155. if not isinstance(entry, IndexEntry):
  156. continue # Skip conflicted entries
  157. path_str = path_bytes.decode("utf-8")
  158. if path_str in included_paths:
  159. entry.set_skip_worktree(False)
  160. else:
  161. entry.set_skip_worktree(True)
  162. index[path_bytes] = entry
  163. index.write()
  164. # 2) Reflect changes in the working tree
  165. for path_bytes, entry in list(index.items()):
  166. if not isinstance(entry, IndexEntry):
  167. continue # Skip conflicted entries
  168. full_path = os.path.join(repo.path, path_bytes.decode("utf-8"))
  169. if entry.skip_worktree:
  170. # Excluded => remove if safe
  171. if os.path.exists(full_path):
  172. if not force and local_modifications_exist(full_path, entry):
  173. raise SparseCheckoutConflictError(
  174. f"Local modifications in {full_path} would be overwritten "
  175. "by sparse checkout. Use force=True to override."
  176. )
  177. try:
  178. os.remove(full_path)
  179. except IsADirectoryError:
  180. pass
  181. except FileNotFoundError:
  182. pass
  183. except PermissionError:
  184. if not force:
  185. raise
  186. else:
  187. # Included => materialize if missing
  188. if not os.path.exists(full_path):
  189. try:
  190. blob = repo.object_store[entry.sha]
  191. except KeyError:
  192. raise BlobNotFoundError(
  193. f"Blob {entry.sha.hex()} not found for {path_bytes.decode('utf-8')}."
  194. )
  195. ensure_dir_exists(os.path.dirname(full_path))
  196. # Apply checkout normalization if normalizer is available
  197. if normalizer and isinstance(blob, Blob):
  198. blob = normalizer.checkout_normalize(blob, path_bytes)
  199. with open(full_path, "wb") as f:
  200. if isinstance(blob, Blob):
  201. f.write(blob.data)
  202. def parse_sparse_patterns(lines: Sequence[str]) -> list[tuple[str, bool, bool, bool]]:
  203. """Parse pattern lines from a sparse-checkout file (.git/info/sparse-checkout).
  204. This simplified parser:
  205. 1. Strips comments (#...) and empty lines.
  206. 2. Returns a list of (pattern, is_negation, is_dir_only, anchored) tuples.
  207. These lines are similar to .gitignore patterns but are used for sparse-checkout
  208. logic. This function strips comments and blank lines, identifies negation,
  209. anchoring, and directory-only markers, and returns data suitable for matching.
  210. Example:
  211. ``line = "/*.txt" -> ("/.txt", False, False, True)``
  212. ``line = "!/docs/" -> ("/docs/", True, True, True)``
  213. ``line = "mydir/" -> ("mydir/", False, True, False)`` not anchored, no leading "/"
  214. Args:
  215. lines: A list of raw lines (strings) from the sparse-checkout file.
  216. Returns:
  217. A list of tuples (pattern, negation, dir_only, anchored), representing
  218. the essential details needed to perform matching.
  219. """
  220. results = []
  221. for raw_line in lines:
  222. line = raw_line.strip()
  223. if not line or line.startswith("#"):
  224. continue # ignore comments and blank lines
  225. negation = line.startswith("!")
  226. if negation:
  227. line = line[1:] # remove leading '!'
  228. anchored = line.startswith("/")
  229. if anchored:
  230. line = line[1:] # remove leading '/'
  231. # If pattern ends with '/', we consider it directory-only
  232. # (like "docs/"). Real Git might treat it slightly differently,
  233. # but we'll simplify and mark it as "dir_only" if it ends in "/".
  234. dir_only = False
  235. if line.endswith("/"):
  236. dir_only = True
  237. line = line[:-1]
  238. results.append((line, negation, dir_only, anchored))
  239. return results
  240. def match_gitignore_patterns(
  241. path_str: str,
  242. parsed_patterns: Sequence[tuple[str, bool, bool, bool]],
  243. path_is_dir: bool = False,
  244. ) -> bool:
  245. """Check whether a path is included based on .gitignore-style patterns.
  246. This is a simplified approach that:
  247. 1. Iterates over patterns in order.
  248. 2. If a pattern matches, we set the "include" state depending on negation.
  249. 3. Later matches override earlier ones.
  250. In a .gitignore sense, lines that do not start with '!' are "ignore" patterns,
  251. lines that start with '!' are "unignore" (re-include). But in sparse checkout,
  252. it's effectively reversed: a non-negation line is "include," negation is "exclude."
  253. However, many flows still rely on the same final logic: the last matching pattern
  254. decides "excluded" vs. "included."
  255. We'll interpret "include" as returning True, "exclude" as returning False.
  256. Each pattern can include negation (!), directory-only markers, or be anchored
  257. to the start of the path. The last matching pattern determines whether the
  258. path is ultimately included or excluded.
  259. Args:
  260. path_str: The path (string) to test.
  261. parsed_patterns: A list of (pattern, negation, dir_only, anchored) tuples
  262. as returned by parse_sparse_patterns.
  263. path_is_dir: Whether to treat the path as a directory (default False).
  264. Returns:
  265. True if the path is included by the last matching pattern, False otherwise.
  266. """
  267. # Start by assuming "excluded" (like a .gitignore starts by including everything
  268. # until matched, but for sparse-checkout we often treat unmatched as "excluded").
  269. # We will flip if we match an "include" pattern.
  270. is_included = False
  271. for pattern, negation, dir_only, anchored in parsed_patterns:
  272. forbidden_path = dir_only and not path_is_dir
  273. if path_str == pattern:
  274. if forbidden_path:
  275. continue
  276. else:
  277. matched = True
  278. else:
  279. matched = False
  280. # If dir_only is True and path_is_dir is False, we skip matching
  281. if dir_only and not matched:
  282. if path_str == pattern + "/":
  283. matched = not forbidden_path
  284. elif fnmatch(path_str, f"{pattern}/*"):
  285. matched = True # root subpath (anchored or unanchored)
  286. elif not anchored:
  287. matched = fnmatch(path_str, f"*/{pattern}/*") # unanchored subpath
  288. # If anchored is True, pattern should match from the start of path_str.
  289. # If not anchored, we can match anywhere.
  290. if anchored and not matched:
  291. # We match from the beginning. For example, pattern = "docs"
  292. # path_str = "docs/readme.md" -> start is "docs"
  293. # We'll just do a prefix check or prefix + slash check
  294. # Or you can do a partial fnmatch. We'll do a manual approach:
  295. if pattern == "":
  296. # Means it was just "/", which can happen if line was "/"
  297. # That might represent top-level only?
  298. # We'll skip for simplicity or treat it as a special case.
  299. continue
  300. elif path_str == pattern:
  301. matched = True
  302. elif path_str.startswith(pattern + "/"):
  303. matched = True
  304. else:
  305. matched = False
  306. elif not matched:
  307. # Not anchored: we can do a simple wildcard match or a substring match.
  308. # For simplicity, let's use Python's fnmatch:
  309. matched = fnmatch(path_str, pattern) or fnmatch(path_str, f"*/{pattern}")
  310. if matched:
  311. # If negation is True, that means 'exclude'. If negation is False, 'include'.
  312. is_included = not negation
  313. # The last matching pattern overrides, so we continue checking until the end.
  314. return is_included