sparse_patterns.py 14 KB

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