test_index.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603
  1. # test_index.py -- Tests for the git index
  2. # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Tests for the index."""
  22. import os
  23. import shutil
  24. import stat
  25. import struct
  26. import sys
  27. import tempfile
  28. from io import BytesIO
  29. from dulwich.index import (
  30. Index,
  31. IndexEntry,
  32. SerializedIndexEntry,
  33. _fs_to_tree_path,
  34. _tree_to_fs_path,
  35. build_index_from_tree,
  36. cleanup_mode,
  37. commit_tree,
  38. get_unstaged_changes,
  39. index_entry_from_directory,
  40. index_entry_from_path,
  41. index_entry_from_stat,
  42. iter_fresh_entries,
  43. read_index,
  44. read_index_dict,
  45. validate_path_element_default,
  46. validate_path_element_ntfs,
  47. write_cache_time,
  48. write_index,
  49. write_index_dict,
  50. )
  51. from dulwich.object_store import MemoryObjectStore
  52. from dulwich.objects import S_IFGITLINK, Blob, Commit, Tree
  53. from dulwich.repo import Repo
  54. from . import TestCase, skipIf
  55. def can_symlink() -> bool:
  56. """Return whether running process can create symlinks."""
  57. if sys.platform != "win32":
  58. # Platforms other than Windows should allow symlinks without issues.
  59. return True
  60. test_source = tempfile.mkdtemp()
  61. test_target = test_source + "can_symlink"
  62. try:
  63. os.symlink(test_source, test_target)
  64. except (NotImplementedError, OSError):
  65. return False
  66. return True
  67. class IndexTestCase(TestCase):
  68. datadir = os.path.join(os.path.dirname(__file__), "../testdata/indexes")
  69. def get_simple_index(self, name):
  70. return Index(os.path.join(self.datadir, name))
  71. class SimpleIndexTestCase(IndexTestCase):
  72. def test_len(self) -> None:
  73. self.assertEqual(1, len(self.get_simple_index("index")))
  74. def test_iter(self) -> None:
  75. self.assertEqual([b"bla"], list(self.get_simple_index("index")))
  76. def test_iter_skip_hash(self) -> None:
  77. self.assertEqual([b"bla"], list(self.get_simple_index("index_skip_hash")))
  78. def test_iterobjects(self) -> None:
  79. self.assertEqual(
  80. [(b"bla", b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", 33188)],
  81. list(self.get_simple_index("index").iterobjects()),
  82. )
  83. def test_getitem(self) -> None:
  84. self.assertEqual(
  85. IndexEntry(
  86. (1230680220, 0),
  87. (1230680220, 0),
  88. 2050,
  89. 3761020,
  90. 33188,
  91. 1000,
  92. 1000,
  93. 0,
  94. b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391",
  95. 0,
  96. 0,
  97. ),
  98. self.get_simple_index("index")[b"bla"],
  99. )
  100. def test_empty(self) -> None:
  101. i = self.get_simple_index("notanindex")
  102. self.assertEqual(0, len(i))
  103. self.assertFalse(os.path.exists(i._filename))
  104. def test_against_empty_tree(self) -> None:
  105. i = self.get_simple_index("index")
  106. changes = list(i.changes_from_tree(MemoryObjectStore(), None))
  107. self.assertEqual(1, len(changes))
  108. (oldname, newname), (oldmode, newmode), (oldsha, newsha) = changes[0]
  109. self.assertEqual(b"bla", newname)
  110. self.assertEqual(b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", newsha)
  111. def test_index_pathlib(self) -> None:
  112. import tempfile
  113. from pathlib import Path
  114. # Create a temporary index file
  115. with tempfile.NamedTemporaryFile(suffix=".index", delete=False) as f:
  116. temp_path = f.name
  117. try:
  118. # Test creating Index with pathlib.Path
  119. path_obj = Path(temp_path)
  120. index = Index(path_obj, read=False)
  121. self.assertEqual(str(path_obj), index.path)
  122. # Add an entry and write
  123. index[b"test"] = IndexEntry(
  124. ctime=(0, 0),
  125. mtime=(0, 0),
  126. dev=0,
  127. ino=0,
  128. mode=33188,
  129. uid=0,
  130. gid=0,
  131. size=0,
  132. sha=b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391",
  133. )
  134. index.write()
  135. # Read it back with pathlib.Path
  136. index2 = Index(path_obj)
  137. self.assertIn(b"test", index2)
  138. finally:
  139. # Clean up
  140. os.unlink(temp_path)
  141. class SimpleIndexWriterTestCase(IndexTestCase):
  142. def setUp(self) -> None:
  143. IndexTestCase.setUp(self)
  144. self.tempdir = tempfile.mkdtemp()
  145. def tearDown(self) -> None:
  146. IndexTestCase.tearDown(self)
  147. shutil.rmtree(self.tempdir)
  148. def test_simple_write(self) -> None:
  149. entries = [
  150. (
  151. SerializedIndexEntry(
  152. b"barbla",
  153. (1230680220, 0),
  154. (1230680220, 0),
  155. 2050,
  156. 3761020,
  157. 33188,
  158. 1000,
  159. 1000,
  160. 0,
  161. b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391",
  162. 0,
  163. 0,
  164. )
  165. )
  166. ]
  167. filename = os.path.join(self.tempdir, "test-simple-write-index")
  168. with open(filename, "wb+") as x:
  169. write_index(x, entries)
  170. with open(filename, "rb") as x:
  171. self.assertEqual(entries, list(read_index(x)))
  172. class ReadIndexDictTests(IndexTestCase):
  173. def setUp(self) -> None:
  174. IndexTestCase.setUp(self)
  175. self.tempdir = tempfile.mkdtemp()
  176. def tearDown(self) -> None:
  177. IndexTestCase.tearDown(self)
  178. shutil.rmtree(self.tempdir)
  179. def test_simple_write(self) -> None:
  180. entries = {
  181. b"barbla": IndexEntry(
  182. (1230680220, 0),
  183. (1230680220, 0),
  184. 2050,
  185. 3761020,
  186. 33188,
  187. 1000,
  188. 1000,
  189. 0,
  190. b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391",
  191. 0,
  192. 0,
  193. )
  194. }
  195. filename = os.path.join(self.tempdir, "test-simple-write-index")
  196. with open(filename, "wb+") as x:
  197. write_index_dict(x, entries)
  198. with open(filename, "rb") as x:
  199. self.assertEqual(entries, read_index_dict(x))
  200. class CommitTreeTests(TestCase):
  201. def setUp(self) -> None:
  202. super().setUp()
  203. self.store = MemoryObjectStore()
  204. def test_single_blob(self) -> None:
  205. blob = Blob()
  206. blob.data = b"foo"
  207. self.store.add_object(blob)
  208. blobs = [(b"bla", blob.id, stat.S_IFREG)]
  209. rootid = commit_tree(self.store, blobs)
  210. self.assertEqual(rootid, b"1a1e80437220f9312e855c37ac4398b68e5c1d50")
  211. self.assertEqual((stat.S_IFREG, blob.id), self.store[rootid][b"bla"])
  212. self.assertEqual({rootid, blob.id}, set(self.store._data.keys()))
  213. def test_nested(self) -> None:
  214. blob = Blob()
  215. blob.data = b"foo"
  216. self.store.add_object(blob)
  217. blobs = [(b"bla/bar", blob.id, stat.S_IFREG)]
  218. rootid = commit_tree(self.store, blobs)
  219. self.assertEqual(rootid, b"d92b959b216ad0d044671981196781b3258fa537")
  220. dirid = self.store[rootid][b"bla"][1]
  221. self.assertEqual(dirid, b"c1a1deb9788150829579a8b4efa6311e7b638650")
  222. self.assertEqual((stat.S_IFDIR, dirid), self.store[rootid][b"bla"])
  223. self.assertEqual((stat.S_IFREG, blob.id), self.store[dirid][b"bar"])
  224. self.assertEqual({rootid, dirid, blob.id}, set(self.store._data.keys()))
  225. class CleanupModeTests(TestCase):
  226. def assertModeEqual(self, expected, got) -> None:
  227. self.assertEqual(expected, got, f"{expected:o} != {got:o}")
  228. def test_file(self) -> None:
  229. self.assertModeEqual(0o100644, cleanup_mode(0o100000))
  230. def test_executable(self) -> None:
  231. self.assertModeEqual(0o100755, cleanup_mode(0o100711))
  232. self.assertModeEqual(0o100755, cleanup_mode(0o100700))
  233. def test_symlink(self) -> None:
  234. self.assertModeEqual(0o120000, cleanup_mode(0o120711))
  235. def test_dir(self) -> None:
  236. self.assertModeEqual(0o040000, cleanup_mode(0o40531))
  237. def test_submodule(self) -> None:
  238. self.assertModeEqual(0o160000, cleanup_mode(0o160744))
  239. class WriteCacheTimeTests(TestCase):
  240. def test_write_string(self) -> None:
  241. f = BytesIO()
  242. self.assertRaises(TypeError, write_cache_time, f, "foo")
  243. def test_write_int(self) -> None:
  244. f = BytesIO()
  245. write_cache_time(f, 434343)
  246. self.assertEqual(struct.pack(">LL", 434343, 0), f.getvalue())
  247. def test_write_tuple(self) -> None:
  248. f = BytesIO()
  249. write_cache_time(f, (434343, 21))
  250. self.assertEqual(struct.pack(">LL", 434343, 21), f.getvalue())
  251. def test_write_float(self) -> None:
  252. f = BytesIO()
  253. write_cache_time(f, 434343.000000021)
  254. self.assertEqual(struct.pack(">LL", 434343, 21), f.getvalue())
  255. class IndexEntryFromStatTests(TestCase):
  256. def test_simple(self) -> None:
  257. st = os.stat_result(
  258. (
  259. 16877,
  260. 131078,
  261. 64769,
  262. 154,
  263. 1000,
  264. 1000,
  265. 12288,
  266. 1323629595,
  267. 1324180496,
  268. 1324180496,
  269. )
  270. )
  271. entry = index_entry_from_stat(st, b"22" * 20)
  272. self.assertEqual(
  273. entry,
  274. IndexEntry(
  275. 1324180496,
  276. 1324180496,
  277. 64769,
  278. 131078,
  279. 16384,
  280. 1000,
  281. 1000,
  282. 12288,
  283. b"2222222222222222222222222222222222222222",
  284. 0,
  285. 0,
  286. ),
  287. )
  288. def test_override_mode(self) -> None:
  289. st = os.stat_result(
  290. (
  291. stat.S_IFREG + 0o644,
  292. 131078,
  293. 64769,
  294. 154,
  295. 1000,
  296. 1000,
  297. 12288,
  298. 1323629595,
  299. 1324180496,
  300. 1324180496,
  301. )
  302. )
  303. entry = index_entry_from_stat(st, b"22" * 20, mode=stat.S_IFREG + 0o755)
  304. self.assertEqual(
  305. entry,
  306. IndexEntry(
  307. 1324180496,
  308. 1324180496,
  309. 64769,
  310. 131078,
  311. 33261,
  312. 1000,
  313. 1000,
  314. 12288,
  315. b"2222222222222222222222222222222222222222",
  316. 0,
  317. 0,
  318. ),
  319. )
  320. class BuildIndexTests(TestCase):
  321. def assertReasonableIndexEntry(self, index_entry, mode, filesize, sha) -> None:
  322. self.assertEqual(index_entry.mode, mode) # mode
  323. self.assertEqual(index_entry.size, filesize) # filesize
  324. self.assertEqual(index_entry.sha, sha) # sha
  325. def assertFileContents(self, path, contents, symlink=False) -> None:
  326. if symlink:
  327. self.assertEqual(os.readlink(path), contents)
  328. else:
  329. with open(path, "rb") as f:
  330. self.assertEqual(f.read(), contents)
  331. def test_empty(self) -> None:
  332. repo_dir = tempfile.mkdtemp()
  333. self.addCleanup(shutil.rmtree, repo_dir)
  334. with Repo.init(repo_dir) as repo:
  335. tree = Tree()
  336. repo.object_store.add_object(tree)
  337. build_index_from_tree(
  338. repo.path, repo.index_path(), repo.object_store, tree.id
  339. )
  340. # Verify index entries
  341. index = repo.open_index()
  342. self.assertEqual(len(index), 0)
  343. # Verify no files
  344. self.assertEqual([".git"], os.listdir(repo.path))
  345. def test_git_dir(self) -> None:
  346. repo_dir = tempfile.mkdtemp()
  347. self.addCleanup(shutil.rmtree, repo_dir)
  348. with Repo.init(repo_dir) as repo:
  349. # Populate repo
  350. filea = Blob.from_string(b"file a")
  351. filee = Blob.from_string(b"d")
  352. tree = Tree()
  353. tree[b".git/a"] = (stat.S_IFREG | 0o644, filea.id)
  354. tree[b"c/e"] = (stat.S_IFREG | 0o644, filee.id)
  355. repo.object_store.add_objects([(o, None) for o in [filea, filee, tree]])
  356. build_index_from_tree(
  357. repo.path, repo.index_path(), repo.object_store, tree.id
  358. )
  359. # Verify index entries
  360. index = repo.open_index()
  361. self.assertEqual(len(index), 1)
  362. # filea
  363. apath = os.path.join(repo.path, ".git", "a")
  364. self.assertFalse(os.path.exists(apath))
  365. # filee
  366. epath = os.path.join(repo.path, "c", "e")
  367. self.assertTrue(os.path.exists(epath))
  368. self.assertReasonableIndexEntry(
  369. index[b"c/e"], stat.S_IFREG | 0o644, 1, filee.id
  370. )
  371. self.assertFileContents(epath, b"d")
  372. def test_nonempty(self) -> None:
  373. repo_dir = tempfile.mkdtemp()
  374. self.addCleanup(shutil.rmtree, repo_dir)
  375. with Repo.init(repo_dir) as repo:
  376. # Populate repo
  377. filea = Blob.from_string(b"file a")
  378. fileb = Blob.from_string(b"file b")
  379. filed = Blob.from_string(b"file d")
  380. tree = Tree()
  381. tree[b"a"] = (stat.S_IFREG | 0o644, filea.id)
  382. tree[b"b"] = (stat.S_IFREG | 0o644, fileb.id)
  383. tree[b"c/d"] = (stat.S_IFREG | 0o644, filed.id)
  384. repo.object_store.add_objects(
  385. [(o, None) for o in [filea, fileb, filed, tree]]
  386. )
  387. build_index_from_tree(
  388. repo.path, repo.index_path(), repo.object_store, tree.id
  389. )
  390. # Verify index entries
  391. index = repo.open_index()
  392. self.assertEqual(len(index), 3)
  393. # filea
  394. apath = os.path.join(repo.path, "a")
  395. self.assertTrue(os.path.exists(apath))
  396. self.assertReasonableIndexEntry(
  397. index[b"a"], stat.S_IFREG | 0o644, 6, filea.id
  398. )
  399. self.assertFileContents(apath, b"file a")
  400. # fileb
  401. bpath = os.path.join(repo.path, "b")
  402. self.assertTrue(os.path.exists(bpath))
  403. self.assertReasonableIndexEntry(
  404. index[b"b"], stat.S_IFREG | 0o644, 6, fileb.id
  405. )
  406. self.assertFileContents(bpath, b"file b")
  407. # filed
  408. dpath = os.path.join(repo.path, "c", "d")
  409. self.assertTrue(os.path.exists(dpath))
  410. self.assertReasonableIndexEntry(
  411. index[b"c/d"], stat.S_IFREG | 0o644, 6, filed.id
  412. )
  413. self.assertFileContents(dpath, b"file d")
  414. # Verify no extra files
  415. self.assertEqual([".git", "a", "b", "c"], sorted(os.listdir(repo.path)))
  416. self.assertEqual(["d"], sorted(os.listdir(os.path.join(repo.path, "c"))))
  417. @skipIf(not getattr(os, "sync", None), "Requires sync support")
  418. def test_norewrite(self) -> None:
  419. repo_dir = tempfile.mkdtemp()
  420. self.addCleanup(shutil.rmtree, repo_dir)
  421. with Repo.init(repo_dir) as repo:
  422. # Populate repo
  423. filea = Blob.from_string(b"file a")
  424. filea_path = os.path.join(repo_dir, "a")
  425. tree = Tree()
  426. tree[b"a"] = (stat.S_IFREG | 0o644, filea.id)
  427. repo.object_store.add_objects([(o, None) for o in [filea, tree]])
  428. # First Write
  429. build_index_from_tree(
  430. repo.path, repo.index_path(), repo.object_store, tree.id
  431. )
  432. # Use sync as metadata can be cached on some FS
  433. os.sync()
  434. mtime = os.stat(filea_path).st_mtime
  435. # Test Rewrite
  436. build_index_from_tree(
  437. repo.path, repo.index_path(), repo.object_store, tree.id
  438. )
  439. os.sync()
  440. self.assertEqual(mtime, os.stat(filea_path).st_mtime)
  441. # Modify content
  442. with open(filea_path, "wb") as fh:
  443. fh.write(b"test a")
  444. os.sync()
  445. mtime = os.stat(filea_path).st_mtime
  446. # Test rewrite
  447. build_index_from_tree(
  448. repo.path, repo.index_path(), repo.object_store, tree.id
  449. )
  450. os.sync()
  451. with open(filea_path, "rb") as fh:
  452. self.assertEqual(b"file a", fh.read())
  453. @skipIf(not can_symlink(), "Requires symlink support")
  454. def test_symlink(self) -> None:
  455. repo_dir = tempfile.mkdtemp()
  456. self.addCleanup(shutil.rmtree, repo_dir)
  457. with Repo.init(repo_dir) as repo:
  458. # Populate repo
  459. filed = Blob.from_string(b"file d")
  460. filee = Blob.from_string(b"d")
  461. tree = Tree()
  462. tree[b"c/d"] = (stat.S_IFREG | 0o644, filed.id)
  463. tree[b"c/e"] = (stat.S_IFLNK, filee.id) # symlink
  464. repo.object_store.add_objects([(o, None) for o in [filed, filee, tree]])
  465. build_index_from_tree(
  466. repo.path, repo.index_path(), repo.object_store, tree.id
  467. )
  468. # Verify index entries
  469. index = repo.open_index()
  470. # symlink to d
  471. epath = os.path.join(repo.path, "c", "e")
  472. self.assertTrue(os.path.exists(epath))
  473. self.assertReasonableIndexEntry(
  474. index[b"c/e"],
  475. stat.S_IFLNK,
  476. 0 if sys.platform == "win32" else 1,
  477. filee.id,
  478. )
  479. self.assertFileContents(epath, "d", symlink=True)
  480. def test_no_decode_encode(self) -> None:
  481. repo_dir = tempfile.mkdtemp()
  482. repo_dir_bytes = os.fsencode(repo_dir)
  483. self.addCleanup(shutil.rmtree, repo_dir)
  484. with Repo.init(repo_dir) as repo:
  485. # Populate repo
  486. file = Blob.from_string(b"foo")
  487. tree = Tree()
  488. latin1_name = "À".encode("latin1")
  489. try:
  490. latin1_path = os.path.join(repo_dir_bytes, latin1_name)
  491. except UnicodeDecodeError:
  492. self.skipTest("can not decode as latin1")
  493. utf8_name = "À".encode()
  494. utf8_path = os.path.join(repo_dir_bytes, utf8_name)
  495. tree[latin1_name] = (stat.S_IFREG | 0o644, file.id)
  496. tree[utf8_name] = (stat.S_IFREG | 0o644, file.id)
  497. repo.object_store.add_objects([(o, None) for o in [file, tree]])
  498. try:
  499. build_index_from_tree(
  500. repo.path, repo.index_path(), repo.object_store, tree.id
  501. )
  502. except OSError as e:
  503. if e.errno == 92 and sys.platform == "darwin":
  504. # Our filename isn't supported by the platform :(
  505. self.skipTest(f"can not write filename {e.filename!r}")
  506. else:
  507. raise
  508. except UnicodeDecodeError:
  509. # This happens e.g. with python3.6 on Windows.
  510. # It implicitly decodes using utf8, which doesn't work.
  511. self.skipTest("can not implicitly convert as utf8")
  512. # Verify index entries
  513. index = repo.open_index()
  514. self.assertIn(latin1_name, index)
  515. self.assertIn(utf8_name, index)
  516. self.assertTrue(os.path.exists(latin1_path))
  517. self.assertTrue(os.path.exists(utf8_path))
  518. def test_git_submodule(self) -> None:
  519. repo_dir = tempfile.mkdtemp()
  520. self.addCleanup(shutil.rmtree, repo_dir)
  521. with Repo.init(repo_dir) as repo:
  522. filea = Blob.from_string(b"file alalala")
  523. subtree = Tree()
  524. subtree[b"a"] = (stat.S_IFREG | 0o644, filea.id)
  525. c = Commit()
  526. c.tree = subtree.id
  527. c.committer = c.author = b"Somebody <somebody@example.com>"
  528. c.commit_time = c.author_time = 42342
  529. c.commit_timezone = c.author_timezone = 0
  530. c.parents = []
  531. c.message = b"Subcommit"
  532. tree = Tree()
  533. tree[b"c"] = (S_IFGITLINK, c.id)
  534. repo.object_store.add_objects([(o, None) for o in [tree]])
  535. build_index_from_tree(
  536. repo.path, repo.index_path(), repo.object_store, tree.id
  537. )
  538. # Verify index entries
  539. index = repo.open_index()
  540. self.assertEqual(len(index), 1)
  541. # filea
  542. apath = os.path.join(repo.path, "c/a")
  543. self.assertFalse(os.path.exists(apath))
  544. # dir c
  545. cpath = os.path.join(repo.path, "c")
  546. self.assertTrue(os.path.isdir(cpath))
  547. self.assertEqual(index[b"c"].mode, S_IFGITLINK) # mode
  548. self.assertEqual(index[b"c"].sha, c.id) # sha
  549. def test_git_submodule_exists(self) -> None:
  550. repo_dir = tempfile.mkdtemp()
  551. self.addCleanup(shutil.rmtree, repo_dir)
  552. with Repo.init(repo_dir) as repo:
  553. filea = Blob.from_string(b"file alalala")
  554. subtree = Tree()
  555. subtree[b"a"] = (stat.S_IFREG | 0o644, filea.id)
  556. c = Commit()
  557. c.tree = subtree.id
  558. c.committer = c.author = b"Somebody <somebody@example.com>"
  559. c.commit_time = c.author_time = 42342
  560. c.commit_timezone = c.author_timezone = 0
  561. c.parents = []
  562. c.message = b"Subcommit"
  563. tree = Tree()
  564. tree[b"c"] = (S_IFGITLINK, c.id)
  565. os.mkdir(os.path.join(repo_dir, "c"))
  566. repo.object_store.add_objects([(o, None) for o in [tree]])
  567. build_index_from_tree(
  568. repo.path, repo.index_path(), repo.object_store, tree.id
  569. )
  570. # Verify index entries
  571. index = repo.open_index()
  572. self.assertEqual(len(index), 1)
  573. # filea
  574. apath = os.path.join(repo.path, "c/a")
  575. self.assertFalse(os.path.exists(apath))
  576. # dir c
  577. cpath = os.path.join(repo.path, "c")
  578. self.assertTrue(os.path.isdir(cpath))
  579. self.assertEqual(index[b"c"].mode, S_IFGITLINK) # mode
  580. self.assertEqual(index[b"c"].sha, c.id) # sha
  581. class GetUnstagedChangesTests(TestCase):
  582. def test_get_unstaged_changes(self) -> None:
  583. """Unit test for get_unstaged_changes."""
  584. repo_dir = tempfile.mkdtemp()
  585. self.addCleanup(shutil.rmtree, repo_dir)
  586. with Repo.init(repo_dir) as repo:
  587. # Commit a dummy file then modify it
  588. foo1_fullpath = os.path.join(repo_dir, "foo1")
  589. with open(foo1_fullpath, "wb") as f:
  590. f.write(b"origstuff")
  591. foo2_fullpath = os.path.join(repo_dir, "foo2")
  592. with open(foo2_fullpath, "wb") as f:
  593. f.write(b"origstuff")
  594. repo.stage(["foo1", "foo2"])
  595. repo.do_commit(
  596. b"test status",
  597. author=b"author <email>",
  598. committer=b"committer <email>",
  599. )
  600. with open(foo1_fullpath, "wb") as f:
  601. f.write(b"newstuff")
  602. # modify access and modify time of path
  603. os.utime(foo1_fullpath, (0, 0))
  604. changes = get_unstaged_changes(repo.open_index(), repo_dir)
  605. self.assertEqual(list(changes), [b"foo1"])
  606. def test_get_unstaged_deleted_changes(self) -> None:
  607. """Unit test for get_unstaged_changes."""
  608. repo_dir = tempfile.mkdtemp()
  609. self.addCleanup(shutil.rmtree, repo_dir)
  610. with Repo.init(repo_dir) as repo:
  611. # Commit a dummy file then remove it
  612. foo1_fullpath = os.path.join(repo_dir, "foo1")
  613. with open(foo1_fullpath, "wb") as f:
  614. f.write(b"origstuff")
  615. repo.stage(["foo1"])
  616. repo.do_commit(
  617. b"test status",
  618. author=b"author <email>",
  619. committer=b"committer <email>",
  620. )
  621. os.unlink(foo1_fullpath)
  622. changes = get_unstaged_changes(repo.open_index(), repo_dir)
  623. self.assertEqual(list(changes), [b"foo1"])
  624. def test_get_unstaged_changes_removed_replaced_by_directory(self) -> None:
  625. """Unit test for get_unstaged_changes."""
  626. repo_dir = tempfile.mkdtemp()
  627. self.addCleanup(shutil.rmtree, repo_dir)
  628. with Repo.init(repo_dir) as repo:
  629. # Commit a dummy file then modify it
  630. foo1_fullpath = os.path.join(repo_dir, "foo1")
  631. with open(foo1_fullpath, "wb") as f:
  632. f.write(b"origstuff")
  633. repo.stage(["foo1"])
  634. repo.do_commit(
  635. b"test status",
  636. author=b"author <email>",
  637. committer=b"committer <email>",
  638. )
  639. os.remove(foo1_fullpath)
  640. os.mkdir(foo1_fullpath)
  641. changes = get_unstaged_changes(repo.open_index(), repo_dir)
  642. self.assertEqual(list(changes), [b"foo1"])
  643. @skipIf(not can_symlink(), "Requires symlink support")
  644. def test_get_unstaged_changes_removed_replaced_by_link(self) -> None:
  645. """Unit test for get_unstaged_changes."""
  646. repo_dir = tempfile.mkdtemp()
  647. self.addCleanup(shutil.rmtree, repo_dir)
  648. with Repo.init(repo_dir) as repo:
  649. # Commit a dummy file then modify it
  650. foo1_fullpath = os.path.join(repo_dir, "foo1")
  651. with open(foo1_fullpath, "wb") as f:
  652. f.write(b"origstuff")
  653. repo.stage(["foo1"])
  654. repo.do_commit(
  655. b"test status",
  656. author=b"author <email>",
  657. committer=b"committer <email>",
  658. )
  659. os.remove(foo1_fullpath)
  660. os.symlink(os.path.dirname(foo1_fullpath), foo1_fullpath)
  661. changes = get_unstaged_changes(repo.open_index(), repo_dir)
  662. self.assertEqual(list(changes), [b"foo1"])
  663. class TestValidatePathElement(TestCase):
  664. def test_default(self) -> None:
  665. self.assertTrue(validate_path_element_default(b"bla"))
  666. self.assertTrue(validate_path_element_default(b".bla"))
  667. self.assertFalse(validate_path_element_default(b".git"))
  668. self.assertFalse(validate_path_element_default(b".giT"))
  669. self.assertFalse(validate_path_element_default(b".."))
  670. self.assertTrue(validate_path_element_default(b"git~1"))
  671. def test_ntfs(self) -> None:
  672. self.assertTrue(validate_path_element_ntfs(b"bla"))
  673. self.assertTrue(validate_path_element_ntfs(b".bla"))
  674. self.assertFalse(validate_path_element_ntfs(b".git"))
  675. self.assertFalse(validate_path_element_ntfs(b".giT"))
  676. self.assertFalse(validate_path_element_ntfs(b".."))
  677. self.assertFalse(validate_path_element_ntfs(b"git~1"))
  678. class TestTreeFSPathConversion(TestCase):
  679. def test_tree_to_fs_path(self) -> None:
  680. tree_path = "délwíçh/foo".encode()
  681. fs_path = _tree_to_fs_path(b"/prefix/path", tree_path)
  682. self.assertEqual(
  683. fs_path,
  684. os.fsencode(os.path.join("/prefix/path", "délwíçh", "foo")),
  685. )
  686. def test_tree_to_fs_path_windows_separator(self) -> None:
  687. tree_path = b"path/with/slash"
  688. original_sep = os.sep.encode("ascii")
  689. try:
  690. # Temporarily modify os_sep_bytes to test Windows path conversion
  691. # This simulates Windows behavior on all platforms for testing
  692. import dulwich.index
  693. dulwich.index.os_sep_bytes = b"\\"
  694. fs_path = _tree_to_fs_path(b"/prefix/path", tree_path)
  695. # The function should join the prefix path with the converted tree path
  696. # The expected behavior is that the path separators in the tree_path are
  697. # converted to the platform-specific separator (which we've set to backslash)
  698. expected_path = os.path.join(b"/prefix/path", b"path\\with\\slash")
  699. self.assertEqual(fs_path, expected_path)
  700. finally:
  701. # Restore original value
  702. dulwich.index.os_sep_bytes = original_sep
  703. def test_fs_to_tree_path_str(self) -> None:
  704. fs_path = os.path.join(os.path.join("délwíçh", "foo"))
  705. tree_path = _fs_to_tree_path(fs_path)
  706. self.assertEqual(tree_path, "délwíçh/foo".encode())
  707. def test_fs_to_tree_path_bytes(self) -> None:
  708. fs_path = os.path.join(os.fsencode(os.path.join("délwíçh", "foo")))
  709. tree_path = _fs_to_tree_path(fs_path)
  710. self.assertEqual(tree_path, "délwíçh/foo".encode())
  711. def test_fs_to_tree_path_windows_separator(self) -> None:
  712. # Test conversion of Windows paths to tree paths
  713. fs_path = b"path\\with\\backslash"
  714. original_sep = os.sep.encode("ascii")
  715. try:
  716. # Temporarily modify os_sep_bytes to test Windows path conversion
  717. import dulwich.index
  718. dulwich.index.os_sep_bytes = b"\\"
  719. tree_path = _fs_to_tree_path(fs_path)
  720. self.assertEqual(tree_path, b"path/with/backslash")
  721. finally:
  722. # Restore original value
  723. dulwich.index.os_sep_bytes = original_sep
  724. class TestIndexEntryFromPath(TestCase):
  725. def setUp(self):
  726. self.tempdir = tempfile.mkdtemp()
  727. self.addCleanup(shutil.rmtree, self.tempdir)
  728. def test_index_entry_from_path_file(self) -> None:
  729. """Test creating index entry from a regular file."""
  730. # Create a test file
  731. test_file = os.path.join(self.tempdir, "testfile")
  732. with open(test_file, "wb") as f:
  733. f.write(b"test content")
  734. # Get the index entry
  735. entry = index_entry_from_path(os.fsencode(test_file))
  736. # Verify the entry was created with the right mode
  737. self.assertIsNotNone(entry)
  738. self.assertEqual(cleanup_mode(os.stat(test_file).st_mode), entry.mode)
  739. @skipIf(not can_symlink(), "Requires symlink support")
  740. def test_index_entry_from_path_symlink(self) -> None:
  741. """Test creating index entry from a symlink."""
  742. # Create a target file
  743. target_file = os.path.join(self.tempdir, "target")
  744. with open(target_file, "wb") as f:
  745. f.write(b"target content")
  746. # Create a symlink
  747. link_file = os.path.join(self.tempdir, "symlink")
  748. os.symlink(target_file, link_file)
  749. # Get the index entry
  750. entry = index_entry_from_path(os.fsencode(link_file))
  751. # Verify the entry was created with the right mode
  752. self.assertIsNotNone(entry)
  753. self.assertEqual(cleanup_mode(os.lstat(link_file).st_mode), entry.mode)
  754. def test_index_entry_from_path_directory(self) -> None:
  755. """Test creating index entry from a directory (should return None)."""
  756. # Create a directory
  757. test_dir = os.path.join(self.tempdir, "testdir")
  758. os.mkdir(test_dir)
  759. # Get the index entry for a directory
  760. entry = index_entry_from_path(os.fsencode(test_dir))
  761. # Should return None for regular directories
  762. self.assertIsNone(entry)
  763. def test_index_entry_from_directory_regular(self) -> None:
  764. """Test index_entry_from_directory with a regular directory."""
  765. # Create a directory
  766. test_dir = os.path.join(self.tempdir, "testdir")
  767. os.mkdir(test_dir)
  768. # Get stat for the directory
  769. st = os.lstat(test_dir)
  770. # Get the index entry for a regular directory
  771. entry = index_entry_from_directory(st, os.fsencode(test_dir))
  772. # Should return None for regular directories
  773. self.assertIsNone(entry)
  774. def test_index_entry_from_directory_git_submodule(self) -> None:
  775. """Test index_entry_from_directory with a Git submodule."""
  776. # Create a git repository that will be a submodule
  777. sub_repo_dir = os.path.join(self.tempdir, "subrepo")
  778. os.mkdir(sub_repo_dir)
  779. # Create the .git directory to make it look like a git repo
  780. git_dir = os.path.join(sub_repo_dir, ".git")
  781. os.mkdir(git_dir)
  782. # Create HEAD file with a fake commit SHA
  783. head_sha = b"1234567890" * 4 # 40-char fake SHA
  784. with open(os.path.join(git_dir, "HEAD"), "wb") as f:
  785. f.write(head_sha)
  786. # Get stat for the submodule directory
  787. st = os.lstat(sub_repo_dir)
  788. # Get the index entry for a git submodule directory
  789. entry = index_entry_from_directory(st, os.fsencode(sub_repo_dir))
  790. # Since we don't have a proper git setup, this might still return None
  791. # This test just ensures the code path is executed
  792. if entry is not None:
  793. # If an entry is returned, it should have the gitlink mode
  794. self.assertEqual(entry.mode, S_IFGITLINK)
  795. def test_index_entry_from_path_with_object_store(self) -> None:
  796. """Test creating index entry with object store."""
  797. # Create a test file
  798. test_file = os.path.join(self.tempdir, "testfile")
  799. with open(test_file, "wb") as f:
  800. f.write(b"test content")
  801. # Create a memory object store
  802. object_store = MemoryObjectStore()
  803. # Get the index entry and add to object store
  804. entry = index_entry_from_path(os.fsencode(test_file), object_store)
  805. # Verify we can access the blob from the object store
  806. self.assertIsNotNone(entry)
  807. blob = object_store[entry.sha]
  808. self.assertEqual(b"test content", blob.data)
  809. def test_iter_fresh_entries(self) -> None:
  810. """Test iterating over fresh entries."""
  811. # Create some test files
  812. file1 = os.path.join(self.tempdir, "file1")
  813. with open(file1, "wb") as f:
  814. f.write(b"file1 content")
  815. file2 = os.path.join(self.tempdir, "file2")
  816. with open(file2, "wb") as f:
  817. f.write(b"file2 content")
  818. # Create a memory object store
  819. object_store = MemoryObjectStore()
  820. # Get fresh entries
  821. paths = [b"file1", b"file2", b"nonexistent"]
  822. entries = dict(
  823. iter_fresh_entries(paths, os.fsencode(self.tempdir), object_store)
  824. )
  825. # Verify both files got entries but nonexistent file is None
  826. self.assertIn(b"file1", entries)
  827. self.assertIn(b"file2", entries)
  828. self.assertIn(b"nonexistent", entries)
  829. self.assertIsNotNone(entries[b"file1"])
  830. self.assertIsNotNone(entries[b"file2"])
  831. self.assertIsNone(entries[b"nonexistent"])
  832. # Check that blobs were added to object store
  833. blob1 = object_store[entries[b"file1"].sha]
  834. self.assertEqual(b"file1 content", blob1.data)
  835. blob2 = object_store[entries[b"file2"].sha]
  836. self.assertEqual(b"file2 content", blob2.data)
  837. def test_read_submodule_head(self) -> None:
  838. """Test reading the HEAD of a submodule."""
  839. from dulwich.index import read_submodule_head
  840. from dulwich.repo import Repo
  841. # Create a test repo that will be our "submodule"
  842. sub_repo_dir = os.path.join(self.tempdir, "subrepo")
  843. os.mkdir(sub_repo_dir)
  844. submodule_repo = Repo.init(sub_repo_dir)
  845. # Create a file and commit it to establish a HEAD
  846. test_file = os.path.join(sub_repo_dir, "testfile")
  847. with open(test_file, "wb") as f:
  848. f.write(b"test content")
  849. submodule_repo.stage(["testfile"])
  850. commit_id = submodule_repo.do_commit(b"Test commit for submodule")
  851. # Test reading the HEAD
  852. head_sha = read_submodule_head(sub_repo_dir)
  853. self.assertEqual(commit_id, head_sha)
  854. # Test with bytes path
  855. head_sha_bytes = read_submodule_head(os.fsencode(sub_repo_dir))
  856. self.assertEqual(commit_id, head_sha_bytes)
  857. # Test with non-existent path
  858. non_repo_dir = os.path.join(self.tempdir, "nonrepo")
  859. os.mkdir(non_repo_dir)
  860. self.assertIsNone(read_submodule_head(non_repo_dir))
  861. # Test with path that doesn't have a .git directory
  862. not_git_dir = os.path.join(self.tempdir, "notgit")
  863. os.mkdir(not_git_dir)
  864. self.assertIsNone(read_submodule_head(not_git_dir))
  865. def test_has_directory_changed(self) -> None:
  866. """Test checking if a directory has changed."""
  867. from dulwich.index import IndexEntry, _has_directory_changed
  868. from dulwich.repo import Repo
  869. # Setup mock IndexEntry
  870. mock_entry = IndexEntry(
  871. (1230680220, 0),
  872. (1230680220, 0),
  873. 2050,
  874. 3761020,
  875. 33188,
  876. 1000,
  877. 1000,
  878. 0,
  879. b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391",
  880. 0,
  881. 0,
  882. )
  883. # Test with a regular directory (not a submodule)
  884. reg_dir = os.path.join(self.tempdir, "regular_dir")
  885. os.mkdir(reg_dir)
  886. # Should return True for regular directory
  887. self.assertTrue(_has_directory_changed(os.fsencode(reg_dir), mock_entry))
  888. # Create a git repository to test submodule scenarios
  889. sub_repo_dir = os.path.join(self.tempdir, "subrepo")
  890. os.mkdir(sub_repo_dir)
  891. submodule_repo = Repo.init(sub_repo_dir)
  892. # Create a file and commit it to establish a HEAD
  893. test_file = os.path.join(sub_repo_dir, "testfile")
  894. with open(test_file, "wb") as f:
  895. f.write(b"test content")
  896. submodule_repo.stage(["testfile"])
  897. commit_id = submodule_repo.do_commit(b"Test commit for submodule")
  898. # Create an entry with the correct commit SHA
  899. correct_entry = IndexEntry(
  900. (1230680220, 0),
  901. (1230680220, 0),
  902. 2050,
  903. 3761020,
  904. 33188,
  905. 1000,
  906. 1000,
  907. 0,
  908. commit_id,
  909. 0,
  910. 0,
  911. )
  912. # Create an entry with an incorrect commit SHA
  913. incorrect_entry = IndexEntry(
  914. (1230680220, 0),
  915. (1230680220, 0),
  916. 2050,
  917. 3761020,
  918. 33188,
  919. 1000,
  920. 1000,
  921. 0,
  922. b"0000000000000000000000000000000000000000",
  923. 0,
  924. 0,
  925. )
  926. # Should return False for submodule with correct SHA
  927. self.assertFalse(
  928. _has_directory_changed(os.fsencode(sub_repo_dir), correct_entry)
  929. )
  930. # Should return True for submodule with incorrect SHA
  931. self.assertTrue(
  932. _has_directory_changed(os.fsencode(sub_repo_dir), incorrect_entry)
  933. )
  934. def test_get_unstaged_changes(self) -> None:
  935. """Test detecting unstaged changes in a working tree."""
  936. from dulwich.index import (
  937. ConflictedIndexEntry,
  938. Index,
  939. IndexEntry,
  940. get_unstaged_changes,
  941. )
  942. # Create a test repo
  943. repo_dir = tempfile.mkdtemp()
  944. self.addCleanup(shutil.rmtree, repo_dir)
  945. # Create test index
  946. index = Index(os.path.join(repo_dir, "index"))
  947. # Create an actual hash of our test content
  948. from dulwich.objects import Blob
  949. test_blob = Blob()
  950. test_blob.data = b"initial content"
  951. # Create some test files with known contents
  952. file1_path = os.path.join(repo_dir, "file1")
  953. with open(file1_path, "wb") as f:
  954. f.write(b"initial content")
  955. file2_path = os.path.join(repo_dir, "file2")
  956. with open(file2_path, "wb") as f:
  957. f.write(b"initial content")
  958. # Add them to index
  959. entry1 = IndexEntry(
  960. (1230680220, 0),
  961. (1230680220, 0),
  962. 2050,
  963. 3761020,
  964. 33188,
  965. 1000,
  966. 1000,
  967. 0,
  968. b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", # Not matching actual content
  969. 0,
  970. 0,
  971. )
  972. entry2 = IndexEntry(
  973. (1230680220, 0),
  974. (1230680220, 0),
  975. 2050,
  976. 3761020,
  977. 33188,
  978. 1000,
  979. 1000,
  980. 0,
  981. test_blob.id, # Will be content's real hash
  982. 0,
  983. 0,
  984. )
  985. # Add a file that has a conflict
  986. entry_conflict = ConflictedIndexEntry(b"conflict", {0: None, 1: None, 2: None})
  987. index._byname = {
  988. b"file1": entry1,
  989. b"file2": entry2,
  990. b"file3": IndexEntry(
  991. (1230680220, 0),
  992. (1230680220, 0),
  993. 2050,
  994. 3761020,
  995. 33188,
  996. 1000,
  997. 1000,
  998. 0,
  999. b"0000000000000000000000000000000000000000",
  1000. 0,
  1001. 0,
  1002. ),
  1003. b"conflict": entry_conflict,
  1004. }
  1005. # Get unstaged changes
  1006. changes = list(get_unstaged_changes(index, repo_dir))
  1007. # File1 should be unstaged (content doesn't match hash)
  1008. # File3 doesn't exist (deleted)
  1009. # Conflict is always unstaged
  1010. self.assertEqual(sorted(changes), [b"conflict", b"file1", b"file3"])
  1011. # Create directory where there should be a file
  1012. os.mkdir(os.path.join(repo_dir, "file4"))
  1013. index._byname[b"file4"] = entry1
  1014. # Get unstaged changes again
  1015. changes = list(get_unstaged_changes(index, repo_dir))
  1016. # Now file4 should also be unstaged because it's a directory instead of a file
  1017. self.assertEqual(sorted(changes), [b"conflict", b"file1", b"file3", b"file4"])
  1018. # Create a custom blob filter function
  1019. def filter_blob_callback(blob, path):
  1020. # Modify blob to make it look changed
  1021. blob.data = b"modified " + blob.data
  1022. return blob
  1023. # Get unstaged changes with blob filter
  1024. changes = list(get_unstaged_changes(index, repo_dir, filter_blob_callback))
  1025. # Now both file1 and file2 should be unstaged due to the filter
  1026. self.assertEqual(
  1027. sorted(changes), [b"conflict", b"file1", b"file2", b"file3", b"file4"]
  1028. )
  1029. class TestManyFilesFeature(TestCase):
  1030. """Tests for the manyFiles feature (index version 4 and skipHash)."""
  1031. def setUp(self):
  1032. self.tempdir = tempfile.mkdtemp()
  1033. self.addCleanup(shutil.rmtree, self.tempdir)
  1034. def test_index_version_4_parsing(self):
  1035. """Test that index version 4 files can be parsed."""
  1036. index_path = os.path.join(self.tempdir, "index")
  1037. # Create an index with version 4
  1038. index = Index(index_path, read=False, version=4)
  1039. # Add some entries
  1040. entry = IndexEntry(
  1041. ctime=(1234567890, 0),
  1042. mtime=(1234567890, 0),
  1043. dev=1,
  1044. ino=1,
  1045. mode=0o100644,
  1046. uid=1000,
  1047. gid=1000,
  1048. size=5,
  1049. sha=b"0" * 40,
  1050. )
  1051. index[b"test.txt"] = entry
  1052. # Write and read back
  1053. index.write()
  1054. # Read the index back
  1055. index2 = Index(index_path)
  1056. self.assertEqual(index2._version, 4)
  1057. self.assertIn(b"test.txt", index2)
  1058. def test_skip_hash_feature(self):
  1059. """Test that skipHash feature works correctly."""
  1060. index_path = os.path.join(self.tempdir, "index")
  1061. # Create an index with skipHash enabled
  1062. index = Index(index_path, read=False, skip_hash=True)
  1063. # Add some entries
  1064. entry = IndexEntry(
  1065. ctime=(1234567890, 0),
  1066. mtime=(1234567890, 0),
  1067. dev=1,
  1068. ino=1,
  1069. mode=0o100644,
  1070. uid=1000,
  1071. gid=1000,
  1072. size=5,
  1073. sha=b"0" * 40,
  1074. )
  1075. index[b"test.txt"] = entry
  1076. # Write the index
  1077. index.write()
  1078. # Verify the file was written with zero hash
  1079. with open(index_path, "rb") as f:
  1080. f.seek(-20, 2) # Seek to last 20 bytes
  1081. trailing_hash = f.read(20)
  1082. self.assertEqual(trailing_hash, b"\x00" * 20)
  1083. # Verify we can still read it back
  1084. index2 = Index(index_path)
  1085. self.assertIn(b"test.txt", index2)
  1086. def test_version_4_no_padding(self):
  1087. """Test that version 4 entries have no padding."""
  1088. # Create entries with names that would show compression benefits
  1089. entries = [
  1090. SerializedIndexEntry(
  1091. name=b"src/main/java/com/example/Service.java",
  1092. ctime=(1234567890, 0),
  1093. mtime=(1234567890, 0),
  1094. dev=1,
  1095. ino=1,
  1096. mode=0o100644,
  1097. uid=1000,
  1098. gid=1000,
  1099. size=5,
  1100. sha=b"0" * 40,
  1101. flags=0,
  1102. extended_flags=0,
  1103. ),
  1104. SerializedIndexEntry(
  1105. name=b"src/main/java/com/example/Controller.java",
  1106. ctime=(1234567890, 0),
  1107. mtime=(1234567890, 0),
  1108. dev=1,
  1109. ino=2,
  1110. mode=0o100644,
  1111. uid=1000,
  1112. gid=1000,
  1113. size=5,
  1114. sha=b"1" * 40,
  1115. flags=0,
  1116. extended_flags=0,
  1117. ),
  1118. ]
  1119. # Test version 2 (with padding, full paths)
  1120. buf_v2 = BytesIO()
  1121. from dulwich.index import write_cache_entry
  1122. previous_path = b""
  1123. for entry in entries:
  1124. # Set proper flags for v2
  1125. entry_v2 = SerializedIndexEntry(
  1126. entry.name,
  1127. entry.ctime,
  1128. entry.mtime,
  1129. entry.dev,
  1130. entry.ino,
  1131. entry.mode,
  1132. entry.uid,
  1133. entry.gid,
  1134. entry.size,
  1135. entry.sha,
  1136. len(entry.name),
  1137. entry.extended_flags,
  1138. )
  1139. write_cache_entry(buf_v2, entry_v2, version=2, previous_path=previous_path)
  1140. previous_path = entry.name
  1141. v2_data = buf_v2.getvalue()
  1142. # Test version 4 (path compression, no padding)
  1143. buf_v4 = BytesIO()
  1144. previous_path = b""
  1145. for entry in entries:
  1146. write_cache_entry(buf_v4, entry, version=4, previous_path=previous_path)
  1147. previous_path = entry.name
  1148. v4_data = buf_v4.getvalue()
  1149. # Version 4 should be shorter due to compression and no padding
  1150. self.assertLess(len(v4_data), len(v2_data))
  1151. # Both should parse correctly
  1152. buf_v2.seek(0)
  1153. from dulwich.index import read_cache_entry
  1154. previous_path = b""
  1155. parsed_v2_entries = []
  1156. for _ in entries:
  1157. parsed = read_cache_entry(buf_v2, version=2, previous_path=previous_path)
  1158. parsed_v2_entries.append(parsed)
  1159. previous_path = parsed.name
  1160. buf_v4.seek(0)
  1161. previous_path = b""
  1162. parsed_v4_entries = []
  1163. for _ in entries:
  1164. parsed = read_cache_entry(buf_v4, version=4, previous_path=previous_path)
  1165. parsed_v4_entries.append(parsed)
  1166. previous_path = parsed.name
  1167. # Both should have the same paths
  1168. for v2_entry, v4_entry in zip(parsed_v2_entries, parsed_v4_entries):
  1169. self.assertEqual(v2_entry.name, v4_entry.name)
  1170. self.assertEqual(v2_entry.sha, v4_entry.sha)
  1171. class TestManyFilesRepoIntegration(TestCase):
  1172. """Tests for manyFiles feature integration with Repo."""
  1173. def setUp(self):
  1174. self.tempdir = tempfile.mkdtemp()
  1175. self.addCleanup(shutil.rmtree, self.tempdir)
  1176. def test_repo_with_manyfiles_config(self):
  1177. """Test that a repository with feature.manyFiles=true uses the right settings."""
  1178. from dulwich.repo import Repo
  1179. # Create a new repository
  1180. repo = Repo.init(self.tempdir)
  1181. # Set feature.manyFiles=true in config
  1182. config = repo.get_config()
  1183. config.set(b"feature", b"manyFiles", b"true")
  1184. config.write_to_path()
  1185. # Open the index - should have skipHash enabled and version 4
  1186. index = repo.open_index()
  1187. self.assertTrue(index._skip_hash)
  1188. self.assertEqual(index._version, 4)
  1189. def test_repo_with_explicit_index_settings(self):
  1190. """Test that explicit index.version and index.skipHash work."""
  1191. from dulwich.repo import Repo
  1192. # Create a new repository
  1193. repo = Repo.init(self.tempdir)
  1194. # Set explicit index settings
  1195. config = repo.get_config()
  1196. config.set(b"index", b"version", b"3")
  1197. config.set(b"index", b"skipHash", b"false")
  1198. config.write_to_path()
  1199. # Open the index - should respect explicit settings
  1200. index = repo.open_index()
  1201. self.assertFalse(index._skip_hash)
  1202. self.assertEqual(index._version, 3)
  1203. class TestPathPrefixCompression(TestCase):
  1204. """Tests for index version 4 path prefix compression."""
  1205. def setUp(self):
  1206. self.tempdir = tempfile.mkdtemp()
  1207. self.addCleanup(shutil.rmtree, self.tempdir)
  1208. def test_varint_encoding_decoding(self):
  1209. """Test variable-width integer encoding and decoding."""
  1210. from dulwich.index import _decode_varint, _encode_varint
  1211. test_values = [0, 1, 127, 128, 255, 256, 16383, 16384, 65535, 65536]
  1212. for value in test_values:
  1213. encoded = _encode_varint(value)
  1214. decoded, _ = _decode_varint(encoded, 0)
  1215. self.assertEqual(value, decoded, f"Failed for value {value}")
  1216. def test_path_compression_simple(self):
  1217. """Test simple path compression cases."""
  1218. from dulwich.index import _compress_path, _decompress_path
  1219. # Test case 1: No common prefix
  1220. compressed = _compress_path(b"file1.txt", b"")
  1221. decompressed, _ = _decompress_path(compressed, 0, b"")
  1222. self.assertEqual(b"file1.txt", decompressed)
  1223. # Test case 2: Common prefix
  1224. compressed = _compress_path(b"src/file2.txt", b"src/file1.txt")
  1225. decompressed, _ = _decompress_path(compressed, 0, b"src/file1.txt")
  1226. self.assertEqual(b"src/file2.txt", decompressed)
  1227. # Test case 3: Completely different paths
  1228. compressed = _compress_path(b"docs/readme.md", b"src/file1.txt")
  1229. decompressed, _ = _decompress_path(compressed, 0, b"src/file1.txt")
  1230. self.assertEqual(b"docs/readme.md", decompressed)
  1231. def test_path_compression_deep_directories(self):
  1232. """Test compression with deep directory structures."""
  1233. from dulwich.index import _compress_path, _decompress_path
  1234. path1 = b"src/main/java/com/example/service/UserService.java"
  1235. path2 = b"src/main/java/com/example/service/OrderService.java"
  1236. path3 = b"src/main/java/com/example/model/User.java"
  1237. # Compress path2 relative to path1
  1238. compressed = _compress_path(path2, path1)
  1239. decompressed, _ = _decompress_path(compressed, 0, path1)
  1240. self.assertEqual(path2, decompressed)
  1241. # Compress path3 relative to path2
  1242. compressed = _compress_path(path3, path2)
  1243. decompressed, _ = _decompress_path(compressed, 0, path2)
  1244. self.assertEqual(path3, decompressed)
  1245. def test_index_version_4_with_compression(self):
  1246. """Test full index version 4 write/read with path compression."""
  1247. index_path = os.path.join(self.tempdir, "index")
  1248. # Create an index with version 4
  1249. index = Index(index_path, read=False, version=4)
  1250. # Add multiple entries with common prefixes
  1251. paths = [
  1252. b"src/main/java/App.java",
  1253. b"src/main/java/Utils.java",
  1254. b"src/main/resources/config.properties",
  1255. b"src/test/java/AppTest.java",
  1256. b"docs/README.md",
  1257. b"docs/INSTALL.md",
  1258. ]
  1259. for i, path in enumerate(paths):
  1260. entry = IndexEntry(
  1261. ctime=(1234567890, 0),
  1262. mtime=(1234567890, 0),
  1263. dev=1,
  1264. ino=i + 1,
  1265. mode=0o100644,
  1266. uid=1000,
  1267. gid=1000,
  1268. size=10,
  1269. sha=f"{i:040d}".encode(),
  1270. )
  1271. index[path] = entry
  1272. # Write and read back
  1273. index.write()
  1274. # Read the index back
  1275. index2 = Index(index_path)
  1276. self.assertEqual(index2._version, 4)
  1277. # Verify all paths were preserved correctly
  1278. for path in paths:
  1279. self.assertIn(path, index2)
  1280. # Verify the index file is smaller than version 2 would be
  1281. with open(index_path, "rb") as f:
  1282. v4_size = len(f.read())
  1283. # Create equivalent version 2 index for comparison
  1284. index_v2_path = os.path.join(self.tempdir, "index_v2")
  1285. index_v2 = Index(index_v2_path, read=False, version=2)
  1286. for path in paths:
  1287. entry = IndexEntry(
  1288. ctime=(1234567890, 0),
  1289. mtime=(1234567890, 0),
  1290. dev=1,
  1291. ino=1,
  1292. mode=0o100644,
  1293. uid=1000,
  1294. gid=1000,
  1295. size=10,
  1296. sha=b"0" * 40,
  1297. )
  1298. index_v2[path] = entry
  1299. index_v2.write()
  1300. with open(index_v2_path, "rb") as f:
  1301. v2_size = len(f.read())
  1302. # Version 4 should be smaller due to compression
  1303. self.assertLess(
  1304. v4_size, v2_size, "Version 4 index should be smaller than version 2"
  1305. )
  1306. def test_path_compression_edge_cases(self):
  1307. """Test edge cases in path compression."""
  1308. from dulwich.index import _compress_path, _decompress_path
  1309. # Empty paths
  1310. compressed = _compress_path(b"", b"")
  1311. decompressed, _ = _decompress_path(compressed, 0, b"")
  1312. self.assertEqual(b"", decompressed)
  1313. # Path identical to previous
  1314. compressed = _compress_path(b"same.txt", b"same.txt")
  1315. decompressed, _ = _decompress_path(compressed, 0, b"same.txt")
  1316. self.assertEqual(b"same.txt", decompressed)
  1317. # Path shorter than previous
  1318. compressed = _compress_path(b"short", b"very/long/path/file.txt")
  1319. decompressed, _ = _decompress_path(compressed, 0, b"very/long/path/file.txt")
  1320. self.assertEqual(b"short", decompressed)