Skip to content

Commit 951601b

Browse files
committed
feat: Process.output return Option type now
- Add exception option for Process.run - Update rubocop config
1 parent f909085 commit 951601b

3 files changed

Lines changed: 39 additions & 4 deletions

File tree

.rubocop.yml

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,17 @@ Metrics/BlockLength:
1010
Metrics/AbcSize:
1111
Enabled: false
1212

13+
Metrics/CyclomaticComplexity:
14+
Enabled: false
15+
16+
Metrics/PerceivedComplexity:
17+
Enabled: false
18+
1319
Style/ConditionalAssignment:
1420
Enabled: false
1521

1622
Style/RaiseArgs:
17-
Enabled: false
23+
Enabled: false
24+
25+
Style/SpecialGlobalVars:
26+
EnforcedStyle: use_builtin_english_names

lib/rb/process.rb

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def success?
3535
alias_method :ok?, :success?
3636
end
3737

38-
def self.run(*args, out: $stdout, err: $stderr, **options)
38+
def self.run(*args, out: $stdout, err: $stderr, exception: false, **options)
3939
stdout_reader, stdout_writer = IO.pipe
4040
stderr_reader, stderr_writer = IO.pipe
4141
childs_io = [stdout_writer, stderr_writer]
@@ -94,10 +94,27 @@ def self.run(*args, out: $stdout, err: $stderr, **options)
9494
else
9595
Err.new(out_strio.string, err_strio.string, status)
9696
end
97+
rescue Errno::ENOENT => e
98+
raise e if exception
99+
100+
Err.new(nil, nil, $?)
97101
end
98102

99-
def self.output(...)
100-
IO.popen(...).read
103+
def self.output(*args, **options)
104+
stdout_reader, stdout_writer = IO.pipe
105+
pid = Process.spawn(*args, **options, out: stdout_writer)
106+
stdout_writer.close
107+
108+
pid, status = Process.wait2(pid)
109+
if status.exited? && status.success?
110+
stdout_reader.read
111+
else
112+
nil
113+
end
114+
rescue Errno::ENOENT
115+
nil
116+
ensure
117+
stdout_reader.close
101118
end
102119

103120
def self.code(...)

spec/rb/process_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,19 @@
4242
end
4343
end
4444

45+
it "not raise by default when Errno::ENOENT" do
46+
expect { Process.run("unamea") }.not_to raise_error
47+
expect { Process.run("unamea", exception: true) }.to raise_error
48+
end
49+
4550
it "get the output and not print" do
4651
expect(Process.output("uname").chomp).to eq "Linux"
4752
end
4853

54+
it "return nil when exec not success" do
55+
expect(Process.output("unamea")).to be_nil
56+
end
57+
4958
it "get array by method chaining" do
5059
expect(Process.output("ls spec").each_line(chomp: true).to_a).to eq ["rb", "spec_helper.rb"]
5160
end

0 commit comments

Comments
 (0)