[PATCH 5/6] cli: notmuch reply: use getopt_long for parsing command line options

Jani Nikula jani at nikula.org
Sun Nov 13 14:47:25 PST 2011


Signed-off-by: Jani Nikula <jani at nikula.org>
---
 notmuch-reply.c |   40 +++++++++++++++++++++++-----------------
 1 files changed, 23 insertions(+), 17 deletions(-)

diff --git a/notmuch-reply.c b/notmuch-reply.c
index 7ac879f..45b9fe9 100644
--- a/notmuch-reply.c
+++ b/notmuch-reply.c
@@ -619,8 +619,8 @@ notmuch_reply_command (void *ctx, int argc, char *argv[])
     notmuch_config_t *config;
     notmuch_database_t *notmuch;
     notmuch_query_t *query;
-    char *opt, *query_string;
-    int i, ret = 0;
+    char *query_string;
+    int ret = 0;
     int (*reply_format_func)(void *ctx, notmuch_config_t *config, notmuch_query_t *query, notmuch_show_params_t *params);
     notmuch_show_params_t params;
 
@@ -628,24 +628,30 @@ notmuch_reply_command (void *ctx, int argc, char *argv[])
     params.part = -1;
     params.cryptoctx = NULL;
 
-    argc--; argv++; /* skip subcommand argument */
+    while (1) {
+	int opt;
+	static struct option options[] = {
+	    { "format", required_argument, NULL, 0 },
+	    { "decrypt", no_argument, NULL, 1 },
+	    { NULL, 0, NULL, 0 },
+	};
 
-    for (i = 0; i < argc && argv[i][0] == '-'; i++) {
-	if (strcmp (argv[i], "--") == 0) {
-	    i++;
+	opt = getopt_long (argc, argv, "", options, NULL);
+	if (opt == -1)
 	    break;
-	}
-        if (STRNCMP_LITERAL (argv[i], "--format=") == 0) {
-	    opt = argv[i] + sizeof ("--format=") - 1;
-	    if (strcmp (opt, "default") == 0) {
+
+	switch (opt) {
+	case 0:
+	    if (strcmp (optarg, "default") == 0) {
 		reply_format_func = notmuch_reply_format_default;
-	    } else if (strcmp (opt, "headers-only") == 0) {
+	    } else if (strcmp (optarg, "headers-only") == 0) {
 		reply_format_func = notmuch_reply_format_headers_only;
 	    } else {
-		fprintf (stderr, "Invalid value for --format: %s\n", opt);
+		fprintf (stderr, "Invalid value for --format: %s\n", optarg);
 		return 1;
 	    }
-	} else if ((STRNCMP_LITERAL (argv[i], "--decrypt") == 0)) {
+	    break;
+	case 1:
 	    if (params.cryptoctx == NULL) {
 		GMimeSession* session = g_object_new(g_mime_session_get_type(), NULL);
 		if (NULL == (params.cryptoctx = g_mime_gpg_context_new(session, "gpg")))
@@ -655,14 +661,14 @@ notmuch_reply_command (void *ctx, int argc, char *argv[])
 		g_object_unref (session);
 		session = NULL;
 	    }
-	} else {
-	    fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
+	    break;
+	case '?':
 	    return 1;
 	}
     }
 
-    argc -= i;
-    argv += i;
+    argc -= optind;
+    argv += optind;
 
     config = notmuch_config_open (ctx, NULL, NULL);
     if (config == NULL)
-- 
1.7.5.4



More information about the notmuch mailing list