index.py 87 KB

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