2020-10-10 14:16:11 +02:00
|
|
|
# typed: false
|
2019-04-19 15:38:03 +09:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2020-11-05 17:17:03 -05:00
|
|
|
# Performs {Formula#mktemp}'s functionality, and tracks the results.
|
2018-07-13 14:42:49 +01:00
|
|
|
# Each instance is only intended to be used once.
|
|
|
|
class Mktemp
|
|
|
|
include FileUtils
|
|
|
|
|
2020-11-05 17:17:03 -05:00
|
|
|
# Path to the tmpdir used in this run, as a {Pathname}.
|
2018-07-13 14:42:49 +01:00
|
|
|
attr_reader :tmpdir
|
|
|
|
|
|
|
|
def initialize(prefix = name, opts = {})
|
|
|
|
@prefix = prefix
|
|
|
|
@retain = opts[:retain]
|
|
|
|
@quiet = false
|
|
|
|
end
|
|
|
|
|
2020-11-05 17:17:03 -05:00
|
|
|
# Instructs this {Mktemp} to retain the staged files.
|
2018-07-13 14:42:49 +01:00
|
|
|
def retain!
|
|
|
|
@retain = true
|
|
|
|
end
|
|
|
|
|
2020-11-05 17:17:03 -05:00
|
|
|
# True if the staged temporary files should be retained.
|
2018-07-13 14:42:49 +01:00
|
|
|
def retain?
|
|
|
|
@retain
|
|
|
|
end
|
|
|
|
|
2020-11-05 17:17:03 -05:00
|
|
|
# Instructs this Mktemp to not emit messages when retention is triggered.
|
2018-07-13 14:42:49 +01:00
|
|
|
def quiet!
|
|
|
|
@quiet = true
|
|
|
|
end
|
|
|
|
|
|
|
|
def to_s
|
|
|
|
"[Mktemp: #{tmpdir} retain=#{@retain} quiet=#{@quiet}]"
|
|
|
|
end
|
|
|
|
|
|
|
|
def run
|
|
|
|
@tmpdir = Pathname.new(Dir.mktmpdir("#{@prefix}-", HOMEBREW_TEMP))
|
|
|
|
|
|
|
|
# Make sure files inside the temporary directory have the same group as the
|
|
|
|
# brew instance.
|
|
|
|
#
|
|
|
|
# Reference from `man 2 open`
|
|
|
|
# > When a new file is created, it is given the group of the directory which
|
|
|
|
# contains it.
|
|
|
|
group_id = if HOMEBREW_BREW_FILE.grpowned?
|
|
|
|
HOMEBREW_BREW_FILE.stat.gid
|
|
|
|
else
|
|
|
|
Process.gid
|
|
|
|
end
|
|
|
|
begin
|
|
|
|
chown(nil, group_id, tmpdir)
|
|
|
|
rescue Errno::EPERM
|
|
|
|
opoo "Failed setting group \"#{Etc.getgrgid(group_id).name}\" on #{tmpdir}"
|
|
|
|
end
|
|
|
|
|
|
|
|
begin
|
|
|
|
Dir.chdir(tmpdir) { yield self }
|
|
|
|
ensure
|
|
|
|
ignore_interrupts { rm_rf(tmpdir) } unless retain?
|
|
|
|
end
|
|
|
|
ensure
|
|
|
|
if retain? && !@tmpdir.nil? && !@quiet
|
|
|
|
ohai "Kept temporary files"
|
|
|
|
puts "Temporary files retained at #{@tmpdir}"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|