A console script that allows you to easily update multiple git repositories at once
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

update.py 8.3 KiB

há 10 anos
há 10 anos
há 10 anos
há 10 anos
há 10 anos
há 10 anos
há 10 anos
há 10 anos
há 10 anos
há 10 anos
há 10 anos
há 10 anos
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2011-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. # Released under the terms of the MIT License. See LICENSE for details.
  5. from __future__ import print_function
  6. import os
  7. from colorama import Fore, Style
  8. from git import RemoteReference as RemoteRef, Repo, exc
  9. from git.util import RemoteProgress
  10. __all__ = ["update_bookmarks", "update_directories"]
  11. BOLD = Style.BRIGHT
  12. BLUE = Fore.BLUE + BOLD
  13. GREEN = Fore.GREEN + BOLD
  14. RED = Fore.RED + BOLD
  15. YELLOW = Fore.YELLOW + BOLD
  16. RESET = Style.RESET_ALL
  17. INDENT1 = " " * 3
  18. INDENT2 = " " * 7
  19. ERROR = RED + "Error:" + RESET
  20. class _ProgressMonitor(RemoteProgress):
  21. """Displays relevant output during the fetching process."""
  22. def __init__(self):
  23. super(_ProgressMonitor, self).__init__()
  24. self._started = False
  25. def update(self, op_code, cur_count, max_count=None, message=''):
  26. """Called whenever progress changes. Overrides default behavior."""
  27. if op_code & (self.COMPRESSING | self.RECEIVING):
  28. cur_count = str(int(cur_count))
  29. if max_count:
  30. max_count = str(int(max_count))
  31. if op_code & self.BEGIN:
  32. print("\b, " if self._started else " (", end="")
  33. if not self._started:
  34. self._started = True
  35. if op_code & self.END:
  36. end = ")"
  37. elif max_count:
  38. end = "\b" * (1 + len(cur_count) + len(max_count))
  39. else:
  40. end = "\b" * len(cur_count)
  41. if max_count:
  42. print("{0}/{1}".format(cur_count, max_count), end=end)
  43. else:
  44. print(str(cur_count), end=end)
  45. def _fetch_remotes(remotes):
  46. """Fetch a list of remotes, displaying progress info along the way."""
  47. def _get_name(ref):
  48. """Return the local name of a remote or tag reference."""
  49. return ref.remote_head if isinstance(ref, RemoteRef) else ref.name
  50. info = [("NEW_HEAD", "new branch", "new branches"),
  51. ("NEW_TAG", "new tag", "new tags"),
  52. ("FAST_FORWARD", "branch update", "branch updates")]
  53. up_to_date = BLUE + "up to date" + RESET
  54. for remote in remotes:
  55. print(INDENT2, "Fetching", BOLD + remote.name, end="")
  56. if not remote.config_reader.has_option("fetch"):
  57. print(":", YELLOW + "skipped:", "no configured refspec.")
  58. continue
  59. try:
  60. results = remote.fetch(progress=_ProgressMonitor())
  61. except exc.GitCommandError as err:
  62. msg = err.command[0].replace("Error when fetching: ", "")
  63. if not msg.endswith("."):
  64. msg += "."
  65. print(":", RED + "error:", msg)
  66. return
  67. except AssertionError: # Seems to be the result of a bug in GitPython
  68. # This happens when git initiates an auto-gc during fetch:
  69. print(":", RED + "error:", "something went wrong in GitPython,",
  70. "but the fetch might have been successful.")
  71. return
  72. rlist = []
  73. for attr, singular, plural in info:
  74. names = [_get_name(res.ref)
  75. for res in results if res.flags & getattr(res, attr)]
  76. if names:
  77. desc = singular if len(names) == 1 else plural
  78. colored = GREEN + desc + RESET
  79. rlist.append("{0} ({1})".format(colored, ", ".join(names)))
  80. print(":", (", ".join(rlist) if rlist else up_to_date) + ".")
  81. def _update_branch(repo, branch, is_active=False):
  82. """Update a single branch."""
  83. print(INDENT2, "Updating", BOLD + branch.name, end=": ")
  84. upstream = branch.tracking_branch()
  85. if not upstream:
  86. print(YELLOW + "skipped:", "no upstream is tracked.")
  87. return
  88. try:
  89. branch.commit, upstream.commit
  90. except ValueError:
  91. print(YELLOW + "skipped:", "branch has no revisions.")
  92. return
  93. base = repo.git.merge_base(branch.commit, upstream.commit)
  94. if repo.commit(base) == upstream.commit:
  95. print(BLUE + "up to date", end=".\n")
  96. return
  97. if is_active:
  98. try:
  99. repo.git.merge(upstream.name, ff_only=True)
  100. print(GREEN + "done", end=".\n")
  101. except exc.GitCommandError as err:
  102. msg = err.stderr
  103. if "local changes" in msg and "would be overwritten" in msg:
  104. print(YELLOW + "skipped:", "uncommitted changes.")
  105. else:
  106. print(YELLOW + "skipped:", "not possible to fast-forward.")
  107. else:
  108. status = repo.git.merge_base(
  109. branch.commit, upstream.commit, is_ancestor=True,
  110. with_extended_output=True, with_exceptions=False)[0]
  111. if status != 0:
  112. print(YELLOW + "skipped:", "not possible to fast-forward.")
  113. else:
  114. repo.git.branch(branch.name, upstream.name, force=True)
  115. print(GREEN + "done", end=".\n")
  116. def _update_repository(repo, current_only=False, fetch_only=False):
  117. """Update a single git repository by fetching remotes and rebasing/merging.
  118. The specific actions depend on the arguments given. We will fetch all
  119. remotes if *current_only* is ``False``, or only the remote tracked by the
  120. current branch if ``True``. If *fetch_only* is ``False``, we will also
  121. update all fast-forwardable branches that are tracking valid upstreams.
  122. """
  123. print(INDENT1, BOLD + os.path.split(repo.working_dir)[1] + ":")
  124. try:
  125. active = repo.active_branch
  126. except TypeError: # Happens when HEAD is detached
  127. active = None
  128. if current_only:
  129. if not active:
  130. print(INDENT2, ERROR,
  131. "--current-only doesn't make sense with a detached HEAD.")
  132. return
  133. ref = active.tracking_branch()
  134. if not ref:
  135. print(INDENT2, ERROR, "no remote tracked by current branch.")
  136. return
  137. remotes = [repo.remotes[ref.remote_name]]
  138. else:
  139. remotes = repo.remotes
  140. if not remotes:
  141. print(INDENT2, ERROR, "no remotes configured to fetch.")
  142. return
  143. _fetch_remotes(remotes)
  144. if not fetch_only:
  145. for branch in sorted(repo.heads, key=lambda b: b.name):
  146. _update_branch(repo, branch, branch == active)
  147. def _update_subdirectories(path, long_name, update_args):
  148. """Update all subdirectories that are git repos in a given directory."""
  149. repos = []
  150. for item in os.listdir(path):
  151. try:
  152. repo = Repo(os.path.join(path, item))
  153. except (exc.InvalidGitRepositoryError, exc.NoSuchPathError):
  154. continue
  155. repos.append(repo)
  156. suffix = "ies" if len(repos) != 1 else "y"
  157. print(long_name[0].upper() + long_name[1:],
  158. "contains {0} git repositor{1}:".format(len(repos), suffix))
  159. for repo in sorted(repos, key=lambda r: os.path.split(r.working_dir)[1]):
  160. _update_repository(repo, *update_args)
  161. def _update_directory(path, update_args, is_bookmark=False):
  162. """Update a particular directory.
  163. Determine whether the directory is a git repo on its own, a directory of
  164. git repositories, or something invalid. If the first, update the single
  165. repository; if the second, update all repositories contained within; if the
  166. third, print an error.
  167. """
  168. dir_type = "bookmark" if is_bookmark else "directory"
  169. long_name = dir_type + ' "' + BOLD + path + RESET + '"'
  170. try:
  171. repo = Repo(path)
  172. except exc.NoSuchPathError:
  173. print(ERROR, long_name, "doesn't exist!")
  174. except exc.InvalidGitRepositoryError:
  175. if os.path.isdir(path):
  176. _update_subdirectories(path, long_name, update_args)
  177. else:
  178. print(ERROR, long_name, "isn't a repository!")
  179. else:
  180. long_name = (dir_type.capitalize() + ' "' + BOLD + repo.working_dir +
  181. RESET + '"')
  182. print(long_name, "is a git repository:")
  183. _update_repository(repo, *update_args)
  184. def update_bookmarks(bookmarks, update_args):
  185. """Loop through and update all bookmarks."""
  186. if bookmarks:
  187. for path, name in bookmarks:
  188. _update_directory(path, update_args, is_bookmark=True)
  189. else:
  190. print("You don't have any bookmarks configured! Get help with 'gitup -h'.")
  191. def update_directories(paths, update_args):
  192. """Update a list of directories supplied by command arguments."""
  193. for path in paths:
  194. full_path = os.path.abspath(path)
  195. _update_directory(full_path, update_args, is_bookmark=False)