Class: SystemCommand

Inherits:
Object show all
Includes:
Context
Defined in:
system_command.rb

Overview

This class is part of an internal API. This class may only be used internally in repositories owned by Homebrew, except in casks or formulae. Third parties should avoid using this class if possible, as it may be removed or changed without warning.

Class for running sub-processes and capturing their output and exit status.

Defined Under Namespace

Modules: Helpers, Mixin Classes: Result

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Context

current, current=, #deferred_environment_expansion?, #quiet?, #with_context

Constructor Details

#initialize(executable, args: [], sudo: false, sudo_as_root: false, env: {}, input: [], must_succeed: false, print_stdout: false, print_stderr: true, debug: nil, verbose: nil, secrets: [], chdir: nil, timeout: nil) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • executable (String, Pathname)
  • args (Array<String, Integer, Float, Pathname>) (defaults to: [])
  • sudo (Boolean) (defaults to: false)
  • sudo_as_root (Boolean) (defaults to: false)
  • env (Hash{String => String, Boolean, PATH, nil}) (defaults to: {})
  • input (String, Array<String>) (defaults to: [])
  • must_succeed (Boolean) (defaults to: false)
  • print_stdout (Boolean, Symbol) (defaults to: false)
  • print_stderr (Boolean, Symbol) (defaults to: true)
  • debug (Boolean, nil) (defaults to: nil)
  • verbose (Boolean, nil) (defaults to: nil)
  • secrets (String, Array<String>) (defaults to: [])
  • chdir (String, Pathname, nil) (defaults to: nil)
  • timeout (Integer, Float, nil) (defaults to: nil)

Raises:

  • (ArgumentError)


321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'system_command.rb', line 321

def initialize(executable, args: [], sudo: false, sudo_as_root: false, env: {}, input: [], must_succeed: false,
               print_stdout: false, print_stderr: true, debug: nil, verbose: nil, secrets: [], chdir: nil,
               timeout: nil)
  @expanded_args = T.let(nil, T.nilable(T::Array[String]))

  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
  env.each_key do |name|
    next if /^[\w&&\D]\w*$/.match?(name)

    raise ArgumentError, "Invalid variable name: #{name}"
  end
  @env = env
  @input = T.let(Array(input), T::Array[String])
  @must_succeed = must_succeed
  @print_stdout = print_stdout
  @print_stderr = print_stderr
  @debug = debug
  @verbose = verbose
  resolved_secrets = (Array(secrets) + ENV.sensitive_environment.values).uniq
  @secrets = T.let(resolved_secrets, T::Array[String])
  @chdir = chdir
  @timeout = timeout
  @sandbox = T.let(nil, T.nilable(Sandbox))
  @sandbox_inheritance = T.let(nil, T.nilable(IO))
end

Instance Attribute Details

#sandbox=(value) ⇒ void (writeonly)

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



104
105
106
# File 'system_command.rb', line 104

def sandbox=(value)
  @sandbox = value
end

#sandbox_inheritance=(value) ⇒ IO (writeonly)

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:

  • (IO)


107
108
109
# File 'system_command.rb', line 107

def sandbox_inheritance=(value)
  @sandbox_inheritance = value
end

Class Method Details

.quiet_system(executable, *positional_args, args: [], env: {}) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



229
230
231
232
233
234
235
# File 'system_command.rb', line 229

def self.quiet_system(executable, *positional_args, args: [], env: {})
  return false if executable.nil? || positional_args.any?(&:nil?) || args.any?(&:nil?)

  # Redirect output streams to `/dev/null` instead of closing as some programs
  # will fail to execute if they can't write to an open stream.
  attached_success?(executable, positional_args.compact + args.compact, env:, out: File::NULL, err: File::NULL)
end

.run(executable, args: [], sudo: false, sudo_as_root: false, env: {}, input: [], must_succeed: false, print_stdout: false, print_stderr: true, debug: nil, verbose: nil, secrets: [], chdir: nil, timeout: nil) ⇒ SystemCommand::Result

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • executable (String, Pathname)
  • args (Array<String, Integer, Float, Pathname>) (defaults to: [])
  • sudo (Boolean, nil) (defaults to: false)
  • sudo_as_root (Boolean) (defaults to: false)
  • env (Hash{String => String, Boolean, PATH, nil}) (defaults to: {})
  • input (String, Array<String>) (defaults to: [])
  • must_succeed (Boolean) (defaults to: false)
  • print_stdout (Boolean, Symbol) (defaults to: false)
  • print_stderr (Boolean, Symbol) (defaults to: true)
  • debug (Boolean, nil) (defaults to: nil)
  • verbose (Boolean, nil) (defaults to: nil)
  • secrets (String, Array<String>) (defaults to: [])
  • chdir (String, Pathname, nil) (defaults to: nil)
  • timeout (Integer, Float, nil) (defaults to: nil)

Returns:



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'system_command.rb', line 127

def self.run(executable, args: [], sudo: false, sudo_as_root: false, env: {}, input: [], must_succeed: false,
             print_stdout: false, print_stderr: true, debug: nil, verbose: nil, secrets: [], chdir: nil,
             timeout: nil)
  # Only use sudo: nil for operations that can safely be retried.
  if sudo.nil?
    result = new(executable, args:, sudo: false, sudo_as_root: false, env:, input:, must_succeed: false,
                 print_stdout:, print_stderr: Homebrew::EnvConfig.no_sudo? ? print_stderr : false,
                 debug:, verbose:, secrets:, chdir:, timeout:).run!
    if result.success? || !sudo_available?
      result.assert_success! if must_succeed
      return result
    end
    sudo = true
  end

  new(executable, args:, sudo:, sudo_as_root:, env:, input:, must_succeed:, print_stdout:, print_stderr:, debug:,
      verbose:, secrets:, chdir:, timeout:).run!
end

.run!(executable, args: [], sudo: false, sudo_as_root: false, env: {}, input: [], must_succeed: true, print_stdout: false, print_stderr: true, debug: nil, verbose: nil, secrets: [], chdir: nil, timeout: nil) ⇒ SystemCommand::Result

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

  • executable (String, Pathname)
  • args (Array<String, Integer, Float, Pathname>) (defaults to: [])
  • sudo (Boolean, nil) (defaults to: false)
  • sudo_as_root (Boolean) (defaults to: false)
  • env (Hash{String => String, Boolean, PATH, nil}) (defaults to: {})
  • input (String, Array<String>) (defaults to: [])
  • must_succeed (Boolean) (defaults to: true)
  • print_stdout (Boolean, Symbol) (defaults to: false)
  • print_stderr (Boolean, Symbol) (defaults to: true)
  • debug (Boolean, nil) (defaults to: nil)
  • verbose (Boolean, nil) (defaults to: nil)
  • secrets (String, Array<String>) (defaults to: [])
  • chdir (String, Pathname, nil) (defaults to: nil)
  • timeout (Integer, Float, nil) (defaults to: nil)

Returns:



176
177
178
179
180
181
# File 'system_command.rb', line 176

def self.run!(executable, args: [], sudo: false, sudo_as_root: false, env: {}, input: [], must_succeed: true,
              print_stdout: false, print_stderr: true, debug: nil, verbose: nil, secrets: [], chdir: nil,
              timeout: nil)
  run(executable, args:, sudo:, sudo_as_root:, env:, input:, must_succeed:, print_stdout:, print_stderr:,
      debug:, verbose:, secrets:, chdir:, timeout:)
end

.safe_system(executable, *positional_args, args: [], env: {}, out: nil) ⇒ void

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.

Run a command attached to the caller's standard streams and terminal, raising if it fails. Unlike run! nothing is captured, so interactive programs such as editors and pagers work. Pass a built-up array of arguments as args: rather than splatting it.

Parameters:

Raises:

  • (ArgumentError)


196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'system_command.rb', line 196

def self.safe_system(executable, *positional_args, args: [], env: {}, out: nil)
  raise ArgumentError, "Missing executable" if executable.nil?
  raise ArgumentError, "Invalid nil command argument" if positional_args.any?(&:nil?) || args.any?(&:nil?)

  args = positional_args.compact + args.compact
  if Context.current.verbose?
    command = "#{executable} #{args.join(" ")}".gsub(RUBY_PATH.to_s, "ruby")
                                               .gsub($LOAD_PATH.join(File::PATH_SEPARATOR), "$LOAD_PATH")
    stream = if out == :err
      $stderr
    else
      $stdout
    end
    stream.puts Formatter.redact_secrets(command, secrets)
  end
  return if attached_success?(executable, args, env:, out:)

  raise ErrorDuringExecution.new([executable, *args], status: $CHILD_STATUS, secrets:)
end

.sudo_available? ⇒ Boolean

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Check access once, when a command first needs sudo.

Returns:

  • (Boolean)


148
149
150
151
152
153
154
155
156
# File 'system_command.rb', line 148

def self.sudo_available?
  return false if Homebrew::EnvConfig.no_sudo?
  return true if ENV["HOMEBREW_SUDO_CHECKED"] == "1"

  ENV["HOMEBREW_NO_SUDO"] = "1" unless run("/bin/bash", args:         [HOMEBREW_LIBRARY_PATH/"utils/sudo.sh"],
                                                        print_stderr: false).success?
  ENV["HOMEBREW_SUDO_CHECKED"] = "1"
  !Homebrew::EnvConfig.no_sudo?
end

Instance Method Details

#command ⇒ Array<String>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Returns:



362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'system_command.rb', line 362

def command
  prefix = if sudo?
    unless self.class.sudo_available?
      raise ErrorDuringExecution.new([executable.to_s, *expanded_args], status: 1, secrets: @secrets,
                                     output: [[:stderr, "sudo is unavailable or disabled by HOMEBREW_NO_SUDO.\n"]])
    end

    askpass_flags = ENV.key?("SUDO_ASKPASS") ? ["-A"] : []
    user_flags = []
    if Homebrew::EnvConfig.sudo_through_sudo_user?
      if homebrew_sudo_user.blank?
        raise ArgumentError, "`$HOMEBREW_SUDO_THROUGH_SUDO_USER` set but `$SUDO_USER` unset!"
      end

      user_flags += ["--prompt", "Password for %p:", "-u", homebrew_sudo_user,
                     *askpass_flags,
                     "-E", *env_args,
                     "--", "/usr/bin/sudo"]
    end
    user_flags += ["-u", "root"] if @sudo_as_root
    ["/usr/bin/sudo", *user_flags, *askpass_flags, "-E", *env_args, "--"]
  else
    ["/usr/bin/env"]
  end
  [*prefix, executable.to_s, *expanded_args]
end

#run! ⇒ SystemCommand::Result

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'system_command.rb', line 272

def run!
  $stderr.puts Formatter.redact_secrets(command.shelljoin.gsub('\=', "="), @secrets) if verbose? && debug?

  output = T.let([], T::Array[[Symbol, String]])

  status = each_output_line do |type, line|
    case type
    when :stdout
      case @print_stdout
      when true
        $stdout << Formatter.redact_secrets(line, @secrets)
      when :debug
        $stderr << Formatter.redact_secrets(line, @secrets) if debug?
      end
      output << [:stdout, line]
    when :stderr
      case @print_stderr
      when true
        $stderr << Formatter.redact_secrets(line, @secrets)
      when :debug
        $stderr << Formatter.redact_secrets(line, @secrets) if debug?
      end
      output << [:stderr, line]
    end
  end

  result = Result.new(command, output, status, secrets: @secrets)
  result.assert_success! if @must_succeed
  result
end