Sha256: 19109779b2c0bf754a6c48c581349bb3a5d57be59e86438bab29958595864aba

Contents?: true

Size: 1.85 KB

Versions: 11

Compression:

Stored size: 1.85 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"}}}'
      --write-out ', HTTP_CODE: %%{http_code}'
    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))

      body = response.gsub(/, HTTP.*/, "")

      pr_url = nil
      begin
        pr_url = JSON.parse(body)["links"]["html"]["href"]
      rescue StandardError
        raise UnableToCreatePR, "BODY: #{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

11 entries across 11 versions & 1 rubygems

Version Path
groundskeeper-bitcore-0.22.0 lib/groundskeeper/bitbucket.rb
groundskeeper-bitcore-0.21.0 lib/groundskeeper/bitbucket.rb
groundskeeper-bitcore-0.20.1 lib/groundskeeper/bitbucket.rb
groundskeeper-bitcore-0.19.0 lib/groundskeeper/bitbucket.rb
groundskeeper-bitcore-0.18.0 lib/groundskeeper/bitbucket.rb
groundskeeper-bitcore-0.17.0 lib/groundskeeper/bitbucket.rb
groundskeeper-bitcore-0.16.0 lib/groundskeeper/bitbucket.rb
groundskeeper-bitcore-0.15.0 lib/groundskeeper/bitbucket.rb
groundskeeper-bitcore-0.14.0 lib/groundskeeper/bitbucket.rb
groundskeeper-bitcore-0.13.0 lib/groundskeeper/bitbucket.rb
groundskeeper-bitcore-0.12.0 lib/groundskeeper/bitbucket.rb