A console script that allows you to easily update multiple git repositories at once
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

303 righe
11 KiB

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