porcelain.py 86 KB

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