Skip to content

Commit

Permalink
Add Process::Status#exit_code? (#15247)
Browse files Browse the repository at this point in the history
This provides an alternative to #exit_code which raises in this case since #15241.
  • Loading branch information
straight-shoota authored Dec 7, 2024
1 parent f8db68e commit 655b8a5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
10 changes: 10 additions & 0 deletions spec/std/process/status_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ describe Process::Status do
end
end

it "#exit_code?" do
Process::Status.new(exit_status(0)).exit_code?.should eq 0
Process::Status.new(exit_status(1)).exit_code?.should eq 1
Process::Status.new(exit_status(127)).exit_code?.should eq 127
Process::Status.new(exit_status(128)).exit_code?.should eq 128
Process::Status.new(exit_status(255)).exit_code?.should eq 255

status_for(:interrupted).exit_code?.should eq({% if flag?(:unix) %}nil{% else %}LibC::STATUS_CONTROL_C_EXIT.to_i32!{% end %})
end

it "#success?" do
Process::Status.new(exit_status(0)).success?.should be_true
Process::Status.new(exit_status(1)).success?.should be_false
Expand Down
15 changes: 14 additions & 1 deletion src/process/status.cr
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,21 @@ class Process::Status
# Process.new("sleep", ["10"]).tap(&.terminate).wait.exit_code # RuntimeError: Abnormal exit has no exit code
# ```
def exit_code : Int32
exit_code? || raise RuntimeError.new("Abnormal exit has no exit code")
end

# Returns the exit code of the process if it exited normally.
#
# Returns `nil` if the status describes an abnormal exit.
#
# ```
# Process.run("true").exit_code? # => 1
# Process.run("exit 123", shell: true).exit_code? # => 123
# Process.new("sleep", ["10"]).tap(&.terminate).wait.exit_code? # => nil
# ```
def exit_code? : Int32?
{% if flag?(:unix) %}
raise RuntimeError.new("Abnormal exit has no exit code") unless normal_exit?
return unless normal_exit?

# define __WEXITSTATUS(status) (((status) & 0xff00) >> 8)
(@exit_status & 0xff00) >> 8
Expand Down

0 comments on commit 655b8a5

Please sign in to comment.