test_index.py 104 KB

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