2
0

index.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  1. # index.py -- File parser/writer for the git index file
  2. # Copyright (C) 2008-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 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. """Parser for the git index file format."""
  22. import os
  23. import stat
  24. import struct
  25. import sys
  26. from collections.abc import Iterable, Iterator
  27. from dataclasses import dataclass
  28. from enum import Enum
  29. from typing import (
  30. Any,
  31. BinaryIO,
  32. Callable,
  33. Optional,
  34. Union,
  35. )
  36. from .file import GitFile
  37. from .object_store import iter_tree_contents
  38. from .objects import (
  39. S_IFGITLINK,
  40. S_ISGITLINK,
  41. Blob,
  42. ObjectID,
  43. Tree,
  44. hex_to_sha,
  45. sha_to_hex,
  46. )
  47. from .pack import ObjectContainer, SHA1Reader, SHA1Writer
  48. # 2-bit stage (during merge)
  49. FLAG_STAGEMASK = 0x3000
  50. FLAG_STAGESHIFT = 12
  51. FLAG_NAMEMASK = 0x0FFF
  52. # assume-valid
  53. FLAG_VALID = 0x8000
  54. # extended flag (must be zero in version 2)
  55. FLAG_EXTENDED = 0x4000
  56. # used by sparse checkout
  57. EXTENDED_FLAG_SKIP_WORKTREE = 0x4000
  58. # used by "git add -N"
  59. EXTENDED_FLAG_INTEND_TO_ADD = 0x2000
  60. DEFAULT_VERSION = 2
  61. # Index extension signatures
  62. TREE_EXTENSION = b"TREE"
  63. REUC_EXTENSION = b"REUC"
  64. UNTR_EXTENSION = b"UNTR"
  65. EOIE_EXTENSION = b"EOIE"
  66. IEOT_EXTENSION = b"IEOT"
  67. def _encode_varint(value: int) -> bytes:
  68. """Encode an integer using variable-width encoding.
  69. Same format as used for OFS_DELTA pack entries and index v4 path compression.
  70. Uses 7 bits per byte, with the high bit indicating continuation.
  71. Args:
  72. value: Integer to encode
  73. Returns:
  74. Encoded bytes
  75. """
  76. if value == 0:
  77. return b"\x00"
  78. result = []
  79. while value > 0:
  80. byte = value & 0x7F # Take lower 7 bits
  81. value >>= 7
  82. if value > 0:
  83. byte |= 0x80 # Set continuation bit
  84. result.append(byte)
  85. return bytes(result)
  86. def _decode_varint(data: bytes, offset: int = 0) -> tuple[int, int]:
  87. """Decode a variable-width encoded integer.
  88. Args:
  89. data: Bytes to decode from
  90. offset: Starting offset in data
  91. Returns:
  92. tuple of (decoded_value, new_offset)
  93. """
  94. value = 0
  95. shift = 0
  96. pos = offset
  97. while pos < len(data):
  98. byte = data[pos]
  99. pos += 1
  100. value |= (byte & 0x7F) << shift
  101. shift += 7
  102. if not (byte & 0x80): # No continuation bit
  103. break
  104. return value, pos
  105. def _compress_path(path: bytes, previous_path: bytes) -> bytes:
  106. """Compress a path relative to the previous path for index version 4.
  107. Args:
  108. path: Path to compress
  109. previous_path: Previous path for comparison
  110. Returns:
  111. Compressed path data (varint prefix_len + suffix)
  112. """
  113. # Find the common prefix length
  114. common_len = 0
  115. min_len = min(len(path), len(previous_path))
  116. for i in range(min_len):
  117. if path[i] == previous_path[i]:
  118. common_len += 1
  119. else:
  120. break
  121. # The number of bytes to remove from the end of previous_path
  122. # to get the common prefix
  123. remove_len = len(previous_path) - common_len
  124. # The suffix to append
  125. suffix = path[common_len:]
  126. # Encode: varint(remove_len) + suffix + NUL
  127. return _encode_varint(remove_len) + suffix + b"\x00"
  128. def _decompress_path(
  129. data: bytes, offset: int, previous_path: bytes
  130. ) -> tuple[bytes, int]:
  131. """Decompress a path from index version 4 compressed format.
  132. Args:
  133. data: Raw data containing compressed path
  134. offset: Starting offset in data
  135. previous_path: Previous path for decompression
  136. Returns:
  137. tuple of (decompressed_path, new_offset)
  138. """
  139. # Decode the number of bytes to remove from previous path
  140. remove_len, new_offset = _decode_varint(data, offset)
  141. # Find the NUL terminator for the suffix
  142. suffix_start = new_offset
  143. suffix_end = suffix_start
  144. while suffix_end < len(data) and data[suffix_end] != 0:
  145. suffix_end += 1
  146. if suffix_end >= len(data):
  147. raise ValueError("Unterminated path suffix in compressed entry")
  148. suffix = data[suffix_start:suffix_end]
  149. new_offset = suffix_end + 1 # Skip the NUL terminator
  150. # Reconstruct the path
  151. if remove_len > len(previous_path):
  152. raise ValueError(
  153. f"Invalid path compression: trying to remove {remove_len} bytes from {len(previous_path)}-byte path"
  154. )
  155. prefix = previous_path[:-remove_len] if remove_len > 0 else previous_path
  156. path = prefix + suffix
  157. return path, new_offset
  158. def _decompress_path_from_stream(f, previous_path: bytes) -> tuple[bytes, int]:
  159. """Decompress a path from index version 4 compressed format, reading from stream.
  160. Args:
  161. f: File-like object to read from
  162. previous_path: Previous path for decompression
  163. Returns:
  164. tuple of (decompressed_path, bytes_consumed)
  165. """
  166. # Decode the varint for remove_len by reading byte by byte
  167. remove_len = 0
  168. shift = 0
  169. bytes_consumed = 0
  170. while True:
  171. byte_data = f.read(1)
  172. if not byte_data:
  173. raise ValueError("Unexpected end of file while reading varint")
  174. byte = byte_data[0]
  175. bytes_consumed += 1
  176. remove_len |= (byte & 0x7F) << shift
  177. shift += 7
  178. if not (byte & 0x80): # No continuation bit
  179. break
  180. # Read the suffix until NUL terminator
  181. suffix = b""
  182. while True:
  183. byte_data = f.read(1)
  184. if not byte_data:
  185. raise ValueError("Unexpected end of file while reading path suffix")
  186. byte = byte_data[0]
  187. bytes_consumed += 1
  188. if byte == 0: # NUL terminator
  189. break
  190. suffix += bytes([byte])
  191. # Reconstruct the path
  192. if remove_len > len(previous_path):
  193. raise ValueError(
  194. f"Invalid path compression: trying to remove {remove_len} bytes from {len(previous_path)}-byte path"
  195. )
  196. prefix = previous_path[:-remove_len] if remove_len > 0 else previous_path
  197. path = prefix + suffix
  198. return path, bytes_consumed
  199. class Stage(Enum):
  200. NORMAL = 0
  201. MERGE_CONFLICT_ANCESTOR = 1
  202. MERGE_CONFLICT_THIS = 2
  203. MERGE_CONFLICT_OTHER = 3
  204. @dataclass
  205. class SerializedIndexEntry:
  206. name: bytes
  207. ctime: Union[int, float, tuple[int, int]]
  208. mtime: Union[int, float, tuple[int, int]]
  209. dev: int
  210. ino: int
  211. mode: int
  212. uid: int
  213. gid: int
  214. size: int
  215. sha: bytes
  216. flags: int
  217. extended_flags: int
  218. def stage(self) -> Stage:
  219. return Stage((self.flags & FLAG_STAGEMASK) >> FLAG_STAGESHIFT)
  220. @dataclass
  221. class IndexExtension:
  222. """Base class for index extensions."""
  223. signature: bytes
  224. data: bytes
  225. @classmethod
  226. def from_raw(cls, signature: bytes, data: bytes) -> "IndexExtension":
  227. """Create an extension from raw data.
  228. Args:
  229. signature: 4-byte extension signature
  230. data: Extension data
  231. Returns:
  232. Parsed extension object
  233. """
  234. if signature == TREE_EXTENSION:
  235. return TreeExtension.from_bytes(data)
  236. elif signature == REUC_EXTENSION:
  237. return ResolveUndoExtension.from_bytes(data)
  238. elif signature == UNTR_EXTENSION:
  239. return UntrackedExtension.from_bytes(data)
  240. else:
  241. # Unknown extension - just store raw data
  242. return cls(signature, data)
  243. def to_bytes(self) -> bytes:
  244. """Serialize extension to bytes."""
  245. return self.data
  246. class TreeExtension(IndexExtension):
  247. """Tree cache extension."""
  248. def __init__(self, entries: list[tuple[bytes, bytes, int]]) -> None:
  249. self.entries = entries
  250. super().__init__(TREE_EXTENSION, b"")
  251. @classmethod
  252. def from_bytes(cls, data: bytes) -> "TreeExtension":
  253. # TODO: Implement tree cache parsing
  254. return cls([])
  255. def to_bytes(self) -> bytes:
  256. # TODO: Implement tree cache serialization
  257. return b""
  258. class ResolveUndoExtension(IndexExtension):
  259. """Resolve undo extension for recording merge conflicts."""
  260. def __init__(self, entries: list[tuple[bytes, list[tuple[int, bytes]]]]) -> None:
  261. self.entries = entries
  262. super().__init__(REUC_EXTENSION, b"")
  263. @classmethod
  264. def from_bytes(cls, data: bytes) -> "ResolveUndoExtension":
  265. # TODO: Implement resolve undo parsing
  266. return cls([])
  267. def to_bytes(self) -> bytes:
  268. # TODO: Implement resolve undo serialization
  269. return b""
  270. class UntrackedExtension(IndexExtension):
  271. """Untracked cache extension."""
  272. def __init__(self, data: bytes) -> None:
  273. super().__init__(UNTR_EXTENSION, data)
  274. @classmethod
  275. def from_bytes(cls, data: bytes) -> "UntrackedExtension":
  276. return cls(data)
  277. @dataclass
  278. class IndexEntry:
  279. ctime: Union[int, float, tuple[int, int]]
  280. mtime: Union[int, float, tuple[int, int]]
  281. dev: int
  282. ino: int
  283. mode: int
  284. uid: int
  285. gid: int
  286. size: int
  287. sha: bytes
  288. flags: int = 0
  289. extended_flags: int = 0
  290. @classmethod
  291. def from_serialized(cls, serialized: SerializedIndexEntry) -> "IndexEntry":
  292. return cls(
  293. ctime=serialized.ctime,
  294. mtime=serialized.mtime,
  295. dev=serialized.dev,
  296. ino=serialized.ino,
  297. mode=serialized.mode,
  298. uid=serialized.uid,
  299. gid=serialized.gid,
  300. size=serialized.size,
  301. sha=serialized.sha,
  302. flags=serialized.flags,
  303. extended_flags=serialized.extended_flags,
  304. )
  305. def serialize(self, name: bytes, stage: Stage) -> SerializedIndexEntry:
  306. # Clear out any existing stage bits, then set them from the Stage.
  307. new_flags = self.flags & ~FLAG_STAGEMASK
  308. new_flags |= stage.value << FLAG_STAGESHIFT
  309. return SerializedIndexEntry(
  310. name=name,
  311. ctime=self.ctime,
  312. mtime=self.mtime,
  313. dev=self.dev,
  314. ino=self.ino,
  315. mode=self.mode,
  316. uid=self.uid,
  317. gid=self.gid,
  318. size=self.size,
  319. sha=self.sha,
  320. flags=new_flags,
  321. extended_flags=self.extended_flags,
  322. )
  323. def stage(self) -> Stage:
  324. return Stage((self.flags & FLAG_STAGEMASK) >> FLAG_STAGESHIFT)
  325. @property
  326. def skip_worktree(self) -> bool:
  327. """Return True if the skip-worktree bit is set in extended_flags."""
  328. return bool(self.extended_flags & EXTENDED_FLAG_SKIP_WORKTREE)
  329. def set_skip_worktree(self, skip: bool = True) -> None:
  330. """Helper method to set or clear the skip-worktree bit in extended_flags.
  331. Also sets FLAG_EXTENDED in self.flags if needed.
  332. """
  333. if skip:
  334. # Turn on the skip-worktree bit
  335. self.extended_flags |= EXTENDED_FLAG_SKIP_WORKTREE
  336. # Also ensure the main 'extended' bit is set in flags
  337. self.flags |= FLAG_EXTENDED
  338. else:
  339. # Turn off the skip-worktree bit
  340. self.extended_flags &= ~EXTENDED_FLAG_SKIP_WORKTREE
  341. # Optionally unset the main extended bit if no extended flags remain
  342. if self.extended_flags == 0:
  343. self.flags &= ~FLAG_EXTENDED
  344. class ConflictedIndexEntry:
  345. """Index entry that represents a conflict."""
  346. ancestor: Optional[IndexEntry]
  347. this: Optional[IndexEntry]
  348. other: Optional[IndexEntry]
  349. def __init__(
  350. self,
  351. ancestor: Optional[IndexEntry] = None,
  352. this: Optional[IndexEntry] = None,
  353. other: Optional[IndexEntry] = None,
  354. ) -> None:
  355. self.ancestor = ancestor
  356. self.this = this
  357. self.other = other
  358. class UnmergedEntries(Exception):
  359. """Unmerged entries exist in the index."""
  360. def pathsplit(path: bytes) -> tuple[bytes, bytes]:
  361. """Split a /-delimited path into a directory part and a basename.
  362. Args:
  363. path: The path to split.
  364. Returns:
  365. Tuple with directory name and basename
  366. """
  367. try:
  368. (dirname, basename) = path.rsplit(b"/", 1)
  369. except ValueError:
  370. return (b"", path)
  371. else:
  372. return (dirname, basename)
  373. def pathjoin(*args):
  374. """Join a /-delimited path."""
  375. return b"/".join([p for p in args if p])
  376. def read_cache_time(f):
  377. """Read a cache time.
  378. Args:
  379. f: File-like object to read from
  380. Returns:
  381. Tuple with seconds and nanoseconds
  382. """
  383. return struct.unpack(">LL", f.read(8))
  384. def write_cache_time(f, t) -> None:
  385. """Write a cache time.
  386. Args:
  387. f: File-like object to write to
  388. t: Time to write (as int, float or tuple with secs and nsecs)
  389. """
  390. if isinstance(t, int):
  391. t = (t, 0)
  392. elif isinstance(t, float):
  393. (secs, nsecs) = divmod(t, 1.0)
  394. t = (int(secs), int(nsecs * 1000000000))
  395. elif not isinstance(t, tuple):
  396. raise TypeError(t)
  397. f.write(struct.pack(">LL", *t))
  398. def read_cache_entry(
  399. f, version: int, previous_path: bytes = b""
  400. ) -> SerializedIndexEntry:
  401. """Read an entry from a cache file.
  402. Args:
  403. f: File-like object to read from
  404. version: Index version
  405. previous_path: Previous entry's path (for version 4 compression)
  406. """
  407. beginoffset = f.tell()
  408. ctime = read_cache_time(f)
  409. mtime = read_cache_time(f)
  410. (
  411. dev,
  412. ino,
  413. mode,
  414. uid,
  415. gid,
  416. size,
  417. sha,
  418. flags,
  419. ) = struct.unpack(">LLLLLL20sH", f.read(20 + 4 * 6 + 2))
  420. if flags & FLAG_EXTENDED:
  421. if version < 3:
  422. raise AssertionError("extended flag set in index with version < 3")
  423. (extended_flags,) = struct.unpack(">H", f.read(2))
  424. else:
  425. extended_flags = 0
  426. if version >= 4:
  427. # Version 4: paths are always compressed (name_len should be 0)
  428. name, consumed = _decompress_path_from_stream(f, previous_path)
  429. else:
  430. # Versions < 4: regular name reading
  431. name = f.read(flags & FLAG_NAMEMASK)
  432. # Padding:
  433. if version < 4:
  434. real_size = (f.tell() - beginoffset + 8) & ~7
  435. f.read((beginoffset + real_size) - f.tell())
  436. return SerializedIndexEntry(
  437. name,
  438. ctime,
  439. mtime,
  440. dev,
  441. ino,
  442. mode,
  443. uid,
  444. gid,
  445. size,
  446. sha_to_hex(sha),
  447. flags & ~FLAG_NAMEMASK,
  448. extended_flags,
  449. )
  450. def write_cache_entry(
  451. f, entry: SerializedIndexEntry, version: int, previous_path: bytes = b""
  452. ) -> None:
  453. """Write an index entry to a file.
  454. Args:
  455. f: File object
  456. entry: IndexEntry to write
  457. version: Index format version
  458. previous_path: Previous entry's path (for version 4 compression)
  459. """
  460. beginoffset = f.tell()
  461. write_cache_time(f, entry.ctime)
  462. write_cache_time(f, entry.mtime)
  463. if version >= 4:
  464. # Version 4: use compression but set name_len to actual filename length
  465. # This matches how C Git implements index v4 flags
  466. compressed_path = _compress_path(entry.name, previous_path)
  467. flags = len(entry.name) | (entry.flags & ~FLAG_NAMEMASK)
  468. else:
  469. # Versions < 4: include actual name length
  470. flags = len(entry.name) | (entry.flags & ~FLAG_NAMEMASK)
  471. if entry.extended_flags:
  472. flags |= FLAG_EXTENDED
  473. if flags & FLAG_EXTENDED and version is not None and version < 3:
  474. raise AssertionError("unable to use extended flags in version < 3")
  475. f.write(
  476. struct.pack(
  477. b">LLLLLL20sH",
  478. entry.dev & 0xFFFFFFFF,
  479. entry.ino & 0xFFFFFFFF,
  480. entry.mode,
  481. entry.uid,
  482. entry.gid,
  483. entry.size,
  484. hex_to_sha(entry.sha),
  485. flags,
  486. )
  487. )
  488. if flags & FLAG_EXTENDED:
  489. f.write(struct.pack(b">H", entry.extended_flags))
  490. if version >= 4:
  491. # Version 4: always write compressed path
  492. f.write(compressed_path)
  493. else:
  494. # Versions < 4: write regular path and padding
  495. f.write(entry.name)
  496. real_size = (f.tell() - beginoffset + 8) & ~7
  497. f.write(b"\0" * ((beginoffset + real_size) - f.tell()))
  498. class UnsupportedIndexFormat(Exception):
  499. """An unsupported index format was encountered."""
  500. def __init__(self, version) -> None:
  501. self.index_format_version = version
  502. def read_index_header(f: BinaryIO) -> tuple[int, int]:
  503. """Read an index header from a file.
  504. Returns:
  505. tuple of (version, num_entries)
  506. """
  507. header = f.read(4)
  508. if header != b"DIRC":
  509. raise AssertionError(f"Invalid index file header: {header!r}")
  510. (version, num_entries) = struct.unpack(b">LL", f.read(4 * 2))
  511. if version not in (1, 2, 3, 4):
  512. raise UnsupportedIndexFormat(version)
  513. return version, num_entries
  514. def write_index_extension(f: BinaryIO, extension: IndexExtension) -> None:
  515. """Write an index extension.
  516. Args:
  517. f: File-like object to write to
  518. extension: Extension to write
  519. """
  520. data = extension.to_bytes()
  521. f.write(extension.signature)
  522. f.write(struct.pack(">I", len(data)))
  523. f.write(data)
  524. def read_index(f: BinaryIO) -> Iterator[SerializedIndexEntry]:
  525. """Read an index file, yielding the individual entries."""
  526. version, num_entries = read_index_header(f)
  527. previous_path = b""
  528. for i in range(num_entries):
  529. entry = read_cache_entry(f, version, previous_path)
  530. previous_path = entry.name
  531. yield entry
  532. def read_index_dict_with_version(
  533. f: BinaryIO,
  534. ) -> tuple[dict[bytes, Union[IndexEntry, ConflictedIndexEntry]], int]:
  535. """Read an index file and return it as a dictionary along with the version.
  536. Returns:
  537. tuple of (entries_dict, version)
  538. """
  539. version, num_entries = read_index_header(f)
  540. ret: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]] = {}
  541. previous_path = b""
  542. for i in range(num_entries):
  543. entry = read_cache_entry(f, version, previous_path)
  544. previous_path = entry.name
  545. stage = entry.stage()
  546. if stage == Stage.NORMAL:
  547. ret[entry.name] = IndexEntry.from_serialized(entry)
  548. else:
  549. existing = ret.setdefault(entry.name, ConflictedIndexEntry())
  550. if isinstance(existing, IndexEntry):
  551. raise AssertionError(f"Non-conflicted entry for {entry.name!r} exists")
  552. if stage == Stage.MERGE_CONFLICT_ANCESTOR:
  553. existing.ancestor = IndexEntry.from_serialized(entry)
  554. elif stage == Stage.MERGE_CONFLICT_THIS:
  555. existing.this = IndexEntry.from_serialized(entry)
  556. elif stage == Stage.MERGE_CONFLICT_OTHER:
  557. existing.other = IndexEntry.from_serialized(entry)
  558. return ret, version
  559. def read_index_dict(f) -> dict[bytes, Union[IndexEntry, ConflictedIndexEntry]]:
  560. """Read an index file and return it as a dictionary.
  561. Dict Key is tuple of path and stage number, as
  562. path alone is not unique
  563. Args:
  564. f: File object to read fromls.
  565. """
  566. ret: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]] = {}
  567. for entry in read_index(f):
  568. stage = entry.stage()
  569. if stage == Stage.NORMAL:
  570. ret[entry.name] = IndexEntry.from_serialized(entry)
  571. else:
  572. existing = ret.setdefault(entry.name, ConflictedIndexEntry())
  573. if isinstance(existing, IndexEntry):
  574. raise AssertionError(f"Non-conflicted entry for {entry.name!r} exists")
  575. if stage == Stage.MERGE_CONFLICT_ANCESTOR:
  576. existing.ancestor = IndexEntry.from_serialized(entry)
  577. elif stage == Stage.MERGE_CONFLICT_THIS:
  578. existing.this = IndexEntry.from_serialized(entry)
  579. elif stage == Stage.MERGE_CONFLICT_OTHER:
  580. existing.other = IndexEntry.from_serialized(entry)
  581. return ret
  582. def write_index(
  583. f: BinaryIO, entries: list[SerializedIndexEntry], version: Optional[int] = None
  584. ) -> None:
  585. """Write an index file.
  586. Args:
  587. f: File-like object to write to
  588. version: Version number to write
  589. entries: Iterable over the entries to write
  590. """
  591. if version is None:
  592. version = DEFAULT_VERSION
  593. # STEP 1: check if any extended_flags are set
  594. uses_extended_flags = any(e.extended_flags != 0 for e in entries)
  595. if uses_extended_flags and version < 3:
  596. # Force or bump the version to 3
  597. version = 3
  598. # The rest is unchanged, but you might insert a final check:
  599. if version < 3:
  600. # Double-check no extended flags appear
  601. for e in entries:
  602. if e.extended_flags != 0:
  603. raise AssertionError("Attempt to use extended flags in index < v3")
  604. # Proceed with the existing code to write the header and entries.
  605. f.write(b"DIRC")
  606. f.write(struct.pack(b">LL", version, len(entries)))
  607. previous_path = b""
  608. for entry in entries:
  609. write_cache_entry(f, entry, version=version, previous_path=previous_path)
  610. previous_path = entry.name
  611. def write_index_dict(
  612. f: BinaryIO,
  613. entries: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]],
  614. version: Optional[int] = None,
  615. ) -> None:
  616. """Write an index file based on the contents of a dictionary.
  617. being careful to sort by path and then by stage.
  618. """
  619. entries_list = []
  620. for key in sorted(entries):
  621. value = entries[key]
  622. if isinstance(value, ConflictedIndexEntry):
  623. if value.ancestor is not None:
  624. entries_list.append(
  625. value.ancestor.serialize(key, Stage.MERGE_CONFLICT_ANCESTOR)
  626. )
  627. if value.this is not None:
  628. entries_list.append(
  629. value.this.serialize(key, Stage.MERGE_CONFLICT_THIS)
  630. )
  631. if value.other is not None:
  632. entries_list.append(
  633. value.other.serialize(key, Stage.MERGE_CONFLICT_OTHER)
  634. )
  635. else:
  636. entries_list.append(value.serialize(key, Stage.NORMAL))
  637. write_index(f, entries_list, version=version)
  638. def cleanup_mode(mode: int) -> int:
  639. """Cleanup a mode value.
  640. This will return a mode that can be stored in a tree object.
  641. Args:
  642. mode: Mode to clean up.
  643. Returns:
  644. mode
  645. """
  646. if stat.S_ISLNK(mode):
  647. return stat.S_IFLNK
  648. elif stat.S_ISDIR(mode):
  649. return stat.S_IFDIR
  650. elif S_ISGITLINK(mode):
  651. return S_IFGITLINK
  652. ret = stat.S_IFREG | 0o644
  653. if mode & 0o100:
  654. ret |= 0o111
  655. return ret
  656. class Index:
  657. """A Git Index file."""
  658. _byname: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]]
  659. def __init__(
  660. self,
  661. filename: Union[bytes, str, os.PathLike],
  662. read=True,
  663. skip_hash: bool = False,
  664. version: Optional[int] = None,
  665. ) -> None:
  666. """Create an index object associated with the given filename.
  667. Args:
  668. filename: Path to the index file
  669. read: Whether to initialize the index from the given file, should it exist.
  670. skip_hash: Whether to skip SHA1 hash when writing (for manyfiles feature)
  671. version: Index format version to use (None = auto-detect from file or use default)
  672. """
  673. self._filename = os.fspath(filename)
  674. # TODO(jelmer): Store the version returned by read_index
  675. self._version = version
  676. self._skip_hash = skip_hash
  677. self.clear()
  678. if read:
  679. self.read()
  680. @property
  681. def path(self):
  682. return self._filename
  683. def __repr__(self) -> str:
  684. return f"{self.__class__.__name__}({self._filename!r})"
  685. def write(self) -> None:
  686. """Write current contents of index to disk."""
  687. f = GitFile(self._filename, "wb")
  688. try:
  689. if self._skip_hash:
  690. # When skipHash is enabled, write the index without computing SHA1
  691. write_index_dict(f, self._byname, version=self._version)
  692. # Write 20 zero bytes instead of SHA1
  693. f.write(b"\x00" * 20)
  694. f.close()
  695. else:
  696. f = SHA1Writer(f)
  697. write_index_dict(f, self._byname, version=self._version)
  698. f.close()
  699. except:
  700. f.close()
  701. raise
  702. def read(self) -> None:
  703. """Read current contents of index from disk."""
  704. if not os.path.exists(self._filename):
  705. return
  706. f = GitFile(self._filename, "rb")
  707. try:
  708. f = SHA1Reader(f)
  709. entries, version = read_index_dict_with_version(f)
  710. self._version = version
  711. self.update(entries)
  712. # Read any remaining data before the SHA
  713. remaining = os.path.getsize(self._filename) - f.tell() - 20
  714. if remaining > 0:
  715. f.read(remaining)
  716. f.check_sha(allow_empty=True)
  717. finally:
  718. f.close()
  719. def __len__(self) -> int:
  720. """Number of entries in this index file."""
  721. return len(self._byname)
  722. def __getitem__(self, key: bytes) -> Union[IndexEntry, ConflictedIndexEntry]:
  723. """Retrieve entry by relative path and stage.
  724. Returns: Either a IndexEntry or a ConflictedIndexEntry
  725. Raises KeyError: if the entry does not exist
  726. """
  727. return self._byname[key]
  728. def __iter__(self) -> Iterator[bytes]:
  729. """Iterate over the paths and stages in this index."""
  730. return iter(self._byname)
  731. def __contains__(self, key) -> bool:
  732. return key in self._byname
  733. def get_sha1(self, path: bytes) -> bytes:
  734. """Return the (git object) SHA1 for the object at a path."""
  735. value = self[path]
  736. if isinstance(value, ConflictedIndexEntry):
  737. raise UnmergedEntries
  738. return value.sha
  739. def get_mode(self, path: bytes) -> int:
  740. """Return the POSIX file mode for the object at a path."""
  741. value = self[path]
  742. if isinstance(value, ConflictedIndexEntry):
  743. raise UnmergedEntries
  744. return value.mode
  745. def iterobjects(self) -> Iterable[tuple[bytes, bytes, int]]:
  746. """Iterate over path, sha, mode tuples for use with commit_tree."""
  747. for path in self:
  748. entry = self[path]
  749. if isinstance(entry, ConflictedIndexEntry):
  750. raise UnmergedEntries
  751. yield path, entry.sha, cleanup_mode(entry.mode)
  752. def has_conflicts(self) -> bool:
  753. for value in self._byname.values():
  754. if isinstance(value, ConflictedIndexEntry):
  755. return True
  756. return False
  757. def clear(self) -> None:
  758. """Remove all contents from this index."""
  759. self._byname = {}
  760. def __setitem__(
  761. self, name: bytes, value: Union[IndexEntry, ConflictedIndexEntry]
  762. ) -> None:
  763. assert isinstance(name, bytes)
  764. self._byname[name] = value
  765. def __delitem__(self, name: bytes) -> None:
  766. del self._byname[name]
  767. def iteritems(
  768. self,
  769. ) -> Iterator[tuple[bytes, Union[IndexEntry, ConflictedIndexEntry]]]:
  770. return iter(self._byname.items())
  771. def items(self) -> Iterator[tuple[bytes, Union[IndexEntry, ConflictedIndexEntry]]]:
  772. return iter(self._byname.items())
  773. def update(
  774. self, entries: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]]
  775. ) -> None:
  776. for key, value in entries.items():
  777. self[key] = value
  778. def paths(self):
  779. yield from self._byname.keys()
  780. def changes_from_tree(
  781. self, object_store, tree: ObjectID, want_unchanged: bool = False
  782. ):
  783. """Find the differences between the contents of this index and a tree.
  784. Args:
  785. object_store: Object store to use for retrieving tree contents
  786. tree: SHA1 of the root tree
  787. want_unchanged: Whether unchanged files should be reported
  788. Returns: Iterator over tuples with (oldpath, newpath), (oldmode,
  789. newmode), (oldsha, newsha)
  790. """
  791. def lookup_entry(path):
  792. entry = self[path]
  793. return entry.sha, cleanup_mode(entry.mode)
  794. yield from changes_from_tree(
  795. self.paths(),
  796. lookup_entry,
  797. object_store,
  798. tree,
  799. want_unchanged=want_unchanged,
  800. )
  801. def commit(self, object_store):
  802. """Create a new tree from an index.
  803. Args:
  804. object_store: Object store to save the tree in
  805. Returns:
  806. Root tree SHA
  807. """
  808. return commit_tree(object_store, self.iterobjects())
  809. def commit_tree(
  810. object_store: ObjectContainer, blobs: Iterable[tuple[bytes, bytes, int]]
  811. ) -> bytes:
  812. """Commit a new tree.
  813. Args:
  814. object_store: Object store to add trees to
  815. blobs: Iterable over blob path, sha, mode entries
  816. Returns:
  817. SHA1 of the created tree.
  818. """
  819. trees: dict[bytes, Any] = {b"": {}}
  820. def add_tree(path):
  821. if path in trees:
  822. return trees[path]
  823. dirname, basename = pathsplit(path)
  824. t = add_tree(dirname)
  825. assert isinstance(basename, bytes)
  826. newtree = {}
  827. t[basename] = newtree
  828. trees[path] = newtree
  829. return newtree
  830. for path, sha, mode in blobs:
  831. tree_path, basename = pathsplit(path)
  832. tree = add_tree(tree_path)
  833. tree[basename] = (mode, sha)
  834. def build_tree(path):
  835. tree = Tree()
  836. for basename, entry in trees[path].items():
  837. if isinstance(entry, dict):
  838. mode = stat.S_IFDIR
  839. sha = build_tree(pathjoin(path, basename))
  840. else:
  841. (mode, sha) = entry
  842. tree.add(basename, mode, sha)
  843. object_store.add_object(tree)
  844. return tree.id
  845. return build_tree(b"")
  846. def commit_index(object_store: ObjectContainer, index: Index) -> bytes:
  847. """Create a new tree from an index.
  848. Args:
  849. object_store: Object store to save the tree in
  850. index: Index file
  851. Note: This function is deprecated, use index.commit() instead.
  852. Returns: Root tree sha.
  853. """
  854. return commit_tree(object_store, index.iterobjects())
  855. def changes_from_tree(
  856. names: Iterable[bytes],
  857. lookup_entry: Callable[[bytes], tuple[bytes, int]],
  858. object_store: ObjectContainer,
  859. tree: Optional[bytes],
  860. want_unchanged=False,
  861. ) -> Iterable[
  862. tuple[
  863. tuple[Optional[bytes], Optional[bytes]],
  864. tuple[Optional[int], Optional[int]],
  865. tuple[Optional[bytes], Optional[bytes]],
  866. ]
  867. ]:
  868. """Find the differences between the contents of a tree and
  869. a working copy.
  870. Args:
  871. names: Iterable of names in the working copy
  872. lookup_entry: Function to lookup an entry in the working copy
  873. object_store: Object store to use for retrieving tree contents
  874. tree: SHA1 of the root tree, or None for an empty tree
  875. want_unchanged: Whether unchanged files should be reported
  876. Returns: Iterator over tuples with (oldpath, newpath), (oldmode, newmode),
  877. (oldsha, newsha)
  878. """
  879. # TODO(jelmer): Support a include_trees option
  880. other_names = set(names)
  881. if tree is not None:
  882. for name, mode, sha in iter_tree_contents(object_store, tree):
  883. try:
  884. (other_sha, other_mode) = lookup_entry(name)
  885. except KeyError:
  886. # Was removed
  887. yield ((name, None), (mode, None), (sha, None))
  888. else:
  889. other_names.remove(name)
  890. if want_unchanged or other_sha != sha or other_mode != mode:
  891. yield ((name, name), (mode, other_mode), (sha, other_sha))
  892. # Mention added files
  893. for name in other_names:
  894. try:
  895. (other_sha, other_mode) = lookup_entry(name)
  896. except KeyError:
  897. pass
  898. else:
  899. yield ((None, name), (None, other_mode), (None, other_sha))
  900. def index_entry_from_stat(
  901. stat_val,
  902. hex_sha: bytes,
  903. mode: Optional[int] = None,
  904. ):
  905. """Create a new index entry from a stat value.
  906. Args:
  907. stat_val: POSIX stat_result instance
  908. hex_sha: Hex sha of the object
  909. """
  910. if mode is None:
  911. mode = cleanup_mode(stat_val.st_mode)
  912. return IndexEntry(
  913. ctime=stat_val.st_ctime,
  914. mtime=stat_val.st_mtime,
  915. dev=stat_val.st_dev,
  916. ino=stat_val.st_ino,
  917. mode=mode,
  918. uid=stat_val.st_uid,
  919. gid=stat_val.st_gid,
  920. size=stat_val.st_size,
  921. sha=hex_sha,
  922. flags=0,
  923. extended_flags=0,
  924. )
  925. if sys.platform == "win32":
  926. # On Windows, creating symlinks either requires administrator privileges
  927. # or developer mode. Raise a more helpful error when we're unable to
  928. # create symlinks
  929. # https://github.com/jelmer/dulwich/issues/1005
  930. class WindowsSymlinkPermissionError(PermissionError):
  931. def __init__(self, errno, msg, filename) -> None:
  932. super(PermissionError, self).__init__(
  933. errno,
  934. f"Unable to create symlink; do you have developer mode enabled? {msg}",
  935. filename,
  936. )
  937. def symlink(src, dst, target_is_directory=False, *, dir_fd=None):
  938. try:
  939. return os.symlink(
  940. src, dst, target_is_directory=target_is_directory, dir_fd=dir_fd
  941. )
  942. except PermissionError as e:
  943. raise WindowsSymlinkPermissionError(e.errno, e.strerror, e.filename) from e
  944. else:
  945. symlink = os.symlink
  946. def build_file_from_blob(
  947. blob: Blob,
  948. mode: int,
  949. target_path: bytes,
  950. *,
  951. honor_filemode=True,
  952. tree_encoding="utf-8",
  953. symlink_fn=None,
  954. ):
  955. """Build a file or symlink on disk based on a Git object.
  956. Args:
  957. blob: The git object
  958. mode: File mode
  959. target_path: Path to write to
  960. honor_filemode: An optional flag to honor core.filemode setting in
  961. config file, default is core.filemode=True, change executable bit
  962. symlink_fn: Function to use for creating symlinks
  963. Returns: stat object for the file
  964. """
  965. try:
  966. oldstat = os.lstat(target_path)
  967. except FileNotFoundError:
  968. oldstat = None
  969. contents = blob.as_raw_string()
  970. if stat.S_ISLNK(mode):
  971. if oldstat:
  972. os.unlink(target_path)
  973. if sys.platform == "win32":
  974. # os.readlink on Python3 on Windows requires a unicode string.
  975. contents = contents.decode(tree_encoding) # type: ignore
  976. target_path = target_path.decode(tree_encoding) # type: ignore
  977. (symlink_fn or symlink)(contents, target_path)
  978. else:
  979. if oldstat is not None and oldstat.st_size == len(contents):
  980. with open(target_path, "rb") as f:
  981. if f.read() == contents:
  982. return oldstat
  983. with open(target_path, "wb") as f:
  984. # Write out file
  985. f.write(contents)
  986. if honor_filemode:
  987. os.chmod(target_path, mode)
  988. return os.lstat(target_path)
  989. INVALID_DOTNAMES = (b".git", b".", b"..", b"")
  990. def validate_path_element_default(element: bytes) -> bool:
  991. return element.lower() not in INVALID_DOTNAMES
  992. def validate_path_element_ntfs(element: bytes) -> bool:
  993. stripped = element.rstrip(b". ").lower()
  994. if stripped in INVALID_DOTNAMES:
  995. return False
  996. if stripped == b"git~1":
  997. return False
  998. return True
  999. def validate_path(path: bytes, element_validator=validate_path_element_default) -> bool:
  1000. """Default path validator that just checks for .git/."""
  1001. parts = path.split(b"/")
  1002. for p in parts:
  1003. if not element_validator(p):
  1004. return False
  1005. else:
  1006. return True
  1007. def build_index_from_tree(
  1008. root_path: Union[str, bytes],
  1009. index_path: Union[str, bytes],
  1010. object_store: ObjectContainer,
  1011. tree_id: bytes,
  1012. honor_filemode: bool = True,
  1013. validate_path_element=validate_path_element_default,
  1014. symlink_fn=None,
  1015. ) -> None:
  1016. """Generate and materialize index from a tree.
  1017. Args:
  1018. tree_id: Tree to materialize
  1019. root_path: Target dir for materialized index files
  1020. index_path: Target path for generated index
  1021. object_store: Non-empty object store holding tree contents
  1022. honor_filemode: An optional flag to honor core.filemode setting in
  1023. config file, default is core.filemode=True, change executable bit
  1024. validate_path_element: Function to validate path elements to check
  1025. out; default just refuses .git and .. directories.
  1026. Note: existing index is wiped and contents are not merged
  1027. in a working dir. Suitable only for fresh clones.
  1028. """
  1029. index = Index(index_path, read=False)
  1030. if not isinstance(root_path, bytes):
  1031. root_path = os.fsencode(root_path)
  1032. for entry in iter_tree_contents(object_store, tree_id):
  1033. if not validate_path(entry.path, validate_path_element):
  1034. continue
  1035. full_path = _tree_to_fs_path(root_path, entry.path)
  1036. if not os.path.exists(os.path.dirname(full_path)):
  1037. os.makedirs(os.path.dirname(full_path))
  1038. # TODO(jelmer): Merge new index into working tree
  1039. if S_ISGITLINK(entry.mode):
  1040. if not os.path.isdir(full_path):
  1041. os.mkdir(full_path)
  1042. st = os.lstat(full_path)
  1043. # TODO(jelmer): record and return submodule paths
  1044. else:
  1045. obj = object_store[entry.sha]
  1046. assert isinstance(obj, Blob)
  1047. st = build_file_from_blob(
  1048. obj,
  1049. entry.mode,
  1050. full_path,
  1051. honor_filemode=honor_filemode,
  1052. symlink_fn=symlink_fn,
  1053. )
  1054. # Add file to index
  1055. if not honor_filemode or S_ISGITLINK(entry.mode):
  1056. # we can not use tuple slicing to build a new tuple,
  1057. # because on windows that will convert the times to
  1058. # longs, which causes errors further along
  1059. st_tuple = (
  1060. entry.mode,
  1061. st.st_ino,
  1062. st.st_dev,
  1063. st.st_nlink,
  1064. st.st_uid,
  1065. st.st_gid,
  1066. st.st_size,
  1067. st.st_atime,
  1068. st.st_mtime,
  1069. st.st_ctime,
  1070. )
  1071. st = st.__class__(st_tuple)
  1072. # default to a stage 0 index entry (normal)
  1073. # when reading from the filesystem
  1074. index[entry.path] = index_entry_from_stat(st, entry.sha)
  1075. index.write()
  1076. def blob_from_path_and_mode(fs_path: bytes, mode: int, tree_encoding="utf-8"):
  1077. """Create a blob from a path and a stat object.
  1078. Args:
  1079. fs_path: Full file system path to file
  1080. mode: File mode
  1081. Returns: A `Blob` object
  1082. """
  1083. assert isinstance(fs_path, bytes)
  1084. blob = Blob()
  1085. if stat.S_ISLNK(mode):
  1086. if sys.platform == "win32":
  1087. # os.readlink on Python3 on Windows requires a unicode string.
  1088. blob.data = os.readlink(os.fsdecode(fs_path)).encode(tree_encoding)
  1089. else:
  1090. blob.data = os.readlink(fs_path)
  1091. else:
  1092. with open(fs_path, "rb") as f:
  1093. blob.data = f.read()
  1094. return blob
  1095. def blob_from_path_and_stat(fs_path: bytes, st, tree_encoding="utf-8"):
  1096. """Create a blob from a path and a stat object.
  1097. Args:
  1098. fs_path: Full file system path to file
  1099. st: A stat object
  1100. Returns: A `Blob` object
  1101. """
  1102. return blob_from_path_and_mode(fs_path, st.st_mode, tree_encoding)
  1103. def read_submodule_head(path: Union[str, bytes]) -> Optional[bytes]:
  1104. """Read the head commit of a submodule.
  1105. Args:
  1106. path: path to the submodule
  1107. Returns: HEAD sha, None if not a valid head/repository
  1108. """
  1109. from .errors import NotGitRepository
  1110. from .repo import Repo
  1111. # Repo currently expects a "str", so decode if necessary.
  1112. # TODO(jelmer): Perhaps move this into Repo() ?
  1113. if not isinstance(path, str):
  1114. path = os.fsdecode(path)
  1115. try:
  1116. repo = Repo(path)
  1117. except NotGitRepository:
  1118. return None
  1119. try:
  1120. return repo.head()
  1121. except KeyError:
  1122. return None
  1123. def _has_directory_changed(tree_path: bytes, entry) -> bool:
  1124. """Check if a directory has changed after getting an error.
  1125. When handling an error trying to create a blob from a path, call this
  1126. function. It will check if the path is a directory. If it's a directory
  1127. and a submodule, check the submodule head to see if it's has changed. If
  1128. not, consider the file as changed as Git tracked a file and not a
  1129. directory.
  1130. Return true if the given path should be considered as changed and False
  1131. otherwise or if the path is not a directory.
  1132. """
  1133. # This is actually a directory
  1134. if os.path.exists(os.path.join(tree_path, b".git")):
  1135. # Submodule
  1136. head = read_submodule_head(tree_path)
  1137. if entry.sha != head:
  1138. return True
  1139. else:
  1140. # The file was changed to a directory, so consider it removed.
  1141. return True
  1142. return False
  1143. def update_working_tree(
  1144. repo,
  1145. old_tree_id,
  1146. new_tree_id,
  1147. honor_filemode=True,
  1148. validate_path_element=None,
  1149. symlink_fn=None,
  1150. force_remove_untracked=False,
  1151. ):
  1152. """Update the working tree and index to match a new tree.
  1153. This function handles:
  1154. - Adding new files
  1155. - Updating modified files
  1156. - Removing deleted files
  1157. - Cleaning up empty directories
  1158. Args:
  1159. repo: Repository object
  1160. old_tree_id: SHA of the tree before the update
  1161. new_tree_id: SHA of the tree to update to
  1162. honor_filemode: An optional flag to honor core.filemode setting
  1163. validate_path_element: Function to validate path elements to check out
  1164. symlink_fn: Function to use for creating symlinks
  1165. force_remove_untracked: If True, remove files that exist in working
  1166. directory but not in target tree, even if old_tree_id is None
  1167. """
  1168. import os
  1169. # Set default validate_path_element if not provided
  1170. if validate_path_element is None:
  1171. validate_path_element = validate_path_element_default
  1172. # Get the trees
  1173. old_tree = repo[old_tree_id] if old_tree_id else None
  1174. repo[new_tree_id]
  1175. # Open the index
  1176. index = repo.open_index()
  1177. # Track which paths we've dealt with
  1178. handled_paths = set()
  1179. # Get repo path as string for comparisons
  1180. repo_path_str = repo.path if isinstance(repo.path, str) else repo.path.decode()
  1181. # First, update/add all files in the new tree
  1182. for entry in iter_tree_contents(repo.object_store, new_tree_id):
  1183. handled_paths.add(entry.path)
  1184. # Skip .git directory
  1185. if entry.path.startswith(b".git"):
  1186. continue
  1187. # Validate path element
  1188. if not validate_path(entry.path, validate_path_element):
  1189. continue
  1190. # Build full path
  1191. full_path = os.path.join(repo_path_str, entry.path.decode())
  1192. # Get the blob
  1193. blob = repo.object_store[entry.sha]
  1194. # Ensure parent directory exists
  1195. parent_dir = os.path.dirname(full_path)
  1196. if parent_dir and not os.path.exists(parent_dir):
  1197. os.makedirs(parent_dir)
  1198. # Write the file
  1199. st = build_file_from_blob(
  1200. blob,
  1201. entry.mode,
  1202. full_path.encode(),
  1203. honor_filemode=honor_filemode,
  1204. symlink_fn=symlink_fn,
  1205. )
  1206. # Update index
  1207. index[entry.path] = index_entry_from_stat(st, entry.sha)
  1208. # Remove files that existed in old tree but not in new tree
  1209. if old_tree:
  1210. for entry in iter_tree_contents(repo.object_store, old_tree_id):
  1211. if entry.path not in handled_paths:
  1212. # Skip .git directory
  1213. if entry.path.startswith(b".git"):
  1214. continue
  1215. # File was deleted
  1216. full_path = os.path.join(repo_path_str, entry.path.decode())
  1217. # Remove from working tree
  1218. if os.path.exists(full_path):
  1219. os.remove(full_path)
  1220. # Remove from index
  1221. if entry.path in index:
  1222. del index[entry.path]
  1223. # Clean up empty directories
  1224. dir_path = os.path.dirname(full_path)
  1225. while (
  1226. dir_path and dir_path != repo_path_str and os.path.exists(dir_path)
  1227. ):
  1228. try:
  1229. if not os.listdir(dir_path):
  1230. os.rmdir(dir_path)
  1231. dir_path = os.path.dirname(dir_path)
  1232. else:
  1233. break
  1234. except OSError:
  1235. break
  1236. # If force_remove_untracked is True, remove any files in working directory
  1237. # that are not in the target tree (useful for reset --hard)
  1238. if force_remove_untracked:
  1239. # Walk through all files in the working directory
  1240. for root, dirs, files in os.walk(repo_path_str):
  1241. # Skip .git directory
  1242. if ".git" in dirs:
  1243. dirs.remove(".git")
  1244. for file in files:
  1245. full_path = os.path.join(root, file)
  1246. # Get relative path from repo root
  1247. rel_path = os.path.relpath(full_path, repo_path_str)
  1248. rel_path_bytes = rel_path.encode()
  1249. # If this file is not in the target tree, remove it
  1250. if rel_path_bytes not in handled_paths:
  1251. os.remove(full_path)
  1252. # Remove from index if present
  1253. if rel_path_bytes in index:
  1254. del index[rel_path_bytes]
  1255. # Clean up empty directories
  1256. for root, dirs, files in os.walk(repo_path_str, topdown=False):
  1257. if ".git" in root:
  1258. continue
  1259. if root != repo_path_str and not files and not dirs:
  1260. try:
  1261. os.rmdir(root)
  1262. except OSError:
  1263. pass
  1264. # Write the updated index
  1265. index.write()
  1266. def get_unstaged_changes(
  1267. index: Index, root_path: Union[str, bytes], filter_blob_callback=None
  1268. ):
  1269. """Walk through an index and check for differences against working tree.
  1270. Args:
  1271. index: index to check
  1272. root_path: path in which to find files
  1273. Returns: iterator over paths with unstaged changes
  1274. """
  1275. # For each entry in the index check the sha1 & ensure not staged
  1276. if not isinstance(root_path, bytes):
  1277. root_path = os.fsencode(root_path)
  1278. for tree_path, entry in index.iteritems():
  1279. full_path = _tree_to_fs_path(root_path, tree_path)
  1280. if isinstance(entry, ConflictedIndexEntry):
  1281. # Conflicted files are always unstaged
  1282. yield tree_path
  1283. continue
  1284. try:
  1285. st = os.lstat(full_path)
  1286. if stat.S_ISDIR(st.st_mode):
  1287. if _has_directory_changed(tree_path, entry):
  1288. yield tree_path
  1289. continue
  1290. if not stat.S_ISREG(st.st_mode) and not stat.S_ISLNK(st.st_mode):
  1291. continue
  1292. blob = blob_from_path_and_stat(full_path, st)
  1293. if filter_blob_callback is not None:
  1294. blob = filter_blob_callback(blob, tree_path)
  1295. except FileNotFoundError:
  1296. # The file was removed, so we assume that counts as
  1297. # different from whatever file used to exist.
  1298. yield tree_path
  1299. else:
  1300. if blob.id != entry.sha:
  1301. yield tree_path
  1302. os_sep_bytes = os.sep.encode("ascii")
  1303. def _tree_to_fs_path(root_path: bytes, tree_path: bytes):
  1304. """Convert a git tree path to a file system path.
  1305. Args:
  1306. root_path: Root filesystem path
  1307. tree_path: Git tree path as bytes
  1308. Returns: File system path.
  1309. """
  1310. assert isinstance(tree_path, bytes)
  1311. if os_sep_bytes != b"/":
  1312. sep_corrected_path = tree_path.replace(b"/", os_sep_bytes)
  1313. else:
  1314. sep_corrected_path = tree_path
  1315. return os.path.join(root_path, sep_corrected_path)
  1316. def _fs_to_tree_path(fs_path: Union[str, bytes]) -> bytes:
  1317. """Convert a file system path to a git tree path.
  1318. Args:
  1319. fs_path: File system path.
  1320. Returns: Git tree path as bytes
  1321. """
  1322. if not isinstance(fs_path, bytes):
  1323. fs_path_bytes = os.fsencode(fs_path)
  1324. else:
  1325. fs_path_bytes = fs_path
  1326. if os_sep_bytes != b"/":
  1327. tree_path = fs_path_bytes.replace(os_sep_bytes, b"/")
  1328. else:
  1329. tree_path = fs_path_bytes
  1330. return tree_path
  1331. def index_entry_from_directory(st, path: bytes) -> Optional[IndexEntry]:
  1332. if os.path.exists(os.path.join(path, b".git")):
  1333. head = read_submodule_head(path)
  1334. if head is None:
  1335. return None
  1336. return index_entry_from_stat(st, head, mode=S_IFGITLINK)
  1337. return None
  1338. def index_entry_from_path(
  1339. path: bytes, object_store: Optional[ObjectContainer] = None
  1340. ) -> Optional[IndexEntry]:
  1341. """Create an index from a filesystem path.
  1342. This returns an index value for files, symlinks
  1343. and tree references. for directories and
  1344. non-existent files it returns None
  1345. Args:
  1346. path: Path to create an index entry for
  1347. object_store: Optional object store to
  1348. save new blobs in
  1349. Returns: An index entry; None for directories
  1350. """
  1351. assert isinstance(path, bytes)
  1352. st = os.lstat(path)
  1353. if stat.S_ISDIR(st.st_mode):
  1354. return index_entry_from_directory(st, path)
  1355. if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode):
  1356. blob = blob_from_path_and_stat(path, st)
  1357. if object_store is not None:
  1358. object_store.add_object(blob)
  1359. return index_entry_from_stat(st, blob.id)
  1360. return None
  1361. def iter_fresh_entries(
  1362. paths: Iterable[bytes],
  1363. root_path: bytes,
  1364. object_store: Optional[ObjectContainer] = None,
  1365. ) -> Iterator[tuple[bytes, Optional[IndexEntry]]]:
  1366. """Iterate over current versions of index entries on disk.
  1367. Args:
  1368. paths: Paths to iterate over
  1369. root_path: Root path to access from
  1370. object_store: Optional store to save new blobs in
  1371. Returns: Iterator over path, index_entry
  1372. """
  1373. for path in paths:
  1374. p = _tree_to_fs_path(root_path, path)
  1375. try:
  1376. entry = index_entry_from_path(p, object_store=object_store)
  1377. except (FileNotFoundError, IsADirectoryError):
  1378. entry = None
  1379. yield path, entry
  1380. def iter_fresh_objects(
  1381. paths: Iterable[bytes], root_path: bytes, include_deleted=False, object_store=None
  1382. ) -> Iterator[tuple[bytes, Optional[bytes], Optional[int]]]:
  1383. """Iterate over versions of objects on disk referenced by index.
  1384. Args:
  1385. root_path: Root path to access from
  1386. include_deleted: Include deleted entries with sha and
  1387. mode set to None
  1388. object_store: Optional object store to report new items to
  1389. Returns: Iterator over path, sha, mode
  1390. """
  1391. for path, entry in iter_fresh_entries(paths, root_path, object_store=object_store):
  1392. if entry is None:
  1393. if include_deleted:
  1394. yield path, None, None
  1395. else:
  1396. yield path, entry.sha, cleanup_mode(entry.mode)
  1397. def refresh_index(index: Index, root_path: bytes) -> None:
  1398. """Refresh the contents of an index.
  1399. This is the equivalent to running 'git commit -a'.
  1400. Args:
  1401. index: Index to update
  1402. root_path: Root filesystem path
  1403. """
  1404. for path, entry in iter_fresh_entries(index, root_path):
  1405. if entry:
  1406. index[path] = entry
  1407. class locked_index:
  1408. """Lock the index while making modifications.
  1409. Works as a context manager.
  1410. """
  1411. def __init__(self, path: Union[bytes, str]) -> None:
  1412. self._path = path
  1413. def __enter__(self):
  1414. self._file = GitFile(self._path, "wb")
  1415. self._index = Index(self._path)
  1416. return self._index
  1417. def __exit__(self, exc_type, exc_value, traceback):
  1418. if exc_type is not None:
  1419. self._file.abort()
  1420. return
  1421. try:
  1422. f = SHA1Writer(self._file)
  1423. write_index_dict(f, self._index._byname)
  1424. except BaseException:
  1425. self._file.abort()
  1426. else:
  1427. f.close()