test_cli.py 106 KB

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