cli.py 177 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417
  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_config(Command):
  1090. """Get and set repository or global options."""
  1091. def run(self, args: Sequence[str]) -> Optional[int]:
  1092. """Execute the config command.
  1093. Args:
  1094. args: Command line arguments
  1095. """
  1096. parser = argparse.ArgumentParser()
  1097. parser.add_argument(
  1098. "--global",
  1099. dest="global_config",
  1100. action="store_true",
  1101. help="Use global config file",
  1102. )
  1103. parser.add_argument(
  1104. "--local",
  1105. action="store_true",
  1106. help="Use repository config file (default)",
  1107. )
  1108. parser.add_argument(
  1109. "-l",
  1110. "--list",
  1111. action="store_true",
  1112. help="List all variables",
  1113. )
  1114. parser.add_argument(
  1115. "--unset",
  1116. action="store_true",
  1117. help="Remove a variable",
  1118. )
  1119. parser.add_argument(
  1120. "--unset-all",
  1121. action="store_true",
  1122. help="Remove all matches for a variable",
  1123. )
  1124. parser.add_argument(
  1125. "--get-all",
  1126. action="store_true",
  1127. help="Get all values for a multivar",
  1128. )
  1129. parser.add_argument(
  1130. "key",
  1131. nargs="?",
  1132. help="Config key (e.g., user.name)",
  1133. )
  1134. parser.add_argument(
  1135. "value",
  1136. nargs="?",
  1137. help="Config value to set",
  1138. )
  1139. parsed_args = parser.parse_args(args)
  1140. # Determine which config file to use
  1141. if parsed_args.global_config:
  1142. # Use global config file
  1143. config_path = os.path.expanduser("~/.gitconfig")
  1144. try:
  1145. from .config import ConfigFile
  1146. config = ConfigFile.from_path(config_path)
  1147. except FileNotFoundError:
  1148. from .config import ConfigFile
  1149. config = ConfigFile()
  1150. config.path = config_path
  1151. else:
  1152. # Use local repository config (default)
  1153. try:
  1154. repo = Repo(".")
  1155. config = repo.get_config()
  1156. except NotGitRepository:
  1157. logger.error("error: not a git repository")
  1158. return 1
  1159. # Handle --list
  1160. if parsed_args.list:
  1161. for section in config.sections():
  1162. for key, value in config.items(section):
  1163. section_str = ".".join(
  1164. s.decode("utf-8") if isinstance(s, bytes) else s
  1165. for s in section
  1166. )
  1167. key_str = key.decode("utf-8") if isinstance(key, bytes) else key
  1168. value_str = (
  1169. value.decode("utf-8") if isinstance(value, bytes) else value
  1170. )
  1171. print(f"{section_str}.{key_str}={value_str}")
  1172. return 0
  1173. # Handle --unset or --unset-all
  1174. if parsed_args.unset or parsed_args.unset_all:
  1175. if not parsed_args.key:
  1176. logger.error("error: key is required for --unset")
  1177. return 1
  1178. # Parse the key (e.g., "user.name" or "remote.origin.url")
  1179. parts = parsed_args.key.split(".")
  1180. if len(parts) < 2:
  1181. logger.error("error: invalid key format")
  1182. return 1
  1183. if len(parts) == 2:
  1184. section = (parts[0],)
  1185. name = parts[1]
  1186. else:
  1187. # For keys like "remote.origin.url", section is ("remote", "origin")
  1188. section = tuple(parts[:-1])
  1189. name = parts[-1]
  1190. try:
  1191. # Check if the key exists first
  1192. try:
  1193. config.get(section, name)
  1194. except KeyError:
  1195. logger.error(f"error: key '{parsed_args.key}' not found")
  1196. return 1
  1197. # Delete the configuration key using ConfigDict's delete method
  1198. section_bytes = tuple(
  1199. s.encode("utf-8") if isinstance(s, str) else s for s in section
  1200. )
  1201. name_bytes = name.encode("utf-8") if isinstance(name, str) else name
  1202. section_dict = config._values.get(section_bytes)
  1203. if section_dict:
  1204. del section_dict[name_bytes]
  1205. config.write_to_path()
  1206. else:
  1207. logger.error(f"error: key '{parsed_args.key}' not found")
  1208. return 1
  1209. except Exception as e:
  1210. logger.error(f"error: {e}")
  1211. return 1
  1212. return 0
  1213. # Handle --get-all
  1214. if parsed_args.get_all:
  1215. if not parsed_args.key:
  1216. logger.error("error: key is required for --get-all")
  1217. return 1
  1218. parts = parsed_args.key.split(".")
  1219. if len(parts) < 2:
  1220. logger.error("error: invalid key format")
  1221. return 1
  1222. if len(parts) == 2:
  1223. section = (parts[0],)
  1224. name = parts[1]
  1225. else:
  1226. section = tuple(parts[:-1])
  1227. name = parts[-1]
  1228. try:
  1229. for value in config.get_multivar(section, name):
  1230. value_str = (
  1231. value.decode("utf-8") if isinstance(value, bytes) else value
  1232. )
  1233. print(value_str)
  1234. return 0
  1235. except KeyError:
  1236. return 1
  1237. # Handle get (no value provided)
  1238. if parsed_args.key and not parsed_args.value:
  1239. parts = parsed_args.key.split(".")
  1240. if len(parts) < 2:
  1241. logger.error("error: invalid key format")
  1242. return 1
  1243. if len(parts) == 2:
  1244. section = (parts[0],)
  1245. name = parts[1]
  1246. else:
  1247. # For keys like "remote.origin.url", section is ("remote", "origin")
  1248. section = tuple(parts[:-1])
  1249. name = parts[-1]
  1250. try:
  1251. value = config.get(section, name)
  1252. value_str = value.decode("utf-8") if isinstance(value, bytes) else value
  1253. print(value_str)
  1254. return 0
  1255. except KeyError:
  1256. return 1
  1257. # Handle set (key and value provided)
  1258. if parsed_args.key and parsed_args.value:
  1259. parts = parsed_args.key.split(".")
  1260. if len(parts) < 2:
  1261. logger.error("error: invalid key format")
  1262. return 1
  1263. if len(parts) == 2:
  1264. section = (parts[0],)
  1265. name = parts[1]
  1266. else:
  1267. # For keys like "remote.origin.url", section is ("remote", "origin")
  1268. section = tuple(parts[:-1])
  1269. name = parts[-1]
  1270. config.set(section, name, parsed_args.value)
  1271. if parsed_args.global_config:
  1272. config.write_to_path()
  1273. else:
  1274. config.write_to_path()
  1275. return 0
  1276. # No action specified
  1277. parser.print_help()
  1278. return 1
  1279. class cmd_commit(Command):
  1280. """Record changes to the repository."""
  1281. def run(self, args: Sequence[str]) -> Optional[int]:
  1282. """Execute the commit command.
  1283. Args:
  1284. args: Command line arguments
  1285. """
  1286. parser = argparse.ArgumentParser()
  1287. parser.add_argument("--message", "-m", help="Commit message")
  1288. parser.add_argument(
  1289. "-a",
  1290. "--all",
  1291. action="store_true",
  1292. help="Automatically stage all tracked files that have been modified",
  1293. )
  1294. parser.add_argument(
  1295. "--amend",
  1296. action="store_true",
  1297. help="Replace the tip of the current branch by creating a new commit",
  1298. )
  1299. parsed_args = parser.parse_args(args)
  1300. message: Union[bytes, str, Callable[[Optional[Repo], Optional[Commit]], bytes]]
  1301. if parsed_args.message:
  1302. message = parsed_args.message
  1303. elif parsed_args.amend:
  1304. # For amend, create a callable that opens editor with original message pre-populated
  1305. def get_amend_message(
  1306. repo: Optional[Repo], commit: Optional[Commit]
  1307. ) -> bytes:
  1308. # Get the original commit message from current HEAD
  1309. assert repo is not None
  1310. try:
  1311. head_commit = repo[repo.head()]
  1312. assert isinstance(head_commit, Commit)
  1313. original_message = head_commit.message
  1314. except KeyError:
  1315. original_message = b""
  1316. # Open editor with original message
  1317. return _get_commit_message_with_template(original_message, repo, commit)
  1318. message = get_amend_message
  1319. else:
  1320. # For regular commits, use empty template
  1321. def get_regular_message(
  1322. repo: Optional[Repo], commit: Optional[Commit]
  1323. ) -> bytes:
  1324. return _get_commit_message_with_template(b"", repo, commit)
  1325. message = get_regular_message
  1326. try:
  1327. porcelain.commit(
  1328. ".", message=message, all=parsed_args.all, amend=parsed_args.amend
  1329. )
  1330. except CommitMessageError as e:
  1331. logging.exception(e)
  1332. return 1
  1333. return None
  1334. class cmd_commit_tree(Command):
  1335. """Create a new commit object from a tree."""
  1336. def run(self, args: Sequence[str]) -> None:
  1337. """Execute the commit-tree command.
  1338. Args:
  1339. args: Command line arguments
  1340. """
  1341. parser = argparse.ArgumentParser()
  1342. parser.add_argument("--message", "-m", required=True, help="Commit message")
  1343. parser.add_argument("tree", help="Tree SHA to commit")
  1344. parsed_args = parser.parse_args(args)
  1345. porcelain.commit_tree(".", tree=parsed_args.tree, message=parsed_args.message)
  1346. class cmd_update_server_info(Command):
  1347. """Update auxiliary info file to help dumb servers."""
  1348. def run(self, args: Sequence[str]) -> None:
  1349. """Execute the update-server-info command.
  1350. Args:
  1351. args: Command line arguments
  1352. """
  1353. porcelain.update_server_info(".")
  1354. class cmd_symbolic_ref(Command):
  1355. """Read, modify and delete symbolic refs."""
  1356. def run(self, args: Sequence[str]) -> Optional[int]:
  1357. """Execute the symbolic-ref command.
  1358. Args:
  1359. args: Command line arguments
  1360. """
  1361. parser = argparse.ArgumentParser()
  1362. parser.add_argument("name", help="Symbolic reference name")
  1363. parser.add_argument("ref", nargs="?", help="Target reference")
  1364. parser.add_argument("--force", action="store_true", help="Force update")
  1365. parsed_args = parser.parse_args(args)
  1366. # If ref is provided, we're setting; otherwise we're reading
  1367. if parsed_args.ref:
  1368. # Set symbolic reference
  1369. from .repo import Repo
  1370. with Repo(".") as repo:
  1371. repo.refs.set_symbolic_ref(
  1372. parsed_args.name.encode(), parsed_args.ref.encode()
  1373. )
  1374. return 0
  1375. else:
  1376. # Read symbolic reference
  1377. from .repo import Repo
  1378. with Repo(".") as repo:
  1379. try:
  1380. target = repo.refs.read_ref(parsed_args.name.encode())
  1381. if target is None:
  1382. logger.error(
  1383. "fatal: ref '%s' is not a symbolic ref", parsed_args.name
  1384. )
  1385. return 1
  1386. elif target.startswith(b"ref: "):
  1387. logger.info(target[5:].decode())
  1388. else:
  1389. logger.info(target.decode())
  1390. return 0
  1391. except KeyError:
  1392. logger.error(
  1393. "fatal: ref '%s' is not a symbolic ref", parsed_args.name
  1394. )
  1395. return 1
  1396. class cmd_pack_refs(Command):
  1397. """Pack heads and tags for efficient repository access."""
  1398. def run(self, argv: Sequence[str]) -> None:
  1399. """Execute the pack-refs command.
  1400. Args:
  1401. argv: Command line arguments
  1402. """
  1403. parser = argparse.ArgumentParser()
  1404. parser.add_argument("--all", action="store_true")
  1405. # ignored, we never prune
  1406. parser.add_argument("--no-prune", action="store_true")
  1407. args = parser.parse_args(argv)
  1408. porcelain.pack_refs(".", all=args.all)
  1409. class cmd_var(Command):
  1410. """Display Git logical variables."""
  1411. def run(self, argv: Sequence[str]) -> Optional[int]:
  1412. """Execute the var command.
  1413. Args:
  1414. argv: Command line arguments
  1415. """
  1416. parser = argparse.ArgumentParser()
  1417. parser.add_argument(
  1418. "variable",
  1419. nargs="?",
  1420. help="Variable to query (e.g., GIT_AUTHOR_IDENT)",
  1421. )
  1422. parser.add_argument(
  1423. "-l",
  1424. "--list",
  1425. action="store_true",
  1426. help="List all variables",
  1427. )
  1428. args = parser.parse_args(argv)
  1429. if args.list:
  1430. # List all variables
  1431. variables = porcelain.var_list(".")
  1432. for key, value in sorted(variables.items()):
  1433. print(f"{key}={value}")
  1434. return 0
  1435. elif args.variable:
  1436. # Query specific variable
  1437. try:
  1438. value = porcelain.var(".", variable=args.variable)
  1439. print(value)
  1440. return 0
  1441. except KeyError:
  1442. logger.error("error: variable '%s' has no value", args.variable)
  1443. return 1
  1444. else:
  1445. # No arguments - print error
  1446. logger.error("error: variable or -l is required")
  1447. parser.print_help()
  1448. return 1
  1449. class cmd_show(Command):
  1450. """Show various types of objects."""
  1451. def run(self, argv: Sequence[str]) -> None:
  1452. """Execute the show command.
  1453. Args:
  1454. argv: Command line arguments
  1455. """
  1456. parser = argparse.ArgumentParser()
  1457. parser.add_argument("objectish", type=str, nargs="*")
  1458. parser.add_argument(
  1459. "--color",
  1460. choices=["always", "never", "auto"],
  1461. default="auto",
  1462. help="Use colored output (requires rich)",
  1463. )
  1464. args = parser.parse_args(argv)
  1465. # Determine if we should use color
  1466. def _should_use_color() -> bool:
  1467. if args.color == "always":
  1468. return True
  1469. elif args.color == "never":
  1470. return False
  1471. else: # auto
  1472. return sys.stdout.isatty()
  1473. def _create_output_stream(outstream: TextIO) -> TextIO:
  1474. """Create output stream, optionally with colorization."""
  1475. if not _should_use_color():
  1476. return outstream
  1477. from .diff import ColorizedDiffStream
  1478. if not ColorizedDiffStream.is_available():
  1479. if args.color == "always":
  1480. raise ImportError(
  1481. "Rich is required for colored output. Install with: pip install 'dulwich[colordiff]'"
  1482. )
  1483. else:
  1484. logging.warning(
  1485. "Rich not available, disabling colored output. Install with: pip install 'dulwich[colordiff]'"
  1486. )
  1487. return outstream
  1488. # Wrap the ColorizedDiffStream (BinaryIO) back to TextIO
  1489. import io
  1490. colorized = ColorizedDiffStream(outstream.buffer)
  1491. return io.TextIOWrapper(colorized, encoding="utf-8", line_buffering=True)
  1492. with Repo(".") as repo:
  1493. config = repo.get_config_stack()
  1494. with get_pager(config=config, cmd_name="show") as outstream:
  1495. output_stream = _create_output_stream(outstream)
  1496. porcelain.show(repo, args.objectish or None, outstream=output_stream)
  1497. class cmd_show_ref(Command):
  1498. """List references in a local repository."""
  1499. def run(self, args: Sequence[str]) -> Optional[int]:
  1500. """Execute the show-ref command.
  1501. Args:
  1502. args: Command line arguments
  1503. Returns:
  1504. Exit code (0 for success, 1 for error/no matches, 2 for missing ref with --exists)
  1505. """
  1506. parser = argparse.ArgumentParser()
  1507. parser.add_argument(
  1508. "--head",
  1509. action="store_true",
  1510. help="Show the HEAD reference",
  1511. )
  1512. parser.add_argument(
  1513. "--branches",
  1514. action="store_true",
  1515. help="Limit to local branches",
  1516. )
  1517. parser.add_argument(
  1518. "--tags",
  1519. action="store_true",
  1520. help="Limit to local tags",
  1521. )
  1522. parser.add_argument(
  1523. "-d",
  1524. "--dereference",
  1525. action="store_true",
  1526. help="Dereference tags into object IDs",
  1527. )
  1528. parser.add_argument(
  1529. "-s",
  1530. "--hash",
  1531. nargs="?",
  1532. const=40,
  1533. type=int,
  1534. metavar="n",
  1535. help="Only show the OID, not the reference name",
  1536. )
  1537. parser.add_argument(
  1538. "--abbrev",
  1539. nargs="?",
  1540. const=7,
  1541. type=int,
  1542. metavar="n",
  1543. help="Abbreviate the object name",
  1544. )
  1545. parser.add_argument(
  1546. "--verify",
  1547. action="store_true",
  1548. help="Enable stricter reference checking (exact path match)",
  1549. )
  1550. parser.add_argument(
  1551. "--exists",
  1552. action="store_true",
  1553. help="Check whether the given reference exists",
  1554. )
  1555. parser.add_argument(
  1556. "-q",
  1557. "--quiet",
  1558. action="store_true",
  1559. help="Do not print any results to stdout",
  1560. )
  1561. parser.add_argument(
  1562. "patterns",
  1563. nargs="*",
  1564. help="Show references matching patterns",
  1565. )
  1566. parsed_args = parser.parse_args(args)
  1567. # Handle --exists mode
  1568. if parsed_args.exists:
  1569. if not parsed_args.patterns or len(parsed_args.patterns) != 1:
  1570. logger.error("--exists requires exactly one reference argument")
  1571. return 1
  1572. try:
  1573. with Repo(".") as repo:
  1574. repo_refs = repo.get_refs()
  1575. pattern_bytes = os.fsencode(parsed_args.patterns[0])
  1576. if pattern_bytes in repo_refs:
  1577. return 0 # Reference exists
  1578. else:
  1579. return 2 # Reference missing
  1580. except (NotGitRepository, OSError, FileFormatException) as e:
  1581. logger.error(f"Error looking up reference: {e}")
  1582. return 1 # Error looking up reference
  1583. # Regular show-ref mode
  1584. try:
  1585. matched_refs = porcelain.show_ref(
  1586. ".",
  1587. patterns=parsed_args.patterns if parsed_args.patterns else None,
  1588. head=parsed_args.head,
  1589. branches=parsed_args.branches,
  1590. tags=parsed_args.tags,
  1591. dereference=parsed_args.dereference,
  1592. verify=parsed_args.verify,
  1593. )
  1594. except (NotGitRepository, OSError, FileFormatException) as e:
  1595. logger.error(f"Error: {e}")
  1596. return 1
  1597. # Return error if no matches found (unless quiet)
  1598. if not matched_refs:
  1599. if parsed_args.verify and not parsed_args.quiet:
  1600. logger.error("error: no matching refs found")
  1601. return 1
  1602. # Output results
  1603. if not parsed_args.quiet:
  1604. abbrev_len = parsed_args.abbrev if parsed_args.abbrev else 40
  1605. hash_only = parsed_args.hash is not None
  1606. if hash_only and parsed_args.hash:
  1607. abbrev_len = parsed_args.hash
  1608. for sha, ref in matched_refs:
  1609. sha_str = sha.decode()
  1610. if abbrev_len < 40:
  1611. sha_str = sha_str[:abbrev_len]
  1612. if hash_only:
  1613. logger.info(sha_str)
  1614. else:
  1615. logger.info(f"{sha_str} {ref.decode()}")
  1616. return 0
  1617. class cmd_show_branch(Command):
  1618. """Show branches and their commits."""
  1619. def run(self, args: Sequence[str]) -> Optional[int]:
  1620. """Execute the show-branch command.
  1621. Args:
  1622. args: Command line arguments
  1623. Returns:
  1624. Exit code (0 for success, 1 for error)
  1625. """
  1626. parser = argparse.ArgumentParser()
  1627. parser.add_argument(
  1628. "-r",
  1629. "--remotes",
  1630. action="store_true",
  1631. help="Show remote-tracking branches",
  1632. )
  1633. parser.add_argument(
  1634. "-a",
  1635. "--all",
  1636. dest="all_branches",
  1637. action="store_true",
  1638. help="Show both remote-tracking and local branches",
  1639. )
  1640. parser.add_argument(
  1641. "--current",
  1642. action="store_true",
  1643. help="Include current branch if not given on command line",
  1644. )
  1645. parser.add_argument(
  1646. "--topo-order",
  1647. dest="topo_order",
  1648. action="store_true",
  1649. help="Show commits in topological order",
  1650. )
  1651. parser.add_argument(
  1652. "--date-order",
  1653. action="store_true",
  1654. help="Show commits in date order (default)",
  1655. )
  1656. parser.add_argument(
  1657. "--more",
  1658. type=int,
  1659. metavar="n",
  1660. help="Show n more commits beyond common ancestor",
  1661. )
  1662. parser.add_argument(
  1663. "--list",
  1664. dest="list_branches",
  1665. action="store_true",
  1666. help="Show only branch names and their tip commits",
  1667. )
  1668. parser.add_argument(
  1669. "--independent",
  1670. dest="independent_branches",
  1671. action="store_true",
  1672. help="Show only branches not reachable from any other",
  1673. )
  1674. parser.add_argument(
  1675. "--merge-base",
  1676. dest="merge_base",
  1677. action="store_true",
  1678. help="Show merge base of specified branches",
  1679. )
  1680. parser.add_argument(
  1681. "branches",
  1682. nargs="*",
  1683. help="Branches to show (default: all local branches)",
  1684. )
  1685. parsed_args = parser.parse_args(args)
  1686. try:
  1687. output_lines = porcelain.show_branch(
  1688. ".",
  1689. branches=parsed_args.branches if parsed_args.branches else None,
  1690. all_branches=parsed_args.all_branches,
  1691. remotes=parsed_args.remotes,
  1692. current=parsed_args.current,
  1693. topo_order=parsed_args.topo_order,
  1694. more=parsed_args.more,
  1695. list_branches=parsed_args.list_branches,
  1696. independent_branches=parsed_args.independent_branches,
  1697. merge_base=parsed_args.merge_base,
  1698. )
  1699. except (NotGitRepository, OSError, FileFormatException) as e:
  1700. logger.error(f"Error: {e}")
  1701. return 1
  1702. # Output results
  1703. for line in output_lines:
  1704. logger.info(line)
  1705. return 0
  1706. class cmd_diff_tree(Command):
  1707. """Compare the content and mode of trees."""
  1708. def run(self, args: Sequence[str]) -> None:
  1709. """Execute the diff-tree command.
  1710. Args:
  1711. args: Command line arguments
  1712. """
  1713. parser = argparse.ArgumentParser()
  1714. parser.add_argument("old_tree", help="Old tree SHA")
  1715. parser.add_argument("new_tree", help="New tree SHA")
  1716. parsed_args = parser.parse_args(args)
  1717. porcelain.diff_tree(".", parsed_args.old_tree, parsed_args.new_tree)
  1718. class cmd_rev_list(Command):
  1719. """List commit objects in reverse chronological order."""
  1720. def run(self, args: Sequence[str]) -> None:
  1721. """Execute the rev-list command.
  1722. Args:
  1723. args: Command line arguments
  1724. """
  1725. parser = argparse.ArgumentParser()
  1726. parser.add_argument("commits", nargs="+", help="Commit IDs to list")
  1727. parsed_args = parser.parse_args(args)
  1728. porcelain.rev_list(".", parsed_args.commits)
  1729. class cmd_tag(Command):
  1730. """Create, list, delete or verify a tag object."""
  1731. def run(self, args: Sequence[str]) -> None:
  1732. """Execute the tag command.
  1733. Args:
  1734. args: Command line arguments
  1735. """
  1736. parser = argparse.ArgumentParser()
  1737. parser.add_argument(
  1738. "-a",
  1739. "--annotated",
  1740. help="Create an annotated tag.",
  1741. action="store_true",
  1742. )
  1743. parser.add_argument(
  1744. "-s", "--sign", help="Sign the annotated tag.", action="store_true"
  1745. )
  1746. parser.add_argument("tag_name", help="Name of the tag to create")
  1747. parsed_args = parser.parse_args(args)
  1748. porcelain.tag_create(
  1749. ".",
  1750. parsed_args.tag_name,
  1751. annotated=parsed_args.annotated,
  1752. sign=parsed_args.sign,
  1753. )
  1754. class cmd_verify_commit(Command):
  1755. """Check the GPG signature of commits."""
  1756. def run(self, args: Sequence[str]) -> Optional[int]:
  1757. """Execute the verify-commit command.
  1758. Args:
  1759. args: Command line arguments
  1760. Returns:
  1761. Exit code (1 on error, None on success)
  1762. """
  1763. parser = argparse.ArgumentParser()
  1764. parser.add_argument(
  1765. "-v",
  1766. "--verbose",
  1767. help="Print the contents of the commit object before validating it.",
  1768. action="store_true",
  1769. )
  1770. parser.add_argument(
  1771. "--raw",
  1772. help="Print the raw gpg status output to standard error.",
  1773. action="store_true",
  1774. )
  1775. parser.add_argument(
  1776. "commits",
  1777. nargs="*",
  1778. default=["HEAD"],
  1779. help="Commits to verify (defaults to HEAD)",
  1780. )
  1781. parsed_args = parser.parse_args(args)
  1782. exit_code = None
  1783. for commit in parsed_args.commits:
  1784. try:
  1785. if parsed_args.verbose:
  1786. # Show commit contents before verification
  1787. porcelain.show(
  1788. ".",
  1789. objects=[commit],
  1790. outstream=sys.stdout,
  1791. )
  1792. porcelain.verify_commit(".", commit)
  1793. if not parsed_args.raw:
  1794. print(f"gpg: Good signature from commit '{commit}'")
  1795. except Exception as e:
  1796. if not parsed_args.raw:
  1797. print(f"error: {commit}: {e}", file=sys.stderr)
  1798. else:
  1799. # In raw mode, let the exception propagate
  1800. raise
  1801. exit_code = 1
  1802. return exit_code
  1803. class cmd_verify_tag(Command):
  1804. """Check the GPG signature of tags."""
  1805. def run(self, args: Sequence[str]) -> Optional[int]:
  1806. """Execute the verify-tag command.
  1807. Args:
  1808. args: Command line arguments
  1809. Returns:
  1810. Exit code (1 on error, None on success)
  1811. """
  1812. parser = argparse.ArgumentParser()
  1813. parser.add_argument(
  1814. "-v",
  1815. "--verbose",
  1816. help="Print the contents of the tag object before validating it.",
  1817. action="store_true",
  1818. )
  1819. parser.add_argument(
  1820. "--raw",
  1821. help="Print the raw gpg status output to standard error.",
  1822. action="store_true",
  1823. )
  1824. parser.add_argument("tags", nargs="+", help="Tags to verify")
  1825. parsed_args = parser.parse_args(args)
  1826. exit_code = None
  1827. for tag in parsed_args.tags:
  1828. try:
  1829. if parsed_args.verbose:
  1830. # Show tag contents before verification
  1831. porcelain.show(
  1832. ".",
  1833. objects=[tag],
  1834. outstream=sys.stdout,
  1835. )
  1836. porcelain.verify_tag(".", tag)
  1837. if not parsed_args.raw:
  1838. print(f"gpg: Good signature from tag '{tag}'")
  1839. except Exception as e:
  1840. if not parsed_args.raw:
  1841. print(f"error: {tag}: {e}", file=sys.stderr)
  1842. else:
  1843. # In raw mode, let the exception propagate
  1844. raise
  1845. exit_code = 1
  1846. return exit_code
  1847. class cmd_repack(Command):
  1848. """Pack unpacked objects in a repository."""
  1849. def run(self, args: Sequence[str]) -> None:
  1850. """Execute the repack command.
  1851. Args:
  1852. args: Command line arguments
  1853. """
  1854. parser = argparse.ArgumentParser()
  1855. parser.parse_args(args)
  1856. porcelain.repack(".")
  1857. class cmd_reflog(Command):
  1858. """Manage reflog information."""
  1859. def run(self, args: Sequence[str]) -> None:
  1860. """Execute the reflog command.
  1861. Args:
  1862. args: Command line arguments
  1863. """
  1864. parser = argparse.ArgumentParser()
  1865. parser.add_argument(
  1866. "ref", nargs="?", default="HEAD", help="Reference to show reflog for"
  1867. )
  1868. parser.add_argument(
  1869. "--all", action="store_true", help="Show reflogs for all refs"
  1870. )
  1871. parsed_args = parser.parse_args(args)
  1872. with Repo(".") as repo:
  1873. config = repo.get_config_stack()
  1874. with get_pager(config=config, cmd_name="reflog") as outstream:
  1875. if parsed_args.all:
  1876. # Show reflogs for all refs
  1877. for ref_bytes, entry in porcelain.reflog(repo, all=True):
  1878. ref_str = ref_bytes.decode("utf-8", "replace")
  1879. short_new = entry.new_sha[:8].decode("ascii")
  1880. outstream.write(
  1881. f"{short_new} {ref_str}: {entry.message.decode('utf-8', 'replace')}\n"
  1882. )
  1883. else:
  1884. ref = (
  1885. parsed_args.ref.encode("utf-8")
  1886. if isinstance(parsed_args.ref, str)
  1887. else parsed_args.ref
  1888. )
  1889. for i, entry in enumerate(porcelain.reflog(repo, ref)):
  1890. # Format similar to git reflog
  1891. from dulwich.reflog import Entry
  1892. assert isinstance(entry, Entry)
  1893. short_new = entry.new_sha[:8].decode("ascii")
  1894. message = (
  1895. entry.message.decode("utf-8", "replace")
  1896. if entry.message
  1897. else ""
  1898. )
  1899. outstream.write(
  1900. f"{short_new} {ref.decode('utf-8', 'replace')}@{{{i}}}: {message}\n"
  1901. )
  1902. class cmd_reset(Command):
  1903. """Reset current HEAD to the specified state."""
  1904. def run(self, args: Sequence[str]) -> None:
  1905. """Execute the reset command.
  1906. Args:
  1907. args: Command line arguments
  1908. """
  1909. parser = argparse.ArgumentParser()
  1910. mode_group = parser.add_mutually_exclusive_group()
  1911. mode_group.add_argument(
  1912. "--hard", action="store_true", help="Reset working tree and index"
  1913. )
  1914. mode_group.add_argument("--soft", action="store_true", help="Reset only HEAD")
  1915. mode_group.add_argument(
  1916. "--mixed", action="store_true", help="Reset HEAD and index"
  1917. )
  1918. parser.add_argument("treeish", nargs="?", help="Commit/tree to reset to")
  1919. parsed_args = parser.parse_args(args)
  1920. if parsed_args.hard:
  1921. mode = "hard"
  1922. elif parsed_args.soft:
  1923. mode = "soft"
  1924. elif parsed_args.mixed:
  1925. mode = "mixed"
  1926. else:
  1927. # Default to mixed behavior
  1928. mode = "mixed"
  1929. # Use the porcelain.reset function for all modes
  1930. porcelain.reset(".", mode=mode, treeish=parsed_args.treeish)
  1931. class cmd_revert(Command):
  1932. """Revert some existing commits."""
  1933. def run(self, args: Sequence[str]) -> None:
  1934. """Execute the revert command.
  1935. Args:
  1936. args: Command line arguments
  1937. """
  1938. parser = argparse.ArgumentParser()
  1939. parser.add_argument(
  1940. "--no-commit",
  1941. "-n",
  1942. action="store_true",
  1943. help="Apply changes but don't create a commit",
  1944. )
  1945. parser.add_argument("-m", "--message", help="Custom commit message")
  1946. parser.add_argument("commits", nargs="+", help="Commits to revert")
  1947. parsed_args = parser.parse_args(args)
  1948. result = porcelain.revert(
  1949. ".",
  1950. commits=parsed_args.commits,
  1951. no_commit=parsed_args.no_commit,
  1952. message=parsed_args.message,
  1953. )
  1954. if result and not parsed_args.no_commit:
  1955. logger.info("[%s] Revert completed", result.decode("ascii")[:7])
  1956. class cmd_daemon(Command):
  1957. """Run a simple Git protocol server."""
  1958. def run(self, args: Sequence[str]) -> None:
  1959. """Execute the daemon command.
  1960. Args:
  1961. args: Command line arguments
  1962. """
  1963. from dulwich import log_utils
  1964. from .protocol import TCP_GIT_PORT
  1965. parser = argparse.ArgumentParser()
  1966. parser.add_argument(
  1967. "-l",
  1968. "--listen_address",
  1969. default="localhost",
  1970. help="Binding IP address.",
  1971. )
  1972. parser.add_argument(
  1973. "-p",
  1974. "--port",
  1975. type=int,
  1976. default=TCP_GIT_PORT,
  1977. help="Binding TCP port.",
  1978. )
  1979. parser.add_argument(
  1980. "gitdir", nargs="?", default=".", help="Git directory to serve"
  1981. )
  1982. parsed_args = parser.parse_args(args)
  1983. log_utils.default_logging_config()
  1984. porcelain.daemon(
  1985. parsed_args.gitdir,
  1986. address=parsed_args.listen_address,
  1987. port=parsed_args.port,
  1988. )
  1989. class cmd_web_daemon(Command):
  1990. """Run a simple HTTP server for Git repositories."""
  1991. def run(self, args: Sequence[str]) -> None:
  1992. """Execute the web-daemon command.
  1993. Args:
  1994. args: Command line arguments
  1995. """
  1996. from dulwich import log_utils
  1997. parser = argparse.ArgumentParser()
  1998. parser.add_argument(
  1999. "-l",
  2000. "--listen_address",
  2001. default="",
  2002. help="Binding IP address.",
  2003. )
  2004. parser.add_argument(
  2005. "-p",
  2006. "--port",
  2007. type=int,
  2008. default=8000,
  2009. help="Binding TCP port.",
  2010. )
  2011. parser.add_argument(
  2012. "gitdir", nargs="?", default=".", help="Git directory to serve"
  2013. )
  2014. parsed_args = parser.parse_args(args)
  2015. log_utils.default_logging_config()
  2016. porcelain.web_daemon(
  2017. parsed_args.gitdir,
  2018. address=parsed_args.listen_address,
  2019. port=parsed_args.port,
  2020. )
  2021. class cmd_write_tree(Command):
  2022. """Create a tree object from the current index."""
  2023. def run(self, args: Sequence[str]) -> None:
  2024. """Execute the write-tree command.
  2025. Args:
  2026. args: Command line arguments
  2027. """
  2028. parser = argparse.ArgumentParser()
  2029. parser.parse_args(args)
  2030. sys.stdout.write("{}\n".format(porcelain.write_tree(".").decode()))
  2031. class cmd_receive_pack(Command):
  2032. """Receive what is pushed into the repository."""
  2033. def run(self, args: Sequence[str]) -> None:
  2034. """Execute the receive-pack command.
  2035. Args:
  2036. args: Command line arguments
  2037. """
  2038. parser = argparse.ArgumentParser()
  2039. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  2040. parsed_args = parser.parse_args(args)
  2041. porcelain.receive_pack(parsed_args.gitdir)
  2042. class cmd_upload_pack(Command):
  2043. """Send objects packed back to git-fetch-pack."""
  2044. def run(self, args: Sequence[str]) -> None:
  2045. """Execute the upload-pack command.
  2046. Args:
  2047. args: Command line arguments
  2048. """
  2049. parser = argparse.ArgumentParser()
  2050. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  2051. parsed_args = parser.parse_args(args)
  2052. porcelain.upload_pack(parsed_args.gitdir)
  2053. class cmd_shortlog(Command):
  2054. """Show a shortlog of commits by author."""
  2055. def run(self, args: Sequence[str]) -> None:
  2056. """Execute the shortlog command with the given CLI arguments.
  2057. Args:
  2058. args: List of command line arguments.
  2059. """
  2060. parser = argparse.ArgumentParser()
  2061. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  2062. parser.add_argument("--summary", action="store_true", help="Show summary only")
  2063. parser.add_argument(
  2064. "--sort", action="store_true", help="Sort authors by commit count"
  2065. )
  2066. parsed_args = parser.parse_args(args)
  2067. shortlog_items: list[dict[str, str]] = porcelain.shortlog(
  2068. repo=parsed_args.gitdir,
  2069. summary_only=parsed_args.summary,
  2070. sort_by_commits=parsed_args.sort,
  2071. )
  2072. for item in shortlog_items:
  2073. author: str = item["author"]
  2074. messages: str = item["messages"]
  2075. if parsed_args.summary:
  2076. count = len(messages.splitlines())
  2077. sys.stdout.write(f"{count}\t{author}\n")
  2078. else:
  2079. sys.stdout.write(f"{author} ({len(messages.splitlines())}):\n")
  2080. for msg in messages.splitlines():
  2081. sys.stdout.write(f" {msg}\n")
  2082. sys.stdout.write("\n")
  2083. class cmd_status(Command):
  2084. """Show the working tree status."""
  2085. def run(self, args: Sequence[str]) -> None:
  2086. """Execute the status command.
  2087. Args:
  2088. args: Command line arguments
  2089. """
  2090. parser = argparse.ArgumentParser()
  2091. parser.add_argument("gitdir", nargs="?", default=".", help="Git directory")
  2092. parsed_args = parser.parse_args(args)
  2093. status = porcelain.status(parsed_args.gitdir)
  2094. if any(names for (kind, names) in status.staged.items()):
  2095. sys.stdout.write("Changes to be committed:\n\n")
  2096. for kind, names in status.staged.items():
  2097. for name in names:
  2098. sys.stdout.write(
  2099. f"\t{kind}: {name.decode(sys.getfilesystemencoding())}\n"
  2100. )
  2101. sys.stdout.write("\n")
  2102. if status.unstaged:
  2103. sys.stdout.write("Changes not staged for commit:\n\n")
  2104. for name in status.unstaged:
  2105. sys.stdout.write(f"\t{name.decode(sys.getfilesystemencoding())}\n")
  2106. sys.stdout.write("\n")
  2107. if status.untracked:
  2108. sys.stdout.write("Untracked files:\n\n")
  2109. for name in status.untracked:
  2110. sys.stdout.write(f"\t{name}\n")
  2111. sys.stdout.write("\n")
  2112. class cmd_ls_remote(Command):
  2113. """List references in a remote repository."""
  2114. def run(self, args: Sequence[str]) -> None:
  2115. """Execute the ls-remote command.
  2116. Args:
  2117. args: Command line arguments
  2118. """
  2119. parser = argparse.ArgumentParser()
  2120. parser.add_argument(
  2121. "--symref", action="store_true", help="Show symbolic references"
  2122. )
  2123. parser.add_argument("url", help="Remote URL to list references from")
  2124. parsed_args = parser.parse_args(args)
  2125. result = porcelain.ls_remote(parsed_args.url)
  2126. if parsed_args.symref:
  2127. # Show symrefs first, like git does
  2128. for ref, target in sorted(result.symrefs.items()):
  2129. if target:
  2130. sys.stdout.write(f"ref: {target.decode()}\t{ref.decode()}\n")
  2131. # Show regular refs
  2132. for ref in sorted(result.refs):
  2133. sha = result.refs[ref]
  2134. if sha is not None:
  2135. sys.stdout.write(f"{sha.decode()}\t{ref.decode()}\n")
  2136. class cmd_ls_tree(Command):
  2137. """List the contents of a tree object."""
  2138. def run(self, args: Sequence[str]) -> None:
  2139. """Execute the ls-tree command.
  2140. Args:
  2141. args: Command line arguments
  2142. """
  2143. parser = argparse.ArgumentParser()
  2144. parser.add_argument(
  2145. "-r",
  2146. "--recursive",
  2147. action="store_true",
  2148. help="Recursively list tree contents.",
  2149. )
  2150. parser.add_argument(
  2151. "--name-only", action="store_true", help="Only display name."
  2152. )
  2153. parser.add_argument("treeish", nargs="?", help="Tree-ish to list")
  2154. parsed_args = parser.parse_args(args)
  2155. with Repo(".") as repo:
  2156. config = repo.get_config_stack()
  2157. with get_pager(config=config, cmd_name="ls-tree") as outstream:
  2158. porcelain.ls_tree(
  2159. repo,
  2160. parsed_args.treeish,
  2161. outstream=outstream,
  2162. recursive=parsed_args.recursive,
  2163. name_only=parsed_args.name_only,
  2164. )
  2165. class cmd_pack_objects(Command):
  2166. """Create a packed archive of objects."""
  2167. def run(self, args: Sequence[str]) -> None:
  2168. """Execute the pack-objects command.
  2169. Args:
  2170. args: Command line arguments
  2171. """
  2172. parser = argparse.ArgumentParser()
  2173. parser.add_argument(
  2174. "--stdout", action="store_true", help="Write pack to stdout"
  2175. )
  2176. parser.add_argument("--deltify", action="store_true", help="Create deltas")
  2177. parser.add_argument(
  2178. "--no-reuse-deltas", action="store_true", help="Don't reuse existing deltas"
  2179. )
  2180. parser.add_argument("basename", nargs="?", help="Base name for pack files")
  2181. parsed_args = parser.parse_args(args)
  2182. if not parsed_args.stdout and not parsed_args.basename:
  2183. parser.error("basename required when not using --stdout")
  2184. object_ids = [line.strip().encode() for line in sys.stdin.readlines()]
  2185. deltify = parsed_args.deltify
  2186. reuse_deltas = not parsed_args.no_reuse_deltas
  2187. if parsed_args.stdout:
  2188. packf = getattr(sys.stdout, "buffer", sys.stdout)
  2189. assert isinstance(packf, BinaryIO)
  2190. idxf = None
  2191. close = []
  2192. else:
  2193. packf = open(parsed_args.basename + ".pack", "wb")
  2194. idxf = open(parsed_args.basename + ".idx", "wb")
  2195. close = [packf, idxf]
  2196. porcelain.pack_objects(
  2197. ".", object_ids, packf, idxf, deltify=deltify, reuse_deltas=reuse_deltas
  2198. )
  2199. for f in close:
  2200. f.close()
  2201. class cmd_unpack_objects(Command):
  2202. """Unpack objects from a packed archive."""
  2203. def run(self, args: Sequence[str]) -> None:
  2204. """Execute the unpack-objects command.
  2205. Args:
  2206. args: Command line arguments
  2207. """
  2208. parser = argparse.ArgumentParser()
  2209. parser.add_argument("pack_file", help="Pack file to unpack")
  2210. parsed_args = parser.parse_args(args)
  2211. count = porcelain.unpack_objects(parsed_args.pack_file)
  2212. logger.info("Unpacked %d objects", count)
  2213. class cmd_prune(Command):
  2214. """Prune all unreachable objects from the object database."""
  2215. def run(self, args: Sequence[str]) -> Optional[int]:
  2216. """Execute the prune command.
  2217. Args:
  2218. args: Command line arguments
  2219. """
  2220. import datetime
  2221. import time
  2222. from dulwich.object_store import DEFAULT_TEMPFILE_GRACE_PERIOD
  2223. parser = argparse.ArgumentParser(
  2224. description="Remove temporary pack files left behind by interrupted operations"
  2225. )
  2226. parser.add_argument(
  2227. "--expire",
  2228. nargs="?",
  2229. const="2.weeks.ago",
  2230. help="Only prune files older than the specified date (default: 2.weeks.ago)",
  2231. )
  2232. parser.add_argument(
  2233. "--dry-run",
  2234. "-n",
  2235. action="store_true",
  2236. help="Only report what would be removed",
  2237. )
  2238. parser.add_argument(
  2239. "--verbose",
  2240. "-v",
  2241. action="store_true",
  2242. help="Report all actions",
  2243. )
  2244. parsed_args = parser.parse_args(args)
  2245. # Parse expire grace period
  2246. grace_period = DEFAULT_TEMPFILE_GRACE_PERIOD
  2247. if parsed_args.expire:
  2248. try:
  2249. grace_period = parse_relative_time(parsed_args.expire)
  2250. except ValueError:
  2251. # Try to parse as absolute date
  2252. try:
  2253. date = datetime.datetime.strptime(parsed_args.expire, "%Y-%m-%d")
  2254. grace_period = int(time.time() - date.timestamp())
  2255. except ValueError:
  2256. logger.error("Invalid expire date: %s", parsed_args.expire)
  2257. return 1
  2258. # Progress callback
  2259. def progress(msg: str) -> None:
  2260. if parsed_args.verbose:
  2261. logger.info("%s", msg)
  2262. try:
  2263. porcelain.prune(
  2264. ".",
  2265. grace_period=grace_period,
  2266. dry_run=parsed_args.dry_run,
  2267. progress=progress if parsed_args.verbose else None,
  2268. )
  2269. return None
  2270. except porcelain.Error as e:
  2271. logger.error("%s", e)
  2272. return 1
  2273. class cmd_pull(Command):
  2274. """Fetch from and integrate with another repository or a local branch."""
  2275. def run(self, args: Sequence[str]) -> None:
  2276. """Execute the pull command.
  2277. Args:
  2278. args: Command line arguments
  2279. """
  2280. parser = argparse.ArgumentParser()
  2281. parser.add_argument("from_location", type=str)
  2282. parser.add_argument("refspec", type=str, nargs="*")
  2283. parser.add_argument("--filter", type=str, nargs=1)
  2284. parser.add_argument("--protocol", type=int)
  2285. parsed_args = parser.parse_args(args)
  2286. porcelain.pull(
  2287. ".",
  2288. remote_location=parsed_args.from_location or None,
  2289. refspecs=parsed_args.refspec or None,
  2290. filter_spec=parsed_args.filter,
  2291. protocol_version=parsed_args.protocol or None,
  2292. )
  2293. class cmd_push(Command):
  2294. """Update remote refs along with associated objects."""
  2295. def run(self, argv: Sequence[str]) -> Optional[int]:
  2296. """Execute the push command.
  2297. Args:
  2298. argv: Command line arguments
  2299. """
  2300. parser = argparse.ArgumentParser()
  2301. parser.add_argument("-f", "--force", action="store_true", help="Force")
  2302. parser.add_argument("to_location", type=str)
  2303. parser.add_argument("refspec", type=str, nargs="*")
  2304. args = parser.parse_args(argv)
  2305. try:
  2306. porcelain.push(
  2307. ".", args.to_location, args.refspec or None, force=args.force
  2308. )
  2309. except porcelain.DivergedBranches:
  2310. sys.stderr.write("Diverged branches; specify --force to override")
  2311. return 1
  2312. return None
  2313. class cmd_remote_add(Command):
  2314. """Add a remote repository."""
  2315. def run(self, args: Sequence[str]) -> None:
  2316. """Execute the remote-add command.
  2317. Args:
  2318. args: Command line arguments
  2319. """
  2320. parser = argparse.ArgumentParser()
  2321. parser.add_argument("name", help="Name of the remote")
  2322. parser.add_argument("url", help="URL of the remote")
  2323. parsed_args = parser.parse_args(args)
  2324. porcelain.remote_add(".", parsed_args.name, parsed_args.url)
  2325. class SuperCommand(Command):
  2326. """Base class for commands that have subcommands."""
  2327. subcommands: ClassVar[dict[str, type[Command]]] = {}
  2328. default_command: ClassVar[Optional[type[Command]]] = None
  2329. def run(self, args: Sequence[str]) -> Optional[int]:
  2330. """Execute the subcommand command.
  2331. Args:
  2332. args: Command line arguments
  2333. """
  2334. if not args:
  2335. if self.default_command:
  2336. return self.default_command().run(args)
  2337. else:
  2338. logger.info(
  2339. "Supported subcommands: %s", ", ".join(self.subcommands.keys())
  2340. )
  2341. return False
  2342. cmd = args[0]
  2343. try:
  2344. cmd_kls = self.subcommands[cmd]
  2345. except KeyError:
  2346. logger.error("No such subcommand: %s", args[0])
  2347. sys.exit(1)
  2348. return cmd_kls().run(args[1:])
  2349. class cmd_remote(SuperCommand):
  2350. """Manage set of tracked repositories."""
  2351. subcommands: ClassVar[dict[str, type[Command]]] = {
  2352. "add": cmd_remote_add,
  2353. }
  2354. class cmd_submodule_list(Command):
  2355. """List submodules."""
  2356. def run(self, argv: Sequence[str]) -> None:
  2357. """Execute the submodule-list command.
  2358. Args:
  2359. argv: Command line arguments
  2360. """
  2361. parser = argparse.ArgumentParser()
  2362. parser.parse_args(argv)
  2363. for path, sha in porcelain.submodule_list("."):
  2364. sys.stdout.write(f" {sha} {path}\n")
  2365. class cmd_submodule_init(Command):
  2366. """Initialize submodules."""
  2367. def run(self, argv: Sequence[str]) -> None:
  2368. """Execute the submodule-init command.
  2369. Args:
  2370. argv: Command line arguments
  2371. """
  2372. parser = argparse.ArgumentParser()
  2373. parser.parse_args(argv)
  2374. porcelain.submodule_init(".")
  2375. class cmd_submodule_add(Command):
  2376. """Add a submodule."""
  2377. def run(self, argv: Sequence[str]) -> None:
  2378. """Execute the submodule-add command.
  2379. Args:
  2380. argv: Command line arguments
  2381. """
  2382. parser = argparse.ArgumentParser()
  2383. parser.add_argument("url", help="URL of repository to add as submodule")
  2384. parser.add_argument("path", nargs="?", help="Path where submodule should live")
  2385. parser.add_argument("--name", help="Name for the submodule")
  2386. args = parser.parse_args(argv)
  2387. porcelain.submodule_add(".", args.url, args.path, args.name)
  2388. class cmd_submodule_update(Command):
  2389. """Update submodules."""
  2390. def run(self, argv: Sequence[str]) -> None:
  2391. """Execute the submodule-update command.
  2392. Args:
  2393. argv: Command line arguments
  2394. """
  2395. parser = argparse.ArgumentParser()
  2396. parser.add_argument(
  2397. "--init", action="store_true", help="Initialize submodules first"
  2398. )
  2399. parser.add_argument(
  2400. "--force",
  2401. action="store_true",
  2402. help="Force update even if local changes exist",
  2403. )
  2404. parser.add_argument(
  2405. "paths", nargs="*", help="Specific submodule paths to update"
  2406. )
  2407. args = parser.parse_args(argv)
  2408. paths = args.paths if args.paths else None
  2409. porcelain.submodule_update(".", paths=paths, init=args.init, force=args.force)
  2410. class cmd_submodule(SuperCommand):
  2411. """Initialize, update or inspect submodules."""
  2412. subcommands: ClassVar[dict[str, type[Command]]] = {
  2413. "add": cmd_submodule_add,
  2414. "init": cmd_submodule_init,
  2415. "list": cmd_submodule_list,
  2416. "update": cmd_submodule_update,
  2417. }
  2418. default_command = cmd_submodule_list
  2419. class cmd_check_ignore(Command):
  2420. """Check whether files are excluded by gitignore."""
  2421. def run(self, args: Sequence[str]) -> int:
  2422. """Execute the check-ignore command.
  2423. Args:
  2424. args: Command line arguments
  2425. """
  2426. parser = argparse.ArgumentParser()
  2427. parser.add_argument("paths", nargs="+", help="Paths to check")
  2428. parsed_args = parser.parse_args(args)
  2429. ret = 1
  2430. for path in porcelain.check_ignore(".", parsed_args.paths):
  2431. logger.info(path)
  2432. ret = 0
  2433. return ret
  2434. class cmd_check_mailmap(Command):
  2435. """Show canonical names and email addresses of contacts."""
  2436. def run(self, args: Sequence[str]) -> None:
  2437. """Execute the check-mailmap command.
  2438. Args:
  2439. args: Command line arguments
  2440. """
  2441. parser = argparse.ArgumentParser()
  2442. parser.add_argument("identities", nargs="+", help="Identities to check")
  2443. parsed_args = parser.parse_args(args)
  2444. for identity in parsed_args.identities:
  2445. canonical_identity = porcelain.check_mailmap(".", identity)
  2446. logger.info(canonical_identity)
  2447. class cmd_branch(Command):
  2448. """List, create, or delete branches."""
  2449. def run(self, args: Sequence[str]) -> Optional[int]:
  2450. """Execute the branch command.
  2451. Args:
  2452. args: Command line arguments
  2453. """
  2454. parser = argparse.ArgumentParser()
  2455. parser.add_argument(
  2456. "branch",
  2457. type=str,
  2458. nargs="?",
  2459. help="Name of the branch",
  2460. )
  2461. parser.add_argument(
  2462. "-d",
  2463. "--delete",
  2464. action="store_true",
  2465. help="Delete branch",
  2466. )
  2467. parser.add_argument("--all", action="store_true", help="List all branches")
  2468. parser.add_argument(
  2469. "--merged", action="store_true", help="List merged into current branch"
  2470. )
  2471. parser.add_argument(
  2472. "--no-merged",
  2473. action="store_true",
  2474. help="List branches not merged into current branch",
  2475. )
  2476. parser.add_argument(
  2477. "--remotes", action="store_true", help="List remotes branches"
  2478. )
  2479. parser.add_argument(
  2480. "--contains",
  2481. nargs="?",
  2482. const="HEAD",
  2483. help="List branches that contain a specific commit",
  2484. )
  2485. parser.add_argument(
  2486. "--column", action="store_true", help="Display branch list in columns"
  2487. )
  2488. parser.add_argument(
  2489. "--list",
  2490. nargs="?",
  2491. const=None,
  2492. help="List branches matching a pattern",
  2493. )
  2494. parsed_args = parser.parse_args(args)
  2495. def print_branches(
  2496. branches: Union[Iterator[bytes], Sequence[bytes]], use_columns: bool = False
  2497. ) -> None:
  2498. if use_columns:
  2499. write_columns(branches, sys.stdout)
  2500. else:
  2501. for branch in branches:
  2502. sys.stdout.write(f"{branch.decode()}\n")
  2503. branches: Union[Iterator[bytes], list[bytes], None] = None
  2504. try:
  2505. if parsed_args.all:
  2506. branches = porcelain.branch_list(".") + porcelain.branch_remotes_list(
  2507. "."
  2508. )
  2509. elif parsed_args.remotes:
  2510. branches = porcelain.branch_remotes_list(".")
  2511. elif parsed_args.merged:
  2512. branches = porcelain.merged_branches(".")
  2513. elif parsed_args.no_merged:
  2514. branches = porcelain.no_merged_branches(".")
  2515. elif parsed_args.contains:
  2516. try:
  2517. branches = list(
  2518. porcelain.branches_containing(".", commit=parsed_args.contains)
  2519. )
  2520. except KeyError as e:
  2521. sys.stderr.write(
  2522. f"error: object name {e.args[0].decode()} not found\n"
  2523. )
  2524. return 1
  2525. except porcelain.Error as e:
  2526. sys.stderr.write(f"{e}")
  2527. return 1
  2528. pattern = parsed_args.list
  2529. if pattern is not None and branches:
  2530. branches = porcelain.filter_branches_by_pattern(branches, pattern)
  2531. if branches is not None:
  2532. print_branches(branches, parsed_args.column)
  2533. return 0
  2534. if not parsed_args.branch:
  2535. logger.error("Usage: dulwich branch [-d] BRANCH_NAME")
  2536. return 1
  2537. if parsed_args.delete:
  2538. porcelain.branch_delete(".", name=parsed_args.branch)
  2539. else:
  2540. try:
  2541. porcelain.branch_create(".", name=parsed_args.branch)
  2542. except porcelain.Error as e:
  2543. sys.stderr.write(f"{e}")
  2544. return 1
  2545. return 0
  2546. class cmd_checkout(Command):
  2547. """Switch branches or restore working tree files."""
  2548. def run(self, args: Sequence[str]) -> Optional[int]:
  2549. """Execute the checkout command.
  2550. Args:
  2551. args: Command line arguments
  2552. """
  2553. parser = argparse.ArgumentParser()
  2554. parser.add_argument(
  2555. "target",
  2556. type=str,
  2557. help="Name of the branch, tag, or commit to checkout",
  2558. )
  2559. parser.add_argument(
  2560. "-f",
  2561. "--force",
  2562. action="store_true",
  2563. help="Force checkout",
  2564. )
  2565. parser.add_argument(
  2566. "-b",
  2567. "--new-branch",
  2568. type=str,
  2569. help="Create a new branch at the target and switch to it",
  2570. )
  2571. parsed_args = parser.parse_args(args)
  2572. if not parsed_args.target:
  2573. logger.error("Usage: dulwich checkout TARGET [--force] [-b NEW_BRANCH]")
  2574. return 1
  2575. try:
  2576. porcelain.checkout(
  2577. ".",
  2578. target=parsed_args.target,
  2579. force=parsed_args.force,
  2580. new_branch=parsed_args.new_branch,
  2581. )
  2582. except porcelain.CheckoutError as e:
  2583. sys.stderr.write(f"{e}\n")
  2584. return 1
  2585. return 0
  2586. class cmd_stash_list(Command):
  2587. """List stash entries."""
  2588. def run(self, args: Sequence[str]) -> None:
  2589. """Execute the stash-list command.
  2590. Args:
  2591. args: Command line arguments
  2592. """
  2593. parser = argparse.ArgumentParser()
  2594. parser.parse_args(args)
  2595. from .repo import Repo
  2596. from .stash import Stash
  2597. with Repo(".") as r:
  2598. stash = Stash.from_repo(r)
  2599. for i, entry in enumerate(stash.stashes()):
  2600. logger.info(
  2601. "stash@{%d}: %s",
  2602. i,
  2603. entry.message.decode("utf-8", "replace").rstrip("\n"),
  2604. )
  2605. class cmd_stash_push(Command):
  2606. """Save your local modifications to a new stash."""
  2607. def run(self, args: Sequence[str]) -> None:
  2608. """Execute the stash-push command.
  2609. Args:
  2610. args: Command line arguments
  2611. """
  2612. parser = argparse.ArgumentParser()
  2613. parser.parse_args(args)
  2614. porcelain.stash_push(".")
  2615. logger.info("Saved working directory and index state")
  2616. class cmd_stash_pop(Command):
  2617. """Apply a stash and remove it from the stash list."""
  2618. def run(self, args: Sequence[str]) -> None:
  2619. """Execute the stash-pop command.
  2620. Args:
  2621. args: Command line arguments
  2622. """
  2623. parser = argparse.ArgumentParser()
  2624. parser.parse_args(args)
  2625. porcelain.stash_pop(".")
  2626. logger.info("Restored working directory and index state")
  2627. class cmd_bisect(SuperCommand):
  2628. """Use binary search to find the commit that introduced a bug."""
  2629. subcommands: ClassVar[dict[str, type[Command]]] = {}
  2630. def run(self, args: Sequence[str]) -> Optional[int]:
  2631. """Execute the bisect command.
  2632. Args:
  2633. args: Command line arguments
  2634. """
  2635. parser = argparse.ArgumentParser(prog="dulwich bisect")
  2636. subparsers = parser.add_subparsers(dest="subcommand", help="bisect subcommands")
  2637. # bisect start
  2638. start_parser = subparsers.add_parser("start", help="Start a new bisect session")
  2639. start_parser.add_argument("bad", nargs="?", help="Bad commit")
  2640. start_parser.add_argument("good", nargs="*", help="Good commit(s)")
  2641. start_parser.add_argument(
  2642. "--no-checkout",
  2643. action="store_true",
  2644. help="Don't checkout commits during bisect",
  2645. )
  2646. start_parser.add_argument(
  2647. "--term-bad", default="bad", help="Term to use for bad commits"
  2648. )
  2649. start_parser.add_argument(
  2650. "--term-good", default="good", help="Term to use for good commits"
  2651. )
  2652. start_parser.add_argument(
  2653. "--", dest="paths", nargs="*", help="Paths to limit bisect to"
  2654. )
  2655. # bisect bad
  2656. bad_parser = subparsers.add_parser("bad", help="Mark a commit as bad")
  2657. bad_parser.add_argument("rev", nargs="?", help="Commit to mark as bad")
  2658. # bisect good
  2659. good_parser = subparsers.add_parser("good", help="Mark a commit as good")
  2660. good_parser.add_argument("rev", nargs="?", help="Commit to mark as good")
  2661. # bisect skip
  2662. skip_parser = subparsers.add_parser("skip", help="Skip commits")
  2663. skip_parser.add_argument("revs", nargs="*", help="Commits to skip")
  2664. # bisect reset
  2665. reset_parser = subparsers.add_parser("reset", help="Reset bisect state")
  2666. reset_parser.add_argument("commit", nargs="?", help="Commit to reset to")
  2667. # bisect log
  2668. subparsers.add_parser("log", help="Show bisect log")
  2669. # bisect replay
  2670. replay_parser = subparsers.add_parser("replay", help="Replay bisect log")
  2671. replay_parser.add_argument("logfile", help="Log file to replay")
  2672. # bisect help
  2673. subparsers.add_parser("help", help="Show help")
  2674. parsed_args = parser.parse_args(args)
  2675. if not parsed_args.subcommand:
  2676. parser.print_help()
  2677. return 1
  2678. try:
  2679. if parsed_args.subcommand == "start":
  2680. next_sha = porcelain.bisect_start(
  2681. bad=parsed_args.bad,
  2682. good=parsed_args.good if parsed_args.good else None,
  2683. paths=parsed_args.paths,
  2684. no_checkout=parsed_args.no_checkout,
  2685. term_bad=parsed_args.term_bad,
  2686. term_good=parsed_args.term_good,
  2687. )
  2688. if next_sha:
  2689. logger.info(
  2690. "Bisecting: checking out '%s'", next_sha.decode("ascii")
  2691. )
  2692. elif parsed_args.subcommand == "bad":
  2693. next_sha = porcelain.bisect_bad(rev=parsed_args.rev)
  2694. if next_sha:
  2695. logger.info(
  2696. "Bisecting: checking out '%s'", next_sha.decode("ascii")
  2697. )
  2698. else:
  2699. # Bisect complete - find the first bad commit
  2700. with porcelain.open_repo_closing(".") as r:
  2701. bad_ref = os.path.join(r.controldir(), "refs", "bisect", "bad")
  2702. with open(bad_ref, "rb") as f:
  2703. bad_sha = f.read().strip()
  2704. commit = r.object_store[bad_sha]
  2705. assert isinstance(commit, Commit)
  2706. message = commit.message.decode(
  2707. "utf-8", errors="replace"
  2708. ).split("\n")[0]
  2709. logger.info(
  2710. "%s is the first bad commit", bad_sha.decode("ascii")
  2711. )
  2712. logger.info("commit %s", bad_sha.decode("ascii"))
  2713. logger.info(" %s", message)
  2714. elif parsed_args.subcommand == "good":
  2715. next_sha = porcelain.bisect_good(rev=parsed_args.rev)
  2716. if next_sha:
  2717. logger.info(
  2718. "Bisecting: checking out '%s'", next_sha.decode("ascii")
  2719. )
  2720. elif parsed_args.subcommand == "skip":
  2721. next_sha = porcelain.bisect_skip(
  2722. revs=parsed_args.revs if parsed_args.revs else None
  2723. )
  2724. if next_sha:
  2725. logger.info(
  2726. "Bisecting: checking out '%s'", next_sha.decode("ascii")
  2727. )
  2728. elif parsed_args.subcommand == "reset":
  2729. porcelain.bisect_reset(commit=parsed_args.commit)
  2730. logger.info("Bisect reset")
  2731. elif parsed_args.subcommand == "log":
  2732. log = porcelain.bisect_log()
  2733. logger.info(log.rstrip())
  2734. elif parsed_args.subcommand == "replay":
  2735. porcelain.bisect_replay(".", log_file=parsed_args.logfile)
  2736. logger.info("Replayed bisect log from %s", parsed_args.logfile)
  2737. elif parsed_args.subcommand == "help":
  2738. parser.print_help()
  2739. except porcelain.Error as e:
  2740. logger.error("%s", e)
  2741. return 1
  2742. except ValueError as e:
  2743. logger.error("%s", e)
  2744. return 1
  2745. return 0
  2746. class cmd_stash(SuperCommand):
  2747. """Stash the changes in a dirty working directory away."""
  2748. subcommands: ClassVar[dict[str, type[Command]]] = {
  2749. "list": cmd_stash_list,
  2750. "pop": cmd_stash_pop,
  2751. "push": cmd_stash_push,
  2752. }
  2753. class cmd_ls_files(Command):
  2754. """Show information about files in the index and working tree."""
  2755. def run(self, args: Sequence[str]) -> None:
  2756. """Execute the ls-files command.
  2757. Args:
  2758. args: Command line arguments
  2759. """
  2760. parser = argparse.ArgumentParser()
  2761. parser.parse_args(args)
  2762. for name in porcelain.ls_files("."):
  2763. logger.info(name)
  2764. class cmd_describe(Command):
  2765. """Give an object a human readable name based on an available ref."""
  2766. def run(self, args: Sequence[str]) -> None:
  2767. """Execute the describe command.
  2768. Args:
  2769. args: Command line arguments
  2770. """
  2771. parser = argparse.ArgumentParser()
  2772. parser.parse_args(args)
  2773. logger.info(porcelain.describe("."))
  2774. class cmd_merge(Command):
  2775. """Join two or more development histories together."""
  2776. def run(self, args: Sequence[str]) -> Optional[int]:
  2777. """Execute the merge command.
  2778. Args:
  2779. args: Command line arguments
  2780. """
  2781. parser = argparse.ArgumentParser()
  2782. parser.add_argument("commit", type=str, nargs="+", help="Commit(s) to merge")
  2783. parser.add_argument(
  2784. "--no-commit", action="store_true", help="Do not create a merge commit"
  2785. )
  2786. parser.add_argument(
  2787. "--no-ff", action="store_true", help="Force create a merge commit"
  2788. )
  2789. parser.add_argument("-m", "--message", type=str, help="Merge commit message")
  2790. parsed_args = parser.parse_args(args)
  2791. try:
  2792. # If multiple commits are provided, pass them as a list
  2793. # If only one commit is provided, pass it as a string
  2794. if len(parsed_args.commit) == 1:
  2795. committish = parsed_args.commit[0]
  2796. else:
  2797. committish = parsed_args.commit
  2798. merge_commit_id, conflicts = porcelain.merge(
  2799. ".",
  2800. committish,
  2801. no_commit=parsed_args.no_commit,
  2802. no_ff=parsed_args.no_ff,
  2803. message=parsed_args.message,
  2804. )
  2805. if conflicts:
  2806. logger.warning("Merge conflicts in %d file(s):", len(conflicts))
  2807. for conflict_path in conflicts:
  2808. logger.warning(" %s", conflict_path.decode())
  2809. if len(parsed_args.commit) > 1:
  2810. logger.error(
  2811. "Octopus merge failed; refusing to merge with conflicts."
  2812. )
  2813. else:
  2814. logger.error(
  2815. "Automatic merge failed; fix conflicts and then commit the result."
  2816. )
  2817. return 1
  2818. elif merge_commit_id is None and not parsed_args.no_commit:
  2819. logger.info("Already up to date.")
  2820. elif parsed_args.no_commit:
  2821. logger.info("Automatic merge successful; not committing as requested.")
  2822. else:
  2823. assert merge_commit_id is not None
  2824. if len(parsed_args.commit) > 1:
  2825. logger.info(
  2826. "Octopus merge successful. Created merge commit %s",
  2827. merge_commit_id.decode(),
  2828. )
  2829. else:
  2830. logger.info(
  2831. "Merge successful. Created merge commit %s",
  2832. merge_commit_id.decode(),
  2833. )
  2834. return 0
  2835. except porcelain.Error as e:
  2836. logger.error("%s", e)
  2837. return 1
  2838. class cmd_merge_base(Command):
  2839. """Find the best common ancestor between commits."""
  2840. def run(self, args: Sequence[str]) -> Optional[int]:
  2841. """Execute the merge-base command.
  2842. Args:
  2843. args: Command line arguments
  2844. """
  2845. parser = argparse.ArgumentParser(
  2846. description="Find the best common ancestor between commits",
  2847. prog="dulwich merge-base",
  2848. )
  2849. parser.add_argument("commits", nargs="+", help="Commits to find merge base for")
  2850. parser.add_argument("--all", action="store_true", help="Output all merge bases")
  2851. parser.add_argument(
  2852. "--octopus",
  2853. action="store_true",
  2854. help="Compute common ancestor of all commits",
  2855. )
  2856. parser.add_argument(
  2857. "--is-ancestor",
  2858. action="store_true",
  2859. help="Check if first commit is ancestor of second",
  2860. )
  2861. parser.add_argument(
  2862. "--independent",
  2863. action="store_true",
  2864. help="List commits not reachable from others",
  2865. )
  2866. parsed_args = parser.parse_args(args)
  2867. try:
  2868. if parsed_args.is_ancestor:
  2869. if len(parsed_args.commits) != 2:
  2870. logger.error("--is-ancestor requires exactly two commits")
  2871. return 1
  2872. is_anc = porcelain.is_ancestor(
  2873. ".",
  2874. ancestor=parsed_args.commits[0],
  2875. descendant=parsed_args.commits[1],
  2876. )
  2877. return 0 if is_anc else 1
  2878. elif parsed_args.independent:
  2879. commits = porcelain.independent_commits(".", parsed_args.commits)
  2880. for commit_id in commits:
  2881. print(commit_id.decode())
  2882. return 0
  2883. else:
  2884. if len(parsed_args.commits) < 2:
  2885. logger.error("At least two commits are required")
  2886. return 1
  2887. merge_bases = porcelain.merge_base(
  2888. ".",
  2889. parsed_args.commits,
  2890. all=parsed_args.all,
  2891. octopus=parsed_args.octopus,
  2892. )
  2893. for commit_id in merge_bases:
  2894. print(commit_id.decode())
  2895. return 0
  2896. except (ValueError, KeyError) as e:
  2897. logger.error("%s", e)
  2898. return 1
  2899. class cmd_notes_add(Command):
  2900. """Add notes to a commit."""
  2901. def run(self, args: Sequence[str]) -> None:
  2902. """Execute the notes-add command.
  2903. Args:
  2904. args: Command line arguments
  2905. """
  2906. parser = argparse.ArgumentParser()
  2907. parser.add_argument("object", help="Object to annotate")
  2908. parser.add_argument("-m", "--message", help="Note message", required=True)
  2909. parser.add_argument(
  2910. "--ref", default="commits", help="Notes ref (default: commits)"
  2911. )
  2912. parsed_args = parser.parse_args(args)
  2913. porcelain.notes_add(
  2914. ".", parsed_args.object, parsed_args.message, ref=parsed_args.ref
  2915. )
  2916. class cmd_notes_show(Command):
  2917. """Show notes for a commit."""
  2918. def run(self, args: Sequence[str]) -> None:
  2919. """Execute the notes-show command.
  2920. Args:
  2921. args: Command line arguments
  2922. """
  2923. parser = argparse.ArgumentParser()
  2924. parser.add_argument("object", help="Object to show notes for")
  2925. parser.add_argument(
  2926. "--ref", default="commits", help="Notes ref (default: commits)"
  2927. )
  2928. parsed_args = parser.parse_args(args)
  2929. note = porcelain.notes_show(".", parsed_args.object, ref=parsed_args.ref)
  2930. if note:
  2931. sys.stdout.buffer.write(note)
  2932. else:
  2933. logger.info("No notes found for object %s", parsed_args.object)
  2934. class cmd_notes_remove(Command):
  2935. """Remove notes for a commit."""
  2936. def run(self, args: Sequence[str]) -> None:
  2937. """Execute the notes-remove command.
  2938. Args:
  2939. args: Command line arguments
  2940. """
  2941. parser = argparse.ArgumentParser()
  2942. parser.add_argument("object", help="Object to remove notes from")
  2943. parser.add_argument(
  2944. "--ref", default="commits", help="Notes ref (default: commits)"
  2945. )
  2946. parsed_args = parser.parse_args(args)
  2947. result = porcelain.notes_remove(".", parsed_args.object, ref=parsed_args.ref)
  2948. if result:
  2949. logger.info("Removed notes for object %s", parsed_args.object)
  2950. else:
  2951. logger.info("No notes found for object %s", parsed_args.object)
  2952. class cmd_notes_list(Command):
  2953. """List all note objects."""
  2954. def run(self, args: Sequence[str]) -> None:
  2955. """Execute the notes-list command.
  2956. Args:
  2957. args: Command line arguments
  2958. """
  2959. parser = argparse.ArgumentParser()
  2960. parser.add_argument(
  2961. "--ref", default="commits", help="Notes ref (default: commits)"
  2962. )
  2963. parsed_args = parser.parse_args(args)
  2964. notes = porcelain.notes_list(".", ref=parsed_args.ref)
  2965. for object_sha, note_content in notes:
  2966. logger.info(object_sha.hex())
  2967. class cmd_notes(SuperCommand):
  2968. """Add or inspect object notes."""
  2969. subcommands: ClassVar[dict[str, type[Command]]] = {
  2970. "add": cmd_notes_add,
  2971. "show": cmd_notes_show,
  2972. "remove": cmd_notes_remove,
  2973. "list": cmd_notes_list,
  2974. }
  2975. default_command = cmd_notes_list
  2976. class cmd_cherry(Command):
  2977. """Find commits not merged upstream."""
  2978. def run(self, args: Sequence[str]) -> Optional[int]:
  2979. """Execute the cherry command.
  2980. Args:
  2981. args: Command line arguments
  2982. Returns:
  2983. Exit code (0 for success, 1 for error)
  2984. """
  2985. parser = argparse.ArgumentParser(description="Find commits not merged upstream")
  2986. parser.add_argument(
  2987. "-v",
  2988. "--verbose",
  2989. action="store_true",
  2990. help="Show commit messages",
  2991. )
  2992. parser.add_argument(
  2993. "upstream",
  2994. nargs="?",
  2995. help="Upstream branch (default: tracking branch or HEAD^)",
  2996. )
  2997. parser.add_argument(
  2998. "head",
  2999. nargs="?",
  3000. help="Head branch (default: HEAD)",
  3001. )
  3002. parser.add_argument(
  3003. "limit",
  3004. nargs="?",
  3005. help="Limit commits to those after this ref",
  3006. )
  3007. parsed_args = parser.parse_args(args)
  3008. try:
  3009. results = porcelain.cherry(
  3010. ".",
  3011. upstream=parsed_args.upstream,
  3012. head=parsed_args.head,
  3013. limit=parsed_args.limit,
  3014. verbose=parsed_args.verbose,
  3015. )
  3016. except (NotGitRepository, OSError, FileFormatException, ValueError) as e:
  3017. logger.error(f"Error: {e}")
  3018. return 1
  3019. # Output results
  3020. for status, commit_sha, message in results:
  3021. # Convert commit_sha to hex string
  3022. if isinstance(commit_sha, bytes):
  3023. commit_hex = commit_sha.hex()
  3024. else:
  3025. commit_hex = commit_sha
  3026. if parsed_args.verbose and message:
  3027. message_str = message.decode("utf-8", errors="replace")
  3028. logger.info(f"{status} {commit_hex} {message_str}")
  3029. else:
  3030. logger.info(f"{status} {commit_hex}")
  3031. return 0
  3032. class cmd_cherry_pick(Command):
  3033. """Apply the changes introduced by some existing commits."""
  3034. def run(self, args: Sequence[str]) -> Optional[int]:
  3035. """Execute the cherry-pick command.
  3036. Args:
  3037. args: Command line arguments
  3038. """
  3039. parser = argparse.ArgumentParser(
  3040. description="Apply the changes introduced by some existing commits"
  3041. )
  3042. parser.add_argument("commit", nargs="?", help="Commit to cherry-pick")
  3043. parser.add_argument(
  3044. "-n",
  3045. "--no-commit",
  3046. action="store_true",
  3047. help="Apply changes without making a commit",
  3048. )
  3049. parser.add_argument(
  3050. "--continue",
  3051. dest="continue_",
  3052. action="store_true",
  3053. help="Continue after resolving conflicts",
  3054. )
  3055. parser.add_argument(
  3056. "--abort",
  3057. action="store_true",
  3058. help="Abort the current cherry-pick operation",
  3059. )
  3060. parsed_args = parser.parse_args(args)
  3061. # Check argument validity
  3062. if parsed_args.continue_ or parsed_args.abort:
  3063. if parsed_args.commit is not None:
  3064. parser.error("Cannot specify commit with --continue or --abort")
  3065. return 1
  3066. else:
  3067. if parsed_args.commit is None:
  3068. parser.error("Commit argument is required")
  3069. return 1
  3070. try:
  3071. commit_arg = parsed_args.commit
  3072. result = porcelain.cherry_pick(
  3073. ".",
  3074. commit_arg,
  3075. no_commit=parsed_args.no_commit,
  3076. continue_=parsed_args.continue_,
  3077. abort=parsed_args.abort,
  3078. )
  3079. if parsed_args.abort:
  3080. logger.info("Cherry-pick aborted.")
  3081. elif parsed_args.continue_:
  3082. if result:
  3083. logger.info("Cherry-pick completed: %s", result.decode())
  3084. else:
  3085. logger.info("Cherry-pick completed.")
  3086. elif result is None:
  3087. if parsed_args.no_commit:
  3088. logger.info("Cherry-pick applied successfully (no commit created).")
  3089. else:
  3090. # This shouldn't happen unless there were conflicts
  3091. logger.warning("Cherry-pick resulted in conflicts.")
  3092. else:
  3093. logger.info("Cherry-pick successful: %s", result.decode())
  3094. return None
  3095. except porcelain.Error as e:
  3096. logger.error("%s", e)
  3097. return 1
  3098. class cmd_merge_tree(Command):
  3099. """Show three-way merge without touching index."""
  3100. def run(self, args: Sequence[str]) -> Optional[int]:
  3101. """Execute the merge-tree command.
  3102. Args:
  3103. args: Command line arguments
  3104. """
  3105. parser = argparse.ArgumentParser(
  3106. description="Perform a tree-level merge without touching the working directory"
  3107. )
  3108. parser.add_argument(
  3109. "base_tree",
  3110. nargs="?",
  3111. help="The common ancestor tree (optional, defaults to empty tree)",
  3112. )
  3113. parser.add_argument("our_tree", help="Our side of the merge")
  3114. parser.add_argument("their_tree", help="Their side of the merge")
  3115. parser.add_argument(
  3116. "-z",
  3117. "--name-only",
  3118. action="store_true",
  3119. help="Output only conflict paths, null-terminated",
  3120. )
  3121. parsed_args = parser.parse_args(args)
  3122. try:
  3123. # Determine base tree - if only two parsed_args provided, base is None
  3124. if parsed_args.base_tree is None:
  3125. # Only two arguments provided
  3126. base_tree = None
  3127. our_tree = parsed_args.our_tree
  3128. their_tree = parsed_args.their_tree
  3129. else:
  3130. # Three arguments provided
  3131. base_tree = parsed_args.base_tree
  3132. our_tree = parsed_args.our_tree
  3133. their_tree = parsed_args.their_tree
  3134. merged_tree_id, conflicts = porcelain.merge_tree(
  3135. ".", base_tree, our_tree, their_tree
  3136. )
  3137. if parsed_args.name_only:
  3138. # Output only conflict paths, null-terminated
  3139. for conflict_path in conflicts:
  3140. sys.stdout.buffer.write(conflict_path)
  3141. sys.stdout.buffer.write(b"\0")
  3142. else:
  3143. # Output the merged tree SHA
  3144. logger.info(merged_tree_id.decode("ascii"))
  3145. # Output conflict information
  3146. if conflicts:
  3147. logger.warning("\nConflicts in %d file(s):", len(conflicts))
  3148. for conflict_path in conflicts:
  3149. logger.warning(" %s", conflict_path.decode())
  3150. return None
  3151. except porcelain.Error as e:
  3152. logger.error("%s", e)
  3153. return 1
  3154. except KeyError as e:
  3155. logger.error("Object not found: %s", e)
  3156. return 1
  3157. class cmd_gc(Command):
  3158. """Cleanup unnecessary files and optimize the local repository."""
  3159. def run(self, args: Sequence[str]) -> Optional[int]:
  3160. """Execute the gc command.
  3161. Args:
  3162. args: Command line arguments
  3163. """
  3164. import datetime
  3165. import time
  3166. parser = argparse.ArgumentParser()
  3167. parser.add_argument(
  3168. "--auto",
  3169. action="store_true",
  3170. help="Only run gc if needed",
  3171. )
  3172. parser.add_argument(
  3173. "--aggressive",
  3174. action="store_true",
  3175. help="Use more aggressive settings",
  3176. )
  3177. parser.add_argument(
  3178. "--no-prune",
  3179. action="store_true",
  3180. help="Do not prune unreachable objects",
  3181. )
  3182. parser.add_argument(
  3183. "--prune",
  3184. nargs="?",
  3185. const="now",
  3186. help="Prune unreachable objects older than date (default: 2 weeks ago)",
  3187. )
  3188. parser.add_argument(
  3189. "--dry-run",
  3190. "-n",
  3191. action="store_true",
  3192. help="Only report what would be done",
  3193. )
  3194. parser.add_argument(
  3195. "--quiet",
  3196. "-q",
  3197. action="store_true",
  3198. help="Only report errors",
  3199. )
  3200. parsed_args = parser.parse_args(args)
  3201. # Parse prune grace period
  3202. grace_period = None
  3203. if parsed_args.prune:
  3204. try:
  3205. grace_period = parse_relative_time(parsed_args.prune)
  3206. except ValueError:
  3207. # Try to parse as absolute date
  3208. try:
  3209. date = datetime.datetime.strptime(parsed_args.prune, "%Y-%m-%d")
  3210. grace_period = int(time.time() - date.timestamp())
  3211. except ValueError:
  3212. logger.error("Invalid prune date: %s", parsed_args.prune)
  3213. return 1
  3214. elif not parsed_args.no_prune:
  3215. # Default to 2 weeks
  3216. grace_period = 1209600
  3217. # Progress callback
  3218. def progress(msg: str) -> None:
  3219. if not parsed_args.quiet:
  3220. logger.info(msg)
  3221. try:
  3222. stats = porcelain.gc(
  3223. ".",
  3224. auto=parsed_args.auto,
  3225. aggressive=parsed_args.aggressive,
  3226. prune=not parsed_args.no_prune,
  3227. grace_period=grace_period,
  3228. dry_run=parsed_args.dry_run,
  3229. progress=progress if not parsed_args.quiet else None,
  3230. )
  3231. # Report results
  3232. if not parsed_args.quiet:
  3233. if parsed_args.dry_run:
  3234. logger.info("\nDry run results:")
  3235. if not parsed_args.quiet:
  3236. if parsed_args.dry_run:
  3237. print("\nDry run results:")
  3238. else:
  3239. logger.info("\nGarbage collection complete:")
  3240. if stats.pruned_objects:
  3241. logger.info(
  3242. " Pruned %d unreachable objects", len(stats.pruned_objects)
  3243. )
  3244. logger.info(" Freed %s", format_bytes(stats.bytes_freed))
  3245. if stats.packs_before != stats.packs_after:
  3246. logger.info(
  3247. " Reduced pack files from %d to %d",
  3248. stats.packs_before,
  3249. stats.packs_after,
  3250. )
  3251. except porcelain.Error as e:
  3252. logger.error("%s", e)
  3253. return 1
  3254. return None
  3255. class cmd_count_objects(Command):
  3256. """Count unpacked number of objects and their disk consumption."""
  3257. def run(self, args: Sequence[str]) -> None:
  3258. """Execute the count-objects command.
  3259. Args:
  3260. args: Command line arguments
  3261. """
  3262. parser = argparse.ArgumentParser()
  3263. parser.add_argument(
  3264. "-v",
  3265. "--verbose",
  3266. action="store_true",
  3267. help="Display verbose information.",
  3268. )
  3269. parsed_args = parser.parse_args(args)
  3270. if parsed_args.verbose:
  3271. stats = porcelain.count_objects(".", verbose=True)
  3272. # Display verbose output
  3273. logger.info("count: %d", stats.count)
  3274. logger.info("size: %d", stats.size // 1024) # Size in KiB
  3275. assert stats.in_pack is not None
  3276. logger.info("in-pack: %d", stats.in_pack)
  3277. assert stats.packs is not None
  3278. logger.info("packs: %d", stats.packs)
  3279. assert stats.size_pack is not None
  3280. logger.info("size-pack: %d", stats.size_pack // 1024) # Size in KiB
  3281. else:
  3282. # Simple output
  3283. stats = porcelain.count_objects(".", verbose=False)
  3284. logger.info("%d objects, %d kilobytes", stats.count, stats.size // 1024)
  3285. class cmd_rebase(Command):
  3286. """Reapply commits on top of another base tip."""
  3287. def run(self, args: Sequence[str]) -> int:
  3288. """Execute the rebase command.
  3289. Args:
  3290. args: Command line arguments
  3291. """
  3292. parser = argparse.ArgumentParser()
  3293. parser.add_argument(
  3294. "upstream", nargs="?", help="Upstream branch to rebase onto"
  3295. )
  3296. parser.add_argument("--onto", type=str, help="Rebase onto specific commit")
  3297. parser.add_argument(
  3298. "--branch", type=str, help="Branch to rebase (default: current)"
  3299. )
  3300. parser.add_argument(
  3301. "-i", "--interactive", action="store_true", help="Interactive rebase"
  3302. )
  3303. parser.add_argument(
  3304. "--edit-todo",
  3305. action="store_true",
  3306. help="Edit the todo list during an interactive rebase",
  3307. )
  3308. parser.add_argument(
  3309. "--abort", action="store_true", help="Abort an in-progress rebase"
  3310. )
  3311. parser.add_argument(
  3312. "--continue",
  3313. dest="continue_rebase",
  3314. action="store_true",
  3315. help="Continue an in-progress rebase",
  3316. )
  3317. parser.add_argument(
  3318. "--skip", action="store_true", help="Skip current commit and continue"
  3319. )
  3320. parsed_args = parser.parse_args(args)
  3321. # Handle abort/continue/skip first
  3322. if parsed_args.abort:
  3323. try:
  3324. porcelain.rebase(".", parsed_args.upstream or "HEAD", abort=True)
  3325. logger.info("Rebase aborted.")
  3326. except porcelain.Error as e:
  3327. logger.error("%s", e)
  3328. return 1
  3329. return 0
  3330. if parsed_args.continue_rebase:
  3331. try:
  3332. # Check if interactive rebase is in progress
  3333. if porcelain.is_interactive_rebase("."):
  3334. result = porcelain.rebase(
  3335. ".",
  3336. parsed_args.upstream or "HEAD",
  3337. continue_rebase=True,
  3338. interactive=True,
  3339. )
  3340. if result:
  3341. logger.info("Rebase complete.")
  3342. else:
  3343. logger.info("Rebase paused. Use --continue to resume.")
  3344. else:
  3345. new_shas = porcelain.rebase(
  3346. ".", parsed_args.upstream or "HEAD", continue_rebase=True
  3347. )
  3348. logger.info("Rebase complete.")
  3349. except porcelain.Error as e:
  3350. logger.error("%s", e)
  3351. return 1
  3352. return 0
  3353. if parsed_args.edit_todo:
  3354. # Edit todo list for interactive rebase
  3355. try:
  3356. porcelain.rebase(".", parsed_args.upstream or "HEAD", edit_todo=True)
  3357. logger.info("Todo list updated.")
  3358. except porcelain.Error as e:
  3359. logger.error("%s", e)
  3360. return 1
  3361. return 0
  3362. # Normal rebase requires upstream
  3363. if not parsed_args.upstream:
  3364. logger.error("Missing required argument 'upstream'")
  3365. return 1
  3366. try:
  3367. if parsed_args.interactive:
  3368. # Interactive rebase
  3369. result = porcelain.rebase(
  3370. ".",
  3371. parsed_args.upstream,
  3372. onto=parsed_args.onto,
  3373. branch=parsed_args.branch,
  3374. interactive=True,
  3375. )
  3376. if result:
  3377. logger.info(
  3378. "Interactive rebase started. Edit the todo list and save."
  3379. )
  3380. else:
  3381. logger.info("No commits to rebase.")
  3382. else:
  3383. # Regular rebase
  3384. new_shas = porcelain.rebase(
  3385. ".",
  3386. parsed_args.upstream,
  3387. onto=parsed_args.onto,
  3388. branch=parsed_args.branch,
  3389. )
  3390. if new_shas:
  3391. logger.info("Successfully rebased %d commits.", len(new_shas))
  3392. else:
  3393. logger.info("Already up to date.")
  3394. return 0
  3395. except porcelain.Error as e:
  3396. logger.error("%s", e)
  3397. return 1
  3398. class cmd_filter_branch(Command):
  3399. """Rewrite branches."""
  3400. def run(self, args: Sequence[str]) -> Optional[int]:
  3401. """Execute the filter-branch command.
  3402. Args:
  3403. args: Command line arguments
  3404. """
  3405. import subprocess
  3406. parser = argparse.ArgumentParser(description="Rewrite branches")
  3407. # Supported Git-compatible options
  3408. parser.add_argument(
  3409. "--subdirectory-filter",
  3410. type=str,
  3411. help="Only include history for subdirectory",
  3412. )
  3413. parser.add_argument("--env-filter", type=str, help="Environment filter command")
  3414. parser.add_argument("--tree-filter", type=str, help="Tree filter command")
  3415. parser.add_argument("--index-filter", type=str, help="Index filter command")
  3416. parser.add_argument("--parent-filter", type=str, help="Parent filter command")
  3417. parser.add_argument("--msg-filter", type=str, help="Message filter command")
  3418. parser.add_argument("--commit-filter", type=str, help="Commit filter command")
  3419. parser.add_argument(
  3420. "--tag-name-filter", type=str, help="Tag name filter command"
  3421. )
  3422. parser.add_argument(
  3423. "--prune-empty", action="store_true", help="Remove empty commits"
  3424. )
  3425. parser.add_argument(
  3426. "--original",
  3427. type=str,
  3428. default="refs/original",
  3429. help="Namespace for original refs",
  3430. )
  3431. parser.add_argument(
  3432. "-f",
  3433. "--force",
  3434. action="store_true",
  3435. help="Force operation even if refs/original/* exists",
  3436. )
  3437. # Branch/ref to rewrite (defaults to HEAD)
  3438. parser.add_argument(
  3439. "branch", nargs="?", default="HEAD", help="Branch or ref to rewrite"
  3440. )
  3441. parsed_args = parser.parse_args(args)
  3442. # Track if any filter fails
  3443. filter_error = False
  3444. # Setup environment for filters
  3445. env = os.environ.copy()
  3446. # Helper function to run shell commands
  3447. def run_filter(
  3448. cmd: str,
  3449. input_data: Optional[bytes] = None,
  3450. cwd: Optional[str] = None,
  3451. extra_env: Optional[dict[str, str]] = None,
  3452. ) -> Optional[bytes]:
  3453. nonlocal filter_error
  3454. filter_env = env.copy()
  3455. if extra_env:
  3456. filter_env.update(extra_env)
  3457. result = subprocess.run(
  3458. cmd,
  3459. shell=True,
  3460. input=input_data,
  3461. cwd=cwd,
  3462. env=filter_env,
  3463. capture_output=True,
  3464. )
  3465. if result.returncode != 0:
  3466. filter_error = True
  3467. return None
  3468. return result.stdout
  3469. # Create filter functions based on arguments
  3470. filter_message = None
  3471. if parsed_args.msg_filter:
  3472. def filter_message(message: bytes) -> bytes:
  3473. result = run_filter(parsed_args.msg_filter, input_data=message)
  3474. return result if result is not None else message
  3475. tree_filter = None
  3476. if parsed_args.tree_filter:
  3477. def tree_filter(tree_sha: bytes, tmpdir: str) -> bytes:
  3478. from dulwich.objects import Blob, Tree
  3479. # Export tree to tmpdir
  3480. with Repo(".") as r:
  3481. tree = r.object_store[tree_sha]
  3482. assert isinstance(tree, Tree)
  3483. for entry in tree.iteritems():
  3484. assert entry.path is not None
  3485. assert entry.sha is not None
  3486. path = Path(tmpdir) / entry.path.decode()
  3487. obj = r.object_store[entry.sha]
  3488. if isinstance(obj, Tree):
  3489. path.mkdir(exist_ok=True)
  3490. else:
  3491. assert isinstance(obj, Blob)
  3492. path.write_bytes(obj.data)
  3493. # Run the filter command in the temp directory
  3494. run_filter(parsed_args.tree_filter, cwd=tmpdir)
  3495. # Rebuild tree from modified temp directory
  3496. def build_tree_from_dir(dir_path: str) -> bytes:
  3497. tree = Tree()
  3498. for name in sorted(os.listdir(dir_path)):
  3499. if name.startswith("."):
  3500. continue
  3501. path = os.path.join(dir_path, name)
  3502. if os.path.isdir(path):
  3503. subtree_sha = build_tree_from_dir(path)
  3504. tree.add(name.encode(), 0o040000, subtree_sha)
  3505. else:
  3506. with open(path, "rb") as f:
  3507. data = f.read()
  3508. blob = Blob.from_string(data)
  3509. r.object_store.add_object(blob)
  3510. # Use appropriate file mode
  3511. mode = os.stat(path).st_mode
  3512. if mode & 0o100:
  3513. file_mode = 0o100755
  3514. else:
  3515. file_mode = 0o100644
  3516. tree.add(name.encode(), file_mode, blob.id)
  3517. r.object_store.add_object(tree)
  3518. return tree.id
  3519. return build_tree_from_dir(tmpdir)
  3520. index_filter = None
  3521. if parsed_args.index_filter:
  3522. def index_filter(tree_sha: bytes, index_path: str) -> Optional[bytes]:
  3523. run_filter(
  3524. parsed_args.index_filter, extra_env={"GIT_INDEX_FILE": index_path}
  3525. )
  3526. return None # Read back from index
  3527. parent_filter = None
  3528. if parsed_args.parent_filter:
  3529. def parent_filter(parents: Sequence[bytes]) -> list[bytes]:
  3530. parent_str = " ".join(p.hex() for p in parents)
  3531. result = run_filter(
  3532. parsed_args.parent_filter, input_data=parent_str.encode()
  3533. )
  3534. if result is None:
  3535. return list(parents)
  3536. output = result.decode().strip()
  3537. if not output:
  3538. return []
  3539. new_parents = []
  3540. for sha in output.split():
  3541. sha_bytes = sha.encode()
  3542. if valid_hexsha(sha_bytes):
  3543. new_parents.append(sha_bytes)
  3544. return new_parents
  3545. commit_filter = None
  3546. if parsed_args.commit_filter:
  3547. def commit_filter(commit_obj: Commit, tree_sha: bytes) -> Optional[bytes]:
  3548. # The filter receives: tree parent1 parent2...
  3549. cmd_input = tree_sha.hex()
  3550. for parent in commit_obj.parents:
  3551. cmd_input += " " + parent.hex()
  3552. result = run_filter(
  3553. parsed_args.commit_filter,
  3554. input_data=cmd_input.encode(),
  3555. extra_env={"GIT_COMMIT": commit_obj.id.hex()},
  3556. )
  3557. if result is None:
  3558. return None
  3559. output = result.decode().strip()
  3560. if not output:
  3561. return None # Skip commit
  3562. if valid_hexsha(output):
  3563. return output.encode()
  3564. return None
  3565. tag_name_filter = None
  3566. if parsed_args.tag_name_filter:
  3567. def tag_name_filter(tag_name: bytes) -> bytes:
  3568. result = run_filter(parsed_args.tag_name_filter, input_data=tag_name)
  3569. return result if result is not None else tag_name
  3570. # Open repo once
  3571. with Repo(".") as r:
  3572. # Check for refs/original if not forcing
  3573. if not parsed_args.force:
  3574. original_prefix = parsed_args.original.encode() + b"/"
  3575. for ref in r.refs.allkeys():
  3576. if ref.startswith(original_prefix):
  3577. logger.error("Cannot create a new backup.")
  3578. logger.error(
  3579. "A previous backup already exists in %s/",
  3580. parsed_args.original,
  3581. )
  3582. logger.error("Force overwriting the backup with -f")
  3583. print("Cannot create a new backup.")
  3584. print(
  3585. f"A previous backup already exists in {parsed_args.original}/"
  3586. )
  3587. print("Force overwriting the backup with -f")
  3588. return 1
  3589. try:
  3590. # Call porcelain.filter_branch with the repo object
  3591. result = porcelain.filter_branch(
  3592. r,
  3593. parsed_args.branch,
  3594. filter_message=filter_message,
  3595. tree_filter=tree_filter if parsed_args.tree_filter else None,
  3596. index_filter=index_filter if parsed_args.index_filter else None,
  3597. parent_filter=parent_filter if parsed_args.parent_filter else None,
  3598. commit_filter=commit_filter if parsed_args.commit_filter else None,
  3599. subdirectory_filter=parsed_args.subdirectory_filter,
  3600. prune_empty=parsed_args.prune_empty,
  3601. tag_name_filter=tag_name_filter
  3602. if parsed_args.tag_name_filter
  3603. else None,
  3604. force=parsed_args.force,
  3605. keep_original=True, # Always keep original with git
  3606. )
  3607. # Check if any filter failed
  3608. if filter_error:
  3609. logger.error("Filter command failed")
  3610. return 1
  3611. # Git filter-branch shows progress
  3612. if result:
  3613. logger.info(
  3614. "Rewrite %s (%d commits)", parsed_args.branch, len(result)
  3615. )
  3616. # Git shows: Ref 'refs/heads/branch' was rewritten
  3617. if parsed_args.branch != "HEAD":
  3618. ref_name = (
  3619. parsed_args.branch
  3620. if parsed_args.branch.startswith("refs/")
  3621. else f"refs/heads/{parsed_args.branch}"
  3622. )
  3623. logger.info("Ref '%s' was rewritten", ref_name)
  3624. return 0
  3625. except porcelain.Error as e:
  3626. logger.error("%s", e)
  3627. return 1
  3628. class cmd_lfs(Command):
  3629. """Git Large File Storage management."""
  3630. """Git LFS management commands."""
  3631. def run(self, argv: Sequence[str]) -> None:
  3632. """Execute the lfs command.
  3633. Args:
  3634. argv: Command line arguments
  3635. """
  3636. parser = argparse.ArgumentParser(prog="dulwich lfs")
  3637. subparsers = parser.add_subparsers(dest="subcommand", help="LFS subcommands")
  3638. # lfs init
  3639. subparsers.add_parser("init", help="Initialize Git LFS")
  3640. # lfs track
  3641. parser_track = subparsers.add_parser(
  3642. "track", help="Track file patterns with LFS"
  3643. )
  3644. parser_track.add_argument("patterns", nargs="*", help="File patterns to track")
  3645. # lfs untrack
  3646. parser_untrack = subparsers.add_parser(
  3647. "untrack", help="Untrack file patterns from LFS"
  3648. )
  3649. parser_untrack.add_argument(
  3650. "patterns", nargs="+", help="File patterns to untrack"
  3651. )
  3652. # lfs ls-files
  3653. parser_ls = subparsers.add_parser("ls-files", help="List LFS files")
  3654. parser_ls.add_argument("--ref", help="Git ref to check (defaults to HEAD)")
  3655. # lfs migrate
  3656. parser_migrate = subparsers.add_parser("migrate", help="Migrate files to LFS")
  3657. parser_migrate.add_argument("--include", nargs="+", help="Patterns to include")
  3658. parser_migrate.add_argument("--exclude", nargs="+", help="Patterns to exclude")
  3659. parser_migrate.add_argument(
  3660. "--everything", action="store_true", help="Migrate all files above 100MB"
  3661. )
  3662. # lfs pointer
  3663. parser_pointer = subparsers.add_parser("pointer", help="Check LFS pointers")
  3664. parser_pointer.add_argument(
  3665. "--check", nargs="*", dest="paths", help="Check if files are LFS pointers"
  3666. )
  3667. # lfs clean
  3668. parser_clean = subparsers.add_parser("clean", help="Clean file to LFS pointer")
  3669. parser_clean.add_argument("path", help="File path to clean")
  3670. # lfs smudge
  3671. parser_smudge = subparsers.add_parser(
  3672. "smudge", help="Smudge LFS pointer to content"
  3673. )
  3674. parser_smudge.add_argument(
  3675. "--stdin", action="store_true", help="Read pointer from stdin"
  3676. )
  3677. # lfs fetch
  3678. parser_fetch = subparsers.add_parser(
  3679. "fetch", help="Fetch LFS objects from remote"
  3680. )
  3681. parser_fetch.add_argument(
  3682. "--remote", default="origin", help="Remote to fetch from"
  3683. )
  3684. parser_fetch.add_argument("refs", nargs="*", help="Specific refs to fetch")
  3685. # lfs pull
  3686. parser_pull = subparsers.add_parser(
  3687. "pull", help="Pull LFS objects for current checkout"
  3688. )
  3689. parser_pull.add_argument(
  3690. "--remote", default="origin", help="Remote to pull from"
  3691. )
  3692. # lfs push
  3693. parser_push = subparsers.add_parser("push", help="Push LFS objects to remote")
  3694. parser_push.add_argument("--remote", default="origin", help="Remote to push to")
  3695. parser_push.add_argument("refs", nargs="*", help="Specific refs to push")
  3696. # lfs status
  3697. subparsers.add_parser("status", help="Show status of LFS files")
  3698. args = parser.parse_args(argv)
  3699. if args.subcommand == "init":
  3700. porcelain.lfs_init()
  3701. logger.info("Git LFS initialized.")
  3702. elif args.subcommand == "track":
  3703. if args.patterns:
  3704. tracked = porcelain.lfs_track(patterns=args.patterns)
  3705. logger.info("Tracking patterns:")
  3706. else:
  3707. tracked = porcelain.lfs_track()
  3708. logger.info("Currently tracked patterns:")
  3709. for pattern in tracked:
  3710. logger.info(" %s", pattern)
  3711. elif args.subcommand == "untrack":
  3712. tracked = porcelain.lfs_untrack(patterns=args.patterns)
  3713. logger.info("Remaining tracked patterns:")
  3714. for pattern in tracked:
  3715. logger.info(" %s", to_display_str(pattern))
  3716. elif args.subcommand == "ls-files":
  3717. files = porcelain.lfs_ls_files(ref=args.ref)
  3718. for path, oid, size in files:
  3719. logger.info(
  3720. "%s * %s (%s)",
  3721. to_display_str(oid[:12]),
  3722. to_display_str(path),
  3723. format_bytes(size),
  3724. )
  3725. elif args.subcommand == "migrate":
  3726. count = porcelain.lfs_migrate(
  3727. include=args.include, exclude=args.exclude, everything=args.everything
  3728. )
  3729. logger.info("Migrated %d file(s) to Git LFS.", count)
  3730. elif args.subcommand == "pointer":
  3731. if args.paths is not None:
  3732. results = porcelain.lfs_pointer_check(paths=args.paths or None)
  3733. for file_path, pointer in results.items():
  3734. if pointer:
  3735. logger.info(
  3736. "%s: LFS pointer (oid: %s, size: %s)",
  3737. to_display_str(file_path),
  3738. to_display_str(pointer.oid[:12]),
  3739. format_bytes(pointer.size),
  3740. )
  3741. else:
  3742. logger.warning(
  3743. "%s: Not an LFS pointer", to_display_str(file_path)
  3744. )
  3745. elif args.subcommand == "clean":
  3746. pointer = porcelain.lfs_clean(path=args.path)
  3747. sys.stdout.buffer.write(pointer)
  3748. elif args.subcommand == "smudge":
  3749. if args.stdin:
  3750. pointer_content = sys.stdin.buffer.read()
  3751. content = porcelain.lfs_smudge(pointer_content=pointer_content)
  3752. sys.stdout.buffer.write(content)
  3753. else:
  3754. logger.error("--stdin required for smudge command")
  3755. sys.exit(1)
  3756. elif args.subcommand == "fetch":
  3757. refs = args.refs or None
  3758. count = porcelain.lfs_fetch(remote=args.remote, refs=refs)
  3759. logger.info("Fetched %d LFS object(s).", count)
  3760. elif args.subcommand == "pull":
  3761. count = porcelain.lfs_pull(remote=args.remote)
  3762. logger.info("Pulled %d LFS object(s).", count)
  3763. elif args.subcommand == "push":
  3764. refs = args.refs or None
  3765. count = porcelain.lfs_push(remote=args.remote, refs=refs)
  3766. logger.info("Pushed %d LFS object(s).", count)
  3767. elif args.subcommand == "status":
  3768. status = porcelain.lfs_status()
  3769. if status["tracked"]:
  3770. logger.info("LFS tracked files: %d", len(status["tracked"]))
  3771. if status["missing"]:
  3772. logger.warning("\nMissing LFS objects:")
  3773. for file_path in status["missing"]:
  3774. logger.warning(" %s", to_display_str(file_path))
  3775. if status["not_staged"]:
  3776. logger.info("\nModified LFS files not staged:")
  3777. for file_path in status["not_staged"]:
  3778. logger.warning(" %s", to_display_str(file_path))
  3779. if not any(status.values()):
  3780. logger.info("No LFS files found.")
  3781. else:
  3782. parser.print_help()
  3783. sys.exit(1)
  3784. class cmd_help(Command):
  3785. """Display help information about git."""
  3786. def run(self, args: Sequence[str]) -> None:
  3787. """Execute the help command.
  3788. Args:
  3789. args: Command line arguments
  3790. """
  3791. parser = argparse.ArgumentParser()
  3792. parser.add_argument(
  3793. "-a",
  3794. "--all",
  3795. action="store_true",
  3796. help="List all commands.",
  3797. )
  3798. parsed_args = parser.parse_args(args)
  3799. if parsed_args.all:
  3800. logger.info("Available commands:")
  3801. for cmd in sorted(commands):
  3802. logger.info(" %s", cmd)
  3803. else:
  3804. logger.info(
  3805. "The dulwich command line tool is currently a very basic frontend for the\n"
  3806. "Dulwich python module. For full functionality, please see the API reference.\n"
  3807. "\n"
  3808. "For a list of supported commands, see 'dulwich help -a'."
  3809. )
  3810. class cmd_format_patch(Command):
  3811. """Prepare patches for e-mail submission."""
  3812. def run(self, args: Sequence[str]) -> None:
  3813. """Execute the format-patch command.
  3814. Args:
  3815. args: Command line arguments
  3816. """
  3817. parser = argparse.ArgumentParser()
  3818. parser.add_argument(
  3819. "committish",
  3820. nargs="?",
  3821. help="Commit or commit range (e.g., HEAD~3..HEAD or origin/master..HEAD)",
  3822. )
  3823. parser.add_argument(
  3824. "-n",
  3825. "--numbered",
  3826. type=int,
  3827. default=1,
  3828. help="Number of commits to format (default: 1)",
  3829. )
  3830. parser.add_argument(
  3831. "-o",
  3832. "--output-directory",
  3833. dest="outdir",
  3834. help="Output directory for patches",
  3835. )
  3836. parser.add_argument(
  3837. "--stdout",
  3838. action="store_true",
  3839. help="Output patches to stdout",
  3840. )
  3841. parsed_args = parser.parse_args(args)
  3842. # Parse committish using the new function
  3843. committish: Optional[Union[bytes, tuple[bytes, bytes]]] = None
  3844. if parsed_args.committish:
  3845. with Repo(".") as r:
  3846. range_result = parse_commit_range(r, parsed_args.committish)
  3847. if range_result:
  3848. # Convert Commit objects to their SHAs
  3849. committish = (range_result[0].id, range_result[1].id)
  3850. else:
  3851. committish = (
  3852. parsed_args.committish.encode()
  3853. if isinstance(parsed_args.committish, str)
  3854. else parsed_args.committish
  3855. )
  3856. filenames = porcelain.format_patch(
  3857. ".",
  3858. committish=committish,
  3859. outstream=sys.stdout,
  3860. outdir=parsed_args.outdir,
  3861. n=parsed_args.numbered,
  3862. stdout=parsed_args.stdout,
  3863. )
  3864. if not parsed_args.stdout:
  3865. for filename in filenames:
  3866. logger.info(filename)
  3867. class cmd_mailsplit(Command):
  3868. """Split mbox or Maildir into individual message files."""
  3869. def run(self, args: Sequence[str]) -> None:
  3870. """Execute the mailsplit command.
  3871. Args:
  3872. args: Command line arguments
  3873. """
  3874. parser = argparse.ArgumentParser()
  3875. parser.add_argument(
  3876. "mbox",
  3877. nargs="?",
  3878. help="Path to mbox file or Maildir. If not specified, reads from stdin.",
  3879. )
  3880. parser.add_argument(
  3881. "-o",
  3882. "--output-directory",
  3883. dest="output_dir",
  3884. required=True,
  3885. help="Directory in which to place the individual messages",
  3886. )
  3887. parser.add_argument(
  3888. "-b",
  3889. action="store_true",
  3890. dest="single_mail",
  3891. help="If any file doesn't begin with a From line, assume it is a single mail message",
  3892. )
  3893. parser.add_argument(
  3894. "-d",
  3895. dest="precision",
  3896. type=int,
  3897. default=4,
  3898. help="Number of digits for generated filenames (default: 4)",
  3899. )
  3900. parser.add_argument(
  3901. "-f",
  3902. dest="start_number",
  3903. type=int,
  3904. default=1,
  3905. help="Skip the first <nn> numbers (default: 1)",
  3906. )
  3907. parser.add_argument(
  3908. "--keep-cr",
  3909. action="store_true",
  3910. help="Do not remove \\r from lines ending with \\r\\n",
  3911. )
  3912. parser.add_argument(
  3913. "--mboxrd",
  3914. action="store_true",
  3915. help='Input is of the "mboxrd" format and "^>+From " line escaping is reversed',
  3916. )
  3917. parsed_args = parser.parse_args(args)
  3918. # Determine if input is a Maildir
  3919. is_maildir = False
  3920. if parsed_args.mbox:
  3921. input_path = Path(parsed_args.mbox)
  3922. if input_path.is_dir():
  3923. # Check if it's a Maildir (has cur, tmp, new subdirectories)
  3924. if (
  3925. (input_path / "cur").exists()
  3926. and (input_path / "tmp").exists()
  3927. and (input_path / "new").exists()
  3928. ):
  3929. is_maildir = True
  3930. else:
  3931. input_path = None
  3932. # Call porcelain function
  3933. output_files = porcelain.mailsplit(
  3934. input_path=input_path,
  3935. output_dir=parsed_args.output_dir,
  3936. start_number=parsed_args.start_number,
  3937. precision=parsed_args.precision,
  3938. keep_cr=parsed_args.keep_cr,
  3939. mboxrd=parsed_args.mboxrd,
  3940. is_maildir=is_maildir,
  3941. )
  3942. # Print information about the split
  3943. logger.info(
  3944. "Split %d messages into %s", len(output_files), parsed_args.output_dir
  3945. )
  3946. class cmd_bundle(Command):
  3947. """Create, unpack, and manipulate bundle files."""
  3948. def run(self, args: Sequence[str]) -> int:
  3949. """Execute the bundle command.
  3950. Args:
  3951. args: Command line arguments
  3952. """
  3953. if not args:
  3954. logger.error("Usage: bundle <create|verify|list-heads|unbundle> <options>")
  3955. return 1
  3956. subcommand = args[0]
  3957. subargs = args[1:]
  3958. if subcommand == "create":
  3959. return self._create(subargs)
  3960. elif subcommand == "verify":
  3961. return self._verify(subargs)
  3962. elif subcommand == "list-heads":
  3963. return self._list_heads(subargs)
  3964. elif subcommand == "unbundle":
  3965. return self._unbundle(subargs)
  3966. else:
  3967. logger.error("Unknown bundle subcommand: %s", subcommand)
  3968. return 1
  3969. def _create(self, args: Sequence[str]) -> int:
  3970. parser = argparse.ArgumentParser(prog="bundle create")
  3971. parser.add_argument(
  3972. "-q", "--quiet", action="store_true", help="Suppress progress"
  3973. )
  3974. parser.add_argument("--progress", action="store_true", help="Show progress")
  3975. parser.add_argument(
  3976. "--version", type=int, choices=[2, 3], help="Bundle version"
  3977. )
  3978. parser.add_argument("--all", action="store_true", help="Include all refs")
  3979. parser.add_argument("--stdin", action="store_true", help="Read refs from stdin")
  3980. parser.add_argument("file", help="Output bundle file (use - for stdout)")
  3981. parser.add_argument("refs", nargs="*", help="References or rev-list args")
  3982. parsed_args = parser.parse_args(args)
  3983. repo = Repo(".")
  3984. progress = None
  3985. if parsed_args.progress and not parsed_args.quiet:
  3986. def progress(*args: Union[str, int]) -> None:
  3987. # Handle both progress(msg) and progress(count, msg) signatures
  3988. if len(args) == 1:
  3989. msg = args[0]
  3990. elif len(args) == 2:
  3991. _count, msg = args
  3992. else:
  3993. msg = str(args)
  3994. # Convert bytes to string if needed
  3995. if isinstance(msg, bytes):
  3996. msg = msg.decode("utf-8", "replace")
  3997. logger.error("%s", msg)
  3998. refs_to_include = []
  3999. prerequisites = []
  4000. if parsed_args.all:
  4001. refs_to_include = list(repo.refs.keys())
  4002. elif parsed_args.stdin:
  4003. for line in sys.stdin:
  4004. ref = line.strip().encode("utf-8")
  4005. if ref:
  4006. refs_to_include.append(ref)
  4007. elif parsed_args.refs:
  4008. for ref_arg in parsed_args.refs:
  4009. if ".." in ref_arg:
  4010. range_result = parse_commit_range(repo, ref_arg)
  4011. if range_result:
  4012. start_commit, _end_commit = range_result
  4013. prerequisites.append(start_commit.id)
  4014. # For ranges like A..B, we need to include B if it's a ref
  4015. # Split the range to get the end part
  4016. end_part = ref_arg.split("..")[1]
  4017. if end_part: # Not empty (not "A..")
  4018. end_ref = end_part.encode("utf-8")
  4019. if end_ref in repo.refs:
  4020. refs_to_include.append(end_ref)
  4021. else:
  4022. sha = repo.refs[ref_arg.encode("utf-8")]
  4023. refs_to_include.append(ref_arg.encode("utf-8"))
  4024. else:
  4025. if ref_arg.startswith("^"):
  4026. sha = repo.refs[ref_arg[1:].encode("utf-8")]
  4027. prerequisites.append(sha)
  4028. else:
  4029. sha = repo.refs[ref_arg.encode("utf-8")]
  4030. refs_to_include.append(ref_arg.encode("utf-8"))
  4031. else:
  4032. logger.error("No refs specified. Use --all, --stdin, or specify refs")
  4033. return 1
  4034. if not refs_to_include:
  4035. logger.error("fatal: Refusing to create empty bundle.")
  4036. return 1
  4037. bundle = create_bundle_from_repo(
  4038. repo,
  4039. refs=refs_to_include,
  4040. prerequisites=prerequisites,
  4041. version=parsed_args.version,
  4042. progress=progress,
  4043. )
  4044. if parsed_args.file == "-":
  4045. write_bundle(sys.stdout.buffer, bundle)
  4046. else:
  4047. with open(parsed_args.file, "wb") as f:
  4048. write_bundle(f, bundle)
  4049. return 0
  4050. def _verify(self, args: Sequence[str]) -> int:
  4051. parser = argparse.ArgumentParser(prog="bundle verify")
  4052. parser.add_argument(
  4053. "-q", "--quiet", action="store_true", help="Suppress output"
  4054. )
  4055. parser.add_argument("file", help="Bundle file to verify (use - for stdin)")
  4056. parsed_args = parser.parse_args(args)
  4057. repo = Repo(".")
  4058. def verify_bundle(bundle: Bundle) -> int:
  4059. missing_prereqs = []
  4060. for prereq_sha, comment in bundle.prerequisites:
  4061. try:
  4062. repo.object_store[prereq_sha]
  4063. except KeyError:
  4064. missing_prereqs.append(prereq_sha)
  4065. if missing_prereqs:
  4066. if not parsed_args.quiet:
  4067. logger.info("The bundle requires these prerequisite commits:")
  4068. for sha in missing_prereqs:
  4069. logger.info(" %s", sha.decode())
  4070. return 1
  4071. else:
  4072. if not parsed_args.quiet:
  4073. logger.info(
  4074. "The bundle is valid and can be applied to the current repository"
  4075. )
  4076. return 0
  4077. if parsed_args.file == "-":
  4078. bundle = read_bundle(sys.stdin.buffer)
  4079. return verify_bundle(bundle)
  4080. else:
  4081. with open(parsed_args.file, "rb") as f:
  4082. bundle = read_bundle(f)
  4083. return verify_bundle(bundle)
  4084. def _list_heads(self, args: Sequence[str]) -> int:
  4085. parser = argparse.ArgumentParser(prog="bundle list-heads")
  4086. parser.add_argument("file", help="Bundle file (use - for stdin)")
  4087. parser.add_argument("refnames", nargs="*", help="Only show these refs")
  4088. parsed_args = parser.parse_args(args)
  4089. def list_heads(bundle: Bundle) -> None:
  4090. for ref, sha in bundle.references.items():
  4091. if not parsed_args.refnames or ref.decode() in parsed_args.refnames:
  4092. logger.info("%s %s", sha.decode(), ref.decode())
  4093. if parsed_args.file == "-":
  4094. bundle = read_bundle(sys.stdin.buffer)
  4095. list_heads(bundle)
  4096. else:
  4097. with open(parsed_args.file, "rb") as f:
  4098. bundle = read_bundle(f)
  4099. list_heads(bundle)
  4100. return 0
  4101. def _unbundle(self, args: Sequence[str]) -> int:
  4102. parser = argparse.ArgumentParser(prog="bundle unbundle")
  4103. parser.add_argument("--progress", action="store_true", help="Show progress")
  4104. parser.add_argument("file", help="Bundle file (use - for stdin)")
  4105. parser.add_argument("refnames", nargs="*", help="Only unbundle these refs")
  4106. parsed_args = parser.parse_args(args)
  4107. repo = Repo(".")
  4108. progress = None
  4109. if parsed_args.progress:
  4110. def progress(*args: Union[str, int, bytes]) -> None:
  4111. # Handle both progress(msg) and progress(count, msg) signatures
  4112. if len(args) == 1:
  4113. msg = args[0]
  4114. elif len(args) == 2:
  4115. _count, msg = args
  4116. else:
  4117. msg = str(args)
  4118. # Convert bytes to string if needed
  4119. if isinstance(msg, bytes):
  4120. msg = msg.decode("utf-8", "replace")
  4121. elif not isinstance(msg, str):
  4122. msg = str(msg)
  4123. logger.error("%s", msg)
  4124. if parsed_args.file == "-":
  4125. bundle = read_bundle(sys.stdin.buffer)
  4126. # Process the bundle while file is still available via stdin
  4127. bundle.store_objects(repo.object_store, progress=progress)
  4128. else:
  4129. # Keep the file open during bundle processing
  4130. with open(parsed_args.file, "rb") as f:
  4131. bundle = read_bundle(f)
  4132. # Process pack data while file is still open
  4133. bundle.store_objects(repo.object_store, progress=progress)
  4134. for ref, sha in bundle.references.items():
  4135. if not parsed_args.refnames or ref.decode() in parsed_args.refnames:
  4136. logger.info(ref.decode())
  4137. return 0
  4138. class cmd_worktree_add(Command):
  4139. """Create a new worktree."""
  4140. """Add a new worktree to the repository."""
  4141. def run(self, args: Sequence[str]) -> Optional[int]:
  4142. """Execute the worktree-add command.
  4143. Args:
  4144. args: Command line arguments
  4145. """
  4146. parser = argparse.ArgumentParser(
  4147. description="Add a new worktree", prog="dulwich worktree add"
  4148. )
  4149. parser.add_argument("path", help="Path for the new worktree")
  4150. parser.add_argument("committish", nargs="?", help="Commit-ish to checkout")
  4151. parser.add_argument("-b", "--create-branch", help="Create a new branch")
  4152. parser.add_argument(
  4153. "-B", "--force-create-branch", help="Create or reset a branch"
  4154. )
  4155. parser.add_argument(
  4156. "--detach", action="store_true", help="Detach HEAD in new worktree"
  4157. )
  4158. parser.add_argument("--force", action="store_true", help="Force creation")
  4159. parsed_args = parser.parse_args(args)
  4160. from dulwich import porcelain
  4161. branch = None
  4162. commit = None
  4163. if parsed_args.create_branch or parsed_args.force_create_branch:
  4164. branch = (
  4165. parsed_args.create_branch or parsed_args.force_create_branch
  4166. ).encode()
  4167. elif parsed_args.committish and not parsed_args.detach:
  4168. # If committish is provided and not detaching, treat as branch
  4169. branch = parsed_args.committish.encode()
  4170. elif parsed_args.committish:
  4171. # If committish is provided and detaching, treat as commit
  4172. commit = parsed_args.committish.encode()
  4173. worktree_path = porcelain.worktree_add(
  4174. repo=".",
  4175. path=parsed_args.path,
  4176. branch=branch,
  4177. commit=commit,
  4178. detach=parsed_args.detach,
  4179. force=parsed_args.force or bool(parsed_args.force_create_branch),
  4180. )
  4181. logger.info("Worktree added: %s", worktree_path)
  4182. return 0
  4183. class cmd_worktree_list(Command):
  4184. """List worktrees."""
  4185. """List details of each worktree."""
  4186. def run(self, args: Sequence[str]) -> Optional[int]:
  4187. """Execute the worktree-list command.
  4188. Args:
  4189. args: Command line arguments
  4190. """
  4191. parser = argparse.ArgumentParser(
  4192. description="List worktrees", prog="dulwich worktree list"
  4193. )
  4194. parser.add_argument(
  4195. "-v", "--verbose", action="store_true", help="Show additional information"
  4196. )
  4197. parser.add_argument(
  4198. "--porcelain", action="store_true", help="Machine-readable output"
  4199. )
  4200. parsed_args = parser.parse_args(args)
  4201. from dulwich import porcelain
  4202. worktrees = porcelain.worktree_list(repo=".")
  4203. for wt in worktrees:
  4204. path = wt.path
  4205. if wt.bare:
  4206. status = "(bare)"
  4207. elif wt.detached:
  4208. status = (
  4209. f"(detached HEAD {wt.head[:7].decode() if wt.head else 'unknown'})"
  4210. )
  4211. elif wt.branch:
  4212. branch_name = wt.branch.decode().replace("refs/heads/", "")
  4213. status = f"[{branch_name}]"
  4214. else:
  4215. status = "(unknown)"
  4216. if parsed_args.porcelain:
  4217. locked = "locked" if wt.locked else "unlocked"
  4218. prunable = "prunable" if wt.prunable else "unprunable"
  4219. logger.info(
  4220. "%s %s %s %s %s",
  4221. path,
  4222. wt.head.decode() if wt.head else "unknown",
  4223. status,
  4224. locked,
  4225. prunable,
  4226. )
  4227. else:
  4228. line = f"{path} {status}"
  4229. if wt.locked:
  4230. line += " locked"
  4231. if wt.prunable:
  4232. line += " prunable"
  4233. logger.info(line)
  4234. return 0
  4235. class cmd_worktree_remove(Command):
  4236. """Remove a worktree."""
  4237. """Remove a worktree."""
  4238. def run(self, args: Sequence[str]) -> Optional[int]:
  4239. """Execute the worktree-remove command.
  4240. Args:
  4241. args: Command line arguments
  4242. """
  4243. parser = argparse.ArgumentParser(
  4244. description="Remove a worktree", prog="dulwich worktree remove"
  4245. )
  4246. parser.add_argument("worktree", help="Path to worktree to remove")
  4247. parser.add_argument("--force", action="store_true", help="Force removal")
  4248. parsed_args = parser.parse_args(args)
  4249. from dulwich import porcelain
  4250. porcelain.worktree_remove(
  4251. repo=".", path=parsed_args.worktree, force=parsed_args.force
  4252. )
  4253. logger.info("Worktree removed: %s", parsed_args.worktree)
  4254. return 0
  4255. class cmd_worktree_prune(Command):
  4256. """Prune worktree information."""
  4257. """Prune worktree information."""
  4258. def run(self, args: Sequence[str]) -> Optional[int]:
  4259. """Execute the worktree-prune command.
  4260. Args:
  4261. args: Command line arguments
  4262. """
  4263. parser = argparse.ArgumentParser(
  4264. description="Prune worktree information", prog="dulwich worktree prune"
  4265. )
  4266. parser.add_argument(
  4267. "--dry-run", action="store_true", help="Do not remove anything"
  4268. )
  4269. parser.add_argument(
  4270. "-v", "--verbose", action="store_true", help="Report all removals"
  4271. )
  4272. parser.add_argument(
  4273. "--expire", type=int, help="Expire worktrees older than time (seconds)"
  4274. )
  4275. parsed_args = parser.parse_args(args)
  4276. from dulwich import porcelain
  4277. pruned = porcelain.worktree_prune(
  4278. repo=".", dry_run=parsed_args.dry_run, expire=parsed_args.expire
  4279. )
  4280. if pruned:
  4281. if parsed_args.dry_run:
  4282. logger.info("Would prune worktrees:")
  4283. elif parsed_args.verbose:
  4284. logger.info("Pruned worktrees:")
  4285. for wt_id in pruned:
  4286. logger.info(" %s", wt_id)
  4287. elif parsed_args.verbose:
  4288. logger.info("No worktrees to prune")
  4289. return 0
  4290. class cmd_worktree_lock(Command):
  4291. """Lock a worktree to prevent it from being pruned."""
  4292. """Lock a worktree."""
  4293. def run(self, args: Sequence[str]) -> Optional[int]:
  4294. """Execute the worktree-lock command.
  4295. Args:
  4296. args: Command line arguments
  4297. """
  4298. parser = argparse.ArgumentParser(
  4299. description="Lock a worktree", prog="dulwich worktree lock"
  4300. )
  4301. parser.add_argument("worktree", help="Path to worktree to lock")
  4302. parser.add_argument("--reason", help="Reason for locking")
  4303. parsed_args = parser.parse_args(args)
  4304. from dulwich import porcelain
  4305. porcelain.worktree_lock(
  4306. repo=".", path=parsed_args.worktree, reason=parsed_args.reason
  4307. )
  4308. logger.info("Worktree locked: %s", parsed_args.worktree)
  4309. return 0
  4310. class cmd_worktree_unlock(Command):
  4311. """Unlock a locked worktree."""
  4312. """Unlock a worktree."""
  4313. def run(self, args: Sequence[str]) -> Optional[int]:
  4314. """Execute the worktree-unlock command.
  4315. Args:
  4316. args: Command line arguments
  4317. """
  4318. parser = argparse.ArgumentParser(
  4319. description="Unlock a worktree", prog="dulwich worktree unlock"
  4320. )
  4321. parser.add_argument("worktree", help="Path to worktree to unlock")
  4322. parsed_args = parser.parse_args(args)
  4323. from dulwich import porcelain
  4324. porcelain.worktree_unlock(repo=".", path=parsed_args.worktree)
  4325. logger.info("Worktree unlocked: %s", parsed_args.worktree)
  4326. return 0
  4327. class cmd_worktree_move(Command):
  4328. """Move a worktree to a new location."""
  4329. """Move a worktree."""
  4330. def run(self, args: Sequence[str]) -> Optional[int]:
  4331. """Execute the worktree-move command.
  4332. Args:
  4333. args: Command line arguments
  4334. """
  4335. parser = argparse.ArgumentParser(
  4336. description="Move a worktree", prog="dulwich worktree move"
  4337. )
  4338. parser.add_argument("worktree", help="Path to worktree to move")
  4339. parser.add_argument("new_path", help="New path for the worktree")
  4340. parsed_args = parser.parse_args(args)
  4341. from dulwich import porcelain
  4342. porcelain.worktree_move(
  4343. repo=".", old_path=parsed_args.worktree, new_path=parsed_args.new_path
  4344. )
  4345. logger.info(
  4346. "Worktree moved: %s -> %s", parsed_args.worktree, parsed_args.new_path
  4347. )
  4348. return 0
  4349. class cmd_worktree_repair(Command):
  4350. """Repair worktree administrative files."""
  4351. """Repair worktree administrative files."""
  4352. def run(self, args: Sequence[str]) -> Optional[int]:
  4353. """Execute the worktree-repair command.
  4354. Args:
  4355. args: Command line arguments
  4356. """
  4357. parser = argparse.ArgumentParser(
  4358. description="Repair worktree administrative files",
  4359. prog="dulwich worktree repair",
  4360. )
  4361. parser.add_argument(
  4362. "path",
  4363. nargs="*",
  4364. help="Paths to worktrees to repair (if not specified, repairs all)",
  4365. )
  4366. parsed_args = parser.parse_args(args)
  4367. from dulwich import porcelain
  4368. paths = parsed_args.path if parsed_args.path else None
  4369. repaired = porcelain.worktree_repair(repo=".", paths=paths)
  4370. if repaired:
  4371. for path in repaired:
  4372. logger.info("Repaired worktree: %s", path)
  4373. else:
  4374. logger.info("No worktrees needed repair")
  4375. return 0
  4376. class cmd_worktree(SuperCommand):
  4377. """Manage multiple working trees."""
  4378. """Manage multiple working trees."""
  4379. subcommands: ClassVar[dict[str, type[Command]]] = {
  4380. "add": cmd_worktree_add,
  4381. "list": cmd_worktree_list,
  4382. "remove": cmd_worktree_remove,
  4383. "prune": cmd_worktree_prune,
  4384. "lock": cmd_worktree_lock,
  4385. "unlock": cmd_worktree_unlock,
  4386. "move": cmd_worktree_move,
  4387. "repair": cmd_worktree_repair,
  4388. }
  4389. default_command = cmd_worktree_list
  4390. commands = {
  4391. "add": cmd_add,
  4392. "annotate": cmd_annotate,
  4393. "archive": cmd_archive,
  4394. "bisect": cmd_bisect,
  4395. "blame": cmd_blame,
  4396. "branch": cmd_branch,
  4397. "bundle": cmd_bundle,
  4398. "check-ignore": cmd_check_ignore,
  4399. "check-mailmap": cmd_check_mailmap,
  4400. "checkout": cmd_checkout,
  4401. "cherry": cmd_cherry,
  4402. "cherry-pick": cmd_cherry_pick,
  4403. "clone": cmd_clone,
  4404. "commit": cmd_commit,
  4405. "commit-tree": cmd_commit_tree,
  4406. "config": cmd_config,
  4407. "count-objects": cmd_count_objects,
  4408. "describe": cmd_describe,
  4409. "daemon": cmd_daemon,
  4410. "diff": cmd_diff,
  4411. "diff-tree": cmd_diff_tree,
  4412. "dump-pack": cmd_dump_pack,
  4413. "dump-index": cmd_dump_index,
  4414. "fetch-pack": cmd_fetch_pack,
  4415. "fetch": cmd_fetch,
  4416. "filter-branch": cmd_filter_branch,
  4417. "for-each-ref": cmd_for_each_ref,
  4418. "format-patch": cmd_format_patch,
  4419. "fsck": cmd_fsck,
  4420. "gc": cmd_gc,
  4421. "help": cmd_help,
  4422. "init": cmd_init,
  4423. "lfs": cmd_lfs,
  4424. "log": cmd_log,
  4425. "ls-files": cmd_ls_files,
  4426. "ls-remote": cmd_ls_remote,
  4427. "ls-tree": cmd_ls_tree,
  4428. "mailsplit": cmd_mailsplit,
  4429. "merge": cmd_merge,
  4430. "merge-base": cmd_merge_base,
  4431. "merge-tree": cmd_merge_tree,
  4432. "notes": cmd_notes,
  4433. "pack-objects": cmd_pack_objects,
  4434. "pack-refs": cmd_pack_refs,
  4435. "prune": cmd_prune,
  4436. "pull": cmd_pull,
  4437. "push": cmd_push,
  4438. "rebase": cmd_rebase,
  4439. "receive-pack": cmd_receive_pack,
  4440. "reflog": cmd_reflog,
  4441. "remote": cmd_remote,
  4442. "repack": cmd_repack,
  4443. "reset": cmd_reset,
  4444. "revert": cmd_revert,
  4445. "rev-list": cmd_rev_list,
  4446. "rm": cmd_rm,
  4447. "mv": cmd_mv,
  4448. "show": cmd_show,
  4449. "show-branch": cmd_show_branch,
  4450. "show-ref": cmd_show_ref,
  4451. "stash": cmd_stash,
  4452. "status": cmd_status,
  4453. "shortlog": cmd_shortlog,
  4454. "symbolic-ref": cmd_symbolic_ref,
  4455. "submodule": cmd_submodule,
  4456. "tag": cmd_tag,
  4457. "unpack-objects": cmd_unpack_objects,
  4458. "update-server-info": cmd_update_server_info,
  4459. "upload-pack": cmd_upload_pack,
  4460. "var": cmd_var,
  4461. "verify-commit": cmd_verify_commit,
  4462. "verify-tag": cmd_verify_tag,
  4463. "web-daemon": cmd_web_daemon,
  4464. "worktree": cmd_worktree,
  4465. "write-tree": cmd_write_tree,
  4466. }
  4467. def main(argv: Optional[Sequence[str]] = None) -> Optional[int]:
  4468. """Main entry point for the Dulwich CLI.
  4469. Args:
  4470. argv: Command line arguments (defaults to sys.argv[1:])
  4471. Returns:
  4472. Exit code or None
  4473. """
  4474. if argv is None:
  4475. argv = sys.argv[1:]
  4476. # Parse only the global options and command, stop at first positional
  4477. parser = argparse.ArgumentParser(
  4478. prog="dulwich",
  4479. description="Simple command-line interface to Dulwich",
  4480. add_help=False, # We'll handle help ourselves
  4481. )
  4482. parser.add_argument("--no-pager", action="store_true", help="Disable pager")
  4483. parser.add_argument("--pager", action="store_true", help="Force enable pager")
  4484. parser.add_argument("--help", "-h", action="store_true", help="Show help")
  4485. # Parse known args to separate global options from command args
  4486. global_args, remaining = parser.parse_known_args(argv)
  4487. # Apply global pager settings
  4488. if global_args.no_pager:
  4489. disable_pager()
  4490. elif global_args.pager:
  4491. enable_pager()
  4492. # Handle help
  4493. if global_args.help or not remaining:
  4494. parser = argparse.ArgumentParser(
  4495. prog="dulwich", description="Simple command-line interface to Dulwich"
  4496. )
  4497. parser.add_argument("--no-pager", action="store_true", help="Disable pager")
  4498. parser.add_argument("--pager", action="store_true", help="Force enable pager")
  4499. parser.add_argument(
  4500. "command",
  4501. nargs="?",
  4502. help=f"Command to run. Available: {', '.join(sorted(commands.keys()))}",
  4503. )
  4504. parser.print_help()
  4505. return 1
  4506. # Try to configure from GIT_TRACE, fall back to default if it fails
  4507. if not _configure_logging_from_trace():
  4508. logging.basicConfig(
  4509. level=logging.INFO,
  4510. format="%(message)s",
  4511. )
  4512. # First remaining arg is the command
  4513. cmd = remaining[0]
  4514. cmd_args = remaining[1:]
  4515. try:
  4516. cmd_kls = commands[cmd]
  4517. except KeyError:
  4518. logging.fatal("No such subcommand: %s", cmd)
  4519. return 1
  4520. # TODO(jelmer): Return non-0 on errors
  4521. return cmd_kls().run(cmd_args)
  4522. def _main() -> None:
  4523. if "DULWICH_PDB" in os.environ and getattr(signal, "SIGQUIT", None):
  4524. signal.signal(signal.SIGQUIT, signal_quit) # type: ignore[attr-defined,unused-ignore]
  4525. signal.signal(signal.SIGINT, signal_int)
  4526. sys.exit(main())
  4527. if __name__ == "__main__":
  4528. _main()