Sha256: 8161491125d3dcf74beb19c11d0d251b4d535d46bd4d02c4b76326d31c6783af

Contents?: true

Size: 1.39 KB

Versions: 74

Compression:

Stored size: 1.39 KB

Contents

require "faraday"

module Danger
  class CircleAPI
    # Determine if there's a PR attached to this commit,
    # and return a bool
    def pull_request?(env)
      url = pull_request_url(env)
      return !url.nil?
    end

    # Determine if there's a PR attached to this commit,
    # and return the url if so
    def pull_request_url(env)
      url = env["CI_PULL_REQUEST"]

      if url.nil? && !env["CIRCLE_PROJECT_USERNAME"].nil? && !env["CIRCLE_PROJECT_REPONAME"].nil?
        repo_slug = env["CIRCLE_PROJECT_USERNAME"] + "/" + env["CIRCLE_PROJECT_REPONAME"]
        token = env["DANGER_CIRCLE_CI_API_TOKEN"] || env["CIRCLE_CI_API_TOKEN"]
        url = fetch_pull_request_url(repo_slug, env["CIRCLE_BUILD_NUM"], token)
      end
      url
    end

    def client
      @client ||= Faraday.new(url: "https://circleci.com/api/v1")
    end

    # Ask the API if the commit is inside a PR
    def fetch_pull_request_url(repo_slug, build_number, token)
      build_json = fetch_build(repo_slug, build_number, token)
      build_json[:pull_request_urls].first
    end

    # Make the API call, and parse the JSON
    def fetch_build(repo_slug, build_number, token)
      url = "project/#{repo_slug}/#{build_number}"
      params = { "circle-token" => token }
      response = client.get url, params, accept: "application/json"
      json = JSON.parse(response.body, symbolize_names: true)
      json
    end
  end
end

Version data entries

74 entries across 74 versions & 1 rubygems

Version Path
danger-5.5.13 lib/danger/ci_source/circle_api.rb
danger-5.5.12 lib/danger/ci_source/circle_api.rb
danger-5.5.11 lib/danger/ci_source/circle_api.rb
danger-5.5.10 lib/danger/ci_source/circle_api.rb
danger-5.5.9 lib/danger/ci_source/circle_api.rb
danger-5.5.8 lib/danger/ci_source/circle_api.rb
danger-5.5.7 lib/danger/ci_source/circle_api.rb
danger-5.5.6 lib/danger/ci_source/circle_api.rb
danger-5.5.5 lib/danger/ci_source/circle_api.rb
danger-5.5.4 lib/danger/ci_source/circle_api.rb
danger-5.5.3 lib/danger/ci_source/circle_api.rb
danger-5.5.2 lib/danger/ci_source/circle_api.rb
danger-5.5.1 lib/danger/ci_source/circle_api.rb
danger-5.5.0 lib/danger/ci_source/circle_api.rb
danger-5.4.3 lib/danger/ci_source/circle_api.rb
danger-5.4.2 lib/danger/ci_source/circle_api.rb
danger-5.4.1 lib/danger/ci_source/circle_api.rb
danger-5.4.0 lib/danger/ci_source/circle_api.rb
danger-5.3.5 lib/danger/ci_source/circle_api.rb
danger-5.3.4 lib/danger/ci_source/circle_api.rb