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.

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