ghp (2890B)
1 #!/usr/bin/env ruby 2 # A script that lets you check build status of github pages and trigger new 3 # builds. You can check one or more pages at once, the script minimizes 4 # requests using etag values. 5 require 'open-uri' 6 require 'net/http' 7 require 'json' 8 9 class Page 10 def initialize name 11 @url = "https://api.github.com/repos/#{ENV['GITHUB_AUTH_USER']}/#{name}/pages/builds" 12 @name = name 13 @headers = {'Authorization' => "token #{ENV['GITHUB_AUTH_TOKEN']}"} 14 end 15 16 def get_status 17 begin 18 if @etag 19 response = URI.open("#{@url}/latest", @headers.merge({'If-None-Match' => @etag})) 20 else 21 response = URI.open("#{@url}/latest", @headers) 22 end 23 j = JSON.parse(response.read) 24 @etag = response.meta['etag'] 25 @code = response.status.first 26 @created_at = j['created_at'] 27 @updated_at = j['updated_at'] 28 @status = j['status'] 29 @error = j['error']['message'] 30 rescue OpenURI::HTTPError => err 31 if err.io.status.first == '304' 32 @etag = err.io.meta['etag'] 33 @code = err.io.status.first 34 else 35 @code = err.io.status.first 36 end 37 end 38 end 39 40 def build 41 response = Net::HTTP.post URI(@url), nil, @headers 42 if response.code == '201' 43 j = JSON.parse(response.body) 44 @code = response.code 45 @etag = response['etag'] 46 @status = j['status'] 47 else 48 @code = response.code 49 end 50 end 51 def to_str 52 str = "#{@name}: #{@status}" 53 str += ", #{@updated_at}" unless @updated_at.nil? 54 str += ", #{@error}" unless @error.nil? 55 str += "not found" if @code == '404' 56 str += "." 57 end 58 end 59 60 subcmd = ARGV.shift 61 62 if ["build", "b"].include? subcmd 63 if ARGV.size > 0 64 values = ARGV.map do |page| 65 Thread.new do 66 p = Page.new page 67 p.build 68 p.to_str 69 end 70 end.map(&:value) 71 72 puts "Builds:" 73 values.each { |v| puts v } 74 else 75 puts "Provide the name of one or more repositories." 76 end 77 elsif ["watch", "w", "status", "s"].include? subcmd 78 if ARGV.size > 0 79 pages = ARGV.map { |p| Page.new p } 80 while true 81 values = pages.map do |page| 82 Thread.new { page.get_status; page.to_str } 83 end.map(&:value) 84 85 system "clear" 86 puts "Status:" 87 values.each { |v| puts v } 88 end 89 else 90 puts "Provide the name of one or more repositories." 91 end 92 elsif ["rate", "remaining", "r"].include? subcmd 93 response = URI.open("https://api.github.com/rate_limit", 'Authorization' => "token #{ENV['GITHUB_AUTH_TOKEN']}") 94 j = JSON.parse(response.read) 95 core = j['resources']['core'] 96 puts "Requests remaining: #{core['remaining']}/#{core['limit']}" 97 else 98 puts <<-YEET 99 Available commands: 100 101 watch, w, status, s print out the status of pages 102 build, b trigger a build of a page 103 rate, remaining, r print out the number of remaining API requests 104 YEET 105 106 end