shared/shell: add --zsh-complete option
authorRonan Pigott <rpigott@berkeley.edu>
Sat, 17 Aug 2019 06:34:50 +0000 (23:34 -0700)
committerhimanshu <h.himanshu@samsung.com>
Tue, 11 Feb 2020 08:57:59 +0000 (14:27 +0530)
This adds a new long form option --zsh-complete to provide all available
commands in an output format suitable for parsing by zsh or other shell
completion scripts.

Invoke like: `bluetoothctl --zsh-complete help`

There is no corresponding short form option.

Change-Id: Idafb56b224f92a786223e43cae63babd1740834c
Signed-off-by: himanshu <h.himanshu@samsung.com>
src/shared/shell.c

index 3c74100..481129c 100644 (file)
@@ -78,6 +78,7 @@ static struct {
        int argc;
        char **argv;
        bool mode;
+       bool zsh;
        bool monitor;
        int timeout;
        struct io *input;
@@ -97,6 +98,7 @@ static struct {
 } data;
 
 static void shell_print_menu(void);
+static void shell_print_menu_zsh_complete(void);
 
 static void cmd_version(int argc, char *argv[])
 {
@@ -287,6 +289,11 @@ static void shell_print_menu(void)
        if (!data.menu)
                return;
 
+       if (data.zsh) {
+               shell_print_menu_zsh_complete();
+               return;
+       }
+
        print_text(COLOR_HIGHLIGHT, "Menu %s:", data.menu->name);
        print_text(COLOR_HIGHLIGHT, "Available commands:");
        print_text(COLOR_HIGHLIGHT, "-------------------");
@@ -313,6 +320,21 @@ static void shell_print_menu(void)
        }
 }
 
+static void shell_print_menu_zsh_complete(void)
+{
+       const struct bt_shell_menu_entry *entry;
+
+       for (entry = data.menu->entries; entry->cmd; entry++)
+               printf("%s:%s\n", entry->cmd, entry->desc ? : "");
+
+       for (entry = default_menu; entry->cmd; entry++) {
+               if (entry->exists && !entry->exists(data.menu))
+                       continue;
+
+               printf("%s:%s\n", entry->cmd, entry->desc ? : "");
+       }
+}
+
 static int parse_args(char *arg, wordexp_t *w, char *del, int flags)
 {
        char *str;
@@ -1015,6 +1037,7 @@ static const struct option main_options[] = {
        { "help",       no_argument, 0, 'h' },
        { "timeout",    required_argument, 0, 't' },
        { "monitor",    no_argument, 0, 'm' },
+       { "zsh-complete",       no_argument, 0, 'z' },
 };
 
 static void usage(int argc, char **argv, const struct bt_shell_opt *opt)
@@ -1075,6 +1098,9 @@ void bt_shell_init(int argc, char **argv, const struct bt_shell_opt *opt)
                case 't':
                        data.timeout = atoi(optarg);
                        break;
+               case 'z':
+                       data.zsh = 1;
+                       break;
                case 'm':
                        data.monitor = true;
                        if (bt_log_open() < 0) {