Add cask-source API

This commit is contained in:
Rylan Polster 2021-08-06 11:56:42 -04:00
parent 0e63fb8200
commit c32223a89c
No known key found for this signature in database
GPG Key ID: 46A744940CFF4D64
3 changed files with 42 additions and 3 deletions

View File

@ -4,6 +4,7 @@
require "api/analytics"
require "api/bottle"
require "api/cask"
require "api/cask-source"
require "api/formula"
require "api/versions"
require "extend/cachable"
@ -21,15 +22,19 @@ module Homebrew
API_DOMAIN = "https://formulae.brew.sh/api"
sig { params(endpoint: String).returns(T.any(String, Hash)) }
def fetch(endpoint)
sig { params(endpoint: String, json: T::Boolean).returns(T.any(String, Hash)) }
def fetch(endpoint, json: true)
return cache[endpoint] if cache.present? && cache.key?(endpoint)
api_url = "#{API_DOMAIN}/#{endpoint}"
output = Utils::Curl.curl_output("--fail", "--max-time", "5", api_url)
raise ArgumentError, "No file found at #{Tty.underline}#{api_url}#{Tty.reset}" unless output.success?
cache[endpoint] = JSON.parse(output.stdout)
cache[endpoint] = if json
JSON.parse(output.stdout)
else
output.stdout
end
rescue JSON::ParserError
raise ArgumentError, "Invalid JSON file: #{Tty.underline}#{api_url}#{Tty.reset}"
end

View File

@ -0,0 +1,28 @@
# typed: false
# frozen_string_literal: true
module Homebrew
module API
# Helper functions for using the cask source API.
#
# @api private
module CaskSource
class << self
extend T::Sig
sig { params(token: String).returns(Hash) }
def fetch(token)
Homebrew::API.fetch "cask-source/#{token}.rb", json: false
end
sig { params(token: String).returns(T::Boolean) }
def available?(token)
fetch token
true
rescue ArgumentError
false
end
end
end
end
end

View File

@ -14,6 +14,12 @@ describe Homebrew::API do
end
describe "::fetch" do
it "fetches a text file" do
mock_curl_output stdout: text
fetched_text = described_class.fetch("foo.txt", json: false)
expect(fetched_text).to eq text
end
it "fetches a JSON file" do
mock_curl_output stdout: json
fetched_json = described_class.fetch("foo.json")