porcelain.py 147 KB

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