porcelain.py 241 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169
  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. * init
  41. * ls_files
  42. * ls_remote
  43. * ls_tree
  44. * merge
  45. * merge_tree
  46. * mv/move
  47. * prune
  48. * pull
  49. * push
  50. * rm
  51. * remote{_add}
  52. * receive_pack
  53. * reset
  54. * revert
  55. * sparse_checkout
  56. * submodule_add
  57. * submodule_init
  58. * submodule_list
  59. * rev_list
  60. * tag{_create,_delete,_list}
  61. * upload_pack
  62. * update_server_info
  63. * var
  64. * write_commit_graph
  65. * status
  66. * shortlog
  67. * symbolic_ref
  68. * worktree{_add,_list,_remove,_prune,_lock,_unlock,_move}
  69. These functions are meant to behave similarly to the git subcommands.
  70. Differences in behaviour are considered bugs.
  71. Note: one of the consequences of this is that paths tend to be
  72. interpreted relative to the current working directory rather than relative
  73. to the repository root.
  74. Functions should generally accept both unicode strings and bytestrings
  75. """
  76. import datetime
  77. import fnmatch
  78. import logging
  79. import os
  80. import posixpath
  81. import stat
  82. import sys
  83. import time
  84. from collections import namedtuple
  85. from collections.abc import Iterable, Iterator, Sequence
  86. from collections.abc import Set as AbstractSet
  87. from contextlib import AbstractContextManager, closing, contextmanager
  88. from dataclasses import dataclass
  89. from io import BytesIO, RawIOBase
  90. from pathlib import Path
  91. from typing import (
  92. IO,
  93. TYPE_CHECKING,
  94. Any,
  95. BinaryIO,
  96. Callable,
  97. Optional,
  98. TextIO,
  99. TypeVar,
  100. Union,
  101. cast,
  102. overload,
  103. )
  104. if sys.version_info >= (3, 12):
  105. from collections.abc import Buffer
  106. from typing import override
  107. else:
  108. from typing_extensions import Buffer, override
  109. if TYPE_CHECKING:
  110. from .filter_branch import CommitData
  111. from .gc import GCStats
  112. from . import replace_me
  113. from .archive import tar_stream
  114. from .bisect import BisectState
  115. from .client import (
  116. FetchPackResult,
  117. LsRemoteResult,
  118. SendPackResult,
  119. get_transport_and_path,
  120. )
  121. from .config import Config, ConfigFile, StackedConfig, read_submodules
  122. from .diff_tree import (
  123. CHANGE_ADD,
  124. CHANGE_COPY,
  125. CHANGE_DELETE,
  126. CHANGE_MODIFY,
  127. CHANGE_RENAME,
  128. RENAME_CHANGE_TYPES,
  129. TreeChange,
  130. tree_changes,
  131. )
  132. from .errors import SendPackError
  133. from .graph import can_fast_forward
  134. from .ignore import IgnoreFilterManager
  135. from .index import (
  136. ConflictedIndexEntry,
  137. Index,
  138. IndexEntry,
  139. _fs_to_tree_path,
  140. blob_from_path_and_stat,
  141. build_file_from_blob,
  142. build_index_from_tree,
  143. get_unstaged_changes,
  144. index_entry_from_stat,
  145. symlink,
  146. update_working_tree,
  147. validate_path_element_default,
  148. validate_path_element_hfs,
  149. validate_path_element_ntfs,
  150. )
  151. from .object_store import BaseObjectStore, tree_lookup_path
  152. from .objects import (
  153. Blob,
  154. Commit,
  155. Tag,
  156. Tree,
  157. TreeEntry,
  158. format_timezone,
  159. parse_timezone,
  160. pretty_format_tree_entry,
  161. )
  162. from .objectspec import (
  163. parse_commit,
  164. parse_object,
  165. parse_ref,
  166. parse_reftuples,
  167. parse_tree,
  168. )
  169. from .pack import UnpackedObject, write_pack_from_container, write_pack_index
  170. from .patch import (
  171. get_summary,
  172. write_commit_patch,
  173. write_object_diff,
  174. write_tree_diff,
  175. )
  176. from .protocol import ZERO_SHA, Protocol
  177. from .refs import (
  178. LOCAL_BRANCH_PREFIX,
  179. LOCAL_NOTES_PREFIX,
  180. LOCAL_REMOTE_PREFIX,
  181. LOCAL_TAG_PREFIX,
  182. Ref,
  183. SymrefLoop,
  184. _import_remote_refs,
  185. )
  186. from .repo import BaseRepo, Repo, get_user_identity
  187. from .server import (
  188. FileSystemBackend,
  189. ReceivePackHandler,
  190. TCPGitServer,
  191. UploadPackHandler,
  192. )
  193. from .server import update_server_info as server_update_server_info
  194. from .sparse_patterns import (
  195. SparseCheckoutConflictError,
  196. apply_included_paths,
  197. determine_included_paths,
  198. )
  199. # Module level tuple definition for status output
  200. GitStatus = namedtuple("GitStatus", "staged unstaged untracked")
  201. # TypeVar for preserving BaseRepo subclass types
  202. T = TypeVar("T", bound="BaseRepo")
  203. # Type alias for common repository parameter pattern
  204. RepoPath = Union[str, os.PathLike[str], Repo]
  205. @dataclass
  206. class CountObjectsResult:
  207. """Result of counting objects in a repository.
  208. Attributes:
  209. count: Number of loose objects
  210. size: Total size of loose objects in bytes
  211. in_pack: Number of objects in pack files
  212. packs: Number of pack files
  213. size_pack: Total size of pack files in bytes
  214. """
  215. count: int
  216. size: int
  217. in_pack: Optional[int] = None
  218. packs: Optional[int] = None
  219. size_pack: Optional[int] = None
  220. class NoneStream(RawIOBase):
  221. """Fallback if stdout or stderr are unavailable, does nothing."""
  222. def read(self, size: int = -1) -> None:
  223. """Read from stream (returns None as this is a null stream)."""
  224. return None
  225. def readall(self) -> bytes:
  226. """Read all bytes (returns empty bytes).
  227. Returns:
  228. Empty bytes object
  229. """
  230. return b""
  231. @override
  232. def readinto(self, b: Buffer) -> Optional[int]:
  233. return 0
  234. @override
  235. def write(self, b: Buffer) -> Optional[int]:
  236. # All Buffer implementations (bytes, bytearray, memoryview) support len()
  237. return len(b) if b else 0 # type: ignore[arg-type]
  238. default_bytes_out_stream: BinaryIO = cast(
  239. BinaryIO, getattr(sys.stdout, "buffer", None) or NoneStream()
  240. )
  241. default_bytes_err_stream: BinaryIO = cast(
  242. BinaryIO, getattr(sys.stderr, "buffer", None) or NoneStream()
  243. )
  244. DEFAULT_ENCODING = "utf-8"
  245. class Error(Exception):
  246. """Porcelain-based error."""
  247. def __init__(self, msg: str) -> None:
  248. """Initialize Error with message."""
  249. super().__init__(msg)
  250. class RemoteExists(Error):
  251. """Raised when the remote already exists."""
  252. class TimezoneFormatError(Error):
  253. """Raised when the timezone cannot be determined from a given string."""
  254. class CheckoutError(Error):
  255. """Indicates that a checkout cannot be performed."""
  256. def parse_timezone_format(tz_str: str) -> int:
  257. """Parse given string and attempt to return a timezone offset.
  258. Different formats are considered in the following order:
  259. - Git internal format: <unix timestamp> <timezone offset>
  260. - RFC 2822: e.g. Mon, 20 Nov 1995 19:12:08 -0500
  261. - ISO 8601: e.g. 1995-11-20T19:12:08-0500
  262. Args:
  263. tz_str: datetime string
  264. Returns: Timezone offset as integer
  265. Raises:
  266. TimezoneFormatError: if timezone information cannot be extracted
  267. """
  268. import re
  269. # Git internal format
  270. internal_format_pattern = re.compile("^[0-9]+ [+-][0-9]{,4}$")
  271. if re.match(internal_format_pattern, tz_str):
  272. try:
  273. tz_internal = parse_timezone(tz_str.split(" ")[1].encode(DEFAULT_ENCODING))
  274. return tz_internal[0]
  275. except ValueError:
  276. pass
  277. # RFC 2822
  278. import email.utils
  279. rfc_2822 = email.utils.parsedate_tz(tz_str)
  280. if rfc_2822 and rfc_2822[9] is not None:
  281. return rfc_2822[9]
  282. # ISO 8601
  283. # Supported offsets:
  284. # sHHMM, sHH:MM, sHH
  285. iso_8601_pattern = re.compile(
  286. "[0-9] ?([+-])([0-9]{2})(?::(?=[0-9]{2}))?([0-9]{2})?$"
  287. )
  288. match = re.search(iso_8601_pattern, tz_str)
  289. total_secs = 0
  290. if match:
  291. sign, hours, minutes = match.groups()
  292. total_secs += int(hours) * 3600
  293. if minutes:
  294. total_secs += int(minutes) * 60
  295. total_secs = -total_secs if sign == "-" else total_secs
  296. return total_secs
  297. # YYYY.MM.DD, MM/DD/YYYY, DD.MM.YYYY contain no timezone information
  298. raise TimezoneFormatError(tz_str)
  299. def get_user_timezones() -> tuple[int, int]:
  300. """Retrieve local timezone as described in git documentation.
  301. https://raw.githubusercontent.com/git/git/v2.3.0/Documentation/date-formats.txt
  302. Returns: A tuple containing author timezone, committer timezone.
  303. """
  304. local_timezone = time.localtime().tm_gmtoff
  305. if os.environ.get("GIT_AUTHOR_DATE"):
  306. author_timezone = parse_timezone_format(os.environ["GIT_AUTHOR_DATE"])
  307. else:
  308. author_timezone = local_timezone
  309. if os.environ.get("GIT_COMMITTER_DATE"):
  310. commit_timezone = parse_timezone_format(os.environ["GIT_COMMITTER_DATE"])
  311. else:
  312. commit_timezone = local_timezone
  313. return author_timezone, commit_timezone
  314. @overload
  315. def open_repo(path_or_repo: T) -> AbstractContextManager[T]: ...
  316. @overload
  317. def open_repo(
  318. path_or_repo: Union[str, os.PathLike[str]],
  319. ) -> AbstractContextManager[Repo]: ...
  320. def open_repo(
  321. path_or_repo: Union[str, os.PathLike[str], T],
  322. ) -> AbstractContextManager[Union[T, Repo]]:
  323. """Open an argument that can be a repository or a path for a repository."""
  324. if isinstance(path_or_repo, BaseRepo):
  325. return _noop_context_manager(path_or_repo)
  326. return Repo(path_or_repo)
  327. @contextmanager
  328. def _noop_context_manager(obj: T) -> Iterator[T]:
  329. """Context manager that has the same api as closing but does nothing."""
  330. yield obj
  331. @overload
  332. def open_repo_closing(path_or_repo: T) -> AbstractContextManager[T]: ...
  333. @overload
  334. def open_repo_closing(
  335. path_or_repo: Union[str, bytes, os.PathLike[str]],
  336. ) -> AbstractContextManager[Repo]: ...
  337. def open_repo_closing(
  338. path_or_repo: Union[str, bytes, os.PathLike[str], T],
  339. ) -> AbstractContextManager[Union[T, Repo]]:
  340. """Open an argument that can be a repository or a path for a repository.
  341. returns a context manager that will close the repo on exit if the argument
  342. is a path, else does nothing if the argument is a repo.
  343. """
  344. if isinstance(path_or_repo, BaseRepo):
  345. return _noop_context_manager(path_or_repo)
  346. return closing(Repo(path_or_repo))
  347. def path_to_tree_path(
  348. repopath: Union[str, bytes, os.PathLike[str]],
  349. path: Union[str, bytes, os.PathLike[str]],
  350. tree_encoding: str = DEFAULT_ENCODING,
  351. ) -> bytes:
  352. """Convert a path to a path usable in an index, e.g. bytes and relative to the repository root.
  353. Args:
  354. repopath: Repository path, absolute or relative to the cwd
  355. path: A path, absolute or relative to the cwd
  356. tree_encoding: Encoding to use for tree paths
  357. Returns: A path formatted for use in e.g. an index
  358. """
  359. # Resolve might returns a relative path on Windows
  360. # https://bugs.python.org/issue38671
  361. if sys.platform == "win32":
  362. path = os.path.abspath(path)
  363. # Convert bytes paths to str for Path
  364. if isinstance(path, bytes):
  365. path = os.fsdecode(path)
  366. path = Path(path)
  367. resolved_path = path.resolve()
  368. # Resolve and abspath seems to behave differently regarding symlinks,
  369. # as we are doing abspath on the file path, we need to do the same on
  370. # the repo path or they might not match
  371. if sys.platform == "win32":
  372. repopath = os.path.abspath(repopath)
  373. # Convert bytes paths to str for Path
  374. if isinstance(repopath, bytes):
  375. repopath = os.fsdecode(repopath)
  376. repopath = Path(repopath).resolve()
  377. try:
  378. relpath = resolved_path.relative_to(repopath)
  379. except ValueError:
  380. # If path is a symlink that points to a file outside the repo, we
  381. # want the relpath for the link itself, not the resolved target
  382. if path.is_symlink():
  383. parent = path.parent.resolve()
  384. relpath = (parent / path.name).relative_to(repopath)
  385. else:
  386. raise
  387. if sys.platform == "win32":
  388. return str(relpath).replace(os.path.sep, "/").encode(tree_encoding)
  389. else:
  390. return bytes(relpath)
  391. class DivergedBranches(Error):
  392. """Branches have diverged and fast-forward is not possible."""
  393. def __init__(self, current_sha: bytes, new_sha: bytes) -> None:
  394. """Initialize DivergedBranches error with current and new SHA values."""
  395. self.current_sha = current_sha
  396. self.new_sha = new_sha
  397. def check_diverged(repo: BaseRepo, current_sha: bytes, new_sha: bytes) -> None:
  398. """Check if updating to a sha can be done with fast forwarding.
  399. Args:
  400. repo: Repository object
  401. current_sha: Current head sha
  402. new_sha: New head sha
  403. """
  404. try:
  405. can = can_fast_forward(repo, current_sha, new_sha)
  406. except KeyError:
  407. can = False
  408. if not can:
  409. raise DivergedBranches(current_sha, new_sha)
  410. def archive(
  411. repo: Union[str, BaseRepo],
  412. committish: Optional[Union[str, bytes, Commit, Tag]] = None,
  413. outstream: Union[BinaryIO, RawIOBase] = default_bytes_out_stream,
  414. errstream: Union[BinaryIO, RawIOBase] = default_bytes_err_stream,
  415. ) -> None:
  416. """Create an archive.
  417. Args:
  418. repo: Path of repository for which to generate an archive.
  419. committish: Commit SHA1 or ref to use
  420. outstream: Output stream (defaults to stdout)
  421. errstream: Error stream (defaults to stderr)
  422. """
  423. if committish is None:
  424. committish = "HEAD"
  425. with open_repo_closing(repo) as repo_obj:
  426. c = parse_commit(repo_obj, committish)
  427. tree = repo_obj.object_store[c.tree]
  428. assert isinstance(tree, Tree)
  429. for chunk in tar_stream(repo_obj.object_store, tree, c.commit_time):
  430. outstream.write(chunk)
  431. def update_server_info(repo: RepoPath = ".") -> None:
  432. """Update server info files for a repository.
  433. Args:
  434. repo: path to the repository
  435. """
  436. with open_repo_closing(repo) as r:
  437. server_update_server_info(r)
  438. def write_commit_graph(repo: RepoPath = ".", reachable: bool = True) -> None:
  439. """Write a commit graph file for a repository.
  440. Args:
  441. repo: path to the repository or a Repo object
  442. reachable: if True, include all commits reachable from refs.
  443. if False, only include direct ref targets.
  444. """
  445. with open_repo_closing(repo) as r:
  446. # Get all refs
  447. refs = list(r.refs.as_dict().values())
  448. if refs:
  449. r.object_store.write_commit_graph(refs, reachable=reachable)
  450. def symbolic_ref(
  451. repo: RepoPath, ref_name: Union[str, bytes], force: bool = False
  452. ) -> None:
  453. """Set git symbolic ref into HEAD.
  454. Args:
  455. repo: path to the repository
  456. ref_name: short name of the new ref
  457. force: force settings without checking if it exists in refs/heads
  458. """
  459. with open_repo_closing(repo) as repo_obj:
  460. ref_path = _make_branch_ref(ref_name)
  461. if not force and ref_path not in repo_obj.refs.keys():
  462. ref_name_str = (
  463. ref_name.decode("utf-8", "replace")
  464. if isinstance(ref_name, bytes)
  465. else ref_name
  466. )
  467. raise Error(f"fatal: ref `{ref_name_str}` is not a ref")
  468. repo_obj.refs.set_symbolic_ref(b"HEAD", ref_path)
  469. def pack_refs(repo: RepoPath, all: bool = False) -> None:
  470. """Pack loose references into packed-refs file."""
  471. with open_repo_closing(repo) as repo_obj:
  472. repo_obj.refs.pack_refs(all=all)
  473. def _get_variables(repo: RepoPath = ".") -> dict[str, str]:
  474. """Internal function to get all Git logical variables.
  475. Args:
  476. repo: Path to the repository
  477. Returns:
  478. A dictionary of all logical variables with values
  479. """
  480. from .repo import get_user_identity
  481. with open_repo_closing(repo) as repo_obj:
  482. config = repo_obj.get_config_stack()
  483. # Define callbacks for each logical variable
  484. def get_author_ident() -> Optional[str]:
  485. """Get GIT_AUTHOR_IDENT."""
  486. try:
  487. author_identity = get_user_identity(config, kind="AUTHOR")
  488. author_tz, _ = get_user_timezones()
  489. timestamp = int(time.time())
  490. return f"{author_identity.decode('utf-8', 'replace')} {timestamp} {author_tz:+05d}"
  491. except Exception:
  492. return None
  493. def get_committer_ident() -> Optional[str]:
  494. """Get GIT_COMMITTER_IDENT."""
  495. try:
  496. committer_identity = get_user_identity(config, kind="COMMITTER")
  497. _, committer_tz = get_user_timezones()
  498. timestamp = int(time.time())
  499. return f"{committer_identity.decode('utf-8', 'replace')} {timestamp} {committer_tz:+05d}"
  500. except Exception:
  501. return None
  502. def get_editor() -> Optional[str]:
  503. """Get GIT_EDITOR."""
  504. editor = os.environ.get("GIT_EDITOR")
  505. if editor is None:
  506. try:
  507. editor_bytes = config.get(("core",), "editor")
  508. editor = editor_bytes.decode("utf-8", "replace")
  509. except KeyError:
  510. editor = os.environ.get("VISUAL") or os.environ.get("EDITOR")
  511. return editor
  512. def get_sequence_editor() -> Optional[str]:
  513. """Get GIT_SEQUENCE_EDITOR."""
  514. sequence_editor = os.environ.get("GIT_SEQUENCE_EDITOR")
  515. if sequence_editor is None:
  516. try:
  517. seq_editor_bytes = config.get(("sequence",), "editor")
  518. sequence_editor = seq_editor_bytes.decode("utf-8", "replace")
  519. except KeyError:
  520. # Falls back to GIT_EDITOR if not set
  521. sequence_editor = get_editor()
  522. return sequence_editor
  523. def get_pager() -> Optional[str]:
  524. """Get GIT_PAGER."""
  525. pager = os.environ.get("GIT_PAGER")
  526. if pager is None:
  527. try:
  528. pager_bytes = config.get(("core",), "pager")
  529. pager = pager_bytes.decode("utf-8", "replace")
  530. except KeyError:
  531. pager = os.environ.get("PAGER")
  532. return pager
  533. def get_default_branch() -> str:
  534. """Get GIT_DEFAULT_BRANCH."""
  535. try:
  536. default_branch_bytes = config.get(("init",), "defaultBranch")
  537. return default_branch_bytes.decode("utf-8", "replace")
  538. except KeyError:
  539. # Git's default is "master"
  540. return "master"
  541. # Dictionary mapping variable names to their getter callbacks
  542. variable_callbacks: dict[str, Callable[[], Optional[str]]] = {
  543. "GIT_AUTHOR_IDENT": get_author_ident,
  544. "GIT_COMMITTER_IDENT": get_committer_ident,
  545. "GIT_EDITOR": get_editor,
  546. "GIT_SEQUENCE_EDITOR": get_sequence_editor,
  547. "GIT_PAGER": get_pager,
  548. "GIT_DEFAULT_BRANCH": get_default_branch,
  549. }
  550. # Build the variables dictionary by calling callbacks
  551. variables: dict[str, str] = {}
  552. for var_name, callback in variable_callbacks.items():
  553. value = callback()
  554. if value is not None:
  555. variables[var_name] = value
  556. return variables
  557. def var_list(repo: RepoPath = ".") -> dict[str, str]:
  558. """List all Git logical variables.
  559. Args:
  560. repo: Path to the repository
  561. Returns:
  562. A dictionary of all logical variables with their values
  563. """
  564. return _get_variables(repo)
  565. def var(repo: RepoPath = ".", variable: str = "GIT_AUTHOR_IDENT") -> str:
  566. """Get the value of a specific Git logical variable.
  567. Args:
  568. repo: Path to the repository
  569. variable: The variable to query (e.g., 'GIT_AUTHOR_IDENT')
  570. Returns:
  571. The value of the requested variable as a string
  572. Raises:
  573. KeyError: If the requested variable has no value
  574. """
  575. variables = _get_variables(repo)
  576. if variable in variables:
  577. return variables[variable]
  578. else:
  579. raise KeyError(f"Variable {variable} has no value")
  580. def commit(
  581. repo: RepoPath = ".",
  582. message: Optional[Union[str, bytes, Callable[[Any, Commit], bytes]]] = None,
  583. author: Optional[bytes] = None,
  584. author_timezone: Optional[int] = None,
  585. committer: Optional[bytes] = None,
  586. commit_timezone: Optional[int] = None,
  587. encoding: Optional[bytes] = None,
  588. no_verify: bool = False,
  589. signoff: Optional[bool] = None,
  590. all: bool = False,
  591. amend: bool = False,
  592. sign: Optional[bool] = None,
  593. ) -> bytes:
  594. """Create a new commit.
  595. Args:
  596. repo: Path to repository
  597. message: Optional commit message (string/bytes or callable that takes
  598. (repo, commit) and returns bytes)
  599. author: Optional author name and email
  600. author_timezone: Author timestamp timezone
  601. committer: Optional committer name and email
  602. commit_timezone: Commit timestamp timezone
  603. encoding: Encoding to use for commit message
  604. no_verify: Skip pre-commit and commit-msg hooks
  605. signoff: Add Signed-off-by line to commit message. If None, uses format.signoff config.
  606. all: Automatically stage all tracked files that have been modified
  607. amend: Replace the tip of the current branch by creating a new commit
  608. sign: GPG sign the commit. If None, uses commit.gpgsign config.
  609. If True, signs with default GPG key. If False, does not sign.
  610. Returns: SHA1 of the new commit
  611. """
  612. encoding_str = encoding.decode("ascii") if encoding else DEFAULT_ENCODING
  613. if isinstance(message, str):
  614. message = message.encode(encoding_str)
  615. if isinstance(author, str):
  616. author = author.encode(encoding_str)
  617. if isinstance(committer, str):
  618. committer = committer.encode(encoding_str)
  619. local_timezone = get_user_timezones()
  620. if author_timezone is None:
  621. author_timezone = local_timezone[0]
  622. if commit_timezone is None:
  623. commit_timezone = local_timezone[1]
  624. with open_repo_closing(repo) as r:
  625. # Handle amend logic
  626. merge_heads = None
  627. if amend:
  628. try:
  629. head_commit = r[r.head()]
  630. assert isinstance(head_commit, Commit)
  631. except KeyError:
  632. raise ValueError("Cannot amend: no existing commit found")
  633. # If message not provided, use the message from the current HEAD
  634. if message is None:
  635. message = head_commit.message
  636. # If author not provided, use the author from the current HEAD
  637. if author is None:
  638. author = head_commit.author
  639. if author_timezone is None:
  640. author_timezone = head_commit.author_timezone
  641. # Use the parent(s) of the current HEAD as our parent(s)
  642. merge_heads = list(head_commit.parents)
  643. # If -a flag is used, stage all modified tracked files
  644. if all:
  645. index = r.open_index()
  646. normalizer = r.get_blob_normalizer()
  647. # Create a wrapper that handles the bytes -> Blob conversion
  648. if normalizer is not None:
  649. def filter_callback(data: bytes, path: bytes) -> bytes:
  650. from dulwich.objects import Blob
  651. blob = Blob()
  652. blob.data = data
  653. normalized_blob = normalizer.checkin_normalize(blob, path)
  654. data_bytes: bytes = normalized_blob.data
  655. return data_bytes
  656. else:
  657. filter_callback = None
  658. unstaged_changes = list(
  659. get_unstaged_changes(index, r.path, filter_callback)
  660. )
  661. if unstaged_changes:
  662. # Convert bytes paths to strings for add function
  663. modified_files: list[Union[str, bytes, os.PathLike[str]]] = []
  664. for path in unstaged_changes:
  665. if isinstance(path, bytes):
  666. modified_files.append(path.decode())
  667. else:
  668. modified_files.append(path)
  669. add(r, paths=modified_files)
  670. # For amend, create dangling commit to avoid adding current HEAD as parent
  671. if amend:
  672. commit_sha = r.get_worktree().commit(
  673. message=message,
  674. author=author,
  675. author_timezone=author_timezone,
  676. committer=committer,
  677. commit_timezone=commit_timezone,
  678. encoding=encoding,
  679. no_verify=no_verify,
  680. sign=sign,
  681. merge_heads=merge_heads,
  682. ref=None,
  683. )
  684. # Update HEAD to point to the new commit
  685. r.refs[b"HEAD"] = commit_sha
  686. return commit_sha
  687. else:
  688. return r.get_worktree().commit(
  689. message=message,
  690. author=author,
  691. author_timezone=author_timezone,
  692. committer=committer,
  693. commit_timezone=commit_timezone,
  694. encoding=encoding,
  695. no_verify=no_verify,
  696. sign=sign,
  697. merge_heads=merge_heads,
  698. )
  699. def commit_tree(
  700. repo: RepoPath,
  701. tree: bytes,
  702. message: Optional[Union[str, bytes]] = None,
  703. author: Optional[bytes] = None,
  704. committer: Optional[bytes] = None,
  705. ) -> bytes:
  706. """Create a new commit object.
  707. Args:
  708. repo: Path to repository
  709. tree: An existing tree object
  710. message: Commit message
  711. author: Optional author name and email
  712. committer: Optional committer name and email
  713. """
  714. with open_repo_closing(repo) as r:
  715. if isinstance(message, str):
  716. message = message.encode(DEFAULT_ENCODING)
  717. return r.get_worktree().commit(
  718. message=message, tree=tree, committer=committer, author=author
  719. )
  720. def init(
  721. path: Union[str, os.PathLike[str]] = ".",
  722. *,
  723. bare: bool = False,
  724. symlinks: Optional[bool] = None,
  725. ) -> Repo:
  726. """Create a new git repository.
  727. Args:
  728. path: Path to repository.
  729. bare: Whether to create a bare repository.
  730. symlinks: Whether to create actual symlinks (defaults to autodetect)
  731. Returns: A Repo instance
  732. """
  733. if not os.path.exists(path):
  734. os.mkdir(path)
  735. if bare:
  736. return Repo.init_bare(path)
  737. else:
  738. return Repo.init(path, symlinks=symlinks)
  739. def clone(
  740. source: Union[str, bytes, Repo],
  741. target: Optional[Union[str, os.PathLike[str]]] = None,
  742. bare: bool = False,
  743. checkout: Optional[bool] = None,
  744. errstream: Union[BinaryIO, RawIOBase] = default_bytes_err_stream,
  745. outstream: Optional[BinaryIO] = None,
  746. origin: Optional[str] = "origin",
  747. depth: Optional[int] = None,
  748. branch: Optional[Union[str, bytes]] = None,
  749. config: Optional[Config] = None,
  750. filter_spec: Optional[str] = None,
  751. protocol_version: Optional[int] = None,
  752. recurse_submodules: bool = False,
  753. **kwargs: Union[Union[str, bytes], Sequence[Union[str, bytes]]],
  754. ) -> Repo:
  755. """Clone a local or remote git repository.
  756. Args:
  757. source: Path or URL for source repository
  758. target: Path to target repository (optional)
  759. bare: Whether or not to create a bare repository
  760. checkout: Whether or not to check-out HEAD after cloning
  761. errstream: Optional stream to write progress to
  762. outstream: Optional stream to write progress to (deprecated)
  763. origin: Name of remote from the repository used to clone
  764. depth: Depth to fetch at
  765. branch: Optional branch or tag to be used as HEAD in the new repository
  766. instead of the cloned repository's HEAD.
  767. config: Configuration to use
  768. filter_spec: A git-rev-list-style object filter spec, as an ASCII string.
  769. Only used if the server supports the Git protocol-v2 'filter'
  770. feature, and ignored otherwise.
  771. protocol_version: desired Git protocol version. By default the highest
  772. mutually supported protocol version will be used.
  773. recurse_submodules: Whether to initialize and clone submodules
  774. **kwargs: Additional keyword arguments including refspecs to fetch.
  775. Can be a bytestring, a string, or a list of bytestring/string.
  776. Returns: The new repository
  777. """
  778. if outstream is not None:
  779. import warnings
  780. warnings.warn(
  781. "outstream= has been deprecated in favour of errstream=.",
  782. DeprecationWarning,
  783. stacklevel=3,
  784. )
  785. # TODO(jelmer): Capture logging output and stream to errstream
  786. if config is None:
  787. config = StackedConfig.default()
  788. if checkout is None:
  789. checkout = not bare
  790. if checkout and bare:
  791. raise Error("checkout and bare are incompatible")
  792. if target is None:
  793. if isinstance(source, Repo):
  794. raise ValueError("target must be specified when cloning from a Repo object")
  795. elif isinstance(source, bytes):
  796. target = source.split(b"/")[-1].decode()
  797. else:
  798. target = source.split("/")[-1]
  799. if isinstance(branch, str):
  800. branch = branch.encode(DEFAULT_ENCODING)
  801. mkdir = not os.path.exists(target)
  802. if isinstance(source, Repo):
  803. # For direct repo cloning, use LocalGitClient
  804. from .client import GitClient, LocalGitClient
  805. client: GitClient = LocalGitClient(config=config)
  806. path = source.path
  807. else:
  808. source_str = source.decode() if isinstance(source, bytes) else source
  809. (client, path) = get_transport_and_path(source_str, config=config, **kwargs) # type: ignore[arg-type]
  810. filter_spec_bytes: Optional[bytes] = None
  811. if filter_spec:
  812. filter_spec_bytes = filter_spec.encode("ascii")
  813. repo = client.clone(
  814. path,
  815. str(target), # Convert PathLike to str
  816. mkdir=mkdir,
  817. bare=bare,
  818. origin=origin,
  819. checkout=checkout,
  820. branch=branch.decode() if branch else None, # Convert bytes to str
  821. progress=lambda data: (errstream.write(data), None)[1],
  822. depth=depth,
  823. filter_spec=filter_spec_bytes,
  824. protocol_version=protocol_version,
  825. )
  826. # Initialize and update submodules if requested
  827. if recurse_submodules and not bare:
  828. try:
  829. submodule_init(repo)
  830. submodule_update(repo, init=True)
  831. except FileNotFoundError as e:
  832. # .gitmodules file doesn't exist - no submodules to process
  833. logging.debug("No .gitmodules file found: %s", e)
  834. except KeyError as e:
  835. # Submodule configuration missing
  836. logging.warning("Submodule configuration error: %s", e)
  837. if errstream:
  838. errstream.write(
  839. f"Warning: Submodule configuration error: {e}\n".encode()
  840. )
  841. return repo
  842. def add(
  843. repo: Union[str, os.PathLike[str], Repo] = ".",
  844. paths: Optional[
  845. Union[
  846. Sequence[Union[str, bytes, os.PathLike[str]]], str, bytes, os.PathLike[str]
  847. ]
  848. ] = None,
  849. ) -> tuple[list[str], set[str]]:
  850. """Add files to the staging area.
  851. Args:
  852. repo: Repository for the files
  853. paths: Paths to add. If None, stages all untracked and modified files from the
  854. current working directory (mimicking 'git add .' behavior).
  855. Returns: Tuple with set of added files and ignored files
  856. If the repository contains ignored directories, the returned set will
  857. contain the path to an ignored directory (with trailing slash). Individual
  858. files within ignored directories will not be returned.
  859. Note: When paths=None, this function adds all untracked and modified files
  860. from the entire repository, mimicking 'git add -A' behavior.
  861. """
  862. ignored = set()
  863. with open_repo_closing(repo) as r:
  864. repo_path = Path(r.path).resolve()
  865. ignore_manager = IgnoreFilterManager.from_repo(r)
  866. # Get unstaged changes once for the entire operation
  867. index = r.open_index()
  868. normalizer = r.get_blob_normalizer()
  869. if normalizer is not None:
  870. def filter_callback(data: bytes, path: bytes) -> bytes:
  871. from dulwich.objects import Blob
  872. blob = Blob()
  873. blob.data = data
  874. normalized_blob = normalizer.checkin_normalize(blob, path)
  875. data_bytes: bytes = normalized_blob.data
  876. return data_bytes
  877. else:
  878. filter_callback = None
  879. # Check if core.preloadIndex is enabled
  880. config = r.get_config_stack()
  881. preload_index = config.get_boolean(b"core", b"preloadIndex", False)
  882. all_unstaged_paths = list(
  883. get_unstaged_changes(index, r.path, filter_callback, preload_index)
  884. )
  885. if not paths:
  886. # When no paths specified, add all untracked and modified files from repo root
  887. paths = [str(repo_path)]
  888. relpaths = []
  889. if isinstance(paths, (str, bytes, os.PathLike)):
  890. paths = [paths]
  891. for p in paths:
  892. # Handle bytes paths by decoding them
  893. if isinstance(p, bytes):
  894. p = p.decode("utf-8")
  895. path = Path(p)
  896. if not path.is_absolute():
  897. # Make relative paths relative to the repo directory
  898. path = repo_path / path
  899. # Don't resolve symlinks completely - only resolve the parent directory
  900. # to avoid issues when symlinks point outside the repository
  901. if path.is_symlink():
  902. # For symlinks, resolve only the parent directory
  903. parent_resolved = path.parent.resolve()
  904. resolved_path = parent_resolved / path.name
  905. else:
  906. # For regular files/dirs, resolve normally
  907. resolved_path = path.resolve()
  908. try:
  909. relpath = str(resolved_path.relative_to(repo_path)).replace(os.sep, "/")
  910. except ValueError as e:
  911. # Path is not within the repository
  912. p_str = p.decode() if isinstance(p, bytes) else str(p)
  913. raise ValueError(
  914. f"Path {p_str} is not within repository {repo_path}"
  915. ) from e
  916. # Handle directories by scanning their contents
  917. if resolved_path.is_dir():
  918. # Check if the directory itself is ignored
  919. dir_relpath = posixpath.join(relpath, "") if relpath != "." else ""
  920. if dir_relpath and ignore_manager.is_ignored(dir_relpath):
  921. ignored.add(dir_relpath)
  922. continue
  923. # When adding a directory, add all untracked files within it
  924. current_untracked = list(
  925. get_untracked_paths(
  926. str(resolved_path),
  927. str(repo_path),
  928. index,
  929. )
  930. )
  931. for untracked_path in current_untracked:
  932. # If we're scanning a subdirectory, adjust the path
  933. if relpath != ".":
  934. untracked_path = posixpath.join(relpath, untracked_path)
  935. if not ignore_manager.is_ignored(untracked_path):
  936. relpaths.append(untracked_path)
  937. else:
  938. ignored.add(untracked_path)
  939. # Also add unstaged (modified) files within this directory
  940. for unstaged_path in all_unstaged_paths:
  941. if isinstance(unstaged_path, bytes):
  942. unstaged_path_str = unstaged_path.decode("utf-8")
  943. else:
  944. unstaged_path_str = unstaged_path
  945. # Check if this unstaged file is within the directory we're processing
  946. unstaged_full_path = repo_path / unstaged_path_str
  947. try:
  948. unstaged_full_path.relative_to(resolved_path)
  949. # File is within this directory, add it
  950. if not ignore_manager.is_ignored(unstaged_path_str):
  951. relpaths.append(unstaged_path_str)
  952. else:
  953. ignored.add(unstaged_path_str)
  954. except ValueError:
  955. # File is not within this directory, skip it
  956. continue
  957. continue
  958. # FIXME: Support patterns
  959. if ignore_manager.is_ignored(relpath):
  960. ignored.add(relpath)
  961. continue
  962. relpaths.append(relpath)
  963. r.get_worktree().stage(relpaths)
  964. return (relpaths, ignored)
  965. def _is_subdir(
  966. subdir: Union[str, os.PathLike[str]], parentdir: Union[str, os.PathLike[str]]
  967. ) -> bool:
  968. """Check whether subdir is parentdir or a subdir of parentdir.
  969. If parentdir or subdir is a relative path, it will be disamgibuated
  970. relative to the pwd.
  971. """
  972. parentdir_abs = os.path.realpath(parentdir) + os.path.sep
  973. subdir_abs = os.path.realpath(subdir) + os.path.sep
  974. return subdir_abs.startswith(parentdir_abs)
  975. # TODO: option to remove ignored files also, in line with `git clean -fdx`
  976. def clean(
  977. repo: Union[str, os.PathLike[str], Repo] = ".",
  978. target_dir: Optional[Union[str, os.PathLike[str]]] = None,
  979. ) -> None:
  980. """Remove any untracked files from the target directory recursively.
  981. Equivalent to running ``git clean -fd`` in target_dir.
  982. Args:
  983. repo: Repository where the files may be tracked
  984. target_dir: Directory to clean - current directory if None
  985. """
  986. if target_dir is None:
  987. target_dir = os.getcwd()
  988. with open_repo_closing(repo) as r:
  989. if not _is_subdir(target_dir, r.path):
  990. raise Error("target_dir must be in the repo's working dir")
  991. config = r.get_config_stack()
  992. config.get_boolean((b"clean",), b"requireForce", True)
  993. # TODO(jelmer): if require_force is set, then make sure that -f, -i or
  994. # -n is specified.
  995. index = r.open_index()
  996. ignore_manager = IgnoreFilterManager.from_repo(r)
  997. paths_in_wd = _walk_working_dir_paths(target_dir, r.path)
  998. # Reverse file visit order, so that files and subdirectories are
  999. # removed before containing directory
  1000. for ap, is_dir in reversed(list(paths_in_wd)):
  1001. # target_dir and r.path are both str, so ap must be str
  1002. assert isinstance(ap, str)
  1003. if is_dir:
  1004. # All subdirectories and files have been removed if untracked,
  1005. # so dir contains no tracked files iff it is empty.
  1006. is_empty = len(os.listdir(ap)) == 0
  1007. if is_empty:
  1008. os.rmdir(ap)
  1009. else:
  1010. ip = path_to_tree_path(r.path, ap)
  1011. is_tracked = ip in index
  1012. rp = os.path.relpath(ap, r.path)
  1013. is_ignored = ignore_manager.is_ignored(rp)
  1014. if not is_tracked and not is_ignored:
  1015. os.remove(ap)
  1016. def remove(
  1017. repo: Union[str, os.PathLike[str], Repo] = ".",
  1018. paths: Sequence[Union[str, bytes, os.PathLike[str]]] = [],
  1019. cached: bool = False,
  1020. ) -> None:
  1021. """Remove files from the staging area.
  1022. Args:
  1023. repo: Repository for the files
  1024. paths: Paths to remove. Can be absolute or relative to the repository root.
  1025. cached: Only remove from index, not from working directory
  1026. """
  1027. with open_repo_closing(repo) as r:
  1028. index = r.open_index()
  1029. blob_normalizer = r.get_blob_normalizer()
  1030. for p in paths:
  1031. # If path is absolute, use it as-is. Otherwise, treat it as relative to repo
  1032. p_str = os.fsdecode(p) if isinstance(p, bytes) else str(p)
  1033. if os.path.isabs(p_str):
  1034. full_path = p_str
  1035. else:
  1036. # Treat relative paths as relative to the repository root
  1037. full_path = os.path.join(r.path, p_str)
  1038. tree_path = path_to_tree_path(r.path, full_path)
  1039. # Convert to bytes for file operations
  1040. full_path_bytes = os.fsencode(full_path)
  1041. try:
  1042. entry = index[tree_path]
  1043. if isinstance(entry, ConflictedIndexEntry):
  1044. raise Error(f"{p_str} has conflicts in the index")
  1045. index_sha = entry.sha
  1046. except KeyError as exc:
  1047. raise Error(f"{p_str} did not match any files") from exc
  1048. if not cached:
  1049. try:
  1050. st = os.lstat(full_path_bytes)
  1051. except OSError:
  1052. pass
  1053. else:
  1054. try:
  1055. blob = blob_from_path_and_stat(full_path_bytes, st)
  1056. # Apply checkin normalization to compare apples to apples
  1057. if blob_normalizer is not None:
  1058. blob = blob_normalizer.checkin_normalize(blob, tree_path)
  1059. except OSError:
  1060. pass
  1061. else:
  1062. try:
  1063. head_commit = r[r.head()]
  1064. assert isinstance(head_commit, Commit)
  1065. committed_sha = tree_lookup_path(
  1066. r.__getitem__, head_commit.tree, tree_path
  1067. )[1]
  1068. except KeyError:
  1069. committed_sha = None
  1070. if blob.id != index_sha and index_sha != committed_sha:
  1071. raise Error(
  1072. "file has staged content differing "
  1073. f"from both the file and head: {p_str}"
  1074. )
  1075. if index_sha != committed_sha:
  1076. raise Error(f"file has staged changes: {p_str}")
  1077. os.remove(full_path_bytes)
  1078. del index[tree_path]
  1079. index.write()
  1080. rm = remove
  1081. def mv(
  1082. repo: Union[str, os.PathLike[str], Repo],
  1083. source: Union[str, bytes, os.PathLike[str]],
  1084. destination: Union[str, bytes, os.PathLike[str]],
  1085. force: bool = False,
  1086. ) -> None:
  1087. """Move or rename a file, directory, or symlink.
  1088. Args:
  1089. repo: Path to the repository
  1090. source: Path to move from
  1091. destination: Path to move to
  1092. force: Force move even if destination exists
  1093. Raises:
  1094. Error: If source doesn't exist, is not tracked, or destination already exists (without force)
  1095. """
  1096. with open_repo_closing(repo) as r:
  1097. index = r.open_index()
  1098. # Handle paths - convert to string if necessary
  1099. if isinstance(source, bytes):
  1100. source = source.decode(sys.getfilesystemencoding())
  1101. elif hasattr(source, "__fspath__"):
  1102. source = os.fspath(source)
  1103. else:
  1104. source = str(source)
  1105. if isinstance(destination, bytes):
  1106. destination = destination.decode(sys.getfilesystemencoding())
  1107. elif hasattr(destination, "__fspath__"):
  1108. destination = os.fspath(destination)
  1109. else:
  1110. destination = str(destination)
  1111. # Get full paths
  1112. if os.path.isabs(source):
  1113. source_full_path = source
  1114. else:
  1115. # Treat relative paths as relative to the repository root
  1116. source_full_path = os.path.join(r.path, source)
  1117. if os.path.isabs(destination):
  1118. destination_full_path = destination
  1119. else:
  1120. # Treat relative paths as relative to the repository root
  1121. destination_full_path = os.path.join(r.path, destination)
  1122. # Check if destination is a directory
  1123. if os.path.isdir(destination_full_path):
  1124. # Move source into destination directory
  1125. basename = os.path.basename(source_full_path)
  1126. destination_full_path = os.path.join(destination_full_path, basename)
  1127. # Convert to tree paths for index
  1128. source_tree_path = path_to_tree_path(r.path, source_full_path)
  1129. destination_tree_path = path_to_tree_path(r.path, destination_full_path)
  1130. # Check if source exists in index
  1131. if source_tree_path not in index:
  1132. raise Error(f"source '{source}' is not under version control")
  1133. # Check if source exists in filesystem
  1134. if not os.path.exists(source_full_path):
  1135. raise Error(f"source '{source}' does not exist")
  1136. # Check if destination already exists
  1137. if os.path.exists(destination_full_path) and not force:
  1138. raise Error(f"destination '{destination}' already exists (use -f to force)")
  1139. # Check if destination is already in index
  1140. if destination_tree_path in index and not force:
  1141. raise Error(
  1142. f"destination '{destination}' already exists in index (use -f to force)"
  1143. )
  1144. # Get the index entry for the source
  1145. source_entry = index[source_tree_path]
  1146. # Convert to bytes for file operations
  1147. source_full_path_bytes = os.fsencode(source_full_path)
  1148. destination_full_path_bytes = os.fsencode(destination_full_path)
  1149. # Create parent directory for destination if needed
  1150. dest_dir = os.path.dirname(destination_full_path_bytes)
  1151. if dest_dir and not os.path.exists(dest_dir):
  1152. os.makedirs(dest_dir)
  1153. # Move the file in the filesystem
  1154. if os.path.exists(destination_full_path_bytes) and force:
  1155. os.remove(destination_full_path_bytes)
  1156. os.rename(source_full_path_bytes, destination_full_path_bytes)
  1157. # Update the index
  1158. del index[source_tree_path]
  1159. index[destination_tree_path] = source_entry
  1160. index.write()
  1161. move = mv
  1162. def commit_decode(
  1163. commit: Commit, contents: bytes, default_encoding: str = DEFAULT_ENCODING
  1164. ) -> str:
  1165. """Decode commit contents using the commit's encoding or default."""
  1166. if commit.encoding:
  1167. encoding = commit.encoding.decode("ascii")
  1168. else:
  1169. encoding = default_encoding
  1170. return contents.decode(encoding, "replace")
  1171. def commit_encode(
  1172. commit: Commit, contents: str, default_encoding: str = DEFAULT_ENCODING
  1173. ) -> bytes:
  1174. """Encode commit contents using the commit's encoding or default."""
  1175. if commit.encoding:
  1176. encoding = commit.encoding.decode("ascii")
  1177. else:
  1178. encoding = default_encoding
  1179. return contents.encode(encoding)
  1180. def print_commit(
  1181. commit: Commit,
  1182. decode: Callable[[bytes], str],
  1183. outstream: TextIO = sys.stdout,
  1184. ) -> None:
  1185. """Write a human-readable commit log entry.
  1186. Args:
  1187. commit: A `Commit` object
  1188. decode: Function to decode commit data
  1189. outstream: A stream file to write to
  1190. """
  1191. outstream.write("-" * 50 + "\n")
  1192. outstream.write("commit: " + commit.id.decode("ascii") + "\n")
  1193. if len(commit.parents) > 1:
  1194. outstream.write(
  1195. "merge: "
  1196. + "...".join([c.decode("ascii") for c in commit.parents[1:]])
  1197. + "\n"
  1198. )
  1199. outstream.write("Author: " + decode(commit.author) + "\n")
  1200. if commit.author != commit.committer:
  1201. outstream.write("Committer: " + decode(commit.committer) + "\n")
  1202. time_tuple = time.gmtime(commit.author_time + commit.author_timezone)
  1203. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  1204. timezone_str = format_timezone(commit.author_timezone).decode("ascii")
  1205. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  1206. if commit.message:
  1207. outstream.write("\n")
  1208. outstream.write(decode(commit.message) + "\n")
  1209. outstream.write("\n")
  1210. def print_tag(
  1211. tag: Tag, decode: Callable[[bytes], str], outstream: TextIO = sys.stdout
  1212. ) -> None:
  1213. """Write a human-readable tag.
  1214. Args:
  1215. tag: A `Tag` object
  1216. decode: Function for decoding bytes to unicode string
  1217. outstream: A stream to write to
  1218. """
  1219. outstream.write("Tagger: " + decode(tag.tagger) + "\n")
  1220. time_tuple = time.gmtime(tag.tag_time + tag.tag_timezone)
  1221. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  1222. timezone_str = format_timezone(tag.tag_timezone).decode("ascii")
  1223. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  1224. outstream.write("\n")
  1225. outstream.write(decode(tag.message))
  1226. outstream.write("\n")
  1227. def show_blob(
  1228. repo: RepoPath,
  1229. blob: Blob,
  1230. decode: Callable[[bytes], str],
  1231. outstream: TextIO = sys.stdout,
  1232. ) -> None:
  1233. """Write a blob to a stream.
  1234. Args:
  1235. repo: A `Repo` object
  1236. blob: A `Blob` object
  1237. decode: Function for decoding bytes to unicode string
  1238. outstream: A stream file to write to
  1239. """
  1240. outstream.write(decode(blob.data))
  1241. def show_commit(
  1242. repo: RepoPath,
  1243. commit: Commit,
  1244. decode: Callable[[bytes], str],
  1245. outstream: TextIO = sys.stdout,
  1246. ) -> None:
  1247. """Show a commit to a stream.
  1248. Args:
  1249. repo: A `Repo` object
  1250. commit: A `Commit` object
  1251. decode: Function for decoding bytes to unicode string
  1252. outstream: Stream to write to
  1253. """
  1254. from .diff import ColorizedDiffStream
  1255. # Create a wrapper for ColorizedDiffStream to handle string/bytes conversion
  1256. class _StreamWrapper:
  1257. def __init__(self, stream: "ColorizedDiffStream") -> None:
  1258. self.stream = stream
  1259. def write(self, data: Union[str, bytes]) -> None:
  1260. if isinstance(data, str):
  1261. # Convert string to bytes for ColorizedDiffStream
  1262. self.stream.write(data.encode("utf-8"))
  1263. else:
  1264. self.stream.write(data)
  1265. with open_repo_closing(repo) as r:
  1266. # Use wrapper for ColorizedDiffStream, direct stream for others
  1267. if isinstance(outstream, ColorizedDiffStream):
  1268. wrapped_stream = _StreamWrapper(outstream)
  1269. print_commit(commit, decode=decode, outstream=wrapped_stream)
  1270. # Write diff directly to the ColorizedDiffStream as bytes
  1271. write_tree_diff(
  1272. outstream,
  1273. r.object_store,
  1274. commit.parents[0] if commit.parents else None,
  1275. commit.tree,
  1276. )
  1277. else:
  1278. print_commit(commit, decode=decode, outstream=outstream)
  1279. if commit.parents:
  1280. parent_commit = r[commit.parents[0]]
  1281. assert isinstance(parent_commit, Commit)
  1282. base_tree = parent_commit.tree
  1283. else:
  1284. base_tree = None
  1285. # Traditional path: buffer diff and write as decoded text
  1286. diffstream = BytesIO()
  1287. write_tree_diff(diffstream, r.object_store, base_tree, commit.tree)
  1288. diffstream.seek(0)
  1289. outstream.write(commit_decode(commit, diffstream.getvalue()))
  1290. def show_tree(
  1291. repo: RepoPath,
  1292. tree: Tree,
  1293. decode: Callable[[bytes], str],
  1294. outstream: TextIO = sys.stdout,
  1295. ) -> None:
  1296. """Print a tree to a stream.
  1297. Args:
  1298. repo: A `Repo` object
  1299. tree: A `Tree` object
  1300. decode: Function for decoding bytes to unicode string
  1301. outstream: Stream to write to
  1302. """
  1303. for n in tree:
  1304. outstream.write(decode(n) + "\n")
  1305. def show_tag(
  1306. repo: RepoPath,
  1307. tag: Tag,
  1308. decode: Callable[[bytes], str],
  1309. outstream: TextIO = sys.stdout,
  1310. ) -> None:
  1311. """Print a tag to a stream.
  1312. Args:
  1313. repo: A `Repo` object
  1314. tag: A `Tag` object
  1315. decode: Function for decoding bytes to unicode string
  1316. outstream: Stream to write to
  1317. """
  1318. with open_repo_closing(repo) as r:
  1319. print_tag(tag, decode, outstream)
  1320. obj = r[tag.object[1]]
  1321. assert isinstance(obj, (Tree, Blob, Commit, Tag))
  1322. show_object(repo, obj, decode, outstream)
  1323. def show_object(
  1324. repo: RepoPath,
  1325. obj: Union[Tree, Blob, Commit, Tag],
  1326. decode: Callable[[bytes], str],
  1327. outstream: TextIO,
  1328. ) -> None:
  1329. """Show details of a git object."""
  1330. handlers: dict[bytes, Callable[[RepoPath, Any, Any, TextIO], None]] = {
  1331. b"tree": show_tree,
  1332. b"blob": show_blob,
  1333. b"commit": show_commit,
  1334. b"tag": show_tag,
  1335. }
  1336. handler = handlers.get(obj.type_name)
  1337. if handler is None:
  1338. raise ValueError(f"Unknown object type: {obj.type_name.decode()}")
  1339. handler(repo, obj, decode, outstream)
  1340. def print_name_status(changes: Iterator[TreeChange]) -> Iterator[str]:
  1341. """Print a simple status summary, listing changed files."""
  1342. for change in changes:
  1343. if not change:
  1344. continue
  1345. if isinstance(change, list):
  1346. change = change[0]
  1347. if change.type == CHANGE_ADD:
  1348. assert change.new is not None
  1349. path1 = change.new.path
  1350. assert path1 is not None
  1351. path2 = b""
  1352. kind = "A"
  1353. elif change.type == CHANGE_DELETE:
  1354. assert change.old is not None
  1355. path1 = change.old.path
  1356. assert path1 is not None
  1357. path2 = b""
  1358. kind = "D"
  1359. elif change.type == CHANGE_MODIFY:
  1360. assert change.new is not None
  1361. path1 = change.new.path
  1362. assert path1 is not None
  1363. path2 = b""
  1364. kind = "M"
  1365. elif change.type in RENAME_CHANGE_TYPES:
  1366. assert change.old is not None and change.new is not None
  1367. path1 = change.old.path
  1368. assert path1 is not None
  1369. path2_opt = change.new.path
  1370. assert path2_opt is not None
  1371. path2 = path2_opt
  1372. if change.type == CHANGE_RENAME:
  1373. kind = "R"
  1374. elif change.type == CHANGE_COPY:
  1375. kind = "C"
  1376. path1_str = (
  1377. path1.decode("utf-8", errors="replace")
  1378. if isinstance(path1, bytes)
  1379. else path1
  1380. )
  1381. path2_str = (
  1382. path2.decode("utf-8", errors="replace")
  1383. if isinstance(path2, bytes)
  1384. else path2
  1385. )
  1386. yield f"{kind:<8}{path1_str:<20}{path2_str:<20}"
  1387. def log(
  1388. repo: RepoPath = ".",
  1389. paths: Optional[Sequence[Union[str, bytes]]] = None,
  1390. outstream: TextIO = sys.stdout,
  1391. max_entries: Optional[int] = None,
  1392. reverse: bool = False,
  1393. name_status: bool = False,
  1394. ) -> None:
  1395. """Write commit logs.
  1396. Args:
  1397. repo: Path to repository
  1398. paths: Optional set of specific paths to print entries for
  1399. outstream: Stream to write log output to
  1400. reverse: Reverse order in which entries are printed
  1401. name_status: Print name status
  1402. max_entries: Optional maximum number of entries to display
  1403. """
  1404. with open_repo_closing(repo) as r:
  1405. try:
  1406. include = [r.head()]
  1407. except KeyError:
  1408. include = []
  1409. # Convert paths to bytes if needed
  1410. paths_bytes = None
  1411. if paths:
  1412. paths_bytes = [p.encode() if isinstance(p, str) else p for p in paths]
  1413. walker = r.get_walker(
  1414. include=include, max_entries=max_entries, paths=paths_bytes, reverse=reverse
  1415. )
  1416. for entry in walker:
  1417. def decode_wrapper(x: bytes) -> str:
  1418. return commit_decode(entry.commit, x)
  1419. print_commit(entry.commit, decode_wrapper, outstream)
  1420. if name_status:
  1421. outstream.writelines(
  1422. [
  1423. line + "\n"
  1424. for line in print_name_status(
  1425. cast(Iterator[TreeChange], entry.changes())
  1426. )
  1427. ]
  1428. )
  1429. # TODO(jelmer): better default for encoding?
  1430. def show(
  1431. repo: RepoPath = ".",
  1432. objects: Optional[Sequence[Union[str, bytes]]] = None,
  1433. outstream: TextIO = sys.stdout,
  1434. default_encoding: str = DEFAULT_ENCODING,
  1435. ) -> None:
  1436. """Print the changes in a commit.
  1437. Args:
  1438. repo: Path to repository
  1439. objects: Objects to show (defaults to [HEAD])
  1440. outstream: Stream to write to
  1441. default_encoding: Default encoding to use if none is set in the
  1442. commit
  1443. """
  1444. if objects is None:
  1445. objects = ["HEAD"]
  1446. if isinstance(objects, (str, bytes)):
  1447. objects = [objects]
  1448. with open_repo_closing(repo) as r:
  1449. for objectish in objects:
  1450. o = parse_object(r, objectish)
  1451. if isinstance(o, Commit):
  1452. def decode(x: bytes) -> str:
  1453. return commit_decode(o, x, default_encoding)
  1454. else:
  1455. def decode(x: bytes) -> str:
  1456. return x.decode(default_encoding)
  1457. assert isinstance(o, (Tree, Blob, Commit, Tag))
  1458. show_object(r, o, decode, outstream)
  1459. def diff_tree(
  1460. repo: RepoPath,
  1461. old_tree: Union[str, bytes, Tree],
  1462. new_tree: Union[str, bytes, Tree],
  1463. outstream: BinaryIO = default_bytes_out_stream,
  1464. ) -> None:
  1465. """Compares the content and mode of blobs found via two tree objects.
  1466. Args:
  1467. repo: Path to repository
  1468. old_tree: Id of old tree
  1469. new_tree: Id of new tree
  1470. outstream: Stream to write to
  1471. """
  1472. with open_repo_closing(repo) as r:
  1473. if isinstance(old_tree, Tree):
  1474. old_tree_id: Optional[bytes] = old_tree.id
  1475. elif isinstance(old_tree, str):
  1476. old_tree_id = old_tree.encode()
  1477. else:
  1478. old_tree_id = old_tree
  1479. if isinstance(new_tree, Tree):
  1480. new_tree_id: Optional[bytes] = new_tree.id
  1481. elif isinstance(new_tree, str):
  1482. new_tree_id = new_tree.encode()
  1483. else:
  1484. new_tree_id = new_tree
  1485. write_tree_diff(outstream, r.object_store, old_tree_id, new_tree_id)
  1486. def diff(
  1487. repo: RepoPath = ".",
  1488. commit: Optional[Union[str, bytes, Commit]] = None,
  1489. commit2: Optional[Union[str, bytes, Commit]] = None,
  1490. staged: bool = False,
  1491. paths: Optional[Sequence[Union[str, bytes]]] = None,
  1492. outstream: BinaryIO = default_bytes_out_stream,
  1493. diff_algorithm: Optional[str] = None,
  1494. ) -> None:
  1495. """Show diff.
  1496. Args:
  1497. repo: Path to repository
  1498. commit: First commit to compare. If staged is True, compare
  1499. index to this commit. If staged is False, compare working tree
  1500. to this commit. If None, defaults to HEAD for staged and index
  1501. for unstaged.
  1502. commit2: Second commit to compare against first commit. If provided,
  1503. show diff between commit and commit2 (ignoring staged flag).
  1504. staged: If True, show staged changes (index vs commit).
  1505. If False, show unstaged changes (working tree vs commit/index).
  1506. Ignored if commit2 is provided.
  1507. paths: Optional list of paths to limit diff
  1508. outstream: Stream to write to
  1509. diff_algorithm: Algorithm to use for diffing ("myers" or "patience"),
  1510. defaults to the underlying function's default if None
  1511. """
  1512. from . import diff as diff_module
  1513. with open_repo_closing(repo) as r:
  1514. # Normalize paths to bytes
  1515. byte_paths: Optional[list[bytes]] = None
  1516. if paths is not None and paths: # Check if paths is not empty
  1517. byte_paths = []
  1518. for p in paths:
  1519. if isinstance(p, str):
  1520. byte_paths.append(p.encode("utf-8"))
  1521. else:
  1522. byte_paths.append(p)
  1523. elif paths == []: # Convert empty list to None
  1524. byte_paths = None
  1525. else:
  1526. byte_paths = None
  1527. # Resolve commit refs to SHAs if provided
  1528. if commit is not None:
  1529. if isinstance(commit, Commit):
  1530. # Already a Commit object
  1531. commit_sha = commit.id
  1532. commit_obj = commit
  1533. else:
  1534. # parse_commit handles both refs and SHAs, and always returns a Commit object
  1535. commit_obj = parse_commit(r, commit)
  1536. commit_sha = commit_obj.id
  1537. else:
  1538. commit_sha = None
  1539. commit_obj = None
  1540. if commit2 is not None:
  1541. # Compare two commits
  1542. if isinstance(commit2, Commit):
  1543. commit2_obj = commit2
  1544. else:
  1545. commit2_obj = parse_commit(r, commit2)
  1546. # Get trees from commits
  1547. old_tree = commit_obj.tree if commit_obj else None
  1548. new_tree = commit2_obj.tree
  1549. # Use tree_changes to get the changes and apply path filtering
  1550. changes = r.object_store.tree_changes(old_tree, new_tree)
  1551. for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
  1552. # Skip if paths are specified and this change doesn't match
  1553. if byte_paths:
  1554. path_to_check = newpath or oldpath
  1555. assert path_to_check is not None
  1556. if not any(
  1557. path_to_check == p or path_to_check.startswith(p + b"/")
  1558. for p in byte_paths
  1559. ):
  1560. continue
  1561. write_object_diff(
  1562. outstream,
  1563. r.object_store,
  1564. (oldpath, oldmode, oldsha),
  1565. (newpath, newmode, newsha),
  1566. diff_algorithm=diff_algorithm,
  1567. )
  1568. elif staged:
  1569. # Show staged changes (index vs commit)
  1570. diff_module.diff_index_to_tree(
  1571. r, outstream, commit_sha, byte_paths, diff_algorithm=diff_algorithm
  1572. )
  1573. elif commit is not None:
  1574. # Compare working tree to a specific commit
  1575. assert (
  1576. commit_sha is not None
  1577. ) # mypy: commit_sha is set when commit is not None
  1578. diff_module.diff_working_tree_to_tree(
  1579. r, outstream, commit_sha, byte_paths, diff_algorithm=diff_algorithm
  1580. )
  1581. else:
  1582. # Compare working tree to index
  1583. diff_module.diff_working_tree_to_index(
  1584. r, outstream, byte_paths, diff_algorithm=diff_algorithm
  1585. )
  1586. def rev_list(
  1587. repo: RepoPath,
  1588. commits: Sequence[Union[str, bytes]],
  1589. outstream: BinaryIO = default_bytes_out_stream,
  1590. ) -> None:
  1591. """Lists commit objects in reverse chronological order.
  1592. Args:
  1593. repo: Path to repository
  1594. commits: Commits over which to iterate
  1595. outstream: Stream to write to
  1596. """
  1597. with open_repo_closing(repo) as r:
  1598. for entry in r.get_walker(
  1599. include=[r[c if isinstance(c, bytes) else c.encode()].id for c in commits]
  1600. ):
  1601. outstream.write(entry.commit.id + b"\n")
  1602. def _canonical_part(url: str) -> str:
  1603. name = url.rsplit("/", 1)[-1]
  1604. if name.endswith(".git"):
  1605. name = name[:-4]
  1606. return name
  1607. def submodule_add(
  1608. repo: Union[str, os.PathLike[str], Repo],
  1609. url: str,
  1610. path: Optional[Union[str, os.PathLike[str]]] = None,
  1611. name: Optional[str] = None,
  1612. ) -> None:
  1613. """Add a new submodule.
  1614. Args:
  1615. repo: Path to repository
  1616. url: URL of repository to add as submodule
  1617. path: Path where submodule should live
  1618. name: Name for the submodule
  1619. """
  1620. with open_repo_closing(repo) as r:
  1621. if path is None:
  1622. path = os.path.relpath(_canonical_part(url), r.path)
  1623. if name is None:
  1624. name = os.fsdecode(path) if path is not None else None
  1625. if name is None:
  1626. raise Error("Submodule name must be specified or derivable from path")
  1627. # TODO(jelmer): Move this logic to dulwich.submodule
  1628. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1629. try:
  1630. config = ConfigFile.from_path(gitmodules_path)
  1631. except FileNotFoundError:
  1632. config = ConfigFile()
  1633. config.path = gitmodules_path
  1634. config.set(("submodule", name), "url", url)
  1635. config.set(("submodule", name), "path", os.fsdecode(path))
  1636. config.write_to_path()
  1637. def submodule_init(repo: Union[str, os.PathLike[str], Repo]) -> None:
  1638. """Initialize submodules.
  1639. Args:
  1640. repo: Path to repository
  1641. """
  1642. with open_repo_closing(repo) as r:
  1643. config = r.get_config()
  1644. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1645. for path, url, name in read_submodules(gitmodules_path):
  1646. config.set((b"submodule", name), b"active", True)
  1647. config.set((b"submodule", name), b"url", url)
  1648. config.write_to_path()
  1649. def submodule_list(repo: RepoPath) -> Iterator[tuple[str, str]]:
  1650. """List submodules.
  1651. Args:
  1652. repo: Path to repository
  1653. """
  1654. from .submodule import iter_cached_submodules
  1655. with open_repo_closing(repo) as r:
  1656. head_commit = r[r.head()]
  1657. assert isinstance(head_commit, Commit)
  1658. for path, sha in iter_cached_submodules(r.object_store, head_commit.tree):
  1659. yield path.decode(DEFAULT_ENCODING), sha.decode(DEFAULT_ENCODING)
  1660. def submodule_update(
  1661. repo: Union[str, os.PathLike[str], Repo],
  1662. paths: Optional[Sequence[Union[str, bytes, os.PathLike[str]]]] = None,
  1663. init: bool = False,
  1664. force: bool = False,
  1665. errstream: Optional[BinaryIO] = None,
  1666. ) -> None:
  1667. """Update submodules.
  1668. Args:
  1669. repo: Path to repository
  1670. paths: Optional list of specific submodule paths to update. If None, updates all.
  1671. init: If True, initialize submodules first
  1672. force: Force update even if local changes exist
  1673. errstream: Error stream for error messages
  1674. """
  1675. from .submodule import iter_cached_submodules
  1676. with open_repo_closing(repo) as r:
  1677. if init:
  1678. submodule_init(r)
  1679. config = r.get_config()
  1680. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1681. # Get list of submodules to update
  1682. submodules_to_update = []
  1683. head_commit = r[r.head()]
  1684. assert isinstance(head_commit, Commit)
  1685. for path, sha in iter_cached_submodules(r.object_store, head_commit.tree):
  1686. path_str = (
  1687. path.decode(DEFAULT_ENCODING) if isinstance(path, bytes) else path
  1688. )
  1689. if paths is None or path_str in paths:
  1690. submodules_to_update.append((path, sha))
  1691. # Read submodule configuration
  1692. for path, target_sha in submodules_to_update:
  1693. path_str = (
  1694. path.decode(DEFAULT_ENCODING) if isinstance(path, bytes) else path
  1695. )
  1696. # Find the submodule name from .gitmodules
  1697. submodule_name: Optional[bytes] = None
  1698. for sm_path, sm_url, sm_name in read_submodules(gitmodules_path):
  1699. if sm_path == path:
  1700. submodule_name = sm_name
  1701. break
  1702. if not submodule_name:
  1703. continue
  1704. # Get the URL from config
  1705. section = (
  1706. b"submodule",
  1707. submodule_name
  1708. if isinstance(submodule_name, bytes)
  1709. else submodule_name.encode(),
  1710. )
  1711. try:
  1712. url_value = config.get(section, b"url")
  1713. if isinstance(url_value, bytes):
  1714. url = url_value.decode(DEFAULT_ENCODING)
  1715. else:
  1716. url = url_value
  1717. except KeyError:
  1718. # URL not in config, skip this submodule
  1719. continue
  1720. # Get or create the submodule repository paths
  1721. submodule_path = os.path.join(r.path, path_str)
  1722. submodule_git_dir = os.path.join(r.path, ".git", "modules", path_str)
  1723. # Clone or fetch the submodule
  1724. if not os.path.exists(submodule_git_dir):
  1725. # Clone the submodule as bare repository
  1726. os.makedirs(os.path.dirname(submodule_git_dir), exist_ok=True)
  1727. # Clone to the git directory
  1728. sub_repo = clone(url, submodule_git_dir, bare=True, checkout=False)
  1729. sub_repo.close()
  1730. # Create the submodule directory if it doesn't exist
  1731. if not os.path.exists(submodule_path):
  1732. os.makedirs(submodule_path)
  1733. # Create .git file in the submodule directory
  1734. depth = path_str.count("/") + 1
  1735. relative_git_dir = "../" * depth + ".git/modules/" + path_str
  1736. git_file_path = os.path.join(submodule_path, ".git")
  1737. with open(git_file_path, "w") as f:
  1738. f.write(f"gitdir: {relative_git_dir}\n")
  1739. # Set up working directory configuration
  1740. with open_repo_closing(submodule_git_dir) as sub_repo:
  1741. sub_config = sub_repo.get_config()
  1742. sub_config.set(
  1743. (b"core",),
  1744. b"worktree",
  1745. os.path.abspath(submodule_path).encode(),
  1746. )
  1747. sub_config.write_to_path()
  1748. # Checkout the target commit
  1749. sub_repo.refs[b"HEAD"] = target_sha
  1750. # Build the index and checkout files
  1751. tree = sub_repo[target_sha]
  1752. if hasattr(tree, "tree"): # If it's a commit, get the tree
  1753. tree_id = tree.tree
  1754. else:
  1755. tree_id = target_sha
  1756. build_index_from_tree(
  1757. submodule_path,
  1758. sub_repo.index_path(),
  1759. sub_repo.object_store,
  1760. tree_id,
  1761. )
  1762. else:
  1763. # Fetch and checkout in existing submodule
  1764. with open_repo_closing(submodule_git_dir) as sub_repo:
  1765. # Fetch from remote
  1766. client, path_segments = get_transport_and_path(url)
  1767. client.fetch(path_segments.encode(), sub_repo)
  1768. # Update to the target commit
  1769. sub_repo.refs[b"HEAD"] = target_sha
  1770. # Reset the working directory
  1771. reset(sub_repo, "hard", target_sha)
  1772. def tag_create(
  1773. repo: RepoPath,
  1774. tag: Union[str, bytes],
  1775. author: Optional[Union[str, bytes]] = None,
  1776. message: Optional[Union[str, bytes]] = None,
  1777. annotated: bool = False,
  1778. objectish: Union[str, bytes] = "HEAD",
  1779. tag_time: Optional[int] = None,
  1780. tag_timezone: Optional[int] = None,
  1781. sign: Optional[bool] = None,
  1782. encoding: str = DEFAULT_ENCODING,
  1783. ) -> None:
  1784. """Creates a tag in git via dulwich calls.
  1785. Args:
  1786. repo: Path to repository
  1787. tag: tag string
  1788. author: tag author (optional, if annotated is set)
  1789. message: tag message (optional)
  1790. annotated: whether to create an annotated tag
  1791. objectish: object the tag should point at, defaults to HEAD
  1792. tag_time: Optional time for annotated tag
  1793. tag_timezone: Optional timezone for annotated tag
  1794. sign: GPG Sign the tag (bool, defaults to False,
  1795. pass True to use default GPG key,
  1796. pass a str containing Key ID to use a specific GPG key)
  1797. encoding: Encoding to use for tag messages
  1798. """
  1799. with open_repo_closing(repo) as r:
  1800. object = parse_object(r, objectish)
  1801. if isinstance(tag, str):
  1802. tag = tag.encode(encoding)
  1803. if annotated:
  1804. # Create the tag object
  1805. tag_obj = Tag()
  1806. if author is None:
  1807. author = get_user_identity(r.get_config_stack())
  1808. elif isinstance(author, str):
  1809. author = author.encode(encoding)
  1810. else:
  1811. assert isinstance(author, bytes)
  1812. tag_obj.tagger = author
  1813. if isinstance(message, str):
  1814. message = message.encode(encoding)
  1815. elif isinstance(message, bytes):
  1816. pass
  1817. else:
  1818. message = b""
  1819. tag_obj.message = message + "\n".encode(encoding)
  1820. tag_obj.name = tag
  1821. tag_obj.object = (type(object), object.id)
  1822. if tag_time is None:
  1823. tag_time = int(time.time())
  1824. tag_obj.tag_time = tag_time
  1825. if tag_timezone is None:
  1826. tag_timezone = get_user_timezones()[1]
  1827. elif isinstance(tag_timezone, str):
  1828. tag_timezone = parse_timezone(tag_timezone.encode())
  1829. tag_obj.tag_timezone = tag_timezone
  1830. # Check if we should sign the tag
  1831. config = r.get_config_stack()
  1832. if sign is None:
  1833. # Check tag.gpgSign configuration when sign is not explicitly set
  1834. try:
  1835. should_sign = config.get_boolean(
  1836. (b"tag",), b"gpgsign", default=False
  1837. )
  1838. except KeyError:
  1839. should_sign = False # Default to not signing if no config
  1840. else:
  1841. should_sign = sign
  1842. # Get the signing key from config if signing is enabled
  1843. keyid = None
  1844. if should_sign:
  1845. try:
  1846. keyid_bytes = config.get((b"user",), b"signingkey")
  1847. keyid = keyid_bytes.decode() if keyid_bytes else None
  1848. except KeyError:
  1849. keyid = None
  1850. tag_obj.sign(keyid)
  1851. r.object_store.add_object(tag_obj)
  1852. tag_id = tag_obj.id
  1853. else:
  1854. tag_id = object.id
  1855. r.refs[_make_tag_ref(tag)] = tag_id
  1856. def verify_commit(
  1857. repo: RepoPath,
  1858. committish: Union[str, bytes] = "HEAD",
  1859. keyids: Optional[list[str]] = None,
  1860. ) -> None:
  1861. """Verify GPG signature on a commit.
  1862. Args:
  1863. repo: Path to repository
  1864. committish: Commit to verify (defaults to HEAD)
  1865. keyids: Optional list of trusted key IDs. If provided, the commit
  1866. must be signed by one of these keys. If not provided, just verifies
  1867. that the commit has a valid signature.
  1868. Raises:
  1869. gpg.errors.BadSignatures: if GPG signature verification fails
  1870. gpg.errors.MissingSignatures: if commit was not signed by a key
  1871. specified in keyids
  1872. """
  1873. with open_repo_closing(repo) as r:
  1874. commit = parse_commit(r, committish)
  1875. commit.verify(keyids)
  1876. def verify_tag(
  1877. repo: RepoPath,
  1878. tagname: Union[str, bytes],
  1879. keyids: Optional[list[str]] = None,
  1880. ) -> None:
  1881. """Verify GPG signature on a tag.
  1882. Args:
  1883. repo: Path to repository
  1884. tagname: Name of tag to verify
  1885. keyids: Optional list of trusted key IDs. If provided, the tag
  1886. must be signed by one of these keys. If not provided, just verifies
  1887. that the tag has a valid signature.
  1888. Raises:
  1889. gpg.errors.BadSignatures: if GPG signature verification fails
  1890. gpg.errors.MissingSignatures: if tag was not signed by a key
  1891. specified in keyids
  1892. """
  1893. with open_repo_closing(repo) as r:
  1894. if isinstance(tagname, str):
  1895. tagname = tagname.encode()
  1896. tag_ref = _make_tag_ref(tagname)
  1897. tag_id = r.refs[tag_ref]
  1898. tag_obj = r[tag_id]
  1899. if not isinstance(tag_obj, Tag):
  1900. raise Error(f"{tagname!r} does not point to a tag object")
  1901. tag_obj.verify(keyids)
  1902. def tag_list(repo: RepoPath, outstream: TextIO = sys.stdout) -> list[bytes]:
  1903. """List all tags.
  1904. Args:
  1905. repo: Path to repository
  1906. outstream: Stream to write tags to
  1907. """
  1908. with open_repo_closing(repo) as r:
  1909. tags = sorted(r.refs.as_dict(b"refs/tags"))
  1910. return tags
  1911. def tag_delete(repo: RepoPath, name: Union[str, bytes]) -> None:
  1912. """Remove a tag.
  1913. Args:
  1914. repo: Path to repository
  1915. name: Name of tag to remove
  1916. """
  1917. with open_repo_closing(repo) as r:
  1918. if isinstance(name, bytes):
  1919. names = [name]
  1920. elif isinstance(name, list):
  1921. names = name
  1922. else:
  1923. raise Error(f"Unexpected tag name type {name!r}")
  1924. for name in names:
  1925. del r.refs[_make_tag_ref(name)]
  1926. def _make_notes_ref(name: bytes) -> bytes:
  1927. """Make a notes ref name."""
  1928. if name.startswith(b"refs/notes/"):
  1929. return name
  1930. return LOCAL_NOTES_PREFIX + name
  1931. def notes_add(
  1932. repo: RepoPath,
  1933. object_sha: bytes,
  1934. note: bytes,
  1935. ref: bytes = b"commits",
  1936. author: Optional[bytes] = None,
  1937. committer: Optional[bytes] = None,
  1938. message: Optional[bytes] = None,
  1939. ) -> bytes:
  1940. """Add or update a note for an object.
  1941. Args:
  1942. repo: Path to repository
  1943. object_sha: SHA of the object to annotate
  1944. note: Note content
  1945. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  1946. author: Author identity (defaults to committer)
  1947. committer: Committer identity (defaults to config)
  1948. message: Commit message for the notes update
  1949. Returns:
  1950. SHA of the new notes commit
  1951. """
  1952. with open_repo_closing(repo) as r:
  1953. # Parse the object to get its SHA
  1954. obj = parse_object(r, object_sha)
  1955. object_sha = obj.id
  1956. if isinstance(note, str):
  1957. note = note.encode(DEFAULT_ENCODING)
  1958. if isinstance(ref, str):
  1959. ref = ref.encode(DEFAULT_ENCODING)
  1960. notes_ref = _make_notes_ref(ref)
  1961. config = r.get_config_stack()
  1962. return r.notes.set_note(
  1963. object_sha,
  1964. note,
  1965. notes_ref,
  1966. author=author,
  1967. committer=committer,
  1968. message=message,
  1969. config=config,
  1970. )
  1971. def notes_remove(
  1972. repo: RepoPath,
  1973. object_sha: bytes,
  1974. ref: bytes = b"commits",
  1975. author: Optional[bytes] = None,
  1976. committer: Optional[bytes] = None,
  1977. message: Optional[bytes] = None,
  1978. ) -> Optional[bytes]:
  1979. """Remove a note for an object.
  1980. Args:
  1981. repo: Path to repository
  1982. object_sha: SHA of the object to remove notes from
  1983. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  1984. author: Author identity (defaults to committer)
  1985. committer: Committer identity (defaults to config)
  1986. message: Commit message for the notes removal
  1987. Returns:
  1988. SHA of the new notes commit, or None if no note existed
  1989. """
  1990. with open_repo_closing(repo) as r:
  1991. # Parse the object to get its SHA
  1992. obj = parse_object(r, object_sha)
  1993. object_sha = obj.id
  1994. if isinstance(ref, str):
  1995. ref = ref.encode(DEFAULT_ENCODING)
  1996. notes_ref = _make_notes_ref(ref)
  1997. config = r.get_config_stack()
  1998. return r.notes.remove_note(
  1999. object_sha,
  2000. notes_ref,
  2001. author=author,
  2002. committer=committer,
  2003. message=message,
  2004. config=config,
  2005. )
  2006. def notes_show(
  2007. repo: Union[str, os.PathLike[str], Repo], object_sha: bytes, ref: bytes = b"commits"
  2008. ) -> Optional[bytes]:
  2009. """Show the note for an object.
  2010. Args:
  2011. repo: Path to repository
  2012. object_sha: SHA of the object
  2013. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  2014. Returns:
  2015. Note content as bytes, or None if no note exists
  2016. """
  2017. with open_repo_closing(repo) as r:
  2018. # Parse the object to get its SHA
  2019. obj = parse_object(r, object_sha)
  2020. object_sha = obj.id
  2021. if isinstance(ref, str):
  2022. ref = ref.encode(DEFAULT_ENCODING)
  2023. notes_ref = _make_notes_ref(ref)
  2024. config = r.get_config_stack()
  2025. return r.notes.get_note(object_sha, notes_ref, config=config)
  2026. def notes_list(repo: RepoPath, ref: bytes = b"commits") -> list[tuple[bytes, bytes]]:
  2027. """List all notes in a notes ref.
  2028. Args:
  2029. repo: Path to repository
  2030. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  2031. Returns:
  2032. List of tuples of (object_sha, note_content)
  2033. """
  2034. with open_repo_closing(repo) as r:
  2035. if isinstance(ref, str):
  2036. ref = ref.encode(DEFAULT_ENCODING)
  2037. notes_ref = _make_notes_ref(ref)
  2038. config = r.get_config_stack()
  2039. return r.notes.list_notes(notes_ref, config=config)
  2040. def reset(
  2041. repo: Union[str, os.PathLike[str], Repo],
  2042. mode: str,
  2043. treeish: Union[str, bytes, Commit, Tree, Tag] = "HEAD",
  2044. ) -> None:
  2045. """Reset current HEAD to the specified state.
  2046. Args:
  2047. repo: Path to repository
  2048. mode: Mode ("hard", "soft", "mixed")
  2049. treeish: Treeish to reset to
  2050. """
  2051. with open_repo_closing(repo) as r:
  2052. # Parse the target tree
  2053. tree = parse_tree(r, treeish)
  2054. # Only parse as commit if treeish is not a Tree object
  2055. if isinstance(treeish, Tree):
  2056. # For Tree objects, we can't determine the commit, skip updating HEAD
  2057. target_commit = None
  2058. else:
  2059. target_commit = parse_commit(r, treeish)
  2060. # Update HEAD to point to the target commit
  2061. if target_commit is not None:
  2062. r.refs[b"HEAD"] = target_commit.id
  2063. if mode == "soft":
  2064. # Soft reset: only update HEAD, leave index and working tree unchanged
  2065. return
  2066. elif mode == "mixed":
  2067. # Mixed reset: update HEAD and index, but leave working tree unchanged
  2068. from .object_store import iter_tree_contents
  2069. # Open the index
  2070. index = r.open_index()
  2071. # Clear the current index
  2072. index.clear()
  2073. # Populate index from the target tree
  2074. for entry in iter_tree_contents(r.object_store, tree.id):
  2075. # Create an IndexEntry from the tree entry
  2076. # Use zeros for filesystem-specific fields since we're not touching the working tree
  2077. assert (
  2078. entry.mode is not None
  2079. and entry.sha is not None
  2080. and entry.path is not None
  2081. )
  2082. index_entry = IndexEntry(
  2083. ctime=(0, 0),
  2084. mtime=(0, 0),
  2085. dev=0,
  2086. ino=0,
  2087. mode=entry.mode,
  2088. uid=0,
  2089. gid=0,
  2090. size=0, # Size will be 0 since we're not reading from disk
  2091. sha=entry.sha,
  2092. flags=0,
  2093. )
  2094. index[entry.path] = index_entry
  2095. # Write the updated index
  2096. index.write()
  2097. elif mode == "hard":
  2098. # Hard reset: update HEAD, index, and working tree
  2099. # Get configuration for working directory update
  2100. config = r.get_config()
  2101. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  2102. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  2103. validate_path_element = validate_path_element_ntfs
  2104. elif config.get_boolean(
  2105. b"core", b"core.protectHFS", sys.platform == "darwin"
  2106. ):
  2107. validate_path_element = validate_path_element_hfs
  2108. else:
  2109. validate_path_element = validate_path_element_default
  2110. if config.get_boolean(b"core", b"symlinks", True):
  2111. def symlink_wrapper(
  2112. source: Union[str, bytes, os.PathLike[str]],
  2113. target: Union[str, bytes, os.PathLike[str]],
  2114. ) -> None:
  2115. symlink(source, target) # type: ignore[arg-type,unused-ignore]
  2116. symlink_fn = symlink_wrapper
  2117. else:
  2118. def symlink_fallback(
  2119. source: Union[str, bytes, os.PathLike[str]],
  2120. target: Union[str, bytes, os.PathLike[str]],
  2121. ) -> None:
  2122. mode = "w" + ("b" if isinstance(source, bytes) else "")
  2123. with open(target, mode) as f:
  2124. f.write(source)
  2125. symlink_fn = symlink_fallback
  2126. # Update working tree and index
  2127. blob_normalizer = r.get_blob_normalizer()
  2128. # For reset --hard, use current index tree as old tree to get proper deletions
  2129. index = r.open_index()
  2130. if len(index) > 0:
  2131. index_tree_id = index.commit(r.object_store)
  2132. else:
  2133. # Empty index
  2134. index_tree_id = None
  2135. changes = tree_changes(
  2136. r.object_store, index_tree_id, tree.id, want_unchanged=True
  2137. )
  2138. update_working_tree(
  2139. r,
  2140. index_tree_id,
  2141. tree.id,
  2142. change_iterator=changes,
  2143. honor_filemode=honor_filemode,
  2144. validate_path_element=validate_path_element,
  2145. symlink_fn=symlink_fn,
  2146. force_remove_untracked=True,
  2147. blob_normalizer=blob_normalizer,
  2148. allow_overwrite_modified=True, # Allow overwriting modified files
  2149. )
  2150. else:
  2151. raise Error(f"Invalid reset mode: {mode}")
  2152. def get_remote_repo(
  2153. repo: Repo, remote_location: Optional[Union[str, bytes]] = None
  2154. ) -> tuple[Optional[str], str]:
  2155. """Get the remote repository information.
  2156. Args:
  2157. repo: Local repository object
  2158. remote_location: Optional remote name or URL; defaults to branch remote
  2159. Returns:
  2160. Tuple of (remote_name, remote_url) where remote_name may be None
  2161. if remote_location is a URL rather than a configured remote
  2162. """
  2163. config = repo.get_config()
  2164. if remote_location is None:
  2165. remote_location = get_branch_remote(repo)
  2166. if isinstance(remote_location, str):
  2167. encoded_location = remote_location.encode()
  2168. else:
  2169. encoded_location = remote_location
  2170. section = (b"remote", encoded_location)
  2171. remote_name: Optional[str] = None
  2172. if config.has_section(section):
  2173. remote_name = encoded_location.decode()
  2174. encoded_location = config.get(section, "url")
  2175. else:
  2176. remote_name = None
  2177. return (remote_name, encoded_location.decode())
  2178. def push(
  2179. repo: RepoPath,
  2180. remote_location: Optional[Union[str, bytes]] = None,
  2181. refspecs: Optional[Union[Union[str, bytes], Sequence[Union[str, bytes]]]] = None,
  2182. outstream: BinaryIO = default_bytes_out_stream,
  2183. errstream: Union[BinaryIO, RawIOBase] = default_bytes_err_stream,
  2184. force: bool = False,
  2185. **kwargs: object,
  2186. ) -> SendPackResult:
  2187. """Remote push with dulwich via dulwich.client.
  2188. Args:
  2189. repo: Path to repository
  2190. remote_location: Location of the remote
  2191. refspecs: Refs to push to remote
  2192. outstream: A stream file to write output
  2193. errstream: A stream file to write errors
  2194. force: Force overwriting refs
  2195. **kwargs: Additional keyword arguments for the client
  2196. """
  2197. # Open the repo
  2198. with open_repo_closing(repo) as r:
  2199. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  2200. # Check if mirror mode is enabled
  2201. mirror_mode = False
  2202. if remote_name:
  2203. try:
  2204. mirror_mode_val = r.get_config_stack().get_boolean(
  2205. (b"remote", remote_name.encode()), b"mirror"
  2206. )
  2207. if mirror_mode_val is not None:
  2208. mirror_mode = mirror_mode_val
  2209. except KeyError:
  2210. pass
  2211. if mirror_mode:
  2212. # Mirror mode: push all refs and delete non-existent ones
  2213. refspecs = []
  2214. for ref in r.refs.keys():
  2215. # Push all refs to the same name on remote
  2216. refspecs.append(ref + b":" + ref)
  2217. elif refspecs is None:
  2218. refspecs = [active_branch(r)]
  2219. # Normalize refspecs to bytes
  2220. if isinstance(refspecs, str):
  2221. refspecs_bytes: Union[bytes, list[bytes]] = refspecs.encode()
  2222. elif isinstance(refspecs, bytes):
  2223. refspecs_bytes = refspecs
  2224. else:
  2225. refspecs_bytes = []
  2226. for spec in refspecs:
  2227. if isinstance(spec, str):
  2228. refspecs_bytes.append(spec.encode())
  2229. else:
  2230. refspecs_bytes.append(spec)
  2231. # Get the client and path
  2232. client, path = get_transport_and_path(
  2233. remote_location,
  2234. config=r.get_config_stack(),
  2235. **kwargs, # type: ignore[arg-type]
  2236. )
  2237. selected_refs = []
  2238. remote_changed_refs: dict[bytes, Optional[bytes]] = {}
  2239. def update_refs(refs: dict[bytes, bytes]) -> dict[bytes, bytes]:
  2240. from .refs import DictRefsContainer
  2241. remote_refs = DictRefsContainer(refs)
  2242. selected_refs.extend(
  2243. parse_reftuples(r.refs, remote_refs, refspecs_bytes, force=force)
  2244. )
  2245. new_refs = {}
  2246. # In mirror mode, delete remote refs that don't exist locally
  2247. if mirror_mode:
  2248. local_refs = set(r.refs.keys())
  2249. for remote_ref in refs.keys():
  2250. if remote_ref not in local_refs:
  2251. new_refs[remote_ref] = ZERO_SHA
  2252. remote_changed_refs[remote_ref] = None
  2253. # TODO: Handle selected_refs == {None: None}
  2254. for lh, rh, force_ref in selected_refs:
  2255. if lh is None:
  2256. assert rh is not None
  2257. new_refs[rh] = ZERO_SHA
  2258. remote_changed_refs[rh] = None
  2259. else:
  2260. try:
  2261. localsha = r.refs[lh]
  2262. except KeyError as exc:
  2263. raise Error(
  2264. f"No valid ref {lh.decode() if isinstance(lh, bytes) else lh} in local repository"
  2265. ) from exc
  2266. assert rh is not None
  2267. if not force_ref and rh in refs:
  2268. check_diverged(r, refs[rh], localsha)
  2269. new_refs[rh] = localsha
  2270. remote_changed_refs[rh] = localsha
  2271. return new_refs
  2272. err_encoding = getattr(errstream, "encoding", None) or DEFAULT_ENCODING
  2273. remote_location = client.get_url(path)
  2274. try:
  2275. def generate_pack_data_wrapper(
  2276. have: AbstractSet[bytes],
  2277. want: AbstractSet[bytes],
  2278. ofs_delta: bool = False,
  2279. ) -> tuple[int, Iterator[UnpackedObject]]:
  2280. # Wrap to match the expected signature
  2281. # Convert AbstractSet to set since generate_pack_data expects set
  2282. return r.generate_pack_data(
  2283. set(have), set(want), progress=None, ofs_delta=ofs_delta
  2284. )
  2285. result = client.send_pack(
  2286. path.encode(),
  2287. update_refs,
  2288. generate_pack_data=generate_pack_data_wrapper,
  2289. progress=lambda data: (errstream.write(data), None)[1],
  2290. )
  2291. except SendPackError as exc:
  2292. raise Error(
  2293. "Push to " + remote_location + " failed -> " + exc.args[0].decode(),
  2294. ) from exc
  2295. else:
  2296. errstream.write(
  2297. b"Push to " + remote_location.encode(err_encoding) + b" successful.\n"
  2298. )
  2299. for ref, error in (result.ref_status or {}).items():
  2300. if error is not None:
  2301. errstream.write(
  2302. b"Push of ref %s failed: %s\n" % (ref, error.encode(err_encoding))
  2303. )
  2304. else:
  2305. errstream.write(b"Ref %s updated\n" % ref)
  2306. if remote_name is not None:
  2307. _import_remote_refs(r.refs, remote_name, remote_changed_refs)
  2308. return result
  2309. # Trigger auto GC if needed
  2310. from .gc import maybe_auto_gc
  2311. with open_repo_closing(repo) as r:
  2312. maybe_auto_gc(r)
  2313. def pull(
  2314. repo: RepoPath,
  2315. remote_location: Optional[Union[str, bytes]] = None,
  2316. refspecs: Optional[Union[Union[str, bytes], Sequence[Union[str, bytes]]]] = None,
  2317. outstream: BinaryIO = default_bytes_out_stream,
  2318. errstream: Union[BinaryIO, RawIOBase] = default_bytes_err_stream,
  2319. fast_forward: bool = True,
  2320. ff_only: bool = False,
  2321. force: bool = False,
  2322. filter_spec: Optional[str] = None,
  2323. protocol_version: Optional[int] = None,
  2324. **kwargs: object,
  2325. ) -> None:
  2326. """Pull from remote via dulwich.client.
  2327. Args:
  2328. repo: Path to repository
  2329. remote_location: Location of the remote
  2330. refspecs: refspecs to fetch. Can be a bytestring, a string, or a list of
  2331. bytestring/string.
  2332. outstream: A stream file to write to output
  2333. errstream: A stream file to write to errors
  2334. fast_forward: If True, raise an exception when fast-forward is not possible
  2335. ff_only: If True, only allow fast-forward merges. Raises DivergedBranches
  2336. when branches have diverged rather than performing a merge.
  2337. force: If True, allow overwriting local changes in the working tree.
  2338. If False, pull will abort if it would overwrite uncommitted changes.
  2339. filter_spec: A git-rev-list-style object filter spec, as an ASCII string.
  2340. Only used if the server supports the Git protocol-v2 'filter'
  2341. feature, and ignored otherwise.
  2342. protocol_version: desired Git protocol version. By default the highest
  2343. mutually supported protocol version will be used
  2344. **kwargs: Additional keyword arguments for the client
  2345. """
  2346. # Open the repo
  2347. with open_repo_closing(repo) as r:
  2348. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  2349. selected_refs = []
  2350. if refspecs is None:
  2351. refspecs_normalized: Union[bytes, list[bytes]] = [b"HEAD"]
  2352. elif isinstance(refspecs, str):
  2353. refspecs_normalized = refspecs.encode()
  2354. elif isinstance(refspecs, bytes):
  2355. refspecs_normalized = refspecs
  2356. else:
  2357. refspecs_normalized = []
  2358. for spec in refspecs:
  2359. if isinstance(spec, str):
  2360. refspecs_normalized.append(spec.encode())
  2361. else:
  2362. refspecs_normalized.append(spec)
  2363. def determine_wants(
  2364. remote_refs: dict[bytes, bytes], depth: Optional[int] = None
  2365. ) -> list[bytes]:
  2366. from .refs import DictRefsContainer
  2367. remote_refs_container = DictRefsContainer(remote_refs)
  2368. selected_refs.extend(
  2369. parse_reftuples(
  2370. remote_refs_container, r.refs, refspecs_normalized, force=force
  2371. )
  2372. )
  2373. return [
  2374. remote_refs[lh]
  2375. for (lh, rh, force_ref) in selected_refs
  2376. if lh is not None
  2377. and lh in remote_refs
  2378. and remote_refs[lh] not in r.object_store
  2379. ]
  2380. client, path = get_transport_and_path(
  2381. remote_location,
  2382. config=r.get_config_stack(),
  2383. **kwargs, # type: ignore[arg-type]
  2384. )
  2385. if filter_spec:
  2386. filter_spec_bytes: Optional[bytes] = filter_spec.encode("ascii")
  2387. else:
  2388. filter_spec_bytes = None
  2389. def progress(data: bytes) -> None:
  2390. errstream.write(data)
  2391. fetch_result = client.fetch(
  2392. path.encode(),
  2393. r,
  2394. progress=progress,
  2395. determine_wants=determine_wants, # type: ignore[arg-type] # Function matches protocol but mypy can't verify
  2396. filter_spec=filter_spec_bytes,
  2397. protocol_version=protocol_version,
  2398. )
  2399. # Store the old HEAD tree before making changes
  2400. try:
  2401. old_head = r.refs[b"HEAD"]
  2402. old_commit = r[old_head]
  2403. assert isinstance(old_commit, Commit)
  2404. old_tree_id = old_commit.tree
  2405. except KeyError:
  2406. old_tree_id = None
  2407. merged = False
  2408. for lh, rh, force_ref in selected_refs:
  2409. if not force_ref and rh is not None and rh in r.refs:
  2410. try:
  2411. assert lh is not None
  2412. followed_ref = r.refs.follow(rh)[1]
  2413. assert followed_ref is not None
  2414. lh_ref = fetch_result.refs[lh]
  2415. assert lh_ref is not None
  2416. check_diverged(r, followed_ref, lh_ref)
  2417. except DivergedBranches as exc:
  2418. if ff_only or fast_forward:
  2419. raise
  2420. else:
  2421. # Perform merge
  2422. assert lh is not None
  2423. merge_ref = fetch_result.refs[lh]
  2424. assert merge_ref is not None
  2425. _merge_result, conflicts = _do_merge(r, merge_ref)
  2426. if conflicts:
  2427. raise Error(
  2428. f"Merge conflicts occurred: {conflicts}"
  2429. ) from exc
  2430. merged = True
  2431. # Skip updating ref since merge already updated HEAD
  2432. continue
  2433. if rh is not None and lh is not None:
  2434. lh_value = fetch_result.refs[lh]
  2435. if lh_value is not None:
  2436. r.refs[rh] = lh_value
  2437. # Only update HEAD if we didn't perform a merge
  2438. if selected_refs and not merged:
  2439. lh, rh, _ = selected_refs[0]
  2440. if lh is not None:
  2441. ref_value = fetch_result.refs[lh]
  2442. if ref_value is not None:
  2443. r[b"HEAD"] = ref_value
  2444. # Update working tree to match the new HEAD
  2445. # Skip if merge was performed as merge already updates the working tree
  2446. if not merged and old_tree_id is not None:
  2447. head_commit = r[b"HEAD"]
  2448. assert isinstance(head_commit, Commit)
  2449. new_tree_id = head_commit.tree
  2450. blob_normalizer = r.get_blob_normalizer()
  2451. changes = tree_changes(r.object_store, old_tree_id, new_tree_id)
  2452. update_working_tree(
  2453. r,
  2454. old_tree_id,
  2455. new_tree_id,
  2456. change_iterator=changes,
  2457. blob_normalizer=blob_normalizer,
  2458. allow_overwrite_modified=force,
  2459. )
  2460. if remote_name is not None:
  2461. _import_remote_refs(r.refs, remote_name, fetch_result.refs)
  2462. # Trigger auto GC if needed
  2463. from .gc import maybe_auto_gc
  2464. with open_repo_closing(repo) as r:
  2465. maybe_auto_gc(r)
  2466. def status(
  2467. repo: Union[str, os.PathLike[str], Repo] = ".",
  2468. ignored: bool = False,
  2469. untracked_files: str = "normal",
  2470. ) -> GitStatus:
  2471. """Returns staged, unstaged, and untracked changes relative to the HEAD.
  2472. Args:
  2473. repo: Path to repository or repository object
  2474. ignored: Whether to include ignored files in untracked
  2475. untracked_files: How to handle untracked files, defaults to "all":
  2476. "no": do not return untracked files
  2477. "normal": return untracked directories, not their contents
  2478. "all": include all files in untracked directories
  2479. Using untracked_files="no" can be faster than "all" when the worktree
  2480. contains many untracked files/directories.
  2481. Using untracked_files="normal" provides a good balance, only showing
  2482. directories that are entirely untracked without listing all their contents.
  2483. Returns: GitStatus tuple,
  2484. staged - dict with lists of staged paths (diff index/HEAD)
  2485. unstaged - list of unstaged paths (diff index/working-tree)
  2486. untracked - list of untracked, un-ignored & non-.git paths
  2487. """
  2488. with open_repo_closing(repo) as r:
  2489. # 1. Get status of staged
  2490. tracked_changes = get_tree_changes(r)
  2491. # 2. Get status of unstaged
  2492. index = r.open_index()
  2493. normalizer = r.get_blob_normalizer()
  2494. # Create a wrapper that handles the bytes -> Blob conversion
  2495. if normalizer is not None:
  2496. def filter_callback(data: bytes, path: bytes) -> bytes:
  2497. from dulwich.objects import Blob
  2498. blob = Blob()
  2499. blob.data = data
  2500. normalized_blob = normalizer.checkin_normalize(blob, path)
  2501. result_data: bytes = normalized_blob.data
  2502. return result_data
  2503. else:
  2504. filter_callback = None
  2505. # Check if core.preloadIndex is enabled
  2506. config = r.get_config_stack()
  2507. preload_index = config.get_boolean(b"core", b"preloadIndex", False)
  2508. unstaged_changes = list(
  2509. get_unstaged_changes(index, r.path, filter_callback, preload_index)
  2510. )
  2511. untracked_paths = get_untracked_paths(
  2512. r.path,
  2513. r.path,
  2514. index,
  2515. exclude_ignored=not ignored,
  2516. untracked_files=untracked_files,
  2517. )
  2518. if sys.platform == "win32":
  2519. untracked_changes = [
  2520. path.replace(os.path.sep, "/") for path in untracked_paths
  2521. ]
  2522. else:
  2523. untracked_changes = list(untracked_paths)
  2524. return GitStatus(tracked_changes, unstaged_changes, untracked_changes)
  2525. def shortlog(
  2526. repo: Union[str, os.PathLike[str], Repo],
  2527. summary_only: bool = False,
  2528. sort_by_commits: bool = False,
  2529. ) -> list[dict[str, str]]:
  2530. """Summarize commits by author, like git shortlog.
  2531. Args:
  2532. repo: Path to repository or Repo object.
  2533. summary_only: If True, only show counts per author.
  2534. sort_by_commits: If True, sort authors by number of commits.
  2535. Returns:
  2536. A list of dictionaries, each containing:
  2537. - "author": the author's name as a string
  2538. - "messages": all commit messages concatenated into a single string
  2539. """
  2540. with open_repo_closing(repo) as r:
  2541. walker = r.get_walker()
  2542. authors: dict[str, list[str]] = {}
  2543. for entry in walker:
  2544. commit = entry.commit
  2545. author = commit.author.decode(commit.encoding or "utf-8")
  2546. message = commit.message.decode(commit.encoding or "utf-8").strip()
  2547. authors.setdefault(author, []).append(message)
  2548. # Convert messages to single string per author
  2549. items: list[dict[str, str]] = [
  2550. {"author": author, "messages": "\n".join(msgs)}
  2551. for author, msgs in authors.items()
  2552. ]
  2553. if sort_by_commits:
  2554. # Sort by number of commits (lines in messages)
  2555. items.sort(key=lambda x: len(x["messages"].splitlines()), reverse=True)
  2556. return items
  2557. def _walk_working_dir_paths(
  2558. frompath: Union[str, bytes, os.PathLike[str]],
  2559. basepath: Union[str, bytes, os.PathLike[str]],
  2560. prune_dirnames: Optional[Callable[[str, list[str]], list[str]]] = None,
  2561. ) -> Iterator[tuple[Union[str, bytes], bool]]:
  2562. """Get path, is_dir for files in working dir from frompath.
  2563. Args:
  2564. frompath: Path to begin walk
  2565. basepath: Path to compare to
  2566. prune_dirnames: Optional callback to prune dirnames during os.walk
  2567. dirnames will be set to result of prune_dirnames(dirpath, dirnames)
  2568. """
  2569. # Convert paths to strings for os.walk compatibility
  2570. for dirpath, dirnames, filenames in os.walk(frompath): # type: ignore[type-var]
  2571. # Skip .git and below.
  2572. if ".git" in dirnames:
  2573. dirnames.remove(".git")
  2574. if dirpath != basepath:
  2575. continue
  2576. if ".git" in filenames:
  2577. filenames.remove(".git")
  2578. if dirpath != basepath:
  2579. continue
  2580. if dirpath != frompath:
  2581. yield dirpath, True # type: ignore[misc]
  2582. for filename in filenames:
  2583. filepath = os.path.join(dirpath, filename) # type: ignore[call-overload]
  2584. yield filepath, False
  2585. if prune_dirnames:
  2586. dirnames[:] = prune_dirnames(dirpath, dirnames) # type: ignore[arg-type]
  2587. def get_untracked_paths(
  2588. frompath: Union[str, bytes, os.PathLike[str]],
  2589. basepath: Union[str, bytes, os.PathLike[str]],
  2590. index: Index,
  2591. exclude_ignored: bool = False,
  2592. untracked_files: str = "all",
  2593. ) -> Iterator[str]:
  2594. """Get untracked paths.
  2595. Args:
  2596. frompath: Path to walk
  2597. basepath: Path to compare to
  2598. index: Index to check against
  2599. exclude_ignored: Whether to exclude ignored paths
  2600. untracked_files: How to handle untracked files:
  2601. - "no": return an empty list
  2602. - "all": return all files in untracked directories
  2603. - "normal": return untracked directories without listing their contents
  2604. Note: ignored directories will never be walked for performance reasons.
  2605. If exclude_ignored is False, only the path to an ignored directory will
  2606. be yielded, no files inside the directory will be returned
  2607. """
  2608. if untracked_files not in ("no", "all", "normal"):
  2609. raise ValueError("untracked_files must be one of (no, all, normal)")
  2610. if untracked_files == "no":
  2611. return
  2612. # Normalize paths to str
  2613. frompath_str = os.fsdecode(os.fspath(frompath))
  2614. basepath_str = os.fsdecode(os.fspath(basepath))
  2615. with open_repo_closing(basepath_str) as r:
  2616. ignore_manager = IgnoreFilterManager.from_repo(r)
  2617. ignored_dirs = []
  2618. # List to store untracked directories found during traversal
  2619. untracked_dir_list = []
  2620. def directory_has_non_ignored_files(dir_path: str, base_rel_path: str) -> bool:
  2621. """Recursively check if directory contains any non-ignored files."""
  2622. try:
  2623. for entry in os.listdir(dir_path):
  2624. entry_path = os.path.join(dir_path, entry)
  2625. rel_entry = os.path.join(base_rel_path, entry)
  2626. if os.path.isfile(entry_path):
  2627. if ignore_manager.is_ignored(rel_entry) is not True:
  2628. return True
  2629. elif os.path.isdir(entry_path):
  2630. if directory_has_non_ignored_files(entry_path, rel_entry):
  2631. return True
  2632. return False
  2633. except OSError:
  2634. # If we can't read the directory, assume it has non-ignored files
  2635. return True
  2636. def prune_dirnames(dirpath: str, dirnames: list[str]) -> list[str]:
  2637. for i in range(len(dirnames) - 1, -1, -1):
  2638. path = os.path.join(dirpath, dirnames[i])
  2639. ip = os.path.join(os.path.relpath(path, basepath_str), "")
  2640. # Check if directory is ignored
  2641. if ignore_manager.is_ignored(ip) is True:
  2642. if not exclude_ignored:
  2643. ignored_dirs.append(
  2644. os.path.join(os.path.relpath(path, frompath_str), "")
  2645. )
  2646. del dirnames[i]
  2647. continue
  2648. # For "normal" mode, check if the directory is entirely untracked
  2649. if untracked_files == "normal":
  2650. # Convert directory path to tree path for index lookup
  2651. dir_tree_path = path_to_tree_path(basepath_str, path)
  2652. # Check if any file in this directory is tracked
  2653. dir_prefix = dir_tree_path + b"/" if dir_tree_path else b""
  2654. has_tracked_files = any(name.startswith(dir_prefix) for name in index)
  2655. if not has_tracked_files:
  2656. # This directory is entirely untracked
  2657. rel_path_base = os.path.relpath(path, basepath_str)
  2658. rel_path_from = os.path.join(
  2659. os.path.relpath(path, frompath_str), ""
  2660. )
  2661. # If excluding ignored, check if directory contains any non-ignored files
  2662. if exclude_ignored:
  2663. if not directory_has_non_ignored_files(path, rel_path_base):
  2664. # Directory only contains ignored files, skip it
  2665. del dirnames[i]
  2666. continue
  2667. # Check if it should be excluded due to ignore rules
  2668. is_ignored = ignore_manager.is_ignored(rel_path_base)
  2669. if not exclude_ignored or not is_ignored:
  2670. untracked_dir_list.append(rel_path_from)
  2671. del dirnames[i]
  2672. return dirnames
  2673. # For "all" mode, use the original behavior
  2674. if untracked_files == "all":
  2675. for ap, is_dir in _walk_working_dir_paths(
  2676. frompath_str, basepath_str, prune_dirnames=prune_dirnames
  2677. ):
  2678. # frompath_str and basepath_str are both str, so ap must be str
  2679. assert isinstance(ap, str)
  2680. if not is_dir:
  2681. ip = path_to_tree_path(basepath_str, ap)
  2682. if ip not in index:
  2683. if not exclude_ignored or not ignore_manager.is_ignored(
  2684. os.path.relpath(ap, basepath_str)
  2685. ):
  2686. yield os.path.relpath(ap, frompath_str)
  2687. else: # "normal" mode
  2688. # Walk directories, handling both files and directories
  2689. for ap, is_dir in _walk_working_dir_paths(
  2690. frompath_str, basepath_str, prune_dirnames=prune_dirnames
  2691. ):
  2692. # frompath_str and basepath_str are both str, so ap must be str
  2693. assert isinstance(ap, str)
  2694. # This part won't be reached for pruned directories
  2695. if is_dir:
  2696. # Check if this directory is entirely untracked
  2697. dir_tree_path = path_to_tree_path(basepath_str, ap)
  2698. dir_prefix = dir_tree_path + b"/" if dir_tree_path else b""
  2699. has_tracked_files = any(name.startswith(dir_prefix) for name in index)
  2700. if not has_tracked_files:
  2701. if not exclude_ignored or not ignore_manager.is_ignored(
  2702. os.path.relpath(ap, basepath_str)
  2703. ):
  2704. yield os.path.join(os.path.relpath(ap, frompath_str), "")
  2705. else:
  2706. # Check individual files in directories that contain tracked files
  2707. ip = path_to_tree_path(basepath_str, ap)
  2708. if ip not in index:
  2709. if not exclude_ignored or not ignore_manager.is_ignored(
  2710. os.path.relpath(ap, basepath_str)
  2711. ):
  2712. yield os.path.relpath(ap, frompath_str)
  2713. # Yield any untracked directories found during pruning
  2714. yield from untracked_dir_list
  2715. yield from ignored_dirs
  2716. def get_tree_changes(repo: RepoPath) -> dict[str, list[Union[str, bytes]]]:
  2717. """Return add/delete/modify changes to tree by comparing index to HEAD.
  2718. Args:
  2719. repo: repo path or object
  2720. Returns: dict with lists for each type of change
  2721. """
  2722. with open_repo_closing(repo) as r:
  2723. index = r.open_index()
  2724. # Compares the Index to the HEAD & determines changes
  2725. # Iterate through the changes and report add/delete/modify
  2726. # TODO: call out to dulwich.diff_tree somehow.
  2727. tracked_changes: dict[str, list[Union[str, bytes]]] = {
  2728. "add": [],
  2729. "delete": [],
  2730. "modify": [],
  2731. }
  2732. try:
  2733. head_commit = r[b"HEAD"]
  2734. assert isinstance(head_commit, Commit)
  2735. tree_id = head_commit.tree
  2736. except KeyError:
  2737. tree_id = None
  2738. for change in index.changes_from_tree(r.object_store, tree_id):
  2739. if not change[0][0]:
  2740. assert change[0][1] is not None
  2741. tracked_changes["add"].append(change[0][1])
  2742. elif not change[0][1]:
  2743. assert change[0][0] is not None
  2744. tracked_changes["delete"].append(change[0][0])
  2745. elif change[0][0] == change[0][1]:
  2746. assert change[0][0] is not None
  2747. tracked_changes["modify"].append(change[0][0])
  2748. else:
  2749. raise NotImplementedError("git mv ops not yet supported")
  2750. return tracked_changes
  2751. def daemon(
  2752. path: Union[str, os.PathLike[str]] = ".",
  2753. address: Optional[str] = None,
  2754. port: Optional[int] = None,
  2755. ) -> None:
  2756. """Run a daemon serving Git requests over TCP/IP.
  2757. Args:
  2758. path: Path to the directory to serve.
  2759. address: Optional address to listen on (defaults to ::)
  2760. port: Optional port to listen on (defaults to TCP_GIT_PORT)
  2761. """
  2762. # TODO(jelmer): Support git-daemon-export-ok and --export-all.
  2763. backend = FileSystemBackend(os.fspath(path))
  2764. server = TCPGitServer(backend, address or "localhost", port or 9418)
  2765. server.serve_forever()
  2766. def web_daemon(
  2767. path: Union[str, os.PathLike[str]] = ".",
  2768. address: Optional[str] = None,
  2769. port: Optional[int] = None,
  2770. ) -> None:
  2771. """Run a daemon serving Git requests over HTTP.
  2772. Args:
  2773. path: Path to the directory to serve
  2774. address: Optional address to listen on (defaults to ::)
  2775. port: Optional port to listen on (defaults to 80)
  2776. """
  2777. from .web import (
  2778. WSGIRequestHandlerLogger,
  2779. WSGIServerLogger,
  2780. make_server,
  2781. make_wsgi_chain,
  2782. )
  2783. backend = FileSystemBackend(os.fspath(path))
  2784. app = make_wsgi_chain(backend)
  2785. server = make_server(
  2786. address or "::",
  2787. port or 80,
  2788. app,
  2789. handler_class=WSGIRequestHandlerLogger,
  2790. server_class=WSGIServerLogger,
  2791. )
  2792. server.serve_forever()
  2793. def upload_pack(
  2794. path: Union[str, os.PathLike[str]] = ".",
  2795. inf: Optional[BinaryIO] = None,
  2796. outf: Optional[BinaryIO] = None,
  2797. ) -> int:
  2798. """Upload a pack file after negotiating its contents using smart protocol.
  2799. Args:
  2800. path: Path to the repository
  2801. inf: Input stream to communicate with client
  2802. outf: Output stream to communicate with client
  2803. """
  2804. if outf is None:
  2805. outf = sys.stdout.buffer
  2806. if inf is None:
  2807. inf = sys.stdin.buffer
  2808. assert outf is not None
  2809. assert inf is not None
  2810. path = os.path.expanduser(path)
  2811. backend = FileSystemBackend(path)
  2812. def send_fn(data: bytes) -> None:
  2813. outf.write(data)
  2814. outf.flush()
  2815. proto = Protocol(inf.read, send_fn)
  2816. handler = UploadPackHandler(backend, [path], proto)
  2817. # FIXME: Catch exceptions and write a single-line summary to outf.
  2818. handler.handle()
  2819. return 0
  2820. def receive_pack(
  2821. path: Union[str, os.PathLike[str]] = ".",
  2822. inf: Optional[BinaryIO] = None,
  2823. outf: Optional[BinaryIO] = None,
  2824. ) -> int:
  2825. """Receive a pack file after negotiating its contents using smart protocol.
  2826. Args:
  2827. path: Path to the repository
  2828. inf: Input stream to communicate with client
  2829. outf: Output stream to communicate with client
  2830. """
  2831. if outf is None:
  2832. outf = sys.stdout.buffer
  2833. if inf is None:
  2834. inf = sys.stdin.buffer
  2835. assert outf is not None
  2836. assert inf is not None
  2837. path = os.path.expanduser(path)
  2838. backend = FileSystemBackend(path)
  2839. def send_fn(data: bytes) -> None:
  2840. outf.write(data)
  2841. outf.flush()
  2842. proto = Protocol(inf.read, send_fn)
  2843. handler = ReceivePackHandler(backend, [path], proto)
  2844. # FIXME: Catch exceptions and write a single-line summary to outf.
  2845. handler.handle()
  2846. return 0
  2847. def _make_branch_ref(name: Union[str, bytes]) -> Ref:
  2848. if isinstance(name, str):
  2849. name = name.encode(DEFAULT_ENCODING)
  2850. return LOCAL_BRANCH_PREFIX + name
  2851. def _make_tag_ref(name: Union[str, bytes]) -> Ref:
  2852. if isinstance(name, str):
  2853. name = name.encode(DEFAULT_ENCODING)
  2854. return LOCAL_TAG_PREFIX + name
  2855. def branch_delete(
  2856. repo: RepoPath, name: Union[str, bytes, Sequence[Union[str, bytes]]]
  2857. ) -> None:
  2858. """Delete a branch.
  2859. Args:
  2860. repo: Path to the repository
  2861. name: Name of the branch
  2862. """
  2863. with open_repo_closing(repo) as r:
  2864. if isinstance(name, (list, tuple)):
  2865. names = name
  2866. else:
  2867. names = [name]
  2868. for branch_name in names:
  2869. del r.refs[_make_branch_ref(branch_name)]
  2870. def branch_create(
  2871. repo: Union[str, os.PathLike[str], Repo],
  2872. name: Union[str, bytes],
  2873. objectish: Optional[Union[str, bytes]] = None,
  2874. force: bool = False,
  2875. ) -> None:
  2876. """Create a branch.
  2877. Args:
  2878. repo: Path to the repository
  2879. name: Name of the new branch
  2880. objectish: Target object to point new branch at (defaults to HEAD)
  2881. force: Force creation of branch, even if it already exists
  2882. """
  2883. with open_repo_closing(repo) as r:
  2884. if objectish is None:
  2885. objectish = "HEAD"
  2886. # Try to expand branch shorthand before parsing
  2887. original_objectish = objectish
  2888. objectish_bytes = (
  2889. objectish.encode(DEFAULT_ENCODING)
  2890. if isinstance(objectish, str)
  2891. else objectish
  2892. )
  2893. if b"refs/remotes/" + objectish_bytes in r.refs:
  2894. objectish = b"refs/remotes/" + objectish_bytes
  2895. elif b"refs/heads/" + objectish_bytes in r.refs:
  2896. objectish = b"refs/heads/" + objectish_bytes
  2897. object = parse_object(r, objectish)
  2898. refname = _make_branch_ref(name)
  2899. ref_message = (
  2900. b"branch: Created from " + original_objectish.encode(DEFAULT_ENCODING)
  2901. if isinstance(original_objectish, str)
  2902. else b"branch: Created from " + original_objectish
  2903. )
  2904. if force:
  2905. r.refs.set_if_equals(refname, None, object.id, message=ref_message)
  2906. else:
  2907. if not r.refs.add_if_new(refname, object.id, message=ref_message):
  2908. name_str = name.decode() if isinstance(name, bytes) else name
  2909. raise Error(f"Branch with name {name_str} already exists.")
  2910. # Check if we should set up tracking
  2911. config = r.get_config_stack()
  2912. try:
  2913. auto_setup_merge = config.get((b"branch",), b"autoSetupMerge").decode()
  2914. except KeyError:
  2915. auto_setup_merge = "true" # Default value
  2916. # Determine if the objectish refers to a remote-tracking branch
  2917. objectish_ref = None
  2918. if original_objectish != "HEAD":
  2919. # Try to resolve objectish as a ref
  2920. objectish_bytes = (
  2921. original_objectish.encode(DEFAULT_ENCODING)
  2922. if isinstance(original_objectish, str)
  2923. else original_objectish
  2924. )
  2925. if objectish_bytes in r.refs:
  2926. objectish_ref = objectish_bytes
  2927. elif b"refs/remotes/" + objectish_bytes in r.refs:
  2928. objectish_ref = b"refs/remotes/" + objectish_bytes
  2929. elif b"refs/heads/" + objectish_bytes in r.refs:
  2930. objectish_ref = b"refs/heads/" + objectish_bytes
  2931. else:
  2932. # HEAD might point to a remote-tracking branch
  2933. head_ref = r.refs.follow(b"HEAD")[0][1]
  2934. if head_ref.startswith(b"refs/remotes/"):
  2935. objectish_ref = head_ref
  2936. # Set up tracking if appropriate
  2937. if objectish_ref and (
  2938. (auto_setup_merge == "always")
  2939. or (
  2940. auto_setup_merge == "true"
  2941. and objectish_ref.startswith(b"refs/remotes/")
  2942. )
  2943. ):
  2944. # Extract remote name and branch from the ref
  2945. if objectish_ref.startswith(b"refs/remotes/"):
  2946. parts = objectish_ref[len(b"refs/remotes/") :].split(b"/", 1)
  2947. if len(parts) == 2:
  2948. remote_name = parts[0]
  2949. remote_branch = b"refs/heads/" + parts[1]
  2950. # Set up tracking
  2951. repo_config = r.get_config()
  2952. branch_name_bytes = (
  2953. name.encode(DEFAULT_ENCODING) if isinstance(name, str) else name
  2954. )
  2955. repo_config.set(
  2956. (b"branch", branch_name_bytes), b"remote", remote_name
  2957. )
  2958. repo_config.set(
  2959. (b"branch", branch_name_bytes), b"merge", remote_branch
  2960. )
  2961. repo_config.write_to_path()
  2962. def filter_branches_by_pattern(branches: Iterable[bytes], pattern: str) -> list[bytes]:
  2963. """Filter branches by fnmatch pattern.
  2964. Args:
  2965. branches: Iterable of branch names as bytes
  2966. pattern: Pattern to match against
  2967. Returns:
  2968. List of filtered branch names
  2969. """
  2970. return [
  2971. branch for branch in branches if fnmatch.fnmatchcase(branch.decode(), pattern)
  2972. ]
  2973. def branch_list(repo: RepoPath) -> list[bytes]:
  2974. """List all branches.
  2975. Args:
  2976. repo: Path to the repository
  2977. Returns:
  2978. List of branch names (without refs/heads/ prefix)
  2979. """
  2980. with open_repo_closing(repo) as r:
  2981. branches = list(r.refs.keys(base=LOCAL_BRANCH_PREFIX))
  2982. # Check for branch.sort configuration
  2983. config = r.get_config_stack()
  2984. try:
  2985. sort_key = config.get((b"branch",), b"sort").decode()
  2986. except KeyError:
  2987. # Default is refname (alphabetical)
  2988. sort_key = "refname"
  2989. # Parse sort key
  2990. reverse = False
  2991. if sort_key.startswith("-"):
  2992. reverse = True
  2993. sort_key = sort_key[1:]
  2994. # Apply sorting
  2995. if sort_key == "refname":
  2996. # Simple alphabetical sort (default)
  2997. branches.sort(reverse=reverse)
  2998. elif sort_key in ("committerdate", "authordate"):
  2999. # Sort by date
  3000. def get_commit_date(branch_name: bytes) -> int:
  3001. ref = LOCAL_BRANCH_PREFIX + branch_name
  3002. sha = r.refs[ref]
  3003. commit = r.object_store[sha]
  3004. assert isinstance(commit, Commit)
  3005. if sort_key == "committerdate":
  3006. return cast(int, commit.commit_time)
  3007. else: # authordate
  3008. return cast(int, commit.author_time)
  3009. # Sort branches by date
  3010. # Note: Python's sort naturally orders smaller values first (ascending)
  3011. # For dates, this means oldest first by default
  3012. # Use a stable sort with branch name as secondary key for consistent ordering
  3013. if reverse:
  3014. # For reverse sort, we want newest dates first but alphabetical names second
  3015. branches.sort(key=lambda b: (-get_commit_date(b), b))
  3016. else:
  3017. branches.sort(key=lambda b: (get_commit_date(b), b))
  3018. else:
  3019. # Unknown sort key, fall back to default
  3020. branches.sort()
  3021. return branches
  3022. def branch_remotes_list(repo: RepoPath) -> list[bytes]:
  3023. """List the short names of all remote branches.
  3024. Args:
  3025. repo: Path to the repository
  3026. Returns:
  3027. List of branch names (without refs/remotes/ prefix, and without remote name; e.g. 'main' from 'origin/main')
  3028. """
  3029. with open_repo_closing(repo) as r:
  3030. branches = list(r.refs.keys(base=LOCAL_REMOTE_PREFIX))
  3031. config = r.get_config_stack()
  3032. try:
  3033. sort_key = config.get((b"branch",), b"sort").decode()
  3034. except KeyError:
  3035. # Default is refname (alphabetical)
  3036. sort_key = "refname"
  3037. # Parse sort key
  3038. reverse = False
  3039. if sort_key.startswith("-"):
  3040. reverse = True
  3041. sort_key = sort_key[1:]
  3042. # Apply sorting
  3043. if sort_key == "refname":
  3044. # Simple alphabetical sort (default)
  3045. branches.sort(reverse=reverse)
  3046. elif sort_key in ("committerdate", "authordate"):
  3047. # Sort by date
  3048. def get_commit_date(branch_name: bytes) -> int:
  3049. ref = LOCAL_REMOTE_PREFIX + branch_name
  3050. sha = r.refs[ref]
  3051. commit = r.object_store[sha]
  3052. assert isinstance(commit, Commit)
  3053. if sort_key == "committerdate":
  3054. return cast(int, commit.commit_time)
  3055. else: # authordate
  3056. return cast(int, commit.author_time)
  3057. # Sort branches by date
  3058. # Note: Python's sort naturally orders smaller values first (ascending)
  3059. # For dates, this means oldest first by default
  3060. # Use a stable sort with branch name as secondary key for consistent ordering
  3061. if reverse:
  3062. # For reverse sort, we want newest dates first but alphabetical names second
  3063. branches.sort(key=lambda b: (-get_commit_date(b), b))
  3064. else:
  3065. branches.sort(key=lambda b: (get_commit_date(b), b))
  3066. else:
  3067. # Unknown sort key
  3068. raise ValueError(f"Unknown sort key: {sort_key}")
  3069. return branches
  3070. def _get_branch_merge_status(repo: RepoPath) -> Iterator[tuple[bytes, bool]]:
  3071. """Get merge status for all branches relative to current HEAD.
  3072. Args:
  3073. repo: Path to the repository
  3074. Yields:
  3075. Tuple of (branch_name, is_merged) where:
  3076. - branch_name: Branch name without refs/heads/ prefix
  3077. - is_merged: True if branch is merged into HEAD, False otherwise
  3078. """
  3079. with open_repo_closing(repo) as r:
  3080. current_sha = r.refs[b"HEAD"]
  3081. for branch_ref, branch_sha in r.refs.as_dict(base=b"refs/heads/").items():
  3082. # Check if branch is an ancestor of HEAD (fully merged)
  3083. is_merged = can_fast_forward(r, branch_sha, current_sha)
  3084. yield branch_ref, is_merged
  3085. def merged_branches(repo: RepoPath) -> Iterator[bytes]:
  3086. """List branches that have been merged into the current branch.
  3087. Args:
  3088. repo: Path to the repository
  3089. Yields:
  3090. Branch names (without refs/heads/ prefix) that are merged
  3091. into the current HEAD
  3092. """
  3093. for branch_name, is_merged in _get_branch_merge_status(repo):
  3094. if is_merged:
  3095. yield branch_name
  3096. def no_merged_branches(repo: RepoPath) -> Iterator[bytes]:
  3097. """List branches that have been merged into the current branch.
  3098. Args:
  3099. repo: Path to the repository
  3100. Yields:
  3101. Branch names (without refs/heads/ prefix) that are merged
  3102. into the current HEAD
  3103. """
  3104. for branch_name, is_merged in _get_branch_merge_status(repo):
  3105. if not is_merged:
  3106. yield branch_name
  3107. def branches_containing(repo: RepoPath, commit: str) -> Iterator[bytes]:
  3108. """List branches that contain the specified commit.
  3109. Args:
  3110. repo: Path to the repository
  3111. commit: Commit-ish string (SHA, branch name, tag, etc.)
  3112. Yields:
  3113. Branch names (without refs/heads/ prefix) that contain the commit
  3114. Raises:
  3115. ValueError: If the commit reference is malformed
  3116. KeyError: If the commit reference does not exist
  3117. """
  3118. with open_repo_closing(repo) as r:
  3119. commit_obj = parse_commit(r, commit)
  3120. commit_sha = commit_obj.id
  3121. for branch_ref, branch_sha in r.refs.as_dict(base=LOCAL_BRANCH_PREFIX).items():
  3122. if can_fast_forward(r, commit_sha, branch_sha):
  3123. yield branch_ref
  3124. def active_branch(repo: RepoPath) -> bytes:
  3125. """Return the active branch in the repository, if any.
  3126. Args:
  3127. repo: Repository to open
  3128. Returns:
  3129. branch name
  3130. Raises:
  3131. KeyError: if the repository does not have a working tree
  3132. IndexError: if HEAD is floating
  3133. """
  3134. with open_repo_closing(repo) as r:
  3135. active_ref = r.refs.follow(b"HEAD")[0][1]
  3136. if not active_ref.startswith(LOCAL_BRANCH_PREFIX):
  3137. raise ValueError(active_ref)
  3138. return active_ref[len(LOCAL_BRANCH_PREFIX) :]
  3139. def get_branch_remote(repo: Union[str, os.PathLike[str], Repo]) -> bytes:
  3140. """Return the active branch's remote name, if any.
  3141. Args:
  3142. repo: Repository to open
  3143. Returns:
  3144. remote name
  3145. Raises:
  3146. KeyError: if the repository does not have a working tree
  3147. """
  3148. with open_repo_closing(repo) as r:
  3149. branch_name = active_branch(r.path)
  3150. config = r.get_config()
  3151. try:
  3152. remote_name = config.get((b"branch", branch_name), b"remote")
  3153. except KeyError:
  3154. remote_name = b"origin"
  3155. return remote_name
  3156. def get_branch_merge(repo: RepoPath, branch_name: Optional[bytes] = None) -> bytes:
  3157. """Return the branch's merge reference (upstream branch), if any.
  3158. Args:
  3159. repo: Repository to open
  3160. branch_name: Name of the branch (defaults to active branch)
  3161. Returns:
  3162. merge reference name (e.g. b"refs/heads/main")
  3163. Raises:
  3164. KeyError: if the branch does not have a merge configuration
  3165. """
  3166. with open_repo_closing(repo) as r:
  3167. if branch_name is None:
  3168. branch_name = active_branch(r.path)
  3169. config = r.get_config()
  3170. return config.get((b"branch", branch_name), b"merge")
  3171. def set_branch_tracking(
  3172. repo: Union[str, os.PathLike[str], Repo],
  3173. branch_name: bytes,
  3174. remote_name: bytes,
  3175. remote_ref: bytes,
  3176. ) -> None:
  3177. """Set up branch tracking configuration.
  3178. Args:
  3179. repo: Repository to open
  3180. branch_name: Name of the local branch
  3181. remote_name: Name of the remote (e.g. b"origin")
  3182. remote_ref: Remote reference to track (e.g. b"refs/heads/main")
  3183. """
  3184. with open_repo_closing(repo) as r:
  3185. config = r.get_config()
  3186. config.set((b"branch", branch_name), b"remote", remote_name)
  3187. config.set((b"branch", branch_name), b"merge", remote_ref)
  3188. config.write_to_path()
  3189. def fetch(
  3190. repo: RepoPath,
  3191. remote_location: Optional[Union[str, bytes]] = None,
  3192. outstream: TextIO = sys.stdout,
  3193. errstream: Union[BinaryIO, RawIOBase] = default_bytes_err_stream,
  3194. message: Optional[bytes] = None,
  3195. depth: Optional[int] = None,
  3196. prune: bool = False,
  3197. prune_tags: bool = False,
  3198. force: bool = False,
  3199. operation: Optional[str] = None,
  3200. thin_packs: bool = True,
  3201. report_activity: Optional[Callable[[int, str], None]] = None,
  3202. quiet: bool = False,
  3203. include_tags: bool = False,
  3204. username: Optional[str] = None,
  3205. password: Optional[str] = None,
  3206. key_filename: Optional[str] = None,
  3207. ssh_command: Optional[str] = None,
  3208. ) -> FetchPackResult:
  3209. """Fetch objects from a remote server.
  3210. Args:
  3211. repo: Path to the repository
  3212. remote_location: String identifying a remote server
  3213. outstream: Output stream (defaults to stdout)
  3214. errstream: Error stream (defaults to stderr)
  3215. message: Reflog message (defaults to b"fetch: from <remote_name>")
  3216. depth: Depth to fetch at
  3217. prune: Prune remote removed refs
  3218. prune_tags: Prune remote removed tags
  3219. force: Force fetching even if it would overwrite local changes
  3220. operation: Git operation for authentication (e.g., "fetch")
  3221. thin_packs: Whether to use thin packs
  3222. report_activity: Optional callback for reporting transport activity
  3223. quiet: Whether to suppress progress output
  3224. include_tags: Whether to include tags
  3225. username: Username for authentication
  3226. password: Password for authentication
  3227. key_filename: SSH key filename
  3228. ssh_command: SSH command to use
  3229. Returns:
  3230. Dictionary with refs on the remote
  3231. """
  3232. with open_repo_closing(repo) as r:
  3233. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  3234. if message is None:
  3235. message = b"fetch: from " + remote_location.encode(DEFAULT_ENCODING)
  3236. client, path = get_transport_and_path(
  3237. remote_location,
  3238. config=r.get_config_stack(),
  3239. operation=operation,
  3240. thin_packs=thin_packs,
  3241. report_activity=report_activity,
  3242. quiet=quiet,
  3243. include_tags=include_tags,
  3244. username=username,
  3245. password=password,
  3246. key_filename=key_filename,
  3247. ssh_command=ssh_command,
  3248. )
  3249. def progress(data: bytes) -> None:
  3250. errstream.write(data)
  3251. fetch_result = client.fetch(path.encode(), r, progress=progress, depth=depth)
  3252. if remote_name is not None:
  3253. _import_remote_refs(
  3254. r.refs,
  3255. remote_name,
  3256. fetch_result.refs,
  3257. message,
  3258. prune=prune,
  3259. prune_tags=prune_tags,
  3260. )
  3261. # Trigger auto GC if needed
  3262. from .gc import maybe_auto_gc
  3263. with open_repo_closing(repo) as r:
  3264. maybe_auto_gc(r)
  3265. return fetch_result
  3266. def for_each_ref(
  3267. repo: Union[Repo, str] = ".",
  3268. pattern: Optional[Union[str, bytes]] = None,
  3269. ) -> list[tuple[bytes, bytes, bytes]]:
  3270. """Iterate over all refs that match the (optional) pattern.
  3271. Args:
  3272. repo: Path to the repository
  3273. pattern: Optional glob (7) patterns to filter the refs with
  3274. Returns: List of bytes tuples with: (sha, object_type, ref_name)
  3275. """
  3276. if isinstance(pattern, str):
  3277. pattern = os.fsencode(pattern)
  3278. with open_repo_closing(repo) as r:
  3279. refs = r.get_refs()
  3280. if pattern:
  3281. matching_refs: dict[bytes, bytes] = {}
  3282. pattern_parts = pattern.split(b"/")
  3283. for ref, sha in refs.items():
  3284. matches = False
  3285. # git for-each-ref uses glob (7) style patterns, but fnmatch
  3286. # is greedy and also matches slashes, unlike glob.glob.
  3287. # We have to check parts of the pattern individually.
  3288. # See https://github.com/python/cpython/issues/72904
  3289. ref_parts = ref.split(b"/")
  3290. if len(ref_parts) > len(pattern_parts):
  3291. continue
  3292. for pat, ref_part in zip(pattern_parts, ref_parts):
  3293. matches = fnmatch.fnmatchcase(ref_part, pat)
  3294. if not matches:
  3295. break
  3296. if matches:
  3297. matching_refs[ref] = sha
  3298. refs = matching_refs
  3299. ret: list[tuple[bytes, bytes, bytes]] = [
  3300. (sha, r.get_object(sha).type_name, ref)
  3301. for ref, sha in sorted(
  3302. refs.items(),
  3303. key=lambda ref_sha: ref_sha[0],
  3304. )
  3305. if ref != b"HEAD"
  3306. ]
  3307. return ret
  3308. def ls_remote(
  3309. remote: Union[str, bytes],
  3310. config: Optional[Config] = None,
  3311. operation: Optional[str] = None,
  3312. thin_packs: bool = True,
  3313. report_activity: Optional[Callable[[int, str], None]] = None,
  3314. quiet: bool = False,
  3315. include_tags: bool = False,
  3316. username: Optional[str] = None,
  3317. password: Optional[str] = None,
  3318. key_filename: Optional[str] = None,
  3319. ssh_command: Optional[str] = None,
  3320. ) -> LsRemoteResult:
  3321. """List the refs in a remote.
  3322. Args:
  3323. remote: Remote repository location
  3324. config: Configuration to use
  3325. operation: Operation type
  3326. thin_packs: Whether to use thin packs
  3327. report_activity: Function to report activity
  3328. quiet: Whether to suppress output
  3329. include_tags: Whether to include tags
  3330. username: Username for authentication
  3331. password: Password for authentication
  3332. key_filename: SSH key filename
  3333. ssh_command: SSH command to use
  3334. Returns:
  3335. LsRemoteResult object with refs and symrefs
  3336. """
  3337. if config is None:
  3338. config = StackedConfig.default()
  3339. remote_str = remote.decode() if isinstance(remote, bytes) else remote
  3340. client, host_path = get_transport_and_path(
  3341. remote_str,
  3342. config=config,
  3343. operation=operation,
  3344. thin_packs=thin_packs,
  3345. report_activity=report_activity,
  3346. quiet=quiet,
  3347. include_tags=include_tags,
  3348. username=username,
  3349. password=password,
  3350. key_filename=key_filename,
  3351. ssh_command=ssh_command,
  3352. )
  3353. return client.get_refs(
  3354. host_path.encode() if isinstance(host_path, str) else host_path
  3355. )
  3356. def repack(repo: RepoPath) -> None:
  3357. """Repack loose files in a repository.
  3358. Currently this only packs loose objects.
  3359. Args:
  3360. repo: Path to the repository
  3361. """
  3362. with open_repo_closing(repo) as r:
  3363. r.object_store.pack_loose_objects()
  3364. def pack_objects(
  3365. repo: RepoPath,
  3366. object_ids: Sequence[bytes],
  3367. packf: BinaryIO,
  3368. idxf: Optional[BinaryIO],
  3369. delta_window_size: Optional[int] = None,
  3370. deltify: Optional[bool] = None,
  3371. reuse_deltas: bool = True,
  3372. pack_index_version: Optional[int] = None,
  3373. ) -> None:
  3374. """Pack objects into a file.
  3375. Args:
  3376. repo: Path to the repository
  3377. object_ids: List of object ids to write
  3378. packf: File-like object to write to
  3379. idxf: File-like object to write to (can be None)
  3380. delta_window_size: Sliding window size for searching for deltas;
  3381. Set to None for default window size.
  3382. deltify: Whether to deltify objects
  3383. reuse_deltas: Allow reuse of existing deltas while deltifying
  3384. pack_index_version: Pack index version to use (1, 2, or 3). If None, uses default version.
  3385. """
  3386. with open_repo_closing(repo) as r:
  3387. entries, data_sum = write_pack_from_container(
  3388. packf.write,
  3389. r.object_store,
  3390. [(oid, None) for oid in object_ids],
  3391. deltify=deltify,
  3392. delta_window_size=delta_window_size,
  3393. reuse_deltas=reuse_deltas,
  3394. )
  3395. if idxf is not None:
  3396. index_entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
  3397. write_pack_index(idxf, index_entries, data_sum, version=pack_index_version)
  3398. def ls_tree(
  3399. repo: RepoPath,
  3400. treeish: Union[str, bytes, Commit, Tree, Tag] = b"HEAD",
  3401. outstream: Union[TextIO, BinaryIO] = sys.stdout,
  3402. recursive: bool = False,
  3403. name_only: bool = False,
  3404. ) -> None:
  3405. """List contents of a tree.
  3406. Args:
  3407. repo: Path to the repository
  3408. treeish: Tree id to list
  3409. outstream: Output stream (defaults to stdout)
  3410. recursive: Whether to recursively list files
  3411. name_only: Only print item name
  3412. """
  3413. def list_tree(store: BaseObjectStore, treeid: bytes, base: bytes) -> None:
  3414. tree = store[treeid]
  3415. assert isinstance(tree, Tree)
  3416. for name, mode, sha in tree.iteritems():
  3417. assert name is not None
  3418. assert mode is not None
  3419. assert sha is not None
  3420. if base:
  3421. name = posixpath.join(base, name)
  3422. if name_only:
  3423. if isinstance(outstream, BinaryIO):
  3424. outstream.write(name + b"\n")
  3425. else:
  3426. outstream.write(name.decode("utf-8", "replace") + "\n")
  3427. else:
  3428. formatted = pretty_format_tree_entry(name, mode, sha)
  3429. if isinstance(outstream, BinaryIO):
  3430. outstream.write(formatted.encode("utf-8"))
  3431. else:
  3432. outstream.write(formatted)
  3433. if stat.S_ISDIR(mode) and recursive:
  3434. list_tree(store, sha, name)
  3435. with open_repo_closing(repo) as r:
  3436. tree = parse_tree(r, treeish)
  3437. list_tree(r.object_store, tree.id, b"")
  3438. def remote_add(
  3439. repo: RepoPath,
  3440. name: Union[bytes, str],
  3441. url: Union[bytes, str],
  3442. ) -> None:
  3443. """Add a remote.
  3444. Args:
  3445. repo: Path to the repository
  3446. name: Remote name
  3447. url: Remote URL
  3448. """
  3449. if not isinstance(name, bytes):
  3450. name = name.encode(DEFAULT_ENCODING)
  3451. if not isinstance(url, bytes):
  3452. url = url.encode(DEFAULT_ENCODING)
  3453. with open_repo_closing(repo) as r:
  3454. c = r.get_config()
  3455. section = (b"remote", name)
  3456. if c.has_section(section):
  3457. raise RemoteExists(f"Remote {name.decode()} already exists")
  3458. c.set(section, b"url", url)
  3459. c.write_to_path()
  3460. def remote_remove(repo: Repo, name: Union[bytes, str]) -> None:
  3461. """Remove a remote.
  3462. Args:
  3463. repo: Path to the repository
  3464. name: Remote name
  3465. """
  3466. if not isinstance(name, bytes):
  3467. name = name.encode(DEFAULT_ENCODING)
  3468. with open_repo_closing(repo) as r:
  3469. c = r.get_config()
  3470. section = (b"remote", name)
  3471. del c[section]
  3472. c.write_to_path()
  3473. def _quote_path(path: str) -> str:
  3474. """Quote a path using C-style quoting similar to git's core.quotePath.
  3475. Args:
  3476. path: Path to quote
  3477. Returns:
  3478. Quoted path string
  3479. """
  3480. # Check if path needs quoting (non-ASCII or special characters)
  3481. needs_quoting = False
  3482. for char in path:
  3483. if ord(char) > 127 or char in '"\\':
  3484. needs_quoting = True
  3485. break
  3486. if not needs_quoting:
  3487. return path
  3488. # Apply C-style quoting
  3489. quoted = '"'
  3490. for char in path:
  3491. if ord(char) > 127:
  3492. # Non-ASCII character, encode as octal escape
  3493. utf8_bytes = char.encode("utf-8")
  3494. for byte in utf8_bytes:
  3495. quoted += f"\\{byte:03o}"
  3496. elif char == '"':
  3497. quoted += '\\"'
  3498. elif char == "\\":
  3499. quoted += "\\\\"
  3500. else:
  3501. quoted += char
  3502. quoted += '"'
  3503. return quoted
  3504. def check_ignore(
  3505. repo: RepoPath,
  3506. paths: Sequence[Union[str, bytes, os.PathLike[str]]],
  3507. no_index: bool = False,
  3508. quote_path: bool = True,
  3509. ) -> Iterator[str]:
  3510. r"""Debug gitignore files.
  3511. Args:
  3512. repo: Path to the repository
  3513. paths: List of paths to check for
  3514. no_index: Don't check index
  3515. quote_path: If True, quote non-ASCII characters in returned paths using
  3516. C-style octal escapes (e.g. "тест.txt" becomes "\\321\\202\\320\\265\\321\\201\\321\\202.txt").
  3517. If False, return raw unicode paths.
  3518. Returns: List of ignored files
  3519. """
  3520. with open_repo_closing(repo) as r:
  3521. index = r.open_index()
  3522. ignore_manager = IgnoreFilterManager.from_repo(r)
  3523. for original_path in paths:
  3524. # Convert path to string for consistent handling
  3525. original_path_fspath = os.fspath(original_path)
  3526. # Normalize to str
  3527. original_path_str = os.fsdecode(original_path_fspath)
  3528. if not no_index and path_to_tree_path(r.path, original_path_str) in index:
  3529. continue
  3530. # Preserve whether the original path had a trailing slash
  3531. had_trailing_slash = original_path_str.endswith(("/", os.path.sep))
  3532. if os.path.isabs(original_path_str):
  3533. path = os.path.relpath(original_path_str, r.path)
  3534. # Normalize Windows paths to use forward slashes
  3535. if os.path.sep != "/":
  3536. path = path.replace(os.path.sep, "/")
  3537. else:
  3538. path = original_path_str
  3539. # Restore trailing slash if it was in the original
  3540. if had_trailing_slash and not path.endswith("/"):
  3541. path = path + "/"
  3542. # For directories, check with trailing slash to get correct ignore behavior
  3543. test_path = path
  3544. path_without_slash = path.rstrip("/")
  3545. is_directory = os.path.isdir(os.path.join(r.path, path_without_slash))
  3546. # If this is a directory path, ensure we test it correctly
  3547. if is_directory and not path.endswith("/"):
  3548. test_path = path + "/"
  3549. if ignore_manager.is_ignored(test_path):
  3550. # Return relative path (like git does) when absolute path was provided
  3551. if os.path.isabs(original_path):
  3552. output_path = path
  3553. else:
  3554. output_path = original_path # type: ignore[assignment]
  3555. yield _quote_path(output_path) if quote_path else output_path
  3556. def update_head(
  3557. repo: RepoPath,
  3558. target: Union[str, bytes],
  3559. detached: bool = False,
  3560. new_branch: Optional[Union[str, bytes]] = None,
  3561. ) -> None:
  3562. """Update HEAD to point at a new branch/commit.
  3563. Note that this does not actually update the working tree.
  3564. Args:
  3565. repo: Path to the repository
  3566. detached: Create a detached head
  3567. target: Branch or committish to switch to
  3568. new_branch: New branch to create
  3569. """
  3570. with open_repo_closing(repo) as r:
  3571. if new_branch is not None:
  3572. to_set = _make_branch_ref(new_branch)
  3573. else:
  3574. to_set = b"HEAD"
  3575. if detached:
  3576. # TODO(jelmer): Provide some way so that the actual ref gets
  3577. # updated rather than what it points to, so the delete isn't
  3578. # necessary.
  3579. del r.refs[to_set]
  3580. r.refs[to_set] = parse_commit(r, target).id
  3581. else:
  3582. r.refs.set_symbolic_ref(to_set, parse_ref(r, target))
  3583. if new_branch is not None:
  3584. r.refs.set_symbolic_ref(b"HEAD", to_set)
  3585. def checkout(
  3586. repo: Union[str, os.PathLike[str], Repo],
  3587. target: Optional[Union[str, bytes, Commit, Tag]] = None,
  3588. force: bool = False,
  3589. new_branch: Optional[Union[bytes, str]] = None,
  3590. paths: Optional[list[Union[bytes, str]]] = None,
  3591. ) -> None:
  3592. """Switch to a branch or commit, updating both HEAD and the working tree.
  3593. This is similar to 'git checkout', allowing you to switch to a branch,
  3594. tag, or specific commit. Unlike update_head, this function also updates
  3595. the working tree to match the target.
  3596. Args:
  3597. repo: Path to repository or repository object
  3598. target: Branch name, tag, or commit SHA to checkout. If None and paths is specified,
  3599. restores files from HEAD
  3600. force: Force checkout even if there are local changes
  3601. new_branch: Create a new branch at target (like git checkout -b)
  3602. paths: List of specific paths to checkout. If specified, only these paths are updated
  3603. and HEAD is not changed
  3604. Raises:
  3605. CheckoutError: If checkout cannot be performed due to conflicts
  3606. KeyError: If the target reference cannot be found
  3607. """
  3608. with open_repo_closing(repo) as r:
  3609. # Store the original target for later reference checks
  3610. original_target = target
  3611. worktree = r.get_worktree()
  3612. # Handle path-specific checkout (like git checkout -- <paths>)
  3613. if paths is not None:
  3614. # Convert paths to bytes
  3615. byte_paths = []
  3616. for path in paths:
  3617. if isinstance(path, str):
  3618. byte_paths.append(path.encode(DEFAULT_ENCODING))
  3619. else:
  3620. byte_paths.append(path)
  3621. # If no target specified, use HEAD
  3622. if target is None:
  3623. try:
  3624. target = r.refs[b"HEAD"]
  3625. except KeyError:
  3626. raise CheckoutError("No HEAD reference found")
  3627. else:
  3628. if isinstance(target, str):
  3629. target = target.encode(DEFAULT_ENCODING)
  3630. # Get the target commit and tree
  3631. target_tree = parse_tree(r, target)
  3632. # Get blob normalizer for line ending conversion
  3633. blob_normalizer = r.get_blob_normalizer()
  3634. # Restore specified paths from target tree
  3635. for path in byte_paths:
  3636. try:
  3637. # Look up the path in the target tree
  3638. mode, sha = target_tree.lookup_path(
  3639. r.object_store.__getitem__, path
  3640. )
  3641. obj = r[sha]
  3642. assert isinstance(obj, Blob), "Expected a Blob object"
  3643. except KeyError:
  3644. # Path doesn't exist in target tree
  3645. pass
  3646. else:
  3647. # Create directories if needed
  3648. # Handle path as string
  3649. if isinstance(path, bytes):
  3650. path_str = path.decode(DEFAULT_ENCODING)
  3651. else:
  3652. path_str = path
  3653. file_path = os.path.join(r.path, path_str)
  3654. os.makedirs(os.path.dirname(file_path), exist_ok=True)
  3655. # Write the file content
  3656. if stat.S_ISREG(mode):
  3657. # Apply checkout filters (smudge)
  3658. if blob_normalizer:
  3659. obj = blob_normalizer.checkout_normalize(obj, path)
  3660. flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
  3661. if sys.platform == "win32":
  3662. flags |= os.O_BINARY
  3663. with os.fdopen(os.open(file_path, flags, mode), "wb") as f:
  3664. f.write(obj.data)
  3665. # Update the index
  3666. worktree.stage(path)
  3667. return
  3668. # Normal checkout (switching branches/commits)
  3669. if target is None:
  3670. raise ValueError("Target must be specified for branch/commit checkout")
  3671. if isinstance(target, str):
  3672. target_bytes = target.encode(DEFAULT_ENCODING)
  3673. elif isinstance(target, bytes):
  3674. target_bytes = target
  3675. else:
  3676. # For Commit/Tag objects, we'll use their SHA
  3677. target_bytes = target.id
  3678. if isinstance(new_branch, str):
  3679. new_branch = new_branch.encode(DEFAULT_ENCODING)
  3680. # Parse the target to get the commit
  3681. assert (
  3682. original_target is not None
  3683. ) # Guaranteed by earlier check for normal checkout
  3684. target_commit = parse_commit(r, original_target)
  3685. target_tree_id = target_commit.tree
  3686. # Get current HEAD tree for comparison
  3687. try:
  3688. current_head = r.refs[b"HEAD"]
  3689. current_commit = r[current_head]
  3690. assert isinstance(current_commit, Commit), "Expected a Commit object"
  3691. current_tree_id = current_commit.tree
  3692. except KeyError:
  3693. # No HEAD yet (empty repo)
  3694. current_tree_id = None
  3695. # Check for uncommitted changes if not forcing
  3696. if not force and current_tree_id is not None:
  3697. status_report = status(r)
  3698. changes = []
  3699. # staged is a dict with 'add', 'delete', 'modify' keys
  3700. if isinstance(status_report.staged, dict):
  3701. changes.extend(status_report.staged.get("add", []))
  3702. changes.extend(status_report.staged.get("delete", []))
  3703. changes.extend(status_report.staged.get("modify", []))
  3704. # unstaged is a list
  3705. changes.extend(status_report.unstaged)
  3706. if changes:
  3707. # Check if any changes would conflict with checkout
  3708. target_tree_obj = r[target_tree_id]
  3709. assert isinstance(target_tree_obj, Tree), "Expected a Tree object"
  3710. target_tree = target_tree_obj
  3711. for change in changes:
  3712. if isinstance(change, str):
  3713. change = change.encode(DEFAULT_ENCODING)
  3714. try:
  3715. target_tree.lookup_path(r.object_store.__getitem__, change)
  3716. except KeyError:
  3717. # File doesn't exist in target tree - change can be preserved
  3718. pass
  3719. else:
  3720. # File exists in target tree - would overwrite local changes
  3721. raise CheckoutError(
  3722. f"Your local changes to '{change.decode()}' would be "
  3723. "overwritten by checkout. Please commit or stash before switching."
  3724. )
  3725. # Get configuration for working directory update
  3726. config = r.get_config()
  3727. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  3728. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  3729. validate_path_element = validate_path_element_ntfs
  3730. else:
  3731. validate_path_element = validate_path_element_default
  3732. if config.get_boolean(b"core", b"symlinks", True):
  3733. def symlink_wrapper(
  3734. source: Union[str, bytes, os.PathLike[str]],
  3735. target: Union[str, bytes, os.PathLike[str]],
  3736. ) -> None:
  3737. symlink(source, target) # type: ignore[arg-type,unused-ignore]
  3738. symlink_fn = symlink_wrapper
  3739. else:
  3740. def symlink_fallback(
  3741. source: Union[str, bytes, os.PathLike[str]],
  3742. target: Union[str, bytes, os.PathLike[str]],
  3743. ) -> None:
  3744. mode = "w" + ("b" if isinstance(source, bytes) else "")
  3745. with open(target, mode) as f:
  3746. f.write(source)
  3747. symlink_fn = symlink_fallback
  3748. # Get blob normalizer for line ending conversion
  3749. blob_normalizer = r.get_blob_normalizer()
  3750. # Update working tree
  3751. tree_change_iterator: Iterator[TreeChange] = tree_changes(
  3752. r.object_store, current_tree_id, target_tree_id
  3753. )
  3754. update_working_tree(
  3755. r,
  3756. current_tree_id,
  3757. target_tree_id,
  3758. change_iterator=tree_change_iterator,
  3759. honor_filemode=honor_filemode,
  3760. validate_path_element=validate_path_element,
  3761. symlink_fn=symlink_fn,
  3762. force_remove_untracked=force,
  3763. blob_normalizer=blob_normalizer,
  3764. allow_overwrite_modified=force,
  3765. )
  3766. # Update HEAD
  3767. if new_branch:
  3768. # Create new branch and switch to it
  3769. branch_create(r, new_branch, objectish=target_commit.id.decode("ascii"))
  3770. update_head(r, new_branch)
  3771. # Set up tracking if creating from a remote branch
  3772. from .refs import LOCAL_REMOTE_PREFIX, parse_remote_ref
  3773. if isinstance(original_target, bytes) and target_bytes.startswith(
  3774. LOCAL_REMOTE_PREFIX
  3775. ):
  3776. try:
  3777. remote_name, branch_name = parse_remote_ref(target_bytes)
  3778. # Set tracking to refs/heads/<branch> on the remote
  3779. set_branch_tracking(
  3780. r, new_branch, remote_name, b"refs/heads/" + branch_name
  3781. )
  3782. except ValueError:
  3783. # Invalid remote ref format, skip tracking setup
  3784. pass
  3785. else:
  3786. # Check if target is a branch name (with or without refs/heads/ prefix)
  3787. branch_ref = None
  3788. if (
  3789. isinstance(original_target, (str, bytes))
  3790. and target_bytes in r.refs.keys()
  3791. ):
  3792. if target_bytes.startswith(LOCAL_BRANCH_PREFIX):
  3793. branch_ref = target_bytes
  3794. else:
  3795. # Try adding refs/heads/ prefix
  3796. potential_branch = (
  3797. _make_branch_ref(target_bytes)
  3798. if isinstance(original_target, (str, bytes))
  3799. else None
  3800. )
  3801. if potential_branch in r.refs.keys():
  3802. branch_ref = potential_branch
  3803. if branch_ref:
  3804. # It's a branch - update HEAD symbolically
  3805. update_head(r, branch_ref)
  3806. else:
  3807. # It's a tag, other ref, or commit SHA - detached HEAD
  3808. update_head(r, target_commit.id.decode("ascii"), detached=True)
  3809. def reset_file(
  3810. repo: Repo,
  3811. file_path: str,
  3812. target: Union[str, bytes, Commit, Tree, Tag] = b"HEAD",
  3813. symlink_fn: Optional[
  3814. Callable[
  3815. [Union[str, bytes, os.PathLike[str]], Union[str, bytes, os.PathLike[str]]],
  3816. None,
  3817. ]
  3818. ] = None,
  3819. ) -> None:
  3820. """Reset the file to specific commit or branch.
  3821. Args:
  3822. repo: dulwich Repo object
  3823. file_path: file to reset, relative to the repository path
  3824. target: branch or commit or b'HEAD' to reset
  3825. symlink_fn: Function to use for creating symlinks
  3826. """
  3827. tree = parse_tree(repo, treeish=target)
  3828. tree_path = _fs_to_tree_path(file_path)
  3829. file_entry = tree.lookup_path(repo.object_store.__getitem__, tree_path)
  3830. full_path = os.path.join(os.fsencode(repo.path), tree_path)
  3831. blob = repo.object_store[file_entry[1]]
  3832. assert isinstance(blob, Blob)
  3833. mode = file_entry[0]
  3834. build_file_from_blob(blob, mode, full_path, symlink_fn=symlink_fn)
  3835. @replace_me(since="0.22.9", remove_in="0.24.0")
  3836. def checkout_branch(
  3837. repo: Union[str, os.PathLike[str], Repo],
  3838. target: Union[bytes, str],
  3839. force: bool = False,
  3840. ) -> None:
  3841. """Switch branches or restore working tree files.
  3842. This is now a wrapper around the general checkout() function.
  3843. Preserved for backward compatibility.
  3844. Args:
  3845. repo: dulwich Repo object
  3846. target: branch name or commit sha to checkout
  3847. force: true or not to force checkout
  3848. """
  3849. # Simply delegate to the new checkout function
  3850. return checkout(repo, target, force=force)
  3851. def sparse_checkout(
  3852. repo: Union[str, os.PathLike[str], Repo],
  3853. patterns: Optional[list[str]] = None,
  3854. force: bool = False,
  3855. cone: Optional[bool] = None,
  3856. ) -> None:
  3857. """Perform a sparse checkout in the repository (either 'full' or 'cone mode').
  3858. Perform sparse checkout in either 'cone' (directory-based) mode or
  3859. 'full pattern' (.gitignore) mode, depending on the ``cone`` parameter.
  3860. If ``cone`` is ``None``, the mode is inferred from the repository's
  3861. ``core.sparseCheckoutCone`` config setting.
  3862. Steps:
  3863. 1) If ``patterns`` is provided, write them to ``.git/info/sparse-checkout``.
  3864. 2) Determine which paths in the index are included vs. excluded.
  3865. - If ``cone=True``, use "cone-compatible" directory-based logic.
  3866. - If ``cone=False``, use standard .gitignore-style matching.
  3867. 3) Update the index's skip-worktree bits and add/remove files in
  3868. the working tree accordingly.
  3869. 4) If ``force=False``, refuse to remove files that have local modifications.
  3870. Args:
  3871. repo: Path to the repository or a Repo object.
  3872. patterns: Optional list of sparse-checkout patterns to write.
  3873. force: Whether to force removal of locally modified files (default False).
  3874. cone: Boolean indicating cone mode (True/False). If None, read from config.
  3875. Returns:
  3876. None
  3877. """
  3878. with open_repo_closing(repo) as repo_obj:
  3879. # --- 0) Possibly infer 'cone' from config ---
  3880. if cone is None:
  3881. cone = repo_obj.get_worktree().infer_cone_mode()
  3882. # --- 1) Read or write patterns ---
  3883. if patterns is None:
  3884. lines = repo_obj.get_worktree().get_sparse_checkout_patterns()
  3885. if lines is None:
  3886. raise Error("No sparse checkout patterns found.")
  3887. else:
  3888. lines = patterns
  3889. repo_obj.get_worktree().set_sparse_checkout_patterns(patterns)
  3890. # --- 2) Determine the set of included paths ---
  3891. index = repo_obj.open_index()
  3892. included_paths = determine_included_paths(index, lines, cone)
  3893. # --- 3) Apply those results to the index & working tree ---
  3894. try:
  3895. apply_included_paths(repo_obj, included_paths, force=force)
  3896. except SparseCheckoutConflictError as exc:
  3897. raise CheckoutError(*exc.args) from exc
  3898. def cone_mode_init(repo: Union[str, os.PathLike[str], Repo]) -> None:
  3899. """Initialize a repository to use sparse checkout in 'cone' mode.
  3900. Sets ``core.sparseCheckout`` and ``core.sparseCheckoutCone`` in the config.
  3901. Writes an initial ``.git/info/sparse-checkout`` file that includes only
  3902. top-level files (and excludes all subdirectories), e.g. ``["/*", "!/*/"]``.
  3903. Then performs a sparse checkout to update the working tree accordingly.
  3904. If no directories are specified, then only top-level files are included:
  3905. https://git-scm.com/docs/git-sparse-checkout#_internalscone_mode_handling
  3906. Args:
  3907. repo: Path to the repository or a Repo object.
  3908. Returns:
  3909. None
  3910. """
  3911. with open_repo_closing(repo) as repo_obj:
  3912. repo_obj.get_worktree().configure_for_cone_mode()
  3913. patterns = ["/*", "!/*/"] # root-level files only
  3914. sparse_checkout(repo_obj, patterns, force=True, cone=True)
  3915. def cone_mode_set(
  3916. repo: Union[str, os.PathLike[str], Repo], dirs: Sequence[str], force: bool = False
  3917. ) -> None:
  3918. """Overwrite the existing 'cone-mode' sparse patterns with a new set of directories.
  3919. Ensures ``core.sparseCheckout`` and ``core.sparseCheckoutCone`` are enabled.
  3920. Writes new patterns so that only the specified directories (and top-level files)
  3921. remain in the working tree, and applies the sparse checkout update.
  3922. Args:
  3923. repo: Path to the repository or a Repo object.
  3924. dirs: List of directory names to include.
  3925. force: Whether to forcibly discard local modifications (default False).
  3926. Returns:
  3927. None
  3928. """
  3929. with open_repo_closing(repo) as repo_obj:
  3930. repo_obj.get_worktree().configure_for_cone_mode()
  3931. repo_obj.get_worktree().set_cone_mode_patterns(dirs=dirs)
  3932. new_patterns = repo_obj.get_worktree().get_sparse_checkout_patterns()
  3933. # Finally, apply the patterns and update the working tree
  3934. sparse_checkout(repo_obj, new_patterns, force=force, cone=True)
  3935. def cone_mode_add(
  3936. repo: Union[str, os.PathLike[str], Repo], dirs: Sequence[str], force: bool = False
  3937. ) -> None:
  3938. """Add new directories to the existing 'cone-mode' sparse-checkout patterns.
  3939. Reads the current patterns from ``.git/info/sparse-checkout``, adds pattern
  3940. lines to include the specified directories, and then performs a sparse
  3941. checkout to update the working tree accordingly.
  3942. Args:
  3943. repo: Path to the repository or a Repo object.
  3944. dirs: List of directory names to add to the sparse-checkout.
  3945. force: Whether to forcibly discard local modifications (default False).
  3946. Returns:
  3947. None
  3948. """
  3949. with open_repo_closing(repo) as repo_obj:
  3950. repo_obj.get_worktree().configure_for_cone_mode()
  3951. # Do not pass base patterns as dirs
  3952. base_patterns = ["/*", "!/*/"]
  3953. existing_dirs = [
  3954. pat.strip("/")
  3955. for pat in repo_obj.get_worktree().get_sparse_checkout_patterns()
  3956. if pat not in base_patterns
  3957. ]
  3958. added_dirs = existing_dirs + list(dirs or [])
  3959. repo_obj.get_worktree().set_cone_mode_patterns(dirs=added_dirs)
  3960. new_patterns = repo_obj.get_worktree().get_sparse_checkout_patterns()
  3961. sparse_checkout(repo_obj, patterns=new_patterns, force=force, cone=True)
  3962. def check_mailmap(repo: RepoPath, contact: Union[str, bytes]) -> bytes:
  3963. """Check canonical name and email of contact.
  3964. Args:
  3965. repo: Path to the repository
  3966. contact: Contact name and/or email
  3967. Returns: Canonical contact data
  3968. """
  3969. with open_repo_closing(repo) as r:
  3970. from .mailmap import Mailmap
  3971. try:
  3972. mailmap = Mailmap.from_path(os.path.join(r.path, ".mailmap"))
  3973. except FileNotFoundError:
  3974. mailmap = Mailmap()
  3975. contact_bytes = (
  3976. contact.encode(DEFAULT_ENCODING) if isinstance(contact, str) else contact
  3977. )
  3978. result = mailmap.lookup(contact_bytes)
  3979. if isinstance(result, bytes):
  3980. return result
  3981. else:
  3982. # Convert tuple back to bytes format
  3983. name, email = result
  3984. if name is None:
  3985. name = b""
  3986. if email is None:
  3987. email = b""
  3988. return name + b" <" + email + b">"
  3989. def fsck(repo: RepoPath) -> Iterator[tuple[bytes, Exception]]:
  3990. """Check a repository.
  3991. Args:
  3992. repo: A path to the repository
  3993. Returns: Iterator over errors/warnings
  3994. """
  3995. with open_repo_closing(repo) as r:
  3996. # TODO(jelmer): check pack files
  3997. # TODO(jelmer): check graph
  3998. # TODO(jelmer): check refs
  3999. for sha in r.object_store:
  4000. o = r.object_store[sha]
  4001. try:
  4002. o.check()
  4003. except Exception as e:
  4004. yield (sha, e)
  4005. def stash_list(
  4006. repo: Union[str, os.PathLike[str], Repo],
  4007. ) -> Iterator[tuple[int, tuple[bytes, bytes]]]:
  4008. """List all stashes in a repository."""
  4009. with open_repo_closing(repo) as r:
  4010. from .stash import Stash
  4011. stash = Stash.from_repo(r)
  4012. entries = stash.stashes()
  4013. # Convert Entry objects to (old_sha, new_sha) tuples
  4014. return enumerate([(entry.old_sha, entry.new_sha) for entry in entries])
  4015. def stash_push(repo: Union[str, os.PathLike[str], Repo]) -> None:
  4016. """Push a new stash onto the stack."""
  4017. with open_repo_closing(repo) as r:
  4018. from .stash import Stash
  4019. stash = Stash.from_repo(r)
  4020. stash.push()
  4021. def stash_pop(repo: Union[str, os.PathLike[str], Repo]) -> None:
  4022. """Pop a stash from the stack."""
  4023. with open_repo_closing(repo) as r:
  4024. from .stash import Stash
  4025. stash = Stash.from_repo(r)
  4026. stash.pop(0)
  4027. def stash_drop(repo: Union[str, os.PathLike[str], Repo], index: int) -> None:
  4028. """Drop a stash from the stack."""
  4029. with open_repo_closing(repo) as r:
  4030. from .stash import Stash
  4031. stash = Stash.from_repo(r)
  4032. stash.drop(index)
  4033. def ls_files(repo: RepoPath) -> list[bytes]:
  4034. """List all files in an index."""
  4035. with open_repo_closing(repo) as r:
  4036. return sorted(r.open_index())
  4037. def find_unique_abbrev(
  4038. object_store: BaseObjectStore, object_id: Union[str, bytes], min_length: int = 7
  4039. ) -> str:
  4040. """Find the shortest unique abbreviation for an object ID.
  4041. Args:
  4042. object_store: Object store to search in
  4043. object_id: The full object ID to abbreviate
  4044. min_length: Minimum length of abbreviation (default 7)
  4045. Returns:
  4046. The shortest unique prefix of the object ID (at least min_length chars)
  4047. """
  4048. if isinstance(object_id, bytes):
  4049. hex_id = object_id.decode("ascii")
  4050. else:
  4051. hex_id = object_id
  4052. # Start with minimum length
  4053. for length in range(min_length, len(hex_id) + 1):
  4054. prefix = hex_id[:length]
  4055. matches = 0
  4056. # Check if this prefix is unique
  4057. for obj_id in object_store:
  4058. if obj_id.decode("ascii").startswith(prefix):
  4059. matches += 1
  4060. if matches > 1:
  4061. # Not unique, need more characters
  4062. break
  4063. if matches == 1:
  4064. # Found unique prefix
  4065. return prefix
  4066. # If we get here, return the full ID
  4067. return hex_id
  4068. def describe(
  4069. repo: Union[str, os.PathLike[str], Repo], abbrev: Optional[int] = None
  4070. ) -> str:
  4071. """Describe the repository version.
  4072. Args:
  4073. repo: git repository
  4074. abbrev: number of characters of commit to take, default is 7
  4075. Returns: a string description of the current git revision
  4076. Examples: "gabcdefh", "v0.1" or "v0.1-5-gabcdefh".
  4077. """
  4078. abbrev_slice = slice(0, abbrev if abbrev is not None else 7)
  4079. # Get the repository
  4080. with open_repo_closing(repo) as r:
  4081. # Get a list of all tags
  4082. refs = r.get_refs()
  4083. tags = {}
  4084. for key, value in refs.items():
  4085. key_str = key.decode()
  4086. obj = r.get_object(value)
  4087. if "tags" not in key_str:
  4088. continue
  4089. _, tag = key_str.rsplit("/", 1)
  4090. if isinstance(obj, Tag):
  4091. # Annotated tag case
  4092. commit = r.get_object(obj.object[1])
  4093. else:
  4094. # Lightweight tag case - obj is already the commit
  4095. commit = obj
  4096. if not isinstance(commit, Commit):
  4097. raise AssertionError(
  4098. f"Expected Commit object, got {type(commit).__name__}"
  4099. )
  4100. tag_info: list[Any] = [
  4101. datetime.datetime(*time.gmtime(commit.commit_time)[:6]),
  4102. commit.id.decode("ascii"),
  4103. ]
  4104. tags[tag] = tag_info
  4105. # Sort tags by datetime (first element of the value list)
  4106. sorted_tags = sorted(
  4107. tags.items(), key=lambda tag_item: tag_item[1][0], reverse=True
  4108. )
  4109. # Get the latest commit
  4110. latest_commit = r[r.head()]
  4111. # If there are no tags, return the latest commit
  4112. if len(sorted_tags) == 0:
  4113. if abbrev is not None:
  4114. return "g{}".format(latest_commit.id.decode("ascii")[abbrev_slice])
  4115. return f"g{find_unique_abbrev(r.object_store, latest_commit.id)}"
  4116. # We're now 0 commits from the top
  4117. commit_count = 0
  4118. # Walk through all commits
  4119. walker = r.get_walker()
  4120. for entry in walker:
  4121. # Check if tag
  4122. commit_id = entry.commit.id.decode("ascii")
  4123. for tag_item in sorted_tags:
  4124. tag_name = tag_item[0]
  4125. tag_commit = tag_item[1][1]
  4126. if commit_id == tag_commit:
  4127. if commit_count == 0:
  4128. return tag_name
  4129. else:
  4130. if abbrev is not None:
  4131. abbrev_hash = latest_commit.id.decode("ascii")[abbrev_slice]
  4132. else:
  4133. abbrev_hash = find_unique_abbrev(
  4134. r.object_store, latest_commit.id
  4135. )
  4136. return f"{tag_name}-{commit_count}-g{abbrev_hash}"
  4137. commit_count += 1
  4138. # Return plain commit if no parent tag can be found
  4139. if abbrev is not None:
  4140. return "g{}".format(latest_commit.id.decode("ascii")[abbrev_slice])
  4141. return f"g{find_unique_abbrev(r.object_store, latest_commit.id)}"
  4142. def get_object_by_path(
  4143. repo: RepoPath,
  4144. path: Union[str, bytes],
  4145. committish: Optional[Union[str, bytes, Commit, Tag]] = None,
  4146. ) -> Union[Blob, Tree, Commit, Tag]:
  4147. """Get an object by path.
  4148. Args:
  4149. repo: A path to the repository
  4150. path: Path to look up
  4151. committish: Commit to look up path in
  4152. Returns: A `ShaFile` object
  4153. """
  4154. if committish is None:
  4155. committish = "HEAD"
  4156. # Get the repository
  4157. with open_repo_closing(repo) as r:
  4158. commit = parse_commit(r, committish)
  4159. base_tree = commit.tree
  4160. if not isinstance(path, bytes):
  4161. path = commit_encode(commit, path)
  4162. (_mode, sha) = tree_lookup_path(r.object_store.__getitem__, base_tree, path)
  4163. obj = r[sha]
  4164. assert isinstance(obj, (Blob, Tree, Commit, Tag))
  4165. return obj
  4166. def write_tree(repo: RepoPath) -> bytes:
  4167. """Write a tree object from the index.
  4168. Args:
  4169. repo: Repository for which to write tree
  4170. Returns: tree id for the tree that was written
  4171. """
  4172. with open_repo_closing(repo) as r:
  4173. return r.open_index().commit(r.object_store)
  4174. def _do_merge(
  4175. r: Repo,
  4176. merge_commit_id: bytes,
  4177. no_commit: bool = False,
  4178. no_ff: bool = False,
  4179. message: Optional[bytes] = None,
  4180. author: Optional[bytes] = None,
  4181. committer: Optional[bytes] = None,
  4182. ) -> tuple[Optional[bytes], list[bytes]]:
  4183. """Internal merge implementation that operates on an open repository.
  4184. Args:
  4185. r: Open repository object
  4186. merge_commit_id: SHA of commit to merge
  4187. no_commit: If True, do not create a merge commit
  4188. no_ff: If True, force creation of a merge commit
  4189. message: Optional merge commit message
  4190. author: Optional author for merge commit
  4191. committer: Optional committer for merge commit
  4192. Returns:
  4193. Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None
  4194. if no_commit=True or there were conflicts
  4195. """
  4196. from .graph import find_merge_base
  4197. from .merge import three_way_merge
  4198. # Get HEAD commit
  4199. try:
  4200. head_commit_id = r.refs[b"HEAD"]
  4201. except KeyError:
  4202. raise Error("No HEAD reference found")
  4203. head_commit = r[head_commit_id]
  4204. assert isinstance(head_commit, Commit), "Expected a Commit object"
  4205. merge_commit = r[merge_commit_id]
  4206. assert isinstance(merge_commit, Commit), "Expected a Commit object"
  4207. # Check if fast-forward is possible
  4208. merge_bases = find_merge_base(r, [head_commit_id, merge_commit_id])
  4209. if not merge_bases:
  4210. raise Error("No common ancestor found")
  4211. # Use the first merge base
  4212. base_commit_id = merge_bases[0]
  4213. # Check if we're trying to merge the same commit
  4214. if head_commit_id == merge_commit_id:
  4215. # Already up to date
  4216. return (None, [])
  4217. # Check for fast-forward
  4218. if base_commit_id == head_commit_id and not no_ff:
  4219. # Fast-forward merge
  4220. r.refs[b"HEAD"] = merge_commit_id
  4221. # Update the working directory
  4222. changes = tree_changes(r.object_store, head_commit.tree, merge_commit.tree)
  4223. update_working_tree(
  4224. r, head_commit.tree, merge_commit.tree, change_iterator=changes
  4225. )
  4226. return (merge_commit_id, [])
  4227. if base_commit_id == merge_commit_id:
  4228. # Already up to date
  4229. return (None, [])
  4230. # Perform three-way merge
  4231. base_commit = r[base_commit_id]
  4232. assert isinstance(base_commit, Commit), "Expected a Commit object"
  4233. gitattributes = r.get_gitattributes()
  4234. config = r.get_config()
  4235. merged_tree, conflicts = three_way_merge(
  4236. r.object_store, base_commit, head_commit, merge_commit, gitattributes, config
  4237. )
  4238. # Add merged tree to object store
  4239. r.object_store.add_object(merged_tree)
  4240. # Update index and working directory
  4241. changes = tree_changes(r.object_store, head_commit.tree, merged_tree.id)
  4242. update_working_tree(r, head_commit.tree, merged_tree.id, change_iterator=changes)
  4243. if conflicts or no_commit:
  4244. # Don't create a commit if there are conflicts or no_commit is True
  4245. return (None, conflicts)
  4246. # Create merge commit
  4247. merge_commit_obj = Commit()
  4248. merge_commit_obj.tree = merged_tree.id
  4249. merge_commit_obj.parents = [head_commit_id, merge_commit_id]
  4250. # Set author/committer
  4251. if author is None:
  4252. author = get_user_identity(r.get_config_stack())
  4253. if committer is None:
  4254. committer = author
  4255. merge_commit_obj.author = author
  4256. merge_commit_obj.committer = committer
  4257. # Set timestamps
  4258. timestamp = int(time.time())
  4259. timezone = 0 # UTC
  4260. merge_commit_obj.author_time = timestamp
  4261. merge_commit_obj.author_timezone = timezone
  4262. merge_commit_obj.commit_time = timestamp
  4263. merge_commit_obj.commit_timezone = timezone
  4264. # Set commit message
  4265. if message is None:
  4266. message = f"Merge commit '{merge_commit_id.decode()[:7]}'\n".encode()
  4267. merge_commit_obj.message = message.encode() if isinstance(message, str) else message
  4268. # Add commit to object store
  4269. r.object_store.add_object(merge_commit_obj)
  4270. # Update HEAD
  4271. r.refs[b"HEAD"] = merge_commit_obj.id
  4272. return (merge_commit_obj.id, [])
  4273. def merge(
  4274. repo: Union[str, os.PathLike[str], Repo],
  4275. committish: Union[str, bytes, Commit, Tag],
  4276. no_commit: bool = False,
  4277. no_ff: bool = False,
  4278. message: Optional[bytes] = None,
  4279. author: Optional[bytes] = None,
  4280. committer: Optional[bytes] = None,
  4281. ) -> tuple[Optional[bytes], list[bytes]]:
  4282. """Merge a commit into the current branch.
  4283. Args:
  4284. repo: Repository to merge into
  4285. committish: Commit to merge
  4286. no_commit: If True, do not create a merge commit
  4287. no_ff: If True, force creation of a merge commit
  4288. message: Optional merge commit message
  4289. author: Optional author for merge commit
  4290. committer: Optional committer for merge commit
  4291. Returns:
  4292. Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None
  4293. if no_commit=True or there were conflicts
  4294. Raises:
  4295. Error: If there is no HEAD reference or commit cannot be found
  4296. """
  4297. with open_repo_closing(repo) as r:
  4298. # Parse the commit to merge
  4299. try:
  4300. merge_commit_id = parse_commit(r, committish).id
  4301. except KeyError:
  4302. raise Error(
  4303. f"Cannot find commit '{committish.decode() if isinstance(committish, bytes) else committish}'"
  4304. )
  4305. result = _do_merge(
  4306. r, merge_commit_id, no_commit, no_ff, message, author, committer
  4307. )
  4308. # Trigger auto GC if needed
  4309. from .gc import maybe_auto_gc
  4310. maybe_auto_gc(r)
  4311. return result
  4312. def unpack_objects(
  4313. pack_path: Union[str, os.PathLike[str]], target: Union[str, os.PathLike[str]] = "."
  4314. ) -> int:
  4315. """Unpack objects from a pack file into the repository.
  4316. Args:
  4317. pack_path: Path to the pack file to unpack
  4318. target: Path to the repository to unpack into
  4319. Returns:
  4320. Number of objects unpacked
  4321. """
  4322. from .pack import Pack
  4323. with open_repo_closing(target) as r:
  4324. pack_basename = os.path.splitext(pack_path)[0]
  4325. with Pack(pack_basename) as pack:
  4326. count = 0
  4327. for unpacked in pack.iter_unpacked():
  4328. obj = unpacked.sha_file()
  4329. r.object_store.add_object(obj)
  4330. count += 1
  4331. return count
  4332. def merge_tree(
  4333. repo: RepoPath,
  4334. base_tree: Optional[Union[str, bytes, Tree, Commit, Tag]],
  4335. our_tree: Union[str, bytes, Tree, Commit, Tag],
  4336. their_tree: Union[str, bytes, Tree, Commit, Tag],
  4337. ) -> tuple[bytes, list[bytes]]:
  4338. """Perform a three-way tree merge without touching the working directory.
  4339. This is similar to git merge-tree, performing a merge at the tree level
  4340. without creating commits or updating any references.
  4341. Args:
  4342. repo: Repository containing the trees
  4343. base_tree: Tree-ish of the common ancestor (or None for no common ancestor)
  4344. our_tree: Tree-ish of our side of the merge
  4345. their_tree: Tree-ish of their side of the merge
  4346. Returns:
  4347. tuple: A tuple of (merged_tree_id, conflicts) where:
  4348. - merged_tree_id is the SHA-1 of the merged tree
  4349. - conflicts is a list of paths (as bytes) that had conflicts
  4350. Raises:
  4351. KeyError: If any of the tree-ish arguments cannot be resolved
  4352. """
  4353. from .merge import Merger
  4354. with open_repo_closing(repo) as r:
  4355. # Resolve tree-ish arguments to actual trees
  4356. base = parse_tree(r, base_tree) if base_tree else None
  4357. ours = parse_tree(r, our_tree)
  4358. theirs = parse_tree(r, their_tree)
  4359. # Perform the merge
  4360. gitattributes = r.get_gitattributes()
  4361. config = r.get_config()
  4362. merger = Merger(r.object_store, gitattributes, config)
  4363. merged_tree, conflicts = merger.merge_trees(base, ours, theirs)
  4364. # Add the merged tree to the object store
  4365. r.object_store.add_object(merged_tree)
  4366. return merged_tree.id, conflicts
  4367. def cherry_pick( # noqa: D417
  4368. repo: Union[str, os.PathLike[str], Repo],
  4369. committish: Union[str, bytes, Commit, Tag, None],
  4370. no_commit: bool = False,
  4371. continue_: bool = False,
  4372. abort: bool = False,
  4373. ) -> Optional[bytes]:
  4374. r"""Cherry-pick a commit onto the current branch.
  4375. Args:
  4376. repo: Repository to cherry-pick into
  4377. committish: Commit to cherry-pick (can be None only when resuming or aborting)
  4378. no_commit: If True, do not create a commit after applying changes
  4379. ``continue_``: Resume an in-progress cherry-pick after resolving conflicts if True
  4380. abort: Abort an in-progress cherry-pick
  4381. Returns:
  4382. The SHA of the newly created commit, or None if no_commit=True or there were conflicts
  4383. Raises:
  4384. Error: If there is no HEAD reference, commit cannot be found, or operation fails
  4385. """
  4386. from .merge import three_way_merge
  4387. # Validate that committish is provided when needed
  4388. if not (continue_ or abort) and committish is None:
  4389. raise ValueError("committish is required when not using --continue or --abort")
  4390. with open_repo_closing(repo) as r:
  4391. # Handle abort
  4392. if abort:
  4393. # Clean up any cherry-pick state
  4394. try:
  4395. os.remove(os.path.join(r.controldir(), "CHERRY_PICK_HEAD"))
  4396. except FileNotFoundError:
  4397. pass
  4398. try:
  4399. os.remove(os.path.join(r.controldir(), "MERGE_MSG"))
  4400. except FileNotFoundError:
  4401. pass
  4402. # Reset index to HEAD
  4403. head_commit = r[b"HEAD"]
  4404. assert isinstance(head_commit, Commit)
  4405. r.get_worktree().reset_index(head_commit.tree)
  4406. return None
  4407. # Handle continue
  4408. if continue_:
  4409. # Check if there's a cherry-pick in progress
  4410. cherry_pick_head_path = os.path.join(r.controldir(), "CHERRY_PICK_HEAD")
  4411. try:
  4412. with open(cherry_pick_head_path, "rb") as f:
  4413. cherry_pick_commit_id = f.read().strip()
  4414. cherry_pick_commit = r[cherry_pick_commit_id]
  4415. except FileNotFoundError:
  4416. raise Error("No cherry-pick in progress")
  4417. # Check for unresolved conflicts
  4418. if r.open_index().has_conflicts():
  4419. raise Error("Unresolved conflicts remain")
  4420. # Create the commit
  4421. tree_id = r.open_index().commit(r.object_store)
  4422. # Read saved message if any
  4423. merge_msg_path = os.path.join(r.controldir(), "MERGE_MSG")
  4424. try:
  4425. with open(merge_msg_path, "rb") as f:
  4426. message = f.read()
  4427. except FileNotFoundError:
  4428. assert isinstance(cherry_pick_commit, Commit)
  4429. message = cherry_pick_commit.message
  4430. assert isinstance(cherry_pick_commit, Commit)
  4431. new_commit = r.get_worktree().commit(
  4432. message=message,
  4433. tree=tree_id,
  4434. author=cherry_pick_commit.author,
  4435. author_timestamp=cherry_pick_commit.author_time,
  4436. author_timezone=cherry_pick_commit.author_timezone,
  4437. )
  4438. # Clean up state files
  4439. try:
  4440. os.remove(cherry_pick_head_path)
  4441. except FileNotFoundError:
  4442. pass
  4443. try:
  4444. os.remove(merge_msg_path)
  4445. except FileNotFoundError:
  4446. pass
  4447. return new_commit
  4448. # Normal cherry-pick operation
  4449. # Get current HEAD
  4450. try:
  4451. head_commit = r[b"HEAD"]
  4452. except KeyError:
  4453. raise Error("No HEAD reference found")
  4454. # Parse the commit to cherry-pick
  4455. # committish cannot be None here due to validation above
  4456. assert committish is not None
  4457. try:
  4458. cherry_pick_commit = parse_commit(r, committish)
  4459. except KeyError:
  4460. raise Error(
  4461. f"Cannot find commit '{committish.decode() if isinstance(committish, bytes) else committish}'"
  4462. )
  4463. # Check if commit has parents
  4464. assert isinstance(cherry_pick_commit, Commit)
  4465. if not cherry_pick_commit.parents:
  4466. raise Error("Cannot cherry-pick root commit")
  4467. # Get parent of cherry-pick commit
  4468. parent_commit = r[cherry_pick_commit.parents[0]]
  4469. assert isinstance(parent_commit, Commit)
  4470. # Perform three-way merge
  4471. assert isinstance(head_commit, Commit)
  4472. merged_tree, conflicts = three_way_merge(
  4473. r.object_store, parent_commit, head_commit, cherry_pick_commit
  4474. )
  4475. # Add merged tree to object store
  4476. r.object_store.add_object(merged_tree)
  4477. # Update working tree and index
  4478. # Reset index to match merged tree
  4479. r.get_worktree().reset_index(merged_tree.id)
  4480. # Update working tree from the new index
  4481. # Allow overwriting because we're applying the merge result
  4482. assert isinstance(head_commit, Commit)
  4483. changes = tree_changes(r.object_store, head_commit.tree, merged_tree.id)
  4484. update_working_tree(
  4485. r,
  4486. head_commit.tree,
  4487. merged_tree.id,
  4488. change_iterator=changes,
  4489. allow_overwrite_modified=True,
  4490. )
  4491. if conflicts:
  4492. # Save state for later continuation
  4493. with open(os.path.join(r.controldir(), "CHERRY_PICK_HEAD"), "wb") as f:
  4494. f.write(cherry_pick_commit.id + b"\n")
  4495. # Save commit message
  4496. with open(os.path.join(r.controldir(), "MERGE_MSG"), "wb") as f:
  4497. f.write(cherry_pick_commit.message)
  4498. raise Error(
  4499. f"Conflicts in: {', '.join(c.decode('utf-8', 'replace') for c in conflicts)}\n"
  4500. f"Fix conflicts and run 'dulwich cherry-pick --continue'"
  4501. )
  4502. if no_commit:
  4503. return None
  4504. # Create the commit
  4505. new_commit = r.get_worktree().commit(
  4506. message=cherry_pick_commit.message,
  4507. tree=merged_tree.id,
  4508. author=cherry_pick_commit.author,
  4509. author_timestamp=cherry_pick_commit.author_time,
  4510. author_timezone=cherry_pick_commit.author_timezone,
  4511. )
  4512. return new_commit
  4513. def revert(
  4514. repo: Union[str, os.PathLike[str], Repo],
  4515. commits: Union[str, bytes, Commit, Tag, Sequence[Union[str, bytes, Commit, Tag]]],
  4516. no_commit: bool = False,
  4517. message: Optional[Union[str, bytes]] = None,
  4518. author: Optional[bytes] = None,
  4519. committer: Optional[bytes] = None,
  4520. ) -> Optional[bytes]:
  4521. """Revert one or more commits.
  4522. This creates a new commit that undoes the changes introduced by the
  4523. specified commits. Unlike reset, revert creates a new commit that
  4524. preserves history.
  4525. Args:
  4526. repo: Path to repository or repository object
  4527. commits: List of commit-ish (SHA, ref, etc.) to revert, or a single commit-ish
  4528. no_commit: If True, apply changes to index/working tree but don't commit
  4529. message: Optional commit message (default: "Revert <original subject>")
  4530. author: Optional author for revert commit
  4531. committer: Optional committer for revert commit
  4532. Returns:
  4533. SHA1 of the new revert commit, or None if no_commit=True
  4534. Raises:
  4535. Error: If revert fails due to conflicts or other issues
  4536. """
  4537. from .merge import three_way_merge
  4538. # Normalize commits to a list
  4539. if isinstance(commits, (str, bytes, Commit, Tag)):
  4540. commits = [commits]
  4541. with open_repo_closing(repo) as r:
  4542. # Convert string refs to bytes
  4543. commits_to_revert = []
  4544. for commit_ref in commits:
  4545. if isinstance(commit_ref, str):
  4546. commit_ref = commit_ref.encode("utf-8")
  4547. commit = parse_commit(r, commit_ref)
  4548. commits_to_revert.append(commit)
  4549. # Get current HEAD
  4550. try:
  4551. head_commit_id = r.refs[b"HEAD"]
  4552. except KeyError:
  4553. raise Error("No HEAD reference found")
  4554. head_commit = r[head_commit_id]
  4555. assert isinstance(head_commit, Commit)
  4556. current_tree = head_commit.tree
  4557. # Process commits in order
  4558. for commit_to_revert in commits_to_revert:
  4559. # For revert, we want to apply the inverse of the commit
  4560. # This means using the commit's tree as "base" and its parent as "theirs"
  4561. if not commit_to_revert.parents:
  4562. raise Error(
  4563. 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"
  4564. )
  4565. # For simplicity, we only handle commits with one parent (no merge commits)
  4566. if len(commit_to_revert.parents) > 1:
  4567. raise Error(
  4568. 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"
  4569. )
  4570. parent_commit = r[commit_to_revert.parents[0]]
  4571. assert isinstance(parent_commit, Commit)
  4572. # Perform three-way merge:
  4573. # - base: the commit we're reverting (what we want to remove)
  4574. # - ours: current HEAD (what we have now)
  4575. # - theirs: parent of commit being reverted (what we want to go back to)
  4576. assert isinstance(commit_to_revert, Commit)
  4577. head_for_merge = r[head_commit_id]
  4578. assert isinstance(head_for_merge, Commit)
  4579. merged_tree, conflicts = three_way_merge(
  4580. r.object_store,
  4581. commit_to_revert, # base
  4582. head_for_merge, # ours
  4583. parent_commit, # theirs
  4584. )
  4585. if conflicts:
  4586. # Update working tree with conflicts
  4587. changes = tree_changes(r.object_store, current_tree, merged_tree.id)
  4588. update_working_tree(
  4589. r, current_tree, merged_tree.id, change_iterator=changes
  4590. )
  4591. conflicted_paths = [c.decode("utf-8", "replace") for c in conflicts]
  4592. raise Error(f"Conflicts while reverting: {', '.join(conflicted_paths)}")
  4593. # Add merged tree to object store
  4594. r.object_store.add_object(merged_tree)
  4595. # Update working tree
  4596. changes = tree_changes(r.object_store, current_tree, merged_tree.id)
  4597. update_working_tree(
  4598. r, current_tree, merged_tree.id, change_iterator=changes
  4599. )
  4600. current_tree = merged_tree.id
  4601. if not no_commit:
  4602. # Create revert commit
  4603. revert_commit = Commit()
  4604. revert_commit.tree = merged_tree.id
  4605. revert_commit.parents = [head_commit_id]
  4606. # Set author/committer
  4607. if author is None:
  4608. author = get_user_identity(r.get_config_stack())
  4609. if committer is None:
  4610. committer = author
  4611. revert_commit.author = author
  4612. revert_commit.committer = committer
  4613. # Set timestamps
  4614. timestamp = int(time.time())
  4615. timezone = 0 # UTC
  4616. revert_commit.author_time = timestamp
  4617. revert_commit.author_timezone = timezone
  4618. revert_commit.commit_time = timestamp
  4619. revert_commit.commit_timezone = timezone
  4620. # Set message
  4621. if message is None:
  4622. # Extract original commit subject
  4623. original_message = commit_to_revert.message
  4624. if isinstance(original_message, bytes):
  4625. original_message = original_message.decode("utf-8", "replace")
  4626. subject = original_message.split("\n")[0]
  4627. message = f'Revert "{subject}"\n\nThis reverts commit {commit_to_revert.id.decode("ascii")}.'.encode()
  4628. elif isinstance(message, str):
  4629. message = message.encode("utf-8")
  4630. revert_commit.message = message
  4631. # Add commit to object store
  4632. r.object_store.add_object(revert_commit)
  4633. # Update HEAD
  4634. r.refs[b"HEAD"] = revert_commit.id
  4635. head_commit_id = revert_commit.id
  4636. return head_commit_id if not no_commit else None
  4637. def gc(
  4638. repo: RepoPath,
  4639. auto: bool = False,
  4640. aggressive: bool = False,
  4641. prune: bool = True,
  4642. grace_period: Optional[int] = 1209600, # 2 weeks default
  4643. dry_run: bool = False,
  4644. progress: Optional[Callable[[str], None]] = None,
  4645. ) -> "GCStats":
  4646. """Run garbage collection on a repository.
  4647. Args:
  4648. repo: Path to the repository or a Repo object
  4649. auto: If True, only run gc if needed
  4650. aggressive: If True, use more aggressive settings
  4651. prune: If True, prune unreachable objects
  4652. grace_period: Grace period in seconds for pruning (default 2 weeks)
  4653. dry_run: If True, only report what would be done
  4654. progress: Optional progress callback
  4655. Returns:
  4656. GCStats object with garbage collection statistics
  4657. """
  4658. from .gc import garbage_collect
  4659. with open_repo_closing(repo) as r:
  4660. return garbage_collect(
  4661. r,
  4662. auto=auto,
  4663. aggressive=aggressive,
  4664. prune=prune,
  4665. grace_period=grace_period,
  4666. dry_run=dry_run,
  4667. progress=progress,
  4668. )
  4669. def prune(
  4670. repo: RepoPath,
  4671. grace_period: Optional[int] = None,
  4672. dry_run: bool = False,
  4673. progress: Optional[Callable[[str], None]] = None,
  4674. ) -> None:
  4675. """Prune/clean up a repository's object store.
  4676. This removes temporary files that were left behind by interrupted
  4677. pack operations.
  4678. Args:
  4679. repo: Path to the repository or a Repo object
  4680. grace_period: Grace period in seconds for removing temporary files
  4681. (default 2 weeks)
  4682. dry_run: If True, only report what would be done
  4683. progress: Optional progress callback
  4684. """
  4685. with open_repo_closing(repo) as r:
  4686. if progress:
  4687. progress("Pruning temporary files")
  4688. if not dry_run:
  4689. r.object_store.prune(grace_period=grace_period)
  4690. def count_objects(repo: RepoPath = ".", verbose: bool = False) -> CountObjectsResult:
  4691. """Count unpacked objects and their disk usage.
  4692. Args:
  4693. repo: Path to repository or repository object
  4694. verbose: Whether to return verbose information
  4695. Returns:
  4696. CountObjectsResult object with detailed statistics
  4697. """
  4698. with open_repo_closing(repo) as r:
  4699. object_store = r.object_store
  4700. # Count loose objects
  4701. loose_count = 0
  4702. loose_size = 0
  4703. for sha in object_store._iter_loose_objects():
  4704. loose_count += 1
  4705. from .object_store import DiskObjectStore
  4706. assert isinstance(object_store, DiskObjectStore)
  4707. path = object_store._get_shafile_path(sha)
  4708. try:
  4709. stat_info = os.stat(path)
  4710. # Git uses disk usage, not file size. st_blocks is always in
  4711. # 512-byte blocks per POSIX standard
  4712. st_blocks = getattr(stat_info, "st_blocks", None)
  4713. if st_blocks is not None:
  4714. # Available on Linux and macOS
  4715. loose_size += st_blocks * 512
  4716. else:
  4717. # Fallback for Windows
  4718. loose_size += stat_info.st_size
  4719. except FileNotFoundError:
  4720. # Object may have been removed between iteration and stat
  4721. pass
  4722. if not verbose:
  4723. return CountObjectsResult(count=loose_count, size=loose_size)
  4724. # Count pack information
  4725. pack_count = len(object_store.packs)
  4726. in_pack_count = 0
  4727. pack_size = 0
  4728. for pack in object_store.packs:
  4729. in_pack_count += len(pack)
  4730. # Get pack file size
  4731. pack_path = pack._data_path
  4732. try:
  4733. pack_size += os.path.getsize(pack_path)
  4734. except FileNotFoundError:
  4735. pass
  4736. # Get index file size
  4737. idx_path = pack._idx_path
  4738. try:
  4739. pack_size += os.path.getsize(idx_path)
  4740. except FileNotFoundError:
  4741. pass
  4742. return CountObjectsResult(
  4743. count=loose_count,
  4744. size=loose_size,
  4745. in_pack=in_pack_count,
  4746. packs=pack_count,
  4747. size_pack=pack_size,
  4748. )
  4749. def is_interactive_rebase(repo: Union[Repo, str]) -> bool:
  4750. """Check if an interactive rebase is in progress.
  4751. Args:
  4752. repo: Repository to check
  4753. Returns:
  4754. True if interactive rebase is in progress, False otherwise
  4755. """
  4756. with open_repo_closing(repo) as r:
  4757. state_manager = r.get_rebase_state_manager()
  4758. if not state_manager.exists():
  4759. return False
  4760. # Check if todo file exists
  4761. todo = state_manager.load_todo()
  4762. return todo is not None
  4763. def rebase(
  4764. repo: Union[Repo, str],
  4765. upstream: Union[bytes, str],
  4766. onto: Optional[Union[bytes, str]] = None,
  4767. branch: Optional[Union[bytes, str]] = None,
  4768. abort: bool = False,
  4769. continue_rebase: bool = False,
  4770. skip: bool = False,
  4771. interactive: bool = False,
  4772. edit_todo: bool = False,
  4773. ) -> list[bytes]:
  4774. """Rebase commits onto another branch.
  4775. Args:
  4776. repo: Repository to rebase in
  4777. upstream: Upstream branch/commit to rebase onto
  4778. onto: Specific commit to rebase onto (defaults to upstream)
  4779. branch: Branch to rebase (defaults to current branch)
  4780. abort: Abort an in-progress rebase
  4781. continue_rebase: Continue an in-progress rebase
  4782. skip: Skip current commit and continue rebase
  4783. interactive: Start an interactive rebase
  4784. edit_todo: Edit the todo list of an interactive rebase
  4785. Returns:
  4786. List of new commit SHAs created by rebase
  4787. Raises:
  4788. Error: If rebase fails or conflicts occur
  4789. """
  4790. from .cli import launch_editor
  4791. from .rebase import (
  4792. RebaseConflict,
  4793. RebaseError,
  4794. Rebaser,
  4795. process_interactive_rebase,
  4796. start_interactive,
  4797. )
  4798. from .rebase import (
  4799. edit_todo as edit_todo_func,
  4800. )
  4801. with open_repo_closing(repo) as r:
  4802. rebaser = Rebaser(r)
  4803. if abort:
  4804. try:
  4805. rebaser.abort()
  4806. return []
  4807. except RebaseError as e:
  4808. raise Error(str(e))
  4809. if edit_todo:
  4810. # Edit the todo list of an interactive rebase
  4811. try:
  4812. edit_todo_func(r, launch_editor)
  4813. print("Todo list updated. Continue with 'rebase --continue'")
  4814. return []
  4815. except RebaseError as e:
  4816. raise Error(str(e))
  4817. if continue_rebase:
  4818. try:
  4819. if interactive:
  4820. # Continue interactive rebase
  4821. is_complete, pause_reason = process_interactive_rebase(
  4822. r, editor_callback=launch_editor
  4823. )
  4824. if is_complete:
  4825. return [c.id for c in rebaser._done]
  4826. else:
  4827. if pause_reason == "conflict":
  4828. raise Error("Conflicts detected. Resolve and continue.")
  4829. elif pause_reason == "edit":
  4830. print("Stopped for editing. Make changes and continue.")
  4831. elif pause_reason == "break":
  4832. print("Rebase paused at break. Continue when ready.")
  4833. else:
  4834. print(f"Rebase paused: {pause_reason}")
  4835. return []
  4836. else:
  4837. # Continue regular rebase
  4838. result = rebaser.continue_()
  4839. if result is None:
  4840. # Rebase complete
  4841. return [c.id for c in rebaser._done]
  4842. elif isinstance(result, tuple) and result[1]:
  4843. # Still have conflicts
  4844. raise Error(
  4845. f"Conflicts in: {', '.join(f.decode('utf-8', 'replace') for f in result[1])}"
  4846. )
  4847. except RebaseError as e:
  4848. raise Error(str(e))
  4849. # Convert string refs to bytes
  4850. if isinstance(upstream, str):
  4851. upstream = upstream.encode("utf-8")
  4852. if isinstance(onto, str):
  4853. onto = onto.encode("utf-8") if onto else None
  4854. if isinstance(branch, str):
  4855. branch = branch.encode("utf-8") if branch else None
  4856. try:
  4857. if interactive:
  4858. # Start interactive rebase
  4859. todo = start_interactive(r, upstream, onto, branch, launch_editor)
  4860. # Process the todo list
  4861. is_complete, pause_reason = process_interactive_rebase(
  4862. r, todo, editor_callback=launch_editor
  4863. )
  4864. if is_complete:
  4865. return [c.id for c in rebaser._done]
  4866. else:
  4867. if pause_reason == "conflict":
  4868. raise Error("Conflicts detected. Resolve and continue.")
  4869. elif pause_reason == "edit":
  4870. print("Stopped for editing. Make changes and continue.")
  4871. elif pause_reason == "break":
  4872. print("Rebase paused at break. Continue when ready.")
  4873. else:
  4874. print(f"Rebase paused: {pause_reason}")
  4875. return []
  4876. else:
  4877. # Regular rebase
  4878. rebaser.start(upstream, onto, branch)
  4879. # Continue rebase automatically
  4880. result = rebaser.continue_()
  4881. if result is not None:
  4882. # Conflicts
  4883. raise RebaseConflict(result[1])
  4884. # Return the SHAs of the rebased commits
  4885. return [c.id for c in rebaser._done]
  4886. except RebaseConflict as e:
  4887. raise Error(str(e))
  4888. except RebaseError as e:
  4889. raise Error(str(e))
  4890. def annotate(
  4891. repo: RepoPath,
  4892. path: Union[str, bytes],
  4893. committish: Optional[Union[str, bytes, Commit, Tag]] = None,
  4894. ) -> list[tuple[tuple[Commit, TreeEntry], bytes]]:
  4895. """Annotate the history of a file.
  4896. :param repo: Path to the repository
  4897. :param path: Path to annotate
  4898. :param committish: Commit id to find path in
  4899. :return: List of ((Commit, TreeChange), line) tuples
  4900. """
  4901. if committish is None:
  4902. committish = "HEAD"
  4903. from dulwich.annotate import annotate_lines
  4904. with open_repo_closing(repo) as r:
  4905. commit_id = parse_commit(r, committish).id
  4906. # Ensure path is bytes
  4907. if isinstance(path, str):
  4908. path = path.encode()
  4909. return annotate_lines(r.object_store, commit_id, path)
  4910. blame = annotate
  4911. def filter_branch(
  4912. repo: RepoPath = ".",
  4913. branch: Union[str, bytes] = "HEAD",
  4914. *,
  4915. filter_fn: Optional[Callable[[Commit], Optional["CommitData"]]] = None,
  4916. filter_author: Optional[Callable[[bytes], Optional[bytes]]] = None,
  4917. filter_committer: Optional[Callable[[bytes], Optional[bytes]]] = None,
  4918. filter_message: Optional[Callable[[bytes], Optional[bytes]]] = None,
  4919. tree_filter: Optional[Callable[[bytes, str], Optional[bytes]]] = None,
  4920. index_filter: Optional[Callable[[bytes, str], Optional[bytes]]] = None,
  4921. parent_filter: Optional[Callable[[Sequence[bytes]], list[bytes]]] = None,
  4922. commit_filter: Optional[Callable[[Commit, bytes], Optional[bytes]]] = None,
  4923. subdirectory_filter: Optional[Union[str, bytes]] = None,
  4924. prune_empty: bool = False,
  4925. tag_name_filter: Optional[Callable[[bytes], Optional[bytes]]] = None,
  4926. force: bool = False,
  4927. keep_original: bool = True,
  4928. refs: Optional[list[bytes]] = None,
  4929. ) -> dict[bytes, bytes]:
  4930. """Rewrite branch history by creating new commits with filtered properties.
  4931. This is similar to git filter-branch, allowing you to rewrite commit
  4932. history by modifying trees, parents, author, committer, or commit messages.
  4933. Args:
  4934. repo: Path to repository
  4935. branch: Branch to rewrite (defaults to HEAD)
  4936. filter_fn: Optional callable that takes a Commit object and returns
  4937. a dict of updated fields (author, committer, message, etc.)
  4938. filter_author: Optional callable that takes author bytes and returns
  4939. updated author bytes or None to keep unchanged
  4940. filter_committer: Optional callable that takes committer bytes and returns
  4941. updated committer bytes or None to keep unchanged
  4942. filter_message: Optional callable that takes commit message bytes
  4943. and returns updated message bytes
  4944. tree_filter: Optional callable that takes (tree_sha, temp_dir) and returns
  4945. new tree SHA after modifying working directory
  4946. index_filter: Optional callable that takes (tree_sha, temp_index_path) and
  4947. returns new tree SHA after modifying index
  4948. parent_filter: Optional callable that takes parent list and returns
  4949. modified parent list
  4950. commit_filter: Optional callable that takes (Commit, tree_sha) and returns
  4951. new commit SHA or None to skip commit
  4952. subdirectory_filter: Optional subdirectory path to extract as new root
  4953. prune_empty: Whether to prune commits that become empty
  4954. tag_name_filter: Optional callable to rename tags
  4955. force: Force operation even if branch has been filtered before
  4956. keep_original: Keep original refs under refs/original/
  4957. refs: List of refs to rewrite (defaults to [branch])
  4958. Returns:
  4959. Dict mapping old commit SHAs to new commit SHAs
  4960. Raises:
  4961. Error: If branch is already filtered and force is False
  4962. """
  4963. from .filter_branch import CommitFilter, filter_refs
  4964. with open_repo_closing(repo) as r:
  4965. # Parse branch/committish
  4966. if isinstance(branch, str):
  4967. branch = branch.encode()
  4968. # Determine which refs to process
  4969. if refs is None:
  4970. if branch == b"HEAD":
  4971. # Resolve HEAD to actual branch
  4972. try:
  4973. resolved = r.refs.follow(b"HEAD")
  4974. if resolved and resolved[0]:
  4975. # resolved is a list of (refname, sha) tuples
  4976. resolved_ref = resolved[0][-1]
  4977. if resolved_ref and resolved_ref != b"HEAD":
  4978. refs = [resolved_ref]
  4979. else:
  4980. # HEAD points directly to a commit
  4981. refs = [b"HEAD"]
  4982. else:
  4983. refs = [b"HEAD"]
  4984. except SymrefLoop:
  4985. refs = [b"HEAD"]
  4986. else:
  4987. # Convert branch name to full ref if needed
  4988. if not branch.startswith(b"refs/"):
  4989. branch = b"refs/heads/" + branch
  4990. refs = [branch]
  4991. # Convert subdirectory filter to bytes if needed
  4992. if subdirectory_filter:
  4993. if isinstance(subdirectory_filter, str):
  4994. subdirectory_filter = subdirectory_filter.encode()
  4995. else:
  4996. subdirectory_filter = None
  4997. # Create commit filter
  4998. filter_obj = CommitFilter(
  4999. r.object_store,
  5000. filter_fn=filter_fn,
  5001. filter_author=filter_author,
  5002. filter_committer=filter_committer,
  5003. filter_message=filter_message,
  5004. tree_filter=tree_filter,
  5005. index_filter=index_filter,
  5006. parent_filter=parent_filter,
  5007. commit_filter=commit_filter,
  5008. subdirectory_filter=subdirectory_filter,
  5009. prune_empty=prune_empty,
  5010. tag_name_filter=tag_name_filter,
  5011. )
  5012. # Tag callback for renaming tags
  5013. def rename_tag(old_ref: bytes, new_ref: bytes) -> None:
  5014. # Copy tag to new name
  5015. r.refs[new_ref] = r.refs[old_ref]
  5016. # Delete old tag
  5017. del r.refs[old_ref]
  5018. # Filter refs
  5019. try:
  5020. return filter_refs(
  5021. r.refs,
  5022. r.object_store,
  5023. refs,
  5024. filter_obj,
  5025. keep_original=keep_original,
  5026. force=force,
  5027. tag_callback=rename_tag if tag_name_filter else None,
  5028. )
  5029. except ValueError as e:
  5030. raise Error(str(e)) from e
  5031. def format_patch(
  5032. repo: RepoPath = ".",
  5033. committish: Optional[Union[bytes, tuple[bytes, bytes]]] = None,
  5034. outstream: TextIO = sys.stdout,
  5035. outdir: Optional[Union[str, os.PathLike[str]]] = None,
  5036. n: int = 1,
  5037. stdout: bool = False,
  5038. version: Optional[str] = None,
  5039. ) -> list[str]:
  5040. """Generate patches suitable for git am.
  5041. Args:
  5042. repo: Path to repository
  5043. committish: Commit-ish or commit range to generate patches for.
  5044. Can be a single commit id, or a tuple of (start, end) commit ids
  5045. for a range. If None, formats the last n commits from HEAD.
  5046. outstream: Stream to write to if stdout=True
  5047. outdir: Directory to write patch files to (default: current directory)
  5048. n: Number of patches to generate if committish is None
  5049. stdout: Write patches to stdout instead of files
  5050. version: Version string to include in patches (default: Dulwich version)
  5051. Returns:
  5052. List of patch filenames that were created (empty if stdout=True)
  5053. """
  5054. if outdir is None:
  5055. outdir = "."
  5056. filenames = []
  5057. with open_repo_closing(repo) as r:
  5058. # Determine which commits to format
  5059. commits_to_format = []
  5060. if committish is None:
  5061. # Get the last n commits from HEAD
  5062. try:
  5063. walker = r.get_walker()
  5064. for entry in walker:
  5065. commits_to_format.append(entry.commit)
  5066. if len(commits_to_format) >= n:
  5067. break
  5068. commits_to_format.reverse()
  5069. except KeyError:
  5070. # No HEAD or empty repository
  5071. pass
  5072. elif isinstance(committish, tuple):
  5073. # Handle commit range (start, end)
  5074. start_commit, end_commit = committish
  5075. # Extract commit IDs from commit objects if needed
  5076. start_id = (
  5077. start_commit.id if isinstance(start_commit, Commit) else start_commit
  5078. )
  5079. end_id = end_commit.id if isinstance(end_commit, Commit) else end_commit
  5080. # Walk from end back to start
  5081. walker = r.get_walker(include=[end_id], exclude=[start_id])
  5082. for entry in walker:
  5083. commits_to_format.append(entry.commit)
  5084. commits_to_format.reverse()
  5085. else:
  5086. # Single commit
  5087. commit = r.object_store[committish]
  5088. assert isinstance(commit, Commit)
  5089. commits_to_format.append(commit)
  5090. # Generate patches
  5091. total = len(commits_to_format)
  5092. for i, commit in enumerate(commits_to_format, 1):
  5093. assert isinstance(commit, Commit)
  5094. # Get the parent
  5095. if commit.parents:
  5096. parent_id = commit.parents[0]
  5097. parent = r.object_store[parent_id]
  5098. assert isinstance(parent, Commit)
  5099. else:
  5100. parent = None
  5101. # Generate the diff
  5102. from io import BytesIO
  5103. diff_content = BytesIO()
  5104. if parent:
  5105. write_tree_diff(
  5106. diff_content,
  5107. r.object_store,
  5108. parent.tree,
  5109. commit.tree,
  5110. )
  5111. else:
  5112. # Initial commit - diff against empty tree
  5113. write_tree_diff(
  5114. diff_content,
  5115. r.object_store,
  5116. None,
  5117. commit.tree,
  5118. )
  5119. # Generate patch with commit metadata
  5120. if stdout:
  5121. # Get binary stream from TextIO
  5122. if hasattr(outstream, "buffer"):
  5123. binary_out: IO[bytes] = outstream.buffer
  5124. else:
  5125. # Fallback for non-text streams
  5126. binary_out = outstream # type: ignore[assignment]
  5127. write_commit_patch(
  5128. binary_out,
  5129. commit,
  5130. diff_content.getvalue(),
  5131. (i, total),
  5132. version=version,
  5133. )
  5134. else:
  5135. # Generate filename
  5136. summary = get_summary(commit)
  5137. filename = os.path.join(outdir, f"{i:04d}-{summary}.patch")
  5138. with open(filename, "wb") as f:
  5139. write_commit_patch(
  5140. f,
  5141. commit,
  5142. diff_content.getvalue(),
  5143. (i, total),
  5144. version=version,
  5145. )
  5146. filenames.append(filename)
  5147. return filenames
  5148. def bisect_start(
  5149. repo: Union[str, os.PathLike[str], Repo] = ".",
  5150. bad: Optional[Union[str, bytes, Commit, Tag]] = None,
  5151. good: Optional[
  5152. Union[str, bytes, Commit, Tag, Sequence[Union[str, bytes, Commit, Tag]]]
  5153. ] = None,
  5154. paths: Optional[Sequence[bytes]] = None,
  5155. no_checkout: bool = False,
  5156. term_bad: str = "bad",
  5157. term_good: str = "good",
  5158. ) -> Optional[bytes]:
  5159. """Start a new bisect session.
  5160. Args:
  5161. repo: Path to repository or a Repo object
  5162. bad: The bad commit (defaults to HEAD)
  5163. good: List of good commits or a single good commit
  5164. paths: Optional paths to limit bisect to
  5165. no_checkout: If True, don't checkout commits during bisect
  5166. term_bad: Term to use for bad commits (default: "bad")
  5167. term_good: Term to use for good commits (default: "good")
  5168. """
  5169. with open_repo_closing(repo) as r:
  5170. state = BisectState(r)
  5171. # Convert single good commit to sequence
  5172. if good is not None and isinstance(good, (str, bytes, Commit, Tag)):
  5173. good = [good]
  5174. # Parse commits
  5175. bad_sha = parse_commit(r, bad).id if bad else None
  5176. good_shas = [parse_commit(r, g).id for g in good] if good else None
  5177. state.start(bad_sha, good_shas, paths, no_checkout, term_bad, term_good)
  5178. # Return the next commit to test if we have both good and bad
  5179. if bad_sha and good_shas:
  5180. next_sha = state._find_next_commit()
  5181. if next_sha and not no_checkout:
  5182. # Checkout the next commit
  5183. old_commit = r[r.head()]
  5184. assert isinstance(old_commit, Commit)
  5185. old_tree = old_commit.tree if r.head() else None
  5186. r.refs[b"HEAD"] = next_sha
  5187. commit = r[next_sha]
  5188. assert isinstance(commit, Commit)
  5189. changes = tree_changes(r.object_store, old_tree, commit.tree)
  5190. update_working_tree(r, old_tree, commit.tree, change_iterator=changes)
  5191. return next_sha
  5192. return None
  5193. def bisect_bad(
  5194. repo: Union[str, os.PathLike[str], Repo] = ".",
  5195. rev: Optional[Union[str, bytes, Commit, Tag]] = None,
  5196. ) -> Optional[bytes]:
  5197. """Mark a commit as bad.
  5198. Args:
  5199. repo: Path to repository or a Repo object
  5200. rev: Commit to mark as bad (defaults to HEAD)
  5201. Returns:
  5202. The SHA of the next commit to test, or None if bisect is complete
  5203. """
  5204. with open_repo_closing(repo) as r:
  5205. state = BisectState(r)
  5206. rev_sha = parse_commit(r, rev).id if rev else None
  5207. next_sha = state.mark_bad(rev_sha)
  5208. if next_sha:
  5209. # Checkout the next commit
  5210. old_commit = r[r.head()]
  5211. assert isinstance(old_commit, Commit)
  5212. old_tree = old_commit.tree if r.head() else None
  5213. r.refs[b"HEAD"] = next_sha
  5214. commit = r[next_sha]
  5215. assert isinstance(commit, Commit)
  5216. changes = tree_changes(r.object_store, old_tree, commit.tree)
  5217. update_working_tree(r, old_tree, commit.tree, change_iterator=changes)
  5218. return next_sha
  5219. def bisect_good(
  5220. repo: Union[str, os.PathLike[str], Repo] = ".",
  5221. rev: Optional[Union[str, bytes, Commit, Tag]] = None,
  5222. ) -> Optional[bytes]:
  5223. """Mark a commit as good.
  5224. Args:
  5225. repo: Path to repository or a Repo object
  5226. rev: Commit to mark as good (defaults to HEAD)
  5227. Returns:
  5228. The SHA of the next commit to test, or None if bisect is complete
  5229. """
  5230. with open_repo_closing(repo) as r:
  5231. state = BisectState(r)
  5232. rev_sha = parse_commit(r, rev).id if rev else None
  5233. next_sha = state.mark_good(rev_sha)
  5234. if next_sha:
  5235. # Checkout the next commit
  5236. old_commit = r[r.head()]
  5237. assert isinstance(old_commit, Commit)
  5238. old_tree = old_commit.tree if r.head() else None
  5239. r.refs[b"HEAD"] = next_sha
  5240. commit = r[next_sha]
  5241. assert isinstance(commit, Commit)
  5242. changes = tree_changes(r.object_store, old_tree, commit.tree)
  5243. update_working_tree(r, old_tree, commit.tree, change_iterator=changes)
  5244. return next_sha
  5245. def bisect_skip(
  5246. repo: Union[str, os.PathLike[str], Repo] = ".",
  5247. revs: Optional[
  5248. Union[str, bytes, Commit, Tag, Sequence[Union[str, bytes, Commit, Tag]]]
  5249. ] = None,
  5250. ) -> Optional[bytes]:
  5251. """Skip one or more commits.
  5252. Args:
  5253. repo: Path to repository or a Repo object
  5254. revs: List of commits to skip (defaults to [HEAD])
  5255. Returns:
  5256. The SHA of the next commit to test, or None if bisect is complete
  5257. """
  5258. with open_repo_closing(repo) as r:
  5259. state = BisectState(r)
  5260. if revs is None:
  5261. rev_shas = None
  5262. else:
  5263. # Convert single rev to sequence
  5264. if isinstance(revs, (str, bytes, Commit, Tag)):
  5265. revs = [revs]
  5266. rev_shas = [parse_commit(r, rev).id for rev in revs]
  5267. next_sha = state.skip(rev_shas)
  5268. if next_sha:
  5269. # Checkout the next commit
  5270. old_commit = r[r.head()]
  5271. assert isinstance(old_commit, Commit)
  5272. old_tree = old_commit.tree if r.head() else None
  5273. r.refs[b"HEAD"] = next_sha
  5274. commit = r[next_sha]
  5275. assert isinstance(commit, Commit)
  5276. changes = tree_changes(r.object_store, old_tree, commit.tree)
  5277. update_working_tree(r, old_tree, commit.tree, change_iterator=changes)
  5278. return next_sha
  5279. def bisect_reset(
  5280. repo: Union[str, os.PathLike[str], Repo] = ".",
  5281. commit: Optional[Union[str, bytes, Commit, Tag]] = None,
  5282. ) -> None:
  5283. """Reset bisect state and return to original branch/commit.
  5284. Args:
  5285. repo: Path to repository or a Repo object
  5286. commit: Optional commit to reset to (defaults to original branch/commit)
  5287. """
  5288. with open_repo_closing(repo) as r:
  5289. state = BisectState(r)
  5290. # Get old tree before reset
  5291. try:
  5292. old_commit = r[r.head()]
  5293. assert isinstance(old_commit, Commit)
  5294. old_tree = old_commit.tree
  5295. except KeyError:
  5296. old_tree = None
  5297. commit_sha = parse_commit(r, commit).id if commit else None
  5298. state.reset(commit_sha)
  5299. # Update working tree to new HEAD
  5300. try:
  5301. new_head = r.head()
  5302. if new_head:
  5303. new_commit = r[new_head]
  5304. assert isinstance(new_commit, Commit)
  5305. changes = tree_changes(r.object_store, old_tree, new_commit.tree)
  5306. update_working_tree(
  5307. r, old_tree, new_commit.tree, change_iterator=changes
  5308. )
  5309. except KeyError:
  5310. # No HEAD after reset
  5311. pass
  5312. def bisect_log(repo: Union[str, os.PathLike[str], Repo] = ".") -> str:
  5313. """Get the bisect log.
  5314. Args:
  5315. repo: Path to repository or a Repo object
  5316. Returns:
  5317. The bisect log as a string
  5318. """
  5319. with open_repo_closing(repo) as r:
  5320. state = BisectState(r)
  5321. return state.get_log()
  5322. def bisect_replay(
  5323. repo: Union[str, os.PathLike[str], Repo],
  5324. log_file: Union[str, os.PathLike[str], BinaryIO],
  5325. ) -> None:
  5326. """Replay a bisect log.
  5327. Args:
  5328. repo: Path to repository or a Repo object
  5329. log_file: Path to the log file or file-like object
  5330. """
  5331. with open_repo_closing(repo) as r:
  5332. state = BisectState(r)
  5333. if isinstance(log_file, (str, os.PathLike)):
  5334. with open(log_file) as f:
  5335. log_content = f.read()
  5336. else:
  5337. content = log_file.read()
  5338. log_content = content.decode() if isinstance(content, bytes) else content
  5339. state.replay(log_content)
  5340. def reflog(
  5341. repo: RepoPath = ".", ref: Union[str, bytes] = b"HEAD", all: bool = False
  5342. ) -> Iterator[Union[Any, tuple[bytes, Any]]]:
  5343. """Show reflog entries for a reference or all references.
  5344. Args:
  5345. repo: Path to repository or a Repo object
  5346. ref: Reference name (defaults to HEAD)
  5347. all: If True, show reflogs for all refs (ignores ref parameter)
  5348. Yields:
  5349. If all=False: ReflogEntry objects
  5350. If all=True: Tuples of (ref_name, ReflogEntry) for all refs with reflogs
  5351. """
  5352. import os
  5353. from .reflog import iter_reflogs
  5354. if isinstance(ref, str):
  5355. ref = ref.encode("utf-8")
  5356. with open_repo_closing(repo) as r:
  5357. if not all:
  5358. yield from r.read_reflog(ref)
  5359. else:
  5360. logs_dir = os.path.join(r.controldir(), "logs")
  5361. # Use iter_reflogs to discover all reflogs
  5362. for ref_bytes in iter_reflogs(logs_dir):
  5363. # Read the reflog entries for this ref
  5364. for entry in r.read_reflog(ref_bytes):
  5365. yield (ref_bytes, entry)
  5366. def lfs_track(
  5367. repo: Union[str, os.PathLike[str], Repo] = ".",
  5368. patterns: Optional[Sequence[str]] = None,
  5369. ) -> list[str]:
  5370. """Track file patterns with Git LFS.
  5371. Args:
  5372. repo: Path to repository
  5373. patterns: List of file patterns to track (e.g., ["*.bin", "*.pdf"])
  5374. If None, returns current tracked patterns
  5375. Returns:
  5376. List of tracked patterns
  5377. """
  5378. from .attrs import GitAttributes
  5379. with open_repo_closing(repo) as r:
  5380. gitattributes_path = os.path.join(r.path, ".gitattributes")
  5381. # Load existing GitAttributes
  5382. if os.path.exists(gitattributes_path):
  5383. gitattributes = GitAttributes.from_file(gitattributes_path)
  5384. else:
  5385. gitattributes = GitAttributes()
  5386. if patterns is None:
  5387. # Return current LFS tracked patterns
  5388. tracked = []
  5389. for pattern_obj, attrs in gitattributes:
  5390. if attrs.get(b"filter") == b"lfs":
  5391. tracked.append(pattern_obj.pattern.decode())
  5392. return tracked
  5393. # Add new patterns
  5394. for pattern in patterns:
  5395. # Ensure pattern is bytes
  5396. pattern_bytes = pattern.encode() if isinstance(pattern, str) else pattern
  5397. # Set LFS attributes for the pattern
  5398. gitattributes.set_attribute(pattern_bytes, b"filter", b"lfs")
  5399. gitattributes.set_attribute(pattern_bytes, b"diff", b"lfs")
  5400. gitattributes.set_attribute(pattern_bytes, b"merge", b"lfs")
  5401. gitattributes.set_attribute(pattern_bytes, b"text", False)
  5402. # Write updated attributes
  5403. gitattributes.write_to_file(gitattributes_path)
  5404. # Stage the .gitattributes file
  5405. add(r, [".gitattributes"])
  5406. return lfs_track(r) # Return updated list
  5407. def lfs_untrack(
  5408. repo: Union[str, os.PathLike[str], Repo] = ".",
  5409. patterns: Optional[Sequence[str]] = None,
  5410. ) -> list[str]:
  5411. """Untrack file patterns from Git LFS.
  5412. Args:
  5413. repo: Path to repository
  5414. patterns: List of file patterns to untrack
  5415. Returns:
  5416. List of remaining tracked patterns
  5417. """
  5418. from .attrs import GitAttributes
  5419. if not patterns:
  5420. return lfs_track(repo)
  5421. with open_repo_closing(repo) as r:
  5422. gitattributes_path = os.path.join(r.path, ".gitattributes")
  5423. if not os.path.exists(gitattributes_path):
  5424. return []
  5425. # Load existing GitAttributes
  5426. gitattributes = GitAttributes.from_file(gitattributes_path)
  5427. # Remove specified patterns
  5428. for pattern in patterns:
  5429. pattern_bytes = pattern.encode() if isinstance(pattern, str) else pattern
  5430. # Check if pattern is tracked by LFS
  5431. for pattern_obj, attrs in list(gitattributes):
  5432. if (
  5433. pattern_obj.pattern == pattern_bytes
  5434. and attrs.get(b"filter") == b"lfs"
  5435. ):
  5436. gitattributes.remove_pattern(pattern_bytes)
  5437. break
  5438. # Write updated attributes
  5439. gitattributes.write_to_file(gitattributes_path)
  5440. # Stage the .gitattributes file
  5441. add(r, [".gitattributes"])
  5442. return lfs_track(r) # Return updated list
  5443. def lfs_init(repo: Union[str, os.PathLike[str], Repo] = ".") -> None:
  5444. """Initialize Git LFS in a repository.
  5445. Args:
  5446. repo: Path to repository
  5447. Returns:
  5448. None
  5449. """
  5450. from .lfs import LFSStore
  5451. with open_repo_closing(repo) as r:
  5452. # Create LFS store
  5453. LFSStore.from_repo(r, create=True)
  5454. # Set up Git config for LFS
  5455. config = r.get_config()
  5456. config.set((b"filter", b"lfs"), b"process", b"git-lfs filter-process")
  5457. config.set((b"filter", b"lfs"), b"required", b"true")
  5458. config.set((b"filter", b"lfs"), b"clean", b"git-lfs clean -- %f")
  5459. config.set((b"filter", b"lfs"), b"smudge", b"git-lfs smudge -- %f")
  5460. config.write_to_path()
  5461. def lfs_clean(
  5462. repo: Union[str, os.PathLike[str], Repo] = ".",
  5463. path: Optional[Union[str, os.PathLike[str]]] = None,
  5464. ) -> bytes:
  5465. """Clean a file by converting it to an LFS pointer.
  5466. Args:
  5467. repo: Path to repository
  5468. path: Path to file to clean (relative to repo root)
  5469. Returns:
  5470. LFS pointer content as bytes
  5471. """
  5472. from .lfs import LFSFilterDriver, LFSStore
  5473. with open_repo_closing(repo) as r:
  5474. if path is None:
  5475. raise ValueError("Path must be specified")
  5476. # Get LFS store
  5477. lfs_store = LFSStore.from_repo(r)
  5478. filter_driver = LFSFilterDriver(lfs_store, config=r.get_config())
  5479. # Read file content
  5480. full_path = os.path.join(r.path, path)
  5481. with open(full_path, "rb") as f:
  5482. content = f.read()
  5483. # Clean the content (convert to LFS pointer)
  5484. return filter_driver.clean(content)
  5485. def lfs_smudge(
  5486. repo: Union[str, os.PathLike[str], Repo] = ".",
  5487. pointer_content: Optional[bytes] = None,
  5488. ) -> bytes:
  5489. """Smudge an LFS pointer by retrieving the actual content.
  5490. Args:
  5491. repo: Path to repository
  5492. pointer_content: LFS pointer content as bytes
  5493. Returns:
  5494. Actual file content as bytes
  5495. """
  5496. from .lfs import LFSFilterDriver, LFSStore
  5497. with open_repo_closing(repo) as r:
  5498. if pointer_content is None:
  5499. raise ValueError("Pointer content must be specified")
  5500. # Get LFS store
  5501. lfs_store = LFSStore.from_repo(r)
  5502. filter_driver = LFSFilterDriver(lfs_store, config=r.get_config())
  5503. # Smudge the pointer (retrieve actual content)
  5504. return filter_driver.smudge(pointer_content)
  5505. def lfs_ls_files(
  5506. repo: Union[str, os.PathLike[str], Repo] = ".",
  5507. ref: Optional[Union[str, bytes]] = None,
  5508. ) -> list[tuple[bytes, str, int]]:
  5509. """List files tracked by Git LFS.
  5510. Args:
  5511. repo: Path to repository
  5512. ref: Git ref to check (defaults to HEAD)
  5513. Returns:
  5514. List of (path, oid, size) tuples for LFS files
  5515. """
  5516. from .lfs import LFSPointer
  5517. from .object_store import iter_tree_contents
  5518. with open_repo_closing(repo) as r:
  5519. if ref is None:
  5520. ref = b"HEAD"
  5521. elif isinstance(ref, str):
  5522. ref = ref.encode()
  5523. # Get the commit and tree
  5524. try:
  5525. commit = r[ref]
  5526. assert isinstance(commit, Commit)
  5527. tree = r[commit.tree]
  5528. assert isinstance(tree, Tree)
  5529. except KeyError:
  5530. return []
  5531. lfs_files = []
  5532. # Walk the tree
  5533. for path, mode, sha in iter_tree_contents(r.object_store, tree.id):
  5534. assert path is not None
  5535. assert mode is not None
  5536. assert sha is not None
  5537. if not stat.S_ISREG(mode):
  5538. continue
  5539. # Check if it's an LFS pointer
  5540. obj = r.object_store[sha]
  5541. if not isinstance(obj, Blob):
  5542. raise AssertionError(f"Expected Blob object, got {type(obj).__name__}")
  5543. pointer = LFSPointer.from_bytes(obj.data)
  5544. if pointer is not None:
  5545. lfs_files.append((path, pointer.oid, pointer.size))
  5546. return lfs_files
  5547. def lfs_migrate(
  5548. repo: Union[str, os.PathLike[str], Repo] = ".",
  5549. include: Optional[list[str]] = None,
  5550. exclude: Optional[list[str]] = None,
  5551. everything: bool = False,
  5552. ) -> int:
  5553. """Migrate files to Git LFS.
  5554. Args:
  5555. repo: Path to repository
  5556. include: Patterns of files to include
  5557. exclude: Patterns of files to exclude
  5558. everything: Migrate all files above a certain size
  5559. Returns:
  5560. Number of migrated files
  5561. """
  5562. from .lfs import LFSFilterDriver, LFSStore
  5563. with open_repo_closing(repo) as r:
  5564. # Initialize LFS if needed
  5565. lfs_store = LFSStore.from_repo(r, create=True)
  5566. filter_driver = LFSFilterDriver(lfs_store, config=r.get_config())
  5567. # Get current index
  5568. index = r.open_index()
  5569. migrated = 0
  5570. # Determine files to migrate
  5571. files_to_migrate = []
  5572. if everything:
  5573. # Migrate all files above 100MB
  5574. for path, entry in index.items():
  5575. full_path = os.path.join(r.path, path.decode())
  5576. if os.path.exists(full_path):
  5577. size = os.path.getsize(full_path)
  5578. if size > 100 * 1024 * 1024: # 100MB
  5579. files_to_migrate.append(path.decode())
  5580. else:
  5581. # Use include/exclude patterns
  5582. for path, entry in index.items():
  5583. path_str = path.decode()
  5584. # Check include patterns
  5585. if include:
  5586. matched = any(
  5587. fnmatch.fnmatch(path_str, pattern) for pattern in include
  5588. )
  5589. if not matched:
  5590. continue
  5591. # Check exclude patterns
  5592. if exclude:
  5593. excluded = any(
  5594. fnmatch.fnmatch(path_str, pattern) for pattern in exclude
  5595. )
  5596. if excluded:
  5597. continue
  5598. files_to_migrate.append(path_str)
  5599. # Migrate files
  5600. for path_str in files_to_migrate:
  5601. full_path = os.path.join(r.path, path_str)
  5602. if not os.path.exists(full_path):
  5603. continue
  5604. # Read file content
  5605. with open(full_path, "rb") as f:
  5606. content = f.read()
  5607. # Convert to LFS pointer
  5608. pointer_content = filter_driver.clean(content)
  5609. # Write pointer back to file
  5610. with open(full_path, "wb") as f:
  5611. f.write(pointer_content)
  5612. # Create blob for pointer content and update index
  5613. blob = Blob()
  5614. blob.data = pointer_content
  5615. r.object_store.add_object(blob)
  5616. st = os.stat(full_path)
  5617. index_entry = index_entry_from_stat(st, blob.id, 0)
  5618. path_bytes = path_str.encode() if isinstance(path_str, str) else path_str
  5619. index[path_bytes] = index_entry
  5620. migrated += 1
  5621. # Write updated index
  5622. index.write()
  5623. # Track patterns if include was specified
  5624. if include:
  5625. lfs_track(r, include)
  5626. return migrated
  5627. def lfs_pointer_check(
  5628. repo: Union[str, os.PathLike[str], Repo] = ".",
  5629. paths: Optional[Sequence[str]] = None,
  5630. ) -> dict[str, Optional[Any]]:
  5631. """Check if files are valid LFS pointers.
  5632. Args:
  5633. repo: Path to repository
  5634. paths: List of file paths to check (if None, check all files)
  5635. Returns:
  5636. Dict mapping paths to LFSPointer objects (or None if not a pointer)
  5637. """
  5638. from .lfs import LFSPointer
  5639. with open_repo_closing(repo) as r:
  5640. results = {}
  5641. if paths is None:
  5642. # Check all files in index
  5643. index = r.open_index()
  5644. paths = [path.decode() for path in index]
  5645. for path in paths:
  5646. full_path = os.path.join(r.path, path)
  5647. if os.path.exists(full_path):
  5648. try:
  5649. with open(full_path, "rb") as f:
  5650. content = f.read()
  5651. pointer = LFSPointer.from_bytes(content)
  5652. results[path] = pointer
  5653. except OSError:
  5654. results[path] = None
  5655. else:
  5656. results[path] = None
  5657. return results
  5658. def lfs_fetch(
  5659. repo: Union[str, os.PathLike[str], Repo] = ".",
  5660. remote: str = "origin",
  5661. refs: Optional[list[Union[str, bytes]]] = None,
  5662. ) -> int:
  5663. """Fetch LFS objects from remote.
  5664. Args:
  5665. repo: Path to repository
  5666. remote: Remote name (default: origin)
  5667. refs: Specific refs to fetch LFS objects for (default: all refs)
  5668. Returns:
  5669. Number of objects fetched
  5670. """
  5671. from .lfs import LFSClient, LFSPointer, LFSStore
  5672. with open_repo_closing(repo) as r:
  5673. # Get LFS server URL from config
  5674. config = r.get_config()
  5675. lfs_url_bytes = config.get((b"lfs",), b"url")
  5676. if not lfs_url_bytes:
  5677. # Try remote URL
  5678. remote_url = config.get((b"remote", remote.encode()), b"url")
  5679. if remote_url:
  5680. # Append /info/lfs to remote URL
  5681. remote_url_str = remote_url.decode()
  5682. if remote_url_str.endswith(".git"):
  5683. remote_url_str = remote_url_str[:-4]
  5684. lfs_url = f"{remote_url_str}/info/lfs"
  5685. else:
  5686. raise ValueError(f"No LFS URL configured for remote {remote}")
  5687. else:
  5688. lfs_url = lfs_url_bytes.decode()
  5689. # Get authentication
  5690. auth = None
  5691. # TODO: Support credential helpers and other auth methods
  5692. # Create LFS client and store
  5693. client = LFSClient(lfs_url, auth)
  5694. store = LFSStore.from_repo(r)
  5695. # Find all LFS pointers in the refs
  5696. pointers_to_fetch = []
  5697. if refs is None:
  5698. # Get all refs
  5699. refs = list(r.refs.keys())
  5700. for ref in refs:
  5701. if isinstance(ref, str):
  5702. ref = ref.encode()
  5703. try:
  5704. commit = r[r.refs[ref]]
  5705. except KeyError:
  5706. continue
  5707. # Walk the commit tree
  5708. assert isinstance(commit, Commit)
  5709. for path, mode, sha in r.object_store.iter_tree_contents(commit.tree):
  5710. assert sha is not None
  5711. try:
  5712. obj = r.object_store[sha]
  5713. except KeyError:
  5714. pass
  5715. else:
  5716. if isinstance(obj, Blob):
  5717. pointer = LFSPointer.from_bytes(obj.data)
  5718. if pointer and pointer.is_valid_oid():
  5719. # Check if we already have it
  5720. try:
  5721. store.open_object(pointer.oid)
  5722. except KeyError:
  5723. pointers_to_fetch.append((pointer.oid, pointer.size))
  5724. # Fetch missing objects
  5725. fetched = 0
  5726. for oid, size in pointers_to_fetch:
  5727. content = client.download(oid, size)
  5728. store.write_object([content])
  5729. fetched += 1
  5730. return fetched
  5731. def lfs_pull(
  5732. repo: Union[str, os.PathLike[str], Repo] = ".", remote: str = "origin"
  5733. ) -> int:
  5734. """Pull LFS objects for current checkout.
  5735. Args:
  5736. repo: Path to repository
  5737. remote: Remote name (default: origin)
  5738. Returns:
  5739. Number of objects fetched
  5740. """
  5741. from .lfs import LFSPointer, LFSStore
  5742. with open_repo_closing(repo) as r:
  5743. # First do a fetch for HEAD
  5744. fetched = lfs_fetch(repo, remote, [b"HEAD"])
  5745. # Then checkout LFS files in working directory
  5746. store = LFSStore.from_repo(r)
  5747. index = r.open_index()
  5748. for path, entry in index.items():
  5749. full_path = os.path.join(r.path, path.decode())
  5750. if os.path.exists(full_path):
  5751. with open(full_path, "rb") as f:
  5752. content = f.read()
  5753. pointer = LFSPointer.from_bytes(content)
  5754. if pointer and pointer.is_valid_oid():
  5755. try:
  5756. # Replace pointer with actual content
  5757. with store.open_object(pointer.oid) as lfs_file:
  5758. lfs_content = lfs_file.read()
  5759. with open(full_path, "wb") as f:
  5760. f.write(lfs_content)
  5761. except KeyError:
  5762. # Object not available
  5763. pass
  5764. return fetched
  5765. def lfs_push(
  5766. repo: Union[str, os.PathLike[str], Repo] = ".",
  5767. remote: str = "origin",
  5768. refs: Optional[list[Union[str, bytes]]] = None,
  5769. ) -> int:
  5770. """Push LFS objects to remote.
  5771. Args:
  5772. repo: Path to repository
  5773. remote: Remote name (default: origin)
  5774. refs: Specific refs to push LFS objects for (default: current branch)
  5775. Returns:
  5776. Number of objects pushed
  5777. """
  5778. from .lfs import LFSClient, LFSPointer, LFSStore
  5779. with open_repo_closing(repo) as r:
  5780. # Get LFS server URL from config
  5781. config = r.get_config()
  5782. lfs_url_bytes = config.get((b"lfs",), b"url")
  5783. if not lfs_url_bytes:
  5784. # Try remote URL
  5785. remote_url = config.get((b"remote", remote.encode()), b"url")
  5786. if remote_url:
  5787. # Append /info/lfs to remote URL
  5788. remote_url_str = remote_url.decode()
  5789. if remote_url_str.endswith(".git"):
  5790. remote_url_str = remote_url_str[:-4]
  5791. lfs_url = f"{remote_url_str}/info/lfs"
  5792. else:
  5793. raise ValueError(f"No LFS URL configured for remote {remote}")
  5794. else:
  5795. lfs_url = lfs_url_bytes.decode()
  5796. # Get authentication
  5797. auth = None
  5798. # TODO: Support credential helpers and other auth methods
  5799. # Create LFS client and store
  5800. client = LFSClient(lfs_url, auth)
  5801. store = LFSStore.from_repo(r)
  5802. # Find all LFS objects to push
  5803. if refs is None:
  5804. # Push current branch
  5805. head_ref = r.refs.read_ref(b"HEAD")
  5806. refs = [head_ref] if head_ref else []
  5807. objects_to_push = set()
  5808. for ref in refs:
  5809. if isinstance(ref, str):
  5810. ref = ref.encode()
  5811. try:
  5812. if ref.startswith(b"refs/"):
  5813. commit = r[r.refs[ref]]
  5814. else:
  5815. commit = r[ref]
  5816. except KeyError:
  5817. continue
  5818. # Walk the commit tree
  5819. assert isinstance(commit, Commit)
  5820. for path, mode, sha in r.object_store.iter_tree_contents(commit.tree):
  5821. assert sha is not None
  5822. try:
  5823. obj = r.object_store[sha]
  5824. except KeyError:
  5825. pass
  5826. else:
  5827. if isinstance(obj, Blob):
  5828. pointer = LFSPointer.from_bytes(obj.data)
  5829. if pointer and pointer.is_valid_oid():
  5830. objects_to_push.add((pointer.oid, pointer.size))
  5831. # Push objects
  5832. pushed = 0
  5833. for oid, size in objects_to_push:
  5834. try:
  5835. with store.open_object(oid) as f:
  5836. content = f.read()
  5837. except KeyError:
  5838. # Object not in local store
  5839. logging.warn("LFS object %s not found locally", oid)
  5840. else:
  5841. client.upload(oid, size, content)
  5842. pushed += 1
  5843. return pushed
  5844. def lfs_status(repo: Union[str, os.PathLike[str], Repo] = ".") -> dict[str, list[str]]:
  5845. """Show status of LFS files.
  5846. Args:
  5847. repo: Path to repository
  5848. Returns:
  5849. Dict with status information
  5850. """
  5851. from .lfs import LFSPointer, LFSStore
  5852. with open_repo_closing(repo) as r:
  5853. store = LFSStore.from_repo(r)
  5854. index = r.open_index()
  5855. status: dict[str, list[str]] = {
  5856. "tracked": [],
  5857. "not_staged": [],
  5858. "not_committed": [],
  5859. "not_pushed": [],
  5860. "missing": [],
  5861. }
  5862. # Check working directory files
  5863. for path, entry in index.items():
  5864. path_str = path.decode()
  5865. full_path = os.path.join(r.path, path_str)
  5866. if os.path.exists(full_path):
  5867. with open(full_path, "rb") as f:
  5868. content = f.read()
  5869. pointer = LFSPointer.from_bytes(content)
  5870. if pointer and pointer.is_valid_oid():
  5871. status["tracked"].append(path_str)
  5872. # Check if object exists locally
  5873. try:
  5874. store.open_object(pointer.oid)
  5875. except KeyError:
  5876. status["missing"].append(path_str)
  5877. # Check if file has been modified
  5878. if isinstance(entry, ConflictedIndexEntry):
  5879. continue # Skip conflicted entries
  5880. try:
  5881. staged_obj = r.object_store[entry.sha]
  5882. except KeyError:
  5883. pass
  5884. else:
  5885. if not isinstance(staged_obj, Blob):
  5886. raise AssertionError(
  5887. f"Expected Blob object, got {type(staged_obj).__name__}"
  5888. )
  5889. staged_pointer = LFSPointer.from_bytes(staged_obj.data)
  5890. if staged_pointer and staged_pointer.oid != pointer.oid:
  5891. status["not_staged"].append(path_str)
  5892. # TODO: Check for not committed and not pushed files
  5893. return status
  5894. def worktree_list(repo: RepoPath = ".") -> list[Any]:
  5895. """List all worktrees for a repository.
  5896. Args:
  5897. repo: Path to repository
  5898. Returns:
  5899. List of WorkTreeInfo objects
  5900. """
  5901. from .worktree import list_worktrees
  5902. with open_repo_closing(repo) as r:
  5903. return list_worktrees(r)
  5904. def worktree_add(
  5905. repo: RepoPath = ".",
  5906. path: Optional[Union[str, os.PathLike[str]]] = None,
  5907. branch: Optional[Union[str, bytes]] = None,
  5908. commit: Optional[Union[str, bytes]] = None,
  5909. detach: bool = False,
  5910. force: bool = False,
  5911. ) -> str:
  5912. """Add a new worktree.
  5913. Args:
  5914. repo: Path to repository
  5915. path: Path for new worktree
  5916. branch: Branch to checkout (creates if doesn't exist)
  5917. commit: Specific commit to checkout
  5918. detach: Create with detached HEAD
  5919. force: Force creation even if branch is already checked out
  5920. Returns:
  5921. Path to the newly created worktree
  5922. """
  5923. from .worktree import add_worktree
  5924. if path is None:
  5925. raise ValueError("Path is required for worktree add")
  5926. with open_repo_closing(repo) as r:
  5927. commit_bytes = commit.encode() if isinstance(commit, str) else commit
  5928. wt_repo = add_worktree(
  5929. r, path, branch=branch, commit=commit_bytes, detach=detach, force=force
  5930. )
  5931. return wt_repo.path
  5932. def worktree_remove(
  5933. repo: RepoPath = ".",
  5934. path: Optional[Union[str, os.PathLike[str]]] = None,
  5935. force: bool = False,
  5936. ) -> None:
  5937. """Remove a worktree.
  5938. Args:
  5939. repo: Path to repository
  5940. path: Path to worktree to remove
  5941. force: Force removal even if there are local changes
  5942. """
  5943. from .worktree import remove_worktree
  5944. if path is None:
  5945. raise ValueError("Path is required for worktree remove")
  5946. with open_repo_closing(repo) as r:
  5947. remove_worktree(r, path, force=force)
  5948. def worktree_prune(
  5949. repo: RepoPath = ".", dry_run: bool = False, expire: Optional[int] = None
  5950. ) -> list[str]:
  5951. """Prune worktree administrative files.
  5952. Args:
  5953. repo: Path to repository
  5954. dry_run: Only show what would be removed
  5955. expire: Only prune worktrees older than this many seconds
  5956. Returns:
  5957. List of pruned worktree names
  5958. """
  5959. from .worktree import prune_worktrees
  5960. with open_repo_closing(repo) as r:
  5961. return prune_worktrees(r, expire=expire, dry_run=dry_run)
  5962. def worktree_lock(
  5963. repo: RepoPath = ".",
  5964. path: Optional[Union[str, os.PathLike[str]]] = None,
  5965. reason: Optional[str] = None,
  5966. ) -> None:
  5967. """Lock a worktree to prevent it from being pruned.
  5968. Args:
  5969. repo: Path to repository
  5970. path: Path to worktree to lock
  5971. reason: Optional reason for locking
  5972. """
  5973. from .worktree import lock_worktree
  5974. if path is None:
  5975. raise ValueError("Path is required for worktree lock")
  5976. with open_repo_closing(repo) as r:
  5977. lock_worktree(r, path, reason=reason)
  5978. def worktree_unlock(
  5979. repo: RepoPath = ".", path: Optional[Union[str, os.PathLike[str]]] = None
  5980. ) -> None:
  5981. """Unlock a worktree.
  5982. Args:
  5983. repo: Path to repository
  5984. path: Path to worktree to unlock
  5985. """
  5986. from .worktree import unlock_worktree
  5987. if path is None:
  5988. raise ValueError("Path is required for worktree unlock")
  5989. with open_repo_closing(repo) as r:
  5990. unlock_worktree(r, path)
  5991. def worktree_move(
  5992. repo: RepoPath = ".",
  5993. old_path: Optional[Union[str, os.PathLike[str]]] = None,
  5994. new_path: Optional[Union[str, os.PathLike[str]]] = None,
  5995. ) -> None:
  5996. """Move a worktree to a new location.
  5997. Args:
  5998. repo: Path to repository
  5999. old_path: Current path of worktree
  6000. new_path: New path for worktree
  6001. """
  6002. from .worktree import move_worktree
  6003. if old_path is None or new_path is None:
  6004. raise ValueError("Both old_path and new_path are required for worktree move")
  6005. with open_repo_closing(repo) as r:
  6006. move_worktree(r, old_path, new_path)
  6007. def worktree_repair(
  6008. repo: RepoPath = ".",
  6009. paths: Optional[list[Union[str, os.PathLike[str]]]] = None,
  6010. ) -> list[str]:
  6011. """Repair worktree administrative files.
  6012. Args:
  6013. repo: Path to repository
  6014. paths: Optional list of worktree paths to repair. If None, repairs
  6015. connections from the main repository to all linked worktrees.
  6016. Returns:
  6017. List of repaired worktree paths
  6018. """
  6019. from .worktree import repair_worktree
  6020. with open_repo_closing(repo) as r:
  6021. return repair_worktree(r, paths=paths)