test_index.py 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002
  1. # test_index.py -- Tests for the git index
  2. # Copyright (C) 2008-2009 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. """Tests for the index."""
  22. import os
  23. import shutil
  24. import stat
  25. import struct
  26. import sys
  27. import tempfile
  28. from io import BytesIO
  29. from dulwich.config import ConfigDict
  30. from dulwich.diff_tree import (
  31. CHANGE_ADD,
  32. CHANGE_COPY,
  33. CHANGE_DELETE,
  34. CHANGE_MODIFY,
  35. CHANGE_RENAME,
  36. TreeChange,
  37. tree_changes,
  38. )
  39. from dulwich.index import (
  40. Index,
  41. IndexEntry,
  42. SerializedIndexEntry,
  43. _compress_path,
  44. _decode_varint,
  45. _decompress_path,
  46. _encode_varint,
  47. _fs_to_tree_path,
  48. _tree_to_fs_path,
  49. build_index_from_tree,
  50. cleanup_mode,
  51. commit_tree,
  52. detect_case_only_renames,
  53. get_unstaged_changes,
  54. index_entry_from_directory,
  55. index_entry_from_path,
  56. index_entry_from_stat,
  57. iter_fresh_entries,
  58. read_index,
  59. read_index_dict,
  60. update_working_tree,
  61. validate_path_element_default,
  62. validate_path_element_hfs,
  63. validate_path_element_ntfs,
  64. write_cache_time,
  65. write_index,
  66. write_index_dict,
  67. )
  68. from dulwich.object_store import MemoryObjectStore
  69. from dulwich.objects import S_IFGITLINK, Blob, Commit, Tree, TreeEntry
  70. from dulwich.repo import Repo
  71. from . import TestCase, skipIf
  72. def can_symlink() -> bool:
  73. """Return whether running process can create symlinks."""
  74. if sys.platform != "win32":
  75. # Platforms other than Windows should allow symlinks without issues.
  76. return True
  77. test_source = tempfile.mkdtemp()
  78. test_target = test_source + "can_symlink"
  79. try:
  80. os.symlink(test_source, test_target)
  81. except (NotImplementedError, OSError):
  82. return False
  83. return True
  84. class IndexTestCase(TestCase):
  85. datadir = os.path.join(os.path.dirname(__file__), "../testdata/indexes")
  86. def get_simple_index(self, name):
  87. return Index(os.path.join(self.datadir, name))
  88. class SimpleIndexTestCase(IndexTestCase):
  89. def test_len(self) -> None:
  90. self.assertEqual(1, len(self.get_simple_index("index")))
  91. def test_iter(self) -> None:
  92. self.assertEqual([b"bla"], list(self.get_simple_index("index")))
  93. def test_iter_skip_hash(self) -> None:
  94. self.assertEqual([b"bla"], list(self.get_simple_index("index_skip_hash")))
  95. def test_iterobjects(self) -> None:
  96. self.assertEqual(
  97. [(b"bla", b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", 33188)],
  98. list(self.get_simple_index("index").iterobjects()),
  99. )
  100. def test_getitem(self) -> None:
  101. self.assertEqual(
  102. IndexEntry(
  103. (1230680220, 0),
  104. (1230680220, 0),
  105. 2050,
  106. 3761020,
  107. 33188,
  108. 1000,
  109. 1000,
  110. 0,
  111. b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391",
  112. 0,
  113. 0,
  114. ),
  115. self.get_simple_index("index")[b"bla"],
  116. )
  117. def test_empty(self) -> None:
  118. i = self.get_simple_index("notanindex")
  119. self.assertEqual(0, len(i))
  120. self.assertFalse(os.path.exists(i._filename))
  121. def test_against_empty_tree(self) -> None:
  122. i = self.get_simple_index("index")
  123. changes = list(i.changes_from_tree(MemoryObjectStore(), None))
  124. self.assertEqual(1, len(changes))
  125. (oldname, newname), (oldmode, newmode), (oldsha, newsha) = changes[0]
  126. self.assertEqual(b"bla", newname)
  127. self.assertEqual(b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", newsha)
  128. def test_index_pathlib(self) -> None:
  129. import tempfile
  130. from pathlib import Path
  131. # Create a temporary index file
  132. with tempfile.NamedTemporaryFile(suffix=".index", delete=False) as f:
  133. temp_path = f.name
  134. self.addCleanup(os.unlink, temp_path)
  135. # Test creating Index with pathlib.Path
  136. path_obj = Path(temp_path)
  137. index = Index(path_obj, read=False)
  138. self.assertEqual(str(path_obj), index.path)
  139. # Add an entry and write
  140. index[b"test"] = IndexEntry(
  141. ctime=(0, 0),
  142. mtime=(0, 0),
  143. dev=0,
  144. ino=0,
  145. mode=33188,
  146. uid=0,
  147. gid=0,
  148. size=0,
  149. sha=b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391",
  150. )
  151. index.write()
  152. # Read it back with pathlib.Path
  153. index2 = Index(path_obj)
  154. self.assertIn(b"test", index2)
  155. class SimpleIndexWriterTestCase(IndexTestCase):
  156. def setUp(self) -> None:
  157. IndexTestCase.setUp(self)
  158. self.tempdir = tempfile.mkdtemp()
  159. def tearDown(self) -> None:
  160. IndexTestCase.tearDown(self)
  161. shutil.rmtree(self.tempdir)
  162. def test_simple_write(self) -> None:
  163. entries = [
  164. (
  165. SerializedIndexEntry(
  166. b"barbla",
  167. (1230680220, 0),
  168. (1230680220, 0),
  169. 2050,
  170. 3761020,
  171. 33188,
  172. 1000,
  173. 1000,
  174. 0,
  175. b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391",
  176. 0,
  177. 0,
  178. )
  179. )
  180. ]
  181. filename = os.path.join(self.tempdir, "test-simple-write-index")
  182. with open(filename, "wb+") as x:
  183. write_index(x, entries)
  184. with open(filename, "rb") as x:
  185. self.assertEqual(entries, list(read_index(x)))
  186. class ReadIndexDictTests(IndexTestCase):
  187. def setUp(self) -> None:
  188. IndexTestCase.setUp(self)
  189. self.tempdir = tempfile.mkdtemp()
  190. def tearDown(self) -> None:
  191. IndexTestCase.tearDown(self)
  192. shutil.rmtree(self.tempdir)
  193. def test_simple_write(self) -> None:
  194. entries = {
  195. b"barbla": IndexEntry(
  196. (1230680220, 0),
  197. (1230680220, 0),
  198. 2050,
  199. 3761020,
  200. 33188,
  201. 1000,
  202. 1000,
  203. 0,
  204. b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391",
  205. 0,
  206. 0,
  207. )
  208. }
  209. filename = os.path.join(self.tempdir, "test-simple-write-index")
  210. with open(filename, "wb+") as x:
  211. write_index_dict(x, entries)
  212. with open(filename, "rb") as x:
  213. self.assertEqual(entries, read_index_dict(x))
  214. class CommitTreeTests(TestCase):
  215. def setUp(self) -> None:
  216. super().setUp()
  217. self.store = MemoryObjectStore()
  218. def test_single_blob(self) -> None:
  219. blob = Blob()
  220. blob.data = b"foo"
  221. self.store.add_object(blob)
  222. blobs = [(b"bla", blob.id, stat.S_IFREG)]
  223. rootid = commit_tree(self.store, blobs)
  224. self.assertEqual(rootid, b"1a1e80437220f9312e855c37ac4398b68e5c1d50")
  225. self.assertEqual((stat.S_IFREG, blob.id), self.store[rootid][b"bla"])
  226. self.assertEqual({rootid, blob.id}, set(self.store._data.keys()))
  227. def test_nested(self) -> None:
  228. blob = Blob()
  229. blob.data = b"foo"
  230. self.store.add_object(blob)
  231. blobs = [(b"bla/bar", blob.id, stat.S_IFREG)]
  232. rootid = commit_tree(self.store, blobs)
  233. self.assertEqual(rootid, b"d92b959b216ad0d044671981196781b3258fa537")
  234. dirid = self.store[rootid][b"bla"][1]
  235. self.assertEqual(dirid, b"c1a1deb9788150829579a8b4efa6311e7b638650")
  236. self.assertEqual((stat.S_IFDIR, dirid), self.store[rootid][b"bla"])
  237. self.assertEqual((stat.S_IFREG, blob.id), self.store[dirid][b"bar"])
  238. self.assertEqual({rootid, dirid, blob.id}, set(self.store._data.keys()))
  239. class CleanupModeTests(TestCase):
  240. def assertModeEqual(self, expected, got) -> None:
  241. self.assertEqual(expected, got, f"{expected:o} != {got:o}")
  242. def test_file(self) -> None:
  243. self.assertModeEqual(0o100644, cleanup_mode(0o100000))
  244. def test_executable(self) -> None:
  245. self.assertModeEqual(0o100755, cleanup_mode(0o100711))
  246. self.assertModeEqual(0o100755, cleanup_mode(0o100700))
  247. def test_symlink(self) -> None:
  248. self.assertModeEqual(0o120000, cleanup_mode(0o120711))
  249. def test_dir(self) -> None:
  250. self.assertModeEqual(0o040000, cleanup_mode(0o40531))
  251. def test_submodule(self) -> None:
  252. self.assertModeEqual(0o160000, cleanup_mode(0o160744))
  253. class WriteCacheTimeTests(TestCase):
  254. def test_write_string(self) -> None:
  255. f = BytesIO()
  256. self.assertRaises(TypeError, write_cache_time, f, "foo")
  257. def test_write_int(self) -> None:
  258. f = BytesIO()
  259. write_cache_time(f, 434343)
  260. self.assertEqual(struct.pack(">LL", 434343, 0), f.getvalue())
  261. def test_write_tuple(self) -> None:
  262. f = BytesIO()
  263. write_cache_time(f, (434343, 21))
  264. self.assertEqual(struct.pack(">LL", 434343, 21), f.getvalue())
  265. def test_write_float(self) -> None:
  266. f = BytesIO()
  267. write_cache_time(f, 434343.000000021)
  268. self.assertEqual(struct.pack(">LL", 434343, 21), f.getvalue())
  269. class IndexEntryFromStatTests(TestCase):
  270. def test_simple(self) -> None:
  271. st = os.stat_result(
  272. (
  273. 16877,
  274. 131078,
  275. 64769,
  276. 154,
  277. 1000,
  278. 1000,
  279. 12288,
  280. 1323629595,
  281. 1324180496,
  282. 1324180496,
  283. )
  284. )
  285. entry = index_entry_from_stat(st, b"22" * 20)
  286. self.assertEqual(
  287. entry,
  288. IndexEntry(
  289. 1324180496,
  290. 1324180496,
  291. 64769,
  292. 131078,
  293. 16384,
  294. 1000,
  295. 1000,
  296. 12288,
  297. b"2222222222222222222222222222222222222222",
  298. 0,
  299. 0,
  300. ),
  301. )
  302. def test_override_mode(self) -> None:
  303. st = os.stat_result(
  304. (
  305. stat.S_IFREG + 0o644,
  306. 131078,
  307. 64769,
  308. 154,
  309. 1000,
  310. 1000,
  311. 12288,
  312. 1323629595,
  313. 1324180496,
  314. 1324180496,
  315. )
  316. )
  317. entry = index_entry_from_stat(st, b"22" * 20, mode=stat.S_IFREG + 0o755)
  318. self.assertEqual(
  319. entry,
  320. IndexEntry(
  321. 1324180496,
  322. 1324180496,
  323. 64769,
  324. 131078,
  325. 33261,
  326. 1000,
  327. 1000,
  328. 12288,
  329. b"2222222222222222222222222222222222222222",
  330. 0,
  331. 0,
  332. ),
  333. )
  334. class BuildIndexTests(TestCase):
  335. def assertReasonableIndexEntry(self, index_entry, mode, filesize, sha) -> None:
  336. self.assertEqual(index_entry.mode, mode) # mode
  337. self.assertEqual(index_entry.size, filesize) # filesize
  338. self.assertEqual(index_entry.sha, sha) # sha
  339. def assertFileContents(self, path, contents, symlink=False) -> None:
  340. if symlink:
  341. self.assertEqual(os.readlink(path), contents)
  342. else:
  343. with open(path, "rb") as f:
  344. self.assertEqual(f.read(), contents)
  345. def test_empty(self) -> None:
  346. repo_dir = tempfile.mkdtemp()
  347. self.addCleanup(shutil.rmtree, repo_dir)
  348. with Repo.init(repo_dir) as repo:
  349. tree = Tree()
  350. repo.object_store.add_object(tree)
  351. build_index_from_tree(
  352. repo.path, repo.index_path(), repo.object_store, tree.id
  353. )
  354. # Verify index entries
  355. index = repo.open_index()
  356. self.assertEqual(len(index), 0)
  357. # Verify no files
  358. self.assertEqual([".git"], os.listdir(repo.path))
  359. def test_git_dir(self) -> None:
  360. repo_dir = tempfile.mkdtemp()
  361. self.addCleanup(shutil.rmtree, repo_dir)
  362. with Repo.init(repo_dir) as repo:
  363. # Populate repo
  364. filea = Blob.from_string(b"file a")
  365. filee = Blob.from_string(b"d")
  366. tree = Tree()
  367. tree[b".git/a"] = (stat.S_IFREG | 0o644, filea.id)
  368. tree[b"c/e"] = (stat.S_IFREG | 0o644, filee.id)
  369. repo.object_store.add_objects([(o, None) for o in [filea, filee, tree]])
  370. build_index_from_tree(
  371. repo.path, repo.index_path(), repo.object_store, tree.id
  372. )
  373. # Verify index entries
  374. index = repo.open_index()
  375. self.assertEqual(len(index), 1)
  376. # filea
  377. apath = os.path.join(repo.path, ".git", "a")
  378. self.assertFalse(os.path.exists(apath))
  379. # filee
  380. epath = os.path.join(repo.path, "c", "e")
  381. self.assertTrue(os.path.exists(epath))
  382. self.assertReasonableIndexEntry(
  383. index[b"c/e"], stat.S_IFREG | 0o644, 1, filee.id
  384. )
  385. self.assertFileContents(epath, b"d")
  386. def test_nonempty(self) -> None:
  387. repo_dir = tempfile.mkdtemp()
  388. self.addCleanup(shutil.rmtree, repo_dir)
  389. with Repo.init(repo_dir) as repo:
  390. # Populate repo
  391. filea = Blob.from_string(b"file a")
  392. fileb = Blob.from_string(b"file b")
  393. filed = Blob.from_string(b"file d")
  394. tree = Tree()
  395. tree[b"a"] = (stat.S_IFREG | 0o644, filea.id)
  396. tree[b"b"] = (stat.S_IFREG | 0o644, fileb.id)
  397. tree[b"c/d"] = (stat.S_IFREG | 0o644, filed.id)
  398. repo.object_store.add_objects(
  399. [(o, None) for o in [filea, fileb, filed, tree]]
  400. )
  401. build_index_from_tree(
  402. repo.path, repo.index_path(), repo.object_store, tree.id
  403. )
  404. # Verify index entries
  405. index = repo.open_index()
  406. self.assertEqual(len(index), 3)
  407. # filea
  408. apath = os.path.join(repo.path, "a")
  409. self.assertTrue(os.path.exists(apath))
  410. self.assertReasonableIndexEntry(
  411. index[b"a"], stat.S_IFREG | 0o644, 6, filea.id
  412. )
  413. self.assertFileContents(apath, b"file a")
  414. # fileb
  415. bpath = os.path.join(repo.path, "b")
  416. self.assertTrue(os.path.exists(bpath))
  417. self.assertReasonableIndexEntry(
  418. index[b"b"], stat.S_IFREG | 0o644, 6, fileb.id
  419. )
  420. self.assertFileContents(bpath, b"file b")
  421. # filed
  422. dpath = os.path.join(repo.path, "c", "d")
  423. self.assertTrue(os.path.exists(dpath))
  424. self.assertReasonableIndexEntry(
  425. index[b"c/d"], stat.S_IFREG | 0o644, 6, filed.id
  426. )
  427. self.assertFileContents(dpath, b"file d")
  428. # Verify no extra files
  429. self.assertEqual([".git", "a", "b", "c"], sorted(os.listdir(repo.path)))
  430. self.assertEqual(["d"], sorted(os.listdir(os.path.join(repo.path, "c"))))
  431. @skipIf(not getattr(os, "sync", None), "Requires sync support")
  432. def test_norewrite(self) -> None:
  433. repo_dir = tempfile.mkdtemp()
  434. self.addCleanup(shutil.rmtree, repo_dir)
  435. with Repo.init(repo_dir) as repo:
  436. # Populate repo
  437. filea = Blob.from_string(b"file a")
  438. filea_path = os.path.join(repo_dir, "a")
  439. tree = Tree()
  440. tree[b"a"] = (stat.S_IFREG | 0o644, filea.id)
  441. repo.object_store.add_objects([(o, None) for o in [filea, tree]])
  442. # First Write
  443. build_index_from_tree(
  444. repo.path, repo.index_path(), repo.object_store, tree.id
  445. )
  446. # Use sync as metadata can be cached on some FS
  447. os.sync()
  448. mtime = os.stat(filea_path).st_mtime
  449. # Test Rewrite
  450. build_index_from_tree(
  451. repo.path, repo.index_path(), repo.object_store, tree.id
  452. )
  453. os.sync()
  454. self.assertEqual(mtime, os.stat(filea_path).st_mtime)
  455. # Modify content
  456. with open(filea_path, "wb") as fh:
  457. fh.write(b"test a")
  458. os.sync()
  459. mtime = os.stat(filea_path).st_mtime
  460. # Test rewrite
  461. build_index_from_tree(
  462. repo.path, repo.index_path(), repo.object_store, tree.id
  463. )
  464. os.sync()
  465. with open(filea_path, "rb") as fh:
  466. self.assertEqual(b"file a", fh.read())
  467. @skipIf(not can_symlink(), "Requires symlink support")
  468. def test_symlink(self) -> None:
  469. repo_dir = tempfile.mkdtemp()
  470. self.addCleanup(shutil.rmtree, repo_dir)
  471. with Repo.init(repo_dir) as repo:
  472. # Populate repo
  473. filed = Blob.from_string(b"file d")
  474. filee = Blob.from_string(b"d")
  475. tree = Tree()
  476. tree[b"c/d"] = (stat.S_IFREG | 0o644, filed.id)
  477. tree[b"c/e"] = (stat.S_IFLNK, filee.id) # symlink
  478. repo.object_store.add_objects([(o, None) for o in [filed, filee, tree]])
  479. build_index_from_tree(
  480. repo.path, repo.index_path(), repo.object_store, tree.id
  481. )
  482. # Verify index entries
  483. index = repo.open_index()
  484. # symlink to d
  485. epath = os.path.join(repo.path, "c", "e")
  486. self.assertTrue(os.path.exists(epath))
  487. self.assertReasonableIndexEntry(
  488. index[b"c/e"],
  489. stat.S_IFLNK,
  490. 0 if sys.platform == "win32" else 1,
  491. filee.id,
  492. )
  493. self.assertFileContents(epath, "d", symlink=True)
  494. def test_no_decode_encode(self) -> None:
  495. repo_dir = tempfile.mkdtemp()
  496. repo_dir_bytes = os.fsencode(repo_dir)
  497. self.addCleanup(shutil.rmtree, repo_dir)
  498. with Repo.init(repo_dir) as repo:
  499. # Populate repo
  500. file = Blob.from_string(b"foo")
  501. tree = Tree()
  502. latin1_name = "À".encode("latin1")
  503. try:
  504. latin1_path = os.path.join(repo_dir_bytes, latin1_name)
  505. except UnicodeDecodeError:
  506. self.skipTest("can not decode as latin1")
  507. utf8_name = "À".encode()
  508. utf8_path = os.path.join(repo_dir_bytes, utf8_name)
  509. tree[latin1_name] = (stat.S_IFREG | 0o644, file.id)
  510. tree[utf8_name] = (stat.S_IFREG | 0o644, file.id)
  511. repo.object_store.add_objects([(o, None) for o in [file, tree]])
  512. try:
  513. build_index_from_tree(
  514. repo.path, repo.index_path(), repo.object_store, tree.id
  515. )
  516. except OSError as e:
  517. if e.errno == 92 and sys.platform == "darwin":
  518. # Our filename isn't supported by the platform :(
  519. self.skipTest(f"can not write filename {e.filename!r}")
  520. else:
  521. raise
  522. except UnicodeDecodeError:
  523. # This happens e.g. with python3.6 on Windows.
  524. # It implicitly decodes using utf8, which doesn't work.
  525. self.skipTest("can not implicitly convert as utf8")
  526. # Verify index entries
  527. index = repo.open_index()
  528. self.assertIn(latin1_name, index)
  529. self.assertIn(utf8_name, index)
  530. self.assertTrue(os.path.exists(latin1_path))
  531. self.assertTrue(os.path.exists(utf8_path))
  532. def test_windows_unicode_filename_encoding(self) -> None:
  533. """Test that Unicode filenames are handled correctly on Windows.
  534. This test verifies the fix for GitHub issue #203, where filenames
  535. containing Unicode characters like 'À' were incorrectly encoded/decoded
  536. on Windows, resulting in corruption like 'À' -> 'À'.
  537. """
  538. repo_dir = tempfile.mkdtemp()
  539. self.addCleanup(shutil.rmtree, repo_dir)
  540. with Repo.init(repo_dir) as repo:
  541. # Create a blob
  542. file_content = b"test file content"
  543. blob = Blob.from_string(file_content)
  544. # Create a tree with a Unicode filename
  545. tree = Tree()
  546. unicode_filename = "À" # This is the character from GitHub issue #203
  547. utf8_filename_bytes = unicode_filename.encode(
  548. "utf-8"
  549. ) # This is how it's stored in git trees
  550. tree[utf8_filename_bytes] = (stat.S_IFREG | 0o644, blob.id)
  551. repo.object_store.add_objects([(blob, None), (tree, None)])
  552. # Build index from tree (this is what happens during checkout/clone)
  553. try:
  554. build_index_from_tree(
  555. repo.path, repo.index_path(), repo.object_store, tree.id
  556. )
  557. except (OSError, UnicodeError) as e:
  558. if sys.platform == "win32" and "cannot" in str(e).lower():
  559. self.skipTest(f"Platform doesn't support filename: {e}")
  560. raise
  561. # Check that the file was created correctly
  562. expected_file_path = os.path.join(repo.path, unicode_filename)
  563. self.assertTrue(
  564. os.path.exists(expected_file_path),
  565. f"File should exist at {expected_file_path}",
  566. )
  567. # Verify the file content is correct
  568. with open(expected_file_path, "rb") as f:
  569. actual_content = f.read()
  570. self.assertEqual(actual_content, file_content)
  571. # Test the reverse: adding a Unicode filename to the index
  572. if sys.platform == "win32":
  573. # On Windows, test that _tree_to_fs_path and _fs_to_tree_path
  574. # handle UTF-8 encoded tree paths correctly
  575. from dulwich.index import _fs_to_tree_path, _tree_to_fs_path
  576. repo_path_bytes = os.fsencode(repo.path)
  577. # Test tree path to filesystem path conversion
  578. fs_path = _tree_to_fs_path(repo_path_bytes, utf8_filename_bytes)
  579. expected_fs_path = os.path.join(
  580. repo_path_bytes, os.fsencode(unicode_filename)
  581. )
  582. self.assertEqual(fs_path, expected_fs_path)
  583. # Test filesystem path to tree path conversion
  584. # _fs_to_tree_path expects relative paths, not absolute paths
  585. # Extract just the filename from the full path
  586. filename_only = os.path.basename(fs_path)
  587. reconstructed_tree_path = _fs_to_tree_path(
  588. filename_only, tree_encoding="utf-8"
  589. )
  590. self.assertEqual(reconstructed_tree_path, utf8_filename_bytes)
  591. def test_git_submodule(self) -> None:
  592. repo_dir = tempfile.mkdtemp()
  593. self.addCleanup(shutil.rmtree, repo_dir)
  594. with Repo.init(repo_dir) as repo:
  595. filea = Blob.from_string(b"file alalala")
  596. subtree = Tree()
  597. subtree[b"a"] = (stat.S_IFREG | 0o644, filea.id)
  598. c = Commit()
  599. c.tree = subtree.id
  600. c.committer = c.author = b"Somebody <somebody@example.com>"
  601. c.commit_time = c.author_time = 42342
  602. c.commit_timezone = c.author_timezone = 0
  603. c.parents = []
  604. c.message = b"Subcommit"
  605. tree = Tree()
  606. tree[b"c"] = (S_IFGITLINK, c.id)
  607. repo.object_store.add_objects([(o, None) for o in [tree]])
  608. build_index_from_tree(
  609. repo.path, repo.index_path(), repo.object_store, tree.id
  610. )
  611. # Verify index entries
  612. index = repo.open_index()
  613. self.assertEqual(len(index), 1)
  614. # filea
  615. apath = os.path.join(repo.path, "c/a")
  616. self.assertFalse(os.path.exists(apath))
  617. # dir c
  618. cpath = os.path.join(repo.path, "c")
  619. self.assertTrue(os.path.isdir(cpath))
  620. self.assertEqual(index[b"c"].mode, S_IFGITLINK) # mode
  621. self.assertEqual(index[b"c"].sha, c.id) # sha
  622. def test_git_submodule_exists(self) -> None:
  623. repo_dir = tempfile.mkdtemp()
  624. self.addCleanup(shutil.rmtree, repo_dir)
  625. with Repo.init(repo_dir) as repo:
  626. filea = Blob.from_string(b"file alalala")
  627. subtree = Tree()
  628. subtree[b"a"] = (stat.S_IFREG | 0o644, filea.id)
  629. c = Commit()
  630. c.tree = subtree.id
  631. c.committer = c.author = b"Somebody <somebody@example.com>"
  632. c.commit_time = c.author_time = 42342
  633. c.commit_timezone = c.author_timezone = 0
  634. c.parents = []
  635. c.message = b"Subcommit"
  636. tree = Tree()
  637. tree[b"c"] = (S_IFGITLINK, c.id)
  638. os.mkdir(os.path.join(repo_dir, "c"))
  639. repo.object_store.add_objects([(o, None) for o in [tree]])
  640. build_index_from_tree(
  641. repo.path, repo.index_path(), repo.object_store, tree.id
  642. )
  643. # Verify index entries
  644. index = repo.open_index()
  645. self.assertEqual(len(index), 1)
  646. # filea
  647. apath = os.path.join(repo.path, "c/a")
  648. self.assertFalse(os.path.exists(apath))
  649. # dir c
  650. cpath = os.path.join(repo.path, "c")
  651. self.assertTrue(os.path.isdir(cpath))
  652. self.assertEqual(index[b"c"].mode, S_IFGITLINK) # mode
  653. self.assertEqual(index[b"c"].sha, c.id) # sha
  654. def test_with_line_ending_normalization(self) -> None:
  655. """Test that build_index_from_tree applies line-ending normalization."""
  656. repo_dir = tempfile.mkdtemp()
  657. self.addCleanup(shutil.rmtree, repo_dir)
  658. from dulwich.line_ending import BlobNormalizer
  659. with Repo.init(repo_dir) as repo:
  660. # Set up autocrlf config
  661. config = repo.get_config()
  662. config.set((b"core",), b"autocrlf", b"true")
  663. config.write_to_path()
  664. # Create blob with LF line endings
  665. content_lf = b"line1\nline2\nline3\n"
  666. blob = Blob.from_string(content_lf)
  667. tree = Tree()
  668. tree[b"test.txt"] = (stat.S_IFREG | 0o644, blob.id)
  669. repo.object_store.add_objects([(blob, None), (tree, None)])
  670. # Create blob normalizer
  671. autocrlf = config.get((b"core",), b"autocrlf")
  672. blob_normalizer = BlobNormalizer(config, {}, autocrlf=autocrlf)
  673. # Build index with normalization
  674. build_index_from_tree(
  675. repo.path,
  676. repo.index_path(),
  677. repo.object_store,
  678. tree.id,
  679. blob_normalizer=blob_normalizer,
  680. )
  681. # On Windows with autocrlf=true, file should have CRLF line endings
  682. test_file = os.path.join(repo.path, "test.txt")
  683. with open(test_file, "rb") as f:
  684. content = f.read()
  685. # autocrlf=true means LF -> CRLF on checkout (on all platforms for testing)
  686. expected_content = b"line1\r\nline2\r\nline3\r\n"
  687. self.assertEqual(content, expected_content)
  688. class GetUnstagedChangesTests(TestCase):
  689. def test_get_unstaged_changes(self) -> None:
  690. """Unit test for get_unstaged_changes."""
  691. repo_dir = tempfile.mkdtemp()
  692. self.addCleanup(shutil.rmtree, repo_dir)
  693. with Repo.init(repo_dir) as repo:
  694. # Commit a dummy file then modify it
  695. foo1_fullpath = os.path.join(repo_dir, "foo1")
  696. with open(foo1_fullpath, "wb") as f:
  697. f.write(b"origstuff")
  698. foo2_fullpath = os.path.join(repo_dir, "foo2")
  699. with open(foo2_fullpath, "wb") as f:
  700. f.write(b"origstuff")
  701. repo.get_worktree().stage(["foo1", "foo2"])
  702. repo.get_worktree().commit(
  703. message=b"test status",
  704. committer=b"committer <email>",
  705. author=b"author <email>",
  706. )
  707. with open(foo1_fullpath, "wb") as f:
  708. f.write(b"newstuff")
  709. # modify access and modify time of path
  710. os.utime(foo1_fullpath, (0, 0))
  711. changes = get_unstaged_changes(repo.open_index(), repo_dir)
  712. self.assertEqual(list(changes), [b"foo1"])
  713. def test_get_unstaged_changes_with_preload(self) -> None:
  714. """Unit test for get_unstaged_changes with preload_index=True."""
  715. repo_dir = tempfile.mkdtemp()
  716. self.addCleanup(shutil.rmtree, repo_dir)
  717. with Repo.init(repo_dir) as repo:
  718. # Create multiple files to test parallel processing
  719. files = []
  720. for i in range(10):
  721. filename = f"foo{i}"
  722. fullpath = os.path.join(repo_dir, filename)
  723. with open(fullpath, "wb") as f:
  724. f.write(b"origstuff" + str(i).encode())
  725. files.append(filename)
  726. repo.stage(files)
  727. repo.do_commit(
  728. b"test status",
  729. author=b"author <email>",
  730. committer=b"committer <email>",
  731. )
  732. # Modify some files
  733. modified_files = [b"foo1", b"foo3", b"foo5", b"foo7"]
  734. for filename in modified_files:
  735. fullpath = os.path.join(repo_dir, filename.decode())
  736. with open(fullpath, "wb") as f:
  737. f.write(b"newstuff")
  738. os.utime(fullpath, (0, 0))
  739. # Test with preload_index=False (serial)
  740. changes_serial = list(
  741. get_unstaged_changes(repo.open_index(), repo_dir, preload_index=False)
  742. )
  743. changes_serial.sort()
  744. # Test with preload_index=True (parallel)
  745. changes_parallel = list(
  746. get_unstaged_changes(repo.open_index(), repo_dir, preload_index=True)
  747. )
  748. changes_parallel.sort()
  749. # Both should return the same results
  750. self.assertEqual(changes_serial, changes_parallel)
  751. self.assertEqual(changes_serial, sorted(modified_files))
  752. def test_get_unstaged_deleted_changes(self) -> None:
  753. """Unit test for get_unstaged_changes."""
  754. repo_dir = tempfile.mkdtemp()
  755. self.addCleanup(shutil.rmtree, repo_dir)
  756. with Repo.init(repo_dir) as repo:
  757. # Commit a dummy file then remove it
  758. foo1_fullpath = os.path.join(repo_dir, "foo1")
  759. with open(foo1_fullpath, "wb") as f:
  760. f.write(b"origstuff")
  761. repo.get_worktree().stage(["foo1"])
  762. repo.get_worktree().commit(
  763. message=b"test status",
  764. committer=b"committer <email>",
  765. author=b"author <email>",
  766. )
  767. os.unlink(foo1_fullpath)
  768. changes = get_unstaged_changes(repo.open_index(), repo_dir)
  769. self.assertEqual(list(changes), [b"foo1"])
  770. def test_get_unstaged_changes_removed_replaced_by_directory(self) -> None:
  771. """Unit test for get_unstaged_changes."""
  772. repo_dir = tempfile.mkdtemp()
  773. self.addCleanup(shutil.rmtree, repo_dir)
  774. with Repo.init(repo_dir) as repo:
  775. # Commit a dummy file then modify it
  776. foo1_fullpath = os.path.join(repo_dir, "foo1")
  777. with open(foo1_fullpath, "wb") as f:
  778. f.write(b"origstuff")
  779. repo.get_worktree().stage(["foo1"])
  780. repo.get_worktree().commit(
  781. message=b"test status",
  782. committer=b"committer <email>",
  783. author=b"author <email>",
  784. )
  785. os.remove(foo1_fullpath)
  786. os.mkdir(foo1_fullpath)
  787. changes = get_unstaged_changes(repo.open_index(), repo_dir)
  788. self.assertEqual(list(changes), [b"foo1"])
  789. @skipIf(not can_symlink(), "Requires symlink support")
  790. def test_get_unstaged_changes_removed_replaced_by_link(self) -> None:
  791. """Unit test for get_unstaged_changes."""
  792. repo_dir = tempfile.mkdtemp()
  793. self.addCleanup(shutil.rmtree, repo_dir)
  794. with Repo.init(repo_dir) as repo:
  795. # Commit a dummy file then modify it
  796. foo1_fullpath = os.path.join(repo_dir, "foo1")
  797. with open(foo1_fullpath, "wb") as f:
  798. f.write(b"origstuff")
  799. repo.get_worktree().stage(["foo1"])
  800. repo.get_worktree().commit(
  801. message=b"test status",
  802. committer=b"committer <email>",
  803. author=b"author <email>",
  804. )
  805. os.remove(foo1_fullpath)
  806. os.symlink(os.path.dirname(foo1_fullpath), foo1_fullpath)
  807. changes = get_unstaged_changes(repo.open_index(), repo_dir)
  808. self.assertEqual(list(changes), [b"foo1"])
  809. class TestValidatePathElement(TestCase):
  810. def test_default(self) -> None:
  811. self.assertTrue(validate_path_element_default(b"bla"))
  812. self.assertTrue(validate_path_element_default(b".bla"))
  813. self.assertFalse(validate_path_element_default(b".git"))
  814. self.assertFalse(validate_path_element_default(b".giT"))
  815. self.assertFalse(validate_path_element_default(b".."))
  816. self.assertTrue(validate_path_element_default(b"git~1"))
  817. def test_ntfs(self) -> None:
  818. self.assertTrue(validate_path_element_ntfs(b"bla"))
  819. self.assertTrue(validate_path_element_ntfs(b".bla"))
  820. self.assertFalse(validate_path_element_ntfs(b".git"))
  821. self.assertFalse(validate_path_element_ntfs(b".giT"))
  822. self.assertFalse(validate_path_element_ntfs(b".."))
  823. self.assertFalse(validate_path_element_ntfs(b"git~1"))
  824. def test_hfs(self) -> None:
  825. # Normal paths should pass
  826. self.assertTrue(validate_path_element_hfs(b"bla"))
  827. self.assertTrue(validate_path_element_hfs(b".bla"))
  828. # Basic .git variations should fail
  829. self.assertFalse(validate_path_element_hfs(b".git"))
  830. self.assertFalse(validate_path_element_hfs(b".giT"))
  831. self.assertFalse(validate_path_element_hfs(b".GIT"))
  832. self.assertFalse(validate_path_element_hfs(b".."))
  833. # git~1 should also fail on HFS+
  834. self.assertFalse(validate_path_element_hfs(b"git~1"))
  835. # Test HFS+ Unicode normalization attacks
  836. # .g\u200cit (zero-width non-joiner)
  837. self.assertFalse(validate_path_element_hfs(b".g\xe2\x80\x8cit"))
  838. # .gi\u200dt (zero-width joiner)
  839. self.assertFalse(validate_path_element_hfs(b".gi\xe2\x80\x8dt"))
  840. # Test other ignorable characters
  841. # .g\ufeffit (zero-width no-break space)
  842. self.assertFalse(validate_path_element_hfs(b".g\xef\xbb\xbfit"))
  843. # Valid Unicode that shouldn't be confused with .git
  844. self.assertTrue(validate_path_element_hfs(b".g\xc3\xaft")) # .gït
  845. self.assertTrue(validate_path_element_hfs(b"git")) # git without dot
  846. class TestTreeFSPathConversion(TestCase):
  847. def test_tree_to_fs_path(self) -> None:
  848. tree_path = "délwíçh/foo".encode()
  849. fs_path = _tree_to_fs_path(b"/prefix/path", tree_path)
  850. self.assertEqual(
  851. fs_path,
  852. os.fsencode(os.path.join("/prefix/path", "délwíçh", "foo")),
  853. )
  854. def test_tree_to_fs_path_windows_separator(self) -> None:
  855. tree_path = b"path/with/slash"
  856. original_sep = os.sep.encode("ascii")
  857. # Temporarily modify os_sep_bytes to test Windows path conversion
  858. # This simulates Windows behavior on all platforms for testing
  859. import dulwich.index
  860. dulwich.index.os_sep_bytes = b"\\"
  861. self.addCleanup(setattr, dulwich.index, "os_sep_bytes", original_sep)
  862. fs_path = _tree_to_fs_path(b"/prefix/path", tree_path)
  863. # The function should join the prefix path with the converted tree path
  864. # The expected behavior is that the path separators in the tree_path are
  865. # converted to the platform-specific separator (which we've set to backslash)
  866. expected_path = os.path.join(b"/prefix/path", b"path\\with\\slash")
  867. self.assertEqual(fs_path, expected_path)
  868. def test_fs_to_tree_path_str(self) -> None:
  869. fs_path = os.path.join(os.path.join("délwíçh", "foo"))
  870. tree_path = _fs_to_tree_path(fs_path)
  871. self.assertEqual(tree_path, "délwíçh/foo".encode())
  872. def test_fs_to_tree_path_bytes(self) -> None:
  873. fs_path = os.path.join(os.fsencode(os.path.join("délwíçh", "foo")))
  874. tree_path = _fs_to_tree_path(fs_path)
  875. self.assertEqual(tree_path, "délwíçh/foo".encode())
  876. def test_fs_to_tree_path_windows_separator(self) -> None:
  877. # Test conversion of Windows paths to tree paths
  878. fs_path = b"path\\with\\backslash"
  879. original_sep = os.sep.encode("ascii")
  880. # Temporarily modify os_sep_bytes to test Windows path conversion
  881. import dulwich.index
  882. dulwich.index.os_sep_bytes = b"\\"
  883. self.addCleanup(setattr, dulwich.index, "os_sep_bytes", original_sep)
  884. tree_path = _fs_to_tree_path(fs_path)
  885. self.assertEqual(tree_path, b"path/with/backslash")
  886. class TestIndexEntryFromPath(TestCase):
  887. def setUp(self):
  888. self.tempdir = tempfile.mkdtemp()
  889. self.addCleanup(shutil.rmtree, self.tempdir)
  890. def test_index_entry_from_path_file(self) -> None:
  891. """Test creating index entry from a regular file."""
  892. # Create a test file
  893. test_file = os.path.join(self.tempdir, "testfile")
  894. with open(test_file, "wb") as f:
  895. f.write(b"test content")
  896. # Get the index entry
  897. entry = index_entry_from_path(os.fsencode(test_file))
  898. # Verify the entry was created with the right mode
  899. self.assertIsNotNone(entry)
  900. self.assertEqual(cleanup_mode(os.stat(test_file).st_mode), entry.mode)
  901. @skipIf(not can_symlink(), "Requires symlink support")
  902. def test_index_entry_from_path_symlink(self) -> None:
  903. """Test creating index entry from a symlink."""
  904. # Create a target file
  905. target_file = os.path.join(self.tempdir, "target")
  906. with open(target_file, "wb") as f:
  907. f.write(b"target content")
  908. # Create a symlink
  909. link_file = os.path.join(self.tempdir, "symlink")
  910. os.symlink(target_file, link_file)
  911. # Get the index entry
  912. entry = index_entry_from_path(os.fsencode(link_file))
  913. # Verify the entry was created with the right mode
  914. self.assertIsNotNone(entry)
  915. self.assertEqual(cleanup_mode(os.lstat(link_file).st_mode), entry.mode)
  916. def test_index_entry_from_path_directory(self) -> None:
  917. """Test creating index entry from a directory (should return None)."""
  918. # Create a directory
  919. test_dir = os.path.join(self.tempdir, "testdir")
  920. os.mkdir(test_dir)
  921. # Get the index entry for a directory
  922. entry = index_entry_from_path(os.fsencode(test_dir))
  923. # Should return None for regular directories
  924. self.assertIsNone(entry)
  925. def test_index_entry_from_directory_regular(self) -> None:
  926. """Test index_entry_from_directory with a regular directory."""
  927. # Create a directory
  928. test_dir = os.path.join(self.tempdir, "testdir")
  929. os.mkdir(test_dir)
  930. # Get stat for the directory
  931. st = os.lstat(test_dir)
  932. # Get the index entry for a regular directory
  933. entry = index_entry_from_directory(st, os.fsencode(test_dir))
  934. # Should return None for regular directories
  935. self.assertIsNone(entry)
  936. def test_index_entry_from_directory_git_submodule(self) -> None:
  937. """Test index_entry_from_directory with a Git submodule."""
  938. # Create a git repository that will be a submodule
  939. sub_repo_dir = os.path.join(self.tempdir, "subrepo")
  940. os.mkdir(sub_repo_dir)
  941. # Create the .git directory to make it look like a git repo
  942. git_dir = os.path.join(sub_repo_dir, ".git")
  943. os.mkdir(git_dir)
  944. # Create HEAD file with a fake commit SHA
  945. head_sha = b"1234567890" * 4 # 40-char fake SHA
  946. with open(os.path.join(git_dir, "HEAD"), "wb") as f:
  947. f.write(head_sha)
  948. # Get stat for the submodule directory
  949. st = os.lstat(sub_repo_dir)
  950. # Get the index entry for a git submodule directory
  951. entry = index_entry_from_directory(st, os.fsencode(sub_repo_dir))
  952. # Since we don't have a proper git setup, this might still return None
  953. # This test just ensures the code path is executed
  954. if entry is not None:
  955. # If an entry is returned, it should have the gitlink mode
  956. self.assertEqual(entry.mode, S_IFGITLINK)
  957. def test_index_entry_from_path_with_object_store(self) -> None:
  958. """Test creating index entry with object store."""
  959. # Create a test file
  960. test_file = os.path.join(self.tempdir, "testfile")
  961. with open(test_file, "wb") as f:
  962. f.write(b"test content")
  963. # Create a memory object store
  964. object_store = MemoryObjectStore()
  965. # Get the index entry and add to object store
  966. entry = index_entry_from_path(os.fsencode(test_file), object_store)
  967. # Verify we can access the blob from the object store
  968. self.assertIsNotNone(entry)
  969. blob = object_store[entry.sha]
  970. self.assertEqual(b"test content", blob.data)
  971. def test_iter_fresh_entries(self) -> None:
  972. """Test iterating over fresh entries."""
  973. # Create some test files
  974. file1 = os.path.join(self.tempdir, "file1")
  975. with open(file1, "wb") as f:
  976. f.write(b"file1 content")
  977. file2 = os.path.join(self.tempdir, "file2")
  978. with open(file2, "wb") as f:
  979. f.write(b"file2 content")
  980. # Create a memory object store
  981. object_store = MemoryObjectStore()
  982. # Get fresh entries
  983. paths = [b"file1", b"file2", b"nonexistent"]
  984. entries = dict(
  985. iter_fresh_entries(paths, os.fsencode(self.tempdir), object_store)
  986. )
  987. # Verify both files got entries but nonexistent file is None
  988. self.assertIn(b"file1", entries)
  989. self.assertIn(b"file2", entries)
  990. self.assertIn(b"nonexistent", entries)
  991. self.assertIsNotNone(entries[b"file1"])
  992. self.assertIsNotNone(entries[b"file2"])
  993. self.assertIsNone(entries[b"nonexistent"])
  994. # Check that blobs were added to object store
  995. blob1 = object_store[entries[b"file1"].sha]
  996. self.assertEqual(b"file1 content", blob1.data)
  997. blob2 = object_store[entries[b"file2"].sha]
  998. self.assertEqual(b"file2 content", blob2.data)
  999. def test_read_submodule_head(self) -> None:
  1000. """Test reading the HEAD of a submodule."""
  1001. from dulwich.index import read_submodule_head
  1002. # Create a test repo that will be our "submodule"
  1003. sub_repo_dir = os.path.join(self.tempdir, "subrepo")
  1004. os.mkdir(sub_repo_dir)
  1005. submodule_repo = Repo.init(sub_repo_dir)
  1006. # Create a file and commit it to establish a HEAD
  1007. test_file = os.path.join(sub_repo_dir, "testfile")
  1008. with open(test_file, "wb") as f:
  1009. f.write(b"test content")
  1010. submodule_repo.get_worktree().stage(["testfile"])
  1011. commit_id = submodule_repo.get_worktree().commit(
  1012. message=b"Test commit for submodule",
  1013. )
  1014. # Test reading the HEAD
  1015. head_sha = read_submodule_head(sub_repo_dir)
  1016. self.assertEqual(commit_id, head_sha)
  1017. # Test with bytes path
  1018. head_sha_bytes = read_submodule_head(os.fsencode(sub_repo_dir))
  1019. self.assertEqual(commit_id, head_sha_bytes)
  1020. # Test with non-existent path
  1021. non_repo_dir = os.path.join(self.tempdir, "nonrepo")
  1022. os.mkdir(non_repo_dir)
  1023. self.assertIsNone(read_submodule_head(non_repo_dir))
  1024. # Test with path that doesn't have a .git directory
  1025. not_git_dir = os.path.join(self.tempdir, "notgit")
  1026. os.mkdir(not_git_dir)
  1027. self.assertIsNone(read_submodule_head(not_git_dir))
  1028. def test_has_directory_changed(self) -> None:
  1029. """Test checking if a directory has changed."""
  1030. from dulwich.index import IndexEntry, _has_directory_changed
  1031. # Setup mock IndexEntry
  1032. mock_entry = IndexEntry(
  1033. (1230680220, 0),
  1034. (1230680220, 0),
  1035. 2050,
  1036. 3761020,
  1037. 33188,
  1038. 1000,
  1039. 1000,
  1040. 0,
  1041. b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391",
  1042. 0,
  1043. 0,
  1044. )
  1045. # Test with a regular directory (not a submodule)
  1046. reg_dir = os.path.join(self.tempdir, "regular_dir")
  1047. os.mkdir(reg_dir)
  1048. # Should return True for regular directory
  1049. self.assertTrue(_has_directory_changed(os.fsencode(reg_dir), mock_entry))
  1050. # Create a git repository to test submodule scenarios
  1051. sub_repo_dir = os.path.join(self.tempdir, "subrepo")
  1052. os.mkdir(sub_repo_dir)
  1053. submodule_repo = Repo.init(sub_repo_dir)
  1054. # Create a file and commit it to establish a HEAD
  1055. test_file = os.path.join(sub_repo_dir, "testfile")
  1056. with open(test_file, "wb") as f:
  1057. f.write(b"test content")
  1058. submodule_repo.get_worktree().stage(["testfile"])
  1059. commit_id = submodule_repo.get_worktree().commit(
  1060. message=b"Test commit for submodule",
  1061. )
  1062. # Create an entry with the correct commit SHA
  1063. correct_entry = IndexEntry(
  1064. (1230680220, 0),
  1065. (1230680220, 0),
  1066. 2050,
  1067. 3761020,
  1068. 33188,
  1069. 1000,
  1070. 1000,
  1071. 0,
  1072. commit_id,
  1073. 0,
  1074. 0,
  1075. )
  1076. # Create an entry with an incorrect commit SHA
  1077. incorrect_entry = IndexEntry(
  1078. (1230680220, 0),
  1079. (1230680220, 0),
  1080. 2050,
  1081. 3761020,
  1082. 33188,
  1083. 1000,
  1084. 1000,
  1085. 0,
  1086. b"0000000000000000000000000000000000000000",
  1087. 0,
  1088. 0,
  1089. )
  1090. # Should return False for submodule with correct SHA
  1091. self.assertFalse(
  1092. _has_directory_changed(os.fsencode(sub_repo_dir), correct_entry)
  1093. )
  1094. # Should return True for submodule with incorrect SHA
  1095. self.assertTrue(
  1096. _has_directory_changed(os.fsencode(sub_repo_dir), incorrect_entry)
  1097. )
  1098. def test_get_unstaged_changes(self) -> None:
  1099. """Test detecting unstaged changes in a working tree."""
  1100. from dulwich.index import (
  1101. ConflictedIndexEntry,
  1102. Index,
  1103. IndexEntry,
  1104. get_unstaged_changes,
  1105. )
  1106. # Create a test repo
  1107. repo_dir = tempfile.mkdtemp()
  1108. self.addCleanup(shutil.rmtree, repo_dir)
  1109. # Create test index
  1110. index = Index(os.path.join(repo_dir, "index"))
  1111. # Create an actual hash of our test content
  1112. from dulwich.objects import Blob
  1113. test_blob = Blob()
  1114. test_blob.data = b"initial content"
  1115. # Create some test files with known contents
  1116. file1_path = os.path.join(repo_dir, "file1")
  1117. with open(file1_path, "wb") as f:
  1118. f.write(b"initial content")
  1119. file2_path = os.path.join(repo_dir, "file2")
  1120. with open(file2_path, "wb") as f:
  1121. f.write(b"initial content")
  1122. # Add them to index
  1123. entry1 = IndexEntry(
  1124. (1230680220, 0),
  1125. (1230680220, 0),
  1126. 2050,
  1127. 3761020,
  1128. 33188,
  1129. 1000,
  1130. 1000,
  1131. 0,
  1132. b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", # Not matching actual content
  1133. 0,
  1134. 0,
  1135. )
  1136. entry2 = IndexEntry(
  1137. (1230680220, 0),
  1138. (1230680220, 0),
  1139. 2050,
  1140. 3761020,
  1141. 33188,
  1142. 1000,
  1143. 1000,
  1144. 0,
  1145. test_blob.id, # Will be content's real hash
  1146. 0,
  1147. 0,
  1148. )
  1149. # Add a file that has a conflict
  1150. entry_conflict = ConflictedIndexEntry(b"conflict", {0: None, 1: None, 2: None})
  1151. index._byname = {
  1152. b"file1": entry1,
  1153. b"file2": entry2,
  1154. b"file3": IndexEntry(
  1155. (1230680220, 0),
  1156. (1230680220, 0),
  1157. 2050,
  1158. 3761020,
  1159. 33188,
  1160. 1000,
  1161. 1000,
  1162. 0,
  1163. b"0000000000000000000000000000000000000000",
  1164. 0,
  1165. 0,
  1166. ),
  1167. b"conflict": entry_conflict,
  1168. }
  1169. # Get unstaged changes
  1170. changes = list(get_unstaged_changes(index, repo_dir))
  1171. # File1 should be unstaged (content doesn't match hash)
  1172. # File3 doesn't exist (deleted)
  1173. # Conflict is always unstaged
  1174. self.assertEqual(sorted(changes), [b"conflict", b"file1", b"file3"])
  1175. # Create directory where there should be a file
  1176. os.mkdir(os.path.join(repo_dir, "file4"))
  1177. index._byname[b"file4"] = entry1
  1178. # Get unstaged changes again
  1179. changes = list(get_unstaged_changes(index, repo_dir))
  1180. # Now file4 should also be unstaged because it's a directory instead of a file
  1181. self.assertEqual(sorted(changes), [b"conflict", b"file1", b"file3", b"file4"])
  1182. # Create a custom blob filter function
  1183. def filter_blob_callback(blob, path):
  1184. # Modify blob to make it look changed
  1185. blob.data = b"modified " + blob.data
  1186. return blob
  1187. # Get unstaged changes with blob filter
  1188. changes = list(get_unstaged_changes(index, repo_dir, filter_blob_callback))
  1189. # Now both file1 and file2 should be unstaged due to the filter
  1190. self.assertEqual(
  1191. sorted(changes), [b"conflict", b"file1", b"file2", b"file3", b"file4"]
  1192. )
  1193. class TestManyFilesFeature(TestCase):
  1194. """Tests for the manyFiles feature (index version 4 and skipHash)."""
  1195. def setUp(self):
  1196. self.tempdir = tempfile.mkdtemp()
  1197. self.addCleanup(shutil.rmtree, self.tempdir)
  1198. def test_index_version_4_parsing(self):
  1199. """Test that index version 4 files can be parsed."""
  1200. index_path = os.path.join(self.tempdir, "index")
  1201. # Create an index with version 4
  1202. index = Index(index_path, read=False, version=4)
  1203. # Add some entries
  1204. entry = IndexEntry(
  1205. ctime=(1234567890, 0),
  1206. mtime=(1234567890, 0),
  1207. dev=1,
  1208. ino=1,
  1209. mode=0o100644,
  1210. uid=1000,
  1211. gid=1000,
  1212. size=5,
  1213. sha=b"0" * 40,
  1214. )
  1215. index[b"test.txt"] = entry
  1216. # Write and read back
  1217. index.write()
  1218. # Read the index back
  1219. index2 = Index(index_path)
  1220. self.assertEqual(index2._version, 4)
  1221. self.assertIn(b"test.txt", index2)
  1222. def test_skip_hash_feature(self):
  1223. """Test that skipHash feature works correctly."""
  1224. index_path = os.path.join(self.tempdir, "index")
  1225. # Create an index with skipHash enabled
  1226. index = Index(index_path, read=False, skip_hash=True)
  1227. # Add some entries
  1228. entry = IndexEntry(
  1229. ctime=(1234567890, 0),
  1230. mtime=(1234567890, 0),
  1231. dev=1,
  1232. ino=1,
  1233. mode=0o100644,
  1234. uid=1000,
  1235. gid=1000,
  1236. size=5,
  1237. sha=b"0" * 40,
  1238. )
  1239. index[b"test.txt"] = entry
  1240. # Write the index
  1241. index.write()
  1242. # Verify the file was written with zero hash
  1243. with open(index_path, "rb") as f:
  1244. f.seek(-20, 2) # Seek to last 20 bytes
  1245. trailing_hash = f.read(20)
  1246. self.assertEqual(trailing_hash, b"\x00" * 20)
  1247. # Verify we can still read it back
  1248. index2 = Index(index_path)
  1249. self.assertIn(b"test.txt", index2)
  1250. def test_version_4_no_padding(self):
  1251. """Test that version 4 entries have no padding."""
  1252. # Create entries with names that would show compression benefits
  1253. entries = [
  1254. SerializedIndexEntry(
  1255. name=b"src/main/java/com/example/Service.java",
  1256. ctime=(1234567890, 0),
  1257. mtime=(1234567890, 0),
  1258. dev=1,
  1259. ino=1,
  1260. mode=0o100644,
  1261. uid=1000,
  1262. gid=1000,
  1263. size=5,
  1264. sha=b"0" * 40,
  1265. flags=0,
  1266. extended_flags=0,
  1267. ),
  1268. SerializedIndexEntry(
  1269. name=b"src/main/java/com/example/Controller.java",
  1270. ctime=(1234567890, 0),
  1271. mtime=(1234567890, 0),
  1272. dev=1,
  1273. ino=2,
  1274. mode=0o100644,
  1275. uid=1000,
  1276. gid=1000,
  1277. size=5,
  1278. sha=b"1" * 40,
  1279. flags=0,
  1280. extended_flags=0,
  1281. ),
  1282. ]
  1283. # Test version 2 (with padding, full paths)
  1284. buf_v2 = BytesIO()
  1285. from dulwich.index import write_cache_entry
  1286. previous_path = b""
  1287. for entry in entries:
  1288. # Set proper flags for v2
  1289. entry_v2 = SerializedIndexEntry(
  1290. entry.name,
  1291. entry.ctime,
  1292. entry.mtime,
  1293. entry.dev,
  1294. entry.ino,
  1295. entry.mode,
  1296. entry.uid,
  1297. entry.gid,
  1298. entry.size,
  1299. entry.sha,
  1300. len(entry.name),
  1301. entry.extended_flags,
  1302. )
  1303. write_cache_entry(buf_v2, entry_v2, version=2, previous_path=previous_path)
  1304. previous_path = entry.name
  1305. v2_data = buf_v2.getvalue()
  1306. # Test version 4 (path compression, no padding)
  1307. buf_v4 = BytesIO()
  1308. previous_path = b""
  1309. for entry in entries:
  1310. write_cache_entry(buf_v4, entry, version=4, previous_path=previous_path)
  1311. previous_path = entry.name
  1312. v4_data = buf_v4.getvalue()
  1313. # Version 4 should be shorter due to compression and no padding
  1314. self.assertLess(len(v4_data), len(v2_data))
  1315. # Both should parse correctly
  1316. buf_v2.seek(0)
  1317. from dulwich.index import read_cache_entry
  1318. previous_path = b""
  1319. parsed_v2_entries = []
  1320. for _ in entries:
  1321. parsed = read_cache_entry(buf_v2, version=2, previous_path=previous_path)
  1322. parsed_v2_entries.append(parsed)
  1323. previous_path = parsed.name
  1324. buf_v4.seek(0)
  1325. previous_path = b""
  1326. parsed_v4_entries = []
  1327. for _ in entries:
  1328. parsed = read_cache_entry(buf_v4, version=4, previous_path=previous_path)
  1329. parsed_v4_entries.append(parsed)
  1330. previous_path = parsed.name
  1331. # Both should have the same paths
  1332. for v2_entry, v4_entry in zip(parsed_v2_entries, parsed_v4_entries):
  1333. self.assertEqual(v2_entry.name, v4_entry.name)
  1334. self.assertEqual(v2_entry.sha, v4_entry.sha)
  1335. class TestManyFilesRepoIntegration(TestCase):
  1336. """Tests for manyFiles feature integration with Repo."""
  1337. def setUp(self):
  1338. self.tempdir = tempfile.mkdtemp()
  1339. self.addCleanup(shutil.rmtree, self.tempdir)
  1340. def test_repo_with_manyfiles_config(self):
  1341. """Test that a repository with feature.manyFiles=true uses the right settings."""
  1342. # Create a new repository
  1343. repo = Repo.init(self.tempdir)
  1344. # Set feature.manyFiles=true in config
  1345. config = repo.get_config()
  1346. config.set(b"feature", b"manyFiles", b"true")
  1347. config.write_to_path()
  1348. # Open the index - should have skipHash enabled and version 4
  1349. index = repo.open_index()
  1350. self.assertTrue(index._skip_hash)
  1351. self.assertEqual(index._version, 4)
  1352. def test_repo_with_explicit_index_settings(self):
  1353. """Test that explicit index.version and index.skipHash work."""
  1354. # Create a new repository
  1355. repo = Repo.init(self.tempdir)
  1356. # Set explicit index settings
  1357. config = repo.get_config()
  1358. config.set(b"index", b"version", b"3")
  1359. config.set(b"index", b"skipHash", b"false")
  1360. config.write_to_path()
  1361. # Open the index - should respect explicit settings
  1362. index = repo.open_index()
  1363. self.assertFalse(index._skip_hash)
  1364. self.assertEqual(index._version, 3)
  1365. class TestPathPrefixCompression(TestCase):
  1366. """Tests for index version 4 path prefix compression."""
  1367. def setUp(self):
  1368. self.tempdir = tempfile.mkdtemp()
  1369. self.addCleanup(shutil.rmtree, self.tempdir)
  1370. def test_varint_encoding_decoding(self):
  1371. """Test variable-width integer encoding and decoding."""
  1372. test_values = [0, 1, 127, 128, 255, 256, 16383, 16384, 65535, 65536]
  1373. for value in test_values:
  1374. encoded = _encode_varint(value)
  1375. decoded, _ = _decode_varint(encoded, 0)
  1376. self.assertEqual(value, decoded, f"Failed for value {value}")
  1377. def test_path_compression_simple(self):
  1378. """Test simple path compression cases."""
  1379. # Test case 1: No common prefix
  1380. compressed = _compress_path(b"file1.txt", b"")
  1381. decompressed, _ = _decompress_path(compressed, 0, b"")
  1382. self.assertEqual(b"file1.txt", decompressed)
  1383. # Test case 2: Common prefix
  1384. compressed = _compress_path(b"src/file2.txt", b"src/file1.txt")
  1385. decompressed, _ = _decompress_path(compressed, 0, b"src/file1.txt")
  1386. self.assertEqual(b"src/file2.txt", decompressed)
  1387. # Test case 3: Completely different paths
  1388. compressed = _compress_path(b"docs/readme.md", b"src/file1.txt")
  1389. decompressed, _ = _decompress_path(compressed, 0, b"src/file1.txt")
  1390. self.assertEqual(b"docs/readme.md", decompressed)
  1391. def test_path_compression_deep_directories(self):
  1392. """Test compression with deep directory structures."""
  1393. path1 = b"src/main/java/com/example/service/UserService.java"
  1394. path2 = b"src/main/java/com/example/service/OrderService.java"
  1395. path3 = b"src/main/java/com/example/model/User.java"
  1396. # Compress path2 relative to path1
  1397. compressed = _compress_path(path2, path1)
  1398. decompressed, _ = _decompress_path(compressed, 0, path1)
  1399. self.assertEqual(path2, decompressed)
  1400. # Compress path3 relative to path2
  1401. compressed = _compress_path(path3, path2)
  1402. decompressed, _ = _decompress_path(compressed, 0, path2)
  1403. self.assertEqual(path3, decompressed)
  1404. def test_index_version_4_with_compression(self):
  1405. """Test full index version 4 write/read with path compression."""
  1406. index_path = os.path.join(self.tempdir, "index")
  1407. # Create an index with version 4
  1408. index = Index(index_path, read=False, version=4)
  1409. # Add multiple entries with common prefixes
  1410. paths = [
  1411. b"src/main/java/App.java",
  1412. b"src/main/java/Utils.java",
  1413. b"src/main/resources/config.properties",
  1414. b"src/test/java/AppTest.java",
  1415. b"docs/README.md",
  1416. b"docs/INSTALL.md",
  1417. ]
  1418. for i, path in enumerate(paths):
  1419. entry = IndexEntry(
  1420. ctime=(1234567890, 0),
  1421. mtime=(1234567890, 0),
  1422. dev=1,
  1423. ino=i + 1,
  1424. mode=0o100644,
  1425. uid=1000,
  1426. gid=1000,
  1427. size=10,
  1428. sha=f"{i:040d}".encode(),
  1429. )
  1430. index[path] = entry
  1431. # Write and read back
  1432. index.write()
  1433. # Read the index back
  1434. index2 = Index(index_path)
  1435. self.assertEqual(index2._version, 4)
  1436. # Verify all paths were preserved correctly
  1437. for path in paths:
  1438. self.assertIn(path, index2)
  1439. # Verify the index file is smaller than version 2 would be
  1440. with open(index_path, "rb") as f:
  1441. v4_size = len(f.read())
  1442. # Create equivalent version 2 index for comparison
  1443. index_v2_path = os.path.join(self.tempdir, "index_v2")
  1444. index_v2 = Index(index_v2_path, read=False, version=2)
  1445. for path in paths:
  1446. entry = IndexEntry(
  1447. ctime=(1234567890, 0),
  1448. mtime=(1234567890, 0),
  1449. dev=1,
  1450. ino=1,
  1451. mode=0o100644,
  1452. uid=1000,
  1453. gid=1000,
  1454. size=10,
  1455. sha=b"0" * 40,
  1456. )
  1457. index_v2[path] = entry
  1458. index_v2.write()
  1459. with open(index_v2_path, "rb") as f:
  1460. v2_size = len(f.read())
  1461. # Version 4 should be smaller due to compression
  1462. self.assertLess(
  1463. v4_size, v2_size, "Version 4 index should be smaller than version 2"
  1464. )
  1465. def test_path_compression_edge_cases(self):
  1466. """Test edge cases in path compression."""
  1467. # Empty paths
  1468. compressed = _compress_path(b"", b"")
  1469. decompressed, _ = _decompress_path(compressed, 0, b"")
  1470. self.assertEqual(b"", decompressed)
  1471. # Path identical to previous
  1472. compressed = _compress_path(b"same.txt", b"same.txt")
  1473. decompressed, _ = _decompress_path(compressed, 0, b"same.txt")
  1474. self.assertEqual(b"same.txt", decompressed)
  1475. # Path shorter than previous
  1476. compressed = _compress_path(b"short", b"very/long/path/file.txt")
  1477. decompressed, _ = _decompress_path(compressed, 0, b"very/long/path/file.txt")
  1478. self.assertEqual(b"short", decompressed)
  1479. class TestDetectCaseOnlyRenames(TestCase):
  1480. """Tests for detect_case_only_renames function."""
  1481. def setUp(self):
  1482. self.config = ConfigDict()
  1483. def test_no_renames(self):
  1484. """Test when there are no renames."""
  1485. changes = [
  1486. TreeChange(
  1487. CHANGE_DELETE,
  1488. TreeEntry(b"file1.txt", 0o100644, b"a" * 40),
  1489. None,
  1490. ),
  1491. TreeChange(
  1492. CHANGE_ADD,
  1493. None,
  1494. TreeEntry(b"file2.txt", 0o100644, b"b" * 40),
  1495. ),
  1496. ]
  1497. result = detect_case_only_renames(changes, self.config)
  1498. # No case-only renames, so should return original changes
  1499. self.assertEqual(changes, result)
  1500. def test_simple_case_rename(self):
  1501. """Test simple case-only rename detection."""
  1502. # Default config uses case-insensitive comparison
  1503. changes = [
  1504. TreeChange(
  1505. CHANGE_DELETE,
  1506. TreeEntry(b"README.txt", 0o100644, b"a" * 40),
  1507. None,
  1508. ),
  1509. TreeChange(
  1510. CHANGE_ADD,
  1511. None,
  1512. TreeEntry(b"readme.txt", 0o100644, b"a" * 40),
  1513. ),
  1514. ]
  1515. result = detect_case_only_renames(changes, self.config)
  1516. # Should return one CHANGE_RENAME instead of ADD/DELETE pair
  1517. self.assertEqual(1, len(result))
  1518. self.assertEqual(CHANGE_RENAME, result[0].type)
  1519. self.assertEqual(b"README.txt", result[0].old.path)
  1520. self.assertEqual(b"readme.txt", result[0].new.path)
  1521. def test_nested_path_case_rename(self):
  1522. """Test case-only rename in nested paths."""
  1523. changes = [
  1524. TreeChange(
  1525. CHANGE_DELETE,
  1526. TreeEntry(b"src/Main.java", 0o100644, b"a" * 40),
  1527. None,
  1528. ),
  1529. TreeChange(
  1530. CHANGE_ADD,
  1531. None,
  1532. TreeEntry(b"src/main.java", 0o100644, b"a" * 40),
  1533. ),
  1534. ]
  1535. result = detect_case_only_renames(changes, self.config)
  1536. # Should return one CHANGE_RENAME instead of ADD/DELETE pair
  1537. self.assertEqual(1, len(result))
  1538. self.assertEqual(CHANGE_RENAME, result[0].type)
  1539. self.assertEqual(b"src/Main.java", result[0].old.path)
  1540. self.assertEqual(b"src/main.java", result[0].new.path)
  1541. def test_multiple_case_renames(self):
  1542. """Test multiple case-only renames."""
  1543. changes = [
  1544. TreeChange(
  1545. CHANGE_DELETE,
  1546. TreeEntry(b"File1.txt", 0o100644, b"a" * 40),
  1547. None,
  1548. ),
  1549. TreeChange(
  1550. CHANGE_DELETE,
  1551. TreeEntry(b"File2.TXT", 0o100644, b"b" * 40),
  1552. None,
  1553. ),
  1554. TreeChange(
  1555. CHANGE_ADD,
  1556. None,
  1557. TreeEntry(b"file1.txt", 0o100644, b"a" * 40),
  1558. ),
  1559. TreeChange(
  1560. CHANGE_ADD,
  1561. None,
  1562. TreeEntry(b"file2.txt", 0o100644, b"b" * 40),
  1563. ),
  1564. ]
  1565. result = detect_case_only_renames(changes, self.config)
  1566. # Should return two CHANGE_RENAME instead of ADD/DELETE pairs
  1567. self.assertEqual(2, len(result))
  1568. rename_changes = [c for c in result if c.type == CHANGE_RENAME]
  1569. self.assertEqual(2, len(rename_changes))
  1570. # Check that the renames are correct (order may vary)
  1571. rename_map = {c.old.path: c.new.path for c in rename_changes}
  1572. self.assertEqual(
  1573. {b"File1.txt": b"file1.txt", b"File2.TXT": b"file2.txt"}, rename_map
  1574. )
  1575. def test_case_rename_with_modify(self):
  1576. """Test case rename detection with CHANGE_MODIFY."""
  1577. changes = [
  1578. TreeChange(
  1579. CHANGE_DELETE,
  1580. TreeEntry(b"README.md", 0o100644, b"a" * 40),
  1581. None,
  1582. ),
  1583. TreeChange(
  1584. CHANGE_MODIFY,
  1585. TreeEntry(b"readme.md", 0o100644, b"a" * 40),
  1586. TreeEntry(b"readme.md", 0o100644, b"b" * 40),
  1587. ),
  1588. ]
  1589. result = detect_case_only_renames(changes, self.config)
  1590. # Should return one CHANGE_RENAME instead of DELETE/MODIFY pair
  1591. self.assertEqual(1, len(result))
  1592. self.assertEqual(CHANGE_RENAME, result[0].type)
  1593. self.assertEqual(b"README.md", result[0].old.path)
  1594. self.assertEqual(b"readme.md", result[0].new.path)
  1595. def test_hfs_normalization(self):
  1596. """Test case rename detection with HFS+ normalization."""
  1597. # Configure for HFS+ (macOS)
  1598. self.config.set((b"core",), b"protectHFS", b"true")
  1599. self.config.set((b"core",), b"protectNTFS", b"false")
  1600. # Test with composed vs decomposed Unicode
  1601. changes = [
  1602. TreeChange(
  1603. CHANGE_DELETE,
  1604. TreeEntry("café.txt".encode(), 0o100644, b"a" * 40),
  1605. None,
  1606. ),
  1607. TreeChange(
  1608. CHANGE_ADD,
  1609. None,
  1610. TreeEntry("CAFÉ.txt".encode(), 0o100644, b"a" * 40),
  1611. ),
  1612. ]
  1613. result = detect_case_only_renames(changes, self.config)
  1614. # Should return one CHANGE_RENAME for the case-only rename
  1615. self.assertEqual(1, len(result))
  1616. self.assertEqual(CHANGE_RENAME, result[0].type)
  1617. self.assertEqual("café.txt".encode(), result[0].old.path)
  1618. self.assertEqual("CAFÉ.txt".encode(), result[0].new.path)
  1619. def test_ntfs_normalization(self):
  1620. """Test case rename detection with NTFS normalization."""
  1621. # Configure for NTFS (Windows)
  1622. self.config.set((b"core",), b"protectNTFS", b"true")
  1623. self.config.set((b"core",), b"protectHFS", b"false")
  1624. # NTFS strips trailing dots and spaces
  1625. changes = [
  1626. TreeChange(
  1627. CHANGE_DELETE,
  1628. TreeEntry(b"file.txt.", 0o100644, b"a" * 40),
  1629. None,
  1630. ),
  1631. TreeChange(
  1632. CHANGE_ADD,
  1633. None,
  1634. TreeEntry(b"FILE.TXT", 0o100644, b"a" * 40),
  1635. ),
  1636. ]
  1637. result = detect_case_only_renames(changes, self.config)
  1638. # Should return one CHANGE_RENAME for the case-only rename
  1639. self.assertEqual(1, len(result))
  1640. self.assertEqual(CHANGE_RENAME, result[0].type)
  1641. self.assertEqual(b"file.txt.", result[0].old.path)
  1642. self.assertEqual(b"FILE.TXT", result[0].new.path)
  1643. def test_invalid_utf8_handling(self):
  1644. """Test handling of invalid UTF-8 in paths."""
  1645. # Invalid UTF-8 sequence
  1646. invalid_path = b"\xff\xfe"
  1647. changes = [
  1648. TreeChange(
  1649. CHANGE_DELETE,
  1650. TreeEntry(invalid_path, 0o100644, b"a" * 40),
  1651. None,
  1652. ),
  1653. TreeChange(
  1654. CHANGE_ADD,
  1655. None,
  1656. TreeEntry(b"valid.txt", 0o100644, b"b" * 40),
  1657. ),
  1658. ]
  1659. # Should not crash, just skip invalid paths
  1660. result = detect_case_only_renames(changes, self.config)
  1661. # No case-only renames detected, returns original changes
  1662. self.assertEqual(changes, result)
  1663. def test_rename_and_copy_changes(self):
  1664. """Test case rename detection with CHANGE_RENAME and CHANGE_COPY."""
  1665. changes = [
  1666. TreeChange(
  1667. CHANGE_DELETE,
  1668. TreeEntry(b"OldFile.txt", 0o100644, b"a" * 40),
  1669. None,
  1670. ),
  1671. TreeChange(
  1672. CHANGE_RENAME,
  1673. TreeEntry(b"other.txt", 0o100644, b"b" * 40),
  1674. TreeEntry(b"oldfile.txt", 0o100644, b"a" * 40),
  1675. ),
  1676. TreeChange(
  1677. CHANGE_COPY,
  1678. TreeEntry(b"source.txt", 0o100644, b"c" * 40),
  1679. TreeEntry(b"OLDFILE.TXT", 0o100644, b"a" * 40),
  1680. ),
  1681. ]
  1682. result = detect_case_only_renames(changes, self.config)
  1683. # The DELETE of OldFile.txt and COPY to OLDFILE.TXT are detected as a case-only rename
  1684. # The original RENAME (other.txt -> oldfile.txt) remains
  1685. # The COPY is consumed by the case-only rename detection
  1686. self.assertEqual(2, len(result))
  1687. # Find the changes
  1688. rename_changes = [c for c in result if c.type == CHANGE_RENAME]
  1689. self.assertEqual(2, len(rename_changes))
  1690. # Check for the case-only rename
  1691. case_rename = None
  1692. for change in rename_changes:
  1693. if change.old.path == b"OldFile.txt" and change.new.path == b"OLDFILE.TXT":
  1694. case_rename = change
  1695. break
  1696. self.assertIsNotNone(case_rename)
  1697. self.assertEqual(b"OldFile.txt", case_rename.old.path)
  1698. self.assertEqual(b"OLDFILE.TXT", case_rename.new.path)
  1699. class TestUpdateWorkingTree(TestCase):
  1700. def setUp(self):
  1701. self.tempdir = tempfile.mkdtemp()
  1702. def cleanup_tempdir():
  1703. """Remove tempdir, handling read-only files on Windows."""
  1704. def remove_readonly(func, path, excinfo):
  1705. """Error handler for Windows read-only files."""
  1706. import stat
  1707. if sys.platform == "win32" and excinfo[0] is PermissionError:
  1708. os.chmod(path, stat.S_IWRITE)
  1709. func(path)
  1710. else:
  1711. raise
  1712. shutil.rmtree(self.tempdir, onerror=remove_readonly)
  1713. self.addCleanup(cleanup_tempdir)
  1714. self.repo = Repo.init(self.tempdir)
  1715. def test_update_working_tree_with_blob_normalizer(self):
  1716. """Test update_working_tree with a blob normalizer."""
  1717. # Create a simple blob normalizer that converts CRLF to LF
  1718. class TestBlobNormalizer:
  1719. def checkout_normalize(self, blob, path):
  1720. # Convert CRLF to LF during checkout
  1721. new_blob = Blob()
  1722. new_blob.data = blob.data.replace(b"\r\n", b"\n")
  1723. return new_blob
  1724. # Create a tree with a file containing CRLF
  1725. blob = Blob()
  1726. blob.data = b"Hello\r\nWorld\r\n"
  1727. self.repo.object_store.add_object(blob)
  1728. tree = Tree()
  1729. tree[b"test.txt"] = (0o100644, blob.id)
  1730. self.repo.object_store.add_object(tree)
  1731. # Update working tree with normalizer
  1732. normalizer = TestBlobNormalizer()
  1733. changes = tree_changes(self.repo.object_store, None, tree.id)
  1734. update_working_tree(
  1735. self.repo,
  1736. None, # old_tree_id
  1737. tree.id, # new_tree_id
  1738. change_iterator=changes,
  1739. blob_normalizer=normalizer,
  1740. )
  1741. # Check that the file was written with LF line endings
  1742. test_file = os.path.join(self.tempdir, "test.txt")
  1743. with open(test_file, "rb") as f:
  1744. content = f.read()
  1745. self.assertEqual(b"Hello\nWorld\n", content)
  1746. # Check that the index has the original blob SHA
  1747. index = self.repo.open_index()
  1748. self.assertEqual(blob.id, index[b"test.txt"].sha)
  1749. def test_update_working_tree_without_blob_normalizer(self):
  1750. """Test update_working_tree without a blob normalizer."""
  1751. # Create a tree with a file containing CRLF
  1752. blob = Blob()
  1753. blob.data = b"Hello\r\nWorld\r\n"
  1754. self.repo.object_store.add_object(blob)
  1755. tree = Tree()
  1756. tree[b"test.txt"] = (0o100644, blob.id)
  1757. self.repo.object_store.add_object(tree)
  1758. # Update working tree without normalizer
  1759. changes = tree_changes(self.repo.object_store, None, tree.id)
  1760. update_working_tree(
  1761. self.repo,
  1762. None, # old_tree_id
  1763. tree.id, # new_tree_id
  1764. change_iterator=changes,
  1765. blob_normalizer=None,
  1766. )
  1767. # Check that the file was written with original CRLF line endings
  1768. test_file = os.path.join(self.tempdir, "test.txt")
  1769. with open(test_file, "rb") as f:
  1770. content = f.read()
  1771. self.assertEqual(b"Hello\r\nWorld\r\n", content)
  1772. # Check that the index has the blob SHA
  1773. index = self.repo.open_index()
  1774. self.assertEqual(blob.id, index[b"test.txt"].sha)
  1775. def test_update_working_tree_remove_directory(self):
  1776. """Test that update_working_tree properly removes directories."""
  1777. # Create initial tree with a directory containing files
  1778. blob1 = Blob()
  1779. blob1.data = b"content1"
  1780. self.repo.object_store.add_object(blob1)
  1781. blob2 = Blob()
  1782. blob2.data = b"content2"
  1783. self.repo.object_store.add_object(blob2)
  1784. tree1 = Tree()
  1785. tree1[b"dir/file1.txt"] = (0o100644, blob1.id)
  1786. tree1[b"dir/file2.txt"] = (0o100644, blob2.id)
  1787. self.repo.object_store.add_object(tree1)
  1788. # Update to tree1 (create directory with files)
  1789. changes = tree_changes(self.repo.object_store, None, tree1.id)
  1790. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  1791. # Verify directory and files exist
  1792. dir_path = os.path.join(self.tempdir, "dir")
  1793. self.assertTrue(os.path.isdir(dir_path))
  1794. self.assertTrue(os.path.exists(os.path.join(dir_path, "file1.txt")))
  1795. self.assertTrue(os.path.exists(os.path.join(dir_path, "file2.txt")))
  1796. # Create empty tree (remove everything)
  1797. tree2 = Tree()
  1798. self.repo.object_store.add_object(tree2)
  1799. # Update to empty tree
  1800. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  1801. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  1802. # Verify directory was removed
  1803. self.assertFalse(os.path.exists(dir_path))
  1804. def test_update_working_tree_submodule_to_file(self):
  1805. """Test replacing a submodule directory with a file."""
  1806. # Create tree with submodule
  1807. submodule_sha = b"a" * 40
  1808. tree1 = Tree()
  1809. tree1[b"submodule"] = (S_IFGITLINK, submodule_sha)
  1810. self.repo.object_store.add_object(tree1)
  1811. # Update to tree with submodule
  1812. changes = tree_changes(self.repo.object_store, None, tree1.id)
  1813. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  1814. # Verify submodule directory exists with .git file
  1815. submodule_path = os.path.join(self.tempdir, "submodule")
  1816. self.assertTrue(os.path.isdir(submodule_path))
  1817. self.assertTrue(os.path.exists(os.path.join(submodule_path, ".git")))
  1818. # Create tree with file at same path
  1819. blob = Blob()
  1820. blob.data = b"file content"
  1821. self.repo.object_store.add_object(blob)
  1822. tree2 = Tree()
  1823. tree2[b"submodule"] = (0o100644, blob.id)
  1824. self.repo.object_store.add_object(tree2)
  1825. # Update to tree with file (should remove submodule directory and create file)
  1826. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  1827. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  1828. # Verify it's now a file
  1829. self.assertTrue(os.path.isfile(submodule_path))
  1830. with open(submodule_path, "rb") as f:
  1831. self.assertEqual(b"file content", f.read())
  1832. def test_update_working_tree_directory_with_nested_subdir(self):
  1833. """Test removing directory with nested subdirectories."""
  1834. # Create tree with nested directories
  1835. blob = Blob()
  1836. blob.data = b"deep content"
  1837. self.repo.object_store.add_object(blob)
  1838. tree1 = Tree()
  1839. tree1[b"a/b/c/file.txt"] = (0o100644, blob.id)
  1840. self.repo.object_store.add_object(tree1)
  1841. # Update to tree1
  1842. changes = tree_changes(self.repo.object_store, None, tree1.id)
  1843. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  1844. # Verify nested structure exists
  1845. path_a = os.path.join(self.tempdir, "a")
  1846. path_b = os.path.join(path_a, "b")
  1847. path_c = os.path.join(path_b, "c")
  1848. file_path = os.path.join(path_c, "file.txt")
  1849. self.assertTrue(os.path.exists(file_path))
  1850. # Create empty tree
  1851. tree2 = Tree()
  1852. self.repo.object_store.add_object(tree2)
  1853. # Update to empty tree
  1854. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  1855. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  1856. # Verify all directories were removed
  1857. self.assertFalse(os.path.exists(path_a))
  1858. def test_update_working_tree_file_replaced_by_dir_not_removed(self):
  1859. """Test that a directory replacing a git file is left alone if not empty."""
  1860. # Create tree with a file
  1861. blob = Blob()
  1862. blob.data = b"file content"
  1863. self.repo.object_store.add_object(blob)
  1864. tree1 = Tree()
  1865. tree1[b"path"] = (0o100644, blob.id)
  1866. self.repo.object_store.add_object(tree1)
  1867. # Update to tree1
  1868. changes = tree_changes(self.repo.object_store, None, tree1.id)
  1869. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  1870. # Verify file exists
  1871. file_path = os.path.join(self.tempdir, "path")
  1872. self.assertTrue(os.path.isfile(file_path))
  1873. # Manually replace file with directory containing untracked file
  1874. os.remove(file_path)
  1875. os.mkdir(file_path)
  1876. with open(os.path.join(file_path, "untracked.txt"), "w") as f:
  1877. f.write("untracked content")
  1878. # Create empty tree
  1879. tree2 = Tree()
  1880. self.repo.object_store.add_object(tree2)
  1881. # Update should succeed but leave the directory alone
  1882. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  1883. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  1884. # Directory should still exist with its contents
  1885. self.assertTrue(os.path.isdir(file_path))
  1886. self.assertTrue(os.path.exists(os.path.join(file_path, "untracked.txt")))
  1887. def test_update_working_tree_file_replaced_by_empty_dir_removed(self):
  1888. """Test that an empty directory replacing a git file is removed."""
  1889. # Create tree with a file
  1890. blob = Blob()
  1891. blob.data = b"file content"
  1892. self.repo.object_store.add_object(blob)
  1893. tree1 = Tree()
  1894. tree1[b"path"] = (0o100644, blob.id)
  1895. self.repo.object_store.add_object(tree1)
  1896. # Update to tree1
  1897. changes = tree_changes(self.repo.object_store, None, tree1.id)
  1898. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  1899. # Verify file exists
  1900. file_path = os.path.join(self.tempdir, "path")
  1901. self.assertTrue(os.path.isfile(file_path))
  1902. # Manually replace file with empty directory
  1903. os.remove(file_path)
  1904. os.mkdir(file_path)
  1905. # Create empty tree
  1906. tree2 = Tree()
  1907. self.repo.object_store.add_object(tree2)
  1908. # Update should remove the empty directory
  1909. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  1910. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  1911. # Directory should be gone
  1912. self.assertFalse(os.path.exists(file_path))
  1913. def test_update_working_tree_symlink_transitions(self):
  1914. """Test transitions involving symlinks."""
  1915. # Skip on Windows where symlinks might not be supported
  1916. if sys.platform == "win32":
  1917. self.skipTest("Symlinks not fully supported on Windows")
  1918. # Create tree with symlink
  1919. blob1 = Blob()
  1920. blob1.data = b"target/path"
  1921. self.repo.object_store.add_object(blob1)
  1922. tree1 = Tree()
  1923. tree1[b"link"] = (0o120000, blob1.id) # Symlink mode
  1924. self.repo.object_store.add_object(tree1)
  1925. # Update to tree with symlink
  1926. changes = tree_changes(self.repo.object_store, None, tree1.id)
  1927. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  1928. link_path = os.path.join(self.tempdir, "link")
  1929. self.assertTrue(os.path.islink(link_path))
  1930. self.assertEqual(b"target/path", os.readlink(link_path).encode())
  1931. # Test 1: Replace symlink with regular file
  1932. blob2 = Blob()
  1933. blob2.data = b"file content"
  1934. self.repo.object_store.add_object(blob2)
  1935. tree2 = Tree()
  1936. tree2[b"link"] = (0o100644, blob2.id)
  1937. self.repo.object_store.add_object(tree2)
  1938. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  1939. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  1940. self.assertFalse(os.path.islink(link_path))
  1941. self.assertTrue(os.path.isfile(link_path))
  1942. with open(link_path, "rb") as f:
  1943. self.assertEqual(b"file content", f.read())
  1944. # Test 2: Replace file with symlink
  1945. changes = tree_changes(self.repo.object_store, tree2.id, tree1.id)
  1946. update_working_tree(self.repo, tree2.id, tree1.id, change_iterator=changes)
  1947. self.assertTrue(os.path.islink(link_path))
  1948. self.assertEqual(b"target/path", os.readlink(link_path).encode())
  1949. # Test 3: Replace symlink with directory (manually)
  1950. os.unlink(link_path)
  1951. os.mkdir(link_path)
  1952. # Create empty tree
  1953. tree3 = Tree()
  1954. self.repo.object_store.add_object(tree3)
  1955. # Should remove empty directory
  1956. changes = tree_changes(self.repo.object_store, tree1.id, tree3.id)
  1957. update_working_tree(self.repo, tree1.id, tree3.id, change_iterator=changes)
  1958. self.assertFalse(os.path.exists(link_path))
  1959. def test_update_working_tree_modified_file_to_dir_transition(self):
  1960. """Test that modified files are not removed when they should be directories."""
  1961. # Create tree with file
  1962. blob1 = Blob()
  1963. blob1.data = b"original content"
  1964. self.repo.object_store.add_object(blob1)
  1965. tree1 = Tree()
  1966. tree1[b"path"] = (0o100644, blob1.id)
  1967. self.repo.object_store.add_object(tree1)
  1968. # Update to tree1
  1969. changes = tree_changes(self.repo.object_store, None, tree1.id)
  1970. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  1971. file_path = os.path.join(self.tempdir, "path")
  1972. # Modify the file locally
  1973. with open(file_path, "w") as f:
  1974. f.write("modified content")
  1975. # Create tree where path is a directory with file
  1976. blob2 = Blob()
  1977. blob2.data = b"subfile content"
  1978. self.repo.object_store.add_object(blob2)
  1979. tree2 = Tree()
  1980. tree2[b"path/subfile"] = (0o100644, blob2.id)
  1981. self.repo.object_store.add_object(tree2)
  1982. # Update should fail because can't create directory where modified file exists
  1983. with self.assertRaises(IOError):
  1984. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  1985. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  1986. # File should still exist with modifications
  1987. self.assertTrue(os.path.isfile(file_path))
  1988. with open(file_path) as f:
  1989. self.assertEqual("modified content", f.read())
  1990. def test_update_working_tree_executable_transitions(self):
  1991. """Test transitions involving executable bit changes."""
  1992. # Skip on Windows where executable bit is not supported
  1993. if sys.platform == "win32":
  1994. self.skipTest("Executable bit not supported on Windows")
  1995. # Create tree with non-executable file
  1996. blob = Blob()
  1997. blob.data = b"#!/bin/sh\necho hello"
  1998. self.repo.object_store.add_object(blob)
  1999. tree1 = Tree()
  2000. tree1[b"script.sh"] = (0o100644, blob.id) # Non-executable
  2001. self.repo.object_store.add_object(tree1)
  2002. # Update to tree1
  2003. changes = tree_changes(self.repo.object_store, None, tree1.id)
  2004. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  2005. script_path = os.path.join(self.tempdir, "script.sh")
  2006. self.assertTrue(os.path.isfile(script_path))
  2007. # Check it's not executable
  2008. mode = os.stat(script_path).st_mode
  2009. self.assertFalse(mode & stat.S_IXUSR)
  2010. # Create tree with executable file (same content)
  2011. tree2 = Tree()
  2012. tree2[b"script.sh"] = (0o100755, blob.id) # Executable
  2013. self.repo.object_store.add_object(tree2)
  2014. # Update to tree2
  2015. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  2016. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  2017. # Check it's now executable
  2018. mode = os.stat(script_path).st_mode
  2019. self.assertTrue(mode & stat.S_IXUSR)
  2020. def test_update_working_tree_submodule_with_untracked_files(self):
  2021. """Test that submodules with untracked files are not removed."""
  2022. from dulwich.objects import S_IFGITLINK, Tree
  2023. # Create tree with submodule
  2024. submodule_sha = b"a" * 40
  2025. tree1 = Tree()
  2026. tree1[b"submodule"] = (S_IFGITLINK, submodule_sha)
  2027. self.repo.object_store.add_object(tree1)
  2028. # Update to tree with submodule
  2029. changes = tree_changes(self.repo.object_store, None, tree1.id)
  2030. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  2031. # Add untracked file to submodule directory
  2032. submodule_path = os.path.join(self.tempdir, "submodule")
  2033. untracked_path = os.path.join(submodule_path, "untracked.txt")
  2034. with open(untracked_path, "w") as f:
  2035. f.write("untracked content")
  2036. # Create empty tree
  2037. tree2 = Tree()
  2038. self.repo.object_store.add_object(tree2)
  2039. # Update should not remove submodule directory with untracked files
  2040. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  2041. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  2042. # Directory should still exist with untracked file
  2043. self.assertTrue(os.path.isdir(submodule_path))
  2044. self.assertTrue(os.path.exists(untracked_path))
  2045. def test_update_working_tree_dir_to_file_with_subdir(self):
  2046. """Test replacing directory structure with a file."""
  2047. # Create tree with nested directory structure
  2048. blob1 = Blob()
  2049. blob1.data = b"content1"
  2050. self.repo.object_store.add_object(blob1)
  2051. blob2 = Blob()
  2052. blob2.data = b"content2"
  2053. self.repo.object_store.add_object(blob2)
  2054. tree1 = Tree()
  2055. tree1[b"dir/subdir/file1"] = (0o100644, blob1.id)
  2056. tree1[b"dir/subdir/file2"] = (0o100644, blob2.id)
  2057. self.repo.object_store.add_object(tree1)
  2058. # Update to tree1
  2059. changes = tree_changes(self.repo.object_store, None, tree1.id)
  2060. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  2061. # Verify structure exists
  2062. dir_path = os.path.join(self.tempdir, "dir")
  2063. self.assertTrue(os.path.isdir(dir_path))
  2064. # Add an untracked file to make directory truly non-empty
  2065. untracked_path = os.path.join(dir_path, "untracked.txt")
  2066. with open(untracked_path, "w") as f:
  2067. f.write("untracked content")
  2068. # Create tree with file at "dir" path
  2069. blob3 = Blob()
  2070. blob3.data = b"replacement file"
  2071. self.repo.object_store.add_object(blob3)
  2072. tree2 = Tree()
  2073. tree2[b"dir"] = (0o100644, blob3.id)
  2074. self.repo.object_store.add_object(tree2)
  2075. # Update should fail because directory is not empty
  2076. with self.assertRaises(IsADirectoryError):
  2077. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  2078. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  2079. # Directory should still exist
  2080. self.assertTrue(os.path.isdir(dir_path))
  2081. def test_update_working_tree_case_sensitivity(self):
  2082. """Test handling of case-sensitive filename changes."""
  2083. # Detect if filesystem is case-insensitive by testing
  2084. test_file = os.path.join(self.tempdir, "TeSt.tmp")
  2085. with open(test_file, "w") as f:
  2086. f.write("test")
  2087. is_case_insensitive = os.path.exists(os.path.join(self.tempdir, "test.tmp"))
  2088. os.unlink(test_file)
  2089. # Set core.ignorecase to match actual filesystem behavior
  2090. # (This ensures test works correctly regardless of platform defaults)
  2091. config = self.repo.get_config()
  2092. config.set((b"core",), b"ignorecase", is_case_insensitive)
  2093. config.write_to_path()
  2094. # Create tree with lowercase file
  2095. blob1 = Blob()
  2096. blob1.data = b"lowercase content"
  2097. self.repo.object_store.add_object(blob1)
  2098. tree1 = Tree()
  2099. tree1[b"readme.txt"] = (0o100644, blob1.id)
  2100. self.repo.object_store.add_object(tree1)
  2101. # Update to tree1
  2102. changes = tree_changes(self.repo.object_store, None, tree1.id)
  2103. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  2104. # Create tree with uppercase file (different content)
  2105. blob2 = Blob()
  2106. blob2.data = b"uppercase content"
  2107. self.repo.object_store.add_object(blob2)
  2108. tree2 = Tree()
  2109. tree2[b"README.txt"] = (0o100644, blob2.id)
  2110. self.repo.object_store.add_object(tree2)
  2111. # Update to tree2
  2112. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  2113. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  2114. # Check what exists (behavior depends on filesystem)
  2115. lowercase_path = os.path.join(self.tempdir, "readme.txt")
  2116. uppercase_path = os.path.join(self.tempdir, "README.txt")
  2117. if is_case_insensitive:
  2118. # On case-insensitive filesystems, should have one file with new content
  2119. # The exact case of the filename may vary by OS
  2120. self.assertTrue(
  2121. os.path.exists(lowercase_path) or os.path.exists(uppercase_path)
  2122. )
  2123. # Verify content is the new content
  2124. if os.path.exists(lowercase_path):
  2125. with open(lowercase_path, "rb") as f:
  2126. self.assertEqual(b"uppercase content", f.read())
  2127. else:
  2128. with open(uppercase_path, "rb") as f:
  2129. self.assertEqual(b"uppercase content", f.read())
  2130. else:
  2131. # On case-sensitive filesystems, only the uppercase file should exist
  2132. self.assertFalse(os.path.exists(lowercase_path))
  2133. self.assertTrue(os.path.exists(uppercase_path))
  2134. with open(uppercase_path, "rb") as f:
  2135. self.assertEqual(b"uppercase content", f.read())
  2136. def test_update_working_tree_case_rename_updates_filename(self):
  2137. """Test that case-only renames update the actual filename on case-insensitive FS."""
  2138. # Detect if filesystem is case-insensitive by testing
  2139. test_file = os.path.join(self.tempdir, "TeSt.tmp")
  2140. with open(test_file, "w") as f:
  2141. f.write("test")
  2142. is_case_insensitive = os.path.exists(os.path.join(self.tempdir, "test.tmp"))
  2143. os.unlink(test_file)
  2144. if not is_case_insensitive:
  2145. self.skipTest("Test only relevant on case-insensitive filesystems")
  2146. # Set core.ignorecase to match actual filesystem behavior
  2147. config = self.repo.get_config()
  2148. config.set((b"core",), b"ignorecase", True)
  2149. config.write_to_path()
  2150. # Create tree with lowercase file
  2151. blob1 = Blob()
  2152. blob1.data = b"same content" # Using same content to test pure case rename
  2153. self.repo.object_store.add_object(blob1)
  2154. tree1 = Tree()
  2155. tree1[b"readme.txt"] = (0o100644, blob1.id)
  2156. self.repo.object_store.add_object(tree1)
  2157. # Update to tree1
  2158. changes = tree_changes(self.repo.object_store, None, tree1.id)
  2159. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  2160. # Verify initial state
  2161. files = [f for f in os.listdir(self.tempdir) if not f.startswith(".git")]
  2162. self.assertEqual(["readme.txt"], files)
  2163. # Create tree with uppercase file (same content, same blob)
  2164. tree2 = Tree()
  2165. tree2[b"README.txt"] = (0o100644, blob1.id) # Same blob!
  2166. self.repo.object_store.add_object(tree2)
  2167. # Update to tree2 (case-only rename)
  2168. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  2169. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  2170. # On case-insensitive filesystems, should have one file with updated case
  2171. files = [f for f in os.listdir(self.tempdir) if not f.startswith(".git")]
  2172. self.assertEqual(
  2173. 1, len(files), "Should have exactly one file after case rename"
  2174. )
  2175. # The file should now have the new case in the directory listing
  2176. actual_filename = files[0]
  2177. self.assertEqual(
  2178. "README.txt",
  2179. actual_filename,
  2180. "Filename case should be updated in directory listing",
  2181. )
  2182. # Verify content is preserved
  2183. file_path = os.path.join(self.tempdir, actual_filename)
  2184. with open(file_path, "rb") as f:
  2185. self.assertEqual(b"same content", f.read())
  2186. # Both old and new case should access the same file
  2187. lowercase_path = os.path.join(self.tempdir, "readme.txt")
  2188. uppercase_path = os.path.join(self.tempdir, "README.txt")
  2189. self.assertTrue(os.path.exists(lowercase_path))
  2190. self.assertTrue(os.path.exists(uppercase_path))
  2191. def test_update_working_tree_deeply_nested_removal(self):
  2192. """Test removal of deeply nested directory structures."""
  2193. # Create deeply nested structure
  2194. blob = Blob()
  2195. blob.data = b"deep content"
  2196. self.repo.object_store.add_object(blob)
  2197. tree1 = Tree()
  2198. # Create a very deep path
  2199. deep_path = b"/".join([b"level%d" % i for i in range(10)])
  2200. tree1[deep_path + b"/file.txt"] = (0o100644, blob.id)
  2201. self.repo.object_store.add_object(tree1)
  2202. # Update to tree1
  2203. changes = tree_changes(self.repo.object_store, None, tree1.id)
  2204. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  2205. # Verify deep structure exists
  2206. current_path = self.tempdir
  2207. for i in range(10):
  2208. current_path = os.path.join(current_path, f"level{i}")
  2209. self.assertTrue(os.path.isdir(current_path))
  2210. # Create empty tree
  2211. tree2 = Tree()
  2212. self.repo.object_store.add_object(tree2)
  2213. # Update should remove all empty directories
  2214. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  2215. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  2216. # Verify top level directory is gone
  2217. top_level = os.path.join(self.tempdir, "level0")
  2218. self.assertFalse(os.path.exists(top_level))
  2219. def test_update_working_tree_read_only_files(self):
  2220. """Test handling of read-only files during updates."""
  2221. # Create tree with file
  2222. blob1 = Blob()
  2223. blob1.data = b"original content"
  2224. self.repo.object_store.add_object(blob1)
  2225. tree1 = Tree()
  2226. tree1[b"readonly.txt"] = (0o100644, blob1.id)
  2227. self.repo.object_store.add_object(tree1)
  2228. # Update to tree1
  2229. changes = tree_changes(self.repo.object_store, None, tree1.id)
  2230. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  2231. # Make file read-only
  2232. file_path = os.path.join(self.tempdir, "readonly.txt")
  2233. os.chmod(file_path, 0o444) # Read-only
  2234. # Create tree with modified file
  2235. blob2 = Blob()
  2236. blob2.data = b"new content"
  2237. self.repo.object_store.add_object(blob2)
  2238. tree2 = Tree()
  2239. tree2[b"readonly.txt"] = (0o100644, blob2.id)
  2240. self.repo.object_store.add_object(tree2)
  2241. # Update should handle read-only file
  2242. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  2243. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  2244. # Verify content was updated
  2245. with open(file_path, "rb") as f:
  2246. self.assertEqual(b"new content", f.read())
  2247. def test_update_working_tree_invalid_filenames(self):
  2248. """Test handling of invalid filenames for the platform."""
  2249. # Create tree with potentially problematic filenames
  2250. blob = Blob()
  2251. blob.data = b"content"
  2252. self.repo.object_store.add_object(blob)
  2253. tree = Tree()
  2254. # Add files with names that might be invalid on some platforms
  2255. tree[b"valid.txt"] = (0o100644, blob.id)
  2256. if sys.platform != "win32":
  2257. # These are invalid on Windows but valid on Unix
  2258. tree[b"file:with:colons.txt"] = (0o100644, blob.id)
  2259. tree[b"file<with>brackets.txt"] = (0o100644, blob.id)
  2260. self.repo.object_store.add_object(tree)
  2261. # Update should skip invalid files based on validation
  2262. changes = tree_changes(self.repo.object_store, None, tree.id)
  2263. update_working_tree(self.repo, None, tree.id, change_iterator=changes)
  2264. # Valid file should exist
  2265. self.assertTrue(os.path.exists(os.path.join(self.tempdir, "valid.txt")))
  2266. def test_update_working_tree_symlink_to_directory(self):
  2267. """Test replacing a symlink pointing to a directory with a real directory."""
  2268. if sys.platform == "win32":
  2269. self.skipTest("Symlinks not fully supported on Windows")
  2270. # Create a target directory
  2271. target_dir = os.path.join(self.tempdir, "target")
  2272. os.mkdir(target_dir)
  2273. with open(os.path.join(target_dir, "file.txt"), "w") as f:
  2274. f.write("target file")
  2275. # Create tree with symlink pointing to directory
  2276. blob1 = Blob()
  2277. blob1.data = b"target" # Relative path to target directory
  2278. self.repo.object_store.add_object(blob1)
  2279. tree1 = Tree()
  2280. tree1[b"link"] = (0o120000, blob1.id)
  2281. self.repo.object_store.add_object(tree1)
  2282. # Update to tree1
  2283. changes = tree_changes(self.repo.object_store, None, tree1.id)
  2284. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  2285. link_path = os.path.join(self.tempdir, "link")
  2286. self.assertTrue(os.path.islink(link_path))
  2287. # Create tree with actual directory at same path
  2288. blob2 = Blob()
  2289. blob2.data = b"new file content"
  2290. self.repo.object_store.add_object(blob2)
  2291. tree2 = Tree()
  2292. tree2[b"link/newfile.txt"] = (0o100644, blob2.id)
  2293. self.repo.object_store.add_object(tree2)
  2294. # Update should replace symlink with actual directory
  2295. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  2296. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  2297. self.assertFalse(os.path.islink(link_path))
  2298. self.assertTrue(os.path.isdir(link_path))
  2299. self.assertTrue(os.path.exists(os.path.join(link_path, "newfile.txt")))
  2300. def test_update_working_tree_comprehensive_transitions(self):
  2301. """Test all possible file type transitions comprehensively."""
  2302. # Skip on Windows where symlinks might not be supported
  2303. if sys.platform == "win32":
  2304. self.skipTest("Symlinks not fully supported on Windows")
  2305. # Create blobs for different file types
  2306. file_blob = Blob()
  2307. file_blob.data = b"regular file content"
  2308. self.repo.object_store.add_object(file_blob)
  2309. exec_blob = Blob()
  2310. exec_blob.data = b"#!/bin/sh\necho executable"
  2311. self.repo.object_store.add_object(exec_blob)
  2312. link_blob = Blob()
  2313. link_blob.data = b"target/path"
  2314. self.repo.object_store.add_object(link_blob)
  2315. submodule_sha = b"a" * 40
  2316. # Test 1: Regular file → Submodule
  2317. tree1 = Tree()
  2318. tree1[b"item"] = (0o100644, file_blob.id)
  2319. self.repo.object_store.add_object(tree1)
  2320. tree2 = Tree()
  2321. tree2[b"item"] = (S_IFGITLINK, submodule_sha)
  2322. self.repo.object_store.add_object(tree2)
  2323. changes = tree_changes(self.repo.object_store, None, tree1.id)
  2324. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  2325. self.assertTrue(os.path.isfile(os.path.join(self.tempdir, "item")))
  2326. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  2327. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  2328. self.assertTrue(os.path.isdir(os.path.join(self.tempdir, "item")))
  2329. # Test 2: Submodule → Executable file
  2330. tree3 = Tree()
  2331. tree3[b"item"] = (0o100755, exec_blob.id)
  2332. self.repo.object_store.add_object(tree3)
  2333. changes = tree_changes(self.repo.object_store, tree2.id, tree3.id)
  2334. update_working_tree(self.repo, tree2.id, tree3.id, change_iterator=changes)
  2335. item_path = os.path.join(self.tempdir, "item")
  2336. self.assertTrue(os.path.isfile(item_path))
  2337. if sys.platform != "win32":
  2338. self.assertTrue(os.access(item_path, os.X_OK))
  2339. # Test 3: Executable file → Symlink
  2340. tree4 = Tree()
  2341. tree4[b"item"] = (0o120000, link_blob.id)
  2342. self.repo.object_store.add_object(tree4)
  2343. changes = tree_changes(self.repo.object_store, tree3.id, tree4.id)
  2344. update_working_tree(self.repo, tree3.id, tree4.id, change_iterator=changes)
  2345. self.assertTrue(os.path.islink(item_path))
  2346. # Test 4: Symlink → Submodule
  2347. tree5 = Tree()
  2348. tree5[b"item"] = (S_IFGITLINK, submodule_sha)
  2349. self.repo.object_store.add_object(tree5)
  2350. changes = tree_changes(self.repo.object_store, tree4.id, tree5.id)
  2351. update_working_tree(self.repo, tree4.id, tree5.id, change_iterator=changes)
  2352. self.assertTrue(os.path.isdir(item_path))
  2353. # Test 5: Clean up - Submodule → absent
  2354. tree6 = Tree()
  2355. self.repo.object_store.add_object(tree6)
  2356. changes = tree_changes(self.repo.object_store, tree5.id, tree6.id)
  2357. update_working_tree(self.repo, tree5.id, tree6.id, change_iterator=changes)
  2358. self.assertFalse(os.path.exists(item_path))
  2359. # Test 6: Symlink → Executable file
  2360. tree7 = Tree()
  2361. tree7[b"item2"] = (0o120000, link_blob.id)
  2362. self.repo.object_store.add_object(tree7)
  2363. changes = tree_changes(self.repo.object_store, tree6.id, tree7.id)
  2364. update_working_tree(self.repo, tree6.id, tree7.id, change_iterator=changes)
  2365. item2_path = os.path.join(self.tempdir, "item2")
  2366. self.assertTrue(os.path.islink(item2_path))
  2367. tree8 = Tree()
  2368. tree8[b"item2"] = (0o100755, exec_blob.id)
  2369. self.repo.object_store.add_object(tree8)
  2370. changes = tree_changes(self.repo.object_store, tree7.id, tree8.id)
  2371. update_working_tree(self.repo, tree7.id, tree8.id, change_iterator=changes)
  2372. self.assertTrue(os.path.isfile(item2_path))
  2373. if sys.platform != "win32":
  2374. self.assertTrue(os.access(item2_path, os.X_OK))
  2375. def test_update_working_tree_partial_update_failure(self):
  2376. """Test handling when update fails partway through."""
  2377. # Create initial tree
  2378. blob1 = Blob()
  2379. blob1.data = b"file1 content"
  2380. self.repo.object_store.add_object(blob1)
  2381. blob2 = Blob()
  2382. blob2.data = b"file2 content"
  2383. self.repo.object_store.add_object(blob2)
  2384. tree1 = Tree()
  2385. tree1[b"file1.txt"] = (0o100644, blob1.id)
  2386. tree1[b"file2.txt"] = (0o100644, blob2.id)
  2387. self.repo.object_store.add_object(tree1)
  2388. # Update to tree1
  2389. changes = tree_changes(self.repo.object_store, None, tree1.id)
  2390. update_working_tree(self.repo, None, tree1.id, change_iterator=changes)
  2391. # Create a directory where file2.txt is, to cause a conflict
  2392. file2_path = os.path.join(self.tempdir, "file2.txt")
  2393. os.remove(file2_path)
  2394. os.mkdir(file2_path)
  2395. # Add untracked file to prevent removal
  2396. with open(os.path.join(file2_path, "blocker.txt"), "w") as f:
  2397. f.write("blocking content")
  2398. # Create tree with updates to both files
  2399. blob3 = Blob()
  2400. blob3.data = b"file1 updated"
  2401. self.repo.object_store.add_object(blob3)
  2402. blob4 = Blob()
  2403. blob4.data = b"file2 updated"
  2404. self.repo.object_store.add_object(blob4)
  2405. tree2 = Tree()
  2406. tree2[b"file1.txt"] = (0o100644, blob3.id)
  2407. tree2[b"file2.txt"] = (0o100644, blob4.id)
  2408. self.repo.object_store.add_object(tree2)
  2409. # Update should partially succeed - file1 updated, file2 blocked
  2410. try:
  2411. changes = tree_changes(self.repo.object_store, tree1.id, tree2.id)
  2412. update_working_tree(self.repo, tree1.id, tree2.id, change_iterator=changes)
  2413. except IsADirectoryError:
  2414. # Expected to fail on file2 because it's a directory
  2415. pass
  2416. # file1 should be updated
  2417. with open(os.path.join(self.tempdir, "file1.txt"), "rb") as f:
  2418. self.assertEqual(b"file1 updated", f.read())
  2419. # file2 should still be a directory
  2420. self.assertTrue(os.path.isdir(file2_path))
  2421. def test_ensure_parent_dir_exists_windows_drive(self):
  2422. """Test that _ensure_parent_dir_exists handles Windows drive letters correctly."""
  2423. from dulwich.index import _ensure_parent_dir_exists
  2424. # Create a temporary directory to work with
  2425. with tempfile.TemporaryDirectory() as tmpdir:
  2426. # Test normal case (creates directory)
  2427. test_path = os.path.join(tmpdir, "subdir", "file.txt").encode()
  2428. _ensure_parent_dir_exists(test_path)
  2429. self.assertTrue(os.path.exists(os.path.dirname(test_path)))
  2430. # Test when parent is a file (should raise error)
  2431. file_path = os.path.join(tmpdir, "testfile").encode()
  2432. with open(file_path, "wb") as f:
  2433. f.write(b"test")
  2434. invalid_path = os.path.join(
  2435. tmpdir.encode(), b"testfile", b"subdir", b"file.txt"
  2436. )
  2437. with self.assertRaisesRegex(
  2438. OSError, "Cannot create directory, parent path is a file"
  2439. ):
  2440. _ensure_parent_dir_exists(invalid_path)
  2441. # Test with nested subdirectories
  2442. nested_path = os.path.join(tmpdir, "a", "b", "c", "d", "file.txt").encode()
  2443. _ensure_parent_dir_exists(nested_path)
  2444. self.assertTrue(os.path.exists(os.path.dirname(nested_path)))
  2445. # Test that various path formats are handled correctly by os.path.dirname
  2446. # This includes Windows drive letters, UNC paths, etc.
  2447. # The key is that we're using os.path.dirname which handles these correctly
  2448. import platform
  2449. if platform.system() == "Windows":
  2450. # Test Windows-specific paths only on Windows
  2451. test_cases = [
  2452. b"C:\\temp\\test\\file.txt",
  2453. b"D:\\file.txt",
  2454. b"\\\\server\\share\\folder\\file.txt",
  2455. ]
  2456. for path in test_cases:
  2457. # Just verify os.path.dirname handles these without errors
  2458. parent = os.path.dirname(path)
  2459. # We're not creating these directories, just testing the logic doesn't fail
  2460. self.assertIsInstance(parent, bytes)