]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/parse-argument.c
cd1d0dde21a54cbbe0b0074ab2a504f3a23c3db6
[thirdparty/systemd.git] / src / shared / parse-argument.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "format-table.h"
4 #include "parse-argument.h"
5 #include "path-util.h"
6 #include "signal-util.h"
7 #include "stdio-util.h"
8 #include "string-table.h"
9 #include "string-util.h"
10
11 /* All functions in this file emit warnigs. */
12
13 int parse_json_argument(const char *s, JsonFormatFlags *ret) {
14 assert(s);
15 assert(ret);
16
17 if (streq(s, "pretty"))
18 *ret = JSON_FORMAT_PRETTY|JSON_FORMAT_COLOR_AUTO;
19 else if (streq(s, "short"))
20 *ret = JSON_FORMAT_NEWLINE;
21 else if (streq(s, "off"))
22 *ret = JSON_FORMAT_OFF;
23 else if (streq(s, "help")) {
24 puts("pretty\n"
25 "short\n"
26 "off");
27 return 0; /* 0 means → we showed a brief help, exit now */
28 } else
29 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown argument to --json= switch: %s", s);
30
31 return 1; /* 1 means → properly parsed */
32 }
33
34 int parse_path_argument(const char *path, bool suppress_root, char **arg) {
35 char *p;
36 int r;
37
38 /*
39 * This function is intended to be used in command line parsers, to handle paths that are passed
40 * in. It makes the path absolute, and reduces it to NULL if omitted or root (the latter optionally).
41 *
42 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON SUCCESS!
43 * Hence, do not pass in uninitialized pointers.
44 */
45
46 if (isempty(path)) {
47 *arg = mfree(*arg);
48 return 0;
49 }
50
51 r = path_make_absolute_cwd(path, &p);
52 if (r < 0)
53 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
54
55 path_simplify(p, false);
56 if (suppress_root && empty_or_root(p))
57 p = mfree(p);
58
59 return free_and_replace(*arg, p);
60 }
61
62 int parse_signal_argument(const char *s, int *ret) {
63 int r;
64
65 assert(s);
66 assert(ret);
67
68 if (streq(s, "help")) {
69 DUMP_STRING_TABLE(signal, int, _NSIG);
70 return 0;
71 }
72
73 if (streq(s, "list")) {
74 _cleanup_(table_unrefp) Table *table = NULL;
75
76 table = table_new("signal", "name");
77 if (!table)
78 return log_oom();
79
80 for (int i = 1; i < _NSIG; i++) {
81 r = table_add_many(
82 table,
83 TABLE_INT, i,
84 TABLE_SIGNAL, i);
85 if (r < 0)
86 return table_log_add_error(r);
87 }
88
89 r = table_print(table, NULL);
90 if (r < 0)
91 return table_log_print_error(r);
92
93 return 0;
94 }
95
96 r = signal_from_string(s);
97 if (r < 0)
98 return log_error_errno(r, "Failed to parse signal string \"%s\".", s);
99
100 *ret = r;
101 return 1; /* work to do */
102 }