test_cli.py 163 KB

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