brew/Library/Homebrew/bundle/brewfile.rb

85 lines
2.8 KiB
Ruby
Raw Normal View History

2025-08-21 22:33:39 +08:00
# typed: strict
# frozen_string_literal: true
require "bundle/dsl"
module Homebrew
module Bundle
module Brewfile
2025-08-21 22:33:39 +08:00
sig {
params(
dash_writes_to_stdout: T::Boolean,
global: T::Boolean,
file: T.nilable(String),
).returns(Pathname)
}
def self.path(dash_writes_to_stdout: false, global: false, file: nil)
env_bundle_file_global = ENV.fetch("HOMEBREW_BUNDLE_FILE_GLOBAL", nil)
env_bundle_file = ENV.fetch("HOMEBREW_BUNDLE_FILE", nil)
user_config_home = ENV.fetch("HOMEBREW_USER_CONFIG_HOME", nil)
filename = if global
if env_bundle_file_global.present?
env_bundle_file_global
else
raise "'HOMEBREW_BUNDLE_FILE' cannot be specified with '--global'" if env_bundle_file.present?
# Determine if we're in XDG mode by checking if user_config_home is XDG-based
# In bin/brew: XDG_CONFIG_HOME set -> HOMEBREW_USER_CONFIG_HOME="${XDG_CONFIG_HOME}/homebrew"
# XDG_CONFIG_HOME not set -> HOMEBREW_USER_CONFIG_HOME="${HOME}/.homebrew"
using_xdg = user_config_home&.end_with?("/homebrew")
if using_xdg && user_config_home
# XDG mode: check both XDG and legacy locations, preferring existing files
xdg_brewfile = "#{user_config_home}/Brewfile"
if File.exist?(xdg_brewfile)
xdg_brewfile
else
legacy_brewfile = Bundle.exchange_uid_if_needed! { "#{Dir.home}/.Brewfile" }
File.exist?(legacy_brewfile) ? legacy_brewfile : xdg_brewfile
end
elsif user_config_home && File.exist?("#{user_config_home}/Brewfile")
"#{user_config_home}/Brewfile"
else
Bundle.exchange_uid_if_needed! do
"#{Dir.home}/.Brewfile"
end
end
end
elsif file.present?
handle_file_value(file, dash_writes_to_stdout)
elsif env_bundle_file.present?
env_bundle_file
else
"Brewfile"
end
Pathname.new(filename).expand_path(Dir.pwd)
end
2025-08-21 22:33:39 +08:00
sig { params(global: T::Boolean, file: T.nilable(String)).returns(Dsl) }
def self.read(global: false, file: nil)
Homebrew::Bundle::Dsl.new(Brewfile.path(global:, file:))
rescue Errno::ENOENT
raise "No Brewfile found"
end
2025-08-21 22:33:39 +08:00
sig {
params(
filename: String,
dash_writes_to_stdout: T::Boolean,
).returns(String)
}
private_class_method def self.handle_file_value(filename, dash_writes_to_stdout)
if filename != "-"
filename
elsif dash_writes_to_stdout
"/dev/stdout"
else
"/dev/stdin"
end
end
end
end
end