test_index.py 82 KB

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