Sha256: 49332b057b901b8b58eb605675a9f9d925c23d05eda6d99eea38262b7daa5424

Contents?: true

Size: 1.75 KB

Versions: 1

Compression:

Stored size: 1.75 KB

Contents

# frozen_string_literal: true

require "json"

module Groundskeeper
  # Bitbucket API wrapper
  class Bitbucket
    # Bitbucket API Error
    class UnableToCreatePR < StandardError
      def initialize(response)
        super
      end
    end

    COMMAND = "curl"
    BITBUCKET_USERNAME = "BITBUCKET_USERNAME"
    BITBUCKET_APP_PASSWORD = "BITBUCKET_APP_PASSWORD"
    URL = "https://api.bitbucket.org/2.0/repositories/"\
          "isgmh-radd/%<repository>s/pullrequests"
    CREATE_PR = <<~REQUEST.split.join(" ")
      #{URL} -u %<username>s:%<password>s
      --request POST
      --header 'Content-Type: application/json'
      --data
      '{"title": "%<branch_name>s", "source": {"branch": {"name": "%<branch_name>s"}}}'
    REQUEST

    attr_reader :bitbucket

    def self.build
      new Executable.new(COMMAND)
    end

    def initialize(bitbucket)
      @bitbucket = bitbucket
    end

    # rubocop:disable Metrics/MethodLength
    def create_pr(repository:, branch_name:)
      response = bitbucket.execute(format(CREATE_PR,
                                          username: ENV[BITBUCKET_USERNAME],
                                          password: ENV[BITBUCKET_APP_PASSWORD],
                                          repository: repository,
                                          branch_name: branch_name))
      pr_url = nil
      begin
        pr_url = JSON.parse(response)["links"]["html"]["href"]
      rescue StandardError
        raise UnableToCreatePR, response
      end

      open_url(pr_url)
    end
    # rubocop:enable Metrics/MethodLength

    def credentials?
      ENV[BITBUCKET_USERNAME].present? && ENV[BITBUCKET_APP_PASSWORD].present?
    end

    private

    # :nocov:
    def open_url(url)
      `open #{url}`
    end
    # :nocov:
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
groundskeeper-bitcore-0.11.0 lib/groundskeeper/bitbucket.rb