test_cli.py 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455
  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 published 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, launch_editor, 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 HelperFunctionsTest(TestCase):
  101. """Tests for CLI helper functions."""
  102. def test_format_bytes(self):
  103. self.assertEqual("0.0 B", format_bytes(0))
  104. self.assertEqual("100.0 B", format_bytes(100))
  105. self.assertEqual("1.0 KB", format_bytes(1024))
  106. self.assertEqual("1.5 KB", format_bytes(1536))
  107. self.assertEqual("1.0 MB", format_bytes(1024 * 1024))
  108. self.assertEqual("1.0 GB", format_bytes(1024 * 1024 * 1024))
  109. self.assertEqual("1.0 TB", format_bytes(1024 * 1024 * 1024 * 1024))
  110. def test_launch_editor_with_cat(self):
  111. """Test launch_editor by using cat as the editor."""
  112. self.overrideEnv("GIT_EDITOR", "cat")
  113. result = launch_editor(b"Test template content")
  114. self.assertEqual(b"Test template content", result)
  115. class AddCommandTest(DulwichCliTestCase):
  116. """Tests for add command."""
  117. def test_add_single_file(self):
  118. # Create a file to add
  119. test_file = os.path.join(self.repo_path, "test.txt")
  120. with open(test_file, "w") as f:
  121. f.write("test content")
  122. result, stdout, stderr = self._run_cli("add", "test.txt")
  123. # Check that file is in index
  124. self.assertIn(b"test.txt", self.repo.open_index())
  125. def test_add_multiple_files(self):
  126. # Create multiple files
  127. for i in range(3):
  128. test_file = os.path.join(self.repo_path, f"test{i}.txt")
  129. with open(test_file, "w") as f:
  130. f.write(f"content {i}")
  131. result, stdout, stderr = self._run_cli(
  132. "add", "test0.txt", "test1.txt", "test2.txt"
  133. )
  134. index = self.repo.open_index()
  135. self.assertIn(b"test0.txt", index)
  136. self.assertIn(b"test1.txt", index)
  137. self.assertIn(b"test2.txt", index)
  138. class RmCommandTest(DulwichCliTestCase):
  139. """Tests for rm command."""
  140. def test_rm_file(self):
  141. # Create, add and commit a file first
  142. test_file = os.path.join(self.repo_path, "test.txt")
  143. with open(test_file, "w") as f:
  144. f.write("test content")
  145. self._run_cli("add", "test.txt")
  146. self._run_cli("commit", "--message=Add test file")
  147. # Now remove it from index and working directory
  148. result, stdout, stderr = self._run_cli("rm", "test.txt")
  149. # Check that file is not in index
  150. self.assertNotIn(b"test.txt", self.repo.open_index())
  151. class CommitCommandTest(DulwichCliTestCase):
  152. """Tests for commit command."""
  153. def test_commit_basic(self):
  154. # Create and add a file
  155. test_file = os.path.join(self.repo_path, "test.txt")
  156. with open(test_file, "w") as f:
  157. f.write("test content")
  158. self._run_cli("add", "test.txt")
  159. # Commit
  160. result, stdout, stderr = self._run_cli("commit", "--message=Initial commit")
  161. # Check that HEAD points to a commit
  162. self.assertIsNotNone(self.repo.head())
  163. def test_commit_all_flag(self):
  164. # Create initial commit
  165. test_file = os.path.join(self.repo_path, "test.txt")
  166. with open(test_file, "w") as f:
  167. f.write("initial content")
  168. self._run_cli("add", "test.txt")
  169. self._run_cli("commit", "--message=Initial commit")
  170. # Modify the file (don't stage it)
  171. with open(test_file, "w") as f:
  172. f.write("modified content")
  173. # Create another file and don't add it (untracked)
  174. untracked_file = os.path.join(self.repo_path, "untracked.txt")
  175. with open(untracked_file, "w") as f:
  176. f.write("untracked content")
  177. # Commit with -a flag should stage and commit the modified file,
  178. # but not the untracked file
  179. result, stdout, stderr = self._run_cli(
  180. "commit", "-a", "--message=Modified commit"
  181. )
  182. self.assertIsNotNone(self.repo.head())
  183. # Check that the modification was committed
  184. with open(test_file) as f:
  185. content = f.read()
  186. self.assertEqual(content, "modified content")
  187. # Check that untracked file is still untracked
  188. self.assertTrue(os.path.exists(untracked_file))
  189. def test_commit_all_flag_no_changes(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("initial content")
  194. self._run_cli("add", "test.txt")
  195. self._run_cli("commit", "--message=Initial commit")
  196. # Try to commit with -a when there are no changes
  197. # This should still work (git allows this)
  198. result, stdout, stderr = self._run_cli(
  199. "commit", "-a", "--message=No changes commit"
  200. )
  201. self.assertIsNotNone(self.repo.head())
  202. def test_commit_all_flag_multiple_files(self):
  203. # Create initial commit with multiple files
  204. file1 = os.path.join(self.repo_path, "file1.txt")
  205. file2 = os.path.join(self.repo_path, "file2.txt")
  206. with open(file1, "w") as f:
  207. f.write("content1")
  208. with open(file2, "w") as f:
  209. f.write("content2")
  210. self._run_cli("add", "file1.txt", "file2.txt")
  211. self._run_cli("commit", "--message=Initial commit")
  212. # Modify both files
  213. with open(file1, "w") as f:
  214. f.write("modified content1")
  215. with open(file2, "w") as f:
  216. f.write("modified content2")
  217. # Create an untracked file
  218. untracked_file = os.path.join(self.repo_path, "untracked.txt")
  219. with open(untracked_file, "w") as f:
  220. f.write("untracked content")
  221. # Commit with -a should stage both modified files but not untracked
  222. result, stdout, stderr = self._run_cli(
  223. "commit", "-a", "--message=Modified both files"
  224. )
  225. self.assertIsNotNone(self.repo.head())
  226. # Verify modifications were committed
  227. with open(file1) as f:
  228. self.assertEqual(f.read(), "modified content1")
  229. with open(file2) as f:
  230. self.assertEqual(f.read(), "modified content2")
  231. # Verify untracked file still exists
  232. self.assertTrue(os.path.exists(untracked_file))
  233. @patch("dulwich.cli.launch_editor")
  234. def test_commit_editor_success(self, mock_editor):
  235. """Test commit with editor when user provides a message."""
  236. # Create and add a file
  237. test_file = os.path.join(self.repo_path, "test.txt")
  238. with open(test_file, "w") as f:
  239. f.write("test content")
  240. self._run_cli("add", "test.txt")
  241. # Mock editor to return a commit message
  242. mock_editor.return_value = b"My commit message\n\n# This is a comment\n"
  243. # Commit without --message flag
  244. result, stdout, stderr = self._run_cli("commit")
  245. # Check that HEAD points to a commit
  246. commit = self.repo[self.repo.head()]
  247. self.assertEqual(commit.message, b"My commit message")
  248. # Verify editor was called
  249. mock_editor.assert_called_once()
  250. @patch("dulwich.cli.launch_editor")
  251. def test_commit_editor_empty_message(self, mock_editor):
  252. """Test commit with editor when user provides empty message."""
  253. # Create and add a file
  254. test_file = os.path.join(self.repo_path, "test.txt")
  255. with open(test_file, "w") as f:
  256. f.write("test content")
  257. self._run_cli("add", "test.txt")
  258. # Mock editor to return only comments
  259. mock_editor.return_value = b"# All lines are comments\n# No actual message\n"
  260. # Commit without --message flag should fail with exit code 1
  261. result, stdout, stderr = self._run_cli("commit")
  262. self.assertEqual(result, 1)
  263. @patch("dulwich.cli.launch_editor")
  264. def test_commit_editor_unchanged_template(self, mock_editor):
  265. """Test commit with editor when user doesn't change the template."""
  266. # Create and add a file
  267. test_file = os.path.join(self.repo_path, "test.txt")
  268. with open(test_file, "w") as f:
  269. f.write("test content")
  270. self._run_cli("add", "test.txt")
  271. # Mock editor to return the exact template that was passed to it
  272. def return_unchanged_template(template):
  273. return template
  274. mock_editor.side_effect = return_unchanged_template
  275. # Commit without --message flag should fail with exit code 1
  276. result, stdout, stderr = self._run_cli("commit")
  277. self.assertEqual(result, 1)
  278. class LogCommandTest(DulwichCliTestCase):
  279. """Tests for log command."""
  280. def test_log_empty_repo(self):
  281. result, stdout, stderr = self._run_cli("log")
  282. # Empty repo should not crash
  283. def test_log_with_commits(self):
  284. # Create some commits
  285. c1, c2, c3 = build_commit_graph(
  286. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  287. )
  288. self.repo.refs[b"HEAD"] = c3.id
  289. result, stdout, stderr = self._run_cli("log")
  290. self.assertIn("Commit 3", stdout)
  291. self.assertIn("Commit 2", stdout)
  292. self.assertIn("Commit 1", stdout)
  293. def test_log_reverse(self):
  294. # Create some commits
  295. c1, c2, c3 = build_commit_graph(
  296. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  297. )
  298. self.repo.refs[b"HEAD"] = c3.id
  299. result, stdout, stderr = self._run_cli("log", "--reverse")
  300. # Check order - commit 1 should appear before commit 3
  301. pos1 = stdout.index("Commit 1")
  302. pos3 = stdout.index("Commit 3")
  303. self.assertLess(pos1, pos3)
  304. class StatusCommandTest(DulwichCliTestCase):
  305. """Tests for status command."""
  306. def test_status_empty(self):
  307. result, stdout, stderr = self._run_cli("status")
  308. # Should not crash on empty repo
  309. def test_status_with_untracked(self):
  310. # Create an untracked file
  311. test_file = os.path.join(self.repo_path, "untracked.txt")
  312. with open(test_file, "w") as f:
  313. f.write("untracked content")
  314. result, stdout, stderr = self._run_cli("status")
  315. self.assertIn("Untracked files:", stdout)
  316. self.assertIn("untracked.txt", stdout)
  317. class BranchCommandTest(DulwichCliTestCase):
  318. """Tests for branch command."""
  319. def test_branch_create(self):
  320. # Create initial commit
  321. test_file = os.path.join(self.repo_path, "test.txt")
  322. with open(test_file, "w") as f:
  323. f.write("test")
  324. self._run_cli("add", "test.txt")
  325. self._run_cli("commit", "--message=Initial")
  326. # Create branch
  327. result, stdout, stderr = self._run_cli("branch", "test-branch")
  328. self.assertIn(b"refs/heads/test-branch", self.repo.refs.keys())
  329. def test_branch_delete(self):
  330. # Create initial commit and branch
  331. test_file = os.path.join(self.repo_path, "test.txt")
  332. with open(test_file, "w") as f:
  333. f.write("test")
  334. self._run_cli("add", "test.txt")
  335. self._run_cli("commit", "--message=Initial")
  336. self._run_cli("branch", "test-branch")
  337. # Delete branch
  338. result, stdout, stderr = self._run_cli("branch", "-d", "test-branch")
  339. self.assertNotIn(b"refs/heads/test-branch", self.repo.refs.keys())
  340. class CheckoutCommandTest(DulwichCliTestCase):
  341. """Tests for checkout command."""
  342. def test_checkout_branch(self):
  343. # Create initial commit and branch
  344. test_file = os.path.join(self.repo_path, "test.txt")
  345. with open(test_file, "w") as f:
  346. f.write("test")
  347. self._run_cli("add", "test.txt")
  348. self._run_cli("commit", "--message=Initial")
  349. self._run_cli("branch", "test-branch")
  350. # Checkout branch
  351. result, stdout, stderr = self._run_cli("checkout", "test-branch")
  352. self.assertEqual(
  353. self.repo.refs.read_ref(b"HEAD"), b"ref: refs/heads/test-branch"
  354. )
  355. class TagCommandTest(DulwichCliTestCase):
  356. """Tests for tag command."""
  357. def test_tag_create(self):
  358. # Create initial commit
  359. test_file = os.path.join(self.repo_path, "test.txt")
  360. with open(test_file, "w") as f:
  361. f.write("test")
  362. self._run_cli("add", "test.txt")
  363. self._run_cli("commit", "--message=Initial")
  364. # Create tag
  365. result, stdout, stderr = self._run_cli("tag", "v1.0")
  366. self.assertIn(b"refs/tags/v1.0", self.repo.refs.keys())
  367. class DiffCommandTest(DulwichCliTestCase):
  368. """Tests for diff command."""
  369. def test_diff_working_tree(self):
  370. # Create and commit a file
  371. test_file = os.path.join(self.repo_path, "test.txt")
  372. with open(test_file, "w") as f:
  373. f.write("initial content\n")
  374. self._run_cli("add", "test.txt")
  375. self._run_cli("commit", "--message=Initial")
  376. # Modify the file
  377. with open(test_file, "w") as f:
  378. f.write("initial content\nmodified\n")
  379. # Test unstaged diff
  380. result, stdout, stderr = self._run_cli("diff")
  381. self.assertIn("+modified", stdout)
  382. def test_diff_staged(self):
  383. # Create initial commit
  384. test_file = os.path.join(self.repo_path, "test.txt")
  385. with open(test_file, "w") as f:
  386. f.write("initial content\n")
  387. self._run_cli("add", "test.txt")
  388. self._run_cli("commit", "--message=Initial")
  389. # Modify and stage the file
  390. with open(test_file, "w") as f:
  391. f.write("initial content\nnew file\n")
  392. self._run_cli("add", "test.txt")
  393. # Test staged diff
  394. result, stdout, stderr = self._run_cli("diff", "--staged")
  395. self.assertIn("+new file", stdout)
  396. def test_diff_cached(self):
  397. # Create initial commit
  398. test_file = os.path.join(self.repo_path, "test.txt")
  399. with open(test_file, "w") as f:
  400. f.write("initial content\n")
  401. self._run_cli("add", "test.txt")
  402. self._run_cli("commit", "--message=Initial")
  403. # Modify and stage the file
  404. with open(test_file, "w") as f:
  405. f.write("initial content\nnew file\n")
  406. self._run_cli("add", "test.txt")
  407. # Test cached diff (alias for staged)
  408. result, stdout, stderr = self._run_cli("diff", "--cached")
  409. self.assertIn("+new file", stdout)
  410. def test_diff_commit(self):
  411. # Create two commits
  412. test_file = os.path.join(self.repo_path, "test.txt")
  413. with open(test_file, "w") as f:
  414. f.write("first version\n")
  415. self._run_cli("add", "test.txt")
  416. self._run_cli("commit", "--message=First")
  417. with open(test_file, "w") as f:
  418. f.write("first version\nsecond line\n")
  419. self._run_cli("add", "test.txt")
  420. self._run_cli("commit", "--message=Second")
  421. # Add working tree changes
  422. with open(test_file, "a") as f:
  423. f.write("working tree change\n")
  424. # Test single commit diff (should show working tree vs HEAD)
  425. result, stdout, stderr = self._run_cli("diff", "HEAD")
  426. self.assertIn("+working tree change", stdout)
  427. def test_diff_two_commits(self):
  428. # Create two commits
  429. test_file = os.path.join(self.repo_path, "test.txt")
  430. with open(test_file, "w") as f:
  431. f.write("first version\n")
  432. self._run_cli("add", "test.txt")
  433. self._run_cli("commit", "--message=First")
  434. # Get first commit SHA
  435. first_commit = self.repo.refs[b"HEAD"].decode()
  436. with open(test_file, "w") as f:
  437. f.write("first version\nsecond line\n")
  438. self._run_cli("add", "test.txt")
  439. self._run_cli("commit", "--message=Second")
  440. # Get second commit SHA
  441. second_commit = self.repo.refs[b"HEAD"].decode()
  442. # Test diff between two commits
  443. result, stdout, stderr = self._run_cli("diff", first_commit, second_commit)
  444. self.assertIn("+second line", stdout)
  445. def test_diff_commit_vs_working_tree(self):
  446. # Test that diff <commit> shows working tree vs commit (not commit vs parent)
  447. test_file = os.path.join(self.repo_path, "test.txt")
  448. with open(test_file, "w") as f:
  449. f.write("first version\n")
  450. self._run_cli("add", "test.txt")
  451. self._run_cli("commit", "--message=First")
  452. first_commit = self.repo.refs[b"HEAD"].decode()
  453. with open(test_file, "w") as f:
  454. f.write("first version\nsecond line\n")
  455. self._run_cli("add", "test.txt")
  456. self._run_cli("commit", "--message=Second")
  457. # Add changes to working tree
  458. with open(test_file, "w") as f:
  459. f.write("completely different\n")
  460. # diff <first_commit> should show working tree vs first commit
  461. result, stdout, stderr = self._run_cli("diff", first_commit)
  462. self.assertIn("-first version", stdout)
  463. self.assertIn("+completely different", stdout)
  464. def test_diff_with_paths(self):
  465. # Test path filtering
  466. # Create multiple files
  467. file1 = os.path.join(self.repo_path, "file1.txt")
  468. file2 = os.path.join(self.repo_path, "file2.txt")
  469. subdir = os.path.join(self.repo_path, "subdir")
  470. os.makedirs(subdir)
  471. file3 = os.path.join(subdir, "file3.txt")
  472. with open(file1, "w") as f:
  473. f.write("content1\n")
  474. with open(file2, "w") as f:
  475. f.write("content2\n")
  476. with open(file3, "w") as f:
  477. f.write("content3\n")
  478. self._run_cli("add", ".")
  479. self._run_cli("commit", "--message=Initial")
  480. # Modify all files
  481. with open(file1, "w") as f:
  482. f.write("modified1\n")
  483. with open(file2, "w") as f:
  484. f.write("modified2\n")
  485. with open(file3, "w") as f:
  486. f.write("modified3\n")
  487. # Test diff with specific file
  488. result, stdout, stderr = self._run_cli("diff", "--", "file1.txt")
  489. self.assertIn("file1.txt", stdout)
  490. self.assertNotIn("file2.txt", stdout)
  491. self.assertNotIn("file3.txt", stdout)
  492. # Test diff with directory
  493. result, stdout, stderr = self._run_cli("diff", "--", "subdir")
  494. self.assertNotIn("file1.txt", stdout)
  495. self.assertNotIn("file2.txt", stdout)
  496. self.assertIn("file3.txt", stdout)
  497. # Test staged diff with paths
  498. self._run_cli("add", "file1.txt")
  499. result, stdout, stderr = self._run_cli("diff", "--staged", "--", "file1.txt")
  500. self.assertIn("file1.txt", stdout)
  501. self.assertIn("+modified1", stdout)
  502. # Test diff with multiple paths (file2 and file3 are still unstaged)
  503. result, stdout, stderr = self._run_cli(
  504. "diff", "--", "file2.txt", "subdir/file3.txt"
  505. )
  506. self.assertIn("file2.txt", stdout)
  507. self.assertIn("file3.txt", stdout)
  508. self.assertNotIn("file1.txt", stdout)
  509. # Test diff with commit and paths
  510. first_commit = self.repo.refs[b"HEAD"].decode()
  511. with open(file1, "w") as f:
  512. f.write("newer1\n")
  513. result, stdout, stderr = self._run_cli("diff", first_commit, "--", "file1.txt")
  514. self.assertIn("file1.txt", stdout)
  515. self.assertIn("-content1", stdout)
  516. self.assertIn("+newer1", stdout)
  517. self.assertNotIn("file2.txt", stdout)
  518. class FilterBranchCommandTest(DulwichCliTestCase):
  519. """Tests for filter-branch command."""
  520. def setUp(self):
  521. super().setUp()
  522. # Create a more complex repository structure for testing
  523. # Create some files in subdirectories
  524. os.makedirs(os.path.join(self.repo_path, "subdir"))
  525. os.makedirs(os.path.join(self.repo_path, "other"))
  526. # Create files
  527. files = {
  528. "README.md": "# Test Repo",
  529. "subdir/file1.txt": "File in subdir",
  530. "subdir/file2.txt": "Another file in subdir",
  531. "other/file3.txt": "File in other dir",
  532. "root.txt": "File at root",
  533. }
  534. for path, content in files.items():
  535. file_path = os.path.join(self.repo_path, path)
  536. with open(file_path, "w") as f:
  537. f.write(content)
  538. # Add all files and create initial commit
  539. self._run_cli("add", ".")
  540. self._run_cli("commit", "--message=Initial commit")
  541. # Create a second commit modifying subdir
  542. with open(os.path.join(self.repo_path, "subdir/file1.txt"), "a") as f:
  543. f.write("\nModified content")
  544. self._run_cli("add", "subdir/file1.txt")
  545. self._run_cli("commit", "--message=Modify subdir file")
  546. # Create a third commit in other dir
  547. with open(os.path.join(self.repo_path, "other/file3.txt"), "a") as f:
  548. f.write("\nMore content")
  549. self._run_cli("add", "other/file3.txt")
  550. self._run_cli("commit", "--message=Modify other file")
  551. # Create a branch
  552. self._run_cli("branch", "test-branch")
  553. # Create a tag
  554. self._run_cli("tag", "v1.0")
  555. def test_filter_branch_subdirectory_filter(self):
  556. """Test filter-branch with subdirectory filter."""
  557. # Run filter-branch to extract only the subdir
  558. result, stdout, stderr = self._run_cli(
  559. "filter-branch", "--subdirectory-filter", "subdir"
  560. )
  561. # Check that the operation succeeded
  562. self.assertEqual(result, 0)
  563. self.assertIn("Rewrite HEAD", stdout)
  564. # filter-branch rewrites history but doesn't update working tree
  565. # We need to check the commit contents, not the working tree
  566. # Reset to the rewritten HEAD to update working tree
  567. self._run_cli("reset", "--hard", "HEAD")
  568. # Now check that only files from subdir remain at root level
  569. self.assertTrue(os.path.exists(os.path.join(self.repo_path, "file1.txt")))
  570. self.assertTrue(os.path.exists(os.path.join(self.repo_path, "file2.txt")))
  571. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "README.md")))
  572. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "root.txt")))
  573. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "other")))
  574. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "subdir")))
  575. # Check that original refs were backed up
  576. original_refs = [
  577. ref for ref in self.repo.refs.keys() if ref.startswith(b"refs/original/")
  578. ]
  579. self.assertTrue(
  580. len(original_refs) > 0, "No original refs found after filter-branch"
  581. )
  582. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  583. def test_filter_branch_msg_filter(self):
  584. """Test filter-branch with message filter."""
  585. # Run filter-branch to prepend [FILTERED] to commit messages
  586. result, stdout, stderr = self._run_cli(
  587. "filter-branch", "--msg-filter", "sed 's/^/[FILTERED] /'"
  588. )
  589. self.assertEqual(result, 0)
  590. # Check that commit messages were modified
  591. result, stdout, stderr = self._run_cli("log")
  592. self.assertIn("[FILTERED] Modify other file", stdout)
  593. self.assertIn("[FILTERED] Modify subdir file", stdout)
  594. self.assertIn("[FILTERED] Initial commit", stdout)
  595. def test_filter_branch_env_filter(self):
  596. """Test filter-branch with environment filter."""
  597. # Run filter-branch to change author email
  598. env_filter = """
  599. if [ "$GIT_AUTHOR_EMAIL" = "test@example.com" ]; then
  600. export GIT_AUTHOR_EMAIL="filtered@example.com"
  601. fi
  602. """
  603. result, stdout, stderr = self._run_cli(
  604. "filter-branch", "--env-filter", env_filter
  605. )
  606. self.assertEqual(result, 0)
  607. def test_filter_branch_prune_empty(self):
  608. """Test filter-branch with prune-empty option."""
  609. # Create a commit that only touches files outside subdir
  610. with open(os.path.join(self.repo_path, "root.txt"), "a") as f:
  611. f.write("\nNew line")
  612. self._run_cli("add", "root.txt")
  613. self._run_cli("commit", "--message=Modify root file only")
  614. # Run filter-branch to extract subdir with prune-empty
  615. result, stdout, stderr = self._run_cli(
  616. "filter-branch", "--subdirectory-filter", "subdir", "--prune-empty"
  617. )
  618. self.assertEqual(result, 0)
  619. # The last commit should have been pruned
  620. result, stdout, stderr = self._run_cli("log")
  621. self.assertNotIn("Modify root file only", stdout)
  622. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  623. def test_filter_branch_force(self):
  624. """Test filter-branch with force option."""
  625. # Run filter-branch once with a filter that actually changes something
  626. result, stdout, stderr = self._run_cli(
  627. "filter-branch", "--msg-filter", "sed 's/^/[TEST] /'"
  628. )
  629. self.assertEqual(result, 0)
  630. # Check that backup refs were created
  631. # The implementation backs up refs under refs/original/
  632. original_refs = [
  633. ref for ref in self.repo.refs.keys() if ref.startswith(b"refs/original/")
  634. ]
  635. self.assertTrue(len(original_refs) > 0, "No original refs found")
  636. # Run again without force - should fail
  637. result, stdout, stderr = self._run_cli(
  638. "filter-branch", "--msg-filter", "sed 's/^/[TEST2] /'"
  639. )
  640. self.assertEqual(result, 1)
  641. self.assertIn("Cannot create a new backup", stdout)
  642. self.assertIn("refs/original", stdout)
  643. # Run with force - should succeed
  644. result, stdout, stderr = self._run_cli(
  645. "filter-branch", "--force", "--msg-filter", "sed 's/^/[TEST3] /'"
  646. )
  647. self.assertEqual(result, 0)
  648. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  649. def test_filter_branch_specific_branch(self):
  650. """Test filter-branch on a specific branch."""
  651. # Switch to test-branch and add a commit
  652. self._run_cli("checkout", "test-branch")
  653. with open(os.path.join(self.repo_path, "branch-file.txt"), "w") as f:
  654. f.write("Branch specific file")
  655. self._run_cli("add", "branch-file.txt")
  656. self._run_cli("commit", "--message=Branch commit")
  657. # Run filter-branch on the test-branch
  658. result, stdout, stderr = self._run_cli(
  659. "filter-branch", "--msg-filter", "sed 's/^/[BRANCH] /'", "test-branch"
  660. )
  661. self.assertEqual(result, 0)
  662. self.assertIn("Ref 'refs/heads/test-branch' was rewritten", stdout)
  663. # Check that only test-branch was modified
  664. result, stdout, stderr = self._run_cli("log")
  665. self.assertIn("[BRANCH] Branch commit", stdout)
  666. # Switch to master and check it wasn't modified
  667. self._run_cli("checkout", "master")
  668. result, stdout, stderr = self._run_cli("log")
  669. self.assertNotIn("[BRANCH]", stdout)
  670. def test_filter_branch_tree_filter(self):
  671. """Test filter-branch with tree filter."""
  672. # Use a tree filter to remove a specific file
  673. tree_filter = "rm -f root.txt"
  674. result, stdout, stderr = self._run_cli(
  675. "filter-branch", "--tree-filter", tree_filter
  676. )
  677. self.assertEqual(result, 0)
  678. # Check that the file was removed from the latest commit
  679. # We need to check the commit tree, not the working directory
  680. result, stdout, stderr = self._run_cli("ls-tree", "HEAD")
  681. self.assertNotIn("root.txt", stdout)
  682. def test_filter_branch_index_filter(self):
  683. """Test filter-branch with index filter."""
  684. # Use an index filter to remove a file from the index
  685. index_filter = "git rm --cached --ignore-unmatch root.txt"
  686. result, stdout, stderr = self._run_cli(
  687. "filter-branch", "--index-filter", index_filter
  688. )
  689. self.assertEqual(result, 0)
  690. def test_filter_branch_parent_filter(self):
  691. """Test filter-branch with parent filter."""
  692. # Create a merge commit first
  693. self._run_cli("checkout", "HEAD", "-b", "feature")
  694. with open(os.path.join(self.repo_path, "feature.txt"), "w") as f:
  695. f.write("Feature")
  696. self._run_cli("add", "feature.txt")
  697. self._run_cli("commit", "--message=Feature commit")
  698. self._run_cli("checkout", "master")
  699. self._run_cli("merge", "feature", "--message=Merge feature")
  700. # Use parent filter to linearize history (remove second parent)
  701. parent_filter = "cut -d' ' -f1"
  702. result, stdout, stderr = self._run_cli(
  703. "filter-branch", "--parent-filter", parent_filter
  704. )
  705. self.assertEqual(result, 0)
  706. def test_filter_branch_commit_filter(self):
  707. """Test filter-branch with commit filter."""
  708. # Use commit filter to skip commits with certain messages
  709. commit_filter = """
  710. if grep -q "Modify other" <<< "$GIT_COMMIT_MESSAGE"; then
  711. skip_commit "$@"
  712. else
  713. git commit-tree "$@"
  714. fi
  715. """
  716. result, stdout, stderr = self._run_cli(
  717. "filter-branch", "--commit-filter", commit_filter
  718. )
  719. # Note: This test may fail because the commit filter syntax is simplified
  720. # In real Git, skip_commit is a function, but our implementation may differ
  721. def test_filter_branch_tag_name_filter(self):
  722. """Test filter-branch with tag name filter."""
  723. # Run filter-branch with tag name filter to rename tags
  724. result, stdout, stderr = self._run_cli(
  725. "filter-branch",
  726. "--tag-name-filter",
  727. "sed 's/^v/version-/'",
  728. "--msg-filter",
  729. "cat",
  730. )
  731. self.assertEqual(result, 0)
  732. # Check that tag was renamed
  733. self.assertIn(b"refs/tags/version-1.0", self.repo.refs.keys())
  734. def test_filter_branch_errors(self):
  735. """Test filter-branch error handling."""
  736. # Test with invalid subdirectory
  737. result, stdout, stderr = self._run_cli(
  738. "filter-branch", "--subdirectory-filter", "nonexistent"
  739. )
  740. # Should still succeed but produce empty history
  741. self.assertEqual(result, 0)
  742. def test_filter_branch_no_args(self):
  743. """Test filter-branch with no arguments."""
  744. # Should work as no-op
  745. result, stdout, stderr = self._run_cli("filter-branch")
  746. self.assertEqual(result, 0)
  747. class ShowCommandTest(DulwichCliTestCase):
  748. """Tests for show command."""
  749. def test_show_commit(self):
  750. # Create a commit
  751. test_file = os.path.join(self.repo_path, "test.txt")
  752. with open(test_file, "w") as f:
  753. f.write("test content")
  754. self._run_cli("add", "test.txt")
  755. self._run_cli("commit", "--message=Test commit")
  756. result, stdout, stderr = self._run_cli("show", "HEAD")
  757. self.assertIn("Test commit", stdout)
  758. class FormatPatchCommandTest(DulwichCliTestCase):
  759. """Tests for format-patch command."""
  760. def test_format_patch_single_commit(self):
  761. # Create a commit with actual content
  762. from dulwich.objects import Blob, Tree
  763. # Initial commit
  764. tree1 = Tree()
  765. self.repo.object_store.add_object(tree1)
  766. self.repo.get_worktree().commit(
  767. message=b"Initial commit",
  768. tree=tree1.id,
  769. )
  770. # Second commit with a file
  771. blob = Blob.from_string(b"Hello, World!\n")
  772. self.repo.object_store.add_object(blob)
  773. tree2 = Tree()
  774. tree2.add(b"hello.txt", 0o100644, blob.id)
  775. self.repo.object_store.add_object(tree2)
  776. self.repo.get_worktree().commit(
  777. message=b"Add hello.txt",
  778. tree=tree2.id,
  779. )
  780. # Test format-patch for last commit
  781. result, stdout, stderr = self._run_cli("format-patch", "-n", "1")
  782. self.assertEqual(result, None)
  783. self.assertIn("0001-Add-hello.txt.patch", stdout)
  784. # Check patch contents
  785. patch_file = os.path.join(self.repo_path, "0001-Add-hello.txt.patch")
  786. with open(patch_file, "rb") as f:
  787. content = f.read()
  788. # Check header
  789. self.assertIn(b"Subject: [PATCH 1/1] Add hello.txt", content)
  790. self.assertIn(b"From:", content)
  791. self.assertIn(b"Date:", content)
  792. # Check diff content
  793. self.assertIn(b"diff --git a/hello.txt b/hello.txt", content)
  794. self.assertIn(b"new file mode", content)
  795. self.assertIn(b"+Hello, World!", content)
  796. # Check footer
  797. self.assertIn(b"-- \nDulwich", content)
  798. # Clean up
  799. os.remove(patch_file)
  800. def test_format_patch_multiple_commits(self):
  801. from dulwich.objects import Blob, Tree
  802. # Initial commit
  803. tree1 = Tree()
  804. self.repo.object_store.add_object(tree1)
  805. self.repo.get_worktree().commit(
  806. message=b"Initial commit",
  807. tree=tree1.id,
  808. )
  809. # Second commit
  810. blob1 = Blob.from_string(b"File 1 content\n")
  811. self.repo.object_store.add_object(blob1)
  812. tree2 = Tree()
  813. tree2.add(b"file1.txt", 0o100644, blob1.id)
  814. self.repo.object_store.add_object(tree2)
  815. self.repo.get_worktree().commit(
  816. message=b"Add file1.txt",
  817. tree=tree2.id,
  818. )
  819. # Third commit
  820. blob2 = Blob.from_string(b"File 2 content\n")
  821. self.repo.object_store.add_object(blob2)
  822. tree3 = Tree()
  823. tree3.add(b"file1.txt", 0o100644, blob1.id)
  824. tree3.add(b"file2.txt", 0o100644, blob2.id)
  825. self.repo.object_store.add_object(tree3)
  826. self.repo.get_worktree().commit(
  827. message=b"Add file2.txt",
  828. tree=tree3.id,
  829. )
  830. # Test format-patch for last 2 commits
  831. result, stdout, stderr = self._run_cli("format-patch", "-n", "2")
  832. self.assertEqual(result, None)
  833. self.assertIn("0001-Add-file1.txt.patch", stdout)
  834. self.assertIn("0002-Add-file2.txt.patch", stdout)
  835. # Check first patch
  836. with open(os.path.join(self.repo_path, "0001-Add-file1.txt.patch"), "rb") as f:
  837. content = f.read()
  838. self.assertIn(b"Subject: [PATCH 1/2] Add file1.txt", content)
  839. self.assertIn(b"+File 1 content", content)
  840. # Check second patch
  841. with open(os.path.join(self.repo_path, "0002-Add-file2.txt.patch"), "rb") as f:
  842. content = f.read()
  843. self.assertIn(b"Subject: [PATCH 2/2] Add file2.txt", content)
  844. self.assertIn(b"+File 2 content", content)
  845. # Clean up
  846. os.remove(os.path.join(self.repo_path, "0001-Add-file1.txt.patch"))
  847. os.remove(os.path.join(self.repo_path, "0002-Add-file2.txt.patch"))
  848. def test_format_patch_output_directory(self):
  849. from dulwich.objects import Blob, Tree
  850. # Create a commit
  851. blob = Blob.from_string(b"Test content\n")
  852. self.repo.object_store.add_object(blob)
  853. tree = Tree()
  854. tree.add(b"test.txt", 0o100644, blob.id)
  855. self.repo.object_store.add_object(tree)
  856. self.repo.get_worktree().commit(
  857. message=b"Test commit",
  858. tree=tree.id,
  859. )
  860. # Create output directory
  861. output_dir = os.path.join(self.test_dir, "patches")
  862. os.makedirs(output_dir)
  863. # Test format-patch with output directory
  864. result, stdout, stderr = self._run_cli(
  865. "format-patch", "-o", output_dir, "-n", "1"
  866. )
  867. self.assertEqual(result, None)
  868. # Check that file was created in output directory with correct content
  869. patch_file = os.path.join(output_dir, "0001-Test-commit.patch")
  870. self.assertTrue(os.path.exists(patch_file))
  871. with open(patch_file, "rb") as f:
  872. content = f.read()
  873. self.assertIn(b"Subject: [PATCH 1/1] Test commit", content)
  874. self.assertIn(b"+Test content", content)
  875. def test_format_patch_commit_range(self):
  876. from dulwich.objects import Blob, Tree
  877. # Create commits with actual file changes
  878. commits = []
  879. trees = []
  880. # Initial empty commit
  881. tree0 = Tree()
  882. self.repo.object_store.add_object(tree0)
  883. trees.append(tree0)
  884. c0 = self.repo.get_worktree().commit(
  885. message=b"Initial commit",
  886. tree=tree0.id,
  887. )
  888. commits.append(c0)
  889. # Add three files in separate commits
  890. for i in range(1, 4):
  891. blob = Blob.from_string(f"Content {i}\n".encode())
  892. self.repo.object_store.add_object(blob)
  893. tree = Tree()
  894. # Copy previous files
  895. for j in range(1, i):
  896. prev_blob_id = trees[j][f"file{j}.txt".encode()][1]
  897. tree.add(f"file{j}.txt".encode(), 0o100644, prev_blob_id)
  898. # Add new file
  899. tree.add(f"file{i}.txt".encode(), 0o100644, blob.id)
  900. self.repo.object_store.add_object(tree)
  901. trees.append(tree)
  902. c = self.repo.get_worktree().commit(
  903. message=f"Add file{i}.txt".encode(),
  904. tree=tree.id,
  905. )
  906. commits.append(c)
  907. # Test format-patch with commit range (should get commits 2 and 3)
  908. result, stdout, stderr = self._run_cli(
  909. "format-patch", f"{commits[1].decode()}..{commits[3].decode()}"
  910. )
  911. self.assertEqual(result, None)
  912. # Should create patches for commits 2 and 3
  913. self.assertIn("0001-Add-file2.txt.patch", stdout)
  914. self.assertIn("0002-Add-file3.txt.patch", stdout)
  915. # Verify patch contents
  916. with open(os.path.join(self.repo_path, "0001-Add-file2.txt.patch"), "rb") as f:
  917. content = f.read()
  918. self.assertIn(b"Subject: [PATCH 1/2] Add file2.txt", content)
  919. self.assertIn(b"+Content 2", content)
  920. self.assertNotIn(b"file3.txt", content) # Should not include file3
  921. with open(os.path.join(self.repo_path, "0002-Add-file3.txt.patch"), "rb") as f:
  922. content = f.read()
  923. self.assertIn(b"Subject: [PATCH 2/2] Add file3.txt", content)
  924. self.assertIn(b"+Content 3", content)
  925. self.assertNotIn(b"file2.txt", content) # Should not modify file2
  926. # Clean up
  927. os.remove(os.path.join(self.repo_path, "0001-Add-file2.txt.patch"))
  928. os.remove(os.path.join(self.repo_path, "0002-Add-file3.txt.patch"))
  929. def test_format_patch_stdout(self):
  930. from dulwich.objects import Blob, Tree
  931. # Create a commit with modified file
  932. tree1 = Tree()
  933. blob1 = Blob.from_string(b"Original content\n")
  934. self.repo.object_store.add_object(blob1)
  935. tree1.add(b"file.txt", 0o100644, blob1.id)
  936. self.repo.object_store.add_object(tree1)
  937. self.repo.get_worktree().commit(
  938. message=b"Initial commit",
  939. tree=tree1.id,
  940. )
  941. tree2 = Tree()
  942. blob2 = Blob.from_string(b"Modified content\n")
  943. self.repo.object_store.add_object(blob2)
  944. tree2.add(b"file.txt", 0o100644, blob2.id)
  945. self.repo.object_store.add_object(tree2)
  946. self.repo.get_worktree().commit(
  947. message=b"Modify file.txt",
  948. tree=tree2.id,
  949. )
  950. # Mock stdout as a BytesIO for binary output
  951. stdout_stream = io.BytesIO()
  952. stdout_stream.buffer = stdout_stream
  953. # Run command with --stdout
  954. old_stdout = sys.stdout
  955. old_stderr = sys.stderr
  956. old_cwd = os.getcwd()
  957. try:
  958. sys.stdout = stdout_stream
  959. sys.stderr = io.StringIO()
  960. os.chdir(self.repo_path)
  961. cli.main(["format-patch", "--stdout", "-n", "1"])
  962. finally:
  963. sys.stdout = old_stdout
  964. sys.stderr = old_stderr
  965. os.chdir(old_cwd)
  966. # Check output
  967. stdout_stream.seek(0)
  968. output = stdout_stream.read()
  969. self.assertIn(b"Subject: [PATCH 1/1] Modify file.txt", output)
  970. self.assertIn(b"diff --git a/file.txt b/file.txt", output)
  971. self.assertIn(b"-Original content", output)
  972. self.assertIn(b"+Modified content", output)
  973. self.assertIn(b"-- \nDulwich", output)
  974. def test_format_patch_empty_repo(self):
  975. # Test with empty repository
  976. result, stdout, stderr = self._run_cli("format-patch", "-n", "5")
  977. self.assertEqual(result, None)
  978. # Should produce no output for empty repo
  979. self.assertEqual(stdout.strip(), "")
  980. class FetchPackCommandTest(DulwichCliTestCase):
  981. """Tests for fetch-pack command."""
  982. @patch("dulwich.cli.get_transport_and_path")
  983. def test_fetch_pack_basic(self, mock_transport):
  984. # Mock the transport
  985. mock_client = MagicMock()
  986. mock_transport.return_value = (mock_client, "/path/to/repo")
  987. mock_client.fetch.return_value = None
  988. result, stdout, stderr = self._run_cli(
  989. "fetch-pack", "git://example.com/repo.git"
  990. )
  991. mock_client.fetch.assert_called_once()
  992. class LsRemoteCommandTest(DulwichCliTestCase):
  993. """Tests for ls-remote command."""
  994. def test_ls_remote_basic(self):
  995. # Create a commit
  996. test_file = os.path.join(self.repo_path, "test.txt")
  997. with open(test_file, "w") as f:
  998. f.write("test")
  999. self._run_cli("add", "test.txt")
  1000. self._run_cli("commit", "--message=Initial")
  1001. # Test basic ls-remote
  1002. result, stdout, stderr = self._run_cli("ls-remote", self.repo_path)
  1003. lines = stdout.strip().split("\n")
  1004. self.assertTrue(any("HEAD" in line for line in lines))
  1005. self.assertTrue(any("refs/heads/master" in line for line in lines))
  1006. def test_ls_remote_symref(self):
  1007. # Create a commit
  1008. test_file = os.path.join(self.repo_path, "test.txt")
  1009. with open(test_file, "w") as f:
  1010. f.write("test")
  1011. self._run_cli("add", "test.txt")
  1012. self._run_cli("commit", "--message=Initial")
  1013. # Test ls-remote with --symref option
  1014. result, stdout, stderr = self._run_cli("ls-remote", "--symref", self.repo_path)
  1015. lines = stdout.strip().split("\n")
  1016. # Should show symref for HEAD in exact format: "ref: refs/heads/master\tHEAD"
  1017. expected_line = "ref: refs/heads/master\tHEAD"
  1018. self.assertIn(
  1019. expected_line,
  1020. lines,
  1021. f"Expected line '{expected_line}' not found in output: {lines}",
  1022. )
  1023. class PullCommandTest(DulwichCliTestCase):
  1024. """Tests for pull command."""
  1025. @patch("dulwich.porcelain.pull")
  1026. def test_pull_basic(self, mock_pull):
  1027. result, stdout, stderr = self._run_cli("pull", "origin")
  1028. mock_pull.assert_called_once()
  1029. @patch("dulwich.porcelain.pull")
  1030. def test_pull_with_refspec(self, mock_pull):
  1031. result, stdout, stderr = self._run_cli("pull", "origin", "master")
  1032. mock_pull.assert_called_once()
  1033. class PushCommandTest(DulwichCliTestCase):
  1034. """Tests for push command."""
  1035. @patch("dulwich.porcelain.push")
  1036. def test_push_basic(self, mock_push):
  1037. result, stdout, stderr = self._run_cli("push", "origin")
  1038. mock_push.assert_called_once()
  1039. @patch("dulwich.porcelain.push")
  1040. def test_push_force(self, mock_push):
  1041. result, stdout, stderr = self._run_cli("push", "-f", "origin")
  1042. mock_push.assert_called_with(".", "origin", None, force=True)
  1043. class ArchiveCommandTest(DulwichCliTestCase):
  1044. """Tests for archive command."""
  1045. def test_archive_basic(self):
  1046. # Create a commit
  1047. test_file = os.path.join(self.repo_path, "test.txt")
  1048. with open(test_file, "w") as f:
  1049. f.write("test content")
  1050. self._run_cli("add", "test.txt")
  1051. self._run_cli("commit", "--message=Initial")
  1052. # Archive produces binary output, so use BytesIO
  1053. result, stdout, stderr = self._run_cli(
  1054. "archive", "HEAD", stdout_stream=io.BytesIO()
  1055. )
  1056. # Should complete without error and produce some binary output
  1057. self.assertIsInstance(stdout, bytes)
  1058. self.assertGreater(len(stdout), 0)
  1059. class ForEachRefCommandTest(DulwichCliTestCase):
  1060. """Tests for for-each-ref command."""
  1061. def test_for_each_ref(self):
  1062. # Create a commit
  1063. test_file = os.path.join(self.repo_path, "test.txt")
  1064. with open(test_file, "w") as f:
  1065. f.write("test")
  1066. self._run_cli("add", "test.txt")
  1067. self._run_cli("commit", "--message=Initial")
  1068. result, stdout, stderr = self._run_cli("for-each-ref")
  1069. self.assertIn("refs/heads/master", stdout)
  1070. class PackRefsCommandTest(DulwichCliTestCase):
  1071. """Tests for pack-refs command."""
  1072. def test_pack_refs(self):
  1073. # Create some refs
  1074. test_file = os.path.join(self.repo_path, "test.txt")
  1075. with open(test_file, "w") as f:
  1076. f.write("test")
  1077. self._run_cli("add", "test.txt")
  1078. self._run_cli("commit", "--message=Initial")
  1079. self._run_cli("branch", "test-branch")
  1080. result, stdout, stderr = self._run_cli("pack-refs", "--all")
  1081. # Check that packed-refs file exists
  1082. self.assertTrue(
  1083. os.path.exists(os.path.join(self.repo_path, ".git", "packed-refs"))
  1084. )
  1085. class SubmoduleCommandTest(DulwichCliTestCase):
  1086. """Tests for submodule commands."""
  1087. def test_submodule_list(self):
  1088. # Create an initial commit so repo has a HEAD
  1089. test_file = os.path.join(self.repo_path, "test.txt")
  1090. with open(test_file, "w") as f:
  1091. f.write("test")
  1092. self._run_cli("add", "test.txt")
  1093. self._run_cli("commit", "--message=Initial")
  1094. result, stdout, stderr = self._run_cli("submodule")
  1095. # Should not crash on repo without submodules
  1096. def test_submodule_init(self):
  1097. # Create .gitmodules file for init to work
  1098. gitmodules = os.path.join(self.repo_path, ".gitmodules")
  1099. with open(gitmodules, "w") as f:
  1100. f.write("") # Empty .gitmodules file
  1101. result, stdout, stderr = self._run_cli("submodule", "init")
  1102. # Should not crash
  1103. class StashCommandTest(DulwichCliTestCase):
  1104. """Tests for stash commands."""
  1105. def test_stash_list_empty(self):
  1106. result, stdout, stderr = self._run_cli("stash", "list")
  1107. # Should not crash on empty stash
  1108. def test_stash_push_pop(self):
  1109. # Create a file and modify it
  1110. test_file = os.path.join(self.repo_path, "test.txt")
  1111. with open(test_file, "w") as f:
  1112. f.write("initial")
  1113. self._run_cli("add", "test.txt")
  1114. self._run_cli("commit", "--message=Initial")
  1115. # Modify file
  1116. with open(test_file, "w") as f:
  1117. f.write("modified")
  1118. # Stash changes
  1119. result, stdout, stderr = self._run_cli("stash", "push")
  1120. self.assertIn("Saved working directory", stdout)
  1121. # Note: Dulwich stash doesn't currently update the working tree
  1122. # so the file remains modified after stash push
  1123. # Note: stash pop is not fully implemented in Dulwich yet
  1124. # so we only test stash push here
  1125. class MergeCommandTest(DulwichCliTestCase):
  1126. """Tests for merge command."""
  1127. def test_merge_basic(self):
  1128. # Create initial commit
  1129. test_file = os.path.join(self.repo_path, "test.txt")
  1130. with open(test_file, "w") as f:
  1131. f.write("initial")
  1132. self._run_cli("add", "test.txt")
  1133. self._run_cli("commit", "--message=Initial")
  1134. # Create and checkout new branch
  1135. self._run_cli("branch", "feature")
  1136. self._run_cli("checkout", "feature")
  1137. # Make changes in feature branch
  1138. with open(test_file, "w") as f:
  1139. f.write("feature changes")
  1140. self._run_cli("add", "test.txt")
  1141. self._run_cli("commit", "--message=Feature commit")
  1142. # Go back to main
  1143. self._run_cli("checkout", "master")
  1144. # Merge feature branch
  1145. result, stdout, stderr = self._run_cli("merge", "feature")
  1146. class HelpCommandTest(DulwichCliTestCase):
  1147. """Tests for help command."""
  1148. def test_help_basic(self):
  1149. result, stdout, stderr = self._run_cli("help")
  1150. self.assertIn("dulwich command line tool", stdout)
  1151. def test_help_all(self):
  1152. result, stdout, stderr = self._run_cli("help", "-a")
  1153. self.assertIn("Available commands:", stdout)
  1154. self.assertIn("add", stdout)
  1155. self.assertIn("commit", stdout)
  1156. class RemoteCommandTest(DulwichCliTestCase):
  1157. """Tests for remote commands."""
  1158. def test_remote_add(self):
  1159. result, stdout, stderr = self._run_cli(
  1160. "remote", "add", "origin", "https://github.com/example/repo.git"
  1161. )
  1162. # Check remote was added to config
  1163. config = self.repo.get_config()
  1164. self.assertEqual(
  1165. config.get((b"remote", b"origin"), b"url"),
  1166. b"https://github.com/example/repo.git",
  1167. )
  1168. class CheckIgnoreCommandTest(DulwichCliTestCase):
  1169. """Tests for check-ignore command."""
  1170. def test_check_ignore(self):
  1171. # Create .gitignore
  1172. gitignore = os.path.join(self.repo_path, ".gitignore")
  1173. with open(gitignore, "w") as f:
  1174. f.write("*.log\n")
  1175. result, stdout, stderr = self._run_cli("check-ignore", "test.log", "test.txt")
  1176. self.assertIn("test.log", stdout)
  1177. self.assertNotIn("test.txt", stdout)
  1178. class LsFilesCommandTest(DulwichCliTestCase):
  1179. """Tests for ls-files command."""
  1180. def test_ls_files(self):
  1181. # Add some files
  1182. for name in ["a.txt", "b.txt", "c.txt"]:
  1183. path = os.path.join(self.repo_path, name)
  1184. with open(path, "w") as f:
  1185. f.write(f"content of {name}")
  1186. self._run_cli("add", "a.txt", "b.txt", "c.txt")
  1187. result, stdout, stderr = self._run_cli("ls-files")
  1188. self.assertIn("a.txt", stdout)
  1189. self.assertIn("b.txt", stdout)
  1190. self.assertIn("c.txt", stdout)
  1191. class LsTreeCommandTest(DulwichCliTestCase):
  1192. """Tests for ls-tree command."""
  1193. def test_ls_tree(self):
  1194. # Create a directory structure
  1195. os.mkdir(os.path.join(self.repo_path, "subdir"))
  1196. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  1197. f.write("file content")
  1198. with open(os.path.join(self.repo_path, "subdir", "nested.txt"), "w") as f:
  1199. f.write("nested content")
  1200. self._run_cli("add", ".")
  1201. self._run_cli("commit", "--message=Initial")
  1202. result, stdout, stderr = self._run_cli("ls-tree", "HEAD")
  1203. self.assertIn("file.txt", stdout)
  1204. self.assertIn("subdir", stdout)
  1205. def test_ls_tree_recursive(self):
  1206. # Create nested structure
  1207. os.mkdir(os.path.join(self.repo_path, "subdir"))
  1208. with open(os.path.join(self.repo_path, "subdir", "nested.txt"), "w") as f:
  1209. f.write("nested")
  1210. self._run_cli("add", ".")
  1211. self._run_cli("commit", "--message=Initial")
  1212. result, stdout, stderr = self._run_cli("ls-tree", "-r", "HEAD")
  1213. self.assertIn("subdir/nested.txt", stdout)
  1214. class DescribeCommandTest(DulwichCliTestCase):
  1215. """Tests for describe command."""
  1216. def test_describe(self):
  1217. # Create tagged commit
  1218. test_file = os.path.join(self.repo_path, "test.txt")
  1219. with open(test_file, "w") as f:
  1220. f.write("test")
  1221. self._run_cli("add", "test.txt")
  1222. self._run_cli("commit", "--message=Initial")
  1223. self._run_cli("tag", "v1.0")
  1224. result, stdout, stderr = self._run_cli("describe")
  1225. self.assertIn("v1.0", stdout)
  1226. class FsckCommandTest(DulwichCliTestCase):
  1227. """Tests for fsck command."""
  1228. def test_fsck(self):
  1229. # Create a commit
  1230. test_file = os.path.join(self.repo_path, "test.txt")
  1231. with open(test_file, "w") as f:
  1232. f.write("test")
  1233. self._run_cli("add", "test.txt")
  1234. self._run_cli("commit", "--message=Initial")
  1235. result, stdout, stderr = self._run_cli("fsck")
  1236. # Should complete without errors
  1237. class RepackCommandTest(DulwichCliTestCase):
  1238. """Tests for repack command."""
  1239. def test_repack(self):
  1240. # Create some objects
  1241. for i in range(5):
  1242. test_file = os.path.join(self.repo_path, f"test{i}.txt")
  1243. with open(test_file, "w") as f:
  1244. f.write(f"content {i}")
  1245. self._run_cli("add", f"test{i}.txt")
  1246. self._run_cli("commit", f"--message=Commit {i}")
  1247. result, stdout, stderr = self._run_cli("repack")
  1248. # Should create pack files
  1249. pack_dir = os.path.join(self.repo_path, ".git", "objects", "pack")
  1250. self.assertTrue(any(f.endswith(".pack") for f in os.listdir(pack_dir)))
  1251. class ResetCommandTest(DulwichCliTestCase):
  1252. """Tests for reset command."""
  1253. def test_reset_soft(self):
  1254. # Create commits
  1255. test_file = os.path.join(self.repo_path, "test.txt")
  1256. with open(test_file, "w") as f:
  1257. f.write("first")
  1258. self._run_cli("add", "test.txt")
  1259. self._run_cli("commit", "--message=First")
  1260. first_commit = self.repo.head()
  1261. with open(test_file, "w") as f:
  1262. f.write("second")
  1263. self._run_cli("add", "test.txt")
  1264. self._run_cli("commit", "--message=Second")
  1265. # Reset soft
  1266. result, stdout, stderr = self._run_cli("reset", "--soft", first_commit.decode())
  1267. # HEAD should be at first commit
  1268. self.assertEqual(self.repo.head(), first_commit)
  1269. class WriteTreeCommandTest(DulwichCliTestCase):
  1270. """Tests for write-tree command."""
  1271. def test_write_tree(self):
  1272. # Create and add files
  1273. test_file = os.path.join(self.repo_path, "test.txt")
  1274. with open(test_file, "w") as f:
  1275. f.write("test")
  1276. self._run_cli("add", "test.txt")
  1277. result, stdout, stderr = self._run_cli("write-tree")
  1278. # Should output tree SHA
  1279. self.assertEqual(len(stdout.strip()), 40)
  1280. class UpdateServerInfoCommandTest(DulwichCliTestCase):
  1281. """Tests for update-server-info command."""
  1282. def test_update_server_info(self):
  1283. result, stdout, stderr = self._run_cli("update-server-info")
  1284. # Should create info/refs file
  1285. info_refs = os.path.join(self.repo_path, ".git", "info", "refs")
  1286. self.assertTrue(os.path.exists(info_refs))
  1287. class SymbolicRefCommandTest(DulwichCliTestCase):
  1288. """Tests for symbolic-ref command."""
  1289. def test_symbolic_ref(self):
  1290. # Create a branch
  1291. test_file = os.path.join(self.repo_path, "test.txt")
  1292. with open(test_file, "w") as f:
  1293. f.write("test")
  1294. self._run_cli("add", "test.txt")
  1295. self._run_cli("commit", "--message=Initial")
  1296. self._run_cli("branch", "test-branch")
  1297. result, stdout, stderr = self._run_cli(
  1298. "symbolic-ref", "HEAD", "refs/heads/test-branch"
  1299. )
  1300. # HEAD should now point to test-branch
  1301. self.assertEqual(
  1302. self.repo.refs.read_ref(b"HEAD"), b"ref: refs/heads/test-branch"
  1303. )
  1304. class BundleCommandTest(DulwichCliTestCase):
  1305. """Tests for bundle commands."""
  1306. def setUp(self):
  1307. super().setUp()
  1308. # Create a basic repository with some commits for bundle testing
  1309. # Create initial commit
  1310. test_file = os.path.join(self.repo_path, "file1.txt")
  1311. with open(test_file, "w") as f:
  1312. f.write("Content of file1\n")
  1313. self._run_cli("add", "file1.txt")
  1314. self._run_cli("commit", "--message=Initial commit")
  1315. # Create second commit
  1316. test_file2 = os.path.join(self.repo_path, "file2.txt")
  1317. with open(test_file2, "w") as f:
  1318. f.write("Content of file2\n")
  1319. self._run_cli("add", "file2.txt")
  1320. self._run_cli("commit", "--message=Add file2")
  1321. # Create a branch and tag for testing
  1322. self._run_cli("branch", "feature")
  1323. self._run_cli("tag", "v1.0")
  1324. def test_bundle_create_basic(self):
  1325. """Test basic bundle creation."""
  1326. bundle_file = os.path.join(self.test_dir, "test.bundle")
  1327. result, stdout, stderr = self._run_cli("bundle", "create", bundle_file, "HEAD")
  1328. self.assertEqual(result, 0)
  1329. self.assertTrue(os.path.exists(bundle_file))
  1330. self.assertGreater(os.path.getsize(bundle_file), 0)
  1331. def test_bundle_create_all_refs(self):
  1332. """Test bundle creation with --all flag."""
  1333. bundle_file = os.path.join(self.test_dir, "all.bundle")
  1334. result, stdout, stderr = self._run_cli("bundle", "create", "--all", bundle_file)
  1335. self.assertEqual(result, 0)
  1336. self.assertTrue(os.path.exists(bundle_file))
  1337. def test_bundle_create_specific_refs(self):
  1338. """Test bundle creation with specific refs."""
  1339. bundle_file = os.path.join(self.test_dir, "refs.bundle")
  1340. # Only use HEAD since feature branch may not exist
  1341. result, stdout, stderr = self._run_cli("bundle", "create", bundle_file, "HEAD")
  1342. self.assertEqual(result, 0)
  1343. self.assertTrue(os.path.exists(bundle_file))
  1344. def test_bundle_create_with_range(self):
  1345. """Test bundle creation with commit range."""
  1346. # Get the first commit SHA by looking at the log
  1347. result, stdout, stderr = self._run_cli("log", "--reverse")
  1348. lines = stdout.strip().split("\n")
  1349. # Find first commit line that contains a SHA
  1350. first_commit = None
  1351. for line in lines:
  1352. if line.startswith("commit "):
  1353. first_commit = line.split()[1][:8] # Get short SHA
  1354. break
  1355. if first_commit:
  1356. bundle_file = os.path.join(self.test_dir, "range.bundle")
  1357. result, stdout, stderr = self._run_cli(
  1358. "bundle", "create", bundle_file, f"{first_commit}..HEAD"
  1359. )
  1360. self.assertEqual(result, 0)
  1361. self.assertTrue(os.path.exists(bundle_file))
  1362. else:
  1363. self.skipTest("Could not determine first commit SHA")
  1364. def test_bundle_create_to_stdout(self):
  1365. """Test bundle creation to stdout."""
  1366. result, stdout, stderr = self._run_cli("bundle", "create", "-", "HEAD")
  1367. self.assertEqual(result, 0)
  1368. self.assertGreater(len(stdout), 0)
  1369. # Bundle output is binary, so check it's not empty
  1370. self.assertIsInstance(stdout, (str, bytes))
  1371. def test_bundle_create_no_refs(self):
  1372. """Test bundle creation with no refs specified."""
  1373. bundle_file = os.path.join(self.test_dir, "noref.bundle")
  1374. result, stdout, stderr = self._run_cli("bundle", "create", bundle_file)
  1375. self.assertEqual(result, 1)
  1376. self.assertIn("No refs specified", stdout)
  1377. def test_bundle_create_empty_bundle_refused(self):
  1378. """Test that empty bundles are refused."""
  1379. bundle_file = os.path.join(self.test_dir, "empty.bundle")
  1380. # Try to create bundle with non-existent ref - this should fail with KeyError
  1381. with self.assertRaises(KeyError):
  1382. result, stdout, stderr = self._run_cli(
  1383. "bundle", "create", bundle_file, "nonexistent-ref"
  1384. )
  1385. def test_bundle_verify_valid(self):
  1386. """Test bundle verification of valid bundle."""
  1387. bundle_file = os.path.join(self.test_dir, "valid.bundle")
  1388. # First create a bundle
  1389. result, stdout, stderr = self._run_cli("bundle", "create", bundle_file, "HEAD")
  1390. self.assertEqual(result, 0)
  1391. # Now verify it
  1392. result, stdout, stderr = self._run_cli("bundle", "verify", bundle_file)
  1393. self.assertEqual(result, 0)
  1394. self.assertIn("valid and can be applied", stdout)
  1395. def test_bundle_verify_quiet(self):
  1396. """Test bundle verification with quiet flag."""
  1397. bundle_file = os.path.join(self.test_dir, "quiet.bundle")
  1398. # Create bundle
  1399. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1400. # Verify quietly
  1401. result, stdout, stderr = self._run_cli(
  1402. "bundle", "verify", "--quiet", bundle_file
  1403. )
  1404. self.assertEqual(result, 0)
  1405. self.assertEqual(stdout.strip(), "")
  1406. def test_bundle_verify_from_stdin(self):
  1407. """Test bundle verification from stdin."""
  1408. bundle_file = os.path.join(self.test_dir, "stdin.bundle")
  1409. # Create bundle
  1410. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1411. # Read bundle content
  1412. with open(bundle_file, "rb") as f:
  1413. bundle_content = f.read()
  1414. # Mock stdin with bundle content
  1415. old_stdin = sys.stdin
  1416. try:
  1417. sys.stdin = io.BytesIO(bundle_content)
  1418. sys.stdin.buffer = sys.stdin
  1419. result, stdout, stderr = self._run_cli("bundle", "verify", "-")
  1420. self.assertEqual(result, 0)
  1421. finally:
  1422. sys.stdin = old_stdin
  1423. def test_bundle_list_heads(self):
  1424. """Test listing bundle heads."""
  1425. bundle_file = os.path.join(self.test_dir, "heads.bundle")
  1426. # Create bundle with HEAD only
  1427. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1428. # List heads
  1429. result, stdout, stderr = self._run_cli("bundle", "list-heads", bundle_file)
  1430. self.assertEqual(result, 0)
  1431. # Should contain at least the HEAD reference
  1432. self.assertTrue(len(stdout.strip()) > 0)
  1433. def test_bundle_list_heads_specific_refs(self):
  1434. """Test listing specific bundle heads."""
  1435. bundle_file = os.path.join(self.test_dir, "specific.bundle")
  1436. # Create bundle with HEAD
  1437. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1438. # List heads without filtering
  1439. result, stdout, stderr = self._run_cli("bundle", "list-heads", bundle_file)
  1440. self.assertEqual(result, 0)
  1441. # Should contain some reference
  1442. self.assertTrue(len(stdout.strip()) > 0)
  1443. def test_bundle_list_heads_from_stdin(self):
  1444. """Test listing bundle heads from stdin."""
  1445. bundle_file = os.path.join(self.test_dir, "stdin-heads.bundle")
  1446. # Create bundle
  1447. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1448. # Read bundle content
  1449. with open(bundle_file, "rb") as f:
  1450. bundle_content = f.read()
  1451. # Mock stdin
  1452. old_stdin = sys.stdin
  1453. try:
  1454. sys.stdin = io.BytesIO(bundle_content)
  1455. sys.stdin.buffer = sys.stdin
  1456. result, stdout, stderr = self._run_cli("bundle", "list-heads", "-")
  1457. self.assertEqual(result, 0)
  1458. finally:
  1459. sys.stdin = old_stdin
  1460. def test_bundle_unbundle(self):
  1461. """Test bundle unbundling."""
  1462. bundle_file = os.path.join(self.test_dir, "unbundle.bundle")
  1463. # Create bundle
  1464. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1465. # Unbundle
  1466. result, stdout, stderr = self._run_cli("bundle", "unbundle", bundle_file)
  1467. self.assertEqual(result, 0)
  1468. def test_bundle_unbundle_specific_refs(self):
  1469. """Test unbundling specific refs."""
  1470. bundle_file = os.path.join(self.test_dir, "unbundle-specific.bundle")
  1471. # Create bundle with HEAD
  1472. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1473. # Unbundle only HEAD
  1474. result, stdout, stderr = self._run_cli(
  1475. "bundle", "unbundle", bundle_file, "HEAD"
  1476. )
  1477. self.assertEqual(result, 0)
  1478. def test_bundle_unbundle_from_stdin(self):
  1479. """Test unbundling from stdin."""
  1480. bundle_file = os.path.join(self.test_dir, "stdin-unbundle.bundle")
  1481. # Create bundle
  1482. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1483. # Read bundle content to simulate stdin
  1484. with open(bundle_file, "rb") as f:
  1485. bundle_content = f.read()
  1486. # Mock stdin with bundle content
  1487. old_stdin = sys.stdin
  1488. try:
  1489. # Create a BytesIO object with buffer attribute
  1490. mock_stdin = io.BytesIO(bundle_content)
  1491. mock_stdin.buffer = mock_stdin
  1492. sys.stdin = mock_stdin
  1493. result, stdout, stderr = self._run_cli("bundle", "unbundle", "-")
  1494. self.assertEqual(result, 0)
  1495. finally:
  1496. sys.stdin = old_stdin
  1497. def test_bundle_unbundle_with_progress(self):
  1498. """Test unbundling with progress output."""
  1499. bundle_file = os.path.join(self.test_dir, "progress.bundle")
  1500. # Create bundle
  1501. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1502. # Unbundle with progress
  1503. result, stdout, stderr = self._run_cli(
  1504. "bundle", "unbundle", "--progress", bundle_file
  1505. )
  1506. self.assertEqual(result, 0)
  1507. def test_bundle_create_with_progress(self):
  1508. """Test bundle creation with progress output."""
  1509. bundle_file = os.path.join(self.test_dir, "create-progress.bundle")
  1510. result, stdout, stderr = self._run_cli(
  1511. "bundle", "create", "--progress", bundle_file, "HEAD"
  1512. )
  1513. self.assertEqual(result, 0)
  1514. self.assertTrue(os.path.exists(bundle_file))
  1515. def test_bundle_create_with_quiet(self):
  1516. """Test bundle creation with quiet flag."""
  1517. bundle_file = os.path.join(self.test_dir, "quiet-create.bundle")
  1518. result, stdout, stderr = self._run_cli(
  1519. "bundle", "create", "--quiet", bundle_file, "HEAD"
  1520. )
  1521. self.assertEqual(result, 0)
  1522. self.assertTrue(os.path.exists(bundle_file))
  1523. def test_bundle_create_version_2(self):
  1524. """Test bundle creation with specific version."""
  1525. bundle_file = os.path.join(self.test_dir, "v2.bundle")
  1526. result, stdout, stderr = self._run_cli(
  1527. "bundle", "create", "--version", "2", bundle_file, "HEAD"
  1528. )
  1529. self.assertEqual(result, 0)
  1530. self.assertTrue(os.path.exists(bundle_file))
  1531. def test_bundle_create_version_3(self):
  1532. """Test bundle creation with version 3."""
  1533. bundle_file = os.path.join(self.test_dir, "v3.bundle")
  1534. result, stdout, stderr = self._run_cli(
  1535. "bundle", "create", "--version", "3", bundle_file, "HEAD"
  1536. )
  1537. self.assertEqual(result, 0)
  1538. self.assertTrue(os.path.exists(bundle_file))
  1539. def test_bundle_invalid_subcommand(self):
  1540. """Test invalid bundle subcommand."""
  1541. result, stdout, stderr = self._run_cli("bundle", "invalid-command")
  1542. self.assertEqual(result, 1)
  1543. self.assertIn("Unknown bundle subcommand", stdout)
  1544. def test_bundle_no_subcommand(self):
  1545. """Test bundle command with no subcommand."""
  1546. result, stdout, stderr = self._run_cli("bundle")
  1547. self.assertEqual(result, 1)
  1548. self.assertIn("Usage: bundle", stdout)
  1549. def test_bundle_create_with_stdin_refs(self):
  1550. """Test bundle creation reading refs from stdin."""
  1551. bundle_file = os.path.join(self.test_dir, "stdin-refs.bundle")
  1552. # Mock stdin with refs
  1553. old_stdin = sys.stdin
  1554. try:
  1555. sys.stdin = io.StringIO("master\nfeature\n")
  1556. result, stdout, stderr = self._run_cli(
  1557. "bundle", "create", "--stdin", bundle_file
  1558. )
  1559. self.assertEqual(result, 0)
  1560. self.assertTrue(os.path.exists(bundle_file))
  1561. finally:
  1562. sys.stdin = old_stdin
  1563. def test_bundle_verify_missing_prerequisites(self):
  1564. """Test bundle verification with missing prerequisites."""
  1565. # Create a simple bundle first
  1566. bundle_file = os.path.join(self.test_dir, "prereq.bundle")
  1567. self._run_cli("bundle", "create", bundle_file, "HEAD")
  1568. # Create a new repo to simulate missing objects
  1569. new_repo_path = os.path.join(self.test_dir, "new_repo")
  1570. os.mkdir(new_repo_path)
  1571. new_repo = Repo.init(new_repo_path)
  1572. new_repo.close()
  1573. # Try to verify in new repo
  1574. old_cwd = os.getcwd()
  1575. try:
  1576. os.chdir(new_repo_path)
  1577. result, stdout, stderr = self._run_cli("bundle", "verify", bundle_file)
  1578. # Just check that verification runs - result depends on bundle content
  1579. self.assertIn(result, [0, 1])
  1580. finally:
  1581. os.chdir(old_cwd)
  1582. def test_bundle_create_with_committish_range(self):
  1583. """Test bundle creation with commit range using parse_committish_range."""
  1584. # Create additional commits for range testing
  1585. test_file3 = os.path.join(self.repo_path, "file3.txt")
  1586. with open(test_file3, "w") as f:
  1587. f.write("Content of file3\n")
  1588. self._run_cli("add", "file3.txt")
  1589. self._run_cli("commit", "--message=Add file3")
  1590. # Get commit SHAs
  1591. result, stdout, stderr = self._run_cli("log")
  1592. lines = stdout.strip().split("\n")
  1593. # Extract SHAs from commit lines
  1594. commits = []
  1595. for line in lines:
  1596. if line.startswith("commit:"):
  1597. sha = line.split()[1]
  1598. commits.append(sha[:8]) # Get short SHA
  1599. # We should have exactly 3 commits: Add file3, Add file2, Initial commit
  1600. self.assertEqual(len(commits), 3)
  1601. bundle_file = os.path.join(self.test_dir, "range-test.bundle")
  1602. # Test with commit range using .. syntax
  1603. # Create a bundle containing commits reachable from commits[0] but not from commits[2]
  1604. result, stdout, stderr = self._run_cli(
  1605. "bundle", "create", bundle_file, f"{commits[2]}..HEAD"
  1606. )
  1607. if result != 0:
  1608. self.fail(
  1609. f"Bundle create failed with exit code {result}. stdout: {stdout!r}, stderr: {stderr!r}"
  1610. )
  1611. self.assertEqual(result, 0)
  1612. self.assertTrue(os.path.exists(bundle_file))
  1613. # Verify the bundle was created
  1614. result, stdout, stderr = self._run_cli("bundle", "verify", bundle_file)
  1615. self.assertEqual(result, 0)
  1616. self.assertIn("valid and can be applied", stdout)
  1617. class FormatBytesTestCase(TestCase):
  1618. """Tests for format_bytes function."""
  1619. def test_bytes(self):
  1620. """Test formatting bytes."""
  1621. self.assertEqual("0.0 B", format_bytes(0))
  1622. self.assertEqual("1.0 B", format_bytes(1))
  1623. self.assertEqual("512.0 B", format_bytes(512))
  1624. self.assertEqual("1023.0 B", format_bytes(1023))
  1625. def test_kilobytes(self):
  1626. """Test formatting kilobytes."""
  1627. self.assertEqual("1.0 KB", format_bytes(1024))
  1628. self.assertEqual("1.5 KB", format_bytes(1536))
  1629. self.assertEqual("2.0 KB", format_bytes(2048))
  1630. self.assertEqual("1023.0 KB", format_bytes(1024 * 1023))
  1631. def test_megabytes(self):
  1632. """Test formatting megabytes."""
  1633. self.assertEqual("1.0 MB", format_bytes(1024 * 1024))
  1634. self.assertEqual("1.5 MB", format_bytes(1024 * 1024 * 1.5))
  1635. self.assertEqual("10.0 MB", format_bytes(1024 * 1024 * 10))
  1636. self.assertEqual("1023.0 MB", format_bytes(1024 * 1024 * 1023))
  1637. def test_gigabytes(self):
  1638. """Test formatting gigabytes."""
  1639. self.assertEqual("1.0 GB", format_bytes(1024 * 1024 * 1024))
  1640. self.assertEqual("2.5 GB", format_bytes(1024 * 1024 * 1024 * 2.5))
  1641. self.assertEqual("1023.0 GB", format_bytes(1024 * 1024 * 1024 * 1023))
  1642. def test_terabytes(self):
  1643. """Test formatting terabytes."""
  1644. self.assertEqual("1.0 TB", format_bytes(1024 * 1024 * 1024 * 1024))
  1645. self.assertEqual("5.0 TB", format_bytes(1024 * 1024 * 1024 * 1024 * 5))
  1646. self.assertEqual("1000.0 TB", format_bytes(1024 * 1024 * 1024 * 1024 * 1000))
  1647. class ParseRelativeTimeTestCase(TestCase):
  1648. """Tests for parse_relative_time function."""
  1649. def test_now(self):
  1650. """Test parsing 'now'."""
  1651. self.assertEqual(0, parse_relative_time("now"))
  1652. def test_seconds(self):
  1653. """Test parsing seconds."""
  1654. self.assertEqual(1, parse_relative_time("1 second ago"))
  1655. self.assertEqual(5, parse_relative_time("5 seconds ago"))
  1656. self.assertEqual(30, parse_relative_time("30 seconds ago"))
  1657. def test_minutes(self):
  1658. """Test parsing minutes."""
  1659. self.assertEqual(60, parse_relative_time("1 minute ago"))
  1660. self.assertEqual(300, parse_relative_time("5 minutes ago"))
  1661. self.assertEqual(1800, parse_relative_time("30 minutes ago"))
  1662. def test_hours(self):
  1663. """Test parsing hours."""
  1664. self.assertEqual(3600, parse_relative_time("1 hour ago"))
  1665. self.assertEqual(7200, parse_relative_time("2 hours ago"))
  1666. self.assertEqual(86400, parse_relative_time("24 hours ago"))
  1667. def test_days(self):
  1668. """Test parsing days."""
  1669. self.assertEqual(86400, parse_relative_time("1 day ago"))
  1670. self.assertEqual(604800, parse_relative_time("7 days ago"))
  1671. self.assertEqual(2592000, parse_relative_time("30 days ago"))
  1672. def test_weeks(self):
  1673. """Test parsing weeks."""
  1674. self.assertEqual(604800, parse_relative_time("1 week ago"))
  1675. self.assertEqual(1209600, parse_relative_time("2 weeks ago"))
  1676. self.assertEqual(
  1677. 36288000, parse_relative_time("60 weeks ago")
  1678. ) # 60 * 7 * 24 * 60 * 60
  1679. def test_invalid_format(self):
  1680. """Test invalid time formats."""
  1681. with self.assertRaises(ValueError) as cm:
  1682. parse_relative_time("invalid")
  1683. self.assertIn("Invalid relative time format", str(cm.exception))
  1684. with self.assertRaises(ValueError) as cm:
  1685. parse_relative_time("2 weeks")
  1686. self.assertIn("Invalid relative time format", str(cm.exception))
  1687. with self.assertRaises(ValueError) as cm:
  1688. parse_relative_time("ago")
  1689. self.assertIn("Invalid relative time format", str(cm.exception))
  1690. with self.assertRaises(ValueError) as cm:
  1691. parse_relative_time("two weeks ago")
  1692. self.assertIn("Invalid number in relative time", str(cm.exception))
  1693. def test_invalid_unit(self):
  1694. """Test invalid time units."""
  1695. with self.assertRaises(ValueError) as cm:
  1696. parse_relative_time("5 months ago")
  1697. self.assertIn("Unknown time unit: months", str(cm.exception))
  1698. with self.assertRaises(ValueError) as cm:
  1699. parse_relative_time("2 years ago")
  1700. self.assertIn("Unknown time unit: years", str(cm.exception))
  1701. def test_singular_plural(self):
  1702. """Test that both singular and plural forms work."""
  1703. self.assertEqual(
  1704. parse_relative_time("1 second ago"), parse_relative_time("1 seconds ago")
  1705. )
  1706. self.assertEqual(
  1707. parse_relative_time("1 minute ago"), parse_relative_time("1 minutes ago")
  1708. )
  1709. self.assertEqual(
  1710. parse_relative_time("1 hour ago"), parse_relative_time("1 hours ago")
  1711. )
  1712. self.assertEqual(
  1713. parse_relative_time("1 day ago"), parse_relative_time("1 days ago")
  1714. )
  1715. self.assertEqual(
  1716. parse_relative_time("1 week ago"), parse_relative_time("1 weeks ago")
  1717. )
  1718. class GetPagerTest(TestCase):
  1719. """Tests for get_pager function."""
  1720. def setUp(self):
  1721. super().setUp()
  1722. # Save original environment
  1723. self.original_env = os.environ.copy()
  1724. # Clear pager-related environment variables
  1725. for var in ["DULWICH_PAGER", "GIT_PAGER", "PAGER"]:
  1726. os.environ.pop(var, None)
  1727. # Reset the global pager disable flag
  1728. cli.get_pager._disabled = False
  1729. def tearDown(self):
  1730. super().tearDown()
  1731. # Restore original environment
  1732. os.environ.clear()
  1733. os.environ.update(self.original_env)
  1734. # Reset the global pager disable flag
  1735. cli.get_pager._disabled = False
  1736. def test_pager_disabled_globally(self):
  1737. """Test that globally disabled pager returns stdout wrapper."""
  1738. cli.disable_pager()
  1739. pager = cli.get_pager()
  1740. self.assertIsInstance(pager, cli._StreamContextAdapter)
  1741. self.assertEqual(pager.stream, sys.stdout)
  1742. def test_pager_not_tty(self):
  1743. """Test that pager is disabled when stdout is not a TTY."""
  1744. with patch("sys.stdout.isatty", return_value=False):
  1745. pager = cli.get_pager()
  1746. self.assertIsInstance(pager, cli._StreamContextAdapter)
  1747. def test_pager_env_dulwich_pager(self):
  1748. """Test DULWICH_PAGER environment variable."""
  1749. os.environ["DULWICH_PAGER"] = "custom_pager"
  1750. with patch("sys.stdout.isatty", return_value=True):
  1751. pager = cli.get_pager()
  1752. self.assertIsInstance(pager, cli.Pager)
  1753. self.assertEqual(pager.pager_cmd, "custom_pager")
  1754. def test_pager_env_dulwich_pager_false(self):
  1755. """Test DULWICH_PAGER=false disables pager."""
  1756. os.environ["DULWICH_PAGER"] = "false"
  1757. with patch("sys.stdout.isatty", return_value=True):
  1758. pager = cli.get_pager()
  1759. self.assertIsInstance(pager, cli._StreamContextAdapter)
  1760. def test_pager_env_git_pager(self):
  1761. """Test GIT_PAGER environment variable."""
  1762. os.environ["GIT_PAGER"] = "git_custom_pager"
  1763. with patch("sys.stdout.isatty", return_value=True):
  1764. pager = cli.get_pager()
  1765. self.assertIsInstance(pager, cli.Pager)
  1766. self.assertEqual(pager.pager_cmd, "git_custom_pager")
  1767. def test_pager_env_pager(self):
  1768. """Test PAGER environment variable."""
  1769. os.environ["PAGER"] = "my_pager"
  1770. with patch("sys.stdout.isatty", return_value=True):
  1771. pager = cli.get_pager()
  1772. self.assertIsInstance(pager, cli.Pager)
  1773. self.assertEqual(pager.pager_cmd, "my_pager")
  1774. def test_pager_env_priority(self):
  1775. """Test environment variable priority order."""
  1776. os.environ["PAGER"] = "pager_low"
  1777. os.environ["GIT_PAGER"] = "pager_medium"
  1778. os.environ["DULWICH_PAGER"] = "pager_high"
  1779. with patch("sys.stdout.isatty", return_value=True):
  1780. pager = cli.get_pager()
  1781. self.assertEqual(pager.pager_cmd, "pager_high")
  1782. def test_pager_config_core_pager(self):
  1783. """Test core.pager configuration."""
  1784. config = MagicMock()
  1785. config.get.return_value = b"config_pager"
  1786. with patch("sys.stdout.isatty", return_value=True):
  1787. pager = cli.get_pager(config=config)
  1788. self.assertIsInstance(pager, cli.Pager)
  1789. self.assertEqual(pager.pager_cmd, "config_pager")
  1790. config.get.assert_called_with(("core",), b"pager")
  1791. def test_pager_config_core_pager_false(self):
  1792. """Test core.pager=false disables pager."""
  1793. config = MagicMock()
  1794. config.get.return_value = b"false"
  1795. with patch("sys.stdout.isatty", return_value=True):
  1796. pager = cli.get_pager(config=config)
  1797. self.assertIsInstance(pager, cli._StreamContextAdapter)
  1798. def test_pager_config_core_pager_empty(self):
  1799. """Test core.pager="" disables pager."""
  1800. config = MagicMock()
  1801. config.get.return_value = b""
  1802. with patch("sys.stdout.isatty", return_value=True):
  1803. pager = cli.get_pager(config=config)
  1804. self.assertIsInstance(pager, cli._StreamContextAdapter)
  1805. def test_pager_config_per_command(self):
  1806. """Test per-command pager configuration."""
  1807. config = MagicMock()
  1808. config.get.side_effect = lambda section, key: {
  1809. (("pager",), b"log"): b"log_pager",
  1810. }.get((section, key), KeyError())
  1811. with patch("sys.stdout.isatty", return_value=True):
  1812. pager = cli.get_pager(config=config, cmd_name="log")
  1813. self.assertIsInstance(pager, cli.Pager)
  1814. self.assertEqual(pager.pager_cmd, "log_pager")
  1815. def test_pager_config_per_command_false(self):
  1816. """Test per-command pager=false disables pager."""
  1817. config = MagicMock()
  1818. config.get.return_value = b"false"
  1819. with patch("sys.stdout.isatty", return_value=True):
  1820. pager = cli.get_pager(config=config, cmd_name="log")
  1821. self.assertIsInstance(pager, cli._StreamContextAdapter)
  1822. def test_pager_config_per_command_true(self):
  1823. """Test per-command pager=true uses default pager."""
  1824. config = MagicMock()
  1825. def get_side_effect(section, key):
  1826. if section == ("pager",) and key == b"log":
  1827. return b"true"
  1828. raise KeyError
  1829. config.get.side_effect = get_side_effect
  1830. with patch("sys.stdout.isatty", return_value=True):
  1831. with patch("shutil.which", side_effect=lambda cmd: cmd == "less"):
  1832. pager = cli.get_pager(config=config, cmd_name="log")
  1833. self.assertIsInstance(pager, cli.Pager)
  1834. self.assertEqual(pager.pager_cmd, "less -FRX")
  1835. def test_pager_priority_order(self):
  1836. """Test complete priority order."""
  1837. # Set up all possible configurations
  1838. os.environ["PAGER"] = "env_pager"
  1839. os.environ["GIT_PAGER"] = "env_git_pager"
  1840. config = MagicMock()
  1841. def get_side_effect(section, key):
  1842. if section == ("pager",) and key == b"log":
  1843. return b"cmd_pager"
  1844. elif section == ("core",) and key == b"pager":
  1845. return b"core_pager"
  1846. raise KeyError
  1847. config.get.side_effect = get_side_effect
  1848. with patch("sys.stdout.isatty", return_value=True):
  1849. # Per-command config should win
  1850. pager = cli.get_pager(config=config, cmd_name="log")
  1851. self.assertEqual(pager.pager_cmd, "cmd_pager")
  1852. def test_pager_fallback_less(self):
  1853. """Test fallback to less with proper flags."""
  1854. with patch("sys.stdout.isatty", return_value=True):
  1855. with patch("shutil.which", side_effect=lambda cmd: cmd == "less"):
  1856. pager = cli.get_pager()
  1857. self.assertIsInstance(pager, cli.Pager)
  1858. self.assertEqual(pager.pager_cmd, "less -FRX")
  1859. def test_pager_fallback_more(self):
  1860. """Test fallback to more when less is not available."""
  1861. with patch("sys.stdout.isatty", return_value=True):
  1862. with patch("shutil.which", side_effect=lambda cmd: cmd == "more"):
  1863. pager = cli.get_pager()
  1864. self.assertIsInstance(pager, cli.Pager)
  1865. self.assertEqual(pager.pager_cmd, "more")
  1866. def test_pager_fallback_cat(self):
  1867. """Test ultimate fallback to cat."""
  1868. with patch("sys.stdout.isatty", return_value=True):
  1869. with patch("shutil.which", return_value=None):
  1870. pager = cli.get_pager()
  1871. self.assertIsInstance(pager, cli.Pager)
  1872. self.assertEqual(pager.pager_cmd, "cat")
  1873. def test_pager_context_manager(self):
  1874. """Test that pager works as a context manager."""
  1875. with patch("sys.stdout.isatty", return_value=True):
  1876. with cli.get_pager() as pager:
  1877. self.assertTrue(hasattr(pager, "write"))
  1878. self.assertTrue(hasattr(pager, "flush"))
  1879. class WorktreeCliTests(DulwichCliTestCase):
  1880. """Tests for worktree CLI commands."""
  1881. def setUp(self):
  1882. super().setUp()
  1883. # Base class already creates and initializes the repo
  1884. # Just create initial commit
  1885. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  1886. f.write("test content")
  1887. from dulwich import porcelain
  1888. porcelain.add(self.repo_path, ["test.txt"])
  1889. porcelain.commit(self.repo_path, message=b"Initial commit")
  1890. def test_worktree_list(self):
  1891. """Test worktree list command."""
  1892. io.StringIO()
  1893. cmd = cli.cmd_worktree()
  1894. result = cmd.run(["list"])
  1895. # Should list the main worktree
  1896. self.assertEqual(result, 0)
  1897. def test_worktree_add(self):
  1898. """Test worktree add command."""
  1899. wt_path = os.path.join(self.test_dir, "worktree1")
  1900. # Change to repo directory like real usage
  1901. old_cwd = os.getcwd()
  1902. os.chdir(self.repo_path)
  1903. try:
  1904. cmd = cli.cmd_worktree()
  1905. with patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
  1906. result = cmd.run(["add", wt_path, "feature"])
  1907. self.assertEqual(result, 0)
  1908. self.assertTrue(os.path.exists(wt_path))
  1909. self.assertIn("Worktree added:", mock_stdout.getvalue())
  1910. finally:
  1911. os.chdir(old_cwd)
  1912. def test_worktree_add_detached(self):
  1913. """Test worktree add with detached HEAD."""
  1914. wt_path = os.path.join(self.test_dir, "detached-wt")
  1915. cmd = cli.cmd_worktree()
  1916. with patch("sys.stdout", new_callable=io.StringIO):
  1917. result = cmd.run(["add", "--detach", wt_path])
  1918. self.assertEqual(result, 0)
  1919. self.assertTrue(os.path.exists(wt_path))
  1920. def test_worktree_remove(self):
  1921. """Test worktree remove command."""
  1922. # First add a worktree
  1923. wt_path = os.path.join(self.test_dir, "to-remove")
  1924. cmd = cli.cmd_worktree()
  1925. cmd.run(["add", wt_path])
  1926. # Then remove it
  1927. with patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
  1928. result = cmd.run(["remove", wt_path])
  1929. self.assertEqual(result, 0)
  1930. self.assertFalse(os.path.exists(wt_path))
  1931. self.assertIn("Worktree removed:", mock_stdout.getvalue())
  1932. def test_worktree_prune(self):
  1933. """Test worktree prune command."""
  1934. # Add a worktree and manually remove it
  1935. wt_path = os.path.join(self.test_dir, "to-prune")
  1936. cmd = cli.cmd_worktree()
  1937. cmd.run(["add", wt_path])
  1938. shutil.rmtree(wt_path)
  1939. # Prune
  1940. with patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
  1941. result = cmd.run(["prune", "-v"])
  1942. self.assertEqual(result, 0)
  1943. output = mock_stdout.getvalue()
  1944. self.assertIn("to-prune", output)
  1945. def test_worktree_lock_unlock(self):
  1946. """Test worktree lock and unlock commands."""
  1947. # Add a worktree
  1948. wt_path = os.path.join(self.test_dir, "lockable")
  1949. cmd = cli.cmd_worktree()
  1950. cmd.run(["add", wt_path])
  1951. # Lock it
  1952. with patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
  1953. result = cmd.run(["lock", wt_path, "--reason", "Testing"])
  1954. self.assertEqual(result, 0)
  1955. self.assertIn("Worktree locked:", mock_stdout.getvalue())
  1956. # Unlock it
  1957. with patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
  1958. result = cmd.run(["unlock", wt_path])
  1959. self.assertEqual(result, 0)
  1960. self.assertIn("Worktree unlocked:", mock_stdout.getvalue())
  1961. def test_worktree_move(self):
  1962. """Test worktree move command."""
  1963. # Add a worktree
  1964. old_path = os.path.join(self.test_dir, "old-location")
  1965. new_path = os.path.join(self.test_dir, "new-location")
  1966. cmd = cli.cmd_worktree()
  1967. cmd.run(["add", old_path])
  1968. # Move it
  1969. with patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
  1970. result = cmd.run(["move", old_path, new_path])
  1971. self.assertEqual(result, 0)
  1972. self.assertFalse(os.path.exists(old_path))
  1973. self.assertTrue(os.path.exists(new_path))
  1974. self.assertIn("Worktree moved:", mock_stdout.getvalue())
  1975. def test_worktree_invalid_command(self):
  1976. """Test invalid worktree subcommand."""
  1977. cmd = cli.cmd_worktree()
  1978. with patch("sys.stderr", new_callable=io.StringIO):
  1979. with self.assertRaises(SystemExit):
  1980. cmd.run(["invalid"])
  1981. if __name__ == "__main__":
  1982. unittest.main()