porcelain.py 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170
  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 public 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. * branch{_create,_delete,_list}
  26. * check_ignore
  27. * checkout
  28. * checkout_branch
  29. * clone
  30. * cone mode{_init, _set, _add}
  31. * commit
  32. * commit_tree
  33. * daemon
  34. * describe
  35. * diff_tree
  36. * fetch
  37. * filter_branch
  38. * for_each_ref
  39. * init
  40. * ls_files
  41. * ls_remote
  42. * ls_tree
  43. * merge
  44. * merge_tree
  45. * mv/move
  46. * prune
  47. * pull
  48. * push
  49. * rm
  50. * remote{_add}
  51. * receive_pack
  52. * reset
  53. * revert
  54. * sparse_checkout
  55. * submodule_add
  56. * submodule_init
  57. * submodule_list
  58. * rev_list
  59. * tag{_create,_delete,_list}
  60. * upload_pack
  61. * update_server_info
  62. * status
  63. * symbolic_ref
  64. These functions are meant to behave similarly to the git subcommands.
  65. Differences in behaviour are considered bugs.
  66. Note: one of the consequences of this is that paths tend to be
  67. interpreted relative to the current working directory rather than relative
  68. to the repository root.
  69. Functions should generally accept both unicode strings and bytestrings
  70. """
  71. import datetime
  72. import fnmatch
  73. import os
  74. import posixpath
  75. import stat
  76. import sys
  77. import time
  78. from collections import namedtuple
  79. from contextlib import closing, contextmanager
  80. from dataclasses import dataclass
  81. from io import BytesIO, RawIOBase
  82. from pathlib import Path
  83. from typing import Optional, Union
  84. from . import replace_me
  85. from .archive import tar_stream
  86. from .client import get_transport_and_path
  87. from .config import Config, ConfigFile, StackedConfig, read_submodules
  88. from .diff_tree import (
  89. CHANGE_ADD,
  90. CHANGE_COPY,
  91. CHANGE_DELETE,
  92. CHANGE_MODIFY,
  93. CHANGE_RENAME,
  94. RENAME_CHANGE_TYPES,
  95. )
  96. from .errors import SendPackError
  97. from .graph import can_fast_forward
  98. from .ignore import IgnoreFilterManager
  99. from .index import (
  100. _fs_to_tree_path,
  101. blob_from_path_and_stat,
  102. build_file_from_blob,
  103. get_unstaged_changes,
  104. update_working_tree,
  105. )
  106. from .object_store import tree_lookup_path
  107. from .objects import (
  108. Commit,
  109. Tag,
  110. format_timezone,
  111. parse_timezone,
  112. pretty_format_tree_entry,
  113. )
  114. from .objectspec import (
  115. parse_commit,
  116. parse_object,
  117. parse_ref,
  118. parse_reftuples,
  119. parse_tree,
  120. )
  121. from .pack import write_pack_from_container, write_pack_index
  122. from .patch import write_tree_diff
  123. from .protocol import ZERO_SHA, Protocol
  124. from .refs import (
  125. LOCAL_BRANCH_PREFIX,
  126. LOCAL_NOTES_PREFIX,
  127. LOCAL_TAG_PREFIX,
  128. Ref,
  129. SymrefLoop,
  130. _import_remote_refs,
  131. )
  132. from .repo import BaseRepo, Repo, get_user_identity
  133. from .server import (
  134. FileSystemBackend,
  135. ReceivePackHandler,
  136. TCPGitServer,
  137. UploadPackHandler,
  138. )
  139. from .server import update_server_info as server_update_server_info
  140. from .sparse_patterns import (
  141. SparseCheckoutConflictError,
  142. apply_included_paths,
  143. determine_included_paths,
  144. )
  145. # Module level tuple definition for status output
  146. GitStatus = namedtuple("GitStatus", "staged unstaged untracked")
  147. @dataclass
  148. class CountObjectsResult:
  149. """Result of counting objects in a repository.
  150. Attributes:
  151. count: Number of loose objects
  152. size: Total size of loose objects in bytes
  153. in_pack: Number of objects in pack files
  154. packs: Number of pack files
  155. size_pack: Total size of pack files in bytes
  156. """
  157. count: int
  158. size: int
  159. in_pack: Optional[int] = None
  160. packs: Optional[int] = None
  161. size_pack: Optional[int] = None
  162. class NoneStream(RawIOBase):
  163. """Fallback if stdout or stderr are unavailable, does nothing."""
  164. def read(self, size=-1) -> None:
  165. return None
  166. def readall(self) -> bytes:
  167. return b""
  168. def readinto(self, b) -> None:
  169. return None
  170. def write(self, b) -> None:
  171. return None
  172. default_bytes_out_stream = getattr(sys.stdout, "buffer", None) or NoneStream()
  173. default_bytes_err_stream = getattr(sys.stderr, "buffer", None) or NoneStream()
  174. DEFAULT_ENCODING = "utf-8"
  175. class Error(Exception):
  176. """Porcelain-based error."""
  177. def __init__(self, msg) -> None:
  178. super().__init__(msg)
  179. class RemoteExists(Error):
  180. """Raised when the remote already exists."""
  181. class TimezoneFormatError(Error):
  182. """Raised when the timezone cannot be determined from a given string."""
  183. class CheckoutError(Error):
  184. """Indicates that a checkout cannot be performed."""
  185. def parse_timezone_format(tz_str):
  186. """Parse given string and attempt to return a timezone offset.
  187. Different formats are considered in the following order:
  188. - Git internal format: <unix timestamp> <timezone offset>
  189. - RFC 2822: e.g. Mon, 20 Nov 1995 19:12:08 -0500
  190. - ISO 8601: e.g. 1995-11-20T19:12:08-0500
  191. Args:
  192. tz_str: datetime string
  193. Returns: Timezone offset as integer
  194. Raises:
  195. TimezoneFormatError: if timezone information cannot be extracted
  196. """
  197. import re
  198. # Git internal format
  199. internal_format_pattern = re.compile("^[0-9]+ [+-][0-9]{,4}$")
  200. if re.match(internal_format_pattern, tz_str):
  201. try:
  202. tz_internal = parse_timezone(tz_str.split(" ")[1].encode(DEFAULT_ENCODING))
  203. return tz_internal[0]
  204. except ValueError:
  205. pass
  206. # RFC 2822
  207. import email.utils
  208. rfc_2822 = email.utils.parsedate_tz(tz_str)
  209. if rfc_2822:
  210. return rfc_2822[9]
  211. # ISO 8601
  212. # Supported offsets:
  213. # sHHMM, sHH:MM, sHH
  214. iso_8601_pattern = re.compile(
  215. "[0-9] ?([+-])([0-9]{2})(?::(?=[0-9]{2}))?([0-9]{2})?$"
  216. )
  217. match = re.search(iso_8601_pattern, tz_str)
  218. total_secs = 0
  219. if match:
  220. sign, hours, minutes = match.groups()
  221. total_secs += int(hours) * 3600
  222. if minutes:
  223. total_secs += int(minutes) * 60
  224. total_secs = -total_secs if sign == "-" else total_secs
  225. return total_secs
  226. # YYYY.MM.DD, MM/DD/YYYY, DD.MM.YYYY contain no timezone information
  227. raise TimezoneFormatError(tz_str)
  228. def get_user_timezones():
  229. """Retrieve local timezone as described in
  230. https://raw.githubusercontent.com/git/git/v2.3.0/Documentation/date-formats.txt
  231. Returns: A tuple containing author timezone, committer timezone.
  232. """
  233. local_timezone = time.localtime().tm_gmtoff
  234. if os.environ.get("GIT_AUTHOR_DATE"):
  235. author_timezone = parse_timezone_format(os.environ["GIT_AUTHOR_DATE"])
  236. else:
  237. author_timezone = local_timezone
  238. if os.environ.get("GIT_COMMITTER_DATE"):
  239. commit_timezone = parse_timezone_format(os.environ["GIT_COMMITTER_DATE"])
  240. else:
  241. commit_timezone = local_timezone
  242. return author_timezone, commit_timezone
  243. def open_repo(path_or_repo: Union[str, os.PathLike, BaseRepo]):
  244. """Open an argument that can be a repository or a path for a repository."""
  245. if isinstance(path_or_repo, BaseRepo):
  246. return path_or_repo
  247. return Repo(path_or_repo)
  248. @contextmanager
  249. def _noop_context_manager(obj):
  250. """Context manager that has the same api as closing but does nothing."""
  251. yield obj
  252. def open_repo_closing(path_or_repo: Union[str, os.PathLike, BaseRepo]):
  253. """Open an argument that can be a repository or a path for a repository.
  254. returns a context manager that will close the repo on exit if the argument
  255. is a path, else does nothing if the argument is a repo.
  256. """
  257. if isinstance(path_or_repo, BaseRepo):
  258. return _noop_context_manager(path_or_repo)
  259. return closing(Repo(path_or_repo))
  260. def path_to_tree_path(repopath, path, tree_encoding=DEFAULT_ENCODING):
  261. """Convert a path to a path usable in an index, e.g. bytes and relative to
  262. the repository root.
  263. Args:
  264. repopath: Repository path, absolute or relative to the cwd
  265. path: A path, absolute or relative to the cwd
  266. Returns: A path formatted for use in e.g. an index
  267. """
  268. # Resolve might returns a relative path on Windows
  269. # https://bugs.python.org/issue38671
  270. if sys.platform == "win32":
  271. path = os.path.abspath(path)
  272. path = Path(path)
  273. resolved_path = path.resolve()
  274. # Resolve and abspath seems to behave differently regarding symlinks,
  275. # as we are doing abspath on the file path, we need to do the same on
  276. # the repo path or they might not match
  277. if sys.platform == "win32":
  278. repopath = os.path.abspath(repopath)
  279. repopath = Path(repopath).resolve()
  280. try:
  281. relpath = resolved_path.relative_to(repopath)
  282. except ValueError:
  283. # If path is a symlink that points to a file outside the repo, we
  284. # want the relpath for the link itself, not the resolved target
  285. if path.is_symlink():
  286. parent = path.parent.resolve()
  287. relpath = (parent / path.name).relative_to(repopath)
  288. else:
  289. raise
  290. if sys.platform == "win32":
  291. return str(relpath).replace(os.path.sep, "/").encode(tree_encoding)
  292. else:
  293. return bytes(relpath)
  294. class DivergedBranches(Error):
  295. """Branches have diverged and fast-forward is not possible."""
  296. def __init__(self, current_sha, new_sha) -> None:
  297. self.current_sha = current_sha
  298. self.new_sha = new_sha
  299. def check_diverged(repo, current_sha, new_sha) -> None:
  300. """Check if updating to a sha can be done with fast forwarding.
  301. Args:
  302. repo: Repository object
  303. current_sha: Current head sha
  304. new_sha: New head sha
  305. """
  306. try:
  307. can = can_fast_forward(repo, current_sha, new_sha)
  308. except KeyError:
  309. can = False
  310. if not can:
  311. raise DivergedBranches(current_sha, new_sha)
  312. def archive(
  313. repo,
  314. committish=None,
  315. outstream=default_bytes_out_stream,
  316. errstream=default_bytes_err_stream,
  317. ) -> None:
  318. """Create an archive.
  319. Args:
  320. repo: Path of repository for which to generate an archive.
  321. committish: Commit SHA1 or ref to use
  322. outstream: Output stream (defaults to stdout)
  323. errstream: Error stream (defaults to stderr)
  324. """
  325. if committish is None:
  326. committish = "HEAD"
  327. with open_repo_closing(repo) as repo_obj:
  328. c = parse_commit(repo_obj, committish)
  329. for chunk in tar_stream(
  330. repo_obj.object_store, repo_obj.object_store[c.tree], c.commit_time
  331. ):
  332. outstream.write(chunk)
  333. def update_server_info(repo=".") -> None:
  334. """Update server info files for a repository.
  335. Args:
  336. repo: path to the repository
  337. """
  338. with open_repo_closing(repo) as r:
  339. server_update_server_info(r)
  340. def symbolic_ref(repo, ref_name, force=False) -> None:
  341. """Set git symbolic ref into HEAD.
  342. Args:
  343. repo: path to the repository
  344. ref_name: short name of the new ref
  345. force: force settings without checking if it exists in refs/heads
  346. """
  347. with open_repo_closing(repo) as repo_obj:
  348. ref_path = _make_branch_ref(ref_name)
  349. if not force and ref_path not in repo_obj.refs.keys():
  350. raise Error(f"fatal: ref `{ref_name}` is not a ref")
  351. repo_obj.refs.set_symbolic_ref(b"HEAD", ref_path)
  352. def pack_refs(repo, all=False) -> None:
  353. with open_repo_closing(repo) as repo_obj:
  354. repo_obj.refs.pack_refs(all=all)
  355. def commit(
  356. repo=".",
  357. message=None,
  358. author=None,
  359. author_timezone=None,
  360. committer=None,
  361. commit_timezone=None,
  362. encoding=None,
  363. no_verify=False,
  364. signoff=False,
  365. ):
  366. """Create a new commit.
  367. Args:
  368. repo: Path to repository
  369. message: Optional commit message
  370. author: Optional author name and email
  371. author_timezone: Author timestamp timezone
  372. committer: Optional committer name and email
  373. commit_timezone: Commit timestamp timezone
  374. no_verify: Skip pre-commit and commit-msg hooks
  375. signoff: GPG Sign the commit (bool, defaults to False,
  376. pass True to use default GPG key,
  377. pass a str containing Key ID to use a specific GPG key)
  378. Returns: SHA1 of the new commit
  379. """
  380. # FIXME: Support --all argument
  381. if getattr(message, "encode", None):
  382. message = message.encode(encoding or DEFAULT_ENCODING)
  383. if getattr(author, "encode", None):
  384. author = author.encode(encoding or DEFAULT_ENCODING)
  385. if getattr(committer, "encode", None):
  386. committer = committer.encode(encoding or DEFAULT_ENCODING)
  387. local_timezone = get_user_timezones()
  388. if author_timezone is None:
  389. author_timezone = local_timezone[0]
  390. if commit_timezone is None:
  391. commit_timezone = local_timezone[1]
  392. with open_repo_closing(repo) as r:
  393. return r.do_commit(
  394. message=message,
  395. author=author,
  396. author_timezone=author_timezone,
  397. committer=committer,
  398. commit_timezone=commit_timezone,
  399. encoding=encoding,
  400. no_verify=no_verify,
  401. sign=signoff if isinstance(signoff, (str, bool)) else None,
  402. )
  403. def commit_tree(repo, tree, message=None, author=None, committer=None):
  404. """Create a new commit object.
  405. Args:
  406. repo: Path to repository
  407. tree: An existing tree object
  408. author: Optional author name and email
  409. committer: Optional committer name and email
  410. """
  411. with open_repo_closing(repo) as r:
  412. return r.do_commit(
  413. message=message, tree=tree, committer=committer, author=author
  414. )
  415. def init(
  416. path: Union[str, os.PathLike] = ".", *, bare=False, symlinks: Optional[bool] = None
  417. ):
  418. """Create a new git repository.
  419. Args:
  420. path: Path to repository.
  421. bare: Whether to create a bare repository.
  422. symlinks: Whether to create actual symlinks (defaults to autodetect)
  423. Returns: A Repo instance
  424. """
  425. if not os.path.exists(path):
  426. os.mkdir(path)
  427. if bare:
  428. return Repo.init_bare(path)
  429. else:
  430. return Repo.init(path, symlinks=symlinks)
  431. def clone(
  432. source,
  433. target: Optional[Union[str, os.PathLike]] = None,
  434. bare=False,
  435. checkout=None,
  436. errstream=default_bytes_err_stream,
  437. outstream=None,
  438. origin: Optional[str] = "origin",
  439. depth: Optional[int] = None,
  440. branch: Optional[Union[str, bytes]] = None,
  441. config: Optional[Config] = None,
  442. filter_spec=None,
  443. protocol_version: Optional[int] = None,
  444. recurse_submodules: bool = False,
  445. **kwargs,
  446. ):
  447. """Clone a local or remote git repository.
  448. Args:
  449. source: Path or URL for source repository
  450. target: Path to target repository (optional)
  451. bare: Whether or not to create a bare repository
  452. checkout: Whether or not to check-out HEAD after cloning
  453. errstream: Optional stream to write progress to
  454. outstream: Optional stream to write progress to (deprecated)
  455. origin: Name of remote from the repository used to clone
  456. depth: Depth to fetch at
  457. branch: Optional branch or tag to be used as HEAD in the new repository
  458. instead of the cloned repository's HEAD.
  459. config: Configuration to use
  460. filter_spec: A git-rev-list-style object filter spec, as an ASCII string.
  461. Only used if the server supports the Git protocol-v2 'filter'
  462. feature, and ignored otherwise.
  463. protocol_version: desired Git protocol version. By default the highest
  464. mutually supported protocol version will be used.
  465. recurse_submodules: Whether to initialize and clone submodules
  466. Keyword Args:
  467. refspecs: refspecs to fetch. Can be a bytestring, a string, or a list of
  468. bytestring/string.
  469. Returns: The new repository
  470. """
  471. if outstream is not None:
  472. import warnings
  473. warnings.warn(
  474. "outstream= has been deprecated in favour of errstream=.",
  475. DeprecationWarning,
  476. stacklevel=3,
  477. )
  478. # TODO(jelmer): Capture logging output and stream to errstream
  479. if config is None:
  480. config = StackedConfig.default()
  481. if checkout is None:
  482. checkout = not bare
  483. if checkout and bare:
  484. raise Error("checkout and bare are incompatible")
  485. if target is None:
  486. target = source.split("/")[-1]
  487. if isinstance(branch, str):
  488. branch = branch.encode(DEFAULT_ENCODING)
  489. mkdir = not os.path.exists(target)
  490. (client, path) = get_transport_and_path(source, config=config, **kwargs)
  491. if filter_spec:
  492. filter_spec = filter_spec.encode("ascii")
  493. repo = client.clone(
  494. path,
  495. target,
  496. mkdir=mkdir,
  497. bare=bare,
  498. origin=origin,
  499. checkout=checkout,
  500. branch=branch,
  501. progress=errstream.write,
  502. depth=depth,
  503. filter_spec=filter_spec,
  504. protocol_version=protocol_version,
  505. )
  506. # Initialize and update submodules if requested
  507. if recurse_submodules and not bare:
  508. try:
  509. submodule_init(repo)
  510. submodule_update(repo, init=True)
  511. except FileNotFoundError as e:
  512. # .gitmodules file doesn't exist - no submodules to process
  513. import logging
  514. logging.debug("No .gitmodules file found: %s", e)
  515. except KeyError as e:
  516. # Submodule configuration missing
  517. import logging
  518. logging.warning("Submodule configuration error: %s", e)
  519. if errstream:
  520. errstream.write(
  521. f"Warning: Submodule configuration error: {e}\n".encode()
  522. )
  523. return repo
  524. def add(repo: Union[str, os.PathLike, BaseRepo] = ".", paths=None):
  525. """Add files to the staging area.
  526. Args:
  527. repo: Repository for the files
  528. paths: Paths to add. If None, stages all untracked and modified files from the
  529. current working directory (mimicking 'git add .' behavior).
  530. Returns: Tuple with set of added files and ignored files
  531. If the repository contains ignored directories, the returned set will
  532. contain the path to an ignored directory (with trailing slash). Individual
  533. files within ignored directories will not be returned.
  534. Note: When paths=None, this function adds all untracked and modified files
  535. from the entire repository, mimicking 'git add -A' behavior.
  536. """
  537. ignored = set()
  538. with open_repo_closing(repo) as r:
  539. repo_path = Path(r.path).resolve()
  540. ignore_manager = IgnoreFilterManager.from_repo(r)
  541. # Get unstaged changes once for the entire operation
  542. index = r.open_index()
  543. normalizer = r.get_blob_normalizer()
  544. filter_callback = normalizer.checkin_normalize
  545. all_unstaged_paths = list(get_unstaged_changes(index, r.path, filter_callback))
  546. if not paths:
  547. # When no paths specified, add all untracked and modified files from repo root
  548. paths = [str(repo_path)]
  549. relpaths = []
  550. if not isinstance(paths, list):
  551. paths = [paths]
  552. for p in paths:
  553. path = Path(p)
  554. if not path.is_absolute():
  555. # Make relative paths relative to the repo directory
  556. path = repo_path / path
  557. # Don't resolve symlinks completely - only resolve the parent directory
  558. # to avoid issues when symlinks point outside the repository
  559. if path.is_symlink():
  560. # For symlinks, resolve only the parent directory
  561. parent_resolved = path.parent.resolve()
  562. resolved_path = parent_resolved / path.name
  563. else:
  564. # For regular files/dirs, resolve normally
  565. resolved_path = path.resolve()
  566. try:
  567. relpath = str(resolved_path.relative_to(repo_path)).replace(os.sep, "/")
  568. except ValueError as e:
  569. # Path is not within the repository
  570. raise ValueError(
  571. f"Path {p} is not within repository {repo_path}"
  572. ) from e
  573. # Handle directories by scanning their contents
  574. if resolved_path.is_dir():
  575. # Check if the directory itself is ignored
  576. dir_relpath = posixpath.join(relpath, "") if relpath != "." else ""
  577. if dir_relpath and ignore_manager.is_ignored(dir_relpath):
  578. ignored.add(dir_relpath)
  579. continue
  580. # When adding a directory, add all untracked files within it
  581. current_untracked = list(
  582. get_untracked_paths(
  583. str(resolved_path),
  584. str(repo_path),
  585. index,
  586. )
  587. )
  588. for untracked_path in current_untracked:
  589. # If we're scanning a subdirectory, adjust the path
  590. if relpath != ".":
  591. untracked_path = posixpath.join(relpath, untracked_path)
  592. if not ignore_manager.is_ignored(untracked_path):
  593. relpaths.append(untracked_path)
  594. else:
  595. ignored.add(untracked_path)
  596. # Also add unstaged (modified) files within this directory
  597. for unstaged_path in all_unstaged_paths:
  598. if isinstance(unstaged_path, bytes):
  599. unstaged_path_str = unstaged_path.decode("utf-8")
  600. else:
  601. unstaged_path_str = unstaged_path
  602. # Check if this unstaged file is within the directory we're processing
  603. unstaged_full_path = repo_path / unstaged_path_str
  604. try:
  605. unstaged_full_path.relative_to(resolved_path)
  606. # File is within this directory, add it
  607. if not ignore_manager.is_ignored(unstaged_path_str):
  608. relpaths.append(unstaged_path_str)
  609. else:
  610. ignored.add(unstaged_path_str)
  611. except ValueError:
  612. # File is not within this directory, skip it
  613. continue
  614. continue
  615. # FIXME: Support patterns
  616. if ignore_manager.is_ignored(relpath):
  617. ignored.add(relpath)
  618. continue
  619. relpaths.append(relpath)
  620. r.stage(relpaths)
  621. return (relpaths, ignored)
  622. def _is_subdir(subdir, parentdir):
  623. """Check whether subdir is parentdir or a subdir of parentdir.
  624. If parentdir or subdir is a relative path, it will be disamgibuated
  625. relative to the pwd.
  626. """
  627. parentdir_abs = os.path.realpath(parentdir) + os.path.sep
  628. subdir_abs = os.path.realpath(subdir) + os.path.sep
  629. return subdir_abs.startswith(parentdir_abs)
  630. # TODO: option to remove ignored files also, in line with `git clean -fdx`
  631. def clean(repo=".", target_dir=None) -> None:
  632. """Remove any untracked files from the target directory recursively.
  633. Equivalent to running ``git clean -fd`` in target_dir.
  634. Args:
  635. repo: Repository where the files may be tracked
  636. target_dir: Directory to clean - current directory if None
  637. """
  638. if target_dir is None:
  639. target_dir = os.getcwd()
  640. with open_repo_closing(repo) as r:
  641. if not _is_subdir(target_dir, r.path):
  642. raise Error("target_dir must be in the repo's working dir")
  643. config = r.get_config_stack()
  644. config.get_boolean((b"clean",), b"requireForce", True)
  645. # TODO(jelmer): if require_force is set, then make sure that -f, -i or
  646. # -n is specified.
  647. index = r.open_index()
  648. ignore_manager = IgnoreFilterManager.from_repo(r)
  649. paths_in_wd = _walk_working_dir_paths(target_dir, r.path)
  650. # Reverse file visit order, so that files and subdirectories are
  651. # removed before containing directory
  652. for ap, is_dir in reversed(list(paths_in_wd)):
  653. if is_dir:
  654. # All subdirectories and files have been removed if untracked,
  655. # so dir contains no tracked files iff it is empty.
  656. is_empty = len(os.listdir(ap)) == 0
  657. if is_empty:
  658. os.rmdir(ap)
  659. else:
  660. ip = path_to_tree_path(r.path, ap)
  661. is_tracked = ip in index
  662. rp = os.path.relpath(ap, r.path)
  663. is_ignored = ignore_manager.is_ignored(rp)
  664. if not is_tracked and not is_ignored:
  665. os.remove(ap)
  666. def remove(repo=".", paths=None, cached=False) -> None:
  667. """Remove files from the staging area.
  668. Args:
  669. repo: Repository for the files
  670. paths: Paths to remove. Can be absolute or relative to the repository root.
  671. """
  672. with open_repo_closing(repo) as r:
  673. index = r.open_index()
  674. for p in paths:
  675. # If path is absolute, use it as-is. Otherwise, treat it as relative to repo
  676. if os.path.isabs(p):
  677. full_path = p
  678. else:
  679. # Treat relative paths as relative to the repository root
  680. full_path = os.path.join(r.path, p)
  681. tree_path = path_to_tree_path(r.path, full_path)
  682. # Convert to bytes for file operations
  683. full_path_bytes = os.fsencode(full_path)
  684. try:
  685. index_sha = index[tree_path].sha
  686. except KeyError as exc:
  687. raise Error(f"{p} did not match any files") from exc
  688. if not cached:
  689. try:
  690. st = os.lstat(full_path_bytes)
  691. except OSError:
  692. pass
  693. else:
  694. try:
  695. blob = blob_from_path_and_stat(full_path_bytes, st)
  696. except OSError:
  697. pass
  698. else:
  699. try:
  700. committed_sha = tree_lookup_path(
  701. r.__getitem__, r[r.head()].tree, tree_path
  702. )[1]
  703. except KeyError:
  704. committed_sha = None
  705. if blob.id != index_sha and index_sha != committed_sha:
  706. raise Error(
  707. "file has staged content differing "
  708. f"from both the file and head: {p}"
  709. )
  710. if index_sha != committed_sha:
  711. raise Error(f"file has staged changes: {p}")
  712. os.remove(full_path_bytes)
  713. del index[tree_path]
  714. index.write()
  715. rm = remove
  716. def mv(
  717. repo: Union[str, os.PathLike, BaseRepo],
  718. source: Union[str, bytes, os.PathLike],
  719. destination: Union[str, bytes, os.PathLike],
  720. force: bool = False,
  721. ) -> None:
  722. """Move or rename a file, directory, or symlink.
  723. Args:
  724. repo: Path to the repository
  725. source: Path to move from
  726. destination: Path to move to
  727. force: Force move even if destination exists
  728. Raises:
  729. Error: If source doesn't exist, is not tracked, or destination already exists (without force)
  730. """
  731. with open_repo_closing(repo) as r:
  732. index = r.open_index()
  733. # Handle paths - convert to string if necessary
  734. if isinstance(source, bytes):
  735. source = source.decode(sys.getfilesystemencoding())
  736. elif hasattr(source, "__fspath__"):
  737. source = os.fspath(source)
  738. else:
  739. source = str(source)
  740. if isinstance(destination, bytes):
  741. destination = destination.decode(sys.getfilesystemencoding())
  742. elif hasattr(destination, "__fspath__"):
  743. destination = os.fspath(destination)
  744. else:
  745. destination = str(destination)
  746. # Get full paths
  747. if os.path.isabs(source):
  748. source_full_path = source
  749. else:
  750. # Treat relative paths as relative to the repository root
  751. source_full_path = os.path.join(r.path, source)
  752. if os.path.isabs(destination):
  753. destination_full_path = destination
  754. else:
  755. # Treat relative paths as relative to the repository root
  756. destination_full_path = os.path.join(r.path, destination)
  757. # Check if destination is a directory
  758. if os.path.isdir(destination_full_path):
  759. # Move source into destination directory
  760. basename = os.path.basename(source_full_path)
  761. destination_full_path = os.path.join(destination_full_path, basename)
  762. # Convert to tree paths for index
  763. source_tree_path = path_to_tree_path(r.path, source_full_path)
  764. destination_tree_path = path_to_tree_path(r.path, destination_full_path)
  765. # Check if source exists in index
  766. if source_tree_path not in index:
  767. raise Error(f"source '{source}' is not under version control")
  768. # Check if source exists in filesystem
  769. if not os.path.exists(source_full_path):
  770. raise Error(f"source '{source}' does not exist")
  771. # Check if destination already exists
  772. if os.path.exists(destination_full_path) and not force:
  773. raise Error(f"destination '{destination}' already exists (use -f to force)")
  774. # Check if destination is already in index
  775. if destination_tree_path in index and not force:
  776. raise Error(
  777. f"destination '{destination}' already exists in index (use -f to force)"
  778. )
  779. # Get the index entry for the source
  780. source_entry = index[source_tree_path]
  781. # Convert to bytes for file operations
  782. source_full_path_bytes = os.fsencode(source_full_path)
  783. destination_full_path_bytes = os.fsencode(destination_full_path)
  784. # Create parent directory for destination if needed
  785. dest_dir = os.path.dirname(destination_full_path_bytes)
  786. if dest_dir and not os.path.exists(dest_dir):
  787. os.makedirs(dest_dir)
  788. # Move the file in the filesystem
  789. if os.path.exists(destination_full_path_bytes) and force:
  790. os.remove(destination_full_path_bytes)
  791. os.rename(source_full_path_bytes, destination_full_path_bytes)
  792. # Update the index
  793. del index[source_tree_path]
  794. index[destination_tree_path] = source_entry
  795. index.write()
  796. move = mv
  797. def commit_decode(commit, contents, default_encoding=DEFAULT_ENCODING):
  798. if commit.encoding:
  799. encoding = commit.encoding.decode("ascii")
  800. else:
  801. encoding = default_encoding
  802. return contents.decode(encoding, "replace")
  803. def commit_encode(commit, contents, default_encoding=DEFAULT_ENCODING):
  804. if commit.encoding:
  805. encoding = commit.encoding.decode("ascii")
  806. else:
  807. encoding = default_encoding
  808. return contents.encode(encoding)
  809. def print_commit(commit, decode, outstream=sys.stdout) -> None:
  810. """Write a human-readable commit log entry.
  811. Args:
  812. commit: A `Commit` object
  813. outstream: A stream file to write to
  814. """
  815. outstream.write("-" * 50 + "\n")
  816. outstream.write("commit: " + commit.id.decode("ascii") + "\n")
  817. if len(commit.parents) > 1:
  818. outstream.write(
  819. "merge: "
  820. + "...".join([c.decode("ascii") for c in commit.parents[1:]])
  821. + "\n"
  822. )
  823. outstream.write("Author: " + decode(commit.author) + "\n")
  824. if commit.author != commit.committer:
  825. outstream.write("Committer: " + decode(commit.committer) + "\n")
  826. time_tuple = time.gmtime(commit.author_time + commit.author_timezone)
  827. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  828. timezone_str = format_timezone(commit.author_timezone).decode("ascii")
  829. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  830. if commit.message:
  831. outstream.write("\n")
  832. outstream.write(decode(commit.message) + "\n")
  833. outstream.write("\n")
  834. def print_tag(tag, decode, outstream=sys.stdout) -> None:
  835. """Write a human-readable tag.
  836. Args:
  837. tag: A `Tag` object
  838. decode: Function for decoding bytes to unicode string
  839. outstream: A stream to write to
  840. """
  841. outstream.write("Tagger: " + decode(tag.tagger) + "\n")
  842. time_tuple = time.gmtime(tag.tag_time + tag.tag_timezone)
  843. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  844. timezone_str = format_timezone(tag.tag_timezone).decode("ascii")
  845. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  846. outstream.write("\n")
  847. outstream.write(decode(tag.message))
  848. outstream.write("\n")
  849. def show_blob(repo, blob, decode, outstream=sys.stdout) -> None:
  850. """Write a blob to a stream.
  851. Args:
  852. repo: A `Repo` object
  853. blob: A `Blob` object
  854. decode: Function for decoding bytes to unicode string
  855. outstream: A stream file to write to
  856. """
  857. outstream.write(decode(blob.data))
  858. def show_commit(repo, commit, decode, outstream=sys.stdout) -> None:
  859. """Show a commit to a stream.
  860. Args:
  861. repo: A `Repo` object
  862. commit: A `Commit` object
  863. decode: Function for decoding bytes to unicode string
  864. outstream: Stream to write to
  865. """
  866. print_commit(commit, decode=decode, outstream=outstream)
  867. if commit.parents:
  868. parent_commit = repo[commit.parents[0]]
  869. base_tree = parent_commit.tree
  870. else:
  871. base_tree = None
  872. diffstream = BytesIO()
  873. write_tree_diff(diffstream, repo.object_store, base_tree, commit.tree)
  874. diffstream.seek(0)
  875. outstream.write(commit_decode(commit, diffstream.getvalue()))
  876. def show_tree(repo, tree, decode, outstream=sys.stdout) -> None:
  877. """Print a tree to a stream.
  878. Args:
  879. repo: A `Repo` object
  880. tree: A `Tree` object
  881. decode: Function for decoding bytes to unicode string
  882. outstream: Stream to write to
  883. """
  884. for n in tree:
  885. outstream.write(decode(n) + "\n")
  886. def show_tag(repo, tag, decode, outstream=sys.stdout) -> None:
  887. """Print a tag to a stream.
  888. Args:
  889. repo: A `Repo` object
  890. tag: A `Tag` object
  891. decode: Function for decoding bytes to unicode string
  892. outstream: Stream to write to
  893. """
  894. print_tag(tag, decode, outstream)
  895. show_object(repo, repo[tag.object[1]], decode, outstream)
  896. def show_object(repo, obj, decode, outstream):
  897. return {
  898. b"tree": show_tree,
  899. b"blob": show_blob,
  900. b"commit": show_commit,
  901. b"tag": show_tag,
  902. }[obj.type_name](repo, obj, decode, outstream)
  903. def print_name_status(changes):
  904. """Print a simple status summary, listing changed files."""
  905. for change in changes:
  906. if not change:
  907. continue
  908. if isinstance(change, list):
  909. change = change[0]
  910. if change.type == CHANGE_ADD:
  911. path1 = change.new.path
  912. path2 = ""
  913. kind = "A"
  914. elif change.type == CHANGE_DELETE:
  915. path1 = change.old.path
  916. path2 = ""
  917. kind = "D"
  918. elif change.type == CHANGE_MODIFY:
  919. path1 = change.new.path
  920. path2 = ""
  921. kind = "M"
  922. elif change.type in RENAME_CHANGE_TYPES:
  923. path1 = change.old.path
  924. path2 = change.new.path
  925. if change.type == CHANGE_RENAME:
  926. kind = "R"
  927. elif change.type == CHANGE_COPY:
  928. kind = "C"
  929. yield "%-8s%-20s%-20s" % (kind, path1, path2) # noqa: UP031
  930. def log(
  931. repo=".",
  932. paths=None,
  933. outstream=sys.stdout,
  934. max_entries=None,
  935. reverse=False,
  936. name_status=False,
  937. ) -> None:
  938. """Write commit logs.
  939. Args:
  940. repo: Path to repository
  941. paths: Optional set of specific paths to print entries for
  942. outstream: Stream to write log output to
  943. reverse: Reverse order in which entries are printed
  944. name_status: Print name status
  945. max_entries: Optional maximum number of entries to display
  946. """
  947. with open_repo_closing(repo) as r:
  948. try:
  949. include = [r.head()]
  950. except KeyError:
  951. include = []
  952. walker = r.get_walker(
  953. include=include, max_entries=max_entries, paths=paths, reverse=reverse
  954. )
  955. for entry in walker:
  956. def decode(x):
  957. return commit_decode(entry.commit, x)
  958. print_commit(entry.commit, decode, outstream)
  959. if name_status:
  960. outstream.writelines(
  961. [line + "\n" for line in print_name_status(entry.changes())]
  962. )
  963. # TODO(jelmer): better default for encoding?
  964. def show(
  965. repo=".",
  966. objects=None,
  967. outstream=sys.stdout,
  968. default_encoding=DEFAULT_ENCODING,
  969. ) -> None:
  970. """Print the changes in a commit.
  971. Args:
  972. repo: Path to repository
  973. objects: Objects to show (defaults to [HEAD])
  974. outstream: Stream to write to
  975. default_encoding: Default encoding to use if none is set in the
  976. commit
  977. """
  978. if objects is None:
  979. objects = ["HEAD"]
  980. if not isinstance(objects, list):
  981. objects = [objects]
  982. with open_repo_closing(repo) as r:
  983. for objectish in objects:
  984. o = parse_object(r, objectish)
  985. if isinstance(o, Commit):
  986. def decode(x):
  987. return commit_decode(o, x, default_encoding)
  988. else:
  989. def decode(x):
  990. return x.decode(default_encoding)
  991. show_object(r, o, decode, outstream)
  992. def diff_tree(repo, old_tree, new_tree, outstream=default_bytes_out_stream) -> None:
  993. """Compares the content and mode of blobs found via two tree objects.
  994. Args:
  995. repo: Path to repository
  996. old_tree: Id of old tree
  997. new_tree: Id of new tree
  998. outstream: Stream to write to
  999. """
  1000. with open_repo_closing(repo) as r:
  1001. write_tree_diff(outstream, r.object_store, old_tree, new_tree)
  1002. def rev_list(repo, commits, outstream=sys.stdout) -> None:
  1003. """Lists commit objects in reverse chronological order.
  1004. Args:
  1005. repo: Path to repository
  1006. commits: Commits over which to iterate
  1007. outstream: Stream to write to
  1008. """
  1009. with open_repo_closing(repo) as r:
  1010. for entry in r.get_walker(include=[r[c].id for c in commits]):
  1011. outstream.write(entry.commit.id + b"\n")
  1012. def _canonical_part(url: str) -> str:
  1013. name = url.rsplit("/", 1)[-1]
  1014. if name.endswith(".git"):
  1015. name = name[:-4]
  1016. return name
  1017. def submodule_add(repo, url, path=None, name=None) -> None:
  1018. """Add a new submodule.
  1019. Args:
  1020. repo: Path to repository
  1021. url: URL of repository to add as submodule
  1022. path: Path where submodule should live
  1023. name: Name for the submodule
  1024. """
  1025. with open_repo_closing(repo) as r:
  1026. if path is None:
  1027. path = os.path.relpath(_canonical_part(url), r.path)
  1028. if name is None:
  1029. name = path
  1030. # TODO(jelmer): Move this logic to dulwich.submodule
  1031. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1032. try:
  1033. config = ConfigFile.from_path(gitmodules_path)
  1034. except FileNotFoundError:
  1035. config = ConfigFile()
  1036. config.path = gitmodules_path
  1037. config.set(("submodule", name), "url", url)
  1038. config.set(("submodule", name), "path", path)
  1039. config.write_to_path()
  1040. def submodule_init(repo) -> None:
  1041. """Initialize submodules.
  1042. Args:
  1043. repo: Path to repository
  1044. """
  1045. with open_repo_closing(repo) as r:
  1046. config = r.get_config()
  1047. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1048. for path, url, name in read_submodules(gitmodules_path):
  1049. config.set((b"submodule", name), b"active", True)
  1050. config.set((b"submodule", name), b"url", url)
  1051. config.write_to_path()
  1052. def submodule_list(repo):
  1053. """List submodules.
  1054. Args:
  1055. repo: Path to repository
  1056. """
  1057. from .submodule import iter_cached_submodules
  1058. with open_repo_closing(repo) as r:
  1059. for path, sha in iter_cached_submodules(r.object_store, r[r.head()].tree):
  1060. yield path, sha.decode(DEFAULT_ENCODING)
  1061. def submodule_update(repo, paths=None, init=False, force=False, errstream=None) -> None:
  1062. """Update submodules.
  1063. Args:
  1064. repo: Path to repository
  1065. paths: Optional list of specific submodule paths to update. If None, updates all.
  1066. init: If True, initialize submodules first
  1067. force: Force update even if local changes exist
  1068. """
  1069. from .client import get_transport_and_path
  1070. from .index import build_index_from_tree
  1071. from .submodule import iter_cached_submodules
  1072. with open_repo_closing(repo) as r:
  1073. if init:
  1074. submodule_init(r)
  1075. config = r.get_config()
  1076. gitmodules_path = os.path.join(r.path, ".gitmodules")
  1077. # Get list of submodules to update
  1078. submodules_to_update = []
  1079. for path, sha in iter_cached_submodules(r.object_store, r[r.head()].tree):
  1080. path_str = (
  1081. path.decode(DEFAULT_ENCODING) if isinstance(path, bytes) else path
  1082. )
  1083. if paths is None or path_str in paths:
  1084. submodules_to_update.append((path, sha))
  1085. # Read submodule configuration
  1086. for path, target_sha in submodules_to_update:
  1087. path_str = (
  1088. path.decode(DEFAULT_ENCODING) if isinstance(path, bytes) else path
  1089. )
  1090. # Find the submodule name from .gitmodules
  1091. submodule_name = None
  1092. for sm_path, sm_url, sm_name in read_submodules(gitmodules_path):
  1093. if sm_path == path:
  1094. submodule_name = sm_name
  1095. break
  1096. if not submodule_name:
  1097. continue
  1098. # Get the URL from config
  1099. section = (
  1100. b"submodule",
  1101. submodule_name
  1102. if isinstance(submodule_name, bytes)
  1103. else submodule_name.encode(),
  1104. )
  1105. try:
  1106. url = config.get(section, b"url")
  1107. if isinstance(url, bytes):
  1108. url = url.decode(DEFAULT_ENCODING)
  1109. except KeyError:
  1110. # URL not in config, skip this submodule
  1111. continue
  1112. # Get or create the submodule repository paths
  1113. submodule_path = os.path.join(r.path, path_str)
  1114. submodule_git_dir = os.path.join(r.path, ".git", "modules", path_str)
  1115. # Clone or fetch the submodule
  1116. if not os.path.exists(submodule_git_dir):
  1117. # Clone the submodule as bare repository
  1118. os.makedirs(os.path.dirname(submodule_git_dir), exist_ok=True)
  1119. # Clone to the git directory
  1120. sub_repo = clone(url, submodule_git_dir, bare=True, checkout=False)
  1121. sub_repo.close()
  1122. # Create the submodule directory if it doesn't exist
  1123. if not os.path.exists(submodule_path):
  1124. os.makedirs(submodule_path)
  1125. # Create .git file in the submodule directory
  1126. depth = path_str.count("/") + 1
  1127. relative_git_dir = "../" * depth + ".git/modules/" + path_str
  1128. git_file_path = os.path.join(submodule_path, ".git")
  1129. with open(git_file_path, "w") as f:
  1130. f.write(f"gitdir: {relative_git_dir}\n")
  1131. # Set up working directory configuration
  1132. with open_repo_closing(submodule_git_dir) as sub_repo:
  1133. sub_config = sub_repo.get_config()
  1134. sub_config.set(
  1135. (b"core",),
  1136. b"worktree",
  1137. os.path.abspath(submodule_path).encode(),
  1138. )
  1139. sub_config.write_to_path()
  1140. # Checkout the target commit
  1141. sub_repo.refs[b"HEAD"] = target_sha
  1142. # Build the index and checkout files
  1143. tree = sub_repo[target_sha]
  1144. if hasattr(tree, "tree"): # If it's a commit, get the tree
  1145. tree_id = tree.tree
  1146. else:
  1147. tree_id = target_sha
  1148. build_index_from_tree(
  1149. submodule_path,
  1150. sub_repo.index_path(),
  1151. sub_repo.object_store,
  1152. tree_id,
  1153. )
  1154. else:
  1155. # Fetch and checkout in existing submodule
  1156. with open_repo_closing(submodule_git_dir) as sub_repo:
  1157. # Fetch from remote
  1158. client, path_segments = get_transport_and_path(url)
  1159. client.fetch(path_segments, sub_repo)
  1160. # Update to the target commit
  1161. sub_repo.refs[b"HEAD"] = target_sha
  1162. # Reset the working directory
  1163. reset(sub_repo, "hard", target_sha)
  1164. def tag_create(
  1165. repo,
  1166. tag: Union[str, bytes],
  1167. author: Optional[Union[str, bytes]] = None,
  1168. message: Optional[Union[str, bytes]] = None,
  1169. annotated=False,
  1170. objectish: Union[str, bytes] = "HEAD",
  1171. tag_time=None,
  1172. tag_timezone=None,
  1173. sign: bool = False,
  1174. encoding: str = DEFAULT_ENCODING,
  1175. ) -> None:
  1176. """Creates a tag in git via dulwich calls.
  1177. Args:
  1178. repo: Path to repository
  1179. tag: tag string
  1180. author: tag author (optional, if annotated is set)
  1181. message: tag message (optional)
  1182. annotated: whether to create an annotated tag
  1183. objectish: object the tag should point at, defaults to HEAD
  1184. tag_time: Optional time for annotated tag
  1185. tag_timezone: Optional timezone for annotated tag
  1186. sign: GPG Sign the tag (bool, defaults to False,
  1187. pass True to use default GPG key,
  1188. pass a str containing Key ID to use a specific GPG key)
  1189. """
  1190. with open_repo_closing(repo) as r:
  1191. object = parse_object(r, objectish)
  1192. if isinstance(tag, str):
  1193. tag = tag.encode(encoding)
  1194. if annotated:
  1195. # Create the tag object
  1196. tag_obj = Tag()
  1197. if author is None:
  1198. author = get_user_identity(r.get_config_stack())
  1199. elif isinstance(author, str):
  1200. author = author.encode(encoding)
  1201. else:
  1202. assert isinstance(author, bytes)
  1203. tag_obj.tagger = author
  1204. if isinstance(message, str):
  1205. message = message.encode(encoding)
  1206. elif isinstance(message, bytes):
  1207. pass
  1208. else:
  1209. message = b""
  1210. tag_obj.message = message + "\n".encode(encoding)
  1211. tag_obj.name = tag
  1212. tag_obj.object = (type(object), object.id)
  1213. if tag_time is None:
  1214. tag_time = int(time.time())
  1215. tag_obj.tag_time = tag_time
  1216. if tag_timezone is None:
  1217. tag_timezone = get_user_timezones()[1]
  1218. elif isinstance(tag_timezone, str):
  1219. tag_timezone = parse_timezone(tag_timezone.encode())
  1220. tag_obj.tag_timezone = tag_timezone
  1221. if sign:
  1222. tag_obj.sign(sign if isinstance(sign, str) else None)
  1223. r.object_store.add_object(tag_obj)
  1224. tag_id = tag_obj.id
  1225. else:
  1226. tag_id = object.id
  1227. r.refs[_make_tag_ref(tag)] = tag_id
  1228. def tag_list(repo, outstream=sys.stdout):
  1229. """List all tags.
  1230. Args:
  1231. repo: Path to repository
  1232. outstream: Stream to write tags to
  1233. """
  1234. with open_repo_closing(repo) as r:
  1235. tags = sorted(r.refs.as_dict(b"refs/tags"))
  1236. return tags
  1237. def tag_delete(repo, name) -> None:
  1238. """Remove a tag.
  1239. Args:
  1240. repo: Path to repository
  1241. name: Name of tag to remove
  1242. """
  1243. with open_repo_closing(repo) as r:
  1244. if isinstance(name, bytes):
  1245. names = [name]
  1246. elif isinstance(name, list):
  1247. names = name
  1248. else:
  1249. raise Error(f"Unexpected tag name type {name!r}")
  1250. for name in names:
  1251. del r.refs[_make_tag_ref(name)]
  1252. def _make_notes_ref(name: bytes) -> bytes:
  1253. """Make a notes ref name."""
  1254. if name.startswith(b"refs/notes/"):
  1255. return name
  1256. return LOCAL_NOTES_PREFIX + name
  1257. def notes_add(
  1258. repo, object_sha, note, ref=b"commits", author=None, committer=None, message=None
  1259. ):
  1260. """Add or update a note for an object.
  1261. Args:
  1262. repo: Path to repository
  1263. object_sha: SHA of the object to annotate
  1264. note: Note content
  1265. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  1266. author: Author identity (defaults to committer)
  1267. committer: Committer identity (defaults to config)
  1268. message: Commit message for the notes update
  1269. Returns:
  1270. SHA of the new notes commit
  1271. """
  1272. with open_repo_closing(repo) as r:
  1273. # Parse the object to get its SHA
  1274. obj = parse_object(r, object_sha)
  1275. object_sha = obj.id
  1276. if isinstance(note, str):
  1277. note = note.encode(DEFAULT_ENCODING)
  1278. if isinstance(ref, str):
  1279. ref = ref.encode(DEFAULT_ENCODING)
  1280. notes_ref = _make_notes_ref(ref)
  1281. config = r.get_config_stack()
  1282. return r.notes.set_note(
  1283. object_sha,
  1284. note,
  1285. notes_ref,
  1286. author=author,
  1287. committer=committer,
  1288. message=message,
  1289. config=config,
  1290. )
  1291. def notes_remove(
  1292. repo, object_sha, ref=b"commits", author=None, committer=None, message=None
  1293. ):
  1294. """Remove a note for an object.
  1295. Args:
  1296. repo: Path to repository
  1297. object_sha: SHA of the object to remove notes from
  1298. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  1299. author: Author identity (defaults to committer)
  1300. committer: Committer identity (defaults to config)
  1301. message: Commit message for the notes removal
  1302. Returns:
  1303. SHA of the new notes commit, or None if no note existed
  1304. """
  1305. with open_repo_closing(repo) as r:
  1306. # Parse the object to get its SHA
  1307. obj = parse_object(r, object_sha)
  1308. object_sha = obj.id
  1309. if isinstance(ref, str):
  1310. ref = ref.encode(DEFAULT_ENCODING)
  1311. notes_ref = _make_notes_ref(ref)
  1312. config = r.get_config_stack()
  1313. return r.notes.remove_note(
  1314. object_sha,
  1315. notes_ref,
  1316. author=author,
  1317. committer=committer,
  1318. message=message,
  1319. config=config,
  1320. )
  1321. def notes_show(repo, object_sha, ref=b"commits"):
  1322. """Show the note for an object.
  1323. Args:
  1324. repo: Path to repository
  1325. object_sha: SHA of the object
  1326. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  1327. Returns:
  1328. Note content as bytes, or None if no note exists
  1329. """
  1330. with open_repo_closing(repo) as r:
  1331. # Parse the object to get its SHA
  1332. obj = parse_object(r, object_sha)
  1333. object_sha = obj.id
  1334. if isinstance(ref, str):
  1335. ref = ref.encode(DEFAULT_ENCODING)
  1336. notes_ref = _make_notes_ref(ref)
  1337. config = r.get_config_stack()
  1338. return r.notes.get_note(object_sha, notes_ref, config=config)
  1339. def notes_list(repo, ref=b"commits"):
  1340. """List all notes in a notes ref.
  1341. Args:
  1342. repo: Path to repository
  1343. ref: Notes ref to use (defaults to "commits" for refs/notes/commits)
  1344. Returns:
  1345. List of tuples of (object_sha, note_content)
  1346. """
  1347. with open_repo_closing(repo) as r:
  1348. if isinstance(ref, str):
  1349. ref = ref.encode(DEFAULT_ENCODING)
  1350. notes_ref = _make_notes_ref(ref)
  1351. config = r.get_config_stack()
  1352. return r.notes.list_notes(notes_ref, config=config)
  1353. def reset(repo, mode, treeish="HEAD") -> None:
  1354. """Reset current HEAD to the specified state.
  1355. Args:
  1356. repo: Path to repository
  1357. mode: Mode ("hard", "soft", "mixed")
  1358. treeish: Treeish to reset to
  1359. """
  1360. with open_repo_closing(repo) as r:
  1361. # Parse the target tree
  1362. tree = parse_tree(r, treeish)
  1363. target_commit = parse_commit(r, treeish)
  1364. # Update HEAD to point to the target commit
  1365. r.refs[b"HEAD"] = target_commit.id
  1366. if mode == "soft":
  1367. # Soft reset: only update HEAD, leave index and working tree unchanged
  1368. return
  1369. elif mode == "mixed":
  1370. # Mixed reset: update HEAD and index, but leave working tree unchanged
  1371. from .index import IndexEntry
  1372. from .object_store import iter_tree_contents
  1373. # Open the index
  1374. index = r.open_index()
  1375. # Clear the current index
  1376. index.clear()
  1377. # Populate index from the target tree
  1378. for entry in iter_tree_contents(r.object_store, tree.id):
  1379. # Create an IndexEntry from the tree entry
  1380. # Use zeros for filesystem-specific fields since we're not touching the working tree
  1381. index_entry = IndexEntry(
  1382. ctime=(0, 0),
  1383. mtime=(0, 0),
  1384. dev=0,
  1385. ino=0,
  1386. mode=entry.mode,
  1387. uid=0,
  1388. gid=0,
  1389. size=0, # Size will be 0 since we're not reading from disk
  1390. sha=entry.sha,
  1391. flags=0,
  1392. )
  1393. index[entry.path] = index_entry
  1394. # Write the updated index
  1395. index.write()
  1396. elif mode == "hard":
  1397. # Hard reset: update HEAD, index, and working tree
  1398. # Get current HEAD tree for comparison
  1399. try:
  1400. current_head = r.refs[b"HEAD"]
  1401. current_tree = r[current_head].tree
  1402. except KeyError:
  1403. current_tree = None
  1404. # Get configuration for working directory update
  1405. config = r.get_config()
  1406. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  1407. # Import validation functions
  1408. from .index import validate_path_element_default, validate_path_element_ntfs
  1409. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  1410. validate_path_element = validate_path_element_ntfs
  1411. else:
  1412. validate_path_element = validate_path_element_default
  1413. if config.get_boolean(b"core", b"symlinks", True):
  1414. # Import symlink function
  1415. from .index import symlink
  1416. symlink_fn = symlink
  1417. else:
  1418. def symlink_fn( # type: ignore
  1419. source, target, target_is_directory=False, *, dir_fd=None
  1420. ) -> None:
  1421. mode = "w" + ("b" if isinstance(source, bytes) else "")
  1422. with open(target, mode) as f:
  1423. f.write(source)
  1424. # Update working tree and index
  1425. blob_normalizer = r.get_blob_normalizer()
  1426. update_working_tree(
  1427. r,
  1428. current_tree,
  1429. tree.id,
  1430. honor_filemode=honor_filemode,
  1431. validate_path_element=validate_path_element,
  1432. symlink_fn=symlink_fn,
  1433. force_remove_untracked=True,
  1434. blob_normalizer=blob_normalizer,
  1435. )
  1436. else:
  1437. raise Error(f"Invalid reset mode: {mode}")
  1438. def get_remote_repo(
  1439. repo: Repo, remote_location: Optional[Union[str, bytes]] = None
  1440. ) -> tuple[Optional[str], str]:
  1441. config = repo.get_config()
  1442. if remote_location is None:
  1443. remote_location = get_branch_remote(repo)
  1444. if isinstance(remote_location, str):
  1445. encoded_location = remote_location.encode()
  1446. else:
  1447. encoded_location = remote_location
  1448. section = (b"remote", encoded_location)
  1449. remote_name: Optional[str] = None
  1450. if config.has_section(section):
  1451. remote_name = encoded_location.decode()
  1452. encoded_location = config.get(section, "url")
  1453. else:
  1454. remote_name = None
  1455. return (remote_name, encoded_location.decode())
  1456. def push(
  1457. repo,
  1458. remote_location=None,
  1459. refspecs=None,
  1460. outstream=default_bytes_out_stream,
  1461. errstream=default_bytes_err_stream,
  1462. force=False,
  1463. **kwargs,
  1464. ):
  1465. """Remote push with dulwich via dulwich.client.
  1466. Args:
  1467. repo: Path to repository
  1468. remote_location: Location of the remote
  1469. refspecs: Refs to push to remote
  1470. outstream: A stream file to write output
  1471. errstream: A stream file to write errors
  1472. force: Force overwriting refs
  1473. """
  1474. # Open the repo
  1475. with open_repo_closing(repo) as r:
  1476. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  1477. # Check if mirror mode is enabled
  1478. mirror_mode = False
  1479. if remote_name:
  1480. try:
  1481. mirror_mode = r.get_config_stack().get_boolean(
  1482. (b"remote", remote_name.encode()), b"mirror"
  1483. )
  1484. except KeyError:
  1485. pass
  1486. if mirror_mode:
  1487. # Mirror mode: push all refs and delete non-existent ones
  1488. refspecs = []
  1489. for ref in r.refs.keys():
  1490. # Push all refs to the same name on remote
  1491. refspecs.append(ref + b":" + ref)
  1492. elif refspecs is None:
  1493. refspecs = [active_branch(r)]
  1494. # Get the client and path
  1495. client, path = get_transport_and_path(
  1496. remote_location, config=r.get_config_stack(), **kwargs
  1497. )
  1498. selected_refs = []
  1499. remote_changed_refs = {}
  1500. def update_refs(refs):
  1501. selected_refs.extend(parse_reftuples(r.refs, refs, refspecs, force=force))
  1502. new_refs = {}
  1503. # In mirror mode, delete remote refs that don't exist locally
  1504. if mirror_mode:
  1505. local_refs = set(r.refs.keys())
  1506. for remote_ref in refs.keys():
  1507. if remote_ref not in local_refs:
  1508. new_refs[remote_ref] = ZERO_SHA
  1509. remote_changed_refs[remote_ref] = None
  1510. # TODO: Handle selected_refs == {None: None}
  1511. for lh, rh, force_ref in selected_refs:
  1512. if lh is None:
  1513. new_refs[rh] = ZERO_SHA
  1514. remote_changed_refs[rh] = None
  1515. else:
  1516. try:
  1517. localsha = r.refs[lh]
  1518. except KeyError as exc:
  1519. raise Error(f"No valid ref {lh} in local repository") from exc
  1520. if not force_ref and rh in refs:
  1521. check_diverged(r, refs[rh], localsha)
  1522. new_refs[rh] = localsha
  1523. remote_changed_refs[rh] = localsha
  1524. return new_refs
  1525. err_encoding = getattr(errstream, "encoding", None) or DEFAULT_ENCODING
  1526. remote_location = client.get_url(path)
  1527. try:
  1528. result = client.send_pack(
  1529. path,
  1530. update_refs,
  1531. generate_pack_data=r.generate_pack_data,
  1532. progress=errstream.write,
  1533. )
  1534. except SendPackError as exc:
  1535. raise Error(
  1536. "Push to " + remote_location + " failed -> " + exc.args[0].decode(),
  1537. ) from exc
  1538. else:
  1539. errstream.write(
  1540. b"Push to " + remote_location.encode(err_encoding) + b" successful.\n"
  1541. )
  1542. for ref, error in (result.ref_status or {}).items():
  1543. if error is not None:
  1544. errstream.write(
  1545. b"Push of ref %s failed: %s\n" % (ref, error.encode(err_encoding))
  1546. )
  1547. else:
  1548. errstream.write(b"Ref %s updated\n" % ref)
  1549. if remote_name is not None:
  1550. _import_remote_refs(r.refs, remote_name, remote_changed_refs)
  1551. return result
  1552. # Trigger auto GC if needed
  1553. from .gc import maybe_auto_gc
  1554. with open_repo_closing(repo) as r:
  1555. maybe_auto_gc(r)
  1556. def pull(
  1557. repo,
  1558. remote_location=None,
  1559. refspecs=None,
  1560. outstream=default_bytes_out_stream,
  1561. errstream=default_bytes_err_stream,
  1562. fast_forward=True,
  1563. ff_only=False,
  1564. force=False,
  1565. filter_spec=None,
  1566. protocol_version=None,
  1567. **kwargs,
  1568. ) -> None:
  1569. """Pull from remote via dulwich.client.
  1570. Args:
  1571. repo: Path to repository
  1572. remote_location: Location of the remote
  1573. refspecs: refspecs to fetch. Can be a bytestring, a string, or a list of
  1574. bytestring/string.
  1575. outstream: A stream file to write to output
  1576. errstream: A stream file to write to errors
  1577. fast_forward: If True, raise an exception when fast-forward is not possible
  1578. ff_only: If True, only allow fast-forward merges. Raises DivergedBranches
  1579. when branches have diverged rather than performing a merge.
  1580. filter_spec: A git-rev-list-style object filter spec, as an ASCII string.
  1581. Only used if the server supports the Git protocol-v2 'filter'
  1582. feature, and ignored otherwise.
  1583. protocol_version: desired Git protocol version. By default the highest
  1584. mutually supported protocol version will be used
  1585. """
  1586. # Open the repo
  1587. with open_repo_closing(repo) as r:
  1588. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  1589. selected_refs = []
  1590. if refspecs is None:
  1591. refspecs = [b"HEAD"]
  1592. def determine_wants(remote_refs, *args, **kwargs):
  1593. selected_refs.extend(
  1594. parse_reftuples(remote_refs, r.refs, refspecs, force=force)
  1595. )
  1596. return [
  1597. remote_refs[lh]
  1598. for (lh, rh, force_ref) in selected_refs
  1599. if remote_refs[lh] not in r.object_store
  1600. ]
  1601. client, path = get_transport_and_path(
  1602. remote_location, config=r.get_config_stack(), **kwargs
  1603. )
  1604. if filter_spec:
  1605. filter_spec = filter_spec.encode("ascii")
  1606. fetch_result = client.fetch(
  1607. path,
  1608. r,
  1609. progress=errstream.write,
  1610. determine_wants=determine_wants,
  1611. filter_spec=filter_spec,
  1612. protocol_version=protocol_version,
  1613. )
  1614. # Store the old HEAD tree before making changes
  1615. try:
  1616. old_head = r.refs[b"HEAD"]
  1617. old_tree_id = r[old_head].tree
  1618. except KeyError:
  1619. old_tree_id = None
  1620. merged = False
  1621. for lh, rh, force_ref in selected_refs:
  1622. if not force_ref and rh in r.refs:
  1623. try:
  1624. check_diverged(r, r.refs.follow(rh)[1], fetch_result.refs[lh])
  1625. except DivergedBranches as exc:
  1626. if ff_only or fast_forward:
  1627. raise
  1628. else:
  1629. # Perform merge
  1630. merge_result, conflicts = _do_merge(r, fetch_result.refs[lh])
  1631. if conflicts:
  1632. raise Error(
  1633. f"Merge conflicts occurred: {conflicts}"
  1634. ) from exc
  1635. merged = True
  1636. # Skip updating ref since merge already updated HEAD
  1637. continue
  1638. r.refs[rh] = fetch_result.refs[lh]
  1639. # Only update HEAD if we didn't perform a merge
  1640. if selected_refs and not merged:
  1641. r[b"HEAD"] = fetch_result.refs[selected_refs[0][1]]
  1642. # Update working tree to match the new HEAD
  1643. # Skip if merge was performed as merge already updates the working tree
  1644. if not merged and old_tree_id is not None:
  1645. new_tree_id = r[b"HEAD"].tree
  1646. blob_normalizer = r.get_blob_normalizer()
  1647. update_working_tree(
  1648. r, old_tree_id, new_tree_id, blob_normalizer=blob_normalizer
  1649. )
  1650. if remote_name is not None:
  1651. _import_remote_refs(r.refs, remote_name, fetch_result.refs)
  1652. # Trigger auto GC if needed
  1653. from .gc import maybe_auto_gc
  1654. with open_repo_closing(repo) as r:
  1655. maybe_auto_gc(r)
  1656. def status(repo=".", ignored=False, untracked_files="normal"):
  1657. """Returns staged, unstaged, and untracked changes relative to the HEAD.
  1658. Args:
  1659. repo: Path to repository or repository object
  1660. ignored: Whether to include ignored files in untracked
  1661. untracked_files: How to handle untracked files, defaults to "all":
  1662. "no": do not return untracked files
  1663. "normal": return untracked directories, not their contents
  1664. "all": include all files in untracked directories
  1665. Using untracked_files="no" can be faster than "all" when the worktree
  1666. contains many untracked files/directories.
  1667. Using untracked_files="normal" provides a good balance, only showing
  1668. directories that are entirely untracked without listing all their contents.
  1669. Returns: GitStatus tuple,
  1670. staged - dict with lists of staged paths (diff index/HEAD)
  1671. unstaged - list of unstaged paths (diff index/working-tree)
  1672. untracked - list of untracked, un-ignored & non-.git paths
  1673. """
  1674. with open_repo_closing(repo) as r:
  1675. # 1. Get status of staged
  1676. tracked_changes = get_tree_changes(r)
  1677. # 2. Get status of unstaged
  1678. index = r.open_index()
  1679. normalizer = r.get_blob_normalizer()
  1680. filter_callback = normalizer.checkin_normalize
  1681. unstaged_changes = list(get_unstaged_changes(index, r.path, filter_callback))
  1682. untracked_paths = get_untracked_paths(
  1683. r.path,
  1684. r.path,
  1685. index,
  1686. exclude_ignored=not ignored,
  1687. untracked_files=untracked_files,
  1688. )
  1689. if sys.platform == "win32":
  1690. untracked_changes = [
  1691. path.replace(os.path.sep, "/") for path in untracked_paths
  1692. ]
  1693. else:
  1694. untracked_changes = list(untracked_paths)
  1695. return GitStatus(tracked_changes, unstaged_changes, untracked_changes)
  1696. def _walk_working_dir_paths(frompath, basepath, prune_dirnames=None):
  1697. """Get path, is_dir for files in working dir from frompath.
  1698. Args:
  1699. frompath: Path to begin walk
  1700. basepath: Path to compare to
  1701. prune_dirnames: Optional callback to prune dirnames during os.walk
  1702. dirnames will be set to result of prune_dirnames(dirpath, dirnames)
  1703. """
  1704. for dirpath, dirnames, filenames in os.walk(frompath):
  1705. # Skip .git and below.
  1706. if ".git" in dirnames:
  1707. dirnames.remove(".git")
  1708. if dirpath != basepath:
  1709. continue
  1710. if ".git" in filenames:
  1711. filenames.remove(".git")
  1712. if dirpath != basepath:
  1713. continue
  1714. if dirpath != frompath:
  1715. yield dirpath, True
  1716. for filename in filenames:
  1717. filepath = os.path.join(dirpath, filename)
  1718. yield filepath, False
  1719. if prune_dirnames:
  1720. dirnames[:] = prune_dirnames(dirpath, dirnames)
  1721. def get_untracked_paths(
  1722. frompath, basepath, index, exclude_ignored=False, untracked_files="all"
  1723. ):
  1724. """Get untracked paths.
  1725. Args:
  1726. frompath: Path to walk
  1727. basepath: Path to compare to
  1728. index: Index to check against
  1729. exclude_ignored: Whether to exclude ignored paths
  1730. untracked_files: How to handle untracked files:
  1731. - "no": return an empty list
  1732. - "all": return all files in untracked directories
  1733. - "normal": return untracked directories without listing their contents
  1734. Note: ignored directories will never be walked for performance reasons.
  1735. If exclude_ignored is False, only the path to an ignored directory will
  1736. be yielded, no files inside the directory will be returned
  1737. """
  1738. if untracked_files not in ("no", "all", "normal"):
  1739. raise ValueError("untracked_files must be one of (no, all, normal)")
  1740. if untracked_files == "no":
  1741. return
  1742. with open_repo_closing(basepath) as r:
  1743. ignore_manager = IgnoreFilterManager.from_repo(r)
  1744. ignored_dirs = []
  1745. # List to store untracked directories found during traversal
  1746. untracked_dir_list = []
  1747. def prune_dirnames(dirpath, dirnames):
  1748. for i in range(len(dirnames) - 1, -1, -1):
  1749. path = os.path.join(dirpath, dirnames[i])
  1750. ip = os.path.join(os.path.relpath(path, basepath), "")
  1751. # Check if directory is ignored
  1752. if ignore_manager.is_ignored(ip):
  1753. if not exclude_ignored:
  1754. ignored_dirs.append(
  1755. os.path.join(os.path.relpath(path, frompath), "")
  1756. )
  1757. del dirnames[i]
  1758. continue
  1759. # For "normal" mode, check if the directory is entirely untracked
  1760. if untracked_files == "normal":
  1761. # Convert directory path to tree path for index lookup
  1762. dir_tree_path = path_to_tree_path(basepath, path)
  1763. # Check if any file in this directory is tracked
  1764. dir_prefix = dir_tree_path + b"/" if dir_tree_path else b""
  1765. has_tracked_files = any(name.startswith(dir_prefix) for name in index)
  1766. if not has_tracked_files:
  1767. # This directory is entirely untracked
  1768. # Check if it should be excluded due to ignore rules
  1769. is_ignored = ignore_manager.is_ignored(
  1770. os.path.relpath(path, basepath)
  1771. )
  1772. if not exclude_ignored or not is_ignored:
  1773. rel_path = os.path.join(os.path.relpath(path, frompath), "")
  1774. untracked_dir_list.append(rel_path)
  1775. del dirnames[i]
  1776. return dirnames
  1777. # For "all" mode, use the original behavior
  1778. if untracked_files == "all":
  1779. for ap, is_dir in _walk_working_dir_paths(
  1780. frompath, basepath, prune_dirnames=prune_dirnames
  1781. ):
  1782. if not is_dir:
  1783. ip = path_to_tree_path(basepath, ap)
  1784. if ip not in index:
  1785. if not exclude_ignored or not ignore_manager.is_ignored(
  1786. os.path.relpath(ap, basepath)
  1787. ):
  1788. yield os.path.relpath(ap, frompath)
  1789. else: # "normal" mode
  1790. # Walk directories, handling both files and directories
  1791. for ap, is_dir in _walk_working_dir_paths(
  1792. frompath, basepath, prune_dirnames=prune_dirnames
  1793. ):
  1794. # This part won't be reached for pruned directories
  1795. if is_dir:
  1796. # Check if this directory is entirely untracked
  1797. dir_tree_path = path_to_tree_path(basepath, ap)
  1798. dir_prefix = dir_tree_path + b"/" if dir_tree_path else b""
  1799. has_tracked_files = any(name.startswith(dir_prefix) for name in index)
  1800. if not has_tracked_files:
  1801. if not exclude_ignored or not ignore_manager.is_ignored(
  1802. os.path.relpath(ap, basepath)
  1803. ):
  1804. yield os.path.join(os.path.relpath(ap, frompath), "")
  1805. else:
  1806. # Check individual files in directories that contain tracked files
  1807. ip = path_to_tree_path(basepath, ap)
  1808. if ip not in index:
  1809. if not exclude_ignored or not ignore_manager.is_ignored(
  1810. os.path.relpath(ap, basepath)
  1811. ):
  1812. yield os.path.relpath(ap, frompath)
  1813. # Yield any untracked directories found during pruning
  1814. yield from untracked_dir_list
  1815. yield from ignored_dirs
  1816. def get_tree_changes(repo):
  1817. """Return add/delete/modify changes to tree by comparing index to HEAD.
  1818. Args:
  1819. repo: repo path or object
  1820. Returns: dict with lists for each type of change
  1821. """
  1822. with open_repo_closing(repo) as r:
  1823. index = r.open_index()
  1824. # Compares the Index to the HEAD & determines changes
  1825. # Iterate through the changes and report add/delete/modify
  1826. # TODO: call out to dulwich.diff_tree somehow.
  1827. tracked_changes = {
  1828. "add": [],
  1829. "delete": [],
  1830. "modify": [],
  1831. }
  1832. try:
  1833. tree_id = r[b"HEAD"].tree
  1834. except KeyError:
  1835. tree_id = None
  1836. for change in index.changes_from_tree(r.object_store, tree_id):
  1837. if not change[0][0]:
  1838. tracked_changes["add"].append(change[0][1])
  1839. elif not change[0][1]:
  1840. tracked_changes["delete"].append(change[0][0])
  1841. elif change[0][0] == change[0][1]:
  1842. tracked_changes["modify"].append(change[0][0])
  1843. else:
  1844. raise NotImplementedError("git mv ops not yet supported")
  1845. return tracked_changes
  1846. def daemon(path=".", address=None, port=None) -> None:
  1847. """Run a daemon serving Git requests over TCP/IP.
  1848. Args:
  1849. path: Path to the directory to serve.
  1850. address: Optional address to listen on (defaults to ::)
  1851. port: Optional port to listen on (defaults to TCP_GIT_PORT)
  1852. """
  1853. # TODO(jelmer): Support git-daemon-export-ok and --export-all.
  1854. backend = FileSystemBackend(path)
  1855. server = TCPGitServer(backend, address, port)
  1856. server.serve_forever()
  1857. def web_daemon(path=".", address=None, port=None) -> None:
  1858. """Run a daemon serving Git requests over HTTP.
  1859. Args:
  1860. path: Path to the directory to serve
  1861. address: Optional address to listen on (defaults to ::)
  1862. port: Optional port to listen on (defaults to 80)
  1863. """
  1864. from .web import (
  1865. WSGIRequestHandlerLogger,
  1866. WSGIServerLogger,
  1867. make_server,
  1868. make_wsgi_chain,
  1869. )
  1870. backend = FileSystemBackend(path)
  1871. app = make_wsgi_chain(backend)
  1872. server = make_server(
  1873. address,
  1874. port,
  1875. app,
  1876. handler_class=WSGIRequestHandlerLogger,
  1877. server_class=WSGIServerLogger,
  1878. )
  1879. server.serve_forever()
  1880. def upload_pack(path=".", inf=None, outf=None) -> int:
  1881. """Upload a pack file after negotiating its contents using smart protocol.
  1882. Args:
  1883. path: Path to the repository
  1884. inf: Input stream to communicate with client
  1885. outf: Output stream to communicate with client
  1886. """
  1887. if outf is None:
  1888. outf = getattr(sys.stdout, "buffer", sys.stdout)
  1889. if inf is None:
  1890. inf = getattr(sys.stdin, "buffer", sys.stdin)
  1891. path = os.path.expanduser(path)
  1892. backend = FileSystemBackend(path)
  1893. def send_fn(data) -> None:
  1894. outf.write(data)
  1895. outf.flush()
  1896. proto = Protocol(inf.read, send_fn)
  1897. handler = UploadPackHandler(backend, [path], proto)
  1898. # FIXME: Catch exceptions and write a single-line summary to outf.
  1899. handler.handle()
  1900. return 0
  1901. def receive_pack(path=".", inf=None, outf=None) -> int:
  1902. """Receive a pack file after negotiating its contents using smart protocol.
  1903. Args:
  1904. path: Path to the repository
  1905. inf: Input stream to communicate with client
  1906. outf: Output stream to communicate with client
  1907. """
  1908. if outf is None:
  1909. outf = getattr(sys.stdout, "buffer", sys.stdout)
  1910. if inf is None:
  1911. inf = getattr(sys.stdin, "buffer", sys.stdin)
  1912. path = os.path.expanduser(path)
  1913. backend = FileSystemBackend(path)
  1914. def send_fn(data) -> None:
  1915. outf.write(data)
  1916. outf.flush()
  1917. proto = Protocol(inf.read, send_fn)
  1918. handler = ReceivePackHandler(backend, [path], proto)
  1919. # FIXME: Catch exceptions and write a single-line summary to outf.
  1920. handler.handle()
  1921. return 0
  1922. def _make_branch_ref(name: Union[str, bytes]) -> Ref:
  1923. if isinstance(name, str):
  1924. name = name.encode(DEFAULT_ENCODING)
  1925. return LOCAL_BRANCH_PREFIX + name
  1926. def _make_tag_ref(name: Union[str, bytes]) -> Ref:
  1927. if isinstance(name, str):
  1928. name = name.encode(DEFAULT_ENCODING)
  1929. return LOCAL_TAG_PREFIX + name
  1930. def branch_delete(repo, name) -> None:
  1931. """Delete a branch.
  1932. Args:
  1933. repo: Path to the repository
  1934. name: Name of the branch
  1935. """
  1936. with open_repo_closing(repo) as r:
  1937. if isinstance(name, list):
  1938. names = name
  1939. else:
  1940. names = [name]
  1941. for name in names:
  1942. del r.refs[_make_branch_ref(name)]
  1943. def branch_create(repo, name, objectish=None, force=False) -> None:
  1944. """Create a branch.
  1945. Args:
  1946. repo: Path to the repository
  1947. name: Name of the new branch
  1948. objectish: Target object to point new branch at (defaults to HEAD)
  1949. force: Force creation of branch, even if it already exists
  1950. """
  1951. with open_repo_closing(repo) as r:
  1952. if objectish is None:
  1953. objectish = "HEAD"
  1954. object = parse_object(r, objectish)
  1955. refname = _make_branch_ref(name)
  1956. ref_message = b"branch: Created from " + objectish.encode(DEFAULT_ENCODING)
  1957. if force:
  1958. r.refs.set_if_equals(refname, None, object.id, message=ref_message)
  1959. else:
  1960. if not r.refs.add_if_new(refname, object.id, message=ref_message):
  1961. raise Error(f"Branch with name {name} already exists.")
  1962. def branch_list(repo):
  1963. """List all branches.
  1964. Args:
  1965. repo: Path to the repository
  1966. """
  1967. with open_repo_closing(repo) as r:
  1968. return r.refs.keys(base=LOCAL_BRANCH_PREFIX)
  1969. def active_branch(repo):
  1970. """Return the active branch in the repository, if any.
  1971. Args:
  1972. repo: Repository to open
  1973. Returns:
  1974. branch name
  1975. Raises:
  1976. KeyError: if the repository does not have a working tree
  1977. IndexError: if HEAD is floating
  1978. """
  1979. with open_repo_closing(repo) as r:
  1980. active_ref = r.refs.follow(b"HEAD")[0][1]
  1981. if not active_ref.startswith(LOCAL_BRANCH_PREFIX):
  1982. raise ValueError(active_ref)
  1983. return active_ref[len(LOCAL_BRANCH_PREFIX) :]
  1984. def get_branch_remote(repo):
  1985. """Return the active branch's remote name, if any.
  1986. Args:
  1987. repo: Repository to open
  1988. Returns:
  1989. remote name
  1990. Raises:
  1991. KeyError: if the repository does not have a working tree
  1992. """
  1993. with open_repo_closing(repo) as r:
  1994. branch_name = active_branch(r.path)
  1995. config = r.get_config()
  1996. try:
  1997. remote_name = config.get((b"branch", branch_name), b"remote")
  1998. except KeyError:
  1999. remote_name = b"origin"
  2000. return remote_name
  2001. def get_branch_merge(repo, branch_name=None):
  2002. """Return the branch's merge reference (upstream branch), if any.
  2003. Args:
  2004. repo: Repository to open
  2005. branch_name: Name of the branch (defaults to active branch)
  2006. Returns:
  2007. merge reference name (e.g. b"refs/heads/main")
  2008. Raises:
  2009. KeyError: if the branch does not have a merge configuration
  2010. """
  2011. with open_repo_closing(repo) as r:
  2012. if branch_name is None:
  2013. branch_name = active_branch(r.path)
  2014. config = r.get_config()
  2015. return config.get((b"branch", branch_name), b"merge")
  2016. def set_branch_tracking(repo, branch_name, remote_name, remote_ref):
  2017. """Set up branch tracking configuration.
  2018. Args:
  2019. repo: Repository to open
  2020. branch_name: Name of the local branch
  2021. remote_name: Name of the remote (e.g. b"origin")
  2022. remote_ref: Remote reference to track (e.g. b"refs/heads/main")
  2023. """
  2024. with open_repo_closing(repo) as r:
  2025. config = r.get_config()
  2026. config.set((b"branch", branch_name), b"remote", remote_name)
  2027. config.set((b"branch", branch_name), b"merge", remote_ref)
  2028. config.write_to_path()
  2029. def fetch(
  2030. repo,
  2031. remote_location=None,
  2032. outstream=sys.stdout,
  2033. errstream=default_bytes_err_stream,
  2034. message=None,
  2035. depth=None,
  2036. prune=False,
  2037. prune_tags=False,
  2038. force=False,
  2039. **kwargs,
  2040. ):
  2041. """Fetch objects from a remote server.
  2042. Args:
  2043. repo: Path to the repository
  2044. remote_location: String identifying a remote server
  2045. outstream: Output stream (defaults to stdout)
  2046. errstream: Error stream (defaults to stderr)
  2047. message: Reflog message (defaults to b"fetch: from <remote_name>")
  2048. depth: Depth to fetch at
  2049. prune: Prune remote removed refs
  2050. prune_tags: Prune reomte removed tags
  2051. Returns:
  2052. Dictionary with refs on the remote
  2053. """
  2054. with open_repo_closing(repo) as r:
  2055. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  2056. if message is None:
  2057. message = b"fetch: from " + remote_location.encode(DEFAULT_ENCODING)
  2058. client, path = get_transport_and_path(
  2059. remote_location, config=r.get_config_stack(), **kwargs
  2060. )
  2061. fetch_result = client.fetch(path, r, progress=errstream.write, depth=depth)
  2062. if remote_name is not None:
  2063. _import_remote_refs(
  2064. r.refs,
  2065. remote_name,
  2066. fetch_result.refs,
  2067. message,
  2068. prune=prune,
  2069. prune_tags=prune_tags,
  2070. )
  2071. # Trigger auto GC if needed
  2072. from .gc import maybe_auto_gc
  2073. with open_repo_closing(repo) as r:
  2074. maybe_auto_gc(r)
  2075. return fetch_result
  2076. def for_each_ref(
  2077. repo: Union[Repo, str] = ".",
  2078. pattern: Optional[Union[str, bytes]] = None,
  2079. ) -> list[tuple[bytes, bytes, bytes]]:
  2080. """Iterate over all refs that match the (optional) pattern.
  2081. Args:
  2082. repo: Path to the repository
  2083. pattern: Optional glob (7) patterns to filter the refs with
  2084. Returns: List of bytes tuples with: (sha, object_type, ref_name)
  2085. """
  2086. if isinstance(pattern, str):
  2087. pattern = os.fsencode(pattern)
  2088. with open_repo_closing(repo) as r:
  2089. refs = r.get_refs()
  2090. if pattern:
  2091. matching_refs: dict[bytes, bytes] = {}
  2092. pattern_parts = pattern.split(b"/")
  2093. for ref, sha in refs.items():
  2094. matches = False
  2095. # git for-each-ref uses glob (7) style patterns, but fnmatch
  2096. # is greedy and also matches slashes, unlike glob.glob.
  2097. # We have to check parts of the pattern individually.
  2098. # See https://github.com/python/cpython/issues/72904
  2099. ref_parts = ref.split(b"/")
  2100. if len(ref_parts) > len(pattern_parts):
  2101. continue
  2102. for pat, ref_part in zip(pattern_parts, ref_parts):
  2103. matches = fnmatch.fnmatchcase(ref_part, pat)
  2104. if not matches:
  2105. break
  2106. if matches:
  2107. matching_refs[ref] = sha
  2108. refs = matching_refs
  2109. ret: list[tuple[bytes, bytes, bytes]] = [
  2110. (sha, r.get_object(sha).type_name, ref)
  2111. for ref, sha in sorted(
  2112. refs.items(),
  2113. key=lambda ref_sha: ref_sha[0],
  2114. )
  2115. if ref != b"HEAD"
  2116. ]
  2117. return ret
  2118. def ls_remote(remote, config: Optional[Config] = None, **kwargs):
  2119. """List the refs in a remote.
  2120. Args:
  2121. remote: Remote repository location
  2122. config: Configuration to use
  2123. Returns:
  2124. LsRemoteResult object with refs and symrefs
  2125. """
  2126. if config is None:
  2127. config = StackedConfig.default()
  2128. client, host_path = get_transport_and_path(remote, config=config, **kwargs)
  2129. return client.get_refs(host_path)
  2130. def repack(repo) -> None:
  2131. """Repack loose files in a repository.
  2132. Currently this only packs loose objects.
  2133. Args:
  2134. repo: Path to the repository
  2135. """
  2136. with open_repo_closing(repo) as r:
  2137. r.object_store.pack_loose_objects()
  2138. def pack_objects(
  2139. repo,
  2140. object_ids,
  2141. packf,
  2142. idxf,
  2143. delta_window_size=None,
  2144. deltify=None,
  2145. reuse_deltas=True,
  2146. pack_index_version=None,
  2147. ) -> None:
  2148. """Pack objects into a file.
  2149. Args:
  2150. repo: Path to the repository
  2151. object_ids: List of object ids to write
  2152. packf: File-like object to write to
  2153. idxf: File-like object to write to (can be None)
  2154. delta_window_size: Sliding window size for searching for deltas;
  2155. Set to None for default window size.
  2156. deltify: Whether to deltify objects
  2157. reuse_deltas: Allow reuse of existing deltas while deltifying
  2158. pack_index_version: Pack index version to use (1, 2, or 3). If None, uses default version.
  2159. """
  2160. with open_repo_closing(repo) as r:
  2161. entries, data_sum = write_pack_from_container(
  2162. packf.write,
  2163. r.object_store,
  2164. [(oid, None) for oid in object_ids],
  2165. deltify=deltify,
  2166. delta_window_size=delta_window_size,
  2167. reuse_deltas=reuse_deltas,
  2168. )
  2169. if idxf is not None:
  2170. entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
  2171. write_pack_index(idxf, entries, data_sum, version=pack_index_version)
  2172. def ls_tree(
  2173. repo,
  2174. treeish=b"HEAD",
  2175. outstream=sys.stdout,
  2176. recursive=False,
  2177. name_only=False,
  2178. ) -> None:
  2179. """List contents of a tree.
  2180. Args:
  2181. repo: Path to the repository
  2182. treeish: Tree id to list
  2183. outstream: Output stream (defaults to stdout)
  2184. recursive: Whether to recursively list files
  2185. name_only: Only print item name
  2186. """
  2187. def list_tree(store, treeid, base) -> None:
  2188. for name, mode, sha in store[treeid].iteritems():
  2189. if base:
  2190. name = posixpath.join(base, name)
  2191. if name_only:
  2192. outstream.write(name + b"\n")
  2193. else:
  2194. outstream.write(pretty_format_tree_entry(name, mode, sha))
  2195. if stat.S_ISDIR(mode) and recursive:
  2196. list_tree(store, sha, name)
  2197. with open_repo_closing(repo) as r:
  2198. tree = parse_tree(r, treeish)
  2199. list_tree(r.object_store, tree.id, "")
  2200. def remote_add(repo, name: Union[bytes, str], url: Union[bytes, str]) -> None:
  2201. """Add a remote.
  2202. Args:
  2203. repo: Path to the repository
  2204. name: Remote name
  2205. url: Remote URL
  2206. """
  2207. if not isinstance(name, bytes):
  2208. name = name.encode(DEFAULT_ENCODING)
  2209. if not isinstance(url, bytes):
  2210. url = url.encode(DEFAULT_ENCODING)
  2211. with open_repo_closing(repo) as r:
  2212. c = r.get_config()
  2213. section = (b"remote", name)
  2214. if c.has_section(section):
  2215. raise RemoteExists(section)
  2216. c.set(section, b"url", url)
  2217. c.write_to_path()
  2218. def remote_remove(repo: Repo, name: Union[bytes, str]) -> None:
  2219. """Remove a remote.
  2220. Args:
  2221. repo: Path to the repository
  2222. name: Remote name
  2223. """
  2224. if not isinstance(name, bytes):
  2225. name = name.encode(DEFAULT_ENCODING)
  2226. with open_repo_closing(repo) as r:
  2227. c = r.get_config()
  2228. section = (b"remote", name)
  2229. del c[section]
  2230. c.write_to_path()
  2231. def _quote_path(path: str) -> str:
  2232. """Quote a path using C-style quoting similar to git's core.quotePath.
  2233. Args:
  2234. path: Path to quote
  2235. Returns:
  2236. Quoted path string
  2237. """
  2238. # Check if path needs quoting (non-ASCII or special characters)
  2239. needs_quoting = False
  2240. for char in path:
  2241. if ord(char) > 127 or char in '"\\':
  2242. needs_quoting = True
  2243. break
  2244. if not needs_quoting:
  2245. return path
  2246. # Apply C-style quoting
  2247. quoted = '"'
  2248. for char in path:
  2249. if ord(char) > 127:
  2250. # Non-ASCII character, encode as octal escape
  2251. utf8_bytes = char.encode("utf-8")
  2252. for byte in utf8_bytes:
  2253. quoted += f"\\{byte:03o}"
  2254. elif char == '"':
  2255. quoted += '\\"'
  2256. elif char == "\\":
  2257. quoted += "\\\\"
  2258. else:
  2259. quoted += char
  2260. quoted += '"'
  2261. return quoted
  2262. def check_ignore(repo, paths, no_index=False, quote_path=True):
  2263. r"""Debug gitignore files.
  2264. Args:
  2265. repo: Path to the repository
  2266. paths: List of paths to check for
  2267. no_index: Don't check index
  2268. quote_path: If True, quote non-ASCII characters in returned paths using
  2269. C-style octal escapes (e.g. "тест.txt" becomes "\\321\\202\\320\\265\\321\\201\\321\\202.txt").
  2270. If False, return raw unicode paths.
  2271. Returns: List of ignored files
  2272. """
  2273. with open_repo_closing(repo) as r:
  2274. index = r.open_index()
  2275. ignore_manager = IgnoreFilterManager.from_repo(r)
  2276. for original_path in paths:
  2277. if not no_index and path_to_tree_path(r.path, original_path) in index:
  2278. continue
  2279. # Preserve whether the original path had a trailing slash
  2280. had_trailing_slash = original_path.endswith(("/", os.path.sep))
  2281. if os.path.isabs(original_path):
  2282. path = os.path.relpath(original_path, r.path)
  2283. # Normalize Windows paths to use forward slashes
  2284. if os.path.sep != "/":
  2285. path = path.replace(os.path.sep, "/")
  2286. else:
  2287. path = original_path
  2288. # Restore trailing slash if it was in the original
  2289. if had_trailing_slash and not path.endswith("/"):
  2290. path = path + "/"
  2291. # For directories, check with trailing slash to get correct ignore behavior
  2292. test_path = path
  2293. path_without_slash = path.rstrip("/")
  2294. is_directory = os.path.isdir(os.path.join(r.path, path_without_slash))
  2295. # If this is a directory path, ensure we test it correctly
  2296. if is_directory and not path.endswith("/"):
  2297. test_path = path + "/"
  2298. if ignore_manager.is_ignored(test_path):
  2299. # Return relative path (like git does) when absolute path was provided
  2300. if os.path.isabs(original_path):
  2301. output_path = path
  2302. else:
  2303. output_path = original_path
  2304. yield _quote_path(output_path) if quote_path else output_path
  2305. def update_head(repo, target, detached=False, new_branch=None) -> None:
  2306. """Update HEAD to point at a new branch/commit.
  2307. Note that this does not actually update the working tree.
  2308. Args:
  2309. repo: Path to the repository
  2310. detached: Create a detached head
  2311. target: Branch or committish to switch to
  2312. new_branch: New branch to create
  2313. """
  2314. with open_repo_closing(repo) as r:
  2315. if new_branch is not None:
  2316. to_set = _make_branch_ref(new_branch)
  2317. else:
  2318. to_set = b"HEAD"
  2319. if detached:
  2320. # TODO(jelmer): Provide some way so that the actual ref gets
  2321. # updated rather than what it points to, so the delete isn't
  2322. # necessary.
  2323. del r.refs[to_set]
  2324. r.refs[to_set] = parse_commit(r, target).id
  2325. else:
  2326. r.refs.set_symbolic_ref(to_set, parse_ref(r, target))
  2327. if new_branch is not None:
  2328. r.refs.set_symbolic_ref(b"HEAD", to_set)
  2329. def checkout(
  2330. repo,
  2331. target: Union[bytes, str],
  2332. force: bool = False,
  2333. new_branch: Optional[Union[bytes, str]] = None,
  2334. ) -> None:
  2335. """Switch to a branch or commit, updating both HEAD and the working tree.
  2336. This is similar to 'git checkout', allowing you to switch to a branch,
  2337. tag, or specific commit. Unlike update_head, this function also updates
  2338. the working tree to match the target.
  2339. Args:
  2340. repo: Path to repository or repository object
  2341. target: Branch name, tag, or commit SHA to checkout
  2342. force: Force checkout even if there are local changes
  2343. new_branch: Create a new branch at target (like git checkout -b)
  2344. Raises:
  2345. CheckoutError: If checkout cannot be performed due to conflicts
  2346. KeyError: If the target reference cannot be found
  2347. """
  2348. with open_repo_closing(repo) as r:
  2349. if isinstance(target, str):
  2350. target = target.encode(DEFAULT_ENCODING)
  2351. if isinstance(new_branch, str):
  2352. new_branch = new_branch.encode(DEFAULT_ENCODING)
  2353. # Parse the target to get the commit
  2354. target_commit = parse_commit(r, target)
  2355. target_tree_id = target_commit.tree
  2356. # Get current HEAD tree for comparison
  2357. try:
  2358. current_head = r.refs[b"HEAD"]
  2359. current_tree_id = r[current_head].tree
  2360. except KeyError:
  2361. # No HEAD yet (empty repo)
  2362. current_tree_id = None
  2363. # Check for uncommitted changes if not forcing
  2364. if not force and current_tree_id is not None:
  2365. status_report = status(r)
  2366. changes = []
  2367. # staged is a dict with 'add', 'delete', 'modify' keys
  2368. if isinstance(status_report.staged, dict):
  2369. changes.extend(status_report.staged.get("add", []))
  2370. changes.extend(status_report.staged.get("delete", []))
  2371. changes.extend(status_report.staged.get("modify", []))
  2372. # unstaged is a list
  2373. changes.extend(status_report.unstaged)
  2374. if changes:
  2375. # Check if any changes would conflict with checkout
  2376. target_tree = r[target_tree_id]
  2377. for change in changes:
  2378. if isinstance(change, str):
  2379. change = change.encode(DEFAULT_ENCODING)
  2380. try:
  2381. target_tree.lookup_path(r.object_store.__getitem__, change)
  2382. # File exists in target tree - would overwrite local changes
  2383. raise CheckoutError(
  2384. f"Your local changes to '{change.decode()}' would be "
  2385. "overwritten by checkout. Please commit or stash before switching."
  2386. )
  2387. except KeyError:
  2388. # File doesn't exist in target tree - change can be preserved
  2389. pass
  2390. # Get configuration for working directory update
  2391. config = r.get_config()
  2392. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  2393. # Import validation functions
  2394. from .index import validate_path_element_default, validate_path_element_ntfs
  2395. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  2396. validate_path_element = validate_path_element_ntfs
  2397. else:
  2398. validate_path_element = validate_path_element_default
  2399. if config.get_boolean(b"core", b"symlinks", True):
  2400. # Import symlink function
  2401. from .index import symlink
  2402. symlink_fn = symlink
  2403. else:
  2404. def symlink_fn(source, target) -> None: # type: ignore
  2405. mode = "w" + ("b" if isinstance(source, bytes) else "")
  2406. with open(target, mode) as f:
  2407. f.write(source)
  2408. # Update working tree
  2409. update_working_tree(
  2410. r,
  2411. current_tree_id,
  2412. target_tree_id,
  2413. honor_filemode=honor_filemode,
  2414. validate_path_element=validate_path_element,
  2415. symlink_fn=symlink_fn,
  2416. force_remove_untracked=force,
  2417. )
  2418. # Update HEAD
  2419. if new_branch:
  2420. # Create new branch and switch to it
  2421. branch_create(r, new_branch, objectish=target_commit.id.decode("ascii"))
  2422. update_head(r, new_branch)
  2423. # Set up tracking if creating from a remote branch
  2424. from .refs import LOCAL_REMOTE_PREFIX, parse_remote_ref
  2425. if target.startswith(LOCAL_REMOTE_PREFIX):
  2426. try:
  2427. remote_name, branch_name = parse_remote_ref(target)
  2428. # Set tracking to refs/heads/<branch> on the remote
  2429. set_branch_tracking(
  2430. r, new_branch, remote_name, b"refs/heads/" + branch_name
  2431. )
  2432. except ValueError:
  2433. # Invalid remote ref format, skip tracking setup
  2434. pass
  2435. else:
  2436. # Check if target is a branch name (with or without refs/heads/ prefix)
  2437. branch_ref = None
  2438. if target in r.refs.keys():
  2439. if target.startswith(LOCAL_BRANCH_PREFIX):
  2440. branch_ref = target
  2441. else:
  2442. # Try adding refs/heads/ prefix
  2443. potential_branch = _make_branch_ref(target)
  2444. if potential_branch in r.refs.keys():
  2445. branch_ref = potential_branch
  2446. if branch_ref:
  2447. # It's a branch - update HEAD symbolically
  2448. update_head(r, branch_ref)
  2449. else:
  2450. # It's a tag, other ref, or commit SHA - detached HEAD
  2451. update_head(r, target_commit.id.decode("ascii"), detached=True)
  2452. def reset_file(repo, file_path: str, target: bytes = b"HEAD", symlink_fn=None) -> None:
  2453. """Reset the file to specific commit or branch.
  2454. Args:
  2455. repo: dulwich Repo object
  2456. file_path: file to reset, relative to the repository path
  2457. target: branch or commit or b'HEAD' to reset
  2458. """
  2459. tree = parse_tree(repo, treeish=target)
  2460. tree_path = _fs_to_tree_path(file_path)
  2461. file_entry = tree.lookup_path(repo.object_store.__getitem__, tree_path)
  2462. full_path = os.path.join(os.fsencode(repo.path), tree_path)
  2463. blob = repo.object_store[file_entry[1]]
  2464. mode = file_entry[0]
  2465. build_file_from_blob(blob, mode, full_path, symlink_fn=symlink_fn)
  2466. @replace_me(since="0.22.9", remove_in="0.24.0")
  2467. def checkout_branch(repo, target: Union[bytes, str], force: bool = False) -> None:
  2468. """Switch branches or restore working tree files.
  2469. This is now a wrapper around the general checkout() function.
  2470. Preserved for backward compatibility.
  2471. Args:
  2472. repo: dulwich Repo object
  2473. target: branch name or commit sha to checkout
  2474. force: true or not to force checkout
  2475. """
  2476. # Simply delegate to the new checkout function
  2477. return checkout(repo, target, force=force)
  2478. def sparse_checkout(
  2479. repo, patterns=None, force: bool = False, cone: Union[bool, None] = None
  2480. ):
  2481. """Perform a sparse checkout in the repository (either 'full' or 'cone mode').
  2482. Perform sparse checkout in either 'cone' (directory-based) mode or
  2483. 'full pattern' (.gitignore) mode, depending on the ``cone`` parameter.
  2484. If ``cone`` is ``None``, the mode is inferred from the repository's
  2485. ``core.sparseCheckoutCone`` config setting.
  2486. Steps:
  2487. 1) If ``patterns`` is provided, write them to ``.git/info/sparse-checkout``.
  2488. 2) Determine which paths in the index are included vs. excluded.
  2489. - If ``cone=True``, use "cone-compatible" directory-based logic.
  2490. - If ``cone=False``, use standard .gitignore-style matching.
  2491. 3) Update the index's skip-worktree bits and add/remove files in
  2492. the working tree accordingly.
  2493. 4) If ``force=False``, refuse to remove files that have local modifications.
  2494. Args:
  2495. repo: Path to the repository or a Repo object.
  2496. patterns: Optional list of sparse-checkout patterns to write.
  2497. force: Whether to force removal of locally modified files (default False).
  2498. cone: Boolean indicating cone mode (True/False). If None, read from config.
  2499. Returns:
  2500. None
  2501. """
  2502. with open_repo_closing(repo) as repo_obj:
  2503. # --- 0) Possibly infer 'cone' from config ---
  2504. if cone is None:
  2505. cone = repo_obj.infer_cone_mode()
  2506. # --- 1) Read or write patterns ---
  2507. if patterns is None:
  2508. lines = repo_obj.get_sparse_checkout_patterns()
  2509. if lines is None:
  2510. raise Error("No sparse checkout patterns found.")
  2511. else:
  2512. lines = patterns
  2513. repo_obj.set_sparse_checkout_patterns(patterns)
  2514. # --- 2) Determine the set of included paths ---
  2515. included_paths = determine_included_paths(repo_obj, lines, cone)
  2516. # --- 3) Apply those results to the index & working tree ---
  2517. try:
  2518. apply_included_paths(repo_obj, included_paths, force=force)
  2519. except SparseCheckoutConflictError as exc:
  2520. raise CheckoutError(*exc.args) from exc
  2521. def cone_mode_init(repo):
  2522. """Initialize a repository to use sparse checkout in 'cone' mode.
  2523. Sets ``core.sparseCheckout`` and ``core.sparseCheckoutCone`` in the config.
  2524. Writes an initial ``.git/info/sparse-checkout`` file that includes only
  2525. top-level files (and excludes all subdirectories), e.g. ``["/*", "!/*/"]``.
  2526. Then performs a sparse checkout to update the working tree accordingly.
  2527. If no directories are specified, then only top-level files are included:
  2528. https://git-scm.com/docs/git-sparse-checkout#_internalscone_mode_handling
  2529. Args:
  2530. repo: Path to the repository or a Repo object.
  2531. Returns:
  2532. None
  2533. """
  2534. with open_repo_closing(repo) as repo_obj:
  2535. repo_obj.configure_for_cone_mode()
  2536. patterns = ["/*", "!/*/"] # root-level files only
  2537. sparse_checkout(repo_obj, patterns, force=True, cone=True)
  2538. def cone_mode_set(repo, dirs, force=False):
  2539. """Overwrite the existing 'cone-mode' sparse patterns with a new set of directories.
  2540. Ensures ``core.sparseCheckout`` and ``core.sparseCheckoutCone`` are enabled.
  2541. Writes new patterns so that only the specified directories (and top-level files)
  2542. remain in the working tree, and applies the sparse checkout update.
  2543. Args:
  2544. repo: Path to the repository or a Repo object.
  2545. dirs: List of directory names to include.
  2546. force: Whether to forcibly discard local modifications (default False).
  2547. Returns:
  2548. None
  2549. """
  2550. with open_repo_closing(repo) as repo_obj:
  2551. repo_obj.configure_for_cone_mode()
  2552. repo_obj.set_cone_mode_patterns(dirs=dirs)
  2553. new_patterns = repo_obj.get_sparse_checkout_patterns()
  2554. # Finally, apply the patterns and update the working tree
  2555. sparse_checkout(repo_obj, new_patterns, force=force, cone=True)
  2556. def cone_mode_add(repo, dirs, force=False):
  2557. """Add new directories to the existing 'cone-mode' sparse-checkout patterns.
  2558. Reads the current patterns from ``.git/info/sparse-checkout``, adds pattern
  2559. lines to include the specified directories, and then performs a sparse
  2560. checkout to update the working tree accordingly.
  2561. Args:
  2562. repo: Path to the repository or a Repo object.
  2563. dirs: List of directory names to add to the sparse-checkout.
  2564. force: Whether to forcibly discard local modifications (default False).
  2565. Returns:
  2566. None
  2567. """
  2568. with open_repo_closing(repo) as repo_obj:
  2569. repo_obj.configure_for_cone_mode()
  2570. # Do not pass base patterns as dirs
  2571. base_patterns = ["/*", "!/*/"]
  2572. existing_dirs = [
  2573. pat.strip("/")
  2574. for pat in repo_obj.get_sparse_checkout_patterns()
  2575. if pat not in base_patterns
  2576. ]
  2577. added_dirs = existing_dirs + (dirs or [])
  2578. repo_obj.set_cone_mode_patterns(dirs=added_dirs)
  2579. new_patterns = repo_obj.get_sparse_checkout_patterns()
  2580. sparse_checkout(repo_obj, patterns=new_patterns, force=force, cone=True)
  2581. def check_mailmap(repo, contact):
  2582. """Check canonical name and email of contact.
  2583. Args:
  2584. repo: Path to the repository
  2585. contact: Contact name and/or email
  2586. Returns: Canonical contact data
  2587. """
  2588. with open_repo_closing(repo) as r:
  2589. from .mailmap import Mailmap
  2590. try:
  2591. mailmap = Mailmap.from_path(os.path.join(r.path, ".mailmap"))
  2592. except FileNotFoundError:
  2593. mailmap = Mailmap()
  2594. return mailmap.lookup(contact)
  2595. def fsck(repo):
  2596. """Check a repository.
  2597. Args:
  2598. repo: A path to the repository
  2599. Returns: Iterator over errors/warnings
  2600. """
  2601. with open_repo_closing(repo) as r:
  2602. # TODO(jelmer): check pack files
  2603. # TODO(jelmer): check graph
  2604. # TODO(jelmer): check refs
  2605. for sha in r.object_store:
  2606. o = r.object_store[sha]
  2607. try:
  2608. o.check()
  2609. except Exception as e:
  2610. yield (sha, e)
  2611. def stash_list(repo):
  2612. """List all stashes in a repository."""
  2613. with open_repo_closing(repo) as r:
  2614. from .stash import Stash
  2615. stash = Stash.from_repo(r)
  2616. return enumerate(list(stash.stashes()))
  2617. def stash_push(repo) -> None:
  2618. """Push a new stash onto the stack."""
  2619. with open_repo_closing(repo) as r:
  2620. from .stash import Stash
  2621. stash = Stash.from_repo(r)
  2622. stash.push()
  2623. def stash_pop(repo) -> None:
  2624. """Pop a stash from the stack."""
  2625. with open_repo_closing(repo) as r:
  2626. from .stash import Stash
  2627. stash = Stash.from_repo(r)
  2628. stash.pop(0)
  2629. def stash_drop(repo, index) -> None:
  2630. """Drop a stash from the stack."""
  2631. with open_repo_closing(repo) as r:
  2632. from .stash import Stash
  2633. stash = Stash.from_repo(r)
  2634. stash.drop(index)
  2635. def ls_files(repo):
  2636. """List all files in an index."""
  2637. with open_repo_closing(repo) as r:
  2638. return sorted(r.open_index())
  2639. def find_unique_abbrev(object_store, object_id):
  2640. """For now, just return 7 characters."""
  2641. # TODO(jelmer): Add some logic here to return a number of characters that
  2642. # scales relative with the size of the repository
  2643. return object_id.decode("ascii")[:7]
  2644. def describe(repo, abbrev=None):
  2645. """Describe the repository version.
  2646. Args:
  2647. repo: git repository
  2648. abbrev: number of characters of commit to take, default is 7
  2649. Returns: a string description of the current git revision
  2650. Examples: "gabcdefh", "v0.1" or "v0.1-5-gabcdefh".
  2651. """
  2652. abbrev_slice = slice(0, abbrev if abbrev is not None else 7)
  2653. # Get the repository
  2654. with open_repo_closing(repo) as r:
  2655. # Get a list of all tags
  2656. refs = r.get_refs()
  2657. tags = {}
  2658. for key, value in refs.items():
  2659. key = key.decode()
  2660. obj = r.get_object(value)
  2661. if "tags" not in key:
  2662. continue
  2663. _, tag = key.rsplit("/", 1)
  2664. try:
  2665. # Annotated tag case
  2666. commit = obj.object
  2667. commit = r.get_object(commit[1])
  2668. except AttributeError:
  2669. # Lightweight tag case - obj is already the commit
  2670. commit = obj
  2671. tags[tag] = [
  2672. datetime.datetime(*time.gmtime(commit.commit_time)[:6]),
  2673. commit.id.decode("ascii"),
  2674. ]
  2675. sorted_tags = sorted(tags.items(), key=lambda tag: tag[1][0], reverse=True)
  2676. # Get the latest commit
  2677. latest_commit = r[r.head()]
  2678. # If there are no tags, return the latest commit
  2679. if len(sorted_tags) == 0:
  2680. if abbrev is not None:
  2681. return "g{}".format(latest_commit.id.decode("ascii")[abbrev_slice])
  2682. return f"g{find_unique_abbrev(r.object_store, latest_commit.id)}"
  2683. # We're now 0 commits from the top
  2684. commit_count = 0
  2685. # Walk through all commits
  2686. walker = r.get_walker()
  2687. for entry in walker:
  2688. # Check if tag
  2689. commit_id = entry.commit.id.decode("ascii")
  2690. for tag in sorted_tags:
  2691. tag_name = tag[0]
  2692. tag_commit = tag[1][1]
  2693. if commit_id == tag_commit:
  2694. if commit_count == 0:
  2695. return tag_name
  2696. else:
  2697. return "{}-{}-g{}".format(
  2698. tag_name,
  2699. commit_count,
  2700. latest_commit.id.decode("ascii")[abbrev_slice],
  2701. )
  2702. commit_count += 1
  2703. # Return plain commit if no parent tag can be found
  2704. return "g{}".format(latest_commit.id.decode("ascii")[abbrev_slice])
  2705. def get_object_by_path(repo, path, committish=None):
  2706. """Get an object by path.
  2707. Args:
  2708. repo: A path to the repository
  2709. path: Path to look up
  2710. committish: Commit to look up path in
  2711. Returns: A `ShaFile` object
  2712. """
  2713. if committish is None:
  2714. committish = "HEAD"
  2715. # Get the repository
  2716. with open_repo_closing(repo) as r:
  2717. commit = parse_commit(r, committish)
  2718. base_tree = commit.tree
  2719. if not isinstance(path, bytes):
  2720. path = commit_encode(commit, path)
  2721. (mode, sha) = tree_lookup_path(r.object_store.__getitem__, base_tree, path)
  2722. return r[sha]
  2723. def write_tree(repo):
  2724. """Write a tree object from the index.
  2725. Args:
  2726. repo: Repository for which to write tree
  2727. Returns: tree id for the tree that was written
  2728. """
  2729. with open_repo_closing(repo) as r:
  2730. return r.open_index().commit(r.object_store)
  2731. def _do_merge(
  2732. r,
  2733. merge_commit_id,
  2734. no_commit=False,
  2735. no_ff=False,
  2736. message=None,
  2737. author=None,
  2738. committer=None,
  2739. ):
  2740. """Internal merge implementation that operates on an open repository.
  2741. Args:
  2742. r: Open repository object
  2743. merge_commit_id: SHA of commit to merge
  2744. no_commit: If True, do not create a merge commit
  2745. no_ff: If True, force creation of a merge commit
  2746. message: Optional merge commit message
  2747. author: Optional author for merge commit
  2748. committer: Optional committer for merge commit
  2749. Returns:
  2750. Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None
  2751. if no_commit=True or there were conflicts
  2752. """
  2753. from .graph import find_merge_base
  2754. from .merge import three_way_merge
  2755. # Get HEAD commit
  2756. try:
  2757. head_commit_id = r.refs[b"HEAD"]
  2758. except KeyError:
  2759. raise Error("No HEAD reference found")
  2760. head_commit = r[head_commit_id]
  2761. merge_commit = r[merge_commit_id]
  2762. # Check if fast-forward is possible
  2763. merge_bases = find_merge_base(r, [head_commit_id, merge_commit_id])
  2764. if not merge_bases:
  2765. raise Error("No common ancestor found")
  2766. # Use the first merge base
  2767. base_commit_id = merge_bases[0]
  2768. # Check if we're trying to merge the same commit
  2769. if head_commit_id == merge_commit_id:
  2770. # Already up to date
  2771. return (None, [])
  2772. # Check for fast-forward
  2773. if base_commit_id == head_commit_id and not no_ff:
  2774. # Fast-forward merge
  2775. r.refs[b"HEAD"] = merge_commit_id
  2776. # Update the working directory
  2777. update_working_tree(r, head_commit.tree, merge_commit.tree)
  2778. return (merge_commit_id, [])
  2779. if base_commit_id == merge_commit_id:
  2780. # Already up to date
  2781. return (None, [])
  2782. # Perform three-way merge
  2783. base_commit = r[base_commit_id]
  2784. merged_tree, conflicts = three_way_merge(
  2785. r.object_store, base_commit, head_commit, merge_commit
  2786. )
  2787. # Add merged tree to object store
  2788. r.object_store.add_object(merged_tree)
  2789. # Update index and working directory
  2790. update_working_tree(r, head_commit.tree, merged_tree.id)
  2791. if conflicts or no_commit:
  2792. # Don't create a commit if there are conflicts or no_commit is True
  2793. return (None, conflicts)
  2794. # Create merge commit
  2795. merge_commit_obj = Commit()
  2796. merge_commit_obj.tree = merged_tree.id
  2797. merge_commit_obj.parents = [head_commit_id, merge_commit_id]
  2798. # Set author/committer
  2799. if author is None:
  2800. author = get_user_identity(r.get_config_stack())
  2801. if committer is None:
  2802. committer = author
  2803. merge_commit_obj.author = author
  2804. merge_commit_obj.committer = committer
  2805. # Set timestamps
  2806. timestamp = int(time.time())
  2807. timezone = 0 # UTC
  2808. merge_commit_obj.author_time = timestamp
  2809. merge_commit_obj.author_timezone = timezone
  2810. merge_commit_obj.commit_time = timestamp
  2811. merge_commit_obj.commit_timezone = timezone
  2812. # Set commit message
  2813. if message is None:
  2814. message = f"Merge commit '{merge_commit_id.decode()[:7]}'\n"
  2815. merge_commit_obj.message = message.encode() if isinstance(message, str) else message
  2816. # Add commit to object store
  2817. r.object_store.add_object(merge_commit_obj)
  2818. # Update HEAD
  2819. r.refs[b"HEAD"] = merge_commit_obj.id
  2820. return (merge_commit_obj.id, [])
  2821. def merge(
  2822. repo,
  2823. committish,
  2824. no_commit=False,
  2825. no_ff=False,
  2826. message=None,
  2827. author=None,
  2828. committer=None,
  2829. ):
  2830. """Merge a commit into the current branch.
  2831. Args:
  2832. repo: Repository to merge into
  2833. committish: Commit to merge
  2834. no_commit: If True, do not create a merge commit
  2835. no_ff: If True, force creation of a merge commit
  2836. message: Optional merge commit message
  2837. author: Optional author for merge commit
  2838. committer: Optional committer for merge commit
  2839. Returns:
  2840. Tuple of (merge_commit_sha, conflicts) where merge_commit_sha is None
  2841. if no_commit=True or there were conflicts
  2842. Raises:
  2843. Error: If there is no HEAD reference or commit cannot be found
  2844. """
  2845. with open_repo_closing(repo) as r:
  2846. # Parse the commit to merge
  2847. try:
  2848. merge_commit_id = parse_commit(r, committish).id
  2849. except KeyError:
  2850. raise Error(f"Cannot find commit '{committish}'")
  2851. result = _do_merge(
  2852. r, merge_commit_id, no_commit, no_ff, message, author, committer
  2853. )
  2854. # Trigger auto GC if needed
  2855. from .gc import maybe_auto_gc
  2856. maybe_auto_gc(r)
  2857. return result
  2858. def unpack_objects(pack_path, target="."):
  2859. """Unpack objects from a pack file into the repository.
  2860. Args:
  2861. pack_path: Path to the pack file to unpack
  2862. target: Path to the repository to unpack into
  2863. Returns:
  2864. Number of objects unpacked
  2865. """
  2866. from .pack import Pack
  2867. with open_repo_closing(target) as r:
  2868. pack_basename = os.path.splitext(pack_path)[0]
  2869. with Pack(pack_basename) as pack:
  2870. count = 0
  2871. for unpacked in pack.iter_unpacked():
  2872. obj = unpacked.sha_file()
  2873. r.object_store.add_object(obj)
  2874. count += 1
  2875. return count
  2876. def merge_tree(repo, base_tree, our_tree, their_tree):
  2877. """Perform a three-way tree merge without touching the working directory.
  2878. This is similar to git merge-tree, performing a merge at the tree level
  2879. without creating commits or updating any references.
  2880. Args:
  2881. repo: Repository containing the trees
  2882. base_tree: Tree-ish of the common ancestor (or None for no common ancestor)
  2883. our_tree: Tree-ish of our side of the merge
  2884. their_tree: Tree-ish of their side of the merge
  2885. Returns:
  2886. tuple: A tuple of (merged_tree_id, conflicts) where:
  2887. - merged_tree_id is the SHA-1 of the merged tree
  2888. - conflicts is a list of paths (as bytes) that had conflicts
  2889. Raises:
  2890. KeyError: If any of the tree-ish arguments cannot be resolved
  2891. """
  2892. from .merge import Merger
  2893. with open_repo_closing(repo) as r:
  2894. # Resolve tree-ish arguments to actual trees
  2895. base = parse_tree(r, base_tree) if base_tree else None
  2896. ours = parse_tree(r, our_tree)
  2897. theirs = parse_tree(r, their_tree)
  2898. # Perform the merge
  2899. merger = Merger(r.object_store)
  2900. merged_tree, conflicts = merger.merge_trees(base, ours, theirs)
  2901. # Add the merged tree to the object store
  2902. r.object_store.add_object(merged_tree)
  2903. return merged_tree.id, conflicts
  2904. def cherry_pick(
  2905. repo,
  2906. committish,
  2907. no_commit=False,
  2908. continue_=False,
  2909. abort=False,
  2910. ):
  2911. r"""Cherry-pick a commit onto the current branch.
  2912. Args:
  2913. repo: Repository to cherry-pick into
  2914. committish: Commit to cherry-pick
  2915. no_commit: If True, do not create a commit after applying changes
  2916. continue\_: Continue an in-progress cherry-pick after resolving conflicts
  2917. abort: Abort an in-progress cherry-pick
  2918. Returns:
  2919. The SHA of the newly created commit, or None if no_commit=True or there were conflicts
  2920. Raises:
  2921. Error: If there is no HEAD reference, commit cannot be found, or operation fails
  2922. """
  2923. from .merge import three_way_merge
  2924. with open_repo_closing(repo) as r:
  2925. # Handle abort
  2926. if abort:
  2927. # Clean up any cherry-pick state
  2928. try:
  2929. os.remove(os.path.join(r.controldir(), "CHERRY_PICK_HEAD"))
  2930. except FileNotFoundError:
  2931. pass
  2932. try:
  2933. os.remove(os.path.join(r.controldir(), "MERGE_MSG"))
  2934. except FileNotFoundError:
  2935. pass
  2936. # Reset index to HEAD
  2937. r.reset_index(r[b"HEAD"].tree)
  2938. return None
  2939. # Handle continue
  2940. if continue_:
  2941. # Check if there's a cherry-pick in progress
  2942. cherry_pick_head_path = os.path.join(r.controldir(), "CHERRY_PICK_HEAD")
  2943. try:
  2944. with open(cherry_pick_head_path, "rb") as f:
  2945. cherry_pick_commit_id = f.read().strip()
  2946. cherry_pick_commit = r[cherry_pick_commit_id]
  2947. except FileNotFoundError:
  2948. raise Error("No cherry-pick in progress")
  2949. # Check for unresolved conflicts
  2950. conflicts = list(r.open_index().conflicts())
  2951. if conflicts:
  2952. raise Error("Unresolved conflicts remain")
  2953. # Create the commit
  2954. tree_id = r.open_index().commit(r.object_store)
  2955. # Read saved message if any
  2956. merge_msg_path = os.path.join(r.controldir(), "MERGE_MSG")
  2957. try:
  2958. with open(merge_msg_path, "rb") as f:
  2959. message = f.read()
  2960. except FileNotFoundError:
  2961. message = cherry_pick_commit.message
  2962. new_commit = r.do_commit(
  2963. message=message,
  2964. tree=tree_id,
  2965. author=cherry_pick_commit.author,
  2966. author_timestamp=cherry_pick_commit.author_time,
  2967. author_timezone=cherry_pick_commit.author_timezone,
  2968. )
  2969. # Clean up state files
  2970. try:
  2971. os.remove(cherry_pick_head_path)
  2972. except FileNotFoundError:
  2973. pass
  2974. try:
  2975. os.remove(merge_msg_path)
  2976. except FileNotFoundError:
  2977. pass
  2978. return new_commit
  2979. # Normal cherry-pick operation
  2980. # Get current HEAD
  2981. try:
  2982. head_commit = r[b"HEAD"]
  2983. except KeyError:
  2984. raise Error("No HEAD reference found")
  2985. # Parse the commit to cherry-pick
  2986. try:
  2987. cherry_pick_commit = parse_commit(r, committish)
  2988. except KeyError:
  2989. raise Error(f"Cannot find commit '{committish}'")
  2990. # Check if commit has parents
  2991. if not cherry_pick_commit.parents:
  2992. raise Error("Cannot cherry-pick root commit")
  2993. # Get parent of cherry-pick commit
  2994. parent_commit = r[cherry_pick_commit.parents[0]]
  2995. # Perform three-way merge
  2996. try:
  2997. merged_tree, conflicts = three_way_merge(
  2998. r.object_store, parent_commit, head_commit, cherry_pick_commit
  2999. )
  3000. except Exception as e:
  3001. raise Error(f"Cherry-pick failed: {e}")
  3002. # Add merged tree to object store
  3003. r.object_store.add_object(merged_tree)
  3004. # Update working tree and index
  3005. # Reset index to match merged tree
  3006. r.reset_index(merged_tree.id)
  3007. # Update working tree from the new index
  3008. update_working_tree(r, head_commit.tree, merged_tree.id)
  3009. if conflicts:
  3010. # Save state for later continuation
  3011. with open(os.path.join(r.controldir(), "CHERRY_PICK_HEAD"), "wb") as f:
  3012. f.write(cherry_pick_commit.id + b"\n")
  3013. # Save commit message
  3014. with open(os.path.join(r.controldir(), "MERGE_MSG"), "wb") as f:
  3015. f.write(cherry_pick_commit.message)
  3016. raise Error(
  3017. f"Conflicts in: {', '.join(c.decode('utf-8', 'replace') for c in conflicts)}\n"
  3018. f"Fix conflicts and run 'dulwich cherry-pick --continue'"
  3019. )
  3020. if no_commit:
  3021. return None
  3022. # Create the commit
  3023. new_commit = r.do_commit(
  3024. message=cherry_pick_commit.message,
  3025. tree=merged_tree.id,
  3026. author=cherry_pick_commit.author,
  3027. author_timestamp=cherry_pick_commit.author_time,
  3028. author_timezone=cherry_pick_commit.author_timezone,
  3029. )
  3030. return new_commit
  3031. def revert(
  3032. repo,
  3033. commits,
  3034. no_commit=False,
  3035. message=None,
  3036. author=None,
  3037. committer=None,
  3038. ):
  3039. """Revert one or more commits.
  3040. This creates a new commit that undoes the changes introduced by the
  3041. specified commits. Unlike reset, revert creates a new commit that
  3042. preserves history.
  3043. Args:
  3044. repo: Path to repository or repository object
  3045. commits: List of commit-ish (SHA, ref, etc.) to revert, or a single commit-ish
  3046. no_commit: If True, apply changes to index/working tree but don't commit
  3047. message: Optional commit message (default: "Revert <original subject>")
  3048. author: Optional author for revert commit
  3049. committer: Optional committer for revert commit
  3050. Returns:
  3051. SHA1 of the new revert commit, or None if no_commit=True
  3052. Raises:
  3053. Error: If revert fails due to conflicts or other issues
  3054. """
  3055. from .merge import three_way_merge
  3056. # Normalize commits to a list
  3057. if isinstance(commits, (str, bytes)):
  3058. commits = [commits]
  3059. with open_repo_closing(repo) as r:
  3060. # Convert string refs to bytes
  3061. commits_to_revert = []
  3062. for commit_ref in commits:
  3063. if isinstance(commit_ref, str):
  3064. commit_ref = commit_ref.encode("utf-8")
  3065. commit = parse_commit(r, commit_ref)
  3066. commits_to_revert.append(commit)
  3067. # Get current HEAD
  3068. try:
  3069. head_commit_id = r.refs[b"HEAD"]
  3070. except KeyError:
  3071. raise Error("No HEAD reference found")
  3072. head_commit = r[head_commit_id]
  3073. current_tree = head_commit.tree
  3074. # Process commits in order
  3075. for commit_to_revert in commits_to_revert:
  3076. # For revert, we want to apply the inverse of the commit
  3077. # This means using the commit's tree as "base" and its parent as "theirs"
  3078. if not commit_to_revert.parents:
  3079. raise Error(
  3080. f"Cannot revert commit {commit_to_revert.id} - it has no parents"
  3081. )
  3082. # For simplicity, we only handle commits with one parent (no merge commits)
  3083. if len(commit_to_revert.parents) > 1:
  3084. raise Error(
  3085. f"Cannot revert merge commit {commit_to_revert.id} - not yet implemented"
  3086. )
  3087. parent_commit = r[commit_to_revert.parents[0]]
  3088. # Perform three-way merge:
  3089. # - base: the commit we're reverting (what we want to remove)
  3090. # - ours: current HEAD (what we have now)
  3091. # - theirs: parent of commit being reverted (what we want to go back to)
  3092. merged_tree, conflicts = three_way_merge(
  3093. r.object_store,
  3094. commit_to_revert, # base
  3095. r[head_commit_id], # ours
  3096. parent_commit, # theirs
  3097. )
  3098. if conflicts:
  3099. # Update working tree with conflicts
  3100. update_working_tree(r, current_tree, merged_tree.id)
  3101. conflicted_paths = [c.decode("utf-8", "replace") for c in conflicts]
  3102. raise Error(f"Conflicts while reverting: {', '.join(conflicted_paths)}")
  3103. # Add merged tree to object store
  3104. r.object_store.add_object(merged_tree)
  3105. # Update working tree
  3106. update_working_tree(r, current_tree, merged_tree.id)
  3107. current_tree = merged_tree.id
  3108. if not no_commit:
  3109. # Create revert commit
  3110. revert_commit = Commit()
  3111. revert_commit.tree = merged_tree.id
  3112. revert_commit.parents = [head_commit_id]
  3113. # Set author/committer
  3114. if author is None:
  3115. author = get_user_identity(r.get_config_stack())
  3116. if committer is None:
  3117. committer = author
  3118. revert_commit.author = author
  3119. revert_commit.committer = committer
  3120. # Set timestamps
  3121. timestamp = int(time.time())
  3122. timezone = 0 # UTC
  3123. revert_commit.author_time = timestamp
  3124. revert_commit.author_timezone = timezone
  3125. revert_commit.commit_time = timestamp
  3126. revert_commit.commit_timezone = timezone
  3127. # Set message
  3128. if message is None:
  3129. # Extract original commit subject
  3130. original_message = commit_to_revert.message
  3131. if isinstance(original_message, bytes):
  3132. original_message = original_message.decode("utf-8", "replace")
  3133. subject = original_message.split("\n")[0]
  3134. message = f'Revert "{subject}"\n\nThis reverts commit {commit_to_revert.id.decode("ascii")}.'.encode()
  3135. elif isinstance(message, str):
  3136. message = message.encode("utf-8")
  3137. revert_commit.message = message
  3138. # Add commit to object store
  3139. r.object_store.add_object(revert_commit)
  3140. # Update HEAD
  3141. r.refs[b"HEAD"] = revert_commit.id
  3142. head_commit_id = revert_commit.id
  3143. return head_commit_id if not no_commit else None
  3144. def gc(
  3145. repo,
  3146. auto: bool = False,
  3147. aggressive: bool = False,
  3148. prune: bool = True,
  3149. grace_period: Optional[int] = 1209600, # 2 weeks default
  3150. dry_run: bool = False,
  3151. progress=None,
  3152. ):
  3153. """Run garbage collection on a repository.
  3154. Args:
  3155. repo: Path to the repository or a Repo object
  3156. auto: If True, only run gc if needed
  3157. aggressive: If True, use more aggressive settings
  3158. prune: If True, prune unreachable objects
  3159. grace_period: Grace period in seconds for pruning (default 2 weeks)
  3160. dry_run: If True, only report what would be done
  3161. progress: Optional progress callback
  3162. Returns:
  3163. GCStats object with garbage collection statistics
  3164. """
  3165. from .gc import garbage_collect
  3166. with open_repo_closing(repo) as r:
  3167. return garbage_collect(
  3168. r,
  3169. auto=auto,
  3170. aggressive=aggressive,
  3171. prune=prune,
  3172. grace_period=grace_period,
  3173. dry_run=dry_run,
  3174. progress=progress,
  3175. )
  3176. def prune(
  3177. repo,
  3178. grace_period: Optional[int] = None,
  3179. dry_run: bool = False,
  3180. progress=None,
  3181. ):
  3182. """Prune/clean up a repository's object store.
  3183. This removes temporary files that were left behind by interrupted
  3184. pack operations.
  3185. Args:
  3186. repo: Path to the repository or a Repo object
  3187. grace_period: Grace period in seconds for removing temporary files
  3188. (default 2 weeks)
  3189. dry_run: If True, only report what would be done
  3190. progress: Optional progress callback
  3191. """
  3192. with open_repo_closing(repo) as r:
  3193. if progress:
  3194. progress("Pruning temporary files")
  3195. if not dry_run:
  3196. r.object_store.prune(grace_period=grace_period)
  3197. def count_objects(repo=".", verbose=False) -> CountObjectsResult:
  3198. """Count unpacked objects and their disk usage.
  3199. Args:
  3200. repo: Path to repository or repository object
  3201. verbose: Whether to return verbose information
  3202. Returns:
  3203. CountObjectsResult object with detailed statistics
  3204. """
  3205. with open_repo_closing(repo) as r:
  3206. object_store = r.object_store
  3207. # Count loose objects
  3208. loose_count = 0
  3209. loose_size = 0
  3210. for sha in object_store._iter_loose_objects():
  3211. loose_count += 1
  3212. path = object_store._get_shafile_path(sha)
  3213. try:
  3214. stat_info = os.stat(path)
  3215. # Git uses disk usage, not file size. st_blocks is always in
  3216. # 512-byte blocks per POSIX standard
  3217. if hasattr(stat_info, "st_blocks"):
  3218. # Available on Linux and macOS
  3219. loose_size += stat_info.st_blocks * 512 # type: ignore
  3220. else:
  3221. # Fallback for Windows
  3222. loose_size += stat_info.st_size
  3223. except FileNotFoundError:
  3224. # Object may have been removed between iteration and stat
  3225. pass
  3226. if not verbose:
  3227. return CountObjectsResult(count=loose_count, size=loose_size)
  3228. # Count pack information
  3229. pack_count = len(object_store.packs)
  3230. in_pack_count = 0
  3231. pack_size = 0
  3232. for pack in object_store.packs:
  3233. in_pack_count += len(pack)
  3234. # Get pack file size
  3235. pack_path = pack._data_path
  3236. try:
  3237. pack_size += os.path.getsize(pack_path)
  3238. except FileNotFoundError:
  3239. pass
  3240. # Get index file size
  3241. idx_path = pack._idx_path
  3242. try:
  3243. pack_size += os.path.getsize(idx_path)
  3244. except FileNotFoundError:
  3245. pass
  3246. return CountObjectsResult(
  3247. count=loose_count,
  3248. size=loose_size,
  3249. in_pack=in_pack_count,
  3250. packs=pack_count,
  3251. size_pack=pack_size,
  3252. )
  3253. def rebase(
  3254. repo: Union[Repo, str],
  3255. upstream: Union[bytes, str],
  3256. onto: Optional[Union[bytes, str]] = None,
  3257. branch: Optional[Union[bytes, str]] = None,
  3258. abort: bool = False,
  3259. continue_rebase: bool = False,
  3260. skip: bool = False,
  3261. ) -> list[bytes]:
  3262. """Rebase commits onto another branch.
  3263. Args:
  3264. repo: Repository to rebase in
  3265. upstream: Upstream branch/commit to rebase onto
  3266. onto: Specific commit to rebase onto (defaults to upstream)
  3267. branch: Branch to rebase (defaults to current branch)
  3268. abort: Abort an in-progress rebase
  3269. continue_rebase: Continue an in-progress rebase
  3270. skip: Skip current commit and continue rebase
  3271. Returns:
  3272. List of new commit SHAs created by rebase
  3273. Raises:
  3274. Error: If rebase fails or conflicts occur
  3275. """
  3276. from .rebase import RebaseConflict, RebaseError, Rebaser
  3277. with open_repo_closing(repo) as r:
  3278. rebaser = Rebaser(r)
  3279. if abort:
  3280. try:
  3281. rebaser.abort()
  3282. return []
  3283. except RebaseError as e:
  3284. raise Error(str(e))
  3285. if continue_rebase:
  3286. try:
  3287. result = rebaser.continue_()
  3288. if result is None:
  3289. # Rebase complete
  3290. return []
  3291. elif isinstance(result, tuple) and result[1]:
  3292. # Still have conflicts
  3293. raise Error(
  3294. f"Conflicts in: {', '.join(f.decode('utf-8', 'replace') for f in result[1])}"
  3295. )
  3296. except RebaseError as e:
  3297. raise Error(str(e))
  3298. # Convert string refs to bytes
  3299. if isinstance(upstream, str):
  3300. upstream = upstream.encode("utf-8")
  3301. if isinstance(onto, str):
  3302. onto = onto.encode("utf-8") if onto else None
  3303. if isinstance(branch, str):
  3304. branch = branch.encode("utf-8") if branch else None
  3305. try:
  3306. # Start rebase
  3307. rebaser.start(upstream, onto, branch)
  3308. # Continue rebase automatically
  3309. result = rebaser.continue_()
  3310. if result is not None:
  3311. # Conflicts
  3312. raise RebaseConflict(result[1])
  3313. # Return the SHAs of the rebased commits
  3314. return [c.id for c in rebaser._done]
  3315. except RebaseConflict as e:
  3316. raise Error(str(e))
  3317. except RebaseError as e:
  3318. raise Error(str(e))
  3319. def annotate(repo, path, committish=None):
  3320. """Annotate the history of a file.
  3321. :param repo: Path to the repository
  3322. :param path: Path to annotate
  3323. :param committish: Commit id to find path in
  3324. :return: List of ((Commit, TreeChange), line) tuples
  3325. """
  3326. if committish is None:
  3327. committish = "HEAD"
  3328. from dulwich.annotate import annotate_lines
  3329. with open_repo_closing(repo) as r:
  3330. commit_id = parse_commit(r, committish).id
  3331. # Ensure path is bytes
  3332. if isinstance(path, str):
  3333. path = path.encode()
  3334. return annotate_lines(r.object_store, commit_id, path)
  3335. blame = annotate
  3336. def filter_branch(
  3337. repo=".",
  3338. branch="HEAD",
  3339. *,
  3340. filter_fn=None,
  3341. filter_author=None,
  3342. filter_committer=None,
  3343. filter_message=None,
  3344. tree_filter=None,
  3345. index_filter=None,
  3346. parent_filter=None,
  3347. commit_filter=None,
  3348. subdirectory_filter=None,
  3349. prune_empty=False,
  3350. tag_name_filter=None,
  3351. force=False,
  3352. keep_original=True,
  3353. refs=None,
  3354. ):
  3355. """Rewrite branch history by creating new commits with filtered properties.
  3356. This is similar to git filter-branch, allowing you to rewrite commit
  3357. history by modifying trees, parents, author, committer, or commit messages.
  3358. Args:
  3359. repo: Path to repository
  3360. branch: Branch to rewrite (defaults to HEAD)
  3361. filter_fn: Optional callable that takes a Commit object and returns
  3362. a dict of updated fields (author, committer, message, etc.)
  3363. filter_author: Optional callable that takes author bytes and returns
  3364. updated author bytes or None to keep unchanged
  3365. filter_committer: Optional callable that takes committer bytes and returns
  3366. updated committer bytes or None to keep unchanged
  3367. filter_message: Optional callable that takes commit message bytes
  3368. and returns updated message bytes
  3369. tree_filter: Optional callable that takes (tree_sha, temp_dir) and returns
  3370. new tree SHA after modifying working directory
  3371. index_filter: Optional callable that takes (tree_sha, temp_index_path) and
  3372. returns new tree SHA after modifying index
  3373. parent_filter: Optional callable that takes parent list and returns
  3374. modified parent list
  3375. commit_filter: Optional callable that takes (Commit, tree_sha) and returns
  3376. new commit SHA or None to skip commit
  3377. subdirectory_filter: Optional subdirectory path to extract as new root
  3378. prune_empty: Whether to prune commits that become empty
  3379. tag_name_filter: Optional callable to rename tags
  3380. force: Force operation even if branch has been filtered before
  3381. keep_original: Keep original refs under refs/original/
  3382. refs: List of refs to rewrite (defaults to [branch])
  3383. Returns:
  3384. Dict mapping old commit SHAs to new commit SHAs
  3385. Raises:
  3386. Error: If branch is already filtered and force is False
  3387. """
  3388. from .filter_branch import CommitFilter, filter_refs
  3389. with open_repo_closing(repo) as r:
  3390. # Parse branch/committish
  3391. if isinstance(branch, str):
  3392. branch = branch.encode()
  3393. # Determine which refs to process
  3394. if refs is None:
  3395. if branch == b"HEAD":
  3396. # Resolve HEAD to actual branch
  3397. try:
  3398. resolved = r.refs.follow(b"HEAD")
  3399. if resolved and resolved[0]:
  3400. # resolved is a list of (refname, sha) tuples
  3401. resolved_ref = resolved[0][-1]
  3402. if resolved_ref and resolved_ref != b"HEAD":
  3403. refs = [resolved_ref]
  3404. else:
  3405. # HEAD points directly to a commit
  3406. refs = [b"HEAD"]
  3407. else:
  3408. refs = [b"HEAD"]
  3409. except SymrefLoop:
  3410. refs = [b"HEAD"]
  3411. else:
  3412. # Convert branch name to full ref if needed
  3413. if not branch.startswith(b"refs/"):
  3414. branch = b"refs/heads/" + branch
  3415. refs = [branch]
  3416. # Convert subdirectory filter to bytes if needed
  3417. if subdirectory_filter and isinstance(subdirectory_filter, str):
  3418. subdirectory_filter = subdirectory_filter.encode()
  3419. # Create commit filter
  3420. commit_filter = CommitFilter(
  3421. r.object_store,
  3422. filter_fn=filter_fn,
  3423. filter_author=filter_author,
  3424. filter_committer=filter_committer,
  3425. filter_message=filter_message,
  3426. tree_filter=tree_filter,
  3427. index_filter=index_filter,
  3428. parent_filter=parent_filter,
  3429. commit_filter=commit_filter,
  3430. subdirectory_filter=subdirectory_filter,
  3431. prune_empty=prune_empty,
  3432. tag_name_filter=tag_name_filter,
  3433. )
  3434. # Tag callback for renaming tags
  3435. def rename_tag(old_ref, new_ref):
  3436. # Copy tag to new name
  3437. r.refs[new_ref] = r.refs[old_ref]
  3438. # Delete old tag
  3439. del r.refs[old_ref]
  3440. # Filter refs
  3441. try:
  3442. return filter_refs(
  3443. r.refs,
  3444. r.object_store,
  3445. refs,
  3446. commit_filter,
  3447. keep_original=keep_original,
  3448. force=force,
  3449. tag_callback=rename_tag if tag_name_filter else None,
  3450. )
  3451. except ValueError as e:
  3452. raise Error(str(e)) from e