index.py 49 KB

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