]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
shared/exit-status: add exit_status_from_string()
authorZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Sun, 28 Jul 2019 08:19:53 +0000 (10:19 +0200)
committerZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Mon, 29 Jul 2019 13:54:53 +0000 (15:54 +0200)
src/shared/exit-status.c
src/shared/exit-status.h
src/test/test-exit-status.c

index 51f23800274e956c8636e2071f0142ea06e09bd7..12880f805ebb32ba51e6977b845cd4f70af82f7e 100644 (file)
@@ -6,7 +6,9 @@
 
 #include "exit-status.h"
 #include "macro.h"
+#include "parse-util.h"
 #include "set.h"
+#include "string-util.h"
 
 const ExitStatusMapping exit_status_mappings[256] = {
         /* Exit status ranges:
@@ -117,6 +119,21 @@ const char* exit_status_class(int code) {
         }
 }
 
+int exit_status_from_string(const char *s) {
+        uint8_t val;
+        int r;
+
+        for (size_t i = 0; i < ELEMENTSOF(exit_status_mappings); i++)
+                if (streq_ptr(s, exit_status_mappings[i].name))
+                        return i;
+
+        r = safe_atou8(s, &val);
+        if (r < 0)
+                return r;
+
+        return val;
+}
+
 bool is_clean_exit(int code, int status, ExitClean clean, ExitStatusSet *success_status) {
         if (code == CLD_EXITED)
                 return status == 0 ||
index 425f8415234a34824fabe659e34b122743b3525d..24eba79f560a1647bd2e4108e0c01e400dd0e653 100644 (file)
@@ -89,6 +89,7 @@ typedef struct ExitStatusSet {
 
 const char* exit_status_to_string(int code, ExitStatusClass class) _const_;
 const char* exit_status_class(int code) _const_;
+int exit_status_from_string(const char *s) _pure_;
 
 typedef struct ExitStatusMapping {
         const char *name;
index bab0596580c35685b8952c4bd4f0bc3a0f11722a..3bcebd06a481d87ac3e978fc9d4796c2c9a8581e 100644 (file)
@@ -14,13 +14,28 @@ static void test_exit_status_to_string(void) {
                 log_info("%d: %s%s%s%s",
                          i, s ?: "-",
                          class ? " (" : "", class ?: "", class ? ")" : "");
+
+                if (s)
+                        assert_se(exit_status_from_string(s) == i);
         }
 }
 
+static void test_exit_status_from_string(void) {
+        log_info("/* %s */", __func__);
+
+        assert_se(exit_status_from_string("11") == 11);
+        assert_se(exit_status_from_string("-1") == -ERANGE);
+        assert_se(exit_status_from_string("256") == -ERANGE);
+        assert_se(exit_status_from_string("foo") == -EINVAL);
+        assert_se(exit_status_from_string("SUCCESS") == 0);
+        assert_se(exit_status_from_string("FAILURE") == 1);
+}
+
 int main(int argc, char *argv[]) {
         test_setup_logging(LOG_DEBUG);
 
         test_exit_status_to_string();
+        test_exit_status_from_string();
 
         return 0;
 }