Add builtin -q

Used to query for a builtin's existence, like `type -q` and `functions
-q` can be used to query for a things and a functions existence respectively.
This commit is contained in:
Fabian Homborg 2019-02-09 12:34:00 +01:00
parent 3382a2145f
commit fb7a6e5f34
5 changed files with 42 additions and 3 deletions

View file

@ -2,7 +2,8 @@
\subsection builtin-synopsis Synopsis
\fish{synopsis}
builtin BUILTINNAME [OPTIONS...]
builtin [OPTIONS...] BUILTINNAME
builtin --query BUILTINNAMES...
\endfish
\subsection builtin-description Description
@ -12,6 +13,7 @@ builtin BUILTINNAME [OPTIONS...]
The following parameters are available:
- `-n` or `--names` List the names of all defined builtins
- `-q` or `--query` tests if any of the specified builtins exists.
\subsection builtin-example Example

View file

@ -17,10 +17,13 @@
struct builtin_cmd_opts_t {
bool print_help = false;
bool list_names = false;
bool query = false;
};
static const wchar_t *const short_options = L":hn";
static const wchar_t *const short_options = L":hnq";
static const struct woption long_options[] = {
{L"help", no_argument, NULL, 'h'}, {L"names", no_argument, NULL, 'n'}, {NULL, 0, NULL, 0}};
{L"help", no_argument, NULL, 'h'}, {L"names", no_argument, NULL, 'n'},
{L"query", no_argument, NULL, 'q'},
{NULL, 0, NULL, 0}};
static int parse_cmd_opts(builtin_cmd_opts_t &opts, int *optind, int argc, wchar_t **argv,
parser_t &parser, io_streams_t &streams) {
@ -37,6 +40,10 @@ static int parse_cmd_opts(builtin_cmd_opts_t &opts, int *optind, int argc, wchar
opts.list_names = true;
break;
}
case 'q': {
opts.query = true;
break;
}
case ':': {
builtin_missing_argument(parser, streams, cmd, argv[w.woptind - 1]);
return STATUS_INVALID_ARGS;
@ -73,6 +80,24 @@ int builtin_builtin(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
return STATUS_CMD_OK;
}
if (opts.query && opts.list_names) {
streams.err.append_format(BUILTIN_ERR_COMBO2, cmd,
_(L"--query and --names are mutually exclusive"));
return STATUS_INVALID_ARGS;
}
if (opts.query) {
wcstring_list_t names = builtin_get_names();
retval = STATUS_CMD_ERROR;
for (int i = optind; i < argc; i++) {
if (contains(names, argv[i])) {
retval = STATUS_CMD_OK;
break;
}
}
return retval;
}
if (opts.list_names) {
wcstring_list_t names = builtin_get_names();
std::sort(names.begin(), names.end());

View file

@ -0,0 +1,2 @@
builtin: Invalid combination of options,
--query and --names are mutually exclusive

View file

@ -0,0 +1,7 @@
# Tests for the "builtin" builtin/keyword.
builtin -q string; and echo String exists
builtin -q; and echo None exists
builtin -q string echo banana; and echo Some of these exist
builtin -nq string
echo $status
exit 0

View file

@ -0,0 +1,3 @@
String exists
Some of these exist
2