index.py 97 KB

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