2
0

test_index.py 86 KB

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