btrfs-progs: help: add helper for unrecognized option error message

Currently any unrecognized option does not print very usable message and
only dumps the whole help. Other common utilities (eg. from the
util-linux suite) print a short message and point to help. And we're
going to do the same.

Example:

  $ btrfs device add --unknown device path
  btrfs device add: unrecognized option '--unknown'
  Try 'btrfs device add --help' for more information

Signed-off-by: David Sterba <dsterba@suse.com>
master
David Sterba 2019-03-01 20:47:00 +01:00
parent bc78d1f217
commit 309719fb97
2 changed files with 47 additions and 0 deletions

44
help.c
View File

@ -238,6 +238,50 @@ void usage_command(const struct cmd_struct *cmd, int full, int err)
usage_command_usagestr(cmd->usagestr, cmd->token, full, err);
}
__attribute__((noreturn))
void usage_unknown_option(const char * const *usagestr, char **argv)
{
int i;
int c;
int prev = 0;
/*
* Guess the command prefix, until the first option or argument
* specifier
*/
i = 0;
do {
c = usagestr[0][i];
if (c == '<' || c == '[' || (prev == ' ' && c == '-')) {
i--;
break;
}
prev = c;
i++;
} while (c);
/*
* Example:
*
* $ btrfs device add --unknown device path
* btrfs device add: unrecognized option '--unknown'
* Try 'btrfs device add --help' for more information
*/
fprintf(stderr, "%.*s: ", i, usagestr[0]);
if (!optopt) {
/*
* There's no better way to get the exact unrecognized token
* from getopt
*/
fprintf(stderr, "unrecognized option '%s'\n", argv[optind - 1]);
} else {
fprintf(stderr, "invalid option '%c'\n", optopt);
}
fprintf(stderr, "Try '%.*s --help' for more information\n", i, usagestr[0]);
exit(1);
}
__attribute__((noreturn))
void usage(const char * const *usagestr)
{

3
help.h
View File

@ -55,6 +55,9 @@
struct cmd_struct;
struct cmd_group;
__attribute__((noreturn))
void usage_unknown_option(const char * const *usagestr, char **argv);
__attribute__((noreturn))
void usage(const char * const *usagestr);
void usage_command(const struct cmd_struct *cmd, int full, int err);