porcelain.py 198 KB

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