2
0

test_cli.py 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795
  1. #!/usr/bin/env python
  2. # test_cli.py -- tests for dulwich.cli
  3. # vim: expandtab
  4. #
  5. # Copyright (C) 2024 Jelmer Vernooij <jelmer@jelmer.uk>
  6. #
  7. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  8. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  9. # General Public License as published by the Free Software Foundation; version 2.0
  10. # or (at your option) any later version. You can redistribute it and/or
  11. # modify it under the terms of either of these two licenses.
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. #
  19. # You should have received a copy of the licenses; if not, see
  20. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  21. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  22. # License, Version 2.0.
  23. """Tests for dulwich.cli."""
  24. import io
  25. import os
  26. import shutil
  27. import sys
  28. import tempfile
  29. import unittest
  30. from unittest import skipIf
  31. from unittest.mock import MagicMock, patch
  32. from dulwich import cli
  33. from dulwich.cli import (
  34. detect_terminal_width,
  35. format_bytes,
  36. launch_editor,
  37. parse_relative_time,
  38. write_columns,
  39. )
  40. from dulwich.repo import Repo
  41. from dulwich.tests.utils import (
  42. build_commit_graph,
  43. )
  44. from . import TestCase
  45. class DulwichCliTestCase(TestCase):
  46. """Base class for CLI tests."""
  47. def setUp(self) -> None:
  48. super().setUp()
  49. self.test_dir = tempfile.mkdtemp()
  50. self.addCleanup(shutil.rmtree, self.test_dir)
  51. self.repo_path = os.path.join(self.test_dir, "repo")
  52. os.mkdir(self.repo_path)
  53. self.repo = Repo.init(self.repo_path)
  54. self.addCleanup(self.repo.close)
  55. def _run_cli(self, *args, stdout_stream=None):
  56. """Run CLI command and capture output."""
  57. class MockStream:
  58. def __init__(self):
  59. self._buffer = io.BytesIO()
  60. self.buffer = self._buffer
  61. def write(self, data):
  62. if isinstance(data, bytes):
  63. self._buffer.write(data)
  64. else:
  65. self._buffer.write(data.encode("utf-8"))
  66. def getvalue(self):
  67. value = self._buffer.getvalue()
  68. try:
  69. return value.decode("utf-8")
  70. except UnicodeDecodeError:
  71. return value
  72. def __getattr__(self, name):
  73. return getattr(self._buffer, name)
  74. old_stdout = sys.stdout
  75. old_stderr = sys.stderr
  76. old_cwd = os.getcwd()
  77. try:
  78. # Use custom stdout_stream if provided, otherwise use MockStream
  79. if stdout_stream:
  80. sys.stdout = stdout_stream
  81. if not hasattr(sys.stdout, "buffer"):
  82. sys.stdout.buffer = sys.stdout
  83. else:
  84. sys.stdout = MockStream()
  85. sys.stderr = MockStream()
  86. os.chdir(self.repo_path)
  87. result = cli.main(list(args))
  88. return result, sys.stdout.getvalue(), sys.stderr.getvalue()
  89. finally:
  90. sys.stdout = old_stdout
  91. sys.stderr = old_stderr
  92. os.chdir(old_cwd)
  93. class InitCommandTest(DulwichCliTestCase):
  94. """Tests for init command."""
  95. def test_init_basic(self):
  96. # Create a new directory for init
  97. new_repo_path = os.path.join(self.test_dir, "new_repo")
  98. _result, _stdout, _stderr = self._run_cli("init", new_repo_path)
  99. self.assertTrue(os.path.exists(os.path.join(new_repo_path, ".git")))
  100. def test_init_bare(self):
  101. # Create a new directory for bare repo
  102. bare_repo_path = os.path.join(self.test_dir, "bare_repo")
  103. _result, _stdout, _stderr = self._run_cli("init", "--bare", bare_repo_path)
  104. self.assertTrue(os.path.exists(os.path.join(bare_repo_path, "HEAD")))
  105. self.assertFalse(os.path.exists(os.path.join(bare_repo_path, ".git")))
  106. class HelperFunctionsTest(TestCase):
  107. """Tests for CLI helper functions."""
  108. def test_format_bytes(self):
  109. self.assertEqual("0.0 B", format_bytes(0))
  110. self.assertEqual("100.0 B", format_bytes(100))
  111. self.assertEqual("1.0 KB", format_bytes(1024))
  112. self.assertEqual("1.5 KB", format_bytes(1536))
  113. self.assertEqual("1.0 MB", format_bytes(1024 * 1024))
  114. self.assertEqual("1.0 GB", format_bytes(1024 * 1024 * 1024))
  115. self.assertEqual("1.0 TB", format_bytes(1024 * 1024 * 1024 * 1024))
  116. def test_launch_editor_with_cat(self):
  117. """Test launch_editor by using cat as the editor."""
  118. self.overrideEnv("GIT_EDITOR", "cat")
  119. result = launch_editor(b"Test template content")
  120. self.assertEqual(b"Test template content", result)
  121. def test_parse_relative_time(self):
  122. """Test parsing relative time strings."""
  123. from dulwich.cli import parse_relative_time
  124. self.assertEqual(0, parse_relative_time("now"))
  125. self.assertEqual(60, parse_relative_time("1 minute ago"))
  126. self.assertEqual(120, parse_relative_time("2 minutes ago"))
  127. self.assertEqual(3600, parse_relative_time("1 hour ago"))
  128. self.assertEqual(7200, parse_relative_time("2 hours ago"))
  129. self.assertEqual(86400, parse_relative_time("1 day ago"))
  130. self.assertEqual(172800, parse_relative_time("2 days ago"))
  131. self.assertEqual(604800, parse_relative_time("1 week ago"))
  132. self.assertEqual(1209600, parse_relative_time("2 weeks ago"))
  133. self.assertEqual(2592000, parse_relative_time("1 month ago"))
  134. self.assertEqual(31536000, parse_relative_time("1 year ago"))
  135. # Test invalid formats
  136. with self.assertRaises(ValueError):
  137. parse_relative_time("invalid")
  138. with self.assertRaises(ValueError):
  139. parse_relative_time("2 days") # Missing "ago"
  140. with self.assertRaises(ValueError):
  141. parse_relative_time("two days ago") # Not a number
  142. def test_parse_time_to_timestamp(self):
  143. """Test parsing time specifications to Unix timestamps."""
  144. import time
  145. from dulwich.cli import parse_time_to_timestamp
  146. # Test special values
  147. self.assertEqual(0, parse_time_to_timestamp("never"))
  148. future_time = parse_time_to_timestamp("all")
  149. self.assertGreater(future_time, int(time.time()))
  150. # Test Unix timestamp
  151. self.assertEqual(1234567890, parse_time_to_timestamp("1234567890"))
  152. # Test relative time
  153. now = int(time.time())
  154. result = parse_time_to_timestamp("1 day ago")
  155. expected = now - 86400
  156. # Allow 2 second tolerance for test execution time
  157. self.assertAlmostEqual(expected, result, delta=2)
  158. class AddCommandTest(DulwichCliTestCase):
  159. """Tests for add command."""
  160. def test_add_single_file(self):
  161. # Create a file to add
  162. test_file = os.path.join(self.repo_path, "test.txt")
  163. with open(test_file, "w") as f:
  164. f.write("test content")
  165. _result, _stdout, _stderr = self._run_cli("add", "test.txt")
  166. # Check that file is in index
  167. self.assertIn(b"test.txt", self.repo.open_index())
  168. def test_add_multiple_files(self):
  169. # Create multiple files
  170. for i in range(3):
  171. test_file = os.path.join(self.repo_path, f"test{i}.txt")
  172. with open(test_file, "w") as f:
  173. f.write(f"content {i}")
  174. _result, _stdout, _stderr = self._run_cli(
  175. "add", "test0.txt", "test1.txt", "test2.txt"
  176. )
  177. index = self.repo.open_index()
  178. self.assertIn(b"test0.txt", index)
  179. self.assertIn(b"test1.txt", index)
  180. self.assertIn(b"test2.txt", index)
  181. class RmCommandTest(DulwichCliTestCase):
  182. """Tests for rm command."""
  183. def test_rm_file(self):
  184. # Create, add and commit a file first
  185. test_file = os.path.join(self.repo_path, "test.txt")
  186. with open(test_file, "w") as f:
  187. f.write("test content")
  188. self._run_cli("add", "test.txt")
  189. self._run_cli("commit", "--message=Add test file")
  190. # Now remove it from index and working directory
  191. _result, _stdout, _stderr = self._run_cli("rm", "test.txt")
  192. # Check that file is not in index
  193. self.assertNotIn(b"test.txt", self.repo.open_index())
  194. class CommitCommandTest(DulwichCliTestCase):
  195. """Tests for commit command."""
  196. def test_commit_basic(self):
  197. # Create and add a file
  198. test_file = os.path.join(self.repo_path, "test.txt")
  199. with open(test_file, "w") as f:
  200. f.write("test content")
  201. self._run_cli("add", "test.txt")
  202. # Commit
  203. _result, _stdout, _stderr = self._run_cli("commit", "--message=Initial commit")
  204. # Check that HEAD points to a commit
  205. self.assertIsNotNone(self.repo.head())
  206. def test_commit_all_flag(self):
  207. # Create initial commit
  208. test_file = os.path.join(self.repo_path, "test.txt")
  209. with open(test_file, "w") as f:
  210. f.write("initial content")
  211. self._run_cli("add", "test.txt")
  212. self._run_cli("commit", "--message=Initial commit")
  213. # Modify the file (don't stage it)
  214. with open(test_file, "w") as f:
  215. f.write("modified content")
  216. # Create another file and don't add it (untracked)
  217. untracked_file = os.path.join(self.repo_path, "untracked.txt")
  218. with open(untracked_file, "w") as f:
  219. f.write("untracked content")
  220. # Commit with -a flag should stage and commit the modified file,
  221. # but not the untracked file
  222. _result, _stdout, _stderr = self._run_cli(
  223. "commit", "-a", "--message=Modified commit"
  224. )
  225. self.assertIsNotNone(self.repo.head())
  226. # Check that the modification was committed
  227. with open(test_file) as f:
  228. content = f.read()
  229. self.assertEqual(content, "modified content")
  230. # Check that untracked file is still untracked
  231. self.assertTrue(os.path.exists(untracked_file))
  232. def test_commit_all_flag_no_changes(self):
  233. # Create initial commit
  234. test_file = os.path.join(self.repo_path, "test.txt")
  235. with open(test_file, "w") as f:
  236. f.write("initial content")
  237. self._run_cli("add", "test.txt")
  238. self._run_cli("commit", "--message=Initial commit")
  239. # Try to commit with -a when there are no changes
  240. # This should still work (git allows this)
  241. _result, _stdout, _stderr = self._run_cli(
  242. "commit", "-a", "--message=No changes commit"
  243. )
  244. self.assertIsNotNone(self.repo.head())
  245. def test_commit_all_flag_multiple_files(self):
  246. # Create initial commit with multiple files
  247. file1 = os.path.join(self.repo_path, "file1.txt")
  248. file2 = os.path.join(self.repo_path, "file2.txt")
  249. with open(file1, "w") as f:
  250. f.write("content1")
  251. with open(file2, "w") as f:
  252. f.write("content2")
  253. self._run_cli("add", "file1.txt", "file2.txt")
  254. self._run_cli("commit", "--message=Initial commit")
  255. # Modify both files
  256. with open(file1, "w") as f:
  257. f.write("modified content1")
  258. with open(file2, "w") as f:
  259. f.write("modified content2")
  260. # Create an untracked file
  261. untracked_file = os.path.join(self.repo_path, "untracked.txt")
  262. with open(untracked_file, "w") as f:
  263. f.write("untracked content")
  264. # Commit with -a should stage both modified files but not untracked
  265. _result, _stdout, _stderr = self._run_cli(
  266. "commit", "-a", "--message=Modified both files"
  267. )
  268. self.assertIsNotNone(self.repo.head())
  269. # Verify modifications were committed
  270. with open(file1) as f:
  271. self.assertEqual(f.read(), "modified content1")
  272. with open(file2) as f:
  273. self.assertEqual(f.read(), "modified content2")
  274. # Verify untracked file still exists
  275. self.assertTrue(os.path.exists(untracked_file))
  276. @patch("dulwich.cli.launch_editor")
  277. def test_commit_editor_success(self, mock_editor):
  278. """Test commit with editor when user provides a message."""
  279. # Create and add a file
  280. test_file = os.path.join(self.repo_path, "test.txt")
  281. with open(test_file, "w") as f:
  282. f.write("test content")
  283. self._run_cli("add", "test.txt")
  284. # Mock editor to return a commit message
  285. mock_editor.return_value = b"My commit message\n\n# This is a comment\n"
  286. # Commit without --message flag
  287. _result, _stdout, _stderr = self._run_cli("commit")
  288. # Check that HEAD points to a commit
  289. commit = self.repo[self.repo.head()]
  290. self.assertEqual(commit.message, b"My commit message")
  291. # Verify editor was called
  292. mock_editor.assert_called_once()
  293. @patch("dulwich.cli.launch_editor")
  294. def test_commit_editor_empty_message(self, mock_editor):
  295. """Test commit with editor when user provides empty message."""
  296. # Create and add a file
  297. test_file = os.path.join(self.repo_path, "test.txt")
  298. with open(test_file, "w") as f:
  299. f.write("test content")
  300. self._run_cli("add", "test.txt")
  301. # Mock editor to return only comments
  302. mock_editor.return_value = b"# All lines are comments\n# No actual message\n"
  303. # Commit without --message flag should fail with exit code 1
  304. result, _stdout, _stderr = self._run_cli("commit")
  305. self.assertEqual(result, 1)
  306. @patch("dulwich.cli.launch_editor")
  307. def test_commit_editor_unchanged_template(self, mock_editor):
  308. """Test commit with editor when user doesn't change the template."""
  309. # Create and add a file
  310. test_file = os.path.join(self.repo_path, "test.txt")
  311. with open(test_file, "w") as f:
  312. f.write("test content")
  313. self._run_cli("add", "test.txt")
  314. # Mock editor to return the exact template that was passed to it
  315. def return_unchanged_template(template):
  316. return template
  317. mock_editor.side_effect = return_unchanged_template
  318. # Commit without --message flag should fail with exit code 1
  319. result, _stdout, _stderr = self._run_cli("commit")
  320. self.assertEqual(result, 1)
  321. class LogCommandTest(DulwichCliTestCase):
  322. """Tests for log command."""
  323. def test_log_empty_repo(self):
  324. _result, _stdout, _stderr = self._run_cli("log")
  325. # Empty repo should not crash
  326. def test_log_with_commits(self):
  327. # Create some commits
  328. _c1, _c2, c3 = build_commit_graph(
  329. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  330. )
  331. self.repo.refs[b"HEAD"] = c3.id
  332. _result, stdout, _stderr = self._run_cli("log")
  333. self.assertIn("Commit 3", stdout)
  334. self.assertIn("Commit 2", stdout)
  335. self.assertIn("Commit 1", stdout)
  336. def test_log_reverse(self):
  337. # Create some commits
  338. _c1, _c2, c3 = build_commit_graph(
  339. self.repo.object_store, [[1], [2, 1], [3, 1, 2]]
  340. )
  341. self.repo.refs[b"HEAD"] = c3.id
  342. _result, stdout, _stderr = self._run_cli("log", "--reverse")
  343. # Check order - commit 1 should appear before commit 3
  344. pos1 = stdout.index("Commit 1")
  345. pos3 = stdout.index("Commit 3")
  346. self.assertLess(pos1, pos3)
  347. class StatusCommandTest(DulwichCliTestCase):
  348. """Tests for status command."""
  349. def test_status_empty(self):
  350. _result, _stdout, _stderr = self._run_cli("status")
  351. # Should not crash on empty repo
  352. def test_status_with_untracked(self):
  353. # Create an untracked file
  354. test_file = os.path.join(self.repo_path, "untracked.txt")
  355. with open(test_file, "w") as f:
  356. f.write("untracked content")
  357. _result, stdout, _stderr = self._run_cli("status")
  358. self.assertIn("Untracked files:", stdout)
  359. self.assertIn("untracked.txt", stdout)
  360. class BranchCommandTest(DulwichCliTestCase):
  361. """Tests for branch command."""
  362. def test_branch_create(self):
  363. # Create initial commit
  364. test_file = os.path.join(self.repo_path, "test.txt")
  365. with open(test_file, "w") as f:
  366. f.write("test")
  367. self._run_cli("add", "test.txt")
  368. self._run_cli("commit", "--message=Initial")
  369. # Create branch
  370. _result, _stdout, _stderr = self._run_cli("branch", "test-branch")
  371. self.assertIn(b"refs/heads/test-branch", self.repo.refs.keys())
  372. def test_branch_delete(self):
  373. # Create initial commit and branch
  374. test_file = os.path.join(self.repo_path, "test.txt")
  375. with open(test_file, "w") as f:
  376. f.write("test")
  377. self._run_cli("add", "test.txt")
  378. self._run_cli("commit", "--message=Initial")
  379. self._run_cli("branch", "test-branch")
  380. # Delete branch
  381. _result, _stdout, _stderr = self._run_cli("branch", "-d", "test-branch")
  382. self.assertNotIn(b"refs/heads/test-branch", self.repo.refs.keys())
  383. def test_branch_list_all(self):
  384. # Create initial commit
  385. test_file = os.path.join(self.repo_path, "test.txt")
  386. with open(test_file, "w") as f:
  387. f.write("test")
  388. self._run_cli("add", "test.txt")
  389. self._run_cli("commit", "--message=Initial")
  390. # Create local test branches
  391. self._run_cli("branch", "feature-1")
  392. self._run_cli("branch", "feature-2")
  393. # Setup a remote and create remote branches
  394. self.repo.refs[b"refs/remotes/origin/master"] = self.repo.refs[
  395. b"refs/heads/master"
  396. ]
  397. self.repo.refs[b"refs/remotes/origin/feature-remote"] = self.repo.refs[
  398. b"refs/heads/master"
  399. ]
  400. # Test --all listing
  401. result, stdout, _stderr = self._run_cli("branch", "--all")
  402. self.assertEqual(result, 0)
  403. expected_branches = {
  404. "feature-1", # local branch
  405. "feature-2", # local branch
  406. "master", # local branch
  407. "origin/master", # remote branch
  408. "origin/feature-remote", # remote branch
  409. }
  410. lines = [line.strip() for line in stdout.splitlines()]
  411. # All branches from stdout
  412. all_branches = set(line for line in lines)
  413. self.assertEqual(all_branches, expected_branches)
  414. def test_branch_list_merged(self):
  415. # Create initial commit
  416. test_file = os.path.join(self.repo_path, "test.txt")
  417. with open(test_file, "w") as f:
  418. f.write("test")
  419. self._run_cli("add", "test.txt")
  420. self._run_cli("commit", "--message=Initial")
  421. master_sha = self.repo.refs[b"refs/heads/master"]
  422. # Create a merged branch (points to same commit as master)
  423. self.repo.refs[b"refs/heads/merged-branch"] = master_sha
  424. # Create a new branch with different content (not merged)
  425. test_file2 = os.path.join(self.repo_path, "test2.txt")
  426. with open(test_file2, "w") as f:
  427. f.write("test2")
  428. self._run_cli("add", "test2.txt")
  429. self._run_cli("commit", "--message=New branch commit")
  430. new_branch_sha = self.repo.refs[b"HEAD"]
  431. # Switch back to master
  432. self.repo.refs[b"HEAD"] = master_sha
  433. # Create a non-merged branch that points to the new branch commit
  434. self.repo.refs[b"refs/heads/non-merged-branch"] = new_branch_sha
  435. # Test --merged listing
  436. result, stdout, _stderr = self._run_cli("branch", "--merged")
  437. self.assertEqual(result, 0)
  438. branches = [line.strip() for line in stdout.splitlines()]
  439. expected_branches = {"master", "merged-branch"}
  440. self.assertEqual(set(branches), expected_branches)
  441. def test_branch_list_no_merged(self):
  442. # Create initial commit
  443. test_file = os.path.join(self.repo_path, "test.txt")
  444. with open(test_file, "w") as f:
  445. f.write("test")
  446. self._run_cli("add", "test.txt")
  447. self._run_cli("commit", "--message=Initial")
  448. master_sha = self.repo.refs[b"refs/heads/master"]
  449. # Create a merged branch (points to same commit as master)
  450. self.repo.refs[b"refs/heads/merged-branch"] = master_sha
  451. # Create a new branch with different content (not merged)
  452. test_file2 = os.path.join(self.repo_path, "test2.txt")
  453. with open(test_file2, "w") as f:
  454. f.write("test2")
  455. self._run_cli("add", "test2.txt")
  456. self._run_cli("commit", "--message=New branch commit")
  457. new_branch_sha = self.repo.refs[b"HEAD"]
  458. # Switch back to master
  459. self.repo.refs[b"HEAD"] = master_sha
  460. # Create a non-merged branch that points to the new branch commit
  461. self.repo.refs[b"refs/heads/non-merged-branch"] = new_branch_sha
  462. # Test --no-merged listing
  463. result, stdout, _stderr = self._run_cli("branch", "--no-merged")
  464. self.assertEqual(result, 0)
  465. branches = [line.strip() for line in stdout.splitlines()]
  466. expected_branches = {"non-merged-branch"}
  467. self.assertEqual(set(branches), expected_branches)
  468. def test_branch_list_remotes(self):
  469. # Create initial commit
  470. test_file = os.path.join(self.repo_path, "test.txt")
  471. with open(test_file, "w") as f:
  472. f.write("test")
  473. self._run_cli("add", "test.txt")
  474. self._run_cli("commit", "--message=Initial")
  475. # Setup a remote and create remote branches
  476. self.repo.refs[b"refs/remotes/origin/master"] = self.repo.refs[
  477. b"refs/heads/master"
  478. ]
  479. self.repo.refs[b"refs/remotes/origin/feature-remote-1"] = self.repo.refs[
  480. b"refs/heads/master"
  481. ]
  482. self.repo.refs[b"refs/remotes/origin/feature-remote-2"] = self.repo.refs[
  483. b"refs/heads/master"
  484. ]
  485. # Test --remotes listing
  486. result, stdout, _stderr = self._run_cli("branch", "--remotes")
  487. self.assertEqual(result, 0)
  488. branches = [line.strip() for line in stdout.splitlines()]
  489. expected_branches = [
  490. "origin/feature-remote-1",
  491. "origin/feature-remote-2",
  492. "origin/master",
  493. ]
  494. self.assertEqual(branches, expected_branches)
  495. def test_branch_list_contains(self):
  496. # Create initial commit
  497. test_file = os.path.join(self.repo_path, "test.txt")
  498. with open(test_file, "w") as f:
  499. f.write("test")
  500. self._run_cli("add", "test.txt")
  501. self._run_cli("commit", "--message=Initial")
  502. initial_commit_sha = self.repo.refs[b"HEAD"]
  503. # Create first branch from initial commit
  504. self._run_cli("branch", "branch-1")
  505. # Make a new commit on master
  506. test_file2 = os.path.join(self.repo_path, "test2.txt")
  507. with open(test_file2, "w") as f:
  508. f.write("test2")
  509. self._run_cli("add", "test2.txt")
  510. self._run_cli("commit", "--message=Second commit")
  511. second_commit_sha = self.repo.refs[b"HEAD"]
  512. # Create second branch from current master (contains both commits)
  513. self._run_cli("branch", "branch-2")
  514. # Create third branch that doesn't contain the second commit
  515. # Switch to initial commit and create branch from there
  516. self.repo.refs[b"HEAD"] = initial_commit_sha
  517. self._run_cli("branch", "branch-3")
  518. # Switch back to master
  519. self.repo.refs[b"HEAD"] = second_commit_sha
  520. # Test --contains with second commit (should include master and branch-2)
  521. result, stdout, stderr = self._run_cli(
  522. "branch", "--contains", second_commit_sha.decode()
  523. )
  524. self.assertEqual(result, 0)
  525. branches = [line.strip() for line in stdout.splitlines()]
  526. expected_branches = {"master", "branch-2"}
  527. self.assertEqual(set(branches), expected_branches)
  528. # Test --contains with initial commit (should include all branches)
  529. result, stdout, stderr = self._run_cli(
  530. "branch", "--contains", initial_commit_sha.decode()
  531. )
  532. self.assertEqual(result, 0)
  533. branches = [line.strip() for line in stdout.splitlines()]
  534. expected_branches = {"master", "branch-1", "branch-2", "branch-3"}
  535. self.assertEqual(set(branches), expected_branches)
  536. # Test --contains without argument (uses HEAD, which is second commit)
  537. result, stdout, stderr = self._run_cli("branch", "--contains")
  538. self.assertEqual(result, 0)
  539. branches = [line.strip() for line in stdout.splitlines()]
  540. expected_branches = {"master", "branch-2"}
  541. self.assertEqual(set(branches), expected_branches)
  542. # Test with invalid commit hash
  543. result, stdout, stderr = self._run_cli("branch", "--contains", "invalid123")
  544. self.assertNotEqual(result, 0)
  545. self.assertIn("error: object name invalid123 not found", stderr)
  546. def test_branch_list_column(self):
  547. """Test branch --column formatting"""
  548. # Create initial commit
  549. test_file = os.path.join(self.repo_path, "test.txt")
  550. with open(test_file, "w") as f:
  551. f.write("test")
  552. self._run_cli("add", "test.txt")
  553. self._run_cli("commit", "--message=Initial")
  554. self._run_cli("branch", "feature-1")
  555. self._run_cli("branch", "feature-2")
  556. self._run_cli("branch", "feature-3")
  557. # Run branch --column
  558. result, stdout, _stderr = self._run_cli("branch", "--all", "--column")
  559. self.assertEqual(result, 0)
  560. expected = ["feature-1", "feature-2", "feature-3"]
  561. for branch in expected:
  562. self.assertIn(branch, stdout)
  563. multiple_columns = any(
  564. sum(branch in line for branch in expected) > 1
  565. for line in stdout.strip().split("\n")
  566. )
  567. self.assertTrue(multiple_columns)
  568. def test_branch_list_flag(self):
  569. # Create an initial commit
  570. test_file = os.path.join(self.repo_path, "test.txt")
  571. with open(test_file, "w") as f:
  572. f.write("test")
  573. self._run_cli("add", "test.txt")
  574. self._run_cli("commit", "--message=Initial")
  575. # Create local branches
  576. self._run_cli("branch", "feature-1")
  577. self._run_cli("branch", "feature-2")
  578. self._run_cli("branch", "branch-1")
  579. # Run `branch --list` with a pattern "feature-*"
  580. result, stdout, _stderr = self._run_cli(
  581. "branch", "--all", "--list", "feature-*"
  582. )
  583. self.assertEqual(result, 0)
  584. # Collect branches from the output
  585. branches = [line.strip() for line in stdout.splitlines()]
  586. # Expected branches — exactly those matching the pattern
  587. expected_branches = ["feature-1", "feature-2"]
  588. self.assertEqual(branches, expected_branches)
  589. class TestTerminalWidth(TestCase):
  590. @patch("os.get_terminal_size")
  591. def test_terminal_size(self, mock_get_terminal_size):
  592. """Test os.get_terminal_size mocking."""
  593. mock_get_terminal_size.return_value.columns = 100
  594. width = detect_terminal_width()
  595. self.assertEqual(width, 100)
  596. @patch("os.get_terminal_size")
  597. def test_terminal_size_os_error(self, mock_get_terminal_size):
  598. """Test os.get_terminal_size raising OSError."""
  599. mock_get_terminal_size.side_effect = OSError("No terminal")
  600. width = detect_terminal_width()
  601. self.assertEqual(width, 80)
  602. class TestWriteColumns(TestCase):
  603. """Tests for write_columns function"""
  604. def test_basic_functionality(self):
  605. """Test basic functionality with default terminal width."""
  606. out = io.StringIO()
  607. items = [b"main", b"dev", b"feature/branch-1"]
  608. write_columns(items, out, width=80)
  609. output_text = out.getvalue()
  610. self.assertEqual(output_text, "main dev feature/branch-1\n")
  611. def test_narrow_terminal_single_column(self):
  612. """Test with narrow terminal forcing single column."""
  613. out = io.StringIO()
  614. items = [b"main", b"dev", b"feature/branch-1"]
  615. write_columns(items, out, 20)
  616. self.assertEqual(out.getvalue(), "main\ndev\nfeature/branch-1\n")
  617. def test_wide_terminal_multiple_columns(self):
  618. """Test with wide terminal allowing multiple columns."""
  619. out = io.StringIO()
  620. items = [
  621. b"main",
  622. b"dev",
  623. b"feature/branch-1",
  624. b"feature/branch-2",
  625. b"feature/branch-3",
  626. ]
  627. write_columns(items, out, 120)
  628. output_text = out.getvalue()
  629. self.assertEqual(
  630. output_text,
  631. "main dev feature/branch-1 feature/branch-2 feature/branch-3\n",
  632. )
  633. def test_single_item(self):
  634. """Test with single item."""
  635. out = io.StringIO()
  636. write_columns([b"single"], out, 80)
  637. output_text = out.getvalue()
  638. self.assertEqual("single\n", output_text)
  639. self.assertTrue(output_text.endswith("\n"))
  640. def test_os_error_fallback(self):
  641. """Test fallback behavior when os.get_terminal_size raises OSError."""
  642. with patch("os.get_terminal_size", side_effect=OSError("No terminal")):
  643. out = io.StringIO()
  644. items = [b"main", b"dev"]
  645. write_columns(items, out)
  646. output_text = out.getvalue()
  647. # With default width (80), should display in columns
  648. self.assertEqual(output_text, "main dev\n")
  649. def test_iterator_input(self):
  650. """Test with iterator input instead of list."""
  651. out = io.StringIO()
  652. items = [b"main", b"dev", b"feature/branch-1"]
  653. items_iterator = iter(items)
  654. write_columns(items_iterator, out, 80)
  655. output_text = out.getvalue()
  656. self.assertEqual(output_text, "main dev feature/branch-1\n")
  657. def test_column_alignment(self):
  658. """Test that columns are properly aligned."""
  659. out = io.StringIO()
  660. items = [b"short", b"medium_length", b"very_long______name"]
  661. write_columns(items, out, 50)
  662. output_text = out.getvalue()
  663. self.assertEqual(output_text, "short medium_length very_long______name\n")
  664. def test_columns_formatting(self):
  665. """Test that items are formatted in columns within single line."""
  666. out = io.StringIO()
  667. items = [b"branch-1", b"branch-2", b"branch-3", b"branch-4", b"branch-5"]
  668. write_columns(items, out, 80)
  669. output_text = out.getvalue()
  670. self.assertEqual(output_text.count("\n"), 1)
  671. self.assertTrue(output_text.endswith("\n"))
  672. line = output_text.strip()
  673. for item in items:
  674. self.assertIn(item.decode(), line)
  675. def test_column_alignment_multiple_lines(self):
  676. """Test that columns are properly aligned across multiple lines."""
  677. items = [
  678. b"short",
  679. b"medium_length",
  680. b"very_long_branch_name",
  681. b"another",
  682. b"more",
  683. b"even_longer_branch_name_here",
  684. ]
  685. out = io.StringIO()
  686. write_columns(items, out, width=60)
  687. output_text = out.getvalue()
  688. lines = output_text.strip().split("\n")
  689. self.assertGreater(len(lines), 1)
  690. line_lengths = [len(line) for line in lines if line.strip()]
  691. for length in line_lengths:
  692. self.assertLessEqual(length, 60)
  693. all_output = " ".join(lines)
  694. for item in items:
  695. self.assertIn(item.decode(), all_output)
  696. class CheckoutCommandTest(DulwichCliTestCase):
  697. """Tests for checkout command."""
  698. def test_checkout_branch(self):
  699. # Create initial commit and branch
  700. test_file = os.path.join(self.repo_path, "test.txt")
  701. with open(test_file, "w") as f:
  702. f.write("test")
  703. self._run_cli("add", "test.txt")
  704. self._run_cli("commit", "--message=Initial")
  705. self._run_cli("branch", "test-branch")
  706. # Checkout branch
  707. _result, _stdout, _stderr = self._run_cli("checkout", "test-branch")
  708. self.assertEqual(
  709. self.repo.refs.read_ref(b"HEAD"), b"ref: refs/heads/test-branch"
  710. )
  711. class TagCommandTest(DulwichCliTestCase):
  712. """Tests for tag command."""
  713. def test_tag_create(self):
  714. # Create initial commit
  715. test_file = os.path.join(self.repo_path, "test.txt")
  716. with open(test_file, "w") as f:
  717. f.write("test")
  718. self._run_cli("add", "test.txt")
  719. self._run_cli("commit", "--message=Initial")
  720. # Create tag
  721. _result, _stdout, _stderr = self._run_cli("tag", "v1.0")
  722. self.assertIn(b"refs/tags/v1.0", self.repo.refs.keys())
  723. class VerifyCommitCommandTest(DulwichCliTestCase):
  724. """Tests for verify-commit command."""
  725. def test_verify_commit_basic(self):
  726. # Create initial commit
  727. test_file = os.path.join(self.repo_path, "test.txt")
  728. with open(test_file, "w") as f:
  729. f.write("test")
  730. self._run_cli("add", "test.txt")
  731. self._run_cli("commit", "--message=Initial")
  732. # Mock the porcelain.verify_commit function since we don't have GPG setup
  733. with patch("dulwich.cli.porcelain.verify_commit") as mock_verify:
  734. _result, stdout, _stderr = self._run_cli("verify-commit", "HEAD")
  735. mock_verify.assert_called_once_with(".", "HEAD")
  736. self.assertIn("Good signature", stdout)
  737. def test_verify_commit_multiple(self):
  738. # Create multiple commits
  739. test_file = os.path.join(self.repo_path, "test.txt")
  740. with open(test_file, "w") as f:
  741. f.write("test1")
  742. self._run_cli("add", "test.txt")
  743. self._run_cli("commit", "--message=First")
  744. with open(test_file, "w") as f:
  745. f.write("test2")
  746. self._run_cli("add", "test.txt")
  747. self._run_cli("commit", "--message=Second")
  748. # Mock the porcelain.verify_commit function
  749. with patch("dulwich.cli.porcelain.verify_commit") as mock_verify:
  750. _result, stdout, _stderr = self._run_cli("verify-commit", "HEAD", "HEAD~1")
  751. self.assertEqual(mock_verify.call_count, 2)
  752. self.assertIn("HEAD", stdout)
  753. self.assertIn("HEAD~1", stdout)
  754. def test_verify_commit_default_head(self):
  755. # Create initial commit
  756. test_file = os.path.join(self.repo_path, "test.txt")
  757. with open(test_file, "w") as f:
  758. f.write("test")
  759. self._run_cli("add", "test.txt")
  760. self._run_cli("commit", "--message=Initial")
  761. # Mock the porcelain.verify_commit function
  762. with patch("dulwich.cli.porcelain.verify_commit") as mock_verify:
  763. # Test that verify-commit without arguments defaults to HEAD
  764. _result, stdout, _stderr = self._run_cli("verify-commit")
  765. mock_verify.assert_called_once_with(".", "HEAD")
  766. self.assertIn("Good signature", stdout)
  767. class VerifyTagCommandTest(DulwichCliTestCase):
  768. """Tests for verify-tag command."""
  769. def test_verify_tag_basic(self):
  770. # Create initial commit
  771. test_file = os.path.join(self.repo_path, "test.txt")
  772. with open(test_file, "w") as f:
  773. f.write("test")
  774. self._run_cli("add", "test.txt")
  775. self._run_cli("commit", "--message=Initial")
  776. # Create an annotated tag
  777. self._run_cli("tag", "--annotated", "v1.0")
  778. # Mock the porcelain.verify_tag function since we don't have GPG setup
  779. with patch("dulwich.cli.porcelain.verify_tag") as mock_verify:
  780. _result, stdout, _stderr = self._run_cli("verify-tag", "v1.0")
  781. mock_verify.assert_called_once_with(".", "v1.0")
  782. self.assertIn("Good signature", stdout)
  783. def test_verify_tag_multiple(self):
  784. # Create initial commit
  785. test_file = os.path.join(self.repo_path, "test.txt")
  786. with open(test_file, "w") as f:
  787. f.write("test")
  788. self._run_cli("add", "test.txt")
  789. self._run_cli("commit", "--message=Initial")
  790. # Create multiple annotated tags
  791. self._run_cli("tag", "--annotated", "v1.0")
  792. self._run_cli("tag", "--annotated", "v2.0")
  793. # Mock the porcelain.verify_tag function
  794. with patch("dulwich.cli.porcelain.verify_tag") as mock_verify:
  795. _result, stdout, _stderr = self._run_cli("verify-tag", "v1.0", "v2.0")
  796. self.assertEqual(mock_verify.call_count, 2)
  797. self.assertIn("v1.0", stdout)
  798. self.assertIn("v2.0", stdout)
  799. class DiffCommandTest(DulwichCliTestCase):
  800. """Tests for diff command."""
  801. def test_diff_working_tree(self):
  802. # Create and commit a file
  803. test_file = os.path.join(self.repo_path, "test.txt")
  804. with open(test_file, "w") as f:
  805. f.write("initial content\n")
  806. self._run_cli("add", "test.txt")
  807. self._run_cli("commit", "--message=Initial")
  808. # Modify the file
  809. with open(test_file, "w") as f:
  810. f.write("initial content\nmodified\n")
  811. # Test unstaged diff
  812. _result, stdout, _stderr = self._run_cli("diff")
  813. self.assertIn("+modified", stdout)
  814. def test_diff_staged(self):
  815. # Create initial commit
  816. test_file = os.path.join(self.repo_path, "test.txt")
  817. with open(test_file, "w") as f:
  818. f.write("initial content\n")
  819. self._run_cli("add", "test.txt")
  820. self._run_cli("commit", "--message=Initial")
  821. # Modify and stage the file
  822. with open(test_file, "w") as f:
  823. f.write("initial content\nnew file\n")
  824. self._run_cli("add", "test.txt")
  825. # Test staged diff
  826. _result, stdout, _stderr = self._run_cli("diff", "--staged")
  827. self.assertIn("+new file", stdout)
  828. def test_diff_cached(self):
  829. # Create initial commit
  830. test_file = os.path.join(self.repo_path, "test.txt")
  831. with open(test_file, "w") as f:
  832. f.write("initial content\n")
  833. self._run_cli("add", "test.txt")
  834. self._run_cli("commit", "--message=Initial")
  835. # Modify and stage the file
  836. with open(test_file, "w") as f:
  837. f.write("initial content\nnew file\n")
  838. self._run_cli("add", "test.txt")
  839. # Test cached diff (alias for staged)
  840. _result, stdout, _stderr = self._run_cli("diff", "--cached")
  841. self.assertIn("+new file", stdout)
  842. def test_diff_commit(self):
  843. # Create two commits
  844. test_file = os.path.join(self.repo_path, "test.txt")
  845. with open(test_file, "w") as f:
  846. f.write("first version\n")
  847. self._run_cli("add", "test.txt")
  848. self._run_cli("commit", "--message=First")
  849. with open(test_file, "w") as f:
  850. f.write("first version\nsecond line\n")
  851. self._run_cli("add", "test.txt")
  852. self._run_cli("commit", "--message=Second")
  853. # Add working tree changes
  854. with open(test_file, "a") as f:
  855. f.write("working tree change\n")
  856. # Test single commit diff (should show working tree vs HEAD)
  857. _result, stdout, _stderr = self._run_cli("diff", "HEAD")
  858. self.assertIn("+working tree change", stdout)
  859. def test_diff_two_commits(self):
  860. # Create two commits
  861. test_file = os.path.join(self.repo_path, "test.txt")
  862. with open(test_file, "w") as f:
  863. f.write("first version\n")
  864. self._run_cli("add", "test.txt")
  865. self._run_cli("commit", "--message=First")
  866. # Get first commit SHA
  867. first_commit = self.repo.refs[b"HEAD"].decode()
  868. with open(test_file, "w") as f:
  869. f.write("first version\nsecond line\n")
  870. self._run_cli("add", "test.txt")
  871. self._run_cli("commit", "--message=Second")
  872. # Get second commit SHA
  873. second_commit = self.repo.refs[b"HEAD"].decode()
  874. # Test diff between two commits
  875. _result, stdout, _stderr = self._run_cli("diff", first_commit, second_commit)
  876. self.assertIn("+second line", stdout)
  877. def test_diff_commit_vs_working_tree(self):
  878. # Test that diff <commit> shows working tree vs commit (not commit vs parent)
  879. test_file = os.path.join(self.repo_path, "test.txt")
  880. with open(test_file, "w") as f:
  881. f.write("first version\n")
  882. self._run_cli("add", "test.txt")
  883. self._run_cli("commit", "--message=First")
  884. first_commit = self.repo.refs[b"HEAD"].decode()
  885. with open(test_file, "w") as f:
  886. f.write("first version\nsecond line\n")
  887. self._run_cli("add", "test.txt")
  888. self._run_cli("commit", "--message=Second")
  889. # Add changes to working tree
  890. with open(test_file, "w") as f:
  891. f.write("completely different\n")
  892. # diff <first_commit> should show working tree vs first commit
  893. _result, stdout, _stderr = self._run_cli("diff", first_commit)
  894. self.assertIn("-first version", stdout)
  895. self.assertIn("+completely different", stdout)
  896. def test_diff_with_paths(self):
  897. # Test path filtering
  898. # Create multiple files
  899. file1 = os.path.join(self.repo_path, "file1.txt")
  900. file2 = os.path.join(self.repo_path, "file2.txt")
  901. subdir = os.path.join(self.repo_path, "subdir")
  902. os.makedirs(subdir)
  903. file3 = os.path.join(subdir, "file3.txt")
  904. with open(file1, "w") as f:
  905. f.write("content1\n")
  906. with open(file2, "w") as f:
  907. f.write("content2\n")
  908. with open(file3, "w") as f:
  909. f.write("content3\n")
  910. self._run_cli("add", ".")
  911. self._run_cli("commit", "--message=Initial")
  912. # Modify all files
  913. with open(file1, "w") as f:
  914. f.write("modified1\n")
  915. with open(file2, "w") as f:
  916. f.write("modified2\n")
  917. with open(file3, "w") as f:
  918. f.write("modified3\n")
  919. # Test diff with specific file
  920. _result, stdout, _stderr = self._run_cli("diff", "--", "file1.txt")
  921. self.assertIn("file1.txt", stdout)
  922. self.assertNotIn("file2.txt", stdout)
  923. self.assertNotIn("file3.txt", stdout)
  924. # Test diff with directory
  925. _result, stdout, _stderr = self._run_cli("diff", "--", "subdir")
  926. self.assertNotIn("file1.txt", stdout)
  927. self.assertNotIn("file2.txt", stdout)
  928. self.assertIn("file3.txt", stdout)
  929. # Test staged diff with paths
  930. self._run_cli("add", "file1.txt")
  931. _result, stdout, _stderr = self._run_cli("diff", "--staged", "--", "file1.txt")
  932. self.assertIn("file1.txt", stdout)
  933. self.assertIn("+modified1", stdout)
  934. # Test diff with multiple paths (file2 and file3 are still unstaged)
  935. _result, stdout, _stderr = self._run_cli(
  936. "diff", "--", "file2.txt", "subdir/file3.txt"
  937. )
  938. self.assertIn("file2.txt", stdout)
  939. self.assertIn("file3.txt", stdout)
  940. self.assertNotIn("file1.txt", stdout)
  941. # Test diff with commit and paths
  942. first_commit = self.repo.refs[b"HEAD"].decode()
  943. with open(file1, "w") as f:
  944. f.write("newer1\n")
  945. _result, stdout, _stderr = self._run_cli(
  946. "diff", first_commit, "--", "file1.txt"
  947. )
  948. self.assertIn("file1.txt", stdout)
  949. self.assertIn("-content1", stdout)
  950. self.assertIn("+newer1", stdout)
  951. self.assertNotIn("file2.txt", stdout)
  952. class FilterBranchCommandTest(DulwichCliTestCase):
  953. """Tests for filter-branch command."""
  954. def setUp(self):
  955. super().setUp()
  956. # Create a more complex repository structure for testing
  957. # Create some files in subdirectories
  958. os.makedirs(os.path.join(self.repo_path, "subdir"))
  959. os.makedirs(os.path.join(self.repo_path, "other"))
  960. # Create files
  961. files = {
  962. "README.md": "# Test Repo",
  963. "subdir/file1.txt": "File in subdir",
  964. "subdir/file2.txt": "Another file in subdir",
  965. "other/file3.txt": "File in other dir",
  966. "root.txt": "File at root",
  967. }
  968. for path, content in files.items():
  969. file_path = os.path.join(self.repo_path, path)
  970. with open(file_path, "w") as f:
  971. f.write(content)
  972. # Add all files and create initial commit
  973. self._run_cli("add", ".")
  974. self._run_cli("commit", "--message=Initial commit")
  975. # Create a second commit modifying subdir
  976. with open(os.path.join(self.repo_path, "subdir/file1.txt"), "a") as f:
  977. f.write("\nModified content")
  978. self._run_cli("add", "subdir/file1.txt")
  979. self._run_cli("commit", "--message=Modify subdir file")
  980. # Create a third commit in other dir
  981. with open(os.path.join(self.repo_path, "other/file3.txt"), "a") as f:
  982. f.write("\nMore content")
  983. self._run_cli("add", "other/file3.txt")
  984. self._run_cli("commit", "--message=Modify other file")
  985. # Create a branch
  986. self._run_cli("branch", "test-branch")
  987. # Create a tag
  988. self._run_cli("tag", "v1.0")
  989. def test_filter_branch_subdirectory_filter(self):
  990. """Test filter-branch with subdirectory filter."""
  991. # Run filter-branch to extract only the subdir
  992. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  993. result, _stdout, _stderr = self._run_cli(
  994. "filter-branch", "--subdirectory-filter", "subdir"
  995. )
  996. # Check that the operation succeeded
  997. self.assertEqual(result, 0)
  998. log_output = "\n".join(cm.output)
  999. self.assertIn("Rewrite HEAD", log_output)
  1000. # filter-branch rewrites history but doesn't update working tree
  1001. # We need to check the commit contents, not the working tree
  1002. # Reset to the rewritten HEAD to update working tree
  1003. self._run_cli("reset", "--hard", "HEAD")
  1004. # Now check that only files from subdir remain at root level
  1005. self.assertTrue(os.path.exists(os.path.join(self.repo_path, "file1.txt")))
  1006. self.assertTrue(os.path.exists(os.path.join(self.repo_path, "file2.txt")))
  1007. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "README.md")))
  1008. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "root.txt")))
  1009. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "other")))
  1010. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "subdir")))
  1011. # Check that original refs were backed up
  1012. original_refs = [
  1013. ref for ref in self.repo.refs.keys() if ref.startswith(b"refs/original/")
  1014. ]
  1015. self.assertTrue(
  1016. len(original_refs) > 0, "No original refs found after filter-branch"
  1017. )
  1018. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  1019. def test_filter_branch_msg_filter(self):
  1020. """Test filter-branch with message filter."""
  1021. # Run filter-branch to prepend [FILTERED] to commit messages
  1022. result, stdout, _stderr = self._run_cli(
  1023. "filter-branch", "--msg-filter", "sed 's/^/[FILTERED] /'"
  1024. )
  1025. self.assertEqual(result, 0)
  1026. # Check that commit messages were modified
  1027. result, stdout, _stderr = self._run_cli("log")
  1028. self.assertIn("[FILTERED] Modify other file", stdout)
  1029. self.assertIn("[FILTERED] Modify subdir file", stdout)
  1030. self.assertIn("[FILTERED] Initial commit", stdout)
  1031. def test_filter_branch_env_filter(self):
  1032. """Test filter-branch with environment filter."""
  1033. # Run filter-branch to change author email
  1034. env_filter = """
  1035. if [ "$GIT_AUTHOR_EMAIL" = "test@example.com" ]; then
  1036. export GIT_AUTHOR_EMAIL="filtered@example.com"
  1037. fi
  1038. """
  1039. result, _stdout, _stderr = self._run_cli(
  1040. "filter-branch", "--env-filter", env_filter
  1041. )
  1042. self.assertEqual(result, 0)
  1043. def test_filter_branch_prune_empty(self):
  1044. """Test filter-branch with prune-empty option."""
  1045. # Create a commit that only touches files outside subdir
  1046. with open(os.path.join(self.repo_path, "root.txt"), "a") as f:
  1047. f.write("\nNew line")
  1048. self._run_cli("add", "root.txt")
  1049. self._run_cli("commit", "--message=Modify root file only")
  1050. # Run filter-branch to extract subdir with prune-empty
  1051. result, stdout, _stderr = self._run_cli(
  1052. "filter-branch", "--subdirectory-filter", "subdir", "--prune-empty"
  1053. )
  1054. self.assertEqual(result, 0)
  1055. # The last commit should have been pruned
  1056. result, stdout, _stderr = self._run_cli("log")
  1057. self.assertNotIn("Modify root file only", stdout)
  1058. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  1059. def test_filter_branch_force(self):
  1060. """Test filter-branch with force option."""
  1061. # Run filter-branch once with a filter that actually changes something
  1062. result, _stdout, _stderr = self._run_cli(
  1063. "filter-branch", "--msg-filter", "sed 's/^/[TEST] /'"
  1064. )
  1065. self.assertEqual(result, 0)
  1066. # Check that backup refs were created
  1067. # The implementation backs up refs under refs/original/
  1068. original_refs = [
  1069. ref for ref in self.repo.refs.keys() if ref.startswith(b"refs/original/")
  1070. ]
  1071. self.assertTrue(len(original_refs) > 0, "No original refs found")
  1072. # Run again without force - should fail
  1073. with self.assertLogs("dulwich.cli", level="ERROR") as cm:
  1074. result, _stdout, _stderr = self._run_cli(
  1075. "filter-branch", "--msg-filter", "sed 's/^/[TEST2] /'"
  1076. )
  1077. self.assertEqual(result, 1)
  1078. log_output = "\n".join(cm.output)
  1079. self.assertIn("Cannot create a new backup", log_output)
  1080. self.assertIn("refs/original", log_output)
  1081. # Run with force - should succeed
  1082. result, _stdout, _stderr = self._run_cli(
  1083. "filter-branch", "--force", "--msg-filter", "sed 's/^/[TEST3] /'"
  1084. )
  1085. self.assertEqual(result, 0)
  1086. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  1087. def test_filter_branch_specific_branch(self):
  1088. """Test filter-branch on a specific branch."""
  1089. # Switch to test-branch and add a commit
  1090. self._run_cli("checkout", "test-branch")
  1091. with open(os.path.join(self.repo_path, "branch-file.txt"), "w") as f:
  1092. f.write("Branch specific file")
  1093. self._run_cli("add", "branch-file.txt")
  1094. self._run_cli("commit", "--message=Branch commit")
  1095. # Run filter-branch on the test-branch
  1096. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1097. result, stdout, _stderr = self._run_cli(
  1098. "filter-branch", "--msg-filter", "sed 's/^/[BRANCH] /'", "test-branch"
  1099. )
  1100. self.assertEqual(result, 0)
  1101. log_output = "\n".join(cm.output)
  1102. self.assertIn("Ref 'refs/heads/test-branch' was rewritten", log_output)
  1103. # Check that only test-branch was modified
  1104. result, stdout, _stderr = self._run_cli("log")
  1105. self.assertIn("[BRANCH] Branch commit", stdout)
  1106. # Switch to master and check it wasn't modified
  1107. self._run_cli("checkout", "master")
  1108. result, stdout, _stderr = self._run_cli("log")
  1109. self.assertNotIn("[BRANCH]", stdout)
  1110. def test_filter_branch_tree_filter(self):
  1111. """Test filter-branch with tree filter."""
  1112. # Use a tree filter to remove a specific file
  1113. tree_filter = "rm -f root.txt"
  1114. result, stdout, _stderr = self._run_cli(
  1115. "filter-branch", "--tree-filter", tree_filter
  1116. )
  1117. self.assertEqual(result, 0)
  1118. # Check that the file was removed from the latest commit
  1119. # We need to check the commit tree, not the working directory
  1120. result, stdout, _stderr = self._run_cli("ls-tree", "HEAD")
  1121. self.assertNotIn("root.txt", stdout)
  1122. def test_filter_branch_index_filter(self):
  1123. """Test filter-branch with index filter."""
  1124. # Use an index filter to remove a file from the index
  1125. index_filter = "git rm --cached --ignore-unmatch root.txt"
  1126. result, _stdout, _stderr = self._run_cli(
  1127. "filter-branch", "--index-filter", index_filter
  1128. )
  1129. self.assertEqual(result, 0)
  1130. def test_filter_branch_parent_filter(self):
  1131. """Test filter-branch with parent filter."""
  1132. # Create a merge commit first
  1133. self._run_cli("checkout", "HEAD", "-b", "feature")
  1134. with open(os.path.join(self.repo_path, "feature.txt"), "w") as f:
  1135. f.write("Feature")
  1136. self._run_cli("add", "feature.txt")
  1137. self._run_cli("commit", "--message=Feature commit")
  1138. self._run_cli("checkout", "master")
  1139. self._run_cli("merge", "feature", "--message=Merge feature")
  1140. # Use parent filter to linearize history (remove second parent)
  1141. parent_filter = "cut -d' ' -f1"
  1142. result, _stdout, _stderr = self._run_cli(
  1143. "filter-branch", "--parent-filter", parent_filter
  1144. )
  1145. self.assertEqual(result, 0)
  1146. def test_filter_branch_commit_filter(self):
  1147. """Test filter-branch with commit filter."""
  1148. # Use commit filter to skip commits with certain messages
  1149. commit_filter = """
  1150. if grep -q "Modify other" <<< "$GIT_COMMIT_MESSAGE"; then
  1151. skip_commit "$@"
  1152. else
  1153. git commit-tree "$@"
  1154. fi
  1155. """
  1156. _result, _stdout, _stderr = self._run_cli(
  1157. "filter-branch", "--commit-filter", commit_filter
  1158. )
  1159. # Note: This test may fail because the commit filter syntax is simplified
  1160. # In real Git, skip_commit is a function, but our implementation may differ
  1161. def test_filter_branch_tag_name_filter(self):
  1162. """Test filter-branch with tag name filter."""
  1163. # Run filter-branch with tag name filter to rename tags
  1164. result, _stdout, _stderr = self._run_cli(
  1165. "filter-branch",
  1166. "--tag-name-filter",
  1167. "sed 's/^v/version-/'",
  1168. "--msg-filter",
  1169. "cat",
  1170. )
  1171. self.assertEqual(result, 0)
  1172. # Check that tag was renamed
  1173. self.assertIn(b"refs/tags/version-1.0", self.repo.refs.keys())
  1174. def test_filter_branch_errors(self):
  1175. """Test filter-branch error handling."""
  1176. # Test with invalid subdirectory
  1177. result, _stdout, _stderr = self._run_cli(
  1178. "filter-branch", "--subdirectory-filter", "nonexistent"
  1179. )
  1180. # Should still succeed but produce empty history
  1181. self.assertEqual(result, 0)
  1182. def test_filter_branch_no_args(self):
  1183. """Test filter-branch with no arguments."""
  1184. # Should work as no-op
  1185. result, _stdout, _stderr = self._run_cli("filter-branch")
  1186. self.assertEqual(result, 0)
  1187. class ShowCommandTest(DulwichCliTestCase):
  1188. """Tests for show command."""
  1189. def test_show_commit(self):
  1190. # Create a commit
  1191. test_file = os.path.join(self.repo_path, "test.txt")
  1192. with open(test_file, "w") as f:
  1193. f.write("test content")
  1194. self._run_cli("add", "test.txt")
  1195. self._run_cli("commit", "--message=Test commit")
  1196. _result, stdout, _stderr = self._run_cli("show", "HEAD")
  1197. self.assertIn("Test commit", stdout)
  1198. class ShowRefCommandTest(DulwichCliTestCase):
  1199. """Tests for show-ref command."""
  1200. def test_show_ref_basic(self):
  1201. """Test basic show-ref functionality."""
  1202. # Create a commit to have a HEAD ref
  1203. test_file = os.path.join(self.repo_path, "test.txt")
  1204. with open(test_file, "w") as f:
  1205. f.write("test content")
  1206. self._run_cli("add", "test.txt")
  1207. self._run_cli("commit", "--message=Test commit")
  1208. # Create a branch
  1209. self._run_cli("branch", "test-branch")
  1210. # Get the exact SHAs
  1211. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1212. test_branch_sha = self.repo.refs[b"refs/heads/test-branch"].decode()
  1213. # Run show-ref
  1214. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1215. _result, _stdout, _stderr = self._run_cli("show-ref")
  1216. output = "\n".join([record.message for record in cm.records])
  1217. expected = (
  1218. f"{master_sha} refs/heads/master\n{test_branch_sha} refs/heads/test-branch"
  1219. )
  1220. self.assertEqual(output, expected)
  1221. def test_show_ref_with_head(self):
  1222. """Test show-ref with --head option."""
  1223. # Create a commit to have a HEAD ref
  1224. test_file = os.path.join(self.repo_path, "test.txt")
  1225. with open(test_file, "w") as f:
  1226. f.write("test content")
  1227. self._run_cli("add", "test.txt")
  1228. self._run_cli("commit", "--message=Test commit")
  1229. # Get the exact SHAs
  1230. head_sha = self.repo.refs[b"HEAD"].decode()
  1231. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1232. # Run show-ref with --head
  1233. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1234. _result, _stdout, _stderr = self._run_cli("show-ref", "--head")
  1235. output = "\n".join([record.message for record in cm.records])
  1236. expected = f"{head_sha} HEAD\n{master_sha} refs/heads/master"
  1237. self.assertEqual(output, expected)
  1238. def test_show_ref_with_pattern(self):
  1239. """Test show-ref with pattern matching."""
  1240. # Create commits and branches
  1241. test_file = os.path.join(self.repo_path, "test.txt")
  1242. with open(test_file, "w") as f:
  1243. f.write("test content")
  1244. self._run_cli("add", "test.txt")
  1245. self._run_cli("commit", "--message=Test commit")
  1246. self._run_cli("branch", "feature-1")
  1247. self._run_cli("branch", "feature-2")
  1248. self._run_cli("branch", "bugfix-1")
  1249. # Get the exact SHA for master
  1250. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1251. # Test pattern matching for "master"
  1252. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1253. _result, _stdout, _stderr = self._run_cli("show-ref", "master")
  1254. output = "\n".join([record.message for record in cm.records])
  1255. expected = f"{master_sha} refs/heads/master"
  1256. self.assertEqual(output, expected)
  1257. def test_show_ref_branches_only(self):
  1258. """Test show-ref with --branches option."""
  1259. # Create commits and a tag
  1260. test_file = os.path.join(self.repo_path, "test.txt")
  1261. with open(test_file, "w") as f:
  1262. f.write("test content")
  1263. self._run_cli("add", "test.txt")
  1264. self._run_cli("commit", "--message=Test commit")
  1265. self._run_cli("tag", "v1.0")
  1266. # Get the exact SHA for master
  1267. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1268. # Run show-ref with --branches
  1269. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1270. _result, _stdout, _stderr = self._run_cli("show-ref", "--branches")
  1271. output = "\n".join([record.message for record in cm.records])
  1272. expected = f"{master_sha} refs/heads/master"
  1273. self.assertEqual(output, expected)
  1274. def test_show_ref_tags_only(self):
  1275. """Test show-ref with --tags option."""
  1276. # Create commits and tags
  1277. test_file = os.path.join(self.repo_path, "test.txt")
  1278. with open(test_file, "w") as f:
  1279. f.write("test content")
  1280. self._run_cli("add", "test.txt")
  1281. self._run_cli("commit", "--message=Test commit")
  1282. self._run_cli("tag", "v1.0")
  1283. self._run_cli("tag", "v2.0")
  1284. # Get the exact SHAs for tags
  1285. v1_sha = self.repo.refs[b"refs/tags/v1.0"].decode()
  1286. v2_sha = self.repo.refs[b"refs/tags/v2.0"].decode()
  1287. # Run show-ref with --tags
  1288. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1289. _result, _stdout, _stderr = self._run_cli("show-ref", "--tags")
  1290. output = "\n".join([record.message for record in cm.records])
  1291. expected = f"{v1_sha} refs/tags/v1.0\n{v2_sha} refs/tags/v2.0"
  1292. self.assertEqual(output, expected)
  1293. def test_show_ref_hash_only(self):
  1294. """Test show-ref with --hash option to show only OID."""
  1295. # Create a commit
  1296. test_file = os.path.join(self.repo_path, "test.txt")
  1297. with open(test_file, "w") as f:
  1298. f.write("test content")
  1299. self._run_cli("add", "test.txt")
  1300. self._run_cli("commit", "--message=Test commit")
  1301. # Get the exact SHA for master
  1302. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1303. # Run show-ref with --hash
  1304. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1305. _result, _stdout, _stderr = self._run_cli(
  1306. "show-ref", "--hash", "--", "master"
  1307. )
  1308. output = "\n".join([record.message for record in cm.records])
  1309. expected = f"{master_sha}"
  1310. self.assertEqual(output, expected)
  1311. def test_show_ref_verify(self):
  1312. """Test show-ref with --verify option for exact matching."""
  1313. # Create a commit
  1314. test_file = os.path.join(self.repo_path, "test.txt")
  1315. with open(test_file, "w") as f:
  1316. f.write("test content")
  1317. self._run_cli("add", "test.txt")
  1318. self._run_cli("commit", "--message=Test commit")
  1319. # Get the exact SHA for master
  1320. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1321. # Verify with exact ref path should succeed
  1322. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1323. result, _stdout, _stderr = self._run_cli(
  1324. "show-ref", "--verify", "refs/heads/master"
  1325. )
  1326. self.assertEqual(result, 0)
  1327. output = "\n".join([record.message for record in cm.records])
  1328. expected = f"{master_sha} refs/heads/master"
  1329. self.assertEqual(output, expected)
  1330. # Verify with partial name should fail
  1331. result, _stdout, _stderr = self._run_cli("show-ref", "--verify", "master")
  1332. self.assertEqual(result, 1)
  1333. def test_show_ref_exists(self):
  1334. """Test show-ref with --exists option."""
  1335. # Create a commit
  1336. test_file = os.path.join(self.repo_path, "test.txt")
  1337. with open(test_file, "w") as f:
  1338. f.write("test content")
  1339. self._run_cli("add", "test.txt")
  1340. self._run_cli("commit", "--message=Test commit")
  1341. # Check if existing ref exists
  1342. result, _stdout, _stderr = self._run_cli(
  1343. "show-ref", "--exists", "refs/heads/master"
  1344. )
  1345. self.assertEqual(result, 0)
  1346. # Check if non-existing ref exists
  1347. result, _stdout, _stderr = self._run_cli(
  1348. "show-ref", "--exists", "refs/heads/nonexistent"
  1349. )
  1350. self.assertEqual(result, 2)
  1351. def test_show_ref_quiet(self):
  1352. """Test show-ref with --quiet option."""
  1353. # Create a commit
  1354. test_file = os.path.join(self.repo_path, "test.txt")
  1355. with open(test_file, "w") as f:
  1356. f.write("test content")
  1357. self._run_cli("add", "test.txt")
  1358. self._run_cli("commit", "--message=Test commit")
  1359. # Run show-ref with --quiet - should not log anything
  1360. result, _stdout, _stderr = self._run_cli("show-ref", "--quiet")
  1361. self.assertEqual(result, 0)
  1362. def test_show_ref_abbrev(self):
  1363. """Test show-ref with --abbrev option."""
  1364. # Create a commit
  1365. test_file = os.path.join(self.repo_path, "test.txt")
  1366. with open(test_file, "w") as f:
  1367. f.write("test content")
  1368. self._run_cli("add", "test.txt")
  1369. self._run_cli("commit", "--message=Test commit")
  1370. # Get the exact SHA for master
  1371. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1372. # Run show-ref with --abbrev=7
  1373. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1374. _result, _stdout, _stderr = self._run_cli("show-ref", "--abbrev=7")
  1375. output = "\n".join([record.message for record in cm.records])
  1376. expected = f"{master_sha[:7]} refs/heads/master"
  1377. self.assertEqual(output, expected)
  1378. def test_show_ref_no_matches(self):
  1379. """Test show-ref returns error when no matches found."""
  1380. # Create a commit
  1381. test_file = os.path.join(self.repo_path, "test.txt")
  1382. with open(test_file, "w") as f:
  1383. f.write("test content")
  1384. self._run_cli("add", "test.txt")
  1385. self._run_cli("commit", "--message=Test commit")
  1386. # Search for non-existent pattern
  1387. result, _stdout, _stderr = self._run_cli("show-ref", "nonexistent")
  1388. self.assertEqual(result, 1)
  1389. class ShowBranchCommandTest(DulwichCliTestCase):
  1390. """Tests for show-branch command."""
  1391. def test_show_branch_basic(self):
  1392. """Test basic show-branch functionality."""
  1393. # Create initial commit
  1394. test_file = os.path.join(self.repo_path, "test.txt")
  1395. with open(test_file, "w") as f:
  1396. f.write("initial content")
  1397. self._run_cli("add", "test.txt")
  1398. self._run_cli("commit", "--message=Initial commit")
  1399. # Create a branch and add a commit
  1400. self._run_cli("branch", "branch1")
  1401. self._run_cli("checkout", "branch1")
  1402. with open(test_file, "a") as f:
  1403. f.write("\nbranch1 content")
  1404. self._run_cli("add", "test.txt")
  1405. self._run_cli("commit", "--message=Branch1 commit")
  1406. # Switch back to master
  1407. self._run_cli("checkout", "master")
  1408. # Run show-branch
  1409. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1410. _result, _stdout, _stderr = self._run_cli(
  1411. "show-branch", "master", "branch1"
  1412. )
  1413. output = "\n".join([record.message for record in cm.records])
  1414. # Check exact output
  1415. expected = (
  1416. "! [branch1] Branch1 commit\n"
  1417. " ![master] Initial commit\n"
  1418. "----\n"
  1419. "* [Branch1 commit]\n"
  1420. "+* [Initial commit]"
  1421. )
  1422. self.assertEqual(expected, output)
  1423. def test_show_branch_list(self):
  1424. """Test show-branch with --list option."""
  1425. # Create initial commit
  1426. test_file = os.path.join(self.repo_path, "test.txt")
  1427. with open(test_file, "w") as f:
  1428. f.write("initial content")
  1429. self._run_cli("add", "test.txt")
  1430. self._run_cli("commit", "--message=Initial commit")
  1431. # Create branches
  1432. self._run_cli("branch", "branch1")
  1433. self._run_cli("branch", "branch2")
  1434. # Run show-branch --list
  1435. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1436. _result, _stdout, _stderr = self._run_cli("show-branch", "--list")
  1437. output = "\n".join([record.message for record in cm.records])
  1438. # Check exact output (only branch headers, no separator)
  1439. expected = (
  1440. "! [branch1] Initial commit\n"
  1441. " ! [branch2] Initial commit\n"
  1442. " ![master] Initial commit"
  1443. )
  1444. self.assertEqual(expected, output)
  1445. def test_show_branch_independent(self):
  1446. """Test show-branch with --independent option."""
  1447. # Create initial commit
  1448. test_file = os.path.join(self.repo_path, "test.txt")
  1449. with open(test_file, "w") as f:
  1450. f.write("initial content")
  1451. self._run_cli("add", "test.txt")
  1452. self._run_cli("commit", "--message=Initial commit")
  1453. # Create a branch and add a commit
  1454. self._run_cli("branch", "branch1")
  1455. self._run_cli("checkout", "branch1")
  1456. with open(test_file, "a") as f:
  1457. f.write("\nbranch1 content")
  1458. self._run_cli("add", "test.txt")
  1459. self._run_cli("commit", "--message=Branch1 commit")
  1460. # Run show-branch --independent
  1461. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1462. _result, _stdout, _stderr = self._run_cli(
  1463. "show-branch", "--independent", "master", "branch1"
  1464. )
  1465. output = "\n".join([record.message for record in cm.records])
  1466. # Only branch1 should be shown (it's not reachable from master)
  1467. expected = "branch1"
  1468. self.assertEqual(expected, output)
  1469. def test_show_branch_merge_base(self):
  1470. """Test show-branch with --merge-base option."""
  1471. # Create initial commit
  1472. test_file = os.path.join(self.repo_path, "test.txt")
  1473. with open(test_file, "w") as f:
  1474. f.write("initial content")
  1475. self._run_cli("add", "test.txt")
  1476. self._run_cli("commit", "--message=Initial commit")
  1477. # Get the initial commit SHA
  1478. initial_sha = self.repo.refs[b"HEAD"]
  1479. # Create a branch and add a commit
  1480. self._run_cli("branch", "branch1")
  1481. self._run_cli("checkout", "branch1")
  1482. with open(test_file, "a") as f:
  1483. f.write("\nbranch1 content")
  1484. self._run_cli("add", "test.txt")
  1485. self._run_cli("commit", "--message=Branch1 commit")
  1486. # Switch back to master and add a different commit
  1487. self._run_cli("checkout", "master")
  1488. with open(test_file, "a") as f:
  1489. f.write("\nmaster content")
  1490. self._run_cli("add", "test.txt")
  1491. self._run_cli("commit", "--message=Master commit")
  1492. # Run show-branch --merge-base
  1493. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1494. _result, _stdout, _stderr = self._run_cli(
  1495. "show-branch", "--merge-base", "master", "branch1"
  1496. )
  1497. output = "\n".join([record.message for record in cm.records])
  1498. # The merge base should be the initial commit SHA
  1499. expected = initial_sha.decode("ascii")
  1500. self.assertEqual(expected, output)
  1501. class FormatPatchCommandTest(DulwichCliTestCase):
  1502. """Tests for format-patch command."""
  1503. def test_format_patch_single_commit(self):
  1504. # Create a commit with actual content
  1505. from dulwich.objects import Blob, Tree
  1506. # Initial commit
  1507. tree1 = Tree()
  1508. self.repo.object_store.add_object(tree1)
  1509. self.repo.get_worktree().commit(
  1510. message=b"Initial commit",
  1511. tree=tree1.id,
  1512. )
  1513. # Second commit with a file
  1514. blob = Blob.from_string(b"Hello, World!\n")
  1515. self.repo.object_store.add_object(blob)
  1516. tree2 = Tree()
  1517. tree2.add(b"hello.txt", 0o100644, blob.id)
  1518. self.repo.object_store.add_object(tree2)
  1519. self.repo.get_worktree().commit(
  1520. message=b"Add hello.txt",
  1521. tree=tree2.id,
  1522. )
  1523. # Test format-patch for last commit
  1524. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1525. result, _stdout, _stderr = self._run_cli("format-patch", "-n", "1")
  1526. self.assertEqual(result, None)
  1527. log_output = "\n".join(cm.output)
  1528. self.assertIn("0001-Add-hello.txt.patch", log_output)
  1529. # Check patch contents
  1530. patch_file = os.path.join(self.repo_path, "0001-Add-hello.txt.patch")
  1531. with open(patch_file, "rb") as f:
  1532. content = f.read()
  1533. # Check header
  1534. self.assertIn(b"Subject: [PATCH 1/1] Add hello.txt", content)
  1535. self.assertIn(b"From:", content)
  1536. self.assertIn(b"Date:", content)
  1537. # Check diff content
  1538. self.assertIn(b"diff --git a/hello.txt b/hello.txt", content)
  1539. self.assertIn(b"new file mode", content)
  1540. self.assertIn(b"+Hello, World!", content)
  1541. # Check footer
  1542. self.assertIn(b"-- \nDulwich", content)
  1543. # Clean up
  1544. os.remove(patch_file)
  1545. def test_format_patch_multiple_commits(self):
  1546. from dulwich.objects import Blob, Tree
  1547. # Initial commit
  1548. tree1 = Tree()
  1549. self.repo.object_store.add_object(tree1)
  1550. self.repo.get_worktree().commit(
  1551. message=b"Initial commit",
  1552. tree=tree1.id,
  1553. )
  1554. # Second commit
  1555. blob1 = Blob.from_string(b"File 1 content\n")
  1556. self.repo.object_store.add_object(blob1)
  1557. tree2 = Tree()
  1558. tree2.add(b"file1.txt", 0o100644, blob1.id)
  1559. self.repo.object_store.add_object(tree2)
  1560. self.repo.get_worktree().commit(
  1561. message=b"Add file1.txt",
  1562. tree=tree2.id,
  1563. )
  1564. # Third commit
  1565. blob2 = Blob.from_string(b"File 2 content\n")
  1566. self.repo.object_store.add_object(blob2)
  1567. tree3 = Tree()
  1568. tree3.add(b"file1.txt", 0o100644, blob1.id)
  1569. tree3.add(b"file2.txt", 0o100644, blob2.id)
  1570. self.repo.object_store.add_object(tree3)
  1571. self.repo.get_worktree().commit(
  1572. message=b"Add file2.txt",
  1573. tree=tree3.id,
  1574. )
  1575. # Test format-patch for last 2 commits
  1576. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1577. result, _stdout, _stderr = self._run_cli("format-patch", "-n", "2")
  1578. self.assertEqual(result, None)
  1579. log_output = "\n".join(cm.output)
  1580. self.assertIn("0001-Add-file1.txt.patch", log_output)
  1581. self.assertIn("0002-Add-file2.txt.patch", log_output)
  1582. # Check first patch
  1583. with open(os.path.join(self.repo_path, "0001-Add-file1.txt.patch"), "rb") as f:
  1584. content = f.read()
  1585. self.assertIn(b"Subject: [PATCH 1/2] Add file1.txt", content)
  1586. self.assertIn(b"+File 1 content", content)
  1587. # Check second patch
  1588. with open(os.path.join(self.repo_path, "0002-Add-file2.txt.patch"), "rb") as f:
  1589. content = f.read()
  1590. self.assertIn(b"Subject: [PATCH 2/2] Add file2.txt", content)
  1591. self.assertIn(b"+File 2 content", content)
  1592. # Clean up
  1593. os.remove(os.path.join(self.repo_path, "0001-Add-file1.txt.patch"))
  1594. os.remove(os.path.join(self.repo_path, "0002-Add-file2.txt.patch"))
  1595. def test_format_patch_output_directory(self):
  1596. from dulwich.objects import Blob, Tree
  1597. # Create a commit
  1598. blob = Blob.from_string(b"Test content\n")
  1599. self.repo.object_store.add_object(blob)
  1600. tree = Tree()
  1601. tree.add(b"test.txt", 0o100644, blob.id)
  1602. self.repo.object_store.add_object(tree)
  1603. self.repo.get_worktree().commit(
  1604. message=b"Test commit",
  1605. tree=tree.id,
  1606. )
  1607. # Create output directory
  1608. output_dir = os.path.join(self.test_dir, "patches")
  1609. os.makedirs(output_dir)
  1610. # Test format-patch with output directory
  1611. result, _stdout, _stderr = self._run_cli(
  1612. "format-patch", "-o", output_dir, "-n", "1"
  1613. )
  1614. self.assertEqual(result, None)
  1615. # Check that file was created in output directory with correct content
  1616. patch_file = os.path.join(output_dir, "0001-Test-commit.patch")
  1617. self.assertTrue(os.path.exists(patch_file))
  1618. with open(patch_file, "rb") as f:
  1619. content = f.read()
  1620. self.assertIn(b"Subject: [PATCH 1/1] Test commit", content)
  1621. self.assertIn(b"+Test content", content)
  1622. def test_format_patch_commit_range(self):
  1623. from dulwich.objects import Blob, Tree
  1624. # Create commits with actual file changes
  1625. commits = []
  1626. trees = []
  1627. # Initial empty commit
  1628. tree0 = Tree()
  1629. self.repo.object_store.add_object(tree0)
  1630. trees.append(tree0)
  1631. c0 = self.repo.get_worktree().commit(
  1632. message=b"Initial commit",
  1633. tree=tree0.id,
  1634. )
  1635. commits.append(c0)
  1636. # Add three files in separate commits
  1637. for i in range(1, 4):
  1638. blob = Blob.from_string(f"Content {i}\n".encode())
  1639. self.repo.object_store.add_object(blob)
  1640. tree = Tree()
  1641. # Copy previous files
  1642. for j in range(1, i):
  1643. prev_blob_id = trees[j][f"file{j}.txt".encode()][1]
  1644. tree.add(f"file{j}.txt".encode(), 0o100644, prev_blob_id)
  1645. # Add new file
  1646. tree.add(f"file{i}.txt".encode(), 0o100644, blob.id)
  1647. self.repo.object_store.add_object(tree)
  1648. trees.append(tree)
  1649. c = self.repo.get_worktree().commit(
  1650. message=f"Add file{i}.txt".encode(),
  1651. tree=tree.id,
  1652. )
  1653. commits.append(c)
  1654. # Test format-patch with commit range (should get commits 2 and 3)
  1655. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1656. result, _stdout, _stderr = self._run_cli(
  1657. "format-patch", f"{commits[1].decode()}..{commits[3].decode()}"
  1658. )
  1659. self.assertEqual(result, None)
  1660. # Should create patches for commits 2 and 3
  1661. log_output = "\n".join(cm.output)
  1662. self.assertIn("0001-Add-file2.txt.patch", log_output)
  1663. self.assertIn("0002-Add-file3.txt.patch", log_output)
  1664. # Verify patch contents
  1665. with open(os.path.join(self.repo_path, "0001-Add-file2.txt.patch"), "rb") as f:
  1666. content = f.read()
  1667. self.assertIn(b"Subject: [PATCH 1/2] Add file2.txt", content)
  1668. self.assertIn(b"+Content 2", content)
  1669. self.assertNotIn(b"file3.txt", content) # Should not include file3
  1670. with open(os.path.join(self.repo_path, "0002-Add-file3.txt.patch"), "rb") as f:
  1671. content = f.read()
  1672. self.assertIn(b"Subject: [PATCH 2/2] Add file3.txt", content)
  1673. self.assertIn(b"+Content 3", content)
  1674. self.assertNotIn(b"file2.txt", content) # Should not modify file2
  1675. # Clean up
  1676. os.remove(os.path.join(self.repo_path, "0001-Add-file2.txt.patch"))
  1677. os.remove(os.path.join(self.repo_path, "0002-Add-file3.txt.patch"))
  1678. def test_format_patch_stdout(self):
  1679. from dulwich.objects import Blob, Tree
  1680. # Create a commit with modified file
  1681. tree1 = Tree()
  1682. blob1 = Blob.from_string(b"Original content\n")
  1683. self.repo.object_store.add_object(blob1)
  1684. tree1.add(b"file.txt", 0o100644, blob1.id)
  1685. self.repo.object_store.add_object(tree1)
  1686. self.repo.get_worktree().commit(
  1687. message=b"Initial commit",
  1688. tree=tree1.id,
  1689. )
  1690. tree2 = Tree()
  1691. blob2 = Blob.from_string(b"Modified content\n")
  1692. self.repo.object_store.add_object(blob2)
  1693. tree2.add(b"file.txt", 0o100644, blob2.id)
  1694. self.repo.object_store.add_object(tree2)
  1695. self.repo.get_worktree().commit(
  1696. message=b"Modify file.txt",
  1697. tree=tree2.id,
  1698. )
  1699. # Mock stdout as a BytesIO for binary output
  1700. stdout_stream = io.BytesIO()
  1701. stdout_stream.buffer = stdout_stream
  1702. # Run command with --stdout
  1703. old_stdout = sys.stdout
  1704. old_stderr = sys.stderr
  1705. old_cwd = os.getcwd()
  1706. try:
  1707. sys.stdout = stdout_stream
  1708. sys.stderr = io.StringIO()
  1709. os.chdir(self.repo_path)
  1710. cli.main(["format-patch", "--stdout", "-n", "1"])
  1711. finally:
  1712. sys.stdout = old_stdout
  1713. sys.stderr = old_stderr
  1714. os.chdir(old_cwd)
  1715. # Check output
  1716. stdout_stream.seek(0)
  1717. output = stdout_stream.read()
  1718. self.assertIn(b"Subject: [PATCH 1/1] Modify file.txt", output)
  1719. self.assertIn(b"diff --git a/file.txt b/file.txt", output)
  1720. self.assertIn(b"-Original content", output)
  1721. self.assertIn(b"+Modified content", output)
  1722. self.assertIn(b"-- \nDulwich", output)
  1723. def test_format_patch_empty_repo(self):
  1724. # Test with empty repository
  1725. result, stdout, _stderr = self._run_cli("format-patch", "-n", "5")
  1726. self.assertEqual(result, None)
  1727. # Should produce no output for empty repo
  1728. self.assertEqual(stdout.strip(), "")
  1729. class FetchPackCommandTest(DulwichCliTestCase):
  1730. """Tests for fetch-pack command."""
  1731. @patch("dulwich.cli.get_transport_and_path")
  1732. def test_fetch_pack_basic(self, mock_transport):
  1733. # Mock the transport
  1734. mock_client = MagicMock()
  1735. mock_transport.return_value = (mock_client, "/path/to/repo")
  1736. mock_client.fetch.return_value = None
  1737. _result, _stdout, _stderr = self._run_cli(
  1738. "fetch-pack", "git://example.com/repo.git"
  1739. )
  1740. mock_client.fetch.assert_called_once()
  1741. class LsRemoteCommandTest(DulwichCliTestCase):
  1742. """Tests for ls-remote command."""
  1743. def test_ls_remote_basic(self):
  1744. # Create a commit
  1745. test_file = os.path.join(self.repo_path, "test.txt")
  1746. with open(test_file, "w") as f:
  1747. f.write("test")
  1748. self._run_cli("add", "test.txt")
  1749. self._run_cli("commit", "--message=Initial")
  1750. # Test basic ls-remote
  1751. _result, stdout, _stderr = self._run_cli("ls-remote", self.repo_path)
  1752. lines = stdout.strip().split("\n")
  1753. self.assertTrue(any("HEAD" in line for line in lines))
  1754. self.assertTrue(any("refs/heads/master" in line for line in lines))
  1755. def test_ls_remote_symref(self):
  1756. # Create a commit
  1757. test_file = os.path.join(self.repo_path, "test.txt")
  1758. with open(test_file, "w") as f:
  1759. f.write("test")
  1760. self._run_cli("add", "test.txt")
  1761. self._run_cli("commit", "--message=Initial")
  1762. # Test ls-remote with --symref option
  1763. _result, stdout, _stderr = self._run_cli(
  1764. "ls-remote", "--symref", self.repo_path
  1765. )
  1766. lines = stdout.strip().split("\n")
  1767. # Should show symref for HEAD in exact format: "ref: refs/heads/master\tHEAD"
  1768. expected_line = "ref: refs/heads/master\tHEAD"
  1769. self.assertIn(
  1770. expected_line,
  1771. lines,
  1772. f"Expected line '{expected_line}' not found in output: {lines}",
  1773. )
  1774. class PullCommandTest(DulwichCliTestCase):
  1775. """Tests for pull command."""
  1776. @patch("dulwich.porcelain.pull")
  1777. def test_pull_basic(self, mock_pull):
  1778. _result, _stdout, _stderr = self._run_cli("pull", "origin")
  1779. mock_pull.assert_called_once()
  1780. @patch("dulwich.porcelain.pull")
  1781. def test_pull_with_refspec(self, mock_pull):
  1782. _result, _stdout, _stderr = self._run_cli("pull", "origin", "master")
  1783. mock_pull.assert_called_once()
  1784. class PushCommandTest(DulwichCliTestCase):
  1785. """Tests for push command."""
  1786. @patch("dulwich.porcelain.push")
  1787. def test_push_basic(self, mock_push):
  1788. _result, _stdout, _stderr = self._run_cli("push", "origin")
  1789. mock_push.assert_called_once()
  1790. @patch("dulwich.porcelain.push")
  1791. def test_push_force(self, mock_push):
  1792. _result, _stdout, _stderr = self._run_cli("push", "-f", "origin")
  1793. mock_push.assert_called_with(".", "origin", None, force=True)
  1794. class ArchiveCommandTest(DulwichCliTestCase):
  1795. """Tests for archive command."""
  1796. def test_archive_basic(self):
  1797. # Create a commit
  1798. test_file = os.path.join(self.repo_path, "test.txt")
  1799. with open(test_file, "w") as f:
  1800. f.write("test content")
  1801. self._run_cli("add", "test.txt")
  1802. self._run_cli("commit", "--message=Initial")
  1803. # Archive produces binary output, so use BytesIO
  1804. _result, stdout, _stderr = self._run_cli(
  1805. "archive", "HEAD", stdout_stream=io.BytesIO()
  1806. )
  1807. # Should complete without error and produce some binary output
  1808. self.assertIsInstance(stdout, bytes)
  1809. self.assertGreater(len(stdout), 0)
  1810. class ForEachRefCommandTest(DulwichCliTestCase):
  1811. """Tests for for-each-ref command."""
  1812. def test_for_each_ref(self):
  1813. # Create a commit
  1814. test_file = os.path.join(self.repo_path, "test.txt")
  1815. with open(test_file, "w") as f:
  1816. f.write("test")
  1817. self._run_cli("add", "test.txt")
  1818. self._run_cli("commit", "--message=Initial")
  1819. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1820. _result, _stdout, _stderr = self._run_cli("for-each-ref")
  1821. log_output = "\n".join(cm.output)
  1822. # Just check that we have some refs output and it contains refs/heads
  1823. self.assertTrue(len(cm.output) > 0, "Expected some ref output")
  1824. self.assertIn("refs/heads/", log_output)
  1825. class PackRefsCommandTest(DulwichCliTestCase):
  1826. """Tests for pack-refs command."""
  1827. def test_pack_refs(self):
  1828. # Create some refs
  1829. test_file = os.path.join(self.repo_path, "test.txt")
  1830. with open(test_file, "w") as f:
  1831. f.write("test")
  1832. self._run_cli("add", "test.txt")
  1833. self._run_cli("commit", "--message=Initial")
  1834. self._run_cli("branch", "test-branch")
  1835. _result, _stdout, _stderr = self._run_cli("pack-refs", "--all")
  1836. # Check that packed-refs file exists
  1837. self.assertTrue(
  1838. os.path.exists(os.path.join(self.repo_path, ".git", "packed-refs"))
  1839. )
  1840. class SubmoduleCommandTest(DulwichCliTestCase):
  1841. """Tests for submodule commands."""
  1842. def test_submodule_list(self):
  1843. # Create an initial commit so repo has a HEAD
  1844. test_file = os.path.join(self.repo_path, "test.txt")
  1845. with open(test_file, "w") as f:
  1846. f.write("test")
  1847. self._run_cli("add", "test.txt")
  1848. self._run_cli("commit", "--message=Initial")
  1849. _result, _stdout, _stderr = self._run_cli("submodule")
  1850. # Should not crash on repo without submodules
  1851. def test_submodule_init(self):
  1852. # Create .gitmodules file for init to work
  1853. gitmodules = os.path.join(self.repo_path, ".gitmodules")
  1854. with open(gitmodules, "w") as f:
  1855. f.write("") # Empty .gitmodules file
  1856. _result, _stdout, _stderr = self._run_cli("submodule", "init")
  1857. # Should not crash
  1858. class StashCommandTest(DulwichCliTestCase):
  1859. """Tests for stash commands."""
  1860. def test_stash_list_empty(self):
  1861. _result, _stdout, _stderr = self._run_cli("stash", "list")
  1862. # Should not crash on empty stash
  1863. def test_stash_push_pop(self):
  1864. # Create a file and modify it
  1865. test_file = os.path.join(self.repo_path, "test.txt")
  1866. with open(test_file, "w") as f:
  1867. f.write("initial")
  1868. self._run_cli("add", "test.txt")
  1869. self._run_cli("commit", "--message=Initial")
  1870. # Modify file
  1871. with open(test_file, "w") as f:
  1872. f.write("modified")
  1873. # Stash changes
  1874. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1875. _result, _stdout, _stderr = self._run_cli("stash", "push")
  1876. self.assertIn("Saved working directory", cm.output[0])
  1877. # Note: Dulwich stash doesn't currently update the working tree
  1878. # so the file remains modified after stash push
  1879. # Note: stash pop is not fully implemented in Dulwich yet
  1880. # so we only test stash push here
  1881. class MergeCommandTest(DulwichCliTestCase):
  1882. """Tests for merge command."""
  1883. def test_merge_basic(self):
  1884. # Create initial commit
  1885. test_file = os.path.join(self.repo_path, "test.txt")
  1886. with open(test_file, "w") as f:
  1887. f.write("initial")
  1888. self._run_cli("add", "test.txt")
  1889. self._run_cli("commit", "--message=Initial")
  1890. # Create and checkout new branch
  1891. self._run_cli("branch", "feature")
  1892. self._run_cli("checkout", "feature")
  1893. # Make changes in feature branch
  1894. with open(test_file, "w") as f:
  1895. f.write("feature changes")
  1896. self._run_cli("add", "test.txt")
  1897. self._run_cli("commit", "--message=Feature commit")
  1898. # Go back to main
  1899. self._run_cli("checkout", "master")
  1900. # Merge feature branch
  1901. _result, _stdout, _stderr = self._run_cli("merge", "feature")
  1902. class HelpCommandTest(DulwichCliTestCase):
  1903. """Tests for help command."""
  1904. def test_help_basic(self):
  1905. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1906. _result, _stdout, _stderr = self._run_cli("help")
  1907. log_output = "\n".join(cm.output)
  1908. self.assertIn("dulwich command line tool", log_output)
  1909. def test_help_all(self):
  1910. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1911. _result, _stdout, _stderr = self._run_cli("help", "-a")
  1912. log_output = "\n".join(cm.output)
  1913. self.assertIn("Available commands:", log_output)
  1914. self.assertIn("add", log_output)
  1915. self.assertIn("commit", log_output)
  1916. class RemoteCommandTest(DulwichCliTestCase):
  1917. """Tests for remote commands."""
  1918. def test_remote_add(self):
  1919. _result, _stdout, _stderr = self._run_cli(
  1920. "remote", "add", "origin", "https://github.com/example/repo.git"
  1921. )
  1922. # Check remote was added to config
  1923. config = self.repo.get_config()
  1924. self.assertEqual(
  1925. config.get((b"remote", b"origin"), b"url"),
  1926. b"https://github.com/example/repo.git",
  1927. )
  1928. class CheckIgnoreCommandTest(DulwichCliTestCase):
  1929. """Tests for check-ignore command."""
  1930. def test_check_ignore(self):
  1931. # Create .gitignore
  1932. gitignore = os.path.join(self.repo_path, ".gitignore")
  1933. with open(gitignore, "w") as f:
  1934. f.write("*.log\n")
  1935. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1936. _result, _stdout, _stderr = self._run_cli(
  1937. "check-ignore", "test.log", "test.txt"
  1938. )
  1939. log_output = "\n".join(cm.output)
  1940. self.assertIn("test.log", log_output)
  1941. self.assertNotIn("test.txt", log_output)
  1942. class LsFilesCommandTest(DulwichCliTestCase):
  1943. """Tests for ls-files command."""
  1944. def test_ls_files(self):
  1945. # Add some files
  1946. for name in ["a.txt", "b.txt", "c.txt"]:
  1947. path = os.path.join(self.repo_path, name)
  1948. with open(path, "w") as f:
  1949. f.write(f"content of {name}")
  1950. self._run_cli("add", "a.txt", "b.txt", "c.txt")
  1951. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1952. _result, _stdout, _stderr = self._run_cli("ls-files")
  1953. log_output = "\n".join(cm.output)
  1954. self.assertIn("a.txt", log_output)
  1955. self.assertIn("b.txt", log_output)
  1956. self.assertIn("c.txt", log_output)
  1957. class LsTreeCommandTest(DulwichCliTestCase):
  1958. """Tests for ls-tree command."""
  1959. def test_ls_tree(self):
  1960. # Create a directory structure
  1961. os.mkdir(os.path.join(self.repo_path, "subdir"))
  1962. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  1963. f.write("file content")
  1964. with open(os.path.join(self.repo_path, "subdir", "nested.txt"), "w") as f:
  1965. f.write("nested content")
  1966. self._run_cli("add", ".")
  1967. self._run_cli("commit", "--message=Initial")
  1968. _result, stdout, _stderr = self._run_cli("ls-tree", "HEAD")
  1969. self.assertIn("file.txt", stdout)
  1970. self.assertIn("subdir", stdout)
  1971. def test_ls_tree_recursive(self):
  1972. # Create nested structure
  1973. os.mkdir(os.path.join(self.repo_path, "subdir"))
  1974. with open(os.path.join(self.repo_path, "subdir", "nested.txt"), "w") as f:
  1975. f.write("nested")
  1976. self._run_cli("add", ".")
  1977. self._run_cli("commit", "--message=Initial")
  1978. _result, stdout, _stderr = self._run_cli("ls-tree", "-r", "HEAD")
  1979. self.assertIn("subdir/nested.txt", stdout)
  1980. class DescribeCommandTest(DulwichCliTestCase):
  1981. """Tests for describe command."""
  1982. def test_describe(self):
  1983. # Create tagged commit
  1984. test_file = os.path.join(self.repo_path, "test.txt")
  1985. with open(test_file, "w") as f:
  1986. f.write("test")
  1987. self._run_cli("add", "test.txt")
  1988. self._run_cli("commit", "--message=Initial")
  1989. self._run_cli("tag", "v1.0")
  1990. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1991. _result, _stdout, _stderr = self._run_cli("describe")
  1992. self.assertIn("v1.0", cm.output[0])
  1993. class FsckCommandTest(DulwichCliTestCase):
  1994. """Tests for fsck command."""
  1995. def test_fsck(self):
  1996. # Create a commit
  1997. test_file = os.path.join(self.repo_path, "test.txt")
  1998. with open(test_file, "w") as f:
  1999. f.write("test")
  2000. self._run_cli("add", "test.txt")
  2001. self._run_cli("commit", "--message=Initial")
  2002. _result, _stdout, _stderr = self._run_cli("fsck")
  2003. # Should complete without errors
  2004. class GrepCommandTest(DulwichCliTestCase):
  2005. """Tests for grep command."""
  2006. def test_grep_basic(self):
  2007. # Create test files
  2008. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  2009. f.write("hello world\n")
  2010. with open(os.path.join(self.repo_path, "file2.txt"), "w") as f:
  2011. f.write("foo bar\n")
  2012. self._run_cli("add", "file1.txt", "file2.txt")
  2013. self._run_cli("commit", "--message=Add files")
  2014. _result, stdout, _stderr = self._run_cli("grep", "world")
  2015. self.assertEqual("file1.txt:hello world\n", stdout.replace("\r\n", "\n"))
  2016. def test_grep_line_numbers(self):
  2017. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  2018. f.write("line1\nline2\nline3\n")
  2019. self._run_cli("add", "test.txt")
  2020. self._run_cli("commit", "--message=Add test")
  2021. _result, stdout, _stderr = self._run_cli("grep", "-n", "line")
  2022. self.assertEqual(
  2023. "test.txt:1:line1\ntest.txt:2:line2\ntest.txt:3:line3\n",
  2024. stdout.replace("\r\n", "\n"),
  2025. )
  2026. def test_grep_case_insensitive(self):
  2027. with open(os.path.join(self.repo_path, "case.txt"), "w") as f:
  2028. f.write("Hello World\n")
  2029. self._run_cli("add", "case.txt")
  2030. self._run_cli("commit", "--message=Add case")
  2031. _result, stdout, _stderr = self._run_cli("grep", "-i", "hello")
  2032. self.assertEqual("case.txt:Hello World\n", stdout.replace("\r\n", "\n"))
  2033. def test_grep_no_matches(self):
  2034. with open(os.path.join(self.repo_path, "empty.txt"), "w") as f:
  2035. f.write("nothing here\n")
  2036. self._run_cli("add", "empty.txt")
  2037. self._run_cli("commit", "--message=Add empty")
  2038. _result, stdout, _stderr = self._run_cli("grep", "nonexistent")
  2039. self.assertEqual("", stdout)
  2040. class RepackCommandTest(DulwichCliTestCase):
  2041. """Tests for repack command."""
  2042. def test_repack(self):
  2043. # Create some objects
  2044. for i in range(5):
  2045. test_file = os.path.join(self.repo_path, f"test{i}.txt")
  2046. with open(test_file, "w") as f:
  2047. f.write(f"content {i}")
  2048. self._run_cli("add", f"test{i}.txt")
  2049. self._run_cli("commit", f"--message=Commit {i}")
  2050. _result, _stdout, _stderr = self._run_cli("repack")
  2051. # Should create pack files
  2052. pack_dir = os.path.join(self.repo_path, ".git", "objects", "pack")
  2053. self.assertTrue(any(f.endswith(".pack") for f in os.listdir(pack_dir)))
  2054. class ResetCommandTest(DulwichCliTestCase):
  2055. """Tests for reset command."""
  2056. def test_reset_soft(self):
  2057. # Create commits
  2058. test_file = os.path.join(self.repo_path, "test.txt")
  2059. with open(test_file, "w") as f:
  2060. f.write("first")
  2061. self._run_cli("add", "test.txt")
  2062. self._run_cli("commit", "--message=First")
  2063. first_commit = self.repo.head()
  2064. with open(test_file, "w") as f:
  2065. f.write("second")
  2066. self._run_cli("add", "test.txt")
  2067. self._run_cli("commit", "--message=Second")
  2068. # Reset soft
  2069. _result, _stdout, _stderr = self._run_cli(
  2070. "reset", "--soft", first_commit.decode()
  2071. )
  2072. # HEAD should be at first commit
  2073. self.assertEqual(self.repo.head(), first_commit)
  2074. class WriteTreeCommandTest(DulwichCliTestCase):
  2075. """Tests for write-tree command."""
  2076. def test_write_tree(self):
  2077. # Create and add files
  2078. test_file = os.path.join(self.repo_path, "test.txt")
  2079. with open(test_file, "w") as f:
  2080. f.write("test")
  2081. self._run_cli("add", "test.txt")
  2082. _result, stdout, _stderr = self._run_cli("write-tree")
  2083. # Should output tree SHA
  2084. self.assertEqual(len(stdout.strip()), 40)
  2085. class UpdateServerInfoCommandTest(DulwichCliTestCase):
  2086. """Tests for update-server-info command."""
  2087. def test_update_server_info(self):
  2088. _result, _stdout, _stderr = self._run_cli("update-server-info")
  2089. # Should create info/refs file
  2090. info_refs = os.path.join(self.repo_path, ".git", "info", "refs")
  2091. self.assertTrue(os.path.exists(info_refs))
  2092. class SymbolicRefCommandTest(DulwichCliTestCase):
  2093. """Tests for symbolic-ref command."""
  2094. def test_symbolic_ref(self):
  2095. # Create a branch
  2096. test_file = os.path.join(self.repo_path, "test.txt")
  2097. with open(test_file, "w") as f:
  2098. f.write("test")
  2099. self._run_cli("add", "test.txt")
  2100. self._run_cli("commit", "--message=Initial")
  2101. self._run_cli("branch", "test-branch")
  2102. _result, _stdout, _stderr = self._run_cli(
  2103. "symbolic-ref", "HEAD", "refs/heads/test-branch"
  2104. )
  2105. # HEAD should now point to test-branch
  2106. self.assertEqual(
  2107. self.repo.refs.read_ref(b"HEAD"), b"ref: refs/heads/test-branch"
  2108. )
  2109. class BundleCommandTest(DulwichCliTestCase):
  2110. """Tests for bundle commands."""
  2111. def setUp(self):
  2112. super().setUp()
  2113. # Create a basic repository with some commits for bundle testing
  2114. # Create initial commit
  2115. test_file = os.path.join(self.repo_path, "file1.txt")
  2116. with open(test_file, "w") as f:
  2117. f.write("Content of file1\n")
  2118. self._run_cli("add", "file1.txt")
  2119. self._run_cli("commit", "--message=Initial commit")
  2120. # Create second commit
  2121. test_file2 = os.path.join(self.repo_path, "file2.txt")
  2122. with open(test_file2, "w") as f:
  2123. f.write("Content of file2\n")
  2124. self._run_cli("add", "file2.txt")
  2125. self._run_cli("commit", "--message=Add file2")
  2126. # Create a branch and tag for testing
  2127. self._run_cli("branch", "feature")
  2128. self._run_cli("tag", "v1.0")
  2129. def test_bundle_create_basic(self):
  2130. """Test basic bundle creation."""
  2131. bundle_file = os.path.join(self.test_dir, "test.bundle")
  2132. result, _stdout, _stderr = self._run_cli(
  2133. "bundle", "create", bundle_file, "HEAD"
  2134. )
  2135. self.assertEqual(result, 0)
  2136. self.assertTrue(os.path.exists(bundle_file))
  2137. self.assertGreater(os.path.getsize(bundle_file), 0)
  2138. def test_bundle_create_all_refs(self):
  2139. """Test bundle creation with --all flag."""
  2140. bundle_file = os.path.join(self.test_dir, "all.bundle")
  2141. result, _stdout, _stderr = self._run_cli(
  2142. "bundle", "create", "--all", bundle_file
  2143. )
  2144. self.assertEqual(result, 0)
  2145. self.assertTrue(os.path.exists(bundle_file))
  2146. def test_bundle_create_specific_refs(self):
  2147. """Test bundle creation with specific refs."""
  2148. bundle_file = os.path.join(self.test_dir, "refs.bundle")
  2149. # Only use HEAD since feature branch may not exist
  2150. result, _stdout, _stderr = self._run_cli(
  2151. "bundle", "create", bundle_file, "HEAD"
  2152. )
  2153. self.assertEqual(result, 0)
  2154. self.assertTrue(os.path.exists(bundle_file))
  2155. def test_bundle_create_with_range(self):
  2156. """Test bundle creation with commit range."""
  2157. # Get the first commit SHA by looking at the log
  2158. result, stdout, _stderr = self._run_cli("log", "--reverse")
  2159. lines = stdout.strip().split("\n")
  2160. # Find first commit line that contains a SHA
  2161. first_commit = None
  2162. for line in lines:
  2163. if line.startswith("commit "):
  2164. first_commit = line.split()[1][:8] # Get short SHA
  2165. break
  2166. if first_commit:
  2167. bundle_file = os.path.join(self.test_dir, "range.bundle")
  2168. result, stdout, _stderr = self._run_cli(
  2169. "bundle", "create", bundle_file, f"{first_commit}..HEAD"
  2170. )
  2171. self.assertEqual(result, 0)
  2172. self.assertTrue(os.path.exists(bundle_file))
  2173. else:
  2174. self.skipTest("Could not determine first commit SHA")
  2175. def test_bundle_create_to_stdout(self):
  2176. """Test bundle creation to stdout."""
  2177. result, stdout, _stderr = self._run_cli("bundle", "create", "-", "HEAD")
  2178. self.assertEqual(result, 0)
  2179. self.assertGreater(len(stdout), 0)
  2180. # Bundle output is binary, so check it's not empty
  2181. self.assertIsInstance(stdout, (str, bytes))
  2182. def test_bundle_create_no_refs(self):
  2183. """Test bundle creation with no refs specified."""
  2184. bundle_file = os.path.join(self.test_dir, "noref.bundle")
  2185. with self.assertLogs("dulwich.cli", level="ERROR") as cm:
  2186. result, _stdout, _stderr = self._run_cli("bundle", "create", bundle_file)
  2187. self.assertEqual(result, 1)
  2188. self.assertIn("No refs specified", cm.output[0])
  2189. def test_bundle_create_empty_bundle_refused(self):
  2190. """Test that empty bundles are refused."""
  2191. bundle_file = os.path.join(self.test_dir, "empty.bundle")
  2192. # Try to create bundle with non-existent ref - this should fail with KeyError
  2193. with self.assertRaises(KeyError):
  2194. _result, _stdout, _stderr = self._run_cli(
  2195. "bundle", "create", bundle_file, "nonexistent-ref"
  2196. )
  2197. def test_bundle_verify_valid(self):
  2198. """Test bundle verification of valid bundle."""
  2199. bundle_file = os.path.join(self.test_dir, "valid.bundle")
  2200. # First create a bundle
  2201. result, _stdout, _stderr = self._run_cli(
  2202. "bundle", "create", bundle_file, "HEAD"
  2203. )
  2204. self.assertEqual(result, 0)
  2205. # Now verify it
  2206. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2207. result, _stdout, _stderr = self._run_cli("bundle", "verify", bundle_file)
  2208. self.assertEqual(result, 0)
  2209. self.assertIn("valid and can be applied", cm.output[0])
  2210. def test_bundle_verify_quiet(self):
  2211. """Test bundle verification with quiet flag."""
  2212. bundle_file = os.path.join(self.test_dir, "quiet.bundle")
  2213. # Create bundle
  2214. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2215. # Verify quietly
  2216. result, stdout, _stderr = self._run_cli(
  2217. "bundle", "verify", "--quiet", bundle_file
  2218. )
  2219. self.assertEqual(result, 0)
  2220. self.assertEqual(stdout.strip(), "")
  2221. def test_bundle_verify_from_stdin(self):
  2222. """Test bundle verification from stdin."""
  2223. bundle_file = os.path.join(self.test_dir, "stdin.bundle")
  2224. # Create bundle
  2225. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2226. # Read bundle content
  2227. with open(bundle_file, "rb") as f:
  2228. bundle_content = f.read()
  2229. # Mock stdin with bundle content
  2230. old_stdin = sys.stdin
  2231. try:
  2232. sys.stdin = io.BytesIO(bundle_content)
  2233. sys.stdin.buffer = sys.stdin
  2234. result, _stdout, _stderr = self._run_cli("bundle", "verify", "-")
  2235. self.assertEqual(result, 0)
  2236. finally:
  2237. sys.stdin = old_stdin
  2238. def test_bundle_list_heads(self):
  2239. """Test listing bundle heads."""
  2240. bundle_file = os.path.join(self.test_dir, "heads.bundle")
  2241. # Create bundle with HEAD only
  2242. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2243. # List heads
  2244. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2245. result, _stdout, _stderr = self._run_cli(
  2246. "bundle", "list-heads", bundle_file
  2247. )
  2248. self.assertEqual(result, 0)
  2249. # Should contain at least the HEAD reference
  2250. self.assertTrue(len(cm.output) > 0)
  2251. def test_bundle_list_heads_specific_refs(self):
  2252. """Test listing specific bundle heads."""
  2253. bundle_file = os.path.join(self.test_dir, "specific.bundle")
  2254. # Create bundle with HEAD
  2255. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2256. # List heads without filtering
  2257. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2258. result, _stdout, _stderr = self._run_cli(
  2259. "bundle", "list-heads", bundle_file
  2260. )
  2261. self.assertEqual(result, 0)
  2262. # Should contain some reference
  2263. self.assertTrue(len(cm.output) > 0)
  2264. def test_bundle_list_heads_from_stdin(self):
  2265. """Test listing bundle heads from stdin."""
  2266. bundle_file = os.path.join(self.test_dir, "stdin-heads.bundle")
  2267. # Create bundle
  2268. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2269. # Read bundle content
  2270. with open(bundle_file, "rb") as f:
  2271. bundle_content = f.read()
  2272. # Mock stdin
  2273. old_stdin = sys.stdin
  2274. try:
  2275. sys.stdin = io.BytesIO(bundle_content)
  2276. sys.stdin.buffer = sys.stdin
  2277. result, _stdout, _stderr = self._run_cli("bundle", "list-heads", "-")
  2278. self.assertEqual(result, 0)
  2279. finally:
  2280. sys.stdin = old_stdin
  2281. def test_bundle_unbundle(self):
  2282. """Test bundle unbundling."""
  2283. bundle_file = os.path.join(self.test_dir, "unbundle.bundle")
  2284. # Create bundle
  2285. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2286. # Unbundle
  2287. result, _stdout, _stderr = self._run_cli("bundle", "unbundle", bundle_file)
  2288. self.assertEqual(result, 0)
  2289. def test_bundle_unbundle_specific_refs(self):
  2290. """Test unbundling specific refs."""
  2291. bundle_file = os.path.join(self.test_dir, "unbundle-specific.bundle")
  2292. # Create bundle with HEAD
  2293. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2294. # Unbundle only HEAD
  2295. result, _stdout, _stderr = self._run_cli(
  2296. "bundle", "unbundle", bundle_file, "HEAD"
  2297. )
  2298. self.assertEqual(result, 0)
  2299. def test_bundle_unbundle_from_stdin(self):
  2300. """Test unbundling from stdin."""
  2301. bundle_file = os.path.join(self.test_dir, "stdin-unbundle.bundle")
  2302. # Create bundle
  2303. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2304. # Read bundle content to simulate stdin
  2305. with open(bundle_file, "rb") as f:
  2306. bundle_content = f.read()
  2307. # Mock stdin with bundle content
  2308. old_stdin = sys.stdin
  2309. try:
  2310. # Create a BytesIO object with buffer attribute
  2311. mock_stdin = io.BytesIO(bundle_content)
  2312. mock_stdin.buffer = mock_stdin
  2313. sys.stdin = mock_stdin
  2314. result, _stdout, _stderr = self._run_cli("bundle", "unbundle", "-")
  2315. self.assertEqual(result, 0)
  2316. finally:
  2317. sys.stdin = old_stdin
  2318. def test_bundle_unbundle_with_progress(self):
  2319. """Test unbundling with progress output."""
  2320. bundle_file = os.path.join(self.test_dir, "progress.bundle")
  2321. # Create bundle
  2322. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2323. # Unbundle with progress
  2324. result, _stdout, _stderr = self._run_cli(
  2325. "bundle", "unbundle", "--progress", bundle_file
  2326. )
  2327. self.assertEqual(result, 0)
  2328. def test_bundle_create_with_progress(self):
  2329. """Test bundle creation with progress output."""
  2330. bundle_file = os.path.join(self.test_dir, "create-progress.bundle")
  2331. result, _stdout, _stderr = self._run_cli(
  2332. "bundle", "create", "--progress", bundle_file, "HEAD"
  2333. )
  2334. self.assertEqual(result, 0)
  2335. self.assertTrue(os.path.exists(bundle_file))
  2336. def test_bundle_create_with_quiet(self):
  2337. """Test bundle creation with quiet flag."""
  2338. bundle_file = os.path.join(self.test_dir, "quiet-create.bundle")
  2339. result, _stdout, _stderr = self._run_cli(
  2340. "bundle", "create", "--quiet", bundle_file, "HEAD"
  2341. )
  2342. self.assertEqual(result, 0)
  2343. self.assertTrue(os.path.exists(bundle_file))
  2344. def test_bundle_create_version_2(self):
  2345. """Test bundle creation with specific version."""
  2346. bundle_file = os.path.join(self.test_dir, "v2.bundle")
  2347. result, _stdout, _stderr = self._run_cli(
  2348. "bundle", "create", "--version", "2", bundle_file, "HEAD"
  2349. )
  2350. self.assertEqual(result, 0)
  2351. self.assertTrue(os.path.exists(bundle_file))
  2352. def test_bundle_create_version_3(self):
  2353. """Test bundle creation with version 3."""
  2354. bundle_file = os.path.join(self.test_dir, "v3.bundle")
  2355. result, _stdout, _stderr = self._run_cli(
  2356. "bundle", "create", "--version", "3", bundle_file, "HEAD"
  2357. )
  2358. self.assertEqual(result, 0)
  2359. self.assertTrue(os.path.exists(bundle_file))
  2360. def test_bundle_invalid_subcommand(self):
  2361. """Test invalid bundle subcommand."""
  2362. with self.assertLogs("dulwich.cli", level="ERROR") as cm:
  2363. result, _stdout, _stderr = self._run_cli("bundle", "invalid-command")
  2364. self.assertEqual(result, 1)
  2365. self.assertIn("Unknown bundle subcommand", cm.output[0])
  2366. def test_bundle_no_subcommand(self):
  2367. """Test bundle command with no subcommand."""
  2368. with self.assertLogs("dulwich.cli", level="ERROR") as cm:
  2369. result, _stdout, _stderr = self._run_cli("bundle")
  2370. self.assertEqual(result, 1)
  2371. self.assertIn("Usage: bundle", cm.output[0])
  2372. def test_bundle_create_with_stdin_refs(self):
  2373. """Test bundle creation reading refs from stdin."""
  2374. bundle_file = os.path.join(self.test_dir, "stdin-refs.bundle")
  2375. # Mock stdin with refs
  2376. old_stdin = sys.stdin
  2377. try:
  2378. sys.stdin = io.StringIO("master\nfeature\n")
  2379. result, _stdout, _stderr = self._run_cli(
  2380. "bundle", "create", "--stdin", bundle_file
  2381. )
  2382. self.assertEqual(result, 0)
  2383. self.assertTrue(os.path.exists(bundle_file))
  2384. finally:
  2385. sys.stdin = old_stdin
  2386. def test_bundle_verify_missing_prerequisites(self):
  2387. """Test bundle verification with missing prerequisites."""
  2388. # Create a simple bundle first
  2389. bundle_file = os.path.join(self.test_dir, "prereq.bundle")
  2390. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2391. # Create a new repo to simulate missing objects
  2392. new_repo_path = os.path.join(self.test_dir, "new_repo")
  2393. os.mkdir(new_repo_path)
  2394. new_repo = Repo.init(new_repo_path)
  2395. new_repo.close()
  2396. # Try to verify in new repo
  2397. old_cwd = os.getcwd()
  2398. try:
  2399. os.chdir(new_repo_path)
  2400. result, _stdout, _stderr = self._run_cli("bundle", "verify", bundle_file)
  2401. # Just check that verification runs - result depends on bundle content
  2402. self.assertIn(result, [0, 1])
  2403. finally:
  2404. os.chdir(old_cwd)
  2405. def test_bundle_create_with_committish_range(self):
  2406. """Test bundle creation with commit range using parse_committish_range."""
  2407. # Create additional commits for range testing
  2408. test_file3 = os.path.join(self.repo_path, "file3.txt")
  2409. with open(test_file3, "w") as f:
  2410. f.write("Content of file3\n")
  2411. self._run_cli("add", "file3.txt")
  2412. self._run_cli("commit", "--message=Add file3")
  2413. # Get commit SHAs
  2414. result, stdout, _stderr = self._run_cli("log")
  2415. lines = stdout.strip().split("\n")
  2416. # Extract SHAs from commit lines
  2417. commits = []
  2418. for line in lines:
  2419. if line.startswith("commit:"):
  2420. sha = line.split()[1]
  2421. commits.append(sha[:8]) # Get short SHA
  2422. # We should have exactly 3 commits: Add file3, Add file2, Initial commit
  2423. self.assertEqual(len(commits), 3)
  2424. bundle_file = os.path.join(self.test_dir, "range-test.bundle")
  2425. # Test with commit range using .. syntax
  2426. # Create a bundle containing commits reachable from commits[0] but not from commits[2]
  2427. result, stdout, stderr = self._run_cli(
  2428. "bundle", "create", bundle_file, f"{commits[2]}..HEAD"
  2429. )
  2430. if result != 0:
  2431. self.fail(
  2432. f"Bundle create failed with exit code {result}. stdout: {stdout!r}, stderr: {stderr!r}"
  2433. )
  2434. self.assertEqual(result, 0)
  2435. self.assertTrue(os.path.exists(bundle_file))
  2436. # Verify the bundle was created
  2437. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2438. result, stdout, stderr = self._run_cli("bundle", "verify", bundle_file)
  2439. self.assertEqual(result, 0)
  2440. self.assertIn("valid and can be applied", cm.output[0])
  2441. class FormatBytesTestCase(TestCase):
  2442. """Tests for format_bytes function."""
  2443. def test_bytes(self):
  2444. """Test formatting bytes."""
  2445. self.assertEqual("0.0 B", format_bytes(0))
  2446. self.assertEqual("1.0 B", format_bytes(1))
  2447. self.assertEqual("512.0 B", format_bytes(512))
  2448. self.assertEqual("1023.0 B", format_bytes(1023))
  2449. def test_kilobytes(self):
  2450. """Test formatting kilobytes."""
  2451. self.assertEqual("1.0 KB", format_bytes(1024))
  2452. self.assertEqual("1.5 KB", format_bytes(1536))
  2453. self.assertEqual("2.0 KB", format_bytes(2048))
  2454. self.assertEqual("1023.0 KB", format_bytes(1024 * 1023))
  2455. def test_megabytes(self):
  2456. """Test formatting megabytes."""
  2457. self.assertEqual("1.0 MB", format_bytes(1024 * 1024))
  2458. self.assertEqual("1.5 MB", format_bytes(1024 * 1024 * 1.5))
  2459. self.assertEqual("10.0 MB", format_bytes(1024 * 1024 * 10))
  2460. self.assertEqual("1023.0 MB", format_bytes(1024 * 1024 * 1023))
  2461. def test_gigabytes(self):
  2462. """Test formatting gigabytes."""
  2463. self.assertEqual("1.0 GB", format_bytes(1024 * 1024 * 1024))
  2464. self.assertEqual("2.5 GB", format_bytes(1024 * 1024 * 1024 * 2.5))
  2465. self.assertEqual("1023.0 GB", format_bytes(1024 * 1024 * 1024 * 1023))
  2466. def test_terabytes(self):
  2467. """Test formatting terabytes."""
  2468. self.assertEqual("1.0 TB", format_bytes(1024 * 1024 * 1024 * 1024))
  2469. self.assertEqual("5.0 TB", format_bytes(1024 * 1024 * 1024 * 1024 * 5))
  2470. self.assertEqual("1000.0 TB", format_bytes(1024 * 1024 * 1024 * 1024 * 1000))
  2471. class ParseRelativeTimeTestCase(TestCase):
  2472. """Tests for parse_relative_time function."""
  2473. def test_now(self):
  2474. """Test parsing 'now'."""
  2475. self.assertEqual(0, parse_relative_time("now"))
  2476. def test_seconds(self):
  2477. """Test parsing seconds."""
  2478. self.assertEqual(1, parse_relative_time("1 second ago"))
  2479. self.assertEqual(5, parse_relative_time("5 seconds ago"))
  2480. self.assertEqual(30, parse_relative_time("30 seconds ago"))
  2481. def test_minutes(self):
  2482. """Test parsing minutes."""
  2483. self.assertEqual(60, parse_relative_time("1 minute ago"))
  2484. self.assertEqual(300, parse_relative_time("5 minutes ago"))
  2485. self.assertEqual(1800, parse_relative_time("30 minutes ago"))
  2486. def test_hours(self):
  2487. """Test parsing hours."""
  2488. self.assertEqual(3600, parse_relative_time("1 hour ago"))
  2489. self.assertEqual(7200, parse_relative_time("2 hours ago"))
  2490. self.assertEqual(86400, parse_relative_time("24 hours ago"))
  2491. def test_days(self):
  2492. """Test parsing days."""
  2493. self.assertEqual(86400, parse_relative_time("1 day ago"))
  2494. self.assertEqual(604800, parse_relative_time("7 days ago"))
  2495. self.assertEqual(2592000, parse_relative_time("30 days ago"))
  2496. def test_weeks(self):
  2497. """Test parsing weeks."""
  2498. self.assertEqual(604800, parse_relative_time("1 week ago"))
  2499. self.assertEqual(1209600, parse_relative_time("2 weeks ago"))
  2500. self.assertEqual(
  2501. 36288000, parse_relative_time("60 weeks ago")
  2502. ) # 60 * 7 * 24 * 60 * 60
  2503. def test_invalid_format(self):
  2504. """Test invalid time formats."""
  2505. with self.assertRaises(ValueError) as cm:
  2506. parse_relative_time("invalid")
  2507. self.assertIn("Invalid relative time format", str(cm.exception))
  2508. with self.assertRaises(ValueError) as cm:
  2509. parse_relative_time("2 weeks")
  2510. self.assertIn("Invalid relative time format", str(cm.exception))
  2511. with self.assertRaises(ValueError) as cm:
  2512. parse_relative_time("ago")
  2513. self.assertIn("Invalid relative time format", str(cm.exception))
  2514. with self.assertRaises(ValueError) as cm:
  2515. parse_relative_time("two weeks ago")
  2516. self.assertIn("Invalid number in relative time", str(cm.exception))
  2517. def test_invalid_unit(self):
  2518. """Test invalid time units."""
  2519. with self.assertRaises(ValueError) as cm:
  2520. parse_relative_time("5 fortnights ago")
  2521. self.assertIn("Unknown time unit: fortnights", str(cm.exception))
  2522. with self.assertRaises(ValueError) as cm:
  2523. parse_relative_time("2 decades ago")
  2524. self.assertIn("Unknown time unit: decades", str(cm.exception))
  2525. def test_singular_plural(self):
  2526. """Test that both singular and plural forms work."""
  2527. self.assertEqual(
  2528. parse_relative_time("1 second ago"), parse_relative_time("1 seconds ago")
  2529. )
  2530. self.assertEqual(
  2531. parse_relative_time("1 minute ago"), parse_relative_time("1 minutes ago")
  2532. )
  2533. self.assertEqual(
  2534. parse_relative_time("1 hour ago"), parse_relative_time("1 hours ago")
  2535. )
  2536. self.assertEqual(
  2537. parse_relative_time("1 day ago"), parse_relative_time("1 days ago")
  2538. )
  2539. self.assertEqual(
  2540. parse_relative_time("1 week ago"), parse_relative_time("1 weeks ago")
  2541. )
  2542. class GetPagerTest(TestCase):
  2543. """Tests for get_pager function."""
  2544. def setUp(self):
  2545. super().setUp()
  2546. # Save original environment
  2547. self.original_env = os.environ.copy()
  2548. # Clear pager-related environment variables
  2549. for var in ["DULWICH_PAGER", "GIT_PAGER", "PAGER"]:
  2550. os.environ.pop(var, None)
  2551. # Reset the global pager disable flag
  2552. cli.get_pager._disabled = False
  2553. def tearDown(self):
  2554. super().tearDown()
  2555. # Restore original environment
  2556. os.environ.clear()
  2557. os.environ.update(self.original_env)
  2558. # Reset the global pager disable flag
  2559. cli.get_pager._disabled = False
  2560. def test_pager_disabled_globally(self):
  2561. """Test that globally disabled pager returns stdout wrapper."""
  2562. cli.disable_pager()
  2563. pager = cli.get_pager()
  2564. self.assertIsInstance(pager, cli._StreamContextAdapter)
  2565. self.assertEqual(pager.stream, sys.stdout)
  2566. def test_pager_not_tty(self):
  2567. """Test that pager is disabled when stdout is not a TTY."""
  2568. with patch("sys.stdout.isatty", return_value=False):
  2569. pager = cli.get_pager()
  2570. self.assertIsInstance(pager, cli._StreamContextAdapter)
  2571. def test_pager_env_dulwich_pager(self):
  2572. """Test DULWICH_PAGER environment variable."""
  2573. os.environ["DULWICH_PAGER"] = "custom_pager"
  2574. with patch("sys.stdout.isatty", return_value=True):
  2575. pager = cli.get_pager()
  2576. self.assertIsInstance(pager, cli.Pager)
  2577. self.assertEqual(pager.pager_cmd, "custom_pager")
  2578. def test_pager_env_dulwich_pager_false(self):
  2579. """Test DULWICH_PAGER=false disables pager."""
  2580. os.environ["DULWICH_PAGER"] = "false"
  2581. with patch("sys.stdout.isatty", return_value=True):
  2582. pager = cli.get_pager()
  2583. self.assertIsInstance(pager, cli._StreamContextAdapter)
  2584. def test_pager_env_git_pager(self):
  2585. """Test GIT_PAGER environment variable."""
  2586. os.environ["GIT_PAGER"] = "git_custom_pager"
  2587. with patch("sys.stdout.isatty", return_value=True):
  2588. pager = cli.get_pager()
  2589. self.assertIsInstance(pager, cli.Pager)
  2590. self.assertEqual(pager.pager_cmd, "git_custom_pager")
  2591. def test_pager_env_pager(self):
  2592. """Test PAGER environment variable."""
  2593. os.environ["PAGER"] = "my_pager"
  2594. with patch("sys.stdout.isatty", return_value=True):
  2595. pager = cli.get_pager()
  2596. self.assertIsInstance(pager, cli.Pager)
  2597. self.assertEqual(pager.pager_cmd, "my_pager")
  2598. def test_pager_env_priority(self):
  2599. """Test environment variable priority order."""
  2600. os.environ["PAGER"] = "pager_low"
  2601. os.environ["GIT_PAGER"] = "pager_medium"
  2602. os.environ["DULWICH_PAGER"] = "pager_high"
  2603. with patch("sys.stdout.isatty", return_value=True):
  2604. pager = cli.get_pager()
  2605. self.assertEqual(pager.pager_cmd, "pager_high")
  2606. def test_pager_config_core_pager(self):
  2607. """Test core.pager configuration."""
  2608. config = MagicMock()
  2609. config.get.return_value = b"config_pager"
  2610. with patch("sys.stdout.isatty", return_value=True):
  2611. pager = cli.get_pager(config=config)
  2612. self.assertIsInstance(pager, cli.Pager)
  2613. self.assertEqual(pager.pager_cmd, "config_pager")
  2614. config.get.assert_called_with(("core",), b"pager")
  2615. def test_pager_config_core_pager_false(self):
  2616. """Test core.pager=false disables pager."""
  2617. config = MagicMock()
  2618. config.get.return_value = b"false"
  2619. with patch("sys.stdout.isatty", return_value=True):
  2620. pager = cli.get_pager(config=config)
  2621. self.assertIsInstance(pager, cli._StreamContextAdapter)
  2622. def test_pager_config_core_pager_empty(self):
  2623. """Test core.pager="" disables pager."""
  2624. config = MagicMock()
  2625. config.get.return_value = b""
  2626. with patch("sys.stdout.isatty", return_value=True):
  2627. pager = cli.get_pager(config=config)
  2628. self.assertIsInstance(pager, cli._StreamContextAdapter)
  2629. def test_pager_config_per_command(self):
  2630. """Test per-command pager configuration."""
  2631. config = MagicMock()
  2632. config.get.side_effect = lambda section, key: {
  2633. (("pager",), b"log"): b"log_pager",
  2634. }.get((section, key), KeyError())
  2635. with patch("sys.stdout.isatty", return_value=True):
  2636. pager = cli.get_pager(config=config, cmd_name="log")
  2637. self.assertIsInstance(pager, cli.Pager)
  2638. self.assertEqual(pager.pager_cmd, "log_pager")
  2639. def test_pager_config_per_command_false(self):
  2640. """Test per-command pager=false disables pager."""
  2641. config = MagicMock()
  2642. config.get.return_value = b"false"
  2643. with patch("sys.stdout.isatty", return_value=True):
  2644. pager = cli.get_pager(config=config, cmd_name="log")
  2645. self.assertIsInstance(pager, cli._StreamContextAdapter)
  2646. def test_pager_config_per_command_true(self):
  2647. """Test per-command pager=true uses default pager."""
  2648. config = MagicMock()
  2649. def get_side_effect(section, key):
  2650. if section == ("pager",) and key == b"log":
  2651. return b"true"
  2652. raise KeyError
  2653. config.get.side_effect = get_side_effect
  2654. with patch("sys.stdout.isatty", return_value=True):
  2655. with patch("shutil.which", side_effect=lambda cmd: cmd == "less"):
  2656. pager = cli.get_pager(config=config, cmd_name="log")
  2657. self.assertIsInstance(pager, cli.Pager)
  2658. self.assertEqual(pager.pager_cmd, "less -FRX")
  2659. def test_pager_priority_order(self):
  2660. """Test complete priority order."""
  2661. # Set up all possible configurations
  2662. os.environ["PAGER"] = "env_pager"
  2663. os.environ["GIT_PAGER"] = "env_git_pager"
  2664. config = MagicMock()
  2665. def get_side_effect(section, key):
  2666. if section == ("pager",) and key == b"log":
  2667. return b"cmd_pager"
  2668. elif section == ("core",) and key == b"pager":
  2669. return b"core_pager"
  2670. raise KeyError
  2671. config.get.side_effect = get_side_effect
  2672. with patch("sys.stdout.isatty", return_value=True):
  2673. # Per-command config should win
  2674. pager = cli.get_pager(config=config, cmd_name="log")
  2675. self.assertEqual(pager.pager_cmd, "cmd_pager")
  2676. def test_pager_fallback_less(self):
  2677. """Test fallback to less with proper flags."""
  2678. with patch("sys.stdout.isatty", return_value=True):
  2679. with patch("shutil.which", side_effect=lambda cmd: cmd == "less"):
  2680. pager = cli.get_pager()
  2681. self.assertIsInstance(pager, cli.Pager)
  2682. self.assertEqual(pager.pager_cmd, "less -FRX")
  2683. def test_pager_fallback_more(self):
  2684. """Test fallback to more when less is not available."""
  2685. with patch("sys.stdout.isatty", return_value=True):
  2686. with patch("shutil.which", side_effect=lambda cmd: cmd == "more"):
  2687. pager = cli.get_pager()
  2688. self.assertIsInstance(pager, cli.Pager)
  2689. self.assertEqual(pager.pager_cmd, "more")
  2690. def test_pager_fallback_cat(self):
  2691. """Test ultimate fallback to cat."""
  2692. with patch("sys.stdout.isatty", return_value=True):
  2693. with patch("shutil.which", return_value=None):
  2694. pager = cli.get_pager()
  2695. self.assertIsInstance(pager, cli.Pager)
  2696. self.assertEqual(pager.pager_cmd, "cat")
  2697. def test_pager_context_manager(self):
  2698. """Test that pager works as a context manager."""
  2699. with patch("sys.stdout.isatty", return_value=True):
  2700. with cli.get_pager() as pager:
  2701. self.assertTrue(hasattr(pager, "write"))
  2702. self.assertTrue(hasattr(pager, "flush"))
  2703. class WorktreeCliTests(DulwichCliTestCase):
  2704. """Tests for worktree CLI commands."""
  2705. def setUp(self):
  2706. super().setUp()
  2707. # Base class already creates and initializes the repo
  2708. # Just create initial commit
  2709. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  2710. f.write("test content")
  2711. from dulwich import porcelain
  2712. porcelain.add(self.repo_path, ["test.txt"])
  2713. porcelain.commit(self.repo_path, message=b"Initial commit")
  2714. def test_worktree_list(self):
  2715. """Test worktree list command."""
  2716. # Change to repo directory
  2717. old_cwd = os.getcwd()
  2718. os.chdir(self.repo_path)
  2719. try:
  2720. io.StringIO()
  2721. cmd = cli.cmd_worktree()
  2722. result = cmd.run(["list"])
  2723. # Should list the main worktree
  2724. self.assertEqual(result, 0)
  2725. finally:
  2726. os.chdir(old_cwd)
  2727. def test_worktree_add(self):
  2728. """Test worktree add command."""
  2729. wt_path = os.path.join(self.test_dir, "worktree1")
  2730. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2731. result, _stdout, _stderr = self._run_cli(
  2732. "worktree", "add", wt_path, "feature"
  2733. )
  2734. self.assertEqual(result, 0)
  2735. self.assertTrue(os.path.exists(wt_path))
  2736. log_output = "\n".join(cm.output)
  2737. self.assertIn("Worktree added:", log_output)
  2738. def test_worktree_add_detached(self):
  2739. """Test worktree add with detached HEAD."""
  2740. wt_path = os.path.join(self.test_dir, "detached-wt")
  2741. # Change to repo directory
  2742. old_cwd = os.getcwd()
  2743. os.chdir(self.repo_path)
  2744. try:
  2745. cmd = cli.cmd_worktree()
  2746. with patch("sys.stdout", new_callable=io.StringIO):
  2747. result = cmd.run(["add", "--detach", wt_path])
  2748. self.assertEqual(result, 0)
  2749. self.assertTrue(os.path.exists(wt_path))
  2750. finally:
  2751. os.chdir(old_cwd)
  2752. def test_worktree_remove(self):
  2753. """Test worktree remove command."""
  2754. # First add a worktree
  2755. wt_path = os.path.join(self.test_dir, "to-remove")
  2756. result, _stdout, _stderr = self._run_cli("worktree", "add", wt_path)
  2757. self.assertEqual(result, 0)
  2758. # Then remove it
  2759. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2760. result, _stdout, _stderr = self._run_cli("worktree", "remove", wt_path)
  2761. self.assertEqual(result, 0)
  2762. self.assertFalse(os.path.exists(wt_path))
  2763. log_output = "\n".join(cm.output)
  2764. self.assertIn("Worktree removed:", log_output)
  2765. def test_worktree_prune(self):
  2766. """Test worktree prune command."""
  2767. # Add a worktree and manually remove it
  2768. wt_path = os.path.join(self.test_dir, "to-prune")
  2769. result, _stdout, _stderr = self._run_cli("worktree", "add", wt_path)
  2770. self.assertEqual(result, 0)
  2771. shutil.rmtree(wt_path)
  2772. # Prune
  2773. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2774. result, _stdout, _stderr = self._run_cli("worktree", "prune", "-v")
  2775. self.assertEqual(result, 0)
  2776. log_output = "\n".join(cm.output)
  2777. self.assertIn("to-prune", log_output)
  2778. def test_worktree_lock_unlock(self):
  2779. """Test worktree lock and unlock commands."""
  2780. # Add a worktree
  2781. wt_path = os.path.join(self.test_dir, "lockable")
  2782. result, _stdout, _stderr = self._run_cli("worktree", "add", wt_path)
  2783. self.assertEqual(result, 0)
  2784. # Lock it
  2785. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2786. result, _stdout, _stderr = self._run_cli(
  2787. "worktree", "lock", wt_path, "--reason", "Testing"
  2788. )
  2789. self.assertEqual(result, 0)
  2790. log_output = "\n".join(cm.output)
  2791. self.assertIn("Worktree locked:", log_output)
  2792. # Unlock it
  2793. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2794. result, _stdout, _stderr = self._run_cli("worktree", "unlock", wt_path)
  2795. self.assertEqual(result, 0)
  2796. log_output = "\n".join(cm.output)
  2797. self.assertIn("Worktree unlocked:", log_output)
  2798. def test_worktree_move(self):
  2799. """Test worktree move command."""
  2800. # Add a worktree
  2801. old_path = os.path.join(self.test_dir, "old-location")
  2802. new_path = os.path.join(self.test_dir, "new-location")
  2803. result, _stdout, _stderr = self._run_cli("worktree", "add", old_path)
  2804. self.assertEqual(result, 0)
  2805. # Move it
  2806. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2807. result, _stdout, _stderr = self._run_cli(
  2808. "worktree", "move", old_path, new_path
  2809. )
  2810. self.assertEqual(result, 0)
  2811. self.assertFalse(os.path.exists(old_path))
  2812. self.assertTrue(os.path.exists(new_path))
  2813. log_output = "\n".join(cm.output)
  2814. self.assertIn("Worktree moved:", log_output)
  2815. def test_worktree_invalid_command(self):
  2816. """Test invalid worktree subcommand."""
  2817. cmd = cli.cmd_worktree()
  2818. with patch("sys.stderr", new_callable=io.StringIO):
  2819. with self.assertRaises(SystemExit):
  2820. cmd.run(["invalid"])
  2821. class MergeBaseCommandTest(DulwichCliTestCase):
  2822. """Tests for merge-base command."""
  2823. def _create_commits(self):
  2824. """Helper to create a commit history for testing."""
  2825. # Create three commits in linear history
  2826. for i in range(1, 4):
  2827. test_file = os.path.join(self.repo_path, f"file{i}.txt")
  2828. with open(test_file, "w") as f:
  2829. f.write(f"content{i}")
  2830. self._run_cli("add", f"file{i}.txt")
  2831. self._run_cli("commit", f"--message=Commit {i}")
  2832. def test_merge_base_linear_history(self):
  2833. """Test merge-base with linear history."""
  2834. self._create_commits()
  2835. result, stdout, _stderr = self._run_cli("merge-base", "HEAD", "HEAD~1")
  2836. self.assertEqual(result, 0)
  2837. # Should return HEAD~1 as the merge base
  2838. output = stdout.strip()
  2839. # Verify it's a valid commit ID (40 hex chars)
  2840. self.assertEqual(len(output), 40)
  2841. self.assertTrue(all(c in "0123456789abcdef" for c in output))
  2842. def test_merge_base_is_ancestor_true(self):
  2843. """Test merge-base --is-ancestor when true."""
  2844. self._create_commits()
  2845. result, _stdout, _stderr = self._run_cli(
  2846. "merge-base", "--is-ancestor", "HEAD~1", "HEAD"
  2847. )
  2848. self.assertEqual(result, 0) # Exit code 0 means true
  2849. def test_merge_base_is_ancestor_false(self):
  2850. """Test merge-base --is-ancestor when false."""
  2851. self._create_commits()
  2852. result, _stdout, _stderr = self._run_cli(
  2853. "merge-base", "--is-ancestor", "HEAD", "HEAD~1"
  2854. )
  2855. self.assertEqual(result, 1) # Exit code 1 means false
  2856. def test_merge_base_independent(self):
  2857. """Test merge-base --independent."""
  2858. self._create_commits()
  2859. # All three commits in linear history - only HEAD should be independent
  2860. head = self.repo.refs[b"HEAD"]
  2861. head_1 = self.repo[head].parents[0]
  2862. head_2 = self.repo[head_1].parents[0]
  2863. result, stdout, _stderr = self._run_cli(
  2864. "merge-base",
  2865. "--independent",
  2866. head.decode(),
  2867. head_1.decode(),
  2868. head_2.decode(),
  2869. )
  2870. self.assertEqual(result, 0)
  2871. # Only HEAD should be in output (as it's the only independent commit)
  2872. lines = stdout.strip().split("\n")
  2873. self.assertEqual(len(lines), 1)
  2874. self.assertEqual(lines[0], head.decode())
  2875. def test_merge_base_requires_two_commits(self):
  2876. """Test merge-base requires at least two commits."""
  2877. self._create_commits()
  2878. result, _stdout, _stderr = self._run_cli("merge-base", "HEAD")
  2879. self.assertEqual(result, 1)
  2880. def test_merge_base_is_ancestor_requires_two_commits(self):
  2881. """Test merge-base --is-ancestor requires exactly two commits."""
  2882. self._create_commits()
  2883. result, _stdout, _stderr = self._run_cli("merge-base", "--is-ancestor", "HEAD")
  2884. self.assertEqual(result, 1)
  2885. class ConfigCommandTest(DulwichCliTestCase):
  2886. """Tests for config command."""
  2887. def test_config_set_and_get(self):
  2888. """Test setting and getting a config value."""
  2889. # Set a config value
  2890. result, stdout, _stderr = self._run_cli("config", "user.name", "Test User")
  2891. self.assertEqual(result, 0)
  2892. self.assertEqual(stdout, "")
  2893. # Get the value back
  2894. result, stdout, _stderr = self._run_cli("config", "user.name")
  2895. self.assertEqual(result, 0)
  2896. self.assertEqual(stdout, "Test User\n")
  2897. def test_config_set_and_get_subsection(self):
  2898. """Test setting and getting a config value with subsection."""
  2899. # Set a config value with subsection (e.g., remote.origin.url)
  2900. result, stdout, _stderr = self._run_cli(
  2901. "config", "remote.origin.url", "https://example.com/repo.git"
  2902. )
  2903. self.assertEqual(result, 0)
  2904. self.assertEqual(stdout, "")
  2905. # Get the value back
  2906. result, stdout, _stderr = self._run_cli("config", "remote.origin.url")
  2907. self.assertEqual(result, 0)
  2908. self.assertEqual(stdout, "https://example.com/repo.git\n")
  2909. def test_config_list(self):
  2910. """Test listing all config values."""
  2911. # Set some config values
  2912. self._run_cli("config", "user.name", "Test User")
  2913. self._run_cli("config", "user.email", "test@example.com")
  2914. # Get the actual config values that may vary by platform
  2915. config = self.repo.get_config()
  2916. filemode = config.get((b"core",), b"filemode")
  2917. try:
  2918. symlinks = config.get((b"core",), b"symlinks")
  2919. except KeyError:
  2920. symlinks = None
  2921. # List all values
  2922. result, stdout, _stderr = self._run_cli("config", "--list")
  2923. self.assertEqual(result, 0)
  2924. # Build expected output with platform-specific values
  2925. expected = "core.repositoryformatversion=0\n"
  2926. expected += f"core.filemode={filemode.decode('utf-8')}\n"
  2927. if symlinks is not None:
  2928. expected += f"core.symlinks={symlinks.decode('utf-8')}\n"
  2929. expected += (
  2930. "core.bare=false\n"
  2931. "core.logallrefupdates=true\n"
  2932. "user.name=Test User\n"
  2933. "user.email=test@example.com\n"
  2934. )
  2935. self.assertEqual(stdout, expected)
  2936. def test_config_unset(self):
  2937. """Test unsetting a config value."""
  2938. # Set a config value
  2939. self._run_cli("config", "user.name", "Test User")
  2940. # Verify it's set
  2941. result, stdout, _stderr = self._run_cli("config", "user.name")
  2942. self.assertEqual(result, 0)
  2943. self.assertEqual(stdout, "Test User\n")
  2944. # Unset it
  2945. result, stdout, _stderr = self._run_cli("config", "--unset", "user.name")
  2946. self.assertEqual(result, 0)
  2947. self.assertEqual(stdout, "")
  2948. # Verify it's gone
  2949. result, stdout, _stderr = self._run_cli("config", "user.name")
  2950. self.assertEqual(result, 1)
  2951. self.assertEqual(stdout, "")
  2952. def test_config_get_nonexistent(self):
  2953. """Test getting a nonexistent config value."""
  2954. result, stdout, _stderr = self._run_cli("config", "nonexistent.key")
  2955. self.assertEqual(result, 1)
  2956. self.assertEqual(stdout, "")
  2957. def test_config_unset_nonexistent(self):
  2958. """Test unsetting a nonexistent config value."""
  2959. result, _stdout, _stderr = self._run_cli("config", "--unset", "nonexistent.key")
  2960. self.assertEqual(result, 1)
  2961. def test_config_invalid_key_format(self):
  2962. """Test config with invalid key format."""
  2963. result, stdout, _stderr = self._run_cli("config", "invalidkey")
  2964. self.assertEqual(result, 1)
  2965. self.assertEqual(stdout, "")
  2966. def test_config_get_all(self):
  2967. """Test getting all values for a multivar."""
  2968. # Set multiple values for the same key
  2969. config = self.repo.get_config()
  2970. config.set(("test",), "multivar", "value1")
  2971. config.add(("test",), "multivar", "value2")
  2972. config.add(("test",), "multivar", "value3")
  2973. config.write_to_path()
  2974. # Get all values
  2975. result, stdout, _stderr = self._run_cli("config", "--get-all", "test.multivar")
  2976. self.assertEqual(result, 0)
  2977. self.assertEqual(stdout, "value1\nvalue2\nvalue3\n")
  2978. class GitFlushTest(TestCase):
  2979. """Tests for GIT_FLUSH environment variable support."""
  2980. def test_should_auto_flush_with_git_flush_1(self):
  2981. """Test that GIT_FLUSH=1 enables auto-flushing."""
  2982. from dulwich.cli import _should_auto_flush
  2983. mock_stream = MagicMock()
  2984. mock_stream.isatty.return_value = True
  2985. self.assertTrue(_should_auto_flush(mock_stream, env={"GIT_FLUSH": "1"}))
  2986. def test_should_auto_flush_with_git_flush_0(self):
  2987. """Test that GIT_FLUSH=0 disables auto-flushing."""
  2988. from dulwich.cli import _should_auto_flush
  2989. mock_stream = MagicMock()
  2990. mock_stream.isatty.return_value = True
  2991. self.assertFalse(_should_auto_flush(mock_stream, env={"GIT_FLUSH": "0"}))
  2992. def test_should_auto_flush_auto_detect_tty(self):
  2993. """Test that auto-detect returns False for TTY (no flush needed)."""
  2994. from dulwich.cli import _should_auto_flush
  2995. mock_stream = MagicMock()
  2996. mock_stream.isatty.return_value = True
  2997. self.assertFalse(_should_auto_flush(mock_stream, env={}))
  2998. def test_should_auto_flush_auto_detect_pipe(self):
  2999. """Test that auto-detect returns True for pipes (flush needed)."""
  3000. from dulwich.cli import _should_auto_flush
  3001. mock_stream = MagicMock()
  3002. mock_stream.isatty.return_value = False
  3003. self.assertTrue(_should_auto_flush(mock_stream, env={}))
  3004. def test_text_wrapper_flushes_on_write(self):
  3005. """Test that AutoFlushTextIOWrapper flushes after write."""
  3006. from dulwich.cli import AutoFlushTextIOWrapper
  3007. mock_stream = MagicMock()
  3008. wrapper = AutoFlushTextIOWrapper(mock_stream)
  3009. wrapper.write("test")
  3010. mock_stream.write.assert_called_once_with("test")
  3011. mock_stream.flush.assert_called_once()
  3012. def test_text_wrapper_flushes_on_writelines(self):
  3013. """Test that AutoFlushTextIOWrapper flushes after writelines."""
  3014. from dulwich.cli import AutoFlushTextIOWrapper
  3015. mock_stream = MagicMock()
  3016. wrapper = AutoFlushTextIOWrapper(mock_stream)
  3017. wrapper.writelines(["line1\n", "line2\n"])
  3018. mock_stream.writelines.assert_called_once()
  3019. mock_stream.flush.assert_called_once()
  3020. def test_binary_wrapper_flushes_on_write(self):
  3021. """Test that AutoFlushBinaryIOWrapper flushes after write."""
  3022. from dulwich.cli import AutoFlushBinaryIOWrapper
  3023. mock_stream = MagicMock()
  3024. wrapper = AutoFlushBinaryIOWrapper(mock_stream)
  3025. wrapper.write(b"test")
  3026. mock_stream.write.assert_called_once_with(b"test")
  3027. mock_stream.flush.assert_called_once()
  3028. def test_text_wrapper_env_classmethod(self):
  3029. """Test that AutoFlushTextIOWrapper.env() respects GIT_FLUSH."""
  3030. from dulwich.cli import AutoFlushTextIOWrapper
  3031. mock_stream = MagicMock()
  3032. mock_stream.isatty.return_value = False
  3033. wrapper = AutoFlushTextIOWrapper.env(mock_stream, env={"GIT_FLUSH": "1"})
  3034. self.assertIsInstance(wrapper, AutoFlushTextIOWrapper)
  3035. wrapper = AutoFlushTextIOWrapper.env(mock_stream, env={"GIT_FLUSH": "0"})
  3036. self.assertIs(mock_stream, wrapper)
  3037. def test_binary_wrapper_env_classmethod(self):
  3038. """Test that AutoFlushBinaryIOWrapper.env() respects GIT_FLUSH."""
  3039. from dulwich.cli import AutoFlushBinaryIOWrapper
  3040. mock_stream = MagicMock()
  3041. mock_stream.isatty.return_value = False
  3042. wrapper = AutoFlushBinaryIOWrapper.env(mock_stream, env={"GIT_FLUSH": "1"})
  3043. self.assertIsInstance(wrapper, AutoFlushBinaryIOWrapper)
  3044. wrapper = AutoFlushBinaryIOWrapper.env(mock_stream, env={"GIT_FLUSH": "0"})
  3045. self.assertIs(wrapper, mock_stream)
  3046. def test_wrapper_delegates_attributes(self):
  3047. """Test that wrapper delegates unknown attributes to stream."""
  3048. from dulwich.cli import AutoFlushTextIOWrapper
  3049. mock_stream = MagicMock()
  3050. mock_stream.encoding = "utf-8"
  3051. wrapper = AutoFlushTextIOWrapper(mock_stream)
  3052. self.assertEqual(wrapper.encoding, "utf-8")
  3053. def test_wrapper_context_manager(self):
  3054. """Test that wrapper supports context manager protocol."""
  3055. from dulwich.cli import AutoFlushTextIOWrapper
  3056. mock_stream = MagicMock()
  3057. wrapper = AutoFlushTextIOWrapper(mock_stream)
  3058. with wrapper as w:
  3059. self.assertIs(w, wrapper)
  3060. if __name__ == "__main__":
  3061. unittest.main()