cli.py 206 KB

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