test_cli.py 107 KB

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