Class: Appship::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/appship/runner.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(verbose: false) ⇒ Runner

Returns a new instance of Runner.



7
8
9
# File 'lib/appship/runner.rb', line 7

def initialize(verbose: false)
  @verbose = verbose
end

Instance Attribute Details

#verboseObject (readonly)

Returns the value of attribute verbose.



5
6
7
# File 'lib/appship/runner.rb', line 5

def verbose
  @verbose
end

Class Method Details

.which(command) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/appship/runner.rb', line 11

def self.which(command)
  ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).each do |directory|
    candidate = File.join(directory, command)
    return candidate if File.file?(candidate) && File.executable?(candidate)
  end
  nil
end

Instance Method Details

#capture!(argv, chdir: nil, env: {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/appship/runner.rb', line 43

def capture!(argv, chdir: nil, env: {})
  spawn_options = {}
  spawn_options[:chdir] = chdir if chdir
  stdout, stderr, status = Open3.capture3(env, *argv, **spawn_options)
  return stdout if status.success?

  detail = [stdout, stderr].reject(&:empty?).join("\n")
  raise CommandError, "命令执行失败: #{Shellwords.join(argv)}\n#{detail}"
rescue Errno::ENOENT
  raise ConfigurationError, "找不到命令: #{argv.first}"
end

#require_command!(command, explanation = nil) ⇒ Object

Raises:



19
20
21
22
23
24
25
# File 'lib/appship/runner.rb', line 19

def require_command!(command, explanation = nil)
  return Runner.which(command) if Runner.which(command)

  message = "找不到命令: #{command}"
  message += "#{explanation}" if explanation
  raise ConfigurationError, message
end

#run!(argv, chdir: nil, env: {}) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/appship/runner.rb', line 27

def run!(argv, chdir: nil, env: {})
  puts "$ #{Shellwords.join(argv)}" if verbose
  status = nil
  spawn_options = {}
  spawn_options[:chdir] = chdir if chdir
  Open3.popen2e(env, *argv, **spawn_options) do |_stdin, output, wait_thread|
    output.each_line { |line| print line }
    status = wait_thread.value
  end
  return true if status&.success?

  raise CommandError, "命令执行失败(退出码 #{status&.exitstatus || "unknown"}): #{argv.first}"
rescue Errno::ENOENT
  raise ConfigurationError, "找不到命令: #{argv.first}"
end