A console script that allows you to easily update multiple git repositories at once
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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