A console script that allows you to easily update multiple git repositories at once
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

221 рядки
8.0 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. 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, 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 = "" if len(repos) == 1 else "s"
  157. print(BOLD + path, "({0} repo{1}):".format(len(repos), suffix))
  158. for repo in sorted(repos, key=lambda r: os.path.split(r.working_dir)[1]):
  159. _update_repository(repo, *update_args)
  160. def _update_directory(path, update_args):
  161. """Update a particular directory.
  162. Determine whether the directory is a git repo on its own, a directory of
  163. git repositories, or something invalid. If the first, update the single
  164. repository; if the second, update all repositories contained within; if the
  165. third, print an error.
  166. """
  167. try:
  168. repo = Repo(path)
  169. except exc.NoSuchPathError:
  170. print(ERROR, BOLD + path, "doesn't exist!")
  171. except exc.InvalidGitRepositoryError:
  172. if os.path.isdir(path):
  173. _update_subdirectories(path, update_args)
  174. else:
  175. print(ERROR, BOLD + path, "isn't a repository!")
  176. else:
  177. print(BOLD + repo.working_dir, "(1 repo):")
  178. _update_repository(repo, *update_args)
  179. def update_bookmarks(bookmarks, update_args):
  180. """Loop through and update all bookmarks."""
  181. if bookmarks:
  182. for path in bookmarks:
  183. _update_directory(path, update_args)
  184. else:
  185. print("You don't have any bookmarks configured! Get help with 'gitup -h'.")
  186. def update_directories(paths, update_args):
  187. """Update a list of directories supplied by command arguments."""
  188. for path in paths:
  189. full_path = os.path.abspath(path)
  190. _update_directory(full_path, update_args)