index.py 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502
  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 published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Parser for the git index file format."""
  22. import errno
  23. import os
  24. import shutil
  25. import stat
  26. import struct
  27. import sys
  28. import types
  29. from collections.abc import Generator, Iterable, Iterator
  30. from dataclasses import dataclass
  31. from enum import Enum
  32. from typing import (
  33. TYPE_CHECKING,
  34. Any,
  35. BinaryIO,
  36. Callable,
  37. Optional,
  38. Union,
  39. cast,
  40. )
  41. if TYPE_CHECKING:
  42. from .config import Config
  43. from .diff_tree import TreeChange
  44. from .file import _GitFile
  45. from .line_ending import BlobNormalizer
  46. from .object_store import BaseObjectStore
  47. from .repo import Repo
  48. from .file import GitFile
  49. from .object_store import iter_tree_contents
  50. from .objects import (
  51. S_IFGITLINK,
  52. S_ISGITLINK,
  53. Blob,
  54. ObjectID,
  55. Tree,
  56. hex_to_sha,
  57. sha_to_hex,
  58. )
  59. from .pack import ObjectContainer, SHA1Reader, SHA1Writer
  60. # 2-bit stage (during merge)
  61. FLAG_STAGEMASK = 0x3000
  62. FLAG_STAGESHIFT = 12
  63. FLAG_NAMEMASK = 0x0FFF
  64. # assume-valid
  65. FLAG_VALID = 0x8000
  66. # extended flag (must be zero in version 2)
  67. FLAG_EXTENDED = 0x4000
  68. # used by sparse checkout
  69. EXTENDED_FLAG_SKIP_WORKTREE = 0x4000
  70. # used by "git add -N"
  71. EXTENDED_FLAG_INTEND_TO_ADD = 0x2000
  72. DEFAULT_VERSION = 2
  73. # Index extension signatures
  74. TREE_EXTENSION = b"TREE"
  75. REUC_EXTENSION = b"REUC"
  76. UNTR_EXTENSION = b"UNTR"
  77. EOIE_EXTENSION = b"EOIE"
  78. IEOT_EXTENSION = b"IEOT"
  79. def _encode_varint(value: int) -> bytes:
  80. """Encode an integer using variable-width encoding.
  81. Same format as used for OFS_DELTA pack entries and index v4 path compression.
  82. Uses 7 bits per byte, with the high bit indicating continuation.
  83. Args:
  84. value: Integer to encode
  85. Returns:
  86. Encoded bytes
  87. """
  88. if value == 0:
  89. return b"\x00"
  90. result = []
  91. while value > 0:
  92. byte = value & 0x7F # Take lower 7 bits
  93. value >>= 7
  94. if value > 0:
  95. byte |= 0x80 # Set continuation bit
  96. result.append(byte)
  97. return bytes(result)
  98. def _decode_varint(data: bytes, offset: int = 0) -> tuple[int, int]:
  99. """Decode a variable-width encoded integer.
  100. Args:
  101. data: Bytes to decode from
  102. offset: Starting offset in data
  103. Returns:
  104. tuple of (decoded_value, new_offset)
  105. """
  106. value = 0
  107. shift = 0
  108. pos = offset
  109. while pos < len(data):
  110. byte = data[pos]
  111. pos += 1
  112. value |= (byte & 0x7F) << shift
  113. shift += 7
  114. if not (byte & 0x80): # No continuation bit
  115. break
  116. return value, pos
  117. def _compress_path(path: bytes, previous_path: bytes) -> bytes:
  118. """Compress a path relative to the previous path for index version 4.
  119. Args:
  120. path: Path to compress
  121. previous_path: Previous path for comparison
  122. Returns:
  123. Compressed path data (varint prefix_len + suffix)
  124. """
  125. # Find the common prefix length
  126. common_len = 0
  127. min_len = min(len(path), len(previous_path))
  128. for i in range(min_len):
  129. if path[i] == previous_path[i]:
  130. common_len += 1
  131. else:
  132. break
  133. # The number of bytes to remove from the end of previous_path
  134. # to get the common prefix
  135. remove_len = len(previous_path) - common_len
  136. # The suffix to append
  137. suffix = path[common_len:]
  138. # Encode: varint(remove_len) + suffix + NUL
  139. return _encode_varint(remove_len) + suffix + b"\x00"
  140. def _decompress_path(
  141. data: bytes, offset: int, previous_path: bytes
  142. ) -> tuple[bytes, int]:
  143. """Decompress a path from index version 4 compressed format.
  144. Args:
  145. data: Raw data containing compressed path
  146. offset: Starting offset in data
  147. previous_path: Previous path for decompression
  148. Returns:
  149. tuple of (decompressed_path, new_offset)
  150. """
  151. # Decode the number of bytes to remove from previous path
  152. remove_len, new_offset = _decode_varint(data, offset)
  153. # Find the NUL terminator for the suffix
  154. suffix_start = new_offset
  155. suffix_end = suffix_start
  156. while suffix_end < len(data) and data[suffix_end] != 0:
  157. suffix_end += 1
  158. if suffix_end >= len(data):
  159. raise ValueError("Unterminated path suffix in compressed entry")
  160. suffix = data[suffix_start:suffix_end]
  161. new_offset = suffix_end + 1 # Skip the NUL terminator
  162. # Reconstruct the path
  163. if remove_len > len(previous_path):
  164. raise ValueError(
  165. f"Invalid path compression: trying to remove {remove_len} bytes from {len(previous_path)}-byte path"
  166. )
  167. prefix = previous_path[:-remove_len] if remove_len > 0 else previous_path
  168. path = prefix + suffix
  169. return path, new_offset
  170. def _decompress_path_from_stream(
  171. f: BinaryIO, previous_path: bytes
  172. ) -> tuple[bytes, int]:
  173. """Decompress a path from index version 4 compressed format, reading from stream.
  174. Args:
  175. f: File-like object to read from
  176. previous_path: Previous path for decompression
  177. Returns:
  178. tuple of (decompressed_path, bytes_consumed)
  179. """
  180. # Decode the varint for remove_len by reading byte by byte
  181. remove_len = 0
  182. shift = 0
  183. bytes_consumed = 0
  184. while True:
  185. byte_data = f.read(1)
  186. if not byte_data:
  187. raise ValueError("Unexpected end of file while reading varint")
  188. byte = byte_data[0]
  189. bytes_consumed += 1
  190. remove_len |= (byte & 0x7F) << shift
  191. shift += 7
  192. if not (byte & 0x80): # No continuation bit
  193. break
  194. # Read the suffix until NUL terminator
  195. suffix = b""
  196. while True:
  197. byte_data = f.read(1)
  198. if not byte_data:
  199. raise ValueError("Unexpected end of file while reading path suffix")
  200. byte = byte_data[0]
  201. bytes_consumed += 1
  202. if byte == 0: # NUL terminator
  203. break
  204. suffix += bytes([byte])
  205. # Reconstruct the path
  206. if remove_len > len(previous_path):
  207. raise ValueError(
  208. f"Invalid path compression: trying to remove {remove_len} bytes from {len(previous_path)}-byte path"
  209. )
  210. prefix = previous_path[:-remove_len] if remove_len > 0 else previous_path
  211. path = prefix + suffix
  212. return path, bytes_consumed
  213. class Stage(Enum):
  214. NORMAL = 0
  215. MERGE_CONFLICT_ANCESTOR = 1
  216. MERGE_CONFLICT_THIS = 2
  217. MERGE_CONFLICT_OTHER = 3
  218. @dataclass
  219. class SerializedIndexEntry:
  220. name: bytes
  221. ctime: Union[int, float, tuple[int, int]]
  222. mtime: Union[int, float, tuple[int, int]]
  223. dev: int
  224. ino: int
  225. mode: int
  226. uid: int
  227. gid: int
  228. size: int
  229. sha: bytes
  230. flags: int
  231. extended_flags: int
  232. def stage(self) -> Stage:
  233. return Stage((self.flags & FLAG_STAGEMASK) >> FLAG_STAGESHIFT)
  234. @dataclass
  235. class IndexExtension:
  236. """Base class for index extensions."""
  237. signature: bytes
  238. data: bytes
  239. @classmethod
  240. def from_raw(cls, signature: bytes, data: bytes) -> "IndexExtension":
  241. """Create an extension from raw data.
  242. Args:
  243. signature: 4-byte extension signature
  244. data: Extension data
  245. Returns:
  246. Parsed extension object
  247. """
  248. if signature == TREE_EXTENSION:
  249. return TreeExtension.from_bytes(data)
  250. elif signature == REUC_EXTENSION:
  251. return ResolveUndoExtension.from_bytes(data)
  252. elif signature == UNTR_EXTENSION:
  253. return UntrackedExtension.from_bytes(data)
  254. else:
  255. # Unknown extension - just store raw data
  256. return cls(signature, data)
  257. def to_bytes(self) -> bytes:
  258. """Serialize extension to bytes."""
  259. return self.data
  260. class TreeExtension(IndexExtension):
  261. """Tree cache extension."""
  262. def __init__(self, entries: list[tuple[bytes, bytes, int]]) -> None:
  263. self.entries = entries
  264. super().__init__(TREE_EXTENSION, b"")
  265. @classmethod
  266. def from_bytes(cls, data: bytes) -> "TreeExtension":
  267. # TODO: Implement tree cache parsing
  268. return cls([])
  269. def to_bytes(self) -> bytes:
  270. # TODO: Implement tree cache serialization
  271. return b""
  272. class ResolveUndoExtension(IndexExtension):
  273. """Resolve undo extension for recording merge conflicts."""
  274. def __init__(self, entries: list[tuple[bytes, list[tuple[int, bytes]]]]) -> None:
  275. self.entries = entries
  276. super().__init__(REUC_EXTENSION, b"")
  277. @classmethod
  278. def from_bytes(cls, data: bytes) -> "ResolveUndoExtension":
  279. # TODO: Implement resolve undo parsing
  280. return cls([])
  281. def to_bytes(self) -> bytes:
  282. # TODO: Implement resolve undo serialization
  283. return b""
  284. class UntrackedExtension(IndexExtension):
  285. """Untracked cache extension."""
  286. def __init__(self, data: bytes) -> None:
  287. super().__init__(UNTR_EXTENSION, data)
  288. @classmethod
  289. def from_bytes(cls, data: bytes) -> "UntrackedExtension":
  290. return cls(data)
  291. @dataclass
  292. class IndexEntry:
  293. ctime: Union[int, float, tuple[int, int]]
  294. mtime: Union[int, float, tuple[int, int]]
  295. dev: int
  296. ino: int
  297. mode: int
  298. uid: int
  299. gid: int
  300. size: int
  301. sha: bytes
  302. flags: int = 0
  303. extended_flags: int = 0
  304. @classmethod
  305. def from_serialized(cls, serialized: SerializedIndexEntry) -> "IndexEntry":
  306. return cls(
  307. ctime=serialized.ctime,
  308. mtime=serialized.mtime,
  309. dev=serialized.dev,
  310. ino=serialized.ino,
  311. mode=serialized.mode,
  312. uid=serialized.uid,
  313. gid=serialized.gid,
  314. size=serialized.size,
  315. sha=serialized.sha,
  316. flags=serialized.flags,
  317. extended_flags=serialized.extended_flags,
  318. )
  319. def serialize(self, name: bytes, stage: Stage) -> SerializedIndexEntry:
  320. # Clear out any existing stage bits, then set them from the Stage.
  321. new_flags = self.flags & ~FLAG_STAGEMASK
  322. new_flags |= stage.value << FLAG_STAGESHIFT
  323. return SerializedIndexEntry(
  324. name=name,
  325. ctime=self.ctime,
  326. mtime=self.mtime,
  327. dev=self.dev,
  328. ino=self.ino,
  329. mode=self.mode,
  330. uid=self.uid,
  331. gid=self.gid,
  332. size=self.size,
  333. sha=self.sha,
  334. flags=new_flags,
  335. extended_flags=self.extended_flags,
  336. )
  337. def stage(self) -> Stage:
  338. return Stage((self.flags & FLAG_STAGEMASK) >> FLAG_STAGESHIFT)
  339. @property
  340. def skip_worktree(self) -> bool:
  341. """Return True if the skip-worktree bit is set in extended_flags."""
  342. return bool(self.extended_flags & EXTENDED_FLAG_SKIP_WORKTREE)
  343. def set_skip_worktree(self, skip: bool = True) -> None:
  344. """Helper method to set or clear the skip-worktree bit in extended_flags.
  345. Also sets FLAG_EXTENDED in self.flags if needed.
  346. """
  347. if skip:
  348. # Turn on the skip-worktree bit
  349. self.extended_flags |= EXTENDED_FLAG_SKIP_WORKTREE
  350. # Also ensure the main 'extended' bit is set in flags
  351. self.flags |= FLAG_EXTENDED
  352. else:
  353. # Turn off the skip-worktree bit
  354. self.extended_flags &= ~EXTENDED_FLAG_SKIP_WORKTREE
  355. # Optionally unset the main extended bit if no extended flags remain
  356. if self.extended_flags == 0:
  357. self.flags &= ~FLAG_EXTENDED
  358. class ConflictedIndexEntry:
  359. """Index entry that represents a conflict."""
  360. ancestor: Optional[IndexEntry]
  361. this: Optional[IndexEntry]
  362. other: Optional[IndexEntry]
  363. def __init__(
  364. self,
  365. ancestor: Optional[IndexEntry] = None,
  366. this: Optional[IndexEntry] = None,
  367. other: Optional[IndexEntry] = None,
  368. ) -> None:
  369. self.ancestor = ancestor
  370. self.this = this
  371. self.other = other
  372. class UnmergedEntries(Exception):
  373. """Unmerged entries exist in the index."""
  374. def pathsplit(path: bytes) -> tuple[bytes, bytes]:
  375. """Split a /-delimited path into a directory part and a basename.
  376. Args:
  377. path: The path to split.
  378. Returns:
  379. Tuple with directory name and basename
  380. """
  381. try:
  382. (dirname, basename) = path.rsplit(b"/", 1)
  383. except ValueError:
  384. return (b"", path)
  385. else:
  386. return (dirname, basename)
  387. def pathjoin(*args: bytes) -> bytes:
  388. """Join a /-delimited path."""
  389. return b"/".join([p for p in args if p])
  390. def read_cache_time(f: BinaryIO) -> tuple[int, int]:
  391. """Read a cache time.
  392. Args:
  393. f: File-like object to read from
  394. Returns:
  395. Tuple with seconds and nanoseconds
  396. """
  397. return struct.unpack(">LL", f.read(8))
  398. def write_cache_time(f: BinaryIO, t: Union[int, float, tuple[int, int]]) -> None:
  399. """Write a cache time.
  400. Args:
  401. f: File-like object to write to
  402. t: Time to write (as int, float or tuple with secs and nsecs)
  403. """
  404. if isinstance(t, int):
  405. t = (t, 0)
  406. elif isinstance(t, float):
  407. (secs, nsecs) = divmod(t, 1.0)
  408. t = (int(secs), int(nsecs * 1000000000))
  409. elif not isinstance(t, tuple):
  410. raise TypeError(t)
  411. f.write(struct.pack(">LL", *t))
  412. def read_cache_entry(
  413. f: BinaryIO, version: int, previous_path: bytes = b""
  414. ) -> SerializedIndexEntry:
  415. """Read an entry from a cache file.
  416. Args:
  417. f: File-like object to read from
  418. version: Index version
  419. previous_path: Previous entry's path (for version 4 compression)
  420. """
  421. beginoffset = f.tell()
  422. ctime = read_cache_time(f)
  423. mtime = read_cache_time(f)
  424. (
  425. dev,
  426. ino,
  427. mode,
  428. uid,
  429. gid,
  430. size,
  431. sha,
  432. flags,
  433. ) = struct.unpack(">LLLLLL20sH", f.read(20 + 4 * 6 + 2))
  434. if flags & FLAG_EXTENDED:
  435. if version < 3:
  436. raise AssertionError("extended flag set in index with version < 3")
  437. (extended_flags,) = struct.unpack(">H", f.read(2))
  438. else:
  439. extended_flags = 0
  440. if version >= 4:
  441. # Version 4: paths are always compressed (name_len should be 0)
  442. name, consumed = _decompress_path_from_stream(f, previous_path)
  443. else:
  444. # Versions < 4: regular name reading
  445. name = f.read(flags & FLAG_NAMEMASK)
  446. # Padding:
  447. if version < 4:
  448. real_size = (f.tell() - beginoffset + 8) & ~7
  449. f.read((beginoffset + real_size) - f.tell())
  450. return SerializedIndexEntry(
  451. name,
  452. ctime,
  453. mtime,
  454. dev,
  455. ino,
  456. mode,
  457. uid,
  458. gid,
  459. size,
  460. sha_to_hex(sha),
  461. flags & ~FLAG_NAMEMASK,
  462. extended_flags,
  463. )
  464. def write_cache_entry(
  465. f: BinaryIO, entry: SerializedIndexEntry, version: int, previous_path: bytes = b""
  466. ) -> None:
  467. """Write an index entry to a file.
  468. Args:
  469. f: File object
  470. entry: IndexEntry to write
  471. version: Index format version
  472. previous_path: Previous entry's path (for version 4 compression)
  473. """
  474. beginoffset = f.tell()
  475. write_cache_time(f, entry.ctime)
  476. write_cache_time(f, entry.mtime)
  477. if version >= 4:
  478. # Version 4: use compression but set name_len to actual filename length
  479. # This matches how C Git implements index v4 flags
  480. compressed_path = _compress_path(entry.name, previous_path)
  481. flags = len(entry.name) | (entry.flags & ~FLAG_NAMEMASK)
  482. else:
  483. # Versions < 4: include actual name length
  484. flags = len(entry.name) | (entry.flags & ~FLAG_NAMEMASK)
  485. if entry.extended_flags:
  486. flags |= FLAG_EXTENDED
  487. if flags & FLAG_EXTENDED and version is not None and version < 3:
  488. raise AssertionError("unable to use extended flags in version < 3")
  489. f.write(
  490. struct.pack(
  491. b">LLLLLL20sH",
  492. entry.dev & 0xFFFFFFFF,
  493. entry.ino & 0xFFFFFFFF,
  494. entry.mode,
  495. entry.uid,
  496. entry.gid,
  497. entry.size,
  498. hex_to_sha(entry.sha),
  499. flags,
  500. )
  501. )
  502. if flags & FLAG_EXTENDED:
  503. f.write(struct.pack(b">H", entry.extended_flags))
  504. if version >= 4:
  505. # Version 4: always write compressed path
  506. f.write(compressed_path)
  507. else:
  508. # Versions < 4: write regular path and padding
  509. f.write(entry.name)
  510. real_size = (f.tell() - beginoffset + 8) & ~7
  511. f.write(b"\0" * ((beginoffset + real_size) - f.tell()))
  512. class UnsupportedIndexFormat(Exception):
  513. """An unsupported index format was encountered."""
  514. def __init__(self, version: int) -> None:
  515. self.index_format_version = version
  516. def read_index_header(f: BinaryIO) -> tuple[int, int]:
  517. """Read an index header from a file.
  518. Returns:
  519. tuple of (version, num_entries)
  520. """
  521. header = f.read(4)
  522. if header != b"DIRC":
  523. raise AssertionError(f"Invalid index file header: {header!r}")
  524. (version, num_entries) = struct.unpack(b">LL", f.read(4 * 2))
  525. if version not in (1, 2, 3, 4):
  526. raise UnsupportedIndexFormat(version)
  527. return version, num_entries
  528. def write_index_extension(f: BinaryIO, extension: IndexExtension) -> None:
  529. """Write an index extension.
  530. Args:
  531. f: File-like object to write to
  532. extension: Extension to write
  533. """
  534. data = extension.to_bytes()
  535. f.write(extension.signature)
  536. f.write(struct.pack(">I", len(data)))
  537. f.write(data)
  538. def read_index(f: BinaryIO) -> Iterator[SerializedIndexEntry]:
  539. """Read an index file, yielding the individual entries."""
  540. version, num_entries = read_index_header(f)
  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. yield entry
  546. def read_index_dict_with_version(
  547. f: BinaryIO,
  548. ) -> tuple[
  549. dict[bytes, Union[IndexEntry, ConflictedIndexEntry]], int, list[IndexExtension]
  550. ]:
  551. """Read an index file and return it as a dictionary along with the version.
  552. Returns:
  553. tuple of (entries_dict, version, extensions)
  554. """
  555. version, num_entries = read_index_header(f)
  556. ret: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]] = {}
  557. previous_path = b""
  558. for i in range(num_entries):
  559. entry = read_cache_entry(f, version, previous_path)
  560. previous_path = entry.name
  561. stage = entry.stage()
  562. if stage == Stage.NORMAL:
  563. ret[entry.name] = IndexEntry.from_serialized(entry)
  564. else:
  565. existing = ret.setdefault(entry.name, ConflictedIndexEntry())
  566. if isinstance(existing, IndexEntry):
  567. raise AssertionError(f"Non-conflicted entry for {entry.name!r} exists")
  568. if stage == Stage.MERGE_CONFLICT_ANCESTOR:
  569. existing.ancestor = IndexEntry.from_serialized(entry)
  570. elif stage == Stage.MERGE_CONFLICT_THIS:
  571. existing.this = IndexEntry.from_serialized(entry)
  572. elif stage == Stage.MERGE_CONFLICT_OTHER:
  573. existing.other = IndexEntry.from_serialized(entry)
  574. # Read extensions
  575. extensions = []
  576. while True:
  577. # Check if we're at the end (20 bytes before EOF for SHA checksum)
  578. current_pos = f.tell()
  579. f.seek(0, 2) # EOF
  580. eof_pos = f.tell()
  581. f.seek(current_pos)
  582. if current_pos >= eof_pos - 20:
  583. break
  584. # Try to read extension signature
  585. signature = f.read(4)
  586. if len(signature) < 4:
  587. break
  588. # Check if it's a valid extension signature (4 uppercase letters)
  589. if not all(65 <= b <= 90 for b in signature):
  590. # Not an extension, seek back
  591. f.seek(-4, 1)
  592. break
  593. # Read extension size
  594. size_data = f.read(4)
  595. if len(size_data) < 4:
  596. break
  597. size = struct.unpack(">I", size_data)[0]
  598. # Read extension data
  599. data = f.read(size)
  600. if len(data) < size:
  601. break
  602. extension = IndexExtension.from_raw(signature, data)
  603. extensions.append(extension)
  604. return ret, version, extensions
  605. def read_index_dict(
  606. f: BinaryIO,
  607. ) -> dict[bytes, Union[IndexEntry, ConflictedIndexEntry]]:
  608. """Read an index file and return it as a dictionary.
  609. Dict Key is tuple of path and stage number, as
  610. path alone is not unique
  611. Args:
  612. f: File object to read fromls.
  613. """
  614. ret: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]] = {}
  615. for entry in read_index(f):
  616. stage = entry.stage()
  617. if stage == Stage.NORMAL:
  618. ret[entry.name] = IndexEntry.from_serialized(entry)
  619. else:
  620. existing = ret.setdefault(entry.name, ConflictedIndexEntry())
  621. if isinstance(existing, IndexEntry):
  622. raise AssertionError(f"Non-conflicted entry for {entry.name!r} exists")
  623. if stage == Stage.MERGE_CONFLICT_ANCESTOR:
  624. existing.ancestor = IndexEntry.from_serialized(entry)
  625. elif stage == Stage.MERGE_CONFLICT_THIS:
  626. existing.this = IndexEntry.from_serialized(entry)
  627. elif stage == Stage.MERGE_CONFLICT_OTHER:
  628. existing.other = IndexEntry.from_serialized(entry)
  629. return ret
  630. def write_index(
  631. f: BinaryIO,
  632. entries: list[SerializedIndexEntry],
  633. version: Optional[int] = None,
  634. extensions: Optional[list[IndexExtension]] = None,
  635. ) -> None:
  636. """Write an index file.
  637. Args:
  638. f: File-like object to write to
  639. version: Version number to write
  640. entries: Iterable over the entries to write
  641. extensions: Optional list of extensions to write
  642. """
  643. if version is None:
  644. version = DEFAULT_VERSION
  645. # STEP 1: check if any extended_flags are set
  646. uses_extended_flags = any(e.extended_flags != 0 for e in entries)
  647. if uses_extended_flags and version < 3:
  648. # Force or bump the version to 3
  649. version = 3
  650. # The rest is unchanged, but you might insert a final check:
  651. if version < 3:
  652. # Double-check no extended flags appear
  653. for e in entries:
  654. if e.extended_flags != 0:
  655. raise AssertionError("Attempt to use extended flags in index < v3")
  656. # Proceed with the existing code to write the header and entries.
  657. f.write(b"DIRC")
  658. f.write(struct.pack(b">LL", version, len(entries)))
  659. previous_path = b""
  660. for entry in entries:
  661. write_cache_entry(f, entry, version=version, previous_path=previous_path)
  662. previous_path = entry.name
  663. # Write extensions
  664. if extensions:
  665. for extension in extensions:
  666. write_index_extension(f, extension)
  667. def write_index_dict(
  668. f: BinaryIO,
  669. entries: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]],
  670. version: Optional[int] = None,
  671. extensions: Optional[list[IndexExtension]] = None,
  672. ) -> None:
  673. """Write an index file based on the contents of a dictionary.
  674. being careful to sort by path and then by stage.
  675. """
  676. entries_list = []
  677. for key in sorted(entries):
  678. value = entries[key]
  679. if isinstance(value, ConflictedIndexEntry):
  680. if value.ancestor is not None:
  681. entries_list.append(
  682. value.ancestor.serialize(key, Stage.MERGE_CONFLICT_ANCESTOR)
  683. )
  684. if value.this is not None:
  685. entries_list.append(
  686. value.this.serialize(key, Stage.MERGE_CONFLICT_THIS)
  687. )
  688. if value.other is not None:
  689. entries_list.append(
  690. value.other.serialize(key, Stage.MERGE_CONFLICT_OTHER)
  691. )
  692. else:
  693. entries_list.append(value.serialize(key, Stage.NORMAL))
  694. write_index(f, entries_list, version=version, extensions=extensions)
  695. def cleanup_mode(mode: int) -> int:
  696. """Cleanup a mode value.
  697. This will return a mode that can be stored in a tree object.
  698. Args:
  699. mode: Mode to clean up.
  700. Returns:
  701. mode
  702. """
  703. if stat.S_ISLNK(mode):
  704. return stat.S_IFLNK
  705. elif stat.S_ISDIR(mode):
  706. return stat.S_IFDIR
  707. elif S_ISGITLINK(mode):
  708. return S_IFGITLINK
  709. ret = stat.S_IFREG | 0o644
  710. if mode & 0o100:
  711. ret |= 0o111
  712. return ret
  713. class Index:
  714. """A Git Index file."""
  715. _byname: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]]
  716. def __init__(
  717. self,
  718. filename: Union[bytes, str, os.PathLike],
  719. read: bool = True,
  720. skip_hash: bool = False,
  721. version: Optional[int] = None,
  722. ) -> None:
  723. """Create an index object associated with the given filename.
  724. Args:
  725. filename: Path to the index file
  726. read: Whether to initialize the index from the given file, should it exist.
  727. skip_hash: Whether to skip SHA1 hash when writing (for manyfiles feature)
  728. version: Index format version to use (None = auto-detect from file or use default)
  729. """
  730. self._filename = os.fspath(filename)
  731. # TODO(jelmer): Store the version returned by read_index
  732. self._version = version
  733. self._skip_hash = skip_hash
  734. self._extensions: list[IndexExtension] = []
  735. self.clear()
  736. if read:
  737. self.read()
  738. @property
  739. def path(self) -> Union[bytes, str]:
  740. return self._filename
  741. def __repr__(self) -> str:
  742. return f"{self.__class__.__name__}({self._filename!r})"
  743. def write(self) -> None:
  744. """Write current contents of index to disk."""
  745. from typing import BinaryIO, cast
  746. f = GitFile(self._filename, "wb")
  747. try:
  748. # Filter out extensions with no meaningful data
  749. meaningful_extensions = []
  750. for ext in self._extensions:
  751. # Skip extensions that have empty data
  752. ext_data = ext.to_bytes()
  753. if ext_data:
  754. meaningful_extensions.append(ext)
  755. if self._skip_hash:
  756. # When skipHash is enabled, write the index without computing SHA1
  757. write_index_dict(
  758. cast(BinaryIO, f),
  759. self._byname,
  760. version=self._version,
  761. extensions=meaningful_extensions,
  762. )
  763. # Write 20 zero bytes instead of SHA1
  764. f.write(b"\x00" * 20)
  765. f.close()
  766. else:
  767. sha1_writer = SHA1Writer(cast(BinaryIO, f))
  768. write_index_dict(
  769. cast(BinaryIO, sha1_writer),
  770. self._byname,
  771. version=self._version,
  772. extensions=meaningful_extensions,
  773. )
  774. sha1_writer.close()
  775. except:
  776. f.close()
  777. raise
  778. def read(self) -> None:
  779. """Read current contents of index from disk."""
  780. if not os.path.exists(self._filename):
  781. return
  782. f = GitFile(self._filename, "rb")
  783. try:
  784. sha1_reader = SHA1Reader(f)
  785. entries, version, extensions = read_index_dict_with_version(
  786. cast(BinaryIO, sha1_reader)
  787. )
  788. self._version = version
  789. self._extensions = extensions
  790. self.update(entries)
  791. # Extensions have already been read by read_index_dict_with_version
  792. sha1_reader.check_sha(allow_empty=True)
  793. finally:
  794. f.close()
  795. def __len__(self) -> int:
  796. """Number of entries in this index file."""
  797. return len(self._byname)
  798. def __getitem__(self, key: bytes) -> Union[IndexEntry, ConflictedIndexEntry]:
  799. """Retrieve entry by relative path and stage.
  800. Returns: Either a IndexEntry or a ConflictedIndexEntry
  801. Raises KeyError: if the entry does not exist
  802. """
  803. return self._byname[key]
  804. def __iter__(self) -> Iterator[bytes]:
  805. """Iterate over the paths and stages in this index."""
  806. return iter(self._byname)
  807. def __contains__(self, key: bytes) -> bool:
  808. return key in self._byname
  809. def get_sha1(self, path: bytes) -> bytes:
  810. """Return the (git object) SHA1 for the object at a path."""
  811. value = self[path]
  812. if isinstance(value, ConflictedIndexEntry):
  813. raise UnmergedEntries
  814. return value.sha
  815. def get_mode(self, path: bytes) -> int:
  816. """Return the POSIX file mode for the object at a path."""
  817. value = self[path]
  818. if isinstance(value, ConflictedIndexEntry):
  819. raise UnmergedEntries
  820. return value.mode
  821. def iterobjects(self) -> Iterable[tuple[bytes, bytes, int]]:
  822. """Iterate over path, sha, mode tuples for use with commit_tree."""
  823. for path in self:
  824. entry = self[path]
  825. if isinstance(entry, ConflictedIndexEntry):
  826. raise UnmergedEntries
  827. yield path, entry.sha, cleanup_mode(entry.mode)
  828. def has_conflicts(self) -> bool:
  829. for value in self._byname.values():
  830. if isinstance(value, ConflictedIndexEntry):
  831. return True
  832. return False
  833. def clear(self) -> None:
  834. """Remove all contents from this index."""
  835. self._byname = {}
  836. def __setitem__(
  837. self, name: bytes, value: Union[IndexEntry, ConflictedIndexEntry]
  838. ) -> None:
  839. assert isinstance(name, bytes)
  840. self._byname[name] = value
  841. def __delitem__(self, name: bytes) -> None:
  842. del self._byname[name]
  843. def iteritems(
  844. self,
  845. ) -> Iterator[tuple[bytes, Union[IndexEntry, ConflictedIndexEntry]]]:
  846. return iter(self._byname.items())
  847. def items(self) -> Iterator[tuple[bytes, Union[IndexEntry, ConflictedIndexEntry]]]:
  848. return iter(self._byname.items())
  849. def update(
  850. self, entries: dict[bytes, Union[IndexEntry, ConflictedIndexEntry]]
  851. ) -> None:
  852. for key, value in entries.items():
  853. self[key] = value
  854. def paths(self) -> Generator[bytes, None, None]:
  855. yield from self._byname.keys()
  856. def changes_from_tree(
  857. self,
  858. object_store: ObjectContainer,
  859. tree: ObjectID,
  860. want_unchanged: bool = False,
  861. ) -> Generator[
  862. tuple[
  863. tuple[Optional[bytes], Optional[bytes]],
  864. tuple[Optional[int], Optional[int]],
  865. tuple[Optional[bytes], Optional[bytes]],
  866. ],
  867. None,
  868. None,
  869. ]:
  870. """Find the differences between the contents of this index and a tree.
  871. Args:
  872. object_store: Object store to use for retrieving tree contents
  873. tree: SHA1 of the root tree
  874. want_unchanged: Whether unchanged files should be reported
  875. Returns: Iterator over tuples with (oldpath, newpath), (oldmode,
  876. newmode), (oldsha, newsha)
  877. """
  878. def lookup_entry(path: bytes) -> tuple[bytes, int]:
  879. entry = self[path]
  880. if hasattr(entry, "sha") and hasattr(entry, "mode"):
  881. return entry.sha, cleanup_mode(entry.mode)
  882. else:
  883. # Handle ConflictedIndexEntry case
  884. return b"", 0
  885. yield from changes_from_tree(
  886. self.paths(),
  887. lookup_entry,
  888. object_store,
  889. tree,
  890. want_unchanged=want_unchanged,
  891. )
  892. def commit(self, object_store: ObjectContainer) -> bytes:
  893. """Create a new tree from an index.
  894. Args:
  895. object_store: Object store to save the tree in
  896. Returns:
  897. Root tree SHA
  898. """
  899. return commit_tree(object_store, self.iterobjects())
  900. def commit_tree(
  901. object_store: ObjectContainer, blobs: Iterable[tuple[bytes, bytes, int]]
  902. ) -> bytes:
  903. """Commit a new tree.
  904. Args:
  905. object_store: Object store to add trees to
  906. blobs: Iterable over blob path, sha, mode entries
  907. Returns:
  908. SHA1 of the created tree.
  909. """
  910. trees: dict[bytes, Any] = {b"": {}}
  911. def add_tree(path: bytes) -> dict[bytes, Any]:
  912. if path in trees:
  913. return trees[path]
  914. dirname, basename = pathsplit(path)
  915. t = add_tree(dirname)
  916. assert isinstance(basename, bytes)
  917. newtree: dict[bytes, Any] = {}
  918. t[basename] = newtree
  919. trees[path] = newtree
  920. return newtree
  921. for path, sha, mode in blobs:
  922. tree_path, basename = pathsplit(path)
  923. tree = add_tree(tree_path)
  924. tree[basename] = (mode, sha)
  925. def build_tree(path: bytes) -> bytes:
  926. tree = Tree()
  927. for basename, entry in trees[path].items():
  928. if isinstance(entry, dict):
  929. mode = stat.S_IFDIR
  930. sha = build_tree(pathjoin(path, basename))
  931. else:
  932. (mode, sha) = entry
  933. tree.add(basename, mode, sha)
  934. object_store.add_object(tree)
  935. return tree.id
  936. return build_tree(b"")
  937. def commit_index(object_store: ObjectContainer, index: Index) -> bytes:
  938. """Create a new tree from an index.
  939. Args:
  940. object_store: Object store to save the tree in
  941. index: Index file
  942. Note: This function is deprecated, use index.commit() instead.
  943. Returns: Root tree sha.
  944. """
  945. return commit_tree(object_store, index.iterobjects())
  946. def changes_from_tree(
  947. names: Iterable[bytes],
  948. lookup_entry: Callable[[bytes], tuple[bytes, int]],
  949. object_store: ObjectContainer,
  950. tree: Optional[bytes],
  951. want_unchanged: bool = False,
  952. ) -> Iterable[
  953. tuple[
  954. tuple[Optional[bytes], Optional[bytes]],
  955. tuple[Optional[int], Optional[int]],
  956. tuple[Optional[bytes], Optional[bytes]],
  957. ]
  958. ]:
  959. """Find the differences between the contents of a tree and
  960. a working copy.
  961. Args:
  962. names: Iterable of names in the working copy
  963. lookup_entry: Function to lookup an entry in the working copy
  964. object_store: Object store to use for retrieving tree contents
  965. tree: SHA1 of the root tree, or None for an empty tree
  966. want_unchanged: Whether unchanged files should be reported
  967. Returns: Iterator over tuples with (oldpath, newpath), (oldmode, newmode),
  968. (oldsha, newsha)
  969. """
  970. # TODO(jelmer): Support a include_trees option
  971. other_names = set(names)
  972. if tree is not None:
  973. for name, mode, sha in iter_tree_contents(object_store, tree):
  974. try:
  975. (other_sha, other_mode) = lookup_entry(name)
  976. except KeyError:
  977. # Was removed
  978. yield ((name, None), (mode, None), (sha, None))
  979. else:
  980. other_names.remove(name)
  981. if want_unchanged or other_sha != sha or other_mode != mode:
  982. yield ((name, name), (mode, other_mode), (sha, other_sha))
  983. # Mention added files
  984. for name in other_names:
  985. try:
  986. (other_sha, other_mode) = lookup_entry(name)
  987. except KeyError:
  988. pass
  989. else:
  990. yield ((None, name), (None, other_mode), (None, other_sha))
  991. def index_entry_from_stat(
  992. stat_val: os.stat_result,
  993. hex_sha: bytes,
  994. mode: Optional[int] = None,
  995. ) -> IndexEntry:
  996. """Create a new index entry from a stat value.
  997. Args:
  998. stat_val: POSIX stat_result instance
  999. hex_sha: Hex sha of the object
  1000. """
  1001. if mode is None:
  1002. mode = cleanup_mode(stat_val.st_mode)
  1003. return IndexEntry(
  1004. ctime=stat_val.st_ctime,
  1005. mtime=stat_val.st_mtime,
  1006. dev=stat_val.st_dev,
  1007. ino=stat_val.st_ino,
  1008. mode=mode,
  1009. uid=stat_val.st_uid,
  1010. gid=stat_val.st_gid,
  1011. size=stat_val.st_size,
  1012. sha=hex_sha,
  1013. flags=0,
  1014. extended_flags=0,
  1015. )
  1016. if sys.platform == "win32":
  1017. # On Windows, creating symlinks either requires administrator privileges
  1018. # or developer mode. Raise a more helpful error when we're unable to
  1019. # create symlinks
  1020. # https://github.com/jelmer/dulwich/issues/1005
  1021. class WindowsSymlinkPermissionError(PermissionError):
  1022. def __init__(self, errno: int, msg: str, filename: Optional[str]) -> None:
  1023. super(PermissionError, self).__init__(
  1024. errno,
  1025. f"Unable to create symlink; do you have developer mode enabled? {msg}",
  1026. filename,
  1027. )
  1028. def symlink(
  1029. src: Union[str, bytes],
  1030. dst: Union[str, bytes],
  1031. target_is_directory: bool = False,
  1032. *,
  1033. dir_fd: Optional[int] = None,
  1034. ) -> None:
  1035. try:
  1036. return os.symlink(
  1037. src, dst, target_is_directory=target_is_directory, dir_fd=dir_fd
  1038. )
  1039. except PermissionError as e:
  1040. raise WindowsSymlinkPermissionError(
  1041. e.errno or 0, e.strerror or "", e.filename
  1042. ) from e
  1043. else:
  1044. symlink = os.symlink
  1045. def build_file_from_blob(
  1046. blob: Blob,
  1047. mode: int,
  1048. target_path: bytes,
  1049. *,
  1050. honor_filemode: bool = True,
  1051. tree_encoding: str = "utf-8",
  1052. symlink_fn: Optional[Callable] = None,
  1053. ) -> os.stat_result:
  1054. """Build a file or symlink on disk based on a Git object.
  1055. Args:
  1056. blob: The git object
  1057. mode: File mode
  1058. target_path: Path to write to
  1059. honor_filemode: An optional flag to honor core.filemode setting in
  1060. config file, default is core.filemode=True, change executable bit
  1061. symlink_fn: Function to use for creating symlinks
  1062. Returns: stat object for the file
  1063. """
  1064. try:
  1065. oldstat = os.lstat(target_path)
  1066. except FileNotFoundError:
  1067. oldstat = None
  1068. contents = blob.as_raw_string()
  1069. if stat.S_ISLNK(mode):
  1070. if oldstat:
  1071. _remove_file_with_readonly_handling(target_path)
  1072. if sys.platform == "win32":
  1073. # os.readlink on Python3 on Windows requires a unicode string.
  1074. contents_str = contents.decode(tree_encoding)
  1075. target_path_str = target_path.decode(tree_encoding)
  1076. (symlink_fn or symlink)(contents_str, target_path_str)
  1077. else:
  1078. (symlink_fn or symlink)(contents, target_path)
  1079. else:
  1080. if oldstat is not None and oldstat.st_size == len(contents):
  1081. with open(target_path, "rb") as f:
  1082. if f.read() == contents:
  1083. return oldstat
  1084. with open(target_path, "wb") as f:
  1085. # Write out file
  1086. f.write(contents)
  1087. if honor_filemode:
  1088. os.chmod(target_path, mode)
  1089. return os.lstat(target_path)
  1090. INVALID_DOTNAMES = (b".git", b".", b"..", b"")
  1091. def _normalize_path_element_default(element: bytes) -> bytes:
  1092. """Normalize path element for default case-insensitive comparison."""
  1093. return element.lower()
  1094. def _normalize_path_element_ntfs(element: bytes) -> bytes:
  1095. """Normalize path element for NTFS filesystem."""
  1096. return element.rstrip(b". ").lower()
  1097. def _normalize_path_element_hfs(element: bytes) -> bytes:
  1098. """Normalize path element for HFS+ filesystem."""
  1099. import unicodedata
  1100. # Decode to Unicode (let UnicodeDecodeError bubble up)
  1101. element_str = element.decode("utf-8", errors="strict")
  1102. # Remove HFS+ ignorable characters
  1103. filtered = "".join(c for c in element_str if ord(c) not in HFS_IGNORABLE_CHARS)
  1104. # Normalize to NFD
  1105. normalized = unicodedata.normalize("NFD", filtered)
  1106. return normalized.lower().encode("utf-8", errors="strict")
  1107. def get_path_element_normalizer(config: "Config") -> Callable[[bytes], bytes]:
  1108. """Get the appropriate path element normalization function based on config.
  1109. Args:
  1110. config: Repository configuration object
  1111. Returns:
  1112. Function that normalizes path elements for the configured filesystem
  1113. """
  1114. import os
  1115. import sys
  1116. if config.get_boolean(b"core", b"protectNTFS", os.name == "nt"):
  1117. return _normalize_path_element_ntfs
  1118. elif config.get_boolean(b"core", b"protectHFS", sys.platform == "darwin"):
  1119. return _normalize_path_element_hfs
  1120. else:
  1121. return _normalize_path_element_default
  1122. def validate_path_element_default(element: bytes) -> bool:
  1123. return _normalize_path_element_default(element) not in INVALID_DOTNAMES
  1124. def validate_path_element_ntfs(element: bytes) -> bool:
  1125. normalized = _normalize_path_element_ntfs(element)
  1126. if normalized in INVALID_DOTNAMES:
  1127. return False
  1128. if normalized == b"git~1":
  1129. return False
  1130. return True
  1131. # HFS+ ignorable Unicode codepoints (from Git's utf8.c)
  1132. HFS_IGNORABLE_CHARS = {
  1133. 0x200C, # ZERO WIDTH NON-JOINER
  1134. 0x200D, # ZERO WIDTH JOINER
  1135. 0x200E, # LEFT-TO-RIGHT MARK
  1136. 0x200F, # RIGHT-TO-LEFT MARK
  1137. 0x202A, # LEFT-TO-RIGHT EMBEDDING
  1138. 0x202B, # RIGHT-TO-LEFT EMBEDDING
  1139. 0x202C, # POP DIRECTIONAL FORMATTING
  1140. 0x202D, # LEFT-TO-RIGHT OVERRIDE
  1141. 0x202E, # RIGHT-TO-LEFT OVERRIDE
  1142. 0x206A, # INHIBIT SYMMETRIC SWAPPING
  1143. 0x206B, # ACTIVATE SYMMETRIC SWAPPING
  1144. 0x206C, # INHIBIT ARABIC FORM SHAPING
  1145. 0x206D, # ACTIVATE ARABIC FORM SHAPING
  1146. 0x206E, # NATIONAL DIGIT SHAPES
  1147. 0x206F, # NOMINAL DIGIT SHAPES
  1148. 0xFEFF, # ZERO WIDTH NO-BREAK SPACE
  1149. }
  1150. def validate_path_element_hfs(element: bytes) -> bool:
  1151. """Validate path element for HFS+ filesystem.
  1152. Equivalent to Git's is_hfs_dotgit and related checks.
  1153. Uses NFD normalization and ignores HFS+ ignorable characters.
  1154. """
  1155. try:
  1156. normalized = _normalize_path_element_hfs(element)
  1157. except UnicodeDecodeError:
  1158. # Malformed UTF-8 - be conservative and reject
  1159. return False
  1160. # Check against invalid names
  1161. if normalized in INVALID_DOTNAMES:
  1162. return False
  1163. # Also check for 8.3 short name
  1164. if normalized == b"git~1":
  1165. return False
  1166. return True
  1167. def validate_path(
  1168. path: bytes,
  1169. element_validator: Callable[[bytes], bool] = validate_path_element_default,
  1170. ) -> bool:
  1171. """Default path validator that just checks for .git/."""
  1172. parts = path.split(b"/")
  1173. for p in parts:
  1174. if not element_validator(p):
  1175. return False
  1176. else:
  1177. return True
  1178. def build_index_from_tree(
  1179. root_path: Union[str, bytes],
  1180. index_path: Union[str, bytes],
  1181. object_store: ObjectContainer,
  1182. tree_id: bytes,
  1183. honor_filemode: bool = True,
  1184. validate_path_element: Callable[[bytes], bool] = validate_path_element_default,
  1185. symlink_fn: Optional[Callable] = None,
  1186. blob_normalizer: Optional["BlobNormalizer"] = None,
  1187. tree_encoding: str = "utf-8",
  1188. ) -> None:
  1189. """Generate and materialize index from a tree.
  1190. Args:
  1191. tree_id: Tree to materialize
  1192. root_path: Target dir for materialized index files
  1193. index_path: Target path for generated index
  1194. object_store: Non-empty object store holding tree contents
  1195. honor_filemode: An optional flag to honor core.filemode setting in
  1196. config file, default is core.filemode=True, change executable bit
  1197. validate_path_element: Function to validate path elements to check
  1198. out; default just refuses .git and .. directories.
  1199. blob_normalizer: An optional BlobNormalizer to use for converting line
  1200. endings when writing blobs to the working directory.
  1201. tree_encoding: Encoding used for tree paths (default: utf-8)
  1202. Note: existing index is wiped and contents are not merged
  1203. in a working dir. Suitable only for fresh clones.
  1204. """
  1205. index = Index(index_path, read=False)
  1206. if not isinstance(root_path, bytes):
  1207. root_path = os.fsencode(root_path)
  1208. for entry in iter_tree_contents(object_store, tree_id):
  1209. if not validate_path(entry.path, validate_path_element):
  1210. continue
  1211. full_path = _tree_to_fs_path(root_path, entry.path, tree_encoding)
  1212. if not os.path.exists(os.path.dirname(full_path)):
  1213. os.makedirs(os.path.dirname(full_path))
  1214. # TODO(jelmer): Merge new index into working tree
  1215. if S_ISGITLINK(entry.mode):
  1216. if not os.path.isdir(full_path):
  1217. os.mkdir(full_path)
  1218. st = os.lstat(full_path)
  1219. # TODO(jelmer): record and return submodule paths
  1220. else:
  1221. obj = object_store[entry.sha]
  1222. assert isinstance(obj, Blob)
  1223. # Apply blob normalization for checkout if normalizer is provided
  1224. if blob_normalizer is not None:
  1225. obj = blob_normalizer.checkout_normalize(obj, entry.path)
  1226. st = build_file_from_blob(
  1227. obj,
  1228. entry.mode,
  1229. full_path,
  1230. honor_filemode=honor_filemode,
  1231. tree_encoding=tree_encoding,
  1232. symlink_fn=symlink_fn,
  1233. )
  1234. # Add file to index
  1235. if not honor_filemode or S_ISGITLINK(entry.mode):
  1236. # we can not use tuple slicing to build a new tuple,
  1237. # because on windows that will convert the times to
  1238. # longs, which causes errors further along
  1239. st_tuple = (
  1240. entry.mode,
  1241. st.st_ino,
  1242. st.st_dev,
  1243. st.st_nlink,
  1244. st.st_uid,
  1245. st.st_gid,
  1246. st.st_size,
  1247. st.st_atime,
  1248. st.st_mtime,
  1249. st.st_ctime,
  1250. )
  1251. st = st.__class__(st_tuple)
  1252. # default to a stage 0 index entry (normal)
  1253. # when reading from the filesystem
  1254. index[entry.path] = index_entry_from_stat(st, entry.sha)
  1255. index.write()
  1256. def blob_from_path_and_mode(
  1257. fs_path: bytes, mode: int, tree_encoding: str = "utf-8"
  1258. ) -> Blob:
  1259. """Create a blob from a path and a stat object.
  1260. Args:
  1261. fs_path: Full file system path to file
  1262. mode: File mode
  1263. Returns: A `Blob` object
  1264. """
  1265. assert isinstance(fs_path, bytes)
  1266. blob = Blob()
  1267. if stat.S_ISLNK(mode):
  1268. if sys.platform == "win32":
  1269. # os.readlink on Python3 on Windows requires a unicode string.
  1270. blob.data = os.readlink(os.fsdecode(fs_path)).encode(tree_encoding)
  1271. else:
  1272. blob.data = os.readlink(fs_path)
  1273. else:
  1274. with open(fs_path, "rb") as f:
  1275. blob.data = f.read()
  1276. return blob
  1277. def blob_from_path_and_stat(
  1278. fs_path: bytes, st: os.stat_result, tree_encoding: str = "utf-8"
  1279. ) -> Blob:
  1280. """Create a blob from a path and a stat object.
  1281. Args:
  1282. fs_path: Full file system path to file
  1283. st: A stat object
  1284. Returns: A `Blob` object
  1285. """
  1286. return blob_from_path_and_mode(fs_path, st.st_mode, tree_encoding)
  1287. def read_submodule_head(path: Union[str, bytes]) -> Optional[bytes]:
  1288. """Read the head commit of a submodule.
  1289. Args:
  1290. path: path to the submodule
  1291. Returns: HEAD sha, None if not a valid head/repository
  1292. """
  1293. from .errors import NotGitRepository
  1294. from .repo import Repo
  1295. # Repo currently expects a "str", so decode if necessary.
  1296. # TODO(jelmer): Perhaps move this into Repo() ?
  1297. if not isinstance(path, str):
  1298. path = os.fsdecode(path)
  1299. try:
  1300. repo = Repo(path)
  1301. except NotGitRepository:
  1302. return None
  1303. try:
  1304. return repo.head()
  1305. except KeyError:
  1306. return None
  1307. def _has_directory_changed(tree_path: bytes, entry: IndexEntry) -> bool:
  1308. """Check if a directory has changed after getting an error.
  1309. When handling an error trying to create a blob from a path, call this
  1310. function. It will check if the path is a directory. If it's a directory
  1311. and a submodule, check the submodule head to see if it's has changed. If
  1312. not, consider the file as changed as Git tracked a file and not a
  1313. directory.
  1314. Return true if the given path should be considered as changed and False
  1315. otherwise or if the path is not a directory.
  1316. """
  1317. # This is actually a directory
  1318. if os.path.exists(os.path.join(tree_path, b".git")):
  1319. # Submodule
  1320. head = read_submodule_head(tree_path)
  1321. if entry.sha != head:
  1322. return True
  1323. else:
  1324. # The file was changed to a directory, so consider it removed.
  1325. return True
  1326. return False
  1327. os_sep_bytes = os.sep.encode("ascii")
  1328. def _ensure_parent_dir_exists(full_path: bytes) -> None:
  1329. """Ensure parent directory exists, checking no parent is a file."""
  1330. parent_dir = os.path.dirname(full_path)
  1331. if parent_dir and not os.path.exists(parent_dir):
  1332. # Walk up the directory tree to find the first existing parent
  1333. current = parent_dir
  1334. parents_to_check: list[bytes] = []
  1335. while current and not os.path.exists(current):
  1336. parents_to_check.insert(0, current)
  1337. new_parent = os.path.dirname(current)
  1338. if new_parent == current:
  1339. # Reached the root or can't go up further
  1340. break
  1341. current = new_parent
  1342. # Check if the existing parent (if any) is a directory
  1343. if current and os.path.exists(current) and not os.path.isdir(current):
  1344. raise OSError(
  1345. f"Cannot create directory, parent path is a file: {current!r}"
  1346. )
  1347. # Now check each parent we need to create isn't blocked by an existing file
  1348. for parent_path in parents_to_check:
  1349. if os.path.exists(parent_path) and not os.path.isdir(parent_path):
  1350. raise OSError(
  1351. f"Cannot create directory, parent path is a file: {parent_path!r}"
  1352. )
  1353. os.makedirs(parent_dir)
  1354. def _remove_file_with_readonly_handling(path: bytes) -> None:
  1355. """Remove a file, handling read-only files on Windows.
  1356. Args:
  1357. path: Path to the file to remove
  1358. """
  1359. try:
  1360. os.unlink(path)
  1361. except PermissionError:
  1362. # On Windows, remove read-only attribute and retry
  1363. if sys.platform == "win32":
  1364. os.chmod(path, stat.S_IWRITE | stat.S_IREAD)
  1365. os.unlink(path)
  1366. else:
  1367. raise
  1368. def _remove_empty_parents(path: bytes, stop_at: bytes) -> None:
  1369. """Remove empty parent directories up to stop_at."""
  1370. parent = os.path.dirname(path)
  1371. while parent and parent != stop_at:
  1372. try:
  1373. os.rmdir(parent)
  1374. parent = os.path.dirname(parent)
  1375. except FileNotFoundError:
  1376. # Directory doesn't exist - stop trying
  1377. break
  1378. except OSError as e:
  1379. if e.errno == errno.ENOTEMPTY:
  1380. # Directory not empty - stop trying
  1381. break
  1382. raise
  1383. def _check_symlink_matches(
  1384. full_path: bytes, repo_object_store: "BaseObjectStore", entry_sha: bytes
  1385. ) -> bool:
  1386. """Check if symlink target matches expected target.
  1387. Returns True if symlink matches, False if it doesn't match.
  1388. """
  1389. try:
  1390. current_target = os.readlink(full_path)
  1391. blob_obj = repo_object_store[entry_sha]
  1392. expected_target = blob_obj.as_raw_string()
  1393. if isinstance(current_target, str):
  1394. current_target = current_target.encode()
  1395. return current_target == expected_target
  1396. except FileNotFoundError:
  1397. # Symlink doesn't exist
  1398. return False
  1399. except OSError as e:
  1400. if e.errno == errno.EINVAL:
  1401. # Not a symlink
  1402. return False
  1403. raise
  1404. def _check_file_matches(
  1405. repo_object_store: "BaseObjectStore",
  1406. full_path: bytes,
  1407. entry_sha: bytes,
  1408. entry_mode: int,
  1409. current_stat: os.stat_result,
  1410. honor_filemode: bool,
  1411. blob_normalizer: Optional["BlobNormalizer"] = None,
  1412. tree_path: Optional[bytes] = None,
  1413. ) -> bool:
  1414. """Check if a file on disk matches the expected git object.
  1415. Returns True if file matches, False if it doesn't match.
  1416. """
  1417. # Check mode first (if honor_filemode is True)
  1418. if honor_filemode:
  1419. current_mode = stat.S_IMODE(current_stat.st_mode)
  1420. expected_mode = stat.S_IMODE(entry_mode)
  1421. # For regular files, only check the user executable bit, not group/other permissions
  1422. # This matches Git's behavior where umask differences don't count as modifications
  1423. if stat.S_ISREG(current_stat.st_mode):
  1424. # Normalize regular file modes to ignore group/other write permissions
  1425. current_mode_normalized = (
  1426. current_mode & 0o755
  1427. ) # Keep only user rwx and all read+execute
  1428. expected_mode_normalized = expected_mode & 0o755
  1429. # For Git compatibility, regular files should be either 644 or 755
  1430. if expected_mode_normalized not in (0o644, 0o755):
  1431. expected_mode_normalized = 0o644 # Default for regular files
  1432. if current_mode_normalized not in (0o644, 0o755):
  1433. # Determine if it should be executable based on user execute bit
  1434. if current_mode & 0o100: # User execute bit is set
  1435. current_mode_normalized = 0o755
  1436. else:
  1437. current_mode_normalized = 0o644
  1438. if current_mode_normalized != expected_mode_normalized:
  1439. return False
  1440. else:
  1441. # For non-regular files (symlinks, etc.), check mode exactly
  1442. if current_mode != expected_mode:
  1443. return False
  1444. # If mode matches (or we don't care), check content via size first
  1445. blob_obj = repo_object_store[entry_sha]
  1446. if current_stat.st_size != blob_obj.raw_length():
  1447. return False
  1448. # Size matches, check actual content
  1449. try:
  1450. with open(full_path, "rb") as f:
  1451. current_content = f.read()
  1452. expected_content = blob_obj.as_raw_string()
  1453. if blob_normalizer and tree_path is not None:
  1454. assert isinstance(blob_obj, Blob)
  1455. normalized_blob = blob_normalizer.checkout_normalize(
  1456. blob_obj, tree_path
  1457. )
  1458. expected_content = normalized_blob.as_raw_string()
  1459. return current_content == expected_content
  1460. except (FileNotFoundError, PermissionError, IsADirectoryError):
  1461. return False
  1462. def _transition_to_submodule(
  1463. repo: "Repo",
  1464. path: bytes,
  1465. full_path: bytes,
  1466. current_stat: Optional[os.stat_result],
  1467. entry: IndexEntry,
  1468. index: Index,
  1469. ) -> None:
  1470. """Transition any type to submodule."""
  1471. from .submodule import ensure_submodule_placeholder
  1472. if current_stat is not None and stat.S_ISDIR(current_stat.st_mode):
  1473. # Already a directory, just ensure .git file exists
  1474. ensure_submodule_placeholder(repo, path)
  1475. else:
  1476. # Remove whatever is there and create submodule
  1477. if current_stat is not None:
  1478. _remove_file_with_readonly_handling(full_path)
  1479. ensure_submodule_placeholder(repo, path)
  1480. st = os.lstat(full_path)
  1481. index[path] = index_entry_from_stat(st, entry.sha)
  1482. def _transition_to_file(
  1483. object_store: "BaseObjectStore",
  1484. path: bytes,
  1485. full_path: bytes,
  1486. current_stat: Optional[os.stat_result],
  1487. entry: IndexEntry,
  1488. index: Index,
  1489. honor_filemode: bool,
  1490. symlink_fn: Optional[Callable[[bytes, bytes], None]],
  1491. blob_normalizer: Optional["BlobNormalizer"],
  1492. tree_encoding: str = "utf-8",
  1493. ) -> None:
  1494. """Transition any type to regular file or symlink."""
  1495. # Check if we need to update
  1496. if (
  1497. current_stat is not None
  1498. and stat.S_ISREG(current_stat.st_mode)
  1499. and not stat.S_ISLNK(entry.mode)
  1500. ):
  1501. # File to file - check if update needed
  1502. file_matches = _check_file_matches(
  1503. object_store,
  1504. full_path,
  1505. entry.sha,
  1506. entry.mode,
  1507. current_stat,
  1508. honor_filemode,
  1509. blob_normalizer,
  1510. path,
  1511. )
  1512. needs_update = not file_matches
  1513. elif (
  1514. current_stat is not None
  1515. and stat.S_ISLNK(current_stat.st_mode)
  1516. and stat.S_ISLNK(entry.mode)
  1517. ):
  1518. # Symlink to symlink - check if update needed
  1519. symlink_matches = _check_symlink_matches(full_path, object_store, entry.sha)
  1520. needs_update = not symlink_matches
  1521. else:
  1522. needs_update = True
  1523. if not needs_update:
  1524. # Just update index - current_stat should always be valid here since we're not updating
  1525. assert current_stat is not None
  1526. index[path] = index_entry_from_stat(current_stat, entry.sha)
  1527. return
  1528. # Remove existing entry if needed
  1529. if current_stat is not None and stat.S_ISDIR(current_stat.st_mode):
  1530. # Remove directory
  1531. dir_contents = set(os.listdir(full_path))
  1532. git_file_name = b".git" if isinstance(full_path, bytes) else ".git"
  1533. if git_file_name in dir_contents:
  1534. if dir_contents != {git_file_name}:
  1535. raise IsADirectoryError(
  1536. f"Cannot replace submodule with untracked files: {full_path!r}"
  1537. )
  1538. shutil.rmtree(full_path)
  1539. else:
  1540. try:
  1541. os.rmdir(full_path)
  1542. except OSError as e:
  1543. if e.errno == errno.ENOTEMPTY:
  1544. raise IsADirectoryError(
  1545. f"Cannot replace non-empty directory with file: {full_path!r}"
  1546. )
  1547. raise
  1548. elif current_stat is not None:
  1549. _remove_file_with_readonly_handling(full_path)
  1550. # Ensure parent directory exists
  1551. _ensure_parent_dir_exists(full_path)
  1552. # Write the file
  1553. blob_obj = object_store[entry.sha]
  1554. assert isinstance(blob_obj, Blob)
  1555. if blob_normalizer:
  1556. blob_obj = blob_normalizer.checkout_normalize(blob_obj, path)
  1557. st = build_file_from_blob(
  1558. blob_obj,
  1559. entry.mode,
  1560. full_path,
  1561. honor_filemode=honor_filemode,
  1562. tree_encoding=tree_encoding,
  1563. symlink_fn=symlink_fn,
  1564. )
  1565. index[path] = index_entry_from_stat(st, entry.sha)
  1566. def _transition_to_absent(
  1567. repo: "Repo",
  1568. path: bytes,
  1569. full_path: bytes,
  1570. current_stat: Optional[os.stat_result],
  1571. index: Index,
  1572. ) -> None:
  1573. """Remove any type of entry."""
  1574. if current_stat is None:
  1575. return
  1576. if stat.S_ISDIR(current_stat.st_mode):
  1577. # Check if it's a submodule directory
  1578. dir_contents = set(os.listdir(full_path))
  1579. git_file_name = b".git" if isinstance(full_path, bytes) else ".git"
  1580. if git_file_name in dir_contents and dir_contents == {git_file_name}:
  1581. shutil.rmtree(full_path)
  1582. else:
  1583. try:
  1584. os.rmdir(full_path)
  1585. except OSError as e:
  1586. if e.errno not in (errno.ENOTEMPTY, errno.EEXIST):
  1587. raise
  1588. else:
  1589. _remove_file_with_readonly_handling(full_path)
  1590. try:
  1591. del index[path]
  1592. except KeyError:
  1593. pass
  1594. # Try to remove empty parent directories
  1595. _remove_empty_parents(
  1596. full_path, repo.path if isinstance(repo.path, bytes) else repo.path.encode()
  1597. )
  1598. def detect_case_only_renames(
  1599. changes: list["TreeChange"],
  1600. config: "Config",
  1601. ) -> list["TreeChange"]:
  1602. """Detect and transform case-only renames in a list of tree changes.
  1603. This function identifies file renames that only differ in case (e.g.,
  1604. README.txt -> readme.txt) and transforms matching ADD/DELETE pairs into
  1605. CHANGE_RENAME operations. It uses filesystem-appropriate path normalization
  1606. based on the repository configuration.
  1607. Args:
  1608. changes: List of TreeChange objects representing file changes
  1609. config: Repository configuration object
  1610. Returns:
  1611. New list of TreeChange objects with case-only renames converted to CHANGE_RENAME
  1612. """
  1613. from .diff_tree import (
  1614. CHANGE_ADD,
  1615. CHANGE_COPY,
  1616. CHANGE_DELETE,
  1617. CHANGE_MODIFY,
  1618. CHANGE_RENAME,
  1619. TreeChange,
  1620. )
  1621. # Build dictionaries of old and new paths with their normalized forms
  1622. old_paths_normalized = {}
  1623. new_paths_normalized = {}
  1624. old_changes = {} # Map from old path to change object
  1625. new_changes = {} # Map from new path to change object
  1626. # Get the appropriate normalizer based on config
  1627. normalize_func = get_path_element_normalizer(config)
  1628. def normalize_path(path: bytes) -> bytes:
  1629. """Normalize entire path using element normalization."""
  1630. return b"/".join(normalize_func(part) for part in path.split(b"/"))
  1631. # Pre-normalize all paths once to avoid repeated normalization
  1632. for change in changes:
  1633. if change.type == CHANGE_DELETE and change.old:
  1634. try:
  1635. normalized = normalize_path(change.old.path)
  1636. except UnicodeDecodeError:
  1637. import logging
  1638. logging.warning(
  1639. "Skipping case-only rename detection for path with invalid UTF-8: %r",
  1640. change.old.path,
  1641. )
  1642. else:
  1643. old_paths_normalized[normalized] = change.old.path
  1644. old_changes[change.old.path] = change
  1645. elif change.type == CHANGE_RENAME and change.old:
  1646. # Treat RENAME as DELETE + ADD for case-only detection
  1647. try:
  1648. normalized = normalize_path(change.old.path)
  1649. except UnicodeDecodeError:
  1650. import logging
  1651. logging.warning(
  1652. "Skipping case-only rename detection for path with invalid UTF-8: %r",
  1653. change.old.path,
  1654. )
  1655. else:
  1656. old_paths_normalized[normalized] = change.old.path
  1657. old_changes[change.old.path] = change
  1658. if (
  1659. change.type in (CHANGE_ADD, CHANGE_MODIFY, CHANGE_RENAME, CHANGE_COPY)
  1660. and change.new
  1661. ):
  1662. try:
  1663. normalized = normalize_path(change.new.path)
  1664. except UnicodeDecodeError:
  1665. import logging
  1666. logging.warning(
  1667. "Skipping case-only rename detection for path with invalid UTF-8: %r",
  1668. change.new.path,
  1669. )
  1670. else:
  1671. new_paths_normalized[normalized] = change.new.path
  1672. new_changes[change.new.path] = change
  1673. # Find case-only renames and transform changes
  1674. case_only_renames = set()
  1675. new_rename_changes = []
  1676. for norm_path, old_path in old_paths_normalized.items():
  1677. if norm_path in new_paths_normalized:
  1678. new_path = new_paths_normalized[norm_path]
  1679. if old_path != new_path:
  1680. # Found a case-only rename
  1681. old_change = old_changes[old_path]
  1682. new_change = new_changes[new_path]
  1683. # Create a CHANGE_RENAME to replace the DELETE and ADD/MODIFY pair
  1684. if new_change.type == CHANGE_ADD:
  1685. # Simple case: DELETE + ADD becomes RENAME
  1686. rename_change = TreeChange(
  1687. CHANGE_RENAME, old_change.old, new_change.new
  1688. )
  1689. else:
  1690. # Complex case: DELETE + MODIFY becomes RENAME
  1691. # Use the old file from DELETE and new file from MODIFY
  1692. rename_change = TreeChange(
  1693. CHANGE_RENAME, old_change.old, new_change.new
  1694. )
  1695. new_rename_changes.append(rename_change)
  1696. # Mark the old changes for removal
  1697. case_only_renames.add(old_change)
  1698. case_only_renames.add(new_change)
  1699. # Return new list with original ADD/DELETE changes replaced by renames
  1700. result = [change for change in changes if change not in case_only_renames]
  1701. result.extend(new_rename_changes)
  1702. return result
  1703. def update_working_tree(
  1704. repo: "Repo",
  1705. old_tree_id: Optional[bytes],
  1706. new_tree_id: bytes,
  1707. change_iterator: Iterator["TreeChange"],
  1708. honor_filemode: bool = True,
  1709. validate_path_element: Optional[Callable[[bytes], bool]] = None,
  1710. symlink_fn: Optional[Callable] = None,
  1711. force_remove_untracked: bool = False,
  1712. blob_normalizer: Optional["BlobNormalizer"] = None,
  1713. tree_encoding: str = "utf-8",
  1714. allow_overwrite_modified: bool = False,
  1715. ) -> None:
  1716. """Update the working tree and index to match a new tree.
  1717. This function handles:
  1718. - Adding new files
  1719. - Updating modified files
  1720. - Removing deleted files
  1721. - Cleaning up empty directories
  1722. Args:
  1723. repo: Repository object
  1724. old_tree_id: SHA of the tree before the update
  1725. new_tree_id: SHA of the tree to update to
  1726. change_iterator: Iterator of TreeChange objects to apply
  1727. honor_filemode: An optional flag to honor core.filemode setting
  1728. validate_path_element: Function to validate path elements to check out
  1729. symlink_fn: Function to use for creating symlinks
  1730. force_remove_untracked: If True, remove files that exist in working
  1731. directory but not in target tree, even if old_tree_id is None
  1732. blob_normalizer: An optional BlobNormalizer to use for converting line
  1733. endings when writing blobs to the working directory.
  1734. tree_encoding: Encoding used for tree paths (default: utf-8)
  1735. allow_overwrite_modified: If False, raise an error when attempting to
  1736. overwrite files that have been modified compared to old_tree_id
  1737. """
  1738. if validate_path_element is None:
  1739. validate_path_element = validate_path_element_default
  1740. from .diff_tree import (
  1741. CHANGE_ADD,
  1742. CHANGE_COPY,
  1743. CHANGE_DELETE,
  1744. CHANGE_MODIFY,
  1745. CHANGE_RENAME,
  1746. CHANGE_UNCHANGED,
  1747. )
  1748. repo_path = repo.path if isinstance(repo.path, bytes) else repo.path.encode()
  1749. index = repo.open_index()
  1750. # Convert iterator to list since we need multiple passes
  1751. changes = list(change_iterator)
  1752. # Transform case-only renames on case-insensitive filesystems
  1753. import platform
  1754. default_ignore_case = platform.system() in ("Windows", "Darwin")
  1755. config = repo.get_config()
  1756. ignore_case = config.get_boolean((b"core",), b"ignorecase", default_ignore_case)
  1757. if ignore_case:
  1758. config = repo.get_config()
  1759. changes = detect_case_only_renames(changes, config)
  1760. # Check for path conflicts where files need to become directories
  1761. paths_becoming_dirs = set()
  1762. for change in changes:
  1763. if change.type in (CHANGE_ADD, CHANGE_MODIFY, CHANGE_RENAME, CHANGE_COPY):
  1764. path = change.new.path
  1765. if b"/" in path: # This is a file inside a directory
  1766. # Check if any parent path exists as a file in the old tree or changes
  1767. parts = path.split(b"/")
  1768. for i in range(1, len(parts)):
  1769. parent = b"/".join(parts[:i])
  1770. # See if this parent path is being deleted (was a file, becoming a dir)
  1771. for other_change in changes:
  1772. if (
  1773. other_change.type == CHANGE_DELETE
  1774. and other_change.old
  1775. and other_change.old.path == parent
  1776. ):
  1777. paths_becoming_dirs.add(parent)
  1778. # Check if any path that needs to become a directory has been modified
  1779. for path in paths_becoming_dirs:
  1780. full_path = _tree_to_fs_path(repo_path, path, tree_encoding)
  1781. try:
  1782. current_stat = os.lstat(full_path)
  1783. except FileNotFoundError:
  1784. continue # File doesn't exist, nothing to check
  1785. except OSError as e:
  1786. raise OSError(
  1787. f"Cannot access {path.decode('utf-8', errors='replace')}: {e}"
  1788. ) from e
  1789. if stat.S_ISREG(current_stat.st_mode):
  1790. # Find the old entry for this path
  1791. old_change = None
  1792. for change in changes:
  1793. if (
  1794. change.type == CHANGE_DELETE
  1795. and change.old
  1796. and change.old.path == path
  1797. ):
  1798. old_change = change
  1799. break
  1800. if old_change:
  1801. # Check if file has been modified
  1802. file_matches = _check_file_matches(
  1803. repo.object_store,
  1804. full_path,
  1805. old_change.old.sha,
  1806. old_change.old.mode,
  1807. current_stat,
  1808. honor_filemode,
  1809. blob_normalizer,
  1810. path,
  1811. )
  1812. if not file_matches:
  1813. raise OSError(
  1814. f"Cannot replace modified file with directory: {path!r}"
  1815. )
  1816. # Check for uncommitted modifications before making any changes
  1817. if not allow_overwrite_modified and old_tree_id:
  1818. for change in changes:
  1819. # Only check files that are being modified or deleted
  1820. if change.type in (CHANGE_MODIFY, CHANGE_DELETE) and change.old:
  1821. path = change.old.path
  1822. if path.startswith(b".git") or not validate_path(
  1823. path, validate_path_element
  1824. ):
  1825. continue
  1826. full_path = _tree_to_fs_path(repo_path, path, tree_encoding)
  1827. try:
  1828. current_stat = os.lstat(full_path)
  1829. except FileNotFoundError:
  1830. continue # File doesn't exist, nothing to check
  1831. except OSError as e:
  1832. raise OSError(
  1833. f"Cannot access {path.decode('utf-8', errors='replace')}: {e}"
  1834. ) from e
  1835. if stat.S_ISREG(current_stat.st_mode):
  1836. # Check if working tree file differs from old tree
  1837. file_matches = _check_file_matches(
  1838. repo.object_store,
  1839. full_path,
  1840. change.old.sha,
  1841. change.old.mode,
  1842. current_stat,
  1843. honor_filemode,
  1844. blob_normalizer,
  1845. path,
  1846. )
  1847. if not file_matches:
  1848. from .errors import WorkingTreeModifiedError
  1849. raise WorkingTreeModifiedError(
  1850. f"Your local changes to '{path.decode('utf-8', errors='replace')}' "
  1851. f"would be overwritten by checkout. "
  1852. f"Please commit your changes or stash them before you switch branches."
  1853. )
  1854. # Apply the changes
  1855. for change in changes:
  1856. if change.type in (CHANGE_DELETE, CHANGE_RENAME):
  1857. # Remove file/directory
  1858. path = change.old.path
  1859. if path.startswith(b".git") or not validate_path(
  1860. path, validate_path_element
  1861. ):
  1862. continue
  1863. full_path = _tree_to_fs_path(repo_path, path, tree_encoding)
  1864. try:
  1865. delete_stat: Optional[os.stat_result] = os.lstat(full_path)
  1866. except FileNotFoundError:
  1867. delete_stat = None
  1868. except OSError as e:
  1869. raise OSError(
  1870. f"Cannot access {path.decode('utf-8', errors='replace')}: {e}"
  1871. ) from e
  1872. _transition_to_absent(repo, path, full_path, delete_stat, index)
  1873. if change.type in (
  1874. CHANGE_ADD,
  1875. CHANGE_MODIFY,
  1876. CHANGE_UNCHANGED,
  1877. CHANGE_COPY,
  1878. CHANGE_RENAME,
  1879. ):
  1880. # Add or modify file
  1881. path = change.new.path
  1882. if path.startswith(b".git") or not validate_path(
  1883. path, validate_path_element
  1884. ):
  1885. continue
  1886. full_path = _tree_to_fs_path(repo_path, path, tree_encoding)
  1887. try:
  1888. modify_stat: Optional[os.stat_result] = os.lstat(full_path)
  1889. except FileNotFoundError:
  1890. modify_stat = None
  1891. except OSError as e:
  1892. raise OSError(
  1893. f"Cannot access {path.decode('utf-8', errors='replace')}: {e}"
  1894. ) from e
  1895. if S_ISGITLINK(change.new.mode):
  1896. _transition_to_submodule(
  1897. repo, path, full_path, modify_stat, change.new, index
  1898. )
  1899. else:
  1900. _transition_to_file(
  1901. repo.object_store,
  1902. path,
  1903. full_path,
  1904. modify_stat,
  1905. change.new,
  1906. index,
  1907. honor_filemode,
  1908. symlink_fn,
  1909. blob_normalizer,
  1910. tree_encoding,
  1911. )
  1912. index.write()
  1913. def get_unstaged_changes(
  1914. index: Index,
  1915. root_path: Union[str, bytes],
  1916. filter_blob_callback: Optional[Callable] = None,
  1917. ) -> Generator[bytes, None, None]:
  1918. """Walk through an index and check for differences against working tree.
  1919. Args:
  1920. index: index to check
  1921. root_path: path in which to find files
  1922. Returns: iterator over paths with unstaged changes
  1923. """
  1924. # For each entry in the index check the sha1 & ensure not staged
  1925. if not isinstance(root_path, bytes):
  1926. root_path = os.fsencode(root_path)
  1927. for tree_path, entry in index.iteritems():
  1928. full_path = _tree_to_fs_path(root_path, tree_path)
  1929. if isinstance(entry, ConflictedIndexEntry):
  1930. # Conflicted files are always unstaged
  1931. yield tree_path
  1932. continue
  1933. try:
  1934. st = os.lstat(full_path)
  1935. if stat.S_ISDIR(st.st_mode):
  1936. if _has_directory_changed(tree_path, entry):
  1937. yield tree_path
  1938. continue
  1939. if not stat.S_ISREG(st.st_mode) and not stat.S_ISLNK(st.st_mode):
  1940. continue
  1941. blob = blob_from_path_and_stat(full_path, st)
  1942. if filter_blob_callback is not None:
  1943. blob = filter_blob_callback(blob, tree_path)
  1944. except FileNotFoundError:
  1945. # The file was removed, so we assume that counts as
  1946. # different from whatever file used to exist.
  1947. yield tree_path
  1948. else:
  1949. if blob.id != entry.sha:
  1950. yield tree_path
  1951. def _tree_to_fs_path(
  1952. root_path: bytes, tree_path: bytes, tree_encoding: str = "utf-8"
  1953. ) -> bytes:
  1954. """Convert a git tree path to a file system path.
  1955. Args:
  1956. root_path: Root filesystem path
  1957. tree_path: Git tree path as bytes (encoded with tree_encoding)
  1958. tree_encoding: Encoding used for tree paths (default: utf-8)
  1959. Returns: File system path.
  1960. """
  1961. assert isinstance(tree_path, bytes)
  1962. if os_sep_bytes != b"/":
  1963. sep_corrected_path = tree_path.replace(b"/", os_sep_bytes)
  1964. else:
  1965. sep_corrected_path = tree_path
  1966. # On Windows, we need to handle tree path encoding properly
  1967. if sys.platform == "win32":
  1968. # Decode from tree encoding, then re-encode for filesystem
  1969. try:
  1970. tree_path_str = sep_corrected_path.decode(tree_encoding)
  1971. sep_corrected_path = os.fsencode(tree_path_str)
  1972. except UnicodeDecodeError:
  1973. # If decoding fails, use the original bytes
  1974. pass
  1975. return os.path.join(root_path, sep_corrected_path)
  1976. def _fs_to_tree_path(fs_path: Union[str, bytes], tree_encoding: str = "utf-8") -> bytes:
  1977. """Convert a file system path to a git tree path.
  1978. Args:
  1979. fs_path: File system path.
  1980. tree_encoding: Encoding to use for tree paths (default: utf-8)
  1981. Returns: Git tree path as bytes (encoded with tree_encoding)
  1982. """
  1983. if not isinstance(fs_path, bytes):
  1984. fs_path_bytes = os.fsencode(fs_path)
  1985. else:
  1986. fs_path_bytes = fs_path
  1987. # On Windows, we need to ensure tree paths are properly encoded
  1988. if sys.platform == "win32":
  1989. try:
  1990. # Decode from filesystem encoding, then re-encode with tree encoding
  1991. fs_path_str = os.fsdecode(fs_path_bytes)
  1992. fs_path_bytes = fs_path_str.encode(tree_encoding)
  1993. except UnicodeDecodeError:
  1994. # If filesystem decoding fails, use the original bytes
  1995. pass
  1996. if os_sep_bytes != b"/":
  1997. tree_path = fs_path_bytes.replace(os_sep_bytes, b"/")
  1998. else:
  1999. tree_path = fs_path_bytes
  2000. return tree_path
  2001. def index_entry_from_directory(st: os.stat_result, path: bytes) -> Optional[IndexEntry]:
  2002. if os.path.exists(os.path.join(path, b".git")):
  2003. head = read_submodule_head(path)
  2004. if head is None:
  2005. return None
  2006. return index_entry_from_stat(st, head, mode=S_IFGITLINK)
  2007. return None
  2008. def index_entry_from_path(
  2009. path: bytes, object_store: Optional[ObjectContainer] = None
  2010. ) -> Optional[IndexEntry]:
  2011. """Create an index from a filesystem path.
  2012. This returns an index value for files, symlinks
  2013. and tree references. for directories and
  2014. non-existent files it returns None
  2015. Args:
  2016. path: Path to create an index entry for
  2017. object_store: Optional object store to
  2018. save new blobs in
  2019. Returns: An index entry; None for directories
  2020. """
  2021. assert isinstance(path, bytes)
  2022. st = os.lstat(path)
  2023. if stat.S_ISDIR(st.st_mode):
  2024. return index_entry_from_directory(st, path)
  2025. if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode):
  2026. blob = blob_from_path_and_stat(path, st)
  2027. if object_store is not None:
  2028. object_store.add_object(blob)
  2029. return index_entry_from_stat(st, blob.id)
  2030. return None
  2031. def iter_fresh_entries(
  2032. paths: Iterable[bytes],
  2033. root_path: bytes,
  2034. object_store: Optional[ObjectContainer] = None,
  2035. ) -> Iterator[tuple[bytes, Optional[IndexEntry]]]:
  2036. """Iterate over current versions of index entries on disk.
  2037. Args:
  2038. paths: Paths to iterate over
  2039. root_path: Root path to access from
  2040. object_store: Optional store to save new blobs in
  2041. Returns: Iterator over path, index_entry
  2042. """
  2043. for path in paths:
  2044. p = _tree_to_fs_path(root_path, path)
  2045. try:
  2046. entry = index_entry_from_path(p, object_store=object_store)
  2047. except (FileNotFoundError, IsADirectoryError):
  2048. entry = None
  2049. yield path, entry
  2050. def iter_fresh_objects(
  2051. paths: Iterable[bytes],
  2052. root_path: bytes,
  2053. include_deleted: bool = False,
  2054. object_store: Optional[ObjectContainer] = None,
  2055. ) -> Iterator[tuple[bytes, Optional[bytes], Optional[int]]]:
  2056. """Iterate over versions of objects on disk referenced by index.
  2057. Args:
  2058. root_path: Root path to access from
  2059. include_deleted: Include deleted entries with sha and
  2060. mode set to None
  2061. object_store: Optional object store to report new items to
  2062. Returns: Iterator over path, sha, mode
  2063. """
  2064. for path, entry in iter_fresh_entries(paths, root_path, object_store=object_store):
  2065. if entry is None:
  2066. if include_deleted:
  2067. yield path, None, None
  2068. else:
  2069. yield path, entry.sha, cleanup_mode(entry.mode)
  2070. def refresh_index(index: Index, root_path: bytes) -> None:
  2071. """Refresh the contents of an index.
  2072. This is the equivalent to running 'git commit -a'.
  2073. Args:
  2074. index: Index to update
  2075. root_path: Root filesystem path
  2076. """
  2077. for path, entry in iter_fresh_entries(index, root_path):
  2078. if entry:
  2079. index[path] = entry
  2080. class locked_index:
  2081. """Lock the index while making modifications.
  2082. Works as a context manager.
  2083. """
  2084. _file: "_GitFile"
  2085. def __init__(self, path: Union[bytes, str]) -> None:
  2086. self._path = path
  2087. def __enter__(self) -> Index:
  2088. f = GitFile(self._path, "wb")
  2089. assert isinstance(f, _GitFile) # GitFile in write mode always returns _GitFile
  2090. self._file = f
  2091. self._index = Index(self._path)
  2092. return self._index
  2093. def __exit__(
  2094. self,
  2095. exc_type: Optional[type],
  2096. exc_value: Optional[BaseException],
  2097. traceback: Optional[types.TracebackType],
  2098. ) -> None:
  2099. if exc_type is not None:
  2100. self._file.abort()
  2101. return
  2102. try:
  2103. from typing import BinaryIO, cast
  2104. f = SHA1Writer(cast(BinaryIO, self._file))
  2105. write_index_dict(cast(BinaryIO, f), self._index._byname)
  2106. except BaseException:
  2107. self._file.abort()
  2108. else:
  2109. f.close()