Sha256: 2201e6fff80e749f379a11f96d5995117c3b7b5588d656e7f600df9ba47c0dc6

Contents?: true

Size: 1.85 KB

Versions: 2

Compression:

Stored size: 1.85 KB

Contents

require 'json'
require "uri"
require "net/https"

module Codacy
  module ClientAPI
    def self.post_results(parsed_result)
      logger.info('Preparing payload...')
      logger.debug(parsed_result)

      project_token = ENV['CODACY_PROJECT_TOKEN']
      codacy_base_api = ENV['CODACY_BASE_API_URL'] || 'https://api.codacy.com'
      commit = Codacy::Git.commit_id
      url = create_url(codacy_base_api, commit)

      result = parsed_result.to_json

      if project_token.to_s == ''
        logger.error 'Could not find Codacy API token, make sure you have it configured in your environment.'
        false
      elsif commit.to_s == ''
        logger.error 'Could not find the current commit, make sure that you are running inside a git project.'
        false
      else
        logger.info('Posting ' + result.to_s.length.to_s + ' bytes to ' + url)
        response = send_request(url, result, project_token)

        logger.info(response)
        response.to_s.include? 'success'
      end
    end

    def self.send_request(url, content, project_token, redirects = 3)
      uri = URI.parse(url)
      http = Net::HTTP.new(uri.host, uri.port)
      request = Net::HTTP::Post.new(uri.path)
      http.use_ssl = uri.scheme == "https"
      request["project_token"] = project_token
      request["Content-Type"] = "application/json"
      request.body = content
      response = http.request(request)

      if [301, 302, 307].include? response.code.to_i and redirects > 0
        redirected_url = response.headers[:location]
        send_request(redirected_url, content, project_token, redirects - 1)
      else
        response.body
      end
    end

    def self.logger
      Codacy::Configuration.logger
    end

    def self.create_url(codacy_base_api, commit)
      commit = commit.gsub(/[^[:alnum:]]/, "")
      codacy_base_api + '/2.0/coverage/' + commit + '/ruby'
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
codacy-coverage-2.1.0 lib/codacy/client.rb
codacy-coverage-2.0.1 lib/codacy/client.rb