/lib/bitbucket-backup/backup.rb
Ruby | 78 lines | 43 code | 16 blank | 19 comment | 5 complexity | a2a648f22e104bedc836f10ce8354218 MD5 | raw file
Possible License(s): 0BSD
- require "net/https"
- require "json"
- module Bitbucket
- module Backup
- # Begins the backup process.
- #
- # @param [String] username
- # the Bitbucket username of the user to backup repos for.
- #
- # @param [String] password
- # the plain-text password of the user to backup repos for.
- #
- # @param [String] backup_root
- # the absolute or relative path of the directory to backup the repos to.
- #
- def self.run(username, password, backup_root)
- backup_root = File.expand_path(backup_root)
-
- puts
- puts "Backing up repos to #{backup_root}"
- puts
-
- repos = get_repo_list(username, password)
-
- repos.each do |repo|
- # Only backup repos that the user owns.
- if repo["owner"] == username
- Bitbucket::Backup::Repository.new(repo, password, backup_root).backup
- end
- end
- end
-
- def self.have_scm_tool?(cmd)
- # From: http://stackoverflow.com/questions/2108727/which-in-ruby-checking-if-program-exists-in-path-from-ruby
- exts = ENV["PATHEXT"] ? ENV["PATHEXT"].split(";") : [""]
-
- ENV["PATH"].split(File::PATH_SEPARATOR).each do |path|
- exts.each do |ext|
- bin = "#{path}/#{cmd}#{ext}"
-
- return bin if File.executable?(bin)
- end
- end
-
- return nil
- end
-
- private
- # Gets the user's repos.
- #
- # @return [Array<String>]
- # the repos.
- #
- def self.get_repo_list(username, password)
- uri = URI.parse("https://api.bitbucket.org/1.0/user/repositories/")
-
- http = Net::HTTP.new(uri.host, uri.port)
-
- http.use_ssl = true
- http.verify_mode = OpenSSL::SSL::VERIFY_NONE
-
- request = Net::HTTP::Get.new(uri.request_uri)
- request.basic_auth(username, password)
-
- response = http.request(request)
-
- # authentication didn't work
- if response.code == "401"
- puts "Invalid username/password."
-
- exit
- end
-
- JSON.parse(response.body)
- end
- end
- end