2
0

test_index.py 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435
  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 public 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_git_submodule(self) -> None:
  522. repo_dir = tempfile.mkdtemp()
  523. self.addCleanup(shutil.rmtree, repo_dir)
  524. with Repo.init(repo_dir) as repo:
  525. filea = Blob.from_string(b"file alalala")
  526. subtree = Tree()
  527. subtree[b"a"] = (stat.S_IFREG | 0o644, filea.id)
  528. c = Commit()
  529. c.tree = subtree.id
  530. c.committer = c.author = b"Somebody <somebody@example.com>"
  531. c.commit_time = c.author_time = 42342
  532. c.commit_timezone = c.author_timezone = 0
  533. c.parents = []
  534. c.message = b"Subcommit"
  535. tree = Tree()
  536. tree[b"c"] = (S_IFGITLINK, c.id)
  537. repo.object_store.add_objects([(o, None) for o in [tree]])
  538. build_index_from_tree(
  539. repo.path, repo.index_path(), repo.object_store, tree.id
  540. )
  541. # Verify index entries
  542. index = repo.open_index()
  543. self.assertEqual(len(index), 1)
  544. # filea
  545. apath = os.path.join(repo.path, "c/a")
  546. self.assertFalse(os.path.exists(apath))
  547. # dir c
  548. cpath = os.path.join(repo.path, "c")
  549. self.assertTrue(os.path.isdir(cpath))
  550. self.assertEqual(index[b"c"].mode, S_IFGITLINK) # mode
  551. self.assertEqual(index[b"c"].sha, c.id) # sha
  552. def test_git_submodule_exists(self) -> None:
  553. repo_dir = tempfile.mkdtemp()
  554. self.addCleanup(shutil.rmtree, repo_dir)
  555. with Repo.init(repo_dir) as repo:
  556. filea = Blob.from_string(b"file alalala")
  557. subtree = Tree()
  558. subtree[b"a"] = (stat.S_IFREG | 0o644, filea.id)
  559. c = Commit()
  560. c.tree = subtree.id
  561. c.committer = c.author = b"Somebody <somebody@example.com>"
  562. c.commit_time = c.author_time = 42342
  563. c.commit_timezone = c.author_timezone = 0
  564. c.parents = []
  565. c.message = b"Subcommit"
  566. tree = Tree()
  567. tree[b"c"] = (S_IFGITLINK, c.id)
  568. os.mkdir(os.path.join(repo_dir, "c"))
  569. repo.object_store.add_objects([(o, None) for o in [tree]])
  570. build_index_from_tree(
  571. repo.path, repo.index_path(), repo.object_store, tree.id
  572. )
  573. # Verify index entries
  574. index = repo.open_index()
  575. self.assertEqual(len(index), 1)
  576. # filea
  577. apath = os.path.join(repo.path, "c/a")
  578. self.assertFalse(os.path.exists(apath))
  579. # dir c
  580. cpath = os.path.join(repo.path, "c")
  581. self.assertTrue(os.path.isdir(cpath))
  582. self.assertEqual(index[b"c"].mode, S_IFGITLINK) # mode
  583. self.assertEqual(index[b"c"].sha, c.id) # sha
  584. def test_with_line_ending_normalization(self) -> None:
  585. """Test that build_index_from_tree applies line-ending normalization."""
  586. repo_dir = tempfile.mkdtemp()
  587. self.addCleanup(shutil.rmtree, repo_dir)
  588. from dulwich.line_ending import BlobNormalizer
  589. with Repo.init(repo_dir) as repo:
  590. # Set up autocrlf config
  591. config = repo.get_config()
  592. config.set((b"core",), b"autocrlf", b"true")
  593. config.write_to_path()
  594. # Create blob with LF line endings
  595. content_lf = b"line1\nline2\nline3\n"
  596. blob = Blob.from_string(content_lf)
  597. tree = Tree()
  598. tree[b"test.txt"] = (stat.S_IFREG | 0o644, blob.id)
  599. repo.object_store.add_objects([(blob, None), (tree, None)])
  600. # Create blob normalizer
  601. blob_normalizer = BlobNormalizer(config, {})
  602. # Build index with normalization
  603. build_index_from_tree(
  604. repo.path,
  605. repo.index_path(),
  606. repo.object_store,
  607. tree.id,
  608. blob_normalizer=blob_normalizer,
  609. )
  610. # On Windows with autocrlf=true, file should have CRLF line endings
  611. test_file = os.path.join(repo.path, "test.txt")
  612. with open(test_file, "rb") as f:
  613. content = f.read()
  614. # autocrlf=true means LF -> CRLF on checkout (on all platforms for testing)
  615. expected_content = b"line1\r\nline2\r\nline3\r\n"
  616. self.assertEqual(content, expected_content)
  617. class GetUnstagedChangesTests(TestCase):
  618. def test_get_unstaged_changes(self) -> None:
  619. """Unit test for get_unstaged_changes."""
  620. repo_dir = tempfile.mkdtemp()
  621. self.addCleanup(shutil.rmtree, repo_dir)
  622. with Repo.init(repo_dir) as repo:
  623. # Commit a dummy file then modify it
  624. foo1_fullpath = os.path.join(repo_dir, "foo1")
  625. with open(foo1_fullpath, "wb") as f:
  626. f.write(b"origstuff")
  627. foo2_fullpath = os.path.join(repo_dir, "foo2")
  628. with open(foo2_fullpath, "wb") as f:
  629. f.write(b"origstuff")
  630. repo.stage(["foo1", "foo2"])
  631. repo.do_commit(
  632. b"test status",
  633. author=b"author <email>",
  634. committer=b"committer <email>",
  635. )
  636. with open(foo1_fullpath, "wb") as f:
  637. f.write(b"newstuff")
  638. # modify access and modify time of path
  639. os.utime(foo1_fullpath, (0, 0))
  640. changes = get_unstaged_changes(repo.open_index(), repo_dir)
  641. self.assertEqual(list(changes), [b"foo1"])
  642. def test_get_unstaged_deleted_changes(self) -> None:
  643. """Unit test for get_unstaged_changes."""
  644. repo_dir = tempfile.mkdtemp()
  645. self.addCleanup(shutil.rmtree, repo_dir)
  646. with Repo.init(repo_dir) as repo:
  647. # Commit a dummy file then remove it
  648. foo1_fullpath = os.path.join(repo_dir, "foo1")
  649. with open(foo1_fullpath, "wb") as f:
  650. f.write(b"origstuff")
  651. repo.stage(["foo1"])
  652. repo.do_commit(
  653. b"test status",
  654. author=b"author <email>",
  655. committer=b"committer <email>",
  656. )
  657. os.unlink(foo1_fullpath)
  658. changes = get_unstaged_changes(repo.open_index(), repo_dir)
  659. self.assertEqual(list(changes), [b"foo1"])
  660. def test_get_unstaged_changes_removed_replaced_by_directory(self) -> None:
  661. """Unit test for get_unstaged_changes."""
  662. repo_dir = tempfile.mkdtemp()
  663. self.addCleanup(shutil.rmtree, repo_dir)
  664. with Repo.init(repo_dir) as repo:
  665. # Commit a dummy file then modify it
  666. foo1_fullpath = os.path.join(repo_dir, "foo1")
  667. with open(foo1_fullpath, "wb") as f:
  668. f.write(b"origstuff")
  669. repo.stage(["foo1"])
  670. repo.do_commit(
  671. b"test status",
  672. author=b"author <email>",
  673. committer=b"committer <email>",
  674. )
  675. os.remove(foo1_fullpath)
  676. os.mkdir(foo1_fullpath)
  677. changes = get_unstaged_changes(repo.open_index(), repo_dir)
  678. self.assertEqual(list(changes), [b"foo1"])
  679. @skipIf(not can_symlink(), "Requires symlink support")
  680. def test_get_unstaged_changes_removed_replaced_by_link(self) -> None:
  681. """Unit test for get_unstaged_changes."""
  682. repo_dir = tempfile.mkdtemp()
  683. self.addCleanup(shutil.rmtree, repo_dir)
  684. with Repo.init(repo_dir) as repo:
  685. # Commit a dummy file then modify it
  686. foo1_fullpath = os.path.join(repo_dir, "foo1")
  687. with open(foo1_fullpath, "wb") as f:
  688. f.write(b"origstuff")
  689. repo.stage(["foo1"])
  690. repo.do_commit(
  691. b"test status",
  692. author=b"author <email>",
  693. committer=b"committer <email>",
  694. )
  695. os.remove(foo1_fullpath)
  696. os.symlink(os.path.dirname(foo1_fullpath), foo1_fullpath)
  697. changes = get_unstaged_changes(repo.open_index(), repo_dir)
  698. self.assertEqual(list(changes), [b"foo1"])
  699. class TestValidatePathElement(TestCase):
  700. def test_default(self) -> None:
  701. self.assertTrue(validate_path_element_default(b"bla"))
  702. self.assertTrue(validate_path_element_default(b".bla"))
  703. self.assertFalse(validate_path_element_default(b".git"))
  704. self.assertFalse(validate_path_element_default(b".giT"))
  705. self.assertFalse(validate_path_element_default(b".."))
  706. self.assertTrue(validate_path_element_default(b"git~1"))
  707. def test_ntfs(self) -> None:
  708. self.assertTrue(validate_path_element_ntfs(b"bla"))
  709. self.assertTrue(validate_path_element_ntfs(b".bla"))
  710. self.assertFalse(validate_path_element_ntfs(b".git"))
  711. self.assertFalse(validate_path_element_ntfs(b".giT"))
  712. self.assertFalse(validate_path_element_ntfs(b".."))
  713. self.assertFalse(validate_path_element_ntfs(b"git~1"))
  714. def test_hfs(self) -> None:
  715. # Normal paths should pass
  716. self.assertTrue(validate_path_element_hfs(b"bla"))
  717. self.assertTrue(validate_path_element_hfs(b".bla"))
  718. # Basic .git variations should fail
  719. self.assertFalse(validate_path_element_hfs(b".git"))
  720. self.assertFalse(validate_path_element_hfs(b".giT"))
  721. self.assertFalse(validate_path_element_hfs(b".GIT"))
  722. self.assertFalse(validate_path_element_hfs(b".."))
  723. # git~1 should also fail on HFS+
  724. self.assertFalse(validate_path_element_hfs(b"git~1"))
  725. # Test HFS+ Unicode normalization attacks
  726. # .g\u200cit (zero-width non-joiner)
  727. self.assertFalse(validate_path_element_hfs(b".g\xe2\x80\x8cit"))
  728. # .gi\u200dt (zero-width joiner)
  729. self.assertFalse(validate_path_element_hfs(b".gi\xe2\x80\x8dt"))
  730. # Test other ignorable characters
  731. # .g\ufeffit (zero-width no-break space)
  732. self.assertFalse(validate_path_element_hfs(b".g\xef\xbb\xbfit"))
  733. # Valid Unicode that shouldn't be confused with .git
  734. self.assertTrue(validate_path_element_hfs(b".g\xc3\xaft")) # .gït
  735. self.assertTrue(validate_path_element_hfs(b"git")) # git without dot
  736. class TestTreeFSPathConversion(TestCase):
  737. def test_tree_to_fs_path(self) -> None:
  738. tree_path = "délwíçh/foo".encode()
  739. fs_path = _tree_to_fs_path(b"/prefix/path", tree_path)
  740. self.assertEqual(
  741. fs_path,
  742. os.fsencode(os.path.join("/prefix/path", "délwíçh", "foo")),
  743. )
  744. def test_tree_to_fs_path_windows_separator(self) -> None:
  745. tree_path = b"path/with/slash"
  746. original_sep = os.sep.encode("ascii")
  747. # Temporarily modify os_sep_bytes to test Windows path conversion
  748. # This simulates Windows behavior on all platforms for testing
  749. import dulwich.index
  750. dulwich.index.os_sep_bytes = b"\\"
  751. self.addCleanup(setattr, dulwich.index, "os_sep_bytes", original_sep)
  752. fs_path = _tree_to_fs_path(b"/prefix/path", tree_path)
  753. # The function should join the prefix path with the converted tree path
  754. # The expected behavior is that the path separators in the tree_path are
  755. # converted to the platform-specific separator (which we've set to backslash)
  756. expected_path = os.path.join(b"/prefix/path", b"path\\with\\slash")
  757. self.assertEqual(fs_path, expected_path)
  758. def test_fs_to_tree_path_str(self) -> None:
  759. fs_path = os.path.join(os.path.join("délwíçh", "foo"))
  760. tree_path = _fs_to_tree_path(fs_path)
  761. self.assertEqual(tree_path, "délwíçh/foo".encode())
  762. def test_fs_to_tree_path_bytes(self) -> None:
  763. fs_path = os.path.join(os.fsencode(os.path.join("délwíçh", "foo")))
  764. tree_path = _fs_to_tree_path(fs_path)
  765. self.assertEqual(tree_path, "délwíçh/foo".encode())
  766. def test_fs_to_tree_path_windows_separator(self) -> None:
  767. # Test conversion of Windows paths to tree paths
  768. fs_path = b"path\\with\\backslash"
  769. original_sep = os.sep.encode("ascii")
  770. # Temporarily modify os_sep_bytes to test Windows path conversion
  771. import dulwich.index
  772. dulwich.index.os_sep_bytes = b"\\"
  773. self.addCleanup(setattr, dulwich.index, "os_sep_bytes", original_sep)
  774. tree_path = _fs_to_tree_path(fs_path)
  775. self.assertEqual(tree_path, b"path/with/backslash")
  776. class TestIndexEntryFromPath(TestCase):
  777. def setUp(self):
  778. self.tempdir = tempfile.mkdtemp()
  779. self.addCleanup(shutil.rmtree, self.tempdir)
  780. def test_index_entry_from_path_file(self) -> None:
  781. """Test creating index entry from a regular file."""
  782. # Create a test file
  783. test_file = os.path.join(self.tempdir, "testfile")
  784. with open(test_file, "wb") as f:
  785. f.write(b"test content")
  786. # Get the index entry
  787. entry = index_entry_from_path(os.fsencode(test_file))
  788. # Verify the entry was created with the right mode
  789. self.assertIsNotNone(entry)
  790. self.assertEqual(cleanup_mode(os.stat(test_file).st_mode), entry.mode)
  791. @skipIf(not can_symlink(), "Requires symlink support")
  792. def test_index_entry_from_path_symlink(self) -> None:
  793. """Test creating index entry from a symlink."""
  794. # Create a target file
  795. target_file = os.path.join(self.tempdir, "target")
  796. with open(target_file, "wb") as f:
  797. f.write(b"target content")
  798. # Create a symlink
  799. link_file = os.path.join(self.tempdir, "symlink")
  800. os.symlink(target_file, link_file)
  801. # Get the index entry
  802. entry = index_entry_from_path(os.fsencode(link_file))
  803. # Verify the entry was created with the right mode
  804. self.assertIsNotNone(entry)
  805. self.assertEqual(cleanup_mode(os.lstat(link_file).st_mode), entry.mode)
  806. def test_index_entry_from_path_directory(self) -> None:
  807. """Test creating index entry from a directory (should return None)."""
  808. # Create a directory
  809. test_dir = os.path.join(self.tempdir, "testdir")
  810. os.mkdir(test_dir)
  811. # Get the index entry for a directory
  812. entry = index_entry_from_path(os.fsencode(test_dir))
  813. # Should return None for regular directories
  814. self.assertIsNone(entry)
  815. def test_index_entry_from_directory_regular(self) -> None:
  816. """Test index_entry_from_directory with a regular directory."""
  817. # Create a directory
  818. test_dir = os.path.join(self.tempdir, "testdir")
  819. os.mkdir(test_dir)
  820. # Get stat for the directory
  821. st = os.lstat(test_dir)
  822. # Get the index entry for a regular directory
  823. entry = index_entry_from_directory(st, os.fsencode(test_dir))
  824. # Should return None for regular directories
  825. self.assertIsNone(entry)
  826. def test_index_entry_from_directory_git_submodule(self) -> None:
  827. """Test index_entry_from_directory with a Git submodule."""
  828. # Create a git repository that will be a submodule
  829. sub_repo_dir = os.path.join(self.tempdir, "subrepo")
  830. os.mkdir(sub_repo_dir)
  831. # Create the .git directory to make it look like a git repo
  832. git_dir = os.path.join(sub_repo_dir, ".git")
  833. os.mkdir(git_dir)
  834. # Create HEAD file with a fake commit SHA
  835. head_sha = b"1234567890" * 4 # 40-char fake SHA
  836. with open(os.path.join(git_dir, "HEAD"), "wb") as f:
  837. f.write(head_sha)
  838. # Get stat for the submodule directory
  839. st = os.lstat(sub_repo_dir)
  840. # Get the index entry for a git submodule directory
  841. entry = index_entry_from_directory(st, os.fsencode(sub_repo_dir))
  842. # Since we don't have a proper git setup, this might still return None
  843. # This test just ensures the code path is executed
  844. if entry is not None:
  845. # If an entry is returned, it should have the gitlink mode
  846. self.assertEqual(entry.mode, S_IFGITLINK)
  847. def test_index_entry_from_path_with_object_store(self) -> None:
  848. """Test creating index entry with object store."""
  849. # Create a test file
  850. test_file = os.path.join(self.tempdir, "testfile")
  851. with open(test_file, "wb") as f:
  852. f.write(b"test content")
  853. # Create a memory object store
  854. object_store = MemoryObjectStore()
  855. # Get the index entry and add to object store
  856. entry = index_entry_from_path(os.fsencode(test_file), object_store)
  857. # Verify we can access the blob from the object store
  858. self.assertIsNotNone(entry)
  859. blob = object_store[entry.sha]
  860. self.assertEqual(b"test content", blob.data)
  861. def test_iter_fresh_entries(self) -> None:
  862. """Test iterating over fresh entries."""
  863. # Create some test files
  864. file1 = os.path.join(self.tempdir, "file1")
  865. with open(file1, "wb") as f:
  866. f.write(b"file1 content")
  867. file2 = os.path.join(self.tempdir, "file2")
  868. with open(file2, "wb") as f:
  869. f.write(b"file2 content")
  870. # Create a memory object store
  871. object_store = MemoryObjectStore()
  872. # Get fresh entries
  873. paths = [b"file1", b"file2", b"nonexistent"]
  874. entries = dict(
  875. iter_fresh_entries(paths, os.fsencode(self.tempdir), object_store)
  876. )
  877. # Verify both files got entries but nonexistent file is None
  878. self.assertIn(b"file1", entries)
  879. self.assertIn(b"file2", entries)
  880. self.assertIn(b"nonexistent", entries)
  881. self.assertIsNotNone(entries[b"file1"])
  882. self.assertIsNotNone(entries[b"file2"])
  883. self.assertIsNone(entries[b"nonexistent"])
  884. # Check that blobs were added to object store
  885. blob1 = object_store[entries[b"file1"].sha]
  886. self.assertEqual(b"file1 content", blob1.data)
  887. blob2 = object_store[entries[b"file2"].sha]
  888. self.assertEqual(b"file2 content", blob2.data)
  889. def test_read_submodule_head(self) -> None:
  890. """Test reading the HEAD of a submodule."""
  891. from dulwich.index import read_submodule_head
  892. # Create a test repo that will be our "submodule"
  893. sub_repo_dir = os.path.join(self.tempdir, "subrepo")
  894. os.mkdir(sub_repo_dir)
  895. submodule_repo = Repo.init(sub_repo_dir)
  896. # Create a file and commit it to establish a HEAD
  897. test_file = os.path.join(sub_repo_dir, "testfile")
  898. with open(test_file, "wb") as f:
  899. f.write(b"test content")
  900. submodule_repo.stage(["testfile"])
  901. commit_id = submodule_repo.do_commit(b"Test commit for submodule")
  902. # Test reading the HEAD
  903. head_sha = read_submodule_head(sub_repo_dir)
  904. self.assertEqual(commit_id, head_sha)
  905. # Test with bytes path
  906. head_sha_bytes = read_submodule_head(os.fsencode(sub_repo_dir))
  907. self.assertEqual(commit_id, head_sha_bytes)
  908. # Test with non-existent path
  909. non_repo_dir = os.path.join(self.tempdir, "nonrepo")
  910. os.mkdir(non_repo_dir)
  911. self.assertIsNone(read_submodule_head(non_repo_dir))
  912. # Test with path that doesn't have a .git directory
  913. not_git_dir = os.path.join(self.tempdir, "notgit")
  914. os.mkdir(not_git_dir)
  915. self.assertIsNone(read_submodule_head(not_git_dir))
  916. def test_has_directory_changed(self) -> None:
  917. """Test checking if a directory has changed."""
  918. from dulwich.index import IndexEntry, _has_directory_changed
  919. # Setup mock IndexEntry
  920. mock_entry = IndexEntry(
  921. (1230680220, 0),
  922. (1230680220, 0),
  923. 2050,
  924. 3761020,
  925. 33188,
  926. 1000,
  927. 1000,
  928. 0,
  929. b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391",
  930. 0,
  931. 0,
  932. )
  933. # Test with a regular directory (not a submodule)
  934. reg_dir = os.path.join(self.tempdir, "regular_dir")
  935. os.mkdir(reg_dir)
  936. # Should return True for regular directory
  937. self.assertTrue(_has_directory_changed(os.fsencode(reg_dir), mock_entry))
  938. # Create a git repository to test submodule scenarios
  939. sub_repo_dir = os.path.join(self.tempdir, "subrepo")
  940. os.mkdir(sub_repo_dir)
  941. submodule_repo = Repo.init(sub_repo_dir)
  942. # Create a file and commit it to establish a HEAD
  943. test_file = os.path.join(sub_repo_dir, "testfile")
  944. with open(test_file, "wb") as f:
  945. f.write(b"test content")
  946. submodule_repo.stage(["testfile"])
  947. commit_id = submodule_repo.do_commit(b"Test commit for submodule")
  948. # Create an entry with the correct commit SHA
  949. correct_entry = IndexEntry(
  950. (1230680220, 0),
  951. (1230680220, 0),
  952. 2050,
  953. 3761020,
  954. 33188,
  955. 1000,
  956. 1000,
  957. 0,
  958. commit_id,
  959. 0,
  960. 0,
  961. )
  962. # Create an entry with an incorrect commit SHA
  963. incorrect_entry = IndexEntry(
  964. (1230680220, 0),
  965. (1230680220, 0),
  966. 2050,
  967. 3761020,
  968. 33188,
  969. 1000,
  970. 1000,
  971. 0,
  972. b"0000000000000000000000000000000000000000",
  973. 0,
  974. 0,
  975. )
  976. # Should return False for submodule with correct SHA
  977. self.assertFalse(
  978. _has_directory_changed(os.fsencode(sub_repo_dir), correct_entry)
  979. )
  980. # Should return True for submodule with incorrect SHA
  981. self.assertTrue(
  982. _has_directory_changed(os.fsencode(sub_repo_dir), incorrect_entry)
  983. )
  984. def test_get_unstaged_changes(self) -> None:
  985. """Test detecting unstaged changes in a working tree."""
  986. from dulwich.index import (
  987. ConflictedIndexEntry,
  988. Index,
  989. IndexEntry,
  990. get_unstaged_changes,
  991. )
  992. # Create a test repo
  993. repo_dir = tempfile.mkdtemp()
  994. self.addCleanup(shutil.rmtree, repo_dir)
  995. # Create test index
  996. index = Index(os.path.join(repo_dir, "index"))
  997. # Create an actual hash of our test content
  998. from dulwich.objects import Blob
  999. test_blob = Blob()
  1000. test_blob.data = b"initial content"
  1001. # Create some test files with known contents
  1002. file1_path = os.path.join(repo_dir, "file1")
  1003. with open(file1_path, "wb") as f:
  1004. f.write(b"initial content")
  1005. file2_path = os.path.join(repo_dir, "file2")
  1006. with open(file2_path, "wb") as f:
  1007. f.write(b"initial content")
  1008. # Add them to index
  1009. entry1 = IndexEntry(
  1010. (1230680220, 0),
  1011. (1230680220, 0),
  1012. 2050,
  1013. 3761020,
  1014. 33188,
  1015. 1000,
  1016. 1000,
  1017. 0,
  1018. b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", # Not matching actual content
  1019. 0,
  1020. 0,
  1021. )
  1022. entry2 = IndexEntry(
  1023. (1230680220, 0),
  1024. (1230680220, 0),
  1025. 2050,
  1026. 3761020,
  1027. 33188,
  1028. 1000,
  1029. 1000,
  1030. 0,
  1031. test_blob.id, # Will be content's real hash
  1032. 0,
  1033. 0,
  1034. )
  1035. # Add a file that has a conflict
  1036. entry_conflict = ConflictedIndexEntry(b"conflict", {0: None, 1: None, 2: None})
  1037. index._byname = {
  1038. b"file1": entry1,
  1039. b"file2": entry2,
  1040. b"file3": IndexEntry(
  1041. (1230680220, 0),
  1042. (1230680220, 0),
  1043. 2050,
  1044. 3761020,
  1045. 33188,
  1046. 1000,
  1047. 1000,
  1048. 0,
  1049. b"0000000000000000000000000000000000000000",
  1050. 0,
  1051. 0,
  1052. ),
  1053. b"conflict": entry_conflict,
  1054. }
  1055. # Get unstaged changes
  1056. changes = list(get_unstaged_changes(index, repo_dir))
  1057. # File1 should be unstaged (content doesn't match hash)
  1058. # File3 doesn't exist (deleted)
  1059. # Conflict is always unstaged
  1060. self.assertEqual(sorted(changes), [b"conflict", b"file1", b"file3"])
  1061. # Create directory where there should be a file
  1062. os.mkdir(os.path.join(repo_dir, "file4"))
  1063. index._byname[b"file4"] = entry1
  1064. # Get unstaged changes again
  1065. changes = list(get_unstaged_changes(index, repo_dir))
  1066. # Now file4 should also be unstaged because it's a directory instead of a file
  1067. self.assertEqual(sorted(changes), [b"conflict", b"file1", b"file3", b"file4"])
  1068. # Create a custom blob filter function
  1069. def filter_blob_callback(blob, path):
  1070. # Modify blob to make it look changed
  1071. blob.data = b"modified " + blob.data
  1072. return blob
  1073. # Get unstaged changes with blob filter
  1074. changes = list(get_unstaged_changes(index, repo_dir, filter_blob_callback))
  1075. # Now both file1 and file2 should be unstaged due to the filter
  1076. self.assertEqual(
  1077. sorted(changes), [b"conflict", b"file1", b"file2", b"file3", b"file4"]
  1078. )
  1079. class TestManyFilesFeature(TestCase):
  1080. """Tests for the manyFiles feature (index version 4 and skipHash)."""
  1081. def setUp(self):
  1082. self.tempdir = tempfile.mkdtemp()
  1083. self.addCleanup(shutil.rmtree, self.tempdir)
  1084. def test_index_version_4_parsing(self):
  1085. """Test that index version 4 files can be parsed."""
  1086. index_path = os.path.join(self.tempdir, "index")
  1087. # Create an index with version 4
  1088. index = Index(index_path, read=False, version=4)
  1089. # Add some entries
  1090. entry = IndexEntry(
  1091. ctime=(1234567890, 0),
  1092. mtime=(1234567890, 0),
  1093. dev=1,
  1094. ino=1,
  1095. mode=0o100644,
  1096. uid=1000,
  1097. gid=1000,
  1098. size=5,
  1099. sha=b"0" * 40,
  1100. )
  1101. index[b"test.txt"] = entry
  1102. # Write and read back
  1103. index.write()
  1104. # Read the index back
  1105. index2 = Index(index_path)
  1106. self.assertEqual(index2._version, 4)
  1107. self.assertIn(b"test.txt", index2)
  1108. def test_skip_hash_feature(self):
  1109. """Test that skipHash feature works correctly."""
  1110. index_path = os.path.join(self.tempdir, "index")
  1111. # Create an index with skipHash enabled
  1112. index = Index(index_path, read=False, skip_hash=True)
  1113. # Add some entries
  1114. entry = IndexEntry(
  1115. ctime=(1234567890, 0),
  1116. mtime=(1234567890, 0),
  1117. dev=1,
  1118. ino=1,
  1119. mode=0o100644,
  1120. uid=1000,
  1121. gid=1000,
  1122. size=5,
  1123. sha=b"0" * 40,
  1124. )
  1125. index[b"test.txt"] = entry
  1126. # Write the index
  1127. index.write()
  1128. # Verify the file was written with zero hash
  1129. with open(index_path, "rb") as f:
  1130. f.seek(-20, 2) # Seek to last 20 bytes
  1131. trailing_hash = f.read(20)
  1132. self.assertEqual(trailing_hash, b"\x00" * 20)
  1133. # Verify we can still read it back
  1134. index2 = Index(index_path)
  1135. self.assertIn(b"test.txt", index2)
  1136. def test_version_4_no_padding(self):
  1137. """Test that version 4 entries have no padding."""
  1138. # Create entries with names that would show compression benefits
  1139. entries = [
  1140. SerializedIndexEntry(
  1141. name=b"src/main/java/com/example/Service.java",
  1142. ctime=(1234567890, 0),
  1143. mtime=(1234567890, 0),
  1144. dev=1,
  1145. ino=1,
  1146. mode=0o100644,
  1147. uid=1000,
  1148. gid=1000,
  1149. size=5,
  1150. sha=b"0" * 40,
  1151. flags=0,
  1152. extended_flags=0,
  1153. ),
  1154. SerializedIndexEntry(
  1155. name=b"src/main/java/com/example/Controller.java",
  1156. ctime=(1234567890, 0),
  1157. mtime=(1234567890, 0),
  1158. dev=1,
  1159. ino=2,
  1160. mode=0o100644,
  1161. uid=1000,
  1162. gid=1000,
  1163. size=5,
  1164. sha=b"1" * 40,
  1165. flags=0,
  1166. extended_flags=0,
  1167. ),
  1168. ]
  1169. # Test version 2 (with padding, full paths)
  1170. buf_v2 = BytesIO()
  1171. from dulwich.index import write_cache_entry
  1172. previous_path = b""
  1173. for entry in entries:
  1174. # Set proper flags for v2
  1175. entry_v2 = SerializedIndexEntry(
  1176. entry.name,
  1177. entry.ctime,
  1178. entry.mtime,
  1179. entry.dev,
  1180. entry.ino,
  1181. entry.mode,
  1182. entry.uid,
  1183. entry.gid,
  1184. entry.size,
  1185. entry.sha,
  1186. len(entry.name),
  1187. entry.extended_flags,
  1188. )
  1189. write_cache_entry(buf_v2, entry_v2, version=2, previous_path=previous_path)
  1190. previous_path = entry.name
  1191. v2_data = buf_v2.getvalue()
  1192. # Test version 4 (path compression, no padding)
  1193. buf_v4 = BytesIO()
  1194. previous_path = b""
  1195. for entry in entries:
  1196. write_cache_entry(buf_v4, entry, version=4, previous_path=previous_path)
  1197. previous_path = entry.name
  1198. v4_data = buf_v4.getvalue()
  1199. # Version 4 should be shorter due to compression and no padding
  1200. self.assertLess(len(v4_data), len(v2_data))
  1201. # Both should parse correctly
  1202. buf_v2.seek(0)
  1203. from dulwich.index import read_cache_entry
  1204. previous_path = b""
  1205. parsed_v2_entries = []
  1206. for _ in entries:
  1207. parsed = read_cache_entry(buf_v2, version=2, previous_path=previous_path)
  1208. parsed_v2_entries.append(parsed)
  1209. previous_path = parsed.name
  1210. buf_v4.seek(0)
  1211. previous_path = b""
  1212. parsed_v4_entries = []
  1213. for _ in entries:
  1214. parsed = read_cache_entry(buf_v4, version=4, previous_path=previous_path)
  1215. parsed_v4_entries.append(parsed)
  1216. previous_path = parsed.name
  1217. # Both should have the same paths
  1218. for v2_entry, v4_entry in zip(parsed_v2_entries, parsed_v4_entries):
  1219. self.assertEqual(v2_entry.name, v4_entry.name)
  1220. self.assertEqual(v2_entry.sha, v4_entry.sha)
  1221. class TestManyFilesRepoIntegration(TestCase):
  1222. """Tests for manyFiles feature integration with Repo."""
  1223. def setUp(self):
  1224. self.tempdir = tempfile.mkdtemp()
  1225. self.addCleanup(shutil.rmtree, self.tempdir)
  1226. def test_repo_with_manyfiles_config(self):
  1227. """Test that a repository with feature.manyFiles=true uses the right settings."""
  1228. # Create a new repository
  1229. repo = Repo.init(self.tempdir)
  1230. # Set feature.manyFiles=true in config
  1231. config = repo.get_config()
  1232. config.set(b"feature", b"manyFiles", b"true")
  1233. config.write_to_path()
  1234. # Open the index - should have skipHash enabled and version 4
  1235. index = repo.open_index()
  1236. self.assertTrue(index._skip_hash)
  1237. self.assertEqual(index._version, 4)
  1238. def test_repo_with_explicit_index_settings(self):
  1239. """Test that explicit index.version and index.skipHash work."""
  1240. # Create a new repository
  1241. repo = Repo.init(self.tempdir)
  1242. # Set explicit index settings
  1243. config = repo.get_config()
  1244. config.set(b"index", b"version", b"3")
  1245. config.set(b"index", b"skipHash", b"false")
  1246. config.write_to_path()
  1247. # Open the index - should respect explicit settings
  1248. index = repo.open_index()
  1249. self.assertFalse(index._skip_hash)
  1250. self.assertEqual(index._version, 3)
  1251. class TestPathPrefixCompression(TestCase):
  1252. """Tests for index version 4 path prefix compression."""
  1253. def setUp(self):
  1254. self.tempdir = tempfile.mkdtemp()
  1255. self.addCleanup(shutil.rmtree, self.tempdir)
  1256. def test_varint_encoding_decoding(self):
  1257. """Test variable-width integer encoding and decoding."""
  1258. test_values = [0, 1, 127, 128, 255, 256, 16383, 16384, 65535, 65536]
  1259. for value in test_values:
  1260. encoded = _encode_varint(value)
  1261. decoded, _ = _decode_varint(encoded, 0)
  1262. self.assertEqual(value, decoded, f"Failed for value {value}")
  1263. def test_path_compression_simple(self):
  1264. """Test simple path compression cases."""
  1265. # Test case 1: No common prefix
  1266. compressed = _compress_path(b"file1.txt", b"")
  1267. decompressed, _ = _decompress_path(compressed, 0, b"")
  1268. self.assertEqual(b"file1.txt", decompressed)
  1269. # Test case 2: Common prefix
  1270. compressed = _compress_path(b"src/file2.txt", b"src/file1.txt")
  1271. decompressed, _ = _decompress_path(compressed, 0, b"src/file1.txt")
  1272. self.assertEqual(b"src/file2.txt", decompressed)
  1273. # Test case 3: Completely different paths
  1274. compressed = _compress_path(b"docs/readme.md", b"src/file1.txt")
  1275. decompressed, _ = _decompress_path(compressed, 0, b"src/file1.txt")
  1276. self.assertEqual(b"docs/readme.md", decompressed)
  1277. def test_path_compression_deep_directories(self):
  1278. """Test compression with deep directory structures."""
  1279. path1 = b"src/main/java/com/example/service/UserService.java"
  1280. path2 = b"src/main/java/com/example/service/OrderService.java"
  1281. path3 = b"src/main/java/com/example/model/User.java"
  1282. # Compress path2 relative to path1
  1283. compressed = _compress_path(path2, path1)
  1284. decompressed, _ = _decompress_path(compressed, 0, path1)
  1285. self.assertEqual(path2, decompressed)
  1286. # Compress path3 relative to path2
  1287. compressed = _compress_path(path3, path2)
  1288. decompressed, _ = _decompress_path(compressed, 0, path2)
  1289. self.assertEqual(path3, decompressed)
  1290. def test_index_version_4_with_compression(self):
  1291. """Test full index version 4 write/read with path compression."""
  1292. index_path = os.path.join(self.tempdir, "index")
  1293. # Create an index with version 4
  1294. index = Index(index_path, read=False, version=4)
  1295. # Add multiple entries with common prefixes
  1296. paths = [
  1297. b"src/main/java/App.java",
  1298. b"src/main/java/Utils.java",
  1299. b"src/main/resources/config.properties",
  1300. b"src/test/java/AppTest.java",
  1301. b"docs/README.md",
  1302. b"docs/INSTALL.md",
  1303. ]
  1304. for i, path in enumerate(paths):
  1305. entry = IndexEntry(
  1306. ctime=(1234567890, 0),
  1307. mtime=(1234567890, 0),
  1308. dev=1,
  1309. ino=i + 1,
  1310. mode=0o100644,
  1311. uid=1000,
  1312. gid=1000,
  1313. size=10,
  1314. sha=f"{i:040d}".encode(),
  1315. )
  1316. index[path] = entry
  1317. # Write and read back
  1318. index.write()
  1319. # Read the index back
  1320. index2 = Index(index_path)
  1321. self.assertEqual(index2._version, 4)
  1322. # Verify all paths were preserved correctly
  1323. for path in paths:
  1324. self.assertIn(path, index2)
  1325. # Verify the index file is smaller than version 2 would be
  1326. with open(index_path, "rb") as f:
  1327. v4_size = len(f.read())
  1328. # Create equivalent version 2 index for comparison
  1329. index_v2_path = os.path.join(self.tempdir, "index_v2")
  1330. index_v2 = Index(index_v2_path, read=False, version=2)
  1331. for path in paths:
  1332. entry = IndexEntry(
  1333. ctime=(1234567890, 0),
  1334. mtime=(1234567890, 0),
  1335. dev=1,
  1336. ino=1,
  1337. mode=0o100644,
  1338. uid=1000,
  1339. gid=1000,
  1340. size=10,
  1341. sha=b"0" * 40,
  1342. )
  1343. index_v2[path] = entry
  1344. index_v2.write()
  1345. with open(index_v2_path, "rb") as f:
  1346. v2_size = len(f.read())
  1347. # Version 4 should be smaller due to compression
  1348. self.assertLess(
  1349. v4_size, v2_size, "Version 4 index should be smaller than version 2"
  1350. )
  1351. def test_path_compression_edge_cases(self):
  1352. """Test edge cases in path compression."""
  1353. # Empty paths
  1354. compressed = _compress_path(b"", b"")
  1355. decompressed, _ = _decompress_path(compressed, 0, b"")
  1356. self.assertEqual(b"", decompressed)
  1357. # Path identical to previous
  1358. compressed = _compress_path(b"same.txt", b"same.txt")
  1359. decompressed, _ = _decompress_path(compressed, 0, b"same.txt")
  1360. self.assertEqual(b"same.txt", decompressed)
  1361. # Path shorter than previous
  1362. compressed = _compress_path(b"short", b"very/long/path/file.txt")
  1363. decompressed, _ = _decompress_path(compressed, 0, b"very/long/path/file.txt")
  1364. self.assertEqual(b"short", decompressed)
  1365. class TestUpdateWorkingTree(TestCase):
  1366. def setUp(self):
  1367. self.tempdir = tempfile.mkdtemp()
  1368. def cleanup_tempdir():
  1369. """Remove tempdir, handling read-only files on Windows."""
  1370. def remove_readonly(func, path, excinfo):
  1371. """Error handler for Windows read-only files."""
  1372. import stat
  1373. if sys.platform == "win32" and excinfo[0] is PermissionError:
  1374. os.chmod(path, stat.S_IWRITE)
  1375. func(path)
  1376. else:
  1377. raise
  1378. shutil.rmtree(self.tempdir, onerror=remove_readonly)
  1379. self.addCleanup(cleanup_tempdir)
  1380. self.repo = Repo.init(self.tempdir)
  1381. def test_update_working_tree_with_blob_normalizer(self):
  1382. """Test update_working_tree with a blob normalizer."""
  1383. # Create a simple blob normalizer that converts CRLF to LF
  1384. class TestBlobNormalizer:
  1385. def checkout_normalize(self, blob, path):
  1386. # Convert CRLF to LF during checkout
  1387. new_blob = Blob()
  1388. new_blob.data = blob.data.replace(b"\r\n", b"\n")
  1389. return new_blob
  1390. # Create a tree with a file containing CRLF
  1391. blob = Blob()
  1392. blob.data = b"Hello\r\nWorld\r\n"
  1393. self.repo.object_store.add_object(blob)
  1394. tree = Tree()
  1395. tree[b"test.txt"] = (0o100644, blob.id)
  1396. self.repo.object_store.add_object(tree)
  1397. # Update working tree with normalizer
  1398. normalizer = TestBlobNormalizer()
  1399. update_working_tree(
  1400. self.repo,
  1401. None, # old_tree_id
  1402. tree.id, # new_tree_id
  1403. blob_normalizer=normalizer,
  1404. )
  1405. # Check that the file was written with LF line endings
  1406. test_file = os.path.join(self.tempdir, "test.txt")
  1407. with open(test_file, "rb") as f:
  1408. content = f.read()
  1409. self.assertEqual(b"Hello\nWorld\n", content)
  1410. # Check that the index has the original blob SHA
  1411. index = self.repo.open_index()
  1412. self.assertEqual(blob.id, index[b"test.txt"].sha)
  1413. def test_update_working_tree_without_blob_normalizer(self):
  1414. """Test update_working_tree without a blob normalizer."""
  1415. # Create a tree with a file containing CRLF
  1416. blob = Blob()
  1417. blob.data = b"Hello\r\nWorld\r\n"
  1418. self.repo.object_store.add_object(blob)
  1419. tree = Tree()
  1420. tree[b"test.txt"] = (0o100644, blob.id)
  1421. self.repo.object_store.add_object(tree)
  1422. # Update working tree without normalizer
  1423. update_working_tree(
  1424. self.repo,
  1425. None, # old_tree_id
  1426. tree.id, # new_tree_id
  1427. blob_normalizer=None,
  1428. )
  1429. # Check that the file was written with original CRLF line endings
  1430. test_file = os.path.join(self.tempdir, "test.txt")
  1431. with open(test_file, "rb") as f:
  1432. content = f.read()
  1433. self.assertEqual(b"Hello\r\nWorld\r\n", content)
  1434. # Check that the index has the blob SHA
  1435. index = self.repo.open_index()
  1436. self.assertEqual(blob.id, index[b"test.txt"].sha)
  1437. def test_update_working_tree_remove_directory(self):
  1438. """Test that update_working_tree properly removes directories."""
  1439. # Create initial tree with a directory containing files
  1440. blob1 = Blob()
  1441. blob1.data = b"content1"
  1442. self.repo.object_store.add_object(blob1)
  1443. blob2 = Blob()
  1444. blob2.data = b"content2"
  1445. self.repo.object_store.add_object(blob2)
  1446. tree1 = Tree()
  1447. tree1[b"dir/file1.txt"] = (0o100644, blob1.id)
  1448. tree1[b"dir/file2.txt"] = (0o100644, blob2.id)
  1449. self.repo.object_store.add_object(tree1)
  1450. # Update to tree1 (create directory with files)
  1451. update_working_tree(self.repo, None, tree1.id)
  1452. # Verify directory and files exist
  1453. dir_path = os.path.join(self.tempdir, "dir")
  1454. self.assertTrue(os.path.isdir(dir_path))
  1455. self.assertTrue(os.path.exists(os.path.join(dir_path, "file1.txt")))
  1456. self.assertTrue(os.path.exists(os.path.join(dir_path, "file2.txt")))
  1457. # Create empty tree (remove everything)
  1458. tree2 = Tree()
  1459. self.repo.object_store.add_object(tree2)
  1460. # Update to empty tree
  1461. update_working_tree(self.repo, tree1.id, tree2.id)
  1462. # Verify directory was removed
  1463. self.assertFalse(os.path.exists(dir_path))
  1464. def test_update_working_tree_submodule_to_file(self):
  1465. """Test replacing a submodule directory with a file."""
  1466. # Create tree with submodule
  1467. submodule_sha = b"a" * 40
  1468. tree1 = Tree()
  1469. tree1[b"submodule"] = (S_IFGITLINK, submodule_sha)
  1470. self.repo.object_store.add_object(tree1)
  1471. # Update to tree with submodule
  1472. update_working_tree(self.repo, None, tree1.id)
  1473. # Verify submodule directory exists with .git file
  1474. submodule_path = os.path.join(self.tempdir, "submodule")
  1475. self.assertTrue(os.path.isdir(submodule_path))
  1476. self.assertTrue(os.path.exists(os.path.join(submodule_path, ".git")))
  1477. # Create tree with file at same path
  1478. blob = Blob()
  1479. blob.data = b"file content"
  1480. self.repo.object_store.add_object(blob)
  1481. tree2 = Tree()
  1482. tree2[b"submodule"] = (0o100644, blob.id)
  1483. self.repo.object_store.add_object(tree2)
  1484. # Update to tree with file (should remove submodule directory and create file)
  1485. update_working_tree(self.repo, tree1.id, tree2.id)
  1486. # Verify it's now a file
  1487. self.assertTrue(os.path.isfile(submodule_path))
  1488. with open(submodule_path, "rb") as f:
  1489. self.assertEqual(b"file content", f.read())
  1490. def test_update_working_tree_directory_with_nested_subdir(self):
  1491. """Test removing directory with nested subdirectories."""
  1492. # Create tree with nested directories
  1493. blob = Blob()
  1494. blob.data = b"deep content"
  1495. self.repo.object_store.add_object(blob)
  1496. tree1 = Tree()
  1497. tree1[b"a/b/c/file.txt"] = (0o100644, blob.id)
  1498. self.repo.object_store.add_object(tree1)
  1499. # Update to tree1
  1500. update_working_tree(self.repo, None, tree1.id)
  1501. # Verify nested structure exists
  1502. path_a = os.path.join(self.tempdir, "a")
  1503. path_b = os.path.join(path_a, "b")
  1504. path_c = os.path.join(path_b, "c")
  1505. file_path = os.path.join(path_c, "file.txt")
  1506. self.assertTrue(os.path.exists(file_path))
  1507. # Create empty tree
  1508. tree2 = Tree()
  1509. self.repo.object_store.add_object(tree2)
  1510. # Update to empty tree
  1511. update_working_tree(self.repo, tree1.id, tree2.id)
  1512. # Verify all directories were removed
  1513. self.assertFalse(os.path.exists(path_a))
  1514. def test_update_working_tree_file_replaced_by_dir_not_removed(self):
  1515. """Test that a directory replacing a git file is left alone if not empty."""
  1516. # Create tree with a file
  1517. blob = Blob()
  1518. blob.data = b"file content"
  1519. self.repo.object_store.add_object(blob)
  1520. tree1 = Tree()
  1521. tree1[b"path"] = (0o100644, blob.id)
  1522. self.repo.object_store.add_object(tree1)
  1523. # Update to tree1
  1524. update_working_tree(self.repo, None, tree1.id)
  1525. # Verify file exists
  1526. file_path = os.path.join(self.tempdir, "path")
  1527. self.assertTrue(os.path.isfile(file_path))
  1528. # Manually replace file with directory containing untracked file
  1529. os.remove(file_path)
  1530. os.mkdir(file_path)
  1531. with open(os.path.join(file_path, "untracked.txt"), "w") as f:
  1532. f.write("untracked content")
  1533. # Create empty tree
  1534. tree2 = Tree()
  1535. self.repo.object_store.add_object(tree2)
  1536. # Update should succeed but leave the directory alone
  1537. update_working_tree(self.repo, tree1.id, tree2.id)
  1538. # Directory should still exist with its contents
  1539. self.assertTrue(os.path.isdir(file_path))
  1540. self.assertTrue(os.path.exists(os.path.join(file_path, "untracked.txt")))
  1541. def test_update_working_tree_file_replaced_by_empty_dir_removed(self):
  1542. """Test that an empty directory replacing a git file is removed."""
  1543. # Create tree with a file
  1544. blob = Blob()
  1545. blob.data = b"file content"
  1546. self.repo.object_store.add_object(blob)
  1547. tree1 = Tree()
  1548. tree1[b"path"] = (0o100644, blob.id)
  1549. self.repo.object_store.add_object(tree1)
  1550. # Update to tree1
  1551. update_working_tree(self.repo, None, tree1.id)
  1552. # Verify file exists
  1553. file_path = os.path.join(self.tempdir, "path")
  1554. self.assertTrue(os.path.isfile(file_path))
  1555. # Manually replace file with empty directory
  1556. os.remove(file_path)
  1557. os.mkdir(file_path)
  1558. # Create empty tree
  1559. tree2 = Tree()
  1560. self.repo.object_store.add_object(tree2)
  1561. # Update should remove the empty directory
  1562. update_working_tree(self.repo, tree1.id, tree2.id)
  1563. # Directory should be gone
  1564. self.assertFalse(os.path.exists(file_path))
  1565. def test_update_working_tree_symlink_transitions(self):
  1566. """Test transitions involving symlinks."""
  1567. # Skip on Windows where symlinks might not be supported
  1568. if sys.platform == "win32":
  1569. self.skipTest("Symlinks not fully supported on Windows")
  1570. # Create tree with symlink
  1571. blob1 = Blob()
  1572. blob1.data = b"target/path"
  1573. self.repo.object_store.add_object(blob1)
  1574. tree1 = Tree()
  1575. tree1[b"link"] = (0o120000, blob1.id) # Symlink mode
  1576. self.repo.object_store.add_object(tree1)
  1577. # Update to tree with symlink
  1578. update_working_tree(self.repo, None, tree1.id)
  1579. link_path = os.path.join(self.tempdir, "link")
  1580. self.assertTrue(os.path.islink(link_path))
  1581. self.assertEqual(b"target/path", os.readlink(link_path).encode())
  1582. # Test 1: Replace symlink with regular file
  1583. blob2 = Blob()
  1584. blob2.data = b"file content"
  1585. self.repo.object_store.add_object(blob2)
  1586. tree2 = Tree()
  1587. tree2[b"link"] = (0o100644, blob2.id)
  1588. self.repo.object_store.add_object(tree2)
  1589. update_working_tree(self.repo, tree1.id, tree2.id)
  1590. self.assertFalse(os.path.islink(link_path))
  1591. self.assertTrue(os.path.isfile(link_path))
  1592. with open(link_path, "rb") as f:
  1593. self.assertEqual(b"file content", f.read())
  1594. # Test 2: Replace file with symlink
  1595. update_working_tree(self.repo, tree2.id, tree1.id)
  1596. self.assertTrue(os.path.islink(link_path))
  1597. self.assertEqual(b"target/path", os.readlink(link_path).encode())
  1598. # Test 3: Replace symlink with directory (manually)
  1599. os.unlink(link_path)
  1600. os.mkdir(link_path)
  1601. # Create empty tree
  1602. tree3 = Tree()
  1603. self.repo.object_store.add_object(tree3)
  1604. # Should remove empty directory
  1605. update_working_tree(self.repo, tree1.id, tree3.id)
  1606. self.assertFalse(os.path.exists(link_path))
  1607. def test_update_working_tree_modified_file_to_dir_transition(self):
  1608. """Test that modified files are not removed when they should be directories."""
  1609. # Create tree with file
  1610. blob1 = Blob()
  1611. blob1.data = b"original content"
  1612. self.repo.object_store.add_object(blob1)
  1613. tree1 = Tree()
  1614. tree1[b"path"] = (0o100644, blob1.id)
  1615. self.repo.object_store.add_object(tree1)
  1616. # Update to tree1
  1617. update_working_tree(self.repo, None, tree1.id)
  1618. file_path = os.path.join(self.tempdir, "path")
  1619. # Modify the file locally
  1620. with open(file_path, "w") as f:
  1621. f.write("modified content")
  1622. # Create tree where path is a directory with file
  1623. blob2 = Blob()
  1624. blob2.data = b"subfile content"
  1625. self.repo.object_store.add_object(blob2)
  1626. tree2 = Tree()
  1627. tree2[b"path/subfile"] = (0o100644, blob2.id)
  1628. self.repo.object_store.add_object(tree2)
  1629. # Update should fail because can't create directory where modified file exists
  1630. with self.assertRaises(IOError):
  1631. update_working_tree(self.repo, tree1.id, tree2.id)
  1632. # File should still exist with modifications
  1633. self.assertTrue(os.path.isfile(file_path))
  1634. with open(file_path) as f:
  1635. self.assertEqual("modified content", f.read())
  1636. def test_update_working_tree_executable_transitions(self):
  1637. """Test transitions involving executable bit changes."""
  1638. # Skip on Windows where executable bit is not supported
  1639. if sys.platform == "win32":
  1640. self.skipTest("Executable bit not supported on Windows")
  1641. # Create tree with non-executable file
  1642. blob = Blob()
  1643. blob.data = b"#!/bin/sh\necho hello"
  1644. self.repo.object_store.add_object(blob)
  1645. tree1 = Tree()
  1646. tree1[b"script.sh"] = (0o100644, blob.id) # Non-executable
  1647. self.repo.object_store.add_object(tree1)
  1648. # Update to tree1
  1649. update_working_tree(self.repo, None, tree1.id)
  1650. script_path = os.path.join(self.tempdir, "script.sh")
  1651. self.assertTrue(os.path.isfile(script_path))
  1652. # Check it's not executable
  1653. mode = os.stat(script_path).st_mode
  1654. self.assertFalse(mode & stat.S_IXUSR)
  1655. # Create tree with executable file (same content)
  1656. tree2 = Tree()
  1657. tree2[b"script.sh"] = (0o100755, blob.id) # Executable
  1658. self.repo.object_store.add_object(tree2)
  1659. # Update to tree2
  1660. update_working_tree(self.repo, tree1.id, tree2.id)
  1661. # Check it's now executable
  1662. mode = os.stat(script_path).st_mode
  1663. self.assertTrue(mode & stat.S_IXUSR)
  1664. def test_update_working_tree_submodule_with_untracked_files(self):
  1665. """Test that submodules with untracked files are not removed."""
  1666. from dulwich.objects import S_IFGITLINK, Tree
  1667. # Create tree with submodule
  1668. submodule_sha = b"a" * 40
  1669. tree1 = Tree()
  1670. tree1[b"submodule"] = (S_IFGITLINK, submodule_sha)
  1671. self.repo.object_store.add_object(tree1)
  1672. # Update to tree with submodule
  1673. update_working_tree(self.repo, None, tree1.id)
  1674. # Add untracked file to submodule directory
  1675. submodule_path = os.path.join(self.tempdir, "submodule")
  1676. untracked_path = os.path.join(submodule_path, "untracked.txt")
  1677. with open(untracked_path, "w") as f:
  1678. f.write("untracked content")
  1679. # Create empty tree
  1680. tree2 = Tree()
  1681. self.repo.object_store.add_object(tree2)
  1682. # Update should not remove submodule directory with untracked files
  1683. update_working_tree(self.repo, tree1.id, tree2.id)
  1684. # Directory should still exist with untracked file
  1685. self.assertTrue(os.path.isdir(submodule_path))
  1686. self.assertTrue(os.path.exists(untracked_path))
  1687. def test_update_working_tree_dir_to_file_with_subdir(self):
  1688. """Test replacing directory structure with a file."""
  1689. # Create tree with nested directory structure
  1690. blob1 = Blob()
  1691. blob1.data = b"content1"
  1692. self.repo.object_store.add_object(blob1)
  1693. blob2 = Blob()
  1694. blob2.data = b"content2"
  1695. self.repo.object_store.add_object(blob2)
  1696. tree1 = Tree()
  1697. tree1[b"dir/subdir/file1"] = (0o100644, blob1.id)
  1698. tree1[b"dir/subdir/file2"] = (0o100644, blob2.id)
  1699. self.repo.object_store.add_object(tree1)
  1700. # Update to tree1
  1701. update_working_tree(self.repo, None, tree1.id)
  1702. # Verify structure exists
  1703. dir_path = os.path.join(self.tempdir, "dir")
  1704. self.assertTrue(os.path.isdir(dir_path))
  1705. # Add an untracked file to make directory truly non-empty
  1706. untracked_path = os.path.join(dir_path, "untracked.txt")
  1707. with open(untracked_path, "w") as f:
  1708. f.write("untracked content")
  1709. # Create tree with file at "dir" path
  1710. blob3 = Blob()
  1711. blob3.data = b"replacement file"
  1712. self.repo.object_store.add_object(blob3)
  1713. tree2 = Tree()
  1714. tree2[b"dir"] = (0o100644, blob3.id)
  1715. self.repo.object_store.add_object(tree2)
  1716. # Update should fail because directory is not empty
  1717. with self.assertRaises(IsADirectoryError):
  1718. update_working_tree(self.repo, tree1.id, tree2.id)
  1719. # Directory should still exist
  1720. self.assertTrue(os.path.isdir(dir_path))
  1721. def test_update_working_tree_case_sensitivity(self):
  1722. """Test handling of case-sensitive filename changes."""
  1723. # Create tree with lowercase file
  1724. blob1 = Blob()
  1725. blob1.data = b"lowercase content"
  1726. self.repo.object_store.add_object(blob1)
  1727. tree1 = Tree()
  1728. tree1[b"readme.txt"] = (0o100644, blob1.id)
  1729. self.repo.object_store.add_object(tree1)
  1730. # Update to tree1
  1731. update_working_tree(self.repo, None, tree1.id)
  1732. # Create tree with uppercase file (different content)
  1733. blob2 = Blob()
  1734. blob2.data = b"uppercase content"
  1735. self.repo.object_store.add_object(blob2)
  1736. tree2 = Tree()
  1737. tree2[b"README.txt"] = (0o100644, blob2.id)
  1738. self.repo.object_store.add_object(tree2)
  1739. # Update to tree2
  1740. update_working_tree(self.repo, tree1.id, tree2.id)
  1741. # Check what exists (behavior depends on filesystem)
  1742. lowercase_path = os.path.join(self.tempdir, "readme.txt")
  1743. uppercase_path = os.path.join(self.tempdir, "README.txt")
  1744. # On case-insensitive filesystems, one will overwrite the other
  1745. # On case-sensitive filesystems, both may exist
  1746. self.assertTrue(
  1747. os.path.exists(lowercase_path) or os.path.exists(uppercase_path)
  1748. )
  1749. def test_update_working_tree_deeply_nested_removal(self):
  1750. """Test removal of deeply nested directory structures."""
  1751. # Create deeply nested structure
  1752. blob = Blob()
  1753. blob.data = b"deep content"
  1754. self.repo.object_store.add_object(blob)
  1755. tree1 = Tree()
  1756. # Create a very deep path
  1757. deep_path = b"/".join([b"level%d" % i for i in range(10)])
  1758. tree1[deep_path + b"/file.txt"] = (0o100644, blob.id)
  1759. self.repo.object_store.add_object(tree1)
  1760. # Update to tree1
  1761. update_working_tree(self.repo, None, tree1.id)
  1762. # Verify deep structure exists
  1763. current_path = self.tempdir
  1764. for i in range(10):
  1765. current_path = os.path.join(current_path, f"level{i}")
  1766. self.assertTrue(os.path.isdir(current_path))
  1767. # Create empty tree
  1768. tree2 = Tree()
  1769. self.repo.object_store.add_object(tree2)
  1770. # Update should remove all empty directories
  1771. update_working_tree(self.repo, tree1.id, tree2.id)
  1772. # Verify top level directory is gone
  1773. top_level = os.path.join(self.tempdir, "level0")
  1774. self.assertFalse(os.path.exists(top_level))
  1775. def test_update_working_tree_read_only_files(self):
  1776. """Test handling of read-only files during updates."""
  1777. # Create tree with file
  1778. blob1 = Blob()
  1779. blob1.data = b"original content"
  1780. self.repo.object_store.add_object(blob1)
  1781. tree1 = Tree()
  1782. tree1[b"readonly.txt"] = (0o100644, blob1.id)
  1783. self.repo.object_store.add_object(tree1)
  1784. # Update to tree1
  1785. update_working_tree(self.repo, None, tree1.id)
  1786. # Make file read-only
  1787. file_path = os.path.join(self.tempdir, "readonly.txt")
  1788. os.chmod(file_path, 0o444) # Read-only
  1789. # Create tree with modified file
  1790. blob2 = Blob()
  1791. blob2.data = b"new content"
  1792. self.repo.object_store.add_object(blob2)
  1793. tree2 = Tree()
  1794. tree2[b"readonly.txt"] = (0o100644, blob2.id)
  1795. self.repo.object_store.add_object(tree2)
  1796. # Update should handle read-only file
  1797. update_working_tree(self.repo, tree1.id, tree2.id)
  1798. # Verify content was updated
  1799. with open(file_path, "rb") as f:
  1800. self.assertEqual(b"new content", f.read())
  1801. def test_update_working_tree_invalid_filenames(self):
  1802. """Test handling of invalid filenames for the platform."""
  1803. # Create tree with potentially problematic filenames
  1804. blob = Blob()
  1805. blob.data = b"content"
  1806. self.repo.object_store.add_object(blob)
  1807. tree = Tree()
  1808. # Add files with names that might be invalid on some platforms
  1809. tree[b"valid.txt"] = (0o100644, blob.id)
  1810. if sys.platform != "win32":
  1811. # These are invalid on Windows but valid on Unix
  1812. tree[b"file:with:colons.txt"] = (0o100644, blob.id)
  1813. tree[b"file<with>brackets.txt"] = (0o100644, blob.id)
  1814. self.repo.object_store.add_object(tree)
  1815. # Update should skip invalid files based on validation
  1816. update_working_tree(self.repo, None, tree.id)
  1817. # Valid file should exist
  1818. self.assertTrue(os.path.exists(os.path.join(self.tempdir, "valid.txt")))
  1819. def test_update_working_tree_symlink_to_directory(self):
  1820. """Test replacing a symlink pointing to a directory with a real directory."""
  1821. if sys.platform == "win32":
  1822. self.skipTest("Symlinks not fully supported on Windows")
  1823. # Create a target directory
  1824. target_dir = os.path.join(self.tempdir, "target")
  1825. os.mkdir(target_dir)
  1826. with open(os.path.join(target_dir, "file.txt"), "w") as f:
  1827. f.write("target file")
  1828. # Create tree with symlink pointing to directory
  1829. blob1 = Blob()
  1830. blob1.data = b"target" # Relative path to target directory
  1831. self.repo.object_store.add_object(blob1)
  1832. tree1 = Tree()
  1833. tree1[b"link"] = (0o120000, blob1.id)
  1834. self.repo.object_store.add_object(tree1)
  1835. # Update to tree1
  1836. update_working_tree(self.repo, None, tree1.id)
  1837. link_path = os.path.join(self.tempdir, "link")
  1838. self.assertTrue(os.path.islink(link_path))
  1839. # Create tree with actual directory at same path
  1840. blob2 = Blob()
  1841. blob2.data = b"new file content"
  1842. self.repo.object_store.add_object(blob2)
  1843. tree2 = Tree()
  1844. tree2[b"link/newfile.txt"] = (0o100644, blob2.id)
  1845. self.repo.object_store.add_object(tree2)
  1846. # Update should replace symlink with actual directory
  1847. update_working_tree(self.repo, tree1.id, tree2.id)
  1848. self.assertFalse(os.path.islink(link_path))
  1849. self.assertTrue(os.path.isdir(link_path))
  1850. self.assertTrue(os.path.exists(os.path.join(link_path, "newfile.txt")))
  1851. def test_update_working_tree_comprehensive_transitions(self):
  1852. """Test all possible file type transitions comprehensively."""
  1853. # Skip on Windows where symlinks might not be supported
  1854. if sys.platform == "win32":
  1855. self.skipTest("Symlinks not fully supported on Windows")
  1856. # Create blobs for different file types
  1857. file_blob = Blob()
  1858. file_blob.data = b"regular file content"
  1859. self.repo.object_store.add_object(file_blob)
  1860. exec_blob = Blob()
  1861. exec_blob.data = b"#!/bin/sh\necho executable"
  1862. self.repo.object_store.add_object(exec_blob)
  1863. link_blob = Blob()
  1864. link_blob.data = b"target/path"
  1865. self.repo.object_store.add_object(link_blob)
  1866. submodule_sha = b"a" * 40
  1867. # Test 1: Regular file → Submodule
  1868. tree1 = Tree()
  1869. tree1[b"item"] = (0o100644, file_blob.id)
  1870. self.repo.object_store.add_object(tree1)
  1871. tree2 = Tree()
  1872. tree2[b"item"] = (S_IFGITLINK, submodule_sha)
  1873. self.repo.object_store.add_object(tree2)
  1874. update_working_tree(self.repo, None, tree1.id)
  1875. self.assertTrue(os.path.isfile(os.path.join(self.tempdir, "item")))
  1876. update_working_tree(self.repo, tree1.id, tree2.id)
  1877. self.assertTrue(os.path.isdir(os.path.join(self.tempdir, "item")))
  1878. # Test 2: Submodule → Executable file
  1879. tree3 = Tree()
  1880. tree3[b"item"] = (0o100755, exec_blob.id)
  1881. self.repo.object_store.add_object(tree3)
  1882. update_working_tree(self.repo, tree2.id, tree3.id)
  1883. item_path = os.path.join(self.tempdir, "item")
  1884. self.assertTrue(os.path.isfile(item_path))
  1885. if sys.platform != "win32":
  1886. self.assertTrue(os.access(item_path, os.X_OK))
  1887. # Test 3: Executable file → Symlink
  1888. tree4 = Tree()
  1889. tree4[b"item"] = (0o120000, link_blob.id)
  1890. self.repo.object_store.add_object(tree4)
  1891. update_working_tree(self.repo, tree3.id, tree4.id)
  1892. self.assertTrue(os.path.islink(item_path))
  1893. # Test 4: Symlink → Submodule
  1894. tree5 = Tree()
  1895. tree5[b"item"] = (S_IFGITLINK, submodule_sha)
  1896. self.repo.object_store.add_object(tree5)
  1897. update_working_tree(self.repo, tree4.id, tree5.id)
  1898. self.assertTrue(os.path.isdir(item_path))
  1899. # Test 5: Clean up - Submodule → absent
  1900. tree6 = Tree()
  1901. self.repo.object_store.add_object(tree6)
  1902. update_working_tree(self.repo, tree5.id, tree6.id)
  1903. self.assertFalse(os.path.exists(item_path))
  1904. # Test 6: Symlink → Executable file
  1905. tree7 = Tree()
  1906. tree7[b"item2"] = (0o120000, link_blob.id)
  1907. self.repo.object_store.add_object(tree7)
  1908. update_working_tree(self.repo, tree6.id, tree7.id)
  1909. item2_path = os.path.join(self.tempdir, "item2")
  1910. self.assertTrue(os.path.islink(item2_path))
  1911. tree8 = Tree()
  1912. tree8[b"item2"] = (0o100755, exec_blob.id)
  1913. self.repo.object_store.add_object(tree8)
  1914. update_working_tree(self.repo, tree7.id, tree8.id)
  1915. self.assertTrue(os.path.isfile(item2_path))
  1916. if sys.platform != "win32":
  1917. self.assertTrue(os.access(item2_path, os.X_OK))
  1918. def test_update_working_tree_partial_update_failure(self):
  1919. """Test handling when update fails partway through."""
  1920. # Create initial tree
  1921. blob1 = Blob()
  1922. blob1.data = b"file1 content"
  1923. self.repo.object_store.add_object(blob1)
  1924. blob2 = Blob()
  1925. blob2.data = b"file2 content"
  1926. self.repo.object_store.add_object(blob2)
  1927. tree1 = Tree()
  1928. tree1[b"file1.txt"] = (0o100644, blob1.id)
  1929. tree1[b"file2.txt"] = (0o100644, blob2.id)
  1930. self.repo.object_store.add_object(tree1)
  1931. # Update to tree1
  1932. update_working_tree(self.repo, None, tree1.id)
  1933. # Create a directory where file2.txt is, to cause a conflict
  1934. file2_path = os.path.join(self.tempdir, "file2.txt")
  1935. os.remove(file2_path)
  1936. os.mkdir(file2_path)
  1937. # Add untracked file to prevent removal
  1938. with open(os.path.join(file2_path, "blocker.txt"), "w") as f:
  1939. f.write("blocking content")
  1940. # Create tree with updates to both files
  1941. blob3 = Blob()
  1942. blob3.data = b"file1 updated"
  1943. self.repo.object_store.add_object(blob3)
  1944. blob4 = Blob()
  1945. blob4.data = b"file2 updated"
  1946. self.repo.object_store.add_object(blob4)
  1947. tree2 = Tree()
  1948. tree2[b"file1.txt"] = (0o100644, blob3.id)
  1949. tree2[b"file2.txt"] = (0o100644, blob4.id)
  1950. self.repo.object_store.add_object(tree2)
  1951. # Update should partially succeed - file1 updated, file2 blocked
  1952. try:
  1953. update_working_tree(self.repo, tree1.id, tree2.id)
  1954. except IsADirectoryError:
  1955. # Expected to fail on file2 because it's a directory
  1956. pass
  1957. # file1 should be updated
  1958. with open(os.path.join(self.tempdir, "file1.txt"), "rb") as f:
  1959. self.assertEqual(b"file1 updated", f.read())
  1960. # file2 should still be a directory
  1961. self.assertTrue(os.path.isdir(file2_path))