2 * Copyright (c) 2008, 2009 Nicira Networks.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include "command-line.h"
25 /* Given the GNU-style long options in 'options', returns a string that may be
26 * passed to getopt() with the corresponding short options. The caller is
27 * responsible for freeing the string. */
29 long_options_to_short_options(const struct option options[])
31 char short_options[UCHAR_MAX * 3 + 1];
32 char *p = short_options;
34 for (; options->name; options++) {
35 const struct option *o = options;
36 if (o->flag == NULL && o->val > 0 && o->val <= UCHAR_MAX) {
38 if (o->has_arg == required_argument) {
40 } else if (o->has_arg == optional_argument) {
48 return xstrdup(short_options);
51 /* Runs the command designated by argv[0] within the command table specified by
52 * 'commands', which must be terminated by a command whose 'name' member is a
55 * Command-line options should be stripped off, so that a typical invocation
56 * looks like "run_command(argc - optind, argv + optind, my_commands);". */
58 run_command(int argc, char *argv[], const struct command commands[])
60 const struct command *p;
63 ovs_fatal(0, "missing command name; use --help for help");
66 for (p = commands; p->name != NULL; p++) {
67 if (!strcmp(p->name, argv[0])) {
69 if (n_arg < p->min_args) {
70 ovs_fatal(0, "'%s' command requires at least %d arguments",
71 p->name, p->min_args);
72 } else if (n_arg > p->max_args) {
73 ovs_fatal(0, "'%s' command takes at most %d arguments",
74 p->name, p->max_args);
76 p->handler(argc, argv);
78 ovs_fatal(0, "write to stdout failed");
81 ovs_fatal(0, "write to stderr failed");
88 ovs_fatal(0, "unknown command '%s'; use --help for help", argv[0]);