porcelain.py 97 KB

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