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.

297 linhas
11 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2011-2014 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. # See the LICENSE file 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. class _Stasher(object):
  46. """Manages the stash state of a given repository."""
  47. def __init__(self, repo):
  48. self._repo = repo
  49. self._clean = self._stashed = False
  50. def clean(self):
  51. """Ensure the working directory is clean, so we can do checkouts."""
  52. if not self._clean:
  53. res = self._repo.git.stash("--all")
  54. self._clean = True
  55. if res != "No local changes to save":
  56. self._stashed = True
  57. def restore(self):
  58. """Restore the pre-stash state."""
  59. if self._stashed:
  60. self._repo.git.stash("pop", "--index")
  61. def _read_config(repo, attr):
  62. """Read an attribute from git config."""
  63. try:
  64. return repo.git.config("--get", attr)
  65. except exc.GitCommandError:
  66. return None
  67. def _fetch_remotes(remotes):
  68. """Fetch a list of remotes, displaying progress info along the way."""
  69. def _get_name(ref):
  70. """Return the local name of a remote or tag reference."""
  71. return ref.remote_head if isinstance(ref, RemoteRef) else ref.name
  72. info = [("NEW_HEAD", "new branch", "new branches"),
  73. ("NEW_TAG", "new tag", "new tags"),
  74. ("FAST_FORWARD", "branch update", "branch updates")]
  75. up_to_date = BLUE + "up to date" + RESET
  76. for remote in remotes:
  77. print(INDENT2, "Fetching", BOLD + remote.name, end="")
  78. try:
  79. results = remote.fetch(progress=_ProgressMonitor())
  80. except exc.GitCommandError as err:
  81. msg = err.command[0].replace("Error when fetching: ", "")
  82. if not msg.endswith("."):
  83. msg += "."
  84. print(":", RED + "error:", msg)
  85. return
  86. except AssertionError: # Seems to be the result of a bug in GitPython
  87. # This happens when git initiates an auto-gc during fetch:
  88. print(":", RED + "error:", "something went wrong in GitPython,",
  89. "but the fetch might have been successful.")
  90. return
  91. rlist = []
  92. for attr, singular, plural in info:
  93. names = [_get_name(res.ref)
  94. for res in results if res.flags & getattr(res, attr)]
  95. if names:
  96. desc = singular if len(names) == 1 else plural
  97. colored = GREEN + desc + RESET
  98. rlist.append("{0} ({1})".format(colored, ", ".join(names)))
  99. print(":", (", ".join(rlist) if rlist else up_to_date) + ".")
  100. def _is_up_to_date(repo, branch, upstream):
  101. """Return whether *branch* is up-to-date with its *upstream*."""
  102. base = repo.git.merge_base(branch.commit, upstream.commit)
  103. return repo.commit(base) == upstream.commit
  104. def _rebase(repo, name):
  105. """Rebase the current HEAD of *repo* onto the branch *name*."""
  106. print(GREEN + "rebasing...", end="")
  107. try:
  108. res = repo.git.rebase(name, "--preserve-merges")
  109. except exc.GitCommandError as err:
  110. msg = err.stderr.replace("\n", " ").strip()
  111. if not msg.endswith("."):
  112. msg += "."
  113. if "unstaged changes" in msg:
  114. print(RED + " error:", "unstaged changes.")
  115. elif "uncommitted changes" in msg:
  116. print(RED + " error:", "uncommitted changes.")
  117. else:
  118. try:
  119. repo.git.rebase("--abort")
  120. except exc.GitCommandError:
  121. pass
  122. print(RED + " error:", msg if msg else "rebase conflict.",
  123. "Aborted.")
  124. else:
  125. print("\b" * 6 + " " * 6 + "\b" * 6 + GREEN + "ed", end=".\n")
  126. def _merge(repo, name):
  127. """Merge the branch *name* into the current HEAD of *repo*."""
  128. print(GREEN + "merging...", end="")
  129. try:
  130. repo.git.merge(name)
  131. except exc.GitCommandError as err:
  132. msg = err.stderr.replace("\n", " ").strip()
  133. if not msg.endswith("."):
  134. msg += "."
  135. if "local changes" in msg and "would be overwritten" in msg:
  136. print(RED + " error:", "uncommitted changes.")
  137. else:
  138. try:
  139. repo.git.merge("--abort")
  140. except exc.GitCommandError:
  141. pass
  142. print(RED + " error:", msg if msg else "merge conflict.",
  143. "Aborted.")
  144. else:
  145. print("\b" * 6 + " " * 6 + "\b" * 6 + GREEN + "ed", end=".\n")
  146. def _update_branch(repo, branch, merge, rebase, stasher=None):
  147. """Update a single branch."""
  148. print(INDENT2, "Updating", BOLD + branch.name, end=": ")
  149. upstream = branch.tracking_branch()
  150. if not upstream:
  151. print(YELLOW + "skipped:", "no upstream is tracked.")
  152. return
  153. try:
  154. branch.commit, upstream.commit
  155. except ValueError:
  156. print(YELLOW + "skipped:", "branch has no revisions.")
  157. return
  158. if _is_up_to_date(repo, branch, upstream):
  159. print(BLUE + "up to date", end=".\n")
  160. return
  161. if stasher:
  162. stasher.clean()
  163. branch.checkout()
  164. config_attr = "branch.{0}.rebase".format(branch.name)
  165. if not merge and (rebase or _read_config(repo, config_attr)):
  166. _rebase(repo, upstream.name)
  167. else:
  168. _merge(repo, upstream.name)
  169. def _update_branches(repo, active, merge, rebase):
  170. """Update a list of branches."""
  171. if active:
  172. _update_branch(repo, active, merge, rebase)
  173. branches = set(repo.heads) - {active}
  174. if branches:
  175. stasher = _Stasher(repo)
  176. try:
  177. for branch in sorted(branches, key=lambda b: b.name):
  178. _update_branch(repo, branch, merge, rebase, stasher)
  179. finally:
  180. if active:
  181. active.checkout()
  182. stasher.restore()
  183. def _update_repository(repo, current_only=False, rebase=False, merge=False):
  184. """Update a single git repository by fetching remotes and rebasing/merging.
  185. The specific actions depend on the arguments given. We will fetch all
  186. remotes if *current_only* is ``False``, or only the remote tracked by the
  187. current branch if ``True``. By default, we will merge unless
  188. ``pull.rebase`` or ``branch.<name>.rebase`` is set in config; *rebase* will
  189. cause us to always rebase with ``--preserve-merges``, and *merge* will
  190. cause us to always merge.
  191. """
  192. print(INDENT1, BOLD + os.path.split(repo.working_dir)[1] + ":")
  193. try:
  194. active = repo.active_branch
  195. except TypeError: # Happens when HEAD is detached
  196. active = None
  197. if current_only:
  198. ref = active.tracking_branch() if active else None
  199. if not ref:
  200. print(INDENT2, ERROR, "no remote tracked by current branch.")
  201. return
  202. remotes = [repo.remotes[ref.remote_name]]
  203. else:
  204. remotes = repo.remotes
  205. if not remotes:
  206. print(INDENT2, ERROR, "no remotes configured to pull from.")
  207. return
  208. rebase = rebase or _read_config(repo, "pull.rebase")
  209. _fetch_remotes(remotes)
  210. _update_branches(repo, active, merge, rebase)
  211. def _update_subdirectories(path, long_name, update_args):
  212. """Update all subdirectories that are git repos in a given directory."""
  213. repos = []
  214. for item in os.listdir(path):
  215. try:
  216. repo = Repo(os.path.join(path, item))
  217. except (exc.InvalidGitRepositoryError, exc.NoSuchPathError):
  218. continue
  219. repos.append(repo)
  220. suffix = "ies" if len(repos) != 1 else "y"
  221. print(long_name[0].upper() + long_name[1:],
  222. "contains {0} git repositor{1}:".format(len(repos), suffix))
  223. for repo in sorted(repos, key=lambda r: os.path.split(r.working_dir)[1]):
  224. _update_repository(repo, *update_args)
  225. def _update_directory(path, update_args, is_bookmark=False):
  226. """Update a particular directory.
  227. Determine whether the directory is a git repo on its own, a directory of
  228. git repositories, or something invalid. If the first, update the single
  229. repository; if the second, update all repositories contained within; if the
  230. third, print an error.
  231. """
  232. dir_type = "bookmark" if is_bookmark else "directory"
  233. long_name = dir_type + ' "' + BOLD + path + RESET + '"'
  234. try:
  235. repo = Repo(path)
  236. except exc.NoSuchPathError:
  237. print(ERROR, long_name, "doesn't exist!")
  238. except exc.InvalidGitRepositoryError:
  239. if os.path.isdir(path):
  240. _update_subdirectories(path, long_name, update_args)
  241. else:
  242. print(ERROR, long_name, "isn't a repository!")
  243. else:
  244. long_name = (dir_type.capitalize() + ' "' + BOLD + repo.working_dir +
  245. RESET + '"')
  246. print(long_name, "is a git repository:")
  247. _update_repository(repo, *update_args)
  248. def update_bookmarks(bookmarks, update_args):
  249. """Loop through and update all bookmarks."""
  250. if bookmarks:
  251. for path, name in bookmarks:
  252. _update_directory(path, update_args, is_bookmark=True)
  253. else:
  254. print("You don't have any bookmarks configured! Get help with 'gitup -h'.")
  255. def update_directories(paths, update_args):
  256. """Update a list of directories supplied by command arguments."""
  257. for path in paths:
  258. full_path = os.path.abspath(path)
  259. _update_directory(full_path, update_args, is_bookmark=False)