PageRenderTime 51ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/bitbucket-backup/backup.rb

https://bitbucket.org/mariusmarais/bitbucket-backup
Ruby | 78 lines | 43 code | 16 blank | 19 comment | 5 complexity | a2a648f22e104bedc836f10ce8354218 MD5 | raw file
Possible License(s): 0BSD
  1. require "net/https"
  2. require "json"
  3. module Bitbucket
  4. module Backup
  5. # Begins the backup process.
  6. #
  7. # @param [String] username
  8. # the Bitbucket username of the user to backup repos for.
  9. #
  10. # @param [String] password
  11. # the plain-text password of the user to backup repos for.
  12. #
  13. # @param [String] backup_root
  14. # the absolute or relative path of the directory to backup the repos to.
  15. #
  16. def self.run(username, password, backup_root)
  17. backup_root = File.expand_path(backup_root)
  18. puts
  19. puts "Backing up repos to #{backup_root}"
  20. puts
  21. repos = get_repo_list(username, password)
  22. repos.each do |repo|
  23. # Only backup repos that the user owns.
  24. if repo["owner"] == username
  25. Bitbucket::Backup::Repository.new(repo, password, backup_root).backup
  26. end
  27. end
  28. end
  29. def self.have_scm_tool?(cmd)
  30. # From: http://stackoverflow.com/questions/2108727/which-in-ruby-checking-if-program-exists-in-path-from-ruby
  31. exts = ENV["PATHEXT"] ? ENV["PATHEXT"].split(";") : [""]
  32. ENV["PATH"].split(File::PATH_SEPARATOR).each do |path|
  33. exts.each do |ext|
  34. bin = "#{path}/#{cmd}#{ext}"
  35. return bin if File.executable?(bin)
  36. end
  37. end
  38. return nil
  39. end
  40. private
  41. # Gets the user's repos.
  42. #
  43. # @return [Array<String>]
  44. # the repos.
  45. #
  46. def self.get_repo_list(username, password)
  47. uri = URI.parse("https://api.bitbucket.org/1.0/user/repositories/")
  48. http = Net::HTTP.new(uri.host, uri.port)
  49. http.use_ssl = true
  50. http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  51. request = Net::HTTP::Get.new(uri.request_uri)
  52. request.basic_auth(username, password)
  53. response = http.request(request)
  54. # authentication didn't work
  55. if response.code == "401"
  56. puts "Invalid username/password."
  57. exit
  58. end
  59. JSON.parse(response.body)
  60. end
  61. end
  62. end