test_index.py 104 KB

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