A console script that allows you to easily update multiple git repositories at once
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

312 rader
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. def out(indent, msg):
  19. """Print a message at a given indentation level."""
  20. width = 4 # amount to indent at each level
  21. if indent == 0:
  22. spacing = "\n"
  23. else:
  24. spacing = " " * width * indent
  25. msg = re.sub("\s+", " ", msg) # collapse multiple spaces into one
  26. print spacing + msg
  27. def style(text, effect):
  28. """Give a text string a certain effect, such as boldness, or a color."""
  29. ansi = { # ANSI escape codes to make terminal output fancy
  30. "reset": "\x1b[0m",
  31. "bold": "\x1b[1m",
  32. "red": "\x1b[1m\x1b[31m",
  33. "green": "\x1b[1m\x1b[32m",
  34. "yellow": "\x1b[1m\x1b[33m",
  35. "blue": "\x1b[1m\x1b[34m",
  36. }
  37. try: # pad text with effect, unless effect does not exist
  38. return "{}{}{}".format(ansi[effect], text, ansi['reset'])
  39. except KeyError:
  40. return text
  41. def exec_shell(command):
  42. """Execute a shell command and get the output."""
  43. command = shlex.split(command)
  44. result = subprocess.check_output(command, stderr=subprocess.STDOUT)
  45. if result:
  46. result = result[:-1] # strip newline if command returned anything
  47. return result
  48. def directory_is_git_repo(directory_path):
  49. """Check if a directory is a git repository."""
  50. if os.path.isdir(directory_path):
  51. git_subfolder = os.path.join(directory_path, ".git")
  52. if os.path.isdir(git_subfolder): # check for path/to/repository/.git
  53. return True
  54. return False
  55. def update_repository(repo_path, repo_name):
  56. """Update a single git repository by pulling from the remote."""
  57. out(1, "{}{}{}:".format(ansi['bold'], repo_name, ansi['reset']))
  58. os.chdir(repo_path) # cd into our folder so git commands target the correct
  59. # repo
  60. try:
  61. dry_fetch = exec_shell("git fetch --dry-run") # check if there is
  62. # anything to pull, but
  63. # don't do it yet
  64. except subprocess.CalledProcessError:
  65. out(2, """{}Error:{} cannot fetch; do you have a remote repository
  66. configured correctly?""".format(ansi['red'], ansi['reset']))
  67. return
  68. try:
  69. last = exec_shell("git log -n 1 --pretty=\"%ar\"") # last commit time
  70. except subprocess.CalledProcessError:
  71. last = "never" # couldn't get a log, so no commits
  72. if not dry_fetch: # no new changes to pull
  73. out(2, "{}No new changes.{} Last commit was {}.".format(ansi['blue'],
  74. ansi['reset'], last))
  75. else: # stuff has happened!
  76. out(2, "There are new changes upstream...")
  77. status = exec_shell("git status")
  78. if status.endswith("nothing to commit (working directory clean)"):
  79. out(2, "{}Pulling new changes...{}".format(ansi['green'],
  80. ansi['reset']))
  81. result = exec_shell("git pull")
  82. out(2, "The following changes have been made since {}:".format(
  83. last))
  84. print result
  85. else:
  86. out(2, """{}Warning:{} You have uncommitted changes in this
  87. repository!""".format(ansi['red'], ansi['reset']))
  88. out(2, "Ignoring.")
  89. def update_directory(dir_path, dir_name, is_bookmark=False):
  90. """First, make sure the specified object is actually a directory, then
  91. determine whether the directory is a git repo on its own or a directory
  92. of git repositories. If the former, update the single repository; if the
  93. latter, update all repositories contained within."""
  94. if is_bookmark:
  95. dir_source = "Bookmark" # where did we get this directory from?
  96. else:
  97. dir_source = "Directory"
  98. try:
  99. os.listdir(dir_path) # test if we can access this directory
  100. except OSError:
  101. out(0, "{}Error:{} cannot enter {} '{}{}{}'; does it exist?".format(
  102. ansi['red'], ansi['reset'], dir_source.lower(), ansi['bold'], dir_path,
  103. ansi['reset']))
  104. return
  105. if not os.path.isdir(dir_path):
  106. if os.path.exists(dir_path):
  107. error_message = "is not a directory"
  108. else:
  109. error_message = "does not exist"
  110. out(0, "{}Error{}: {} '{}{}{}' {}!".format(ansi['red'], ansi['reset'],
  111. dir_source, ansi['bold'], dir_path, ansi['reset'],
  112. error_message))
  113. return
  114. if directory_is_git_repo(dir_path):
  115. out(0, "{} '{}{}{}' is a git repository:".format(dir_source,
  116. ansi['bold'], dir_path, ansi['reset']))
  117. update_repository(dir_path, dir_name)
  118. else:
  119. repositories = []
  120. dir_contents = os.listdir(dir_path) # get potential repos in directory
  121. for item in dir_contents:
  122. repo_path = os.path.join(dir_path, item)
  123. repo_name = os.path.join(dir_name, item)
  124. if directory_is_git_repo(repo_path): # filter out non-repositories
  125. repositories.append((repo_path, repo_name))
  126. repo_count = len(repositories)
  127. if repo_count == 1:
  128. pluralize = "repository"
  129. else:
  130. pluralize = "repositories"
  131. out(0, "{} '{}{}{}' contains {} git {}:".format(dir_source,
  132. ansi['bold'], dir_path, ansi['reset'], repo_count, pluralize))
  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, "{}Added bookmarks:{}".format(ansi['yellow'], ansi['reset']))
  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, "{}{}{}".format(ansi['bold'], path, ansi['reset']))
  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, "{}Deleted bookmarks:{}".format(ansi['yellow'], ansi['reset']))
  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, "{}{}{}".format(ansi['bold'], path, ansi['reset']))
  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, "{}Current bookmarks:{}".format(ansi['yellow'], ansi['reset']))
  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 "{}gitup{}: the git-repo-updater".format(ansi['bold'], ansi['reset'])
  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.")