A console script that allows you to easily update multiple git repositories at once
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

313 lines
11 KiB

  1. #! /usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. """
  4. gitup: the git repository updater
  5. """
  6. import argparse
  7. import ConfigParser as configparser
  8. import os
  9. import re
  10. import shlex
  11. import subprocess
  12. __author__ = "Ben Kurtovic"
  13. __copyright__ = "Copyright (c) 2011-2012 Ben Kurtovic"
  14. __license__ = "MIT License"
  15. __version__ = "0.1"
  16. __email__ = "ben.kurtovic@verizon.net"
  17. config_filename = os.path.join(os.path.expanduser("~"), ".gitup")
  18. # Text formatting functions
  19. bold = lambda t: style_text(t, "bold")
  20. red = lambda t: style_text(t, "red")
  21. green = lambda t: style_text(t, "green")
  22. yellow = lambda t: style_text(t, "yellow")
  23. blue = lambda t: style_text(t, "blue")
  24. def style_text(text, effect):
  25. """Give a text string a certain effect, such as boldness, or a color."""
  26. ansi = { # ANSI escape codes to make terminal output fancy
  27. "reset": "\x1b[0m",
  28. "bold": "\x1b[1m",
  29. "red": "\x1b[1m\x1b[31m",
  30. "green": "\x1b[1m\x1b[32m",
  31. "yellow": "\x1b[1m\x1b[33m",
  32. "blue": "\x1b[1m\x1b[34m",
  33. }
  34. try: # pad text with effect, unless effect does not exist
  35. return "{}{}{}".format(ansi[effect], text, ansi['reset'])
  36. except KeyError:
  37. return text
  38. def out(indent, msg):
  39. """Print a message at a given indentation level."""
  40. width = 4 # amount to indent at each level
  41. if indent == 0:
  42. spacing = "\n"
  43. else:
  44. spacing = " " * width * indent
  45. msg = re.sub("\s+", " ", msg) # collapse multiple spaces into one
  46. print spacing + msg
  47. def exec_shell(command):
  48. """Execute a shell command and get the output."""
  49. command = shlex.split(command)
  50. result = subprocess.check_output(command, stderr=subprocess.STDOUT)
  51. if result:
  52. result = result[:-1] # strip newline if command returned anything
  53. return result
  54. def directory_is_git_repo(directory_path):
  55. """Check if a directory is a git repository."""
  56. if os.path.isdir(directory_path):
  57. git_subfolder = os.path.join(directory_path, ".git")
  58. if os.path.isdir(git_subfolder): # check for path/to/repository/.git
  59. return True
  60. return False
  61. def update_repository(repo_path, repo_name):
  62. """Update a single git repository by pulling from the remote."""
  63. out(1, bold(repo_name) + ":")
  64. os.chdir(repo_path) # cd into our folder so git commands target the correct
  65. # repo
  66. try:
  67. dry_fetch = exec_shell("git fetch --dry-run") # check if there is
  68. # anything to pull, but
  69. # don't do it yet
  70. except subprocess.CalledProcessError:
  71. out(2, red("Error: ") + "cannot fetch; do you have a remote " +
  72. "repository configured correctly?")
  73. return
  74. try:
  75. last_commit = exec_shell("git log -n 1 --pretty=\"%ar\"")
  76. except subprocess.CalledProcessError:
  77. last_commit = "never" # couldn't get a log, so no commits
  78. if not dry_fetch: # no new changes to pull
  79. out(2, blue("No new changes.") + " Last commit was {}.".format(
  80. last_commit))
  81. else: # stuff has happened!
  82. out(2, "There are new changes upstream...")
  83. status = exec_shell("git status")
  84. if status.endswith("nothing to commit (working directory clean)"):
  85. out(2, green("Pulling new changes..."))
  86. result = exec_shell("git pull")
  87. out(2, "The following changes have been made since {}:".format(
  88. last_commit))
  89. print result
  90. else:
  91. out(2, red("Warning: ") + "you have uncommitted changes in this " +
  92. "repository!")
  93. out(2, "Ignoring.")
  94. def update_directory(dir_path, dir_name, is_bookmark=False):
  95. """First, make sure the specified object is actually a directory, then
  96. determine whether the directory is a git repo on its own or a directory
  97. of git repositories. If the former, update the single repository; if the
  98. latter, update all repositories contained within."""
  99. if is_bookmark:
  100. dir_type = "bookmark" # where did we get this directory from?
  101. else:
  102. dir_type = "directory"
  103. dir_long_name = "{} '{}'".format(dir_type, bold(dir_path))
  104. try:
  105. os.listdir(dir_path) # test if we can access this directory
  106. except OSError:
  107. out(0, red("Error: ") + "cannot enter {}; does it exist?".format(
  108. dir_long_name))
  109. return
  110. if not os.path.isdir(dir_path):
  111. if os.path.exists(dir_path):
  112. out(0, red("Error: ") + dir_long_name + " is not a directory!")
  113. else:
  114. out(0, red("Error: ") + dir_long_name + " does not exist!")
  115. return
  116. if directory_is_git_repo(dir_path):
  117. out(0, dir_long_name.capitalize() + " is a git repository:")
  118. update_repository(dir_path, dir_name)
  119. else:
  120. repositories = []
  121. dir_contents = os.listdir(dir_path) # get potential repos in directory
  122. for item in dir_contents:
  123. repo_path = os.path.join(dir_path, item)
  124. repo_name = os.path.join(dir_name, item)
  125. if directory_is_git_repo(repo_path): # filter out non-repositories
  126. repositories.append((repo_path, repo_name))
  127. num_of_repos = len(repositories)
  128. if num_of_repos == 1:
  129. out(0, dir_long_name.capitalize() + " contains 1 git repository:")
  130. else:
  131. out(0, dir_long_name.capitalize() +
  132. " contains {} git repositories:".format(num_of_repos))
  133. repositories.sort() # go alphabetically instead of randomly
  134. for repo_path, repo_name in repositories:
  135. update_repository(repo_path, repo_name)
  136. def update_directories(paths):
  137. """Update a list of directories supplied by command arguments."""
  138. for path in paths:
  139. path = os.path.abspath(path) # convert relative to absolute path
  140. path_name = os.path.split(path)[1] # directory name; "x" in /path/to/x/
  141. update_directory(path, path_name, is_bookmark=False)
  142. def update_bookmarks():
  143. """Loop through and update all bookmarks."""
  144. try:
  145. bookmarks = load_config_file().items("bookmarks")
  146. except configparser.NoSectionError:
  147. bookmarks = []
  148. if bookmarks:
  149. for bookmark_path, bookmark_name in bookmarks:
  150. update_directory(bookmark_path, bookmark_name, is_bookmark=True)
  151. else:
  152. out(0, "You don't have any bookmarks configured! Get help with " +
  153. "'gitup -h'.")
  154. def load_config_file():
  155. """Read the file storing our config options from config_filename and return
  156. the resulting SafeConfigParser() object."""
  157. config = configparser.SafeConfigParser()
  158. config.optionxform = str # don't lowercase option names, because we are
  159. # storing paths there
  160. config.read(config_filename)
  161. return config
  162. def save_config_file(config):
  163. """Save our config changes to the config file specified by
  164. config_filename."""
  165. with open(config_filename, "wb") as config_file:
  166. config.write(config_file)
  167. def add_bookmarks(paths):
  168. """Add a list of paths as bookmarks to the config file."""
  169. config = load_config_file()
  170. if not config.has_section("bookmarks"):
  171. config.add_section("bookmarks")
  172. out(0, yellow("Added bookmarks:"))
  173. for path in paths:
  174. path = os.path.abspath(path) # convert relative to absolute path
  175. if config.has_option("bookmarks", path):
  176. out(1, "'{}' is already bookmarked.".format(path))
  177. else:
  178. path_name = os.path.split(path)[1]
  179. config.set("bookmarks", path, path_name)
  180. out(1, bold(path))
  181. save_config_file(config)
  182. def delete_bookmarks(paths):
  183. """Remove a list of paths from the bookmark config file."""
  184. config = load_config_file()
  185. if config.has_section("bookmarks"):
  186. out(0, yellow("Deleted bookmarks:"))
  187. for path in paths:
  188. path = os.path.abspath(path) # convert relative to absolute path
  189. config_was_changed = config.remove_option("bookmarks", path)
  190. if config_was_changed:
  191. out(1, bold(path))
  192. else:
  193. out(1, "'{}' is not bookmarked.".format(path))
  194. save_config_file(config)
  195. else:
  196. out(0, "There are no bookmarks to delete!")
  197. def list_bookmarks():
  198. """Print all of our current bookmarks."""
  199. config = load_config_file()
  200. try:
  201. bookmarks = config.items("bookmarks")
  202. except configparser.NoSectionError:
  203. bookmarks = []
  204. if bookmarks:
  205. out(0, yellow("Current bookmarks:"))
  206. for bookmark_path, bookmark_name in bookmarks:
  207. out(1, bookmark_path)
  208. else:
  209. out(0, "You have no bookmarks to display.")
  210. def main():
  211. """Parse arguments and then call the appropriate function(s)."""
  212. parser = argparse.ArgumentParser(description="""Easily pull to multiple git
  213. repositories at once.""", epilog="""Both relative and absolute
  214. paths are accepted by all arguments. Questions? Comments? Email the
  215. author at {}.""".format(__email__), add_help=False)
  216. group_u = parser.add_argument_group("updating repositories")
  217. group_b = parser.add_argument_group("bookmarking")
  218. group_m = parser.add_argument_group("miscellaneous")
  219. group_u.add_argument('directories_to_update', nargs="*", metavar="path",
  220. help="""update all repositories in this directory (or the directory
  221. itself, if it is a repo)""")
  222. group_u.add_argument('-u', '--update', action="store_true", help="""update
  223. all bookmarks (default behavior when called without arguments)""")
  224. group_b.add_argument('-a', '--add', dest="bookmarks_to_add", nargs="+",
  225. metavar="path", help="add directory(s) as bookmarks")
  226. group_b.add_argument('-d', '--delete', dest="bookmarks_to_del", nargs="+",
  227. metavar="path",
  228. help="delete bookmark(s) (leaves actual directories alone)")
  229. group_b.add_argument('-l', '--list', dest="list_bookmarks",
  230. action="store_true", help="list current bookmarks")
  231. group_m.add_argument('-h', '--help', action="help",
  232. help="show this help message and exit")
  233. group_m.add_argument('-v', '--version', action="version",
  234. version="gitup version "+__version__)
  235. args = parser.parse_args()
  236. print bold("gitup") + ": the git-repo-updater"
  237. if args.bookmarks_to_add:
  238. add_bookmarks(args.bookmarks_to_add)
  239. if args.bookmarks_to_del:
  240. delete_bookmarks(args.bookmarks_to_del)
  241. if args.list_bookmarks:
  242. list_bookmarks()
  243. if args.directories_to_update:
  244. update_directories(args.directories_to_update)
  245. if args.update:
  246. update_bookmarks()
  247. if not any(vars(args).values()): # if they did not tell us to do anything,
  248. update_bookmarks() # automatically update bookmarks
  249. if __name__ == "__main__":
  250. try:
  251. main()
  252. except KeyboardInterrupt:
  253. out(0, "Stopped by user.")