test_cli.py 40 KB

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