index.py 97 KB

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