porcelain.py 194 KB

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