cli.py 193 KB

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