2
0

test_cli.py 94 KB

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