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.

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