require 'bitbucket_rest_api' require 'rest_client' require 'open3' class Fanforce::PluginFactory::CLI::Bitbucket include Fanforce::PluginFactory::CLI::Utils attr_reader :plugin def initialize(plugin) @plugin = plugin end def bitbucket @@bitbucket = ::BitBucket.new(login: config[:bitbucket][:user], password: config[:bitbucket][:password]) end def create repo_name = "plugin-#{plugin.dir_name}" error "Bitbucket repo already exists (#{repo_name})" if find_repo(repo_name) create_repo(repo_name) puts "#{'Created '.format(:green,:bold)}" + "#{repo_name} repository on bitbucket" end def setup repo_name = "plugin-#{plugin.dir_name}" error "Bitbucket repo does not exist (#{repo_name})" if !find_repo(repo_name) "#{'Found '.format(:green,:bold)}" + "#{repo_name} repository already exists on bitbucket" setup_git_remote(repo_name) end def destroy repo_name = "plugin-#{plugin.dir_name}" if find_repo(repo_name) RestClient::Request.execute(:method => :delete, :url => "https://#{config[:bitbucket][:user]}:#{config[:bitbucket][:password]}@api.bitbucket.org/1.0/repositories/#{config[:bitbucket][:user]}/#{repo_name}", :ssl_version => 'SSLv23') puts "#{'Removed'.format(:green,:bold)}" + " #{repo_name}" else puts "#{'Already Removed'.format(:green,:bold)}" + " #{repo_name}" end end def find_repo(repo_name) bitbucket.repos.find(config[:bitbucket][:user], repo_name) rescue return nil end def setup_git_remote(repo_name) Dir.chdir(plugin.dir) do if console_command('git remote').split(/\r?\n/).include?('bitbucket') log "#{'Found '.format(:green,:bold)}" + "git remote for bitbucket (#{config[:bitbucket][:user]})" else console_command("git remote add bitbucket git@bitbucket.org:#{config[:bitbucket][:user]}/#{repo_name}.git") console_command('git fetch bitbucket') log "#{'Created '.format(:green,:bold)}" + "git remote for bitbucket (#{config[:bitbucket][:user]})" end upstream_error = Open3.popen3('git rev-parse --abbrev-ref master@{upstream}')[2].gets.to_s if upstream_error.include?('fatal') console_command('git branch -u bitbucket/master') log "#{'Connected '.format(:green,:bold)}" + 'upstream to bitbucket/master' else log "#{'Found '.format(:green,:bold)}" + 'upstream connection to bitbucket/master' end log "#{'Pushing '.format(:green,:bold)}" + 'latest commit to bitbucket/master...' console_command('git push bitbucket --all', true) end end def create_repo(repo_name) bitbucket.repos.create(name: repo_name, is_private: true) rescue ::BitBucket::Error::Unauthorized => e raise "Bitbucket user #{config[:bitbucket][:user]} does not seem to exist: #{e.message}" end end