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

311 строки
11 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2011-2018 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. # Released under the terms of the MIT License. See LICENSE for details.
  5. import logging
  6. from glob import glob
  7. import os
  8. import re
  9. import shlex
  10. from colorama import Fore, Style
  11. from git import RemoteReference as RemoteRef, Repo, exc
  12. from git.util import RemoteProgress
  13. logger = logging.getLogger(__name__)
  14. __all__ = ["update_bookmarks", "update_directories", "run_command"]
  15. BOLD = Style.BRIGHT
  16. BLUE = Fore.BLUE + BOLD
  17. GREEN = Fore.GREEN + BOLD
  18. RED = Fore.RED + BOLD
  19. CYAN = Fore.CYAN + BOLD
  20. YELLOW = Fore.YELLOW + BOLD
  21. RESET = Style.RESET_ALL
  22. INDENT1 = " " * 3
  23. INDENT2 = " " * 7
  24. ERROR = RED + "Error:" + RESET
  25. class _ProgressMonitor(RemoteProgress):
  26. """Displays relevant output during the fetching process."""
  27. def __init__(self):
  28. super(_ProgressMonitor, self).__init__()
  29. self._started = False
  30. def update(self, op_code, cur_count, max_count=None, message=''):
  31. """Called whenever progress changes. Overrides default behavior."""
  32. if op_code & (self.COMPRESSING | self.RECEIVING):
  33. cur_count = str(int(cur_count))
  34. if max_count:
  35. max_count = str(int(max_count))
  36. if op_code & self.BEGIN:
  37. print("\b, " if self._started else " (", end="")
  38. if not self._started:
  39. self._started = True
  40. if op_code & self.END:
  41. end = ")"
  42. elif max_count:
  43. end = "\b" * (1 + len(cur_count) + len(max_count))
  44. else:
  45. end = "\b" * len(cur_count)
  46. if max_count:
  47. print("{0}/{1}".format(cur_count, max_count), end=end)
  48. else:
  49. print(str(cur_count), end=end)
  50. def _fetch_remotes(remotes, prune):
  51. """Fetch a list of remotes, displaying progress info along the way."""
  52. def _get_name(ref):
  53. """Return the local name of a remote or tag reference."""
  54. return ref.remote_head if isinstance(ref, RemoteRef) else ref.name
  55. # TODO: missing branch deleted (via --prune):
  56. info = [("NEW_HEAD", "new branch", "new branches"),
  57. ("NEW_TAG", "new tag", "new tags"),
  58. ("FAST_FORWARD", "branch update", "branch updates")]
  59. up_to_date = BLUE + "up to date" + RESET
  60. for remote in remotes:
  61. print(INDENT2, "Fetching", BOLD + remote.name, end="")
  62. if not remote.config_reader.has_option("fetch"):
  63. print(":", YELLOW + "skipped:", "no configured refspec.")
  64. continue
  65. try:
  66. results = remote.fetch(progress=_ProgressMonitor(), prune=prune)
  67. except exc.GitCommandError as err:
  68. # We should have to do this ourselves, but GitPython doesn't give
  69. # us a sensible way to get the raw stderr...
  70. msg = re.sub(r"\s+", " ", err.stderr).strip()
  71. msg = re.sub(r"^stderr: *'(fatal: *)?", "", msg).strip("'")
  72. if not msg:
  73. command = " ".join(shlex.quote(arg) for arg in err.command)
  74. msg = "{0} failed with status {1}.".format(command, err.status)
  75. elif not msg.endswith("."):
  76. msg += "."
  77. print(":", RED + "error:", msg)
  78. return
  79. except AssertionError: # Seems to be the result of a bug in GitPython
  80. # This happens when git initiates an auto-gc during fetch:
  81. print(":", RED + "error:", "something went wrong in GitPython,",
  82. "but the fetch might have been successful.")
  83. return
  84. rlist = []
  85. for attr, singular, plural in info:
  86. names = [_get_name(res.ref)
  87. for res in results if res.flags & getattr(res, attr)]
  88. if names:
  89. desc = singular if len(names) == 1 else plural
  90. colored = GREEN + desc + RESET
  91. rlist.append("{0} ({1})".format(colored, ", ".join(names)))
  92. print(":", (", ".join(rlist) if rlist else up_to_date) + ".")
  93. def _update_branch(repo, branch, is_active=False):
  94. """Update a single branch."""
  95. print(INDENT2, "Updating", BOLD + branch.name, end=": ")
  96. upstream = branch.tracking_branch()
  97. if not upstream:
  98. print(YELLOW + "skipped:", "no upstream is tracked.")
  99. return
  100. try:
  101. branch.commit
  102. except ValueError:
  103. print(YELLOW + "skipped:", "branch has no revisions.")
  104. return
  105. try:
  106. upstream.commit
  107. except ValueError:
  108. print(YELLOW + "skipped:", "upstream does not exist.")
  109. return
  110. try:
  111. base = repo.git.merge_base(branch.commit, upstream.commit)
  112. except exc.GitCommandError as err:
  113. logger.debug(err)
  114. print(YELLOW + "skipped:", "can't find merge base with upstream.")
  115. return
  116. if repo.commit(base) == upstream.commit:
  117. print(BLUE + "up to date", end=".\n")
  118. return
  119. if is_active:
  120. try:
  121. repo.git.merge(upstream.name, ff_only=True)
  122. print(GREEN + "done", end=".\n")
  123. except exc.GitCommandError as err:
  124. msg = err.stderr
  125. if "local changes" in msg and "would be overwritten" in msg:
  126. print(YELLOW + "skipped:", "uncommitted changes.")
  127. else:
  128. print(YELLOW + "skipped:", "not possible to fast-forward.")
  129. else:
  130. status = repo.git.merge_base(
  131. branch.commit, upstream.commit, is_ancestor=True,
  132. with_extended_output=True, with_exceptions=False)[0]
  133. if status != 0:
  134. print(YELLOW + "skipped:", "not possible to fast-forward.")
  135. else:
  136. repo.git.branch(branch.name, upstream.name, force=True)
  137. print(GREEN + "done", end=".\n")
  138. def _update_repository(repo, repo_name, args):
  139. """Update a single git repository by fetching remotes and rebasing/merging.
  140. The specific actions depend on the arguments given. We will fetch all
  141. remotes if *args.current_only* is ``False``, or only the remote tracked by
  142. the current branch if ``True``. If *args.fetch_only* is ``False``, we will
  143. also update all fast-forwardable branches that are tracking valid
  144. upstreams. If *args.prune* is ``True``, remote-tracking branches that no
  145. longer exist on their remote after fetching will be deleted.
  146. """
  147. print(INDENT1, BOLD + repo_name + ":")
  148. try:
  149. active = repo.active_branch
  150. except TypeError: # Happens when HEAD is detached
  151. active = None
  152. if args.current_only:
  153. if not active:
  154. print(INDENT2, ERROR,
  155. "--current-only doesn't make sense with a detached HEAD.")
  156. return
  157. ref = active.tracking_branch()
  158. if not ref:
  159. print(INDENT2, ERROR, "no remote tracked by current branch.")
  160. return
  161. remotes = [repo.remotes[ref.remote_name]]
  162. else:
  163. remotes = repo.remotes
  164. if not remotes:
  165. print(INDENT2, ERROR, "no remotes configured to fetch.")
  166. return
  167. _fetch_remotes(remotes, args.prune)
  168. if not args.fetch_only:
  169. for branch in sorted(repo.heads, key=lambda b: b.name):
  170. _update_branch(repo, branch, branch == active)
  171. def _run_command(repo, repo_name, args):
  172. """Run an arbitrary shell command on the given repository."""
  173. print(INDENT1, BOLD + repo_name + ":")
  174. cmd = shlex.split(args.command)
  175. try:
  176. out = repo.git.execute(
  177. cmd, with_extended_output=True, with_exceptions=False)
  178. except exc.GitCommandNotFound as err:
  179. print(INDENT2, ERROR, err)
  180. return
  181. for line in out[1].splitlines() + out[2].splitlines():
  182. print(INDENT2, line)
  183. def _dispatch(base_path, callback, args):
  184. """Apply a callback function on each valid repo in the given path.
  185. Determine whether the directory is a git repo on its own, a directory of
  186. git repositories, a shell glob pattern, or something invalid. If the first,
  187. apply the callback on it; if the second or third, apply the callback on all
  188. repositories contained within; if the last, print an error.
  189. The given args are passed directly to the callback function after the repo.
  190. """
  191. def _collect(paths, max_depth):
  192. """Return all valid repo paths in the given paths, recursively."""
  193. if max_depth == 0:
  194. return []
  195. valid = []
  196. for path in paths:
  197. try:
  198. Repo(path)
  199. valid.append(path)
  200. except exc.InvalidGitRepositoryError:
  201. if not os.path.isdir(path):
  202. continue
  203. children = [os.path.join(path, it) for it in os.listdir(path)]
  204. valid += _collect(children, max_depth - 1)
  205. except exc.NoSuchPathError:
  206. continue
  207. return valid
  208. def _get_basename(base, path):
  209. """Return a reasonable name for a repo path in the given base."""
  210. if path.startswith(base + os.path.sep):
  211. return path.split(base + os.path.sep, 1)[1]
  212. prefix = os.path.commonprefix([base, path])
  213. while not base.startswith(prefix + os.path.sep):
  214. old = prefix
  215. prefix = os.path.split(prefix)[0]
  216. if prefix == old:
  217. break # Prevent infinite loop, but should be almost impossible
  218. return path.split(prefix + os.path.sep, 1)[1]
  219. base = os.path.expanduser(base_path)
  220. max_depth = args.max_depth
  221. if max_depth >= 0:
  222. max_depth += 1
  223. try:
  224. Repo(base)
  225. valid = [base]
  226. except exc.NoSuchPathError:
  227. if is_comment(base):
  228. comment = get_comment(base)
  229. if comment:
  230. print(CYAN + BOLD + comment)
  231. return
  232. paths = glob(base)
  233. if not paths:
  234. print(ERROR, BOLD + base, "doesn't exist!")
  235. return
  236. valid = _collect(paths, max_depth)
  237. except exc.InvalidGitRepositoryError:
  238. if not os.path.isdir(base) or args.max_depth == 0:
  239. print(ERROR, BOLD + base, "isn't a repository!")
  240. return
  241. valid = _collect([base], max_depth)
  242. base = os.path.abspath(base)
  243. suffix = "" if len(valid) == 1 else "s"
  244. print(BOLD + base, "({0} repo{1}):".format(len(valid), suffix))
  245. valid = [os.path.abspath(path) for path in valid]
  246. paths = [(_get_basename(base, path), path) for path in valid]
  247. for name, path in sorted(paths):
  248. callback(Repo(path), name, args)
  249. def is_comment(path):
  250. """Does the line start with a # symbol?"""
  251. return path.lstrip().startswith("#")
  252. def get_comment(path):
  253. """Return the string minus the comment symbol."""
  254. return path.lstrip().lstrip("#").strip()
  255. def update_bookmarks(bookmarks, args):
  256. """Loop through and update all bookmarks."""
  257. if not bookmarks:
  258. print("You don't have any bookmarks configured! Get help with 'gitup -h'.")
  259. return
  260. for path in bookmarks:
  261. _dispatch(path, _update_repository, args)
  262. def update_directories(paths, args):
  263. """Update a list of directories supplied by command arguments."""
  264. for path in paths:
  265. _dispatch(path, _update_repository, args)
  266. def run_command(paths, args):
  267. """Run an arbitrary shell command on all repos."""
  268. for path in paths:
  269. _dispatch(path, _run_command, args)