2
0

test_cli.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  1. #!/usr/bin/env python
  2. # test_cli.py -- tests for dulwich.cli
  3. # vim: expandtab
  4. #
  5. # Copyright (C) 2024 Jelmer Vernooij <jelmer@jelmer.uk>
  6. #
  7. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  8. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  9. # General Public License as public by the Free Software Foundation; version 2.0
  10. # or (at your option) any later version. You can redistribute it and/or
  11. # modify it under the terms of either of these two licenses.
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. #
  19. # You should have received a copy of the licenses; if not, see
  20. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  21. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  22. # License, Version 2.0.
  23. """Tests for dulwich.cli."""
  24. import io
  25. import os
  26. import shutil
  27. import sys
  28. import tempfile
  29. import unittest
  30. from unittest import skipIf
  31. from unittest.mock import MagicMock, patch
  32. from dulwich import cli
  33. from dulwich.cli import format_bytes, parse_relative_time
  34. from dulwich.repo import Repo
  35. from dulwich.tests.utils import (
  36. build_commit_graph,
  37. )
  38. from . import TestCase
  39. class DulwichCliTestCase(TestCase):
  40. """Base class for CLI tests."""
  41. def setUp(self) -> None:
  42. super().setUp()
  43. self.test_dir = tempfile.mkdtemp()
  44. self.addCleanup(shutil.rmtree, self.test_dir)
  45. self.repo_path = os.path.join(self.test_dir, "repo")
  46. os.mkdir(self.repo_path)
  47. self.repo = Repo.init(self.repo_path)
  48. self.addCleanup(self.repo.close)
  49. def _run_cli(self, *args, stdout_stream=None):
  50. """Run CLI command and capture output."""
  51. class MockStream:
  52. def __init__(self):
  53. self._buffer = io.BytesIO()
  54. self.buffer = self._buffer
  55. def write(self, data):
  56. if isinstance(data, bytes):
  57. self._buffer.write(data)
  58. else:
  59. self._buffer.write(data.encode("utf-8"))
  60. def getvalue(self):
  61. value = self._buffer.getvalue()
  62. try:
  63. return value.decode("utf-8")
  64. except UnicodeDecodeError:
  65. return value
  66. def __getattr__(self, name):
  67. return getattr(self._buffer, name)
  68. old_stdout = sys.stdout
  69. old_stderr = sys.stderr
  70. old_cwd = os.getcwd()
  71. try:
  72. # Use custom stdout_stream if provided, otherwise use MockStream
  73. if stdout_stream:
  74. sys.stdout = stdout_stream
  75. if not hasattr(sys.stdout, "buffer"):
  76. sys.stdout.buffer = sys.stdout
  77. else:
  78. sys.stdout = MockStream()
  79. sys.stderr = MockStream()
  80. os.chdir(self.repo_path)
  81. result = cli.main(list(args))
  82. return result, sys.stdout.getvalue(), sys.stderr.getvalue()
  83. finally:
  84. sys.stdout = old_stdout
  85. sys.stderr = old_stderr
  86. os.chdir(old_cwd)
  87. class InitCommandTest(DulwichCliTestCase):
  88. """Tests for init command."""
  89. def test_init_basic(self):
  90. # Create a new directory for init
  91. new_repo_path = os.path.join(self.test_dir, "new_repo")
  92. result, stdout, stderr = self._run_cli("init", new_repo_path)
  93. self.assertTrue(os.path.exists(os.path.join(new_repo_path, ".git")))
  94. def test_init_bare(self):
  95. # Create a new directory for bare repo
  96. bare_repo_path = os.path.join(self.test_dir, "bare_repo")
  97. result, stdout, stderr = self._run_cli("init", "--bare", bare_repo_path)
  98. self.assertTrue(os.path.exists(os.path.join(bare_repo_path, "HEAD")))
  99. self.assertFalse(os.path.exists(os.path.join(bare_repo_path, ".git")))
  100. class AddCommandTest(DulwichCliTestCase):
  101. """Tests for add command."""
  102. def test_add_single_file(self):
  103. # Create a file to add
  104. test_file = os.path.join(self.repo_path, "test.txt")
  105. with open(test_file, "w") as f:
  106. f.write("test content")
  107. result, stdout, stderr = self._run_cli("add", "test.txt")
  108. # Check that file is in index
  109. self.assertIn(b"test.txt", self.repo.open_index())
  110. def test_add_multiple_files(self):
  111. # Create multiple files
  112. for i in range(3):
  113. test_file = os.path.join(self.repo_path, f"test{i}.txt")
  114. with open(test_file, "w") as f:
  115. f.write(f"content {i}")
  116. result, stdout, stderr = self._run_cli(
  117. "add", "test0.txt", "test1.txt", "test2.txt"
  118. )
  119. index = self.repo.open_index()
  120. self.assertIn(b"test0.txt", index)
  121. self.assertIn(b"test1.txt", index)
  122. self.assertIn(b"test2.txt", index)
  123. class RmCommandTest(DulwichCliTestCase):
  124. """Tests for rm command."""
  125. def test_rm_file(self):
  126. # Create, add and commit a file first
  127. test_file = os.path.join(self.repo_path, "test.txt")
  128. with open(test_file, "w") as f:
  129. f.write("test content")
  130. self._run_cli("add", "test.txt")
  131. self._run_cli("commit", "--message=Add test file")
  132. # Now remove it from index and working directory
  133. result, stdout, stderr = self._run_cli("rm", "test.txt")
  134. # Check that file is not in index
  135. self.assertNotIn(b"test.txt", self.repo.open_index())
  136. class CommitCommandTest(DulwichCliTestCase):
  137. """Tests for commit command."""
  138. def test_commit_basic(self):
  139. # Create and add a file
  140. test_file = os.path.join(self.repo_path, "test.txt")
  141. with open(test_file, "w") as f:
  142. f.write("test content")
  143. self._run_cli("add", "test.txt")
  144. # Commit
  145. result, stdout, stderr = self._run_cli("commit", "--message=Initial commit")
  146. # Check that HEAD points to a commit
  147. self.assertIsNotNone(self.repo.head())
  148. class LogCommandTest(DulwichCliTestCase):
  149. """Tests for log command."""
  150. def test_log_empty_repo(self):
  151. result, stdout, stderr = self._run_cli("log")
  152. # Empty repo should not crash
  153. def test_log_with_commits(self):
  154. # Create some commits
  155. c1, c2, c3 = build_commit_graph(
  156. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  157. )
  158. self.repo.refs[b"HEAD"] = c3.id
  159. result, stdout, stderr = self._run_cli("log")
  160. self.assertIn("Commit 3", stdout)
  161. self.assertIn("Commit 2", stdout)
  162. self.assertIn("Commit 1", stdout)
  163. def test_log_reverse(self):
  164. # Create some commits
  165. c1, c2, c3 = build_commit_graph(
  166. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  167. )
  168. self.repo.refs[b"HEAD"] = c3.id
  169. result, stdout, stderr = self._run_cli("log", "--reverse")
  170. # Check order - commit 1 should appear before commit 3
  171. pos1 = stdout.index("Commit 1")
  172. pos3 = stdout.index("Commit 3")
  173. self.assertLess(pos1, pos3)
  174. class StatusCommandTest(DulwichCliTestCase):
  175. """Tests for status command."""
  176. def test_status_empty(self):
  177. result, stdout, stderr = self._run_cli("status")
  178. # Should not crash on empty repo
  179. def test_status_with_untracked(self):
  180. # Create an untracked file
  181. test_file = os.path.join(self.repo_path, "untracked.txt")
  182. with open(test_file, "w") as f:
  183. f.write("untracked content")
  184. result, stdout, stderr = self._run_cli("status")
  185. self.assertIn("Untracked files:", stdout)
  186. self.assertIn("untracked.txt", stdout)
  187. class BranchCommandTest(DulwichCliTestCase):
  188. """Tests for branch command."""
  189. def test_branch_create(self):
  190. # Create initial commit
  191. test_file = os.path.join(self.repo_path, "test.txt")
  192. with open(test_file, "w") as f:
  193. f.write("test")
  194. self._run_cli("add", "test.txt")
  195. self._run_cli("commit", "--message=Initial")
  196. # Create branch
  197. result, stdout, stderr = self._run_cli("branch", "test-branch")
  198. self.assertIn(b"refs/heads/test-branch", self.repo.refs.keys())
  199. def test_branch_delete(self):
  200. # Create initial commit and branch
  201. test_file = os.path.join(self.repo_path, "test.txt")
  202. with open(test_file, "w") as f:
  203. f.write("test")
  204. self._run_cli("add", "test.txt")
  205. self._run_cli("commit", "--message=Initial")
  206. self._run_cli("branch", "test-branch")
  207. # Delete branch
  208. result, stdout, stderr = self._run_cli("branch", "-d", "test-branch")
  209. self.assertNotIn(b"refs/heads/test-branch", self.repo.refs.keys())
  210. class CheckoutCommandTest(DulwichCliTestCase):
  211. """Tests for checkout command."""
  212. def test_checkout_branch(self):
  213. # Create initial commit and branch
  214. test_file = os.path.join(self.repo_path, "test.txt")
  215. with open(test_file, "w") as f:
  216. f.write("test")
  217. self._run_cli("add", "test.txt")
  218. self._run_cli("commit", "--message=Initial")
  219. self._run_cli("branch", "test-branch")
  220. # Checkout branch
  221. result, stdout, stderr = self._run_cli("checkout", "test-branch")
  222. self.assertEqual(
  223. self.repo.refs.read_ref(b"HEAD"), b"ref: refs/heads/test-branch"
  224. )
  225. class TagCommandTest(DulwichCliTestCase):
  226. """Tests for tag command."""
  227. def test_tag_create(self):
  228. # Create initial commit
  229. test_file = os.path.join(self.repo_path, "test.txt")
  230. with open(test_file, "w") as f:
  231. f.write("test")
  232. self._run_cli("add", "test.txt")
  233. self._run_cli("commit", "--message=Initial")
  234. # Create tag
  235. result, stdout, stderr = self._run_cli("tag", "v1.0")
  236. self.assertIn(b"refs/tags/v1.0", self.repo.refs.keys())
  237. class FilterBranchCommandTest(DulwichCliTestCase):
  238. """Tests for filter-branch command."""
  239. def setUp(self):
  240. super().setUp()
  241. # Create a more complex repository structure for testing
  242. # Create some files in subdirectories
  243. os.makedirs(os.path.join(self.repo_path, "subdir"))
  244. os.makedirs(os.path.join(self.repo_path, "other"))
  245. # Create files
  246. files = {
  247. "README.md": "# Test Repo",
  248. "subdir/file1.txt": "File in subdir",
  249. "subdir/file2.txt": "Another file in subdir",
  250. "other/file3.txt": "File in other dir",
  251. "root.txt": "File at root",
  252. }
  253. for path, content in files.items():
  254. file_path = os.path.join(self.repo_path, path)
  255. with open(file_path, "w") as f:
  256. f.write(content)
  257. # Add all files and create initial commit
  258. self._run_cli("add", ".")
  259. self._run_cli("commit", "--message=Initial commit")
  260. # Create a second commit modifying subdir
  261. with open(os.path.join(self.repo_path, "subdir/file1.txt"), "a") as f:
  262. f.write("\nModified content")
  263. self._run_cli("add", "subdir/file1.txt")
  264. self._run_cli("commit", "--message=Modify subdir file")
  265. # Create a third commit in other dir
  266. with open(os.path.join(self.repo_path, "other/file3.txt"), "a") as f:
  267. f.write("\nMore content")
  268. self._run_cli("add", "other/file3.txt")
  269. self._run_cli("commit", "--message=Modify other file")
  270. # Create a branch
  271. self._run_cli("branch", "test-branch")
  272. # Create a tag
  273. self._run_cli("tag", "v1.0")
  274. def test_filter_branch_subdirectory_filter(self):
  275. """Test filter-branch with subdirectory filter."""
  276. # Run filter-branch to extract only the subdir
  277. result, stdout, stderr = self._run_cli(
  278. "filter-branch", "--subdirectory-filter", "subdir"
  279. )
  280. # Check that the operation succeeded
  281. self.assertEqual(result, 0)
  282. self.assertIn("Rewrite HEAD", stdout)
  283. # filter-branch rewrites history but doesn't update working tree
  284. # We need to check the commit contents, not the working tree
  285. # Reset to the rewritten HEAD to update working tree
  286. self._run_cli("reset", "--hard", "HEAD")
  287. # Now check that only files from subdir remain at root level
  288. self.assertTrue(os.path.exists(os.path.join(self.repo_path, "file1.txt")))
  289. self.assertTrue(os.path.exists(os.path.join(self.repo_path, "file2.txt")))
  290. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "README.md")))
  291. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "root.txt")))
  292. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "other")))
  293. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "subdir")))
  294. # Check that original refs were backed up
  295. original_refs = [
  296. ref for ref in self.repo.refs.keys() if ref.startswith(b"refs/original/")
  297. ]
  298. self.assertTrue(
  299. len(original_refs) > 0, "No original refs found after filter-branch"
  300. )
  301. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  302. def test_filter_branch_msg_filter(self):
  303. """Test filter-branch with message filter."""
  304. # Run filter-branch to prepend [FILTERED] to commit messages
  305. result, stdout, stderr = self._run_cli(
  306. "filter-branch", "--msg-filter", "sed 's/^/[FILTERED] /'"
  307. )
  308. self.assertEqual(result, 0)
  309. # Check that commit messages were modified
  310. result, stdout, stderr = self._run_cli("log")
  311. self.assertIn("[FILTERED] Modify other file", stdout)
  312. self.assertIn("[FILTERED] Modify subdir file", stdout)
  313. self.assertIn("[FILTERED] Initial commit", stdout)
  314. def test_filter_branch_env_filter(self):
  315. """Test filter-branch with environment filter."""
  316. # Run filter-branch to change author email
  317. env_filter = """
  318. if [ "$GIT_AUTHOR_EMAIL" = "test@example.com" ]; then
  319. export GIT_AUTHOR_EMAIL="filtered@example.com"
  320. fi
  321. """
  322. result, stdout, stderr = self._run_cli(
  323. "filter-branch", "--env-filter", env_filter
  324. )
  325. self.assertEqual(result, 0)
  326. def test_filter_branch_prune_empty(self):
  327. """Test filter-branch with prune-empty option."""
  328. # Create a commit that only touches files outside subdir
  329. with open(os.path.join(self.repo_path, "root.txt"), "a") as f:
  330. f.write("\nNew line")
  331. self._run_cli("add", "root.txt")
  332. self._run_cli("commit", "--message=Modify root file only")
  333. # Run filter-branch to extract subdir with prune-empty
  334. result, stdout, stderr = self._run_cli(
  335. "filter-branch", "--subdirectory-filter", "subdir", "--prune-empty"
  336. )
  337. self.assertEqual(result, 0)
  338. # The last commit should have been pruned
  339. result, stdout, stderr = self._run_cli("log")
  340. self.assertNotIn("Modify root file only", stdout)
  341. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  342. def test_filter_branch_force(self):
  343. """Test filter-branch with force option."""
  344. # Run filter-branch once with a filter that actually changes something
  345. result, stdout, stderr = self._run_cli(
  346. "filter-branch", "--msg-filter", "sed 's/^/[TEST] /'"
  347. )
  348. self.assertEqual(result, 0)
  349. # Check that backup refs were created
  350. # The implementation backs up refs under refs/original/
  351. original_refs = [
  352. ref for ref in self.repo.refs.keys() if ref.startswith(b"refs/original/")
  353. ]
  354. self.assertTrue(len(original_refs) > 0, "No original refs found")
  355. # Run again without force - should fail
  356. result, stdout, stderr = self._run_cli(
  357. "filter-branch", "--msg-filter", "sed 's/^/[TEST2] /'"
  358. )
  359. self.assertEqual(result, 1)
  360. self.assertIn("Cannot create a new backup", stdout)
  361. self.assertIn("refs/original", stdout)
  362. # Run with force - should succeed
  363. result, stdout, stderr = self._run_cli(
  364. "filter-branch", "--force", "--msg-filter", "sed 's/^/[TEST3] /'"
  365. )
  366. self.assertEqual(result, 0)
  367. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  368. def test_filter_branch_specific_branch(self):
  369. """Test filter-branch on a specific branch."""
  370. # Switch to test-branch and add a commit
  371. self._run_cli("checkout", "test-branch")
  372. with open(os.path.join(self.repo_path, "branch-file.txt"), "w") as f:
  373. f.write("Branch specific file")
  374. self._run_cli("add", "branch-file.txt")
  375. self._run_cli("commit", "--message=Branch commit")
  376. # Run filter-branch on the test-branch
  377. result, stdout, stderr = self._run_cli(
  378. "filter-branch", "--msg-filter", "sed 's/^/[BRANCH] /'", "test-branch"
  379. )
  380. self.assertEqual(result, 0)
  381. self.assertIn("Ref 'refs/heads/test-branch' was rewritten", stdout)
  382. # Check that only test-branch was modified
  383. result, stdout, stderr = self._run_cli("log")
  384. self.assertIn("[BRANCH] Branch commit", stdout)
  385. # Switch to master and check it wasn't modified
  386. self._run_cli("checkout", "master")
  387. result, stdout, stderr = self._run_cli("log")
  388. self.assertNotIn("[BRANCH]", stdout)
  389. def test_filter_branch_tree_filter(self):
  390. """Test filter-branch with tree filter."""
  391. # Use a tree filter to remove a specific file
  392. tree_filter = "rm -f root.txt"
  393. result, stdout, stderr = self._run_cli(
  394. "filter-branch", "--tree-filter", tree_filter
  395. )
  396. self.assertEqual(result, 0)
  397. # Check that the file was removed from the latest commit
  398. # We need to check the commit tree, not the working directory
  399. result, stdout, stderr = self._run_cli("ls-tree", "HEAD")
  400. self.assertNotIn("root.txt", stdout)
  401. def test_filter_branch_index_filter(self):
  402. """Test filter-branch with index filter."""
  403. # Use an index filter to remove a file from the index
  404. index_filter = "git rm --cached --ignore-unmatch root.txt"
  405. result, stdout, stderr = self._run_cli(
  406. "filter-branch", "--index-filter", index_filter
  407. )
  408. self.assertEqual(result, 0)
  409. def test_filter_branch_parent_filter(self):
  410. """Test filter-branch with parent filter."""
  411. # Create a merge commit first
  412. self._run_cli("checkout", "HEAD", "-b", "feature")
  413. with open(os.path.join(self.repo_path, "feature.txt"), "w") as f:
  414. f.write("Feature")
  415. self._run_cli("add", "feature.txt")
  416. self._run_cli("commit", "--message=Feature commit")
  417. self._run_cli("checkout", "master")
  418. self._run_cli("merge", "feature", "--message=Merge feature")
  419. # Use parent filter to linearize history (remove second parent)
  420. parent_filter = "cut -d' ' -f1"
  421. result, stdout, stderr = self._run_cli(
  422. "filter-branch", "--parent-filter", parent_filter
  423. )
  424. self.assertEqual(result, 0)
  425. def test_filter_branch_commit_filter(self):
  426. """Test filter-branch with commit filter."""
  427. # Use commit filter to skip commits with certain messages
  428. commit_filter = """
  429. if grep -q "Modify other" <<< "$GIT_COMMIT_MESSAGE"; then
  430. skip_commit "$@"
  431. else
  432. git commit-tree "$@"
  433. fi
  434. """
  435. result, stdout, stderr = self._run_cli(
  436. "filter-branch", "--commit-filter", commit_filter
  437. )
  438. # Note: This test may fail because the commit filter syntax is simplified
  439. # In real Git, skip_commit is a function, but our implementation may differ
  440. def test_filter_branch_tag_name_filter(self):
  441. """Test filter-branch with tag name filter."""
  442. # Run filter-branch with tag name filter to rename tags
  443. result, stdout, stderr = self._run_cli(
  444. "filter-branch",
  445. "--tag-name-filter",
  446. "sed 's/^v/version-/'",
  447. "--msg-filter",
  448. "cat",
  449. )
  450. self.assertEqual(result, 0)
  451. # Check that tag was renamed
  452. self.assertIn(b"refs/tags/version-1.0", self.repo.refs.keys())
  453. def test_filter_branch_errors(self):
  454. """Test filter-branch error handling."""
  455. # Test with invalid subdirectory
  456. result, stdout, stderr = self._run_cli(
  457. "filter-branch", "--subdirectory-filter", "nonexistent"
  458. )
  459. # Should still succeed but produce empty history
  460. self.assertEqual(result, 0)
  461. def test_filter_branch_no_args(self):
  462. """Test filter-branch with no arguments."""
  463. # Should work as no-op
  464. result, stdout, stderr = self._run_cli("filter-branch")
  465. self.assertEqual(result, 0)
  466. class ShowCommandTest(DulwichCliTestCase):
  467. """Tests for show command."""
  468. def test_show_commit(self):
  469. # Create a commit
  470. test_file = os.path.join(self.repo_path, "test.txt")
  471. with open(test_file, "w") as f:
  472. f.write("test content")
  473. self._run_cli("add", "test.txt")
  474. self._run_cli("commit", "--message=Test commit")
  475. result, stdout, stderr = self._run_cli("show", "HEAD")
  476. self.assertIn("Test commit", stdout)
  477. class FetchPackCommandTest(DulwichCliTestCase):
  478. """Tests for fetch-pack command."""
  479. @patch("dulwich.cli.get_transport_and_path")
  480. def test_fetch_pack_basic(self, mock_transport):
  481. # Mock the transport
  482. mock_client = MagicMock()
  483. mock_transport.return_value = (mock_client, "/path/to/repo")
  484. mock_client.fetch.return_value = None
  485. result, stdout, stderr = self._run_cli(
  486. "fetch-pack", "git://example.com/repo.git"
  487. )
  488. mock_client.fetch.assert_called_once()
  489. class LsRemoteCommandTest(DulwichCliTestCase):
  490. """Tests for ls-remote command."""
  491. def test_ls_remote_basic(self):
  492. # Create a commit
  493. test_file = os.path.join(self.repo_path, "test.txt")
  494. with open(test_file, "w") as f:
  495. f.write("test")
  496. self._run_cli("add", "test.txt")
  497. self._run_cli("commit", "--message=Initial")
  498. # Test basic ls-remote
  499. result, stdout, stderr = self._run_cli("ls-remote", self.repo_path)
  500. lines = stdout.strip().split("\n")
  501. self.assertTrue(any("HEAD" in line for line in lines))
  502. self.assertTrue(any("refs/heads/master" in line for line in lines))
  503. def test_ls_remote_symref(self):
  504. # Create a commit
  505. test_file = os.path.join(self.repo_path, "test.txt")
  506. with open(test_file, "w") as f:
  507. f.write("test")
  508. self._run_cli("add", "test.txt")
  509. self._run_cli("commit", "--message=Initial")
  510. # Test ls-remote with --symref option
  511. result, stdout, stderr = self._run_cli("ls-remote", "--symref", self.repo_path)
  512. lines = stdout.strip().split("\n")
  513. # Should show symref for HEAD in exact format: "ref: refs/heads/master\tHEAD"
  514. expected_line = "ref: refs/heads/master\tHEAD"
  515. self.assertIn(
  516. expected_line,
  517. lines,
  518. f"Expected line '{expected_line}' not found in output: {lines}",
  519. )
  520. class PullCommandTest(DulwichCliTestCase):
  521. """Tests for pull command."""
  522. @patch("dulwich.porcelain.pull")
  523. def test_pull_basic(self, mock_pull):
  524. result, stdout, stderr = self._run_cli("pull", "origin")
  525. mock_pull.assert_called_once()
  526. @patch("dulwich.porcelain.pull")
  527. def test_pull_with_refspec(self, mock_pull):
  528. result, stdout, stderr = self._run_cli("pull", "origin", "master")
  529. mock_pull.assert_called_once()
  530. class PushCommandTest(DulwichCliTestCase):
  531. """Tests for push command."""
  532. @patch("dulwich.porcelain.push")
  533. def test_push_basic(self, mock_push):
  534. result, stdout, stderr = self._run_cli("push", "origin")
  535. mock_push.assert_called_once()
  536. @patch("dulwich.porcelain.push")
  537. def test_push_force(self, mock_push):
  538. result, stdout, stderr = self._run_cli("push", "-f", "origin")
  539. mock_push.assert_called_with(".", "origin", None, force=True)
  540. class ArchiveCommandTest(DulwichCliTestCase):
  541. """Tests for archive command."""
  542. def test_archive_basic(self):
  543. # Create a commit
  544. test_file = os.path.join(self.repo_path, "test.txt")
  545. with open(test_file, "w") as f:
  546. f.write("test content")
  547. self._run_cli("add", "test.txt")
  548. self._run_cli("commit", "--message=Initial")
  549. # Archive produces binary output, so use BytesIO
  550. result, stdout, stderr = self._run_cli(
  551. "archive", "HEAD", stdout_stream=io.BytesIO()
  552. )
  553. # Should complete without error and produce some binary output
  554. self.assertIsInstance(stdout, bytes)
  555. self.assertGreater(len(stdout), 0)
  556. class ForEachRefCommandTest(DulwichCliTestCase):
  557. """Tests for for-each-ref command."""
  558. def test_for_each_ref(self):
  559. # Create a commit
  560. test_file = os.path.join(self.repo_path, "test.txt")
  561. with open(test_file, "w") as f:
  562. f.write("test")
  563. self._run_cli("add", "test.txt")
  564. self._run_cli("commit", "--message=Initial")
  565. result, stdout, stderr = self._run_cli("for-each-ref")
  566. self.assertIn("refs/heads/master", stdout)
  567. class PackRefsCommandTest(DulwichCliTestCase):
  568. """Tests for pack-refs command."""
  569. def test_pack_refs(self):
  570. # Create some refs
  571. test_file = os.path.join(self.repo_path, "test.txt")
  572. with open(test_file, "w") as f:
  573. f.write("test")
  574. self._run_cli("add", "test.txt")
  575. self._run_cli("commit", "--message=Initial")
  576. self._run_cli("branch", "test-branch")
  577. result, stdout, stderr = self._run_cli("pack-refs", "--all")
  578. # Check that packed-refs file exists
  579. self.assertTrue(
  580. os.path.exists(os.path.join(self.repo_path, ".git", "packed-refs"))
  581. )
  582. class SubmoduleCommandTest(DulwichCliTestCase):
  583. """Tests for submodule commands."""
  584. def test_submodule_list(self):
  585. # Create an initial commit so repo has a HEAD
  586. test_file = os.path.join(self.repo_path, "test.txt")
  587. with open(test_file, "w") as f:
  588. f.write("test")
  589. self._run_cli("add", "test.txt")
  590. self._run_cli("commit", "--message=Initial")
  591. result, stdout, stderr = self._run_cli("submodule")
  592. # Should not crash on repo without submodules
  593. def test_submodule_init(self):
  594. # Create .gitmodules file for init to work
  595. gitmodules = os.path.join(self.repo_path, ".gitmodules")
  596. with open(gitmodules, "w") as f:
  597. f.write("") # Empty .gitmodules file
  598. result, stdout, stderr = self._run_cli("submodule", "init")
  599. # Should not crash
  600. class StashCommandTest(DulwichCliTestCase):
  601. """Tests for stash commands."""
  602. def test_stash_list_empty(self):
  603. result, stdout, stderr = self._run_cli("stash", "list")
  604. # Should not crash on empty stash
  605. def test_stash_push_pop(self):
  606. # Create a file and modify it
  607. test_file = os.path.join(self.repo_path, "test.txt")
  608. with open(test_file, "w") as f:
  609. f.write("initial")
  610. self._run_cli("add", "test.txt")
  611. self._run_cli("commit", "--message=Initial")
  612. # Modify file
  613. with open(test_file, "w") as f:
  614. f.write("modified")
  615. # Stash changes
  616. result, stdout, stderr = self._run_cli("stash", "push")
  617. self.assertIn("Saved working directory", stdout)
  618. # Note: Dulwich stash doesn't currently update the working tree
  619. # so the file remains modified after stash push
  620. # Note: stash pop is not fully implemented in Dulwich yet
  621. # so we only test stash push here
  622. class MergeCommandTest(DulwichCliTestCase):
  623. """Tests for merge command."""
  624. def test_merge_basic(self):
  625. # Create initial commit
  626. test_file = os.path.join(self.repo_path, "test.txt")
  627. with open(test_file, "w") as f:
  628. f.write("initial")
  629. self._run_cli("add", "test.txt")
  630. self._run_cli("commit", "--message=Initial")
  631. # Create and checkout new branch
  632. self._run_cli("branch", "feature")
  633. self._run_cli("checkout", "feature")
  634. # Make changes in feature branch
  635. with open(test_file, "w") as f:
  636. f.write("feature changes")
  637. self._run_cli("add", "test.txt")
  638. self._run_cli("commit", "--message=Feature commit")
  639. # Go back to main
  640. self._run_cli("checkout", "master")
  641. # Merge feature branch
  642. result, stdout, stderr = self._run_cli("merge", "feature")
  643. class HelpCommandTest(DulwichCliTestCase):
  644. """Tests for help command."""
  645. def test_help_basic(self):
  646. result, stdout, stderr = self._run_cli("help")
  647. self.assertIn("dulwich command line tool", stdout)
  648. def test_help_all(self):
  649. result, stdout, stderr = self._run_cli("help", "-a")
  650. self.assertIn("Available commands:", stdout)
  651. self.assertIn("add", stdout)
  652. self.assertIn("commit", stdout)
  653. class RemoteCommandTest(DulwichCliTestCase):
  654. """Tests for remote commands."""
  655. def test_remote_add(self):
  656. result, stdout, stderr = self._run_cli(
  657. "remote", "add", "origin", "https://github.com/example/repo.git"
  658. )
  659. # Check remote was added to config
  660. config = self.repo.get_config()
  661. self.assertEqual(
  662. config.get((b"remote", b"origin"), b"url"),
  663. b"https://github.com/example/repo.git",
  664. )
  665. class CheckIgnoreCommandTest(DulwichCliTestCase):
  666. """Tests for check-ignore command."""
  667. def test_check_ignore(self):
  668. # Create .gitignore
  669. gitignore = os.path.join(self.repo_path, ".gitignore")
  670. with open(gitignore, "w") as f:
  671. f.write("*.log\n")
  672. result, stdout, stderr = self._run_cli("check-ignore", "test.log", "test.txt")
  673. self.assertIn("test.log", stdout)
  674. self.assertNotIn("test.txt", stdout)
  675. class LsFilesCommandTest(DulwichCliTestCase):
  676. """Tests for ls-files command."""
  677. def test_ls_files(self):
  678. # Add some files
  679. for name in ["a.txt", "b.txt", "c.txt"]:
  680. path = os.path.join(self.repo_path, name)
  681. with open(path, "w") as f:
  682. f.write(f"content of {name}")
  683. self._run_cli("add", "a.txt", "b.txt", "c.txt")
  684. result, stdout, stderr = self._run_cli("ls-files")
  685. self.assertIn("a.txt", stdout)
  686. self.assertIn("b.txt", stdout)
  687. self.assertIn("c.txt", stdout)
  688. class LsTreeCommandTest(DulwichCliTestCase):
  689. """Tests for ls-tree command."""
  690. def test_ls_tree(self):
  691. # Create a directory structure
  692. os.mkdir(os.path.join(self.repo_path, "subdir"))
  693. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  694. f.write("file content")
  695. with open(os.path.join(self.repo_path, "subdir", "nested.txt"), "w") as f:
  696. f.write("nested content")
  697. self._run_cli("add", ".")
  698. self._run_cli("commit", "--message=Initial")
  699. result, stdout, stderr = self._run_cli("ls-tree", "HEAD")
  700. self.assertIn("file.txt", stdout)
  701. self.assertIn("subdir", stdout)
  702. def test_ls_tree_recursive(self):
  703. # Create nested structure
  704. os.mkdir(os.path.join(self.repo_path, "subdir"))
  705. with open(os.path.join(self.repo_path, "subdir", "nested.txt"), "w") as f:
  706. f.write("nested")
  707. self._run_cli("add", ".")
  708. self._run_cli("commit", "--message=Initial")
  709. result, stdout, stderr = self._run_cli("ls-tree", "-r", "HEAD")
  710. self.assertIn("subdir/nested.txt", stdout)
  711. class DescribeCommandTest(DulwichCliTestCase):
  712. """Tests for describe command."""
  713. def test_describe(self):
  714. # Create tagged commit
  715. test_file = os.path.join(self.repo_path, "test.txt")
  716. with open(test_file, "w") as f:
  717. f.write("test")
  718. self._run_cli("add", "test.txt")
  719. self._run_cli("commit", "--message=Initial")
  720. self._run_cli("tag", "v1.0")
  721. result, stdout, stderr = self._run_cli("describe")
  722. self.assertIn("v1.0", stdout)
  723. class FsckCommandTest(DulwichCliTestCase):
  724. """Tests for fsck command."""
  725. def test_fsck(self):
  726. # Create a commit
  727. test_file = os.path.join(self.repo_path, "test.txt")
  728. with open(test_file, "w") as f:
  729. f.write("test")
  730. self._run_cli("add", "test.txt")
  731. self._run_cli("commit", "--message=Initial")
  732. result, stdout, stderr = self._run_cli("fsck")
  733. # Should complete without errors
  734. class RepackCommandTest(DulwichCliTestCase):
  735. """Tests for repack command."""
  736. def test_repack(self):
  737. # Create some objects
  738. for i in range(5):
  739. test_file = os.path.join(self.repo_path, f"test{i}.txt")
  740. with open(test_file, "w") as f:
  741. f.write(f"content {i}")
  742. self._run_cli("add", f"test{i}.txt")
  743. self._run_cli("commit", f"--message=Commit {i}")
  744. result, stdout, stderr = self._run_cli("repack")
  745. # Should create pack files
  746. pack_dir = os.path.join(self.repo_path, ".git", "objects", "pack")
  747. self.assertTrue(any(f.endswith(".pack") for f in os.listdir(pack_dir)))
  748. class ResetCommandTest(DulwichCliTestCase):
  749. """Tests for reset command."""
  750. def test_reset_soft(self):
  751. # Create commits
  752. test_file = os.path.join(self.repo_path, "test.txt")
  753. with open(test_file, "w") as f:
  754. f.write("first")
  755. self._run_cli("add", "test.txt")
  756. self._run_cli("commit", "--message=First")
  757. first_commit = self.repo.head()
  758. with open(test_file, "w") as f:
  759. f.write("second")
  760. self._run_cli("add", "test.txt")
  761. self._run_cli("commit", "--message=Second")
  762. # Reset soft
  763. result, stdout, stderr = self._run_cli("reset", "--soft", first_commit.decode())
  764. # HEAD should be at first commit
  765. self.assertEqual(self.repo.head(), first_commit)
  766. class WriteTreeCommandTest(DulwichCliTestCase):
  767. """Tests for write-tree command."""
  768. def test_write_tree(self):
  769. # Create and add files
  770. test_file = os.path.join(self.repo_path, "test.txt")
  771. with open(test_file, "w") as f:
  772. f.write("test")
  773. self._run_cli("add", "test.txt")
  774. result, stdout, stderr = self._run_cli("write-tree")
  775. # Should output tree SHA
  776. self.assertEqual(len(stdout.strip()), 40)
  777. class UpdateServerInfoCommandTest(DulwichCliTestCase):
  778. """Tests for update-server-info command."""
  779. def test_update_server_info(self):
  780. result, stdout, stderr = self._run_cli("update-server-info")
  781. # Should create info/refs file
  782. info_refs = os.path.join(self.repo_path, ".git", "info", "refs")
  783. self.assertTrue(os.path.exists(info_refs))
  784. class SymbolicRefCommandTest(DulwichCliTestCase):
  785. """Tests for symbolic-ref command."""
  786. def test_symbolic_ref(self):
  787. # Create a branch
  788. test_file = os.path.join(self.repo_path, "test.txt")
  789. with open(test_file, "w") as f:
  790. f.write("test")
  791. self._run_cli("add", "test.txt")
  792. self._run_cli("commit", "--message=Initial")
  793. self._run_cli("branch", "test-branch")
  794. result, stdout, stderr = self._run_cli(
  795. "symbolic-ref", "HEAD", "refs/heads/test-branch"
  796. )
  797. # HEAD should now point to test-branch
  798. self.assertEqual(
  799. self.repo.refs.read_ref(b"HEAD"), b"ref: refs/heads/test-branch"
  800. )
  801. class FormatBytesTestCase(TestCase):
  802. """Tests for format_bytes function."""
  803. def test_bytes(self):
  804. """Test formatting bytes."""
  805. self.assertEqual("0.0 B", format_bytes(0))
  806. self.assertEqual("1.0 B", format_bytes(1))
  807. self.assertEqual("512.0 B", format_bytes(512))
  808. self.assertEqual("1023.0 B", format_bytes(1023))
  809. def test_kilobytes(self):
  810. """Test formatting kilobytes."""
  811. self.assertEqual("1.0 KB", format_bytes(1024))
  812. self.assertEqual("1.5 KB", format_bytes(1536))
  813. self.assertEqual("2.0 KB", format_bytes(2048))
  814. self.assertEqual("1023.0 KB", format_bytes(1024 * 1023))
  815. def test_megabytes(self):
  816. """Test formatting megabytes."""
  817. self.assertEqual("1.0 MB", format_bytes(1024 * 1024))
  818. self.assertEqual("1.5 MB", format_bytes(1024 * 1024 * 1.5))
  819. self.assertEqual("10.0 MB", format_bytes(1024 * 1024 * 10))
  820. self.assertEqual("1023.0 MB", format_bytes(1024 * 1024 * 1023))
  821. def test_gigabytes(self):
  822. """Test formatting gigabytes."""
  823. self.assertEqual("1.0 GB", format_bytes(1024 * 1024 * 1024))
  824. self.assertEqual("2.5 GB", format_bytes(1024 * 1024 * 1024 * 2.5))
  825. self.assertEqual("1023.0 GB", format_bytes(1024 * 1024 * 1024 * 1023))
  826. def test_terabytes(self):
  827. """Test formatting terabytes."""
  828. self.assertEqual("1.0 TB", format_bytes(1024 * 1024 * 1024 * 1024))
  829. self.assertEqual("5.0 TB", format_bytes(1024 * 1024 * 1024 * 1024 * 5))
  830. self.assertEqual("1000.0 TB", format_bytes(1024 * 1024 * 1024 * 1024 * 1000))
  831. class ParseRelativeTimeTestCase(TestCase):
  832. """Tests for parse_relative_time function."""
  833. def test_now(self):
  834. """Test parsing 'now'."""
  835. self.assertEqual(0, parse_relative_time("now"))
  836. def test_seconds(self):
  837. """Test parsing seconds."""
  838. self.assertEqual(1, parse_relative_time("1 second ago"))
  839. self.assertEqual(5, parse_relative_time("5 seconds ago"))
  840. self.assertEqual(30, parse_relative_time("30 seconds ago"))
  841. def test_minutes(self):
  842. """Test parsing minutes."""
  843. self.assertEqual(60, parse_relative_time("1 minute ago"))
  844. self.assertEqual(300, parse_relative_time("5 minutes ago"))
  845. self.assertEqual(1800, parse_relative_time("30 minutes ago"))
  846. def test_hours(self):
  847. """Test parsing hours."""
  848. self.assertEqual(3600, parse_relative_time("1 hour ago"))
  849. self.assertEqual(7200, parse_relative_time("2 hours ago"))
  850. self.assertEqual(86400, parse_relative_time("24 hours ago"))
  851. def test_days(self):
  852. """Test parsing days."""
  853. self.assertEqual(86400, parse_relative_time("1 day ago"))
  854. self.assertEqual(604800, parse_relative_time("7 days ago"))
  855. self.assertEqual(2592000, parse_relative_time("30 days ago"))
  856. def test_weeks(self):
  857. """Test parsing weeks."""
  858. self.assertEqual(604800, parse_relative_time("1 week ago"))
  859. self.assertEqual(1209600, parse_relative_time("2 weeks ago"))
  860. self.assertEqual(
  861. 36288000, parse_relative_time("60 weeks ago")
  862. ) # 60 * 7 * 24 * 60 * 60
  863. def test_invalid_format(self):
  864. """Test invalid time formats."""
  865. with self.assertRaises(ValueError) as cm:
  866. parse_relative_time("invalid")
  867. self.assertIn("Invalid relative time format", str(cm.exception))
  868. with self.assertRaises(ValueError) as cm:
  869. parse_relative_time("2 weeks")
  870. self.assertIn("Invalid relative time format", str(cm.exception))
  871. with self.assertRaises(ValueError) as cm:
  872. parse_relative_time("ago")
  873. self.assertIn("Invalid relative time format", str(cm.exception))
  874. with self.assertRaises(ValueError) as cm:
  875. parse_relative_time("two weeks ago")
  876. self.assertIn("Invalid number in relative time", str(cm.exception))
  877. def test_invalid_unit(self):
  878. """Test invalid time units."""
  879. with self.assertRaises(ValueError) as cm:
  880. parse_relative_time("5 months ago")
  881. self.assertIn("Unknown time unit: months", str(cm.exception))
  882. with self.assertRaises(ValueError) as cm:
  883. parse_relative_time("2 years ago")
  884. self.assertIn("Unknown time unit: years", str(cm.exception))
  885. def test_singular_plural(self):
  886. """Test that both singular and plural forms work."""
  887. self.assertEqual(
  888. parse_relative_time("1 second ago"), parse_relative_time("1 seconds ago")
  889. )
  890. self.assertEqual(
  891. parse_relative_time("1 minute ago"), parse_relative_time("1 minutes ago")
  892. )
  893. self.assertEqual(
  894. parse_relative_time("1 hour ago"), parse_relative_time("1 hours ago")
  895. )
  896. self.assertEqual(
  897. parse_relative_time("1 day ago"), parse_relative_time("1 days ago")
  898. )
  899. self.assertEqual(
  900. parse_relative_time("1 week ago"), parse_relative_time("1 weeks ago")
  901. )
  902. if __name__ == "__main__":
  903. unittest.main()