您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

877 行
35KB

  1. # remote.py
  2. # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
  3. #
  4. # This module is part of GitPython and is released under
  5. # the BSD License: http://www.opensource.org/licenses/bsd-license.php
  6. # Module implementing a remote object allowing easy access to git remotes
  7. import logging
  8. import re
  9. from git.cmd import handle_process_output, Git
  10. from git.compat import (defenc, force_text, is_win)
  11. from git.exc import GitCommandError
  12. from git.util import (
  13. LazyMixin,
  14. Iterable,
  15. IterableList,
  16. RemoteProgress,
  17. CallableRemoteProgress
  18. )
  19. from git.util import (
  20. join_path,
  21. )
  22. import os.path as osp
  23. from .config import (
  24. SectionConstraint,
  25. cp,
  26. )
  27. from .refs import (
  28. Head,
  29. Reference,
  30. RemoteReference,
  31. SymbolicReference,
  32. TagReference
  33. )
  34. log = logging.getLogger('git.remote')
  35. log.addHandler(logging.NullHandler())
  36. __all__ = ('RemoteProgress', 'PushInfo', 'FetchInfo', 'Remote')
  37. #{ Utilities
  38. def add_progress(kwargs, git, progress):
  39. """Add the --progress flag to the given kwargs dict if supported by the
  40. git command. If the actual progress in the given progress instance is not
  41. given, we do not request any progress
  42. :return: possibly altered kwargs"""
  43. if progress is not None:
  44. v = git.version_info[:2]
  45. if v >= (1, 7):
  46. kwargs['progress'] = True
  47. # END handle --progress
  48. # END handle progress
  49. return kwargs
  50. #} END utilities
  51. def to_progress_instance(progress):
  52. """Given the 'progress' return a suitable object derived from
  53. RemoteProgress().
  54. """
  55. # new API only needs progress as a function
  56. if callable(progress):
  57. return CallableRemoteProgress(progress)
  58. # where None is passed create a parser that eats the progress
  59. elif progress is None:
  60. return RemoteProgress()
  61. # assume its the old API with an instance of RemoteProgress.
  62. else:
  63. return progress
  64. class PushInfo(object):
  65. """
  66. Carries information about the result of a push operation of a single head::
  67. info = remote.push()[0]
  68. info.flags # bitflags providing more information about the result
  69. info.local_ref # Reference pointing to the local reference that was pushed
  70. # It is None if the ref was deleted.
  71. info.remote_ref_string # path to the remote reference located on the remote side
  72. info.remote_ref # Remote Reference on the local side corresponding to
  73. # the remote_ref_string. It can be a TagReference as well.
  74. info.old_commit # commit at which the remote_ref was standing before we pushed
  75. # it to local_ref.commit. Will be None if an error was indicated
  76. info.summary # summary line providing human readable english text about the push
  77. """
  78. __slots__ = ('local_ref', 'remote_ref_string', 'flags', '_old_commit_sha', '_remote', 'summary')
  79. NEW_TAG, NEW_HEAD, NO_MATCH, REJECTED, REMOTE_REJECTED, REMOTE_FAILURE, DELETED, \
  80. FORCED_UPDATE, FAST_FORWARD, UP_TO_DATE, ERROR = [1 << x for x in range(11)]
  81. _flag_map = {'X': NO_MATCH,
  82. '-': DELETED,
  83. '*': 0,
  84. '+': FORCED_UPDATE,
  85. ' ': FAST_FORWARD,
  86. '=': UP_TO_DATE,
  87. '!': ERROR}
  88. def __init__(self, flags, local_ref, remote_ref_string, remote, old_commit=None,
  89. summary=''):
  90. """ Initialize a new instance """
  91. self.flags = flags
  92. self.local_ref = local_ref
  93. self.remote_ref_string = remote_ref_string
  94. self._remote = remote
  95. self._old_commit_sha = old_commit
  96. self.summary = summary
  97. @property
  98. def old_commit(self):
  99. return self._old_commit_sha and self._remote.repo.commit(self._old_commit_sha) or None
  100. @property
  101. def remote_ref(self):
  102. """
  103. :return:
  104. Remote Reference or TagReference in the local repository corresponding
  105. to the remote_ref_string kept in this instance."""
  106. # translate heads to a local remote, tags stay as they are
  107. if self.remote_ref_string.startswith("refs/tags"):
  108. return TagReference(self._remote.repo, self.remote_ref_string)
  109. elif self.remote_ref_string.startswith("refs/heads"):
  110. remote_ref = Reference(self._remote.repo, self.remote_ref_string)
  111. return RemoteReference(self._remote.repo, "refs/remotes/%s/%s" % (str(self._remote), remote_ref.name))
  112. else:
  113. raise ValueError("Could not handle remote ref: %r" % self.remote_ref_string)
  114. # END
  115. @classmethod
  116. def _from_line(cls, remote, line):
  117. """Create a new PushInfo instance as parsed from line which is expected to be like
  118. refs/heads/master:refs/heads/master 05d2687..1d0568e as bytes"""
  119. control_character, from_to, summary = line.split('\t', 3)
  120. flags = 0
  121. # control character handling
  122. try:
  123. flags |= cls._flag_map[control_character]
  124. except KeyError:
  125. raise ValueError("Control character %r unknown as parsed from line %r" % (control_character, line))
  126. # END handle control character
  127. # from_to handling
  128. from_ref_string, to_ref_string = from_to.split(':')
  129. if flags & cls.DELETED:
  130. from_ref = None
  131. else:
  132. from_ref = Reference.from_path(remote.repo, from_ref_string)
  133. # commit handling, could be message or commit info
  134. old_commit = None
  135. if summary.startswith('['):
  136. if "[rejected]" in summary:
  137. flags |= cls.REJECTED
  138. elif "[remote rejected]" in summary:
  139. flags |= cls.REMOTE_REJECTED
  140. elif "[remote failure]" in summary:
  141. flags |= cls.REMOTE_FAILURE
  142. elif "[no match]" in summary:
  143. flags |= cls.ERROR
  144. elif "[new tag]" in summary:
  145. flags |= cls.NEW_TAG
  146. elif "[new branch]" in summary:
  147. flags |= cls.NEW_HEAD
  148. # uptodate encoded in control character
  149. else:
  150. # fast-forward or forced update - was encoded in control character,
  151. # but we parse the old and new commit
  152. split_token = "..."
  153. if control_character == " ":
  154. split_token = ".."
  155. old_sha, new_sha = summary.split(' ')[0].split(split_token) # @UnusedVariable
  156. # have to use constructor here as the sha usually is abbreviated
  157. old_commit = old_sha
  158. # END message handling
  159. return PushInfo(flags, from_ref, to_ref_string, remote, old_commit, summary)
  160. class FetchInfo(object):
  161. """
  162. Carries information about the results of a fetch operation of a single head::
  163. info = remote.fetch()[0]
  164. info.ref # Symbolic Reference or RemoteReference to the changed
  165. # remote head or FETCH_HEAD
  166. info.flags # additional flags to be & with enumeration members,
  167. # i.e. info.flags & info.REJECTED
  168. # is 0 if ref is SymbolicReference
  169. info.note # additional notes given by git-fetch intended for the user
  170. info.old_commit # if info.flags & info.FORCED_UPDATE|info.FAST_FORWARD,
  171. # field is set to the previous location of ref, otherwise None
  172. info.remote_ref_path # The path from which we fetched on the remote. It's the remote's version of our info.ref
  173. """
  174. __slots__ = ('ref', 'old_commit', 'flags', 'note', 'remote_ref_path')
  175. NEW_TAG, NEW_HEAD, HEAD_UPTODATE, TAG_UPDATE, REJECTED, FORCED_UPDATE, \
  176. FAST_FORWARD, ERROR = [1 << x for x in range(8)]
  177. _re_fetch_result = re.compile(r'^\s*(.) (\[?[\w\s\.$@]+\]?)\s+(.+) -> ([^\s]+)( \(.*\)?$)?')
  178. _flag_map = {
  179. '!': ERROR,
  180. '+': FORCED_UPDATE,
  181. '*': 0,
  182. '=': HEAD_UPTODATE,
  183. ' ': FAST_FORWARD,
  184. '-': TAG_UPDATE,
  185. }
  186. @classmethod
  187. def refresh(cls):
  188. """This gets called by the refresh function (see the top level
  189. __init__).
  190. """
  191. # clear the old values in _flag_map
  192. try:
  193. del cls._flag_map["t"]
  194. except KeyError:
  195. pass
  196. try:
  197. del cls._flag_map["-"]
  198. except KeyError:
  199. pass
  200. # set the value given the git version
  201. if Git().version_info[:2] >= (2, 10):
  202. cls._flag_map["t"] = cls.TAG_UPDATE
  203. else:
  204. cls._flag_map["-"] = cls.TAG_UPDATE
  205. return True
  206. def __init__(self, ref, flags, note='', old_commit=None, remote_ref_path=None):
  207. """
  208. Initialize a new instance
  209. """
  210. self.ref = ref
  211. self.flags = flags
  212. self.note = note
  213. self.old_commit = old_commit
  214. self.remote_ref_path = remote_ref_path
  215. def __str__(self):
  216. return self.name
  217. @property
  218. def name(self):
  219. """:return: Name of our remote ref"""
  220. return self.ref.name
  221. @property
  222. def commit(self):
  223. """:return: Commit of our remote ref"""
  224. return self.ref.commit
  225. @classmethod
  226. def _from_line(cls, repo, line, fetch_line):
  227. """Parse information from the given line as returned by git-fetch -v
  228. and return a new FetchInfo object representing this information.
  229. We can handle a line as follows
  230. "%c %-*s %-*s -> %s%s"
  231. Where c is either ' ', !, +, -, *, or =
  232. ! means error
  233. + means success forcing update
  234. - means a tag was updated
  235. * means birth of new branch or tag
  236. = means the head was up to date ( and not moved )
  237. ' ' means a fast-forward
  238. fetch line is the corresponding line from FETCH_HEAD, like
  239. acb0fa8b94ef421ad60c8507b634759a472cd56c not-for-merge branch '0.1.7RC' of /tmp/tmpya0vairemote_repo"""
  240. match = cls._re_fetch_result.match(line)
  241. if match is None:
  242. raise ValueError("Failed to parse line: %r" % line)
  243. # parse lines
  244. control_character, operation, local_remote_ref, remote_local_ref, note = match.groups()
  245. try:
  246. new_hex_sha, fetch_operation, fetch_note = fetch_line.split("\t") # @UnusedVariable
  247. ref_type_name, fetch_note = fetch_note.split(' ', 1)
  248. except ValueError: # unpack error
  249. raise ValueError("Failed to parse FETCH_HEAD line: %r" % fetch_line)
  250. # parse flags from control_character
  251. flags = 0
  252. try:
  253. flags |= cls._flag_map[control_character]
  254. except KeyError:
  255. raise ValueError("Control character %r unknown as parsed from line %r" % (control_character, line))
  256. # END control char exception handling
  257. # parse operation string for more info - makes no sense for symbolic refs, but we parse it anyway
  258. old_commit = None
  259. is_tag_operation = False
  260. if 'rejected' in operation:
  261. flags |= cls.REJECTED
  262. if 'new tag' in operation:
  263. flags |= cls.NEW_TAG
  264. is_tag_operation = True
  265. if 'tag update' in operation:
  266. flags |= cls.TAG_UPDATE
  267. is_tag_operation = True
  268. if 'new branch' in operation:
  269. flags |= cls.NEW_HEAD
  270. if '...' in operation or '..' in operation:
  271. split_token = '...'
  272. if control_character == ' ':
  273. split_token = split_token[:-1]
  274. old_commit = repo.rev_parse(operation.split(split_token)[0])
  275. # END handle refspec
  276. # handle FETCH_HEAD and figure out ref type
  277. # If we do not specify a target branch like master:refs/remotes/origin/master,
  278. # the fetch result is stored in FETCH_HEAD which destroys the rule we usually
  279. # have. In that case we use a symbolic reference which is detached
  280. ref_type = None
  281. if remote_local_ref == "FETCH_HEAD":
  282. ref_type = SymbolicReference
  283. elif ref_type_name == "tag" or is_tag_operation:
  284. # the ref_type_name can be branch, whereas we are still seeing a tag operation. It happens during
  285. # testing, which is based on actual git operations
  286. ref_type = TagReference
  287. elif ref_type_name in ("remote-tracking", "branch"):
  288. # note: remote-tracking is just the first part of the 'remote-tracking branch' token.
  289. # We don't parse it correctly, but its enough to know what to do, and its new in git 1.7something
  290. ref_type = RemoteReference
  291. elif '/' in ref_type_name:
  292. # If the fetch spec look something like this '+refs/pull/*:refs/heads/pull/*', and is thus pretty
  293. # much anything the user wants, we will have trouble to determine what's going on
  294. # For now, we assume the local ref is a Head
  295. ref_type = Head
  296. else:
  297. raise TypeError("Cannot handle reference type: %r" % ref_type_name)
  298. # END handle ref type
  299. # create ref instance
  300. if ref_type is SymbolicReference:
  301. remote_local_ref = ref_type(repo, "FETCH_HEAD")
  302. else:
  303. # determine prefix. Tags are usually pulled into refs/tags, they may have subdirectories.
  304. # It is not clear sometimes where exactly the item is, unless we have an absolute path as indicated
  305. # by the 'ref/' prefix. Otherwise even a tag could be in refs/remotes, which is when it will have the
  306. # 'tags/' subdirectory in its path.
  307. # We don't want to test for actual existence, but try to figure everything out analytically.
  308. ref_path = None
  309. remote_local_ref = remote_local_ref.strip()
  310. if remote_local_ref.startswith(Reference._common_path_default + "/"):
  311. # always use actual type if we get absolute paths
  312. # Will always be the case if something is fetched outside of refs/remotes (if its not a tag)
  313. ref_path = remote_local_ref
  314. if ref_type is not TagReference and not \
  315. remote_local_ref.startswith(RemoteReference._common_path_default + "/"):
  316. ref_type = Reference
  317. # END downgrade remote reference
  318. elif ref_type is TagReference and 'tags/' in remote_local_ref:
  319. # even though its a tag, it is located in refs/remotes
  320. ref_path = join_path(RemoteReference._common_path_default, remote_local_ref)
  321. else:
  322. ref_path = join_path(ref_type._common_path_default, remote_local_ref)
  323. # END obtain refpath
  324. # even though the path could be within the git conventions, we make
  325. # sure we respect whatever the user wanted, and disabled path checking
  326. remote_local_ref = ref_type(repo, ref_path, check_path=False)
  327. # END create ref instance
  328. note = (note and note.strip()) or ''
  329. return cls(remote_local_ref, flags, note, old_commit, local_remote_ref)
  330. class Remote(LazyMixin, Iterable):
  331. """Provides easy read and write access to a git remote.
  332. Everything not part of this interface is considered an option for the current
  333. remote, allowing constructs like remote.pushurl to query the pushurl.
  334. NOTE: When querying configuration, the configuration accessor will be cached
  335. to speed up subsequent accesses."""
  336. __slots__ = ("repo", "name", "_config_reader")
  337. _id_attribute_ = "name"
  338. def __init__(self, repo, name):
  339. """Initialize a remote instance
  340. :param repo: The repository we are a remote of
  341. :param name: the name of the remote, i.e. 'origin'"""
  342. self.repo = repo
  343. self.name = name
  344. if is_win:
  345. # some oddity: on windows, python 2.5, it for some reason does not realize
  346. # that it has the config_writer property, but instead calls __getattr__
  347. # which will not yield the expected results. 'pinging' the members
  348. # with a dir call creates the config_writer property that we require
  349. # ... bugs like these make me wonder whether python really wants to be used
  350. # for production. It doesn't happen on linux though.
  351. dir(self)
  352. # END windows special handling
  353. def __getattr__(self, attr):
  354. """Allows to call this instance like
  355. remote.special( \\*args, \\*\\*kwargs) to call git-remote special self.name"""
  356. if attr == "_config_reader":
  357. return super(Remote, self).__getattr__(attr)
  358. # sometimes, probably due to a bug in python itself, we are being called
  359. # even though a slot of the same name exists
  360. try:
  361. return self._config_reader.get(attr)
  362. except cp.NoOptionError:
  363. return super(Remote, self).__getattr__(attr)
  364. # END handle exception
  365. def _config_section_name(self):
  366. return 'remote "%s"' % self.name
  367. def _set_cache_(self, attr):
  368. if attr == "_config_reader":
  369. # NOTE: This is cached as __getattr__ is overridden to return remote config values implicitly, such as
  370. # in print(r.pushurl)
  371. self._config_reader = SectionConstraint(self.repo.config_reader("repository"), self._config_section_name())
  372. else:
  373. super(Remote, self)._set_cache_(attr)
  374. def __str__(self):
  375. return self.name
  376. def __repr__(self):
  377. return '<git.%s "%s">' % (self.__class__.__name__, self.name)
  378. def __eq__(self, other):
  379. return self.name == other.name
  380. def __ne__(self, other):
  381. return not (self == other)
  382. def __hash__(self):
  383. return hash(self.name)
  384. def exists(self):
  385. """
  386. :return: True if this is a valid, existing remote.
  387. Valid remotes have an entry in the repository's configuration"""
  388. try:
  389. self.config_reader.get('url')
  390. return True
  391. except cp.NoOptionError:
  392. # we have the section at least ...
  393. return True
  394. except cp.NoSectionError:
  395. return False
  396. # end
  397. @classmethod
  398. def iter_items(cls, repo):
  399. """:return: Iterator yielding Remote objects of the given repository"""
  400. for section in repo.config_reader("repository").sections():
  401. if not section.startswith('remote '):
  402. continue
  403. lbound = section.find('"')
  404. rbound = section.rfind('"')
  405. if lbound == -1 or rbound == -1:
  406. raise ValueError("Remote-Section has invalid format: %r" % section)
  407. yield Remote(repo, section[lbound + 1:rbound])
  408. # END for each configuration section
  409. def set_url(self, new_url, old_url=None, **kwargs):
  410. """Configure URLs on current remote (cf command git remote set_url)
  411. This command manages URLs on the remote.
  412. :param new_url: string being the URL to add as an extra remote URL
  413. :param old_url: when set, replaces this URL with new_url for the remote
  414. :return: self
  415. """
  416. scmd = 'set-url'
  417. kwargs['insert_kwargs_after'] = scmd
  418. if old_url:
  419. self.repo.git.remote(scmd, self.name, new_url, old_url, **kwargs)
  420. else:
  421. self.repo.git.remote(scmd, self.name, new_url, **kwargs)
  422. return self
  423. def add_url(self, url, **kwargs):
  424. """Adds a new url on current remote (special case of git remote set_url)
  425. This command adds new URLs to a given remote, making it possible to have
  426. multiple URLs for a single remote.
  427. :param url: string being the URL to add as an extra remote URL
  428. :return: self
  429. """
  430. return self.set_url(url, add=True)
  431. def delete_url(self, url, **kwargs):
  432. """Deletes a new url on current remote (special case of git remote set_url)
  433. This command deletes new URLs to a given remote, making it possible to have
  434. multiple URLs for a single remote.
  435. :param url: string being the URL to delete from the remote
  436. :return: self
  437. """
  438. return self.set_url(url, delete=True)
  439. @property
  440. def urls(self):
  441. """:return: Iterator yielding all configured URL targets on a remote as strings"""
  442. try:
  443. remote_details = self.repo.git.remote("get-url", "--all", self.name)
  444. for line in remote_details.split('\n'):
  445. yield line
  446. except GitCommandError as ex:
  447. ## We are on git < 2.7 (i.e TravisCI as of Oct-2016),
  448. # so `get-utl` command does not exist yet!
  449. # see: https://github.com/gitpython-developers/GitPython/pull/528#issuecomment-252976319
  450. # and: http://stackoverflow.com/a/32991784/548792
  451. #
  452. if 'Unknown subcommand: get-url' in str(ex):
  453. try:
  454. remote_details = self.repo.git.remote("show", self.name)
  455. for line in remote_details.split('\n'):
  456. if ' Push URL:' in line:
  457. yield line.split(': ')[-1]
  458. except GitCommandError as ex:
  459. if any(msg in str(ex) for msg in ['correct access rights', 'cannot run ssh']):
  460. # If ssh is not setup to access this repository, see issue 694
  461. remote_details = self.repo.git.config('--get-all', 'remote.%s.url' % self.name)
  462. for line in remote_details.split('\n'):
  463. yield line
  464. else:
  465. raise ex
  466. else:
  467. raise ex
  468. @property
  469. def refs(self):
  470. """
  471. :return:
  472. IterableList of RemoteReference objects. It is prefixed, allowing
  473. you to omit the remote path portion, i.e.::
  474. remote.refs.master # yields RemoteReference('/refs/remotes/origin/master')"""
  475. out_refs = IterableList(RemoteReference._id_attribute_, "%s/" % self.name)
  476. out_refs.extend(RemoteReference.list_items(self.repo, remote=self.name))
  477. return out_refs
  478. @property
  479. def stale_refs(self):
  480. """
  481. :return:
  482. IterableList RemoteReference objects that do not have a corresponding
  483. head in the remote reference anymore as they have been deleted on the
  484. remote side, but are still available locally.
  485. The IterableList is prefixed, hence the 'origin' must be omitted. See
  486. 'refs' property for an example.
  487. To make things more complicated, it can be possible for the list to include
  488. other kinds of references, for example, tag references, if these are stale
  489. as well. This is a fix for the issue described here:
  490. https://github.com/gitpython-developers/GitPython/issues/260
  491. """
  492. out_refs = IterableList(RemoteReference._id_attribute_, "%s/" % self.name)
  493. for line in self.repo.git.remote("prune", "--dry-run", self).splitlines()[2:]:
  494. # expecting
  495. # * [would prune] origin/new_branch
  496. token = " * [would prune] "
  497. if not line.startswith(token):
  498. raise ValueError("Could not parse git-remote prune result: %r" % line)
  499. ref_name = line.replace(token, "")
  500. # sometimes, paths start with a full ref name, like refs/tags/foo, see #260
  501. if ref_name.startswith(Reference._common_path_default + '/'):
  502. out_refs.append(SymbolicReference.from_path(self.repo, ref_name))
  503. else:
  504. fqhn = "%s/%s" % (RemoteReference._common_path_default, ref_name)
  505. out_refs.append(RemoteReference(self.repo, fqhn))
  506. # end special case handling
  507. # END for each line
  508. return out_refs
  509. @classmethod
  510. def create(cls, repo, name, url, **kwargs):
  511. """Create a new remote to the given repository
  512. :param repo: Repository instance that is to receive the new remote
  513. :param name: Desired name of the remote
  514. :param url: URL which corresponds to the remote's name
  515. :param kwargs: Additional arguments to be passed to the git-remote add command
  516. :return: New Remote instance
  517. :raise GitCommandError: in case an origin with that name already exists"""
  518. scmd = 'add'
  519. kwargs['insert_kwargs_after'] = scmd
  520. repo.git.remote(scmd, name, Git.polish_url(url), **kwargs)
  521. return cls(repo, name)
  522. # add is an alias
  523. add = create
  524. @classmethod
  525. def remove(cls, repo, name):
  526. """Remove the remote with the given name
  527. :return: the passed remote name to remove
  528. """
  529. repo.git.remote("rm", name)
  530. if isinstance(name, cls):
  531. name._clear_cache()
  532. return name
  533. # alias
  534. rm = remove
  535. def rename(self, new_name):
  536. """Rename self to the given new_name
  537. :return: self """
  538. if self.name == new_name:
  539. return self
  540. self.repo.git.remote("rename", self.name, new_name)
  541. self.name = new_name
  542. self._clear_cache()
  543. return self
  544. def update(self, **kwargs):
  545. """Fetch all changes for this remote, including new branches which will
  546. be forced in ( in case your local remote branch is not part the new remote branches
  547. ancestry anymore ).
  548. :param kwargs:
  549. Additional arguments passed to git-remote update
  550. :return: self """
  551. scmd = 'update'
  552. kwargs['insert_kwargs_after'] = scmd
  553. self.repo.git.remote(scmd, self.name, **kwargs)
  554. return self
  555. def _get_fetch_info_from_stderr(self, proc, progress):
  556. progress = to_progress_instance(progress)
  557. # skip first line as it is some remote info we are not interested in
  558. output = IterableList('name')
  559. # lines which are no progress are fetch info lines
  560. # this also waits for the command to finish
  561. # Skip some progress lines that don't provide relevant information
  562. fetch_info_lines = []
  563. # Basically we want all fetch info lines which appear to be in regular form, and thus have a
  564. # command character. Everything else we ignore,
  565. cmds = set(FetchInfo._flag_map.keys())
  566. progress_handler = progress.new_message_handler()
  567. handle_process_output(proc, None, progress_handler, finalizer=None, decode_streams=False)
  568. stderr_text = progress.error_lines and '\n'.join(progress.error_lines) or ''
  569. proc.wait(stderr=stderr_text)
  570. if stderr_text:
  571. log.warning("Error lines received while fetching: %s", stderr_text)
  572. for line in progress.other_lines:
  573. line = force_text(line)
  574. for cmd in cmds:
  575. if len(line) > 1 and line[0] == ' ' and line[1] == cmd:
  576. fetch_info_lines.append(line)
  577. continue
  578. # read head information
  579. with open(osp.join(self.repo.common_dir, 'FETCH_HEAD'), 'rb') as fp:
  580. fetch_head_info = [l.decode(defenc) for l in fp.readlines()]
  581. l_fil = len(fetch_info_lines)
  582. l_fhi = len(fetch_head_info)
  583. if l_fil != l_fhi:
  584. msg = "Fetch head lines do not match lines provided via progress information\n"
  585. msg += "length of progress lines %i should be equal to lines in FETCH_HEAD file %i\n"
  586. msg += "Will ignore extra progress lines or fetch head lines."
  587. msg %= (l_fil, l_fhi)
  588. log.debug(msg)
  589. log.debug("info lines: " + str(fetch_info_lines))
  590. log.debug("head info : " + str(fetch_head_info))
  591. if l_fil < l_fhi:
  592. fetch_head_info = fetch_head_info[:l_fil]
  593. else:
  594. fetch_info_lines = fetch_info_lines[:l_fhi]
  595. # end truncate correct list
  596. # end sanity check + sanitization
  597. output.extend(FetchInfo._from_line(self.repo, err_line, fetch_line)
  598. for err_line, fetch_line in zip(fetch_info_lines, fetch_head_info))
  599. return output
  600. def _get_push_info(self, proc, progress):
  601. progress = to_progress_instance(progress)
  602. # read progress information from stderr
  603. # we hope stdout can hold all the data, it should ...
  604. # read the lines manually as it will use carriage returns between the messages
  605. # to override the previous one. This is why we read the bytes manually
  606. progress_handler = progress.new_message_handler()
  607. output = IterableList('name')
  608. def stdout_handler(line):
  609. try:
  610. output.append(PushInfo._from_line(self, line))
  611. except ValueError:
  612. # If an error happens, additional info is given which we parse below.
  613. pass
  614. handle_process_output(proc, stdout_handler, progress_handler, finalizer=None, decode_streams=False)
  615. stderr_text = progress.error_lines and '\n'.join(progress.error_lines) or ''
  616. try:
  617. proc.wait(stderr=stderr_text)
  618. except Exception:
  619. if not output:
  620. raise
  621. elif stderr_text:
  622. log.warning("Error lines received while fetching: %s", stderr_text)
  623. return output
  624. def _assert_refspec(self):
  625. """Turns out we can't deal with remotes if the refspec is missing"""
  626. config = self.config_reader
  627. unset = 'placeholder'
  628. try:
  629. if config.get_value('fetch', default=unset) is unset:
  630. msg = "Remote '%s' has no refspec set.\n"
  631. msg += "You can set it as follows:"
  632. msg += " 'git config --add \"remote.%s.fetch +refs/heads/*:refs/heads/*\"'."
  633. raise AssertionError(msg % (self.name, self.name))
  634. finally:
  635. config.release()
  636. def fetch(self, refspec=None, progress=None, **kwargs):
  637. """Fetch the latest changes for this remote
  638. :param refspec:
  639. A "refspec" is used by fetch and push to describe the mapping
  640. between remote ref and local ref. They are combined with a colon in
  641. the format <src>:<dst>, preceded by an optional plus sign, +.
  642. For example: git fetch $URL refs/heads/master:refs/heads/origin means
  643. "grab the master branch head from the $URL and store it as my origin
  644. branch head". And git push $URL refs/heads/master:refs/heads/to-upstream
  645. means "publish my master branch head as to-upstream branch at $URL".
  646. See also git-push(1).
  647. Taken from the git manual
  648. Fetch supports multiple refspecs (as the
  649. underlying git-fetch does) - supplying a list rather than a string
  650. for 'refspec' will make use of this facility.
  651. :param progress: See 'push' method
  652. :param kwargs: Additional arguments to be passed to git-fetch
  653. :return:
  654. IterableList(FetchInfo, ...) list of FetchInfo instances providing detailed
  655. information about the fetch results
  656. :note:
  657. As fetch does not provide progress information to non-ttys, we cannot make
  658. it available here unfortunately as in the 'push' method."""
  659. if refspec is None:
  660. # No argument refspec, then ensure the repo's config has a fetch refspec.
  661. self._assert_refspec()
  662. kwargs = add_progress(kwargs, self.repo.git, progress)
  663. if isinstance(refspec, list):
  664. args = refspec
  665. else:
  666. args = [refspec]
  667. proc = self.repo.git.fetch(self, *args, as_process=True, with_stdout=False,
  668. universal_newlines=True, v=True, **kwargs)
  669. res = self._get_fetch_info_from_stderr(proc, progress)
  670. if hasattr(self.repo.odb, 'update_cache'):
  671. self.repo.odb.update_cache()
  672. return res
  673. def pull(self, refspec=None, progress=None, **kwargs):
  674. """Pull changes from the given branch, being the same as a fetch followed
  675. by a merge of branch with your local branch.
  676. :param refspec: see 'fetch' method
  677. :param progress: see 'push' method
  678. :param kwargs: Additional arguments to be passed to git-pull
  679. :return: Please see 'fetch' method """
  680. if refspec is None:
  681. # No argument refspec, then ensure the repo's config has a fetch refspec.
  682. self._assert_refspec()
  683. kwargs = add_progress(kwargs, self.repo.git, progress)
  684. proc = self.repo.git.pull(self, refspec, with_stdout=False, as_process=True,
  685. universal_newlines=True, v=True, **kwargs)
  686. res = self._get_fetch_info_from_stderr(proc, progress)
  687. if hasattr(self.repo.odb, 'update_cache'):
  688. self.repo.odb.update_cache()
  689. return res
  690. def push(self, refspec=None, progress=None, **kwargs):
  691. """Push changes from source branch in refspec to target branch in refspec.
  692. :param refspec: see 'fetch' method
  693. :param progress:
  694. Can take one of many value types:
  695. * None to discard progress information
  696. * A function (callable) that is called with the progress information.
  697. Signature: ``progress(op_code, cur_count, max_count=None, message='')``.
  698. `Click here <http://goo.gl/NPa7st>`_ for a description of all arguments
  699. given to the function.
  700. * An instance of a class derived from ``git.RemoteProgress`` that
  701. overrides the ``update()`` function.
  702. :note: No further progress information is returned after push returns.
  703. :param kwargs: Additional arguments to be passed to git-push
  704. :return:
  705. IterableList(PushInfo, ...) iterable list of PushInfo instances, each
  706. one informing about an individual head which had been updated on the remote
  707. side.
  708. If the push contains rejected heads, these will have the PushInfo.ERROR bit set
  709. in their flags.
  710. If the operation fails completely, the length of the returned IterableList will
  711. be null."""
  712. kwargs = add_progress(kwargs, self.repo.git, progress)
  713. proc = self.repo.git.push(self, refspec, porcelain=True, as_process=True,
  714. universal_newlines=True, **kwargs)
  715. return self._get_push_info(proc, progress)
  716. @property
  717. def config_reader(self):
  718. """
  719. :return:
  720. GitConfigParser compatible object able to read options for only our remote.
  721. Hence you may simple type config.get("pushurl") to obtain the information"""
  722. return self._config_reader
  723. def _clear_cache(self):
  724. try:
  725. del(self._config_reader)
  726. except AttributeError:
  727. pass
  728. # END handle exception
  729. @property
  730. def config_writer(self):
  731. """
  732. :return: GitConfigParser compatible object able to write options for this remote.
  733. :note:
  734. You can only own one writer at a time - delete it to release the
  735. configuration file and make it usable by others.
  736. To assure consistent results, you should only query options through the
  737. writer. Once you are done writing, you are free to use the config reader
  738. once again."""
  739. writer = self.repo.config_writer()
  740. # clear our cache to assure we re-read the possibly changed configuration
  741. self._clear_cache()
  742. return SectionConstraint(writer, self._config_section_name())