2
0

test_cli.py 158 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320
  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. class FilterBranchCommandTest(DulwichCliTestCase):
  958. """Tests for filter-branch command."""
  959. def setUp(self):
  960. super().setUp()
  961. # Create a more complex repository structure for testing
  962. # Create some files in subdirectories
  963. os.makedirs(os.path.join(self.repo_path, "subdir"))
  964. os.makedirs(os.path.join(self.repo_path, "other"))
  965. # Create files
  966. files = {
  967. "README.md": "# Test Repo",
  968. "subdir/file1.txt": "File in subdir",
  969. "subdir/file2.txt": "Another file in subdir",
  970. "other/file3.txt": "File in other dir",
  971. "root.txt": "File at root",
  972. }
  973. for path, content in files.items():
  974. file_path = os.path.join(self.repo_path, path)
  975. with open(file_path, "w") as f:
  976. f.write(content)
  977. # Add all files and create initial commit
  978. self._run_cli("add", ".")
  979. self._run_cli("commit", "--message=Initial commit")
  980. # Create a second commit modifying subdir
  981. with open(os.path.join(self.repo_path, "subdir/file1.txt"), "a") as f:
  982. f.write("\nModified content")
  983. self._run_cli("add", "subdir/file1.txt")
  984. self._run_cli("commit", "--message=Modify subdir file")
  985. # Create a third commit in other dir
  986. with open(os.path.join(self.repo_path, "other/file3.txt"), "a") as f:
  987. f.write("\nMore content")
  988. self._run_cli("add", "other/file3.txt")
  989. self._run_cli("commit", "--message=Modify other file")
  990. # Create a branch
  991. self._run_cli("branch", "test-branch")
  992. # Create a tag
  993. self._run_cli("tag", "v1.0")
  994. def test_filter_branch_subdirectory_filter(self):
  995. """Test filter-branch with subdirectory filter."""
  996. # Run filter-branch to extract only the subdir
  997. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  998. result, _stdout, _stderr = self._run_cli(
  999. "filter-branch", "--subdirectory-filter", "subdir"
  1000. )
  1001. # Check that the operation succeeded
  1002. self.assertEqual(result, 0)
  1003. log_output = "\n".join(cm.output)
  1004. self.assertIn("Rewrite HEAD", log_output)
  1005. # filter-branch rewrites history but doesn't update working tree
  1006. # We need to check the commit contents, not the working tree
  1007. # Reset to the rewritten HEAD to update working tree
  1008. self._run_cli("reset", "--hard", "HEAD")
  1009. # Now check that only files from subdir remain at root level
  1010. self.assertTrue(os.path.exists(os.path.join(self.repo_path, "file1.txt")))
  1011. self.assertTrue(os.path.exists(os.path.join(self.repo_path, "file2.txt")))
  1012. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "README.md")))
  1013. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "root.txt")))
  1014. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "other")))
  1015. self.assertFalse(os.path.exists(os.path.join(self.repo_path, "subdir")))
  1016. # Check that original refs were backed up
  1017. original_refs = [
  1018. ref for ref in self.repo.refs.keys() if ref.startswith(b"refs/original/")
  1019. ]
  1020. self.assertTrue(
  1021. len(original_refs) > 0, "No original refs found after filter-branch"
  1022. )
  1023. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  1024. def test_filter_branch_msg_filter(self):
  1025. """Test filter-branch with message filter."""
  1026. # Run filter-branch to prepend [FILTERED] to commit messages
  1027. result, stdout, _stderr = self._run_cli(
  1028. "filter-branch", "--msg-filter", "sed 's/^/[FILTERED] /'"
  1029. )
  1030. self.assertEqual(result, 0)
  1031. # Check that commit messages were modified
  1032. result, stdout, _stderr = self._run_cli("log")
  1033. self.assertIn("[FILTERED] Modify other file", stdout)
  1034. self.assertIn("[FILTERED] Modify subdir file", stdout)
  1035. self.assertIn("[FILTERED] Initial commit", stdout)
  1036. def test_filter_branch_env_filter(self):
  1037. """Test filter-branch with environment filter."""
  1038. # Run filter-branch to change author email
  1039. env_filter = """
  1040. if [ "$GIT_AUTHOR_EMAIL" = "test@example.com" ]; then
  1041. export GIT_AUTHOR_EMAIL="filtered@example.com"
  1042. fi
  1043. """
  1044. result, _stdout, _stderr = self._run_cli(
  1045. "filter-branch", "--env-filter", env_filter
  1046. )
  1047. self.assertEqual(result, 0)
  1048. def test_filter_branch_prune_empty(self):
  1049. """Test filter-branch with prune-empty option."""
  1050. # Create a commit that only touches files outside subdir
  1051. with open(os.path.join(self.repo_path, "root.txt"), "a") as f:
  1052. f.write("\nNew line")
  1053. self._run_cli("add", "root.txt")
  1054. self._run_cli("commit", "--message=Modify root file only")
  1055. # Run filter-branch to extract subdir with prune-empty
  1056. result, stdout, _stderr = self._run_cli(
  1057. "filter-branch", "--subdirectory-filter", "subdir", "--prune-empty"
  1058. )
  1059. self.assertEqual(result, 0)
  1060. # The last commit should have been pruned
  1061. result, stdout, _stderr = self._run_cli("log")
  1062. self.assertNotIn("Modify root file only", stdout)
  1063. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  1064. def test_filter_branch_force(self):
  1065. """Test filter-branch with force option."""
  1066. # Run filter-branch once with a filter that actually changes something
  1067. result, _stdout, _stderr = self._run_cli(
  1068. "filter-branch", "--msg-filter", "sed 's/^/[TEST] /'"
  1069. )
  1070. self.assertEqual(result, 0)
  1071. # Check that backup refs were created
  1072. # The implementation backs up refs under refs/original/
  1073. original_refs = [
  1074. ref for ref in self.repo.refs.keys() if ref.startswith(b"refs/original/")
  1075. ]
  1076. self.assertTrue(len(original_refs) > 0, "No original refs found")
  1077. # Run again without force - should fail
  1078. with self.assertLogs("dulwich.cli", level="ERROR") as cm:
  1079. result, _stdout, _stderr = self._run_cli(
  1080. "filter-branch", "--msg-filter", "sed 's/^/[TEST2] /'"
  1081. )
  1082. self.assertEqual(result, 1)
  1083. log_output = "\n".join(cm.output)
  1084. self.assertIn("Cannot create a new backup", log_output)
  1085. self.assertIn("refs/original", log_output)
  1086. # Run with force - should succeed
  1087. result, _stdout, _stderr = self._run_cli(
  1088. "filter-branch", "--force", "--msg-filter", "sed 's/^/[TEST3] /'"
  1089. )
  1090. self.assertEqual(result, 0)
  1091. @skipIf(sys.platform == "win32", "sed command not available on Windows")
  1092. def test_filter_branch_specific_branch(self):
  1093. """Test filter-branch on a specific branch."""
  1094. # Switch to test-branch and add a commit
  1095. self._run_cli("checkout", "test-branch")
  1096. with open(os.path.join(self.repo_path, "branch-file.txt"), "w") as f:
  1097. f.write("Branch specific file")
  1098. self._run_cli("add", "branch-file.txt")
  1099. self._run_cli("commit", "--message=Branch commit")
  1100. # Run filter-branch on the test-branch
  1101. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1102. result, stdout, _stderr = self._run_cli(
  1103. "filter-branch", "--msg-filter", "sed 's/^/[BRANCH] /'", "test-branch"
  1104. )
  1105. self.assertEqual(result, 0)
  1106. log_output = "\n".join(cm.output)
  1107. self.assertIn("Ref 'refs/heads/test-branch' was rewritten", log_output)
  1108. # Check that only test-branch was modified
  1109. result, stdout, _stderr = self._run_cli("log")
  1110. self.assertIn("[BRANCH] Branch commit", stdout)
  1111. # Switch to master and check it wasn't modified
  1112. self._run_cli("checkout", "master")
  1113. result, stdout, _stderr = self._run_cli("log")
  1114. self.assertNotIn("[BRANCH]", stdout)
  1115. def test_filter_branch_tree_filter(self):
  1116. """Test filter-branch with tree filter."""
  1117. # Use a tree filter to remove a specific file
  1118. tree_filter = "rm -f root.txt"
  1119. result, stdout, _stderr = self._run_cli(
  1120. "filter-branch", "--tree-filter", tree_filter
  1121. )
  1122. self.assertEqual(result, 0)
  1123. # Check that the file was removed from the latest commit
  1124. # We need to check the commit tree, not the working directory
  1125. result, stdout, _stderr = self._run_cli("ls-tree", "HEAD")
  1126. self.assertNotIn("root.txt", stdout)
  1127. def test_filter_branch_index_filter(self):
  1128. """Test filter-branch with index filter."""
  1129. # Use an index filter to remove a file from the index
  1130. index_filter = "git rm --cached --ignore-unmatch root.txt"
  1131. result, _stdout, _stderr = self._run_cli(
  1132. "filter-branch", "--index-filter", index_filter
  1133. )
  1134. self.assertEqual(result, 0)
  1135. def test_filter_branch_parent_filter(self):
  1136. """Test filter-branch with parent filter."""
  1137. # Create a merge commit first
  1138. self._run_cli("checkout", "HEAD", "-b", "feature")
  1139. with open(os.path.join(self.repo_path, "feature.txt"), "w") as f:
  1140. f.write("Feature")
  1141. self._run_cli("add", "feature.txt")
  1142. self._run_cli("commit", "--message=Feature commit")
  1143. self._run_cli("checkout", "master")
  1144. self._run_cli("merge", "feature", "--message=Merge feature")
  1145. # Use parent filter to linearize history (remove second parent)
  1146. parent_filter = "cut -d' ' -f1"
  1147. result, _stdout, _stderr = self._run_cli(
  1148. "filter-branch", "--parent-filter", parent_filter
  1149. )
  1150. self.assertEqual(result, 0)
  1151. def test_filter_branch_commit_filter(self):
  1152. """Test filter-branch with commit filter."""
  1153. # Use commit filter to skip commits with certain messages
  1154. commit_filter = """
  1155. if grep -q "Modify other" <<< "$GIT_COMMIT_MESSAGE"; then
  1156. skip_commit "$@"
  1157. else
  1158. git commit-tree "$@"
  1159. fi
  1160. """
  1161. _result, _stdout, _stderr = self._run_cli(
  1162. "filter-branch", "--commit-filter", commit_filter
  1163. )
  1164. # Note: This test may fail because the commit filter syntax is simplified
  1165. # In real Git, skip_commit is a function, but our implementation may differ
  1166. def test_filter_branch_tag_name_filter(self):
  1167. """Test filter-branch with tag name filter."""
  1168. # Run filter-branch with tag name filter to rename tags
  1169. result, _stdout, _stderr = self._run_cli(
  1170. "filter-branch",
  1171. "--tag-name-filter",
  1172. "sed 's/^v/version-/'",
  1173. "--msg-filter",
  1174. "cat",
  1175. )
  1176. self.assertEqual(result, 0)
  1177. # Check that tag was renamed
  1178. self.assertIn(b"refs/tags/version-1.0", self.repo.refs.keys())
  1179. def test_filter_branch_errors(self):
  1180. """Test filter-branch error handling."""
  1181. # Test with invalid subdirectory
  1182. result, _stdout, _stderr = self._run_cli(
  1183. "filter-branch", "--subdirectory-filter", "nonexistent"
  1184. )
  1185. # Should still succeed but produce empty history
  1186. self.assertEqual(result, 0)
  1187. def test_filter_branch_no_args(self):
  1188. """Test filter-branch with no arguments."""
  1189. # Should work as no-op
  1190. result, _stdout, _stderr = self._run_cli("filter-branch")
  1191. self.assertEqual(result, 0)
  1192. class ShowCommandTest(DulwichCliTestCase):
  1193. """Tests for show command."""
  1194. def test_show_commit(self):
  1195. # Create a commit
  1196. test_file = os.path.join(self.repo_path, "test.txt")
  1197. with open(test_file, "w") as f:
  1198. f.write("test content")
  1199. self._run_cli("add", "test.txt")
  1200. self._run_cli("commit", "--message=Test commit")
  1201. _result, stdout, _stderr = self._run_cli("show", "HEAD")
  1202. self.assertIn("Test commit", stdout)
  1203. class ShowRefCommandTest(DulwichCliTestCase):
  1204. """Tests for show-ref command."""
  1205. def test_show_ref_basic(self):
  1206. """Test basic show-ref functionality."""
  1207. # Create a commit to have a HEAD ref
  1208. test_file = os.path.join(self.repo_path, "test.txt")
  1209. with open(test_file, "w") as f:
  1210. f.write("test content")
  1211. self._run_cli("add", "test.txt")
  1212. self._run_cli("commit", "--message=Test commit")
  1213. # Create a branch
  1214. self._run_cli("branch", "test-branch")
  1215. # Get the exact SHAs
  1216. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1217. test_branch_sha = self.repo.refs[b"refs/heads/test-branch"].decode()
  1218. # Run show-ref
  1219. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1220. _result, _stdout, _stderr = self._run_cli("show-ref")
  1221. output = "\n".join([record.message for record in cm.records])
  1222. expected = (
  1223. f"{master_sha} refs/heads/master\n{test_branch_sha} refs/heads/test-branch"
  1224. )
  1225. self.assertEqual(output, expected)
  1226. def test_show_ref_with_head(self):
  1227. """Test show-ref with --head option."""
  1228. # Create a commit to have a HEAD ref
  1229. test_file = os.path.join(self.repo_path, "test.txt")
  1230. with open(test_file, "w") as f:
  1231. f.write("test content")
  1232. self._run_cli("add", "test.txt")
  1233. self._run_cli("commit", "--message=Test commit")
  1234. # Get the exact SHAs
  1235. head_sha = self.repo.refs[b"HEAD"].decode()
  1236. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1237. # Run show-ref with --head
  1238. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1239. _result, _stdout, _stderr = self._run_cli("show-ref", "--head")
  1240. output = "\n".join([record.message for record in cm.records])
  1241. expected = f"{head_sha} HEAD\n{master_sha} refs/heads/master"
  1242. self.assertEqual(output, expected)
  1243. def test_show_ref_with_pattern(self):
  1244. """Test show-ref with pattern matching."""
  1245. # Create commits and branches
  1246. test_file = os.path.join(self.repo_path, "test.txt")
  1247. with open(test_file, "w") as f:
  1248. f.write("test content")
  1249. self._run_cli("add", "test.txt")
  1250. self._run_cli("commit", "--message=Test commit")
  1251. self._run_cli("branch", "feature-1")
  1252. self._run_cli("branch", "feature-2")
  1253. self._run_cli("branch", "bugfix-1")
  1254. # Get the exact SHA for master
  1255. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1256. # Test pattern matching for "master"
  1257. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1258. _result, _stdout, _stderr = self._run_cli("show-ref", "master")
  1259. output = "\n".join([record.message for record in cm.records])
  1260. expected = f"{master_sha} refs/heads/master"
  1261. self.assertEqual(output, expected)
  1262. def test_show_ref_branches_only(self):
  1263. """Test show-ref with --branches option."""
  1264. # Create commits and a tag
  1265. test_file = os.path.join(self.repo_path, "test.txt")
  1266. with open(test_file, "w") as f:
  1267. f.write("test content")
  1268. self._run_cli("add", "test.txt")
  1269. self._run_cli("commit", "--message=Test commit")
  1270. self._run_cli("tag", "v1.0")
  1271. # Get the exact SHA for master
  1272. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1273. # Run show-ref with --branches
  1274. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1275. _result, _stdout, _stderr = self._run_cli("show-ref", "--branches")
  1276. output = "\n".join([record.message for record in cm.records])
  1277. expected = f"{master_sha} refs/heads/master"
  1278. self.assertEqual(output, expected)
  1279. def test_show_ref_tags_only(self):
  1280. """Test show-ref with --tags option."""
  1281. # Create commits and tags
  1282. test_file = os.path.join(self.repo_path, "test.txt")
  1283. with open(test_file, "w") as f:
  1284. f.write("test content")
  1285. self._run_cli("add", "test.txt")
  1286. self._run_cli("commit", "--message=Test commit")
  1287. self._run_cli("tag", "v1.0")
  1288. self._run_cli("tag", "v2.0")
  1289. # Get the exact SHAs for tags
  1290. v1_sha = self.repo.refs[b"refs/tags/v1.0"].decode()
  1291. v2_sha = self.repo.refs[b"refs/tags/v2.0"].decode()
  1292. # Run show-ref with --tags
  1293. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1294. _result, _stdout, _stderr = self._run_cli("show-ref", "--tags")
  1295. output = "\n".join([record.message for record in cm.records])
  1296. expected = f"{v1_sha} refs/tags/v1.0\n{v2_sha} refs/tags/v2.0"
  1297. self.assertEqual(output, expected)
  1298. def test_show_ref_hash_only(self):
  1299. """Test show-ref with --hash option to show only OID."""
  1300. # Create a commit
  1301. test_file = os.path.join(self.repo_path, "test.txt")
  1302. with open(test_file, "w") as f:
  1303. f.write("test content")
  1304. self._run_cli("add", "test.txt")
  1305. self._run_cli("commit", "--message=Test commit")
  1306. # Get the exact SHA for master
  1307. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1308. # Run show-ref with --hash
  1309. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1310. _result, _stdout, _stderr = self._run_cli(
  1311. "show-ref", "--hash", "--", "master"
  1312. )
  1313. output = "\n".join([record.message for record in cm.records])
  1314. expected = f"{master_sha}"
  1315. self.assertEqual(output, expected)
  1316. def test_show_ref_verify(self):
  1317. """Test show-ref with --verify option for exact matching."""
  1318. # Create a commit
  1319. test_file = os.path.join(self.repo_path, "test.txt")
  1320. with open(test_file, "w") as f:
  1321. f.write("test content")
  1322. self._run_cli("add", "test.txt")
  1323. self._run_cli("commit", "--message=Test commit")
  1324. # Get the exact SHA for master
  1325. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1326. # Verify with exact ref path should succeed
  1327. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1328. result, _stdout, _stderr = self._run_cli(
  1329. "show-ref", "--verify", "refs/heads/master"
  1330. )
  1331. self.assertEqual(result, 0)
  1332. output = "\n".join([record.message for record in cm.records])
  1333. expected = f"{master_sha} refs/heads/master"
  1334. self.assertEqual(output, expected)
  1335. # Verify with partial name should fail
  1336. result, _stdout, _stderr = self._run_cli("show-ref", "--verify", "master")
  1337. self.assertEqual(result, 1)
  1338. def test_show_ref_exists(self):
  1339. """Test show-ref with --exists option."""
  1340. # Create a commit
  1341. test_file = os.path.join(self.repo_path, "test.txt")
  1342. with open(test_file, "w") as f:
  1343. f.write("test content")
  1344. self._run_cli("add", "test.txt")
  1345. self._run_cli("commit", "--message=Test commit")
  1346. # Check if existing ref exists
  1347. result, _stdout, _stderr = self._run_cli(
  1348. "show-ref", "--exists", "refs/heads/master"
  1349. )
  1350. self.assertEqual(result, 0)
  1351. # Check if non-existing ref exists
  1352. result, _stdout, _stderr = self._run_cli(
  1353. "show-ref", "--exists", "refs/heads/nonexistent"
  1354. )
  1355. self.assertEqual(result, 2)
  1356. def test_show_ref_quiet(self):
  1357. """Test show-ref with --quiet option."""
  1358. # Create a commit
  1359. test_file = os.path.join(self.repo_path, "test.txt")
  1360. with open(test_file, "w") as f:
  1361. f.write("test content")
  1362. self._run_cli("add", "test.txt")
  1363. self._run_cli("commit", "--message=Test commit")
  1364. # Run show-ref with --quiet - should not log anything
  1365. result, _stdout, _stderr = self._run_cli("show-ref", "--quiet")
  1366. self.assertEqual(result, 0)
  1367. def test_show_ref_abbrev(self):
  1368. """Test show-ref with --abbrev option."""
  1369. # Create a commit
  1370. test_file = os.path.join(self.repo_path, "test.txt")
  1371. with open(test_file, "w") as f:
  1372. f.write("test content")
  1373. self._run_cli("add", "test.txt")
  1374. self._run_cli("commit", "--message=Test commit")
  1375. # Get the exact SHA for master
  1376. master_sha = self.repo.refs[b"refs/heads/master"].decode()
  1377. # Run show-ref with --abbrev=7
  1378. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1379. _result, _stdout, _stderr = self._run_cli("show-ref", "--abbrev=7")
  1380. output = "\n".join([record.message for record in cm.records])
  1381. expected = f"{master_sha[:7]} refs/heads/master"
  1382. self.assertEqual(output, expected)
  1383. def test_show_ref_no_matches(self):
  1384. """Test show-ref returns error when no matches found."""
  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. # Search for non-existent pattern
  1392. result, _stdout, _stderr = self._run_cli("show-ref", "nonexistent")
  1393. self.assertEqual(result, 1)
  1394. class ShowBranchCommandTest(DulwichCliTestCase):
  1395. """Tests for show-branch command."""
  1396. def test_show_branch_basic(self):
  1397. """Test basic show-branch functionality."""
  1398. # Create initial commit
  1399. test_file = os.path.join(self.repo_path, "test.txt")
  1400. with open(test_file, "w") as f:
  1401. f.write("initial content")
  1402. self._run_cli("add", "test.txt")
  1403. self._run_cli("commit", "--message=Initial commit")
  1404. # Create a branch and add a commit
  1405. self._run_cli("branch", "branch1")
  1406. self._run_cli("checkout", "branch1")
  1407. with open(test_file, "a") as f:
  1408. f.write("\nbranch1 content")
  1409. self._run_cli("add", "test.txt")
  1410. self._run_cli("commit", "--message=Branch1 commit")
  1411. # Switch back to master
  1412. self._run_cli("checkout", "master")
  1413. # Run show-branch
  1414. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1415. _result, _stdout, _stderr = self._run_cli(
  1416. "show-branch", "master", "branch1"
  1417. )
  1418. output = "\n".join([record.message for record in cm.records])
  1419. # Check exact output
  1420. expected = (
  1421. "! [branch1] Branch1 commit\n"
  1422. " ![master] Initial commit\n"
  1423. "----\n"
  1424. "* [Branch1 commit]\n"
  1425. "+* [Initial commit]"
  1426. )
  1427. self.assertEqual(expected, output)
  1428. def test_show_branch_list(self):
  1429. """Test show-branch with --list option."""
  1430. # Create initial commit
  1431. test_file = os.path.join(self.repo_path, "test.txt")
  1432. with open(test_file, "w") as f:
  1433. f.write("initial content")
  1434. self._run_cli("add", "test.txt")
  1435. self._run_cli("commit", "--message=Initial commit")
  1436. # Create branches
  1437. self._run_cli("branch", "branch1")
  1438. self._run_cli("branch", "branch2")
  1439. # Run show-branch --list
  1440. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1441. _result, _stdout, _stderr = self._run_cli("show-branch", "--list")
  1442. output = "\n".join([record.message for record in cm.records])
  1443. # Check exact output (only branch headers, no separator)
  1444. expected = (
  1445. "! [branch1] Initial commit\n"
  1446. " ! [branch2] Initial commit\n"
  1447. " ![master] Initial commit"
  1448. )
  1449. self.assertEqual(expected, output)
  1450. def test_show_branch_independent(self):
  1451. """Test show-branch with --independent option."""
  1452. # Create initial commit
  1453. test_file = os.path.join(self.repo_path, "test.txt")
  1454. with open(test_file, "w") as f:
  1455. f.write("initial content")
  1456. self._run_cli("add", "test.txt")
  1457. self._run_cli("commit", "--message=Initial commit")
  1458. # Create a branch and add a commit
  1459. self._run_cli("branch", "branch1")
  1460. self._run_cli("checkout", "branch1")
  1461. with open(test_file, "a") as f:
  1462. f.write("\nbranch1 content")
  1463. self._run_cli("add", "test.txt")
  1464. self._run_cli("commit", "--message=Branch1 commit")
  1465. # Run show-branch --independent
  1466. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1467. _result, _stdout, _stderr = self._run_cli(
  1468. "show-branch", "--independent", "master", "branch1"
  1469. )
  1470. output = "\n".join([record.message for record in cm.records])
  1471. # Only branch1 should be shown (it's not reachable from master)
  1472. expected = "branch1"
  1473. self.assertEqual(expected, output)
  1474. def test_show_branch_merge_base(self):
  1475. """Test show-branch with --merge-base option."""
  1476. # Create initial commit
  1477. test_file = os.path.join(self.repo_path, "test.txt")
  1478. with open(test_file, "w") as f:
  1479. f.write("initial content")
  1480. self._run_cli("add", "test.txt")
  1481. self._run_cli("commit", "--message=Initial commit")
  1482. # Get the initial commit SHA
  1483. initial_sha = self.repo.refs[b"HEAD"]
  1484. # Create a branch and add a commit
  1485. self._run_cli("branch", "branch1")
  1486. self._run_cli("checkout", "branch1")
  1487. with open(test_file, "a") as f:
  1488. f.write("\nbranch1 content")
  1489. self._run_cli("add", "test.txt")
  1490. self._run_cli("commit", "--message=Branch1 commit")
  1491. # Switch back to master and add a different commit
  1492. self._run_cli("checkout", "master")
  1493. with open(test_file, "a") as f:
  1494. f.write("\nmaster content")
  1495. self._run_cli("add", "test.txt")
  1496. self._run_cli("commit", "--message=Master commit")
  1497. # Run show-branch --merge-base
  1498. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1499. _result, _stdout, _stderr = self._run_cli(
  1500. "show-branch", "--merge-base", "master", "branch1"
  1501. )
  1502. output = "\n".join([record.message for record in cm.records])
  1503. # The merge base should be the initial commit SHA
  1504. expected = initial_sha.decode("ascii")
  1505. self.assertEqual(expected, output)
  1506. class FormatPatchCommandTest(DulwichCliTestCase):
  1507. """Tests for format-patch command."""
  1508. def test_format_patch_single_commit(self):
  1509. # Create a commit with actual content
  1510. from dulwich.objects import Blob, Tree
  1511. # Initial commit
  1512. tree1 = Tree()
  1513. self.repo.object_store.add_object(tree1)
  1514. self.repo.get_worktree().commit(
  1515. message=b"Initial commit",
  1516. tree=tree1.id,
  1517. )
  1518. # Second commit with a file
  1519. blob = Blob.from_string(b"Hello, World!\n")
  1520. self.repo.object_store.add_object(blob)
  1521. tree2 = Tree()
  1522. tree2.add(b"hello.txt", 0o100644, blob.id)
  1523. self.repo.object_store.add_object(tree2)
  1524. self.repo.get_worktree().commit(
  1525. message=b"Add hello.txt",
  1526. tree=tree2.id,
  1527. )
  1528. # Test format-patch for last commit
  1529. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1530. result, _stdout, _stderr = self._run_cli("format-patch", "-n", "1")
  1531. self.assertEqual(result, None)
  1532. log_output = "\n".join(cm.output)
  1533. self.assertIn("0001-Add-hello.txt.patch", log_output)
  1534. # Check patch contents
  1535. patch_file = os.path.join(self.repo_path, "0001-Add-hello.txt.patch")
  1536. with open(patch_file, "rb") as f:
  1537. content = f.read()
  1538. # Check header
  1539. self.assertIn(b"Subject: [PATCH 1/1] Add hello.txt", content)
  1540. self.assertIn(b"From:", content)
  1541. self.assertIn(b"Date:", content)
  1542. # Check diff content
  1543. self.assertIn(b"diff --git a/hello.txt b/hello.txt", content)
  1544. self.assertIn(b"new file mode", content)
  1545. self.assertIn(b"+Hello, World!", content)
  1546. # Check footer
  1547. self.assertIn(b"-- \nDulwich", content)
  1548. # Clean up
  1549. os.remove(patch_file)
  1550. def test_format_patch_multiple_commits(self):
  1551. from dulwich.objects import Blob, Tree
  1552. # Initial commit
  1553. tree1 = Tree()
  1554. self.repo.object_store.add_object(tree1)
  1555. self.repo.get_worktree().commit(
  1556. message=b"Initial commit",
  1557. tree=tree1.id,
  1558. )
  1559. # Second commit
  1560. blob1 = Blob.from_string(b"File 1 content\n")
  1561. self.repo.object_store.add_object(blob1)
  1562. tree2 = Tree()
  1563. tree2.add(b"file1.txt", 0o100644, blob1.id)
  1564. self.repo.object_store.add_object(tree2)
  1565. self.repo.get_worktree().commit(
  1566. message=b"Add file1.txt",
  1567. tree=tree2.id,
  1568. )
  1569. # Third commit
  1570. blob2 = Blob.from_string(b"File 2 content\n")
  1571. self.repo.object_store.add_object(blob2)
  1572. tree3 = Tree()
  1573. tree3.add(b"file1.txt", 0o100644, blob1.id)
  1574. tree3.add(b"file2.txt", 0o100644, blob2.id)
  1575. self.repo.object_store.add_object(tree3)
  1576. self.repo.get_worktree().commit(
  1577. message=b"Add file2.txt",
  1578. tree=tree3.id,
  1579. )
  1580. # Test format-patch for last 2 commits
  1581. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1582. result, _stdout, _stderr = self._run_cli("format-patch", "-n", "2")
  1583. self.assertEqual(result, None)
  1584. log_output = "\n".join(cm.output)
  1585. self.assertIn("0001-Add-file1.txt.patch", log_output)
  1586. self.assertIn("0002-Add-file2.txt.patch", log_output)
  1587. # Check first patch
  1588. with open(os.path.join(self.repo_path, "0001-Add-file1.txt.patch"), "rb") as f:
  1589. content = f.read()
  1590. self.assertIn(b"Subject: [PATCH 1/2] Add file1.txt", content)
  1591. self.assertIn(b"+File 1 content", content)
  1592. # Check second patch
  1593. with open(os.path.join(self.repo_path, "0002-Add-file2.txt.patch"), "rb") as f:
  1594. content = f.read()
  1595. self.assertIn(b"Subject: [PATCH 2/2] Add file2.txt", content)
  1596. self.assertIn(b"+File 2 content", content)
  1597. # Clean up
  1598. os.remove(os.path.join(self.repo_path, "0001-Add-file1.txt.patch"))
  1599. os.remove(os.path.join(self.repo_path, "0002-Add-file2.txt.patch"))
  1600. def test_format_patch_output_directory(self):
  1601. from dulwich.objects import Blob, Tree
  1602. # Create a commit
  1603. blob = Blob.from_string(b"Test content\n")
  1604. self.repo.object_store.add_object(blob)
  1605. tree = Tree()
  1606. tree.add(b"test.txt", 0o100644, blob.id)
  1607. self.repo.object_store.add_object(tree)
  1608. self.repo.get_worktree().commit(
  1609. message=b"Test commit",
  1610. tree=tree.id,
  1611. )
  1612. # Create output directory
  1613. output_dir = os.path.join(self.test_dir, "patches")
  1614. os.makedirs(output_dir)
  1615. # Test format-patch with output directory
  1616. result, _stdout, _stderr = self._run_cli(
  1617. "format-patch", "-o", output_dir, "-n", "1"
  1618. )
  1619. self.assertEqual(result, None)
  1620. # Check that file was created in output directory with correct content
  1621. patch_file = os.path.join(output_dir, "0001-Test-commit.patch")
  1622. self.assertTrue(os.path.exists(patch_file))
  1623. with open(patch_file, "rb") as f:
  1624. content = f.read()
  1625. self.assertIn(b"Subject: [PATCH 1/1] Test commit", content)
  1626. self.assertIn(b"+Test content", content)
  1627. def test_format_patch_commit_range(self):
  1628. from dulwich.objects import Blob, Tree
  1629. # Create commits with actual file changes
  1630. commits = []
  1631. trees = []
  1632. # Initial empty commit
  1633. tree0 = Tree()
  1634. self.repo.object_store.add_object(tree0)
  1635. trees.append(tree0)
  1636. c0 = self.repo.get_worktree().commit(
  1637. message=b"Initial commit",
  1638. tree=tree0.id,
  1639. )
  1640. commits.append(c0)
  1641. # Add three files in separate commits
  1642. for i in range(1, 4):
  1643. blob = Blob.from_string(f"Content {i}\n".encode())
  1644. self.repo.object_store.add_object(blob)
  1645. tree = Tree()
  1646. # Copy previous files
  1647. for j in range(1, i):
  1648. prev_blob_id = trees[j][f"file{j}.txt".encode()][1]
  1649. tree.add(f"file{j}.txt".encode(), 0o100644, prev_blob_id)
  1650. # Add new file
  1651. tree.add(f"file{i}.txt".encode(), 0o100644, blob.id)
  1652. self.repo.object_store.add_object(tree)
  1653. trees.append(tree)
  1654. c = self.repo.get_worktree().commit(
  1655. message=f"Add file{i}.txt".encode(),
  1656. tree=tree.id,
  1657. )
  1658. commits.append(c)
  1659. # Test format-patch with commit range (should get commits 2 and 3)
  1660. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1661. result, _stdout, _stderr = self._run_cli(
  1662. "format-patch", f"{commits[1].decode()}..{commits[3].decode()}"
  1663. )
  1664. self.assertEqual(result, None)
  1665. # Should create patches for commits 2 and 3
  1666. log_output = "\n".join(cm.output)
  1667. self.assertIn("0001-Add-file2.txt.patch", log_output)
  1668. self.assertIn("0002-Add-file3.txt.patch", log_output)
  1669. # Verify patch contents
  1670. with open(os.path.join(self.repo_path, "0001-Add-file2.txt.patch"), "rb") as f:
  1671. content = f.read()
  1672. self.assertIn(b"Subject: [PATCH 1/2] Add file2.txt", content)
  1673. self.assertIn(b"+Content 2", content)
  1674. self.assertNotIn(b"file3.txt", content) # Should not include file3
  1675. with open(os.path.join(self.repo_path, "0002-Add-file3.txt.patch"), "rb") as f:
  1676. content = f.read()
  1677. self.assertIn(b"Subject: [PATCH 2/2] Add file3.txt", content)
  1678. self.assertIn(b"+Content 3", content)
  1679. self.assertNotIn(b"file2.txt", content) # Should not modify file2
  1680. # Clean up
  1681. os.remove(os.path.join(self.repo_path, "0001-Add-file2.txt.patch"))
  1682. os.remove(os.path.join(self.repo_path, "0002-Add-file3.txt.patch"))
  1683. def test_format_patch_stdout(self):
  1684. from dulwich.objects import Blob, Tree
  1685. # Create a commit with modified file
  1686. tree1 = Tree()
  1687. blob1 = Blob.from_string(b"Original content\n")
  1688. self.repo.object_store.add_object(blob1)
  1689. tree1.add(b"file.txt", 0o100644, blob1.id)
  1690. self.repo.object_store.add_object(tree1)
  1691. self.repo.get_worktree().commit(
  1692. message=b"Initial commit",
  1693. tree=tree1.id,
  1694. )
  1695. tree2 = Tree()
  1696. blob2 = Blob.from_string(b"Modified content\n")
  1697. self.repo.object_store.add_object(blob2)
  1698. tree2.add(b"file.txt", 0o100644, blob2.id)
  1699. self.repo.object_store.add_object(tree2)
  1700. self.repo.get_worktree().commit(
  1701. message=b"Modify file.txt",
  1702. tree=tree2.id,
  1703. )
  1704. # Mock stdout as a BytesIO for binary output
  1705. stdout_stream = io.BytesIO()
  1706. stdout_stream.buffer = stdout_stream
  1707. # Run command with --stdout
  1708. old_stdout = sys.stdout
  1709. old_stderr = sys.stderr
  1710. old_cwd = os.getcwd()
  1711. try:
  1712. sys.stdout = stdout_stream
  1713. sys.stderr = io.StringIO()
  1714. os.chdir(self.repo_path)
  1715. cli.main(["format-patch", "--stdout", "-n", "1"])
  1716. finally:
  1717. sys.stdout = old_stdout
  1718. sys.stderr = old_stderr
  1719. os.chdir(old_cwd)
  1720. # Check output
  1721. stdout_stream.seek(0)
  1722. output = stdout_stream.read()
  1723. self.assertIn(b"Subject: [PATCH 1/1] Modify file.txt", output)
  1724. self.assertIn(b"diff --git a/file.txt b/file.txt", output)
  1725. self.assertIn(b"-Original content", output)
  1726. self.assertIn(b"+Modified content", output)
  1727. self.assertIn(b"-- \nDulwich", output)
  1728. def test_format_patch_empty_repo(self):
  1729. # Test with empty repository
  1730. result, stdout, _stderr = self._run_cli("format-patch", "-n", "5")
  1731. self.assertEqual(result, None)
  1732. # Should produce no output for empty repo
  1733. self.assertEqual(stdout.strip(), "")
  1734. class FetchPackCommandTest(DulwichCliTestCase):
  1735. """Tests for fetch-pack command."""
  1736. @patch("dulwich.cli.get_transport_and_path")
  1737. def test_fetch_pack_basic(self, mock_transport):
  1738. # Mock the transport
  1739. mock_client = MagicMock()
  1740. mock_transport.return_value = (mock_client, "/path/to/repo")
  1741. mock_client.fetch.return_value = None
  1742. _result, _stdout, _stderr = self._run_cli(
  1743. "fetch-pack", "git://example.com/repo.git"
  1744. )
  1745. mock_client.fetch.assert_called_once()
  1746. class LsRemoteCommandTest(DulwichCliTestCase):
  1747. """Tests for ls-remote command."""
  1748. def test_ls_remote_basic(self):
  1749. # Create a commit
  1750. test_file = os.path.join(self.repo_path, "test.txt")
  1751. with open(test_file, "w") as f:
  1752. f.write("test")
  1753. self._run_cli("add", "test.txt")
  1754. self._run_cli("commit", "--message=Initial")
  1755. # Test basic ls-remote
  1756. _result, stdout, _stderr = self._run_cli("ls-remote", self.repo_path)
  1757. lines = stdout.strip().split("\n")
  1758. self.assertTrue(any("HEAD" in line for line in lines))
  1759. self.assertTrue(any("refs/heads/master" in line for line in lines))
  1760. def test_ls_remote_symref(self):
  1761. # Create a commit
  1762. test_file = os.path.join(self.repo_path, "test.txt")
  1763. with open(test_file, "w") as f:
  1764. f.write("test")
  1765. self._run_cli("add", "test.txt")
  1766. self._run_cli("commit", "--message=Initial")
  1767. # Test ls-remote with --symref option
  1768. _result, stdout, _stderr = self._run_cli(
  1769. "ls-remote", "--symref", self.repo_path
  1770. )
  1771. lines = stdout.strip().split("\n")
  1772. # Should show symref for HEAD in exact format: "ref: refs/heads/master\tHEAD"
  1773. expected_line = "ref: refs/heads/master\tHEAD"
  1774. self.assertIn(
  1775. expected_line,
  1776. lines,
  1777. f"Expected line '{expected_line}' not found in output: {lines}",
  1778. )
  1779. class PullCommandTest(DulwichCliTestCase):
  1780. """Tests for pull command."""
  1781. @patch("dulwich.porcelain.pull")
  1782. def test_pull_basic(self, mock_pull):
  1783. _result, _stdout, _stderr = self._run_cli("pull", "origin")
  1784. mock_pull.assert_called_once()
  1785. @patch("dulwich.porcelain.pull")
  1786. def test_pull_with_refspec(self, mock_pull):
  1787. _result, _stdout, _stderr = self._run_cli("pull", "origin", "master")
  1788. mock_pull.assert_called_once()
  1789. class PushCommandTest(DulwichCliTestCase):
  1790. """Tests for push command."""
  1791. @patch("dulwich.porcelain.push")
  1792. def test_push_basic(self, mock_push):
  1793. _result, _stdout, _stderr = self._run_cli("push", "origin")
  1794. mock_push.assert_called_once()
  1795. @patch("dulwich.porcelain.push")
  1796. def test_push_force(self, mock_push):
  1797. _result, _stdout, _stderr = self._run_cli("push", "-f", "origin")
  1798. mock_push.assert_called_with(".", "origin", None, force=True)
  1799. class ArchiveCommandTest(DulwichCliTestCase):
  1800. """Tests for archive command."""
  1801. def test_archive_basic(self):
  1802. # Create a commit
  1803. test_file = os.path.join(self.repo_path, "test.txt")
  1804. with open(test_file, "w") as f:
  1805. f.write("test content")
  1806. self._run_cli("add", "test.txt")
  1807. self._run_cli("commit", "--message=Initial")
  1808. # Archive produces binary output, so use BytesIO
  1809. _result, stdout, _stderr = self._run_cli(
  1810. "archive", "HEAD", stdout_stream=io.BytesIO()
  1811. )
  1812. # Should complete without error and produce some binary output
  1813. self.assertIsInstance(stdout, bytes)
  1814. self.assertGreater(len(stdout), 0)
  1815. class ForEachRefCommandTest(DulwichCliTestCase):
  1816. """Tests for for-each-ref command."""
  1817. def test_for_each_ref(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")
  1822. self._run_cli("add", "test.txt")
  1823. self._run_cli("commit", "--message=Initial")
  1824. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1825. _result, _stdout, _stderr = self._run_cli("for-each-ref")
  1826. log_output = "\n".join(cm.output)
  1827. # Just check that we have some refs output and it contains refs/heads
  1828. self.assertTrue(len(cm.output) > 0, "Expected some ref output")
  1829. self.assertIn("refs/heads/", log_output)
  1830. class PackRefsCommandTest(DulwichCliTestCase):
  1831. """Tests for pack-refs command."""
  1832. def test_pack_refs(self):
  1833. # Create some refs
  1834. test_file = os.path.join(self.repo_path, "test.txt")
  1835. with open(test_file, "w") as f:
  1836. f.write("test")
  1837. self._run_cli("add", "test.txt")
  1838. self._run_cli("commit", "--message=Initial")
  1839. self._run_cli("branch", "test-branch")
  1840. _result, _stdout, _stderr = self._run_cli("pack-refs", "--all")
  1841. # Check that packed-refs file exists
  1842. self.assertTrue(
  1843. os.path.exists(os.path.join(self.repo_path, ".git", "packed-refs"))
  1844. )
  1845. class SubmoduleCommandTest(DulwichCliTestCase):
  1846. """Tests for submodule commands."""
  1847. def test_submodule_list(self):
  1848. # Create an initial commit so repo has a HEAD
  1849. test_file = os.path.join(self.repo_path, "test.txt")
  1850. with open(test_file, "w") as f:
  1851. f.write("test")
  1852. self._run_cli("add", "test.txt")
  1853. self._run_cli("commit", "--message=Initial")
  1854. _result, _stdout, _stderr = self._run_cli("submodule")
  1855. # Should not crash on repo without submodules
  1856. def test_submodule_init(self):
  1857. # Create .gitmodules file for init to work
  1858. gitmodules = os.path.join(self.repo_path, ".gitmodules")
  1859. with open(gitmodules, "w") as f:
  1860. f.write("") # Empty .gitmodules file
  1861. _result, _stdout, _stderr = self._run_cli("submodule", "init")
  1862. # Should not crash
  1863. class StashCommandTest(DulwichCliTestCase):
  1864. """Tests for stash commands."""
  1865. def test_stash_list_empty(self):
  1866. _result, _stdout, _stderr = self._run_cli("stash", "list")
  1867. # Should not crash on empty stash
  1868. def test_stash_push_pop(self):
  1869. # Create a file and modify it
  1870. test_file = os.path.join(self.repo_path, "test.txt")
  1871. with open(test_file, "w") as f:
  1872. f.write("initial")
  1873. self._run_cli("add", "test.txt")
  1874. self._run_cli("commit", "--message=Initial")
  1875. # Modify file
  1876. with open(test_file, "w") as f:
  1877. f.write("modified")
  1878. # Stash changes
  1879. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1880. _result, _stdout, _stderr = self._run_cli("stash", "push")
  1881. self.assertIn("Saved working directory", cm.output[0])
  1882. # Note: Dulwich stash doesn't currently update the working tree
  1883. # so the file remains modified after stash push
  1884. # Note: stash pop is not fully implemented in Dulwich yet
  1885. # so we only test stash push here
  1886. class MergeCommandTest(DulwichCliTestCase):
  1887. """Tests for merge command."""
  1888. def test_merge_basic(self):
  1889. # Create initial commit
  1890. test_file = os.path.join(self.repo_path, "test.txt")
  1891. with open(test_file, "w") as f:
  1892. f.write("initial")
  1893. self._run_cli("add", "test.txt")
  1894. self._run_cli("commit", "--message=Initial")
  1895. # Create and checkout new branch
  1896. self._run_cli("branch", "feature")
  1897. self._run_cli("checkout", "feature")
  1898. # Make changes in feature branch
  1899. with open(test_file, "w") as f:
  1900. f.write("feature changes")
  1901. self._run_cli("add", "test.txt")
  1902. self._run_cli("commit", "--message=Feature commit")
  1903. # Go back to main
  1904. self._run_cli("checkout", "master")
  1905. # Merge feature branch
  1906. _result, _stdout, _stderr = self._run_cli("merge", "feature")
  1907. class HelpCommandTest(DulwichCliTestCase):
  1908. """Tests for help command."""
  1909. def test_help_basic(self):
  1910. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1911. _result, _stdout, _stderr = self._run_cli("help")
  1912. log_output = "\n".join(cm.output)
  1913. self.assertIn("dulwich command line tool", log_output)
  1914. def test_help_all(self):
  1915. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1916. _result, _stdout, _stderr = self._run_cli("help", "-a")
  1917. log_output = "\n".join(cm.output)
  1918. self.assertIn("Available commands:", log_output)
  1919. self.assertIn("add", log_output)
  1920. self.assertIn("commit", log_output)
  1921. class RemoteCommandTest(DulwichCliTestCase):
  1922. """Tests for remote commands."""
  1923. def test_remote_add(self):
  1924. _result, _stdout, _stderr = self._run_cli(
  1925. "remote", "add", "origin", "https://github.com/example/repo.git"
  1926. )
  1927. # Check remote was added to config
  1928. config = self.repo.get_config()
  1929. self.assertEqual(
  1930. config.get((b"remote", b"origin"), b"url"),
  1931. b"https://github.com/example/repo.git",
  1932. )
  1933. class CheckIgnoreCommandTest(DulwichCliTestCase):
  1934. """Tests for check-ignore command."""
  1935. def test_check_ignore(self):
  1936. # Create .gitignore
  1937. gitignore = os.path.join(self.repo_path, ".gitignore")
  1938. with open(gitignore, "w") as f:
  1939. f.write("*.log\n")
  1940. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1941. _result, _stdout, _stderr = self._run_cli(
  1942. "check-ignore", "test.log", "test.txt"
  1943. )
  1944. log_output = "\n".join(cm.output)
  1945. self.assertIn("test.log", log_output)
  1946. self.assertNotIn("test.txt", log_output)
  1947. class LsFilesCommandTest(DulwichCliTestCase):
  1948. """Tests for ls-files command."""
  1949. def test_ls_files(self):
  1950. # Add some files
  1951. for name in ["a.txt", "b.txt", "c.txt"]:
  1952. path = os.path.join(self.repo_path, name)
  1953. with open(path, "w") as f:
  1954. f.write(f"content of {name}")
  1955. self._run_cli("add", "a.txt", "b.txt", "c.txt")
  1956. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1957. _result, _stdout, _stderr = self._run_cli("ls-files")
  1958. log_output = "\n".join(cm.output)
  1959. self.assertIn("a.txt", log_output)
  1960. self.assertIn("b.txt", log_output)
  1961. self.assertIn("c.txt", log_output)
  1962. class LsTreeCommandTest(DulwichCliTestCase):
  1963. """Tests for ls-tree command."""
  1964. def test_ls_tree(self):
  1965. # Create a directory structure
  1966. os.mkdir(os.path.join(self.repo_path, "subdir"))
  1967. with open(os.path.join(self.repo_path, "file.txt"), "w") as f:
  1968. f.write("file content")
  1969. with open(os.path.join(self.repo_path, "subdir", "nested.txt"), "w") as f:
  1970. f.write("nested content")
  1971. self._run_cli("add", ".")
  1972. self._run_cli("commit", "--message=Initial")
  1973. _result, stdout, _stderr = self._run_cli("ls-tree", "HEAD")
  1974. self.assertIn("file.txt", stdout)
  1975. self.assertIn("subdir", stdout)
  1976. def test_ls_tree_recursive(self):
  1977. # Create nested structure
  1978. os.mkdir(os.path.join(self.repo_path, "subdir"))
  1979. with open(os.path.join(self.repo_path, "subdir", "nested.txt"), "w") as f:
  1980. f.write("nested")
  1981. self._run_cli("add", ".")
  1982. self._run_cli("commit", "--message=Initial")
  1983. _result, stdout, _stderr = self._run_cli("ls-tree", "-r", "HEAD")
  1984. self.assertIn("subdir/nested.txt", stdout)
  1985. class DescribeCommandTest(DulwichCliTestCase):
  1986. """Tests for describe command."""
  1987. def test_describe(self):
  1988. # Create tagged commit
  1989. test_file = os.path.join(self.repo_path, "test.txt")
  1990. with open(test_file, "w") as f:
  1991. f.write("test")
  1992. self._run_cli("add", "test.txt")
  1993. self._run_cli("commit", "--message=Initial")
  1994. self._run_cli("tag", "v1.0")
  1995. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  1996. _result, _stdout, _stderr = self._run_cli("describe")
  1997. self.assertIn("v1.0", cm.output[0])
  1998. class FsckCommandTest(DulwichCliTestCase):
  1999. """Tests for fsck command."""
  2000. def test_fsck(self):
  2001. # Create a commit
  2002. test_file = os.path.join(self.repo_path, "test.txt")
  2003. with open(test_file, "w") as f:
  2004. f.write("test")
  2005. self._run_cli("add", "test.txt")
  2006. self._run_cli("commit", "--message=Initial")
  2007. _result, _stdout, _stderr = self._run_cli("fsck")
  2008. # Should complete without errors
  2009. class GrepCommandTest(DulwichCliTestCase):
  2010. """Tests for grep command."""
  2011. def test_grep_basic(self):
  2012. # Create test files
  2013. with open(os.path.join(self.repo_path, "file1.txt"), "w") as f:
  2014. f.write("hello world\n")
  2015. with open(os.path.join(self.repo_path, "file2.txt"), "w") as f:
  2016. f.write("foo bar\n")
  2017. self._run_cli("add", "file1.txt", "file2.txt")
  2018. self._run_cli("commit", "--message=Add files")
  2019. _result, stdout, _stderr = self._run_cli("grep", "world")
  2020. self.assertEqual("file1.txt:hello world\n", stdout.replace("\r\n", "\n"))
  2021. def test_grep_line_numbers(self):
  2022. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  2023. f.write("line1\nline2\nline3\n")
  2024. self._run_cli("add", "test.txt")
  2025. self._run_cli("commit", "--message=Add test")
  2026. _result, stdout, _stderr = self._run_cli("grep", "-n", "line")
  2027. self.assertEqual(
  2028. "test.txt:1:line1\ntest.txt:2:line2\ntest.txt:3:line3\n",
  2029. stdout.replace("\r\n", "\n"),
  2030. )
  2031. def test_grep_case_insensitive(self):
  2032. with open(os.path.join(self.repo_path, "case.txt"), "w") as f:
  2033. f.write("Hello World\n")
  2034. self._run_cli("add", "case.txt")
  2035. self._run_cli("commit", "--message=Add case")
  2036. _result, stdout, _stderr = self._run_cli("grep", "-i", "hello")
  2037. self.assertEqual("case.txt:Hello World\n", stdout.replace("\r\n", "\n"))
  2038. def test_grep_no_matches(self):
  2039. with open(os.path.join(self.repo_path, "empty.txt"), "w") as f:
  2040. f.write("nothing here\n")
  2041. self._run_cli("add", "empty.txt")
  2042. self._run_cli("commit", "--message=Add empty")
  2043. _result, stdout, _stderr = self._run_cli("grep", "nonexistent")
  2044. self.assertEqual("", stdout)
  2045. class RepackCommandTest(DulwichCliTestCase):
  2046. """Tests for repack command."""
  2047. def test_repack(self):
  2048. # Create some objects
  2049. for i in range(5):
  2050. test_file = os.path.join(self.repo_path, f"test{i}.txt")
  2051. with open(test_file, "w") as f:
  2052. f.write(f"content {i}")
  2053. self._run_cli("add", f"test{i}.txt")
  2054. self._run_cli("commit", f"--message=Commit {i}")
  2055. _result, _stdout, _stderr = self._run_cli("repack")
  2056. # Should create pack files
  2057. pack_dir = os.path.join(self.repo_path, ".git", "objects", "pack")
  2058. self.assertTrue(any(f.endswith(".pack") for f in os.listdir(pack_dir)))
  2059. class ResetCommandTest(DulwichCliTestCase):
  2060. """Tests for reset command."""
  2061. def test_reset_soft(self):
  2062. # Create commits
  2063. test_file = os.path.join(self.repo_path, "test.txt")
  2064. with open(test_file, "w") as f:
  2065. f.write("first")
  2066. self._run_cli("add", "test.txt")
  2067. self._run_cli("commit", "--message=First")
  2068. first_commit = self.repo.head()
  2069. with open(test_file, "w") as f:
  2070. f.write("second")
  2071. self._run_cli("add", "test.txt")
  2072. self._run_cli("commit", "--message=Second")
  2073. # Reset soft
  2074. _result, _stdout, _stderr = self._run_cli(
  2075. "reset", "--soft", first_commit.decode()
  2076. )
  2077. # HEAD should be at first commit
  2078. self.assertEqual(self.repo.head(), first_commit)
  2079. class WriteTreeCommandTest(DulwichCliTestCase):
  2080. """Tests for write-tree command."""
  2081. def test_write_tree(self):
  2082. # Create and add files
  2083. test_file = os.path.join(self.repo_path, "test.txt")
  2084. with open(test_file, "w") as f:
  2085. f.write("test")
  2086. self._run_cli("add", "test.txt")
  2087. _result, stdout, _stderr = self._run_cli("write-tree")
  2088. # Should output tree SHA
  2089. self.assertEqual(len(stdout.strip()), 40)
  2090. class UpdateServerInfoCommandTest(DulwichCliTestCase):
  2091. """Tests for update-server-info command."""
  2092. def test_update_server_info(self):
  2093. _result, _stdout, _stderr = self._run_cli("update-server-info")
  2094. # Should create info/refs file
  2095. info_refs = os.path.join(self.repo_path, ".git", "info", "refs")
  2096. self.assertTrue(os.path.exists(info_refs))
  2097. class SymbolicRefCommandTest(DulwichCliTestCase):
  2098. """Tests for symbolic-ref command."""
  2099. def test_symbolic_ref(self):
  2100. # Create a branch
  2101. test_file = os.path.join(self.repo_path, "test.txt")
  2102. with open(test_file, "w") as f:
  2103. f.write("test")
  2104. self._run_cli("add", "test.txt")
  2105. self._run_cli("commit", "--message=Initial")
  2106. self._run_cli("branch", "test-branch")
  2107. _result, _stdout, _stderr = self._run_cli(
  2108. "symbolic-ref", "HEAD", "refs/heads/test-branch"
  2109. )
  2110. # HEAD should now point to test-branch
  2111. self.assertEqual(
  2112. self.repo.refs.read_ref(b"HEAD"), b"ref: refs/heads/test-branch"
  2113. )
  2114. class BundleCommandTest(DulwichCliTestCase):
  2115. """Tests for bundle commands."""
  2116. def setUp(self):
  2117. super().setUp()
  2118. # Create a basic repository with some commits for bundle testing
  2119. # Create initial commit
  2120. test_file = os.path.join(self.repo_path, "file1.txt")
  2121. with open(test_file, "w") as f:
  2122. f.write("Content of file1\n")
  2123. self._run_cli("add", "file1.txt")
  2124. self._run_cli("commit", "--message=Initial commit")
  2125. # Create second commit
  2126. test_file2 = os.path.join(self.repo_path, "file2.txt")
  2127. with open(test_file2, "w") as f:
  2128. f.write("Content of file2\n")
  2129. self._run_cli("add", "file2.txt")
  2130. self._run_cli("commit", "--message=Add file2")
  2131. # Create a branch and tag for testing
  2132. self._run_cli("branch", "feature")
  2133. self._run_cli("tag", "v1.0")
  2134. def test_bundle_create_basic(self):
  2135. """Test basic bundle creation."""
  2136. bundle_file = os.path.join(self.test_dir, "test.bundle")
  2137. result, _stdout, _stderr = self._run_cli(
  2138. "bundle", "create", bundle_file, "HEAD"
  2139. )
  2140. self.assertEqual(result, 0)
  2141. self.assertTrue(os.path.exists(bundle_file))
  2142. self.assertGreater(os.path.getsize(bundle_file), 0)
  2143. def test_bundle_create_all_refs(self):
  2144. """Test bundle creation with --all flag."""
  2145. bundle_file = os.path.join(self.test_dir, "all.bundle")
  2146. result, _stdout, _stderr = self._run_cli(
  2147. "bundle", "create", "--all", bundle_file
  2148. )
  2149. self.assertEqual(result, 0)
  2150. self.assertTrue(os.path.exists(bundle_file))
  2151. def test_bundle_create_specific_refs(self):
  2152. """Test bundle creation with specific refs."""
  2153. bundle_file = os.path.join(self.test_dir, "refs.bundle")
  2154. # Only use HEAD since feature branch may not exist
  2155. result, _stdout, _stderr = self._run_cli(
  2156. "bundle", "create", bundle_file, "HEAD"
  2157. )
  2158. self.assertEqual(result, 0)
  2159. self.assertTrue(os.path.exists(bundle_file))
  2160. def test_bundle_create_with_range(self):
  2161. """Test bundle creation with commit range."""
  2162. # Get the first commit SHA by looking at the log
  2163. result, stdout, _stderr = self._run_cli("log", "--reverse")
  2164. lines = stdout.strip().split("\n")
  2165. # Find first commit line that contains a SHA
  2166. first_commit = None
  2167. for line in lines:
  2168. if line.startswith("commit "):
  2169. first_commit = line.split()[1][:8] # Get short SHA
  2170. break
  2171. if first_commit:
  2172. bundle_file = os.path.join(self.test_dir, "range.bundle")
  2173. result, stdout, _stderr = self._run_cli(
  2174. "bundle", "create", bundle_file, f"{first_commit}..HEAD"
  2175. )
  2176. self.assertEqual(result, 0)
  2177. self.assertTrue(os.path.exists(bundle_file))
  2178. else:
  2179. self.skipTest("Could not determine first commit SHA")
  2180. def test_bundle_create_to_stdout(self):
  2181. """Test bundle creation to stdout."""
  2182. result, stdout, _stderr = self._run_cli("bundle", "create", "-", "HEAD")
  2183. self.assertEqual(result, 0)
  2184. self.assertGreater(len(stdout), 0)
  2185. # Bundle output is binary, so check it's not empty
  2186. self.assertIsInstance(stdout, (str, bytes))
  2187. def test_bundle_create_no_refs(self):
  2188. """Test bundle creation with no refs specified."""
  2189. bundle_file = os.path.join(self.test_dir, "noref.bundle")
  2190. with self.assertLogs("dulwich.cli", level="ERROR") as cm:
  2191. result, _stdout, _stderr = self._run_cli("bundle", "create", bundle_file)
  2192. self.assertEqual(result, 1)
  2193. self.assertIn("No refs specified", cm.output[0])
  2194. def test_bundle_create_empty_bundle_refused(self):
  2195. """Test that empty bundles are refused."""
  2196. bundle_file = os.path.join(self.test_dir, "empty.bundle")
  2197. # Try to create bundle with non-existent ref - this should fail with KeyError
  2198. with self.assertRaises(KeyError):
  2199. _result, _stdout, _stderr = self._run_cli(
  2200. "bundle", "create", bundle_file, "nonexistent-ref"
  2201. )
  2202. def test_bundle_verify_valid(self):
  2203. """Test bundle verification of valid bundle."""
  2204. bundle_file = os.path.join(self.test_dir, "valid.bundle")
  2205. # First create a bundle
  2206. result, _stdout, _stderr = self._run_cli(
  2207. "bundle", "create", bundle_file, "HEAD"
  2208. )
  2209. self.assertEqual(result, 0)
  2210. # Now verify it
  2211. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2212. result, _stdout, _stderr = self._run_cli("bundle", "verify", bundle_file)
  2213. self.assertEqual(result, 0)
  2214. self.assertIn("valid and can be applied", cm.output[0])
  2215. def test_bundle_verify_quiet(self):
  2216. """Test bundle verification with quiet flag."""
  2217. bundle_file = os.path.join(self.test_dir, "quiet.bundle")
  2218. # Create bundle
  2219. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2220. # Verify quietly
  2221. result, stdout, _stderr = self._run_cli(
  2222. "bundle", "verify", "--quiet", bundle_file
  2223. )
  2224. self.assertEqual(result, 0)
  2225. self.assertEqual(stdout.strip(), "")
  2226. def test_bundle_verify_from_stdin(self):
  2227. """Test bundle verification from stdin."""
  2228. bundle_file = os.path.join(self.test_dir, "stdin.bundle")
  2229. # Create bundle
  2230. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2231. # Read bundle content
  2232. with open(bundle_file, "rb") as f:
  2233. bundle_content = f.read()
  2234. # Mock stdin with bundle content
  2235. old_stdin = sys.stdin
  2236. try:
  2237. sys.stdin = io.BytesIO(bundle_content)
  2238. sys.stdin.buffer = sys.stdin
  2239. result, _stdout, _stderr = self._run_cli("bundle", "verify", "-")
  2240. self.assertEqual(result, 0)
  2241. finally:
  2242. sys.stdin = old_stdin
  2243. def test_bundle_list_heads(self):
  2244. """Test listing bundle heads."""
  2245. bundle_file = os.path.join(self.test_dir, "heads.bundle")
  2246. # Create bundle with HEAD only
  2247. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2248. # List heads
  2249. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2250. result, _stdout, _stderr = self._run_cli(
  2251. "bundle", "list-heads", bundle_file
  2252. )
  2253. self.assertEqual(result, 0)
  2254. # Should contain at least the HEAD reference
  2255. self.assertTrue(len(cm.output) > 0)
  2256. def test_bundle_list_heads_specific_refs(self):
  2257. """Test listing specific bundle heads."""
  2258. bundle_file = os.path.join(self.test_dir, "specific.bundle")
  2259. # Create bundle with HEAD
  2260. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2261. # List heads without filtering
  2262. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2263. result, _stdout, _stderr = self._run_cli(
  2264. "bundle", "list-heads", bundle_file
  2265. )
  2266. self.assertEqual(result, 0)
  2267. # Should contain some reference
  2268. self.assertTrue(len(cm.output) > 0)
  2269. def test_bundle_list_heads_from_stdin(self):
  2270. """Test listing bundle heads from stdin."""
  2271. bundle_file = os.path.join(self.test_dir, "stdin-heads.bundle")
  2272. # Create bundle
  2273. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2274. # Read bundle content
  2275. with open(bundle_file, "rb") as f:
  2276. bundle_content = f.read()
  2277. # Mock stdin
  2278. old_stdin = sys.stdin
  2279. try:
  2280. sys.stdin = io.BytesIO(bundle_content)
  2281. sys.stdin.buffer = sys.stdin
  2282. result, _stdout, _stderr = self._run_cli("bundle", "list-heads", "-")
  2283. self.assertEqual(result, 0)
  2284. finally:
  2285. sys.stdin = old_stdin
  2286. def test_bundle_unbundle(self):
  2287. """Test bundle unbundling."""
  2288. bundle_file = os.path.join(self.test_dir, "unbundle.bundle")
  2289. # Create bundle
  2290. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2291. # Unbundle
  2292. result, _stdout, _stderr = self._run_cli("bundle", "unbundle", bundle_file)
  2293. self.assertEqual(result, 0)
  2294. def test_bundle_unbundle_specific_refs(self):
  2295. """Test unbundling specific refs."""
  2296. bundle_file = os.path.join(self.test_dir, "unbundle-specific.bundle")
  2297. # Create bundle with HEAD
  2298. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2299. # Unbundle only HEAD
  2300. result, _stdout, _stderr = self._run_cli(
  2301. "bundle", "unbundle", bundle_file, "HEAD"
  2302. )
  2303. self.assertEqual(result, 0)
  2304. def test_bundle_unbundle_from_stdin(self):
  2305. """Test unbundling from stdin."""
  2306. bundle_file = os.path.join(self.test_dir, "stdin-unbundle.bundle")
  2307. # Create bundle
  2308. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2309. # Read bundle content to simulate stdin
  2310. with open(bundle_file, "rb") as f:
  2311. bundle_content = f.read()
  2312. # Mock stdin with bundle content
  2313. old_stdin = sys.stdin
  2314. try:
  2315. # Create a BytesIO object with buffer attribute
  2316. mock_stdin = io.BytesIO(bundle_content)
  2317. mock_stdin.buffer = mock_stdin
  2318. sys.stdin = mock_stdin
  2319. result, _stdout, _stderr = self._run_cli("bundle", "unbundle", "-")
  2320. self.assertEqual(result, 0)
  2321. finally:
  2322. sys.stdin = old_stdin
  2323. def test_bundle_unbundle_with_progress(self):
  2324. """Test unbundling with progress output."""
  2325. bundle_file = os.path.join(self.test_dir, "progress.bundle")
  2326. # Create bundle
  2327. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2328. # Unbundle with progress
  2329. result, _stdout, _stderr = self._run_cli(
  2330. "bundle", "unbundle", "--progress", bundle_file
  2331. )
  2332. self.assertEqual(result, 0)
  2333. def test_bundle_create_with_progress(self):
  2334. """Test bundle creation with progress output."""
  2335. bundle_file = os.path.join(self.test_dir, "create-progress.bundle")
  2336. result, _stdout, _stderr = self._run_cli(
  2337. "bundle", "create", "--progress", bundle_file, "HEAD"
  2338. )
  2339. self.assertEqual(result, 0)
  2340. self.assertTrue(os.path.exists(bundle_file))
  2341. def test_bundle_create_with_quiet(self):
  2342. """Test bundle creation with quiet flag."""
  2343. bundle_file = os.path.join(self.test_dir, "quiet-create.bundle")
  2344. result, _stdout, _stderr = self._run_cli(
  2345. "bundle", "create", "--quiet", bundle_file, "HEAD"
  2346. )
  2347. self.assertEqual(result, 0)
  2348. self.assertTrue(os.path.exists(bundle_file))
  2349. def test_bundle_create_version_2(self):
  2350. """Test bundle creation with specific version."""
  2351. bundle_file = os.path.join(self.test_dir, "v2.bundle")
  2352. result, _stdout, _stderr = self._run_cli(
  2353. "bundle", "create", "--version", "2", bundle_file, "HEAD"
  2354. )
  2355. self.assertEqual(result, 0)
  2356. self.assertTrue(os.path.exists(bundle_file))
  2357. def test_bundle_create_version_3(self):
  2358. """Test bundle creation with version 3."""
  2359. bundle_file = os.path.join(self.test_dir, "v3.bundle")
  2360. result, _stdout, _stderr = self._run_cli(
  2361. "bundle", "create", "--version", "3", bundle_file, "HEAD"
  2362. )
  2363. self.assertEqual(result, 0)
  2364. self.assertTrue(os.path.exists(bundle_file))
  2365. def test_bundle_invalid_subcommand(self):
  2366. """Test invalid bundle subcommand."""
  2367. with self.assertLogs("dulwich.cli", level="ERROR") as cm:
  2368. result, _stdout, _stderr = self._run_cli("bundle", "invalid-command")
  2369. self.assertEqual(result, 1)
  2370. self.assertIn("Unknown bundle subcommand", cm.output[0])
  2371. def test_bundle_no_subcommand(self):
  2372. """Test bundle command with no subcommand."""
  2373. with self.assertLogs("dulwich.cli", level="ERROR") as cm:
  2374. result, _stdout, _stderr = self._run_cli("bundle")
  2375. self.assertEqual(result, 1)
  2376. self.assertIn("Usage: bundle", cm.output[0])
  2377. def test_bundle_create_with_stdin_refs(self):
  2378. """Test bundle creation reading refs from stdin."""
  2379. bundle_file = os.path.join(self.test_dir, "stdin-refs.bundle")
  2380. # Mock stdin with refs
  2381. old_stdin = sys.stdin
  2382. try:
  2383. sys.stdin = io.StringIO("master\nfeature\n")
  2384. result, _stdout, _stderr = self._run_cli(
  2385. "bundle", "create", "--stdin", bundle_file
  2386. )
  2387. self.assertEqual(result, 0)
  2388. self.assertTrue(os.path.exists(bundle_file))
  2389. finally:
  2390. sys.stdin = old_stdin
  2391. def test_bundle_verify_missing_prerequisites(self):
  2392. """Test bundle verification with missing prerequisites."""
  2393. # Create a simple bundle first
  2394. bundle_file = os.path.join(self.test_dir, "prereq.bundle")
  2395. self._run_cli("bundle", "create", bundle_file, "HEAD")
  2396. # Create a new repo to simulate missing objects
  2397. new_repo_path = os.path.join(self.test_dir, "new_repo")
  2398. os.mkdir(new_repo_path)
  2399. new_repo = Repo.init(new_repo_path)
  2400. new_repo.close()
  2401. # Try to verify in new repo
  2402. old_cwd = os.getcwd()
  2403. try:
  2404. os.chdir(new_repo_path)
  2405. result, _stdout, _stderr = self._run_cli("bundle", "verify", bundle_file)
  2406. # Just check that verification runs - result depends on bundle content
  2407. self.assertIn(result, [0, 1])
  2408. finally:
  2409. os.chdir(old_cwd)
  2410. def test_bundle_create_with_committish_range(self):
  2411. """Test bundle creation with commit range using parse_committish_range."""
  2412. # Create additional commits for range testing
  2413. test_file3 = os.path.join(self.repo_path, "file3.txt")
  2414. with open(test_file3, "w") as f:
  2415. f.write("Content of file3\n")
  2416. self._run_cli("add", "file3.txt")
  2417. self._run_cli("commit", "--message=Add file3")
  2418. # Get commit SHAs
  2419. result, stdout, _stderr = self._run_cli("log")
  2420. lines = stdout.strip().split("\n")
  2421. # Extract SHAs from commit lines
  2422. commits = []
  2423. for line in lines:
  2424. if line.startswith("commit:"):
  2425. sha = line.split()[1]
  2426. commits.append(sha[:8]) # Get short SHA
  2427. # We should have exactly 3 commits: Add file3, Add file2, Initial commit
  2428. self.assertEqual(len(commits), 3)
  2429. bundle_file = os.path.join(self.test_dir, "range-test.bundle")
  2430. # Test with commit range using .. syntax
  2431. # Create a bundle containing commits reachable from commits[0] but not from commits[2]
  2432. result, stdout, stderr = self._run_cli(
  2433. "bundle", "create", bundle_file, f"{commits[2]}..HEAD"
  2434. )
  2435. if result != 0:
  2436. self.fail(
  2437. f"Bundle create failed with exit code {result}. stdout: {stdout!r}, stderr: {stderr!r}"
  2438. )
  2439. self.assertEqual(result, 0)
  2440. self.assertTrue(os.path.exists(bundle_file))
  2441. # Verify the bundle was created
  2442. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2443. result, stdout, stderr = self._run_cli("bundle", "verify", bundle_file)
  2444. self.assertEqual(result, 0)
  2445. self.assertIn("valid and can be applied", cm.output[0])
  2446. class FormatBytesTestCase(TestCase):
  2447. """Tests for format_bytes function."""
  2448. def test_bytes(self):
  2449. """Test formatting bytes."""
  2450. self.assertEqual("0.0 B", format_bytes(0))
  2451. self.assertEqual("1.0 B", format_bytes(1))
  2452. self.assertEqual("512.0 B", format_bytes(512))
  2453. self.assertEqual("1023.0 B", format_bytes(1023))
  2454. def test_kilobytes(self):
  2455. """Test formatting kilobytes."""
  2456. self.assertEqual("1.0 KB", format_bytes(1024))
  2457. self.assertEqual("1.5 KB", format_bytes(1536))
  2458. self.assertEqual("2.0 KB", format_bytes(2048))
  2459. self.assertEqual("1023.0 KB", format_bytes(1024 * 1023))
  2460. def test_megabytes(self):
  2461. """Test formatting megabytes."""
  2462. self.assertEqual("1.0 MB", format_bytes(1024 * 1024))
  2463. self.assertEqual("1.5 MB", format_bytes(1024 * 1024 * 1.5))
  2464. self.assertEqual("10.0 MB", format_bytes(1024 * 1024 * 10))
  2465. self.assertEqual("1023.0 MB", format_bytes(1024 * 1024 * 1023))
  2466. def test_gigabytes(self):
  2467. """Test formatting gigabytes."""
  2468. self.assertEqual("1.0 GB", format_bytes(1024 * 1024 * 1024))
  2469. self.assertEqual("2.5 GB", format_bytes(1024 * 1024 * 1024 * 2.5))
  2470. self.assertEqual("1023.0 GB", format_bytes(1024 * 1024 * 1024 * 1023))
  2471. def test_terabytes(self):
  2472. """Test formatting terabytes."""
  2473. self.assertEqual("1.0 TB", format_bytes(1024 * 1024 * 1024 * 1024))
  2474. self.assertEqual("5.0 TB", format_bytes(1024 * 1024 * 1024 * 1024 * 5))
  2475. self.assertEqual("1000.0 TB", format_bytes(1024 * 1024 * 1024 * 1024 * 1000))
  2476. class GetPagerTest(TestCase):
  2477. """Tests for get_pager function."""
  2478. def setUp(self):
  2479. super().setUp()
  2480. # Save original environment
  2481. self.original_env = os.environ.copy()
  2482. # Clear pager-related environment variables
  2483. for var in ["DULWICH_PAGER", "GIT_PAGER", "PAGER"]:
  2484. os.environ.pop(var, None)
  2485. # Reset the global pager disable flag
  2486. cli.get_pager._disabled = False
  2487. def tearDown(self):
  2488. super().tearDown()
  2489. # Restore original environment
  2490. os.environ.clear()
  2491. os.environ.update(self.original_env)
  2492. # Reset the global pager disable flag
  2493. cli.get_pager._disabled = False
  2494. def test_pager_disabled_globally(self):
  2495. """Test that globally disabled pager returns stdout wrapper."""
  2496. cli.disable_pager()
  2497. pager = cli.get_pager()
  2498. self.assertIsInstance(pager, cli._StreamContextAdapter)
  2499. self.assertEqual(pager.stream, sys.stdout)
  2500. def test_pager_not_tty(self):
  2501. """Test that pager is disabled when stdout is not a TTY."""
  2502. with patch("sys.stdout.isatty", return_value=False):
  2503. pager = cli.get_pager()
  2504. self.assertIsInstance(pager, cli._StreamContextAdapter)
  2505. def test_pager_env_dulwich_pager(self):
  2506. """Test DULWICH_PAGER environment variable."""
  2507. os.environ["DULWICH_PAGER"] = "custom_pager"
  2508. with patch("sys.stdout.isatty", return_value=True):
  2509. pager = cli.get_pager()
  2510. self.assertIsInstance(pager, cli.Pager)
  2511. self.assertEqual(pager.pager_cmd, "custom_pager")
  2512. def test_pager_env_dulwich_pager_false(self):
  2513. """Test DULWICH_PAGER=false disables pager."""
  2514. os.environ["DULWICH_PAGER"] = "false"
  2515. with patch("sys.stdout.isatty", return_value=True):
  2516. pager = cli.get_pager()
  2517. self.assertIsInstance(pager, cli._StreamContextAdapter)
  2518. def test_pager_env_git_pager(self):
  2519. """Test GIT_PAGER environment variable."""
  2520. os.environ["GIT_PAGER"] = "git_custom_pager"
  2521. with patch("sys.stdout.isatty", return_value=True):
  2522. pager = cli.get_pager()
  2523. self.assertIsInstance(pager, cli.Pager)
  2524. self.assertEqual(pager.pager_cmd, "git_custom_pager")
  2525. def test_pager_env_pager(self):
  2526. """Test PAGER environment variable."""
  2527. os.environ["PAGER"] = "my_pager"
  2528. with patch("sys.stdout.isatty", return_value=True):
  2529. pager = cli.get_pager()
  2530. self.assertIsInstance(pager, cli.Pager)
  2531. self.assertEqual(pager.pager_cmd, "my_pager")
  2532. def test_pager_env_priority(self):
  2533. """Test environment variable priority order."""
  2534. os.environ["PAGER"] = "pager_low"
  2535. os.environ["GIT_PAGER"] = "pager_medium"
  2536. os.environ["DULWICH_PAGER"] = "pager_high"
  2537. with patch("sys.stdout.isatty", return_value=True):
  2538. pager = cli.get_pager()
  2539. self.assertEqual(pager.pager_cmd, "pager_high")
  2540. def test_pager_config_core_pager(self):
  2541. """Test core.pager configuration."""
  2542. config = MagicMock()
  2543. config.get.return_value = b"config_pager"
  2544. with patch("sys.stdout.isatty", return_value=True):
  2545. pager = cli.get_pager(config=config)
  2546. self.assertIsInstance(pager, cli.Pager)
  2547. self.assertEqual(pager.pager_cmd, "config_pager")
  2548. config.get.assert_called_with(("core",), b"pager")
  2549. def test_pager_config_core_pager_false(self):
  2550. """Test core.pager=false disables pager."""
  2551. config = MagicMock()
  2552. config.get.return_value = b"false"
  2553. with patch("sys.stdout.isatty", return_value=True):
  2554. pager = cli.get_pager(config=config)
  2555. self.assertIsInstance(pager, cli._StreamContextAdapter)
  2556. def test_pager_config_core_pager_empty(self):
  2557. """Test core.pager="" disables pager."""
  2558. config = MagicMock()
  2559. config.get.return_value = b""
  2560. with patch("sys.stdout.isatty", return_value=True):
  2561. pager = cli.get_pager(config=config)
  2562. self.assertIsInstance(pager, cli._StreamContextAdapter)
  2563. def test_pager_config_per_command(self):
  2564. """Test per-command pager configuration."""
  2565. config = MagicMock()
  2566. config.get.side_effect = lambda section, key: {
  2567. (("pager",), b"log"): b"log_pager",
  2568. }.get((section, key), KeyError())
  2569. with patch("sys.stdout.isatty", return_value=True):
  2570. pager = cli.get_pager(config=config, cmd_name="log")
  2571. self.assertIsInstance(pager, cli.Pager)
  2572. self.assertEqual(pager.pager_cmd, "log_pager")
  2573. def test_pager_config_per_command_false(self):
  2574. """Test per-command pager=false disables pager."""
  2575. config = MagicMock()
  2576. config.get.return_value = b"false"
  2577. with patch("sys.stdout.isatty", return_value=True):
  2578. pager = cli.get_pager(config=config, cmd_name="log")
  2579. self.assertIsInstance(pager, cli._StreamContextAdapter)
  2580. def test_pager_config_per_command_true(self):
  2581. """Test per-command pager=true uses default pager."""
  2582. config = MagicMock()
  2583. def get_side_effect(section, key):
  2584. if section == ("pager",) and key == b"log":
  2585. return b"true"
  2586. raise KeyError
  2587. config.get.side_effect = get_side_effect
  2588. with patch("sys.stdout.isatty", return_value=True):
  2589. with patch("shutil.which", side_effect=lambda cmd: cmd == "less"):
  2590. pager = cli.get_pager(config=config, cmd_name="log")
  2591. self.assertIsInstance(pager, cli.Pager)
  2592. self.assertEqual(pager.pager_cmd, "less -FRX")
  2593. def test_pager_priority_order(self):
  2594. """Test complete priority order."""
  2595. # Set up all possible configurations
  2596. os.environ["PAGER"] = "env_pager"
  2597. os.environ["GIT_PAGER"] = "env_git_pager"
  2598. config = MagicMock()
  2599. def get_side_effect(section, key):
  2600. if section == ("pager",) and key == b"log":
  2601. return b"cmd_pager"
  2602. elif section == ("core",) and key == b"pager":
  2603. return b"core_pager"
  2604. raise KeyError
  2605. config.get.side_effect = get_side_effect
  2606. with patch("sys.stdout.isatty", return_value=True):
  2607. # Per-command config should win
  2608. pager = cli.get_pager(config=config, cmd_name="log")
  2609. self.assertEqual(pager.pager_cmd, "cmd_pager")
  2610. def test_pager_fallback_less(self):
  2611. """Test fallback to less with proper flags."""
  2612. with patch("sys.stdout.isatty", return_value=True):
  2613. with patch("shutil.which", side_effect=lambda cmd: cmd == "less"):
  2614. pager = cli.get_pager()
  2615. self.assertIsInstance(pager, cli.Pager)
  2616. self.assertEqual(pager.pager_cmd, "less -FRX")
  2617. def test_pager_fallback_more(self):
  2618. """Test fallback to more when less is not available."""
  2619. with patch("sys.stdout.isatty", return_value=True):
  2620. with patch("shutil.which", side_effect=lambda cmd: cmd == "more"):
  2621. pager = cli.get_pager()
  2622. self.assertIsInstance(pager, cli.Pager)
  2623. self.assertEqual(pager.pager_cmd, "more")
  2624. def test_pager_fallback_cat(self):
  2625. """Test ultimate fallback to cat."""
  2626. with patch("sys.stdout.isatty", return_value=True):
  2627. with patch("shutil.which", return_value=None):
  2628. pager = cli.get_pager()
  2629. self.assertIsInstance(pager, cli.Pager)
  2630. self.assertEqual(pager.pager_cmd, "cat")
  2631. def test_pager_context_manager(self):
  2632. """Test that pager works as a context manager."""
  2633. with patch("sys.stdout.isatty", return_value=True):
  2634. with cli.get_pager() as pager:
  2635. self.assertTrue(hasattr(pager, "write"))
  2636. self.assertTrue(hasattr(pager, "flush"))
  2637. class WorktreeCliTests(DulwichCliTestCase):
  2638. """Tests for worktree CLI commands."""
  2639. def setUp(self):
  2640. super().setUp()
  2641. # Base class already creates and initializes the repo
  2642. # Just create initial commit
  2643. with open(os.path.join(self.repo_path, "test.txt"), "w") as f:
  2644. f.write("test content")
  2645. from dulwich import porcelain
  2646. porcelain.add(self.repo_path, ["test.txt"])
  2647. porcelain.commit(self.repo_path, message=b"Initial commit")
  2648. def test_worktree_list(self):
  2649. """Test worktree list command."""
  2650. # Change to repo directory
  2651. old_cwd = os.getcwd()
  2652. os.chdir(self.repo_path)
  2653. try:
  2654. io.StringIO()
  2655. cmd = cli.cmd_worktree()
  2656. result = cmd.run(["list"])
  2657. # Should list the main worktree
  2658. self.assertEqual(result, 0)
  2659. finally:
  2660. os.chdir(old_cwd)
  2661. def test_worktree_add(self):
  2662. """Test worktree add command."""
  2663. wt_path = os.path.join(self.test_dir, "worktree1")
  2664. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2665. result, _stdout, _stderr = self._run_cli(
  2666. "worktree", "add", wt_path, "feature"
  2667. )
  2668. self.assertEqual(result, 0)
  2669. self.assertTrue(os.path.exists(wt_path))
  2670. log_output = "\n".join(cm.output)
  2671. self.assertIn("Worktree added:", log_output)
  2672. def test_worktree_add_detached(self):
  2673. """Test worktree add with detached HEAD."""
  2674. wt_path = os.path.join(self.test_dir, "detached-wt")
  2675. # Change to repo directory
  2676. old_cwd = os.getcwd()
  2677. os.chdir(self.repo_path)
  2678. try:
  2679. cmd = cli.cmd_worktree()
  2680. with patch("sys.stdout", new_callable=io.StringIO):
  2681. result = cmd.run(["add", "--detach", wt_path])
  2682. self.assertEqual(result, 0)
  2683. self.assertTrue(os.path.exists(wt_path))
  2684. finally:
  2685. os.chdir(old_cwd)
  2686. def test_worktree_remove(self):
  2687. """Test worktree remove command."""
  2688. # First add a worktree
  2689. wt_path = os.path.join(self.test_dir, "to-remove")
  2690. result, _stdout, _stderr = self._run_cli("worktree", "add", wt_path)
  2691. self.assertEqual(result, 0)
  2692. # Then remove it
  2693. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2694. result, _stdout, _stderr = self._run_cli("worktree", "remove", wt_path)
  2695. self.assertEqual(result, 0)
  2696. self.assertFalse(os.path.exists(wt_path))
  2697. log_output = "\n".join(cm.output)
  2698. self.assertIn("Worktree removed:", log_output)
  2699. def test_worktree_prune(self):
  2700. """Test worktree prune command."""
  2701. # Add a worktree and manually remove it
  2702. wt_path = os.path.join(self.test_dir, "to-prune")
  2703. result, _stdout, _stderr = self._run_cli("worktree", "add", wt_path)
  2704. self.assertEqual(result, 0)
  2705. shutil.rmtree(wt_path)
  2706. # Prune
  2707. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2708. result, _stdout, _stderr = self._run_cli("worktree", "prune", "-v")
  2709. self.assertEqual(result, 0)
  2710. log_output = "\n".join(cm.output)
  2711. self.assertIn("to-prune", log_output)
  2712. def test_worktree_lock_unlock(self):
  2713. """Test worktree lock and unlock commands."""
  2714. # Add a worktree
  2715. wt_path = os.path.join(self.test_dir, "lockable")
  2716. result, _stdout, _stderr = self._run_cli("worktree", "add", wt_path)
  2717. self.assertEqual(result, 0)
  2718. # Lock it
  2719. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2720. result, _stdout, _stderr = self._run_cli(
  2721. "worktree", "lock", wt_path, "--reason", "Testing"
  2722. )
  2723. self.assertEqual(result, 0)
  2724. log_output = "\n".join(cm.output)
  2725. self.assertIn("Worktree locked:", log_output)
  2726. # Unlock it
  2727. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2728. result, _stdout, _stderr = self._run_cli("worktree", "unlock", wt_path)
  2729. self.assertEqual(result, 0)
  2730. log_output = "\n".join(cm.output)
  2731. self.assertIn("Worktree unlocked:", log_output)
  2732. def test_worktree_move(self):
  2733. """Test worktree move command."""
  2734. # Add a worktree
  2735. old_path = os.path.join(self.test_dir, "old-location")
  2736. new_path = os.path.join(self.test_dir, "new-location")
  2737. result, _stdout, _stderr = self._run_cli("worktree", "add", old_path)
  2738. self.assertEqual(result, 0)
  2739. # Move it
  2740. with self.assertLogs("dulwich.cli", level="INFO") as cm:
  2741. result, _stdout, _stderr = self._run_cli(
  2742. "worktree", "move", old_path, new_path
  2743. )
  2744. self.assertEqual(result, 0)
  2745. self.assertFalse(os.path.exists(old_path))
  2746. self.assertTrue(os.path.exists(new_path))
  2747. log_output = "\n".join(cm.output)
  2748. self.assertIn("Worktree moved:", log_output)
  2749. def test_worktree_invalid_command(self):
  2750. """Test invalid worktree subcommand."""
  2751. cmd = cli.cmd_worktree()
  2752. with patch("sys.stderr", new_callable=io.StringIO):
  2753. with self.assertRaises(SystemExit):
  2754. cmd.run(["invalid"])
  2755. class MergeBaseCommandTest(DulwichCliTestCase):
  2756. """Tests for merge-base command."""
  2757. def _create_commits(self):
  2758. """Helper to create a commit history for testing."""
  2759. # Create three commits in linear history
  2760. for i in range(1, 4):
  2761. test_file = os.path.join(self.repo_path, f"file{i}.txt")
  2762. with open(test_file, "w") as f:
  2763. f.write(f"content{i}")
  2764. self._run_cli("add", f"file{i}.txt")
  2765. self._run_cli("commit", f"--message=Commit {i}")
  2766. def test_merge_base_linear_history(self):
  2767. """Test merge-base with linear history."""
  2768. self._create_commits()
  2769. result, stdout, _stderr = self._run_cli("merge-base", "HEAD", "HEAD~1")
  2770. self.assertEqual(result, 0)
  2771. # Should return HEAD~1 as the merge base
  2772. output = stdout.strip()
  2773. # Verify it's a valid commit ID (40 hex chars)
  2774. self.assertEqual(len(output), 40)
  2775. self.assertTrue(all(c in "0123456789abcdef" for c in output))
  2776. def test_merge_base_is_ancestor_true(self):
  2777. """Test merge-base --is-ancestor when true."""
  2778. self._create_commits()
  2779. result, _stdout, _stderr = self._run_cli(
  2780. "merge-base", "--is-ancestor", "HEAD~1", "HEAD"
  2781. )
  2782. self.assertEqual(result, 0) # Exit code 0 means true
  2783. def test_merge_base_is_ancestor_false(self):
  2784. """Test merge-base --is-ancestor when false."""
  2785. self._create_commits()
  2786. result, _stdout, _stderr = self._run_cli(
  2787. "merge-base", "--is-ancestor", "HEAD", "HEAD~1"
  2788. )
  2789. self.assertEqual(result, 1) # Exit code 1 means false
  2790. def test_merge_base_independent(self):
  2791. """Test merge-base --independent."""
  2792. self._create_commits()
  2793. # All three commits in linear history - only HEAD should be independent
  2794. head = self.repo.refs[b"HEAD"]
  2795. head_1 = self.repo[head].parents[0]
  2796. head_2 = self.repo[head_1].parents[0]
  2797. result, stdout, _stderr = self._run_cli(
  2798. "merge-base",
  2799. "--independent",
  2800. head.decode(),
  2801. head_1.decode(),
  2802. head_2.decode(),
  2803. )
  2804. self.assertEqual(result, 0)
  2805. # Only HEAD should be in output (as it's the only independent commit)
  2806. lines = stdout.strip().split("\n")
  2807. self.assertEqual(len(lines), 1)
  2808. self.assertEqual(lines[0], head.decode())
  2809. def test_merge_base_requires_two_commits(self):
  2810. """Test merge-base requires at least two commits."""
  2811. self._create_commits()
  2812. result, _stdout, _stderr = self._run_cli("merge-base", "HEAD")
  2813. self.assertEqual(result, 1)
  2814. def test_merge_base_is_ancestor_requires_two_commits(self):
  2815. """Test merge-base --is-ancestor requires exactly two commits."""
  2816. self._create_commits()
  2817. result, _stdout, _stderr = self._run_cli("merge-base", "--is-ancestor", "HEAD")
  2818. self.assertEqual(result, 1)
  2819. class ConfigCommandTest(DulwichCliTestCase):
  2820. """Tests for config command."""
  2821. def test_config_set_and_get(self):
  2822. """Test setting and getting a config value."""
  2823. # Set a config value
  2824. result, stdout, _stderr = self._run_cli("config", "user.name", "Test User")
  2825. self.assertEqual(result, 0)
  2826. self.assertEqual(stdout, "")
  2827. # Get the value back
  2828. result, stdout, _stderr = self._run_cli("config", "user.name")
  2829. self.assertEqual(result, 0)
  2830. self.assertEqual(stdout, "Test User\n")
  2831. def test_config_set_and_get_subsection(self):
  2832. """Test setting and getting a config value with subsection."""
  2833. # Set a config value with subsection (e.g., remote.origin.url)
  2834. result, stdout, _stderr = self._run_cli(
  2835. "config", "remote.origin.url", "https://example.com/repo.git"
  2836. )
  2837. self.assertEqual(result, 0)
  2838. self.assertEqual(stdout, "")
  2839. # Get the value back
  2840. result, stdout, _stderr = self._run_cli("config", "remote.origin.url")
  2841. self.assertEqual(result, 0)
  2842. self.assertEqual(stdout, "https://example.com/repo.git\n")
  2843. def test_config_list(self):
  2844. """Test listing all config values."""
  2845. # Set some config values
  2846. self._run_cli("config", "user.name", "Test User")
  2847. self._run_cli("config", "user.email", "test@example.com")
  2848. # Get the actual config values that may vary by platform
  2849. config = self.repo.get_config()
  2850. filemode = config.get((b"core",), b"filemode")
  2851. try:
  2852. symlinks = config.get((b"core",), b"symlinks")
  2853. except KeyError:
  2854. symlinks = None
  2855. # List all values
  2856. result, stdout, _stderr = self._run_cli("config", "--list")
  2857. self.assertEqual(result, 0)
  2858. # Build expected output with platform-specific values
  2859. expected = "core.repositoryformatversion=0\n"
  2860. expected += f"core.filemode={filemode.decode('utf-8')}\n"
  2861. if symlinks is not None:
  2862. expected += f"core.symlinks={symlinks.decode('utf-8')}\n"
  2863. expected += (
  2864. "core.bare=false\n"
  2865. "core.logallrefupdates=true\n"
  2866. "user.name=Test User\n"
  2867. "user.email=test@example.com\n"
  2868. )
  2869. self.assertEqual(stdout, expected)
  2870. def test_config_unset(self):
  2871. """Test unsetting a config value."""
  2872. # Set a config value
  2873. self._run_cli("config", "user.name", "Test User")
  2874. # Verify it's set
  2875. result, stdout, _stderr = self._run_cli("config", "user.name")
  2876. self.assertEqual(result, 0)
  2877. self.assertEqual(stdout, "Test User\n")
  2878. # Unset it
  2879. result, stdout, _stderr = self._run_cli("config", "--unset", "user.name")
  2880. self.assertEqual(result, 0)
  2881. self.assertEqual(stdout, "")
  2882. # Verify it's gone
  2883. result, stdout, _stderr = self._run_cli("config", "user.name")
  2884. self.assertEqual(result, 1)
  2885. self.assertEqual(stdout, "")
  2886. def test_config_get_nonexistent(self):
  2887. """Test getting a nonexistent config value."""
  2888. result, stdout, _stderr = self._run_cli("config", "nonexistent.key")
  2889. self.assertEqual(result, 1)
  2890. self.assertEqual(stdout, "")
  2891. def test_config_unset_nonexistent(self):
  2892. """Test unsetting a nonexistent config value."""
  2893. result, _stdout, _stderr = self._run_cli("config", "--unset", "nonexistent.key")
  2894. self.assertEqual(result, 1)
  2895. def test_config_invalid_key_format(self):
  2896. """Test config with invalid key format."""
  2897. result, stdout, _stderr = self._run_cli("config", "invalidkey")
  2898. self.assertEqual(result, 1)
  2899. self.assertEqual(stdout, "")
  2900. def test_config_get_all(self):
  2901. """Test getting all values for a multivar."""
  2902. # Set multiple values for the same key
  2903. config = self.repo.get_config()
  2904. config.set(("test",), "multivar", "value1")
  2905. config.add(("test",), "multivar", "value2")
  2906. config.add(("test",), "multivar", "value3")
  2907. config.write_to_path()
  2908. # Get all values
  2909. result, stdout, _stderr = self._run_cli("config", "--get-all", "test.multivar")
  2910. self.assertEqual(result, 0)
  2911. self.assertEqual(stdout, "value1\nvalue2\nvalue3\n")
  2912. class GitFlushTest(TestCase):
  2913. """Tests for GIT_FLUSH environment variable support."""
  2914. def test_should_auto_flush_with_git_flush_1(self):
  2915. """Test that GIT_FLUSH=1 enables auto-flushing."""
  2916. mock_stream = MagicMock()
  2917. mock_stream.isatty.return_value = True
  2918. self.assertTrue(_should_auto_flush(mock_stream, env={"GIT_FLUSH": "1"}))
  2919. def test_should_auto_flush_with_git_flush_0(self):
  2920. """Test that GIT_FLUSH=0 disables auto-flushing."""
  2921. mock_stream = MagicMock()
  2922. mock_stream.isatty.return_value = True
  2923. self.assertFalse(_should_auto_flush(mock_stream, env={"GIT_FLUSH": "0"}))
  2924. def test_should_auto_flush_auto_detect_tty(self):
  2925. """Test that auto-detect returns False for TTY (no flush needed)."""
  2926. mock_stream = MagicMock()
  2927. mock_stream.isatty.return_value = True
  2928. self.assertFalse(_should_auto_flush(mock_stream, env={}))
  2929. def test_should_auto_flush_auto_detect_pipe(self):
  2930. """Test that auto-detect returns True for pipes (flush needed)."""
  2931. mock_stream = MagicMock()
  2932. mock_stream.isatty.return_value = False
  2933. self.assertTrue(_should_auto_flush(mock_stream, env={}))
  2934. def test_text_wrapper_flushes_on_write(self):
  2935. """Test that AutoFlushTextIOWrapper flushes after write."""
  2936. mock_stream = MagicMock()
  2937. wrapper = AutoFlushTextIOWrapper(mock_stream)
  2938. wrapper.write("test")
  2939. mock_stream.write.assert_called_once_with("test")
  2940. mock_stream.flush.assert_called_once()
  2941. def test_text_wrapper_flushes_on_writelines(self):
  2942. """Test that AutoFlushTextIOWrapper flushes after writelines."""
  2943. from dulwich.cli import AutoFlushTextIOWrapper
  2944. mock_stream = MagicMock()
  2945. wrapper = AutoFlushTextIOWrapper(mock_stream)
  2946. wrapper.writelines(["line1\n", "line2\n"])
  2947. mock_stream.writelines.assert_called_once()
  2948. mock_stream.flush.assert_called_once()
  2949. def test_binary_wrapper_flushes_on_write(self):
  2950. """Test that AutoFlushBinaryIOWrapper flushes after write."""
  2951. mock_stream = MagicMock()
  2952. wrapper = AutoFlushBinaryIOWrapper(mock_stream)
  2953. wrapper.write(b"test")
  2954. mock_stream.write.assert_called_once_with(b"test")
  2955. mock_stream.flush.assert_called_once()
  2956. def test_text_wrapper_env_classmethod(self):
  2957. """Test that AutoFlushTextIOWrapper.env() respects GIT_FLUSH."""
  2958. mock_stream = MagicMock()
  2959. mock_stream.isatty.return_value = False
  2960. wrapper = AutoFlushTextIOWrapper.env(mock_stream, env={"GIT_FLUSH": "1"})
  2961. self.assertIsInstance(wrapper, AutoFlushTextIOWrapper)
  2962. wrapper = AutoFlushTextIOWrapper.env(mock_stream, env={"GIT_FLUSH": "0"})
  2963. self.assertIs(mock_stream, wrapper)
  2964. def test_binary_wrapper_env_classmethod(self):
  2965. """Test that AutoFlushBinaryIOWrapper.env() respects GIT_FLUSH."""
  2966. mock_stream = MagicMock()
  2967. mock_stream.isatty.return_value = False
  2968. wrapper = AutoFlushBinaryIOWrapper.env(mock_stream, env={"GIT_FLUSH": "1"})
  2969. self.assertIsInstance(wrapper, AutoFlushBinaryIOWrapper)
  2970. wrapper = AutoFlushBinaryIOWrapper.env(mock_stream, env={"GIT_FLUSH": "0"})
  2971. self.assertIs(wrapper, mock_stream)
  2972. def test_wrapper_delegates_attributes(self):
  2973. """Test that wrapper delegates unknown attributes to stream."""
  2974. mock_stream = MagicMock()
  2975. mock_stream.encoding = "utf-8"
  2976. wrapper = AutoFlushTextIOWrapper(mock_stream)
  2977. self.assertEqual(wrapper.encoding, "utf-8")
  2978. def test_wrapper_context_manager(self):
  2979. """Test that wrapper supports context manager protocol."""
  2980. mock_stream = MagicMock()
  2981. wrapper = AutoFlushTextIOWrapper(mock_stream)
  2982. with wrapper as w:
  2983. self.assertIs(w, wrapper)
  2984. class MaintenanceCommandTest(DulwichCliTestCase):
  2985. """Tests for maintenance command."""
  2986. def setUp(self):
  2987. super().setUp()
  2988. # Set up a temporary HOME for testing global config
  2989. self.temp_home = tempfile.mkdtemp()
  2990. self.addCleanup(shutil.rmtree, self.temp_home)
  2991. self.overrideEnv("HOME", self.temp_home)
  2992. def test_maintenance_run_default(self):
  2993. """Test maintenance run with default tasks."""
  2994. result, _stdout, _stderr = self._run_cli("maintenance", "run")
  2995. self.assertIsNone(result)
  2996. def test_maintenance_run_specific_task(self):
  2997. """Test maintenance run with a specific task."""
  2998. result, _stdout, _stderr = self._run_cli(
  2999. "maintenance", "run", "--task", "pack-refs"
  3000. )
  3001. self.assertIsNone(result)
  3002. def test_maintenance_run_multiple_tasks(self):
  3003. """Test maintenance run with multiple specific tasks."""
  3004. result, _stdout, _stderr = self._run_cli(
  3005. "maintenance", "run", "--task", "pack-refs", "--task", "gc"
  3006. )
  3007. self.assertIsNone(result)
  3008. def test_maintenance_run_quiet(self):
  3009. """Test maintenance run with quiet flag."""
  3010. result, _stdout, _stderr = self._run_cli("maintenance", "run", "--quiet")
  3011. self.assertIsNone(result)
  3012. def test_maintenance_run_auto(self):
  3013. """Test maintenance run with auto flag."""
  3014. result, _stdout, _stderr = self._run_cli("maintenance", "run", "--auto")
  3015. self.assertIsNone(result)
  3016. def test_maintenance_no_subcommand(self):
  3017. """Test maintenance command without subcommand shows help."""
  3018. result, _stdout, _stderr = self._run_cli("maintenance")
  3019. self.assertEqual(result, 1)
  3020. def test_maintenance_register(self):
  3021. """Test maintenance register subcommand."""
  3022. result, _stdout, _stderr = self._run_cli("maintenance", "register")
  3023. self.assertIsNone(result)
  3024. def test_maintenance_unregister(self):
  3025. """Test maintenance unregister subcommand."""
  3026. # First register
  3027. _result, _stdout, _stderr = self._run_cli("maintenance", "register")
  3028. # Then unregister
  3029. result, _stdout, _stderr = self._run_cli("maintenance", "unregister")
  3030. self.assertIsNone(result)
  3031. def test_maintenance_unregister_not_registered(self):
  3032. """Test unregistering a repository that is not registered."""
  3033. result, _stdout, _stderr = self._run_cli("maintenance", "unregister")
  3034. self.assertEqual(result, 1)
  3035. def test_maintenance_unregister_force(self):
  3036. """Test unregistering with --force flag."""
  3037. result, _stdout, _stderr = self._run_cli("maintenance", "unregister", "--force")
  3038. self.assertIsNone(result)
  3039. def test_maintenance_unimplemented_subcommand(self):
  3040. """Test unimplemented maintenance subcommands."""
  3041. for subcommand in ["start", "stop"]:
  3042. result, _stdout, _stderr = self._run_cli("maintenance", subcommand)
  3043. self.assertEqual(result, 1)
  3044. class InterpretTrailersCommandTest(DulwichCliTestCase):
  3045. """Tests for interpret-trailers command."""
  3046. def test_parse_trailers_from_file(self):
  3047. """Test parsing trailers from a file."""
  3048. # Create a message file with trailers
  3049. msg_file = os.path.join(self.test_dir, "message.txt")
  3050. with open(msg_file, "wb") as f:
  3051. f.write(b"Subject\n\nBody\n\nSigned-off-by: Alice <alice@example.com>\n")
  3052. result, stdout, _stderr = self._run_cli(
  3053. "interpret-trailers", "--only-trailers", msg_file
  3054. )
  3055. self.assertIsNone(result)
  3056. self.assertIn("Signed-off-by: Alice <alice@example.com>", stdout)
  3057. def test_add_trailer_to_message(self):
  3058. """Test adding a trailer to a message."""
  3059. msg_file = os.path.join(self.test_dir, "message.txt")
  3060. with open(msg_file, "wb") as f:
  3061. f.write(b"Subject\n\nBody text\n")
  3062. result, stdout, _stderr = self._run_cli(
  3063. "interpret-trailers",
  3064. "--trailer",
  3065. "Signed-off-by:Alice <alice@example.com>",
  3066. msg_file,
  3067. )
  3068. self.assertIsNone(result)
  3069. self.assertIn("Signed-off-by: Alice <alice@example.com>", stdout)
  3070. self.assertIn("Subject", stdout)
  3071. self.assertIn("Body text", stdout)
  3072. def test_add_multiple_trailers(self):
  3073. """Test adding multiple trailers."""
  3074. msg_file = os.path.join(self.test_dir, "message.txt")
  3075. with open(msg_file, "wb") as f:
  3076. f.write(b"Subject\n\nBody\n")
  3077. result, stdout, _stderr = self._run_cli(
  3078. "interpret-trailers",
  3079. "--trailer",
  3080. "Signed-off-by:Alice",
  3081. "--trailer",
  3082. "Reviewed-by:Bob",
  3083. msg_file,
  3084. )
  3085. self.assertIsNone(result)
  3086. self.assertIn("Signed-off-by: Alice", stdout)
  3087. self.assertIn("Reviewed-by: Bob", stdout)
  3088. def test_parse_shorthand(self):
  3089. """Test --parse shorthand option."""
  3090. msg_file = os.path.join(self.test_dir, "message.txt")
  3091. with open(msg_file, "wb") as f:
  3092. f.write(b"Subject\n\nBody\n\nSigned-off-by: Alice\n")
  3093. result, stdout, _stderr = self._run_cli(
  3094. "interpret-trailers", "--parse", msg_file
  3095. )
  3096. self.assertIsNone(result)
  3097. # --parse is shorthand for --only-trailers --only-input --unfold
  3098. self.assertEqual(stdout, "Signed-off-by: Alice\n")
  3099. def test_trim_empty(self):
  3100. """Test --trim-empty option."""
  3101. msg_file = os.path.join(self.test_dir, "message.txt")
  3102. with open(msg_file, "wb") as f:
  3103. f.write(b"Subject\n\nBody\n\nSigned-off-by: Alice\nReviewed-by: \n")
  3104. result, stdout, _stderr = self._run_cli(
  3105. "interpret-trailers", "--trim-empty", "--only-trailers", msg_file
  3106. )
  3107. self.assertIsNone(result)
  3108. self.assertIn("Signed-off-by: Alice", stdout)
  3109. self.assertNotIn("Reviewed-by:", stdout)
  3110. def test_if_exists_replace(self):
  3111. """Test --if-exists replace option."""
  3112. msg_file = os.path.join(self.test_dir, "message.txt")
  3113. with open(msg_file, "wb") as f:
  3114. f.write(b"Subject\n\nBody\n\nSigned-off-by: Alice\n")
  3115. result, stdout, _stderr = self._run_cli(
  3116. "interpret-trailers",
  3117. "--if-exists",
  3118. "replace",
  3119. "--trailer",
  3120. "Signed-off-by:Bob",
  3121. msg_file,
  3122. )
  3123. self.assertIsNone(result)
  3124. self.assertIn("Signed-off-by: Bob", stdout)
  3125. self.assertNotIn("Alice", stdout)
  3126. def test_trailer_with_equals(self):
  3127. """Test trailer with equals separator."""
  3128. msg_file = os.path.join(self.test_dir, "message.txt")
  3129. with open(msg_file, "wb") as f:
  3130. f.write(b"Subject\n\nBody\n")
  3131. result, stdout, _stderr = self._run_cli(
  3132. "interpret-trailers", "--trailer", "Bug=12345", msg_file
  3133. )
  3134. self.assertIsNone(result)
  3135. self.assertIn("Bug: 12345", stdout)
  3136. class ReplaceCommandTest(DulwichCliTestCase):
  3137. """Tests for replace command."""
  3138. def test_replace_create(self):
  3139. """Test creating a replacement ref."""
  3140. # Create two commits
  3141. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  3142. self.repo[b"HEAD"] = c1.id
  3143. # Create replacement using the create form (decode to string for CLI)
  3144. c1_str = c1.id.decode("ascii")
  3145. c2_str = c2.id.decode("ascii")
  3146. _result, _stdout, _stderr = self._run_cli("replace", c1_str, c2_str)
  3147. # Verify the replacement ref was created
  3148. replace_ref = b"refs/replace/" + c1.id
  3149. self.assertIn(replace_ref, self.repo.refs.keys())
  3150. self.assertEqual(c2.id, self.repo.refs[replace_ref])
  3151. def test_replace_list_empty(self):
  3152. """Test listing replacements when there are none."""
  3153. _result, stdout, _stderr = self._run_cli("replace", "list")
  3154. self.assertEqual("", stdout)
  3155. def test_replace_list(self):
  3156. """Test listing replacement refs."""
  3157. # Create two commits
  3158. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  3159. self.repo[b"HEAD"] = c1.id
  3160. # Create replacement
  3161. c1_str = c1.id.decode("ascii")
  3162. c2_str = c2.id.decode("ascii")
  3163. self._run_cli("replace", c1_str, c2_str)
  3164. # List replacements
  3165. _result, stdout, _stderr = self._run_cli("replace", "list")
  3166. self.assertIn(c1_str, stdout)
  3167. self.assertIn(c2_str, stdout)
  3168. def test_replace_default_list(self):
  3169. """Test that replace without subcommand defaults to list."""
  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
  3174. c1_str = c1.id.decode("ascii")
  3175. c2_str = c2.id.decode("ascii")
  3176. self._run_cli("replace", c1_str, c2_str)
  3177. # Call replace without subcommand (should list)
  3178. _result, stdout, _stderr = self._run_cli("replace")
  3179. self.assertIn(c1_str, stdout)
  3180. self.assertIn(c2_str, stdout)
  3181. def test_replace_delete(self):
  3182. """Test deleting a replacement ref."""
  3183. # Create two commits
  3184. [c1, c2] = build_commit_graph(self.repo.object_store, [[1], [2]])
  3185. self.repo[b"HEAD"] = c1.id
  3186. # Create replacement
  3187. c1_str = c1.id.decode("ascii")
  3188. c2_str = c2.id.decode("ascii")
  3189. self._run_cli("replace", c1_str, c2_str)
  3190. # Verify it exists
  3191. replace_ref = b"refs/replace/" + c1.id
  3192. self.assertIn(replace_ref, self.repo.refs.keys())
  3193. # Delete the replacement
  3194. _result, _stdout, _stderr = self._run_cli("replace", "delete", c1_str)
  3195. # Verify it's gone
  3196. self.assertNotIn(replace_ref, self.repo.refs.keys())
  3197. def test_replace_delete_nonexistent(self):
  3198. """Test deleting a nonexistent replacement ref fails."""
  3199. # Create a commit
  3200. [c1] = build_commit_graph(self.repo.object_store, [[1]])
  3201. self.repo[b"HEAD"] = c1.id
  3202. # Try to delete a non-existent replacement
  3203. c1_str = c1.id.decode("ascii")
  3204. result, _stdout, _stderr = self._run_cli("replace", "delete", c1_str)
  3205. self.assertEqual(result, 1)
  3206. class StripspaceCommandTest(DulwichCliTestCase):
  3207. """Tests for stripspace command."""
  3208. def test_stripspace_from_file(self):
  3209. """Test stripspace from a file."""
  3210. # Create a text file with whitespace issues
  3211. text_file = os.path.join(self.test_dir, "message.txt")
  3212. with open(text_file, "wb") as f:
  3213. f.write(b" hello \n\n\n\n world \n\n")
  3214. result, stdout, _stderr = self._run_cli("stripspace", text_file)
  3215. self.assertIsNone(result)
  3216. self.assertEqual(stdout, "hello\n\nworld\n")
  3217. def test_stripspace_simple(self):
  3218. """Test basic stripspace functionality."""
  3219. text_file = os.path.join(self.test_dir, "message.txt")
  3220. with open(text_file, "wb") as f:
  3221. f.write(b"hello\nworld\n")
  3222. result, stdout, _stderr = self._run_cli("stripspace", text_file)
  3223. self.assertIsNone(result)
  3224. self.assertEqual(stdout, "hello\nworld\n")
  3225. def test_stripspace_trailing_whitespace(self):
  3226. """Test that trailing whitespace is removed."""
  3227. text_file = os.path.join(self.test_dir, "message.txt")
  3228. with open(text_file, "wb") as f:
  3229. f.write(b"hello \nworld\t\n")
  3230. result, stdout, _stderr = self._run_cli("stripspace", text_file)
  3231. self.assertIsNone(result)
  3232. self.assertEqual(stdout, "hello\nworld\n")
  3233. def test_stripspace_strip_comments(self):
  3234. """Test stripping comments."""
  3235. text_file = os.path.join(self.test_dir, "message.txt")
  3236. with open(text_file, "wb") as f:
  3237. f.write(b"# comment\nhello\n# another comment\nworld\n")
  3238. result, stdout, _stderr = self._run_cli(
  3239. "stripspace", "--strip-comments", text_file
  3240. )
  3241. self.assertIsNone(result)
  3242. self.assertEqual(stdout, "hello\nworld\n")
  3243. def test_stripspace_comment_lines(self):
  3244. """Test prepending comment character."""
  3245. text_file = os.path.join(self.test_dir, "message.txt")
  3246. with open(text_file, "wb") as f:
  3247. f.write(b"hello\nworld\n")
  3248. result, stdout, _stderr = self._run_cli(
  3249. "stripspace", "--comment-lines", text_file
  3250. )
  3251. self.assertIsNone(result)
  3252. self.assertEqual(stdout, "# hello\n# world\n")
  3253. def test_stripspace_custom_comment_char(self):
  3254. """Test using custom comment character."""
  3255. text_file = os.path.join(self.test_dir, "message.txt")
  3256. with open(text_file, "wb") as f:
  3257. f.write(b"; comment\nhello\n; another comment\nworld\n")
  3258. result, stdout, _stderr = self._run_cli(
  3259. "stripspace", "--strip-comments", "--comment-char", ";", text_file
  3260. )
  3261. self.assertIsNone(result)
  3262. self.assertEqual(stdout, "hello\nworld\n")
  3263. def test_stripspace_leading_trailing_blanks(self):
  3264. """Test removing leading and trailing blank lines."""
  3265. text_file = os.path.join(self.test_dir, "message.txt")
  3266. with open(text_file, "wb") as f:
  3267. f.write(b"\n\nhello\nworld\n\n\n")
  3268. result, stdout, _stderr = self._run_cli("stripspace", text_file)
  3269. self.assertIsNone(result)
  3270. self.assertEqual(stdout, "hello\nworld\n")
  3271. def test_stripspace_collapse_blank_lines(self):
  3272. """Test collapsing multiple blank lines."""
  3273. text_file = os.path.join(self.test_dir, "message.txt")
  3274. with open(text_file, "wb") as f:
  3275. f.write(b"hello\n\n\n\nworld\n")
  3276. result, stdout, _stderr = self._run_cli("stripspace", text_file)
  3277. self.assertIsNone(result)
  3278. self.assertEqual(stdout, "hello\n\nworld\n")
  3279. class ColumnCommandTest(DulwichCliTestCase):
  3280. """Tests for column command."""
  3281. def test_column_mode_default(self):
  3282. """Test column mode (default) - fills columns first."""
  3283. old_stdin = sys.stdin
  3284. try:
  3285. sys.stdin = io.StringIO("1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n")
  3286. result, stdout, _stderr = self._run_cli("column", "--width", "40")
  3287. self.assertIsNone(result)
  3288. # In column mode, items go down then across
  3289. # With 12 items and width 40, should fit in multiple columns
  3290. lines = stdout.strip().split("\n")
  3291. # First line should start with "1"
  3292. self.assertTrue(lines[0].startswith("1"))
  3293. finally:
  3294. sys.stdin = old_stdin
  3295. def test_column_mode_row(self):
  3296. """Test row mode - fills rows first."""
  3297. old_stdin = sys.stdin
  3298. try:
  3299. sys.stdin = io.StringIO("1\n2\n3\n4\n5\n6\n")
  3300. result, stdout, _stderr = self._run_cli(
  3301. "column", "--mode", "row", "--width", "40"
  3302. )
  3303. self.assertIsNone(result)
  3304. # In row mode, items go across then down
  3305. # Should have items 1, 2, 3... on first line
  3306. lines = stdout.strip().split("\n")
  3307. self.assertTrue("1" in lines[0])
  3308. self.assertTrue("2" in lines[0])
  3309. finally:
  3310. sys.stdin = old_stdin
  3311. def test_column_mode_plain(self):
  3312. """Test plain mode - one item per line."""
  3313. old_stdin = sys.stdin
  3314. try:
  3315. sys.stdin = io.StringIO("apple\nbanana\ncherry\n")
  3316. result, stdout, _stderr = self._run_cli("column", "--mode", "plain")
  3317. self.assertIsNone(result)
  3318. self.assertEqual(stdout, "apple\nbanana\ncherry\n")
  3319. finally:
  3320. sys.stdin = old_stdin
  3321. def test_column_padding(self):
  3322. """Test custom padding between columns."""
  3323. old_stdin = sys.stdin
  3324. try:
  3325. sys.stdin = io.StringIO("a\nb\nc\nd\ne\nf\n")
  3326. result, stdout, _stderr = self._run_cli(
  3327. "column", "--mode", "row", "--padding", "5", "--width", "80"
  3328. )
  3329. self.assertIsNone(result)
  3330. # With padding=5, should have 5 spaces between items
  3331. self.assertIn(" ", stdout)
  3332. finally:
  3333. sys.stdin = old_stdin
  3334. def test_column_indent(self):
  3335. """Test indent prepended to each line."""
  3336. old_stdin = sys.stdin
  3337. try:
  3338. sys.stdin = io.StringIO("apple\nbanana\n")
  3339. result, stdout, _stderr = self._run_cli(
  3340. "column", "--mode", "plain", "--indent", " "
  3341. )
  3342. self.assertIsNone(result)
  3343. lines = stdout.split("\n")
  3344. self.assertTrue(lines[0].startswith(" apple"))
  3345. self.assertTrue(lines[1].startswith(" banana"))
  3346. finally:
  3347. sys.stdin = old_stdin
  3348. def test_column_empty_input(self):
  3349. """Test with empty input."""
  3350. old_stdin = sys.stdin
  3351. try:
  3352. sys.stdin = io.StringIO("")
  3353. result, stdout, _stderr = self._run_cli("column")
  3354. self.assertIsNone(result)
  3355. self.assertEqual(stdout, "")
  3356. finally:
  3357. sys.stdin = old_stdin
  3358. def test_column_single_item(self):
  3359. """Test with single item."""
  3360. old_stdin = sys.stdin
  3361. try:
  3362. sys.stdin = io.StringIO("single\n")
  3363. result, stdout, _stderr = self._run_cli("column")
  3364. self.assertIsNone(result)
  3365. self.assertEqual(stdout, "single\n")
  3366. finally:
  3367. sys.stdin = old_stdin
  3368. class MailinfoCommandTests(DulwichCliTestCase):
  3369. """Tests for the mailinfo command."""
  3370. def test_mailinfo_basic(self):
  3371. """Test basic mailinfo command."""
  3372. email_content = b"""From: Test User <test@example.com>
  3373. Subject: [PATCH] Add feature
  3374. Date: Mon, 1 Jan 2024 12:00:00 +0000
  3375. This is the commit message.
  3376. ---
  3377. diff --git a/file.txt b/file.txt
  3378. """
  3379. email_file = os.path.join(self.test_dir, "email.txt")
  3380. with open(email_file, "wb") as f:
  3381. f.write(email_content)
  3382. msg_file = os.path.join(self.test_dir, "msg")
  3383. patch_file = os.path.join(self.test_dir, "patch")
  3384. result, stdout, _stderr = self._run_cli(
  3385. "mailinfo", msg_file, patch_file, email_file
  3386. )
  3387. self.assertIsNone(result)
  3388. # Check stdout contains author info
  3389. self.assertIn("Author: Test User", stdout)
  3390. self.assertIn("Email: test@example.com", stdout)
  3391. self.assertIn("Subject: Add feature", stdout)
  3392. # Check files were written
  3393. self.assertTrue(os.path.exists(msg_file))
  3394. self.assertTrue(os.path.exists(patch_file))
  3395. # Check file contents
  3396. with open(msg_file) as f:
  3397. msg_content = f.read()
  3398. self.assertIn("This is the commit message.", msg_content)
  3399. with open(patch_file) as f:
  3400. patch_content = f.read()
  3401. self.assertIn("diff --git", patch_content)
  3402. def test_mailinfo_keep_subject(self):
  3403. """Test mailinfo with -k flag."""
  3404. email_content = b"""From: Test <test@example.com>
  3405. Subject: [PATCH 1/2] Feature
  3406. Body
  3407. """
  3408. email_file = os.path.join(self.test_dir, "email.txt")
  3409. with open(email_file, "wb") as f:
  3410. f.write(email_content)
  3411. msg_file = os.path.join(self.test_dir, "msg")
  3412. patch_file = os.path.join(self.test_dir, "patch")
  3413. result, stdout, _stderr = self._run_cli(
  3414. "mailinfo", "-k", msg_file, patch_file, email_file
  3415. )
  3416. self.assertIsNone(result)
  3417. self.assertIn("Subject: [PATCH 1/2] Feature", stdout)
  3418. def test_mailinfo_keep_non_patch(self):
  3419. """Test mailinfo with -b flag."""
  3420. email_content = b"""From: Test <test@example.com>
  3421. Subject: [RFC][PATCH] Feature
  3422. Body
  3423. """
  3424. email_file = os.path.join(self.test_dir, "email.txt")
  3425. with open(email_file, "wb") as f:
  3426. f.write(email_content)
  3427. msg_file = os.path.join(self.test_dir, "msg")
  3428. patch_file = os.path.join(self.test_dir, "patch")
  3429. result, stdout, _stderr = self._run_cli(
  3430. "mailinfo", "-b", msg_file, patch_file, email_file
  3431. )
  3432. self.assertIsNone(result)
  3433. self.assertIn("Subject: [RFC] Feature", stdout)
  3434. def test_mailinfo_scissors(self):
  3435. """Test mailinfo with --scissors flag."""
  3436. email_content = b"""From: Test <test@example.com>
  3437. Subject: Test
  3438. Ignore this part
  3439. -- >8 --
  3440. Keep this part
  3441. """
  3442. email_file = os.path.join(self.test_dir, "email.txt")
  3443. with open(email_file, "wb") as f:
  3444. f.write(email_content)
  3445. msg_file = os.path.join(self.test_dir, "msg")
  3446. patch_file = os.path.join(self.test_dir, "patch")
  3447. result, _stdout, _stderr = self._run_cli(
  3448. "mailinfo", "--scissors", msg_file, patch_file, email_file
  3449. )
  3450. self.assertIsNone(result)
  3451. # Check message file
  3452. with open(msg_file) as f:
  3453. msg_content = f.read()
  3454. self.assertIn("Keep this part", msg_content)
  3455. self.assertNotIn("Ignore this part", msg_content)
  3456. def test_mailinfo_message_id(self):
  3457. """Test mailinfo with -m flag."""
  3458. email_content = b"""From: Test <test@example.com>
  3459. Subject: Test
  3460. Message-ID: <test123@example.com>
  3461. Body
  3462. """
  3463. email_file = os.path.join(self.test_dir, "email.txt")
  3464. with open(email_file, "wb") as f:
  3465. f.write(email_content)
  3466. msg_file = os.path.join(self.test_dir, "msg")
  3467. patch_file = os.path.join(self.test_dir, "patch")
  3468. result, _stdout, _stderr = self._run_cli(
  3469. "mailinfo", "-m", msg_file, patch_file, email_file
  3470. )
  3471. self.assertIsNone(result)
  3472. # Check message file contains Message-ID
  3473. with open(msg_file) as f:
  3474. msg_content = f.read()
  3475. self.assertIn("Message-ID:", msg_content)
  3476. def test_mailinfo_encoding(self):
  3477. """Test mailinfo with --encoding flag."""
  3478. email_content = (
  3479. b"From: Test <test@example.com>\n"
  3480. b"Subject: Test\n"
  3481. b"Content-Type: text/plain; charset=utf-8\n"
  3482. b"\n"
  3483. b"Body with UTF-8: " + "naïve".encode() + b"\n"
  3484. )
  3485. email_file = os.path.join(self.test_dir, "email.txt")
  3486. with open(email_file, "wb") as f:
  3487. f.write(email_content)
  3488. msg_file = os.path.join(self.test_dir, "msg")
  3489. patch_file = os.path.join(self.test_dir, "patch")
  3490. result, _stdout, _stderr = self._run_cli(
  3491. "mailinfo", "--encoding", "utf-8", msg_file, patch_file, email_file
  3492. )
  3493. self.assertIsNone(result)
  3494. # Just verify the command runs successfully
  3495. with open(msg_file) as f:
  3496. msg_content = f.read()
  3497. self.assertIn("Body", msg_content)
  3498. if __name__ == "__main__":
  3499. unittest.main()