porcelain.py 111 KB

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