From 655b8a58cb95f41eb7eff17e9b58f79d2839f199 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20M=C3=BCller?= Date: Sat, 7 Dec 2024 19:55:40 +0100 Subject: [PATCH] Add `Process::Status#exit_code?` (#15247) This provides an alternative to #exit_code which raises in this case since #15241. --- spec/std/process/status_spec.cr | 10 ++++++++++ src/process/status.cr | 15 ++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/spec/std/process/status_spec.cr b/spec/std/process/status_spec.cr index 96802be31489..5f0c3b597376 100644 --- a/spec/std/process/status_spec.cr +++ b/spec/std/process/status_spec.cr @@ -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 diff --git a/src/process/status.cr b/src/process/status.cr index a3db8a7c4346..738128519f36 100644 --- a/src/process/status.cr +++ b/src/process/status.cr @@ -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