]>
git.proxmox.com Git - mirror_iproute2.git/blob - tipc/cmdl.c
2 * cmdl.c Framework for handling command line options.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
9 * Authors: Richard Alpe <richard.alpe@ericsson.com>
16 #include <libmnl/libmnl.h>
20 const struct cmd
*find_cmd(const struct cmd
*cmds
, char *str
)
23 const struct cmd
*match
= NULL
;
25 for (c
= cmds
; c
->cmd
; c
++) {
26 if (strstr(c
->cmd
, str
) != c
->cmd
)
36 static struct opt
*find_opt(struct opt
*opts
, char *str
)
39 struct opt
*match
= NULL
;
41 for (o
= opts
; o
->key
; o
++) {
42 if (strstr(o
->key
, str
) != o
->key
)
53 struct opt
*get_opt(struct opt
*opts
, char *key
)
57 for (o
= opts
; o
->key
; o
++) {
58 if (strcmp(o
->key
, key
) == 0 && o
->val
)
65 bool has_opt(struct opt
*opts
, char *key
)
67 return get_opt(opts
, key
) ? true : false;
70 char *shift_cmdl(struct cmdl
*cmdl
)
74 if (cmdl
->optind
< cmdl
->argc
)
75 next
= (cmdl
->optind
)++;
79 return cmdl
->argv
[next
];
82 /* Returns the number of options parsed or a negative error code upon failure */
83 int parse_opts(struct opt
*opts
, struct cmdl
*cmdl
)
88 for (i
= cmdl
->optind
; i
< cmdl
->argc
; i
++) {
91 o
= find_opt(opts
, cmdl
->argv
[i
]);
93 fprintf(stderr
, "error, invalid option \"%s\"\n",
97 if (o
->flag
& OPT_KEYVAL
) {
102 o
->val
= cmdl
->argv
[i
];
109 int run_cmd(struct nlmsghdr
*nlh
, const struct cmd
*caller
,
110 const struct cmd
*cmds
, struct cmdl
*cmdl
, void *data
)
113 const struct cmd
*cmd
;
115 if ((cmdl
->optind
) >= cmdl
->argc
) {
117 (caller
->help
)(cmdl
);
120 name
= cmdl
->argv
[cmdl
->optind
];
123 cmd
= find_cmd(cmds
, name
);
125 /* Show help about last command if we don't find this one */
126 if (help_flag
&& caller
->help
) {
127 (caller
->help
)(cmdl
);
129 fprintf(stderr
, "error, invalid command \"%s\"\n", name
);
130 fprintf(stderr
, "use --help for command help\n");
135 return (cmd
->func
)(nlh
, cmd
, cmdl
, data
);