1 API usage examples
Dorian edited this page 2017-02-03 16:03:14 -08:00

drone-builds:

#!/usr/bin/env ruby

# A simple script to get the list of builds with some quick info about them,
# and the possibility to get the build logs for a build that can be filtered to only
# show failing files or failing lines
#
# USAGE:
#  drone-builds
#  drone-builds ID
#  drone-builds ID --files
#  drone-builds ID --lines

require 'open-uri'
require 'json'

# Store your DRONECI_TOKEN is your ~/.env
ENV_CONTENT = File.read(ENV['HOME'] + '/.env')
HOME_ENV = Hash[*ENV_CONTENT.lines.map { |l| l.strip.split("=") }.flatten]
DRONE_API_TOKEN = HOME_ENV['DRONECI_TOKEN']

OWNER      = "your_org_name"
NAME       = "your_repo_name"
DOMAIN     = "ci.server.name"
BASE_URL   = DOMAIN + "/api"
BUILDS_URL = BASE_URL + "/repos/#{OWNER}/#{NAME}/builds"
LOGS_URL   = BASE_URL + "/repos/#{OWNER}/#{NAME}/logs/:build_id/1"

def api(url)
  url << "?access_token=#{DRONE_API_TOKEN}"
  text = open(url).read
  JSON.parse(text) rescue text
end

if ARGV.first
  text = api(LOGS_URL.gsub(':build_id', ARGV.first))
  if ARGV[1] == "--lines"
    puts text.lines.grep(%r{rspec \./spec/}).map { |l| l.split('#').first }.join("\n")
  elsif ARGV[1] == "--files"
    puts text.lines.grep(%r{rspec \./spec/}).map { |l| l.split(':').first.split.last }.uniq.join("\n")
  else
    puts text
  end
else
  puts "id | ref | status | message"
  api(BUILDS_URL).reverse.last(10).each do |build|
    puts [
      build["id"],
      build["ref"].gsub("refs/heads/", "").gsub("/head", ""),
      build["status"],
      build["message"].lines.first
    ].join(" | ")
  end
end