porcelain.py 183 KB

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