index.py 84 KB

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