cli.py 204 KB

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