PageRenderTime 51ms CodeModel.GetById 8ms RepoModel.GetById 10ms app.codeStats 0ms

/lib/bitbucket-backup/backup.rb

https://bitbucket.org/seth/bitbucket-backup
Ruby | 85 lines | 47 code | 16 blank | 22 comment | 6 complexity | 67d59ce4456122939e4b438116364af4 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. # @param [Boolean] all_repos
  17. # whether to backup every repo the user has access to or just the
  18. # ones they own.
  19. def self.run(username, password, backup_root, all_repos = false)
  20. backup_root = File.expand_path(backup_root)
  21. puts
  22. puts "Backing up repos to #{backup_root}"
  23. puts
  24. repos = get_repo_list(username, password)
  25. repos.each do |repo|
  26. if all_repos
  27. Bitbucket::Backup::Repository.new(repo, username, password, backup_root).backup
  28. else
  29. # Only backup repos that the user owns.
  30. if repo["owner"] == username
  31. Bitbucket::Backup::Repository.new(repo, username, password, backup_root).backup
  32. end
  33. end
  34. end
  35. end
  36. def self.have_scm_tool?(cmd)
  37. # From: http://stackoverflow.com/questions/2108727/which-in-ruby-checking-if-program-exists-in-path-from-ruby
  38. exts = ENV["PATHEXT"] ? ENV["PATHEXT"].split(";") : [""]
  39. ENV["PATH"].split(File::PATH_SEPARATOR).each do |path|
  40. exts.each do |ext|
  41. bin = "#{path}/#{cmd}#{ext}"
  42. return bin if File.executable?(bin)
  43. end
  44. end
  45. return nil
  46. end
  47. private
  48. # Gets the user's repos.
  49. #
  50. # @return [Array<String>]
  51. # the repos.
  52. #
  53. def self.get_repo_list(username, password)
  54. uri = URI.parse("https://api.bitbucket.org/1.0/user/repositories")
  55. http = Net::HTTP.new(uri.host, uri.port)
  56. http.use_ssl = true
  57. http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  58. request = Net::HTTP::Get.new(uri.request_uri)
  59. request.basic_auth(username, password)
  60. response = http.request(request)
  61. # authentication didn't work
  62. if response.code == "401"
  63. puts "Invalid username/password."
  64. exit
  65. end
  66. JSON.parse(response.body)
  67. end
  68. end
  69. end