cli.py 221 KB

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