test_cli.py 101 KB

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