porcelain.py 284 KB

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