cli.py 165 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029
  1. #
  2. # dulwich - Simple command-line interface to Dulwich
  3. # Copyright (C) 2008-2011 Jelmer Vernooij <jelmer@jelmer.uk>
  4. # vim: expandtab
  5. #
  6. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  7. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  8. # General Public License as published by the Free Software Foundation; version 2.0
  9. # or (at your option) any later version. You can redistribute it and/or
  10. # modify it under the terms of either of these two licenses.
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. #
  18. # You should have received a copy of the licenses; if not, see
  19. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  20. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  21. # License, Version 2.0.
  22. #
  23. """Simple command-line interface to Dulwich>.
  24. This is a very simple command-line wrapper for Dulwich. It is by
  25. no means intended to be a full-blown Git command-line interface but just
  26. a way to test Dulwich.
  27. """
  28. import argparse
  29. import io
  30. import logging
  31. import os
  32. import shutil
  33. import signal
  34. import subprocess
  35. import sys
  36. import tempfile
  37. import types
  38. from collections.abc import Iterable, Iterator, Mapping, Sequence
  39. from pathlib import Path
  40. from types import TracebackType
  41. from typing import (
  42. BinaryIO,
  43. Callable,
  44. ClassVar,
  45. Optional,
  46. TextIO,
  47. Union,
  48. )
  49. if sys.version_info >= (3, 12):
  50. from collections.abc import Buffer
  51. else:
  52. Buffer = Union[bytes, bytearray, memoryview]
  53. from dulwich import porcelain
  54. from .bundle import Bundle, create_bundle_from_repo, read_bundle, write_bundle
  55. from .client import get_transport_and_path
  56. from .config import Config
  57. from .errors import (
  58. ApplyDeltaError,
  59. FileFormatException,
  60. GitProtocolError,
  61. NotGitRepository,
  62. )
  63. from .index import Index
  64. from .log_utils import _configure_logging_from_trace
  65. from .objects import Commit, sha_to_hex, valid_hexsha
  66. from .objectspec import parse_commit_range
  67. from .pack import Pack
  68. from .patch import DiffAlgorithmNotAvailable
  69. from .repo import Repo
  70. logger = logging.getLogger(__name__)
  71. def to_display_str(value: Union[bytes, str]) -> str:
  72. """Convert a bytes or string value to a display string.
  73. Args:
  74. value: The value to convert (bytes or str)
  75. Returns:
  76. A string suitable for display
  77. """
  78. if isinstance(value, bytes):
  79. return value.decode("utf-8", "replace")
  80. return value
  81. class CommitMessageError(Exception):
  82. """Raised when there's an issue with the commit message."""
  83. def signal_int(signal: int, frame: Optional[types.FrameType]) -> None:
  84. """Handle interrupt signal by exiting.
  85. Args:
  86. signal: Signal number
  87. frame: Current stack frame
  88. """
  89. sys.exit(1)
  90. def signal_quit(signal: int, frame: Optional[types.FrameType]) -> None:
  91. """Handle quit signal by entering debugger.
  92. Args:
  93. signal: Signal number
  94. frame: Current stack frame
  95. """
  96. import pdb
  97. pdb.set_trace()
  98. def parse_relative_time(time_str: str) -> int:
  99. """Parse a relative time string like '2 weeks ago' into seconds.
  100. Args:
  101. time_str: String like '2 weeks ago' or 'now'
  102. Returns:
  103. Number of seconds
  104. Raises:
  105. ValueError: If the time string cannot be parsed
  106. """
  107. if time_str == "now":
  108. return 0
  109. if not time_str.endswith(" ago"):
  110. raise ValueError(f"Invalid relative time format: {time_str}")
  111. parts = time_str[:-4].split()
  112. if len(parts) != 2:
  113. raise ValueError(f"Invalid relative time format: {time_str}")
  114. try:
  115. num = int(parts[0])
  116. unit = parts[1]
  117. multipliers = {
  118. "second": 1,
  119. "seconds": 1,
  120. "minute": 60,
  121. "minutes": 60,
  122. "hour": 3600,
  123. "hours": 3600,
  124. "day": 86400,
  125. "days": 86400,
  126. "week": 604800,
  127. "weeks": 604800,
  128. }
  129. if unit in multipliers:
  130. return num * multipliers[unit]
  131. else:
  132. raise ValueError(f"Unknown time unit: {unit}")
  133. except ValueError as e:
  134. if "invalid literal" in str(e):
  135. raise ValueError(f"Invalid number in relative time: {parts[0]}")
  136. raise
  137. def format_bytes(bytes: float) -> str:
  138. """Format bytes as human-readable string.
  139. Args:
  140. bytes: Number of bytes
  141. Returns:
  142. Human-readable string like "1.5 MB"
  143. """
  144. for unit in ["B", "KB", "MB", "GB"]:
  145. if bytes < 1024.0:
  146. return f"{bytes:.1f} {unit}"
  147. bytes /= 1024.0
  148. return f"{bytes:.1f} TB"
  149. def launch_editor(template_content: bytes = b"") -> bytes:
  150. """Launch an editor for the user to enter text.
  151. Args:
  152. template_content: Initial content for the editor
  153. Returns:
  154. The edited content as bytes
  155. """
  156. # Determine which editor to use
  157. editor = os.environ.get("GIT_EDITOR") or os.environ.get("EDITOR") or "vi"
  158. # Create a temporary file
  159. with tempfile.NamedTemporaryFile(mode="wb", delete=False, suffix=".txt") as f:
  160. temp_file = f.name
  161. f.write(template_content)
  162. try:
  163. # Launch the editor
  164. subprocess.run([editor, temp_file], check=True)
  165. # Read the edited content
  166. with open(temp_file, "rb") as f:
  167. content = f.read()
  168. return content
  169. finally:
  170. # Clean up the temporary file
  171. os.unlink(temp_file)
  172. def detect_terminal_width() -> int:
  173. """Detect the width of the terminal.
  174. Returns:
  175. Width of the terminal in characters, or 80 if it cannot be determined
  176. """
  177. try:
  178. return os.get_terminal_size().columns
  179. except OSError:
  180. return 80
  181. def write_columns(
  182. items: Union[Iterator[bytes], Sequence[bytes]],
  183. out: TextIO,
  184. width: Optional[int] = None,
  185. ) -> None:
  186. """Display items in formatted columns based on terminal width.
  187. Args:
  188. items: List or iterator of bytes objects to display in columns
  189. out: Output stream to write to
  190. width: Optional width of the terminal (if None, auto-detect)
  191. The function calculates the optimal number of columns to fit the terminal
  192. width and displays the items in a formatted column layout with proper
  193. padding and alignment.
  194. """
  195. if width is None:
  196. ter_width = detect_terminal_width()
  197. else:
  198. ter_width = width
  199. item_names = [item.decode() for item in items]
  200. def columns(
  201. names: Sequence[str], width: int, num_cols: int
  202. ) -> tuple[bool, list[int]]:
  203. if num_cols <= 0:
  204. return False, []
  205. num_rows = (len(names) + num_cols - 1) // num_cols
  206. col_widths = []
  207. for col in range(num_cols):
  208. max_width = 0
  209. for row in range(num_rows):
  210. idx = row + col * num_rows
  211. if idx < len(names):
  212. max_width = max(max_width, len(names[idx]))
  213. col_widths.append(max_width + 2) # add padding
  214. total_width = sum(col_widths)
  215. if total_width <= width:
  216. return True, col_widths
  217. return False, []
  218. best_cols = 1
  219. best_widths = []
  220. for num_cols in range(min(8, len(item_names)), 0, -1):
  221. fits, widths = columns(item_names, ter_width, num_cols)
  222. if fits:
  223. best_cols = num_cols
  224. best_widths = widths
  225. break
  226. if not best_widths:
  227. best_cols = 1
  228. best_widths = [max(len(name) for name in item_names) + 2]
  229. num_rows = (len(item_names) + best_cols - 1) // best_cols
  230. for row in range(num_rows):
  231. lines = []
  232. for col in range(best_cols):
  233. idx = row + col * num_rows
  234. if idx < len(item_names):
  235. branch_name = item_names[idx]
  236. if col < len(best_widths):
  237. lines.append(branch_name.ljust(best_widths[col]))
  238. else:
  239. lines.append(branch_name)
  240. if lines:
  241. out.write("".join(lines).rstrip() + "\n")
  242. class PagerBuffer(BinaryIO):
  243. """Binary buffer wrapper for Pager to mimic sys.stdout.buffer."""
  244. def __init__(self, pager: "Pager") -> None:
  245. """Initialize PagerBuffer.
  246. Args:
  247. pager: Pager instance to wrap
  248. """
  249. self.pager = pager
  250. def write(self, data: Union[bytes, bytearray, memoryview]) -> int: # type: ignore[override]
  251. """Write bytes to pager."""
  252. # Convert to bytes and decode to string for the pager
  253. text = bytes(data).decode("utf-8", errors="replace")
  254. return self.pager.write(text)
  255. def flush(self) -> None:
  256. """Flush the pager."""
  257. return self.pager.flush()
  258. def writelines(self, lines: Iterable[Union[bytes, bytearray, memoryview]]) -> None: # type: ignore[override]
  259. """Write multiple lines to pager."""
  260. for line in lines:
  261. self.write(line)
  262. def readable(self) -> bool:
  263. """Return whether the buffer is readable (it's not)."""
  264. return False
  265. def writable(self) -> bool:
  266. """Return whether the buffer is writable."""
  267. return not self.pager._closed
  268. def seekable(self) -> bool:
  269. """Return whether the buffer is seekable (it's not)."""
  270. return False
  271. def close(self) -> None:
  272. """Close the pager."""
  273. return self.pager.close()
  274. @property
  275. def closed(self) -> bool:
  276. """Return whether the buffer is closed."""
  277. return self.pager.closed
  278. @property
  279. def mode(self) -> str:
  280. """Return the mode."""
  281. return "wb"
  282. @property
  283. def name(self) -> str:
  284. """Return the name."""
  285. return "<pager.buffer>"
  286. def fileno(self) -> int:
  287. """Return the file descriptor (not supported)."""
  288. raise io.UnsupportedOperation("PagerBuffer does not support fileno()")
  289. def isatty(self) -> bool:
  290. """Return whether the buffer is a TTY."""
  291. return False
  292. def read(self, size: int = -1) -> bytes:
  293. """Read from the buffer (not supported)."""
  294. raise io.UnsupportedOperation("PagerBuffer does not support reading")
  295. def read1(self, size: int = -1) -> bytes:
  296. """Read from the buffer (not supported)."""
  297. raise io.UnsupportedOperation("PagerBuffer does not support reading")
  298. def readinto(self, b: bytearray) -> int:
  299. """Read into buffer (not supported)."""
  300. raise io.UnsupportedOperation("PagerBuffer does not support reading")
  301. def readinto1(self, b: bytearray) -> int:
  302. """Read into buffer (not supported)."""
  303. raise io.UnsupportedOperation("PagerBuffer does not support reading")
  304. def readline(self, size: int = -1) -> bytes:
  305. """Read a line from the buffer (not supported)."""
  306. raise io.UnsupportedOperation("PagerBuffer does not support reading")
  307. def readlines(self, hint: int = -1) -> list[bytes]:
  308. """Read lines from the buffer (not supported)."""
  309. raise io.UnsupportedOperation("PagerBuffer does not support reading")
  310. def seek(self, offset: int, whence: int = 0) -> int:
  311. """Seek in the buffer (not supported)."""
  312. raise io.UnsupportedOperation("PagerBuffer does not support seeking")
  313. def tell(self) -> int:
  314. """Return the current position (not supported)."""
  315. raise io.UnsupportedOperation("PagerBuffer does not support tell()")
  316. def truncate(self, size: Optional[int] = None) -> int:
  317. """Truncate the buffer (not supported)."""
  318. raise io.UnsupportedOperation("PagerBuffer does not support truncation")
  319. def __iter__(self) -> "PagerBuffer":
  320. """Return iterator (not supported)."""
  321. raise io.UnsupportedOperation("PagerBuffer does not support iteration")
  322. def __next__(self) -> bytes:
  323. """Return next line (not supported)."""
  324. raise io.UnsupportedOperation("PagerBuffer does not support iteration")
  325. def __enter__(self) -> "PagerBuffer":
  326. """Enter context manager."""
  327. return self
  328. def __exit__(
  329. self,
  330. exc_type: Optional[type[BaseException]],
  331. exc_val: Optional[BaseException],
  332. exc_tb: Optional[TracebackType],
  333. ) -> None:
  334. """Exit context manager."""
  335. self.close()
  336. class Pager(TextIO):
  337. """File-like object that pages output through external pager programs."""
  338. def __init__(self, pager_cmd: str = "cat") -> None:
  339. """Initialize Pager.
  340. Args:
  341. pager_cmd: Command to use for paging (default: "cat")
  342. """
  343. self.pager_process: Optional[subprocess.Popen[str]] = None
  344. self._buffer = PagerBuffer(self)
  345. self._closed = False
  346. self.pager_cmd = pager_cmd
  347. self._pager_died = False
  348. def _get_pager_command(self) -> str:
  349. """Get the pager command to use."""
  350. return self.pager_cmd
  351. def _ensure_pager_started(self) -> None:
  352. """Start the pager process if not already started."""
  353. if self.pager_process is None and not self._closed:
  354. try:
  355. pager_cmd = self._get_pager_command()
  356. self.pager_process = subprocess.Popen(
  357. pager_cmd,
  358. shell=True,
  359. stdin=subprocess.PIPE,
  360. stdout=sys.stdout,
  361. stderr=sys.stderr,
  362. text=True,
  363. )
  364. except (OSError, subprocess.SubprocessError):
  365. # Pager failed to start, fall back to direct output
  366. self.pager_process = None
  367. def write(self, text: str) -> int:
  368. """Write text to the pager."""
  369. if self._closed:
  370. raise ValueError("I/O operation on closed file")
  371. # If pager died (user quit), stop writing output
  372. if self._pager_died:
  373. return len(text)
  374. self._ensure_pager_started()
  375. if self.pager_process and self.pager_process.stdin:
  376. try:
  377. result = self.pager_process.stdin.write(text)
  378. assert isinstance(result, int)
  379. return result
  380. except (OSError, subprocess.SubprocessError, BrokenPipeError):
  381. # Pager died (user quit), stop writing output
  382. self._pager_died = True
  383. return len(text)
  384. else:
  385. # No pager available, write directly to stdout
  386. return sys.stdout.write(text)
  387. def flush(self) -> None:
  388. """Flush the pager."""
  389. if self._closed or self._pager_died:
  390. return
  391. if self.pager_process and self.pager_process.stdin:
  392. try:
  393. self.pager_process.stdin.flush()
  394. except (OSError, subprocess.SubprocessError, BrokenPipeError):
  395. self._pager_died = True
  396. else:
  397. sys.stdout.flush()
  398. def close(self) -> None:
  399. """Close the pager."""
  400. if self._closed:
  401. return
  402. self._closed = True
  403. if self.pager_process:
  404. try:
  405. if self.pager_process.stdin:
  406. self.pager_process.stdin.close()
  407. self.pager_process.wait()
  408. except (OSError, subprocess.SubprocessError):
  409. pass
  410. self.pager_process = None
  411. def __enter__(self) -> "Pager":
  412. """Context manager entry."""
  413. return self
  414. def __exit__(
  415. self,
  416. exc_type: Optional[type],
  417. exc_val: Optional[BaseException],
  418. exc_tb: Optional[types.TracebackType],
  419. ) -> None:
  420. """Context manager exit."""
  421. self.close()
  422. # Additional file-like methods for compatibility
  423. def writelines(self, lines: Iterable[str]) -> None:
  424. """Write a list of lines to the pager."""
  425. if self._pager_died:
  426. return
  427. for line in lines:
  428. self.write(line)
  429. @property
  430. def closed(self) -> bool:
  431. """Return whether the pager is closed."""
  432. return self._closed
  433. def readable(self) -> bool:
  434. """Return whether the pager is readable (it's not)."""
  435. return False
  436. def writable(self) -> bool:
  437. """Return whether the pager is writable."""
  438. return not self._closed
  439. def seekable(self) -> bool:
  440. """Return whether the pager is seekable (it's not)."""
  441. return False
  442. @property
  443. def buffer(self) -> BinaryIO:
  444. """Return the underlying binary buffer."""
  445. return self._buffer
  446. @property
  447. def encoding(self) -> str:
  448. """Return the encoding used."""
  449. return "utf-8"
  450. @property
  451. def errors(self) -> Optional[str]:
  452. """Return the error handling scheme."""
  453. return "replace"
  454. def fileno(self) -> int:
  455. """Return the file descriptor (not supported)."""
  456. raise io.UnsupportedOperation("Pager does not support fileno()")
  457. def isatty(self) -> bool:
  458. """Return whether the pager is a TTY."""
  459. return False
  460. @property
  461. def line_buffering(self) -> bool:
  462. """Return whether line buffering is enabled."""
  463. return True
  464. @property
  465. def mode(self) -> str:
  466. """Return the mode."""
  467. return "w"
  468. @property
  469. def name(self) -> str:
  470. """Return the name."""
  471. return "<pager>"
  472. @property
  473. def newlines(self) -> Optional[Union[str, tuple[str, ...]]]:
  474. """Return the newlines mode."""
  475. return None
  476. def read(self, size: int = -1) -> str:
  477. """Read from the pager (not supported)."""
  478. raise io.UnsupportedOperation("Pager does not support reading")
  479. def readline(self, size: int = -1) -> str:
  480. """Read a line from the pager (not supported)."""
  481. raise io.UnsupportedOperation("Pager does not support reading")
  482. def readlines(self, hint: int = -1) -> list[str]:
  483. """Read lines from the pager (not supported)."""
  484. raise io.UnsupportedOperation("Pager does not support reading")
  485. def seek(self, offset: int, whence: int = 0) -> int:
  486. """Seek in the pager (not supported)."""
  487. raise io.UnsupportedOperation("Pager does not support seeking")
  488. def tell(self) -> int:
  489. """Return the current position (not supported)."""
  490. raise io.UnsupportedOperation("Pager does not support tell()")
  491. def truncate(self, size: Optional[int] = None) -> int:
  492. """Truncate the pager (not supported)."""
  493. raise io.UnsupportedOperation("Pager does not support truncation")
  494. def __iter__(self) -> "Pager":
  495. """Return iterator (not supported)."""
  496. raise io.UnsupportedOperation("Pager does not support iteration")
  497. def __next__(self) -> str:
  498. """Return next line (not supported)."""
  499. raise io.UnsupportedOperation("Pager does not support iteration")
  500. class _StreamContextAdapter:
  501. """Adapter to make streams work with context manager protocol."""
  502. def __init__(self, stream: Union[TextIO, BinaryIO]) -> None:
  503. self.stream = stream
  504. # Expose buffer if it exists
  505. if hasattr(stream, "buffer"):
  506. self.buffer = stream.buffer
  507. else:
  508. self.buffer = stream
  509. def __enter__(self) -> TextIO:
  510. # We only use this with sys.stdout which is TextIO
  511. return self.stream # type: ignore[return-value]
  512. def __exit__(
  513. self,
  514. exc_type: Optional[type[BaseException]],
  515. exc_val: Optional[BaseException],
  516. exc_tb: Optional[TracebackType],
  517. ) -> None:
  518. # For stdout/stderr, we don't close them
  519. pass
  520. def __getattr__(self, name: str) -> object:
  521. return getattr(self.stream, name)
  522. def get_pager(
  523. config: Optional[Config] = None, cmd_name: Optional[str] = None
  524. ) -> Union[_StreamContextAdapter, "Pager"]:
  525. """Get a pager instance if paging should be used, otherwise return sys.stdout.
  526. Args:
  527. config: Optional config instance (e.g., StackedConfig) to read settings from
  528. cmd_name: Optional command name for per-command pager settings
  529. Returns:
  530. Either a wrapped sys.stdout or a Pager instance (both context managers)
  531. """
  532. # Check global pager disable flag
  533. if getattr(get_pager, "_disabled", False):
  534. return _StreamContextAdapter(sys.stdout)
  535. # Don't page if stdout is not a terminal
  536. if not sys.stdout.isatty():
  537. return _StreamContextAdapter(sys.stdout)
  538. # Priority order for pager command (following git's behavior):
  539. # 1. Check pager.<cmd> config (if cmd_name provided)
  540. # 2. Check environment variables: DULWICH_PAGER, GIT_PAGER, PAGER
  541. # 3. Check core.pager config
  542. # 4. Fallback to common pagers
  543. pager_cmd = None
  544. # 1. Check per-command pager config (pager.<cmd>)
  545. if config and cmd_name:
  546. try:
  547. pager_value = config.get(
  548. ("pager",), cmd_name.encode() if isinstance(cmd_name, str) else cmd_name
  549. )
  550. except KeyError:
  551. pass
  552. else:
  553. if pager_value == b"false":
  554. return _StreamContextAdapter(sys.stdout)
  555. elif pager_value != b"true":
  556. # It's a custom pager command
  557. pager_cmd = (
  558. pager_value.decode()
  559. if isinstance(pager_value, bytes)
  560. else pager_value
  561. )
  562. # 2. Check environment variables
  563. if not pager_cmd:
  564. for env_var in ["DULWICH_PAGER", "GIT_PAGER", "PAGER"]:
  565. pager = os.environ.get(env_var)
  566. if pager:
  567. if pager == "false":
  568. return _StreamContextAdapter(sys.stdout)
  569. pager_cmd = pager
  570. break
  571. # 3. Check core.pager config
  572. if not pager_cmd and config:
  573. try:
  574. core_pager = config.get(("core",), b"pager")
  575. except KeyError:
  576. pass
  577. else:
  578. if core_pager == b"false" or core_pager == b"":
  579. return _StreamContextAdapter(sys.stdout)
  580. pager_cmd = (
  581. core_pager.decode() if isinstance(core_pager, bytes) else core_pager
  582. )
  583. # 4. Fallback to common pagers
  584. if not pager_cmd:
  585. for pager in ["less", "more", "cat"]:
  586. if shutil.which(pager):
  587. if pager == "less":
  588. pager_cmd = "less -FRX" # -F: quit if one screen, -R: raw control chars, -X: no init/deinit
  589. else:
  590. pager_cmd = pager
  591. break
  592. else:
  593. pager_cmd = "cat" # Ultimate fallback
  594. return Pager(pager_cmd)
  595. def disable_pager() -> None:
  596. """Disable pager for this session."""
  597. get_pager._disabled = True # type: ignore[attr-defined]
  598. def enable_pager() -> None:
  599. """Enable pager for this session."""
  600. get_pager._disabled = False # type: ignore[attr-defined]
  601. class Command:
  602. """A Dulwich subcommand."""
  603. def run(self, args: Sequence[str]) -> Optional[int]:
  604. """Run the command."""
  605. raise NotImplementedError(self.run)
  606. class cmd_archive(Command):
  607. """Create an archive of files from a named tree."""
  608. def run(self, args: Sequence[str]) -> None:
  609. """Execute the archive command.
  610. Args:
  611. args: Command line arguments
  612. """
  613. parser = argparse.ArgumentParser()
  614. parser.add_argument(
  615. "--remote",
  616. type=str,
  617. help="Retrieve archive from specified remote repo",
  618. )
  619. parser.add_argument("committish", type=str, nargs="?")
  620. parsed_args = parser.parse_args(args)
  621. if parsed_args.remote:
  622. client, path = get_transport_and_path(parsed_args.remote)
  623. def stdout_write(data: bytes) -> None:
  624. sys.stdout.buffer.write(data)
  625. def stderr_write(data: bytes) -> None:
  626. sys.stderr.buffer.write(data)
  627. client.archive(
  628. path.encode("utf-8") if isinstance(path, str) else path,
  629. parsed_args.committish.encode("utf-8")
  630. if isinstance(parsed_args.committish, str)
  631. else parsed_args.committish,
  632. stdout_write,
  633. write_error=stderr_write,
  634. )
  635. else:
  636. # Use binary buffer for archive output
  637. outstream: BinaryIO = sys.stdout.buffer
  638. errstream: BinaryIO = sys.stderr.buffer
  639. porcelain.archive(
  640. ".",
  641. parsed_args.committish,
  642. outstream=outstream,
  643. errstream=errstream,
  644. )
  645. class cmd_add(Command):
  646. """Add file contents to the index."""
  647. def run(self, argv: Sequence[str]) -> None:
  648. """Execute the add command.
  649. Args:
  650. argv: Command line arguments
  651. """
  652. parser = argparse.ArgumentParser()
  653. parser.add_argument("path", nargs="+")
  654. args = parser.parse_args(argv)
  655. # Convert '.' to None to add all files
  656. paths = args.path
  657. if len(paths) == 1 and paths[0] == ".":
  658. paths = None
  659. porcelain.add(".", paths=paths)
  660. class cmd_annotate(Command):
  661. """Annotate each line in a file with commit information."""
  662. def run(self, argv: Sequence[str]) -> None:
  663. """Execute the annotate command.
  664. Args:
  665. argv: Command line arguments
  666. """
  667. parser = argparse.ArgumentParser()
  668. parser.add_argument("path", help="Path to file to annotate")
  669. parser.add_argument("committish", nargs="?", help="Commit to start from")
  670. args = parser.parse_args(argv)
  671. with Repo(".") as repo:
  672. config = repo.get_config_stack()
  673. with get_pager(config=config, cmd_name="annotate") as outstream:
  674. results = porcelain.annotate(repo, args.path, args.committish)
  675. for (commit, entry), line in results:
  676. # Show shortened commit hash and line content
  677. commit_hash = commit.id[:8]
  678. outstream.write(f"{commit_hash.decode()} {line.decode()}\n")
  679. class cmd_blame(Command):
  680. """Show what revision and author last modified each line of a file."""
  681. def run(self, argv: Sequence[str]) -> None:
  682. """Execute the blame command.
  683. Args:
  684. argv: Command line arguments
  685. """
  686. # blame is an alias for annotate
  687. cmd_annotate().run(argv)
  688. class cmd_rm(Command):
  689. """Remove files from the working tree and from the index."""
  690. def run(self, argv: Sequence[str]) -> None:
  691. """Execute the rm command.
  692. Args:
  693. argv: Command line arguments
  694. """
  695. parser = argparse.ArgumentParser()
  696. parser.add_argument(
  697. "--cached", action="store_true", help="Remove from index only"
  698. )
  699. parser.add_argument("path", type=Path, nargs="+")
  700. args = parser.parse_args(argv)
  701. porcelain.remove(".", paths=args.path, cached=args.cached)
  702. class cmd_mv(Command):
  703. """Move or rename a file, a directory, or a symlink."""
  704. def run(self, argv: Sequence[str]) -> None:
  705. """Execute the mv command.
  706. Args:
  707. argv: Command line arguments
  708. """
  709. parser = argparse.ArgumentParser()
  710. parser.add_argument(
  711. "-f",
  712. "--force",
  713. action="store_true",
  714. help="Force move even if destination exists",
  715. )
  716. parser.add_argument("source", type=Path)
  717. parser.add_argument("destination", type=Path)
  718. args = parser.parse_args(argv)
  719. porcelain.mv(".", args.source, args.destination, force=args.force)
  720. class cmd_fetch_pack(Command):
  721. """Receive missing objects from another repository."""
  722. def run(self, argv: Sequence[str]) -> None:
  723. """Execute the fetch-pack command.
  724. Args:
  725. argv: Command line arguments
  726. """
  727. parser = argparse.ArgumentParser()
  728. parser.add_argument("--all", action="store_true")
  729. parser.add_argument("location", nargs="?", type=str)
  730. parser.add_argument("refs", nargs="*", type=str)
  731. args = parser.parse_args(argv)
  732. client, path = get_transport_and_path(args.location)
  733. r = Repo(".")
  734. if args.all:
  735. determine_wants = r.object_store.determine_wants_all
  736. else:
  737. def determine_wants(
  738. refs: Mapping[bytes, bytes], depth: Optional[int] = None
  739. ) -> list[bytes]:
  740. return [y.encode("utf-8") for y in args.refs if y not in r.object_store]
  741. client.fetch(path.encode("utf-8"), r, determine_wants)
  742. class cmd_fetch(Command):
  743. """Download objects and refs from another repository."""
  744. def run(self, args: Sequence[str]) -> None:
  745. """Execute the fetch command.
  746. Args:
  747. args: Command line arguments
  748. """
  749. parser = argparse.ArgumentParser()
  750. parser.add_argument("location", help="Remote location to fetch from")
  751. parsed_args = parser.parse_args(args)
  752. client, path = get_transport_and_path(parsed_args.location)
  753. r = Repo(".")
  754. def progress(msg: bytes) -> None:
  755. sys.stdout.buffer.write(msg)
  756. result = client.fetch(path.encode("utf-8"), r, progress=progress)
  757. logger.info("Remote refs:")
  758. for ref, sha in result.refs.items():
  759. if sha is not None:
  760. logger.info("%s → %s", ref.decode(), sha.decode())
  761. class cmd_for_each_ref(Command):
  762. """Output information on each ref."""
  763. def run(self, args: Sequence[str]) -> None:
  764. """Execute the for-each-ref command.
  765. Args:
  766. args: Command line arguments
  767. """
  768. parser = argparse.ArgumentParser()
  769. parser.add_argument("pattern", type=str, nargs="?")
  770. parsed_args = parser.parse_args(args)
  771. for sha, object_type, ref in porcelain.for_each_ref(".", parsed_args.pattern):
  772. logger.info("%s %s\t%s", sha.decode(), object_type.decode(), ref.decode())
  773. class cmd_fsck(Command):
  774. """Verify the connectivity and validity of objects in the database."""
  775. def run(self, args: Sequence[str]) -> None:
  776. """Execute the fsck command.
  777. Args:
  778. args: Command line arguments
  779. """
  780. parser = argparse.ArgumentParser()
  781. parser.parse_args(args)
  782. for obj, msg in porcelain.fsck("."):
  783. logger.info("%s: %s", obj.decode() if isinstance(obj, bytes) else obj, msg)
  784. class cmd_log(Command):
  785. """Show commit logs."""
  786. def run(self, args: Sequence[str]) -> None:
  787. """Execute the log command.
  788. Args:
  789. args: Command line arguments
  790. """
  791. parser = argparse.ArgumentParser()
  792. parser.add_argument(
  793. "--reverse",
  794. action="store_true",
  795. help="Reverse order in which entries are printed",
  796. )
  797. parser.add_argument(
  798. "--name-status",
  799. action="store_true",
  800. help="Print name/status for each changed file",
  801. )
  802. parser.add_argument("paths", nargs="*", help="Paths to show log for")
  803. parsed_args = parser.parse_args(args)
  804. with Repo(".") as repo:
  805. config = repo.get_config_stack()
  806. with get_pager(config=config, cmd_name="log") as outstream:
  807. porcelain.log(
  808. repo,
  809. paths=parsed_args.paths,
  810. reverse=parsed_args.reverse,
  811. name_status=parsed_args.name_status,
  812. outstream=outstream,
  813. )
  814. class cmd_diff(Command):
  815. """Show changes between commits, commit and working tree, etc."""
  816. def run(self, args: Sequence[str]) -> None:
  817. """Execute the diff command.
  818. Args:
  819. args: Command line arguments
  820. """
  821. parser = argparse.ArgumentParser()
  822. parser.add_argument(
  823. "committish", nargs="*", default=[], help="Commits or refs to compare"
  824. )
  825. parser.add_argument("--staged", action="store_true", help="Show staged changes")
  826. parser.add_argument(
  827. "--cached",
  828. action="store_true",
  829. help="Show staged changes (same as --staged)",
  830. )
  831. parser.add_argument(
  832. "--color",
  833. choices=["always", "never", "auto"],
  834. default="auto",
  835. help="Use colored output (requires rich)",
  836. )
  837. parser.add_argument(
  838. "--patience",
  839. action="store_true",
  840. help="Use patience diff algorithm",
  841. )
  842. parser.add_argument(
  843. "--diff-algorithm",
  844. choices=["myers", "patience"],
  845. default="myers",
  846. help="Choose a diff algorithm",
  847. )
  848. parser.add_argument(
  849. "--", dest="separator", action="store_true", help=argparse.SUPPRESS
  850. )
  851. parser.add_argument("paths", nargs="*", default=[], help="Paths to limit diff")
  852. # Handle the -- separator for paths
  853. if "--" in args:
  854. sep_index = args.index("--")
  855. parsed_args = parser.parse_args(args[:sep_index])
  856. parsed_args.paths = args[sep_index + 1 :]
  857. else:
  858. parsed_args = parser.parse_args(args)
  859. # Determine diff algorithm
  860. diff_algorithm = parsed_args.diff_algorithm
  861. if parsed_args.patience:
  862. diff_algorithm = "patience"
  863. # Determine if we should use color
  864. def _should_use_color() -> bool:
  865. if parsed_args.color == "always":
  866. return True
  867. elif parsed_args.color == "never":
  868. return False
  869. else: # auto
  870. return sys.stdout.isatty()
  871. def _create_output_stream(outstream: TextIO) -> BinaryIO:
  872. """Create output stream, optionally with colorization."""
  873. if not _should_use_color():
  874. return outstream.buffer
  875. from .diff import ColorizedDiffStream
  876. if not ColorizedDiffStream.is_available():
  877. if parsed_args.color == "always":
  878. raise ImportError(
  879. "Rich is required for colored output. Install with: pip install 'dulwich[colordiff]'"
  880. )
  881. else:
  882. logging.warning(
  883. "Rich not available, disabling colored output. Install with: pip install 'dulwich[colordiff]'"
  884. )
  885. return outstream.buffer
  886. return ColorizedDiffStream(outstream.buffer)
  887. with Repo(".") as repo:
  888. config = repo.get_config_stack()
  889. with get_pager(config=config, cmd_name="diff") as outstream:
  890. output_stream = _create_output_stream(outstream)
  891. try:
  892. if len(parsed_args.committish) == 0:
  893. # Show diff for working tree or staged changes
  894. porcelain.diff(
  895. repo,
  896. staged=(parsed_args.staged or parsed_args.cached),
  897. paths=parsed_args.paths or None,
  898. outstream=output_stream,
  899. diff_algorithm=diff_algorithm,
  900. )
  901. elif len(parsed_args.committish) == 1:
  902. # Show diff between working tree and specified commit
  903. if parsed_args.staged or parsed_args.cached:
  904. parser.error(
  905. "--staged/--cached cannot be used with commits"
  906. )
  907. porcelain.diff(
  908. repo,
  909. commit=parsed_args.committish[0],
  910. staged=False,
  911. paths=parsed_args.paths or None,
  912. outstream=output_stream,
  913. diff_algorithm=diff_algorithm,
  914. )
  915. elif len(parsed_args.committish) == 2:
  916. # Show diff between two commits
  917. porcelain.diff(
  918. repo,
  919. commit=parsed_args.committish[0],
  920. commit2=parsed_args.committish[1],
  921. paths=parsed_args.paths or None,
  922. outstream=output_stream,
  923. diff_algorithm=diff_algorithm,
  924. )
  925. else:
  926. parser.error("Too many arguments - specify at most two commits")
  927. except DiffAlgorithmNotAvailable as e:
  928. sys.stderr.write(f"fatal: {e}\n")
  929. sys.exit(1)
  930. # Flush any remaining output
  931. if hasattr(output_stream, "flush"):
  932. output_stream.flush()
  933. class cmd_dump_pack(Command):
  934. """Dump the contents of a pack file for debugging."""
  935. def run(self, args: Sequence[str]) -> None:
  936. """Execute the dump-pack command.
  937. Args:
  938. args: Command line arguments
  939. """
  940. parser = argparse.ArgumentParser()
  941. parser.add_argument("filename", help="Pack file to dump")
  942. parsed_args = parser.parse_args(args)
  943. basename, _ = os.path.splitext(parsed_args.filename)
  944. x = Pack(basename)
  945. logger.info("Object names checksum: %s", x.name().decode("ascii", "replace"))
  946. logger.info("Checksum: %r", sha_to_hex(x.get_stored_checksum()))
  947. x.check()
  948. logger.info("Length: %d", len(x))
  949. for name in x:
  950. try:
  951. logger.info("\t%s", x[name])
  952. except KeyError as k:
  953. logger.error(
  954. "\t%s: Unable to resolve base %r",
  955. name.decode("ascii", "replace"),
  956. k,
  957. )
  958. except ApplyDeltaError as e:
  959. logger.error(
  960. "\t%s: Unable to apply delta: %r",
  961. name.decode("ascii", "replace"),
  962. e,
  963. )
  964. class cmd_dump_index(Command):
  965. """Show information about a pack index file."""
  966. def run(self, args: Sequence[str]) -> None:
  967. """Execute the dump-index command.
  968. Args:
  969. args: Command line arguments
  970. """
  971. parser = argparse.ArgumentParser()
  972. parser.add_argument("filename", help="Index file to dump")
  973. parsed_args = parser.parse_args(args)
  974. idx = Index(parsed_args.filename)
  975. for o in idx:
  976. logger.info("%s %s", o, idx[o])
  977. class cmd_init(Command):
  978. """Create an empty Git repository or reinitialize an existing one."""
  979. def run(self, args: Sequence[str]) -> None:
  980. """Execute the init command.
  981. Args:
  982. args: Command line arguments
  983. """
  984. parser = argparse.ArgumentParser()
  985. parser.add_argument(
  986. "--bare", action="store_true", help="Create a bare repository"
  987. )
  988. parser.add_argument(
  989. "path", nargs="?", default=os.getcwd(), help="Repository path"
  990. )
  991. parsed_args = parser.parse_args(args)
  992. porcelain.init(parsed_args.path, bare=parsed_args.bare)
  993. class cmd_clone(Command):
  994. """Clone a repository into a new directory."""
  995. def run(self, args: Sequence[str]) -> None:
  996. """Execute the clone command.
  997. Args:
  998. args: Command line arguments
  999. """
  1000. parser = argparse.ArgumentParser()
  1001. parser.add_argument(
  1002. "--bare",
  1003. help="Whether to create a bare repository.",
  1004. action="store_true",
  1005. )
  1006. parser.add_argument("--depth", type=int, help="Depth at which to fetch")
  1007. parser.add_argument(
  1008. "-b",
  1009. "--branch",
  1010. type=str,
  1011. help="Check out branch instead of branch pointed to by remote HEAD",
  1012. )
  1013. parser.add_argument(
  1014. "--refspec",
  1015. type=str,
  1016. help="References to fetch",
  1017. action="append",
  1018. )
  1019. parser.add_argument(
  1020. "--filter",
  1021. dest="filter_spec",
  1022. type=str,
  1023. help="git-rev-list-style object filter",
  1024. )
  1025. parser.add_argument(
  1026. "--protocol",
  1027. type=int,
  1028. help="Git protocol version to use",
  1029. )
  1030. parser.add_argument(
  1031. "--recurse-submodules",
  1032. action="store_true",
  1033. help="Initialize and clone submodules",
  1034. )
  1035. parser.add_argument("source", help="Repository to clone from")
  1036. parser.add_argument("target", nargs="?", help="Directory to clone into")
  1037. parsed_args = parser.parse_args(args)
  1038. try:
  1039. porcelain.clone(
  1040. parsed_args.source,
  1041. parsed_args.target,
  1042. bare=parsed_args.bare,
  1043. depth=parsed_args.depth,
  1044. branch=parsed_args.branch,
  1045. refspec=parsed_args.refspec,
  1046. filter_spec=parsed_args.filter_spec,
  1047. protocol_version=parsed_args.protocol,
  1048. recurse_submodules=parsed_args.recurse_submodules,
  1049. )
  1050. except GitProtocolError as e:
  1051. logging.exception(e)
  1052. def _get_commit_message_with_template(
  1053. initial_message: Optional[bytes],
  1054. repo: Optional[Repo] = None,
  1055. commit: Optional[Commit] = None,
  1056. ) -> bytes:
  1057. """Get commit message with an initial message template."""
  1058. # Start with the initial message
  1059. template = initial_message or b""
  1060. if template and not template.endswith(b"\n"):
  1061. template += b"\n"
  1062. template += b"\n"
  1063. template += b"# Please enter the commit message for your changes. Lines starting\n"
  1064. template += b"# with '#' will be ignored, and an empty message aborts the commit.\n"
  1065. template += b"#\n"
  1066. # Add branch info if repo is provided
  1067. if repo:
  1068. try:
  1069. ref_names, _ref_sha = repo.refs.follow(b"HEAD")
  1070. ref_path = ref_names[-1] # Get the final reference
  1071. if ref_path.startswith(b"refs/heads/"):
  1072. branch = ref_path[11:] # Remove 'refs/heads/' prefix
  1073. else:
  1074. branch = ref_path
  1075. template += b"# On branch %s\n" % branch
  1076. except (KeyError, IndexError):
  1077. template += b"# On branch (unknown)\n"
  1078. template += b"#\n"
  1079. template += b"# Changes to be committed:\n"
  1080. # Launch editor
  1081. content = launch_editor(template)
  1082. # Remove comment lines and strip
  1083. lines = content.split(b"\n")
  1084. message_lines = [line for line in lines if not line.strip().startswith(b"#")]
  1085. message = b"\n".join(message_lines).strip()
  1086. if not message:
  1087. raise CommitMessageError("Aborting commit due to empty commit message")
  1088. return message
  1089. class cmd_commit(Command):
  1090. """Record changes to the repository."""
  1091. def run(self, args: Sequence[str]) -> Optional[int]:
  1092. """Execute the commit command.
  1093. Args:
  1094. args: Command line arguments
  1095. """
  1096. parser = argparse.ArgumentParser()
  1097. parser.add_argument("--message", "-m", help="Commit message")
  1098. parser.add_argument(
  1099. "-a",
  1100. "--all",
  1101. action="store_true",
  1102. help="Automatically stage all tracked files that have been modified",
  1103. )
  1104. parser.add_argument(
  1105. "--amend",
  1106. action="store_true",
  1107. help="Replace the tip of the current branch by creating a new commit",
  1108. )
  1109. parsed_args = parser.parse_args(args)
  1110. message: Union[bytes, str, Callable[[Optional[Repo], Optional[Commit]], bytes]]
  1111. if parsed_args.message:
  1112. message = parsed_args.message
  1113. elif parsed_args.amend:
  1114. # For amend, create a callable that opens editor with original message pre-populated
  1115. def get_amend_message(
  1116. repo: Optional[Repo], commit: Optional[Commit]
  1117. ) -> bytes:
  1118. # Get the original commit message from current HEAD
  1119. assert repo is not None
  1120. try:
  1121. head_commit = repo[repo.head()]
  1122. assert isinstance(head_commit, Commit)
  1123. original_message = head_commit.message
  1124. except KeyError:
  1125. original_message = b""
  1126. # Open editor with original message
  1127. return _get_commit_message_with_template(original_message, repo, commit)
  1128. message = get_amend_message
  1129. else:
  1130. # For regular commits, use empty template
  1131. def get_regular_message(
  1132. repo: Optional[Repo], commit: Optional[Commit]
  1133. ) -> bytes:
  1134. return _get_commit_message_with_template(b"", repo, commit)
  1135. message = get_regular_message
  1136. try:
  1137. porcelain.commit(
  1138. ".", message=message, all=parsed_args.all, amend=parsed_args.amend
  1139. )
  1140. except CommitMessageError as e:
  1141. logging.exception(e)
  1142. return 1
  1143. return None
  1144. class cmd_commit_tree(Command):
  1145. """Create a new commit object from a tree."""
  1146. def run(self, args: Sequence[str]) -> None:
  1147. """Execute the commit-tree command.
  1148. Args:
  1149. args: Command line arguments
  1150. """
  1151. parser = argparse.ArgumentParser()
  1152. parser.add_argument("--message", "-m", required=True, help="Commit message")
  1153. parser.add_argument("tree", help="Tree SHA to commit")
  1154. parsed_args = parser.parse_args(args)
  1155. porcelain.commit_tree(".", tree=parsed_args.tree, message=parsed_args.message)
  1156. class cmd_update_server_info(Command):
  1157. """Update auxiliary info file to help dumb servers."""
  1158. def run(self, args: Sequence[str]) -> None:
  1159. """Execute the update-server-info command.
  1160. Args:
  1161. args: Command line arguments
  1162. """
  1163. porcelain.update_server_info(".")
  1164. class cmd_symbolic_ref(Command):
  1165. """Read, modify and delete symbolic refs."""
  1166. def run(self, args: Sequence[str]) -> Optional[int]:
  1167. """Execute the symbolic-ref command.
  1168. Args:
  1169. args: Command line arguments
  1170. """
  1171. parser = argparse.ArgumentParser()
  1172. parser.add_argument("name", help="Symbolic reference name")
  1173. parser.add_argument("ref", nargs="?", help="Target reference")
  1174. parser.add_argument("--force", action="store_true", help="Force update")
  1175. parsed_args = parser.parse_args(args)
  1176. # If ref is provided, we're setting; otherwise we're reading
  1177. if parsed_args.ref:
  1178. # Set symbolic reference
  1179. from .repo import Repo
  1180. with Repo(".") as repo:
  1181. repo.refs.set_symbolic_ref(
  1182. parsed_args.name.encode(), parsed_args.ref.encode()
  1183. )
  1184. return 0
  1185. else:
  1186. # Read symbolic reference
  1187. from .repo import Repo
  1188. with Repo(".") as repo:
  1189. try:
  1190. target = repo.refs.read_ref(parsed_args.name.encode())
  1191. if target is None:
  1192. logger.error(
  1193. "fatal: ref '%s' is not a symbolic ref", parsed_args.name
  1194. )
  1195. return 1
  1196. elif target.startswith(b"ref: "):
  1197. logger.info(target[5:].decode())
  1198. else:
  1199. logger.info(target.decode())
  1200. return 0
  1201. except KeyError:
  1202. logger.error(
  1203. "fatal: ref '%s' is not a symbolic ref", parsed_args.name
  1204. )
  1205. return 1
  1206. class cmd_pack_refs(Command):
  1207. """Pack heads and tags for efficient repository access."""
  1208. def run(self, argv: Sequence[str]) -> None:
  1209. """Execute the pack-refs command.
  1210. Args:
  1211. argv: Command line arguments
  1212. """
  1213. parser = argparse.ArgumentParser()
  1214. parser.add_argument("--all", action="store_true")
  1215. # ignored, we never prune
  1216. parser.add_argument("--no-prune", action="store_true")
  1217. args = parser.parse_args(argv)
  1218. porcelain.pack_refs(".", all=args.all)
  1219. class cmd_var(Command):
  1220. """Display Git logical variables."""
  1221. def run(self, argv: Sequence[str]) -> Optional[int]:
  1222. """Execute the var command.
  1223. Args:
  1224. argv: Command line arguments
  1225. """
  1226. parser = argparse.ArgumentParser()
  1227. parser.add_argument(
  1228. "variable",
  1229. nargs="?",
  1230. help="Variable to query (e.g., GIT_AUTHOR_IDENT)",
  1231. )
  1232. parser.add_argument(
  1233. "-l",
  1234. "--list",
  1235. action="store_true",
  1236. help="List all variables",
  1237. )
  1238. args = parser.parse_args(argv)
  1239. if args.list:
  1240. # List all variables
  1241. variables = porcelain.var_list(".")
  1242. for key, value in sorted(variables.items()):
  1243. print(f"{key}={value}")
  1244. return 0
  1245. elif args.variable:
  1246. # Query specific variable
  1247. try:
  1248. value = porcelain.var(".", variable=args.variable)
  1249. print(value)
  1250. return 0
  1251. except KeyError:
  1252. logger.error("error: variable '%s' has no value", args.variable)
  1253. return 1
  1254. else:
  1255. # No arguments - print error
  1256. logger.error("error: variable or -l is required")
  1257. parser.print_help()
  1258. return 1
  1259. class cmd_show(Command):
  1260. """Show various types of objects."""
  1261. def run(self, argv: Sequence[str]) -> None:
  1262. """Execute the show command.
  1263. Args:
  1264. argv: Command line arguments
  1265. """
  1266. parser = argparse.ArgumentParser()
  1267. parser.add_argument("objectish", type=str, nargs="*")
  1268. parser.add_argument(
  1269. "--color",
  1270. choices=["always", "never", "auto"],
  1271. default="auto",
  1272. help="Use colored output (requires rich)",
  1273. )
  1274. args = parser.parse_args(argv)
  1275. # Determine if we should use color
  1276. def _should_use_color() -> bool:
  1277. if args.color == "always":
  1278. return True
  1279. elif args.color == "never":
  1280. return False
  1281. else: # auto
  1282. return sys.stdout.isatty()
  1283. def _create_output_stream(outstream: TextIO) -> TextIO:
  1284. """Create output stream, optionally with colorization."""
  1285. if not _should_use_color():
  1286. return outstream
  1287. from .diff import ColorizedDiffStream
  1288. if not ColorizedDiffStream.is_available():
  1289. if args.color == "always":
  1290. raise ImportError(
  1291. "Rich is required for colored output. Install with: pip install 'dulwich[colordiff]'"
  1292. )
  1293. else:
  1294. logging.warning(
  1295. "Rich not available, disabling colored output. Install with: pip install 'dulwich[colordiff]'"
  1296. )
  1297. return outstream
  1298. # Wrap the ColorizedDiffStream (BinaryIO) back to TextIO
  1299. import io
  1300. colorized = ColorizedDiffStream(outstream.buffer)
  1301. return io.TextIOWrapper(colorized, encoding="utf-8", line_buffering=True)
  1302. with Repo(".") as repo:
  1303. config = repo.get_config_stack()
  1304. with get_pager(config=config, cmd_name="show") as outstream:
  1305. output_stream = _create_output_stream(outstream)
  1306. porcelain.show(repo, args.objectish or None, outstream=output_stream)
  1307. class cmd_show_ref(Command):
  1308. """List references in a local repository."""
  1309. def run(self, args: Sequence[str]) -> Optional[int]:
  1310. """Execute the show-ref command.
  1311. Args:
  1312. args: Command line arguments
  1313. Returns:
  1314. Exit code (0 for success, 1 for error/no matches, 2 for missing ref with --exists)
  1315. """
  1316. parser = argparse.ArgumentParser()
  1317. parser.add_argument(
  1318. "--head",
  1319. action="store_true",
  1320. help="Show the HEAD reference",
  1321. )
  1322. parser.add_argument(
  1323. "--branches",
  1324. action="store_true",
  1325. help="Limit to local branches",
  1326. )
  1327. parser.add_argument(
  1328. "--tags",
  1329. action="store_true",
  1330. help="Limit to local tags",
  1331. )
  1332. parser.add_argument(
  1333. "-d",
  1334. "--dereference",
  1335. action="store_true",
  1336. help="Dereference tags into object IDs",
  1337. )
  1338. parser.add_argument(
  1339. "-s",
  1340. "--hash",
  1341. nargs="?",
  1342. const=40,
  1343. type=int,
  1344. metavar="n",
  1345. help="Only show the OID, not the reference name",
  1346. )
  1347. parser.add_argument(
  1348. "--abbrev",
  1349. nargs="?",
  1350. const=7,
  1351. type=int,
  1352. metavar="n",
  1353. help="Abbreviate the object name",
  1354. )
  1355. parser.add_argument(
  1356. "--verify",
  1357. action="store_true",
  1358. help="Enable stricter reference checking (exact path match)",
  1359. )
  1360. parser.add_argument(
  1361. "--exists",
  1362. action="store_true",
  1363. help="Check whether the given reference exists",
  1364. )
  1365. parser.add_argument(
  1366. "-q",
  1367. "--quiet",
  1368. action="store_true",
  1369. help="Do not print any results to stdout",
  1370. )
  1371. parser.add_argument(
  1372. "patterns",
  1373. nargs="*",
  1374. help="Show references matching patterns",
  1375. )
  1376. parsed_args = parser.parse_args(args)
  1377. # Handle --exists mode
  1378. if parsed_args.exists:
  1379. if not parsed_args.patterns or len(parsed_args.patterns) != 1:
  1380. logger.error("--exists requires exactly one reference argument")
  1381. return 1
  1382. try:
  1383. with Repo(".") as repo:
  1384. repo_refs = repo.get_refs()
  1385. pattern_bytes = os.fsencode(parsed_args.patterns[0])
  1386. if pattern_bytes in repo_refs:
  1387. return 0 # Reference exists
  1388. else:
  1389. return 2 # Reference missing
  1390. except (NotGitRepository, OSError, FileFormatException) as e:
  1391. logger.error(f"Error looking up reference: {e}")
  1392. return 1 # Error looking up reference
  1393. # Regular show-ref mode
  1394. try:
  1395. matched_refs = porcelain.show_ref(
  1396. ".",
  1397. patterns=parsed_args.patterns if parsed_args.patterns else None,
  1398. head=parsed_args.head,
  1399. branches=parsed_args.branches,
  1400. tags=parsed_args.tags,
  1401. dereference=parsed_args.dereference,
  1402. verify=parsed_args.verify,
  1403. )
  1404. except (NotGitRepository, OSError, FileFormatException) as e:
  1405. logger.error(f"Error: {e}")
  1406. return 1
  1407. # Return error if no matches found (unless quiet)
  1408. if not matched_refs:
  1409. if parsed_args.verify and not parsed_args.quiet:
  1410. logger.error("error: no matching refs found")
  1411. return 1
  1412. # Output results
  1413. if not parsed_args.quiet:
  1414. abbrev_len = parsed_args.abbrev if parsed_args.abbrev else 40
  1415. hash_only = parsed_args.hash is not None
  1416. if hash_only and parsed_args.hash:
  1417. abbrev_len = parsed_args.hash
  1418. for sha, ref in matched_refs:
  1419. sha_str = sha.decode()
  1420. if abbrev_len < 40:
  1421. sha_str = sha_str[:abbrev_len]
  1422. if hash_only:
  1423. logger.info(sha_str)
  1424. else:
  1425. logger.info(f"{sha_str} {ref.decode()}")
  1426. return 0
  1427. class cmd_show_branch(Command):
  1428. """Show branches and their commits."""
  1429. def run(self, args: Sequence[str]) -> Optional[int]:
  1430. """Execute the show-branch command.
  1431. Args:
  1432. args: Command line arguments
  1433. Returns:
  1434. Exit code (0 for success, 1 for error)
  1435. """
  1436. parser = argparse.ArgumentParser()
  1437. parser.add_argument(
  1438. "-r",
  1439. "--remotes",
  1440. action="store_true",
  1441. help="Show remote-tracking branches",
  1442. )
  1443. parser.add_argument(
  1444. "-a",
  1445. "--all",
  1446. dest="all_branches",
  1447. action="store_true",
  1448. help="Show both remote-tracking and local branches",
  1449. )
  1450. parser.add_argument(
  1451. "--current",
  1452. action="store_true",
  1453. help="Include current branch if not given on command line",
  1454. )
  1455. parser.add_argument(
  1456. "--topo-order",
  1457. dest="topo_order",
  1458. action="store_true",
  1459. help="Show commits in topological order",
  1460. )
  1461. parser.add_argument(
  1462. "--date-order",
  1463. action="store_true",
  1464. help="Show commits in date order (default)",
  1465. )
  1466. parser.add_argument(
  1467. "--more",
  1468. type=int,
  1469. metavar="n",
  1470. help="Show n more commits beyond common ancestor",
  1471. )
  1472. parser.add_argument(
  1473. "--list",
  1474. dest="list_branches",
  1475. action="store_true",
  1476. help="Show only branch names and their tip commits",
  1477. )
  1478. parser.add_argument(
  1479. "--independent",
  1480. dest="independent_branches",
  1481. action="store_true",
  1482. help="Show only branches not reachable from any other",
  1483. )
  1484. parser.add_argument(
  1485. "--merge-base",
  1486. dest="merge_base",
  1487. action="store_true",
  1488. help="Show merge base of specified branches",
  1489. )
  1490. parser.add_argument(
  1491. "branches",
  1492. nargs="*",
  1493. help="Branches to show (default: all local branches)",
  1494. )
  1495. parsed_args = parser.parse_args(args)
  1496. try:
  1497. output_lines = porcelain.show_branch(
  1498. ".",
  1499. branches=parsed_args.branches if parsed_args.branches else None,
  1500. all_branches=parsed_args.all_branches,
  1501. remotes=parsed_args.remotes,
  1502. current=parsed_args.current,
  1503. topo_order=parsed_args.topo_order,
  1504. more=parsed_args.more,
  1505. list_branches=parsed_args.list_branches,
  1506. independent_branches=parsed_args.independent_branches,
  1507. merge_base=parsed_args.merge_base,
  1508. )
  1509. except (NotGitRepository, OSError, FileFormatException) as e:
  1510. logger.error(f"Error: {e}")
  1511. return 1
  1512. # Output results
  1513. for line in output_lines:
  1514. logger.info(line)
  1515. return 0
  1516. class cmd_diff_tree(Command):
  1517. """Compare the content and mode of trees."""
  1518. def run(self, args: Sequence[str]) -> None:
  1519. """Execute the diff-tree command.
  1520. Args:
  1521. args: Command line arguments
  1522. """
  1523. parser = argparse.ArgumentParser()
  1524. parser.add_argument("old_tree", help="Old tree SHA")
  1525. parser.add_argument("new_tree", help="New tree SHA")
  1526. parsed_args = parser.parse_args(args)
  1527. porcelain.diff_tree(".", parsed_args.old_tree, parsed_args.new_tree)
  1528. class cmd_rev_list(Command):
  1529. """List commit objects in reverse chronological order."""
  1530. def run(self, args: Sequence[str]) -> None:
  1531. """Execute the rev-list command.
  1532. Args:
  1533. args: Command line arguments
  1534. """
  1535. parser = argparse.ArgumentParser()
  1536. parser.add_argument("commits", nargs="+", help="Commit IDs to list")
  1537. parsed_args = parser.parse_args(args)
  1538. porcelain.rev_list(".", parsed_args.commits)
  1539. class cmd_tag(Command):
  1540. """Create, list, delete or verify a tag object."""
  1541. def run(self, args: Sequence[str]) -> None:
  1542. """Execute the tag command.
  1543. Args:
  1544. args: Command line arguments
  1545. """
  1546. parser = argparse.ArgumentParser()
  1547. parser.add_argument(
  1548. "-a",
  1549. "--annotated",
  1550. help="Create an annotated tag.",
  1551. action="store_true",
  1552. )
  1553. parser.add_argument(
  1554. "-s", "--sign", help="Sign the annotated tag.", action="store_true"
  1555. )
  1556. parser.add_argument("tag_name", help="Name of the tag to create")
  1557. parsed_args = parser.parse_args(args)
  1558. porcelain.tag_create(
  1559. ".",
  1560. parsed_args.tag_name,
  1561. annotated=parsed_args.annotated,
  1562. sign=parsed_args.sign,
  1563. )
  1564. class cmd_verify_commit(Command):
  1565. """Check the GPG signature of commits."""
  1566. def run(self, args: Sequence[str]) -> Optional[int]:
  1567. """Execute the verify-commit command.
  1568. Args:
  1569. args: Command line arguments
  1570. Returns:
  1571. Exit code (1 on error, None on success)
  1572. """
  1573. parser = argparse.ArgumentParser()
  1574. parser.add_argument(
  1575. "-v",
  1576. "--verbose",
  1577. help="Print the contents of the commit object before validating it.",
  1578. action="store_true",
  1579. )
  1580. parser.add_argument(
  1581. "--raw",
  1582. help="Print the raw gpg status output to standard error.",
  1583. action="store_true",
  1584. )
  1585. parser.add_argument(
  1586. "commits",
  1587. nargs="*",
  1588. default=["HEAD"],
  1589. help="Commits to verify (defaults to HEAD)",
  1590. )
  1591. parsed_args = parser.parse_args(args)
  1592. exit_code = None
  1593. for commit in parsed_args.commits:
  1594. try:
  1595. if parsed_args.verbose:
  1596. # Show commit contents before verification
  1597. porcelain.show(
  1598. ".",
  1599. objects=[commit],
  1600. outstream=sys.stdout,
  1601. )
  1602. porcelain.verify_commit(".", commit)
  1603. if not parsed_args.raw:
  1604. print(f"gpg: Good signature from commit '{commit}'")
  1605. except Exception as e:
  1606. if not parsed_args.raw:
  1607. print(f"error: {commit}: {e}", file=sys.stderr)
  1608. else:
  1609. # In raw mode, let the exception propagate
  1610. raise
  1611. exit_code = 1
  1612. return exit_code
  1613. class cmd_verify_tag(Command):
  1614. """Check the GPG signature of tags."""
  1615. def run(self, args: Sequence[str]) -> Optional[int]:
  1616. """Execute the verify-tag command.
  1617. Args:
  1618. args: Command line arguments
  1619. Returns:
  1620. Exit code (1 on error, None on success)
  1621. """
  1622. parser = argparse.ArgumentParser()
  1623. parser.add_argument(
  1624. "-v",
  1625. "--verbose",
  1626. help="Print the contents of the tag object before validating it.",
  1627. action="store_true",
  1628. )
  1629. parser.add_argument(
  1630. "--raw",
  1631. help="Print the raw gpg status output to standard error.",
  1632. action="store_true",
  1633. )
  1634. parser.add_argument("tags", nargs="+", help="Tags to verify")
  1635. parsed_args = parser.parse_args(args)
  1636. exit_code = None
  1637. for tag in parsed_args.tags:
  1638. try:
  1639. if parsed_args.verbose:
  1640. # Show tag contents before verification
  1641. porcelain.show(
  1642. ".",
  1643. objects=[tag],
  1644. outstream=sys.stdout,
  1645. )
  1646. porcelain.verify_tag(".", tag)
  1647. if not parsed_args.raw:
  1648. print(f"gpg: Good signature from tag '{tag}'")
  1649. except Exception as e:
  1650. if not parsed_args.raw:
  1651. print(f"error: {tag}: {e}", file=sys.stderr)
  1652. else:
  1653. # In raw mode, let the exception propagate
  1654. raise
  1655. exit_code = 1
  1656. return exit_code
  1657. class cmd_repack(Command):
  1658. """Pack unpacked objects in a repository."""
  1659. def run(self, args: Sequence[str]) -> None:
  1660. """Execute the repack command.
  1661. Args:
  1662. args: Command line arguments
  1663. """
  1664. parser = argparse.ArgumentParser()
  1665. parser.parse_args(args)
  1666. porcelain.repack(".")
  1667. class cmd_reflog(Command):
  1668. """Manage reflog information."""
  1669. def run(self, args: Sequence[str]) -> None:
  1670. """Execute the reflog command.
  1671. Args:
  1672. args: Command line arguments
  1673. """
  1674. parser = argparse.ArgumentParser()
  1675. parser.add_argument(
  1676. "ref", nargs="?", default="HEAD", help="Reference to show reflog for"
  1677. )
  1678. parser.add_argument(
  1679. "--all", action="store_true", help="Show reflogs for all refs"
  1680. )
  1681. parsed_args = parser.parse_args(args)
  1682. with Repo(".") as repo:
  1683. config = repo.get_config_stack()
  1684. with get_pager(config=config, cmd_name="reflog") as outstream:
  1685. if parsed_args.all:
  1686. # Show reflogs for all refs
  1687. for ref_bytes, entry in porcelain.reflog(repo, all=True):
  1688. ref_str = ref_bytes.decode("utf-8", "replace")
  1689. short_new = entry.new_sha[:8].decode("ascii")
  1690. outstream.write(
  1691. f"{short_new} {ref_str}: {entry.message.decode('utf-8', 'replace')}\n"
  1692. )
  1693. else:
  1694. ref = (
  1695. parsed_args.ref.encode("utf-8")
  1696. if isinstance(parsed_args.ref, str)
  1697. else parsed_args.ref
  1698. )
  1699. for i, entry in enumerate(porcelain.reflog(repo, ref)):
  1700. # Format similar to git reflog
  1701. from dulwich.reflog import Entry
  1702. assert isinstance(entry, Entry)
  1703. short_new = entry.new_sha[:8].decode("ascii")
  1704. message = (
  1705. entry.message.decode("utf-8", "replace")
  1706. if entry.message
  1707. else ""
  1708. )
  1709. outstream.write(
  1710. f"{short_new} {ref.decode('utf-8', 'replace')}@{{{i}}}: {message}\n"
  1711. )
  1712. class cmd_reset(Command):
  1713. """Reset current HEAD to the specified state."""
  1714. def run(self, args: Sequence[str]) -> None:
  1715. """Execute the reset command.
  1716. Args:
  1717. args: Command line arguments
  1718. """
  1719. parser = argparse.ArgumentParser()
  1720. mode_group = parser.add_mutually_exclusive_group()
  1721. mode_group.add_argument(
  1722. "--hard", action="store_true", help="Reset working tree and index"
  1723. )
  1724. mode_group.add_argument("--soft", action="store_true", help="Reset only HEAD")
  1725. mode_group.add_argument(
  1726. "--mixed", action="store_true", help="Reset HEAD and index"
  1727. )
  1728. parser.add_argument("treeish", nargs="?", help="Commit/tree to reset to")
  1729. parsed_args = parser.parse_args(args)
  1730. if parsed_args.hard:
  1731. mode = "hard"
  1732. elif parsed_args.soft:
  1733. mode = "soft"
  1734. elif parsed_args.mixed:
  1735. mode = "mixed"
  1736. else:
  1737. # Default to mixed behavior
  1738. mode = "mixed"
  1739. # Use the porcelain.reset function for all modes
  1740. porcelain.reset(".", mode=mode, treeish=parsed_args.treeish)
  1741. class cmd_revert(Command):
  1742. """Revert some existing commits."""
  1743. def run(self, args: Sequence[str]) -> None:
  1744. """Execute the revert command.
  1745. Args:
  1746. args: Command line arguments
  1747. """
  1748. parser = argparse.ArgumentParser()
  1749. parser.add_argument(
  1750. "--no-commit",
  1751. "-n",
  1752. action="store_true",
  1753. help="Apply changes but don't create a commit",
  1754. )
  1755. parser.add_argument("-m", "--message", help="Custom commit message")
  1756. parser.add_argument("commits", nargs="+", help="Commits to revert")
  1757. parsed_args = parser.parse_args(args)
  1758. result = porcelain.revert(
  1759. ".",
  1760. commits=parsed_args.commits,
  1761. no_commit=parsed_args.no_commit,
  1762. message=parsed_args.message,
  1763. )
  1764. if result and not parsed_args.no_commit:
  1765. logger.info("[%s] Revert completed", result.decode("ascii")[:7])
  1766. class cmd_daemon(Command):
  1767. """Run a simple Git protocol server."""
  1768. def run(self, args: Sequence[str]) -> None:
  1769. """Execute the daemon command.
  1770. Args:
  1771. args: Command line arguments
  1772. """
  1773. from dulwich import log_utils
  1774. from .protocol import TCP_GIT_PORT
  1775. parser = argparse.ArgumentParser()
  1776. parser.add_argument(
  1777. "-l",
  1778. "--listen_address",
  1779. default="localhost",
  1780. help="Binding IP address.",
  1781. )
  1782. parser.add_argument(
  1783. "-p",
  1784. "--port",
  1785. type=int,
  1786. default=TCP_GIT_PORT,
  1787. help="Binding TCP port.",
  1788. )
  1789. parser.add_argument(
  1790. "gitdir", nargs="?", default=".", help="Git directory to serve"
  1791. )
  1792. parsed_args = parser.parse_args(args)
  1793. log_utils.default_logging_config()
  1794. porcelain.daemon(
  1795. parsed_args.gitdir,
  1796. address=parsed_args.listen_address,
  1797. port=parsed_args.port,
  1798. )
  1799. class cmd_web_daemon(Command):
  1800. """Run a simple HTTP server for Git repositories."""
  1801. def run(self, args: Sequence[str]) -> None:
  1802. """Execute the web-daemon command.
  1803. Args:
  1804. args: Command line arguments
  1805. """
  1806. from dulwich import log_utils
  1807. parser = argparse.ArgumentParser()
  1808. parser.add_argument(
  1809. "-l",
  1810. "--listen_address",
  1811. default="",
  1812. help="Binding IP address.",
  1813. )
  1814. parser.add_argument(
  1815. "-p",
  1816. "--port",
  1817. type=int,
  1818. default=8000,
  1819. help="Binding TCP port.",
  1820. )
  1821. parser.add_argument(
  1822. "gitdir", nargs="?", default=".", help="Git directory to serve"
  1823. )
  1824. parsed_args = parser.parse_args(args)
  1825. log_utils.default_logging_config()
  1826. porcelain.web_daemon(
  1827. parsed_args.gitdir,
  1828. address=parsed_args.listen_address,
  1829. port=parsed_args.port,
  1830. )
  1831. class cmd_write_tree(Command):
  1832. """Create a tree object from the current index."""
  1833. def run(self, args: Sequence[str]) -> None:
  1834. """Execute the write-tree command.
  1835. Args:
  1836. args: Command line arguments
  1837. """
  1838. parser = argparse.ArgumentParser()
  1839. parser.parse_args(args)
  1840. sys.stdout.write("{}\n".format(porcelain.write_tree(".").decode()))
  1841. class cmd_receive_pack(Command):
  1842. """Receive what is pushed into the repository."""
  1843. def run(self, args: Sequence[str]) -> None:
  1844. """Execute the receive-pack command.
  1845. Args:
  1846. args: Command line arguments
  1847. """
  1848. parser = argparse.ArgumentParser()
  1849. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  1850. parsed_args = parser.parse_args(args)
  1851. porcelain.receive_pack(parsed_args.gitdir)
  1852. class cmd_upload_pack(Command):
  1853. """Send objects packed back to git-fetch-pack."""
  1854. def run(self, args: Sequence[str]) -> None:
  1855. """Execute the upload-pack command.
  1856. Args:
  1857. args: Command line arguments
  1858. """
  1859. parser = argparse.ArgumentParser()
  1860. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  1861. parsed_args = parser.parse_args(args)
  1862. porcelain.upload_pack(parsed_args.gitdir)
  1863. class cmd_shortlog(Command):
  1864. """Show a shortlog of commits by author."""
  1865. def run(self, args: Sequence[str]) -> None:
  1866. """Execute the shortlog command with the given CLI arguments.
  1867. Args:
  1868. args: List of command line arguments.
  1869. """
  1870. parser = argparse.ArgumentParser()
  1871. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  1872. parser.add_argument("--summary", action="store_true", help="Show summary only")
  1873. parser.add_argument(
  1874. "--sort", action="store_true", help="Sort authors by commit count"
  1875. )
  1876. parsed_args = parser.parse_args(args)
  1877. shortlog_items: list[dict[str, str]] = porcelain.shortlog(
  1878. repo=parsed_args.gitdir,
  1879. summary_only=parsed_args.summary,
  1880. sort_by_commits=parsed_args.sort,
  1881. )
  1882. for item in shortlog_items:
  1883. author: str = item["author"]
  1884. messages: str = item["messages"]
  1885. if parsed_args.summary:
  1886. count = len(messages.splitlines())
  1887. sys.stdout.write(f"{count}\t{author}\n")
  1888. else:
  1889. sys.stdout.write(f"{author} ({len(messages.splitlines())}):\n")
  1890. for msg in messages.splitlines():
  1891. sys.stdout.write(f" {msg}\n")
  1892. sys.stdout.write("\n")
  1893. class cmd_status(Command):
  1894. """Show the working tree status."""
  1895. def run(self, args: Sequence[str]) -> None:
  1896. """Execute the status command.
  1897. Args:
  1898. args: Command line arguments
  1899. """
  1900. parser = argparse.ArgumentParser()
  1901. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  1902. parsed_args = parser.parse_args(args)
  1903. status = porcelain.status(parsed_args.gitdir)
  1904. if any(names for (kind, names) in status.staged.items()):
  1905. sys.stdout.write("Changes to be committed:\n\n")
  1906. for kind, names in status.staged.items():
  1907. for name in names:
  1908. sys.stdout.write(
  1909. f"\t{kind}: {name.decode(sys.getfilesystemencoding())}\n"
  1910. )
  1911. sys.stdout.write("\n")
  1912. if status.unstaged:
  1913. sys.stdout.write("Changes not staged for commit:\n\n")
  1914. for name in status.unstaged:
  1915. sys.stdout.write(f"\t{name.decode(sys.getfilesystemencoding())}\n")
  1916. sys.stdout.write("\n")
  1917. if status.untracked:
  1918. sys.stdout.write("Untracked files:\n\n")
  1919. for name in status.untracked:
  1920. sys.stdout.write(f"\t{name}\n")
  1921. sys.stdout.write("\n")
  1922. class cmd_ls_remote(Command):
  1923. """List references in a remote repository."""
  1924. def run(self, args: Sequence[str]) -> None:
  1925. """Execute the ls-remote command.
  1926. Args:
  1927. args: Command line arguments
  1928. """
  1929. parser = argparse.ArgumentParser()
  1930. parser.add_argument(
  1931. "--symref", action="store_true", help="Show symbolic references"
  1932. )
  1933. parser.add_argument("url", help="Remote URL to list references from")
  1934. parsed_args = parser.parse_args(args)
  1935. result = porcelain.ls_remote(parsed_args.url)
  1936. if parsed_args.symref:
  1937. # Show symrefs first, like git does
  1938. for ref, target in sorted(result.symrefs.items()):
  1939. if target:
  1940. sys.stdout.write(f"ref: {target.decode()}\t{ref.decode()}\n")
  1941. # Show regular refs
  1942. for ref in sorted(result.refs):
  1943. sha = result.refs[ref]
  1944. if sha is not None:
  1945. sys.stdout.write(f"{sha.decode()}\t{ref.decode()}\n")
  1946. class cmd_ls_tree(Command):
  1947. """List the contents of a tree object."""
  1948. def run(self, args: Sequence[str]) -> None:
  1949. """Execute the ls-tree command.
  1950. Args:
  1951. args: Command line arguments
  1952. """
  1953. parser = argparse.ArgumentParser()
  1954. parser.add_argument(
  1955. "-r",
  1956. "--recursive",
  1957. action="store_true",
  1958. help="Recursively list tree contents.",
  1959. )
  1960. parser.add_argument(
  1961. "--name-only", action="store_true", help="Only display name."
  1962. )
  1963. parser.add_argument("treeish", nargs="?", help="Tree-ish to list")
  1964. parsed_args = parser.parse_args(args)
  1965. with Repo(".") as repo:
  1966. config = repo.get_config_stack()
  1967. with get_pager(config=config, cmd_name="ls-tree") as outstream:
  1968. porcelain.ls_tree(
  1969. repo,
  1970. parsed_args.treeish,
  1971. outstream=outstream,
  1972. recursive=parsed_args.recursive,
  1973. name_only=parsed_args.name_only,
  1974. )
  1975. class cmd_pack_objects(Command):
  1976. """Create a packed archive of objects."""
  1977. def run(self, args: Sequence[str]) -> None:
  1978. """Execute the pack-objects command.
  1979. Args:
  1980. args: Command line arguments
  1981. """
  1982. parser = argparse.ArgumentParser()
  1983. parser.add_argument(
  1984. "--stdout", action="store_true", help="Write pack to stdout"
  1985. )
  1986. parser.add_argument("--deltify", action="store_true", help="Create deltas")
  1987. parser.add_argument(
  1988. "--no-reuse-deltas", action="store_true", help="Don't reuse existing deltas"
  1989. )
  1990. parser.add_argument("basename", nargs="?", help="Base name for pack files")
  1991. parsed_args = parser.parse_args(args)
  1992. if not parsed_args.stdout and not parsed_args.basename:
  1993. parser.error("basename required when not using --stdout")
  1994. object_ids = [line.strip().encode() for line in sys.stdin.readlines()]
  1995. deltify = parsed_args.deltify
  1996. reuse_deltas = not parsed_args.no_reuse_deltas
  1997. if parsed_args.stdout:
  1998. packf = getattr(sys.stdout, "buffer", sys.stdout)
  1999. assert isinstance(packf, BinaryIO)
  2000. idxf = None
  2001. close = []
  2002. else:
  2003. packf = open(parsed_args.basename + ".pack", "wb")
  2004. idxf = open(parsed_args.basename + ".idx", "wb")
  2005. close = [packf, idxf]
  2006. porcelain.pack_objects(
  2007. ".", object_ids, packf, idxf, deltify=deltify, reuse_deltas=reuse_deltas
  2008. )
  2009. for f in close:
  2010. f.close()
  2011. class cmd_unpack_objects(Command):
  2012. """Unpack objects from a packed archive."""
  2013. def run(self, args: Sequence[str]) -> None:
  2014. """Execute the unpack-objects command.
  2015. Args:
  2016. args: Command line arguments
  2017. """
  2018. parser = argparse.ArgumentParser()
  2019. parser.add_argument("pack_file", help="Pack file to unpack")
  2020. parsed_args = parser.parse_args(args)
  2021. count = porcelain.unpack_objects(parsed_args.pack_file)
  2022. logger.info("Unpacked %d objects", count)
  2023. class cmd_prune(Command):
  2024. """Prune all unreachable objects from the object database."""
  2025. def run(self, args: Sequence[str]) -> Optional[int]:
  2026. """Execute the prune command.
  2027. Args:
  2028. args: Command line arguments
  2029. """
  2030. import datetime
  2031. import time
  2032. from dulwich.object_store import DEFAULT_TEMPFILE_GRACE_PERIOD
  2033. parser = argparse.ArgumentParser(
  2034. description="Remove temporary pack files left behind by interrupted operations"
  2035. )
  2036. parser.add_argument(
  2037. "--expire",
  2038. nargs="?",
  2039. const="2.weeks.ago",
  2040. help="Only prune files older than the specified date (default: 2.weeks.ago)",
  2041. )
  2042. parser.add_argument(
  2043. "--dry-run",
  2044. "-n",
  2045. action="store_true",
  2046. help="Only report what would be removed",
  2047. )
  2048. parser.add_argument(
  2049. "--verbose",
  2050. "-v",
  2051. action="store_true",
  2052. help="Report all actions",
  2053. )
  2054. parsed_args = parser.parse_args(args)
  2055. # Parse expire grace period
  2056. grace_period = DEFAULT_TEMPFILE_GRACE_PERIOD
  2057. if parsed_args.expire:
  2058. try:
  2059. grace_period = parse_relative_time(parsed_args.expire)
  2060. except ValueError:
  2061. # Try to parse as absolute date
  2062. try:
  2063. date = datetime.datetime.strptime(parsed_args.expire, "%Y-%m-%d")
  2064. grace_period = int(time.time() - date.timestamp())
  2065. except ValueError:
  2066. logger.error("Invalid expire date: %s", parsed_args.expire)
  2067. return 1
  2068. # Progress callback
  2069. def progress(msg: str) -> None:
  2070. if parsed_args.verbose:
  2071. logger.info("%s", msg)
  2072. try:
  2073. porcelain.prune(
  2074. ".",
  2075. grace_period=grace_period,
  2076. dry_run=parsed_args.dry_run,
  2077. progress=progress if parsed_args.verbose else None,
  2078. )
  2079. return None
  2080. except porcelain.Error as e:
  2081. logger.error("%s", e)
  2082. return 1
  2083. class cmd_pull(Command):
  2084. """Fetch from and integrate with another repository or a local branch."""
  2085. def run(self, args: Sequence[str]) -> None:
  2086. """Execute the pull command.
  2087. Args:
  2088. args: Command line arguments
  2089. """
  2090. parser = argparse.ArgumentParser()
  2091. parser.add_argument("from_location", type=str)
  2092. parser.add_argument("refspec", type=str, nargs="*")
  2093. parser.add_argument("--filter", type=str, nargs=1)
  2094. parser.add_argument("--protocol", type=int)
  2095. parsed_args = parser.parse_args(args)
  2096. porcelain.pull(
  2097. ".",
  2098. remote_location=parsed_args.from_location or None,
  2099. refspecs=parsed_args.refspec or None,
  2100. filter_spec=parsed_args.filter,
  2101. protocol_version=parsed_args.protocol or None,
  2102. )
  2103. class cmd_push(Command):
  2104. """Update remote refs along with associated objects."""
  2105. def run(self, argv: Sequence[str]) -> Optional[int]:
  2106. """Execute the push command.
  2107. Args:
  2108. argv: Command line arguments
  2109. """
  2110. parser = argparse.ArgumentParser()
  2111. parser.add_argument("-f", "--force", action="store_true", help="Force")
  2112. parser.add_argument("to_location", type=str)
  2113. parser.add_argument("refspec", type=str, nargs="*")
  2114. args = parser.parse_args(argv)
  2115. try:
  2116. porcelain.push(
  2117. ".", args.to_location, args.refspec or None, force=args.force
  2118. )
  2119. except porcelain.DivergedBranches:
  2120. sys.stderr.write("Diverged branches; specify --force to override")
  2121. return 1
  2122. return None
  2123. class cmd_remote_add(Command):
  2124. """Add a remote repository."""
  2125. def run(self, args: Sequence[str]) -> None:
  2126. """Execute the remote-add command.
  2127. Args:
  2128. args: Command line arguments
  2129. """
  2130. parser = argparse.ArgumentParser()
  2131. parser.add_argument("name", help="Name of the remote")
  2132. parser.add_argument("url", help="URL of the remote")
  2133. parsed_args = parser.parse_args(args)
  2134. porcelain.remote_add(".", parsed_args.name, parsed_args.url)
  2135. class SuperCommand(Command):
  2136. """Base class for commands that have subcommands."""
  2137. subcommands: ClassVar[dict[str, type[Command]]] = {}
  2138. default_command: ClassVar[Optional[type[Command]]] = None
  2139. def run(self, args: Sequence[str]) -> Optional[int]:
  2140. """Execute the subcommand command.
  2141. Args:
  2142. args: Command line arguments
  2143. """
  2144. if not args:
  2145. if self.default_command:
  2146. return self.default_command().run(args)
  2147. else:
  2148. logger.info(
  2149. "Supported subcommands: %s", ", ".join(self.subcommands.keys())
  2150. )
  2151. return False
  2152. cmd = args[0]
  2153. try:
  2154. cmd_kls = self.subcommands[cmd]
  2155. except KeyError:
  2156. logger.error("No such subcommand: %s", args[0])
  2157. sys.exit(1)
  2158. return cmd_kls().run(args[1:])
  2159. class cmd_remote(SuperCommand):
  2160. """Manage set of tracked repositories."""
  2161. subcommands: ClassVar[dict[str, type[Command]]] = {
  2162. "add": cmd_remote_add,
  2163. }
  2164. class cmd_submodule_list(Command):
  2165. """List submodules."""
  2166. def run(self, argv: Sequence[str]) -> None:
  2167. """Execute the submodule-list command.
  2168. Args:
  2169. argv: Command line arguments
  2170. """
  2171. parser = argparse.ArgumentParser()
  2172. parser.parse_args(argv)
  2173. for path, sha in porcelain.submodule_list("."):
  2174. sys.stdout.write(f" {sha} {path}\n")
  2175. class cmd_submodule_init(Command):
  2176. """Initialize submodules."""
  2177. def run(self, argv: Sequence[str]) -> None:
  2178. """Execute the submodule-init command.
  2179. Args:
  2180. argv: Command line arguments
  2181. """
  2182. parser = argparse.ArgumentParser()
  2183. parser.parse_args(argv)
  2184. porcelain.submodule_init(".")
  2185. class cmd_submodule_add(Command):
  2186. """Add a submodule."""
  2187. def run(self, argv: Sequence[str]) -> None:
  2188. """Execute the submodule-add command.
  2189. Args:
  2190. argv: Command line arguments
  2191. """
  2192. parser = argparse.ArgumentParser()
  2193. parser.add_argument("url", help="URL of repository to add as submodule")
  2194. parser.add_argument("path", nargs="?", help="Path where submodule should live")
  2195. parser.add_argument("--name", help="Name for the submodule")
  2196. args = parser.parse_args(argv)
  2197. porcelain.submodule_add(".", args.url, args.path, args.name)
  2198. class cmd_submodule_update(Command):
  2199. """Update submodules."""
  2200. def run(self, argv: Sequence[str]) -> None:
  2201. """Execute the submodule-update command.
  2202. Args:
  2203. argv: Command line arguments
  2204. """
  2205. parser = argparse.ArgumentParser()
  2206. parser.add_argument(
  2207. "--init", action="store_true", help="Initialize submodules first"
  2208. )
  2209. parser.add_argument(
  2210. "--force",
  2211. action="store_true",
  2212. help="Force update even if local changes exist",
  2213. )
  2214. parser.add_argument(
  2215. "paths", nargs="*", help="Specific submodule paths to update"
  2216. )
  2217. args = parser.parse_args(argv)
  2218. paths = args.paths if args.paths else None
  2219. porcelain.submodule_update(".", paths=paths, init=args.init, force=args.force)
  2220. class cmd_submodule(SuperCommand):
  2221. """Initialize, update or inspect submodules."""
  2222. subcommands: ClassVar[dict[str, type[Command]]] = {
  2223. "add": cmd_submodule_add,
  2224. "init": cmd_submodule_init,
  2225. "list": cmd_submodule_list,
  2226. "update": cmd_submodule_update,
  2227. }
  2228. default_command = cmd_submodule_list
  2229. class cmd_check_ignore(Command):
  2230. """Check whether files are excluded by gitignore."""
  2231. def run(self, args: Sequence[str]) -> int:
  2232. """Execute the check-ignore command.
  2233. Args:
  2234. args: Command line arguments
  2235. """
  2236. parser = argparse.ArgumentParser()
  2237. parser.add_argument("paths", nargs="+", help="Paths to check")
  2238. parsed_args = parser.parse_args(args)
  2239. ret = 1
  2240. for path in porcelain.check_ignore(".", parsed_args.paths):
  2241. logger.info(path)
  2242. ret = 0
  2243. return ret
  2244. class cmd_check_mailmap(Command):
  2245. """Show canonical names and email addresses of contacts."""
  2246. def run(self, args: Sequence[str]) -> None:
  2247. """Execute the check-mailmap command.
  2248. Args:
  2249. args: Command line arguments
  2250. """
  2251. parser = argparse.ArgumentParser()
  2252. parser.add_argument("identities", nargs="+", help="Identities to check")
  2253. parsed_args = parser.parse_args(args)
  2254. for identity in parsed_args.identities:
  2255. canonical_identity = porcelain.check_mailmap(".", identity)
  2256. logger.info(canonical_identity)
  2257. class cmd_branch(Command):
  2258. """List, create, or delete branches."""
  2259. def run(self, args: Sequence[str]) -> Optional[int]:
  2260. """Execute the branch command.
  2261. Args:
  2262. args: Command line arguments
  2263. """
  2264. parser = argparse.ArgumentParser()
  2265. parser.add_argument(
  2266. "branch",
  2267. type=str,
  2268. nargs="?",
  2269. help="Name of the branch",
  2270. )
  2271. parser.add_argument(
  2272. "-d",
  2273. "--delete",
  2274. action="store_true",
  2275. help="Delete branch",
  2276. )
  2277. parser.add_argument("--all", action="store_true", help="List all branches")
  2278. parser.add_argument(
  2279. "--merged", action="store_true", help="List merged into current branch"
  2280. )
  2281. parser.add_argument(
  2282. "--no-merged",
  2283. action="store_true",
  2284. help="List branches not merged into current branch",
  2285. )
  2286. parser.add_argument(
  2287. "--remotes", action="store_true", help="List remotes branches"
  2288. )
  2289. parser.add_argument(
  2290. "--contains",
  2291. nargs="?",
  2292. const="HEAD",
  2293. help="List branches that contain a specific commit",
  2294. )
  2295. parser.add_argument(
  2296. "--column", action="store_true", help="Display branch list in columns"
  2297. )
  2298. parser.add_argument(
  2299. "--list",
  2300. nargs="?",
  2301. const=None,
  2302. help="List branches matching a pattern",
  2303. )
  2304. parsed_args = parser.parse_args(args)
  2305. def print_branches(
  2306. branches: Union[Iterator[bytes], Sequence[bytes]], use_columns: bool = False
  2307. ) -> None:
  2308. if use_columns:
  2309. write_columns(branches, sys.stdout)
  2310. else:
  2311. for branch in branches:
  2312. sys.stdout.write(f"{branch.decode()}\n")
  2313. branches: Union[Iterator[bytes], list[bytes], None] = None
  2314. try:
  2315. if parsed_args.all:
  2316. branches = porcelain.branch_list(".") + porcelain.branch_remotes_list(
  2317. "."
  2318. )
  2319. elif parsed_args.remotes:
  2320. branches = porcelain.branch_remotes_list(".")
  2321. elif parsed_args.merged:
  2322. branches = porcelain.merged_branches(".")
  2323. elif parsed_args.no_merged:
  2324. branches = porcelain.no_merged_branches(".")
  2325. elif parsed_args.contains:
  2326. try:
  2327. branches = list(
  2328. porcelain.branches_containing(".", commit=parsed_args.contains)
  2329. )
  2330. except KeyError as e:
  2331. sys.stderr.write(
  2332. f"error: object name {e.args[0].decode()} not found\n"
  2333. )
  2334. return 1
  2335. except porcelain.Error as e:
  2336. sys.stderr.write(f"{e}")
  2337. return 1
  2338. pattern = parsed_args.list
  2339. if pattern is not None and branches:
  2340. branches = porcelain.filter_branches_by_pattern(branches, pattern)
  2341. if branches is not None:
  2342. print_branches(branches, parsed_args.column)
  2343. return 0
  2344. if not parsed_args.branch:
  2345. logger.error("Usage: dulwich branch [-d] BRANCH_NAME")
  2346. return 1
  2347. if parsed_args.delete:
  2348. porcelain.branch_delete(".", name=parsed_args.branch)
  2349. else:
  2350. try:
  2351. porcelain.branch_create(".", name=parsed_args.branch)
  2352. except porcelain.Error as e:
  2353. sys.stderr.write(f"{e}")
  2354. return 1
  2355. return 0
  2356. class cmd_checkout(Command):
  2357. """Switch branches or restore working tree files."""
  2358. def run(self, args: Sequence[str]) -> Optional[int]:
  2359. """Execute the checkout command.
  2360. Args:
  2361. args: Command line arguments
  2362. """
  2363. parser = argparse.ArgumentParser()
  2364. parser.add_argument(
  2365. "target",
  2366. type=str,
  2367. help="Name of the branch, tag, or commit to checkout",
  2368. )
  2369. parser.add_argument(
  2370. "-f",
  2371. "--force",
  2372. action="store_true",
  2373. help="Force checkout",
  2374. )
  2375. parser.add_argument(
  2376. "-b",
  2377. "--new-branch",
  2378. type=str,
  2379. help="Create a new branch at the target and switch to it",
  2380. )
  2381. parsed_args = parser.parse_args(args)
  2382. if not parsed_args.target:
  2383. logger.error("Usage: dulwich checkout TARGET [--force] [-b NEW_BRANCH]")
  2384. return 1
  2385. try:
  2386. porcelain.checkout(
  2387. ".",
  2388. target=parsed_args.target,
  2389. force=parsed_args.force,
  2390. new_branch=parsed_args.new_branch,
  2391. )
  2392. except porcelain.CheckoutError as e:
  2393. sys.stderr.write(f"{e}\n")
  2394. return 1
  2395. return 0
  2396. class cmd_stash_list(Command):
  2397. """List stash entries."""
  2398. def run(self, args: Sequence[str]) -> None:
  2399. """Execute the stash-list command.
  2400. Args:
  2401. args: Command line arguments
  2402. """
  2403. parser = argparse.ArgumentParser()
  2404. parser.parse_args(args)
  2405. from .repo import Repo
  2406. from .stash import Stash
  2407. with Repo(".") as r:
  2408. stash = Stash.from_repo(r)
  2409. for i, entry in enumerate(stash.stashes()):
  2410. logger.info(
  2411. "stash@{%d}: %s",
  2412. i,
  2413. entry.message.decode("utf-8", "replace").rstrip("\n"),
  2414. )
  2415. class cmd_stash_push(Command):
  2416. """Save your local modifications to a new stash."""
  2417. def run(self, args: Sequence[str]) -> None:
  2418. """Execute the stash-push command.
  2419. Args:
  2420. args: Command line arguments
  2421. """
  2422. parser = argparse.ArgumentParser()
  2423. parser.parse_args(args)
  2424. porcelain.stash_push(".")
  2425. logger.info("Saved working directory and index state")
  2426. class cmd_stash_pop(Command):
  2427. """Apply a stash and remove it from the stash list."""
  2428. def run(self, args: Sequence[str]) -> None:
  2429. """Execute the stash-pop command.
  2430. Args:
  2431. args: Command line arguments
  2432. """
  2433. parser = argparse.ArgumentParser()
  2434. parser.parse_args(args)
  2435. porcelain.stash_pop(".")
  2436. logger.info("Restored working directory and index state")
  2437. class cmd_bisect(SuperCommand):
  2438. """Use binary search to find the commit that introduced a bug."""
  2439. subcommands: ClassVar[dict[str, type[Command]]] = {}
  2440. def run(self, args: Sequence[str]) -> Optional[int]:
  2441. """Execute the bisect command.
  2442. Args:
  2443. args: Command line arguments
  2444. """
  2445. parser = argparse.ArgumentParser(prog="dulwich bisect")
  2446. subparsers = parser.add_subparsers(dest="subcommand", help="bisect subcommands")
  2447. # bisect start
  2448. start_parser = subparsers.add_parser("start", help="Start a new bisect session")
  2449. start_parser.add_argument("bad", nargs="?", help="Bad commit")
  2450. start_parser.add_argument("good", nargs="*", help="Good commit(s)")
  2451. start_parser.add_argument(
  2452. "--no-checkout",
  2453. action="store_true",
  2454. help="Don't checkout commits during bisect",
  2455. )
  2456. start_parser.add_argument(
  2457. "--term-bad", default="bad", help="Term to use for bad commits"
  2458. )
  2459. start_parser.add_argument(
  2460. "--term-good", default="good", help="Term to use for good commits"
  2461. )
  2462. start_parser.add_argument(
  2463. "--", dest="paths", nargs="*", help="Paths to limit bisect to"
  2464. )
  2465. # bisect bad
  2466. bad_parser = subparsers.add_parser("bad", help="Mark a commit as bad")
  2467. bad_parser.add_argument("rev", nargs="?", help="Commit to mark as bad")
  2468. # bisect good
  2469. good_parser = subparsers.add_parser("good", help="Mark a commit as good")
  2470. good_parser.add_argument("rev", nargs="?", help="Commit to mark as good")
  2471. # bisect skip
  2472. skip_parser = subparsers.add_parser("skip", help="Skip commits")
  2473. skip_parser.add_argument("revs", nargs="*", help="Commits to skip")
  2474. # bisect reset
  2475. reset_parser = subparsers.add_parser("reset", help="Reset bisect state")
  2476. reset_parser.add_argument("commit", nargs="?", help="Commit to reset to")
  2477. # bisect log
  2478. subparsers.add_parser("log", help="Show bisect log")
  2479. # bisect replay
  2480. replay_parser = subparsers.add_parser("replay", help="Replay bisect log")
  2481. replay_parser.add_argument("logfile", help="Log file to replay")
  2482. # bisect help
  2483. subparsers.add_parser("help", help="Show help")
  2484. parsed_args = parser.parse_args(args)
  2485. if not parsed_args.subcommand:
  2486. parser.print_help()
  2487. return 1
  2488. try:
  2489. if parsed_args.subcommand == "start":
  2490. next_sha = porcelain.bisect_start(
  2491. bad=parsed_args.bad,
  2492. good=parsed_args.good if parsed_args.good else None,
  2493. paths=parsed_args.paths,
  2494. no_checkout=parsed_args.no_checkout,
  2495. term_bad=parsed_args.term_bad,
  2496. term_good=parsed_args.term_good,
  2497. )
  2498. if next_sha:
  2499. logger.info(
  2500. "Bisecting: checking out '%s'", next_sha.decode("ascii")
  2501. )
  2502. elif parsed_args.subcommand == "bad":
  2503. next_sha = porcelain.bisect_bad(rev=parsed_args.rev)
  2504. if next_sha:
  2505. logger.info(
  2506. "Bisecting: checking out '%s'", next_sha.decode("ascii")
  2507. )
  2508. else:
  2509. # Bisect complete - find the first bad commit
  2510. with porcelain.open_repo_closing(".") as r:
  2511. bad_ref = os.path.join(r.controldir(), "refs", "bisect", "bad")
  2512. with open(bad_ref, "rb") as f:
  2513. bad_sha = f.read().strip()
  2514. commit = r.object_store[bad_sha]
  2515. assert isinstance(commit, Commit)
  2516. message = commit.message.decode(
  2517. "utf-8", errors="replace"
  2518. ).split("\n")[0]
  2519. logger.info(
  2520. "%s is the first bad commit", bad_sha.decode("ascii")
  2521. )
  2522. logger.info("commit %s", bad_sha.decode("ascii"))
  2523. logger.info(" %s", message)
  2524. elif parsed_args.subcommand == "good":
  2525. next_sha = porcelain.bisect_good(rev=parsed_args.rev)
  2526. if next_sha:
  2527. logger.info(
  2528. "Bisecting: checking out '%s'", next_sha.decode("ascii")
  2529. )
  2530. elif parsed_args.subcommand == "skip":
  2531. next_sha = porcelain.bisect_skip(
  2532. revs=parsed_args.revs if parsed_args.revs else None
  2533. )
  2534. if next_sha:
  2535. logger.info(
  2536. "Bisecting: checking out '%s'", next_sha.decode("ascii")
  2537. )
  2538. elif parsed_args.subcommand == "reset":
  2539. porcelain.bisect_reset(commit=parsed_args.commit)
  2540. logger.info("Bisect reset")
  2541. elif parsed_args.subcommand == "log":
  2542. log = porcelain.bisect_log()
  2543. logger.info(log.rstrip())
  2544. elif parsed_args.subcommand == "replay":
  2545. porcelain.bisect_replay(".", log_file=parsed_args.logfile)
  2546. logger.info("Replayed bisect log from %s", parsed_args.logfile)
  2547. elif parsed_args.subcommand == "help":
  2548. parser.print_help()
  2549. except porcelain.Error as e:
  2550. logger.error("%s", e)
  2551. return 1
  2552. except ValueError as e:
  2553. logger.error("%s", e)
  2554. return 1
  2555. return 0
  2556. class cmd_stash(SuperCommand):
  2557. """Stash the changes in a dirty working directory away."""
  2558. subcommands: ClassVar[dict[str, type[Command]]] = {
  2559. "list": cmd_stash_list,
  2560. "pop": cmd_stash_pop,
  2561. "push": cmd_stash_push,
  2562. }
  2563. class cmd_ls_files(Command):
  2564. """Show information about files in the index and working tree."""
  2565. def run(self, args: Sequence[str]) -> None:
  2566. """Execute the ls-files command.
  2567. Args:
  2568. args: Command line arguments
  2569. """
  2570. parser = argparse.ArgumentParser()
  2571. parser.parse_args(args)
  2572. for name in porcelain.ls_files("."):
  2573. logger.info(name)
  2574. class cmd_describe(Command):
  2575. """Give an object a human readable name based on an available ref."""
  2576. def run(self, args: Sequence[str]) -> None:
  2577. """Execute the describe command.
  2578. Args:
  2579. args: Command line arguments
  2580. """
  2581. parser = argparse.ArgumentParser()
  2582. parser.parse_args(args)
  2583. logger.info(porcelain.describe("."))
  2584. class cmd_merge(Command):
  2585. """Join two or more development histories together."""
  2586. def run(self, args: Sequence[str]) -> Optional[int]:
  2587. """Execute the merge command.
  2588. Args:
  2589. args: Command line arguments
  2590. """
  2591. parser = argparse.ArgumentParser()
  2592. parser.add_argument("commit", type=str, help="Commit to merge")
  2593. parser.add_argument(
  2594. "--no-commit", action="store_true", help="Do not create a merge commit"
  2595. )
  2596. parser.add_argument(
  2597. "--no-ff", action="store_true", help="Force create a merge commit"
  2598. )
  2599. parser.add_argument("-m", "--message", type=str, help="Merge commit message")
  2600. parsed_args = parser.parse_args(args)
  2601. try:
  2602. merge_commit_id, conflicts = porcelain.merge(
  2603. ".",
  2604. parsed_args.commit,
  2605. no_commit=parsed_args.no_commit,
  2606. no_ff=parsed_args.no_ff,
  2607. message=parsed_args.message,
  2608. )
  2609. if conflicts:
  2610. logger.warning("Merge conflicts in %d file(s):", len(conflicts))
  2611. for conflict_path in conflicts:
  2612. logger.warning(" %s", conflict_path.decode())
  2613. logger.error(
  2614. "Automatic merge failed; fix conflicts and then commit the result."
  2615. )
  2616. return 1
  2617. elif merge_commit_id is None and not parsed_args.no_commit:
  2618. logger.info("Already up to date.")
  2619. elif parsed_args.no_commit:
  2620. logger.info("Automatic merge successful; not committing as requested.")
  2621. else:
  2622. assert merge_commit_id is not None
  2623. logger.info(
  2624. "Merge successful. Created merge commit %s",
  2625. merge_commit_id.decode(),
  2626. )
  2627. return 0
  2628. except porcelain.Error as e:
  2629. logger.error("%s", e)
  2630. return 1
  2631. class cmd_merge_base(Command):
  2632. """Find the best common ancestor between commits."""
  2633. def run(self, args: Sequence[str]) -> Optional[int]:
  2634. """Execute the merge-base command.
  2635. Args:
  2636. args: Command line arguments
  2637. """
  2638. parser = argparse.ArgumentParser(
  2639. description="Find the best common ancestor between commits",
  2640. prog="dulwich merge-base",
  2641. )
  2642. parser.add_argument("commits", nargs="+", help="Commits to find merge base for")
  2643. parser.add_argument("--all", action="store_true", help="Output all merge bases")
  2644. parser.add_argument(
  2645. "--octopus",
  2646. action="store_true",
  2647. help="Compute common ancestor of all commits",
  2648. )
  2649. parser.add_argument(
  2650. "--is-ancestor",
  2651. action="store_true",
  2652. help="Check if first commit is ancestor of second",
  2653. )
  2654. parser.add_argument(
  2655. "--independent",
  2656. action="store_true",
  2657. help="List commits not reachable from others",
  2658. )
  2659. parsed_args = parser.parse_args(args)
  2660. try:
  2661. if parsed_args.is_ancestor:
  2662. if len(parsed_args.commits) != 2:
  2663. logger.error("--is-ancestor requires exactly two commits")
  2664. return 1
  2665. is_anc = porcelain.is_ancestor(
  2666. ".",
  2667. ancestor=parsed_args.commits[0],
  2668. descendant=parsed_args.commits[1],
  2669. )
  2670. return 0 if is_anc else 1
  2671. elif parsed_args.independent:
  2672. commits = porcelain.independent_commits(".", parsed_args.commits)
  2673. for commit_id in commits:
  2674. print(commit_id.decode())
  2675. return 0
  2676. else:
  2677. if len(parsed_args.commits) < 2:
  2678. logger.error("At least two commits are required")
  2679. return 1
  2680. merge_bases = porcelain.merge_base(
  2681. ".",
  2682. parsed_args.commits,
  2683. all=parsed_args.all,
  2684. octopus=parsed_args.octopus,
  2685. )
  2686. for commit_id in merge_bases:
  2687. print(commit_id.decode())
  2688. return 0
  2689. except (ValueError, KeyError) as e:
  2690. logger.error("%s", e)
  2691. return 1
  2692. class cmd_notes_add(Command):
  2693. """Add notes to a commit."""
  2694. def run(self, args: Sequence[str]) -> None:
  2695. """Execute the notes-add command.
  2696. Args:
  2697. args: Command line arguments
  2698. """
  2699. parser = argparse.ArgumentParser()
  2700. parser.add_argument("object", help="Object to annotate")
  2701. parser.add_argument("-m", "--message", help="Note message", required=True)
  2702. parser.add_argument(
  2703. "--ref", default="commits", help="Notes ref (default: commits)"
  2704. )
  2705. parsed_args = parser.parse_args(args)
  2706. porcelain.notes_add(
  2707. ".", parsed_args.object, parsed_args.message, ref=parsed_args.ref
  2708. )
  2709. class cmd_notes_show(Command):
  2710. """Show notes for a commit."""
  2711. def run(self, args: Sequence[str]) -> None:
  2712. """Execute the notes-show command.
  2713. Args:
  2714. args: Command line arguments
  2715. """
  2716. parser = argparse.ArgumentParser()
  2717. parser.add_argument("object", help="Object to show notes for")
  2718. parser.add_argument(
  2719. "--ref", default="commits", help="Notes ref (default: commits)"
  2720. )
  2721. parsed_args = parser.parse_args(args)
  2722. note = porcelain.notes_show(".", parsed_args.object, ref=parsed_args.ref)
  2723. if note:
  2724. sys.stdout.buffer.write(note)
  2725. else:
  2726. logger.info("No notes found for object %s", parsed_args.object)
  2727. class cmd_notes_remove(Command):
  2728. """Remove notes for a commit."""
  2729. def run(self, args: Sequence[str]) -> None:
  2730. """Execute the notes-remove command.
  2731. Args:
  2732. args: Command line arguments
  2733. """
  2734. parser = argparse.ArgumentParser()
  2735. parser.add_argument("object", help="Object to remove notes from")
  2736. parser.add_argument(
  2737. "--ref", default="commits", help="Notes ref (default: commits)"
  2738. )
  2739. parsed_args = parser.parse_args(args)
  2740. result = porcelain.notes_remove(".", parsed_args.object, ref=parsed_args.ref)
  2741. if result:
  2742. logger.info("Removed notes for object %s", parsed_args.object)
  2743. else:
  2744. logger.info("No notes found for object %s", parsed_args.object)
  2745. class cmd_notes_list(Command):
  2746. """List all note objects."""
  2747. def run(self, args: Sequence[str]) -> None:
  2748. """Execute the notes-list command.
  2749. Args:
  2750. args: Command line arguments
  2751. """
  2752. parser = argparse.ArgumentParser()
  2753. parser.add_argument(
  2754. "--ref", default="commits", help="Notes ref (default: commits)"
  2755. )
  2756. parsed_args = parser.parse_args(args)
  2757. notes = porcelain.notes_list(".", ref=parsed_args.ref)
  2758. for object_sha, note_content in notes:
  2759. logger.info(object_sha.hex())
  2760. class cmd_notes(SuperCommand):
  2761. """Add or inspect object notes."""
  2762. subcommands: ClassVar[dict[str, type[Command]]] = {
  2763. "add": cmd_notes_add,
  2764. "show": cmd_notes_show,
  2765. "remove": cmd_notes_remove,
  2766. "list": cmd_notes_list,
  2767. }
  2768. default_command = cmd_notes_list
  2769. class cmd_cherry_pick(Command):
  2770. """Apply the changes introduced by some existing commits."""
  2771. def run(self, args: Sequence[str]) -> Optional[int]:
  2772. """Execute the cherry-pick command.
  2773. Args:
  2774. args: Command line arguments
  2775. """
  2776. parser = argparse.ArgumentParser(
  2777. description="Apply the changes introduced by some existing commits"
  2778. )
  2779. parser.add_argument("commit", nargs="?", help="Commit to cherry-pick")
  2780. parser.add_argument(
  2781. "-n",
  2782. "--no-commit",
  2783. action="store_true",
  2784. help="Apply changes without making a commit",
  2785. )
  2786. parser.add_argument(
  2787. "--continue",
  2788. dest="continue_",
  2789. action="store_true",
  2790. help="Continue after resolving conflicts",
  2791. )
  2792. parser.add_argument(
  2793. "--abort",
  2794. action="store_true",
  2795. help="Abort the current cherry-pick operation",
  2796. )
  2797. parsed_args = parser.parse_args(args)
  2798. # Check argument validity
  2799. if parsed_args.continue_ or parsed_args.abort:
  2800. if parsed_args.commit is not None:
  2801. parser.error("Cannot specify commit with --continue or --abort")
  2802. return 1
  2803. else:
  2804. if parsed_args.commit is None:
  2805. parser.error("Commit argument is required")
  2806. return 1
  2807. try:
  2808. commit_arg = parsed_args.commit
  2809. result = porcelain.cherry_pick(
  2810. ".",
  2811. commit_arg,
  2812. no_commit=parsed_args.no_commit,
  2813. continue_=parsed_args.continue_,
  2814. abort=parsed_args.abort,
  2815. )
  2816. if parsed_args.abort:
  2817. logger.info("Cherry-pick aborted.")
  2818. elif parsed_args.continue_:
  2819. if result:
  2820. logger.info("Cherry-pick completed: %s", result.decode())
  2821. else:
  2822. logger.info("Cherry-pick completed.")
  2823. elif result is None:
  2824. if parsed_args.no_commit:
  2825. logger.info("Cherry-pick applied successfully (no commit created).")
  2826. else:
  2827. # This shouldn't happen unless there were conflicts
  2828. logger.warning("Cherry-pick resulted in conflicts.")
  2829. else:
  2830. logger.info("Cherry-pick successful: %s", result.decode())
  2831. return None
  2832. except porcelain.Error as e:
  2833. logger.error("%s", e)
  2834. return 1
  2835. class cmd_merge_tree(Command):
  2836. """Show three-way merge without touching index."""
  2837. def run(self, args: Sequence[str]) -> Optional[int]:
  2838. """Execute the merge-tree command.
  2839. Args:
  2840. args: Command line arguments
  2841. """
  2842. parser = argparse.ArgumentParser(
  2843. description="Perform a tree-level merge without touching the working directory"
  2844. )
  2845. parser.add_argument(
  2846. "base_tree",
  2847. nargs="?",
  2848. help="The common ancestor tree (optional, defaults to empty tree)",
  2849. )
  2850. parser.add_argument("our_tree", help="Our side of the merge")
  2851. parser.add_argument("their_tree", help="Their side of the merge")
  2852. parser.add_argument(
  2853. "-z",
  2854. "--name-only",
  2855. action="store_true",
  2856. help="Output only conflict paths, null-terminated",
  2857. )
  2858. parsed_args = parser.parse_args(args)
  2859. try:
  2860. # Determine base tree - if only two parsed_args provided, base is None
  2861. if parsed_args.base_tree is None:
  2862. # Only two arguments provided
  2863. base_tree = None
  2864. our_tree = parsed_args.our_tree
  2865. their_tree = parsed_args.their_tree
  2866. else:
  2867. # Three arguments provided
  2868. base_tree = parsed_args.base_tree
  2869. our_tree = parsed_args.our_tree
  2870. their_tree = parsed_args.their_tree
  2871. merged_tree_id, conflicts = porcelain.merge_tree(
  2872. ".", base_tree, our_tree, their_tree
  2873. )
  2874. if parsed_args.name_only:
  2875. # Output only conflict paths, null-terminated
  2876. for conflict_path in conflicts:
  2877. sys.stdout.buffer.write(conflict_path)
  2878. sys.stdout.buffer.write(b"\0")
  2879. else:
  2880. # Output the merged tree SHA
  2881. logger.info(merged_tree_id.decode("ascii"))
  2882. # Output conflict information
  2883. if conflicts:
  2884. logger.warning("\nConflicts in %d file(s):", len(conflicts))
  2885. for conflict_path in conflicts:
  2886. logger.warning(" %s", conflict_path.decode())
  2887. return None
  2888. except porcelain.Error as e:
  2889. logger.error("%s", e)
  2890. return 1
  2891. except KeyError as e:
  2892. logger.error("Object not found: %s", e)
  2893. return 1
  2894. class cmd_gc(Command):
  2895. """Cleanup unnecessary files and optimize the local repository."""
  2896. def run(self, args: Sequence[str]) -> Optional[int]:
  2897. """Execute the gc command.
  2898. Args:
  2899. args: Command line arguments
  2900. """
  2901. import datetime
  2902. import time
  2903. parser = argparse.ArgumentParser()
  2904. parser.add_argument(
  2905. "--auto",
  2906. action="store_true",
  2907. help="Only run gc if needed",
  2908. )
  2909. parser.add_argument(
  2910. "--aggressive",
  2911. action="store_true",
  2912. help="Use more aggressive settings",
  2913. )
  2914. parser.add_argument(
  2915. "--no-prune",
  2916. action="store_true",
  2917. help="Do not prune unreachable objects",
  2918. )
  2919. parser.add_argument(
  2920. "--prune",
  2921. nargs="?",
  2922. const="now",
  2923. help="Prune unreachable objects older than date (default: 2 weeks ago)",
  2924. )
  2925. parser.add_argument(
  2926. "--dry-run",
  2927. "-n",
  2928. action="store_true",
  2929. help="Only report what would be done",
  2930. )
  2931. parser.add_argument(
  2932. "--quiet",
  2933. "-q",
  2934. action="store_true",
  2935. help="Only report errors",
  2936. )
  2937. parsed_args = parser.parse_args(args)
  2938. # Parse prune grace period
  2939. grace_period = None
  2940. if parsed_args.prune:
  2941. try:
  2942. grace_period = parse_relative_time(parsed_args.prune)
  2943. except ValueError:
  2944. # Try to parse as absolute date
  2945. try:
  2946. date = datetime.datetime.strptime(parsed_args.prune, "%Y-%m-%d")
  2947. grace_period = int(time.time() - date.timestamp())
  2948. except ValueError:
  2949. logger.error("Invalid prune date: %s", parsed_args.prune)
  2950. return 1
  2951. elif not parsed_args.no_prune:
  2952. # Default to 2 weeks
  2953. grace_period = 1209600
  2954. # Progress callback
  2955. def progress(msg: str) -> None:
  2956. if not parsed_args.quiet:
  2957. logger.info(msg)
  2958. try:
  2959. stats = porcelain.gc(
  2960. ".",
  2961. auto=parsed_args.auto,
  2962. aggressive=parsed_args.aggressive,
  2963. prune=not parsed_args.no_prune,
  2964. grace_period=grace_period,
  2965. dry_run=parsed_args.dry_run,
  2966. progress=progress if not parsed_args.quiet else None,
  2967. )
  2968. # Report results
  2969. if not parsed_args.quiet:
  2970. if parsed_args.dry_run:
  2971. logger.info("\nDry run results:")
  2972. if not parsed_args.quiet:
  2973. if parsed_args.dry_run:
  2974. print("\nDry run results:")
  2975. else:
  2976. logger.info("\nGarbage collection complete:")
  2977. if stats.pruned_objects:
  2978. logger.info(
  2979. " Pruned %d unreachable objects", len(stats.pruned_objects)
  2980. )
  2981. logger.info(" Freed %s", format_bytes(stats.bytes_freed))
  2982. if stats.packs_before != stats.packs_after:
  2983. logger.info(
  2984. " Reduced pack files from %d to %d",
  2985. stats.packs_before,
  2986. stats.packs_after,
  2987. )
  2988. except porcelain.Error as e:
  2989. logger.error("%s", e)
  2990. return 1
  2991. return None
  2992. class cmd_count_objects(Command):
  2993. """Count unpacked number of objects and their disk consumption."""
  2994. def run(self, args: Sequence[str]) -> None:
  2995. """Execute the count-objects command.
  2996. Args:
  2997. args: Command line arguments
  2998. """
  2999. parser = argparse.ArgumentParser()
  3000. parser.add_argument(
  3001. "-v",
  3002. "--verbose",
  3003. action="store_true",
  3004. help="Display verbose information.",
  3005. )
  3006. parsed_args = parser.parse_args(args)
  3007. if parsed_args.verbose:
  3008. stats = porcelain.count_objects(".", verbose=True)
  3009. # Display verbose output
  3010. logger.info("count: %d", stats.count)
  3011. logger.info("size: %d", stats.size // 1024) # Size in KiB
  3012. assert stats.in_pack is not None
  3013. logger.info("in-pack: %d", stats.in_pack)
  3014. assert stats.packs is not None
  3015. logger.info("packs: %d", stats.packs)
  3016. assert stats.size_pack is not None
  3017. logger.info("size-pack: %d", stats.size_pack // 1024) # Size in KiB
  3018. else:
  3019. # Simple output
  3020. stats = porcelain.count_objects(".", verbose=False)
  3021. logger.info("%d objects, %d kilobytes", stats.count, stats.size // 1024)
  3022. class cmd_rebase(Command):
  3023. """Reapply commits on top of another base tip."""
  3024. def run(self, args: Sequence[str]) -> int:
  3025. """Execute the rebase command.
  3026. Args:
  3027. args: Command line arguments
  3028. """
  3029. parser = argparse.ArgumentParser()
  3030. parser.add_argument(
  3031. "upstream", nargs="?", help="Upstream branch to rebase onto"
  3032. )
  3033. parser.add_argument("--onto", type=str, help="Rebase onto specific commit")
  3034. parser.add_argument(
  3035. "--branch", type=str, help="Branch to rebase (default: current)"
  3036. )
  3037. parser.add_argument(
  3038. "-i", "--interactive", action="store_true", help="Interactive rebase"
  3039. )
  3040. parser.add_argument(
  3041. "--edit-todo",
  3042. action="store_true",
  3043. help="Edit the todo list during an interactive rebase",
  3044. )
  3045. parser.add_argument(
  3046. "--abort", action="store_true", help="Abort an in-progress rebase"
  3047. )
  3048. parser.add_argument(
  3049. "--continue",
  3050. dest="continue_rebase",
  3051. action="store_true",
  3052. help="Continue an in-progress rebase",
  3053. )
  3054. parser.add_argument(
  3055. "--skip", action="store_true", help="Skip current commit and continue"
  3056. )
  3057. parsed_args = parser.parse_args(args)
  3058. # Handle abort/continue/skip first
  3059. if parsed_args.abort:
  3060. try:
  3061. porcelain.rebase(".", parsed_args.upstream or "HEAD", abort=True)
  3062. logger.info("Rebase aborted.")
  3063. except porcelain.Error as e:
  3064. logger.error("%s", e)
  3065. return 1
  3066. return 0
  3067. if parsed_args.continue_rebase:
  3068. try:
  3069. # Check if interactive rebase is in progress
  3070. if porcelain.is_interactive_rebase("."):
  3071. result = porcelain.rebase(
  3072. ".",
  3073. parsed_args.upstream or "HEAD",
  3074. continue_rebase=True,
  3075. interactive=True,
  3076. )
  3077. if result:
  3078. logger.info("Rebase complete.")
  3079. else:
  3080. logger.info("Rebase paused. Use --continue to resume.")
  3081. else:
  3082. new_shas = porcelain.rebase(
  3083. ".", parsed_args.upstream or "HEAD", continue_rebase=True
  3084. )
  3085. logger.info("Rebase complete.")
  3086. except porcelain.Error as e:
  3087. logger.error("%s", e)
  3088. return 1
  3089. return 0
  3090. if parsed_args.edit_todo:
  3091. # Edit todo list for interactive rebase
  3092. try:
  3093. porcelain.rebase(".", parsed_args.upstream or "HEAD", edit_todo=True)
  3094. logger.info("Todo list updated.")
  3095. except porcelain.Error as e:
  3096. logger.error("%s", e)
  3097. return 1
  3098. return 0
  3099. # Normal rebase requires upstream
  3100. if not parsed_args.upstream:
  3101. logger.error("Missing required argument 'upstream'")
  3102. return 1
  3103. try:
  3104. if parsed_args.interactive:
  3105. # Interactive rebase
  3106. result = porcelain.rebase(
  3107. ".",
  3108. parsed_args.upstream,
  3109. onto=parsed_args.onto,
  3110. branch=parsed_args.branch,
  3111. interactive=True,
  3112. )
  3113. if result:
  3114. logger.info(
  3115. "Interactive rebase started. Edit the todo list and save."
  3116. )
  3117. else:
  3118. logger.info("No commits to rebase.")
  3119. else:
  3120. # Regular rebase
  3121. new_shas = porcelain.rebase(
  3122. ".",
  3123. parsed_args.upstream,
  3124. onto=parsed_args.onto,
  3125. branch=parsed_args.branch,
  3126. )
  3127. if new_shas:
  3128. logger.info("Successfully rebased %d commits.", len(new_shas))
  3129. else:
  3130. logger.info("Already up to date.")
  3131. return 0
  3132. except porcelain.Error as e:
  3133. logger.error("%s", e)
  3134. return 1
  3135. class cmd_filter_branch(Command):
  3136. """Rewrite branches."""
  3137. def run(self, args: Sequence[str]) -> Optional[int]:
  3138. """Execute the filter-branch command.
  3139. Args:
  3140. args: Command line arguments
  3141. """
  3142. import subprocess
  3143. parser = argparse.ArgumentParser(description="Rewrite branches")
  3144. # Supported Git-compatible options
  3145. parser.add_argument(
  3146. "--subdirectory-filter",
  3147. type=str,
  3148. help="Only include history for subdirectory",
  3149. )
  3150. parser.add_argument("--env-filter", type=str, help="Environment filter command")
  3151. parser.add_argument("--tree-filter", type=str, help="Tree filter command")
  3152. parser.add_argument("--index-filter", type=str, help="Index filter command")
  3153. parser.add_argument("--parent-filter", type=str, help="Parent filter command")
  3154. parser.add_argument("--msg-filter", type=str, help="Message filter command")
  3155. parser.add_argument("--commit-filter", type=str, help="Commit filter command")
  3156. parser.add_argument(
  3157. "--tag-name-filter", type=str, help="Tag name filter command"
  3158. )
  3159. parser.add_argument(
  3160. "--prune-empty", action="store_true", help="Remove empty commits"
  3161. )
  3162. parser.add_argument(
  3163. "--original",
  3164. type=str,
  3165. default="refs/original",
  3166. help="Namespace for original refs",
  3167. )
  3168. parser.add_argument(
  3169. "-f",
  3170. "--force",
  3171. action="store_true",
  3172. help="Force operation even if refs/original/* exists",
  3173. )
  3174. # Branch/ref to rewrite (defaults to HEAD)
  3175. parser.add_argument(
  3176. "branch", nargs="?", default="HEAD", help="Branch or ref to rewrite"
  3177. )
  3178. parsed_args = parser.parse_args(args)
  3179. # Track if any filter fails
  3180. filter_error = False
  3181. # Setup environment for filters
  3182. env = os.environ.copy()
  3183. # Helper function to run shell commands
  3184. def run_filter(
  3185. cmd: str,
  3186. input_data: Optional[bytes] = None,
  3187. cwd: Optional[str] = None,
  3188. extra_env: Optional[dict[str, str]] = None,
  3189. ) -> Optional[bytes]:
  3190. nonlocal filter_error
  3191. filter_env = env.copy()
  3192. if extra_env:
  3193. filter_env.update(extra_env)
  3194. result = subprocess.run(
  3195. cmd,
  3196. shell=True,
  3197. input=input_data,
  3198. cwd=cwd,
  3199. env=filter_env,
  3200. capture_output=True,
  3201. )
  3202. if result.returncode != 0:
  3203. filter_error = True
  3204. return None
  3205. return result.stdout
  3206. # Create filter functions based on arguments
  3207. filter_message = None
  3208. if parsed_args.msg_filter:
  3209. def filter_message(message: bytes) -> bytes:
  3210. result = run_filter(parsed_args.msg_filter, input_data=message)
  3211. return result if result is not None else message
  3212. tree_filter = None
  3213. if parsed_args.tree_filter:
  3214. def tree_filter(tree_sha: bytes, tmpdir: str) -> bytes:
  3215. from dulwich.objects import Blob, Tree
  3216. # Export tree to tmpdir
  3217. with Repo(".") as r:
  3218. tree = r.object_store[tree_sha]
  3219. assert isinstance(tree, Tree)
  3220. for entry in tree.iteritems():
  3221. assert entry.path is not None
  3222. assert entry.sha is not None
  3223. path = Path(tmpdir) / entry.path.decode()
  3224. obj = r.object_store[entry.sha]
  3225. if isinstance(obj, Tree):
  3226. path.mkdir(exist_ok=True)
  3227. else:
  3228. assert isinstance(obj, Blob)
  3229. path.write_bytes(obj.data)
  3230. # Run the filter command in the temp directory
  3231. run_filter(parsed_args.tree_filter, cwd=tmpdir)
  3232. # Rebuild tree from modified temp directory
  3233. def build_tree_from_dir(dir_path: str) -> bytes:
  3234. tree = Tree()
  3235. for name in sorted(os.listdir(dir_path)):
  3236. if name.startswith("."):
  3237. continue
  3238. path = os.path.join(dir_path, name)
  3239. if os.path.isdir(path):
  3240. subtree_sha = build_tree_from_dir(path)
  3241. tree.add(name.encode(), 0o040000, subtree_sha)
  3242. else:
  3243. with open(path, "rb") as f:
  3244. data = f.read()
  3245. blob = Blob.from_string(data)
  3246. r.object_store.add_object(blob)
  3247. # Use appropriate file mode
  3248. mode = os.stat(path).st_mode
  3249. if mode & 0o100:
  3250. file_mode = 0o100755
  3251. else:
  3252. file_mode = 0o100644
  3253. tree.add(name.encode(), file_mode, blob.id)
  3254. r.object_store.add_object(tree)
  3255. return tree.id
  3256. return build_tree_from_dir(tmpdir)
  3257. index_filter = None
  3258. if parsed_args.index_filter:
  3259. def index_filter(tree_sha: bytes, index_path: str) -> Optional[bytes]:
  3260. run_filter(
  3261. parsed_args.index_filter, extra_env={"GIT_INDEX_FILE": index_path}
  3262. )
  3263. return None # Read back from index
  3264. parent_filter = None
  3265. if parsed_args.parent_filter:
  3266. def parent_filter(parents: Sequence[bytes]) -> list[bytes]:
  3267. parent_str = " ".join(p.hex() for p in parents)
  3268. result = run_filter(
  3269. parsed_args.parent_filter, input_data=parent_str.encode()
  3270. )
  3271. if result is None:
  3272. return list(parents)
  3273. output = result.decode().strip()
  3274. if not output:
  3275. return []
  3276. new_parents = []
  3277. for sha in output.split():
  3278. sha_bytes = sha.encode()
  3279. if valid_hexsha(sha_bytes):
  3280. new_parents.append(sha_bytes)
  3281. return new_parents
  3282. commit_filter = None
  3283. if parsed_args.commit_filter:
  3284. def commit_filter(commit_obj: Commit, tree_sha: bytes) -> Optional[bytes]:
  3285. # The filter receives: tree parent1 parent2...
  3286. cmd_input = tree_sha.hex()
  3287. for parent in commit_obj.parents:
  3288. cmd_input += " " + parent.hex()
  3289. result = run_filter(
  3290. parsed_args.commit_filter,
  3291. input_data=cmd_input.encode(),
  3292. extra_env={"GIT_COMMIT": commit_obj.id.hex()},
  3293. )
  3294. if result is None:
  3295. return None
  3296. output = result.decode().strip()
  3297. if not output:
  3298. return None # Skip commit
  3299. if valid_hexsha(output):
  3300. return output.encode()
  3301. return None
  3302. tag_name_filter = None
  3303. if parsed_args.tag_name_filter:
  3304. def tag_name_filter(tag_name: bytes) -> bytes:
  3305. result = run_filter(parsed_args.tag_name_filter, input_data=tag_name)
  3306. return result if result is not None else tag_name
  3307. # Open repo once
  3308. with Repo(".") as r:
  3309. # Check for refs/original if not forcing
  3310. if not parsed_args.force:
  3311. original_prefix = parsed_args.original.encode() + b"/"
  3312. for ref in r.refs.allkeys():
  3313. if ref.startswith(original_prefix):
  3314. logger.error("Cannot create a new backup.")
  3315. logger.error(
  3316. "A previous backup already exists in %s/",
  3317. parsed_args.original,
  3318. )
  3319. logger.error("Force overwriting the backup with -f")
  3320. print("Cannot create a new backup.")
  3321. print(
  3322. f"A previous backup already exists in {parsed_args.original}/"
  3323. )
  3324. print("Force overwriting the backup with -f")
  3325. return 1
  3326. try:
  3327. # Call porcelain.filter_branch with the repo object
  3328. result = porcelain.filter_branch(
  3329. r,
  3330. parsed_args.branch,
  3331. filter_message=filter_message,
  3332. tree_filter=tree_filter if parsed_args.tree_filter else None,
  3333. index_filter=index_filter if parsed_args.index_filter else None,
  3334. parent_filter=parent_filter if parsed_args.parent_filter else None,
  3335. commit_filter=commit_filter if parsed_args.commit_filter else None,
  3336. subdirectory_filter=parsed_args.subdirectory_filter,
  3337. prune_empty=parsed_args.prune_empty,
  3338. tag_name_filter=tag_name_filter
  3339. if parsed_args.tag_name_filter
  3340. else None,
  3341. force=parsed_args.force,
  3342. keep_original=True, # Always keep original with git
  3343. )
  3344. # Check if any filter failed
  3345. if filter_error:
  3346. logger.error("Filter command failed")
  3347. return 1
  3348. # Git filter-branch shows progress
  3349. if result:
  3350. logger.info(
  3351. "Rewrite %s (%d commits)", parsed_args.branch, len(result)
  3352. )
  3353. # Git shows: Ref 'refs/heads/branch' was rewritten
  3354. if parsed_args.branch != "HEAD":
  3355. ref_name = (
  3356. parsed_args.branch
  3357. if parsed_args.branch.startswith("refs/")
  3358. else f"refs/heads/{parsed_args.branch}"
  3359. )
  3360. logger.info("Ref '%s' was rewritten", ref_name)
  3361. return 0
  3362. except porcelain.Error as e:
  3363. logger.error("%s", e)
  3364. return 1
  3365. class cmd_lfs(Command):
  3366. """Git Large File Storage management."""
  3367. """Git LFS management commands."""
  3368. def run(self, argv: Sequence[str]) -> None:
  3369. """Execute the lfs command.
  3370. Args:
  3371. argv: Command line arguments
  3372. """
  3373. parser = argparse.ArgumentParser(prog="dulwich lfs")
  3374. subparsers = parser.add_subparsers(dest="subcommand", help="LFS subcommands")
  3375. # lfs init
  3376. subparsers.add_parser("init", help="Initialize Git LFS")
  3377. # lfs track
  3378. parser_track = subparsers.add_parser(
  3379. "track", help="Track file patterns with LFS"
  3380. )
  3381. parser_track.add_argument("patterns", nargs="*", help="File patterns to track")
  3382. # lfs untrack
  3383. parser_untrack = subparsers.add_parser(
  3384. "untrack", help="Untrack file patterns from LFS"
  3385. )
  3386. parser_untrack.add_argument(
  3387. "patterns", nargs="+", help="File patterns to untrack"
  3388. )
  3389. # lfs ls-files
  3390. parser_ls = subparsers.add_parser("ls-files", help="List LFS files")
  3391. parser_ls.add_argument("--ref", help="Git ref to check (defaults to HEAD)")
  3392. # lfs migrate
  3393. parser_migrate = subparsers.add_parser("migrate", help="Migrate files to LFS")
  3394. parser_migrate.add_argument("--include", nargs="+", help="Patterns to include")
  3395. parser_migrate.add_argument("--exclude", nargs="+", help="Patterns to exclude")
  3396. parser_migrate.add_argument(
  3397. "--everything", action="store_true", help="Migrate all files above 100MB"
  3398. )
  3399. # lfs pointer
  3400. parser_pointer = subparsers.add_parser("pointer", help="Check LFS pointers")
  3401. parser_pointer.add_argument(
  3402. "--check", nargs="*", dest="paths", help="Check if files are LFS pointers"
  3403. )
  3404. # lfs clean
  3405. parser_clean = subparsers.add_parser("clean", help="Clean file to LFS pointer")
  3406. parser_clean.add_argument("path", help="File path to clean")
  3407. # lfs smudge
  3408. parser_smudge = subparsers.add_parser(
  3409. "smudge", help="Smudge LFS pointer to content"
  3410. )
  3411. parser_smudge.add_argument(
  3412. "--stdin", action="store_true", help="Read pointer from stdin"
  3413. )
  3414. # lfs fetch
  3415. parser_fetch = subparsers.add_parser(
  3416. "fetch", help="Fetch LFS objects from remote"
  3417. )
  3418. parser_fetch.add_argument(
  3419. "--remote", default="origin", help="Remote to fetch from"
  3420. )
  3421. parser_fetch.add_argument("refs", nargs="*", help="Specific refs to fetch")
  3422. # lfs pull
  3423. parser_pull = subparsers.add_parser(
  3424. "pull", help="Pull LFS objects for current checkout"
  3425. )
  3426. parser_pull.add_argument(
  3427. "--remote", default="origin", help="Remote to pull from"
  3428. )
  3429. # lfs push
  3430. parser_push = subparsers.add_parser("push", help="Push LFS objects to remote")
  3431. parser_push.add_argument("--remote", default="origin", help="Remote to push to")
  3432. parser_push.add_argument("refs", nargs="*", help="Specific refs to push")
  3433. # lfs status
  3434. subparsers.add_parser("status", help="Show status of LFS files")
  3435. args = parser.parse_args(argv)
  3436. if args.subcommand == "init":
  3437. porcelain.lfs_init()
  3438. logger.info("Git LFS initialized.")
  3439. elif args.subcommand == "track":
  3440. if args.patterns:
  3441. tracked = porcelain.lfs_track(patterns=args.patterns)
  3442. logger.info("Tracking patterns:")
  3443. else:
  3444. tracked = porcelain.lfs_track()
  3445. logger.info("Currently tracked patterns:")
  3446. for pattern in tracked:
  3447. logger.info(" %s", pattern)
  3448. elif args.subcommand == "untrack":
  3449. tracked = porcelain.lfs_untrack(patterns=args.patterns)
  3450. logger.info("Remaining tracked patterns:")
  3451. for pattern in tracked:
  3452. logger.info(" %s", to_display_str(pattern))
  3453. elif args.subcommand == "ls-files":
  3454. files = porcelain.lfs_ls_files(ref=args.ref)
  3455. for path, oid, size in files:
  3456. logger.info(
  3457. "%s * %s (%s)",
  3458. to_display_str(oid[:12]),
  3459. to_display_str(path),
  3460. format_bytes(size),
  3461. )
  3462. elif args.subcommand == "migrate":
  3463. count = porcelain.lfs_migrate(
  3464. include=args.include, exclude=args.exclude, everything=args.everything
  3465. )
  3466. logger.info("Migrated %d file(s) to Git LFS.", count)
  3467. elif args.subcommand == "pointer":
  3468. if args.paths is not None:
  3469. results = porcelain.lfs_pointer_check(paths=args.paths or None)
  3470. for file_path, pointer in results.items():
  3471. if pointer:
  3472. logger.info(
  3473. "%s: LFS pointer (oid: %s, size: %s)",
  3474. to_display_str(file_path),
  3475. to_display_str(pointer.oid[:12]),
  3476. format_bytes(pointer.size),
  3477. )
  3478. else:
  3479. logger.warning(
  3480. "%s: Not an LFS pointer", to_display_str(file_path)
  3481. )
  3482. elif args.subcommand == "clean":
  3483. pointer = porcelain.lfs_clean(path=args.path)
  3484. sys.stdout.buffer.write(pointer)
  3485. elif args.subcommand == "smudge":
  3486. if args.stdin:
  3487. pointer_content = sys.stdin.buffer.read()
  3488. content = porcelain.lfs_smudge(pointer_content=pointer_content)
  3489. sys.stdout.buffer.write(content)
  3490. else:
  3491. logger.error("--stdin required for smudge command")
  3492. sys.exit(1)
  3493. elif args.subcommand == "fetch":
  3494. refs = args.refs or None
  3495. count = porcelain.lfs_fetch(remote=args.remote, refs=refs)
  3496. logger.info("Fetched %d LFS object(s).", count)
  3497. elif args.subcommand == "pull":
  3498. count = porcelain.lfs_pull(remote=args.remote)
  3499. logger.info("Pulled %d LFS object(s).", count)
  3500. elif args.subcommand == "push":
  3501. refs = args.refs or None
  3502. count = porcelain.lfs_push(remote=args.remote, refs=refs)
  3503. logger.info("Pushed %d LFS object(s).", count)
  3504. elif args.subcommand == "status":
  3505. status = porcelain.lfs_status()
  3506. if status["tracked"]:
  3507. logger.info("LFS tracked files: %d", len(status["tracked"]))
  3508. if status["missing"]:
  3509. logger.warning("\nMissing LFS objects:")
  3510. for file_path in status["missing"]:
  3511. logger.warning(" %s", to_display_str(file_path))
  3512. if status["not_staged"]:
  3513. logger.info("\nModified LFS files not staged:")
  3514. for file_path in status["not_staged"]:
  3515. logger.warning(" %s", to_display_str(file_path))
  3516. if not any(status.values()):
  3517. logger.info("No LFS files found.")
  3518. else:
  3519. parser.print_help()
  3520. sys.exit(1)
  3521. class cmd_help(Command):
  3522. """Display help information about git."""
  3523. def run(self, args: Sequence[str]) -> None:
  3524. """Execute the help command.
  3525. Args:
  3526. args: Command line arguments
  3527. """
  3528. parser = argparse.ArgumentParser()
  3529. parser.add_argument(
  3530. "-a",
  3531. "--all",
  3532. action="store_true",
  3533. help="List all commands.",
  3534. )
  3535. parsed_args = parser.parse_args(args)
  3536. if parsed_args.all:
  3537. logger.info("Available commands:")
  3538. for cmd in sorted(commands):
  3539. logger.info(" %s", cmd)
  3540. else:
  3541. logger.info(
  3542. "The dulwich command line tool is currently a very basic frontend for the\n"
  3543. "Dulwich python module. For full functionality, please see the API reference.\n"
  3544. "\n"
  3545. "For a list of supported commands, see 'dulwich help -a'."
  3546. )
  3547. class cmd_format_patch(Command):
  3548. """Prepare patches for e-mail submission."""
  3549. def run(self, args: Sequence[str]) -> None:
  3550. """Execute the format-patch command.
  3551. Args:
  3552. args: Command line arguments
  3553. """
  3554. parser = argparse.ArgumentParser()
  3555. parser.add_argument(
  3556. "committish",
  3557. nargs="?",
  3558. help="Commit or commit range (e.g., HEAD~3..HEAD or origin/master..HEAD)",
  3559. )
  3560. parser.add_argument(
  3561. "-n",
  3562. "--numbered",
  3563. type=int,
  3564. default=1,
  3565. help="Number of commits to format (default: 1)",
  3566. )
  3567. parser.add_argument(
  3568. "-o",
  3569. "--output-directory",
  3570. dest="outdir",
  3571. help="Output directory for patches",
  3572. )
  3573. parser.add_argument(
  3574. "--stdout",
  3575. action="store_true",
  3576. help="Output patches to stdout",
  3577. )
  3578. parsed_args = parser.parse_args(args)
  3579. # Parse committish using the new function
  3580. committish: Optional[Union[bytes, tuple[bytes, bytes]]] = None
  3581. if parsed_args.committish:
  3582. with Repo(".") as r:
  3583. range_result = parse_commit_range(r, parsed_args.committish)
  3584. if range_result:
  3585. # Convert Commit objects to their SHAs
  3586. committish = (range_result[0].id, range_result[1].id)
  3587. else:
  3588. committish = (
  3589. parsed_args.committish.encode()
  3590. if isinstance(parsed_args.committish, str)
  3591. else parsed_args.committish
  3592. )
  3593. filenames = porcelain.format_patch(
  3594. ".",
  3595. committish=committish,
  3596. outstream=sys.stdout,
  3597. outdir=parsed_args.outdir,
  3598. n=parsed_args.numbered,
  3599. stdout=parsed_args.stdout,
  3600. )
  3601. if not parsed_args.stdout:
  3602. for filename in filenames:
  3603. logger.info(filename)
  3604. class cmd_bundle(Command):
  3605. """Create, unpack, and manipulate bundle files."""
  3606. def run(self, args: Sequence[str]) -> int:
  3607. """Execute the bundle command.
  3608. Args:
  3609. args: Command line arguments
  3610. """
  3611. if not args:
  3612. logger.error("Usage: bundle <create|verify|list-heads|unbundle> <options>")
  3613. return 1
  3614. subcommand = args[0]
  3615. subargs = args[1:]
  3616. if subcommand == "create":
  3617. return self._create(subargs)
  3618. elif subcommand == "verify":
  3619. return self._verify(subargs)
  3620. elif subcommand == "list-heads":
  3621. return self._list_heads(subargs)
  3622. elif subcommand == "unbundle":
  3623. return self._unbundle(subargs)
  3624. else:
  3625. logger.error("Unknown bundle subcommand: %s", subcommand)
  3626. return 1
  3627. def _create(self, args: Sequence[str]) -> int:
  3628. parser = argparse.ArgumentParser(prog="bundle create")
  3629. parser.add_argument(
  3630. "-q", "--quiet", action="store_true", help="Suppress progress"
  3631. )
  3632. parser.add_argument("--progress", action="store_true", help="Show progress")
  3633. parser.add_argument(
  3634. "--version", type=int, choices=[2, 3], help="Bundle version"
  3635. )
  3636. parser.add_argument("--all", action="store_true", help="Include all refs")
  3637. parser.add_argument("--stdin", action="store_true", help="Read refs from stdin")
  3638. parser.add_argument("file", help="Output bundle file (use - for stdout)")
  3639. parser.add_argument("refs", nargs="*", help="References or rev-list args")
  3640. parsed_args = parser.parse_args(args)
  3641. repo = Repo(".")
  3642. progress = None
  3643. if parsed_args.progress and not parsed_args.quiet:
  3644. def progress(*args: Union[str, int]) -> None:
  3645. # Handle both progress(msg) and progress(count, msg) signatures
  3646. if len(args) == 1:
  3647. msg = args[0]
  3648. elif len(args) == 2:
  3649. _count, msg = args
  3650. else:
  3651. msg = str(args)
  3652. # Convert bytes to string if needed
  3653. if isinstance(msg, bytes):
  3654. msg = msg.decode("utf-8", "replace")
  3655. logger.error("%s", msg)
  3656. refs_to_include = []
  3657. prerequisites = []
  3658. if parsed_args.all:
  3659. refs_to_include = list(repo.refs.keys())
  3660. elif parsed_args.stdin:
  3661. for line in sys.stdin:
  3662. ref = line.strip().encode("utf-8")
  3663. if ref:
  3664. refs_to_include.append(ref)
  3665. elif parsed_args.refs:
  3666. for ref_arg in parsed_args.refs:
  3667. if ".." in ref_arg:
  3668. range_result = parse_commit_range(repo, ref_arg)
  3669. if range_result:
  3670. start_commit, _end_commit = range_result
  3671. prerequisites.append(start_commit.id)
  3672. # For ranges like A..B, we need to include B if it's a ref
  3673. # Split the range to get the end part
  3674. end_part = ref_arg.split("..")[1]
  3675. if end_part: # Not empty (not "A..")
  3676. end_ref = end_part.encode("utf-8")
  3677. if end_ref in repo.refs:
  3678. refs_to_include.append(end_ref)
  3679. else:
  3680. sha = repo.refs[ref_arg.encode("utf-8")]
  3681. refs_to_include.append(ref_arg.encode("utf-8"))
  3682. else:
  3683. if ref_arg.startswith("^"):
  3684. sha = repo.refs[ref_arg[1:].encode("utf-8")]
  3685. prerequisites.append(sha)
  3686. else:
  3687. sha = repo.refs[ref_arg.encode("utf-8")]
  3688. refs_to_include.append(ref_arg.encode("utf-8"))
  3689. else:
  3690. logger.error("No refs specified. Use --all, --stdin, or specify refs")
  3691. return 1
  3692. if not refs_to_include:
  3693. logger.error("fatal: Refusing to create empty bundle.")
  3694. return 1
  3695. bundle = create_bundle_from_repo(
  3696. repo,
  3697. refs=refs_to_include,
  3698. prerequisites=prerequisites,
  3699. version=parsed_args.version,
  3700. progress=progress,
  3701. )
  3702. if parsed_args.file == "-":
  3703. write_bundle(sys.stdout.buffer, bundle)
  3704. else:
  3705. with open(parsed_args.file, "wb") as f:
  3706. write_bundle(f, bundle)
  3707. return 0
  3708. def _verify(self, args: Sequence[str]) -> int:
  3709. parser = argparse.ArgumentParser(prog="bundle verify")
  3710. parser.add_argument(
  3711. "-q", "--quiet", action="store_true", help="Suppress output"
  3712. )
  3713. parser.add_argument("file", help="Bundle file to verify (use - for stdin)")
  3714. parsed_args = parser.parse_args(args)
  3715. repo = Repo(".")
  3716. def verify_bundle(bundle: Bundle) -> int:
  3717. missing_prereqs = []
  3718. for prereq_sha, comment in bundle.prerequisites:
  3719. try:
  3720. repo.object_store[prereq_sha]
  3721. except KeyError:
  3722. missing_prereqs.append(prereq_sha)
  3723. if missing_prereqs:
  3724. if not parsed_args.quiet:
  3725. logger.info("The bundle requires these prerequisite commits:")
  3726. for sha in missing_prereqs:
  3727. logger.info(" %s", sha.decode())
  3728. return 1
  3729. else:
  3730. if not parsed_args.quiet:
  3731. logger.info(
  3732. "The bundle is valid and can be applied to the current repository"
  3733. )
  3734. return 0
  3735. if parsed_args.file == "-":
  3736. bundle = read_bundle(sys.stdin.buffer)
  3737. return verify_bundle(bundle)
  3738. else:
  3739. with open(parsed_args.file, "rb") as f:
  3740. bundle = read_bundle(f)
  3741. return verify_bundle(bundle)
  3742. def _list_heads(self, args: Sequence[str]) -> int:
  3743. parser = argparse.ArgumentParser(prog="bundle list-heads")
  3744. parser.add_argument("file", help="Bundle file (use - for stdin)")
  3745. parser.add_argument("refnames", nargs="*", help="Only show these refs")
  3746. parsed_args = parser.parse_args(args)
  3747. def list_heads(bundle: Bundle) -> None:
  3748. for ref, sha in bundle.references.items():
  3749. if not parsed_args.refnames or ref.decode() in parsed_args.refnames:
  3750. logger.info("%s %s", sha.decode(), ref.decode())
  3751. if parsed_args.file == "-":
  3752. bundle = read_bundle(sys.stdin.buffer)
  3753. list_heads(bundle)
  3754. else:
  3755. with open(parsed_args.file, "rb") as f:
  3756. bundle = read_bundle(f)
  3757. list_heads(bundle)
  3758. return 0
  3759. def _unbundle(self, args: Sequence[str]) -> int:
  3760. parser = argparse.ArgumentParser(prog="bundle unbundle")
  3761. parser.add_argument("--progress", action="store_true", help="Show progress")
  3762. parser.add_argument("file", help="Bundle file (use - for stdin)")
  3763. parser.add_argument("refnames", nargs="*", help="Only unbundle these refs")
  3764. parsed_args = parser.parse_args(args)
  3765. repo = Repo(".")
  3766. progress = None
  3767. if parsed_args.progress:
  3768. def progress(*args: Union[str, int, bytes]) -> None:
  3769. # Handle both progress(msg) and progress(count, msg) signatures
  3770. if len(args) == 1:
  3771. msg = args[0]
  3772. elif len(args) == 2:
  3773. _count, msg = args
  3774. else:
  3775. msg = str(args)
  3776. # Convert bytes to string if needed
  3777. if isinstance(msg, bytes):
  3778. msg = msg.decode("utf-8", "replace")
  3779. elif not isinstance(msg, str):
  3780. msg = str(msg)
  3781. logger.error("%s", msg)
  3782. if parsed_args.file == "-":
  3783. bundle = read_bundle(sys.stdin.buffer)
  3784. # Process the bundle while file is still available via stdin
  3785. bundle.store_objects(repo.object_store, progress=progress)
  3786. else:
  3787. # Keep the file open during bundle processing
  3788. with open(parsed_args.file, "rb") as f:
  3789. bundle = read_bundle(f)
  3790. # Process pack data while file is still open
  3791. bundle.store_objects(repo.object_store, progress=progress)
  3792. for ref, sha in bundle.references.items():
  3793. if not parsed_args.refnames or ref.decode() in parsed_args.refnames:
  3794. logger.info(ref.decode())
  3795. return 0
  3796. class cmd_worktree_add(Command):
  3797. """Create a new worktree."""
  3798. """Add a new worktree to the repository."""
  3799. def run(self, args: Sequence[str]) -> Optional[int]:
  3800. """Execute the worktree-add command.
  3801. Args:
  3802. args: Command line arguments
  3803. """
  3804. parser = argparse.ArgumentParser(
  3805. description="Add a new worktree", prog="dulwich worktree add"
  3806. )
  3807. parser.add_argument("path", help="Path for the new worktree")
  3808. parser.add_argument("committish", nargs="?", help="Commit-ish to checkout")
  3809. parser.add_argument("-b", "--create-branch", help="Create a new branch")
  3810. parser.add_argument(
  3811. "-B", "--force-create-branch", help="Create or reset a branch"
  3812. )
  3813. parser.add_argument(
  3814. "--detach", action="store_true", help="Detach HEAD in new worktree"
  3815. )
  3816. parser.add_argument("--force", action="store_true", help="Force creation")
  3817. parsed_args = parser.parse_args(args)
  3818. from dulwich import porcelain
  3819. branch = None
  3820. commit = None
  3821. if parsed_args.create_branch or parsed_args.force_create_branch:
  3822. branch = (
  3823. parsed_args.create_branch or parsed_args.force_create_branch
  3824. ).encode()
  3825. elif parsed_args.committish and not parsed_args.detach:
  3826. # If committish is provided and not detaching, treat as branch
  3827. branch = parsed_args.committish.encode()
  3828. elif parsed_args.committish:
  3829. # If committish is provided and detaching, treat as commit
  3830. commit = parsed_args.committish.encode()
  3831. worktree_path = porcelain.worktree_add(
  3832. repo=".",
  3833. path=parsed_args.path,
  3834. branch=branch,
  3835. commit=commit,
  3836. detach=parsed_args.detach,
  3837. force=parsed_args.force or bool(parsed_args.force_create_branch),
  3838. )
  3839. logger.info("Worktree added: %s", worktree_path)
  3840. return 0
  3841. class cmd_worktree_list(Command):
  3842. """List worktrees."""
  3843. """List details of each worktree."""
  3844. def run(self, args: Sequence[str]) -> Optional[int]:
  3845. """Execute the worktree-list command.
  3846. Args:
  3847. args: Command line arguments
  3848. """
  3849. parser = argparse.ArgumentParser(
  3850. description="List worktrees", prog="dulwich worktree list"
  3851. )
  3852. parser.add_argument(
  3853. "-v", "--verbose", action="store_true", help="Show additional information"
  3854. )
  3855. parser.add_argument(
  3856. "--porcelain", action="store_true", help="Machine-readable output"
  3857. )
  3858. parsed_args = parser.parse_args(args)
  3859. from dulwich import porcelain
  3860. worktrees = porcelain.worktree_list(repo=".")
  3861. for wt in worktrees:
  3862. path = wt.path
  3863. if wt.bare:
  3864. status = "(bare)"
  3865. elif wt.detached:
  3866. status = (
  3867. f"(detached HEAD {wt.head[:7].decode() if wt.head else 'unknown'})"
  3868. )
  3869. elif wt.branch:
  3870. branch_name = wt.branch.decode().replace("refs/heads/", "")
  3871. status = f"[{branch_name}]"
  3872. else:
  3873. status = "(unknown)"
  3874. if parsed_args.porcelain:
  3875. locked = "locked" if wt.locked else "unlocked"
  3876. prunable = "prunable" if wt.prunable else "unprunable"
  3877. logger.info(
  3878. "%s %s %s %s %s",
  3879. path,
  3880. wt.head.decode() if wt.head else "unknown",
  3881. status,
  3882. locked,
  3883. prunable,
  3884. )
  3885. else:
  3886. line = f"{path} {status}"
  3887. if wt.locked:
  3888. line += " locked"
  3889. if wt.prunable:
  3890. line += " prunable"
  3891. logger.info(line)
  3892. return 0
  3893. class cmd_worktree_remove(Command):
  3894. """Remove a worktree."""
  3895. """Remove a worktree."""
  3896. def run(self, args: Sequence[str]) -> Optional[int]:
  3897. """Execute the worktree-remove command.
  3898. Args:
  3899. args: Command line arguments
  3900. """
  3901. parser = argparse.ArgumentParser(
  3902. description="Remove a worktree", prog="dulwich worktree remove"
  3903. )
  3904. parser.add_argument("worktree", help="Path to worktree to remove")
  3905. parser.add_argument("--force", action="store_true", help="Force removal")
  3906. parsed_args = parser.parse_args(args)
  3907. from dulwich import porcelain
  3908. porcelain.worktree_remove(
  3909. repo=".", path=parsed_args.worktree, force=parsed_args.force
  3910. )
  3911. logger.info("Worktree removed: %s", parsed_args.worktree)
  3912. return 0
  3913. class cmd_worktree_prune(Command):
  3914. """Prune worktree information."""
  3915. """Prune worktree information."""
  3916. def run(self, args: Sequence[str]) -> Optional[int]:
  3917. """Execute the worktree-prune command.
  3918. Args:
  3919. args: Command line arguments
  3920. """
  3921. parser = argparse.ArgumentParser(
  3922. description="Prune worktree information", prog="dulwich worktree prune"
  3923. )
  3924. parser.add_argument(
  3925. "--dry-run", action="store_true", help="Do not remove anything"
  3926. )
  3927. parser.add_argument(
  3928. "-v", "--verbose", action="store_true", help="Report all removals"
  3929. )
  3930. parser.add_argument(
  3931. "--expire", type=int, help="Expire worktrees older than time (seconds)"
  3932. )
  3933. parsed_args = parser.parse_args(args)
  3934. from dulwich import porcelain
  3935. pruned = porcelain.worktree_prune(
  3936. repo=".", dry_run=parsed_args.dry_run, expire=parsed_args.expire
  3937. )
  3938. if pruned:
  3939. if parsed_args.dry_run:
  3940. logger.info("Would prune worktrees:")
  3941. elif parsed_args.verbose:
  3942. logger.info("Pruned worktrees:")
  3943. for wt_id in pruned:
  3944. logger.info(" %s", wt_id)
  3945. elif parsed_args.verbose:
  3946. logger.info("No worktrees to prune")
  3947. return 0
  3948. class cmd_worktree_lock(Command):
  3949. """Lock a worktree to prevent it from being pruned."""
  3950. """Lock a worktree."""
  3951. def run(self, args: Sequence[str]) -> Optional[int]:
  3952. """Execute the worktree-lock command.
  3953. Args:
  3954. args: Command line arguments
  3955. """
  3956. parser = argparse.ArgumentParser(
  3957. description="Lock a worktree", prog="dulwich worktree lock"
  3958. )
  3959. parser.add_argument("worktree", help="Path to worktree to lock")
  3960. parser.add_argument("--reason", help="Reason for locking")
  3961. parsed_args = parser.parse_args(args)
  3962. from dulwich import porcelain
  3963. porcelain.worktree_lock(
  3964. repo=".", path=parsed_args.worktree, reason=parsed_args.reason
  3965. )
  3966. logger.info("Worktree locked: %s", parsed_args.worktree)
  3967. return 0
  3968. class cmd_worktree_unlock(Command):
  3969. """Unlock a locked worktree."""
  3970. """Unlock a worktree."""
  3971. def run(self, args: Sequence[str]) -> Optional[int]:
  3972. """Execute the worktree-unlock command.
  3973. Args:
  3974. args: Command line arguments
  3975. """
  3976. parser = argparse.ArgumentParser(
  3977. description="Unlock a worktree", prog="dulwich worktree unlock"
  3978. )
  3979. parser.add_argument("worktree", help="Path to worktree to unlock")
  3980. parsed_args = parser.parse_args(args)
  3981. from dulwich import porcelain
  3982. porcelain.worktree_unlock(repo=".", path=parsed_args.worktree)
  3983. logger.info("Worktree unlocked: %s", parsed_args.worktree)
  3984. return 0
  3985. class cmd_worktree_move(Command):
  3986. """Move a worktree to a new location."""
  3987. """Move a worktree."""
  3988. def run(self, args: Sequence[str]) -> Optional[int]:
  3989. """Execute the worktree-move command.
  3990. Args:
  3991. args: Command line arguments
  3992. """
  3993. parser = argparse.ArgumentParser(
  3994. description="Move a worktree", prog="dulwich worktree move"
  3995. )
  3996. parser.add_argument("worktree", help="Path to worktree to move")
  3997. parser.add_argument("new_path", help="New path for the worktree")
  3998. parsed_args = parser.parse_args(args)
  3999. from dulwich import porcelain
  4000. porcelain.worktree_move(
  4001. repo=".", old_path=parsed_args.worktree, new_path=parsed_args.new_path
  4002. )
  4003. logger.info(
  4004. "Worktree moved: %s -> %s", parsed_args.worktree, parsed_args.new_path
  4005. )
  4006. return 0
  4007. class cmd_worktree_repair(Command):
  4008. """Repair worktree administrative files."""
  4009. """Repair worktree administrative files."""
  4010. def run(self, args: Sequence[str]) -> Optional[int]:
  4011. """Execute the worktree-repair command.
  4012. Args:
  4013. args: Command line arguments
  4014. """
  4015. parser = argparse.ArgumentParser(
  4016. description="Repair worktree administrative files",
  4017. prog="dulwich worktree repair",
  4018. )
  4019. parser.add_argument(
  4020. "path",
  4021. nargs="*",
  4022. help="Paths to worktrees to repair (if not specified, repairs all)",
  4023. )
  4024. parsed_args = parser.parse_args(args)
  4025. from dulwich import porcelain
  4026. paths = parsed_args.path if parsed_args.path else None
  4027. repaired = porcelain.worktree_repair(repo=".", paths=paths)
  4028. if repaired:
  4029. for path in repaired:
  4030. logger.info("Repaired worktree: %s", path)
  4031. else:
  4032. logger.info("No worktrees needed repair")
  4033. return 0
  4034. class cmd_worktree(SuperCommand):
  4035. """Manage multiple working trees."""
  4036. """Manage multiple working trees."""
  4037. subcommands: ClassVar[dict[str, type[Command]]] = {
  4038. "add": cmd_worktree_add,
  4039. "list": cmd_worktree_list,
  4040. "remove": cmd_worktree_remove,
  4041. "prune": cmd_worktree_prune,
  4042. "lock": cmd_worktree_lock,
  4043. "unlock": cmd_worktree_unlock,
  4044. "move": cmd_worktree_move,
  4045. "repair": cmd_worktree_repair,
  4046. }
  4047. default_command = cmd_worktree_list
  4048. commands = {
  4049. "add": cmd_add,
  4050. "annotate": cmd_annotate,
  4051. "archive": cmd_archive,
  4052. "bisect": cmd_bisect,
  4053. "blame": cmd_blame,
  4054. "branch": cmd_branch,
  4055. "bundle": cmd_bundle,
  4056. "check-ignore": cmd_check_ignore,
  4057. "check-mailmap": cmd_check_mailmap,
  4058. "checkout": cmd_checkout,
  4059. "cherry-pick": cmd_cherry_pick,
  4060. "clone": cmd_clone,
  4061. "commit": cmd_commit,
  4062. "commit-tree": cmd_commit_tree,
  4063. "count-objects": cmd_count_objects,
  4064. "describe": cmd_describe,
  4065. "daemon": cmd_daemon,
  4066. "diff": cmd_diff,
  4067. "diff-tree": cmd_diff_tree,
  4068. "dump-pack": cmd_dump_pack,
  4069. "dump-index": cmd_dump_index,
  4070. "fetch-pack": cmd_fetch_pack,
  4071. "fetch": cmd_fetch,
  4072. "filter-branch": cmd_filter_branch,
  4073. "for-each-ref": cmd_for_each_ref,
  4074. "format-patch": cmd_format_patch,
  4075. "fsck": cmd_fsck,
  4076. "gc": cmd_gc,
  4077. "help": cmd_help,
  4078. "init": cmd_init,
  4079. "lfs": cmd_lfs,
  4080. "log": cmd_log,
  4081. "ls-files": cmd_ls_files,
  4082. "ls-remote": cmd_ls_remote,
  4083. "ls-tree": cmd_ls_tree,
  4084. "merge": cmd_merge,
  4085. "merge-base": cmd_merge_base,
  4086. "merge-tree": cmd_merge_tree,
  4087. "notes": cmd_notes,
  4088. "pack-objects": cmd_pack_objects,
  4089. "pack-refs": cmd_pack_refs,
  4090. "prune": cmd_prune,
  4091. "pull": cmd_pull,
  4092. "push": cmd_push,
  4093. "rebase": cmd_rebase,
  4094. "receive-pack": cmd_receive_pack,
  4095. "reflog": cmd_reflog,
  4096. "remote": cmd_remote,
  4097. "repack": cmd_repack,
  4098. "reset": cmd_reset,
  4099. "revert": cmd_revert,
  4100. "rev-list": cmd_rev_list,
  4101. "rm": cmd_rm,
  4102. "mv": cmd_mv,
  4103. "show": cmd_show,
  4104. "show-branch": cmd_show_branch,
  4105. "show-ref": cmd_show_ref,
  4106. "stash": cmd_stash,
  4107. "status": cmd_status,
  4108. "shortlog": cmd_shortlog,
  4109. "symbolic-ref": cmd_symbolic_ref,
  4110. "submodule": cmd_submodule,
  4111. "tag": cmd_tag,
  4112. "unpack-objects": cmd_unpack_objects,
  4113. "update-server-info": cmd_update_server_info,
  4114. "upload-pack": cmd_upload_pack,
  4115. "var": cmd_var,
  4116. "verify-commit": cmd_verify_commit,
  4117. "verify-tag": cmd_verify_tag,
  4118. "web-daemon": cmd_web_daemon,
  4119. "worktree": cmd_worktree,
  4120. "write-tree": cmd_write_tree,
  4121. }
  4122. def main(argv: Optional[Sequence[str]] = None) -> Optional[int]:
  4123. """Main entry point for the Dulwich CLI.
  4124. Args:
  4125. argv: Command line arguments (defaults to sys.argv[1:])
  4126. Returns:
  4127. Exit code or None
  4128. """
  4129. if argv is None:
  4130. argv = sys.argv[1:]
  4131. # Parse only the global options and command, stop at first positional
  4132. parser = argparse.ArgumentParser(
  4133. prog="dulwich",
  4134. description="Simple command-line interface to Dulwich",
  4135. add_help=False, # We'll handle help ourselves
  4136. )
  4137. parser.add_argument("--no-pager", action="store_true", help="Disable pager")
  4138. parser.add_argument("--pager", action="store_true", help="Force enable pager")
  4139. parser.add_argument("--help", "-h", action="store_true", help="Show help")
  4140. # Parse known args to separate global options from command args
  4141. global_args, remaining = parser.parse_known_args(argv)
  4142. # Apply global pager settings
  4143. if global_args.no_pager:
  4144. disable_pager()
  4145. elif global_args.pager:
  4146. enable_pager()
  4147. # Handle help
  4148. if global_args.help or not remaining:
  4149. parser = argparse.ArgumentParser(
  4150. prog="dulwich", description="Simple command-line interface to Dulwich"
  4151. )
  4152. parser.add_argument("--no-pager", action="store_true", help="Disable pager")
  4153. parser.add_argument("--pager", action="store_true", help="Force enable pager")
  4154. parser.add_argument(
  4155. "command",
  4156. nargs="?",
  4157. help=f"Command to run. Available: {', '.join(sorted(commands.keys()))}",
  4158. )
  4159. parser.print_help()
  4160. return 1
  4161. # Try to configure from GIT_TRACE, fall back to default if it fails
  4162. if not _configure_logging_from_trace():
  4163. logging.basicConfig(
  4164. level=logging.INFO,
  4165. format="%(message)s",
  4166. )
  4167. # First remaining arg is the command
  4168. cmd = remaining[0]
  4169. cmd_args = remaining[1:]
  4170. try:
  4171. cmd_kls = commands[cmd]
  4172. except KeyError:
  4173. logging.fatal("No such subcommand: %s", cmd)
  4174. return 1
  4175. # TODO(jelmer): Return non-0 on errors
  4176. return cmd_kls().run(cmd_args)
  4177. def _main() -> None:
  4178. if "DULWICH_PDB" in os.environ and getattr(signal, "SIGQUIT", None):
  4179. signal.signal(signal.SIGQUIT, signal_quit) # type: ignore[attr-defined,unused-ignore]
  4180. signal.signal(signal.SIGINT, signal_int)
  4181. sys.exit(main())
  4182. if __name__ == "__main__":
  4183. _main()