Repository navigation
Expand file tree
/
Copy pathsystem_command.rb
More file actions
233 lines (182 loc) · 5.56 KB
/
Copy pathsystem_command.rb
File metadata and controls
233 lines (182 loc) · 5.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# frozen_string_literal: true
require "open3"
require "ostruct"
require "plist"
require "shellwords"
require "extend/io"
require "extend/hash_validator"
using HashValidator
require "extend/predicable"
module Kernel
def system_command(*args)
SystemCommand.run(*args)
end
def system_command!(*args)
SystemCommand.run!(*args)
end
end
class SystemCommand
extend Predicable
attr_reader :pid
def self.run(executable, **options)
new(executable, **options).run!
end
def self.run!(command, **options)
run(command, **options, must_succeed: true)
end
def run!
puts redact_secrets(command.shelljoin.gsub('\=', "="), @secrets) if verbose? || ARGV.debug?
@output = []
each_output_line do |type, line|
case type
when :stdout
$stdout << line if print_stdout?
@output << [:stdout, line]
when :stderr
$stderr << line if print_stderr?
@output << [:stderr, line]
end
end
result = Result.new(command, @output, @status, secrets: @secrets)
result.assert_success! if must_succeed?
result
end
def initialize(executable, args: [], sudo: false, env: {}, input: [], must_succeed: false,
print_stdout: false, print_stderr: true, verbose: false, secrets: [], **options)
require "extend/ENV"
@executable = executable
@args = args
@sudo = sudo
@input = [*input]
@print_stdout = print_stdout
@print_stderr = print_stderr
@verbose = verbose
@secrets = (Array(secrets) + ENV.sensitive_environment.values).uniq
@must_succeed = must_succeed
options.assert_valid_keys!(:chdir)
@options = options
@env = env
@env.keys.grep_v(/^[\w&&\D]\w*$/) do |name|
raise ArgumentError, "Invalid variable name: '#{name}'"
end
end
def command
[*sudo_prefix, *env_args, executable.to_s, *expanded_args]
end
private
attr_reader :executable, :args, :input, :options, :env
attr_predicate :sudo?, :print_stdout?, :print_stderr?, :verbose?, :must_succeed?
def env_args
set_variables = env.reject { |_, value| value.nil? }
.map do |name, value|
sanitized_name = Shellwords.escape(name)
sanitized_value = Shellwords.escape(value)
"#{sanitized_name}=#{sanitized_value}"
end
return [] if set_variables.empty?
["/usr/bin/env", *set_variables]
end
def sudo_prefix
return [] unless sudo?
askpass_flags = ENV.key?("SUDO_ASKPASS") ? ["-A"] : []
["/usr/bin/sudo", *askpass_flags, "-E", "--"]
end
def expanded_args
@expanded_args ||= args.map do |arg|
if arg.respond_to?(:to_path)
File.absolute_path(arg)
elsif arg.is_a?(Integer) || arg.is_a?(Float) || arg.is_a?(URI)
arg.to_s
else
arg.to_str
end
end
end
def each_output_line(&b)
executable, *args = command
raw_stdin, raw_stdout, raw_stderr, raw_wait_thr =
Open3.popen3(env, [executable, executable], *args, **options)
@pid = raw_wait_thr.pid
write_input_to(raw_stdin)
raw_stdin.close_write
each_line_from [raw_stdout, raw_stderr], &b
@status = raw_wait_thr.value
rescue SystemCallError => e
@status = $CHILD_STATUS
@output << [:stderr, e.message]
end
def write_input_to(raw_stdin)
input.each(&raw_stdin.method(:write))
end
def each_line_from(sources)
loop do
readable_sources, = IO.select(sources)
readable_sources = readable_sources.reject(&:eof?)
break if readable_sources.empty?
readable_sources.each do |source|
line = source.readline_nonblock || ""
type = (source == sources[0]) ? :stdout : :stderr
yield(type, line)
rescue IO::WaitReadable, EOFError
next
end
end
sources.each(&:close_read)
end
class Result
attr_accessor :command, :status, :exit_status
def initialize(command, output, status, secrets:)
@command = command
@output = output
@status = status
@exit_status = status.exitstatus
@secrets = secrets
end
def assert_success!
return if @status.success?
raise ErrorDuringExecution.new(command, status: @status, output: @output, secrets: @secrets)
end
def stdout
@stdout ||= @output.select { |type,| type == :stdout }
.map { |_, line| line }
.join
end
def stderr
@stderr ||= @output.select { |type,| type == :stderr }
.map { |_, line| line }
.join
end
def merged_output
@merged_output ||= @output.map { |_, line| line }
.join
end
def success?
return false if @exit_status.nil?
@exit_status.zero?
end
def to_ary
[stdout, stderr, status]
end
def plist
@plist ||= begin
output = stdout
if /\A(?<garbage>.*?)<\?\s*xml/m =~ output
output = output.sub(/\A#{Regexp.escape(garbage)}/m, "")
warn_plist_garbage(garbage)
end
if %r{<\s*/\s*plist\s*>(?<garbage>.*?)\Z}m =~ output
output = output.sub(/#{Regexp.escape(garbage)}\Z/, "")
warn_plist_garbage(garbage)
end
Plist.parse_xml(output)
end
end
def warn_plist_garbage(garbage)
return unless ARGV.verbose?
return unless garbage.match?(/\S/)
opoo "Received non-XML output from #{Formatter.identifier(command.first)}:"
$stderr.puts garbage.strip
end
private :warn_plist_garbage
end
end