2
0

test_index.py 108 KB

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