A console script that allows you to easily update multiple git repositories at once
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

440 Zeilen
15 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 = [
  57. ("NEW_HEAD", "new branch", "new branches"),
  58. ("NEW_TAG", "new tag", "new tags"),
  59. ("FAST_FORWARD", "branch update", "branch updates"),
  60. ]
  61. up_to_date = BLUE + "up to date" + RESET
  62. for remote in remotes:
  63. print(INDENT2, "Fetching", BOLD + remote.name, end="")
  64. if not remote.config_reader.has_option("fetch"):
  65. print(":", YELLOW + "skipped:", "no configured refspec.")
  66. continue
  67. try:
  68. results = remote.fetch(progress=_ProgressMonitor(), prune=prune)
  69. except exc.GitCommandError as err:
  70. # We should have to do this ourselves, but GitPython doesn't give
  71. # us a sensible way to get the raw stderr...
  72. msg = _git_error_text(err)
  73. if not msg:
  74. command = " ".join(shlex.quote(arg) for arg in err.command)
  75. msg = "{0} failed with status {1}.".format(command, err.status)
  76. elif not msg.endswith("."):
  77. msg += "."
  78. print(":", RED + "error:", msg)
  79. return
  80. except AssertionError: # Seems to be the result of a bug in GitPython
  81. # This happens when git initiates an auto-gc during fetch:
  82. print(
  83. ":",
  84. RED + "error:",
  85. "something went wrong in GitPython,",
  86. "but the fetch might have been successful.",
  87. )
  88. return
  89. rlist = []
  90. for attr, singular, plural in info:
  91. names = [
  92. _get_name(res.ref) for res in results if res.flags & getattr(res, attr)
  93. ]
  94. if names:
  95. desc = singular if len(names) == 1 else plural
  96. colored = GREEN + desc + RESET
  97. rlist.append("{0} ({1})".format(colored, ", ".join(names)))
  98. print(":", (", ".join(rlist) if rlist else up_to_date) + ".")
  99. def _git_error_text(err):
  100. """Return a concise message from a GitPython command error."""
  101. raw = err.stderr or ""
  102. if isinstance(raw, bytes):
  103. raw = raw.decode("utf8", errors="replace")
  104. msg = re.sub(r"\s+", " ", raw).strip()
  105. msg = re.sub(r"^stderr: *'(fatal: *)?", "", msg).strip("'")
  106. return msg
  107. def _same_path(left, right):
  108. """Return whether two filesystem paths refer to the same location."""
  109. if not left or not right:
  110. return False
  111. try:
  112. return os.path.samefile(left, right)
  113. except OSError:
  114. return os.path.normcase(os.path.realpath(left)) == os.path.normcase(
  115. os.path.realpath(right)
  116. )
  117. def _parse_worktree_porcelain(output):
  118. """Map local branch names to the worktree path where they are checked out."""
  119. def attrs_from_entry(entry):
  120. attrs = {}
  121. for line in entry.splitlines():
  122. if not line:
  123. continue
  124. if " " in line:
  125. key, value = line.split(" ", 1)
  126. attrs[key] = value
  127. else:
  128. attrs[line] = True
  129. return attrs
  130. def branch_and_path(attrs):
  131. path = attrs.get("worktree")
  132. ref = attrs.get("branch")
  133. if not path or not isinstance(ref, str):
  134. return None
  135. name = (
  136. ref[len("refs/heads/") :] if ref.startswith("refs/heads/") else ref
  137. )
  138. return name, path
  139. normalized = output.replace("\r\n", "\n")
  140. pairs = [
  141. branch_and_path(attrs_from_entry(entry))
  142. for entry in normalized.split("\n\n")
  143. ]
  144. return dict(pair for pair in pairs if pair)
  145. def _branch_worktrees(repo):
  146. """Return {branch_name: worktree_path} for checkouts with a branch."""
  147. try:
  148. # GitPython puts kwargs before subcommands (`worktree --porcelain list`),
  149. # which git rejects. Pass --porcelain as a positional argument.
  150. output = repo.git.worktree("list", "--porcelain")
  151. except exc.GitCommandError:
  152. return {}
  153. return _parse_worktree_porcelain(output or "")
  154. def _repo_for_workdir(repo, worktree_path):
  155. """Return a Repo for *worktree_path*, reusing *repo* when it is the same tree."""
  156. if repo.working_dir and _same_path(repo.working_dir, worktree_path):
  157. return repo
  158. return Repo(worktree_path)
  159. def _merge_ff_only(repo, upstream_name):
  160. """Fast-forward *repo*'s current checkout; print done or skipped."""
  161. try:
  162. repo.git.merge(upstream_name, ff_only=True)
  163. print(GREEN + "done", end=".\n")
  164. except exc.GitCommandError as err:
  165. msg = _git_error_text(err)
  166. if "local changes" in msg and "would be overwritten" in msg:
  167. print(YELLOW + "skipped:", "uncommitted changes.")
  168. else:
  169. print(YELLOW + "skipped:", "not possible to fast-forward.")
  170. def _update_branch(repo, branch, is_active=False, worktrees=None):
  171. """Update a single branch.
  172. Branches checked out in this repo or another worktree are fast-forwarded
  173. with ``merge --ff-only`` in that checkout. Other tracking branches are
  174. moved with ``git branch --force`` when the update is a fast-forward.
  175. """
  176. print(INDENT2, "Updating", BOLD + branch.name, end=": ")
  177. try:
  178. _update_branch_body(repo, branch, is_active, worktrees)
  179. except exc.GitCommandError as err:
  180. msg = _git_error_text(err) or "git command failed"
  181. if not msg.endswith("."):
  182. msg += "."
  183. print(YELLOW + "skipped:", msg)
  184. def _update_branch_body(repo, branch, is_active, worktrees):
  185. """Perform the update for a single branch, printing the result."""
  186. upstream = branch.tracking_branch()
  187. if not upstream:
  188. print(YELLOW + "skipped:", "no upstream is tracked.")
  189. return
  190. try:
  191. branch.commit
  192. except ValueError:
  193. print(YELLOW + "skipped:", "branch has no revisions.")
  194. return
  195. try:
  196. upstream.commit
  197. except ValueError:
  198. print(YELLOW + "skipped:", "upstream does not exist.")
  199. return
  200. try:
  201. base = repo.git.merge_base(branch.commit, upstream.commit)
  202. except exc.GitCommandError as err:
  203. logger.debug(err)
  204. print(YELLOW + "skipped:", "can't find merge base with upstream.")
  205. return
  206. if repo.commit(base) == upstream.commit:
  207. print(BLUE + "up to date", end=".\n")
  208. return
  209. if worktrees is None:
  210. worktrees = _branch_worktrees(repo)
  211. checkout = worktrees.get(branch.name)
  212. if is_active or checkout:
  213. try:
  214. target = _repo_for_workdir(repo, checkout) if checkout else repo
  215. except (exc.NoSuchPathError, exc.InvalidGitRepositoryError):
  216. print(YELLOW + "skipped:", "worktree path does not exist.")
  217. return
  218. _merge_ff_only(target, upstream.name)
  219. return
  220. status = repo.git.merge_base(
  221. branch.commit,
  222. upstream.commit,
  223. is_ancestor=True,
  224. with_extended_output=True,
  225. with_exceptions=False,
  226. )[0]
  227. if status != 0:
  228. print(YELLOW + "skipped:", "not possible to fast-forward.")
  229. return
  230. repo.git.branch(branch.name, upstream.name, force=True)
  231. print(GREEN + "done", end=".\n")
  232. def _update_repository(repo, repo_name, args):
  233. """Update a single git repository by fetching remotes and rebasing/merging.
  234. The specific actions depend on the arguments given. We will fetch all
  235. remotes if *args.current_only* is ``False``, or only the remote tracked by
  236. the current branch if ``True``. If *args.fetch_only* is ``False``, we will
  237. also update all fast-forwardable branches that are tracking valid
  238. upstreams. If *args.prune* is ``True``, remote-tracking branches that no
  239. longer exist on their remote after fetching will be deleted.
  240. """
  241. print(INDENT1, BOLD + repo_name + ":")
  242. try:
  243. active = repo.active_branch
  244. except TypeError: # Happens when HEAD is detached
  245. active = None
  246. if args.current_only:
  247. if not active:
  248. print(
  249. INDENT2,
  250. ERROR,
  251. "--current-only doesn't make sense with a detached HEAD.",
  252. )
  253. return
  254. ref = active.tracking_branch()
  255. if not ref:
  256. print(INDENT2, ERROR, "no remote tracked by current branch.")
  257. return
  258. remotes = [repo.remotes[ref.remote_name]]
  259. else:
  260. remotes = repo.remotes
  261. if not remotes:
  262. print(INDENT2, ERROR, "no remotes configured to fetch.")
  263. return
  264. _fetch_remotes(remotes, args.prune)
  265. if not args.fetch_only:
  266. worktrees = _branch_worktrees(repo)
  267. for branch in sorted(repo.heads, key=lambda b: b.name):
  268. _update_branch(repo, branch, branch == active, worktrees)
  269. def _run_command(repo, repo_name, args):
  270. """Run an arbitrary shell command on the given repository."""
  271. print(INDENT1, BOLD + repo_name + ":")
  272. cmd = shlex.split(args.command)
  273. try:
  274. out = repo.git.execute(cmd, with_extended_output=True, with_exceptions=False)
  275. except exc.GitCommandNotFound as err:
  276. print(INDENT2, ERROR, err)
  277. return
  278. for line in out[1].splitlines() + out[2].splitlines():
  279. print(INDENT2, line)
  280. def _dispatch(base_path, callback, args):
  281. """Apply a callback function on each valid repo in the given path.
  282. Determine whether the directory is a git repo on its own, a directory of
  283. git repositories, a shell glob pattern, or something invalid. If the first,
  284. apply the callback on it; if the second or third, apply the callback on all
  285. repositories contained within; if the last, print an error.
  286. The given args are passed directly to the callback function after the repo.
  287. """
  288. def _collect(paths, max_depth):
  289. """Return all valid repo paths in the given paths, recursively."""
  290. if max_depth == 0:
  291. return []
  292. valid = []
  293. for path in paths:
  294. try:
  295. Repo(path)
  296. valid.append(path)
  297. except exc.InvalidGitRepositoryError:
  298. if not os.path.isdir(path):
  299. continue
  300. children = [os.path.join(path, it) for it in os.listdir(path)]
  301. valid += _collect(children, max_depth - 1)
  302. except exc.NoSuchPathError:
  303. continue
  304. return valid
  305. def _get_basename(base, path):
  306. """Return a reasonable name for a repo path in the given base."""
  307. if path.startswith(base + os.path.sep):
  308. return path.split(base + os.path.sep, 1)[1]
  309. prefix = os.path.commonprefix([base, path])
  310. while not base.startswith(prefix + os.path.sep):
  311. old = prefix
  312. prefix = os.path.split(prefix)[0]
  313. if prefix == old:
  314. break # Prevent infinite loop, but should be almost impossible
  315. return path.split(prefix + os.path.sep, 1)[1]
  316. base = os.path.expanduser(base_path)
  317. max_depth = args.max_depth
  318. if max_depth >= 0:
  319. max_depth += 1
  320. try:
  321. Repo(base)
  322. valid = [base]
  323. except exc.NoSuchPathError:
  324. if is_comment(base):
  325. comment = get_comment(base)
  326. if comment:
  327. print(CYAN + BOLD + comment)
  328. return
  329. paths = glob(base)
  330. if not paths:
  331. print(ERROR, BOLD + base, "doesn't exist!")
  332. return
  333. valid = _collect(paths, max_depth)
  334. except exc.InvalidGitRepositoryError:
  335. if not os.path.isdir(base) or args.max_depth == 0:
  336. print(ERROR, BOLD + base, "isn't a repository!")
  337. return
  338. valid = _collect([base], max_depth)
  339. base = os.path.abspath(base)
  340. suffix = "" if len(valid) == 1 else "s"
  341. print(BOLD + base, "({0} repo{1}):".format(len(valid), suffix))
  342. valid = [os.path.abspath(path) for path in valid]
  343. paths = [(_get_basename(base, path), path) for path in valid]
  344. for name, path in sorted(paths):
  345. callback(Repo(path), name, args)
  346. def is_comment(path):
  347. """Does the line start with a # symbol?"""
  348. return path.lstrip().startswith("#")
  349. def get_comment(path):
  350. """Return the string minus the comment symbol."""
  351. return path.lstrip().lstrip("#").strip()
  352. def update_bookmarks(bookmarks, args):
  353. """Loop through and update all bookmarks."""
  354. if not bookmarks:
  355. print("You don't have any bookmarks configured! Get help with 'gitup -h'.")
  356. return
  357. for path in bookmarks:
  358. _dispatch(path, _update_repository, args)
  359. def update_directories(paths, args):
  360. """Update a list of directories supplied by command arguments."""
  361. for path in paths:
  362. _dispatch(path, _update_repository, args)
  363. def run_command(paths, args):
  364. """Run an arbitrary shell command on all repos."""
  365. for path in paths:
  366. _dispatch(path, _run_command, args)