brew/Library/Homebrew/system_command.rb

417 lines
11 KiB
Ruby
Raw Normal View History

2020-11-25 17:03:23 +01:00
# typed: true
# frozen_string_literal: true
require "open3"
require "plist"
require "shellwords"
require "extend/io"
require "extend/predicable"
require "extend/time"
# Class for running sub-processes and capturing their output and exit status.
2020-08-19 07:33:07 +02:00
#
# @api private
class SystemCommand
using TimeRemaining
2020-11-23 02:05:50 +01:00
# Helper functions for calling {SystemCommand.run}.
module Mixin
def system_command(executable, **options)
SystemCommand.run(executable, **options)
end
2018-07-22 23:13:32 +02:00
def system_command!(command, **options)
SystemCommand.run!(command, **options)
end
end
2018-07-22 23:13:32 +02:00
include Context
extend Predicable
def self.run(executable, **options)
new(executable, **options).run!
end
def self.run!(command, **options)
run(command, **options, must_succeed: true)
end
2020-10-20 12:03:48 +02:00
sig { returns(SystemCommand::Result) }
def run!
2020-12-17 15:45:50 +01:00
$stderr.puts redact_secrets(command.shelljoin.gsub('\=', "="), @secrets) if verbose? || debug?
2018-08-29 19:56:32 +02:00
@output = []
each_output_line do |type, line|
case type
when :stdout
case @print_stdout
when true
$stdout << redact_secrets(line, @secrets)
when :debug
$stderr << redact_secrets(line, @secrets) if debug?
end
2018-08-29 19:56:32 +02:00
@output << [:stdout, line]
when :stderr
case @print_stderr
when true
$stderr << redact_secrets(line, @secrets)
when :debug
$stderr << redact_secrets(line, @secrets) if debug?
end
2018-08-29 19:56:32 +02:00
@output << [:stderr, line]
end
end
result = Result.new(command, @output, @status, secrets: @secrets)
result.assert_success! if must_succeed?
result
end
sig {
2020-11-23 02:05:50 +01:00
params(
executable: T.any(String, Pathname),
args: T::Array[T.any(String, Integer, Float, URI::Generic)],
sudo: T::Boolean,
sudo_as_root: T::Boolean,
2020-11-23 02:05:50 +01:00
env: T::Hash[String, String],
input: T.any(String, T::Array[String]),
must_succeed: T::Boolean,
print_stdout: T.any(T::Boolean, Symbol),
print_stderr: T.any(T::Boolean, Symbol),
debug: T.nilable(T::Boolean),
verbose: T.nilable(T::Boolean),
secrets: T.any(String, T::Array[String]),
2020-11-23 02:05:50 +01:00
chdir: T.any(String, Pathname),
timeout: T.nilable(T.any(Integer, Float)),
2020-11-23 02:05:50 +01:00
).void
}
def initialize(
executable,
args: [],
sudo: false,
sudo_as_root: false,
env: {},
input: [],
must_succeed: false,
print_stdout: false,
print_stderr: true,
debug: nil,
verbose: false,
secrets: [],
chdir: T.unsafe(nil),
timeout: nil
)
require "extend/ENV"
@executable = executable
@args = args
raise ArgumentError, "`sudo_as_root` cannot be set if sudo is false" if !sudo && sudo_as_root
if print_stdout.is_a?(Symbol) && print_stdout != :debug
raise ArgumentError, "`print_stdout` is not a valid symbol"
end
if print_stderr.is_a?(Symbol) && print_stderr != :debug
raise ArgumentError, "`print_stderr` is not a valid symbol"
end
@sudo = sudo
@sudo_as_root = sudo_as_root
2020-11-23 02:05:50 +01:00
env.each_key do |name|
next if /^[\w&&\D]\w*$/.match?(name)
2021-01-26 15:21:24 -05:00
raise ArgumentError, "Invalid variable name: #{name}"
2020-11-23 02:05:50 +01:00
end
@env = env
2020-07-13 22:48:53 +10:00
@input = Array(input)
2020-11-23 02:05:50 +01:00
@must_succeed = must_succeed
@print_stdout = print_stdout
@print_stderr = print_stderr
2020-12-14 12:36:32 -05:00
@debug = debug
@verbose = verbose
@secrets = (Array(secrets) + ENV.sensitive_environment.values).uniq
2020-11-23 02:05:50 +01:00
@chdir = chdir
@timeout = timeout
end
2020-11-23 02:05:50 +01:00
sig { returns(T::Array[String]) }
def command
[*command_prefix, executable.to_s, *expanded_args]
end
private
2020-11-23 02:05:50 +01:00
attr_reader :executable, :args, :input, :chdir, :env
attr_predicate :sudo?, :sudo_as_root?, :must_succeed?
2020-11-23 02:05:50 +01:00
sig { returns(T::Boolean) }
2020-12-14 12:36:32 -05:00
def debug?
return super if @debug.nil?
@debug
end
sig { returns(T::Boolean) }
def verbose?
return super if @verbose.nil?
@verbose
end
2020-11-23 02:05:50 +01:00
sig { returns(T::Array[String]) }
def env_args
2020-11-09 20:15:28 +11:00
set_variables = env.compact.map do |name, value|
sanitized_name = Shellwords.escape(name)
sanitized_value = Shellwords.escape(value)
"#{sanitized_name}=#{sanitized_value}"
end
2018-07-30 10:11:00 +02:00
return [] if set_variables.empty?
set_variables
end
sig { returns(T.nilable(String)) }
def homebrew_sudo_user
ENV.fetch("HOMEBREW_SUDO_USER", nil)
end
2020-11-23 02:05:50 +01:00
sig { returns(T::Array[String]) }
def sudo_prefix
askpass_flags = ENV.key?("SUDO_ASKPASS") ? ["-A"] : []
user_flags = []
if Homebrew::EnvConfig.sudo_through_sudo_user?
raise ArgumentError, "HOMEBREW_SUDO_THROUGH_SUDO_USER set but SUDO_USER unset!" if homebrew_sudo_user.blank?
user_flags += ["--prompt", "Password for %p:", "-u", homebrew_sudo_user,
*askpass_flags,
"-E", *env_args,
"--", "/usr/bin/sudo"]
end
if sudo_as_root?
user_flags += ["-u", "root"]
end
["/usr/bin/sudo", *user_flags, *askpass_flags, "-E", *env_args, "--"]
end
sig { returns(T::Array[String]) }
2023-02-14 13:02:59 +00:00
def env_prefix
["/usr/bin/env", *env_args]
end
sig { returns(T::Array[String]) }
def command_prefix
2023-02-14 13:02:59 +00:00
sudo? ? sudo_prefix : env_prefix
end
2020-11-23 02:05:50 +01:00
sig { returns(T::Array[String]) }
def expanded_args
@expanded_args ||= args.map do |arg|
if arg.respond_to?(:to_path)
File.absolute_path(arg)
2020-11-23 02:05:50 +01:00
elsif arg.is_a?(Integer) || arg.is_a?(Float) || arg.is_a?(URI::Generic)
arg.to_s
else
arg.to_str
end
end
end
class ProcessTerminatedInterrupt < StandardError; end
private_constant :ProcessTerminatedInterrupt
2020-12-17 15:45:50 +01:00
sig { params(block: T.proc.params(type: Symbol, line: String).void).void }
def each_output_line(&block)
executable, *args = command
2020-12-17 15:45:50 +01:00
options = {
# Create a new process group so that we can send `SIGINT` from
# parent to child rather than the child receiving `SIGINT` directly.
2020-12-19 19:30:33 +01:00
pgroup: sudo? ? nil : true,
2020-12-17 15:45:50 +01:00
}
options[:chdir] = chdir if chdir
raw_stdin, raw_stdout, raw_stderr, raw_wait_thr = ignore_interrupts do
2023-04-17 23:30:25 +02:00
Open3.popen3(
env.merge({ "COLUMNS" => Tty.width.to_s }),
[executable, executable],
*args,
**options,
)
2020-12-17 15:45:50 +01:00
end
write_input_to(raw_stdin)
raw_stdin.close_write
2023-10-10 03:39:42 +02:00
thread_context = Context.current
thread_ready_queue = Queue.new
thread_done_queue = Queue.new
line_thread = Thread.new do
2023-10-10 03:39:42 +02:00
# Ensure the new thread inherits the current context.
Context.current = thread_context
Thread.handle_interrupt(ProcessTerminatedInterrupt => :never) do
thread_ready_queue << true
each_line_from [raw_stdout, raw_stderr], &block
end
thread_done_queue.pop
rescue ProcessTerminatedInterrupt
nil
end
end_time = Time.now + @timeout if @timeout
raise Timeout::Error if raw_wait_thr.join(end_time&.remaining).nil?
@status = raw_wait_thr.value
thread_ready_queue.pop
line_thread.raise ProcessTerminatedInterrupt.new
thread_done_queue << true
line_thread.join
2020-12-17 15:45:50 +01:00
rescue Interrupt
2023-04-17 23:30:25 +02:00
Process.kill("INT", raw_wait_thr.pid) if raw_wait_thr && !sudo?
2020-12-17 15:45:50 +01:00
raise Interrupt
rescue SystemCallError => e
@status = $CHILD_STATUS
2018-08-29 19:56:32 +02:00
@output << [:stderr, e.message]
end
2020-12-17 15:45:50 +01:00
sig { params(raw_stdin: IO).void }
def write_input_to(raw_stdin)
input.each(&raw_stdin.method(:write))
end
2020-12-17 15:45:50 +01:00
sig { params(sources: T::Array[IO], _block: T.proc.params(type: Symbol, line: String).void).void }
def each_line_from(sources, &_block)
2021-04-03 06:03:59 +02:00
sources = {
sources[0] => :stdout,
sources[1] => :stderr,
}
pending_interrupt = T.let(false, T::Boolean)
until pending_interrupt || sources.empty?
readable_sources = T.let([], T::Array[IO])
begin
Thread.handle_interrupt(ProcessTerminatedInterrupt => :on_blocking) do
readable_sources = T.must(IO.select(sources.keys)).fetch(0)
end
rescue ProcessTerminatedInterrupt
readable_sources = sources.keys
pending_interrupt = true
end
readable_sources.each do |source|
loop do
line = source.readline_nonblock || ""
yield(sources.fetch(source), line)
end
2021-04-01 15:42:16 +01:00
rescue EOFError
source.close_read
2021-04-03 06:03:59 +02:00
sources.delete(source)
2021-04-01 15:42:16 +01:00
rescue IO::WaitReadable
# We've got all the data that was ready, but the other end of the stream isn't finished yet
end
end
2021-04-03 06:03:59 +02:00
sources.each_key(&:close_read)
end
2020-08-19 07:33:07 +02:00
# Result containing the output and exit status of a finished sub-process.
class Result
include Context
2018-08-29 19:56:32 +02:00
attr_accessor :command, :status, :exit_status
sig {
2020-11-23 02:05:50 +01:00
params(
command: T::Array[String],
output: T::Array[[Symbol, String]],
status: Process::Status,
secrets: T::Array[String],
).void
}
def initialize(command, output, status, secrets:)
2018-08-29 19:56:32 +02:00
@command = command
@output = output
@status = status
@exit_status = status.exitstatus
@secrets = secrets
end
2020-11-23 02:05:50 +01:00
sig { void }
def assert_success!
return if @status.success?
raise ErrorDuringExecution.new(command, status: @status, output: @output, secrets: @secrets)
2018-08-29 19:56:32 +02:00
end
2020-11-23 02:05:50 +01:00
sig { returns(String) }
2018-08-29 19:56:32 +02:00
def stdout
@stdout ||= @output.select { |type,| type == :stdout }
.map { |_, line| line }
.join
end
2020-11-23 02:05:50 +01:00
sig { returns(String) }
2018-08-29 19:56:32 +02:00
def stderr
@stderr ||= @output.select { |type,| type == :stderr }
.map { |_, line| line }
.join
end
2020-11-23 02:05:50 +01:00
sig { returns(String) }
def merged_output
@merged_output ||= @output.map { |_, line| line }
.join
end
2020-11-23 02:05:50 +01:00
sig { returns(T::Boolean) }
def success?
return false if @exit_status.nil?
@exit_status.zero?
end
2020-11-23 02:05:50 +01:00
sig { returns([String, String, Process::Status]) }
2018-07-30 10:11:00 +02:00
def to_ary
[stdout, stderr, status]
end
2020-11-23 02:05:50 +01:00
sig { returns(T.nilable(T.any(Array, Hash))) }
def plist
@plist ||= begin
output = stdout
2020-11-23 02:05:50 +01:00
output = output.sub(/\A(.*?)(\s*<\?\s*xml)/m) do
warn_plist_garbage(T.must(Regexp.last_match(1)))
Regexp.last_match(2)
end
2020-11-23 02:05:50 +01:00
output = output.sub(%r{(<\s*/\s*plist\s*>\s*)(.*?)\Z}m) do
warn_plist_garbage(T.must(Regexp.last_match(2)))
Regexp.last_match(1)
end
2023-02-22 22:52:06 +00:00
Plist.parse_xml(output, marshal: false)
end
end
2020-11-23 02:05:50 +01:00
sig { params(garbage: String).void }
def warn_plist_garbage(garbage)
return unless verbose?
return unless garbage.match?(/\S/)
2018-09-17 02:45:00 +02:00
opoo "Received non-XML output from #{Formatter.identifier(command.first)}:"
$stderr.puts garbage.strip
end
private :warn_plist_garbage
end
end
# Make `system_command` available everywhere.
# FIXME: Include this explicitly only where it is needed.
include SystemCommand::Mixin # rubocop:disable Style/MixinUsage