porcelain.py 199 KB

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