A console script that allows you to easily update multiple git repositories at once
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

304 wiersze
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. for repo_path, repo_name in repositories:
  128. update_repository(repo_path, repo_name)
  129. def update_directories(paths):
  130. """Update a list of directories supplied by command arguments."""
  131. for path in paths:
  132. path = os.path.abspath(path) # convert relative to absolute path
  133. path_name = os.path.split(path)[1] # directory name; "x" in /path/to/x/
  134. update_directory(path, path_name, is_bookmark=False)
  135. def update_bookmarks():
  136. """Loop through and update all bookmarks."""
  137. try:
  138. bookmarks = load_config_file().items("bookmarks")
  139. except configparser.NoSectionError:
  140. bookmarks = []
  141. if bookmarks:
  142. for bookmark_path, bookmark_name in bookmarks:
  143. update_directory(bookmark_path, bookmark_name, is_bookmark=True)
  144. else:
  145. out(0, """You don't have any bookmarks configured! Get help with
  146. 'gitup -h'.""")
  147. def load_config_file():
  148. """Read the file storing our config options from config_filename and return
  149. the resulting SafeConfigParser() object."""
  150. config = configparser.SafeConfigParser()
  151. config.optionxform = str # don't lowercase option names, because we are
  152. # storing paths there
  153. config.read(config_filename)
  154. return config
  155. def save_config_file(config):
  156. """Save our config changes to the config file specified by
  157. config_filename."""
  158. with open(config_filename, "wb") as config_file:
  159. config.write(config_file)
  160. def add_bookmarks(paths):
  161. """Add a list of paths as bookmarks to the config file."""
  162. config = load_config_file()
  163. if not config.has_section("bookmarks"):
  164. config.add_section("bookmarks")
  165. out(0, "{}Added bookmarks:{}".format(ansi['yellow'], ansi['reset']))
  166. for path in paths:
  167. path = os.path.abspath(path) # convert relative to absolute path
  168. if config.has_option("bookmarks", path):
  169. out(1, "'{}' is already bookmarked.".format(path))
  170. else:
  171. path_name = os.path.split(path)[1]
  172. config.set("bookmarks", path, path_name)
  173. out(1, "{}{}{}".format(ansi['bold'], path, ansi['reset']))
  174. save_config_file(config)
  175. def delete_bookmarks(paths):
  176. """Remove a list of paths from the bookmark config file."""
  177. config = load_config_file()
  178. if config.has_section("bookmarks"):
  179. out(0, "{}Deleted bookmarks:{}".format(ansi['yellow'], ansi['reset']))
  180. for path in paths:
  181. path = os.path.abspath(path) # convert relative to absolute path
  182. config_was_changed = config.remove_option("bookmarks", path)
  183. if config_was_changed:
  184. out(1, "{}{}{}".format(ansi['bold'], path, ansi['reset']))
  185. else:
  186. out(1, "'{}' is not bookmarked.".format(path))
  187. save_config_file(config)
  188. else:
  189. out(0, "There are no bookmarks to delete!")
  190. def list_bookmarks():
  191. """Print all of our current bookmarks."""
  192. config = load_config_file()
  193. try:
  194. bookmarks = config.items("bookmarks")
  195. except configparser.NoSectionError:
  196. bookmarks = []
  197. if bookmarks:
  198. out(0, "{}Current bookmarks:{}".format(ansi['yellow'], ansi['reset']))
  199. for bookmark_path, bookmark_name in bookmarks:
  200. out(1, bookmark_path)
  201. else:
  202. out(0, "You have no bookmarks to display.")
  203. def main():
  204. """Parse arguments and then call the appropriate function(s)."""
  205. parser = argparse.ArgumentParser(description="""Easily pull to multiple git
  206. repositories at once.""", epilog="""Both relative and absolute
  207. paths are accepted by all arguments. Questions? Comments? Email the
  208. author at {}.""".format(__email__), add_help=False)
  209. group_u = parser.add_argument_group("updating repositories")
  210. group_b = parser.add_argument_group("bookmarking")
  211. group_m = parser.add_argument_group("miscellaneous")
  212. group_u.add_argument('directories_to_update', nargs="*", metavar="path",
  213. help="""update all repositories in this directory (or the directory
  214. itself, if it is a repo)""")
  215. group_u.add_argument('-u', '--update', action="store_true", help="""update
  216. all bookmarks (default behavior when called without arguments)""")
  217. group_b.add_argument('-a', '--add', dest="bookmarks_to_add", nargs="+",
  218. metavar="path", help="add directory(s) as bookmarks")
  219. group_b.add_argument('-d', '--delete', dest="bookmarks_to_del", nargs="+",
  220. metavar="path",
  221. help="delete bookmark(s) (leaves actual directories alone)")
  222. group_b.add_argument('-l', '--list', dest="list_bookmarks",
  223. action="store_true", help="list current bookmarks")
  224. group_m.add_argument('-h', '--help', action="help",
  225. help="show this help message and exit")
  226. group_m.add_argument('-v', '--version', action="version",
  227. version="gitup version "+__version__)
  228. args = parser.parse_args()
  229. print "{}gitup{}: the git-repo-updater".format(ansi['bold'], ansi['reset'])
  230. if args.bookmarks_to_add:
  231. add_bookmarks(args.bookmarks_to_add)
  232. if args.bookmarks_to_del:
  233. delete_bookmarks(args.bookmarks_to_del)
  234. if args.list_bookmarks:
  235. list_bookmarks()
  236. if args.directories_to_update:
  237. update_directories(args.directories_to_update)
  238. if args.update:
  239. update_bookmarks()
  240. if not any(vars(args).values()): # if they did not tell us to do anything,
  241. update_bookmarks() # automatically update bookmarks
  242. if __name__ == "__main__":
  243. try:
  244. main()
  245. except KeyboardInterrupt:
  246. out(0, "Stopped by user.")