remote.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  1. # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
  2. #
  3. # This module is part of GitPython and is released under the
  4. # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
  5. """Module implementing a remote object allowing easy access to git remotes."""
  6. __all__ = ["RemoteProgress", "PushInfo", "FetchInfo", "Remote"]
  7. import contextlib
  8. import logging
  9. import re
  10. from git.cmd import Git, handle_process_output
  11. from git.compat import defenc, force_text
  12. from git.config import GitConfigParser, SectionConstraint, cp
  13. from git.exc import GitCommandError
  14. from git.refs import Head, Reference, RemoteReference, SymbolicReference, TagReference
  15. from git.util import (
  16. CallableRemoteProgress,
  17. IterableList,
  18. IterableObj,
  19. LazyMixin,
  20. RemoteProgress,
  21. join_path,
  22. )
  23. # typing-------------------------------------------------------
  24. from typing import (
  25. Any,
  26. Callable,
  27. Dict,
  28. Iterator,
  29. List,
  30. NoReturn,
  31. Optional,
  32. Sequence,
  33. TYPE_CHECKING,
  34. Type,
  35. Union,
  36. cast,
  37. overload,
  38. )
  39. from git.types import AnyGitObject, Literal, PathLike
  40. if TYPE_CHECKING:
  41. from git.objects.commit import Commit
  42. from git.objects.submodule.base import UpdateProgress
  43. from git.repo.base import Repo
  44. flagKeyLiteral = Literal[" ", "!", "+", "-", "*", "=", "t", "?"]
  45. # -------------------------------------------------------------
  46. _logger = logging.getLogger(__name__)
  47. # { Utilities
  48. def add_progress(
  49. kwargs: Any,
  50. git: Git,
  51. progress: Union[RemoteProgress, "UpdateProgress", Callable[..., RemoteProgress], None],
  52. ) -> Any:
  53. """Add the ``--progress`` flag to the given `kwargs` dict if supported by the git
  54. command.
  55. :note:
  56. If the actual progress in the given progress instance is not given, we do not
  57. request any progress.
  58. :return:
  59. Possibly altered `kwargs`
  60. """
  61. if progress is not None:
  62. v = git.version_info[:2]
  63. if v >= (1, 7):
  64. kwargs["progress"] = True
  65. # END handle --progress
  66. # END handle progress
  67. return kwargs
  68. # } END utilities
  69. @overload
  70. def to_progress_instance(progress: None) -> RemoteProgress: ...
  71. @overload
  72. def to_progress_instance(progress: Callable[..., Any]) -> CallableRemoteProgress: ...
  73. @overload
  74. def to_progress_instance(progress: RemoteProgress) -> RemoteProgress: ...
  75. def to_progress_instance(
  76. progress: Union[Callable[..., Any], RemoteProgress, None],
  77. ) -> Union[RemoteProgress, CallableRemoteProgress]:
  78. """Given the `progress` return a suitable object derived from
  79. :class:`~git.util.RemoteProgress`."""
  80. # New API only needs progress as a function.
  81. if callable(progress):
  82. return CallableRemoteProgress(progress)
  83. # Where None is passed create a parser that eats the progress.
  84. elif progress is None:
  85. return RemoteProgress()
  86. # Assume its the old API with an instance of RemoteProgress.
  87. return progress
  88. class PushInfo(IterableObj):
  89. """
  90. Carries information about the result of a push operation of a single head::
  91. info = remote.push()[0]
  92. info.flags # bitflags providing more information about the result
  93. info.local_ref # Reference pointing to the local reference that was pushed
  94. # It is None if the ref was deleted.
  95. info.remote_ref_string # path to the remote reference located on the remote side
  96. info.remote_ref # Remote Reference on the local side corresponding to
  97. # the remote_ref_string. It can be a TagReference as well.
  98. info.old_commit # commit at which the remote_ref was standing before we pushed
  99. # it to local_ref.commit. Will be None if an error was indicated
  100. info.summary # summary line providing human readable english text about the push
  101. """
  102. __slots__ = (
  103. "local_ref",
  104. "remote_ref_string",
  105. "flags",
  106. "_old_commit_sha",
  107. "_remote",
  108. "summary",
  109. )
  110. _id_attribute_ = "pushinfo"
  111. (
  112. NEW_TAG,
  113. NEW_HEAD,
  114. NO_MATCH,
  115. REJECTED,
  116. REMOTE_REJECTED,
  117. REMOTE_FAILURE,
  118. DELETED,
  119. FORCED_UPDATE,
  120. FAST_FORWARD,
  121. UP_TO_DATE,
  122. ERROR,
  123. ) = [1 << x for x in range(11)]
  124. _flag_map = {
  125. "X": NO_MATCH,
  126. "-": DELETED,
  127. "*": 0,
  128. "+": FORCED_UPDATE,
  129. " ": FAST_FORWARD,
  130. "=": UP_TO_DATE,
  131. "!": ERROR,
  132. }
  133. def __init__(
  134. self,
  135. flags: int,
  136. local_ref: Union[SymbolicReference, None],
  137. remote_ref_string: str,
  138. remote: "Remote",
  139. old_commit: Optional[str] = None,
  140. summary: str = "",
  141. ) -> None:
  142. """Initialize a new instance.
  143. local_ref: HEAD | Head | RemoteReference | TagReference | Reference | SymbolicReference | None
  144. """
  145. self.flags = flags
  146. self.local_ref = local_ref
  147. self.remote_ref_string = remote_ref_string
  148. self._remote = remote
  149. self._old_commit_sha = old_commit
  150. self.summary = summary
  151. @property
  152. def old_commit(self) -> Union["Commit", None]:
  153. return self._old_commit_sha and self._remote.repo.commit(self._old_commit_sha) or None
  154. @property
  155. def remote_ref(self) -> Union[RemoteReference, TagReference]:
  156. """
  157. :return:
  158. Remote :class:`~git.refs.reference.Reference` or
  159. :class:`~git.refs.tag.TagReference` in the local repository corresponding to
  160. the :attr:`remote_ref_string` kept in this instance.
  161. """
  162. # Translate heads to a local remote. Tags stay as they are.
  163. if self.remote_ref_string.startswith("refs/tags"):
  164. return TagReference(self._remote.repo, self.remote_ref_string)
  165. elif self.remote_ref_string.startswith("refs/heads"):
  166. remote_ref = Reference(self._remote.repo, self.remote_ref_string)
  167. return RemoteReference(
  168. self._remote.repo,
  169. "refs/remotes/%s/%s" % (str(self._remote), remote_ref.name),
  170. )
  171. else:
  172. raise ValueError("Could not handle remote ref: %r" % self.remote_ref_string)
  173. # END
  174. @classmethod
  175. def _from_line(cls, remote: "Remote", line: str) -> "PushInfo":
  176. """Create a new :class:`PushInfo` instance as parsed from line which is expected
  177. to be like refs/heads/master:refs/heads/master 05d2687..1d0568e as bytes."""
  178. control_character, from_to, summary = line.split("\t", 3)
  179. flags = 0
  180. # Control character handling
  181. try:
  182. flags |= cls._flag_map[control_character]
  183. except KeyError as e:
  184. raise ValueError("Control character %r unknown as parsed from line %r" % (control_character, line)) from e
  185. # END handle control character
  186. # from_to handling
  187. from_ref_string, to_ref_string = from_to.split(":")
  188. if flags & cls.DELETED:
  189. from_ref: Union[SymbolicReference, None] = None
  190. else:
  191. if from_ref_string == "(delete)":
  192. from_ref = None
  193. else:
  194. from_ref = Reference.from_path(remote.repo, from_ref_string)
  195. # Commit handling, could be message or commit info
  196. old_commit: Optional[str] = None
  197. if summary.startswith("["):
  198. if "[rejected]" in summary:
  199. flags |= cls.REJECTED
  200. elif "[remote rejected]" in summary:
  201. flags |= cls.REMOTE_REJECTED
  202. elif "[remote failure]" in summary:
  203. flags |= cls.REMOTE_FAILURE
  204. elif "[no match]" in summary:
  205. flags |= cls.ERROR
  206. elif "[new tag]" in summary:
  207. flags |= cls.NEW_TAG
  208. elif "[new branch]" in summary:
  209. flags |= cls.NEW_HEAD
  210. # `uptodate` encoded in control character
  211. else:
  212. # Fast-forward or forced update - was encoded in control character,
  213. # but we parse the old and new commit.
  214. split_token = "..."
  215. if control_character == " ":
  216. split_token = ".."
  217. old_sha, _new_sha = summary.split(" ")[0].split(split_token)
  218. # Have to use constructor here as the sha usually is abbreviated.
  219. old_commit = old_sha
  220. # END message handling
  221. return PushInfo(flags, from_ref, to_ref_string, remote, old_commit, summary)
  222. @classmethod
  223. def iter_items(cls, repo: "Repo", *args: Any, **kwargs: Any) -> NoReturn: # -> Iterator['PushInfo']:
  224. raise NotImplementedError
  225. class PushInfoList(IterableList[PushInfo]):
  226. """:class:`~git.util.IterableList` of :class:`PushInfo` objects."""
  227. def __new__(cls) -> "PushInfoList":
  228. return cast(PushInfoList, IterableList.__new__(cls, "push_infos"))
  229. def __init__(self) -> None:
  230. super().__init__("push_infos")
  231. self.error: Optional[Exception] = None
  232. def raise_if_error(self) -> None:
  233. """Raise an exception if any ref failed to push."""
  234. if self.error:
  235. raise self.error
  236. class FetchInfo(IterableObj):
  237. """
  238. Carries information about the results of a fetch operation of a single head::
  239. info = remote.fetch()[0]
  240. info.ref # Symbolic Reference or RemoteReference to the changed
  241. # remote head or FETCH_HEAD
  242. info.flags # additional flags to be & with enumeration members,
  243. # i.e. info.flags & info.REJECTED
  244. # is 0 if ref is SymbolicReference
  245. info.note # additional notes given by git-fetch intended for the user
  246. info.old_commit # if info.flags & info.FORCED_UPDATE|info.FAST_FORWARD,
  247. # field is set to the previous location of ref, otherwise None
  248. info.remote_ref_path # The path from which we fetched on the remote. It's the remote's version of our info.ref
  249. """
  250. __slots__ = ("ref", "old_commit", "flags", "note", "remote_ref_path")
  251. _id_attribute_ = "fetchinfo"
  252. (
  253. NEW_TAG,
  254. NEW_HEAD,
  255. HEAD_UPTODATE,
  256. TAG_UPDATE,
  257. REJECTED,
  258. FORCED_UPDATE,
  259. FAST_FORWARD,
  260. ERROR,
  261. ) = [1 << x for x in range(8)]
  262. _re_fetch_result = re.compile(r"^ *(?:.{0,3})(.) (\[[\w \.$@]+\]|[\w\.$@]+) +(.+) -> ([^ ]+)( \(.*\)?$)?")
  263. _flag_map: Dict[flagKeyLiteral, int] = {
  264. "!": ERROR,
  265. "+": FORCED_UPDATE,
  266. "*": 0,
  267. "=": HEAD_UPTODATE,
  268. " ": FAST_FORWARD,
  269. "-": TAG_UPDATE,
  270. }
  271. @classmethod
  272. def refresh(cls) -> Literal[True]:
  273. """Update information about which :manpage:`git-fetch(1)` flags are supported
  274. by the git executable being used.
  275. Called by the :func:`git.refresh` function in the top level ``__init__``.
  276. """
  277. # Clear the old values in _flag_map.
  278. with contextlib.suppress(KeyError):
  279. del cls._flag_map["t"]
  280. with contextlib.suppress(KeyError):
  281. del cls._flag_map["-"]
  282. # Set the value given the git version.
  283. if Git().version_info[:2] >= (2, 10):
  284. cls._flag_map["t"] = cls.TAG_UPDATE
  285. else:
  286. cls._flag_map["-"] = cls.TAG_UPDATE
  287. return True
  288. def __init__(
  289. self,
  290. ref: SymbolicReference,
  291. flags: int,
  292. note: str = "",
  293. old_commit: Union[AnyGitObject, None] = None,
  294. remote_ref_path: Optional[PathLike] = None,
  295. ) -> None:
  296. """Initialize a new instance."""
  297. self.ref = ref
  298. self.flags = flags
  299. self.note = note
  300. self.old_commit = old_commit
  301. self.remote_ref_path = remote_ref_path
  302. def __str__(self) -> str:
  303. return self.name
  304. @property
  305. def name(self) -> str:
  306. """:return: Name of our remote ref"""
  307. return self.ref.name
  308. @property
  309. def commit(self) -> "Commit":
  310. """:return: Commit of our remote ref"""
  311. return self.ref.commit
  312. @classmethod
  313. def _from_line(cls, repo: "Repo", line: str, fetch_line: str) -> "FetchInfo":
  314. """Parse information from the given line as returned by ``git-fetch -v`` and
  315. return a new :class:`FetchInfo` object representing this information.
  316. We can handle a line as follows::
  317. %c %-*s %-*s -> %s%s
  318. Where ``c`` is either a space, ``!``, ``+``, ``-``, ``*``, or ``=``:
  319. - '!' means error
  320. - '+' means success forcing update
  321. - '-' means a tag was updated
  322. - '*' means birth of new branch or tag
  323. - '=' means the head was up to date (and not moved)
  324. - ' ' means a fast-forward
  325. `fetch_line` is the corresponding line from FETCH_HEAD, like::
  326. acb0fa8b94ef421ad60c8507b634759a472cd56c not-for-merge branch '0.1.7RC' of /tmp/tmpya0vairemote_repo
  327. """
  328. match = cls._re_fetch_result.match(line)
  329. if match is None:
  330. raise ValueError("Failed to parse line: %r" % line)
  331. # Parse lines.
  332. remote_local_ref_str: str
  333. (
  334. control_character,
  335. operation,
  336. local_remote_ref,
  337. remote_local_ref_str,
  338. note,
  339. ) = match.groups()
  340. control_character = cast(flagKeyLiteral, control_character)
  341. try:
  342. _new_hex_sha, _fetch_operation, fetch_note = fetch_line.split("\t")
  343. ref_type_name, fetch_note = fetch_note.split(" ", 1)
  344. except ValueError as e: # unpack error
  345. raise ValueError("Failed to parse FETCH_HEAD line: %r" % fetch_line) from e
  346. # Parse flags from control_character.
  347. flags = 0
  348. try:
  349. flags |= cls._flag_map[control_character]
  350. except KeyError as e:
  351. raise ValueError("Control character %r unknown as parsed from line %r" % (control_character, line)) from e
  352. # END control char exception handling
  353. # Parse operation string for more info.
  354. # This makes no sense for symbolic refs, but we parse it anyway.
  355. old_commit: Union[AnyGitObject, None] = None
  356. is_tag_operation = False
  357. if "rejected" in operation:
  358. flags |= cls.REJECTED
  359. if "new tag" in operation:
  360. flags |= cls.NEW_TAG
  361. is_tag_operation = True
  362. if "tag update" in operation:
  363. flags |= cls.TAG_UPDATE
  364. is_tag_operation = True
  365. if "new branch" in operation:
  366. flags |= cls.NEW_HEAD
  367. if "..." in operation or ".." in operation:
  368. split_token = "..."
  369. if control_character == " ":
  370. split_token = split_token[:-1]
  371. old_commit = repo.rev_parse(operation.split(split_token)[0])
  372. # END handle refspec
  373. # Handle FETCH_HEAD and figure out ref type.
  374. # If we do not specify a target branch like master:refs/remotes/origin/master,
  375. # the fetch result is stored in FETCH_HEAD which destroys the rule we usually
  376. # have. In that case we use a symbolic reference which is detached.
  377. ref_type: Optional[Type[SymbolicReference]] = None
  378. if remote_local_ref_str == "FETCH_HEAD":
  379. ref_type = SymbolicReference
  380. elif ref_type_name == "tag" or is_tag_operation:
  381. # The ref_type_name can be branch, whereas we are still seeing a tag
  382. # operation. It happens during testing, which is based on actual git
  383. # operations.
  384. ref_type = TagReference
  385. elif ref_type_name in ("remote-tracking", "branch"):
  386. # Note: remote-tracking is just the first part of the
  387. # 'remote-tracking branch' token. We don't parse it correctly, but it's
  388. # enough to know what to do, and it's new in git 1.7something.
  389. ref_type = RemoteReference
  390. elif "/" in ref_type_name:
  391. # If the fetch spec look something like '+refs/pull/*:refs/heads/pull/*',
  392. # and is thus pretty much anything the user wants, we will have trouble
  393. # determining what's going on. For now, we assume the local ref is a Head.
  394. ref_type = Head
  395. else:
  396. raise TypeError("Cannot handle reference type: %r" % ref_type_name)
  397. # END handle ref type
  398. # Create ref instance.
  399. if ref_type is SymbolicReference:
  400. remote_local_ref = ref_type(repo, "FETCH_HEAD")
  401. else:
  402. # Determine prefix. Tags are usually pulled into refs/tags; they may have
  403. # subdirectories. It is not clear sometimes where exactly the item is,
  404. # unless we have an absolute path as indicated by the 'ref/' prefix.
  405. # Otherwise even a tag could be in refs/remotes, which is when it will have
  406. # the 'tags/' subdirectory in its path. We don't want to test for actual
  407. # existence, but try to figure everything out analytically.
  408. ref_path: Optional[PathLike] = None
  409. remote_local_ref_str = remote_local_ref_str.strip()
  410. if remote_local_ref_str.startswith(Reference._common_path_default + "/"):
  411. # Always use actual type if we get absolute paths. This will always be
  412. # the case if something is fetched outside of refs/remotes (if its not a
  413. # tag).
  414. ref_path = remote_local_ref_str
  415. if ref_type is not TagReference and not remote_local_ref_str.startswith(
  416. RemoteReference._common_path_default + "/"
  417. ):
  418. ref_type = Reference
  419. # END downgrade remote reference
  420. elif ref_type is TagReference and "tags/" in remote_local_ref_str:
  421. # Even though it's a tag, it is located in refs/remotes.
  422. ref_path = join_path(RemoteReference._common_path_default, remote_local_ref_str)
  423. else:
  424. ref_path = join_path(ref_type._common_path_default, remote_local_ref_str)
  425. # END obtain refpath
  426. # Even though the path could be within the git conventions, we make sure we
  427. # respect whatever the user wanted, and disabled path checking.
  428. remote_local_ref = ref_type(repo, ref_path, check_path=False)
  429. # END create ref instance
  430. note = (note and note.strip()) or ""
  431. return cls(remote_local_ref, flags, note, old_commit, local_remote_ref)
  432. @classmethod
  433. def iter_items(cls, repo: "Repo", *args: Any, **kwargs: Any) -> NoReturn: # -> Iterator['FetchInfo']:
  434. raise NotImplementedError
  435. class Remote(LazyMixin, IterableObj):
  436. """Provides easy read and write access to a git remote.
  437. Everything not part of this interface is considered an option for the current
  438. remote, allowing constructs like ``remote.pushurl`` to query the pushurl.
  439. :note:
  440. When querying configuration, the configuration accessor will be cached to speed
  441. up subsequent accesses.
  442. """
  443. __slots__ = ("repo", "name", "_config_reader")
  444. _id_attribute_ = "name"
  445. unsafe_git_fetch_options = [
  446. # This option allows users to execute arbitrary commands.
  447. # https://git-scm.com/docs/git-fetch#Documentation/git-fetch.txt---upload-packltupload-packgt
  448. "--upload-pack",
  449. ]
  450. unsafe_git_pull_options = [
  451. # This option allows users to execute arbitrary commands.
  452. # https://git-scm.com/docs/git-pull#Documentation/git-pull.txt---upload-packltupload-packgt
  453. "--upload-pack"
  454. ]
  455. unsafe_git_push_options = [
  456. # This option allows users to execute arbitrary commands.
  457. # https://git-scm.com/docs/git-push#Documentation/git-push.txt---execltgit-receive-packgt
  458. "--receive-pack",
  459. "--exec",
  460. ]
  461. url: str # Obtained dynamically from _config_reader. See __getattr__ below.
  462. """The URL configured for the remote."""
  463. def __init__(self, repo: "Repo", name: str) -> None:
  464. """Initialize a remote instance.
  465. :param repo:
  466. The repository we are a remote of.
  467. :param name:
  468. The name of the remote, e.g. ``origin``.
  469. """
  470. self.repo = repo
  471. self.name = name
  472. def __getattr__(self, attr: str) -> Any:
  473. """Allows to call this instance like ``remote.special(*args, **kwargs)`` to
  474. call ``git remote special self.name``."""
  475. if attr == "_config_reader":
  476. return super().__getattr__(attr)
  477. # Sometimes, probably due to a bug in Python itself, we are being called even
  478. # though a slot of the same name exists.
  479. try:
  480. return self._config_reader.get(attr)
  481. except cp.NoOptionError:
  482. return super().__getattr__(attr)
  483. # END handle exception
  484. def _config_section_name(self) -> str:
  485. return 'remote "%s"' % self.name
  486. def _set_cache_(self, attr: str) -> None:
  487. if attr == "_config_reader":
  488. # NOTE: This is cached as __getattr__ is overridden to return remote config
  489. # values implicitly, such as in print(r.pushurl).
  490. self._config_reader = SectionConstraint(
  491. self.repo.config_reader("repository"),
  492. self._config_section_name(),
  493. )
  494. else:
  495. super()._set_cache_(attr)
  496. def __str__(self) -> str:
  497. return self.name
  498. def __repr__(self) -> str:
  499. return '<git.%s "%s">' % (self.__class__.__name__, self.name)
  500. def __eq__(self, other: object) -> bool:
  501. return isinstance(other, type(self)) and self.name == other.name
  502. def __ne__(self, other: object) -> bool:
  503. return not (self == other)
  504. def __hash__(self) -> int:
  505. return hash(self.name)
  506. def exists(self) -> bool:
  507. """
  508. :return:
  509. ``True`` if this is a valid, existing remote.
  510. Valid remotes have an entry in the repository's configuration.
  511. """
  512. try:
  513. self.config_reader.get("url")
  514. return True
  515. except cp.NoOptionError:
  516. # We have the section at least...
  517. return True
  518. except cp.NoSectionError:
  519. return False
  520. @classmethod
  521. def iter_items(cls, repo: "Repo", *args: Any, **kwargs: Any) -> Iterator["Remote"]:
  522. """:return: Iterator yielding :class:`Remote` objects of the given repository"""
  523. for section in repo.config_reader("repository").sections():
  524. if not section.startswith("remote "):
  525. continue
  526. lbound = section.find('"')
  527. rbound = section.rfind('"')
  528. if lbound == -1 or rbound == -1:
  529. raise ValueError("Remote-Section has invalid format: %r" % section)
  530. yield Remote(repo, section[lbound + 1 : rbound])
  531. # END for each configuration section
  532. def set_url(
  533. self, new_url: str, old_url: Optional[str] = None, allow_unsafe_protocols: bool = False, **kwargs: Any
  534. ) -> "Remote":
  535. """Configure URLs on current remote (cf. command ``git remote set-url``).
  536. This command manages URLs on the remote.
  537. :param new_url:
  538. String being the URL to add as an extra remote URL.
  539. :param old_url:
  540. When set, replaces this URL with `new_url` for the remote.
  541. :param allow_unsafe_protocols:
  542. Allow unsafe protocols to be used, like ``ext``.
  543. :return:
  544. self
  545. """
  546. if not allow_unsafe_protocols:
  547. Git.check_unsafe_protocols(new_url)
  548. scmd = "set-url"
  549. kwargs["insert_kwargs_after"] = scmd
  550. if old_url:
  551. self.repo.git.remote(scmd, "--", self.name, new_url, old_url, **kwargs)
  552. else:
  553. self.repo.git.remote(scmd, "--", self.name, new_url, **kwargs)
  554. return self
  555. def add_url(self, url: str, allow_unsafe_protocols: bool = False, **kwargs: Any) -> "Remote":
  556. """Adds a new url on current remote (special case of ``git remote set-url``).
  557. This command adds new URLs to a given remote, making it possible to have
  558. multiple URLs for a single remote.
  559. :param url:
  560. String being the URL to add as an extra remote URL.
  561. :param allow_unsafe_protocols:
  562. Allow unsafe protocols to be used, like ``ext``.
  563. :return:
  564. self
  565. """
  566. return self.set_url(url, add=True, allow_unsafe_protocols=allow_unsafe_protocols)
  567. def delete_url(self, url: str, **kwargs: Any) -> "Remote":
  568. """Deletes a new url on current remote (special case of ``git remote set-url``).
  569. This command deletes new URLs to a given remote, making it possible to have
  570. multiple URLs for a single remote.
  571. :param url:
  572. String being the URL to delete from the remote.
  573. :return:
  574. self
  575. """
  576. return self.set_url(url, delete=True)
  577. @property
  578. def urls(self) -> Iterator[str]:
  579. """:return: Iterator yielding all configured URL targets on a remote as strings"""
  580. try:
  581. remote_details = self.repo.git.remote("get-url", "--all", self.name)
  582. assert isinstance(remote_details, str)
  583. for line in remote_details.split("\n"):
  584. yield line
  585. except GitCommandError as ex:
  586. ## We are on git < 2.7 (i.e TravisCI as of Oct-2016),
  587. # so `get-utl` command does not exist yet!
  588. # see: https://github.com/gitpython-developers/GitPython/pull/528#issuecomment-252976319
  589. # and: http://stackoverflow.com/a/32991784/548792
  590. #
  591. if "Unknown subcommand: get-url" in str(ex):
  592. try:
  593. remote_details = self.repo.git.remote("show", self.name)
  594. assert isinstance(remote_details, str)
  595. for line in remote_details.split("\n"):
  596. if " Push URL:" in line:
  597. yield line.split(": ")[-1]
  598. except GitCommandError as _ex:
  599. if any(msg in str(_ex) for msg in ["correct access rights", "cannot run ssh"]):
  600. # If ssh is not setup to access this repository, see issue 694.
  601. remote_details = self.repo.git.config("--get-all", "remote.%s.url" % self.name)
  602. assert isinstance(remote_details, str)
  603. for line in remote_details.split("\n"):
  604. yield line
  605. else:
  606. raise _ex
  607. else:
  608. raise ex
  609. @property
  610. def refs(self) -> IterableList[RemoteReference]:
  611. """
  612. :return:
  613. :class:`~git.util.IterableList` of :class:`~git.refs.remote.RemoteReference`
  614. objects.
  615. It is prefixed, allowing you to omit the remote path portion, e.g.::
  616. remote.refs.master # yields RemoteReference('/refs/remotes/origin/master')
  617. """
  618. out_refs: IterableList[RemoteReference] = IterableList(RemoteReference._id_attribute_, "%s/" % self.name)
  619. out_refs.extend(RemoteReference.list_items(self.repo, remote=self.name))
  620. return out_refs
  621. @property
  622. def stale_refs(self) -> IterableList[Reference]:
  623. """
  624. :return:
  625. :class:`~git.util.IterableList` of :class:`~git.refs.remote.RemoteReference`
  626. objects that do not have a corresponding head in the remote reference
  627. anymore as they have been deleted on the remote side, but are still
  628. available locally.
  629. The :class:`~git.util.IterableList` is prefixed, hence the 'origin' must be
  630. omitted. See :attr:`refs` property for an example.
  631. To make things more complicated, it can be possible for the list to include
  632. other kinds of references, for example, tag references, if these are stale
  633. as well. This is a fix for the issue described here:
  634. https://github.com/gitpython-developers/GitPython/issues/260
  635. """
  636. out_refs: IterableList[Reference] = IterableList(RemoteReference._id_attribute_, "%s/" % self.name)
  637. for line in self.repo.git.remote("prune", "--dry-run", self).splitlines()[2:]:
  638. # expecting
  639. # * [would prune] origin/new_branch
  640. token = " * [would prune] "
  641. if not line.startswith(token):
  642. continue
  643. ref_name = line.replace(token, "")
  644. # Sometimes, paths start with a full ref name, like refs/tags/foo. See #260.
  645. if ref_name.startswith(Reference._common_path_default + "/"):
  646. out_refs.append(Reference.from_path(self.repo, ref_name))
  647. else:
  648. fqhn = "%s/%s" % (RemoteReference._common_path_default, ref_name)
  649. out_refs.append(RemoteReference(self.repo, fqhn))
  650. # END special case handling
  651. # END for each line
  652. return out_refs
  653. @classmethod
  654. def create(cls, repo: "Repo", name: str, url: str, allow_unsafe_protocols: bool = False, **kwargs: Any) -> "Remote":
  655. """Create a new remote to the given repository.
  656. :param repo:
  657. Repository instance that is to receive the new remote.
  658. :param name:
  659. Desired name of the remote.
  660. :param url:
  661. URL which corresponds to the remote's name.
  662. :param allow_unsafe_protocols:
  663. Allow unsafe protocols to be used, like ``ext``.
  664. :param kwargs:
  665. Additional arguments to be passed to the ``git remote add`` command.
  666. :return:
  667. New :class:`Remote` instance
  668. :raise git.exc.GitCommandError:
  669. In case an origin with that name already exists.
  670. """
  671. scmd = "add"
  672. kwargs["insert_kwargs_after"] = scmd
  673. url = Git.polish_url(url)
  674. if not allow_unsafe_protocols:
  675. Git.check_unsafe_protocols(url)
  676. repo.git.remote(scmd, "--", name, url, **kwargs)
  677. return cls(repo, name)
  678. # `add` is an alias.
  679. @classmethod
  680. def add(cls, repo: "Repo", name: str, url: str, **kwargs: Any) -> "Remote":
  681. return cls.create(repo, name, url, **kwargs)
  682. @classmethod
  683. def remove(cls, repo: "Repo", name: str) -> str:
  684. """Remove the remote with the given name.
  685. :return:
  686. The passed remote name to remove
  687. """
  688. repo.git.remote("rm", name)
  689. if isinstance(name, cls):
  690. name._clear_cache()
  691. return name
  692. @classmethod
  693. def rm(cls, repo: "Repo", name: str) -> str:
  694. """Alias of remove.
  695. Remove the remote with the given name.
  696. :return:
  697. The passed remote name to remove
  698. """
  699. return cls.remove(repo, name)
  700. def rename(self, new_name: str) -> "Remote":
  701. """Rename self to the given `new_name`.
  702. :return:
  703. self
  704. """
  705. if self.name == new_name:
  706. return self
  707. self.repo.git.remote("rename", self.name, new_name)
  708. self.name = new_name
  709. self._clear_cache()
  710. return self
  711. def update(self, **kwargs: Any) -> "Remote":
  712. """Fetch all changes for this remote, including new branches which will be
  713. forced in (in case your local remote branch is not part the new remote branch's
  714. ancestry anymore).
  715. :param kwargs:
  716. Additional arguments passed to ``git remote update``.
  717. :return:
  718. self
  719. """
  720. scmd = "update"
  721. kwargs["insert_kwargs_after"] = scmd
  722. self.repo.git.remote(scmd, self.name, **kwargs)
  723. return self
  724. def _get_fetch_info_from_stderr(
  725. self,
  726. proc: "Git.AutoInterrupt",
  727. progress: Union[Callable[..., Any], RemoteProgress, None],
  728. kill_after_timeout: Union[None, float] = None,
  729. ) -> IterableList["FetchInfo"]:
  730. progress = to_progress_instance(progress)
  731. # Skip first line as it is some remote info we are not interested in.
  732. output: IterableList["FetchInfo"] = IterableList("name")
  733. # Lines which are no progress are fetch info lines.
  734. # This also waits for the command to finish.
  735. # Skip some progress lines that don't provide relevant information.
  736. fetch_info_lines = []
  737. # Basically we want all fetch info lines which appear to be in regular form, and
  738. # thus have a command character. Everything else we ignore.
  739. cmds = set(FetchInfo._flag_map.keys())
  740. progress_handler = progress.new_message_handler()
  741. handle_process_output(
  742. proc,
  743. None,
  744. progress_handler,
  745. finalizer=None,
  746. decode_streams=False,
  747. kill_after_timeout=kill_after_timeout,
  748. )
  749. stderr_text = progress.error_lines and "\n".join(progress.error_lines) or ""
  750. proc.wait(stderr=stderr_text)
  751. if stderr_text:
  752. _logger.warning("Error lines received while fetching: %s", stderr_text)
  753. for line in progress.other_lines:
  754. line = force_text(line)
  755. for cmd in cmds:
  756. if len(line) > 1 and line[0] == " " and line[1] == cmd:
  757. fetch_info_lines.append(line)
  758. continue
  759. # Read head information.
  760. fetch_head = SymbolicReference(self.repo, "FETCH_HEAD")
  761. with open(fetch_head.abspath, "rb") as fp:
  762. fetch_head_info = [line.decode(defenc) for line in fp.readlines()]
  763. l_fil = len(fetch_info_lines)
  764. l_fhi = len(fetch_head_info)
  765. if l_fil != l_fhi:
  766. msg = "Fetch head lines do not match lines provided via progress information\n"
  767. msg += "length of progress lines %i should be equal to lines in FETCH_HEAD file %i\n"
  768. msg += "Will ignore extra progress lines or fetch head lines."
  769. msg %= (l_fil, l_fhi)
  770. _logger.debug(msg)
  771. _logger.debug(b"info lines: " + str(fetch_info_lines).encode("UTF-8"))
  772. _logger.debug(b"head info: " + str(fetch_head_info).encode("UTF-8"))
  773. if l_fil < l_fhi:
  774. fetch_head_info = fetch_head_info[:l_fil]
  775. else:
  776. fetch_info_lines = fetch_info_lines[:l_fhi]
  777. # END truncate correct list
  778. # END sanity check + sanitization
  779. for err_line, fetch_line in zip(fetch_info_lines, fetch_head_info):
  780. try:
  781. output.append(FetchInfo._from_line(self.repo, err_line, fetch_line))
  782. except ValueError as exc:
  783. _logger.debug("Caught error while parsing line: %s", exc)
  784. _logger.warning("Git informed while fetching: %s", err_line.strip())
  785. return output
  786. def _get_push_info(
  787. self,
  788. proc: "Git.AutoInterrupt",
  789. progress: Union[Callable[..., Any], RemoteProgress, None],
  790. kill_after_timeout: Union[None, float] = None,
  791. ) -> PushInfoList:
  792. progress = to_progress_instance(progress)
  793. # Read progress information from stderr.
  794. # We hope stdout can hold all the data, it should...
  795. # Read the lines manually as it will use carriage returns between the messages
  796. # to override the previous one. This is why we read the bytes manually.
  797. progress_handler = progress.new_message_handler()
  798. output: PushInfoList = PushInfoList()
  799. def stdout_handler(line: str) -> None:
  800. try:
  801. output.append(PushInfo._from_line(self, line))
  802. except ValueError:
  803. # If an error happens, additional info is given which we parse below.
  804. pass
  805. handle_process_output(
  806. proc,
  807. stdout_handler,
  808. progress_handler,
  809. finalizer=None,
  810. decode_streams=False,
  811. kill_after_timeout=kill_after_timeout,
  812. )
  813. stderr_text = progress.error_lines and "\n".join(progress.error_lines) or ""
  814. try:
  815. proc.wait(stderr=stderr_text)
  816. except Exception as e:
  817. # This is different than fetch (which fails if there is any stderr
  818. # even if there is an output).
  819. if not output:
  820. raise
  821. elif stderr_text:
  822. _logger.warning("Error lines received while fetching: %s", stderr_text)
  823. output.error = e
  824. return output
  825. def _assert_refspec(self) -> None:
  826. """Turns out we can't deal with remotes if the refspec is missing."""
  827. config = self.config_reader
  828. unset = "placeholder"
  829. try:
  830. if config.get_value("fetch", default=unset) is unset:
  831. msg = "Remote '%s' has no refspec set.\n"
  832. msg += "You can set it as follows:"
  833. msg += " 'git config --add \"remote.%s.fetch +refs/heads/*:refs/heads/*\"'."
  834. raise AssertionError(msg % (self.name, self.name))
  835. finally:
  836. config.release()
  837. def fetch(
  838. self,
  839. refspec: Union[str, List[str], None] = None,
  840. progress: Union[RemoteProgress, None, "UpdateProgress"] = None,
  841. verbose: bool = True,
  842. kill_after_timeout: Union[None, float] = None,
  843. allow_unsafe_protocols: bool = False,
  844. allow_unsafe_options: bool = False,
  845. **kwargs: Any,
  846. ) -> IterableList[FetchInfo]:
  847. """Fetch the latest changes for this remote.
  848. :param refspec:
  849. A "refspec" is used by fetch and push to describe the mapping
  850. between remote ref and local ref. They are combined with a colon in
  851. the format ``<src>:<dst>``, preceded by an optional plus sign, ``+``.
  852. For example: ``git fetch $URL refs/heads/master:refs/heads/origin`` means
  853. "grab the master branch head from the $URL and store it as my origin
  854. branch head". And ``git push $URL refs/heads/master:refs/heads/to-upstream``
  855. means "publish my master branch head as to-upstream branch at $URL".
  856. See also :manpage:`git-push(1)`.
  857. Taken from the git manual, :manpage:`gitglossary(7)`.
  858. Fetch supports multiple refspecs (as the underlying :manpage:`git-fetch(1)`
  859. does) - supplying a list rather than a string for 'refspec' will make use of
  860. this facility.
  861. :param progress:
  862. See the :meth:`push` method.
  863. :param verbose:
  864. Boolean for verbose output.
  865. :param kill_after_timeout:
  866. To specify a timeout in seconds for the git command, after which the process
  867. should be killed. It is set to ``None`` by default.
  868. :param allow_unsafe_protocols:
  869. Allow unsafe protocols to be used, like ``ext``.
  870. :param allow_unsafe_options:
  871. Allow unsafe options to be used, like ``--upload-pack``.
  872. :param kwargs:
  873. Additional arguments to be passed to :manpage:`git-fetch(1)`.
  874. :return:
  875. IterableList(FetchInfo, ...) list of :class:`FetchInfo` instances providing
  876. detailed information about the fetch results
  877. :note:
  878. As fetch does not provide progress information to non-ttys, we cannot make
  879. it available here unfortunately as in the :meth:`push` method.
  880. """
  881. if refspec is None:
  882. # No argument refspec, then ensure the repo's config has a fetch refspec.
  883. self._assert_refspec()
  884. kwargs = add_progress(kwargs, self.repo.git, progress)
  885. if isinstance(refspec, list):
  886. args: Sequence[Optional[str]] = refspec
  887. else:
  888. args = [refspec]
  889. if not allow_unsafe_protocols:
  890. for ref in args:
  891. if ref:
  892. Git.check_unsafe_protocols(ref)
  893. if not allow_unsafe_options:
  894. Git.check_unsafe_options(options=list(kwargs.keys()), unsafe_options=self.unsafe_git_fetch_options)
  895. proc = self.repo.git.fetch(
  896. "--", self, *args, as_process=True, with_stdout=False, universal_newlines=True, v=verbose, **kwargs
  897. )
  898. res = self._get_fetch_info_from_stderr(proc, progress, kill_after_timeout=kill_after_timeout)
  899. if hasattr(self.repo.odb, "update_cache"):
  900. self.repo.odb.update_cache()
  901. return res
  902. def pull(
  903. self,
  904. refspec: Union[str, List[str], None] = None,
  905. progress: Union[RemoteProgress, "UpdateProgress", None] = None,
  906. kill_after_timeout: Union[None, float] = None,
  907. allow_unsafe_protocols: bool = False,
  908. allow_unsafe_options: bool = False,
  909. **kwargs: Any,
  910. ) -> IterableList[FetchInfo]:
  911. """Pull changes from the given branch, being the same as a fetch followed by a
  912. merge of branch with your local branch.
  913. :param refspec:
  914. See :meth:`fetch` method.
  915. :param progress:
  916. See :meth:`push` method.
  917. :param kill_after_timeout:
  918. See :meth:`fetch` method.
  919. :param allow_unsafe_protocols:
  920. Allow unsafe protocols to be used, like ``ext``.
  921. :param allow_unsafe_options:
  922. Allow unsafe options to be used, like ``--upload-pack``.
  923. :param kwargs:
  924. Additional arguments to be passed to :manpage:`git-pull(1)`.
  925. :return:
  926. Please see :meth:`fetch` method.
  927. """
  928. if refspec is None:
  929. # No argument refspec, then ensure the repo's config has a fetch refspec.
  930. self._assert_refspec()
  931. kwargs = add_progress(kwargs, self.repo.git, progress)
  932. refspec = Git._unpack_args(refspec or [])
  933. if not allow_unsafe_protocols:
  934. for ref in refspec:
  935. Git.check_unsafe_protocols(ref)
  936. if not allow_unsafe_options:
  937. Git.check_unsafe_options(options=list(kwargs.keys()), unsafe_options=self.unsafe_git_pull_options)
  938. proc = self.repo.git.pull(
  939. "--", self, refspec, with_stdout=False, as_process=True, universal_newlines=True, v=True, **kwargs
  940. )
  941. res = self._get_fetch_info_from_stderr(proc, progress, kill_after_timeout=kill_after_timeout)
  942. if hasattr(self.repo.odb, "update_cache"):
  943. self.repo.odb.update_cache()
  944. return res
  945. def push(
  946. self,
  947. refspec: Union[str, List[str], None] = None,
  948. progress: Union[RemoteProgress, "UpdateProgress", Callable[..., RemoteProgress], None] = None,
  949. kill_after_timeout: Union[None, float] = None,
  950. allow_unsafe_protocols: bool = False,
  951. allow_unsafe_options: bool = False,
  952. **kwargs: Any,
  953. ) -> PushInfoList:
  954. """Push changes from source branch in refspec to target branch in refspec.
  955. :param refspec:
  956. See :meth:`fetch` method.
  957. :param progress:
  958. Can take one of many value types:
  959. * ``None``, to discard progress information.
  960. * A function (callable) that is called with the progress information.
  961. Signature: ``progress(op_code, cur_count, max_count=None, message='')``.
  962. See :meth:`RemoteProgress.update <git.util.RemoteProgress.update>` for a
  963. description of all arguments given to the function.
  964. * An instance of a class derived from :class:`~git.util.RemoteProgress` that
  965. overrides the
  966. :meth:`RemoteProgress.update <git.util.RemoteProgress.update>` method.
  967. :note:
  968. No further progress information is returned after push returns.
  969. :param kill_after_timeout:
  970. To specify a timeout in seconds for the git command, after which the process
  971. should be killed. It is set to ``None`` by default.
  972. :param allow_unsafe_protocols:
  973. Allow unsafe protocols to be used, like ``ext``.
  974. :param allow_unsafe_options:
  975. Allow unsafe options to be used, like ``--receive-pack``.
  976. :param kwargs:
  977. Additional arguments to be passed to :manpage:`git-push(1)`.
  978. :return:
  979. A :class:`PushInfoList` object, where each list member represents an
  980. individual head which had been updated on the remote side.
  981. If the push contains rejected heads, these will have the
  982. :const:`PushInfo.ERROR` bit set in their flags.
  983. If the operation fails completely, the length of the returned
  984. :class:`PushInfoList` will be 0.
  985. Call :meth:`~PushInfoList.raise_if_error` on the returned object to raise on
  986. any failure.
  987. """
  988. kwargs = add_progress(kwargs, self.repo.git, progress)
  989. refspec = Git._unpack_args(refspec or [])
  990. if not allow_unsafe_protocols:
  991. for ref in refspec:
  992. Git.check_unsafe_protocols(ref)
  993. if not allow_unsafe_options:
  994. Git.check_unsafe_options(options=list(kwargs.keys()), unsafe_options=self.unsafe_git_push_options)
  995. proc = self.repo.git.push(
  996. "--",
  997. self,
  998. refspec,
  999. porcelain=True,
  1000. as_process=True,
  1001. universal_newlines=True,
  1002. kill_after_timeout=kill_after_timeout,
  1003. **kwargs,
  1004. )
  1005. return self._get_push_info(proc, progress, kill_after_timeout=kill_after_timeout)
  1006. @property
  1007. def config_reader(self) -> SectionConstraint[GitConfigParser]:
  1008. """
  1009. :return:
  1010. :class:`~git.config.GitConfigParser` compatible object able to read options
  1011. for only our remote. Hence you may simply type ``config.get("pushurl")`` to
  1012. obtain the information.
  1013. """
  1014. return self._config_reader
  1015. def _clear_cache(self) -> None:
  1016. try:
  1017. del self._config_reader
  1018. except AttributeError:
  1019. pass
  1020. # END handle exception
  1021. @property
  1022. def config_writer(self) -> SectionConstraint:
  1023. """
  1024. :return:
  1025. :class:`~git.config.GitConfigParser`-compatible object able to write options
  1026. for this remote.
  1027. :note:
  1028. You can only own one writer at a time - delete it to release the
  1029. configuration file and make it usable by others.
  1030. To assure consistent results, you should only query options through the
  1031. writer. Once you are done writing, you are free to use the config reader
  1032. once again.
  1033. """
  1034. writer = self.repo.config_writer()
  1035. # Clear our cache to ensure we re-read the possibly changed configuration.
  1036. self._clear_cache()
  1037. return SectionConstraint(writer, self._config_section_name())