2
0

test_cli.py 161 KB

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