PageRenderTime 81ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/bitbucket-backup.rb

https://bitbucket.org/chadmaughan/repos-backup
Ruby | 75 lines | 42 code | 15 blank | 18 comment | 3 complexity | c238dd5e2fdf7be0b6c3bf9ea2aa7050 MD5 | raw file
  1. #!/usr/bin/env ruby
  2. # Chad Maughan
  3. # chadmaughan.com
  4. # 2012-09-24
  5. #
  6. # This is a script for cloning or pulling changes from repositories
  7. # on a scheduled basis from http://bitbucket.org using their OAuth API
  8. require 'rubygems'
  9. require 'oauth'
  10. require 'json'
  11. require 'yaml'
  12. require './lib/cli.rb'
  13. cli = BackupCLI.new
  14. cli.parse_options
  15. user = cli.config[:user]
  16. path = cli.config[:path]
  17. if user.nil? || path.nil?
  18. puts "Incorrect usage, use '--help' (-h) to see required arguments"
  19. Process.exit
  20. end
  21. url = "https://api.bitbucket.org/1.0"
  22. # make the consumer out of your secret and key
  23. # you need to set this up on the bitbucket website (under Account -> Integrated Applications)
  24. #
  25. # this file is stored in ~/.repo-backup/.oauth-token
  26. config = YAML.load_file(ENV['HOME'] + "/.repo-backup/.oauth-token")
  27. consumer_key = config["consumer"]["key"]
  28. consumer_secret = config["consumer"]["secret"]
  29. consumer = OAuth::Consumer.new(consumer_key, consumer_secret,
  30. :site => url,
  31. :request_token_path => "/oauth/request_token",
  32. :authorize_path => "/oauth/authorize",
  33. :access_token_path => "/oauth/access_token",
  34. :http_method => :get)
  35. # make the access token from your consumer
  36. access_token = OAuth::AccessToken.new(consumer)
  37. # nifty way to debug all HTTP traffic
  38. # consumer.http.set_debug_output($stderr)
  39. # make a signed request
  40. response = access_token.get("/user")
  41. # fix the path if it doesn't end with a '/'
  42. path = /\/$/.match(path) ? path : path + "/"
  43. # parse the response
  44. json = JSON.parse(response.body)
  45. puts "Number of Bitbucket repositories to check: #{json['repositories'].size}"
  46. json['repositories'].each do |repo|
  47. name = repo['name']
  48. puts name
  49. dir = path + name
  50. Dir.chdir(path)
  51. # see if the directory exists (update or clone)
  52. if File.directory?(dir)
  53. Dir.chdir(dir)
  54. puts "repository exists, updating to: " + dir
  55. puts system "git pull"
  56. else
  57. puts "repository doesn't exit, cloning to: " + dir
  58. puts system "git clone git@bitbucket.org:#{user}/#{name}.git"
  59. end
  60. end