index.py 99 KB

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