test_cli.py 154 KB

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