diff --git a/Library/Homebrew/api/formula.rb b/Library/Homebrew/api/formula.rb index dabdce75d4..3cc9fb2414 100644 --- a/Library/Homebrew/api/formula.rb +++ b/Library/Homebrew/api/formula.rb @@ -16,6 +16,11 @@ module Homebrew end alias generic_formula_api_path formula_api_path + sig { returns(String) } + def cached_formula_json_file + HOMEBREW_CACHE_API/"#{formula_api_path}.json" + end + sig { params(name: String).returns(Hash) } def fetch(name) Homebrew::API.fetch "#{formula_api_path}/#{name}.json" @@ -24,13 +29,29 @@ module Homebrew sig { returns(Array) } def all_formulae @all_formulae ||= begin - json_formulae = JSON.parse((HOMEBREW_CACHE_API/"#{formula_api_path}.json").read) + download_formulae_if_needed + + json_formulae = JSON.parse(cached_formula_json_file.read) json_formulae.to_h do |json_formula| [json_formula["name"], json_formula.except("name")] end end end + + private + + sig { void } + def download_formulae_if_needed + curl_args = %w[--compressed --silent https://formulae.brew.sh/api/formula.json] + if cached_formula_json_file.exist? + last_modified = cached_formula_json_file.mtime.utc + last_modified = last_modified.strftime("%a, %d %b %Y %H:%M:%S GMT") + curl_args = ["--header", "If-Modified-Since: #{last_modified}", *curl_args] + end + + curl_download(*curl_args, to: HOMEBREW_CACHE_API/"#{formula_api_path}.json", max_time: 5) + end end end end diff --git a/Library/Homebrew/cmd/update.sh b/Library/Homebrew/cmd/update.sh index 706fb936dd..e315c6cd3d 100644 --- a/Library/Homebrew/cmd/update.sh +++ b/Library/Homebrew/cmd/update.sh @@ -752,7 +752,7 @@ EOS curl \ "${CURL_DISABLE_CURLRC_ARGS[@]}" \ --fail --compressed --silent --max-time 5 \ - --location --output "${HOMEBREW_CACHE}/api/formula.json" \ + --location --remote-time --output "${HOMEBREW_CACHE}/api/formula.json" \ --user-agent "${HOMEBREW_USER_AGENT_CURL}" \ "https://formulae.brew.sh/api/formula.json" # TODO: we probably want to print an error if this fails.