test_index.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. # test_index.py -- Git index compatibility tests
  2. # Copyright (C) 2024 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. """Compatibility tests for Git index format v4."""
  22. import os
  23. import tempfile
  24. from dulwich.index import Index, read_index_dict_with_version, write_index_dict
  25. from dulwich.repo import Repo
  26. from .utils import CompatTestCase, require_git_version, run_git, run_git_or_fail
  27. class IndexV4CompatTestCase(CompatTestCase):
  28. """Tests for Git index format v4 compatibility with C Git."""
  29. def setUp(self) -> None:
  30. super().setUp()
  31. self.tempdir = tempfile.mkdtemp()
  32. self.addCleanup(self._cleanup)
  33. def _cleanup(self) -> None:
  34. import shutil
  35. shutil.rmtree(self.tempdir, ignore_errors=True)
  36. def _init_repo_with_manyfiles(self) -> Repo:
  37. """Initialize a repo with manyFiles feature enabled."""
  38. # Create repo
  39. repo_path = os.path.join(self.tempdir, "test_repo")
  40. os.mkdir(repo_path)
  41. # Initialize with C git and enable manyFiles
  42. run_git_or_fail(["init"], cwd=repo_path)
  43. run_git_or_fail(["config", "feature.manyFiles", "true"], cwd=repo_path)
  44. # Open with dulwich
  45. return Repo(repo_path)
  46. def test_index_v4_path_compression(self) -> None:
  47. """Test that dulwich can read and write index v4 with path compression."""
  48. require_git_version((2, 20, 0)) # manyFiles feature requires newer Git
  49. repo = self._init_repo_with_manyfiles()
  50. # Create test files with paths that will benefit from compression
  51. test_files = [
  52. "dir1/subdir/file1.txt",
  53. "dir1/subdir/file2.txt",
  54. "dir1/subdir/file3.txt",
  55. "dir2/another/path.txt",
  56. "dir2/another/path2.txt",
  57. "file_at_root.txt",
  58. ]
  59. for path in test_files:
  60. full_path = os.path.join(repo.path, path)
  61. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  62. with open(full_path, "w") as f:
  63. f.write(f"content of {path}\n")
  64. # Add files with C git - this should create index v4
  65. run_git_or_fail(["add", "."], cwd=repo.path)
  66. # Read the index with dulwich
  67. index_path = os.path.join(repo.path, ".git", "index")
  68. with open(index_path, "rb") as f:
  69. entries, version, extensions = read_index_dict_with_version(f)
  70. # Verify it's version 4
  71. self.assertEqual(version, 4)
  72. # Verify all files are in the index
  73. self.assertEqual(len(entries), len(test_files))
  74. for path in test_files:
  75. self.assertIn(path.encode(), entries)
  76. # Write the index back with dulwich
  77. with open(index_path + ".dulwich", "wb") as f:
  78. from dulwich.pack import SHA1Writer
  79. sha1_writer = SHA1Writer(f)
  80. write_index_dict(sha1_writer, entries, version=4, extensions=extensions)
  81. sha1_writer.close()
  82. # Compare with C git - use git ls-files to read both indexes
  83. output1 = run_git_or_fail(["ls-files", "--stage"], cwd=repo.path)
  84. # Replace index with dulwich version
  85. if os.path.exists(index_path):
  86. os.remove(index_path)
  87. os.rename(index_path + ".dulwich", index_path)
  88. output2 = run_git_or_fail(["ls-files", "--stage"], cwd=repo.path)
  89. # Both outputs should be identical
  90. self.assertEqual(output1, output2)
  91. def test_index_v4_round_trip(self) -> None:
  92. """Test round-trip: C Git write -> dulwich read -> dulwich write -> C Git read."""
  93. require_git_version((2, 20, 0))
  94. repo = self._init_repo_with_manyfiles()
  95. # Create files that test various edge cases
  96. test_files = [
  97. "a", # Very short name
  98. "abc/def/ghi/jkl/mno/pqr/stu/vwx/yz.txt", # Deep path
  99. "same_prefix_1.txt",
  100. "same_prefix_2.txt",
  101. "same_prefix_3.txt",
  102. "different/path/here.txt",
  103. ]
  104. for path in test_files:
  105. full_path = os.path.join(repo.path, path)
  106. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  107. with open(full_path, "w") as f:
  108. f.write("test content\n")
  109. # Stage with C Git
  110. run_git_or_fail(["add", "."], cwd=repo.path)
  111. # Get original state
  112. original_output = run_git_or_fail(["ls-files", "--stage"], cwd=repo.path)
  113. # Read with dulwich, write back
  114. index = Index(os.path.join(repo.path, ".git", "index"))
  115. index.write()
  116. # Verify C Git can still read it
  117. final_output = run_git_or_fail(["ls-files", "--stage"], cwd=repo.path)
  118. self.assertEqual(original_output, final_output)
  119. def test_index_v4_skip_hash(self) -> None:
  120. """Test index v4 with skipHash extension."""
  121. require_git_version((2, 20, 0))
  122. repo = self._init_repo_with_manyfiles()
  123. # Enable skipHash
  124. run_git_or_fail(["config", "index.skipHash", "true"], cwd=repo.path)
  125. # Create a file
  126. test_file = os.path.join(repo.path, "test.txt")
  127. with open(test_file, "w") as f:
  128. f.write("test content\n")
  129. # Add with C Git
  130. run_git_or_fail(["add", "test.txt"], cwd=repo.path)
  131. # Read the index
  132. index_path = os.path.join(repo.path, ".git", "index")
  133. with open(index_path, "rb") as f:
  134. entries, version, extensions = read_index_dict_with_version(f)
  135. self.assertEqual(version, 4)
  136. self.assertIn(b"test.txt", entries)
  137. # Verify skipHash is active by checking last 20 bytes
  138. with open(index_path, "rb") as f:
  139. f.seek(-20, 2)
  140. last_bytes = f.read(20)
  141. self.assertEqual(last_bytes, b"\x00" * 20)
  142. # Write with dulwich (with skipHash)
  143. index = Index(index_path, skip_hash=True, version=4)
  144. index.write()
  145. # Verify C Git can read it
  146. output = run_git_or_fail(["ls-files"], cwd=repo.path)
  147. self.assertEqual(output.strip(), b"test.txt")
  148. def test_index_v4_with_various_filenames(self) -> None:
  149. """Test v4 with various filename patterns."""
  150. require_git_version((2, 20, 0))
  151. repo = self._init_repo_with_manyfiles()
  152. # Test various filename patterns that might trigger different behaviors
  153. test_files = [
  154. "a", # Single character
  155. "ab", # Two characters
  156. "abc", # Three characters
  157. "file.txt", # Normal filename
  158. "very_long_filename_to_test_edge_cases.extension", # Long filename
  159. "dir/file.txt", # With directory
  160. "dir1/dir2/dir3/file.txt", # Deep directory
  161. "unicode_café.txt", # Unicode filename
  162. "with-dashes-and_underscores.txt", # Special chars
  163. ".hidden", # Hidden file
  164. "UPPERCASE.TXT", # Uppercase
  165. ]
  166. for filename in test_files:
  167. filepath = os.path.join(repo.path, filename)
  168. os.makedirs(os.path.dirname(filepath), exist_ok=True)
  169. with open(filepath, "w", encoding="utf-8") as f:
  170. f.write(f"Content of {filename}\n")
  171. # Add all files
  172. run_git_or_fail(["add", "."], cwd=repo.path)
  173. # Read with dulwich
  174. index_path = os.path.join(repo.path, ".git", "index")
  175. with open(index_path, "rb") as f:
  176. entries, version, extensions = read_index_dict_with_version(f)
  177. self.assertEqual(version, 4)
  178. self.assertEqual(len(entries), len(test_files))
  179. # Verify all filenames are correctly stored
  180. for filename in test_files:
  181. filename_bytes = filename.encode("utf-8")
  182. self.assertIn(filename_bytes, entries)
  183. # Test round-trip: dulwich write -> C Git read
  184. with open(index_path + ".dulwich", "wb") as f:
  185. from dulwich.pack import SHA1Writer
  186. sha1_writer = SHA1Writer(f)
  187. write_index_dict(sha1_writer, entries, version=4, extensions=extensions)
  188. sha1_writer.close()
  189. # Replace index
  190. if os.path.exists(index_path):
  191. os.remove(index_path)
  192. os.rename(index_path + ".dulwich", index_path)
  193. # Verify C Git can read all files
  194. # Use -z flag to avoid quoting of non-ASCII filenames
  195. output = run_git_or_fail(["ls-files", "-z"], cwd=repo.path)
  196. git_files = set(output.strip(b"\x00").split(b"\x00"))
  197. expected_files = {f.encode("utf-8") for f in test_files}
  198. self.assertEqual(git_files, expected_files)
  199. def test_index_v4_path_compression_scenarios(self) -> None:
  200. """Test various scenarios where path compression should/shouldn't be used."""
  201. require_git_version((2, 20, 0))
  202. repo = self._init_repo_with_manyfiles()
  203. # Create files that should trigger compression
  204. compression_files = [
  205. "src/main/java/com/example/Service.java",
  206. "src/main/java/com/example/Controller.java",
  207. "src/main/java/com/example/Repository.java",
  208. "src/test/java/com/example/ServiceTest.java",
  209. ]
  210. # Create files that shouldn't benefit much from compression
  211. no_compression_files = [
  212. "README.md",
  213. "LICENSE",
  214. "docs/guide.txt",
  215. "config/settings.json",
  216. ]
  217. all_files = compression_files + no_compression_files
  218. for filename in all_files:
  219. filepath = os.path.join(repo.path, filename)
  220. os.makedirs(os.path.dirname(filepath), exist_ok=True)
  221. with open(filepath, "w") as f:
  222. f.write(f"Content of {filename}\n")
  223. # Add files
  224. run_git_or_fail(["add", "."], cwd=repo.path)
  225. # Read the index
  226. index_path = os.path.join(repo.path, ".git", "index")
  227. with open(index_path, "rb") as f:
  228. entries, version, extensions = read_index_dict_with_version(f)
  229. self.assertEqual(version, 4)
  230. self.assertEqual(len(entries), len(all_files))
  231. # Verify all files are present
  232. for filename in all_files:
  233. self.assertIn(filename.encode(), entries)
  234. # Test that dulwich can write a compatible index
  235. with open(index_path + ".dulwich", "wb") as f:
  236. from dulwich.pack import SHA1Writer
  237. sha1_writer = SHA1Writer(f)
  238. write_index_dict(sha1_writer, entries, version=4, extensions=extensions)
  239. sha1_writer.close()
  240. # Verify the written index is the same size (for byte-for-byte compatibility)
  241. original_size = os.path.getsize(index_path)
  242. dulwich_size = os.path.getsize(index_path + ".dulwich")
  243. # For v4 format with proper compression, checksum, and extensions, sizes should match
  244. self.assertEqual(
  245. original_size,
  246. dulwich_size,
  247. f"Index sizes don't match: Git={original_size}, Dulwich={dulwich_size}",
  248. )
  249. def test_index_v4_with_extensions(self) -> None:
  250. """Test v4 index with various extensions."""
  251. require_git_version((2, 20, 0))
  252. repo = self._init_repo_with_manyfiles()
  253. # Create some files
  254. files = ["file1.txt", "file2.txt", "dir/file3.txt"]
  255. for filename in files:
  256. filepath = os.path.join(repo.path, filename)
  257. os.makedirs(os.path.dirname(filepath), exist_ok=True)
  258. with open(filepath, "w") as f:
  259. f.write("content\n")
  260. # Add files
  261. run_git_or_fail(["add", "."], cwd=repo.path)
  262. # Enable untracked cache (creates UNTR extension)
  263. run_git_or_fail(["config", "core.untrackedCache", "true"], cwd=repo.path)
  264. run_git_or_fail(["status"], cwd=repo.path) # Trigger cache update
  265. # Read index with extensions
  266. index_path = os.path.join(repo.path, ".git", "index")
  267. with open(index_path, "rb") as f:
  268. entries, version, extensions = read_index_dict_with_version(f)
  269. self.assertEqual(version, 4)
  270. self.assertEqual(len(entries), len(files))
  271. # Test round-trip with extensions present
  272. index = Index(index_path)
  273. index.write()
  274. # Verify C Git can still read it
  275. output = run_git_or_fail(["ls-files"], cwd=repo.path)
  276. git_files = set(output.strip().split(b"\n"))
  277. expected_files = {f.encode() for f in files}
  278. self.assertEqual(git_files, expected_files)
  279. def test_index_v4_empty_repository(self) -> None:
  280. """Test v4 index behavior with empty repository."""
  281. require_git_version((2, 20, 0))
  282. repo = self._init_repo_with_manyfiles()
  283. # Create empty commit to get an index file
  284. run_git_or_fail(["commit", "--allow-empty", "-m", "empty"], cwd=repo.path)
  285. # Read the empty index
  286. index_path = os.path.join(repo.path, ".git", "index")
  287. if os.path.exists(index_path):
  288. with open(index_path, "rb") as f:
  289. entries, version, extensions = read_index_dict_with_version(f)
  290. # Even empty indexes should be readable
  291. self.assertEqual(len(entries), 0)
  292. # Test writing empty index
  293. with open(index_path + ".dulwich", "wb") as f:
  294. from dulwich.pack import SHA1Writer
  295. sha1_writer = SHA1Writer(f)
  296. write_index_dict(
  297. sha1_writer, entries, version=version, extensions=extensions
  298. )
  299. sha1_writer.close()
  300. def test_index_v4_large_file_count(self) -> None:
  301. """Test v4 index with many files (stress test)."""
  302. require_git_version((2, 20, 0))
  303. repo = self._init_repo_with_manyfiles()
  304. # Create many files with similar paths to test compression
  305. files = []
  306. for i in range(50): # Reasonable number for CI
  307. filename = f"src/component_{i:03d}/index.js"
  308. files.append(filename)
  309. filepath = os.path.join(repo.path, filename)
  310. os.makedirs(os.path.dirname(filepath), exist_ok=True)
  311. with open(filepath, "w") as f:
  312. f.write(f"// Component {i}\nexport default {{}};")
  313. # Add all files
  314. run_git_or_fail(["add", "."], cwd=repo.path)
  315. # Read index
  316. index_path = os.path.join(repo.path, ".git", "index")
  317. with open(index_path, "rb") as f:
  318. entries, version, extensions = read_index_dict_with_version(f)
  319. self.assertEqual(version, 4)
  320. self.assertEqual(len(entries), len(files))
  321. # Test dulwich can handle large indexes
  322. index = Index(index_path)
  323. index.write()
  324. # Verify all files are still present
  325. output = run_git_or_fail(["ls-files"], cwd=repo.path)
  326. git_files = output.strip().split(b"\n")
  327. self.assertEqual(len(git_files), len(files))
  328. def test_index_v4_concurrent_modifications(self) -> None:
  329. """Test v4 index behavior with file modifications."""
  330. require_git_version((2, 20, 0))
  331. repo = self._init_repo_with_manyfiles()
  332. # Create initial files
  333. files = ["file1.txt", "file2.txt", "subdir/file3.txt"]
  334. for filename in files:
  335. filepath = os.path.join(repo.path, filename)
  336. os.makedirs(os.path.dirname(filepath), exist_ok=True)
  337. with open(filepath, "w") as f:
  338. f.write("initial content\n")
  339. # Add files
  340. run_git_or_fail(["add", "."], cwd=repo.path)
  341. # Modify some files
  342. with open(os.path.join(repo.path, "file1.txt"), "w") as f:
  343. f.write("modified content\n")
  344. # Add new file
  345. with open(os.path.join(repo.path, "file4.txt"), "w") as f:
  346. f.write("new file\n")
  347. run_git_or_fail(["add", "file4.txt"], cwd=repo.path)
  348. # Test dulwich can read the updated index
  349. index_path = os.path.join(repo.path, ".git", "index")
  350. with open(index_path, "rb") as f:
  351. entries, version, extensions = read_index_dict_with_version(f)
  352. self.assertEqual(version, 4)
  353. self.assertEqual(len(entries), 4) # 3 original + 1 new
  354. # Verify specific files
  355. self.assertIn(b"file1.txt", entries)
  356. self.assertIn(b"file4.txt", entries)
  357. # Test round-trip
  358. index = Index(index_path)
  359. index.write()
  360. # Verify state is preserved
  361. output = run_git_or_fail(["ls-files"], cwd=repo.path)
  362. self.assertIn(b"file4.txt", output)
  363. def test_index_v4_with_merge_conflicts(self) -> None:
  364. """Test v4 index behavior with merge conflicts and staging."""
  365. require_git_version((2, 20, 0))
  366. repo = self._init_repo_with_manyfiles()
  367. # Create initial commit
  368. with open(os.path.join(repo.path, "conflict.txt"), "w") as f:
  369. f.write("original content\n")
  370. with open(os.path.join(repo.path, "normal.txt"), "w") as f:
  371. f.write("normal file\n")
  372. run_git_or_fail(["add", "."], cwd=repo.path)
  373. run_git_or_fail(["commit", "-m", "initial"], cwd=repo.path)
  374. # Create branch and modify file
  375. run_git_or_fail(["checkout", "-b", "feature"], cwd=repo.path)
  376. with open(os.path.join(repo.path, "conflict.txt"), "w") as f:
  377. f.write("feature content\n")
  378. run_git_or_fail(["add", "conflict.txt"], cwd=repo.path)
  379. run_git_or_fail(["commit", "-m", "feature change"], cwd=repo.path)
  380. # Go back to main and make conflicting change
  381. run_git_or_fail(["checkout", "master"], cwd=repo.path)
  382. with open(os.path.join(repo.path, "conflict.txt"), "w") as f:
  383. f.write("master content\n")
  384. run_git_or_fail(["add", "conflict.txt"], cwd=repo.path)
  385. run_git_or_fail(["commit", "-m", "master change"], cwd=repo.path)
  386. # Try to merge (should create conflicts)
  387. run_git(["merge", "feature"], cwd=repo.path)
  388. # Read the index with conflicts
  389. index_path = os.path.join(repo.path, ".git", "index")
  390. if os.path.exists(index_path):
  391. with open(index_path, "rb") as f:
  392. entries, version, extensions = read_index_dict_with_version(f)
  393. self.assertEqual(version, 4)
  394. # Test dulwich can handle conflicted index
  395. index = Index(index_path)
  396. index.write()
  397. # Verify Git can still read it
  398. output = run_git_or_fail(["status", "--porcelain"], cwd=repo.path)
  399. self.assertIn(b"conflict.txt", output)
  400. def test_index_v4_boundary_filename_lengths(self) -> None:
  401. """Test v4 with boundary conditions for filename lengths."""
  402. require_git_version((2, 20, 0))
  403. repo = self._init_repo_with_manyfiles()
  404. import sys
  405. # Test various boundary conditions
  406. if sys.platform == "win32":
  407. # Windows has path length limitations
  408. boundary_files = [
  409. "", # Empty name (invalid, but test robustness)
  410. "x", # Single char
  411. "xx", # Two chars
  412. "x" * 100, # Long but within Windows limit
  413. "a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p", # Deep nesting but shorter
  414. "file_with_" + "very_" * 10 + "long_name.txt", # Long name within limit
  415. ]
  416. else:
  417. boundary_files = [
  418. "", # Empty name (invalid, but test robustness)
  419. "x", # Single char
  420. "xx", # Two chars
  421. "x" * 255, # Max typical filename length
  422. "x" * 4095, # Max path length in many filesystems
  423. "a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z", # Deep nesting
  424. "file_with_" + "very_" * 50 + "long_name.txt", # Very long name
  425. ]
  426. valid_files = []
  427. for filename in boundary_files:
  428. if not filename: # Skip empty filename
  429. continue
  430. try:
  431. filepath = os.path.join(repo.path, filename)
  432. os.makedirs(os.path.dirname(filepath), exist_ok=True)
  433. with open(filepath, "w") as f:
  434. f.write("Content\n")
  435. valid_files.append(filename)
  436. except (OSError, ValueError):
  437. # Skip files that can't be created on this system
  438. continue
  439. if valid_files:
  440. # Add files
  441. run_git_or_fail(["add", "."], cwd=repo.path)
  442. # Test reading
  443. index_path = os.path.join(repo.path, ".git", "index")
  444. with open(index_path, "rb") as f:
  445. entries, version, extensions = read_index_dict_with_version(f)
  446. self.assertEqual(version, 4)
  447. # Test round-trip
  448. index = Index(index_path)
  449. index.write()
  450. def test_index_v4_special_characters_and_encoding(self) -> None:
  451. """Test v4 with special characters and various encodings."""
  452. require_git_version((2, 20, 0))
  453. repo = self._init_repo_with_manyfiles()
  454. # Test files with special characters
  455. special_files = [
  456. "file with spaces.txt",
  457. "file\twith\ttabs.txt",
  458. "file-with-dashes.txt",
  459. "file_with_underscores.txt",
  460. "file.with.dots.txt",
  461. "UPPERCASE.TXT",
  462. "MixedCase.TxT",
  463. "file123numbers.txt",
  464. "file@#$%special.txt",
  465. "café.txt", # Unicode
  466. "файл.txt", # Cyrillic
  467. "文件.txt", # Chinese
  468. "🚀rocket.txt", # Emoji
  469. "file'with'quotes.txt",
  470. 'file"with"doublequotes.txt',
  471. "file[with]brackets.txt",
  472. "file(with)parens.txt",
  473. "file{with}braces.txt",
  474. ]
  475. valid_files = []
  476. for filename in special_files:
  477. try:
  478. filepath = os.path.join(repo.path, filename)
  479. with open(filepath, "w", encoding="utf-8") as f:
  480. f.write(f"Content of {filename}\n")
  481. valid_files.append(filename)
  482. except (OSError, UnicodeError):
  483. # Skip files that can't be created on this system
  484. continue
  485. if valid_files:
  486. # Add files
  487. run_git_or_fail(["add", "."], cwd=repo.path)
  488. # Test reading
  489. index_path = os.path.join(repo.path, ".git", "index")
  490. with open(index_path, "rb") as f:
  491. entries, version, extensions = read_index_dict_with_version(f)
  492. self.assertEqual(version, 4)
  493. self.assertGreater(len(entries), 0)
  494. # Test all valid files are present
  495. for filename in valid_files:
  496. filename_bytes = filename.encode("utf-8")
  497. self.assertIn(filename_bytes, entries)
  498. def test_index_v4_symlinks_and_special_modes(self) -> None:
  499. """Test v4 with symlinks and special file modes."""
  500. require_git_version((2, 20, 0))
  501. repo = self._init_repo_with_manyfiles()
  502. # Create regular file
  503. with open(os.path.join(repo.path, "regular.txt"), "w") as f:
  504. f.write("regular file\n")
  505. # Create executable file
  506. exec_path = os.path.join(repo.path, "executable.sh")
  507. with open(exec_path, "w") as f:
  508. f.write("#!/bin/bash\necho hello\n")
  509. os.chmod(exec_path, 0o755)
  510. # Create symlink (if supported)
  511. try:
  512. os.symlink("regular.txt", os.path.join(repo.path, "symlink.txt"))
  513. has_symlink = True
  514. except (OSError, NotImplementedError):
  515. has_symlink = False
  516. # Add files
  517. run_git_or_fail(["add", "."], cwd=repo.path)
  518. # Test reading
  519. index_path = os.path.join(repo.path, ".git", "index")
  520. with open(index_path, "rb") as f:
  521. entries, version, extensions = read_index_dict_with_version(f)
  522. self.assertEqual(version, 4)
  523. # Verify files with different modes
  524. self.assertIn(b"regular.txt", entries)
  525. self.assertIn(b"executable.sh", entries)
  526. if has_symlink:
  527. self.assertIn(b"symlink.txt", entries)
  528. # Test round-trip preserves modes
  529. index = Index(index_path)
  530. index.write()
  531. # Verify Git can read it
  532. output = run_git_or_fail(["ls-files", "-s"], cwd=repo.path)
  533. self.assertIn(b"regular.txt", output)
  534. self.assertIn(b"executable.sh", output)
  535. def test_index_v4_alternating_compression_patterns(self) -> None:
  536. """Test v4 with files that alternate between compressed/uncompressed."""
  537. require_git_version((2, 20, 0))
  538. repo = self._init_repo_with_manyfiles()
  539. # Create files that should create alternating compression patterns
  540. files = [
  541. # These should be uncompressed (no common prefix)
  542. "a.txt",
  543. "b.txt",
  544. "c.txt",
  545. # These should be compressed (common prefix)
  546. "common/path/file1.txt",
  547. "common/path/file2.txt",
  548. "common/path/file3.txt",
  549. # Back to uncompressed (different pattern)
  550. "different/structure/x.txt",
  551. "another/structure/y.txt",
  552. # More compression opportunities
  553. "src/main/Component1.java",
  554. "src/main/Component2.java",
  555. "src/test/Test1.java",
  556. "src/test/Test2.java",
  557. ]
  558. for filename in files:
  559. filepath = os.path.join(repo.path, filename)
  560. os.makedirs(os.path.dirname(filepath), exist_ok=True)
  561. with open(filepath, "w") as f:
  562. f.write(f"Content of {filename}\n")
  563. # Add files
  564. run_git_or_fail(["add", "."], cwd=repo.path)
  565. # Test reading
  566. index_path = os.path.join(repo.path, ".git", "index")
  567. with open(index_path, "rb") as f:
  568. entries, version, extensions = read_index_dict_with_version(f)
  569. self.assertEqual(version, 4)
  570. self.assertEqual(len(entries), len(files))
  571. # Verify all files are present
  572. for filename in files:
  573. self.assertIn(filename.encode(), entries)
  574. # Test round-trip
  575. index = Index(index_path)
  576. index.write()
  577. def test_index_v4_git_submodules(self) -> None:
  578. """Test v4 index with Git submodules."""
  579. require_git_version((2, 20, 0))
  580. repo = self._init_repo_with_manyfiles()
  581. # Create a submodule directory structure
  582. submodule_dir = os.path.join(repo.path, "submodule")
  583. os.makedirs(submodule_dir)
  584. # Initialize a separate repo for the submodule
  585. run_git_or_fail(["init"], cwd=submodule_dir)
  586. with open(os.path.join(submodule_dir, "sub.txt"), "w") as f:
  587. f.write("submodule content\n")
  588. run_git_or_fail(["add", "sub.txt"], cwd=submodule_dir)
  589. run_git_or_fail(["commit", "-m", "submodule commit"], cwd=submodule_dir)
  590. # Add some regular files to main repo
  591. with open(os.path.join(repo.path, "main.txt"), "w") as f:
  592. f.write("main repo content\n")
  593. run_git_or_fail(["add", "main.txt"], cwd=repo.path)
  594. # Add submodule (this creates a gitlink entry)
  595. run_git_or_fail(["submodule", "add", "./submodule", "submodule"], cwd=repo.path)
  596. # Test reading index with submodule
  597. index_path = os.path.join(repo.path, ".git", "index")
  598. with open(index_path, "rb") as f:
  599. entries, version, extensions = read_index_dict_with_version(f)
  600. self.assertEqual(version, 4)
  601. # Should have main.txt, .gitmodules, and submodule gitlink
  602. self.assertIn(b"main.txt", entries)
  603. self.assertIn(b".gitmodules", entries)
  604. self.assertIn(b"submodule", entries)
  605. # Test round-trip
  606. index = Index(index_path)
  607. index.write()
  608. def test_index_v4_partial_staging(self) -> None:
  609. """Test v4 with partial file staging (git add -p simulation)."""
  610. require_git_version((2, 20, 0))
  611. repo = self._init_repo_with_manyfiles()
  612. # Create initial file
  613. filepath = os.path.join(repo.path, "partial.txt")
  614. with open(filepath, "w") as f:
  615. f.write("line1\nline2\nline3\n")
  616. run_git_or_fail(["add", "partial.txt"], cwd=repo.path)
  617. run_git_or_fail(["commit", "-m", "initial"], cwd=repo.path)
  618. # Modify the file
  619. with open(filepath, "w") as f:
  620. f.write("line1 modified\nline2\nline3 modified\n")
  621. # Stage only part of the changes (simulate git add -p)
  622. # This creates an interesting index state
  623. run_git_or_fail(["add", "partial.txt"], cwd=repo.path)
  624. # Make more changes
  625. with open(filepath, "w") as f:
  626. f.write("line1 modified\nline2 modified\nline3 modified\n")
  627. # Now we have staged and unstaged changes
  628. # Test reading this complex index state
  629. index_path = os.path.join(repo.path, ".git", "index")
  630. with open(index_path, "rb") as f:
  631. entries, version, extensions = read_index_dict_with_version(f)
  632. self.assertEqual(version, 4)
  633. self.assertIn(b"partial.txt", entries)
  634. # Test round-trip
  635. index = Index(index_path)
  636. index.write()
  637. def test_index_v4_with_gitattributes_and_ignore(self) -> None:
  638. """Test v4 with .gitattributes and .gitignore files."""
  639. require_git_version((2, 20, 0))
  640. repo = self._init_repo_with_manyfiles()
  641. # Create .gitignore
  642. with open(os.path.join(repo.path, ".gitignore"), "w") as f:
  643. f.write("*.tmp\n*.log\nbuild/\n")
  644. # Create .gitattributes
  645. with open(os.path.join(repo.path, ".gitattributes"), "w") as f:
  646. f.write("*.txt text\n*.bin binary\n")
  647. # Create various files
  648. files = [
  649. "regular.txt",
  650. "binary.bin",
  651. "script.sh",
  652. "config.json",
  653. "README.md",
  654. ]
  655. for filename in files:
  656. filepath = os.path.join(repo.path, filename)
  657. with open(filepath, "w") as f:
  658. f.write(f"Content of {filename}\n")
  659. # Create some files that should be ignored
  660. with open(os.path.join(repo.path, "temp.tmp"), "w") as f:
  661. f.write("temporary file\n")
  662. # Add files
  663. run_git_or_fail(["add", "."], cwd=repo.path)
  664. # Test reading
  665. index_path = os.path.join(repo.path, ".git", "index")
  666. with open(index_path, "rb") as f:
  667. entries, version, extensions = read_index_dict_with_version(f)
  668. self.assertEqual(version, 4)
  669. # Should have .gitignore, .gitattributes, and regular files
  670. self.assertIn(b".gitignore", entries)
  671. self.assertIn(b".gitattributes", entries)
  672. for filename in files:
  673. self.assertIn(filename.encode(), entries)
  674. # Should NOT have ignored files
  675. self.assertNotIn(b"temp.tmp", entries)
  676. def test_index_v4_stress_test_many_entries(self) -> None:
  677. """Stress test v4 with many entries in complex directory structure."""
  678. require_git_version((2, 20, 0))
  679. repo = self._init_repo_with_manyfiles()
  680. # Create a complex directory structure with many files
  681. dirs = [
  682. "src/main/java/com/example",
  683. "src/main/resources",
  684. "src/test/java/com/example",
  685. "docs/api",
  686. "docs/user",
  687. "scripts/build",
  688. "config/env",
  689. ]
  690. for dir_path in dirs:
  691. os.makedirs(os.path.join(repo.path, dir_path), exist_ok=True)
  692. # Create many files
  693. files = []
  694. for i in range(200): # Reasonable for CI
  695. if i % 7 == 0:
  696. filename = f"src/main/java/com/example/Service{i}.java"
  697. elif i % 7 == 1:
  698. filename = f"src/test/java/com/example/Test{i}.java"
  699. elif i % 7 == 2:
  700. filename = f"docs/api/page{i}.md"
  701. elif i % 7 == 3:
  702. filename = f"config/env/config{i}.properties"
  703. elif i % 7 == 4:
  704. filename = f"scripts/build/script{i}.sh"
  705. elif i % 7 == 5:
  706. filename = f"src/main/resources/resource{i}.txt"
  707. else:
  708. filename = f"file{i}.txt"
  709. files.append(filename)
  710. filepath = os.path.join(repo.path, filename)
  711. os.makedirs(os.path.dirname(filepath), exist_ok=True)
  712. with open(filepath, "w") as f:
  713. f.write(f"// File {i}\ncontent here\n")
  714. # Add files in batches to avoid command line length limits
  715. batch_size = 50
  716. for i in range(0, len(files), batch_size):
  717. batch = files[i : i + batch_size]
  718. run_git_or_fail(["add", *batch], cwd=repo.path)
  719. # Test reading large index
  720. index_path = os.path.join(repo.path, ".git", "index")
  721. with open(index_path, "rb") as f:
  722. entries, version, extensions = read_index_dict_with_version(f)
  723. self.assertEqual(version, 4)
  724. self.assertEqual(len(entries), len(files))
  725. # Verify some files are present
  726. for i in range(0, len(files), 20): # Check every 20th file
  727. filename = files[i]
  728. self.assertIn(filename.encode(), entries)
  729. def test_index_v4_rename_detection_scenario(self) -> None:
  730. """Test v4 with file renames (complex staging scenario)."""
  731. require_git_version((2, 20, 0))
  732. repo = self._init_repo_with_manyfiles()
  733. # Create initial files
  734. files = ["old1.txt", "old2.txt", "unchanged.txt"]
  735. for filename in files:
  736. filepath = os.path.join(repo.path, filename)
  737. with open(filepath, "w") as f:
  738. f.write(f"Content of {filename}\n")
  739. run_git_or_fail(["add", "."], cwd=repo.path)
  740. run_git_or_fail(["commit", "-m", "initial"], cwd=repo.path)
  741. # Rename files
  742. os.rename(
  743. os.path.join(repo.path, "old1.txt"), os.path.join(repo.path, "new1.txt")
  744. )
  745. os.rename(
  746. os.path.join(repo.path, "old2.txt"), os.path.join(repo.path, "new2.txt")
  747. )
  748. # Stage renames
  749. run_git_or_fail(["add", "-A"], cwd=repo.path)
  750. # Test reading index with renames
  751. index_path = os.path.join(repo.path, ".git", "index")
  752. with open(index_path, "rb") as f:
  753. entries, version, extensions = read_index_dict_with_version(f)
  754. self.assertEqual(version, 4)
  755. # Should have new names, not old names
  756. self.assertIn(b"new1.txt", entries)
  757. self.assertIn(b"new2.txt", entries)
  758. self.assertIn(b"unchanged.txt", entries)
  759. self.assertNotIn(b"old1.txt", entries)
  760. self.assertNotIn(b"old2.txt", entries)