porcelain.py 312 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270
  1. # e porcelain.py -- Porcelain-like layer on top of Dulwich
  2. # Copyright (C) 2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Simple wrapper that provides porcelain-like functions on top of Dulwich.
  22. Currently implemented:
  23. * archive
  24. * add
  25. * bisect{_start,_bad,_good,_skip,_reset,_log,_replay}
  26. * branch{_create,_delete,_list}
  27. * check_ignore
  28. * checkout
  29. * checkout_branch
  30. * clone
  31. * cone mode{_init, _set, _add}
  32. * commit
  33. * commit_tree
  34. * daemon
  35. * describe
  36. * diff_tree
  37. * fetch
  38. * filter_branch
  39. * for_each_ref
  40. * grep
  41. * init
  42. * interpret_trailers
  43. * ls_files
  44. * ls_remote
  45. * ls_tree
  46. * mailsplit
  47. * merge
  48. * merge_tree
  49. * mv/move
  50. * prune
  51. * pull
  52. * push
  53. * rm
  54. * remote{_add}
  55. * receive_pack
  56. * replace{_create,_delete,_list}
  57. * rerere{_status,_diff,_forget,_clear,_gc}
  58. * reset
  59. * revert
  60. * sparse_checkout
  61. * submodule_add
  62. * submodule_init
  63. * submodule_list
  64. * rev_list
  65. * tag{_create,_delete,_list}
  66. * upload_pack
  67. * update_server_info
  68. * var
  69. * write_commit_graph
  70. * status
  71. * shortlog
  72. * symbolic_ref
  73. * worktree{_add,_list,_remove,_prune,_lock,_unlock,_move}
  74. These functions are meant to behave similarly to the git subcommands.
  75. Differences in behaviour are considered bugs.
  76. Note: one of the consequences of this is that paths tend to be
  77. interpreted relative to the current working directory rather than relative
  78. to the repository root.
  79. Functions should generally accept both unicode strings and bytestrings
  80. """
  81. import datetime
  82. import fnmatch
  83. import logging
  84. import os
  85. import posixpath
  86. import re
  87. import stat
  88. import sys
  89. import time
  90. from collections import namedtuple
  91. from collections.abc import Callable, Iterable, Iterator, Sequence
  92. from collections.abc import Set as AbstractSet
  93. from contextlib import AbstractContextManager, closing, contextmanager
  94. from dataclasses import dataclass
  95. from io import BytesIO, RawIOBase
  96. from pathlib import Path
  97. from typing import (
  98. IO,
  99. TYPE_CHECKING,
  100. Any,
  101. BinaryIO,
  102. TextIO,
  103. TypedDict,
  104. TypeVar,
  105. cast,
  106. overload,
  107. )
  108. if sys.version_info >= (3, 12):
  109. from typing import override
  110. else:
  111. from typing_extensions import override
  112. from ._typing import Buffer
  113. if TYPE_CHECKING:
  114. import urllib3
  115. from .filter_branch import CommitData
  116. from .gc import GCStats
  117. from .maintenance import MaintenanceResult
  118. from . import replace_me
  119. from .archive import tar_stream
  120. from .bisect import BisectState
  121. from .client import (
  122. FetchPackResult,
  123. LsRemoteResult,
  124. SendPackResult,
  125. get_transport_and_path,
  126. )
  127. from .config import Config, ConfigFile, StackedConfig, read_submodules
  128. from .diff_tree import (
  129. CHANGE_ADD,
  130. CHANGE_COPY,
  131. CHANGE_DELETE,
  132. CHANGE_MODIFY,
  133. CHANGE_RENAME,
  134. RENAME_CHANGE_TYPES,
  135. TreeChange,
  136. tree_changes,
  137. )
  138. from .errors import SendPackError
  139. from .graph import can_fast_forward
  140. from .ignore import IgnoreFilterManager
  141. from .index import (
  142. ConflictedIndexEntry,
  143. Index,
  144. IndexEntry,
  145. _fs_to_tree_path,
  146. blob_from_path_and_stat,
  147. build_file_from_blob,
  148. build_index_from_tree,
  149. get_unstaged_changes,
  150. index_entry_from_stat,
  151. symlink,
  152. update_working_tree,
  153. validate_path_element_default,
  154. validate_path_element_hfs,
  155. validate_path_element_ntfs,
  156. )
  157. from .object_store import BaseObjectStore, tree_lookup_path
  158. from .objects import (
  159. Blob,
  160. Commit,
  161. Tag,
  162. Tree,
  163. TreeEntry,
  164. format_timezone,
  165. parse_timezone,
  166. pretty_format_tree_entry,
  167. )
  168. from .objectspec import (
  169. parse_commit,
  170. parse_object,
  171. parse_ref,
  172. parse_reftuples,
  173. parse_tree,
  174. )
  175. from .pack import UnpackedObject, write_pack_from_container, write_pack_index
  176. from .patch import (
  177. MailinfoResult,
  178. get_summary,
  179. write_commit_patch,
  180. write_object_diff,
  181. write_tree_diff,
  182. )
  183. from .protocol import ZERO_SHA, Protocol
  184. from .refs import (
  185. LOCAL_BRANCH_PREFIX,
  186. LOCAL_NOTES_PREFIX,
  187. LOCAL_REMOTE_PREFIX,
  188. LOCAL_REPLACE_PREFIX,
  189. LOCAL_TAG_PREFIX,
  190. DictRefsContainer,
  191. Ref,
  192. SymrefLoop,
  193. _import_remote_refs,
  194. filter_ref_prefix,
  195. local_branch_name,
  196. local_replace_name,
  197. local_tag_name,
  198. parse_remote_ref,
  199. shorten_ref_name,
  200. )
  201. from .repo import BaseRepo, Repo, get_user_identity
  202. from .server import (
  203. FileSystemBackend,
  204. ReceivePackHandler,
  205. TCPGitServer,
  206. UploadPackHandler,
  207. )
  208. from .server import update_server_info as server_update_server_info
  209. from .sparse_patterns import (
  210. SparseCheckoutConflictError,
  211. apply_included_paths,
  212. determine_included_paths,
  213. )
  214. from .trailers import add_trailer_to_message, format_trailers, parse_trailers
  215. # Module level tuple definition for status output
  216. GitStatus = namedtuple("GitStatus", "staged unstaged untracked")
  217. # TypeVar for preserving BaseRepo subclass types
  218. T = TypeVar("T", bound="BaseRepo")
  219. # Type alias for common repository parameter pattern
  220. RepoPath = str | os.PathLike[str] | Repo
  221. class TransportKwargs(TypedDict, total=False):
  222. """Keyword arguments accepted by get_transport_and_path."""
  223. operation: str | None
  224. thin_packs: bool
  225. report_activity: Callable[[int, str], None] | None
  226. quiet: bool
  227. include_tags: bool
  228. username: str | None
  229. password: str | None
  230. key_filename: str | None
  231. ssh_command: str | None
  232. pool_manager: "urllib3.PoolManager | None"
  233. @dataclass
  234. class CountObjectsResult:
  235. """Result of counting objects in a repository.
  236. Attributes:
  237. count: Number of loose objects
  238. size: Total size of loose objects in bytes
  239. in_pack: Number of objects in pack files
  240. packs: Number of pack files
  241. size_pack: Total size of pack files in bytes
  242. """
  243. count: int
  244. size: int
  245. in_pack: int | None = None
  246. packs: int | None = None
  247. size_pack: int | None = None
  248. class NoneStream(RawIOBase):
  249. """Fallback if stdout or stderr are unavailable, does nothing."""
  250. def read(self, size: int = -1) -> None:
  251. """Read from stream (returns None as this is a null stream)."""
  252. return None
  253. def readall(self) -> bytes:
  254. """Read all bytes (returns empty bytes).
  255. Returns:
  256. Empty bytes object
  257. """
  258. return b""
  259. if sys.version_info >= (3, 12):
  260. @override
  261. def readinto(self, b: Buffer) -> int | None:
  262. return 0
  263. @override
  264. def write(self, b: Buffer) -> int | None:
  265. return len(cast(bytes, b)) if b else 0
  266. else:
  267. @override
  268. def readinto(self, b: bytearray | memoryview) -> int | None: # type: ignore[override]
  269. return 0
  270. @override
  271. def write(self, b: bytes | bytearray | memoryview) -> int | None: # type: ignore[override]
  272. return len(b) if b else 0
  273. default_bytes_out_stream: BinaryIO = cast(
  274. BinaryIO, getattr(sys.stdout, "buffer", None) or NoneStream()
  275. )
  276. default_bytes_err_stream: BinaryIO = cast(
  277. BinaryIO, getattr(sys.stderr, "buffer", None) or NoneStream()
  278. )
  279. DEFAULT_ENCODING = "utf-8"
  280. class Error(Exception):
  281. """Porcelain-based error."""
  282. def __init__(self, msg: str) -> None:
  283. """Initialize Error with message."""
  284. super().__init__(msg)
  285. class RemoteExists(Error):
  286. """Raised when the remote already exists."""
  287. class TimezoneFormatError(Error):
  288. """Raised when the timezone cannot be determined from a given string."""
  289. class CheckoutError(Error):
  290. """Indicates that a checkout cannot be performed."""
  291. def parse_timezone_format(tz_str: str) -> int:
  292. """Parse given string and attempt to return a timezone offset.
  293. Different formats are considered in the following order:
  294. - Git internal format: <unix timestamp> <timezone offset>
  295. - RFC 2822: e.g. Mon, 20 Nov 1995 19:12:08 -0500
  296. - ISO 8601: e.g. 1995-11-20T19:12:08-0500
  297. Args:
  298. tz_str: datetime string
  299. Returns: Timezone offset as integer
  300. Raises:
  301. TimezoneFormatError: if timezone information cannot be extracted
  302. """
  303. import re
  304. # Git internal format
  305. internal_format_pattern = re.compile("^[0-9]+ [+-][0-9]{,4}$")
  306. if re.match(internal_format_pattern, tz_str):
  307. try:
  308. tz_internal = parse_timezone(tz_str.split(" ")[1].encode(DEFAULT_ENCODING))
  309. return tz_internal[0]
  310. except ValueError:
  311. pass
  312. # RFC 2822
  313. import email.utils
  314. rfc_2822 = email.utils.parsedate_tz(tz_str)
  315. if rfc_2822 and rfc_2822[9] is not None:
  316. return rfc_2822[9]
  317. # ISO 8601
  318. # Supported offsets:
  319. # sHHMM, sHH:MM, sHH
  320. iso_8601_pattern = re.compile(
  321. "[0-9] ?([+-])([0-9]{2})(?::(?=[0-9]{2}))?([0-9]{2})?$"
  322. )
  323. match = re.search(iso_8601_pattern, tz_str)
  324. total_secs = 0
  325. if match:
  326. sign, hours, minutes = match.groups()
  327. total_secs += int(hours) * 3600
  328. if minutes:
  329. total_secs += int(minutes) * 60
  330. total_secs = -total_secs if sign == "-" else total_secs
  331. return total_secs
  332. # YYYY.MM.DD, MM/DD/YYYY, DD.MM.YYYY contain no timezone information
  333. raise TimezoneFormatError(tz_str)
  334. def get_user_timezones() -> tuple[int, int]:
  335. """Retrieve local timezone as described in git documentation.
  336. https://raw.githubusercontent.com/git/git/v2.3.0/Documentation/date-formats.txt
  337. Returns: A tuple containing author timezone, committer timezone.
  338. """
  339. local_timezone = time.localtime().tm_gmtoff
  340. if os.environ.get("GIT_AUTHOR_DATE"):
  341. author_timezone = parse_timezone_format(os.environ["GIT_AUTHOR_DATE"])
  342. else:
  343. author_timezone = local_timezone
  344. if os.environ.get("GIT_COMMITTER_DATE"):
  345. commit_timezone = parse_timezone_format(os.environ["GIT_COMMITTER_DATE"])
  346. else:
  347. commit_timezone = local_timezone
  348. return author_timezone, commit_timezone
  349. @overload
  350. def open_repo(path_or_repo: T) -> AbstractContextManager[T]: ...
  351. @overload
  352. def open_repo(
  353. path_or_repo: str | os.PathLike[str],
  354. ) -> AbstractContextManager[Repo]: ...
  355. def open_repo(
  356. path_or_repo: str | os.PathLike[str] | T,
  357. ) -> AbstractContextManager[T | Repo]:
  358. """Open an argument that can be a repository or a path for a repository."""
  359. if isinstance(path_or_repo, BaseRepo):
  360. return _noop_context_manager(path_or_repo)
  361. return Repo(path_or_repo)
  362. @contextmanager
  363. def _noop_context_manager(obj: T) -> Iterator[T]:
  364. """Context manager that has the same api as closing but does nothing."""
  365. yield obj
  366. def _get_reflog_message(
  367. default_message: bytes, explicit_message: bytes | None = None
  368. ) -> bytes:
  369. """Get reflog message, checking GIT_REFLOG_ACTION environment variable.
  370. Args:
  371. default_message: Default message to use if no explicit message or env var
  372. explicit_message: Explicit message passed as argument (takes precedence)
  373. Returns:
  374. The reflog message to use, with priority:
  375. 1. explicit_message if provided
  376. 2. GIT_REFLOG_ACTION environment variable if set
  377. 3. default_message otherwise
  378. """
  379. if explicit_message is not None:
  380. return explicit_message
  381. env_action = os.environ.get("GIT_REFLOG_ACTION")
  382. if env_action is not None:
  383. return env_action.encode("utf-8")
  384. return default_message
  385. @overload
  386. def open_repo_closing(path_or_repo: T) -> AbstractContextManager[T]: ...
  387. @overload
  388. def open_repo_closing(
  389. path_or_repo: str | bytes | os.PathLike[str],
  390. ) -> AbstractContextManager[Repo]: ...
  391. def open_repo_closing(
  392. path_or_repo: str | bytes | os.PathLike[str] | T,
  393. ) -> AbstractContextManager[T | Repo]:
  394. """Open an argument that can be a repository or a path for a repository.
  395. returns a context manager that will close the repo on exit if the argument
  396. is a path, else does nothing if the argument is a repo.
  397. """
  398. if isinstance(path_or_repo, BaseRepo):
  399. return _noop_context_manager(path_or_repo)
  400. return closing(Repo(path_or_repo))
  401. def path_to_tree_path(
  402. repopath: str | bytes | os.PathLike[str],
  403. path: str | bytes | os.PathLike[str],
  404. tree_encoding: str = DEFAULT_ENCODING,
  405. ) -> bytes:
  406. """Convert a path to a path usable in an index, e.g. bytes and relative to the repository root.
  407. Args:
  408. repopath: Repository path, absolute or relative to the cwd
  409. path: A path, absolute or relative to the cwd
  410. tree_encoding: Encoding to use for tree paths
  411. Returns: A path formatted for use in e.g. an index
  412. """
  413. # Resolve might returns a relative path on Windows
  414. # https://bugs.python.org/issue38671
  415. if sys.platform == "win32":
  416. path = os.path.abspath(path)
  417. # Convert bytes paths to str for Path
  418. if isinstance(path, bytes):
  419. path = os.fsdecode(path)
  420. path = Path(path)
  421. resolved_path = path.resolve()
  422. # Resolve and abspath seems to behave differently regarding symlinks,
  423. # as we are doing abspath on the file path, we need to do the same on
  424. # the repo path or they might not match
  425. if sys.platform == "win32":
  426. repopath = os.path.abspath(repopath)
  427. # Convert bytes paths to str for Path
  428. if isinstance(repopath, bytes):
  429. repopath = os.fsdecode(repopath)
  430. repopath = Path(repopath).resolve()
  431. try:
  432. relpath = resolved_path.relative_to(repopath)
  433. except ValueError:
  434. # If path is a symlink that points to a file outside the repo, we
  435. # want the relpath for the link itself, not the resolved target
  436. if path.is_symlink():
  437. parent = path.parent.resolve()
  438. relpath = (parent / path.name).relative_to(repopath)
  439. else:
  440. raise
  441. if sys.platform == "win32":
  442. return str(relpath).replace(os.path.sep, "/").encode(tree_encoding)
  443. else:
  444. return bytes(relpath)
  445. class DivergedBranches(Error):
  446. """Branches have diverged and fast-forward is not possible."""
  447. def __init__(self, current_sha: bytes, new_sha: bytes) -> None:
  448. """Initialize DivergedBranches error with current and new SHA values."""
  449. self.current_sha = current_sha
  450. self.new_sha = new_sha
  451. def check_diverged(repo: BaseRepo, current_sha: bytes, new_sha: bytes) -> None:
  452. """Check if updating to a sha can be done with fast forwarding.
  453. Args:
  454. repo: Repository object
  455. current_sha: Current head sha
  456. new_sha: New head sha
  457. """
  458. try:
  459. can = can_fast_forward(repo, current_sha, new_sha)
  460. except KeyError:
  461. can = False
  462. if not can:
  463. raise DivergedBranches(current_sha, new_sha)
  464. def archive(
  465. repo: str | BaseRepo,
  466. committish: str | bytes | Commit | Tag | None = None,
  467. outstream: BinaryIO | RawIOBase = default_bytes_out_stream,
  468. errstream: BinaryIO | RawIOBase = default_bytes_err_stream,
  469. ) -> None:
  470. """Create an archive.
  471. Args:
  472. repo: Path of repository for which to generate an archive.
  473. committish: Commit SHA1 or ref to use
  474. outstream: Output stream (defaults to stdout)
  475. errstream: Error stream (defaults to stderr)
  476. """
  477. if committish is None:
  478. committish = "HEAD"
  479. with open_repo_closing(repo) as repo_obj:
  480. c = parse_commit(repo_obj, committish)
  481. tree = repo_obj.object_store[c.tree]
  482. assert isinstance(tree, Tree)
  483. for chunk in tar_stream(repo_obj.object_store, tree, c.commit_time):
  484. outstream.write(chunk)
  485. def update_server_info(repo: RepoPath = ".") -> None:
  486. """Update server info files for a repository.
  487. Args:
  488. repo: path to the repository
  489. """
  490. with open_repo_closing(repo) as r:
  491. server_update_server_info(r)
  492. def write_commit_graph(repo: RepoPath = ".", reachable: bool = True) -> None:
  493. """Write a commit graph file for a repository.
  494. Args:
  495. repo: path to the repository or a Repo object
  496. reachable: if True, include all commits reachable from refs.
  497. if False, only include direct ref targets.
  498. """
  499. with open_repo_closing(repo) as r:
  500. # Get all refs
  501. refs = list(r.refs.as_dict().values())
  502. if refs:
  503. r.object_store.write_commit_graph(refs, reachable=reachable)
  504. def symbolic_ref(repo: RepoPath, ref_name: str | bytes, force: bool = False) -> None:
  505. """Set git symbolic ref into HEAD.
  506. Args:
  507. repo: path to the repository
  508. ref_name: short name of the new ref
  509. force: force settings without checking if it exists in refs/heads
  510. """
  511. with open_repo_closing(repo) as repo_obj:
  512. ref_path = _make_branch_ref(ref_name)
  513. if not force and ref_path not in repo_obj.refs.keys():
  514. ref_name_str = (
  515. ref_name.decode("utf-8", "replace")
  516. if isinstance(ref_name, bytes)
  517. else ref_name
  518. )
  519. raise Error(f"fatal: ref `{ref_name_str}` is not a ref")
  520. repo_obj.refs.set_symbolic_ref(b"HEAD", ref_path)
  521. def pack_refs(repo: RepoPath, all: bool = False) -> None:
  522. """Pack loose references into packed-refs file."""
  523. with open_repo_closing(repo) as repo_obj:
  524. repo_obj.refs.pack_refs(all=all)
  525. def _get_variables(repo: RepoPath = ".") -> dict[str, str]:
  526. """Internal function to get all Git logical variables.
  527. Args:
  528. repo: Path to the repository
  529. Returns:
  530. A dictionary of all logical variables with values
  531. """
  532. with open_repo_closing(repo) as repo_obj:
  533. config = repo_obj.get_config_stack()
  534. # Define callbacks for each logical variable
  535. def get_author_ident() -> str | None:
  536. """Get GIT_AUTHOR_IDENT."""
  537. try:
  538. author_identity = get_user_identity(config, kind="AUTHOR")
  539. author_tz, _ = get_user_timezones()
  540. timestamp = int(time.time())
  541. return f"{author_identity.decode('utf-8', 'replace')} {timestamp} {author_tz:+05d}"
  542. except Exception:
  543. return None
  544. def get_committer_ident() -> str | None:
  545. """Get GIT_COMMITTER_IDENT."""
  546. try:
  547. committer_identity = get_user_identity(config, kind="COMMITTER")
  548. _, committer_tz = get_user_timezones()
  549. timestamp = int(time.time())
  550. return f"{committer_identity.decode('utf-8', 'replace')} {timestamp} {committer_tz:+05d}"
  551. except Exception:
  552. return None
  553. def get_editor() -> str | None:
  554. """Get GIT_EDITOR."""
  555. editor = os.environ.get("GIT_EDITOR")
  556. if editor is None:
  557. try:
  558. editor_bytes = config.get(("core",), "editor")
  559. editor = editor_bytes.decode("utf-8", "replace")
  560. except KeyError:
  561. editor = os.environ.get("VISUAL") or os.environ.get("EDITOR")
  562. return editor
  563. def get_sequence_editor() -> str | None:
  564. """Get GIT_SEQUENCE_EDITOR."""
  565. sequence_editor = os.environ.get("GIT_SEQUENCE_EDITOR")
  566. if sequence_editor is None:
  567. try:
  568. seq_editor_bytes = config.get(("sequence",), "editor")
  569. sequence_editor = seq_editor_bytes.decode("utf-8", "replace")
  570. except KeyError:
  571. # Falls back to GIT_EDITOR if not set
  572. sequence_editor = get_editor()
  573. return sequence_editor
  574. def get_pager() -> str | None:
  575. """Get GIT_PAGER."""
  576. pager = os.environ.get("GIT_PAGER")
  577. if pager is None:
  578. try:
  579. pager_bytes = config.get(("core",), "pager")
  580. pager = pager_bytes.decode("utf-8", "replace")
  581. except KeyError:
  582. pager = os.environ.get("PAGER")
  583. return pager
  584. def get_default_branch() -> str:
  585. """Get GIT_DEFAULT_BRANCH."""
  586. try:
  587. default_branch_bytes = config.get(("init",), "defaultBranch")
  588. return default_branch_bytes.decode("utf-8", "replace")
  589. except KeyError:
  590. # Git's default is "master"
  591. return "master"
  592. # Dictionary mapping variable names to their getter callbacks
  593. variable_callbacks: dict[str, Callable[[], str | None]] = {
  594. "GIT_AUTHOR_IDENT": get_author_ident,
  595. "GIT_COMMITTER_IDENT": get_committer_ident,
  596. "GIT_EDITOR": get_editor,
  597. "GIT_SEQUENCE_EDITOR": get_sequence_editor,
  598. "GIT_PAGER": get_pager,
  599. "GIT_DEFAULT_BRANCH": get_default_branch,
  600. }
  601. # Build the variables dictionary by calling callbacks
  602. variables: dict[str, str] = {}
  603. for var_name, callback in variable_callbacks.items():
  604. value = callback()
  605. if value is not None:
  606. variables[var_name] = value
  607. return variables
  608. def var_list(repo: RepoPath = ".") -> dict[str, str]:
  609. """List all Git logical variables.
  610. Args:
  611. repo: Path to the repository
  612. Returns:
  613. A dictionary of all logical variables with their values
  614. """
  615. return _get_variables(repo)
  616. def var(repo: RepoPath = ".", variable: str = "GIT_AUTHOR_IDENT") -> str:
  617. """Get the value of a specific Git logical variable.
  618. Args:
  619. repo: Path to the repository
  620. variable: The variable to query (e.g., 'GIT_AUTHOR_IDENT')
  621. Returns:
  622. The value of the requested variable as a string
  623. Raises:
  624. KeyError: If the requested variable has no value
  625. """
  626. variables = _get_variables(repo)
  627. if variable in variables:
  628. return variables[variable]
  629. else:
  630. raise KeyError(f"Variable {variable} has no value")
  631. def commit(
  632. repo: RepoPath = ".",
  633. message: str | bytes | Callable[[Any, Commit], bytes] | None = None,
  634. author: bytes | None = None,
  635. author_timezone: int | None = None,
  636. committer: bytes | None = None,
  637. commit_timezone: int | None = None,
  638. encoding: bytes | None = None,
  639. no_verify: bool = False,
  640. signoff: bool | None = None,
  641. all: bool = False,
  642. amend: bool = False,
  643. sign: bool | None = None,
  644. ) -> bytes:
  645. """Create a new commit.
  646. Args:
  647. repo: Path to repository
  648. message: Optional commit message (string/bytes or callable that takes
  649. (repo, commit) and returns bytes)
  650. author: Optional author name and email
  651. author_timezone: Author timestamp timezone
  652. committer: Optional committer name and email
  653. commit_timezone: Commit timestamp timezone
  654. encoding: Encoding to use for commit message
  655. no_verify: Skip pre-commit and commit-msg hooks
  656. signoff: Add Signed-off-by line to commit message. If None, uses format.signoff config.
  657. all: Automatically stage all tracked files that have been modified
  658. amend: Replace the tip of the current branch by creating a new commit
  659. sign: GPG sign the commit. If None, uses commit.gpgsign config.
  660. If True, signs with default GPG key. If False, does not sign.
  661. Returns: SHA1 of the new commit
  662. """
  663. encoding_str = encoding.decode("ascii") if encoding else DEFAULT_ENCODING
  664. if isinstance(message, str):
  665. message = message.encode(encoding_str)
  666. if isinstance(author, str):
  667. author = author.encode(encoding_str)
  668. if isinstance(committer, str):
  669. committer = committer.encode(encoding_str)
  670. local_timezone = get_user_timezones()
  671. if author_timezone is None:
  672. author_timezone = local_timezone[0]
  673. if commit_timezone is None:
  674. commit_timezone = local_timezone[1]
  675. with open_repo_closing(repo) as r:
  676. # Handle amend logic
  677. merge_heads = None
  678. if amend:
  679. try:
  680. head_commit = r[r.head()]
  681. assert isinstance(head_commit, Commit)
  682. except KeyError:
  683. raise ValueError("Cannot amend: no existing commit found")
  684. # If message not provided, use the message from the current HEAD
  685. if message is None:
  686. message = head_commit.message
  687. # If author not provided, use the author from the current HEAD
  688. if author is None:
  689. author = head_commit.author
  690. if author_timezone is None:
  691. author_timezone = head_commit.author_timezone
  692. # Use the parent(s) of the current HEAD as our parent(s)
  693. merge_heads = list(head_commit.parents)
  694. # If -a flag is used, stage all modified tracked files
  695. if all:
  696. index = r.open_index()
  697. normalizer = r.get_blob_normalizer()
  698. # Create a wrapper that handles the bytes -> Blob conversion
  699. if normalizer is not None:
  700. def filter_callback(data: bytes, path: bytes) -> bytes:
  701. blob = Blob()
  702. blob.data = data
  703. normalized_blob = normalizer.checkin_normalize(blob, path)
  704. data_bytes: bytes = normalized_blob.data
  705. return data_bytes
  706. else:
  707. filter_callback = None
  708. unstaged_changes = list(
  709. get_unstaged_changes(index, r.path, filter_callback)
  710. )
  711. if unstaged_changes:
  712. # Convert bytes paths to strings for add function
  713. modified_files: list[str | bytes | os.PathLike[str]] = []
  714. for path in unstaged_changes:
  715. if isinstance(path, bytes):
  716. modified_files.append(path.decode())
  717. else:
  718. modified_files.append(path)
  719. add(r, paths=modified_files)
  720. # For amend, create dangling commit to avoid adding current HEAD as parent
  721. if amend:
  722. commit_sha = r.get_worktree().commit(
  723. message=message,
  724. author=author,
  725. author_timezone=author_timezone,
  726. committer=committer,
  727. commit_timezone=commit_timezone,
  728. encoding=encoding,
  729. no_verify=no_verify,
  730. sign=sign,
  731. signoff=signoff,
  732. merge_heads=merge_heads,
  733. ref=None,
  734. )
  735. # Update HEAD to point to the new commit with reflog message
  736. try:
  737. old_head = r.refs[b"HEAD"]
  738. except KeyError:
  739. old_head = None
  740. # Get the actual commit message from the created commit
  741. commit_obj = r[commit_sha]
  742. assert isinstance(commit_obj, Commit)
  743. commit_message = commit_obj.message
  744. default_message = b"commit (amend): " + commit_message
  745. # Truncate message if too long for reflog
  746. if len(default_message) > 100:
  747. default_message = default_message[:97] + b"..."
  748. reflog_message = _get_reflog_message(default_message)
  749. r.refs.set_if_equals(b"HEAD", old_head, commit_sha, message=reflog_message)
  750. return commit_sha
  751. else:
  752. return r.get_worktree().commit(
  753. message=message,
  754. author=author,
  755. author_timezone=author_timezone,
  756. committer=committer,
  757. commit_timezone=commit_timezone,
  758. encoding=encoding,
  759. no_verify=no_verify,
  760. sign=sign,
  761. signoff=signoff,
  762. merge_heads=merge_heads,
  763. )
  764. def commit_tree(
  765. repo: RepoPath,
  766. tree: bytes,
  767. message: str | bytes | None = None,
  768. author: bytes | None = None,
  769. committer: bytes | None = None,
  770. ) -> bytes:
  771. """Create a new commit object.
  772. Args:
  773. repo: Path to repository
  774. tree: An existing tree object
  775. message: Commit message
  776. author: Optional author name and email
  777. committer: Optional committer name and email
  778. """
  779. with open_repo_closing(repo) as r:
  780. if isinstance(message, str):
  781. message = message.encode(DEFAULT_ENCODING)
  782. return r.get_worktree().commit(
  783. message=message, tree=tree, committer=committer, author=author
  784. )
  785. def interpret_trailers(
  786. message: str | bytes,
  787. *,
  788. trailers: list[tuple[str, str]] | None = None,
  789. trim_empty: bool = False,
  790. only_trailers: bool = False,
  791. only_input: bool = False,
  792. unfold: bool = False,
  793. parse: bool = False,
  794. where: str = "end",
  795. if_exists: str = "addIfDifferentNeighbor",
  796. if_missing: str = "add",
  797. separators: str = ":",
  798. ) -> bytes:
  799. r"""Parse and manipulate trailers in a commit message.
  800. This function implements the functionality of `git interpret-trailers`,
  801. allowing parsing and manipulation of structured metadata (trailers) in
  802. commit messages.
  803. Trailers are key-value pairs at the end of commit messages, formatted like:
  804. Signed-off-by: Alice <alice@example.com>
  805. Reviewed-by: Bob <bob@example.com>
  806. Args:
  807. message: The commit message (string or bytes)
  808. trailers: List of (key, value) tuples to add as new trailers
  809. trim_empty: Remove trailers with empty values
  810. only_trailers: Output only the trailers, not the message body
  811. only_input: Don't add new trailers, only parse existing ones
  812. unfold: Join multiline trailer values into a single line
  813. parse: Shorthand for --only-trailers --only-input --unfold
  814. where: Where to add new trailers ('end', 'start', 'after', 'before')
  815. if_exists: How to handle duplicate keys
  816. - 'add': Always add
  817. - 'replace': Replace all existing
  818. - 'addIfDifferent': Add only if value differs from all existing
  819. - 'addIfDifferentNeighbor': Add only if value differs from neighbors
  820. - 'doNothing': Don't add if key exists
  821. if_missing: What to do if key doesn't exist ('add' or 'doNothing')
  822. separators: Valid separator characters (default ':')
  823. Returns:
  824. The processed message as bytes
  825. Examples:
  826. >>> msg = b"Subject\\n\\nBody text\\n"
  827. >>> interpret_trailers(msg, trailers=[("Signed-off-by", "Alice <alice@example.com>")])
  828. b'Subject\\n\\nBody text\\n\\nSigned-off-by: Alice <alice@example.com>\\n'
  829. >>> msg = b"Subject\\n\\nSigned-off-by: Alice\\n"
  830. >>> interpret_trailers(msg, only_trailers=True)
  831. b'Signed-off-by: Alice\\n'
  832. """
  833. # Handle --parse shorthand
  834. if parse:
  835. only_trailers = True
  836. only_input = True
  837. unfold = True
  838. # Convert message to bytes
  839. if isinstance(message, str):
  840. message_bytes = message.encode("utf-8")
  841. else:
  842. message_bytes = message
  843. # Parse existing trailers
  844. _message_body, parsed_trailers = parse_trailers(message_bytes, separators)
  845. # Apply unfold if requested
  846. if unfold:
  847. for trailer in parsed_trailers:
  848. # Replace newlines and multiple spaces with single space
  849. trailer.value = " ".join(trailer.value.split())
  850. # Apply trim_empty if requested
  851. if trim_empty:
  852. parsed_trailers = [t for t in parsed_trailers if t.value.strip()]
  853. # Add new trailers if requested and not only_input
  854. if not only_input and trailers:
  855. for key, value in trailers:
  856. message_bytes = add_trailer_to_message(
  857. message_bytes,
  858. key,
  859. value,
  860. separators[0], # Use first separator as default
  861. where=where,
  862. if_exists=if_exists,
  863. if_missing=if_missing,
  864. )
  865. # Re-parse to get updated trailers for output
  866. if only_trailers:
  867. _message_body, parsed_trailers = parse_trailers(message_bytes, separators)
  868. # Return based on only_trailers flag
  869. if only_trailers:
  870. return format_trailers(parsed_trailers)
  871. else:
  872. return message_bytes
  873. def stripspace(
  874. text: str | bytes,
  875. *,
  876. strip_comments: bool = False,
  877. comment_char: str = "#",
  878. comment_lines: bool = False,
  879. ) -> bytes:
  880. r"""Strip unnecessary whitespace from text.
  881. This function implements the functionality of `git stripspace`, commonly
  882. used to clean up commit messages and other text content.
  883. Args:
  884. text: The text to process (string or bytes)
  885. strip_comments: If True, remove lines that begin with comment_char
  886. comment_char: The comment character to use (default: "#")
  887. comment_lines: If True, prepend comment_char to each line
  888. Returns:
  889. The processed text as bytes
  890. The function performs the following operations:
  891. 1. If comment_lines is True, prepend comment_char + space to each line
  892. 2. Strip trailing whitespace from each line
  893. 3. If strip_comments is True, remove lines starting with comment_char
  894. 4. Collapse multiple consecutive blank lines into a single blank line
  895. 5. Remove leading blank lines
  896. 6. Remove trailing blank lines
  897. 7. Ensure the text ends with a newline (unless empty)
  898. Examples:
  899. >>> stripspace(b" hello \\n\\n\\nworld \\n\\n")
  900. b'hello\\n\\nworld\\n'
  901. >>> stripspace(b"# comment\\ntext\\n", strip_comments=True)
  902. b'text\\n'
  903. >>> stripspace(b"line\\n", comment_lines=True)
  904. b'# line\\n'
  905. """
  906. from .stripspace import stripspace as _stripspace
  907. # Convert text to bytes
  908. if isinstance(text, str):
  909. text_bytes = text.encode("utf-8")
  910. else:
  911. text_bytes = text
  912. # Convert comment_char to bytes
  913. comment_char_bytes = (
  914. comment_char.encode("utf-8") if isinstance(comment_char, str) else comment_char
  915. )
  916. return _stripspace(
  917. text_bytes,
  918. strip_comments=strip_comments,
  919. comment_char=comment_char_bytes,
  920. comment_lines=comment_lines,
  921. )
  922. def init(
  923. path: str | os.PathLike[str] = ".",
  924. *,
  925. bare: bool = False,
  926. symlinks: bool | None = None,
  927. ) -> Repo:
  928. """Create a new git repository.
  929. Args:
  930. path: Path to repository.
  931. bare: Whether to create a bare repository.
  932. symlinks: Whether to create actual symlinks (defaults to autodetect)
  933. Returns: A Repo instance
  934. """
  935. if not os.path.exists(path):
  936. os.mkdir(path)
  937. if bare:
  938. return Repo.init_bare(path)
  939. else:
  940. return Repo.init(path, symlinks=symlinks)
  941. def _filter_transport_kwargs(**kwargs: object) -> TransportKwargs:
  942. """Filter kwargs to only include parameters accepted by get_transport_and_path.
  943. Args:
  944. **kwargs: Arbitrary keyword arguments
  945. Returns:
  946. Dictionary containing only the kwargs that get_transport_and_path accepts
  947. """
  948. valid_params = {
  949. "operation",
  950. "thin_packs",
  951. "report_activity",
  952. "quiet",
  953. "include_tags",
  954. "username",
  955. "password",
  956. "key_filename",
  957. "ssh_command",
  958. "pool_manager",
  959. }
  960. return cast(TransportKwargs, {k: v for k, v in kwargs.items() if k in valid_params})
  961. def clone(
  962. source: str | bytes | Repo,
  963. target: str | os.PathLike[str] | None = None,
  964. bare: bool = False,
  965. checkout: bool | None = None,
  966. errstream: BinaryIO | RawIOBase = default_bytes_err_stream,
  967. outstream: BinaryIO | None = None,
  968. origin: str | None = "origin",
  969. depth: int | None = None,
  970. branch: str | bytes | None = None,
  971. config: Config | None = None,
  972. filter_spec: str | None = None,
  973. protocol_version: int | None = None,
  974. recurse_submodules: bool = False,
  975. **kwargs: str | bytes | Sequence[str | bytes],
  976. ) -> Repo:
  977. """Clone a local or remote git repository.
  978. Args:
  979. source: Path or URL for source repository
  980. target: Path to target repository (optional)
  981. bare: Whether or not to create a bare repository
  982. checkout: Whether or not to check-out HEAD after cloning
  983. errstream: Optional stream to write progress to
  984. outstream: Optional stream to write progress to (deprecated)
  985. origin: Name of remote from the repository used to clone
  986. depth: Depth to fetch at
  987. branch: Optional branch or tag to be used as HEAD in the new repository
  988. instead of the cloned repository's HEAD.
  989. config: Configuration to use
  990. filter_spec: A git-rev-list-style object filter spec, as an ASCII string.
  991. Only used if the server supports the Git protocol-v2 'filter'
  992. feature, and ignored otherwise.
  993. protocol_version: desired Git protocol version. By default the highest
  994. mutually supported protocol version will be used.
  995. recurse_submodules: Whether to initialize and clone submodules
  996. **kwargs: Additional keyword arguments including refspecs to fetch.
  997. Can be a bytestring, a string, or a list of bytestring/string.
  998. Returns: The new repository
  999. """
  1000. if outstream is not None:
  1001. import warnings
  1002. warnings.warn(
  1003. "outstream= has been deprecated in favour of errstream=.",
  1004. DeprecationWarning,
  1005. stacklevel=3,
  1006. )
  1007. # TODO(jelmer): Capture logging output and stream to errstream
  1008. if config is None:
  1009. config = StackedConfig.default()
  1010. if checkout is None:
  1011. checkout = not bare
  1012. if checkout and bare:
  1013. raise Error("checkout and bare are incompatible")
  1014. if target is None:
  1015. if isinstance(source, Repo):
  1016. raise ValueError("target must be specified when cloning from a Repo object")
  1017. elif isinstance(source, bytes):
  1018. target = source.split(b"/")[-1].decode()
  1019. else:
  1020. target = source.split("/")[-1]
  1021. if isinstance(branch, str):
  1022. branch = branch.encode(DEFAULT_ENCODING)
  1023. mkdir = not os.path.exists(target)
  1024. if isinstance(source, Repo):
  1025. # For direct repo cloning, use LocalGitClient
  1026. from .client import GitClient, LocalGitClient
  1027. client: GitClient = LocalGitClient(config=config)
  1028. path = source.path
  1029. else:
  1030. source_str = source.decode() if isinstance(source, bytes) else source
  1031. transport_kwargs = _filter_transport_kwargs(**kwargs)
  1032. (client, path) = get_transport_and_path(
  1033. source_str, config=config, **transport_kwargs
  1034. )
  1035. filter_spec_bytes: bytes | None = None
  1036. if filter_spec:
  1037. filter_spec_bytes = filter_spec.encode("ascii")
  1038. repo = client.clone(
  1039. path,
  1040. str(target), # Convert PathLike to str
  1041. mkdir=mkdir,
  1042. bare=bare,
  1043. origin=origin,
  1044. checkout=checkout,
  1045. branch=branch.decode() if branch else None, # Convert bytes to str
  1046. progress=lambda data: (errstream.write(data), None)[1],
  1047. depth=depth,
  1048. filter_spec=filter_spec_bytes,
  1049. protocol_version=protocol_version,
  1050. )
  1051. # Initialize and update submodules if requested
  1052. if recurse_submodules and not bare:
  1053. try:
  1054. submodule_init(repo)
  1055. submodule_update(repo, init=True, recursive=True)
  1056. except FileNotFoundError as e:
  1057. # .gitmodules file doesn't exist - no submodules to process
  1058. logging.debug("No .gitmodules file found: %s", e)
  1059. except KeyError as e:
  1060. # Submodule configuration missing
  1061. logging.warning("Submodule configuration error: %s", e)
  1062. if errstream:
  1063. errstream.write(
  1064. f"Warning: Submodule configuration error: {e}\n".encode()
  1065. )
  1066. return repo
  1067. def add(
  1068. repo: str | os.PathLike[str] | Repo = ".",
  1069. paths: Sequence[str | bytes | os.PathLike[str]]
  1070. | str
  1071. | bytes
  1072. | os.PathLike[str]
  1073. | None = None,
  1074. ) -> tuple[list[str], set[str]]:
  1075. """Add files to the staging area.
  1076. Args:
  1077. repo: Repository for the files
  1078. paths: Paths to add. If None, stages all untracked and modified files from the
  1079. current working directory (mimicking 'git add .' behavior).
  1080. Returns: Tuple with set of added files and ignored files
  1081. If the repository contains ignored directories, the returned set will
  1082. contain the path to an ignored directory (with trailing slash). Individual
  1083. files within ignored directories will not be returned.
  1084. Note: When paths=None, this function adds all untracked and modified files
  1085. from the entire repository, mimicking 'git add -A' behavior.
  1086. """
  1087. ignored = set()
  1088. with open_repo_closing(repo) as r:
  1089. repo_path = Path(r.path).resolve()
  1090. ignore_manager = IgnoreFilterManager.from_repo(r)
  1091. # Get unstaged changes once for the entire operation
  1092. index = r.open_index()
  1093. normalizer = r.get_blob_normalizer()
  1094. if normalizer is not None:
  1095. def filter_callback(data: bytes, path: bytes) -> bytes:
  1096. blob = Blob()
  1097. blob.data = data
  1098. normalized_blob = normalizer.checkin_normalize(blob, path)
  1099. data_bytes: bytes = normalized_blob.data
  1100. return data_bytes
  1101. else:
  1102. filter_callback = None
  1103. # Check if core.preloadIndex is enabled
  1104. config = r.get_config_stack()
  1105. preload_index = config.get_boolean(b"core", b"preloadIndex", False)
  1106. all_unstaged_paths = list(
  1107. get_unstaged_changes(index, r.path, filter_callback, preload_index)
  1108. )
  1109. if not paths:
  1110. # When no paths specified, add all untracked and modified files from repo root
  1111. paths = [str(repo_path)]
  1112. relpaths = []
  1113. if isinstance(paths, (str, bytes, os.PathLike)):
  1114. paths = [paths]
  1115. for p in paths:
  1116. # Handle bytes paths by decoding them
  1117. if isinstance(p, bytes):
  1118. p = p.decode("utf-8")
  1119. path = Path(p)
  1120. if not path.is_absolute():
  1121. # Make relative paths relative to the repo directory
  1122. path = repo_path / path
  1123. # Don't resolve symlinks completely - only resolve the parent directory
  1124. # to avoid issues when symlinks point outside the repository
  1125. if path.is_symlink():
  1126. # For symlinks, resolve only the parent directory
  1127. parent_resolved = path.parent.resolve()
  1128. resolved_path = parent_resolved / path.name
  1129. else:
  1130. # For regular files/dirs, resolve normally
  1131. resolved_path = path.resolve()
  1132. try:
  1133. relpath = str(resolved_path.relative_to(repo_path)).replace(os.sep, "/")
  1134. except ValueError as e:
  1135. # Path is not within the repository
  1136. p_str = p.decode() if isinstance(p, bytes) else str(p)
  1137. raise ValueError(
  1138. f"Path {p_str} is not within repository {repo_path}"
  1139. ) from e
  1140. # Handle directories by scanning their contents
  1141. if resolved_path.is_dir():
  1142. # Check if the directory itself is ignored
  1143. dir_relpath = posixpath.join(relpath, "") if relpath != "." else ""
  1144. if dir_relpath and ignore_manager.is_ignored(dir_relpath):
  1145. ignored.add(dir_relpath)
  1146. continue
  1147. # When adding a directory, add all untracked files within it
  1148. current_untracked = list(
  1149. get_untracked_paths(
  1150. str(resolved_path),
  1151. str(repo_path),
  1152. index,
  1153. )
  1154. )
  1155. for untracked_path in current_untracked:
  1156. # If we're scanning a subdirectory, adjust the path
  1157. if relpath != ".":
  1158. untracked_path = posixpath.join(relpath, untracked_path)
  1159. if not ignore_manager.is_ignored(untracked_path):
  1160. relpaths.append(untracked_path)
  1161. else:
  1162. ignored.add(untracked_path)
  1163. # Also add unstaged (modified) files within this directory
  1164. for unstaged_path in all_unstaged_paths:
  1165. if isinstance(unstaged_path, bytes):
  1166. unstaged_path_str = unstaged_path.decode("utf-8")
  1167. else:
  1168. unstaged_path_str = unstaged_path
  1169. # Check if this unstaged file is within the directory we're processing
  1170. unstaged_full_path = repo_path / unstaged_path_str
  1171. try:
  1172. unstaged_full_path.relative_to(resolved_path)
  1173. # File is within this directory, add it
  1174. if not ignore_manager.is_ignored(unstaged_path_str):
  1175. relpaths.append(unstaged_path_str)
  1176. else:
  1177. ignored.add(unstaged_path_str)
  1178. except ValueError:
  1179. # File is not within this directory, skip it
  1180. continue
  1181. continue
  1182. # FIXME: Support patterns
  1183. if ignore_manager.is_ignored(relpath):
  1184. ignored.add(relpath)
  1185. continue
  1186. relpaths.append(relpath)
  1187. r.get_worktree().stage(relpaths)
  1188. return (relpaths, ignored)
  1189. def _is_subdir(
  1190. subdir: str | os.PathLike[str], parentdir: str | os.PathLike[str]
  1191. ) -> bool:
  1192. """Check whether subdir is parentdir or a subdir of parentdir.
  1193. If parentdir or subdir is a relative path, it will be disamgibuated
  1194. relative to the pwd.
  1195. """
  1196. parentdir_abs = os.path.realpath(parentdir) + os.path.sep
  1197. subdir_abs = os.path.realpath(subdir) + os.path.sep
  1198. return subdir_abs.startswith(parentdir_abs)
  1199. # TODO: option to remove ignored files also, in line with `git clean -fdx`
  1200. def clean(
  1201. repo: str | os.PathLike[str] | Repo = ".",
  1202. target_dir: str | os.PathLike[str] | None = None,
  1203. ) -> None:
  1204. """Remove any untracked files from the target directory recursively.
  1205. Equivalent to running ``git clean -fd`` in target_dir.
  1206. Args:
  1207. repo: Repository where the files may be tracked
  1208. target_dir: Directory to clean - current directory if None
  1209. """
  1210. if target_dir is None:
  1211. target_dir = os.getcwd()
  1212. with open_repo_closing(repo) as r:
  1213. if not _is_subdir(target_dir, r.path):
  1214. raise Error("target_dir must be in the repo's working dir")
  1215. config = r.get_config_stack()
  1216. config.get_boolean((b"clean",), b"requireForce", True)
  1217. # TODO(jelmer): if require_force is set, then make sure that -f, -i or
  1218. # -n is specified.
  1219. index = r.open_index()
  1220. ignore_manager = IgnoreFilterManager.from_repo(r)
  1221. paths_in_wd = _walk_working_dir_paths(target_dir, r.path)
  1222. # Reverse file visit order, so that files and subdirectories are
  1223. # removed before containing directory
  1224. for ap, is_dir in reversed(list(paths_in_wd)):
  1225. # target_dir and r.path are both str, so ap must be str
  1226. assert isinstance(ap, str)
  1227. if is_dir:
  1228. # All subdirectories and files have been removed if untracked,
  1229. # so dir contains no tracked files iff it is empty.
  1230. is_empty = len(os.listdir(ap)) == 0
  1231. if is_empty:
  1232. os.rmdir(ap)
  1233. else:
  1234. ip = path_to_tree_path(r.path, ap)
  1235. is_tracked = ip in index
  1236. rp = os.path.relpath(ap, r.path)
  1237. is_ignored = ignore_manager.is_ignored(rp)
  1238. if not is_tracked and not is_ignored:
  1239. os.remove(ap)
  1240. def remove(
  1241. repo: str | os.PathLike[str] | Repo = ".",
  1242. paths: Sequence[str | bytes | os.PathLike[str]] = [],
  1243. cached: bool = False,
  1244. ) -> None:
  1245. """Remove files from the staging area.
  1246. Args:
  1247. repo: Repository for the files
  1248. paths: Paths to remove. Can be absolute or relative to the repository root.
  1249. cached: Only remove from index, not from working directory
  1250. """
  1251. with open_repo_closing(repo) as r:
  1252. index = r.open_index()
  1253. blob_normalizer = r.get_blob_normalizer()
  1254. for p in paths:
  1255. # If path is absolute, use it as-is. Otherwise, treat it as relative to repo
  1256. p_str = os.fsdecode(p) if isinstance(p, bytes) else str(p)
  1257. if os.path.isabs(p_str):
  1258. full_path = p_str
  1259. else:
  1260. # Treat relative paths as relative to the repository root
  1261. full_path = os.path.join(r.path, p_str)
  1262. tree_path = path_to_tree_path(r.path, full_path)
  1263. # Convert to bytes for file operations
  1264. full_path_bytes = os.fsencode(full_path)
  1265. try:
  1266. entry = index[tree_path]
  1267. if isinstance(entry, ConflictedIndexEntry):
  1268. raise Error(f"{p_str} has conflicts in the index")
  1269. index_sha = entry.sha
  1270. except KeyError as exc:
  1271. raise Error(f"{p_str} did not match any files") from exc
  1272. if not cached:
  1273. try:
  1274. st = os.lstat(full_path_bytes)
  1275. except OSError:
  1276. pass
  1277. else:
  1278. try:
  1279. blob = blob_from_path_and_stat(full_path_bytes, st)
  1280. # Apply checkin normalization to compare apples to apples
  1281. if blob_normalizer is not None:
  1282. blob = blob_normalizer.checkin_normalize(blob, tree_path)
  1283. except OSError:
  1284. pass
  1285. else:
  1286. try:
  1287. head_commit = r[r.head()]
  1288. assert isinstance(head_commit, Commit)
  1289. committed_sha = tree_lookup_path(
  1290. r.__getitem__, head_commit.tree, tree_path
  1291. )[1]
  1292. except KeyError:
  1293. committed_sha = None
  1294. if blob.id != index_sha and index_sha != committed_sha:
  1295. raise Error(
  1296. "file has staged content differing "
  1297. f"from both the file and head: {p_str}"
  1298. )
  1299. if index_sha != committed_sha:
  1300. raise Error(f"file has staged changes: {p_str}")
  1301. os.remove(full_path_bytes)
  1302. del index[tree_path]
  1303. index.write()
  1304. rm = remove
  1305. def mv(
  1306. repo: str | os.PathLike[str] | Repo,
  1307. source: str | bytes | os.PathLike[str],
  1308. destination: str | bytes | os.PathLike[str],
  1309. force: bool = False,
  1310. ) -> None:
  1311. """Move or rename a file, directory, or symlink.
  1312. Args:
  1313. repo: Path to the repository
  1314. source: Path to move from
  1315. destination: Path to move to
  1316. force: Force move even if destination exists
  1317. Raises:
  1318. Error: If source doesn't exist, is not tracked, or destination already exists (without force)
  1319. """
  1320. with open_repo_closing(repo) as r:
  1321. index = r.open_index()
  1322. # Handle paths - convert to string if necessary
  1323. if isinstance(source, bytes):
  1324. source = source.decode(sys.getfilesystemencoding())
  1325. elif hasattr(source, "__fspath__"):
  1326. source = os.fspath(source)
  1327. else:
  1328. source = str(source)
  1329. if isinstance(destination, bytes):
  1330. destination = destination.decode(sys.getfilesystemencoding())
  1331. elif hasattr(destination, "__fspath__"):
  1332. destination = os.fspath(destination)
  1333. else:
  1334. destination = str(destination)
  1335. # Get full paths
  1336. if os.path.isabs(source):
  1337. source_full_path = source
  1338. else:
  1339. # Treat relative paths as relative to the repository root
  1340. source_full_path = os.path.join(r.path, source)
  1341. if os.path.isabs(destination):
  1342. destination_full_path = destination
  1343. else:
  1344. # Treat relative paths as relative to the repository root
  1345. destination_full_path = os.path.join(r.path, destination)
  1346. # Check if destination is a directory
  1347. if os.path.isdir(destination_full_path):
  1348. # Move source into destination directory
  1349. basename = os.path.basename(source_full_path)
  1350. destination_full_path = os.path.join(destination_full_path, basename)
  1351. # Convert to tree paths for index
  1352. source_tree_path = path_to_tree_path(r.path, source_full_path)
  1353. destination_tree_path = path_to_tree_path(r.path, destination_full_path)
  1354. # Check if source exists in index
  1355. if source_tree_path not in index:
  1356. raise Error(f"source '{source}' is not under version control")
  1357. # Check if source exists in filesystem
  1358. if not os.path.exists(source_full_path):
  1359. raise Error(f"source '{source}' does not exist")
  1360. # Check if destination already exists
  1361. if os.path.exists(destination_full_path) and not force:
  1362. raise Error(f"destination '{destination}' already exists (use -f to force)")
  1363. # Check if destination is already in index
  1364. if destination_tree_path in index and not force:
  1365. raise Error(
  1366. f"destination '{destination}' already exists in index (use -f to force)"
  1367. )
  1368. # Get the index entry for the source
  1369. source_entry = index[source_tree_path]
  1370. # Convert to bytes for file operations
  1371. source_full_path_bytes = os.fsencode(source_full_path)
  1372. destination_full_path_bytes = os.fsencode(destination_full_path)
  1373. # Create parent directory for destination if needed
  1374. dest_dir = os.path.dirname(destination_full_path_bytes)
  1375. if dest_dir and not os.path.exists(dest_dir):
  1376. os.makedirs(dest_dir)
  1377. # Move the file in the filesystem
  1378. if os.path.exists(destination_full_path_bytes) and force:
  1379. os.remove(destination_full_path_bytes)
  1380. os.rename(source_full_path_bytes, destination_full_path_bytes)
  1381. # Update the index
  1382. del index[source_tree_path]
  1383. index[destination_tree_path] = source_entry
  1384. index.write()
  1385. move = mv
  1386. def commit_decode(
  1387. commit: Commit, contents: bytes, default_encoding: str = DEFAULT_ENCODING
  1388. ) -> str:
  1389. """Decode commit contents using the commit's encoding or default."""
  1390. if commit.encoding:
  1391. encoding = commit.encoding.decode("ascii")
  1392. else:
  1393. encoding = default_encoding
  1394. return contents.decode(encoding, "replace")
  1395. def commit_encode(
  1396. commit: Commit, contents: str, default_encoding: str = DEFAULT_ENCODING
  1397. ) -> bytes:
  1398. """Encode commit contents using the commit's encoding or default."""
  1399. if commit.encoding:
  1400. encoding = commit.encoding.decode("ascii")
  1401. else:
  1402. encoding = default_encoding
  1403. return contents.encode(encoding)
  1404. def print_commit(
  1405. commit: Commit,
  1406. decode: Callable[[bytes], str],
  1407. outstream: TextIO = sys.stdout,
  1408. ) -> None:
  1409. """Write a human-readable commit log entry.
  1410. Args:
  1411. commit: A `Commit` object
  1412. decode: Function to decode commit data
  1413. outstream: A stream file to write to
  1414. """
  1415. outstream.write("-" * 50 + "\n")
  1416. outstream.write("commit: " + commit.id.decode("ascii") + "\n")
  1417. if len(commit.parents) > 1:
  1418. outstream.write(
  1419. "merge: "
  1420. + "...".join([c.decode("ascii") for c in commit.parents[1:]])
  1421. + "\n"
  1422. )
  1423. outstream.write("Author: " + decode(commit.author) + "\n")
  1424. if commit.author != commit.committer:
  1425. outstream.write("Committer: " + decode(commit.committer) + "\n")
  1426. time_tuple = time.gmtime(commit.author_time + commit.author_timezone)
  1427. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  1428. timezone_str = format_timezone(commit.author_timezone).decode("ascii")
  1429. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  1430. if commit.message:
  1431. outstream.write("\n")
  1432. outstream.write(decode(commit.message) + "\n")
  1433. outstream.write("\n")
  1434. def print_tag(
  1435. tag: Tag, decode: Callable[[bytes], str], outstream: TextIO = sys.stdout
  1436. ) -> None:
  1437. """Write a human-readable tag.
  1438. Args:
  1439. tag: A `Tag` object
  1440. decode: Function for decoding bytes to unicode string
  1441. outstream: A stream to write to
  1442. """
  1443. outstream.write("Tagger: " + decode(tag.tagger) + "\n")
  1444. time_tuple = time.gmtime(tag.tag_time + tag.tag_timezone)
  1445. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  1446. timezone_str = format_timezone(tag.tag_timezone).decode("ascii")
  1447. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  1448. outstream.write("\n")
  1449. outstream.write(decode(tag.message))
  1450. outstream.write("\n")
  1451. def show_blob(
  1452. repo: RepoPath,
  1453. blob: Blob,
  1454. decode: Callable[[bytes], str],
  1455. outstream: TextIO = sys.stdout,
  1456. ) -> None:
  1457. """Write a blob to a stream.
  1458. Args:
  1459. repo: A `Repo` object
  1460. blob: A `Blob` object
  1461. decode: Function for decoding bytes to unicode string
  1462. outstream: A stream file to write to
  1463. """
  1464. outstream.write(decode(blob.data))
  1465. def show_commit(
  1466. repo: RepoPath,
  1467. commit: Commit,
  1468. decode: Callable[[bytes], str],
  1469. outstream: TextIO = sys.stdout,
  1470. ) -> None:
  1471. """Show a commit to a stream.
  1472. Args:
  1473. repo: A `Repo` object
  1474. commit: A `Commit` object
  1475. decode: Function for decoding bytes to unicode string
  1476. outstream: Stream to write to
  1477. """
  1478. from .diff import ColorizedDiffStream
  1479. # Create a wrapper for ColorizedDiffStream to handle string/bytes conversion
  1480. class _StreamWrapper:
  1481. def __init__(self, stream: "ColorizedDiffStream") -> None:
  1482. self.stream = stream
  1483. def write(self, data: str | bytes) -> None:
  1484. if isinstance(data, str):
  1485. # Convert string to bytes for ColorizedDiffStream
  1486. self.stream.write(data.encode("utf-8"))
  1487. else:
  1488. self.stream.write(data)
  1489. with open_repo_closing(repo) as r:
  1490. # Use wrapper for ColorizedDiffStream, direct stream for others
  1491. if isinstance(outstream, ColorizedDiffStream):
  1492. wrapped_stream = _StreamWrapper(outstream)
  1493. print_commit(commit, decode=decode, outstream=wrapped_stream)
  1494. # Write diff directly to the ColorizedDiffStream as bytes
  1495. write_tree_diff(
  1496. outstream,
  1497. r.object_store,
  1498. commit.parents[0] if commit.parents else None,
  1499. commit.tree,
  1500. )
  1501. else:
  1502. print_commit(commit, decode=decode, outstream=outstream)
  1503. if commit.parents:
  1504. parent_commit = r[commit.parents[0]]
  1505. assert isinstance(parent_commit, Commit)
  1506. base_tree = parent_commit.tree
  1507. else:
  1508. base_tree = None
  1509. # Traditional path: buffer diff and write as decoded text
  1510. diffstream = BytesIO()
  1511. write_tree_diff(diffstream, r.object_store, base_tree, commit.tree)
  1512. diffstream.seek(0)
  1513. outstream.write(commit_decode(commit, diffstream.getvalue()))
  1514. def show_tree(
  1515. repo: RepoPath,
  1516. tree: Tree,
  1517. decode: Callable[[bytes], str],
  1518. outstream: TextIO = sys.stdout,
  1519. ) -> None:
  1520. """Print a tree to a stream.
  1521. Args:
  1522. repo: A `Repo` object
  1523. tree: A `Tree` object
  1524. decode: Function for decoding bytes to unicode string
  1525. outstream: Stream to write to
  1526. """
  1527. for n in tree:
  1528. outstream.write(decode(n) + "\n")
  1529. def show_tag(
  1530. repo: RepoPath,
  1531. tag: Tag,
  1532. decode: Callable[[bytes], str],
  1533. outstream: TextIO = sys.stdout,
  1534. ) -> None:
  1535. """Print a tag to a stream.
  1536. Args:
  1537. repo: A `Repo` object
  1538. tag: A `Tag` object
  1539. decode: Function for decoding bytes to unicode string
  1540. outstream: Stream to write to
  1541. """
  1542. with open_repo_closing(repo) as r:
  1543. print_tag(tag, decode, outstream)
  1544. obj = r[tag.object[1]]
  1545. assert isinstance(obj, (Tree, Blob, Commit, Tag))
  1546. show_object(repo, obj, decode, outstream)
  1547. def show_object(
  1548. repo: RepoPath,
  1549. obj: Tree | Blob | Commit | Tag,
  1550. decode: Callable[[bytes], str],
  1551. outstream: TextIO,
  1552. ) -> None:
  1553. """Show details of a git object."""
  1554. handlers: dict[bytes, Callable[[RepoPath, Any, Any, TextIO], None]] = {
  1555. b"tree": show_tree,
  1556. b"blob": show_blob,
  1557. b"commit": show_commit,
  1558. b"tag": show_tag,
  1559. }
  1560. handler = handlers.get(obj.type_name)
  1561. if handler is None:
  1562. raise ValueError(f"Unknown object type: {obj.type_name.decode()}")
  1563. handler(repo, obj, decode, outstream)
  1564. def print_name_status(changes: Iterator[TreeChange]) -> Iterator[str]:
  1565. """Print a simple status summary, listing changed files."""
  1566. for change in changes:
  1567. if not change:
  1568. continue
  1569. if isinstance(change, list):
  1570. change = change[0]
  1571. if change.type == CHANGE_ADD:
  1572. assert change.new is not None
  1573. path1 = change.new.path
  1574. assert path1 is not None
  1575. path2 = b""
  1576. kind = "A"
  1577. elif change.type == CHANGE_DELETE:
  1578. assert change.old is not None
  1579. path1 = change.old.path
  1580. assert path1 is not None
  1581. path2 = b""
  1582. kind = "D"
  1583. elif change.type == CHANGE_MODIFY:
  1584. assert change.new is not None
  1585. path1 = change.new.path
  1586. assert path1 is not None
  1587. path2 = b""
  1588. kind = "M"
  1589. elif change.type in RENAME_CHANGE_TYPES:
  1590. assert change.old is not None and change.new is not None
  1591. path1 = change.old.path
  1592. assert path1 is not None
  1593. path2_opt = change.new.path
  1594. assert path2_opt is not None
  1595. path2 = path2_opt
  1596. if change.type == CHANGE_RENAME:
  1597. kind = "R"
  1598. elif change.type == CHANGE_COPY:
  1599. kind = "C"
  1600. path1_str = (
  1601. path1.decode("utf-8", errors="replace")
  1602. if isinstance(path1, bytes)
  1603. else path1
  1604. )
  1605. path2_str = (
  1606. path2.decode("utf-8", errors="replace")
  1607. if isinstance(path2, bytes)
  1608. else path2
  1609. )
  1610. yield f"{kind:<8}{path1_str:<20}{path2_str:<20}"
  1611. def log(
  1612. repo: RepoPath = ".",
  1613. paths: Sequence[str | bytes] | None = None,
  1614. outstream: TextIO = sys.stdout,
  1615. max_entries: int | None = None,
  1616. reverse: bool = False,
  1617. name_status: bool = False,
  1618. ) -> None:
  1619. """Write commit logs.
  1620. Args:
  1621. repo: Path to repository
  1622. paths: Optional set of specific paths to print entries for
  1623. outstream: Stream to write log output to
  1624. reverse: Reverse order in which entries are printed
  1625. name_status: Print name status
  1626. max_entries: Optional maximum number of entries to display
  1627. """
  1628. with open_repo_closing(repo) as r:
  1629. try:
  1630. include = [r.head()]
  1631. except KeyError:
  1632. include = []
  1633. # Convert paths to bytes if needed
  1634. paths_bytes = None
  1635. if paths:
  1636. paths_bytes = [p.encode() if isinstance(p, str) else p for p in paths]
  1637. walker = r.get_walker(
  1638. include=include, max_entries=max_entries, paths=paths_bytes, reverse=reverse
  1639. )
  1640. for entry in walker:
  1641. def decode_wrapper(x: bytes) -> str:
  1642. return commit_decode(entry.commit, x)
  1643. print_commit(entry.commit, decode_wrapper, outstream)
  1644. if name_status:
  1645. outstream.writelines(
  1646. [
  1647. line + "\n"
  1648. for line in print_name_status(
  1649. cast(Iterator[TreeChange], entry.changes())
  1650. )
  1651. ]
  1652. )
  1653. # TODO(jelmer): better default for encoding?
  1654. def show(
  1655. repo: RepoPath = ".",
  1656. objects: Sequence[str | bytes] | None = None,
  1657. outstream: TextIO = sys.stdout,
  1658. default_encoding: str = DEFAULT_ENCODING,
  1659. ) -> None:
  1660. """Print the changes in a commit.
  1661. Args:
  1662. repo: Path to repository
  1663. objects: Objects to show (defaults to [HEAD])
  1664. outstream: Stream to write to
  1665. default_encoding: Default encoding to use if none is set in the
  1666. commit
  1667. """
  1668. if objects is None:
  1669. objects = ["HEAD"]
  1670. if isinstance(objects, (str, bytes)):
  1671. objects = [objects]
  1672. with open_repo_closing(repo) as r:
  1673. for objectish in objects:
  1674. o = parse_object(r, objectish)
  1675. if isinstance(o, Commit):
  1676. def decode(x: bytes) -> str:
  1677. return commit_decode(o, x, default_encoding)
  1678. else:
  1679. def decode(x: bytes) -> str:
  1680. return x.decode(default_encoding)
  1681. assert isinstance(o, (Tree, Blob, Commit, Tag))
  1682. show_object(r, o, decode, outstream)
  1683. def diff_tree(
  1684. repo: RepoPath,
  1685. old_tree: str | bytes | Tree,
  1686. new_tree: str | bytes | Tree,
  1687. outstream: BinaryIO = default_bytes_out_stream,
  1688. ) -> None:
  1689. """Compares the content and mode of blobs found via two tree objects.
  1690. Args:
  1691. repo: Path to repository
  1692. old_tree: Id of old tree
  1693. new_tree: Id of new tree
  1694. outstream: Stream to write to
  1695. """
  1696. with open_repo_closing(repo) as r:
  1697. if isinstance(old_tree, Tree):
  1698. old_tree_id: bytes | None = old_tree.id
  1699. elif isinstance(old_tree, str):
  1700. old_tree_id = old_tree.encode()
  1701. else:
  1702. old_tree_id = old_tree
  1703. if isinstance(new_tree, Tree):
  1704. new_tree_id: bytes | None = new_tree.id
  1705. elif isinstance(new_tree, str):
  1706. new_tree_id = new_tree.encode()
  1707. else:
  1708. new_tree_id = new_tree
  1709. write_tree_diff(outstream, r.object_store, old_tree_id, new_tree_id)
  1710. def diff(
  1711. repo: RepoPath = ".",
  1712. commit: str | bytes | Commit | None = None,
  1713. commit2: str | bytes | Commit | None = None,
  1714. staged: bool = False,
  1715. paths: Sequence[str | bytes] | None = None,
  1716. outstream: BinaryIO = default_bytes_out_stream,
  1717. diff_algorithm: str | None = None,
  1718. ) -> None:
  1719. """Show diff.
  1720. Args:
  1721. repo: Path to repository
  1722. commit: First commit to compare. If staged is True, compare
  1723. index to this commit. If staged is False, compare working tree
  1724. to this commit. If None, defaults to HEAD for staged and index
  1725. for unstaged.
  1726. commit2: Second commit to compare against first commit. If provided,
  1727. show diff between commit and commit2 (ignoring staged flag).
  1728. staged: If True, show staged changes (index vs commit).
  1729. If False, show unstaged changes (working tree vs commit/index).
  1730. Ignored if commit2 is provided.
  1731. paths: Optional list of paths to limit diff
  1732. outstream: Stream to write to
  1733. diff_algorithm: Algorithm to use for diffing ("myers" or "patience"),
  1734. defaults to the underlying function's default if None
  1735. """
  1736. from . import diff as diff_module
  1737. with open_repo_closing(repo) as r:
  1738. # Normalize paths to bytes
  1739. byte_paths: list[bytes] | None = None
  1740. if paths is not None and paths: # Check if paths is not empty
  1741. byte_paths = []
  1742. for p in paths:
  1743. if isinstance(p, str):
  1744. byte_paths.append(p.encode("utf-8"))
  1745. else:
  1746. byte_paths.append(p)
  1747. elif paths == []: # Convert empty list to None
  1748. byte_paths = None
  1749. else:
  1750. byte_paths = None
  1751. # Resolve commit refs to SHAs if provided
  1752. if commit is not None:
  1753. if isinstance(commit, Commit):
  1754. # Already a Commit object
  1755. commit_sha = commit.id
  1756. commit_obj = commit
  1757. else:
  1758. # parse_commit handles both refs and SHAs, and always returns a Commit object
  1759. commit_obj = parse_commit(r, commit)
  1760. commit_sha = commit_obj.id
  1761. else:
  1762. commit_sha = None
  1763. commit_obj = None
  1764. if commit2 is not None:
  1765. # Compare two commits
  1766. if isinstance(commit2, Commit):
  1767. commit2_obj = commit2
  1768. else:
  1769. commit2_obj = parse_commit(r, commit2)
  1770. # Get trees from commits
  1771. old_tree = commit_obj.tree if commit_obj else None
  1772. new_tree = commit2_obj.tree
  1773. # Use tree_changes to get the changes and apply path filtering
  1774. changes = r.object_store.tree_changes(old_tree, new_tree)
  1775. for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
  1776. # Skip if paths are specified and this change doesn't match
  1777. if byte_paths:
  1778. path_to_check = newpath or oldpath
  1779. assert path_to_check is not None
  1780. if not any(
  1781. path_to_check == p or path_to_check.startswith(p + b"/")
  1782. for p in byte_paths
  1783. ):
  1784. continue
  1785. write_object_diff(
  1786. outstream,
  1787. r.object_store,
  1788. (oldpath, oldmode, oldsha),
  1789. (newpath, newmode, newsha),
  1790. diff_algorithm=diff_algorithm,
  1791. )
  1792. elif staged:
  1793. # Show staged changes (index vs commit)
  1794. diff_module.diff_index_to_tree(
  1795. r, outstream, commit_sha, byte_paths, diff_algorithm=diff_algorithm
  1796. )
  1797. elif commit is not None:
  1798. # Compare working tree to a specific commit
  1799. assert (
  1800. commit_sha is not None
  1801. ) # mypy: commit_sha is set when commit is not None
  1802. diff_module.diff_working_tree_to_tree(
  1803. r, outstream, commit_sha, byte_paths, diff_algorithm=diff_algorithm
  1804. )
  1805. else:
  1806. # Compare working tree to index
  1807. diff_module.diff_working_tree_to_index(
  1808. r, outstream, byte_paths, diff_algorithm=diff_algorithm
  1809. )
  1810. def rev_list(
  1811. repo: RepoPath,
  1812. commits: Sequence[str | bytes],
  1813. outstream: BinaryIO = default_bytes_out_stream,
  1814. ) -> None:
  1815. """Lists commit objects in reverse chronological order.
  1816. Args:
  1817. repo: Path to repository
  1818. commits: Commits over which to iterate
  1819. outstream: Stream to write to
  1820. """
  1821. with open_repo_closing(repo) as r:
  1822. for entry in r.get_walker(
  1823. include=[r[c if isinstance(c, bytes) else c.encode()].id for c in commits]
  1824. ):
  1825. outstream.write(entry.commit.id + b"\n")
  1826. def _canonical_part(url: str) -> str:
  1827. name = url.rsplit("/", 1)[-1]
  1828. if name.endswith(".git"):
  1829. name = name[:-4]
  1830. return name
  1831. def submodule_add(
  1832. repo: str | os.PathLike[str] | Repo,
  1833. url: str,
  1834. path: str | os.PathLike[str] | None = None,
  1835. name: str | None = None,
  1836. ) -> None:
  1837. """Add a new submodule.
  1838. Args:
  1839. repo: Path to repository
  1840. url: URL of repository to add as submodule
  1841. path: Path where submodule should live
  1842. name: Name for the submodule
  1843. """
  1844. with open_repo_closing(repo) as r:
  1845. if path is None:
  1846. path = os.path.relpath(_canonical_part(url), r.path)
  1847. if name is None:
  1848. name = os.fsdecode(path) if path is not None else None
  1849. if name is None:
  1850. raise Error("Submodule name must be specified or derivable from path")
  1851. # TODO(jelmer): Move this logic to dulwich.submodule
  1852. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1853. try:
  1854. config = ConfigFile.from_path(gitmodules_path)
  1855. except FileNotFoundError:
  1856. config = ConfigFile()
  1857. config.path = gitmodules_path
  1858. config.set(("submodule", name), "url", url)
  1859. config.set(("submodule", name), "path", os.fsdecode(path))
  1860. config.write_to_path()
  1861. def submodule_init(repo: str | os.PathLike[str] | Repo) -> None:
  1862. """Initialize submodules.
  1863. Args:
  1864. repo: Path to repository
  1865. """
  1866. with open_repo_closing(repo) as r:
  1867. config = r.get_config()
  1868. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1869. for path, url, name in read_submodules(gitmodules_path):
  1870. config.set((b"submodule", name), b"active", True)
  1871. config.set((b"submodule", name), b"url", url)
  1872. config.write_to_path()
  1873. def submodule_list(repo: RepoPath) -> Iterator[tuple[str, str]]:
  1874. """List submodules.
  1875. Args:
  1876. repo: Path to repository
  1877. """
  1878. from .submodule import iter_cached_submodules
  1879. with open_repo_closing(repo) as r:
  1880. head_commit = r[r.head()]
  1881. assert isinstance(head_commit, Commit)
  1882. for path, sha in iter_cached_submodules(r.object_store, head_commit.tree):
  1883. yield path.decode(DEFAULT_ENCODING), sha.decode(DEFAULT_ENCODING)
  1884. def submodule_update(
  1885. repo: str | os.PathLike[str] | Repo,
  1886. paths: Sequence[str | bytes | os.PathLike[str]] | None = None,
  1887. init: bool = False,
  1888. force: bool = False,
  1889. recursive: bool = False,
  1890. errstream: BinaryIO | None = None,
  1891. ) -> None:
  1892. """Update submodules.
  1893. Args:
  1894. repo: Path to repository
  1895. paths: Optional list of specific submodule paths to update. If None, updates all.
  1896. init: If True, initialize submodules first
  1897. force: Force update even if local changes exist
  1898. recursive: If True, recursively update nested submodules
  1899. errstream: Error stream for error messages
  1900. """
  1901. from .submodule import iter_cached_submodules
  1902. with open_repo_closing(repo) as r:
  1903. if init:
  1904. submodule_init(r)
  1905. config = r.get_config()
  1906. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1907. # Get list of submodules to update
  1908. submodules_to_update = []
  1909. head_commit = r[r.head()]
  1910. assert isinstance(head_commit, Commit)
  1911. for path, sha in iter_cached_submodules(r.object_store, head_commit.tree):
  1912. path_str = (
  1913. path.decode(DEFAULT_ENCODING) if isinstance(path, bytes) else path
  1914. )
  1915. if paths is None or path_str in paths:
  1916. submodules_to_update.append((path, sha))
  1917. # Read submodule configuration
  1918. for path, target_sha in submodules_to_update:
  1919. path_str = (
  1920. path.decode(DEFAULT_ENCODING) if isinstance(path, bytes) else path
  1921. )
  1922. # Find the submodule name from .gitmodules
  1923. submodule_name: bytes | None = None
  1924. for sm_path, sm_url, sm_name in read_submodules(gitmodules_path):
  1925. if sm_path == path:
  1926. submodule_name = sm_name
  1927. break
  1928. if not submodule_name:
  1929. continue
  1930. # Get the URL from config
  1931. section = (
  1932. b"submodule",
  1933. submodule_name
  1934. if isinstance(submodule_name, bytes)
  1935. else submodule_name.encode(),
  1936. )
  1937. try:
  1938. url_value = config.get(section, b"url")
  1939. if isinstance(url_value, bytes):
  1940. url = url_value.decode(DEFAULT_ENCODING)
  1941. else:
  1942. url = url_value
  1943. except KeyError:
  1944. # URL not in config, skip this submodule
  1945. continue
  1946. # Get or create the submodule repository paths
  1947. submodule_path = os.path.join(r.path, path_str)
  1948. submodule_git_dir = os.path.join(r.controldir(), "modules", path_str)
  1949. # Clone or fetch the submodule
  1950. if not os.path.exists(submodule_git_dir):
  1951. # Clone the submodule as bare repository
  1952. os.makedirs(os.path.dirname(submodule_git_dir), exist_ok=True)
  1953. # Clone to the git directory
  1954. sub_repo = clone(url, submodule_git_dir, bare=True, checkout=False)
  1955. sub_repo.close()
  1956. # Create the submodule directory if it doesn't exist
  1957. if not os.path.exists(submodule_path):
  1958. os.makedirs(submodule_path)
  1959. # Create .git file in the submodule directory
  1960. relative_git_dir = os.path.relpath(submodule_git_dir, submodule_path)
  1961. git_file_path = os.path.join(submodule_path, ".git")
  1962. with open(git_file_path, "w") as f:
  1963. f.write(f"gitdir: {relative_git_dir}\n")
  1964. # Set up working directory configuration
  1965. with open_repo_closing(submodule_git_dir) as sub_repo:
  1966. sub_config = sub_repo.get_config()
  1967. sub_config.set(
  1968. (b"core",),
  1969. b"worktree",
  1970. os.path.abspath(submodule_path).encode(),
  1971. )
  1972. sub_config.write_to_path()
  1973. # Checkout the target commit
  1974. sub_repo.refs[b"HEAD"] = target_sha
  1975. # Build the index and checkout files
  1976. tree = sub_repo[target_sha]
  1977. if hasattr(tree, "tree"): # If it's a commit, get the tree
  1978. tree_id = tree.tree
  1979. else:
  1980. tree_id = target_sha
  1981. build_index_from_tree(
  1982. submodule_path,
  1983. sub_repo.index_path(),
  1984. sub_repo.object_store,
  1985. tree_id,
  1986. )
  1987. else:
  1988. # Fetch and checkout in existing submodule
  1989. with open_repo_closing(submodule_git_dir) as sub_repo:
  1990. # Fetch from remote
  1991. client, path_segments = get_transport_and_path(url)
  1992. client.fetch(path_segments.encode(), sub_repo)
  1993. # Update to the target commit
  1994. sub_repo.refs[b"HEAD"] = target_sha
  1995. # Reset the working directory
  1996. reset(sub_repo, "hard", target_sha)
  1997. # Recursively update nested submodules if requested
  1998. if recursive:
  1999. submodule_gitmodules = os.path.join(submodule_path, ".gitmodules")
  2000. if os.path.exists(submodule_gitmodules):
  2001. submodule_update(
  2002. submodule_path,
  2003. paths=None,
  2004. init=True, # Always initialize nested submodules
  2005. force=force,
  2006. recursive=True,
  2007. errstream=errstream,
  2008. )
  2009. def tag_create(
  2010. repo: RepoPath,
  2011. tag: str | bytes,
  2012. author: str | bytes | None = None,
  2013. message: str | bytes | None = None,
  2014. annotated: bool = False,
  2015. objectish: str | bytes = "HEAD",
  2016. tag_time: int | None = None,
  2017. tag_timezone: int | None = None,
  2018. sign: bool | None = None,
  2019. encoding: str = DEFAULT_ENCODING,
  2020. ) -> None:
  2021. """Creates a tag in git via dulwich calls.
  2022. Args:
  2023. repo: Path to repository
  2024. tag: tag string
  2025. author: tag author (optional, if annotated is set)
  2026. message: tag message (optional)
  2027. annotated: whether to create an annotated tag
  2028. objectish: object the tag should point at, defaults to HEAD
  2029. tag_time: Optional time for annotated tag
  2030. tag_timezone: Optional timezone for annotated tag
  2031. sign: GPG Sign the tag (bool, defaults to False,
  2032. pass True to use default GPG key,
  2033. pass a str containing Key ID to use a specific GPG key)
  2034. encoding: Encoding to use for tag messages
  2035. """
  2036. with open_repo_closing(repo) as r:
  2037. object = parse_object(r, objectish)
  2038. if isinstance(tag, str):
  2039. tag = tag.encode(encoding)
  2040. if annotated:
  2041. # Create the tag object
  2042. tag_obj = Tag()
  2043. if author is None:
  2044. author = get_user_identity(r.get_config_stack())
  2045. elif isinstance(author, str):
  2046. author = author.encode(encoding)
  2047. else:
  2048. assert isinstance(author, bytes)
  2049. tag_obj.tagger = author
  2050. if isinstance(message, str):
  2051. message = message.encode(encoding)
  2052. elif isinstance(message, bytes):
  2053. pass
  2054. else:
  2055. message = b""
  2056. tag_obj.message = message + "\n".encode(encoding)
  2057. tag_obj.name = tag
  2058. tag_obj.object = (type(object), object.id)
  2059. if tag_time is None:
  2060. tag_time = int(time.time())
  2061. tag_obj.tag_time = tag_time
  2062. if tag_timezone is None:
  2063. tag_timezone = get_user_timezones()[1]
  2064. elif isinstance(tag_timezone, str):
  2065. tag_timezone = parse_timezone(tag_timezone.encode())
  2066. tag_obj.tag_timezone = tag_timezone
  2067. # Check if we should sign the tag
  2068. config = r.get_config_stack()
  2069. if sign is None:
  2070. # Check tag.gpgSign configuration when sign is not explicitly set
  2071. try:
  2072. should_sign = config.get_boolean(
  2073. (b"tag",), b"gpgsign", default=False
  2074. )
  2075. except KeyError:
  2076. should_sign = False # Default to not signing if no config
  2077. else:
  2078. should_sign = sign
  2079. # Get the signing key from config if signing is enabled
  2080. keyid = None
  2081. if should_sign:
  2082. try:
  2083. keyid_bytes = config.get((b"user",), b"signingkey")
  2084. keyid = keyid_bytes.decode() if keyid_bytes else None
  2085. except KeyError:
  2086. keyid = None
  2087. tag_obj.sign(keyid)
  2088. r.object_store.add_object(tag_obj)
  2089. tag_id = tag_obj.id
  2090. else:
  2091. tag_id = object.id
  2092. r.refs[_make_tag_ref(tag)] = tag_id
  2093. def verify_commit(
  2094. repo: RepoPath,
  2095. committish: str | bytes = "HEAD",
  2096. keyids: list[str] | None = None,
  2097. ) -> None:
  2098. """Verify GPG signature on a commit.
  2099. Args:
  2100. repo: Path to repository
  2101. committish: Commit to verify (defaults to HEAD)
  2102. keyids: Optional list of trusted key IDs. If provided, the commit
  2103. must be signed by one of these keys. If not provided, just verifies
  2104. that the commit has a valid signature.
  2105. Raises:
  2106. gpg.errors.BadSignatures: if GPG signature verification fails
  2107. gpg.errors.MissingSignatures: if commit was not signed by a key
  2108. specified in keyids
  2109. """
  2110. with open_repo_closing(repo) as r:
  2111. commit = parse_commit(r, committish)
  2112. commit.verify(keyids)
  2113. def verify_tag(
  2114. repo: RepoPath,
  2115. tagname: str | bytes,
  2116. keyids: list[str] | None = None,
  2117. ) -> None:
  2118. """Verify GPG signature on a tag.
  2119. Args:
  2120. repo: Path to repository
  2121. tagname: Name of tag to verify
  2122. keyids: Optional list of trusted key IDs. If provided, the tag
  2123. must be signed by one of these keys. If not provided, just verifies
  2124. that the tag has a valid signature.
  2125. Raises:
  2126. gpg.errors.BadSignatures: if GPG signature verification fails
  2127. gpg.errors.MissingSignatures: if tag was not signed by a key
  2128. specified in keyids
  2129. """
  2130. with open_repo_closing(repo) as r:
  2131. if isinstance(tagname, str):
  2132. tagname = tagname.encode()
  2133. tag_ref = _make_tag_ref(tagname)
  2134. tag_id = r.refs[tag_ref]
  2135. tag_obj = r[tag_id]
  2136. if not isinstance(tag_obj, Tag):
  2137. raise Error(f"{tagname!r} does not point to a tag object")
  2138. tag_obj.verify(keyids)
  2139. def tag_list(repo: RepoPath, outstream: TextIO = sys.stdout) -> list[bytes]:
  2140. """List all tags.
  2141. Args:
  2142. repo: Path to repository
  2143. outstream: Stream to write tags to
  2144. """
  2145. with open_repo_closing(repo) as r:
  2146. tags = sorted(r.refs.as_dict(b"refs/tags"))
  2147. return tags
  2148. def tag_delete(repo: RepoPath, name: str | bytes) -> None:
  2149. """Remove a tag.
  2150. Args:
  2151. repo: Path to repository
  2152. name: Name of tag to remove
  2153. """
  2154. with open_repo_closing(repo) as r:
  2155. if isinstance(name, bytes):
  2156. names = [name]
  2157. elif isinstance(name, list):
  2158. names = name
  2159. else:
  2160. raise Error(f"Unexpected tag name type {name!r}")
  2161. for name in names:
  2162. del r.refs[_make_tag_ref(name)]
  2163. def _make_notes_ref(name: bytes) -> bytes:
  2164. """Make a notes ref name."""
  2165. if name.startswith(b"refs/notes/"):
  2166. return name
  2167. return LOCAL_NOTES_PREFIX + name
  2168. def notes_add(
  2169. repo: RepoPath,
  2170. object_sha: bytes,
  2171. note: bytes,
  2172. ref: bytes = b"commits",
  2173. author: bytes | None = None,
  2174. committer: bytes | None = None,
  2175. message: bytes | None = None,
  2176. ) -> bytes:
  2177. """Add or update a note for an object.
  2178. Args:
  2179. repo: Path to repository
  2180. object_sha: SHA of the object to annotate
  2181. note: Note content
  2182. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  2183. author: Author identity (defaults to committer)
  2184. committer: Committer identity (defaults to config)
  2185. message: Commit message for the notes update
  2186. Returns:
  2187. SHA of the new notes commit
  2188. """
  2189. with open_repo_closing(repo) as r:
  2190. # Parse the object to get its SHA
  2191. obj = parse_object(r, object_sha)
  2192. object_sha = obj.id
  2193. if isinstance(note, str):
  2194. note = note.encode(DEFAULT_ENCODING)
  2195. if isinstance(ref, str):
  2196. ref = ref.encode(DEFAULT_ENCODING)
  2197. notes_ref = _make_notes_ref(ref)
  2198. config = r.get_config_stack()
  2199. return r.notes.set_note(
  2200. object_sha,
  2201. note,
  2202. notes_ref,
  2203. author=author,
  2204. committer=committer,
  2205. message=message,
  2206. config=config,
  2207. )
  2208. def notes_remove(
  2209. repo: RepoPath,
  2210. object_sha: bytes,
  2211. ref: bytes = b"commits",
  2212. author: bytes | None = None,
  2213. committer: bytes | None = None,
  2214. message: bytes | None = None,
  2215. ) -> bytes | None:
  2216. """Remove a note for an object.
  2217. Args:
  2218. repo: Path to repository
  2219. object_sha: SHA of the object to remove notes from
  2220. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  2221. author: Author identity (defaults to committer)
  2222. committer: Committer identity (defaults to config)
  2223. message: Commit message for the notes removal
  2224. Returns:
  2225. SHA of the new notes commit, or None if no note existed
  2226. """
  2227. with open_repo_closing(repo) as r:
  2228. # Parse the object to get its SHA
  2229. obj = parse_object(r, object_sha)
  2230. object_sha = obj.id
  2231. if isinstance(ref, str):
  2232. ref = ref.encode(DEFAULT_ENCODING)
  2233. notes_ref = _make_notes_ref(ref)
  2234. config = r.get_config_stack()
  2235. return r.notes.remove_note(
  2236. object_sha,
  2237. notes_ref,
  2238. author=author,
  2239. committer=committer,
  2240. message=message,
  2241. config=config,
  2242. )
  2243. def notes_show(
  2244. repo: str | os.PathLike[str] | Repo, object_sha: bytes, ref: bytes = b"commits"
  2245. ) -> bytes | None:
  2246. """Show the note for an object.
  2247. Args:
  2248. repo: Path to repository
  2249. object_sha: SHA of the object
  2250. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  2251. Returns:
  2252. Note content as bytes, or None if no note exists
  2253. """
  2254. with open_repo_closing(repo) as r:
  2255. # Parse the object to get its SHA
  2256. obj = parse_object(r, object_sha)
  2257. object_sha = obj.id
  2258. if isinstance(ref, str):
  2259. ref = ref.encode(DEFAULT_ENCODING)
  2260. notes_ref = _make_notes_ref(ref)
  2261. config = r.get_config_stack()
  2262. return r.notes.get_note(object_sha, notes_ref, config=config)
  2263. def notes_list(repo: RepoPath, ref: bytes = b"commits") -> list[tuple[bytes, bytes]]:
  2264. """List all notes in a notes ref.
  2265. Args:
  2266. repo: Path to repository
  2267. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  2268. Returns:
  2269. List of tuples of (object_sha, note_content)
  2270. """
  2271. with open_repo_closing(repo) as r:
  2272. if isinstance(ref, str):
  2273. ref = ref.encode(DEFAULT_ENCODING)
  2274. notes_ref = _make_notes_ref(ref)
  2275. config = r.get_config_stack()
  2276. return r.notes.list_notes(notes_ref, config=config)
  2277. def replace_list(repo: RepoPath) -> list[tuple[bytes, bytes]]:
  2278. """List all replacement refs.
  2279. Args:
  2280. repo: Path to repository
  2281. Returns:
  2282. List of tuples of (object_sha, replacement_sha) where object_sha is the
  2283. object being replaced and replacement_sha is what it's replaced with
  2284. """
  2285. with open_repo_closing(repo) as r:
  2286. replacements = []
  2287. for ref in r.refs.keys():
  2288. if ref.startswith(LOCAL_REPLACE_PREFIX):
  2289. object_sha = ref[len(LOCAL_REPLACE_PREFIX) :]
  2290. replacement_sha = r.refs[ref]
  2291. replacements.append((object_sha, replacement_sha))
  2292. return replacements
  2293. def replace_delete(repo: RepoPath, object_sha: bytes | str) -> None:
  2294. """Delete a replacement ref.
  2295. Args:
  2296. repo: Path to repository
  2297. object_sha: SHA of the object whose replacement should be removed
  2298. """
  2299. with open_repo_closing(repo) as r:
  2300. # Convert to bytes if string
  2301. if isinstance(object_sha, str):
  2302. object_sha_hex = object_sha.encode("ascii")
  2303. else:
  2304. object_sha_hex = object_sha
  2305. replace_ref = _make_replace_ref(object_sha_hex)
  2306. if replace_ref not in r.refs:
  2307. raise KeyError(
  2308. f"No replacement ref found for {object_sha_hex.decode('ascii')}"
  2309. )
  2310. del r.refs[replace_ref]
  2311. def replace_create(
  2312. repo: RepoPath,
  2313. object_sha: str | bytes,
  2314. replacement_sha: str | bytes,
  2315. ) -> None:
  2316. """Create a replacement ref to replace one object with another.
  2317. Args:
  2318. repo: Path to repository
  2319. object_sha: SHA of the object to replace
  2320. replacement_sha: SHA of the replacement object
  2321. """
  2322. with open_repo_closing(repo) as r:
  2323. # Convert to bytes if string
  2324. if isinstance(object_sha, str):
  2325. object_sha_hex = object_sha.encode("ascii")
  2326. else:
  2327. object_sha_hex = object_sha
  2328. if isinstance(replacement_sha, str):
  2329. replacement_sha_hex = replacement_sha.encode("ascii")
  2330. else:
  2331. replacement_sha_hex = replacement_sha
  2332. # Create the replacement ref
  2333. replace_ref = _make_replace_ref(object_sha_hex)
  2334. r.refs[replace_ref] = replacement_sha_hex
  2335. def reset(
  2336. repo: str | os.PathLike[str] | Repo,
  2337. mode: str,
  2338. treeish: str | bytes | Commit | Tree | Tag = "HEAD",
  2339. ) -> None:
  2340. """Reset current HEAD to the specified state.
  2341. Args:
  2342. repo: Path to repository
  2343. mode: Mode ("hard", "soft", "mixed")
  2344. treeish: Treeish to reset to
  2345. """
  2346. with open_repo_closing(repo) as r:
  2347. # Parse the target tree
  2348. tree = parse_tree(r, treeish)
  2349. # Only parse as commit if treeish is not a Tree object
  2350. if isinstance(treeish, Tree):
  2351. # For Tree objects, we can't determine the commit, skip updating HEAD
  2352. target_commit = None
  2353. else:
  2354. target_commit = parse_commit(r, treeish)
  2355. # Update HEAD to point to the target commit
  2356. if target_commit is not None:
  2357. # Get the current HEAD value for set_if_equals
  2358. try:
  2359. old_head = r.refs[b"HEAD"]
  2360. except KeyError:
  2361. old_head = None
  2362. # Create reflog message
  2363. treeish_str = (
  2364. treeish.decode("utf-8")
  2365. if isinstance(treeish, bytes)
  2366. else str(treeish)
  2367. if not isinstance(treeish, (Commit, Tree, Tag))
  2368. else target_commit.id.hex()
  2369. )
  2370. default_message = f"reset: moving to {treeish_str}".encode()
  2371. reflog_message = _get_reflog_message(default_message)
  2372. # Update HEAD with reflog message
  2373. r.refs.set_if_equals(
  2374. b"HEAD", old_head, target_commit.id, message=reflog_message
  2375. )
  2376. if mode == "soft":
  2377. # Soft reset: only update HEAD, leave index and working tree unchanged
  2378. return
  2379. elif mode == "mixed":
  2380. # Mixed reset: update HEAD and index, but leave working tree unchanged
  2381. from .object_store import iter_tree_contents
  2382. # Open the index
  2383. index = r.open_index()
  2384. # Clear the current index
  2385. index.clear()
  2386. # Populate index from the target tree
  2387. for entry in iter_tree_contents(r.object_store, tree.id):
  2388. # Create an IndexEntry from the tree entry
  2389. # Use zeros for filesystem-specific fields since we're not touching the working tree
  2390. assert (
  2391. entry.mode is not None
  2392. and entry.sha is not None
  2393. and entry.path is not None
  2394. )
  2395. index_entry = IndexEntry(
  2396. ctime=(0, 0),
  2397. mtime=(0, 0),
  2398. dev=0,
  2399. ino=0,
  2400. mode=entry.mode,
  2401. uid=0,
  2402. gid=0,
  2403. size=0, # Size will be 0 since we're not reading from disk
  2404. sha=entry.sha,
  2405. flags=0,
  2406. )
  2407. index[entry.path] = index_entry
  2408. # Write the updated index
  2409. index.write()
  2410. elif mode == "hard":
  2411. # Hard reset: update HEAD, index, and working tree
  2412. # For reset --hard, use current index tree as old tree to get proper deletions
  2413. index = r.open_index()
  2414. if len(index) > 0:
  2415. index_tree_id = index.commit(r.object_store)
  2416. else:
  2417. # Empty index
  2418. index_tree_id = None
  2419. # Get configuration for working tree updates
  2420. honor_filemode, validate_path_element, symlink_fn = (
  2421. _get_worktree_update_config(r)
  2422. )
  2423. blob_normalizer = r.get_blob_normalizer()
  2424. changes = tree_changes(
  2425. r.object_store, index_tree_id, tree.id, want_unchanged=True
  2426. )
  2427. update_working_tree(
  2428. r,
  2429. index_tree_id,
  2430. tree.id,
  2431. change_iterator=changes,
  2432. honor_filemode=honor_filemode,
  2433. validate_path_element=validate_path_element,
  2434. symlink_fn=symlink_fn,
  2435. force_remove_untracked=True,
  2436. blob_normalizer=blob_normalizer,
  2437. allow_overwrite_modified=True, # Allow overwriting modified files
  2438. )
  2439. else:
  2440. raise Error(f"Invalid reset mode: {mode}")
  2441. def get_remote_repo(
  2442. repo: Repo, remote_location: str | bytes | None = None
  2443. ) -> tuple[str | None, str]:
  2444. """Get the remote repository information.
  2445. Args:
  2446. repo: Local repository object
  2447. remote_location: Optional remote name or URL; defaults to branch remote
  2448. Returns:
  2449. Tuple of (remote_name, remote_url) where remote_name may be None
  2450. if remote_location is a URL rather than a configured remote
  2451. """
  2452. config = repo.get_config()
  2453. if remote_location is None:
  2454. remote_location = get_branch_remote(repo)
  2455. if isinstance(remote_location, str):
  2456. encoded_location = remote_location.encode()
  2457. else:
  2458. encoded_location = remote_location
  2459. section = (b"remote", encoded_location)
  2460. remote_name: str | None = None
  2461. if config.has_section(section):
  2462. remote_name = encoded_location.decode()
  2463. encoded_location = config.get(section, "url")
  2464. else:
  2465. remote_name = None
  2466. return (remote_name, encoded_location.decode())
  2467. def push(
  2468. repo: RepoPath,
  2469. remote_location: str | bytes | None = None,
  2470. refspecs: str | bytes | Sequence[str | bytes] | None = None,
  2471. outstream: BinaryIO = default_bytes_out_stream,
  2472. errstream: BinaryIO | RawIOBase = default_bytes_err_stream,
  2473. force: bool = False,
  2474. **kwargs: object,
  2475. ) -> SendPackResult:
  2476. """Remote push with dulwich via dulwich.client.
  2477. Args:
  2478. repo: Path to repository
  2479. remote_location: Location of the remote
  2480. refspecs: Refs to push to remote
  2481. outstream: A stream file to write output
  2482. errstream: A stream file to write errors
  2483. force: Force overwriting refs
  2484. **kwargs: Additional keyword arguments for the client
  2485. """
  2486. # Open the repo
  2487. with open_repo_closing(repo) as r:
  2488. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  2489. # Check if mirror mode is enabled
  2490. mirror_mode = False
  2491. if remote_name:
  2492. try:
  2493. mirror_mode_val = r.get_config_stack().get_boolean(
  2494. (b"remote", remote_name.encode()), b"mirror"
  2495. )
  2496. if mirror_mode_val is not None:
  2497. mirror_mode = mirror_mode_val
  2498. except KeyError:
  2499. pass
  2500. if mirror_mode:
  2501. # Mirror mode: push all refs and delete non-existent ones
  2502. refspecs = []
  2503. for ref in r.refs.keys():
  2504. # Push all refs to the same name on remote
  2505. refspecs.append(ref + b":" + ref)
  2506. elif refspecs is None:
  2507. refspecs = [active_branch(r)]
  2508. # Normalize refspecs to bytes
  2509. if isinstance(refspecs, str):
  2510. refspecs_bytes: bytes | list[bytes] = refspecs.encode()
  2511. elif isinstance(refspecs, bytes):
  2512. refspecs_bytes = refspecs
  2513. else:
  2514. refspecs_bytes = []
  2515. for spec in refspecs:
  2516. if isinstance(spec, str):
  2517. refspecs_bytes.append(spec.encode())
  2518. else:
  2519. refspecs_bytes.append(spec)
  2520. # Get the client and path
  2521. transport_kwargs = _filter_transport_kwargs(**kwargs)
  2522. client, path = get_transport_and_path(
  2523. remote_location,
  2524. config=r.get_config_stack(),
  2525. **transport_kwargs,
  2526. )
  2527. selected_refs = []
  2528. remote_changed_refs: dict[bytes, bytes | None] = {}
  2529. def update_refs(refs: dict[bytes, bytes]) -> dict[bytes, bytes]:
  2530. remote_refs = DictRefsContainer(refs)
  2531. selected_refs.extend(
  2532. parse_reftuples(r.refs, remote_refs, refspecs_bytes, force=force)
  2533. )
  2534. new_refs = {}
  2535. # In mirror mode, delete remote refs that don't exist locally
  2536. if mirror_mode:
  2537. local_refs = set(r.refs.keys())
  2538. for remote_ref in refs.keys():
  2539. if remote_ref not in local_refs:
  2540. new_refs[remote_ref] = ZERO_SHA
  2541. remote_changed_refs[remote_ref] = None
  2542. # TODO: Handle selected_refs == {None: None}
  2543. for lh, rh, force_ref in selected_refs:
  2544. if lh is None:
  2545. assert rh is not None
  2546. new_refs[rh] = ZERO_SHA
  2547. remote_changed_refs[rh] = None
  2548. else:
  2549. try:
  2550. localsha = r.refs[lh]
  2551. except KeyError as exc:
  2552. raise Error(
  2553. f"No valid ref {lh.decode() if isinstance(lh, bytes) else lh} in local repository"
  2554. ) from exc
  2555. assert rh is not None
  2556. if not force_ref and rh in refs:
  2557. check_diverged(r, refs[rh], localsha)
  2558. new_refs[rh] = localsha
  2559. remote_changed_refs[rh] = localsha
  2560. return new_refs
  2561. err_encoding = getattr(errstream, "encoding", None) or DEFAULT_ENCODING
  2562. remote_location = client.get_url(path)
  2563. try:
  2564. def generate_pack_data_wrapper(
  2565. have: AbstractSet[bytes],
  2566. want: AbstractSet[bytes],
  2567. *,
  2568. ofs_delta: bool = False,
  2569. progress: Callable[..., None] | None = None,
  2570. ) -> tuple[int, Iterator[UnpackedObject]]:
  2571. # Wrap to match the expected signature
  2572. # Convert AbstractSet to set since generate_pack_data expects set
  2573. return r.generate_pack_data(
  2574. set(have), set(want), progress=progress, ofs_delta=ofs_delta
  2575. )
  2576. result = client.send_pack(
  2577. path.encode(),
  2578. update_refs,
  2579. generate_pack_data=generate_pack_data_wrapper,
  2580. progress=lambda data: (errstream.write(data), None)[1],
  2581. )
  2582. except SendPackError as exc:
  2583. raise Error(
  2584. "Push to " + remote_location + " failed -> " + exc.args[0].decode(),
  2585. ) from exc
  2586. else:
  2587. errstream.write(
  2588. b"Push to " + remote_location.encode(err_encoding) + b" successful.\n"
  2589. )
  2590. for ref, error in (result.ref_status or {}).items():
  2591. if error is not None:
  2592. errstream.write(
  2593. f"Push of ref {ref.decode('utf-8', 'replace')} failed: {error}\n".encode(
  2594. err_encoding
  2595. )
  2596. )
  2597. else:
  2598. errstream.write(
  2599. f"Ref {ref.decode('utf-8', 'replace')} updated\n".encode()
  2600. )
  2601. if remote_name is not None:
  2602. _import_remote_refs(r.refs, remote_name, remote_changed_refs)
  2603. return result
  2604. # Trigger auto GC if needed
  2605. from .gc import maybe_auto_gc
  2606. with open_repo_closing(repo) as r:
  2607. maybe_auto_gc(r)
  2608. def pull(
  2609. repo: RepoPath,
  2610. remote_location: str | bytes | None = None,
  2611. refspecs: str | bytes | Sequence[str | bytes] | None = None,
  2612. outstream: BinaryIO = default_bytes_out_stream,
  2613. errstream: BinaryIO | RawIOBase = default_bytes_err_stream,
  2614. fast_forward: bool = True,
  2615. ff_only: bool = False,
  2616. force: bool = False,
  2617. filter_spec: str | None = None,
  2618. protocol_version: int | None = None,
  2619. **kwargs: object,
  2620. ) -> None:
  2621. """Pull from remote via dulwich.client.
  2622. Args:
  2623. repo: Path to repository
  2624. remote_location: Location of the remote
  2625. refspecs: refspecs to fetch. Can be a bytestring, a string, or a list of
  2626. bytestring/string.
  2627. outstream: A stream file to write to output
  2628. errstream: A stream file to write to errors
  2629. fast_forward: If True, raise an exception when fast-forward is not possible
  2630. ff_only: If True, only allow fast-forward merges. Raises DivergedBranches
  2631. when branches have diverged rather than performing a merge.
  2632. force: If True, allow overwriting local changes in the working tree.
  2633. If False, pull will abort if it would overwrite uncommitted changes.
  2634. filter_spec: A git-rev-list-style object filter spec, as an ASCII string.
  2635. Only used if the server supports the Git protocol-v2 'filter'
  2636. feature, and ignored otherwise.
  2637. protocol_version: desired Git protocol version. By default the highest
  2638. mutually supported protocol version will be used
  2639. **kwargs: Additional keyword arguments for the client
  2640. """
  2641. # Open the repo
  2642. with open_repo_closing(repo) as r:
  2643. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  2644. selected_refs = []
  2645. if refspecs is None:
  2646. refspecs_normalized: bytes | list[bytes] = [b"HEAD"]
  2647. elif isinstance(refspecs, str):
  2648. refspecs_normalized = refspecs.encode()
  2649. elif isinstance(refspecs, bytes):
  2650. refspecs_normalized = refspecs
  2651. else:
  2652. refspecs_normalized = []
  2653. for spec in refspecs:
  2654. if isinstance(spec, str):
  2655. refspecs_normalized.append(spec.encode())
  2656. else:
  2657. refspecs_normalized.append(spec)
  2658. def determine_wants(
  2659. remote_refs: dict[bytes, bytes], depth: int | None = None
  2660. ) -> list[bytes]:
  2661. remote_refs_container = DictRefsContainer(remote_refs)
  2662. selected_refs.extend(
  2663. parse_reftuples(
  2664. remote_refs_container, r.refs, refspecs_normalized, force=force
  2665. )
  2666. )
  2667. return [
  2668. remote_refs[lh]
  2669. for (lh, rh, force_ref) in selected_refs
  2670. if lh is not None
  2671. and lh in remote_refs
  2672. and remote_refs[lh] not in r.object_store
  2673. ]
  2674. transport_kwargs = _filter_transport_kwargs(**kwargs)
  2675. client, path = get_transport_and_path(
  2676. remote_location,
  2677. config=r.get_config_stack(),
  2678. **transport_kwargs,
  2679. )
  2680. if filter_spec:
  2681. filter_spec_bytes: bytes | None = filter_spec.encode("ascii")
  2682. else:
  2683. filter_spec_bytes = None
  2684. def progress(data: bytes) -> None:
  2685. errstream.write(data)
  2686. fetch_result = client.fetch(
  2687. path.encode(),
  2688. r,
  2689. progress=progress,
  2690. determine_wants=determine_wants, # type: ignore[arg-type] # Function matches protocol but mypy can't verify
  2691. filter_spec=filter_spec_bytes,
  2692. protocol_version=protocol_version,
  2693. )
  2694. # Store the old HEAD tree before making changes
  2695. try:
  2696. old_head = r.refs[b"HEAD"]
  2697. old_commit = r[old_head]
  2698. assert isinstance(old_commit, Commit)
  2699. old_tree_id = old_commit.tree
  2700. except KeyError:
  2701. old_tree_id = None
  2702. merged = False
  2703. for lh, rh, force_ref in selected_refs:
  2704. if not force_ref and rh is not None and rh in r.refs:
  2705. try:
  2706. assert lh is not None
  2707. followed_ref = r.refs.follow(rh)[1]
  2708. assert followed_ref is not None
  2709. lh_ref = fetch_result.refs[lh]
  2710. assert lh_ref is not None
  2711. check_diverged(r, followed_ref, lh_ref)
  2712. except DivergedBranches as exc:
  2713. if ff_only or fast_forward:
  2714. raise
  2715. else:
  2716. # Perform merge
  2717. assert lh is not None
  2718. merge_ref = fetch_result.refs[lh]
  2719. assert merge_ref is not None
  2720. _merge_result, conflicts = _do_merge(r, merge_ref)
  2721. if conflicts:
  2722. raise Error(
  2723. f"Merge conflicts occurred: {conflicts}"
  2724. ) from exc
  2725. merged = True
  2726. # Skip updating ref since merge already updated HEAD
  2727. continue
  2728. if rh is not None and lh is not None:
  2729. lh_value = fetch_result.refs[lh]
  2730. if lh_value is not None:
  2731. r.refs[rh] = lh_value
  2732. # Only update HEAD if we didn't perform a merge
  2733. if selected_refs and not merged:
  2734. lh, rh, _ = selected_refs[0]
  2735. if lh is not None:
  2736. ref_value = fetch_result.refs[lh]
  2737. if ref_value is not None:
  2738. r[b"HEAD"] = ref_value
  2739. # Update working tree to match the new HEAD
  2740. # Skip if merge was performed as merge already updates the working tree
  2741. if not merged and old_tree_id is not None:
  2742. head_commit = r[b"HEAD"]
  2743. assert isinstance(head_commit, Commit)
  2744. new_tree_id = head_commit.tree
  2745. blob_normalizer = r.get_blob_normalizer()
  2746. changes = tree_changes(r.object_store, old_tree_id, new_tree_id)
  2747. update_working_tree(
  2748. r,
  2749. old_tree_id,
  2750. new_tree_id,
  2751. change_iterator=changes,
  2752. blob_normalizer=blob_normalizer,
  2753. allow_overwrite_modified=force,
  2754. )
  2755. if remote_name is not None:
  2756. _import_remote_refs(r.refs, remote_name, fetch_result.refs)
  2757. # Trigger auto GC if needed
  2758. from .gc import maybe_auto_gc
  2759. with open_repo_closing(repo) as r:
  2760. maybe_auto_gc(r)
  2761. def status(
  2762. repo: str | os.PathLike[str] | Repo = ".",
  2763. ignored: bool = False,
  2764. untracked_files: str = "normal",
  2765. ) -> GitStatus:
  2766. """Returns staged, unstaged, and untracked changes relative to the HEAD.
  2767. Args:
  2768. repo: Path to repository or repository object
  2769. ignored: Whether to include ignored files in untracked
  2770. untracked_files: How to handle untracked files, defaults to "all":
  2771. "no": do not return untracked files
  2772. "normal": return untracked directories, not their contents
  2773. "all": include all files in untracked directories
  2774. Using untracked_files="no" can be faster than "all" when the worktree
  2775. contains many untracked files/directories.
  2776. Using untracked_files="normal" provides a good balance, only showing
  2777. directories that are entirely untracked without listing all their contents.
  2778. Returns: GitStatus tuple,
  2779. staged - dict with lists of staged paths (diff index/HEAD)
  2780. unstaged - list of unstaged paths (diff index/working-tree)
  2781. untracked - list of untracked, un-ignored & non-.git paths
  2782. """
  2783. with open_repo_closing(repo) as r:
  2784. # Open the index once and reuse it for both staged and unstaged checks
  2785. index = r.open_index()
  2786. # 1. Get status of staged
  2787. tracked_changes = get_tree_changes(r, index)
  2788. # 2. Get status of unstaged
  2789. normalizer = r.get_blob_normalizer()
  2790. # Create a wrapper that handles the bytes -> Blob conversion
  2791. if normalizer is not None:
  2792. def filter_callback(data: bytes, path: bytes) -> bytes:
  2793. blob = Blob()
  2794. blob.data = data
  2795. normalized_blob = normalizer.checkin_normalize(blob, path)
  2796. result_data: bytes = normalized_blob.data
  2797. return result_data
  2798. else:
  2799. filter_callback = None
  2800. # Check if core.preloadIndex is enabled
  2801. config = r.get_config_stack()
  2802. preload_index = config.get_boolean(b"core", b"preloadIndex", False)
  2803. unstaged_changes = list(
  2804. get_unstaged_changes(index, r.path, filter_callback, preload_index)
  2805. )
  2806. untracked_paths = get_untracked_paths(
  2807. r.path,
  2808. r.path,
  2809. index,
  2810. exclude_ignored=not ignored,
  2811. untracked_files=untracked_files,
  2812. )
  2813. if sys.platform == "win32":
  2814. untracked_changes = [
  2815. path.replace(os.path.sep, "/") for path in untracked_paths
  2816. ]
  2817. else:
  2818. untracked_changes = list(untracked_paths)
  2819. return GitStatus(tracked_changes, unstaged_changes, untracked_changes)
  2820. def shortlog(
  2821. repo: str | os.PathLike[str] | Repo,
  2822. summary_only: bool = False,
  2823. sort_by_commits: bool = False,
  2824. ) -> list[dict[str, str]]:
  2825. """Summarize commits by author, like git shortlog.
  2826. Args:
  2827. repo: Path to repository or Repo object.
  2828. summary_only: If True, only show counts per author.
  2829. sort_by_commits: If True, sort authors by number of commits.
  2830. Returns:
  2831. A list of dictionaries, each containing:
  2832. - "author": the author's name as a string
  2833. - "messages": all commit messages concatenated into a single string
  2834. """
  2835. with open_repo_closing(repo) as r:
  2836. walker = r.get_walker()
  2837. authors: dict[str, list[str]] = {}
  2838. for entry in walker:
  2839. commit = entry.commit
  2840. author = commit.author.decode(commit.encoding or "utf-8")
  2841. message = commit.message.decode(commit.encoding or "utf-8").strip()
  2842. authors.setdefault(author, []).append(message)
  2843. # Convert messages to single string per author
  2844. items: list[dict[str, str]] = [
  2845. {"author": author, "messages": "\n".join(msgs)}
  2846. for author, msgs in authors.items()
  2847. ]
  2848. if sort_by_commits:
  2849. # Sort by number of commits (lines in messages)
  2850. items.sort(key=lambda x: len(x["messages"].splitlines()), reverse=True)
  2851. return items
  2852. def _walk_working_dir_paths(
  2853. frompath: str | bytes | os.PathLike[str],
  2854. basepath: str | bytes | os.PathLike[str],
  2855. prune_dirnames: Callable[[str, list[str]], list[str]] | None = None,
  2856. ) -> Iterator[tuple[str | bytes, bool]]:
  2857. """Get path, is_dir for files in working dir from frompath.
  2858. Args:
  2859. frompath: Path to begin walk
  2860. basepath: Path to compare to
  2861. prune_dirnames: Optional callback to prune dirnames during os.walk
  2862. dirnames will be set to result of prune_dirnames(dirpath, dirnames)
  2863. """
  2864. # Convert paths to strings for os.walk compatibility
  2865. for dirpath, dirnames, filenames in os.walk(frompath): # type: ignore[type-var]
  2866. # Skip .git and below.
  2867. if ".git" in dirnames:
  2868. dirnames.remove(".git")
  2869. if dirpath != basepath:
  2870. continue
  2871. if ".git" in filenames:
  2872. filenames.remove(".git")
  2873. if dirpath != basepath:
  2874. continue
  2875. if dirpath != frompath:
  2876. yield dirpath, True # type: ignore[misc]
  2877. for filename in filenames:
  2878. filepath = os.path.join(dirpath, filename) # type: ignore[call-overload]
  2879. yield filepath, False
  2880. if prune_dirnames:
  2881. dirnames[:] = prune_dirnames(dirpath, dirnames) # type: ignore[arg-type]
  2882. def get_untracked_paths(
  2883. frompath: str | bytes | os.PathLike[str],
  2884. basepath: str | bytes | os.PathLike[str],
  2885. index: Index,
  2886. exclude_ignored: bool = False,
  2887. untracked_files: str = "all",
  2888. ) -> Iterator[str]:
  2889. """Get untracked paths.
  2890. Args:
  2891. frompath: Path to walk
  2892. basepath: Path to compare to
  2893. index: Index to check against
  2894. exclude_ignored: Whether to exclude ignored paths
  2895. untracked_files: How to handle untracked files:
  2896. - "no": return an empty list
  2897. - "all": return all files in untracked directories
  2898. - "normal": return untracked directories without listing their contents
  2899. Note: ignored directories will never be walked for performance reasons.
  2900. If exclude_ignored is False, only the path to an ignored directory will
  2901. be yielded, no files inside the directory will be returned
  2902. """
  2903. if untracked_files not in ("no", "all", "normal"):
  2904. raise ValueError("untracked_files must be one of (no, all, normal)")
  2905. if untracked_files == "no":
  2906. return
  2907. # Normalize paths to str
  2908. frompath_str = os.fsdecode(os.fspath(frompath))
  2909. basepath_str = os.fsdecode(os.fspath(basepath))
  2910. with open_repo_closing(basepath_str) as r:
  2911. ignore_manager = IgnoreFilterManager.from_repo(r)
  2912. ignored_dirs = []
  2913. # List to store untracked directories found during traversal
  2914. untracked_dir_list = []
  2915. def directory_has_non_ignored_files(dir_path: str, base_rel_path: str) -> bool:
  2916. """Recursively check if directory contains any non-ignored files."""
  2917. try:
  2918. for entry in os.listdir(dir_path):
  2919. entry_path = os.path.join(dir_path, entry)
  2920. rel_entry = os.path.join(base_rel_path, entry)
  2921. if os.path.isfile(entry_path):
  2922. if ignore_manager.is_ignored(rel_entry) is not True:
  2923. return True
  2924. elif os.path.isdir(entry_path):
  2925. if directory_has_non_ignored_files(entry_path, rel_entry):
  2926. return True
  2927. return False
  2928. except OSError:
  2929. # If we can't read the directory, assume it has non-ignored files
  2930. return True
  2931. def prune_dirnames(dirpath: str, dirnames: list[str]) -> list[str]:
  2932. for i in range(len(dirnames) - 1, -1, -1):
  2933. path = os.path.join(dirpath, dirnames[i])
  2934. ip = os.path.join(os.path.relpath(path, basepath_str), "")
  2935. # Check if directory is ignored
  2936. if ignore_manager.is_ignored(ip) is True:
  2937. if not exclude_ignored:
  2938. ignored_dirs.append(
  2939. os.path.join(os.path.relpath(path, frompath_str), "")
  2940. )
  2941. del dirnames[i]
  2942. continue
  2943. # For "normal" mode, check if the directory is entirely untracked
  2944. if untracked_files == "normal":
  2945. # Convert directory path to tree path for index lookup
  2946. dir_tree_path = path_to_tree_path(basepath_str, path)
  2947. # Check if any file in this directory is tracked
  2948. dir_prefix = dir_tree_path + b"/" if dir_tree_path else b""
  2949. has_tracked_files = any(name.startswith(dir_prefix) for name in index)
  2950. if not has_tracked_files:
  2951. # This directory is entirely untracked
  2952. rel_path_base = os.path.relpath(path, basepath_str)
  2953. rel_path_from = os.path.join(
  2954. os.path.relpath(path, frompath_str), ""
  2955. )
  2956. # If excluding ignored, check if directory contains any non-ignored files
  2957. if exclude_ignored:
  2958. if not directory_has_non_ignored_files(path, rel_path_base):
  2959. # Directory only contains ignored files, skip it
  2960. del dirnames[i]
  2961. continue
  2962. # Check if it should be excluded due to ignore rules
  2963. is_ignored = ignore_manager.is_ignored(rel_path_base)
  2964. if not exclude_ignored or not is_ignored:
  2965. untracked_dir_list.append(rel_path_from)
  2966. del dirnames[i]
  2967. return dirnames
  2968. # For "all" mode, use the original behavior
  2969. if untracked_files == "all":
  2970. for ap, is_dir in _walk_working_dir_paths(
  2971. frompath_str, basepath_str, prune_dirnames=prune_dirnames
  2972. ):
  2973. # frompath_str and basepath_str are both str, so ap must be str
  2974. assert isinstance(ap, str)
  2975. if not is_dir:
  2976. ip = path_to_tree_path(basepath_str, ap)
  2977. if ip not in index:
  2978. if not exclude_ignored or not ignore_manager.is_ignored(
  2979. os.path.relpath(ap, basepath_str)
  2980. ):
  2981. yield os.path.relpath(ap, frompath_str)
  2982. else: # "normal" mode
  2983. # Walk directories, handling both files and directories
  2984. for ap, is_dir in _walk_working_dir_paths(
  2985. frompath_str, basepath_str, prune_dirnames=prune_dirnames
  2986. ):
  2987. # frompath_str and basepath_str are both str, so ap must be str
  2988. assert isinstance(ap, str)
  2989. # This part won't be reached for pruned directories
  2990. if is_dir:
  2991. # Check if this directory is entirely untracked
  2992. dir_tree_path = path_to_tree_path(basepath_str, ap)
  2993. dir_prefix = dir_tree_path + b"/" if dir_tree_path else b""
  2994. has_tracked_files = any(name.startswith(dir_prefix) for name in index)
  2995. if not has_tracked_files:
  2996. if not exclude_ignored or not ignore_manager.is_ignored(
  2997. os.path.relpath(ap, basepath_str)
  2998. ):
  2999. yield os.path.join(os.path.relpath(ap, frompath_str), "")
  3000. else:
  3001. # Check individual files in directories that contain tracked files
  3002. ip = path_to_tree_path(basepath_str, ap)
  3003. if ip not in index:
  3004. if not exclude_ignored or not ignore_manager.is_ignored(
  3005. os.path.relpath(ap, basepath_str)
  3006. ):
  3007. yield os.path.relpath(ap, frompath_str)
  3008. # Yield any untracked directories found during pruning
  3009. yield from untracked_dir_list
  3010. yield from ignored_dirs
  3011. def grep(
  3012. repo: RepoPath,
  3013. pattern: str | bytes,
  3014. *,
  3015. outstream: TextIO = sys.stdout,
  3016. rev: str | bytes | None = None,
  3017. pathspecs: Sequence[str | bytes] | None = None,
  3018. ignore_case: bool = False,
  3019. line_number: bool = False,
  3020. max_depth: int | None = None,
  3021. respect_ignores: bool = True,
  3022. ) -> None:
  3023. """Search for a pattern in tracked files.
  3024. Args:
  3025. repo: Path to repository or Repo object
  3026. pattern: Regular expression pattern to search for
  3027. outstream: Stream to write results to
  3028. rev: Revision to search in (defaults to HEAD)
  3029. pathspecs: Optional list of path patterns to limit search
  3030. ignore_case: Whether to perform case-insensitive matching
  3031. line_number: Whether to output line numbers
  3032. max_depth: Maximum directory depth to search
  3033. respect_ignores: Whether to respect .gitignore patterns
  3034. """
  3035. from .object_store import iter_tree_contents
  3036. # Compile the pattern
  3037. flags = re.IGNORECASE if ignore_case else 0
  3038. try:
  3039. if isinstance(pattern, bytes):
  3040. compiled_pattern = re.compile(pattern, flags)
  3041. else:
  3042. compiled_pattern = re.compile(pattern.encode("utf-8"), flags)
  3043. except re.error as e:
  3044. raise ValueError(f"Invalid regular expression: {e}") from e
  3045. with open_repo_closing(repo) as r:
  3046. # Get the tree to search
  3047. if rev is None:
  3048. try:
  3049. commit = r[b"HEAD"]
  3050. assert isinstance(commit, Commit)
  3051. except KeyError as e:
  3052. raise ValueError("No HEAD commit found") from e
  3053. else:
  3054. rev_bytes = rev if isinstance(rev, bytes) else rev.encode("utf-8")
  3055. commit_obj = parse_commit(r, rev_bytes)
  3056. if commit_obj is None:
  3057. raise ValueError(f"Invalid revision: {rev}")
  3058. commit = commit_obj
  3059. tree = r[commit.tree]
  3060. assert isinstance(tree, Tree)
  3061. # Set up ignore filter if requested
  3062. ignore_manager = None
  3063. if respect_ignores:
  3064. ignore_manager = IgnoreFilterManager.from_repo(r)
  3065. # Convert pathspecs to bytes
  3066. pathspecs_bytes: list[bytes] | None = None
  3067. if pathspecs:
  3068. pathspecs_bytes = [
  3069. p if isinstance(p, bytes) else p.encode("utf-8") for p in pathspecs
  3070. ]
  3071. # Iterate through all files in the tree
  3072. for entry in iter_tree_contents(r.object_store, tree.id):
  3073. path, mode, sha = entry.path, entry.mode, entry.sha
  3074. assert path is not None
  3075. assert mode is not None
  3076. assert sha is not None
  3077. # Skip directories
  3078. if stat.S_ISDIR(mode):
  3079. continue
  3080. # Check max depth
  3081. if max_depth is not None:
  3082. depth = path.count(b"/")
  3083. if depth > max_depth:
  3084. continue
  3085. # Check pathspecs
  3086. if pathspecs_bytes:
  3087. matches_pathspec = False
  3088. for pathspec in pathspecs_bytes:
  3089. # Simple prefix matching (could be enhanced with full pathspec support)
  3090. if path.startswith(pathspec) or fnmatch.fnmatch(
  3091. path.decode("utf-8", errors="replace"),
  3092. pathspec.decode("utf-8", errors="replace"),
  3093. ):
  3094. matches_pathspec = True
  3095. break
  3096. if not matches_pathspec:
  3097. continue
  3098. # Check ignore patterns
  3099. if ignore_manager:
  3100. path_str = path.decode("utf-8", errors="replace")
  3101. if ignore_manager.is_ignored(path_str) is True:
  3102. continue
  3103. # Get the blob content
  3104. blob = r[sha]
  3105. assert isinstance(blob, Blob)
  3106. # Search for pattern in the blob
  3107. content = blob.data
  3108. lines = content.split(b"\n")
  3109. for line_num, line in enumerate(lines, 1):
  3110. if compiled_pattern.search(line):
  3111. path_str = path.decode("utf-8", errors="replace")
  3112. line_str = line.decode("utf-8", errors="replace")
  3113. if line_number:
  3114. outstream.write(f"{path_str}:{line_num}:{line_str}\n")
  3115. else:
  3116. outstream.write(f"{path_str}:{line_str}\n")
  3117. def get_tree_changes(
  3118. repo: RepoPath, index: Index | None = None
  3119. ) -> dict[str, list[str | bytes]]:
  3120. """Return add/delete/modify changes to tree by comparing index to HEAD.
  3121. Args:
  3122. repo: repo path or object
  3123. index: optional Index object to reuse (avoids re-opening the index)
  3124. Returns: dict with lists for each type of change
  3125. """
  3126. with open_repo_closing(repo) as r:
  3127. if index is None:
  3128. index = r.open_index()
  3129. # Compares the Index to the HEAD & determines changes
  3130. # Iterate through the changes and report add/delete/modify
  3131. # TODO: call out to dulwich.diff_tree somehow.
  3132. tracked_changes: dict[str, list[str | bytes]] = {
  3133. "add": [],
  3134. "delete": [],
  3135. "modify": [],
  3136. }
  3137. try:
  3138. head_commit = r[b"HEAD"]
  3139. assert isinstance(head_commit, Commit)
  3140. tree_id = head_commit.tree
  3141. except KeyError:
  3142. tree_id = None
  3143. for change in index.changes_from_tree(r.object_store, tree_id):
  3144. if not change[0][0]:
  3145. assert change[0][1] is not None
  3146. tracked_changes["add"].append(change[0][1])
  3147. elif not change[0][1]:
  3148. assert change[0][0] is not None
  3149. tracked_changes["delete"].append(change[0][0])
  3150. elif change[0][0] == change[0][1]:
  3151. assert change[0][0] is not None
  3152. tracked_changes["modify"].append(change[0][0])
  3153. else:
  3154. raise NotImplementedError("git mv ops not yet supported")
  3155. return tracked_changes
  3156. def daemon(
  3157. path: str | os.PathLike[str] = ".",
  3158. address: str | None = None,
  3159. port: int | None = None,
  3160. ) -> None:
  3161. """Run a daemon serving Git requests over TCP/IP.
  3162. Args:
  3163. path: Path to the directory to serve.
  3164. address: Optional address to listen on (defaults to ::)
  3165. port: Optional port to listen on (defaults to TCP_GIT_PORT)
  3166. """
  3167. # TODO(jelmer): Support git-daemon-export-ok and --export-all.
  3168. backend = FileSystemBackend(os.fspath(path))
  3169. server = TCPGitServer(backend, address or "localhost", port or 9418)
  3170. server.serve_forever()
  3171. def web_daemon(
  3172. path: str | os.PathLike[str] = ".",
  3173. address: str | None = None,
  3174. port: int | None = None,
  3175. ) -> None:
  3176. """Run a daemon serving Git requests over HTTP.
  3177. Args:
  3178. path: Path to the directory to serve
  3179. address: Optional address to listen on (defaults to ::)
  3180. port: Optional port to listen on (defaults to 80)
  3181. """
  3182. from .web import (
  3183. WSGIRequestHandlerLogger,
  3184. WSGIServerLogger,
  3185. make_server,
  3186. make_wsgi_chain,
  3187. )
  3188. backend = FileSystemBackend(os.fspath(path))
  3189. app = make_wsgi_chain(backend)
  3190. server = make_server(
  3191. address or "::",
  3192. port or 80,
  3193. app,
  3194. handler_class=WSGIRequestHandlerLogger,
  3195. server_class=WSGIServerLogger,
  3196. )
  3197. server.serve_forever()
  3198. def upload_pack(
  3199. path: str | os.PathLike[str] = ".",
  3200. inf: BinaryIO | None = None,
  3201. outf: BinaryIO | None = None,
  3202. ) -> int:
  3203. """Upload a pack file after negotiating its contents using smart protocol.
  3204. Args:
  3205. path: Path to the repository
  3206. inf: Input stream to communicate with client
  3207. outf: Output stream to communicate with client
  3208. """
  3209. if outf is None:
  3210. outf = sys.stdout.buffer
  3211. if inf is None:
  3212. inf = sys.stdin.buffer
  3213. assert outf is not None
  3214. assert inf is not None
  3215. path = os.path.expanduser(path)
  3216. backend = FileSystemBackend(path)
  3217. def send_fn(data: bytes) -> None:
  3218. outf.write(data)
  3219. outf.flush()
  3220. proto = Protocol(inf.read, send_fn)
  3221. handler = UploadPackHandler(backend, [path], proto)
  3222. # FIXME: Catch exceptions and write a single-line summary to outf.
  3223. handler.handle()
  3224. return 0
  3225. def receive_pack(
  3226. path: str | os.PathLike[str] = ".",
  3227. inf: BinaryIO | None = None,
  3228. outf: BinaryIO | None = None,
  3229. ) -> int:
  3230. """Receive a pack file after negotiating its contents using smart protocol.
  3231. Args:
  3232. path: Path to the repository
  3233. inf: Input stream to communicate with client
  3234. outf: Output stream to communicate with client
  3235. """
  3236. if outf is None:
  3237. outf = sys.stdout.buffer
  3238. if inf is None:
  3239. inf = sys.stdin.buffer
  3240. assert outf is not None
  3241. assert inf is not None
  3242. path = os.path.expanduser(path)
  3243. backend = FileSystemBackend(path)
  3244. def send_fn(data: bytes) -> None:
  3245. outf.write(data)
  3246. outf.flush()
  3247. proto = Protocol(inf.read, send_fn)
  3248. handler = ReceivePackHandler(backend, [path], proto)
  3249. # FIXME: Catch exceptions and write a single-line summary to outf.
  3250. handler.handle()
  3251. return 0
  3252. def _make_branch_ref(name: str | bytes) -> Ref:
  3253. if isinstance(name, str):
  3254. name = name.encode(DEFAULT_ENCODING)
  3255. return local_branch_name(name)
  3256. def _make_tag_ref(name: str | bytes) -> Ref:
  3257. if isinstance(name, str):
  3258. name = name.encode(DEFAULT_ENCODING)
  3259. return local_tag_name(name)
  3260. def _make_replace_ref(name: str | bytes) -> Ref:
  3261. if isinstance(name, str):
  3262. name = name.encode(DEFAULT_ENCODING)
  3263. return local_replace_name(name)
  3264. def branch_delete(repo: RepoPath, name: str | bytes | Sequence[str | bytes]) -> None:
  3265. """Delete a branch.
  3266. Args:
  3267. repo: Path to the repository
  3268. name: Name of the branch
  3269. """
  3270. with open_repo_closing(repo) as r:
  3271. if isinstance(name, (list, tuple)):
  3272. names = name
  3273. else:
  3274. names = [name]
  3275. for branch_name in names:
  3276. del r.refs[_make_branch_ref(branch_name)]
  3277. def branch_create(
  3278. repo: str | os.PathLike[str] | Repo,
  3279. name: str | bytes,
  3280. objectish: str | bytes | None = None,
  3281. force: bool = False,
  3282. ) -> None:
  3283. """Create a branch.
  3284. Args:
  3285. repo: Path to the repository
  3286. name: Name of the new branch
  3287. objectish: Target object to point new branch at (defaults to HEAD)
  3288. force: Force creation of branch, even if it already exists
  3289. """
  3290. with open_repo_closing(repo) as r:
  3291. if objectish is None:
  3292. objectish = "HEAD"
  3293. # Try to expand branch shorthand before parsing
  3294. original_objectish = objectish
  3295. objectish_bytes = (
  3296. objectish.encode(DEFAULT_ENCODING)
  3297. if isinstance(objectish, str)
  3298. else objectish
  3299. )
  3300. if b"refs/remotes/" + objectish_bytes in r.refs:
  3301. objectish = b"refs/remotes/" + objectish_bytes
  3302. elif local_branch_name(objectish_bytes) in r.refs:
  3303. objectish = local_branch_name(objectish_bytes)
  3304. object = parse_object(r, objectish)
  3305. refname = _make_branch_ref(name)
  3306. default_message = (
  3307. b"branch: Created from " + original_objectish.encode(DEFAULT_ENCODING)
  3308. if isinstance(original_objectish, str)
  3309. else b"branch: Created from " + original_objectish
  3310. )
  3311. ref_message = _get_reflog_message(default_message)
  3312. if force:
  3313. r.refs.set_if_equals(refname, None, object.id, message=ref_message)
  3314. else:
  3315. if not r.refs.add_if_new(refname, object.id, message=ref_message):
  3316. name_str = name.decode() if isinstance(name, bytes) else name
  3317. raise Error(f"Branch with name {name_str} already exists.")
  3318. # Check if we should set up tracking
  3319. config = r.get_config_stack()
  3320. try:
  3321. auto_setup_merge = config.get((b"branch",), b"autoSetupMerge").decode()
  3322. except KeyError:
  3323. auto_setup_merge = "true" # Default value
  3324. # Determine if the objectish refers to a remote-tracking branch
  3325. objectish_ref = None
  3326. if original_objectish != "HEAD":
  3327. # Try to resolve objectish as a ref
  3328. objectish_bytes = (
  3329. original_objectish.encode(DEFAULT_ENCODING)
  3330. if isinstance(original_objectish, str)
  3331. else original_objectish
  3332. )
  3333. if objectish_bytes in r.refs:
  3334. objectish_ref = objectish_bytes
  3335. elif b"refs/remotes/" + objectish_bytes in r.refs:
  3336. objectish_ref = b"refs/remotes/" + objectish_bytes
  3337. elif local_branch_name(objectish_bytes) in r.refs:
  3338. objectish_ref = local_branch_name(objectish_bytes)
  3339. else:
  3340. # HEAD might point to a remote-tracking branch
  3341. head_ref = r.refs.follow(b"HEAD")[0][1]
  3342. if head_ref.startswith(b"refs/remotes/"):
  3343. objectish_ref = head_ref
  3344. # Set up tracking if appropriate
  3345. if objectish_ref and (
  3346. (auto_setup_merge == "always")
  3347. or (
  3348. auto_setup_merge == "true"
  3349. and objectish_ref.startswith(b"refs/remotes/")
  3350. )
  3351. ):
  3352. # Extract remote name and branch from the ref
  3353. if objectish_ref.startswith(b"refs/remotes/"):
  3354. parts = objectish_ref[len(b"refs/remotes/") :].split(b"/", 1)
  3355. if len(parts) == 2:
  3356. remote_name = parts[0]
  3357. remote_branch = local_branch_name(parts[1])
  3358. # Set up tracking
  3359. repo_config = r.get_config()
  3360. branch_name_bytes = (
  3361. name.encode(DEFAULT_ENCODING) if isinstance(name, str) else name
  3362. )
  3363. repo_config.set(
  3364. (b"branch", branch_name_bytes), b"remote", remote_name
  3365. )
  3366. repo_config.set(
  3367. (b"branch", branch_name_bytes), b"merge", remote_branch
  3368. )
  3369. repo_config.write_to_path()
  3370. def filter_branches_by_pattern(branches: Iterable[bytes], pattern: str) -> list[bytes]:
  3371. """Filter branches by fnmatch pattern.
  3372. Args:
  3373. branches: Iterable of branch names as bytes
  3374. pattern: Pattern to match against
  3375. Returns:
  3376. List of filtered branch names
  3377. """
  3378. return [
  3379. branch for branch in branches if fnmatch.fnmatchcase(branch.decode(), pattern)
  3380. ]
  3381. def branch_list(repo: RepoPath) -> list[bytes]:
  3382. """List all branches.
  3383. Args:
  3384. repo: Path to the repository
  3385. Returns:
  3386. List of branch names (without refs/heads/ prefix)
  3387. """
  3388. with open_repo_closing(repo) as r:
  3389. branches = list(r.refs.keys(base=LOCAL_BRANCH_PREFIX))
  3390. # Check for branch.sort configuration
  3391. config = r.get_config_stack()
  3392. try:
  3393. sort_key = config.get((b"branch",), b"sort").decode()
  3394. except KeyError:
  3395. # Default is refname (alphabetical)
  3396. sort_key = "refname"
  3397. # Parse sort key
  3398. reverse = False
  3399. if sort_key.startswith("-"):
  3400. reverse = True
  3401. sort_key = sort_key[1:]
  3402. # Apply sorting
  3403. if sort_key == "refname":
  3404. # Simple alphabetical sort (default)
  3405. branches.sort(reverse=reverse)
  3406. elif sort_key in ("committerdate", "authordate"):
  3407. # Sort by date
  3408. def get_commit_date(branch_name: bytes) -> int:
  3409. ref = local_branch_name(branch_name)
  3410. sha = r.refs[ref]
  3411. commit = r.object_store[sha]
  3412. assert isinstance(commit, Commit)
  3413. if sort_key == "committerdate":
  3414. return cast(int, commit.commit_time)
  3415. else: # authordate
  3416. return cast(int, commit.author_time)
  3417. # Sort branches by date
  3418. # Note: Python's sort naturally orders smaller values first (ascending)
  3419. # For dates, this means oldest first by default
  3420. # Use a stable sort with branch name as secondary key for consistent ordering
  3421. if reverse:
  3422. # For reverse sort, we want newest dates first but alphabetical names second
  3423. branches.sort(key=lambda b: (-get_commit_date(b), b))
  3424. else:
  3425. branches.sort(key=lambda b: (get_commit_date(b), b))
  3426. else:
  3427. # Unknown sort key, fall back to default
  3428. branches.sort()
  3429. return branches
  3430. def branch_remotes_list(repo: RepoPath) -> list[bytes]:
  3431. """List the short names of all remote branches.
  3432. Args:
  3433. repo: Path to the repository
  3434. Returns:
  3435. List of branch names (without refs/remotes/ prefix, and without remote name; e.g. 'main' from 'origin/main')
  3436. """
  3437. with open_repo_closing(repo) as r:
  3438. branches = list(r.refs.keys(base=LOCAL_REMOTE_PREFIX))
  3439. config = r.get_config_stack()
  3440. try:
  3441. sort_key = config.get((b"branch",), b"sort").decode()
  3442. except KeyError:
  3443. # Default is refname (alphabetical)
  3444. sort_key = "refname"
  3445. # Parse sort key
  3446. reverse = False
  3447. if sort_key.startswith("-"):
  3448. reverse = True
  3449. sort_key = sort_key[1:]
  3450. # Apply sorting
  3451. if sort_key == "refname":
  3452. # Simple alphabetical sort (default)
  3453. branches.sort(reverse=reverse)
  3454. elif sort_key in ("committerdate", "authordate"):
  3455. # Sort by date
  3456. def get_commit_date(branch_name: bytes) -> int:
  3457. ref = LOCAL_REMOTE_PREFIX + branch_name
  3458. sha = r.refs[ref]
  3459. commit = r.object_store[sha]
  3460. assert isinstance(commit, Commit)
  3461. if sort_key == "committerdate":
  3462. return cast(int, commit.commit_time)
  3463. else: # authordate
  3464. return cast(int, commit.author_time)
  3465. # Sort branches by date
  3466. # Note: Python's sort naturally orders smaller values first (ascending)
  3467. # For dates, this means oldest first by default
  3468. # Use a stable sort with branch name as secondary key for consistent ordering
  3469. if reverse:
  3470. # For reverse sort, we want newest dates first but alphabetical names second
  3471. branches.sort(key=lambda b: (-get_commit_date(b), b))
  3472. else:
  3473. branches.sort(key=lambda b: (get_commit_date(b), b))
  3474. else:
  3475. # Unknown sort key
  3476. raise ValueError(f"Unknown sort key: {sort_key}")
  3477. return branches
  3478. def _get_branch_merge_status(repo: RepoPath) -> Iterator[tuple[bytes, bool]]:
  3479. """Get merge status for all branches relative to current HEAD.
  3480. Args:
  3481. repo: Path to the repository
  3482. Yields:
  3483. Tuple of (``branch_name``, ``is_merged``) where:
  3484. - ``branch_name``: Branch name without refs/heads/ prefix
  3485. - ``is_merged``: True if branch is merged into HEAD, False otherwise
  3486. """
  3487. with open_repo_closing(repo) as r:
  3488. current_sha = r.refs[b"HEAD"]
  3489. for branch_ref, branch_sha in r.refs.as_dict(base=b"refs/heads/").items():
  3490. # Check if branch is an ancestor of HEAD (fully merged)
  3491. is_merged = can_fast_forward(r, branch_sha, current_sha)
  3492. yield branch_ref, is_merged
  3493. def merged_branches(repo: RepoPath) -> Iterator[bytes]:
  3494. """List branches that have been merged into the current branch.
  3495. Args:
  3496. repo: Path to the repository
  3497. Yields:
  3498. Branch names (without refs/heads/ prefix) that are merged
  3499. into the current HEAD
  3500. """
  3501. for branch_name, is_merged in _get_branch_merge_status(repo):
  3502. if is_merged:
  3503. yield branch_name
  3504. def no_merged_branches(repo: RepoPath) -> Iterator[bytes]:
  3505. """List branches that have been merged into the current branch.
  3506. Args:
  3507. repo: Path to the repository
  3508. Yields:
  3509. Branch names (without refs/heads/ prefix) that are merged
  3510. into the current HEAD
  3511. """
  3512. for branch_name, is_merged in _get_branch_merge_status(repo):
  3513. if not is_merged:
  3514. yield branch_name
  3515. def branches_containing(repo: RepoPath, commit: str) -> Iterator[bytes]:
  3516. """List branches that contain the specified commit.
  3517. Args:
  3518. repo: Path to the repository
  3519. commit: Commit-ish string (SHA, branch name, tag, etc.)
  3520. Yields:
  3521. Branch names (without refs/heads/ prefix) that contain the commit
  3522. Raises:
  3523. ValueError: If the commit reference is malformed
  3524. KeyError: If the commit reference does not exist
  3525. """
  3526. with open_repo_closing(repo) as r:
  3527. commit_obj = parse_commit(r, commit)
  3528. commit_sha = commit_obj.id
  3529. for branch_ref, branch_sha in r.refs.as_dict(base=LOCAL_BRANCH_PREFIX).items():
  3530. if can_fast_forward(r, commit_sha, branch_sha):
  3531. yield branch_ref
  3532. def active_branch(repo: RepoPath) -> bytes:
  3533. """Return the active branch in the repository, if any.
  3534. Args:
  3535. repo: Repository to open
  3536. Returns:
  3537. branch name
  3538. Raises:
  3539. KeyError: if the repository does not have a working tree
  3540. IndexError: if HEAD is floating
  3541. """
  3542. with open_repo_closing(repo) as r:
  3543. active_ref = r.refs.follow(b"HEAD")[0][1]
  3544. if not active_ref.startswith(LOCAL_BRANCH_PREFIX):
  3545. raise ValueError(active_ref)
  3546. return active_ref[len(LOCAL_BRANCH_PREFIX) :]
  3547. def get_branch_remote(repo: str | os.PathLike[str] | Repo) -> bytes:
  3548. """Return the active branch's remote name, if any.
  3549. Args:
  3550. repo: Repository to open
  3551. Returns:
  3552. remote name
  3553. Raises:
  3554. KeyError: if the repository does not have a working tree
  3555. """
  3556. with open_repo_closing(repo) as r:
  3557. branch_name = active_branch(r.path)
  3558. config = r.get_config()
  3559. try:
  3560. remote_name = config.get((b"branch", branch_name), b"remote")
  3561. except KeyError:
  3562. remote_name = b"origin"
  3563. return remote_name
  3564. def get_branch_merge(repo: RepoPath, branch_name: bytes | None = None) -> bytes:
  3565. """Return the branch's merge reference (upstream branch), if any.
  3566. Args:
  3567. repo: Repository to open
  3568. branch_name: Name of the branch (defaults to active branch)
  3569. Returns:
  3570. merge reference name (e.g. b"refs/heads/main")
  3571. Raises:
  3572. KeyError: if the branch does not have a merge configuration
  3573. """
  3574. with open_repo_closing(repo) as r:
  3575. if branch_name is None:
  3576. branch_name = active_branch(r.path)
  3577. config = r.get_config()
  3578. return config.get((b"branch", branch_name), b"merge")
  3579. def set_branch_tracking(
  3580. repo: str | os.PathLike[str] | Repo,
  3581. branch_name: bytes,
  3582. remote_name: bytes,
  3583. remote_ref: bytes,
  3584. ) -> None:
  3585. """Set up branch tracking configuration.
  3586. Args:
  3587. repo: Repository to open
  3588. branch_name: Name of the local branch
  3589. remote_name: Name of the remote (e.g. b"origin")
  3590. remote_ref: Remote reference to track (e.g. b"refs/heads/main")
  3591. """
  3592. with open_repo_closing(repo) as r:
  3593. config = r.get_config()
  3594. config.set((b"branch", branch_name), b"remote", remote_name)
  3595. config.set((b"branch", branch_name), b"merge", remote_ref)
  3596. config.write_to_path()
  3597. def fetch(
  3598. repo: RepoPath,
  3599. remote_location: str | bytes | None = None,
  3600. outstream: TextIO = sys.stdout,
  3601. errstream: BinaryIO | RawIOBase = default_bytes_err_stream,
  3602. message: bytes | None = None,
  3603. depth: int | None = None,
  3604. prune: bool = False,
  3605. prune_tags: bool = False,
  3606. force: bool = False,
  3607. operation: str | None = None,
  3608. thin_packs: bool = True,
  3609. report_activity: Callable[[int, str], None] | None = None,
  3610. quiet: bool = False,
  3611. include_tags: bool = False,
  3612. username: str | None = None,
  3613. password: str | None = None,
  3614. key_filename: str | None = None,
  3615. ssh_command: str | None = None,
  3616. shallow_since: str | None = None,
  3617. shallow_exclude: list[str] | None = None,
  3618. ) -> FetchPackResult:
  3619. """Fetch objects from a remote server.
  3620. Args:
  3621. repo: Path to the repository
  3622. remote_location: String identifying a remote server
  3623. outstream: Output stream (defaults to stdout)
  3624. errstream: Error stream (defaults to stderr)
  3625. message: Reflog message (defaults to b"fetch: from <remote_name>")
  3626. depth: Depth to fetch at
  3627. prune: Prune remote removed refs
  3628. prune_tags: Prune remote removed tags
  3629. force: Force fetching even if it would overwrite local changes
  3630. operation: Git operation for authentication (e.g., "fetch")
  3631. thin_packs: Whether to use thin packs
  3632. report_activity: Optional callback for reporting transport activity
  3633. quiet: Whether to suppress progress output
  3634. include_tags: Whether to include tags
  3635. username: Username for authentication
  3636. password: Password for authentication
  3637. key_filename: SSH key filename
  3638. ssh_command: SSH command to use
  3639. shallow_since: Deepen or shorten the history to include commits after this date
  3640. shallow_exclude: Deepen or shorten the history to exclude commits reachable from these refs
  3641. Returns:
  3642. Dictionary with refs on the remote
  3643. """
  3644. with open_repo_closing(repo) as r:
  3645. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  3646. default_message = b"fetch: from " + remote_location.encode(DEFAULT_ENCODING)
  3647. message = _get_reflog_message(default_message, message)
  3648. client, path = get_transport_and_path(
  3649. remote_location,
  3650. config=r.get_config_stack(),
  3651. operation=operation,
  3652. thin_packs=thin_packs,
  3653. report_activity=report_activity,
  3654. quiet=quiet,
  3655. include_tags=include_tags,
  3656. username=username,
  3657. password=password,
  3658. key_filename=key_filename,
  3659. ssh_command=ssh_command,
  3660. )
  3661. def progress(data: bytes) -> None:
  3662. errstream.write(data)
  3663. fetch_result = client.fetch(
  3664. path.encode(),
  3665. r,
  3666. progress=progress,
  3667. depth=depth,
  3668. shallow_since=shallow_since,
  3669. shallow_exclude=shallow_exclude,
  3670. )
  3671. if remote_name is not None:
  3672. _import_remote_refs(
  3673. r.refs,
  3674. remote_name,
  3675. fetch_result.refs,
  3676. message,
  3677. prune=prune,
  3678. prune_tags=prune_tags,
  3679. )
  3680. # Trigger auto GC if needed
  3681. from .gc import maybe_auto_gc
  3682. with open_repo_closing(repo) as r:
  3683. maybe_auto_gc(r)
  3684. return fetch_result
  3685. def for_each_ref(
  3686. repo: Repo | str = ".",
  3687. pattern: str | bytes | None = None,
  3688. ) -> list[tuple[bytes, bytes, bytes]]:
  3689. """Iterate over all refs that match the (optional) pattern.
  3690. Args:
  3691. repo: Path to the repository
  3692. pattern: Optional glob (7) patterns to filter the refs with
  3693. Returns: List of bytes tuples with: (sha, object_type, ref_name)
  3694. """
  3695. if isinstance(pattern, str):
  3696. pattern = os.fsencode(pattern)
  3697. with open_repo_closing(repo) as r:
  3698. refs = r.get_refs()
  3699. if pattern:
  3700. matching_refs: dict[bytes, bytes] = {}
  3701. pattern_parts = pattern.split(b"/")
  3702. for ref, sha in refs.items():
  3703. matches = False
  3704. # git for-each-ref uses glob (7) style patterns, but fnmatch
  3705. # is greedy and also matches slashes, unlike glob.glob.
  3706. # We have to check parts of the pattern individually.
  3707. # See https://github.com/python/cpython/issues/72904
  3708. ref_parts = ref.split(b"/")
  3709. if len(ref_parts) > len(pattern_parts):
  3710. continue
  3711. for pat, ref_part in zip(pattern_parts, ref_parts):
  3712. matches = fnmatch.fnmatchcase(ref_part, pat)
  3713. if not matches:
  3714. break
  3715. if matches:
  3716. matching_refs[ref] = sha
  3717. refs = matching_refs
  3718. ret: list[tuple[bytes, bytes, bytes]] = [
  3719. (sha, r.get_object(sha).type_name, ref)
  3720. for ref, sha in sorted(
  3721. refs.items(),
  3722. key=lambda ref_sha: ref_sha[0],
  3723. )
  3724. if ref != b"HEAD"
  3725. ]
  3726. return ret
  3727. def show_ref(
  3728. repo: Repo | str = ".",
  3729. patterns: list[str | bytes] | None = None,
  3730. head: bool = False,
  3731. branches: bool = False,
  3732. tags: bool = False,
  3733. dereference: bool = False,
  3734. verify: bool = False,
  3735. ) -> list[tuple[bytes, bytes]]:
  3736. """List references in a local repository.
  3737. Args:
  3738. repo: Path to the repository
  3739. patterns: Optional list of patterns to filter refs (matched from the end)
  3740. head: Show the HEAD reference
  3741. branches: Limit to local branches (refs/heads/)
  3742. tags: Limit to local tags (refs/tags/)
  3743. dereference: Dereference tags into object IDs
  3744. verify: Enable stricter reference checking (exact path match)
  3745. Returns: List of tuples with (sha, ref_name) or (sha, ref_name^{}) for dereferenced tags
  3746. """
  3747. # Convert string patterns to bytes
  3748. byte_patterns: list[bytes] | None = None
  3749. if patterns:
  3750. byte_patterns = [os.fsencode(p) if isinstance(p, str) else p for p in patterns]
  3751. with open_repo_closing(repo) as r:
  3752. refs = r.get_refs()
  3753. # Filter by branches/tags if specified
  3754. if branches or tags:
  3755. prefixes = []
  3756. if branches:
  3757. prefixes.append(LOCAL_BRANCH_PREFIX)
  3758. if tags:
  3759. prefixes.append(LOCAL_TAG_PREFIX)
  3760. filtered_refs = filter_ref_prefix(refs, prefixes)
  3761. else:
  3762. # By default, show tags, heads, and remote refs (but not HEAD)
  3763. filtered_refs = filter_ref_prefix(refs, [b"refs/"])
  3764. # Add HEAD if requested
  3765. if head and b"HEAD" in refs:
  3766. filtered_refs[b"HEAD"] = refs[b"HEAD"]
  3767. # Filter by patterns if specified
  3768. if byte_patterns:
  3769. matching_refs: dict[bytes, bytes] = {}
  3770. for ref, sha in filtered_refs.items():
  3771. for pattern in byte_patterns:
  3772. if verify:
  3773. # Verify mode requires exact match
  3774. if ref == pattern:
  3775. matching_refs[ref] = sha
  3776. break
  3777. else:
  3778. # Pattern matching from the end of the full name
  3779. # Only complete parts are matched
  3780. # E.g., "master" matches "refs/heads/master" but not "refs/heads/mymaster"
  3781. pattern_parts = pattern.split(b"/")
  3782. ref_parts = ref.split(b"/")
  3783. # Try to match from the end
  3784. if len(pattern_parts) <= len(ref_parts):
  3785. # Check if the end of ref matches the pattern
  3786. matches = True
  3787. for i in range(len(pattern_parts)):
  3788. if (
  3789. ref_parts[-(len(pattern_parts) - i)]
  3790. != pattern_parts[i]
  3791. ):
  3792. matches = False
  3793. break
  3794. if matches:
  3795. matching_refs[ref] = sha
  3796. break
  3797. filtered_refs = matching_refs
  3798. # Sort by ref name
  3799. sorted_refs = sorted(filtered_refs.items(), key=lambda x: x[0])
  3800. # Build result list
  3801. result: list[tuple[bytes, bytes]] = []
  3802. for ref, sha in sorted_refs:
  3803. result.append((sha, ref))
  3804. # Dereference tags if requested
  3805. if dereference and ref.startswith(LOCAL_TAG_PREFIX):
  3806. try:
  3807. obj = r.get_object(sha)
  3808. # Peel tag objects to get the underlying commit/object
  3809. while obj.type_name == b"tag":
  3810. assert isinstance(obj, Tag)
  3811. _obj_class, sha = obj.object
  3812. obj = r.get_object(sha)
  3813. result.append((sha, ref + b"^{}"))
  3814. except KeyError:
  3815. # Object not found, skip dereferencing
  3816. pass
  3817. return result
  3818. def show_branch(
  3819. repo: Repo | str = ".",
  3820. branches: list[str | bytes] | None = None,
  3821. all_branches: bool = False,
  3822. remotes: bool = False,
  3823. current: bool = False,
  3824. topo_order: bool = False,
  3825. more: int | None = None,
  3826. list_branches: bool = False,
  3827. independent_branches: bool = False,
  3828. merge_base: bool = False,
  3829. ) -> list[str]:
  3830. """Display branches and their commits.
  3831. Args:
  3832. repo: Path to the repository
  3833. branches: List of specific branches to show (default: all local branches)
  3834. all_branches: Show both local and remote branches
  3835. remotes: Show only remote branches
  3836. current: Include current branch if not specified
  3837. topo_order: Show in topological order instead of chronological
  3838. more: Show N more commits beyond common ancestor (negative to show only headers)
  3839. list_branches: Synonym for more=-1 (show only branch headers)
  3840. independent_branches: Show only branches not reachable from others
  3841. merge_base: Show merge bases instead of commit list
  3842. Returns:
  3843. List of output lines
  3844. """
  3845. from .graph import find_octopus_base, independent
  3846. output_lines: list[str] = []
  3847. with open_repo_closing(repo) as r:
  3848. refs = r.get_refs()
  3849. # Determine which branches to show
  3850. branch_refs: dict[bytes, bytes] = {}
  3851. if branches:
  3852. # Specific branches requested
  3853. for branch in branches:
  3854. branch_bytes = (
  3855. os.fsencode(branch) if isinstance(branch, str) else branch
  3856. )
  3857. # Try as full ref name first
  3858. if branch_bytes in refs:
  3859. branch_refs[branch_bytes] = refs[branch_bytes]
  3860. else:
  3861. # Try as branch name
  3862. branch_ref = local_branch_name(branch_bytes)
  3863. if branch_ref in refs:
  3864. branch_refs[branch_ref] = refs[branch_ref]
  3865. # Try as remote branch
  3866. elif LOCAL_REMOTE_PREFIX + branch_bytes in refs:
  3867. branch_refs[LOCAL_REMOTE_PREFIX + branch_bytes] = refs[
  3868. LOCAL_REMOTE_PREFIX + branch_bytes
  3869. ]
  3870. else:
  3871. # Default behavior: show local branches
  3872. if all_branches:
  3873. # Show both local and remote branches
  3874. branch_refs = filter_ref_prefix(
  3875. refs, [LOCAL_BRANCH_PREFIX, LOCAL_REMOTE_PREFIX]
  3876. )
  3877. elif remotes:
  3878. # Show only remote branches
  3879. branch_refs = filter_ref_prefix(refs, [LOCAL_REMOTE_PREFIX])
  3880. else:
  3881. # Show only local branches
  3882. branch_refs = filter_ref_prefix(refs, [LOCAL_BRANCH_PREFIX])
  3883. # Add current branch if requested and not already included
  3884. if current:
  3885. try:
  3886. head_refs, _ = r.refs.follow(b"HEAD")
  3887. if head_refs:
  3888. head_ref = head_refs[0]
  3889. if head_ref not in branch_refs and head_ref in refs:
  3890. branch_refs[head_ref] = refs[head_ref]
  3891. except (KeyError, TypeError):
  3892. # HEAD doesn't point to a branch or doesn't exist
  3893. pass
  3894. if not branch_refs:
  3895. return output_lines
  3896. # Sort branches for consistent output
  3897. sorted_branches = sorted(branch_refs.items(), key=lambda x: x[0])
  3898. branch_sha_list = [sha for _, sha in sorted_branches]
  3899. # Handle --independent flag
  3900. if independent_branches:
  3901. independent_shas = independent(r, branch_sha_list)
  3902. for ref_name, sha in sorted_branches:
  3903. if sha in independent_shas:
  3904. ref_str = os.fsdecode(shorten_ref_name(ref_name))
  3905. output_lines.append(ref_str)
  3906. return output_lines
  3907. # Handle --merge-base flag
  3908. if merge_base:
  3909. if len(branch_sha_list) < 2:
  3910. # Need at least 2 branches for merge base
  3911. return output_lines
  3912. merge_bases = find_octopus_base(r, branch_sha_list)
  3913. for sha in merge_bases:
  3914. output_lines.append(sha.decode("ascii"))
  3915. return output_lines
  3916. # Get current branch for marking
  3917. current_branch: bytes | None = None
  3918. try:
  3919. head_refs, _ = r.refs.follow(b"HEAD")
  3920. if head_refs:
  3921. current_branch = head_refs[0]
  3922. except (KeyError, TypeError):
  3923. pass
  3924. # Collect commit information for each branch
  3925. branch_commits: list[tuple[bytes, str]] = [] # (sha, message)
  3926. for ref_name, sha in sorted_branches:
  3927. try:
  3928. commit = r[sha]
  3929. if hasattr(commit, "message"):
  3930. message = commit.message.decode("utf-8", errors="replace").split(
  3931. "\n"
  3932. )[0]
  3933. else:
  3934. message = ""
  3935. branch_commits.append((sha, message))
  3936. except KeyError:
  3937. branch_commits.append((sha, ""))
  3938. # Handle --list flag (show only branch headers)
  3939. if list_branches or (more is not None and more < 0):
  3940. # Just show the branch headers
  3941. for i, (ref_name, sha) in enumerate(sorted_branches):
  3942. is_current = ref_name == current_branch
  3943. marker = "*" if is_current else "!"
  3944. # Create spacing for alignment
  3945. prefix = " " * i + marker + " " * (len(sorted_branches) - i - 1)
  3946. ref_str = os.fsdecode(shorten_ref_name(ref_name))
  3947. _, message = branch_commits[i]
  3948. output_lines.append(f"{prefix}[{ref_str}] {message}")
  3949. return output_lines
  3950. # Build commit history for visualization
  3951. # Collect all commits reachable from any branch
  3952. all_commits: dict[
  3953. bytes, tuple[int, list[bytes], str]
  3954. ] = {} # sha -> (timestamp, parents, message)
  3955. def collect_commits(sha: bytes, branch_idx: int, visited: set[bytes]) -> None:
  3956. """Recursively collect commits."""
  3957. if sha in visited:
  3958. return
  3959. visited.add(sha)
  3960. try:
  3961. commit = r[sha]
  3962. if not hasattr(commit, "commit_time"):
  3963. return
  3964. timestamp = commit.commit_time
  3965. parents = commit.parents if hasattr(commit, "parents") else []
  3966. message = (
  3967. commit.message.decode("utf-8", errors="replace").split("\n")[0]
  3968. if hasattr(commit, "message")
  3969. else ""
  3970. )
  3971. if sha not in all_commits:
  3972. all_commits[sha] = (timestamp, parents, message)
  3973. # Recurse to parents
  3974. for parent in parents:
  3975. collect_commits(parent, branch_idx, visited)
  3976. except KeyError:
  3977. # Commit not found, stop traversal
  3978. pass
  3979. # Collect commits from all branches
  3980. for i, (_, sha) in enumerate(sorted_branches):
  3981. collect_commits(sha, i, set())
  3982. # Find common ancestor
  3983. common_ancestor_sha = None
  3984. if len(branch_sha_list) >= 2:
  3985. try:
  3986. merge_bases = find_octopus_base(r, branch_sha_list)
  3987. if merge_bases:
  3988. common_ancestor_sha = merge_bases[0]
  3989. except (KeyError, IndexError):
  3990. pass
  3991. # Sort commits (chronological by default, or topological if requested)
  3992. if topo_order:
  3993. # Topological sort is more complex, for now use chronological
  3994. # TODO: Implement proper topological ordering
  3995. sorted_commits = sorted(all_commits.items(), key=lambda x: -x[1][0])
  3996. else:
  3997. # Reverse chronological order (newest first)
  3998. sorted_commits = sorted(all_commits.items(), key=lambda x: -x[1][0])
  3999. # Determine how many commits to show
  4000. if more is not None:
  4001. # Find index of common ancestor
  4002. if common_ancestor_sha and common_ancestor_sha in all_commits:
  4003. ancestor_idx = next(
  4004. (
  4005. i
  4006. for i, (sha, _) in enumerate(sorted_commits)
  4007. if sha == common_ancestor_sha
  4008. ),
  4009. None,
  4010. )
  4011. if ancestor_idx is not None:
  4012. # Show commits up to ancestor + more
  4013. sorted_commits = sorted_commits[: ancestor_idx + 1 + more]
  4014. # Determine which branches contain which commits
  4015. branch_contains: list[set[bytes]] = []
  4016. for ref_name, sha in sorted_branches:
  4017. reachable = set()
  4018. def mark_reachable(commit_sha: bytes) -> None:
  4019. if commit_sha in reachable:
  4020. return
  4021. reachable.add(commit_sha)
  4022. if commit_sha in all_commits:
  4023. _, parents, _ = all_commits[commit_sha]
  4024. for parent in parents:
  4025. mark_reachable(parent)
  4026. mark_reachable(sha)
  4027. branch_contains.append(reachable)
  4028. # Output branch headers
  4029. for i, (ref_name, sha) in enumerate(sorted_branches):
  4030. is_current = ref_name == current_branch
  4031. marker = "*" if is_current else "!"
  4032. # Create spacing for alignment
  4033. prefix = " " * i + marker + " " * (len(sorted_branches) - i - 1)
  4034. ref_str = os.fsdecode(shorten_ref_name(ref_name))
  4035. _, message = branch_commits[i]
  4036. output_lines.append(f"{prefix}[{ref_str}] {message}")
  4037. # Output separator
  4038. output_lines.append("-" * (len(sorted_branches) + 2))
  4039. # Output commits
  4040. for commit_sha, (_, _, message) in sorted_commits:
  4041. # Build marker string
  4042. markers = []
  4043. for i, (ref_name, branch_sha) in enumerate(sorted_branches):
  4044. if commit_sha == branch_sha:
  4045. # This is the tip of the branch
  4046. markers.append("*")
  4047. elif commit_sha in branch_contains[i]:
  4048. # This commit is in the branch
  4049. markers.append("+")
  4050. else:
  4051. # This commit is not in the branch
  4052. markers.append(" ")
  4053. marker_str = "".join(markers)
  4054. output_lines.append(f"{marker_str} [{message}]")
  4055. # Limit output to 26 branches (git show-branch limitation)
  4056. if len(sorted_branches) > 26:
  4057. break
  4058. return output_lines
  4059. def ls_remote(
  4060. remote: str | bytes,
  4061. config: Config | None = None,
  4062. operation: str | None = None,
  4063. thin_packs: bool = True,
  4064. report_activity: Callable[[int, str], None] | None = None,
  4065. quiet: bool = False,
  4066. include_tags: bool = False,
  4067. username: str | None = None,
  4068. password: str | None = None,
  4069. key_filename: str | None = None,
  4070. ssh_command: str | None = None,
  4071. ) -> LsRemoteResult:
  4072. """List the refs in a remote.
  4073. Args:
  4074. remote: Remote repository location
  4075. config: Configuration to use
  4076. operation: Operation type
  4077. thin_packs: Whether to use thin packs
  4078. report_activity: Function to report activity
  4079. quiet: Whether to suppress output
  4080. include_tags: Whether to include tags
  4081. username: Username for authentication
  4082. password: Password for authentication
  4083. key_filename: SSH key filename
  4084. ssh_command: SSH command to use
  4085. Returns:
  4086. LsRemoteResult object with refs and symrefs
  4087. """
  4088. if config is None:
  4089. config = StackedConfig.default()
  4090. remote_str = remote.decode() if isinstance(remote, bytes) else remote
  4091. client, host_path = get_transport_and_path(
  4092. remote_str,
  4093. config=config,
  4094. operation=operation,
  4095. thin_packs=thin_packs,
  4096. report_activity=report_activity,
  4097. quiet=quiet,
  4098. include_tags=include_tags,
  4099. username=username,
  4100. password=password,
  4101. key_filename=key_filename,
  4102. ssh_command=ssh_command,
  4103. )
  4104. return client.get_refs(
  4105. host_path.encode() if isinstance(host_path, str) else host_path
  4106. )
  4107. def repack(repo: RepoPath, write_bitmaps: bool = False) -> None:
  4108. """Repack loose files in a repository.
  4109. Currently this only packs loose objects.
  4110. Args:
  4111. repo: Path to the repository
  4112. write_bitmaps: Whether to write bitmap indexes for packs
  4113. """
  4114. with open_repo_closing(repo) as r:
  4115. r.object_store.pack_loose_objects()
  4116. if write_bitmaps:
  4117. # Update pack cache to pick up newly created packs
  4118. r.object_store._update_pack_cache()
  4119. r.object_store.generate_pack_bitmaps(r.refs.as_dict())
  4120. def pack_objects(
  4121. repo: RepoPath,
  4122. object_ids: Sequence[bytes],
  4123. packf: BinaryIO,
  4124. idxf: BinaryIO | None,
  4125. delta_window_size: int | None = None,
  4126. deltify: bool | None = None,
  4127. reuse_deltas: bool = True,
  4128. pack_index_version: int | None = None,
  4129. ) -> None:
  4130. """Pack objects into a file.
  4131. Args:
  4132. repo: Path to the repository
  4133. object_ids: List of object ids to write
  4134. packf: File-like object to write to
  4135. idxf: File-like object to write to (can be None)
  4136. delta_window_size: Sliding window size for searching for deltas;
  4137. Set to None for default window size.
  4138. deltify: Whether to deltify objects
  4139. reuse_deltas: Allow reuse of existing deltas while deltifying
  4140. pack_index_version: Pack index version to use (1, 2, or 3). If None, uses default version.
  4141. """
  4142. with open_repo_closing(repo) as r:
  4143. entries, data_sum = write_pack_from_container(
  4144. packf.write,
  4145. r.object_store,
  4146. [(oid, None) for oid in object_ids],
  4147. deltify=deltify,
  4148. delta_window_size=delta_window_size,
  4149. reuse_deltas=reuse_deltas,
  4150. )
  4151. if idxf is not None:
  4152. index_entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
  4153. write_pack_index(idxf, index_entries, data_sum, version=pack_index_version)
  4154. def ls_tree(
  4155. repo: RepoPath,
  4156. treeish: str | bytes | Commit | Tree | Tag = b"HEAD",
  4157. outstream: TextIO | BinaryIO = sys.stdout,
  4158. recursive: bool = False,
  4159. name_only: bool = False,
  4160. ) -> None:
  4161. """List contents of a tree.
  4162. Args:
  4163. repo: Path to the repository
  4164. treeish: Tree id to list
  4165. outstream: Output stream (defaults to stdout)
  4166. recursive: Whether to recursively list files
  4167. name_only: Only print item name
  4168. """
  4169. def list_tree(store: BaseObjectStore, treeid: bytes, base: bytes) -> None:
  4170. tree = store[treeid]
  4171. assert isinstance(tree, Tree)
  4172. for name, mode, sha in tree.iteritems():
  4173. assert name is not None
  4174. assert mode is not None
  4175. assert sha is not None
  4176. if base:
  4177. name = posixpath.join(base, name)
  4178. if name_only:
  4179. if isinstance(outstream, BinaryIO):
  4180. outstream.write(name + b"\n")
  4181. else:
  4182. outstream.write(name.decode("utf-8", "replace") + "\n")
  4183. else:
  4184. formatted = pretty_format_tree_entry(name, mode, sha)
  4185. if isinstance(outstream, BinaryIO):
  4186. outstream.write(formatted.encode("utf-8"))
  4187. else:
  4188. outstream.write(formatted)
  4189. if stat.S_ISDIR(mode) and recursive:
  4190. list_tree(store, sha, name)
  4191. with open_repo_closing(repo) as r:
  4192. tree = parse_tree(r, treeish)
  4193. list_tree(r.object_store, tree.id, b"")
  4194. def remote_add(
  4195. repo: RepoPath,
  4196. name: bytes | str,
  4197. url: bytes | str,
  4198. ) -> None:
  4199. """Add a remote.
  4200. Args:
  4201. repo: Path to the repository
  4202. name: Remote name
  4203. url: Remote URL
  4204. """
  4205. if not isinstance(name, bytes):
  4206. name = name.encode(DEFAULT_ENCODING)
  4207. if not isinstance(url, bytes):
  4208. url = url.encode(DEFAULT_ENCODING)
  4209. with open_repo_closing(repo) as r:
  4210. c = r.get_config()
  4211. section = (b"remote", name)
  4212. if c.has_section(section):
  4213. raise RemoteExists(f"Remote {name.decode()} already exists")
  4214. c.set(section, b"url", url)
  4215. c.write_to_path()
  4216. def remote_remove(repo: Repo, name: bytes | str) -> None:
  4217. """Remove a remote.
  4218. Args:
  4219. repo: Path to the repository
  4220. name: Remote name
  4221. """
  4222. if not isinstance(name, bytes):
  4223. name = name.encode(DEFAULT_ENCODING)
  4224. with open_repo_closing(repo) as r:
  4225. c = r.get_config()
  4226. section = (b"remote", name)
  4227. del c[section]
  4228. c.write_to_path()
  4229. def _quote_path(path: str) -> str:
  4230. """Quote a path using C-style quoting similar to git's core.quotePath.
  4231. Args:
  4232. path: Path to quote
  4233. Returns:
  4234. Quoted path string
  4235. """
  4236. # Check if path needs quoting (non-ASCII or special characters)
  4237. needs_quoting = False
  4238. for char in path:
  4239. if ord(char) > 127 or char in '"\\':
  4240. needs_quoting = True
  4241. break
  4242. if not needs_quoting:
  4243. return path
  4244. # Apply C-style quoting
  4245. quoted = '"'
  4246. for char in path:
  4247. if ord(char) > 127:
  4248. # Non-ASCII character, encode as octal escape
  4249. utf8_bytes = char.encode("utf-8")
  4250. for byte in utf8_bytes:
  4251. quoted += f"\\{byte:03o}"
  4252. elif char == '"':
  4253. quoted += '\\"'
  4254. elif char == "\\":
  4255. quoted += "\\\\"
  4256. else:
  4257. quoted += char
  4258. quoted += '"'
  4259. return quoted
  4260. def check_ignore(
  4261. repo: RepoPath,
  4262. paths: Sequence[str | bytes | os.PathLike[str]],
  4263. no_index: bool = False,
  4264. quote_path: bool = True,
  4265. ) -> Iterator[str]:
  4266. r"""Debug gitignore files.
  4267. Args:
  4268. repo: Path to the repository
  4269. paths: List of paths to check for
  4270. no_index: Don't check index
  4271. quote_path: If True, quote non-ASCII characters in returned paths using
  4272. C-style octal escapes (e.g. "тест.txt" becomes "\\321\\202\\320\\265\\321\\201\\321\\202.txt").
  4273. If False, return raw unicode paths.
  4274. Returns: List of ignored files
  4275. """
  4276. with open_repo_closing(repo) as r:
  4277. index = r.open_index()
  4278. ignore_manager = IgnoreFilterManager.from_repo(r)
  4279. for original_path in paths:
  4280. # Convert path to string for consistent handling
  4281. original_path_fspath = os.fspath(original_path)
  4282. # Normalize to str
  4283. original_path_str = os.fsdecode(original_path_fspath)
  4284. if not no_index and path_to_tree_path(r.path, original_path_str) in index:
  4285. continue
  4286. # Preserve whether the original path had a trailing slash
  4287. had_trailing_slash = original_path_str.endswith(("/", os.path.sep))
  4288. if os.path.isabs(original_path_str):
  4289. path = os.path.relpath(original_path_str, r.path)
  4290. # Normalize Windows paths to use forward slashes
  4291. if os.path.sep != "/":
  4292. path = path.replace(os.path.sep, "/")
  4293. else:
  4294. path = original_path_str
  4295. # Restore trailing slash if it was in the original
  4296. if had_trailing_slash and not path.endswith("/"):
  4297. path = path + "/"
  4298. # For directories, check with trailing slash to get correct ignore behavior
  4299. test_path = path
  4300. path_without_slash = path.rstrip("/")
  4301. is_directory = os.path.isdir(os.path.join(r.path, path_without_slash))
  4302. # If this is a directory path, ensure we test it correctly
  4303. if is_directory and not path.endswith("/"):
  4304. test_path = path + "/"
  4305. if ignore_manager.is_ignored(test_path):
  4306. # Return relative path (like git does) when absolute path was provided
  4307. if os.path.isabs(original_path):
  4308. output_path = path
  4309. else:
  4310. output_path = original_path # type: ignore[assignment]
  4311. yield _quote_path(output_path) if quote_path else output_path
  4312. def _get_current_head_tree(repo: Repo) -> bytes | None:
  4313. """Get the current HEAD tree ID.
  4314. Args:
  4315. repo: Repository object
  4316. Returns:
  4317. Tree ID of current HEAD, or None if no HEAD exists (empty repo)
  4318. """
  4319. try:
  4320. current_head = repo.refs[b"HEAD"]
  4321. current_commit = repo[current_head]
  4322. assert isinstance(current_commit, Commit), "Expected a Commit object"
  4323. tree_id: bytes = current_commit.tree
  4324. return tree_id
  4325. except KeyError:
  4326. # No HEAD yet (empty repo)
  4327. return None
  4328. def _check_uncommitted_changes(
  4329. repo: Repo, target_tree_id: bytes, force: bool = False
  4330. ) -> None:
  4331. """Check for uncommitted changes that would conflict with a checkout/switch.
  4332. Args:
  4333. repo: Repository object
  4334. target_tree_id: Tree ID to check conflicts against
  4335. force: If True, skip the check
  4336. Raises:
  4337. CheckoutError: If there are conflicting local changes
  4338. """
  4339. if force:
  4340. return
  4341. # Get current HEAD tree for comparison
  4342. current_tree_id = _get_current_head_tree(repo)
  4343. if current_tree_id is None:
  4344. # No HEAD yet (empty repo)
  4345. return
  4346. status_report = status(repo)
  4347. changes = []
  4348. # staged is a dict with 'add', 'delete', 'modify' keys
  4349. if isinstance(status_report.staged, dict):
  4350. changes.extend(status_report.staged.get("add", []))
  4351. changes.extend(status_report.staged.get("delete", []))
  4352. changes.extend(status_report.staged.get("modify", []))
  4353. # unstaged is a list
  4354. changes.extend(status_report.unstaged)
  4355. if changes:
  4356. # Check if any changes would conflict with checkout
  4357. target_tree_obj = repo[target_tree_id]
  4358. assert isinstance(target_tree_obj, Tree), "Expected a Tree object"
  4359. target_tree = target_tree_obj
  4360. for change in changes:
  4361. if isinstance(change, str):
  4362. change = change.encode(DEFAULT_ENCODING)
  4363. try:
  4364. target_tree.lookup_path(repo.object_store.__getitem__, change)
  4365. except KeyError:
  4366. # File doesn't exist in target tree - change can be preserved
  4367. pass
  4368. else:
  4369. # File exists in target tree - would overwrite local changes
  4370. raise CheckoutError(
  4371. f"Your local changes to '{change.decode()}' would be "
  4372. "overwritten. Please commit or stash before switching."
  4373. )
  4374. def _get_worktree_update_config(
  4375. repo: Repo,
  4376. ) -> tuple[
  4377. bool,
  4378. Callable[[bytes], bool],
  4379. Callable[[str | bytes | os.PathLike[str], str | bytes | os.PathLike[str]], None],
  4380. ]:
  4381. """Get configuration for working tree updates.
  4382. Args:
  4383. repo: Repository object
  4384. Returns:
  4385. Tuple of (honor_filemode, validate_path_element, symlink_fn)
  4386. """
  4387. config = repo.get_config()
  4388. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  4389. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  4390. validate_path_element = validate_path_element_ntfs
  4391. elif config.get_boolean(b"core", b"core.protectHFS", sys.platform == "darwin"):
  4392. validate_path_element = validate_path_element_hfs
  4393. else:
  4394. validate_path_element = validate_path_element_default
  4395. if config.get_boolean(b"core", b"symlinks", True):
  4396. def symlink_wrapper(
  4397. source: str | bytes | os.PathLike[str],
  4398. target: str | bytes | os.PathLike[str],
  4399. ) -> None:
  4400. symlink(source, target) # type: ignore[arg-type,unused-ignore]
  4401. symlink_fn = symlink_wrapper
  4402. else:
  4403. def symlink_fallback(
  4404. source: str | bytes | os.PathLike[str],
  4405. target: str | bytes | os.PathLike[str],
  4406. ) -> None:
  4407. mode = "w" + ("b" if isinstance(source, bytes) else "")
  4408. with open(target, mode) as f:
  4409. f.write(source)
  4410. symlink_fn = symlink_fallback
  4411. return honor_filemode, validate_path_element, symlink_fn
  4412. def _perform_tree_switch(
  4413. repo: Repo,
  4414. current_tree_id: bytes | None,
  4415. target_tree_id: bytes,
  4416. force: bool = False,
  4417. ) -> None:
  4418. """Perform the actual working tree switch.
  4419. Args:
  4420. repo: Repository object
  4421. current_tree_id: Current tree ID (or None for empty repo)
  4422. target_tree_id: Target tree ID to switch to
  4423. force: If True, force removal of untracked files and allow overwriting modified files
  4424. """
  4425. honor_filemode, validate_path_element, symlink_fn = _get_worktree_update_config(
  4426. repo
  4427. )
  4428. # Get blob normalizer for line ending conversion
  4429. blob_normalizer = repo.get_blob_normalizer()
  4430. # Update working tree
  4431. tree_change_iterator: Iterator[TreeChange] = tree_changes(
  4432. repo.object_store, current_tree_id, target_tree_id
  4433. )
  4434. update_working_tree(
  4435. repo,
  4436. current_tree_id,
  4437. target_tree_id,
  4438. change_iterator=tree_change_iterator,
  4439. honor_filemode=honor_filemode,
  4440. validate_path_element=validate_path_element,
  4441. symlink_fn=symlink_fn,
  4442. force_remove_untracked=force,
  4443. blob_normalizer=blob_normalizer,
  4444. allow_overwrite_modified=force,
  4445. )
  4446. def update_head(
  4447. repo: RepoPath,
  4448. target: str | bytes,
  4449. detached: bool = False,
  4450. new_branch: str | bytes | None = None,
  4451. ) -> None:
  4452. """Update HEAD to point at a new branch/commit.
  4453. Note that this does not actually update the working tree.
  4454. Args:
  4455. repo: Path to the repository
  4456. detached: Create a detached head
  4457. target: Branch or committish to switch to
  4458. new_branch: New branch to create
  4459. """
  4460. with open_repo_closing(repo) as r:
  4461. if new_branch is not None:
  4462. to_set = _make_branch_ref(new_branch)
  4463. else:
  4464. to_set = b"HEAD"
  4465. if detached:
  4466. # TODO(jelmer): Provide some way so that the actual ref gets
  4467. # updated rather than what it points to, so the delete isn't
  4468. # necessary.
  4469. del r.refs[to_set]
  4470. r.refs[to_set] = parse_commit(r, target).id
  4471. else:
  4472. r.refs.set_symbolic_ref(to_set, parse_ref(r, target))
  4473. if new_branch is not None:
  4474. r.refs.set_symbolic_ref(b"HEAD", to_set)
  4475. def checkout(
  4476. repo: str | os.PathLike[str] | Repo,
  4477. target: str | bytes | Commit | Tag | None = None,
  4478. force: bool = False,
  4479. new_branch: bytes | str | None = None,
  4480. paths: list[bytes | str] | None = None,
  4481. ) -> None:
  4482. """Switch to a branch or commit, updating both HEAD and the working tree.
  4483. This is similar to 'git checkout', allowing you to switch to a branch,
  4484. tag, or specific commit. Unlike update_head, this function also updates
  4485. the working tree to match the target.
  4486. Args:
  4487. repo: Path to repository or repository object
  4488. target: Branch name, tag, or commit SHA to checkout. If None and paths is specified,
  4489. restores files from HEAD
  4490. force: Force checkout even if there are local changes
  4491. new_branch: Create a new branch at target (like git checkout -b)
  4492. paths: List of specific paths to checkout. If specified, only these paths are updated
  4493. and HEAD is not changed
  4494. Raises:
  4495. CheckoutError: If checkout cannot be performed due to conflicts
  4496. KeyError: If the target reference cannot be found
  4497. """
  4498. with open_repo_closing(repo) as r:
  4499. # Store the original target for later reference checks
  4500. original_target = target
  4501. worktree = r.get_worktree()
  4502. # Handle path-specific checkout (like git checkout -- <paths>)
  4503. if paths is not None:
  4504. # Convert paths to bytes
  4505. byte_paths = []
  4506. for path in paths:
  4507. if isinstance(path, str):
  4508. byte_paths.append(path.encode(DEFAULT_ENCODING))
  4509. else:
  4510. byte_paths.append(path)
  4511. # If no target specified, use HEAD
  4512. if target is None:
  4513. try:
  4514. target = r.refs[b"HEAD"]
  4515. except KeyError:
  4516. raise CheckoutError("No HEAD reference found")
  4517. else:
  4518. if isinstance(target, str):
  4519. target = target.encode(DEFAULT_ENCODING)
  4520. # Get the target commit and tree
  4521. target_tree = parse_tree(r, target)
  4522. # Get blob normalizer for line ending conversion
  4523. blob_normalizer = r.get_blob_normalizer()
  4524. # Restore specified paths from target tree
  4525. for path in byte_paths:
  4526. try:
  4527. # Look up the path in the target tree
  4528. mode, sha = target_tree.lookup_path(
  4529. r.object_store.__getitem__, path
  4530. )
  4531. obj = r[sha]
  4532. assert isinstance(obj, Blob), "Expected a Blob object"
  4533. except KeyError:
  4534. # Path doesn't exist in target tree
  4535. pass
  4536. else:
  4537. # Create directories if needed
  4538. # Handle path as string
  4539. if isinstance(path, bytes):
  4540. path_str = path.decode(DEFAULT_ENCODING)
  4541. else:
  4542. path_str = path
  4543. file_path = os.path.join(r.path, path_str)
  4544. os.makedirs(os.path.dirname(file_path), exist_ok=True)
  4545. # Write the file content
  4546. if stat.S_ISREG(mode):
  4547. # Apply checkout filters (smudge)
  4548. if blob_normalizer:
  4549. obj = blob_normalizer.checkout_normalize(obj, path)
  4550. flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
  4551. if sys.platform == "win32":
  4552. flags |= os.O_BINARY
  4553. with os.fdopen(os.open(file_path, flags, mode), "wb") as f:
  4554. f.write(obj.data)
  4555. # Update the index
  4556. worktree.stage(path)
  4557. return
  4558. # Normal checkout (switching branches/commits)
  4559. if target is None:
  4560. raise ValueError("Target must be specified for branch/commit checkout")
  4561. if isinstance(target, str):
  4562. target_bytes = target.encode(DEFAULT_ENCODING)
  4563. elif isinstance(target, bytes):
  4564. target_bytes = target
  4565. else:
  4566. # For Commit/Tag objects, we'll use their SHA
  4567. target_bytes = target.id
  4568. if isinstance(new_branch, str):
  4569. new_branch = new_branch.encode(DEFAULT_ENCODING)
  4570. # Parse the target to get the commit
  4571. assert (
  4572. original_target is not None
  4573. ) # Guaranteed by earlier check for normal checkout
  4574. target_commit = parse_commit(r, original_target)
  4575. target_tree_id = target_commit.tree
  4576. # Get current HEAD tree for comparison
  4577. current_tree_id = _get_current_head_tree(r)
  4578. # Check for uncommitted changes if not forcing
  4579. if current_tree_id is not None:
  4580. _check_uncommitted_changes(r, target_tree_id, force)
  4581. # Update working tree
  4582. _perform_tree_switch(r, current_tree_id, target_tree_id, force)
  4583. # Update HEAD
  4584. if new_branch:
  4585. # Create new branch and switch to it
  4586. branch_create(r, new_branch, objectish=target_commit.id.decode("ascii"))
  4587. update_head(r, new_branch)
  4588. # Set up tracking if creating from a remote branch
  4589. if isinstance(original_target, bytes) and target_bytes.startswith(
  4590. LOCAL_REMOTE_PREFIX
  4591. ):
  4592. try:
  4593. remote_name, branch_name = parse_remote_ref(target_bytes)
  4594. # Set tracking to refs/heads/<branch> on the remote
  4595. set_branch_tracking(
  4596. r, new_branch, remote_name, local_branch_name(branch_name)
  4597. )
  4598. except ValueError:
  4599. # Invalid remote ref format, skip tracking setup
  4600. pass
  4601. else:
  4602. # Check if target is a branch name (with or without refs/heads/ prefix)
  4603. branch_ref = None
  4604. if (
  4605. isinstance(original_target, (str, bytes))
  4606. and target_bytes in r.refs.keys()
  4607. ):
  4608. if target_bytes.startswith(LOCAL_BRANCH_PREFIX):
  4609. branch_ref = target_bytes
  4610. else:
  4611. # Try adding refs/heads/ prefix
  4612. potential_branch = (
  4613. _make_branch_ref(target_bytes)
  4614. if isinstance(original_target, (str, bytes))
  4615. else None
  4616. )
  4617. if potential_branch in r.refs.keys():
  4618. branch_ref = potential_branch
  4619. if branch_ref:
  4620. # It's a branch - update HEAD symbolically
  4621. update_head(r, branch_ref)
  4622. else:
  4623. # It's a tag, other ref, or commit SHA - detached HEAD
  4624. update_head(r, target_commit.id.decode("ascii"), detached=True)
  4625. def restore(
  4626. repo: str | os.PathLike[str] | Repo,
  4627. paths: list[bytes | str],
  4628. source: str | bytes | Commit | Tag | None = None,
  4629. staged: bool = False,
  4630. worktree: bool = True,
  4631. ) -> None:
  4632. """Restore working tree files.
  4633. This is similar to 'git restore', allowing you to restore specific files
  4634. from a commit or the index without changing HEAD.
  4635. Args:
  4636. repo: Path to repository or repository object
  4637. paths: List of specific paths to restore
  4638. source: Branch name, tag, or commit SHA to restore from. If None, restores
  4639. staged files from HEAD, or worktree files from index
  4640. staged: Restore files in the index (--staged)
  4641. worktree: Restore files in the working tree (default: True)
  4642. Raises:
  4643. CheckoutError: If restore cannot be performed
  4644. ValueError: If neither staged nor worktree is specified
  4645. KeyError: If the source reference cannot be found
  4646. """
  4647. if not staged and not worktree:
  4648. raise ValueError("At least one of staged or worktree must be True")
  4649. with open_repo_closing(repo) as r:
  4650. from .index import _fs_to_tree_path, build_file_from_blob
  4651. # Determine the source tree
  4652. if source is None:
  4653. if staged:
  4654. # Restoring staged files from HEAD
  4655. try:
  4656. source = r.refs[b"HEAD"]
  4657. except KeyError:
  4658. raise CheckoutError("No HEAD reference found")
  4659. elif worktree:
  4660. # Restoring worktree files from index
  4661. from .index import ConflictedIndexEntry, IndexEntry
  4662. index = r.open_index()
  4663. for path in paths:
  4664. if isinstance(path, str):
  4665. tree_path = _fs_to_tree_path(path)
  4666. else:
  4667. tree_path = path
  4668. try:
  4669. index_entry = index[tree_path]
  4670. if isinstance(index_entry, ConflictedIndexEntry):
  4671. raise CheckoutError(
  4672. f"Path '{path if isinstance(path, str) else path.decode(DEFAULT_ENCODING)}' has conflicts"
  4673. )
  4674. blob = r[index_entry.sha]
  4675. assert isinstance(blob, Blob), "Expected a Blob object"
  4676. full_path = os.path.join(os.fsencode(r.path), tree_path)
  4677. mode = index_entry.mode
  4678. # Use build_file_from_blob to write the file
  4679. build_file_from_blob(blob, mode, full_path)
  4680. except KeyError:
  4681. # Path doesn't exist in index
  4682. raise CheckoutError(
  4683. f"Path '{path if isinstance(path, str) else path.decode(DEFAULT_ENCODING)}' not in index"
  4684. )
  4685. return
  4686. # source is not None at this point
  4687. assert source is not None
  4688. # Get the source tree
  4689. source_tree = parse_tree(r, treeish=source)
  4690. # Restore specified paths from source tree
  4691. for path in paths:
  4692. if isinstance(path, str):
  4693. tree_path = _fs_to_tree_path(path)
  4694. else:
  4695. tree_path = path
  4696. try:
  4697. # Look up the path in the source tree
  4698. mode, sha = source_tree.lookup_path(
  4699. r.object_store.__getitem__, tree_path
  4700. )
  4701. blob = r[sha]
  4702. assert isinstance(blob, Blob), "Expected a Blob object"
  4703. except KeyError:
  4704. # Path doesn't exist in source tree
  4705. raise CheckoutError(
  4706. f"Path '{path if isinstance(path, str) else path.decode(DEFAULT_ENCODING)}' not found in source"
  4707. )
  4708. full_path = os.path.join(os.fsencode(r.path), tree_path)
  4709. if worktree:
  4710. # Use build_file_from_blob to restore to working tree
  4711. build_file_from_blob(blob, mode, full_path)
  4712. if staged:
  4713. # Update the index with the blob from source
  4714. from .index import IndexEntry
  4715. index = r.open_index()
  4716. # When only updating staged (not worktree), we want to reset the index
  4717. # to the source, but invalidate the stat cache so Git knows to check
  4718. # the worktree file. Use zeros for stat fields.
  4719. if not worktree:
  4720. # Invalidate stat cache by using zeros
  4721. new_entry = IndexEntry(
  4722. ctime=(0, 0),
  4723. mtime=(0, 0),
  4724. dev=0,
  4725. ino=0,
  4726. mode=mode,
  4727. uid=0,
  4728. gid=0,
  4729. size=0,
  4730. sha=sha,
  4731. )
  4732. else:
  4733. # If we also updated worktree, use actual stat
  4734. from .index import index_entry_from_stat
  4735. st = os.lstat(full_path)
  4736. new_entry = index_entry_from_stat(st, sha, mode)
  4737. index[tree_path] = new_entry
  4738. index.write()
  4739. def switch(
  4740. repo: str | os.PathLike[str] | Repo,
  4741. target: str | bytes | Commit | Tag,
  4742. create: str | bytes | None = None,
  4743. force: bool = False,
  4744. detach: bool = False,
  4745. ) -> None:
  4746. """Switch branches.
  4747. This is similar to 'git switch', allowing you to switch to a different
  4748. branch or commit, updating both HEAD and the working tree.
  4749. Args:
  4750. repo: Path to repository or repository object
  4751. target: Branch name, tag, or commit SHA to switch to
  4752. create: Create a new branch at target before switching (like git switch -c)
  4753. force: Force switch even if there are local changes
  4754. detach: Switch to a commit in detached HEAD state (like git switch --detach)
  4755. Raises:
  4756. CheckoutError: If switch cannot be performed due to conflicts
  4757. KeyError: If the target reference cannot be found
  4758. ValueError: If both create and detach are specified
  4759. """
  4760. if create and detach:
  4761. raise ValueError("Cannot use both create and detach options")
  4762. with open_repo_closing(repo) as r:
  4763. # Store the original target for later reference checks
  4764. original_target = target
  4765. if isinstance(target, str):
  4766. target_bytes = target.encode(DEFAULT_ENCODING)
  4767. elif isinstance(target, bytes):
  4768. target_bytes = target
  4769. else:
  4770. # For Commit/Tag objects, we'll use their SHA
  4771. target_bytes = target.id
  4772. if isinstance(create, str):
  4773. create = create.encode(DEFAULT_ENCODING)
  4774. # Parse the target to get the commit
  4775. target_commit = parse_commit(r, original_target)
  4776. target_tree_id = target_commit.tree
  4777. # Get current HEAD tree for comparison
  4778. current_tree_id = _get_current_head_tree(r)
  4779. # Check for uncommitted changes if not forcing
  4780. if current_tree_id is not None:
  4781. _check_uncommitted_changes(r, target_tree_id, force)
  4782. # Update working tree
  4783. _perform_tree_switch(r, current_tree_id, target_tree_id, force)
  4784. # Update HEAD
  4785. if create:
  4786. # Create new branch and switch to it
  4787. branch_create(r, create, objectish=target_commit.id.decode("ascii"))
  4788. update_head(r, create)
  4789. # Set up tracking if creating from a remote branch
  4790. from .refs import LOCAL_REMOTE_PREFIX, local_branch_name, parse_remote_ref
  4791. if isinstance(original_target, bytes) and target_bytes.startswith(
  4792. LOCAL_REMOTE_PREFIX
  4793. ):
  4794. try:
  4795. remote_name, branch_name = parse_remote_ref(target_bytes)
  4796. # Set tracking to refs/heads/<branch> on the remote
  4797. set_branch_tracking(
  4798. r, create, remote_name, local_branch_name(branch_name)
  4799. )
  4800. except ValueError:
  4801. # Invalid remote ref format, skip tracking setup
  4802. pass
  4803. elif detach:
  4804. # Detached HEAD mode
  4805. update_head(r, target_commit.id.decode("ascii"), detached=True)
  4806. else:
  4807. # Check if target is a branch name (with or without refs/heads/ prefix)
  4808. branch_ref = None
  4809. if (
  4810. isinstance(original_target, (str, bytes))
  4811. and target_bytes in r.refs.keys()
  4812. ):
  4813. if target_bytes.startswith(LOCAL_BRANCH_PREFIX):
  4814. branch_ref = target_bytes
  4815. else:
  4816. # Try adding refs/heads/ prefix
  4817. potential_branch = (
  4818. _make_branch_ref(target_bytes)
  4819. if isinstance(original_target, (str, bytes))
  4820. else None
  4821. )
  4822. if potential_branch in r.refs.keys():
  4823. branch_ref = potential_branch
  4824. if branch_ref:
  4825. # It's a branch - update HEAD symbolically
  4826. update_head(r, branch_ref)
  4827. else:
  4828. # It's a tag, other ref, or commit SHA
  4829. # In git switch, this would be an error unless --detach is used
  4830. raise CheckoutError(
  4831. f"'{target_bytes.decode(DEFAULT_ENCODING)}' is not a branch. "
  4832. "Use detach=True to switch to a commit in detached HEAD state."
  4833. )
  4834. def reset_file(
  4835. repo: Repo,
  4836. file_path: str,
  4837. target: str | bytes | Commit | Tree | Tag = b"HEAD",
  4838. symlink_fn: Callable[
  4839. [str | bytes | os.PathLike[str], str | bytes | os.PathLike[str]], None
  4840. ]
  4841. | None = None,
  4842. ) -> None:
  4843. """Reset the file to specific commit or branch.
  4844. Args:
  4845. repo: dulwich Repo object
  4846. file_path: file to reset, relative to the repository path
  4847. target: branch or commit or b'HEAD' to reset
  4848. symlink_fn: Function to use for creating symlinks
  4849. """
  4850. tree = parse_tree(repo, treeish=target)
  4851. tree_path = _fs_to_tree_path(file_path)
  4852. file_entry = tree.lookup_path(repo.object_store.__getitem__, tree_path)
  4853. full_path = os.path.join(os.fsencode(repo.path), tree_path)
  4854. blob = repo.object_store[file_entry[1]]
  4855. assert isinstance(blob, Blob)
  4856. mode = file_entry[0]
  4857. build_file_from_blob(blob, mode, full_path, symlink_fn=symlink_fn)
  4858. @replace_me(since="0.22.9", remove_in="0.24.0")
  4859. def checkout_branch(
  4860. repo: str | os.PathLike[str] | Repo,
  4861. target: bytes | str,
  4862. force: bool = False,
  4863. ) -> None:
  4864. """Switch branches or restore working tree files.
  4865. This is now a wrapper around the general checkout() function.
  4866. Preserved for backward compatibility.
  4867. Args:
  4868. repo: dulwich Repo object
  4869. target: branch name or commit sha to checkout
  4870. force: true or not to force checkout
  4871. """
  4872. # Simply delegate to the new checkout function
  4873. return checkout(repo, target, force=force)
  4874. def sparse_checkout(
  4875. repo: str | os.PathLike[str] | Repo,
  4876. patterns: list[str] | None = None,
  4877. force: bool = False,
  4878. cone: bool | None = None,
  4879. ) -> None:
  4880. """Perform a sparse checkout in the repository (either 'full' or 'cone mode').
  4881. Perform sparse checkout in either 'cone' (directory-based) mode or
  4882. 'full pattern' (.gitignore) mode, depending on the ``cone`` parameter.
  4883. If ``cone`` is ``None``, the mode is inferred from the repository's
  4884. ``core.sparseCheckoutCone`` config setting.
  4885. Steps:
  4886. 1) If ``patterns`` is provided, write them to ``.git/info/sparse-checkout``.
  4887. 2) Determine which paths in the index are included vs. excluded.
  4888. - If ``cone=True``, use "cone-compatible" directory-based logic.
  4889. - If ``cone=False``, use standard .gitignore-style matching.
  4890. 3) Update the index's skip-worktree bits and add/remove files in
  4891. the working tree accordingly.
  4892. 4) If ``force=False``, refuse to remove files that have local modifications.
  4893. Args:
  4894. repo: Path to the repository or a Repo object.
  4895. patterns: Optional list of sparse-checkout patterns to write.
  4896. force: Whether to force removal of locally modified files (default False).
  4897. cone: Boolean indicating cone mode (True/False). If None, read from config.
  4898. Returns:
  4899. None
  4900. """
  4901. with open_repo_closing(repo) as repo_obj:
  4902. # --- 0) Possibly infer 'cone' from config ---
  4903. if cone is None:
  4904. cone = repo_obj.get_worktree().infer_cone_mode()
  4905. # --- 1) Read or write patterns ---
  4906. if patterns is None:
  4907. lines = repo_obj.get_worktree().get_sparse_checkout_patterns()
  4908. if lines is None:
  4909. raise Error("No sparse checkout patterns found.")
  4910. else:
  4911. lines = patterns
  4912. repo_obj.get_worktree().set_sparse_checkout_patterns(patterns)
  4913. # --- 2) Determine the set of included paths ---
  4914. index = repo_obj.open_index()
  4915. included_paths = determine_included_paths(index, lines, cone)
  4916. # --- 3) Apply those results to the index & working tree ---
  4917. try:
  4918. apply_included_paths(repo_obj, included_paths, force=force)
  4919. except SparseCheckoutConflictError as exc:
  4920. raise CheckoutError(*exc.args) from exc
  4921. def cone_mode_init(repo: str | os.PathLike[str] | Repo) -> None:
  4922. """Initialize a repository to use sparse checkout in 'cone' mode.
  4923. Sets ``core.sparseCheckout`` and ``core.sparseCheckoutCone`` in the config.
  4924. Writes an initial ``.git/info/sparse-checkout`` file that includes only
  4925. top-level files (and excludes all subdirectories), e.g. ``["/*", "!/*/"]``.
  4926. Then performs a sparse checkout to update the working tree accordingly.
  4927. If no directories are specified, then only top-level files are included:
  4928. https://git-scm.com/docs/git-sparse-checkout#_internalscone_mode_handling
  4929. Args:
  4930. repo: Path to the repository or a Repo object.
  4931. Returns:
  4932. None
  4933. """
  4934. with open_repo_closing(repo) as repo_obj:
  4935. repo_obj.get_worktree().configure_for_cone_mode()
  4936. patterns = ["/*", "!/*/"] # root-level files only
  4937. sparse_checkout(repo_obj, patterns, force=True, cone=True)
  4938. def cone_mode_set(
  4939. repo: str | os.PathLike[str] | Repo, dirs: Sequence[str], force: bool = False
  4940. ) -> None:
  4941. """Overwrite the existing 'cone-mode' sparse patterns with a new set of directories.
  4942. Ensures ``core.sparseCheckout`` and ``core.sparseCheckoutCone`` are enabled.
  4943. Writes new patterns so that only the specified directories (and top-level files)
  4944. remain in the working tree, and applies the sparse checkout update.
  4945. Args:
  4946. repo: Path to the repository or a Repo object.
  4947. dirs: List of directory names to include.
  4948. force: Whether to forcibly discard local modifications (default False).
  4949. Returns:
  4950. None
  4951. """
  4952. with open_repo_closing(repo) as repo_obj:
  4953. repo_obj.get_worktree().configure_for_cone_mode()
  4954. repo_obj.get_worktree().set_cone_mode_patterns(dirs=dirs)
  4955. new_patterns = repo_obj.get_worktree().get_sparse_checkout_patterns()
  4956. # Finally, apply the patterns and update the working tree
  4957. sparse_checkout(repo_obj, new_patterns, force=force, cone=True)
  4958. def cone_mode_add(
  4959. repo: str | os.PathLike[str] | Repo, dirs: Sequence[str], force: bool = False
  4960. ) -> None:
  4961. """Add new directories to the existing 'cone-mode' sparse-checkout patterns.
  4962. Reads the current patterns from ``.git/info/sparse-checkout``, adds pattern
  4963. lines to include the specified directories, and then performs a sparse
  4964. checkout to update the working tree accordingly.
  4965. Args:
  4966. repo: Path to the repository or a Repo object.
  4967. dirs: List of directory names to add to the sparse-checkout.
  4968. force: Whether to forcibly discard local modifications (default False).
  4969. Returns:
  4970. None
  4971. """
  4972. with open_repo_closing(repo) as repo_obj:
  4973. repo_obj.get_worktree().configure_for_cone_mode()
  4974. # Do not pass base patterns as dirs
  4975. base_patterns = ["/*", "!/*/"]
  4976. existing_dirs = [
  4977. pat.strip("/")
  4978. for pat in repo_obj.get_worktree().get_sparse_checkout_patterns()
  4979. if pat not in base_patterns
  4980. ]
  4981. added_dirs = existing_dirs + list(dirs or [])
  4982. repo_obj.get_worktree().set_cone_mode_patterns(dirs=added_dirs)
  4983. new_patterns = repo_obj.get_worktree().get_sparse_checkout_patterns()
  4984. sparse_checkout(repo_obj, patterns=new_patterns, force=force, cone=True)
  4985. def check_mailmap(repo: RepoPath, contact: str | bytes) -> bytes:
  4986. """Check canonical name and email of contact.
  4987. Args:
  4988. repo: Path to the repository
  4989. contact: Contact name and/or email
  4990. Returns: Canonical contact data
  4991. """
  4992. with open_repo_closing(repo) as r:
  4993. from .mailmap import Mailmap
  4994. try:
  4995. mailmap = Mailmap.from_path(os.path.join(r.path, ".mailmap"))
  4996. except FileNotFoundError:
  4997. mailmap = Mailmap()
  4998. contact_bytes = (
  4999. contact.encode(DEFAULT_ENCODING) if isinstance(contact, str) else contact
  5000. )
  5001. result = mailmap.lookup(contact_bytes)
  5002. if isinstance(result, bytes):
  5003. return result
  5004. else:
  5005. # Convert tuple back to bytes format
  5006. name, email = result
  5007. if name is None:
  5008. name = b""
  5009. if email is None:
  5010. email = b""
  5011. return name + b" <" + email + b">"
  5012. def fsck(repo: RepoPath) -> Iterator[tuple[bytes, Exception]]:
  5013. """Check a repository.
  5014. Args:
  5015. repo: A path to the repository
  5016. Returns: Iterator over errors/warnings
  5017. """
  5018. with open_repo_closing(repo) as r:
  5019. # TODO(jelmer): check pack files
  5020. # TODO(jelmer): check graph
  5021. # TODO(jelmer): check refs
  5022. for sha in r.object_store:
  5023. o = r.object_store[sha]
  5024. try:
  5025. o.check()
  5026. except Exception as e:
  5027. yield (sha, e)
  5028. def stash_list(
  5029. repo: str | os.PathLike[str] | Repo,
  5030. ) -> Iterator[tuple[int, tuple[bytes, bytes]]]:
  5031. """List all stashes in a repository."""
  5032. with open_repo_closing(repo) as r:
  5033. from .stash import Stash
  5034. stash = Stash.from_repo(r)
  5035. entries = stash.stashes()
  5036. # Convert Entry objects to (old_sha, new_sha) tuples
  5037. return enumerate([(entry.old_sha, entry.new_sha) for entry in entries])
  5038. def stash_push(repo: str | os.PathLike[str] | Repo) -> None:
  5039. """Push a new stash onto the stack."""
  5040. with open_repo_closing(repo) as r:
  5041. from .stash import Stash
  5042. stash = Stash.from_repo(r)
  5043. stash.push()
  5044. def stash_pop(repo: str | os.PathLike[str] | Repo) -> None:
  5045. """Pop a stash from the stack."""
  5046. with open_repo_closing(repo) as r:
  5047. from .stash import Stash
  5048. stash = Stash.from_repo(r)
  5049. stash.pop(0)
  5050. def stash_drop(repo: str | os.PathLike[str] | Repo, index: int) -> None:
  5051. """Drop a stash from the stack."""
  5052. with open_repo_closing(repo) as r:
  5053. from .stash import Stash
  5054. stash = Stash.from_repo(r)
  5055. stash.drop(index)
  5056. def ls_files(repo: RepoPath) -> list[bytes]:
  5057. """List all files in an index."""
  5058. with open_repo_closing(repo) as r:
  5059. return sorted(r.open_index())
  5060. def find_unique_abbrev(
  5061. object_store: BaseObjectStore, object_id: str | bytes, min_length: int = 7
  5062. ) -> str:
  5063. """Find the shortest unique abbreviation for an object ID.
  5064. Args:
  5065. object_store: Object store to search in
  5066. object_id: The full object ID to abbreviate
  5067. min_length: Minimum length of abbreviation (default 7)
  5068. Returns:
  5069. The shortest unique prefix of the object ID (at least min_length chars)
  5070. """
  5071. if isinstance(object_id, bytes):
  5072. hex_id = object_id.decode("ascii")
  5073. else:
  5074. hex_id = object_id
  5075. # Start with minimum length
  5076. for length in range(min_length, len(hex_id) + 1):
  5077. prefix = hex_id[:length]
  5078. matches = 0
  5079. # Check if this prefix is unique
  5080. for obj_id in object_store:
  5081. if obj_id.decode("ascii").startswith(prefix):
  5082. matches += 1
  5083. if matches > 1:
  5084. # Not unique, need more characters
  5085. break
  5086. if matches == 1:
  5087. # Found unique prefix
  5088. return prefix
  5089. # If we get here, return the full ID
  5090. return hex_id
  5091. def describe(repo: str | os.PathLike[str] | Repo, abbrev: int | None = None) -> str:
  5092. """Describe the repository version.
  5093. Args:
  5094. repo: git repository
  5095. abbrev: number of characters of commit to take, default is 7
  5096. Returns: a string description of the current git revision
  5097. Examples: "gabcdefh", "v0.1" or "v0.1-5-gabcdefh".
  5098. """
  5099. abbrev_slice = slice(0, abbrev if abbrev is not None else 7)
  5100. # Get the repository
  5101. with open_repo_closing(repo) as r:
  5102. # Get a list of all tags
  5103. refs = r.get_refs()
  5104. tags = {}
  5105. for key, value in refs.items():
  5106. key_str = key.decode()
  5107. obj = r.get_object(value)
  5108. if "tags" not in key_str:
  5109. continue
  5110. _, tag = key_str.rsplit("/", 1)
  5111. if isinstance(obj, Tag):
  5112. # Annotated tag case
  5113. commit = r.get_object(obj.object[1])
  5114. else:
  5115. # Lightweight tag case - obj is already the commit
  5116. commit = obj
  5117. if not isinstance(commit, Commit):
  5118. raise AssertionError(
  5119. f"Expected Commit object, got {type(commit).__name__}"
  5120. )
  5121. tag_info: list[Any] = [
  5122. datetime.datetime(*time.gmtime(commit.commit_time)[:6]),
  5123. commit.id.decode("ascii"),
  5124. ]
  5125. tags[tag] = tag_info
  5126. # Sort tags by datetime (first element of the value list)
  5127. sorted_tags = sorted(
  5128. tags.items(), key=lambda tag_item: tag_item[1][0], reverse=True
  5129. )
  5130. # Get the latest commit
  5131. latest_commit = r[r.head()]
  5132. # If there are no tags, return the latest commit
  5133. if len(sorted_tags) == 0:
  5134. if abbrev is not None:
  5135. return "g{}".format(latest_commit.id.decode("ascii")[abbrev_slice])
  5136. return f"g{find_unique_abbrev(r.object_store, latest_commit.id)}"
  5137. # We're now 0 commits from the top
  5138. commit_count = 0
  5139. # Walk through all commits
  5140. walker = r.get_walker()
  5141. for entry in walker:
  5142. # Check if tag
  5143. commit_id = entry.commit.id.decode("ascii")
  5144. for tag_item in sorted_tags:
  5145. tag_name = tag_item[0]
  5146. tag_commit = tag_item[1][1]
  5147. if commit_id == tag_commit:
  5148. if commit_count == 0:
  5149. return tag_name
  5150. else:
  5151. if abbrev is not None:
  5152. abbrev_hash = latest_commit.id.decode("ascii")[abbrev_slice]
  5153. else:
  5154. abbrev_hash = find_unique_abbrev(
  5155. r.object_store, latest_commit.id
  5156. )
  5157. return f"{tag_name}-{commit_count}-g{abbrev_hash}"
  5158. commit_count += 1
  5159. # Return plain commit if no parent tag can be found
  5160. if abbrev is not None:
  5161. return "g{}".format(latest_commit.id.decode("ascii")[abbrev_slice])
  5162. return f"g{find_unique_abbrev(r.object_store, latest_commit.id)}"
  5163. def get_object_by_path(
  5164. repo: RepoPath,
  5165. path: str | bytes,
  5166. committish: str | bytes | Commit | Tag | None = None,
  5167. ) -> Blob | Tree | Commit | Tag:
  5168. """Get an object by path.
  5169. Args:
  5170. repo: A path to the repository
  5171. path: Path to look up
  5172. committish: Commit to look up path in
  5173. Returns: A `ShaFile` object
  5174. """
  5175. if committish is None:
  5176. committish = "HEAD"
  5177. # Get the repository
  5178. with open_repo_closing(repo) as r:
  5179. commit = parse_commit(r, committish)
  5180. base_tree = commit.tree
  5181. if not isinstance(path, bytes):
  5182. path = commit_encode(commit, path)
  5183. (_mode, sha) = tree_lookup_path(r.object_store.__getitem__, base_tree, path)
  5184. obj = r[sha]
  5185. assert isinstance(obj, (Blob, Tree, Commit, Tag))
  5186. return obj
  5187. def write_tree(repo: RepoPath) -> bytes:
  5188. """Write a tree object from the index.
  5189. Args:
  5190. repo: Repository for which to write tree
  5191. Returns: tree id for the tree that was written
  5192. """
  5193. with open_repo_closing(repo) as r:
  5194. return r.open_index().commit(r.object_store)
  5195. def _do_merge(
  5196. r: Repo,
  5197. merge_commit_id: bytes,
  5198. no_commit: bool = False,
  5199. no_ff: bool = False,
  5200. message: bytes | None = None,
  5201. author: bytes | None = None,
  5202. committer: bytes | None = None,
  5203. ) -> tuple[bytes | None, list[bytes]]:
  5204. """Internal merge implementation that operates on an open repository.
  5205. Args:
  5206. r: Open repository object
  5207. merge_commit_id: SHA of commit to merge
  5208. no_commit: If True, do not create a merge commit
  5209. no_ff: If True, force creation of a merge commit
  5210. message: Optional merge commit message
  5211. author: Optional author for merge commit
  5212. committer: Optional committer for merge commit
  5213. Returns:
  5214. Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None
  5215. if no_commit=True or there were conflicts
  5216. """
  5217. from .graph import find_merge_base
  5218. from .merge import recursive_merge
  5219. # Get HEAD commit
  5220. try:
  5221. head_commit_id = r.refs[b"HEAD"]
  5222. except KeyError:
  5223. raise Error("No HEAD reference found")
  5224. head_commit = r[head_commit_id]
  5225. assert isinstance(head_commit, Commit), "Expected a Commit object"
  5226. merge_commit = r[merge_commit_id]
  5227. assert isinstance(merge_commit, Commit), "Expected a Commit object"
  5228. # Check if fast-forward is possible
  5229. merge_bases = find_merge_base(r, [head_commit_id, merge_commit_id])
  5230. if not merge_bases:
  5231. raise Error("No common ancestor found")
  5232. # Use the first merge base for fast-forward checks
  5233. base_commit_id = merge_bases[0]
  5234. # Check if we're trying to merge the same commit
  5235. if head_commit_id == merge_commit_id:
  5236. # Already up to date
  5237. return (None, [])
  5238. # Check for fast-forward
  5239. if base_commit_id == head_commit_id and not no_ff:
  5240. # Fast-forward merge
  5241. r.refs[b"HEAD"] = merge_commit_id
  5242. # Update the working directory
  5243. changes = tree_changes(r.object_store, head_commit.tree, merge_commit.tree)
  5244. update_working_tree(
  5245. r, head_commit.tree, merge_commit.tree, change_iterator=changes
  5246. )
  5247. return (merge_commit_id, [])
  5248. if base_commit_id == merge_commit_id:
  5249. # Already up to date
  5250. return (None, [])
  5251. # Perform recursive merge (handles multiple merge bases automatically)
  5252. gitattributes = r.get_gitattributes()
  5253. config = r.get_config()
  5254. merged_tree, conflicts = recursive_merge(
  5255. r.object_store, merge_bases, head_commit, merge_commit, gitattributes, config
  5256. )
  5257. # Add merged tree to object store
  5258. r.object_store.add_object(merged_tree)
  5259. # Update index and working directory
  5260. changes = tree_changes(r.object_store, head_commit.tree, merged_tree.id)
  5261. update_working_tree(r, head_commit.tree, merged_tree.id, change_iterator=changes)
  5262. if conflicts or no_commit:
  5263. # Don't create a commit if there are conflicts or no_commit is True
  5264. return (None, conflicts)
  5265. # Create merge commit
  5266. merge_commit_obj = Commit()
  5267. merge_commit_obj.tree = merged_tree.id
  5268. merge_commit_obj.parents = [head_commit_id, merge_commit_id]
  5269. # Set author/committer
  5270. if author is None:
  5271. author = get_user_identity(r.get_config_stack())
  5272. if committer is None:
  5273. committer = author
  5274. merge_commit_obj.author = author
  5275. merge_commit_obj.committer = committer
  5276. # Set timestamps
  5277. timestamp = int(time.time())
  5278. timezone = 0 # UTC
  5279. merge_commit_obj.author_time = timestamp
  5280. merge_commit_obj.author_timezone = timezone
  5281. merge_commit_obj.commit_time = timestamp
  5282. merge_commit_obj.commit_timezone = timezone
  5283. # Set commit message
  5284. if message is None:
  5285. message = f"Merge commit '{merge_commit_id.decode()[:7]}'\n".encode()
  5286. merge_commit_obj.message = message.encode() if isinstance(message, str) else message
  5287. # Add commit to object store
  5288. r.object_store.add_object(merge_commit_obj)
  5289. # Update HEAD
  5290. r.refs[b"HEAD"] = merge_commit_obj.id
  5291. return (merge_commit_obj.id, [])
  5292. def _do_octopus_merge(
  5293. r: Repo,
  5294. merge_commit_ids: list[bytes],
  5295. no_commit: bool = False,
  5296. no_ff: bool = False,
  5297. message: bytes | None = None,
  5298. author: bytes | None = None,
  5299. committer: bytes | None = None,
  5300. ) -> tuple[bytes | None, list[bytes]]:
  5301. """Internal octopus merge implementation that operates on an open repository.
  5302. Args:
  5303. r: Open repository object
  5304. merge_commit_ids: List of commit SHAs to merge
  5305. no_commit: If True, do not create a merge commit
  5306. no_ff: If True, force creation of a merge commit (ignored for octopus)
  5307. message: Optional merge commit message
  5308. author: Optional author for merge commit
  5309. committer: Optional committer for merge commit
  5310. Returns:
  5311. Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None
  5312. if no_commit=True or there were conflicts
  5313. """
  5314. from .graph import find_octopus_base
  5315. from .merge import octopus_merge
  5316. # Get HEAD commit
  5317. try:
  5318. head_commit_id = r.refs[b"HEAD"]
  5319. except KeyError:
  5320. raise Error("No HEAD reference found")
  5321. head_commit = r[head_commit_id]
  5322. assert isinstance(head_commit, Commit), "Expected a Commit object"
  5323. # Get all commits to merge
  5324. other_commits = []
  5325. for merge_commit_id in merge_commit_ids:
  5326. merge_commit = r[merge_commit_id]
  5327. assert isinstance(merge_commit, Commit), "Expected a Commit object"
  5328. # Check if we're trying to merge the same commit as HEAD
  5329. if head_commit_id == merge_commit_id:
  5330. # Skip this commit, it's already merged
  5331. continue
  5332. other_commits.append(merge_commit)
  5333. # If no commits to merge after filtering, we're already up to date
  5334. if not other_commits:
  5335. return (None, [])
  5336. # If only one commit to merge, use regular merge
  5337. if len(other_commits) == 1:
  5338. return _do_merge(
  5339. r, other_commits[0].id, no_commit, no_ff, message, author, committer
  5340. )
  5341. # Find the octopus merge base
  5342. all_commit_ids = [head_commit_id] + [c.id for c in other_commits]
  5343. merge_bases = find_octopus_base(r, all_commit_ids)
  5344. if not merge_bases:
  5345. raise Error("No common ancestor found")
  5346. # Check if this is a fast-forward (HEAD is the merge base)
  5347. # For octopus merges, fast-forward doesn't really apply, so we always create a merge commit
  5348. # Perform octopus merge
  5349. gitattributes = r.get_gitattributes()
  5350. config = r.get_config()
  5351. merged_tree, conflicts = octopus_merge(
  5352. r.object_store, merge_bases, head_commit, other_commits, gitattributes, config
  5353. )
  5354. # Add merged tree to object store
  5355. r.object_store.add_object(merged_tree)
  5356. # Update index and working directory
  5357. changes = tree_changes(r.object_store, head_commit.tree, merged_tree.id)
  5358. update_working_tree(r, head_commit.tree, merged_tree.id, change_iterator=changes)
  5359. if conflicts:
  5360. # Don't create a commit if there are conflicts
  5361. # Octopus merge refuses to proceed with conflicts
  5362. return (None, conflicts)
  5363. if no_commit:
  5364. # Don't create a commit if no_commit is True
  5365. return (None, [])
  5366. # Create merge commit with multiple parents
  5367. merge_commit_obj = Commit()
  5368. merge_commit_obj.tree = merged_tree.id
  5369. merge_commit_obj.parents = [head_commit_id] + [c.id for c in other_commits]
  5370. # Set author/committer
  5371. if author is None:
  5372. author = get_user_identity(r.get_config_stack())
  5373. if committer is None:
  5374. committer = author
  5375. merge_commit_obj.author = author
  5376. merge_commit_obj.committer = committer
  5377. # Set timestamps
  5378. timestamp = int(time.time())
  5379. timezone = 0 # UTC
  5380. merge_commit_obj.author_time = timestamp
  5381. merge_commit_obj.author_timezone = timezone
  5382. merge_commit_obj.commit_time = timestamp
  5383. merge_commit_obj.commit_timezone = timezone
  5384. # Set commit message
  5385. if message is None:
  5386. # Generate default message for octopus merge
  5387. branch_names = []
  5388. for commit_id in merge_commit_ids:
  5389. branch_names.append(commit_id.decode()[:7])
  5390. message = f"Merge commits {', '.join(branch_names)}\n".encode()
  5391. merge_commit_obj.message = message.encode() if isinstance(message, str) else message
  5392. # Add commit to object store
  5393. r.object_store.add_object(merge_commit_obj)
  5394. # Update HEAD
  5395. r.refs[b"HEAD"] = merge_commit_obj.id
  5396. return (merge_commit_obj.id, [])
  5397. def merge(
  5398. repo: str | os.PathLike[str] | Repo,
  5399. committish: str | bytes | Commit | Tag | Sequence[str | bytes | Commit | Tag],
  5400. no_commit: bool = False,
  5401. no_ff: bool = False,
  5402. message: bytes | None = None,
  5403. author: bytes | None = None,
  5404. committer: bytes | None = None,
  5405. ) -> tuple[bytes | None, list[bytes]]:
  5406. """Merge one or more commits into the current branch.
  5407. Args:
  5408. repo: Repository to merge into
  5409. committish: Commit(s) to merge. Can be a single commit or a sequence of commits.
  5410. When merging more than two heads, the octopus merge strategy is used.
  5411. no_commit: If True, do not create a merge commit
  5412. no_ff: If True, force creation of a merge commit
  5413. message: Optional merge commit message
  5414. author: Optional author for merge commit
  5415. committer: Optional committer for merge commit
  5416. Returns:
  5417. Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None
  5418. if no_commit=True or there were conflicts
  5419. Raises:
  5420. Error: If there is no HEAD reference or commit cannot be found
  5421. """
  5422. with open_repo_closing(repo) as r:
  5423. # Handle both single commit and multiple commits
  5424. if isinstance(committish, (list, tuple)):
  5425. # Multiple commits - use octopus merge
  5426. merge_commit_ids = []
  5427. for c in committish:
  5428. try:
  5429. merge_commit_ids.append(parse_commit(r, c).id)
  5430. except KeyError:
  5431. raise Error(
  5432. f"Cannot find commit '{c.decode() if isinstance(c, bytes) else c}'"
  5433. )
  5434. if len(merge_commit_ids) == 1:
  5435. # Only one commit, use regular merge
  5436. result = _do_merge(
  5437. r, merge_commit_ids[0], no_commit, no_ff, message, author, committer
  5438. )
  5439. else:
  5440. # Multiple commits, use octopus merge
  5441. result = _do_octopus_merge(
  5442. r, merge_commit_ids, no_commit, no_ff, message, author, committer
  5443. )
  5444. else:
  5445. # Single commit - use regular merge
  5446. # Type narrowing: committish is not a sequence in this branch
  5447. single_committish = cast(str | bytes | Commit | Tag, committish)
  5448. try:
  5449. merge_commit_id = parse_commit(r, single_committish).id
  5450. except KeyError:
  5451. raise Error(
  5452. f"Cannot find commit '{single_committish.decode() if isinstance(single_committish, bytes) else single_committish}'"
  5453. )
  5454. result = _do_merge(
  5455. r, merge_commit_id, no_commit, no_ff, message, author, committer
  5456. )
  5457. # Trigger auto GC if needed
  5458. from .gc import maybe_auto_gc
  5459. maybe_auto_gc(r)
  5460. return result
  5461. def unpack_objects(
  5462. pack_path: str | os.PathLike[str], target: str | os.PathLike[str] = "."
  5463. ) -> int:
  5464. """Unpack objects from a pack file into the repository.
  5465. Args:
  5466. pack_path: Path to the pack file to unpack
  5467. target: Path to the repository to unpack into
  5468. Returns:
  5469. Number of objects unpacked
  5470. """
  5471. from .pack import Pack
  5472. with open_repo_closing(target) as r:
  5473. pack_basename = os.path.splitext(pack_path)[0]
  5474. with Pack(pack_basename) as pack:
  5475. count = 0
  5476. for unpacked in pack.iter_unpacked():
  5477. obj = unpacked.sha_file()
  5478. r.object_store.add_object(obj)
  5479. count += 1
  5480. return count
  5481. def merge_tree(
  5482. repo: RepoPath,
  5483. base_tree: str | bytes | Tree | Commit | Tag | None,
  5484. our_tree: str | bytes | Tree | Commit | Tag,
  5485. their_tree: str | bytes | Tree | Commit | Tag,
  5486. ) -> tuple[bytes, list[bytes]]:
  5487. """Perform a three-way tree merge without touching the working directory.
  5488. This is similar to git merge-tree, performing a merge at the tree level
  5489. without creating commits or updating any references.
  5490. Args:
  5491. repo: Repository containing the trees
  5492. base_tree: Tree-ish of the common ancestor (or None for no common ancestor)
  5493. our_tree: Tree-ish of our side of the merge
  5494. their_tree: Tree-ish of their side of the merge
  5495. Returns:
  5496. tuple: A tuple of (merged_tree_id, conflicts) where:
  5497. - merged_tree_id is the SHA-1 of the merged tree
  5498. - conflicts is a list of paths (as bytes) that had conflicts
  5499. Raises:
  5500. KeyError: If any of the tree-ish arguments cannot be resolved
  5501. """
  5502. from .merge import Merger
  5503. with open_repo_closing(repo) as r:
  5504. # Resolve tree-ish arguments to actual trees
  5505. base = parse_tree(r, base_tree) if base_tree else None
  5506. ours = parse_tree(r, our_tree)
  5507. theirs = parse_tree(r, their_tree)
  5508. # Perform the merge
  5509. gitattributes = r.get_gitattributes()
  5510. config = r.get_config()
  5511. merger = Merger(r.object_store, gitattributes, config)
  5512. merged_tree, conflicts = merger.merge_trees(base, ours, theirs)
  5513. # Add the merged tree to the object store
  5514. r.object_store.add_object(merged_tree)
  5515. return merged_tree.id, conflicts
  5516. def cherry(
  5517. repo: str | os.PathLike[str] | Repo,
  5518. upstream: str | bytes | None = None,
  5519. head: str | bytes | None = None,
  5520. limit: str | bytes | None = None,
  5521. verbose: bool = False,
  5522. ) -> list[tuple[str, bytes, bytes | None]]:
  5523. """Find commits not merged upstream.
  5524. Args:
  5525. repo: Repository path or object
  5526. upstream: Upstream branch (default: tracking branch or @{upstream})
  5527. head: Head branch (default: HEAD)
  5528. limit: Limit commits to those after this ref
  5529. verbose: Include commit messages in output
  5530. Returns:
  5531. List of tuples (status, commit_sha, message) where status is '+' or '-'
  5532. '+' means commit is not in upstream, '-' means equivalent patch exists upstream
  5533. message is None unless verbose=True
  5534. """
  5535. from .patch import commit_patch_id
  5536. with open_repo_closing(repo) as r:
  5537. # Resolve upstream
  5538. if upstream is None:
  5539. # Try to find tracking branch
  5540. upstream_found = False
  5541. head_refs, _ = r.refs.follow(b"HEAD")
  5542. if head_refs:
  5543. head_ref = head_refs[0]
  5544. if head_ref.startswith(b"refs/heads/"):
  5545. config = r.get_config()
  5546. branch_name = head_ref[len(b"refs/heads/") :]
  5547. try:
  5548. upstream_ref = config.get((b"branch", branch_name), b"merge")
  5549. except KeyError:
  5550. upstream_ref = None
  5551. if upstream_ref:
  5552. try:
  5553. remote_name = config.get(
  5554. (b"branch", branch_name), b"remote"
  5555. )
  5556. except KeyError:
  5557. remote_name = None
  5558. if remote_name:
  5559. # Build the tracking branch ref
  5560. upstream_refname = (
  5561. b"refs/remotes/"
  5562. + remote_name
  5563. + b"/"
  5564. + upstream_ref.split(b"/")[-1]
  5565. )
  5566. if upstream_refname in r.refs:
  5567. upstream = upstream_refname
  5568. upstream_found = True
  5569. if not upstream_found:
  5570. # Default to HEAD^ if no tracking branch found
  5571. head_commit = r[b"HEAD"]
  5572. if isinstance(head_commit, Commit) and head_commit.parents:
  5573. upstream = head_commit.parents[0]
  5574. else:
  5575. raise ValueError("Could not determine upstream branch")
  5576. # Resolve head
  5577. if head is None:
  5578. head = b"HEAD"
  5579. # Convert strings to bytes
  5580. if isinstance(upstream, str):
  5581. upstream = upstream.encode("utf-8")
  5582. if isinstance(head, str):
  5583. head = head.encode("utf-8")
  5584. if limit is not None and isinstance(limit, str):
  5585. limit = limit.encode("utf-8")
  5586. # Resolve refs to commit IDs
  5587. assert upstream is not None
  5588. upstream_obj = r[upstream]
  5589. head_obj = r[head]
  5590. upstream_id = upstream_obj.id
  5591. head_id = head_obj.id
  5592. # Get limit commit ID if specified
  5593. limit_id = None
  5594. if limit is not None:
  5595. limit_id = r[limit].id
  5596. # Find all commits reachable from head but not from upstream
  5597. # This is equivalent to: git rev-list ^upstream head
  5598. # Get commits from head that are not in upstream
  5599. walker = r.get_walker([head_id], exclude=[upstream_id])
  5600. head_commits = []
  5601. for entry in walker:
  5602. commit = entry.commit
  5603. # Apply limit if specified
  5604. if limit_id is not None:
  5605. # Stop when we reach the limit commit
  5606. if commit.id == limit_id:
  5607. break
  5608. head_commits.append(commit.id)
  5609. # Compute patch IDs for upstream commits
  5610. upstream_walker = r.get_walker([upstream_id])
  5611. upstream_patch_ids = {} # Maps patch_id -> commit_id for debugging
  5612. for entry in upstream_walker:
  5613. commit = entry.commit
  5614. pid = commit_patch_id(r.object_store, commit.id)
  5615. upstream_patch_ids[pid] = commit.id
  5616. # For each head commit, check if equivalent patch exists in upstream
  5617. results: list[tuple[str, bytes, bytes | None]] = []
  5618. for commit_id in reversed(head_commits): # Show oldest first
  5619. obj = r.object_store[commit_id]
  5620. assert isinstance(obj, Commit)
  5621. commit = obj
  5622. pid = commit_patch_id(r.object_store, commit_id)
  5623. if pid in upstream_patch_ids:
  5624. status = "-"
  5625. else:
  5626. status = "+"
  5627. message = None
  5628. if verbose:
  5629. message = commit.message.split(b"\n")[0] # First line only
  5630. results.append((status, commit_id, message))
  5631. return results
  5632. def cherry_pick( # noqa: D417
  5633. repo: str | os.PathLike[str] | Repo,
  5634. committish: str | bytes | Commit | Tag | None,
  5635. no_commit: bool = False,
  5636. continue_: bool = False,
  5637. abort: bool = False,
  5638. ) -> bytes | None:
  5639. r"""Cherry-pick a commit onto the current branch.
  5640. Args:
  5641. repo: Repository to cherry-pick into
  5642. committish: Commit to cherry-pick (can be None only when resuming or aborting)
  5643. no_commit: If True, do not create a commit after applying changes
  5644. ``continue_``: Resume an in-progress cherry-pick after resolving conflicts if True
  5645. abort: Abort an in-progress cherry-pick
  5646. Returns:
  5647. The SHA of the newly created commit, or None if no_commit=True or there were conflicts
  5648. Raises:
  5649. Error: If there is no HEAD reference, commit cannot be found, or operation fails
  5650. """
  5651. from .merge import three_way_merge
  5652. # Validate that committish is provided when needed
  5653. if not (continue_ or abort) and committish is None:
  5654. raise ValueError("committish is required when not using --continue or --abort")
  5655. with open_repo_closing(repo) as r:
  5656. # Handle abort
  5657. if abort:
  5658. # Clean up any cherry-pick state
  5659. try:
  5660. os.remove(os.path.join(r.controldir(), "CHERRY_PICK_HEAD"))
  5661. except FileNotFoundError:
  5662. pass
  5663. try:
  5664. os.remove(os.path.join(r.controldir(), "MERGE_MSG"))
  5665. except FileNotFoundError:
  5666. pass
  5667. # Reset index to HEAD
  5668. head_commit = r[b"HEAD"]
  5669. assert isinstance(head_commit, Commit)
  5670. r.get_worktree().reset_index(head_commit.tree)
  5671. return None
  5672. # Handle continue
  5673. if continue_:
  5674. # Check if there's a cherry-pick in progress
  5675. cherry_pick_head_path = os.path.join(r.controldir(), "CHERRY_PICK_HEAD")
  5676. try:
  5677. with open(cherry_pick_head_path, "rb") as f:
  5678. cherry_pick_commit_id = f.read().strip()
  5679. cherry_pick_commit = r[cherry_pick_commit_id]
  5680. except FileNotFoundError:
  5681. raise Error("No cherry-pick in progress")
  5682. # Check for unresolved conflicts
  5683. if r.open_index().has_conflicts():
  5684. raise Error("Unresolved conflicts remain")
  5685. # Create the commit
  5686. tree_id = r.open_index().commit(r.object_store)
  5687. # Read saved message if any
  5688. merge_msg_path = os.path.join(r.controldir(), "MERGE_MSG")
  5689. try:
  5690. with open(merge_msg_path, "rb") as f:
  5691. message = f.read()
  5692. except FileNotFoundError:
  5693. assert isinstance(cherry_pick_commit, Commit)
  5694. message = cherry_pick_commit.message
  5695. assert isinstance(cherry_pick_commit, Commit)
  5696. new_commit = r.get_worktree().commit(
  5697. message=message,
  5698. tree=tree_id,
  5699. author=cherry_pick_commit.author,
  5700. author_timestamp=cherry_pick_commit.author_time,
  5701. author_timezone=cherry_pick_commit.author_timezone,
  5702. )
  5703. # Clean up state files
  5704. try:
  5705. os.remove(cherry_pick_head_path)
  5706. except FileNotFoundError:
  5707. pass
  5708. try:
  5709. os.remove(merge_msg_path)
  5710. except FileNotFoundError:
  5711. pass
  5712. return new_commit
  5713. # Normal cherry-pick operation
  5714. # Get current HEAD
  5715. try:
  5716. head_commit = r[b"HEAD"]
  5717. except KeyError:
  5718. raise Error("No HEAD reference found")
  5719. # Parse the commit to cherry-pick
  5720. # committish cannot be None here due to validation above
  5721. assert committish is not None
  5722. try:
  5723. cherry_pick_commit = parse_commit(r, committish)
  5724. except KeyError:
  5725. raise Error(
  5726. f"Cannot find commit '{committish.decode() if isinstance(committish, bytes) else committish}'"
  5727. )
  5728. # Check if commit has parents
  5729. assert isinstance(cherry_pick_commit, Commit)
  5730. if not cherry_pick_commit.parents:
  5731. raise Error("Cannot cherry-pick root commit")
  5732. # Get parent of cherry-pick commit
  5733. parent_commit = r[cherry_pick_commit.parents[0]]
  5734. assert isinstance(parent_commit, Commit)
  5735. # Perform three-way merge
  5736. assert isinstance(head_commit, Commit)
  5737. merged_tree, conflicts = three_way_merge(
  5738. r.object_store, parent_commit, head_commit, cherry_pick_commit
  5739. )
  5740. # Add merged tree to object store
  5741. r.object_store.add_object(merged_tree)
  5742. # Update working tree and index
  5743. # Reset index to match merged tree
  5744. r.get_worktree().reset_index(merged_tree.id)
  5745. # Update working tree from the new index
  5746. # Allow overwriting because we're applying the merge result
  5747. assert isinstance(head_commit, Commit)
  5748. changes = tree_changes(r.object_store, head_commit.tree, merged_tree.id)
  5749. update_working_tree(
  5750. r,
  5751. head_commit.tree,
  5752. merged_tree.id,
  5753. change_iterator=changes,
  5754. allow_overwrite_modified=True,
  5755. )
  5756. if conflicts:
  5757. # Save state for later continuation
  5758. with open(os.path.join(r.controldir(), "CHERRY_PICK_HEAD"), "wb") as f:
  5759. f.write(cherry_pick_commit.id + b"\n")
  5760. # Save commit message
  5761. with open(os.path.join(r.controldir(), "MERGE_MSG"), "wb") as f:
  5762. f.write(cherry_pick_commit.message)
  5763. raise Error(
  5764. f"Conflicts in: {', '.join(c.decode('utf-8', 'replace') for c in conflicts)}\n"
  5765. f"Fix conflicts and run 'dulwich cherry-pick --continue'"
  5766. )
  5767. if no_commit:
  5768. return None
  5769. # Create the commit
  5770. new_commit = r.get_worktree().commit(
  5771. message=cherry_pick_commit.message,
  5772. tree=merged_tree.id,
  5773. author=cherry_pick_commit.author,
  5774. author_timestamp=cherry_pick_commit.author_time,
  5775. author_timezone=cherry_pick_commit.author_timezone,
  5776. )
  5777. return new_commit
  5778. def revert(
  5779. repo: str | os.PathLike[str] | Repo,
  5780. commits: str | bytes | Commit | Tag | Sequence[str | bytes | Commit | Tag],
  5781. no_commit: bool = False,
  5782. message: str | bytes | None = None,
  5783. author: bytes | None = None,
  5784. committer: bytes | None = None,
  5785. ) -> bytes | None:
  5786. """Revert one or more commits.
  5787. This creates a new commit that undoes the changes introduced by the
  5788. specified commits. Unlike reset, revert creates a new commit that
  5789. preserves history.
  5790. Args:
  5791. repo: Path to repository or repository object
  5792. commits: List of commit-ish (SHA, ref, etc.) to revert, or a single commit-ish
  5793. no_commit: If True, apply changes to index/working tree but don't commit
  5794. message: Optional commit message (default: "Revert <original subject>")
  5795. author: Optional author for revert commit
  5796. committer: Optional committer for revert commit
  5797. Returns:
  5798. SHA1 of the new revert commit, or None if no_commit=True
  5799. Raises:
  5800. Error: If revert fails due to conflicts or other issues
  5801. """
  5802. from .merge import three_way_merge
  5803. # Normalize commits to a list
  5804. if isinstance(commits, (str, bytes, Commit, Tag)):
  5805. commits = [commits]
  5806. with open_repo_closing(repo) as r:
  5807. # Convert string refs to bytes
  5808. commits_to_revert = []
  5809. for commit_ref in commits:
  5810. if isinstance(commit_ref, str):
  5811. commit_ref = commit_ref.encode("utf-8")
  5812. commit = parse_commit(r, commit_ref)
  5813. commits_to_revert.append(commit)
  5814. # Get current HEAD
  5815. try:
  5816. head_commit_id = r.refs[b"HEAD"]
  5817. except KeyError:
  5818. raise Error("No HEAD reference found")
  5819. head_commit = r[head_commit_id]
  5820. assert isinstance(head_commit, Commit)
  5821. current_tree = head_commit.tree
  5822. # Process commits in order
  5823. for commit_to_revert in commits_to_revert:
  5824. # For revert, we want to apply the inverse of the commit
  5825. # This means using the commit's tree as "base" and its parent as "theirs"
  5826. if not commit_to_revert.parents:
  5827. raise Error(
  5828. f"Cannot revert commit {commit_to_revert.id.decode() if isinstance(commit_to_revert.id, bytes) else commit_to_revert.id} - it has no parents"
  5829. )
  5830. # For simplicity, we only handle commits with one parent (no merge commits)
  5831. if len(commit_to_revert.parents) > 1:
  5832. raise Error(
  5833. f"Cannot revert merge commit {commit_to_revert.id.decode() if isinstance(commit_to_revert.id, bytes) else commit_to_revert.id} - not yet implemented"
  5834. )
  5835. parent_commit = r[commit_to_revert.parents[0]]
  5836. assert isinstance(parent_commit, Commit)
  5837. # Perform three-way merge:
  5838. # - base: the commit we're reverting (what we want to remove)
  5839. # - ours: current HEAD (what we have now)
  5840. # - theirs: parent of commit being reverted (what we want to go back to)
  5841. assert isinstance(commit_to_revert, Commit)
  5842. head_for_merge = r[head_commit_id]
  5843. assert isinstance(head_for_merge, Commit)
  5844. merged_tree, conflicts = three_way_merge(
  5845. r.object_store,
  5846. commit_to_revert, # base
  5847. head_for_merge, # ours
  5848. parent_commit, # theirs
  5849. )
  5850. if conflicts:
  5851. # Update working tree with conflicts
  5852. changes = tree_changes(r.object_store, current_tree, merged_tree.id)
  5853. update_working_tree(
  5854. r, current_tree, merged_tree.id, change_iterator=changes
  5855. )
  5856. conflicted_paths = [c.decode("utf-8", "replace") for c in conflicts]
  5857. raise Error(f"Conflicts while reverting: {', '.join(conflicted_paths)}")
  5858. # Add merged tree to object store
  5859. r.object_store.add_object(merged_tree)
  5860. # Update working tree
  5861. changes = tree_changes(r.object_store, current_tree, merged_tree.id)
  5862. update_working_tree(
  5863. r, current_tree, merged_tree.id, change_iterator=changes
  5864. )
  5865. current_tree = merged_tree.id
  5866. if not no_commit:
  5867. # Create revert commit
  5868. revert_commit = Commit()
  5869. revert_commit.tree = merged_tree.id
  5870. revert_commit.parents = [head_commit_id]
  5871. # Set author/committer
  5872. if author is None:
  5873. author = get_user_identity(r.get_config_stack())
  5874. if committer is None:
  5875. committer = author
  5876. revert_commit.author = author
  5877. revert_commit.committer = committer
  5878. # Set timestamps
  5879. timestamp = int(time.time())
  5880. timezone = 0 # UTC
  5881. revert_commit.author_time = timestamp
  5882. revert_commit.author_timezone = timezone
  5883. revert_commit.commit_time = timestamp
  5884. revert_commit.commit_timezone = timezone
  5885. # Set message
  5886. if message is None:
  5887. # Extract original commit subject
  5888. original_message = commit_to_revert.message
  5889. if isinstance(original_message, bytes):
  5890. original_message = original_message.decode("utf-8", "replace")
  5891. subject = original_message.split("\n")[0]
  5892. message = f'Revert "{subject}"\n\nThis reverts commit {commit_to_revert.id.decode("ascii")}.'.encode()
  5893. elif isinstance(message, str):
  5894. message = message.encode("utf-8")
  5895. revert_commit.message = message
  5896. # Add commit to object store
  5897. r.object_store.add_object(revert_commit)
  5898. # Update HEAD
  5899. r.refs[b"HEAD"] = revert_commit.id
  5900. head_commit_id = revert_commit.id
  5901. return head_commit_id if not no_commit else None
  5902. def gc(
  5903. repo: RepoPath,
  5904. auto: bool = False,
  5905. aggressive: bool = False,
  5906. prune: bool = True,
  5907. grace_period: int | None = 1209600, # 2 weeks default
  5908. dry_run: bool = False,
  5909. progress: Callable[[str], None] | None = None,
  5910. ) -> "GCStats":
  5911. """Run garbage collection on a repository.
  5912. Args:
  5913. repo: Path to the repository or a Repo object
  5914. auto: If True, only run gc if needed
  5915. aggressive: If True, use more aggressive settings
  5916. prune: If True, prune unreachable objects
  5917. grace_period: Grace period in seconds for pruning (default 2 weeks)
  5918. dry_run: If True, only report what would be done
  5919. progress: Optional progress callback
  5920. Returns:
  5921. GCStats object with garbage collection statistics
  5922. """
  5923. from .gc import garbage_collect
  5924. with open_repo_closing(repo) as r:
  5925. return garbage_collect(
  5926. r,
  5927. auto=auto,
  5928. aggressive=aggressive,
  5929. prune=prune,
  5930. grace_period=grace_period,
  5931. dry_run=dry_run,
  5932. progress=progress,
  5933. )
  5934. def prune(
  5935. repo: RepoPath,
  5936. grace_period: int | None = None,
  5937. dry_run: bool = False,
  5938. progress: Callable[[str], None] | None = None,
  5939. ) -> None:
  5940. """Prune/clean up a repository's object store.
  5941. This removes temporary files that were left behind by interrupted
  5942. pack operations.
  5943. Args:
  5944. repo: Path to the repository or a Repo object
  5945. grace_period: Grace period in seconds for removing temporary files
  5946. (default 2 weeks)
  5947. dry_run: If True, only report what would be done
  5948. progress: Optional progress callback
  5949. """
  5950. with open_repo_closing(repo) as r:
  5951. if progress:
  5952. progress("Pruning temporary files")
  5953. if not dry_run:
  5954. r.object_store.prune(grace_period=grace_period)
  5955. def maintenance_run(
  5956. repo: RepoPath,
  5957. tasks: list[str] | None = None,
  5958. auto: bool = False,
  5959. progress: Callable[[str], None] | None = None,
  5960. ) -> "MaintenanceResult":
  5961. """Run maintenance tasks on a repository.
  5962. Args:
  5963. repo: Path to the repository or a Repo object
  5964. tasks: Optional list of specific task names to run
  5965. (e.g., ['gc', 'commit-graph', 'pack-refs'])
  5966. auto: If True, only run tasks if needed
  5967. progress: Optional progress callback
  5968. Returns:
  5969. MaintenanceResult object with task execution results
  5970. """
  5971. from .maintenance import run_maintenance
  5972. with open_repo_closing(repo) as r:
  5973. return run_maintenance(r, tasks=tasks, auto=auto, progress=progress)
  5974. def maintenance_register(repo: RepoPath) -> None:
  5975. """Register a repository for background maintenance.
  5976. This adds the repository to the global maintenance.repo config and sets
  5977. up recommended configuration for scheduled maintenance.
  5978. Args:
  5979. repo: Path to the repository or repository object
  5980. """
  5981. from .maintenance import register_repository
  5982. with open_repo_closing(repo) as r:
  5983. register_repository(r)
  5984. def maintenance_unregister(repo: RepoPath, force: bool = False) -> None:
  5985. """Unregister a repository from background maintenance.
  5986. This removes the repository from the global maintenance.repo config.
  5987. Args:
  5988. repo: Path to the repository or repository object
  5989. force: If True, don't error if repository is not registered
  5990. """
  5991. from .maintenance import unregister_repository
  5992. with open_repo_closing(repo) as r:
  5993. unregister_repository(r, force=force)
  5994. def count_objects(repo: RepoPath = ".", verbose: bool = False) -> CountObjectsResult:
  5995. """Count unpacked objects and their disk usage.
  5996. Args:
  5997. repo: Path to repository or repository object
  5998. verbose: Whether to return verbose information
  5999. Returns:
  6000. CountObjectsResult object with detailed statistics
  6001. """
  6002. with open_repo_closing(repo) as r:
  6003. object_store = r.object_store
  6004. # Count loose objects
  6005. loose_count = 0
  6006. loose_size = 0
  6007. for sha in object_store._iter_loose_objects():
  6008. loose_count += 1
  6009. from .object_store import DiskObjectStore
  6010. assert isinstance(object_store, DiskObjectStore)
  6011. path = object_store._get_shafile_path(sha)
  6012. try:
  6013. stat_info = os.stat(path)
  6014. # Git uses disk usage, not file size. st_blocks is always in
  6015. # 512-byte blocks per POSIX standard
  6016. st_blocks = getattr(stat_info, "st_blocks", None)
  6017. if st_blocks is not None:
  6018. # Available on Linux and macOS
  6019. loose_size += st_blocks * 512
  6020. else:
  6021. # Fallback for Windows
  6022. loose_size += stat_info.st_size
  6023. except FileNotFoundError:
  6024. # Object may have been removed between iteration and stat
  6025. pass
  6026. if not verbose:
  6027. return CountObjectsResult(count=loose_count, size=loose_size)
  6028. # Count pack information
  6029. pack_count = len(object_store.packs)
  6030. in_pack_count = 0
  6031. pack_size = 0
  6032. for pack in object_store.packs:
  6033. in_pack_count += len(pack)
  6034. # Get pack file size
  6035. pack_path = pack._data_path
  6036. try:
  6037. pack_size += os.path.getsize(pack_path)
  6038. except FileNotFoundError:
  6039. pass
  6040. # Get index file size
  6041. idx_path = pack._idx_path
  6042. try:
  6043. pack_size += os.path.getsize(idx_path)
  6044. except FileNotFoundError:
  6045. pass
  6046. return CountObjectsResult(
  6047. count=loose_count,
  6048. size=loose_size,
  6049. in_pack=in_pack_count,
  6050. packs=pack_count,
  6051. size_pack=pack_size,
  6052. )
  6053. def is_interactive_rebase(repo: Repo | str) -> bool:
  6054. """Check if an interactive rebase is in progress.
  6055. Args:
  6056. repo: Repository to check
  6057. Returns:
  6058. True if interactive rebase is in progress, False otherwise
  6059. """
  6060. with open_repo_closing(repo) as r:
  6061. state_manager = r.get_rebase_state_manager()
  6062. if not state_manager.exists():
  6063. return False
  6064. # Check if todo file exists
  6065. todo = state_manager.load_todo()
  6066. return todo is not None
  6067. def rebase(
  6068. repo: Repo | str,
  6069. upstream: bytes | str,
  6070. onto: bytes | str | None = None,
  6071. branch: bytes | str | None = None,
  6072. abort: bool = False,
  6073. continue_rebase: bool = False,
  6074. skip: bool = False,
  6075. interactive: bool = False,
  6076. edit_todo: bool = False,
  6077. ) -> list[bytes]:
  6078. """Rebase commits onto another branch.
  6079. Args:
  6080. repo: Repository to rebase in
  6081. upstream: Upstream branch/commit to rebase onto
  6082. onto: Specific commit to rebase onto (defaults to upstream)
  6083. branch: Branch to rebase (defaults to current branch)
  6084. abort: Abort an in-progress rebase
  6085. continue_rebase: Continue an in-progress rebase
  6086. skip: Skip current commit and continue rebase
  6087. interactive: Start an interactive rebase
  6088. edit_todo: Edit the todo list of an interactive rebase
  6089. Returns:
  6090. List of new commit SHAs created by rebase
  6091. Raises:
  6092. Error: If rebase fails or conflicts occur
  6093. """
  6094. # TODO: Avoid importing from .cli
  6095. from .cli import launch_editor
  6096. from .rebase import (
  6097. RebaseConflict,
  6098. RebaseError,
  6099. Rebaser,
  6100. process_interactive_rebase,
  6101. start_interactive,
  6102. )
  6103. from .rebase import (
  6104. edit_todo as edit_todo_func,
  6105. )
  6106. with open_repo_closing(repo) as r:
  6107. rebaser = Rebaser(r)
  6108. if abort:
  6109. try:
  6110. rebaser.abort()
  6111. return []
  6112. except RebaseError as e:
  6113. raise Error(str(e))
  6114. if edit_todo:
  6115. # Edit the todo list of an interactive rebase
  6116. try:
  6117. edit_todo_func(r, launch_editor)
  6118. print("Todo list updated. Continue with 'rebase --continue'")
  6119. return []
  6120. except RebaseError as e:
  6121. raise Error(str(e))
  6122. if continue_rebase:
  6123. try:
  6124. if interactive:
  6125. # Continue interactive rebase
  6126. is_complete, pause_reason = process_interactive_rebase(
  6127. r, editor_callback=launch_editor
  6128. )
  6129. if is_complete:
  6130. return [c.id for c in rebaser._done]
  6131. else:
  6132. if pause_reason == "conflict":
  6133. raise Error("Conflicts detected. Resolve and continue.")
  6134. elif pause_reason == "edit":
  6135. print("Stopped for editing. Make changes and continue.")
  6136. elif pause_reason == "break":
  6137. print("Rebase paused at break. Continue when ready.")
  6138. else:
  6139. print(f"Rebase paused: {pause_reason}")
  6140. return []
  6141. else:
  6142. # Continue regular rebase
  6143. result = rebaser.continue_()
  6144. if result is None:
  6145. # Rebase complete
  6146. return [c.id for c in rebaser._done]
  6147. elif isinstance(result, tuple) and result[1]:
  6148. # Still have conflicts
  6149. raise Error(
  6150. f"Conflicts in: {', '.join(f.decode('utf-8', 'replace') for f in result[1])}"
  6151. )
  6152. except RebaseError as e:
  6153. raise Error(str(e))
  6154. # Convert string refs to bytes
  6155. if isinstance(upstream, str):
  6156. upstream = upstream.encode("utf-8")
  6157. if isinstance(onto, str):
  6158. onto = onto.encode("utf-8") if onto else None
  6159. if isinstance(branch, str):
  6160. branch = branch.encode("utf-8") if branch else None
  6161. try:
  6162. if interactive:
  6163. # Start interactive rebase
  6164. todo = start_interactive(r, upstream, onto, branch, launch_editor)
  6165. # Process the todo list
  6166. is_complete, pause_reason = process_interactive_rebase(
  6167. r, todo, editor_callback=launch_editor
  6168. )
  6169. if is_complete:
  6170. return [c.id for c in rebaser._done]
  6171. else:
  6172. if pause_reason == "conflict":
  6173. raise Error("Conflicts detected. Resolve and continue.")
  6174. elif pause_reason == "edit":
  6175. print("Stopped for editing. Make changes and continue.")
  6176. elif pause_reason == "break":
  6177. print("Rebase paused at break. Continue when ready.")
  6178. else:
  6179. print(f"Rebase paused: {pause_reason}")
  6180. return []
  6181. else:
  6182. # Regular rebase
  6183. rebaser.start(upstream, onto, branch)
  6184. # Continue rebase automatically
  6185. result = rebaser.continue_()
  6186. if result is not None:
  6187. # Conflicts
  6188. raise RebaseConflict(result[1])
  6189. # Return the SHAs of the rebased commits
  6190. return [c.id for c in rebaser._done]
  6191. except RebaseConflict as e:
  6192. raise Error(str(e))
  6193. except RebaseError as e:
  6194. raise Error(str(e))
  6195. def annotate(
  6196. repo: RepoPath,
  6197. path: str | bytes,
  6198. committish: str | bytes | Commit | Tag | None = None,
  6199. ) -> list[tuple[tuple[Commit, TreeEntry], bytes]]:
  6200. """Annotate the history of a file.
  6201. :param repo: Path to the repository
  6202. :param path: Path to annotate
  6203. :param committish: Commit id to find path in
  6204. :return: List of ((Commit, TreeChange), line) tuples
  6205. """
  6206. if committish is None:
  6207. committish = "HEAD"
  6208. from .annotate import annotate_lines
  6209. with open_repo_closing(repo) as r:
  6210. commit_id = parse_commit(r, committish).id
  6211. # Ensure path is bytes
  6212. if isinstance(path, str):
  6213. path = path.encode()
  6214. return annotate_lines(r.object_store, commit_id, path)
  6215. blame = annotate
  6216. def filter_branch(
  6217. repo: RepoPath = ".",
  6218. branch: str | bytes = "HEAD",
  6219. *,
  6220. filter_fn: Callable[[Commit], "CommitData | None"] | None = None,
  6221. filter_author: Callable[[bytes], bytes | None] | None = None,
  6222. filter_committer: Callable[[bytes], bytes | None] | None = None,
  6223. filter_message: Callable[[bytes], bytes | None] | None = None,
  6224. tree_filter: Callable[[bytes, str], bytes | None] | None = None,
  6225. index_filter: Callable[[bytes, str], bytes | None] | None = None,
  6226. parent_filter: Callable[[Sequence[bytes]], list[bytes]] | None = None,
  6227. commit_filter: Callable[[Commit, bytes], bytes | None] | None = None,
  6228. subdirectory_filter: str | bytes | None = None,
  6229. prune_empty: bool = False,
  6230. tag_name_filter: Callable[[bytes], bytes | None] | None = None,
  6231. force: bool = False,
  6232. keep_original: bool = True,
  6233. refs: list[bytes] | None = None,
  6234. ) -> dict[bytes, bytes]:
  6235. """Rewrite branch history by creating new commits with filtered properties.
  6236. This is similar to git filter-branch, allowing you to rewrite commit
  6237. history by modifying trees, parents, author, committer, or commit messages.
  6238. Args:
  6239. repo: Path to repository
  6240. branch: Branch to rewrite (defaults to HEAD)
  6241. filter_fn: Optional callable that takes a Commit object and returns
  6242. a dict of updated fields (author, committer, message, etc.)
  6243. filter_author: Optional callable that takes author bytes and returns
  6244. updated author bytes or None to keep unchanged
  6245. filter_committer: Optional callable that takes committer bytes and returns
  6246. updated committer bytes or None to keep unchanged
  6247. filter_message: Optional callable that takes commit message bytes
  6248. and returns updated message bytes
  6249. tree_filter: Optional callable that takes (tree_sha, temp_dir) and returns
  6250. new tree SHA after modifying working directory
  6251. index_filter: Optional callable that takes (tree_sha, temp_index_path) and
  6252. returns new tree SHA after modifying index
  6253. parent_filter: Optional callable that takes parent list and returns
  6254. modified parent list
  6255. commit_filter: Optional callable that takes (Commit, tree_sha) and returns
  6256. new commit SHA or None to skip commit
  6257. subdirectory_filter: Optional subdirectory path to extract as new root
  6258. prune_empty: Whether to prune commits that become empty
  6259. tag_name_filter: Optional callable to rename tags
  6260. force: Force operation even if branch has been filtered before
  6261. keep_original: Keep original refs under refs/original/
  6262. refs: List of refs to rewrite (defaults to [branch])
  6263. Returns:
  6264. Dict mapping old commit SHAs to new commit SHAs
  6265. Raises:
  6266. Error: If branch is already filtered and force is False
  6267. """
  6268. from .filter_branch import CommitFilter, filter_refs
  6269. with open_repo_closing(repo) as r:
  6270. # Parse branch/committish
  6271. if isinstance(branch, str):
  6272. branch = branch.encode()
  6273. # Determine which refs to process
  6274. if refs is None:
  6275. if branch == b"HEAD":
  6276. # Resolve HEAD to actual branch
  6277. try:
  6278. resolved = r.refs.follow(b"HEAD")
  6279. if resolved and resolved[0]:
  6280. # resolved is a list of (refname, sha) tuples
  6281. resolved_ref = resolved[0][-1]
  6282. if resolved_ref and resolved_ref != b"HEAD":
  6283. refs = [resolved_ref]
  6284. else:
  6285. # HEAD points directly to a commit
  6286. refs = [b"HEAD"]
  6287. else:
  6288. refs = [b"HEAD"]
  6289. except SymrefLoop:
  6290. refs = [b"HEAD"]
  6291. else:
  6292. # Convert branch name to full ref if needed
  6293. if not branch.startswith(b"refs/"):
  6294. branch = local_branch_name(branch)
  6295. refs = [branch]
  6296. # Convert subdirectory filter to bytes if needed
  6297. if subdirectory_filter:
  6298. if isinstance(subdirectory_filter, str):
  6299. subdirectory_filter = subdirectory_filter.encode()
  6300. else:
  6301. subdirectory_filter = None
  6302. # Create commit filter
  6303. filter_obj = CommitFilter(
  6304. r.object_store,
  6305. filter_fn=filter_fn,
  6306. filter_author=filter_author,
  6307. filter_committer=filter_committer,
  6308. filter_message=filter_message,
  6309. tree_filter=tree_filter,
  6310. index_filter=index_filter,
  6311. parent_filter=parent_filter,
  6312. commit_filter=commit_filter,
  6313. subdirectory_filter=subdirectory_filter,
  6314. prune_empty=prune_empty,
  6315. tag_name_filter=tag_name_filter,
  6316. )
  6317. # Tag callback for renaming tags
  6318. def rename_tag(old_ref: bytes, new_ref: bytes) -> None:
  6319. # Copy tag to new name
  6320. r.refs[new_ref] = r.refs[old_ref]
  6321. # Delete old tag
  6322. del r.refs[old_ref]
  6323. # Filter refs
  6324. try:
  6325. return filter_refs(
  6326. r.refs,
  6327. r.object_store,
  6328. refs,
  6329. filter_obj,
  6330. keep_original=keep_original,
  6331. force=force,
  6332. tag_callback=rename_tag if tag_name_filter else None,
  6333. )
  6334. except ValueError as e:
  6335. raise Error(str(e)) from e
  6336. def format_patch(
  6337. repo: RepoPath = ".",
  6338. committish: bytes | tuple[bytes, bytes] | None = None,
  6339. outstream: TextIO = sys.stdout,
  6340. outdir: str | os.PathLike[str] | None = None,
  6341. n: int = 1,
  6342. stdout: bool = False,
  6343. version: str | None = None,
  6344. ) -> list[str]:
  6345. """Generate patches suitable for git am.
  6346. Args:
  6347. repo: Path to repository
  6348. committish: Commit-ish or commit range to generate patches for.
  6349. Can be a single commit id, or a tuple of (start, end) commit ids
  6350. for a range. If None, formats the last n commits from HEAD.
  6351. outstream: Stream to write to if stdout=True
  6352. outdir: Directory to write patch files to (default: current directory)
  6353. n: Number of patches to generate if committish is None
  6354. stdout: Write patches to stdout instead of files
  6355. version: Version string to include in patches (default: Dulwich version)
  6356. Returns:
  6357. List of patch filenames that were created (empty if stdout=True)
  6358. """
  6359. if outdir is None:
  6360. outdir = "."
  6361. filenames = []
  6362. with open_repo_closing(repo) as r:
  6363. # Determine which commits to format
  6364. commits_to_format = []
  6365. if committish is None:
  6366. # Get the last n commits from HEAD
  6367. try:
  6368. walker = r.get_walker()
  6369. for entry in walker:
  6370. commits_to_format.append(entry.commit)
  6371. if len(commits_to_format) >= n:
  6372. break
  6373. commits_to_format.reverse()
  6374. except KeyError:
  6375. # No HEAD or empty repository
  6376. pass
  6377. elif isinstance(committish, tuple):
  6378. # Handle commit range (start, end)
  6379. start_commit, end_commit = committish
  6380. # Extract commit IDs from commit objects if needed
  6381. start_id = (
  6382. start_commit.id if isinstance(start_commit, Commit) else start_commit
  6383. )
  6384. end_id = end_commit.id if isinstance(end_commit, Commit) else end_commit
  6385. # Walk from end back to start
  6386. walker = r.get_walker(include=[end_id], exclude=[start_id])
  6387. for entry in walker:
  6388. commits_to_format.append(entry.commit)
  6389. commits_to_format.reverse()
  6390. else:
  6391. # Single commit
  6392. commit = r.object_store[committish]
  6393. assert isinstance(commit, Commit)
  6394. commits_to_format.append(commit)
  6395. # Generate patches
  6396. total = len(commits_to_format)
  6397. for i, commit in enumerate(commits_to_format, 1):
  6398. assert isinstance(commit, Commit)
  6399. # Get the parent
  6400. if commit.parents:
  6401. parent_id = commit.parents[0]
  6402. parent = r.object_store[parent_id]
  6403. assert isinstance(parent, Commit)
  6404. else:
  6405. parent = None
  6406. # Generate the diff
  6407. from io import BytesIO
  6408. diff_content = BytesIO()
  6409. if parent:
  6410. write_tree_diff(
  6411. diff_content,
  6412. r.object_store,
  6413. parent.tree,
  6414. commit.tree,
  6415. )
  6416. else:
  6417. # Initial commit - diff against empty tree
  6418. write_tree_diff(
  6419. diff_content,
  6420. r.object_store,
  6421. None,
  6422. commit.tree,
  6423. )
  6424. # Generate patch with commit metadata
  6425. if stdout:
  6426. # Get binary stream from TextIO
  6427. if hasattr(outstream, "buffer"):
  6428. binary_out: IO[bytes] = outstream.buffer
  6429. else:
  6430. # Fallback for non-text streams
  6431. binary_out = outstream # type: ignore[assignment]
  6432. write_commit_patch(
  6433. binary_out,
  6434. commit,
  6435. diff_content.getvalue(),
  6436. (i, total),
  6437. version=version,
  6438. )
  6439. else:
  6440. # Generate filename
  6441. summary = get_summary(commit)
  6442. filename = os.path.join(outdir, f"{i:04d}-{summary}.patch")
  6443. with open(filename, "wb") as f:
  6444. write_commit_patch(
  6445. f,
  6446. commit,
  6447. diff_content.getvalue(),
  6448. (i, total),
  6449. version=version,
  6450. )
  6451. filenames.append(filename)
  6452. return filenames
  6453. def bisect_start(
  6454. repo: str | os.PathLike[str] | Repo = ".",
  6455. bad: str | bytes | Commit | Tag | None = None,
  6456. good: str
  6457. | bytes
  6458. | Commit
  6459. | Tag
  6460. | Sequence[str | bytes | Commit | Tag]
  6461. | None = None,
  6462. paths: Sequence[bytes] | None = None,
  6463. no_checkout: bool = False,
  6464. term_bad: str = "bad",
  6465. term_good: str = "good",
  6466. ) -> bytes | None:
  6467. """Start a new bisect session.
  6468. Args:
  6469. repo: Path to repository or a Repo object
  6470. bad: The bad commit (defaults to HEAD)
  6471. good: List of good commits or a single good commit
  6472. paths: Optional paths to limit bisect to
  6473. no_checkout: If True, don't checkout commits during bisect
  6474. term_bad: Term to use for bad commits (default: "bad")
  6475. term_good: Term to use for good commits (default: "good")
  6476. """
  6477. with open_repo_closing(repo) as r:
  6478. state = BisectState(r)
  6479. # Convert single good commit to sequence
  6480. if good is not None and isinstance(good, (str, bytes, Commit, Tag)):
  6481. good = [good]
  6482. # Parse commits
  6483. bad_sha = parse_commit(r, bad).id if bad else None
  6484. good_shas = [parse_commit(r, g).id for g in good] if good else None
  6485. state.start(bad_sha, good_shas, paths, no_checkout, term_bad, term_good)
  6486. # Return the next commit to test if we have both good and bad
  6487. if bad_sha and good_shas:
  6488. next_sha = state._find_next_commit()
  6489. if next_sha and not no_checkout:
  6490. # Checkout the next commit
  6491. old_commit = r[r.head()]
  6492. assert isinstance(old_commit, Commit)
  6493. old_tree = old_commit.tree if r.head() else None
  6494. r.refs[b"HEAD"] = next_sha
  6495. commit = r[next_sha]
  6496. assert isinstance(commit, Commit)
  6497. changes = tree_changes(r.object_store, old_tree, commit.tree)
  6498. update_working_tree(r, old_tree, commit.tree, change_iterator=changes)
  6499. return next_sha
  6500. return None
  6501. def bisect_bad(
  6502. repo: str | os.PathLike[str] | Repo = ".",
  6503. rev: str | bytes | Commit | Tag | None = None,
  6504. ) -> bytes | None:
  6505. """Mark a commit as bad.
  6506. Args:
  6507. repo: Path to repository or a Repo object
  6508. rev: Commit to mark as bad (defaults to HEAD)
  6509. Returns:
  6510. The SHA of the next commit to test, or None if bisect is complete
  6511. """
  6512. with open_repo_closing(repo) as r:
  6513. state = BisectState(r)
  6514. rev_sha = parse_commit(r, rev).id if rev else None
  6515. next_sha = state.mark_bad(rev_sha)
  6516. if next_sha:
  6517. # Checkout the next commit
  6518. old_commit = r[r.head()]
  6519. assert isinstance(old_commit, Commit)
  6520. old_tree = old_commit.tree if r.head() else None
  6521. r.refs[b"HEAD"] = next_sha
  6522. commit = r[next_sha]
  6523. assert isinstance(commit, Commit)
  6524. changes = tree_changes(r.object_store, old_tree, commit.tree)
  6525. update_working_tree(r, old_tree, commit.tree, change_iterator=changes)
  6526. return next_sha
  6527. def bisect_good(
  6528. repo: str | os.PathLike[str] | Repo = ".",
  6529. rev: str | bytes | Commit | Tag | None = None,
  6530. ) -> bytes | None:
  6531. """Mark a commit as good.
  6532. Args:
  6533. repo: Path to repository or a Repo object
  6534. rev: Commit to mark as good (defaults to HEAD)
  6535. Returns:
  6536. The SHA of the next commit to test, or None if bisect is complete
  6537. """
  6538. with open_repo_closing(repo) as r:
  6539. state = BisectState(r)
  6540. rev_sha = parse_commit(r, rev).id if rev else None
  6541. next_sha = state.mark_good(rev_sha)
  6542. if next_sha:
  6543. # Checkout the next commit
  6544. old_commit = r[r.head()]
  6545. assert isinstance(old_commit, Commit)
  6546. old_tree = old_commit.tree if r.head() else None
  6547. r.refs[b"HEAD"] = next_sha
  6548. commit = r[next_sha]
  6549. assert isinstance(commit, Commit)
  6550. changes = tree_changes(r.object_store, old_tree, commit.tree)
  6551. update_working_tree(r, old_tree, commit.tree, change_iterator=changes)
  6552. return next_sha
  6553. def bisect_skip(
  6554. repo: str | os.PathLike[str] | Repo = ".",
  6555. revs: str
  6556. | bytes
  6557. | Commit
  6558. | Tag
  6559. | Sequence[str | bytes | Commit | Tag]
  6560. | None = None,
  6561. ) -> bytes | None:
  6562. """Skip one or more commits.
  6563. Args:
  6564. repo: Path to repository or a Repo object
  6565. revs: List of commits to skip (defaults to [HEAD])
  6566. Returns:
  6567. The SHA of the next commit to test, or None if bisect is complete
  6568. """
  6569. with open_repo_closing(repo) as r:
  6570. state = BisectState(r)
  6571. if revs is None:
  6572. rev_shas = None
  6573. else:
  6574. # Convert single rev to sequence
  6575. if isinstance(revs, (str, bytes, Commit, Tag)):
  6576. revs = [revs]
  6577. rev_shas = [parse_commit(r, rev).id for rev in revs]
  6578. next_sha = state.skip(rev_shas)
  6579. if next_sha:
  6580. # Checkout the next commit
  6581. old_commit = r[r.head()]
  6582. assert isinstance(old_commit, Commit)
  6583. old_tree = old_commit.tree if r.head() else None
  6584. r.refs[b"HEAD"] = next_sha
  6585. commit = r[next_sha]
  6586. assert isinstance(commit, Commit)
  6587. changes = tree_changes(r.object_store, old_tree, commit.tree)
  6588. update_working_tree(r, old_tree, commit.tree, change_iterator=changes)
  6589. return next_sha
  6590. def bisect_reset(
  6591. repo: str | os.PathLike[str] | Repo = ".",
  6592. commit: str | bytes | Commit | Tag | None = None,
  6593. ) -> None:
  6594. """Reset bisect state and return to original branch/commit.
  6595. Args:
  6596. repo: Path to repository or a Repo object
  6597. commit: Optional commit to reset to (defaults to original branch/commit)
  6598. """
  6599. with open_repo_closing(repo) as r:
  6600. state = BisectState(r)
  6601. # Get old tree before reset
  6602. try:
  6603. old_commit = r[r.head()]
  6604. assert isinstance(old_commit, Commit)
  6605. old_tree = old_commit.tree
  6606. except KeyError:
  6607. old_tree = None
  6608. commit_sha = parse_commit(r, commit).id if commit else None
  6609. state.reset(commit_sha)
  6610. # Update working tree to new HEAD
  6611. try:
  6612. new_head = r.head()
  6613. if new_head:
  6614. new_commit = r[new_head]
  6615. assert isinstance(new_commit, Commit)
  6616. changes = tree_changes(r.object_store, old_tree, new_commit.tree)
  6617. update_working_tree(
  6618. r, old_tree, new_commit.tree, change_iterator=changes
  6619. )
  6620. except KeyError:
  6621. # No HEAD after reset
  6622. pass
  6623. def bisect_log(repo: str | os.PathLike[str] | Repo = ".") -> str:
  6624. """Get the bisect log.
  6625. Args:
  6626. repo: Path to repository or a Repo object
  6627. Returns:
  6628. The bisect log as a string
  6629. """
  6630. with open_repo_closing(repo) as r:
  6631. state = BisectState(r)
  6632. return state.get_log()
  6633. def bisect_replay(
  6634. repo: str | os.PathLike[str] | Repo,
  6635. log_file: str | os.PathLike[str] | BinaryIO,
  6636. ) -> None:
  6637. """Replay a bisect log.
  6638. Args:
  6639. repo: Path to repository or a Repo object
  6640. log_file: Path to the log file or file-like object
  6641. """
  6642. with open_repo_closing(repo) as r:
  6643. state = BisectState(r)
  6644. if isinstance(log_file, (str, os.PathLike)):
  6645. with open(log_file) as f:
  6646. log_content = f.read()
  6647. else:
  6648. content = log_file.read()
  6649. log_content = content.decode() if isinstance(content, bytes) else content
  6650. state.replay(log_content)
  6651. def reflog(
  6652. repo: RepoPath = ".", ref: str | bytes = b"HEAD", all: bool = False
  6653. ) -> Iterator[Any | tuple[bytes, Any]]:
  6654. """Show reflog entries for a reference or all references.
  6655. Args:
  6656. repo: Path to repository or a Repo object
  6657. ref: Reference name (defaults to HEAD)
  6658. all: If True, show reflogs for all refs (ignores ref parameter)
  6659. Yields:
  6660. If all=False: ReflogEntry objects
  6661. If all=True: Tuples of (ref_name, ReflogEntry) for all refs with reflogs
  6662. """
  6663. import os
  6664. from .reflog import iter_reflogs
  6665. if isinstance(ref, str):
  6666. ref = ref.encode("utf-8")
  6667. with open_repo_closing(repo) as r:
  6668. if not all:
  6669. yield from r.read_reflog(ref)
  6670. else:
  6671. logs_dir = os.path.join(r.controldir(), "logs")
  6672. # Use iter_reflogs to discover all reflogs
  6673. for ref_bytes in iter_reflogs(logs_dir):
  6674. # Read the reflog entries for this ref
  6675. for entry in r.read_reflog(ref_bytes):
  6676. yield (ref_bytes, entry)
  6677. def reflog_expire(
  6678. repo: RepoPath = ".",
  6679. ref: str | bytes | None = None,
  6680. all: bool = False,
  6681. expire_time: int | None = None,
  6682. expire_unreachable_time: int | None = None,
  6683. dry_run: bool = False,
  6684. ) -> dict[bytes, int]:
  6685. """Expire reflog entries based on age and reachability.
  6686. Args:
  6687. repo: Path to repository or a Repo object
  6688. ref: Reference name (if not using --all)
  6689. all: If True, expire reflogs for all refs
  6690. expire_time: Expire entries older than this timestamp (seconds since epoch)
  6691. expire_unreachable_time: Expire unreachable entries older than this timestamp
  6692. dry_run: If True, show what would be expired without making changes
  6693. Returns:
  6694. Dictionary mapping ref names to number of expired entries
  6695. """
  6696. import os
  6697. import time
  6698. from .reflog import expire_reflog, iter_reflogs
  6699. if not all and ref is None:
  6700. raise ValueError("Must specify either ref or all=True")
  6701. if isinstance(ref, str):
  6702. ref = ref.encode("utf-8")
  6703. # Default expire times if not specified
  6704. if expire_time is None and expire_unreachable_time is None:
  6705. # Default: expire entries older than 90 days, unreachable older than 30 days
  6706. now = int(time.time())
  6707. expire_time = now - (90 * 24 * 60 * 60)
  6708. expire_unreachable_time = now - (30 * 24 * 60 * 60)
  6709. result = {}
  6710. with open_repo_closing(repo) as r:
  6711. # Determine which refs to process
  6712. refs_to_process: list[bytes] = []
  6713. if all:
  6714. logs_dir = os.path.join(r.controldir(), "logs")
  6715. refs_to_process = list(iter_reflogs(logs_dir))
  6716. else:
  6717. assert ref is not None # Already checked above
  6718. refs_to_process = [ref]
  6719. # Build set of reachable objects if we have unreachable expiration time
  6720. reachable_objects: set[bytes] | None = None
  6721. if expire_unreachable_time is not None:
  6722. from .gc import find_reachable_objects
  6723. reachable_objects = find_reachable_objects(
  6724. r.object_store, r.refs, include_reflogs=False
  6725. )
  6726. # Process each ref
  6727. for ref_name in refs_to_process:
  6728. reflog_path = r._reflog_path(ref_name)
  6729. if not os.path.exists(reflog_path):
  6730. continue
  6731. # Create reachability checker
  6732. def is_reachable(sha: bytes) -> bool:
  6733. if reachable_objects is None:
  6734. # No unreachable expiration, so assume everything is reachable
  6735. return True
  6736. return sha in reachable_objects
  6737. # Open the reflog file
  6738. if dry_run:
  6739. # For dry run, just read and count what would be expired
  6740. with open(reflog_path, "rb") as f:
  6741. from .reflog import read_reflog
  6742. count = 0
  6743. for entry in read_reflog(f):
  6744. is_obj_reachable = is_reachable(entry.new_sha)
  6745. should_expire = False
  6746. if is_obj_reachable and expire_time is not None:
  6747. if entry.timestamp < expire_time:
  6748. should_expire = True
  6749. elif (
  6750. not is_obj_reachable and expire_unreachable_time is not None
  6751. ):
  6752. if entry.timestamp < expire_unreachable_time:
  6753. should_expire = True
  6754. if should_expire:
  6755. count += 1
  6756. result[ref_name] = count
  6757. else:
  6758. # Actually expire entries
  6759. with open(reflog_path, "r+b") as f: # type: ignore[assignment]
  6760. count = expire_reflog(
  6761. f,
  6762. expire_time=expire_time,
  6763. expire_unreachable_time=expire_unreachable_time,
  6764. reachable_checker=is_reachable,
  6765. )
  6766. result[ref_name] = count
  6767. return result
  6768. def reflog_delete(
  6769. repo: RepoPath = ".",
  6770. ref: str | bytes = b"HEAD",
  6771. index: int = 0,
  6772. rewrite: bool = False,
  6773. ) -> None:
  6774. """Delete a specific reflog entry.
  6775. Args:
  6776. repo: Path to repository or a Repo object
  6777. ref: Reference name
  6778. index: Reflog entry index (0 = newest, in Git reflog order)
  6779. rewrite: If True, rewrite old_sha of subsequent entries to maintain consistency
  6780. """
  6781. import os
  6782. from .reflog import drop_reflog_entry
  6783. if isinstance(ref, str):
  6784. ref = ref.encode("utf-8")
  6785. with open_repo_closing(repo) as r:
  6786. reflog_path = r._reflog_path(ref)
  6787. if not os.path.exists(reflog_path):
  6788. raise ValueError(f"No reflog for ref {ref.decode()}")
  6789. with open(reflog_path, "r+b") as f:
  6790. drop_reflog_entry(f, index, rewrite=rewrite)
  6791. def lfs_track(
  6792. repo: str | os.PathLike[str] | Repo = ".",
  6793. patterns: Sequence[str] | None = None,
  6794. ) -> list[str]:
  6795. """Track file patterns with Git LFS.
  6796. Args:
  6797. repo: Path to repository
  6798. patterns: List of file patterns to track (e.g., ["*.bin", "*.pdf"])
  6799. If None, returns current tracked patterns
  6800. Returns:
  6801. List of tracked patterns
  6802. """
  6803. from .attrs import GitAttributes
  6804. with open_repo_closing(repo) as r:
  6805. gitattributes_path = os.path.join(r.path, ".gitattributes")
  6806. # Load existing GitAttributes
  6807. if os.path.exists(gitattributes_path):
  6808. gitattributes = GitAttributes.from_file(gitattributes_path)
  6809. else:
  6810. gitattributes = GitAttributes()
  6811. if patterns is None:
  6812. # Return current LFS tracked patterns
  6813. tracked = []
  6814. for pattern_obj, attrs in gitattributes:
  6815. if attrs.get(b"filter") == b"lfs":
  6816. tracked.append(pattern_obj.pattern.decode())
  6817. return tracked
  6818. # Add new patterns
  6819. for pattern in patterns:
  6820. # Ensure pattern is bytes
  6821. pattern_bytes = pattern.encode() if isinstance(pattern, str) else pattern
  6822. # Set LFS attributes for the pattern
  6823. gitattributes.set_attribute(pattern_bytes, b"filter", b"lfs")
  6824. gitattributes.set_attribute(pattern_bytes, b"diff", b"lfs")
  6825. gitattributes.set_attribute(pattern_bytes, b"merge", b"lfs")
  6826. gitattributes.set_attribute(pattern_bytes, b"text", False)
  6827. # Write updated attributes
  6828. gitattributes.write_to_file(gitattributes_path)
  6829. # Stage the .gitattributes file
  6830. add(r, [".gitattributes"])
  6831. return lfs_track(r) # Return updated list
  6832. def lfs_untrack(
  6833. repo: str | os.PathLike[str] | Repo = ".",
  6834. patterns: Sequence[str] | None = None,
  6835. ) -> list[str]:
  6836. """Untrack file patterns from Git LFS.
  6837. Args:
  6838. repo: Path to repository
  6839. patterns: List of file patterns to untrack
  6840. Returns:
  6841. List of remaining tracked patterns
  6842. """
  6843. from .attrs import GitAttributes
  6844. if not patterns:
  6845. return lfs_track(repo)
  6846. with open_repo_closing(repo) as r:
  6847. gitattributes_path = os.path.join(r.path, ".gitattributes")
  6848. if not os.path.exists(gitattributes_path):
  6849. return []
  6850. # Load existing GitAttributes
  6851. gitattributes = GitAttributes.from_file(gitattributes_path)
  6852. # Remove specified patterns
  6853. for pattern in patterns:
  6854. pattern_bytes = pattern.encode() if isinstance(pattern, str) else pattern
  6855. # Check if pattern is tracked by LFS
  6856. for pattern_obj, attrs in list(gitattributes):
  6857. if (
  6858. pattern_obj.pattern == pattern_bytes
  6859. and attrs.get(b"filter") == b"lfs"
  6860. ):
  6861. gitattributes.remove_pattern(pattern_bytes)
  6862. break
  6863. # Write updated attributes
  6864. gitattributes.write_to_file(gitattributes_path)
  6865. # Stage the .gitattributes file
  6866. add(r, [".gitattributes"])
  6867. return lfs_track(r) # Return updated list
  6868. def lfs_init(repo: str | os.PathLike[str] | Repo = ".") -> None:
  6869. """Initialize Git LFS in a repository.
  6870. Args:
  6871. repo: Path to repository
  6872. Returns:
  6873. None
  6874. """
  6875. from .lfs import LFSStore
  6876. with open_repo_closing(repo) as r:
  6877. # Create LFS store
  6878. LFSStore.from_repo(r, create=True)
  6879. # Set up Git config for LFS
  6880. config = r.get_config()
  6881. config.set((b"filter", b"lfs"), b"process", b"git-lfs filter-process")
  6882. config.set((b"filter", b"lfs"), b"required", b"true")
  6883. config.set((b"filter", b"lfs"), b"clean", b"git-lfs clean -- %f")
  6884. config.set((b"filter", b"lfs"), b"smudge", b"git-lfs smudge -- %f")
  6885. config.write_to_path()
  6886. def lfs_clean(
  6887. repo: str | os.PathLike[str] | Repo = ".",
  6888. path: str | os.PathLike[str] | None = None,
  6889. ) -> bytes:
  6890. """Clean a file by converting it to an LFS pointer.
  6891. Args:
  6892. repo: Path to repository
  6893. path: Path to file to clean (relative to repo root)
  6894. Returns:
  6895. LFS pointer content as bytes
  6896. """
  6897. from .lfs import LFSFilterDriver, LFSStore
  6898. with open_repo_closing(repo) as r:
  6899. if path is None:
  6900. raise ValueError("Path must be specified")
  6901. # Get LFS store
  6902. lfs_store = LFSStore.from_repo(r)
  6903. filter_driver = LFSFilterDriver(lfs_store, config=r.get_config())
  6904. # Read file content
  6905. full_path = os.path.join(r.path, path)
  6906. with open(full_path, "rb") as f:
  6907. content = f.read()
  6908. # Clean the content (convert to LFS pointer)
  6909. return filter_driver.clean(content)
  6910. def lfs_smudge(
  6911. repo: str | os.PathLike[str] | Repo = ".",
  6912. pointer_content: bytes | None = None,
  6913. ) -> bytes:
  6914. """Smudge an LFS pointer by retrieving the actual content.
  6915. Args:
  6916. repo: Path to repository
  6917. pointer_content: LFS pointer content as bytes
  6918. Returns:
  6919. Actual file content as bytes
  6920. """
  6921. from .lfs import LFSFilterDriver, LFSStore
  6922. with open_repo_closing(repo) as r:
  6923. if pointer_content is None:
  6924. raise ValueError("Pointer content must be specified")
  6925. # Get LFS store
  6926. lfs_store = LFSStore.from_repo(r)
  6927. filter_driver = LFSFilterDriver(lfs_store, config=r.get_config())
  6928. # Smudge the pointer (retrieve actual content)
  6929. return filter_driver.smudge(pointer_content)
  6930. def lfs_ls_files(
  6931. repo: str | os.PathLike[str] | Repo = ".",
  6932. ref: str | bytes | None = None,
  6933. ) -> list[tuple[bytes, str, int]]:
  6934. """List files tracked by Git LFS.
  6935. Args:
  6936. repo: Path to repository
  6937. ref: Git ref to check (defaults to HEAD)
  6938. Returns:
  6939. List of (path, oid, size) tuples for LFS files
  6940. """
  6941. from .lfs import LFSPointer
  6942. from .object_store import iter_tree_contents
  6943. with open_repo_closing(repo) as r:
  6944. if ref is None:
  6945. ref = b"HEAD"
  6946. elif isinstance(ref, str):
  6947. ref = ref.encode()
  6948. # Get the commit and tree
  6949. try:
  6950. commit = r[ref]
  6951. assert isinstance(commit, Commit)
  6952. tree = r[commit.tree]
  6953. assert isinstance(tree, Tree)
  6954. except KeyError:
  6955. return []
  6956. lfs_files = []
  6957. # Walk the tree
  6958. for path, mode, sha in iter_tree_contents(r.object_store, tree.id):
  6959. assert path is not None
  6960. assert mode is not None
  6961. assert sha is not None
  6962. if not stat.S_ISREG(mode):
  6963. continue
  6964. # Check if it's an LFS pointer
  6965. obj = r.object_store[sha]
  6966. if not isinstance(obj, Blob):
  6967. raise AssertionError(f"Expected Blob object, got {type(obj).__name__}")
  6968. pointer = LFSPointer.from_bytes(obj.data)
  6969. if pointer is not None:
  6970. lfs_files.append((path, pointer.oid, pointer.size))
  6971. return lfs_files
  6972. def lfs_migrate(
  6973. repo: str | os.PathLike[str] | Repo = ".",
  6974. include: list[str] | None = None,
  6975. exclude: list[str] | None = None,
  6976. everything: bool = False,
  6977. ) -> int:
  6978. """Migrate files to Git LFS.
  6979. Args:
  6980. repo: Path to repository
  6981. include: Patterns of files to include
  6982. exclude: Patterns of files to exclude
  6983. everything: Migrate all files above a certain size
  6984. Returns:
  6985. Number of migrated files
  6986. """
  6987. from .lfs import LFSFilterDriver, LFSStore
  6988. with open_repo_closing(repo) as r:
  6989. # Initialize LFS if needed
  6990. lfs_store = LFSStore.from_repo(r, create=True)
  6991. filter_driver = LFSFilterDriver(lfs_store, config=r.get_config())
  6992. # Get current index
  6993. index = r.open_index()
  6994. migrated = 0
  6995. # Determine files to migrate
  6996. files_to_migrate = []
  6997. if everything:
  6998. # Migrate all files above 100MB
  6999. for path, entry in index.items():
  7000. full_path = os.path.join(r.path, path.decode())
  7001. if os.path.exists(full_path):
  7002. size = os.path.getsize(full_path)
  7003. if size > 100 * 1024 * 1024: # 100MB
  7004. files_to_migrate.append(path.decode())
  7005. else:
  7006. # Use include/exclude patterns
  7007. for path, entry in index.items():
  7008. path_str = path.decode()
  7009. # Check include patterns
  7010. if include:
  7011. matched = any(
  7012. fnmatch.fnmatch(path_str, pattern) for pattern in include
  7013. )
  7014. if not matched:
  7015. continue
  7016. # Check exclude patterns
  7017. if exclude:
  7018. excluded = any(
  7019. fnmatch.fnmatch(path_str, pattern) for pattern in exclude
  7020. )
  7021. if excluded:
  7022. continue
  7023. files_to_migrate.append(path_str)
  7024. # Migrate files
  7025. for path_str in files_to_migrate:
  7026. full_path = os.path.join(r.path, path_str)
  7027. if not os.path.exists(full_path):
  7028. continue
  7029. # Read file content
  7030. with open(full_path, "rb") as f:
  7031. content = f.read()
  7032. # Convert to LFS pointer
  7033. pointer_content = filter_driver.clean(content)
  7034. # Write pointer back to file
  7035. with open(full_path, "wb") as f:
  7036. f.write(pointer_content)
  7037. # Create blob for pointer content and update index
  7038. blob = Blob()
  7039. blob.data = pointer_content
  7040. r.object_store.add_object(blob)
  7041. st = os.stat(full_path)
  7042. index_entry = index_entry_from_stat(st, blob.id, 0)
  7043. path_bytes = path_str.encode() if isinstance(path_str, str) else path_str
  7044. index[path_bytes] = index_entry
  7045. migrated += 1
  7046. # Write updated index
  7047. index.write()
  7048. # Track patterns if include was specified
  7049. if include:
  7050. lfs_track(r, include)
  7051. return migrated
  7052. def lfs_pointer_check(
  7053. repo: str | os.PathLike[str] | Repo = ".",
  7054. paths: Sequence[str] | None = None,
  7055. ) -> dict[str, Any | None]:
  7056. """Check if files are valid LFS pointers.
  7057. Args:
  7058. repo: Path to repository
  7059. paths: List of file paths to check (if None, check all files)
  7060. Returns:
  7061. Dict mapping paths to LFSPointer objects (or None if not a pointer)
  7062. """
  7063. from .lfs import LFSPointer
  7064. with open_repo_closing(repo) as r:
  7065. results = {}
  7066. if paths is None:
  7067. # Check all files in index
  7068. index = r.open_index()
  7069. paths = [path.decode() for path in index]
  7070. for path in paths:
  7071. full_path = os.path.join(r.path, path)
  7072. if os.path.exists(full_path):
  7073. try:
  7074. with open(full_path, "rb") as f:
  7075. content = f.read()
  7076. pointer = LFSPointer.from_bytes(content)
  7077. results[path] = pointer
  7078. except OSError:
  7079. results[path] = None
  7080. else:
  7081. results[path] = None
  7082. return results
  7083. def lfs_fetch(
  7084. repo: str | os.PathLike[str] | Repo = ".",
  7085. remote: str = "origin",
  7086. refs: list[str | bytes] | None = None,
  7087. ) -> int:
  7088. """Fetch LFS objects from remote.
  7089. Args:
  7090. repo: Path to repository
  7091. remote: Remote name (default: origin)
  7092. refs: Specific refs to fetch LFS objects for (default: all refs)
  7093. Returns:
  7094. Number of objects fetched
  7095. """
  7096. from .lfs import LFSClient, LFSPointer, LFSStore
  7097. with open_repo_closing(repo) as r:
  7098. # Get LFS server URL from config
  7099. config = r.get_config()
  7100. lfs_url_bytes = config.get((b"lfs",), b"url")
  7101. if not lfs_url_bytes:
  7102. # Try remote URL
  7103. remote_url = config.get((b"remote", remote.encode()), b"url")
  7104. if remote_url:
  7105. # Append /info/lfs to remote URL
  7106. remote_url_str = remote_url.decode()
  7107. if remote_url_str.endswith(".git"):
  7108. remote_url_str = remote_url_str[:-4]
  7109. lfs_url = f"{remote_url_str}/info/lfs"
  7110. else:
  7111. raise ValueError(f"No LFS URL configured for remote {remote}")
  7112. else:
  7113. lfs_url = lfs_url_bytes.decode()
  7114. # Get authentication
  7115. auth = None
  7116. # TODO: Support credential helpers and other auth methods
  7117. # Create LFS client and store
  7118. client = LFSClient(lfs_url, auth)
  7119. store = LFSStore.from_repo(r)
  7120. # Find all LFS pointers in the refs
  7121. pointers_to_fetch = []
  7122. if refs is None:
  7123. # Get all refs
  7124. refs = list(r.refs.keys())
  7125. for ref in refs:
  7126. if isinstance(ref, str):
  7127. ref = ref.encode()
  7128. try:
  7129. commit = r[r.refs[ref]]
  7130. except KeyError:
  7131. continue
  7132. # Walk the commit tree
  7133. assert isinstance(commit, Commit)
  7134. for path, mode, sha in r.object_store.iter_tree_contents(commit.tree):
  7135. assert sha is not None
  7136. try:
  7137. obj = r.object_store[sha]
  7138. except KeyError:
  7139. pass
  7140. else:
  7141. if isinstance(obj, Blob):
  7142. pointer = LFSPointer.from_bytes(obj.data)
  7143. if pointer and pointer.is_valid_oid():
  7144. # Check if we already have it
  7145. try:
  7146. with store.open_object(pointer.oid):
  7147. pass # Object exists, no need to fetch
  7148. except KeyError:
  7149. pointers_to_fetch.append((pointer.oid, pointer.size))
  7150. # Fetch missing objects
  7151. fetched = 0
  7152. for oid, size in pointers_to_fetch:
  7153. content = client.download(oid, size)
  7154. store.write_object([content])
  7155. fetched += 1
  7156. return fetched
  7157. def lfs_pull(repo: str | os.PathLike[str] | Repo = ".", remote: str = "origin") -> int:
  7158. """Pull LFS objects for current checkout.
  7159. Args:
  7160. repo: Path to repository
  7161. remote: Remote name (default: origin)
  7162. Returns:
  7163. Number of objects fetched
  7164. """
  7165. from .lfs import LFSPointer, LFSStore
  7166. with open_repo_closing(repo) as r:
  7167. # First do a fetch for HEAD
  7168. fetched = lfs_fetch(repo, remote, [b"HEAD"])
  7169. # Then checkout LFS files in working directory
  7170. store = LFSStore.from_repo(r)
  7171. index = r.open_index()
  7172. for path, entry in index.items():
  7173. full_path = os.path.join(r.path, path.decode())
  7174. if os.path.exists(full_path):
  7175. with open(full_path, "rb") as f:
  7176. content = f.read()
  7177. pointer = LFSPointer.from_bytes(content)
  7178. if pointer and pointer.is_valid_oid():
  7179. try:
  7180. # Replace pointer with actual content
  7181. with store.open_object(pointer.oid) as lfs_file:
  7182. lfs_content = lfs_file.read()
  7183. with open(full_path, "wb") as f:
  7184. f.write(lfs_content)
  7185. except KeyError:
  7186. # Object not available
  7187. pass
  7188. return fetched
  7189. def lfs_push(
  7190. repo: str | os.PathLike[str] | Repo = ".",
  7191. remote: str = "origin",
  7192. refs: list[str | bytes] | None = None,
  7193. ) -> int:
  7194. """Push LFS objects to remote.
  7195. Args:
  7196. repo: Path to repository
  7197. remote: Remote name (default: origin)
  7198. refs: Specific refs to push LFS objects for (default: current branch)
  7199. Returns:
  7200. Number of objects pushed
  7201. """
  7202. from .lfs import LFSClient, LFSPointer, LFSStore
  7203. with open_repo_closing(repo) as r:
  7204. # Get LFS server URL from config
  7205. config = r.get_config()
  7206. lfs_url_bytes = config.get((b"lfs",), b"url")
  7207. if not lfs_url_bytes:
  7208. # Try remote URL
  7209. remote_url = config.get((b"remote", remote.encode()), b"url")
  7210. if remote_url:
  7211. # Append /info/lfs to remote URL
  7212. remote_url_str = remote_url.decode()
  7213. if remote_url_str.endswith(".git"):
  7214. remote_url_str = remote_url_str[:-4]
  7215. lfs_url = f"{remote_url_str}/info/lfs"
  7216. else:
  7217. raise ValueError(f"No LFS URL configured for remote {remote}")
  7218. else:
  7219. lfs_url = lfs_url_bytes.decode()
  7220. # Get authentication
  7221. auth = None
  7222. # TODO: Support credential helpers and other auth methods
  7223. # Create LFS client and store
  7224. client = LFSClient(lfs_url, auth)
  7225. store = LFSStore.from_repo(r)
  7226. # Find all LFS objects to push
  7227. if refs is None:
  7228. # Push current branch
  7229. head_ref = r.refs.read_ref(b"HEAD")
  7230. refs = [head_ref] if head_ref else []
  7231. objects_to_push = set()
  7232. for ref in refs:
  7233. if isinstance(ref, str):
  7234. ref = ref.encode()
  7235. try:
  7236. if ref.startswith(b"refs/"):
  7237. commit = r[r.refs[ref]]
  7238. else:
  7239. commit = r[ref]
  7240. except KeyError:
  7241. continue
  7242. # Walk the commit tree
  7243. assert isinstance(commit, Commit)
  7244. for path, mode, sha in r.object_store.iter_tree_contents(commit.tree):
  7245. assert sha is not None
  7246. try:
  7247. obj = r.object_store[sha]
  7248. except KeyError:
  7249. pass
  7250. else:
  7251. if isinstance(obj, Blob):
  7252. pointer = LFSPointer.from_bytes(obj.data)
  7253. if pointer and pointer.is_valid_oid():
  7254. objects_to_push.add((pointer.oid, pointer.size))
  7255. # Push objects
  7256. pushed = 0
  7257. for oid, size in objects_to_push:
  7258. try:
  7259. with store.open_object(oid) as f:
  7260. content = f.read()
  7261. except KeyError:
  7262. # Object not in local store
  7263. logging.warn("LFS object %s not found locally", oid)
  7264. else:
  7265. client.upload(oid, size, content)
  7266. pushed += 1
  7267. return pushed
  7268. def lfs_status(repo: str | os.PathLike[str] | Repo = ".") -> dict[str, list[str]]:
  7269. """Show status of LFS files.
  7270. Args:
  7271. repo: Path to repository
  7272. Returns:
  7273. Dict with status information
  7274. """
  7275. from .lfs import LFSPointer, LFSStore
  7276. with open_repo_closing(repo) as r:
  7277. store = LFSStore.from_repo(r)
  7278. index = r.open_index()
  7279. status: dict[str, list[str]] = {
  7280. "tracked": [],
  7281. "not_staged": [],
  7282. "not_committed": [],
  7283. "not_pushed": [],
  7284. "missing": [],
  7285. }
  7286. # Check working directory files
  7287. for path, entry in index.items():
  7288. path_str = path.decode()
  7289. full_path = os.path.join(r.path, path_str)
  7290. if os.path.exists(full_path):
  7291. with open(full_path, "rb") as f:
  7292. content = f.read()
  7293. pointer = LFSPointer.from_bytes(content)
  7294. if pointer and pointer.is_valid_oid():
  7295. status["tracked"].append(path_str)
  7296. # Check if object exists locally
  7297. try:
  7298. with store.open_object(pointer.oid):
  7299. pass # Object exists locally
  7300. except KeyError:
  7301. status["missing"].append(path_str)
  7302. # Check if file has been modified
  7303. if isinstance(entry, ConflictedIndexEntry):
  7304. continue # Skip conflicted entries
  7305. try:
  7306. staged_obj = r.object_store[entry.sha]
  7307. except KeyError:
  7308. pass
  7309. else:
  7310. if not isinstance(staged_obj, Blob):
  7311. raise AssertionError(
  7312. f"Expected Blob object, got {type(staged_obj).__name__}"
  7313. )
  7314. staged_pointer = LFSPointer.from_bytes(staged_obj.data)
  7315. if staged_pointer and staged_pointer.oid != pointer.oid:
  7316. status["not_staged"].append(path_str)
  7317. # TODO: Check for not committed and not pushed files
  7318. return status
  7319. def worktree_list(repo: RepoPath = ".") -> list[Any]:
  7320. """List all worktrees for a repository.
  7321. Args:
  7322. repo: Path to repository
  7323. Returns:
  7324. List of WorkTreeInfo objects
  7325. """
  7326. from .worktree import list_worktrees
  7327. with open_repo_closing(repo) as r:
  7328. return list_worktrees(r)
  7329. def worktree_add(
  7330. repo: RepoPath = ".",
  7331. path: str | os.PathLike[str] | None = None,
  7332. branch: str | bytes | None = None,
  7333. commit: str | bytes | None = None,
  7334. detach: bool = False,
  7335. force: bool = False,
  7336. ) -> str:
  7337. """Add a new worktree.
  7338. Args:
  7339. repo: Path to repository
  7340. path: Path for new worktree
  7341. branch: Branch to checkout (creates if doesn't exist)
  7342. commit: Specific commit to checkout
  7343. detach: Create with detached HEAD
  7344. force: Force creation even if branch is already checked out
  7345. Returns:
  7346. Path to the newly created worktree
  7347. """
  7348. from .worktree import add_worktree
  7349. if path is None:
  7350. raise ValueError("Path is required for worktree add")
  7351. with open_repo_closing(repo) as r:
  7352. commit_bytes = commit.encode() if isinstance(commit, str) else commit
  7353. wt_repo = add_worktree(
  7354. r, path, branch=branch, commit=commit_bytes, detach=detach, force=force
  7355. )
  7356. return wt_repo.path
  7357. def worktree_remove(
  7358. repo: RepoPath = ".",
  7359. path: str | os.PathLike[str] | None = None,
  7360. force: bool = False,
  7361. ) -> None:
  7362. """Remove a worktree.
  7363. Args:
  7364. repo: Path to repository
  7365. path: Path to worktree to remove
  7366. force: Force removal even if there are local changes
  7367. """
  7368. from .worktree import remove_worktree
  7369. if path is None:
  7370. raise ValueError("Path is required for worktree remove")
  7371. with open_repo_closing(repo) as r:
  7372. remove_worktree(r, path, force=force)
  7373. def worktree_prune(
  7374. repo: RepoPath = ".", dry_run: bool = False, expire: int | None = None
  7375. ) -> list[str]:
  7376. """Prune worktree administrative files.
  7377. Args:
  7378. repo: Path to repository
  7379. dry_run: Only show what would be removed
  7380. expire: Only prune worktrees older than this many seconds
  7381. Returns:
  7382. List of pruned worktree names
  7383. """
  7384. from .worktree import prune_worktrees
  7385. with open_repo_closing(repo) as r:
  7386. return prune_worktrees(r, expire=expire, dry_run=dry_run)
  7387. def worktree_lock(
  7388. repo: RepoPath = ".",
  7389. path: str | os.PathLike[str] | None = None,
  7390. reason: str | None = None,
  7391. ) -> None:
  7392. """Lock a worktree to prevent it from being pruned.
  7393. Args:
  7394. repo: Path to repository
  7395. path: Path to worktree to lock
  7396. reason: Optional reason for locking
  7397. """
  7398. from .worktree import lock_worktree
  7399. if path is None:
  7400. raise ValueError("Path is required for worktree lock")
  7401. with open_repo_closing(repo) as r:
  7402. lock_worktree(r, path, reason=reason)
  7403. def worktree_unlock(
  7404. repo: RepoPath = ".", path: str | os.PathLike[str] | None = None
  7405. ) -> None:
  7406. """Unlock a worktree.
  7407. Args:
  7408. repo: Path to repository
  7409. path: Path to worktree to unlock
  7410. """
  7411. from .worktree import unlock_worktree
  7412. if path is None:
  7413. raise ValueError("Path is required for worktree unlock")
  7414. with open_repo_closing(repo) as r:
  7415. unlock_worktree(r, path)
  7416. def worktree_move(
  7417. repo: RepoPath = ".",
  7418. old_path: str | os.PathLike[str] | None = None,
  7419. new_path: str | os.PathLike[str] | None = None,
  7420. ) -> None:
  7421. """Move a worktree to a new location.
  7422. Args:
  7423. repo: Path to repository
  7424. old_path: Current path of worktree
  7425. new_path: New path for worktree
  7426. """
  7427. from .worktree import move_worktree
  7428. if old_path is None or new_path is None:
  7429. raise ValueError("Both old_path and new_path are required for worktree move")
  7430. with open_repo_closing(repo) as r:
  7431. move_worktree(r, old_path, new_path)
  7432. def worktree_repair(
  7433. repo: RepoPath = ".",
  7434. paths: list[str | os.PathLike[str]] | None = None,
  7435. ) -> list[str]:
  7436. """Repair worktree administrative files.
  7437. Args:
  7438. repo: Path to repository
  7439. paths: Optional list of worktree paths to repair. If None, repairs
  7440. connections from the main repository to all linked worktrees.
  7441. Returns:
  7442. List of repaired worktree paths
  7443. """
  7444. from .worktree import repair_worktree
  7445. with open_repo_closing(repo) as r:
  7446. return repair_worktree(r, paths=paths)
  7447. def merge_base(
  7448. repo: RepoPath = ".",
  7449. committishes: Sequence[str | bytes] | None = None,
  7450. all: bool = False,
  7451. octopus: bool = False,
  7452. ) -> list[bytes]:
  7453. """Find the best common ancestor(s) between commits.
  7454. Args:
  7455. repo: Path to repository
  7456. committishes: List of commit references (branches, tags, commit IDs)
  7457. all: If True, return all merge bases, not just one
  7458. octopus: If True, find merge base of all commits (n-way merge)
  7459. Returns:
  7460. List of commit IDs that are merge bases
  7461. """
  7462. from .graph import find_merge_base, find_octopus_base
  7463. from .objectspec import parse_object
  7464. if committishes is None or len(committishes) < 2:
  7465. raise ValueError("At least two commits are required")
  7466. with open_repo_closing(repo) as r:
  7467. # Resolve committish references to commit IDs
  7468. commit_ids = []
  7469. for committish in committishes:
  7470. obj = parse_object(r, committish)
  7471. if not isinstance(obj, Commit):
  7472. raise ValueError(f"Expected commit, got {obj.type_name.decode()}")
  7473. commit_ids.append(obj.id)
  7474. # Find merge base
  7475. if octopus:
  7476. result = find_octopus_base(r, commit_ids)
  7477. else:
  7478. result = find_merge_base(r, commit_ids)
  7479. # Return first result only if all=False
  7480. if not all and result:
  7481. return [result[0]]
  7482. return result
  7483. def is_ancestor(
  7484. repo: RepoPath = ".",
  7485. ancestor: str | bytes | None = None,
  7486. descendant: str | bytes | None = None,
  7487. ) -> bool:
  7488. """Check if one commit is an ancestor of another.
  7489. Args:
  7490. repo: Path to repository
  7491. ancestor: Commit that might be the ancestor
  7492. descendant: Commit that might be the descendant
  7493. Returns:
  7494. True if ancestor is an ancestor of descendant, False otherwise
  7495. """
  7496. from .graph import find_merge_base
  7497. from .objectspec import parse_object
  7498. if ancestor is None or descendant is None:
  7499. raise ValueError("Both ancestor and descendant are required")
  7500. with open_repo_closing(repo) as r:
  7501. # Resolve committish references to commit IDs
  7502. ancestor_obj = parse_object(r, ancestor)
  7503. if not isinstance(ancestor_obj, Commit):
  7504. raise ValueError(f"Expected commit, got {ancestor_obj.type_name.decode()}")
  7505. descendant_obj = parse_object(r, descendant)
  7506. if not isinstance(descendant_obj, Commit):
  7507. raise ValueError(
  7508. f"Expected commit, got {descendant_obj.type_name.decode()}"
  7509. )
  7510. # If ancestor is the merge base of (ancestor, descendant), then it's an ancestor
  7511. merge_bases = find_merge_base(r, [ancestor_obj.id, descendant_obj.id])
  7512. return merge_bases == [ancestor_obj.id]
  7513. def independent_commits(
  7514. repo: RepoPath = ".",
  7515. committishes: Sequence[str | bytes] | None = None,
  7516. ) -> list[bytes]:
  7517. """Filter commits to only those that are not reachable from others.
  7518. Args:
  7519. repo: Path to repository
  7520. committishes: List of commit references to filter
  7521. Returns:
  7522. List of commit IDs that are not ancestors of any other commits in the list
  7523. """
  7524. from .graph import independent
  7525. from .objectspec import parse_object
  7526. if committishes is None or len(committishes) == 0:
  7527. return []
  7528. with open_repo_closing(repo) as r:
  7529. # Resolve committish references to commit IDs
  7530. commit_ids = []
  7531. for committish in committishes:
  7532. obj = parse_object(r, committish)
  7533. if not isinstance(obj, Commit):
  7534. raise ValueError(f"Expected commit, got {obj.type_name.decode()}")
  7535. commit_ids.append(obj.id)
  7536. # Filter to independent commits
  7537. return independent(r, commit_ids)
  7538. def mailsplit(
  7539. input_path: str | os.PathLike[str] | IO[bytes] | None = None,
  7540. output_dir: str | os.PathLike[str] = ".",
  7541. start_number: int = 1,
  7542. precision: int = 4,
  7543. keep_cr: bool = False,
  7544. mboxrd: bool = False,
  7545. is_maildir: bool = False,
  7546. ) -> list[str]:
  7547. r"""Split an mbox file or Maildir into individual message files.
  7548. This is similar to git mailsplit.
  7549. Args:
  7550. input_path: Path to mbox file, Maildir, or file-like object. If None, reads from stdin.
  7551. output_dir: Directory where individual messages will be written
  7552. start_number: Starting number for output files (default: 1)
  7553. precision: Number of digits for output filenames (default: 4)
  7554. keep_cr: If True, preserve \r in lines ending with \r\n (default: False)
  7555. mboxrd: If True, treat input as mboxrd format and reverse escaping (default: False)
  7556. is_maildir: If True, treat input_path as a Maildir (default: False)
  7557. Returns:
  7558. List of output file paths that were created
  7559. Raises:
  7560. ValueError: If output_dir doesn't exist or input is invalid
  7561. OSError: If there are issues reading/writing files
  7562. """
  7563. from .mbox import split_maildir, split_mbox
  7564. if is_maildir:
  7565. if input_path is None:
  7566. raise ValueError("input_path is required for Maildir splitting")
  7567. if not isinstance(input_path, (str, bytes, os.PathLike)):
  7568. raise ValueError("Maildir splitting requires a path, not a file object")
  7569. # Convert PathLike to str for split_maildir
  7570. maildir_path: str | bytes = (
  7571. os.fspath(input_path) if isinstance(input_path, os.PathLike) else input_path
  7572. )
  7573. out_dir: str | bytes = (
  7574. os.fspath(output_dir) if isinstance(output_dir, os.PathLike) else output_dir
  7575. )
  7576. return split_maildir(
  7577. maildir_path,
  7578. out_dir,
  7579. start_number=start_number,
  7580. precision=precision,
  7581. keep_cr=keep_cr,
  7582. )
  7583. else:
  7584. if input_path is None:
  7585. # Read from stdin
  7586. input_file: str | bytes | BinaryIO = sys.stdin.buffer
  7587. else:
  7588. # Convert PathLike to str if needed
  7589. if isinstance(input_path, os.PathLike):
  7590. input_file = os.fspath(input_path)
  7591. else:
  7592. # input_path is either str or IO[bytes] here
  7593. input_file = cast(str | BinaryIO, input_path)
  7594. out_dir = (
  7595. os.fspath(output_dir) if isinstance(output_dir, os.PathLike) else output_dir
  7596. )
  7597. return split_mbox(
  7598. input_file,
  7599. out_dir,
  7600. start_number=start_number,
  7601. precision=precision,
  7602. keep_cr=keep_cr,
  7603. mboxrd=mboxrd,
  7604. )
  7605. def mailinfo(
  7606. input_path: str | os.PathLike[str] | IO[bytes] | IO[str] | None = None,
  7607. msg_file: str | os.PathLike[str] | None = None,
  7608. patch_file: str | os.PathLike[str] | None = None,
  7609. keep_subject: bool = False,
  7610. keep_non_patch: bool = False,
  7611. encoding: str | None = None,
  7612. scissors: bool = False,
  7613. message_id: bool = False,
  7614. ) -> MailinfoResult:
  7615. """Extract patch information from an email message.
  7616. This is similar to git mailinfo.
  7617. Args:
  7618. input_path: Path to email file or file-like object. If None, reads from stdin.
  7619. msg_file: Path to write commit message. If None, message not written to file.
  7620. patch_file: Path to write patch content. If None, patch not written to file.
  7621. keep_subject: If True, keep subject intact without munging (-k)
  7622. keep_non_patch: If True, only strip [PATCH] from brackets (-b)
  7623. encoding: Character encoding to use (default: detect from message)
  7624. scissors: If True, remove everything before scissors line
  7625. message_id: If True, include Message-ID in commit message (-m)
  7626. Returns:
  7627. MailinfoResult with parsed information
  7628. Raises:
  7629. ValueError: If message is malformed or missing required fields
  7630. OSError: If there are issues reading/writing files
  7631. Example:
  7632. >>> result = mailinfo("patch.eml", "msg", "patch")
  7633. >>> print(f"Author: {result.author_name} <{result.author_email}>")
  7634. >>> print(f"Subject: {result.subject}")
  7635. """
  7636. from .mbox import mailinfo as mbox_mailinfo
  7637. if input_path is None:
  7638. # Read from stdin
  7639. input_file: str | bytes | BinaryIO | TextIO = sys.stdin.buffer
  7640. else:
  7641. # Convert PathLike to str if needed
  7642. if isinstance(input_path, os.PathLike):
  7643. input_file = os.fspath(input_path)
  7644. else:
  7645. # input_path is either str or IO[bytes] or IO[str] here
  7646. input_file = cast(str | BinaryIO | TextIO, input_path)
  7647. result = mbox_mailinfo(
  7648. input_file,
  7649. keep_subject=keep_subject,
  7650. keep_non_patch=keep_non_patch,
  7651. encoding=encoding,
  7652. scissors=scissors,
  7653. message_id=message_id,
  7654. )
  7655. # Write message to file if requested
  7656. if msg_file is not None:
  7657. msg_path = (
  7658. os.fspath(msg_file) if isinstance(msg_file, os.PathLike) else msg_file
  7659. )
  7660. with open(msg_path, "w", encoding=encoding or "utf-8") as f:
  7661. f.write(result.message)
  7662. if not result.message.endswith("\n"):
  7663. f.write("\n")
  7664. # Write patch to file if requested
  7665. if patch_file is not None:
  7666. patch_path = (
  7667. os.fspath(patch_file) if isinstance(patch_file, os.PathLike) else patch_file
  7668. )
  7669. with open(patch_path, "w", encoding=encoding or "utf-8") as f:
  7670. f.write(result.patch)
  7671. return result
  7672. def rerere(repo: RepoPath = ".") -> tuple[list[tuple[bytes, str]], list[bytes]]:
  7673. """Record current conflict resolutions and apply known resolutions.
  7674. This reads conflicted files from the working tree and records them
  7675. in the rerere cache. If rerere.autoupdate is enabled and a known
  7676. resolution exists, it will be automatically applied.
  7677. Args:
  7678. repo: Path to the repository
  7679. Returns:
  7680. Tuple of:
  7681. - List of tuples (path, conflict_id) for recorded conflicts
  7682. - List of paths where resolutions were automatically applied
  7683. """
  7684. from .rerere import _has_conflict_markers, rerere_auto
  7685. with open_repo_closing(repo) as r:
  7686. # Get conflicts from the index (if available)
  7687. index = r.open_index()
  7688. conflicts = []
  7689. for path, entry in index.items():
  7690. if isinstance(entry, ConflictedIndexEntry):
  7691. conflicts.append(path)
  7692. # Also scan working tree for files with conflict markers
  7693. # This is needed because merge() doesn't always create ConflictedIndexEntry
  7694. if not conflicts:
  7695. working_tree = r.path
  7696. for path in index:
  7697. file_path = os.path.join(working_tree, os.fsdecode(path))
  7698. try:
  7699. with open(file_path, "rb") as f:
  7700. content = f.read()
  7701. if _has_conflict_markers(content):
  7702. conflicts.append(path)
  7703. except (FileNotFoundError, IsADirectoryError, PermissionError):
  7704. pass
  7705. # Record conflicts and apply known resolutions
  7706. working_tree = r.path
  7707. return rerere_auto(r, working_tree, conflicts)
  7708. def rerere_status(repo: RepoPath = ".") -> list[tuple[str, bool]]:
  7709. """Get the status of all conflicts in the rerere cache.
  7710. Args:
  7711. repo: Path to the repository
  7712. Returns:
  7713. List of tuples (conflict_id, has_resolution)
  7714. """
  7715. from .rerere import RerereCache
  7716. with open_repo_closing(repo) as r:
  7717. cache = RerereCache.from_repo(r)
  7718. return cache.status()
  7719. def rerere_diff(
  7720. repo: RepoPath = ".", conflict_id: str | None = None
  7721. ) -> list[tuple[str, bytes, bytes | None]]:
  7722. """Show differences for recorded rerere conflicts.
  7723. Args:
  7724. repo: Path to the repository
  7725. conflict_id: Optional specific conflict ID to show
  7726. Returns:
  7727. List of tuples (conflict_id, preimage, postimage)
  7728. """
  7729. from .rerere import RerereCache
  7730. with open_repo_closing(repo) as r:
  7731. cache = RerereCache.from_repo(r)
  7732. if conflict_id:
  7733. preimage, postimage = cache.diff(conflict_id)
  7734. if preimage is not None:
  7735. return [(conflict_id, preimage, postimage)]
  7736. return []
  7737. # Show all conflicts
  7738. results = []
  7739. for cid, _has_res in cache.status():
  7740. preimage, postimage = cache.diff(cid)
  7741. if preimage is not None:
  7742. results.append((cid, preimage, postimage))
  7743. return results
  7744. def rerere_forget(repo: RepoPath = ".", pathspec: str | bytes | None = None) -> None:
  7745. """Forget recorded rerere resolutions for a pathspec.
  7746. Args:
  7747. repo: Path to the repository
  7748. pathspec: Path to forget (currently not implemented, forgets all)
  7749. """
  7750. from .rerere import RerereCache
  7751. with open_repo_closing(repo) as r:
  7752. cache = RerereCache.from_repo(r)
  7753. if pathspec:
  7754. # TODO: Implement pathspec matching
  7755. # For now, we need to track which conflict IDs correspond to which paths
  7756. raise NotImplementedError("Pathspec matching not yet implemented")
  7757. # Forget all conflicts (this is when called with no pathspec after resolving)
  7758. cache.clear()
  7759. def rerere_clear(repo: RepoPath = ".") -> None:
  7760. """Clear all recorded rerere resolutions.
  7761. Args:
  7762. repo: Path to the repository
  7763. """
  7764. from .rerere import RerereCache
  7765. with open_repo_closing(repo) as r:
  7766. cache = RerereCache.from_repo(r)
  7767. cache.clear()
  7768. def rerere_gc(repo: RepoPath = ".", max_age_days: int = 60) -> None:
  7769. """Garbage collect old rerere resolutions.
  7770. Args:
  7771. repo: Path to the repository
  7772. max_age_days: Maximum age in days for keeping resolutions
  7773. """
  7774. from .rerere import RerereCache
  7775. with open_repo_closing(repo) as r:
  7776. cache = RerereCache.from_repo(r)
  7777. cache.gc(max_age_days)