test_index.py 118 KB

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