A console script that allows you to easily update multiple git repositories at once
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

update.py 10 KiB

hace 10 años
hace 10 años
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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, current_only, fetch_only, prune):
  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 *current_only* is ``False``, or only the remote tracked by the
  132. current branch if ``True``. If *fetch_only* is ``False``, we will also
  133. update all fast-forwardable branches that are tracking valid upstreams.
  134. If *prune* is ``True``, remote-tracking branches that no longer exist on
  135. 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 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, prune)
  158. if not 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, command):
  162. """Run an arbitrary shell command on the given repository."""
  163. print(INDENT1, BOLD + repo_name + ":")
  164. cmd = shlex.split(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, maxdepth=6):
  182. """Return all valid repo paths in the given paths, recursively."""
  183. if maxdepth <= 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, maxdepth=maxdepth-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. try:
  211. Repo(base)
  212. valid = [base]
  213. except exc.NoSuchPathError:
  214. paths = glob(base)
  215. if not paths:
  216. print(ERROR, BOLD + base, "doesn't exist!")
  217. return
  218. valid = _collect(paths)
  219. except exc.InvalidGitRepositoryError:
  220. if not os.path.isdir(base):
  221. print(ERROR, BOLD + base, "isn't a repository!")
  222. return
  223. valid = _collect([base])
  224. base = os.path.abspath(base)
  225. suffix = "" if len(valid) == 1 else "s"
  226. print(BOLD + base, "({0} repo{1}):".format(len(valid), suffix))
  227. valid = [os.path.abspath(path) for path in valid]
  228. paths = [(_get_basename(base, path), path) for path in valid]
  229. for name, path in sorted(paths):
  230. callback(Repo(path), name, *args)
  231. def update_bookmarks(bookmarks, update_args):
  232. """Loop through and update all bookmarks."""
  233. if not bookmarks:
  234. print("You don't have any bookmarks configured! Get help with 'gitup -h'.")
  235. return
  236. for path in bookmarks:
  237. _dispatch(path, _update_repository, *update_args)
  238. def update_directories(paths, update_args):
  239. """Update a list of directories supplied by command arguments."""
  240. for path in paths:
  241. _dispatch(path, _update_repository, *update_args)
  242. def run_command(paths, command):
  243. """Run an arbitrary shell command on all repos."""
  244. for path in paths:
  245. _dispatch(path, _run_command, command)