sparse_patterns.py 14 KB

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