A console script that allows you to easily update multiple git repositories at once
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

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