test_cli.py 150 KB

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