]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/verbs.c
util: add generalization of verb parsing for command line tools
[thirdparty/systemd.git] / src / shared / verbs.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4 This file is part of systemd.
5
6 Copyright 2014 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include "util.h"
23 #include "verbs.h"
24
25 int dispatch_verb(int argc, char *argv[], const Verb verbs[], void *userdata) {
26 const Verb *verb;
27 const char *name;
28 unsigned i;
29 int left;
30
31 assert(verbs);
32 assert(verbs[0].dispatch);
33 assert(argc >= 0);
34 assert(argv);
35 assert(argc >= optind);
36
37 left = argc - optind;
38 name = argv[optind];
39
40 for (i = 0;; i++) {
41 bool found;
42
43 /* At the end of the list? */
44 if (!verbs[i].dispatch) {
45 if (name)
46 log_error("Unknown operation %s.", name);
47 else
48 log_error("Requires operation parameter.");
49 return -EINVAL;
50 }
51
52
53 if (!name)
54 found = !!(verbs[i].flags & VERB_DEFAULT);
55 else
56 found = streq(name, verbs[i].verb);
57
58 if (found) {
59 verb = &verbs[i];
60 break;
61 }
62 }
63
64 if (verb->min_args != VERB_ANY &&
65 (unsigned) left < verb->min_args) {
66 log_error("Too few arguments.");
67 return -EINVAL;
68 }
69
70 if (verb->max_args != VERB_ANY &&
71 (unsigned) left > verb->max_args) {
72 log_error("Too many argument.s");
73 return -EINVAL;
74 }
75
76 return verb->dispatch(left, argv + optind, userdata);
77 }