diff --git a/Library/Homebrew/bundle/brewfile.rb b/Library/Homebrew/bundle/brewfile.rb index 4c526504d0..992ce4fe03 100644 --- a/Library/Homebrew/bundle/brewfile.rb +++ b/Library/Homebrew/bundle/brewfile.rb @@ -25,7 +25,15 @@ module Homebrew raise "'HOMEBREW_BUNDLE_FILE' cannot be specified with '--global'" if env_bundle_file.present? if user_config_home - "#{user_config_home}/Brewfile" + xdg_path = "#{user_config_home}/Brewfile" + legacy_path = Bundle.exchange_uid_if_needed! { "#{Dir.home}/.Brewfile" } + + # Prefer existing file to maintain backwards compatibility + if File.exist?(xdg_path) || !File.exist?(legacy_path) + xdg_path + else + legacy_path + end else Bundle.exchange_uid_if_needed! do "#{Dir.home}/.Brewfile" diff --git a/Library/Homebrew/bundle/dumper.rb b/Library/Homebrew/bundle/dumper.rb index c5ef1ddb17..c48687583a 100644 --- a/Library/Homebrew/bundle/dumper.rb +++ b/Library/Homebrew/bundle/dumper.rb @@ -81,7 +81,7 @@ module Homebrew sig { params(file: Pathname, content: String).void } def self.write_file(file, content) Bundle.exchange_uid_if_needed! do - FileUtils.mkdir_p file.parent + file.parent.mkpath file.open("w") { |io| io.write content } end end diff --git a/Library/Homebrew/test/bundle/brewfile_spec.rb b/Library/Homebrew/test/bundle/brewfile_spec.rb index febdcb0afe..4b08323418 100644 --- a/Library/Homebrew/test/bundle/brewfile_spec.rb +++ b/Library/Homebrew/test/bundle/brewfile_spec.rb @@ -1,4 +1,3 @@ -# typed: strict # frozen_string_literal: true require "bundle" @@ -173,10 +172,16 @@ RSpec.describe Homebrew::Bundle::Brewfile do end end - context "when HOMEBREW_USER_CONFIG_HOME is set but Brewfile does not exist" do + context "when HOMEBREW_USER_CONFIG_HOME is set but neither Brewfile exists" do let(:config_dir_brewfile_exist) { false } - it "returns the XDG-compliant path when HOMEBREW_USER_CONFIG_HOME is set" do + before do + # Mock that both XDG and legacy Brewfiles don't exist + allow(File).to receive(:exist?).with("/Users/username/.homebrew/Brewfile").and_return(false) + allow(File).to receive(:exist?).with("#{Dir.home}/.Brewfile").and_return(false) + end + + it "returns the XDG path for initial Brewfile creation" do expect(path).to eq(Pathname.new("#{env_user_config_home_value}/Brewfile")) end end