/bitbucket-backup.rb
Ruby | 75 lines | 42 code | 15 blank | 18 comment | 3 complexity | c238dd5e2fdf7be0b6c3bf9ea2aa7050 MD5 | raw file
- #!/usr/bin/env ruby
- # Chad Maughan
- # chadmaughan.com
- # 2012-09-24
- #
- # This is a script for cloning or pulling changes from repositories
- # on a scheduled basis from http://bitbucket.org using their OAuth API
- require 'rubygems'
- require 'oauth'
- require 'json'
- require 'yaml'
- require './lib/cli.rb'
- cli = BackupCLI.new
- cli.parse_options
- user = cli.config[:user]
- path = cli.config[:path]
- if user.nil? || path.nil?
- puts "Incorrect usage, use '--help' (-h) to see required arguments"
- Process.exit
- end
- url = "https://api.bitbucket.org/1.0"
- # make the consumer out of your secret and key
- # you need to set this up on the bitbucket website (under Account -> Integrated Applications)
- #
- # this file is stored in ~/.repo-backup/.oauth-token
- config = YAML.load_file(ENV['HOME'] + "/.repo-backup/.oauth-token")
- consumer_key = config["consumer"]["key"]
- consumer_secret = config["consumer"]["secret"]
- consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
- :site => url,
- :request_token_path => "/oauth/request_token",
- :authorize_path => "/oauth/authorize",
- :access_token_path => "/oauth/access_token",
- :http_method => :get)
- # make the access token from your consumer
- access_token = OAuth::AccessToken.new(consumer)
- # nifty way to debug all HTTP traffic
- # consumer.http.set_debug_output($stderr)
- # make a signed request
- response = access_token.get("/user")
- # fix the path if it doesn't end with a '/'
- path = /\/$/.match(path) ? path : path + "/"
- # parse the response
- json = JSON.parse(response.body)
- puts "Number of Bitbucket repositories to check: #{json['repositories'].size}"
- json['repositories'].each do |repo|
- name = repo['name']
- puts name
- dir = path + name
- Dir.chdir(path)
- # see if the directory exists (update or clone)
- if File.directory?(dir)
- Dir.chdir(dir)
- puts "repository exists, updating to: " + dir
- puts system "git pull"
- else
- puts "repository doesn't exit, cloning to: " + dir
- puts system "git clone git@bitbucket.org:#{user}/#{name}.git"
- end
- end