From afaef55e230c6fcfb4e8a27c1b970f7e6400a7f6 Mon Sep 17 00:00:00 2001 From: Christian Couder Date: Sat, 9 Dec 2017 21:40:07 +0100 Subject: git-compat-util: introduce skip_to_optional_arg() We often accept both a "--key" option and a "--key=" option. These options currently are parsed using something like: if (!strcmp(arg, "--key")) { /* do something */ } else if (skip_prefix(arg, "--key=", &arg)) { /* do something with arg */ } which is a bit cumbersome compared to just: if (skip_to_optional_arg(arg, "--key", &arg)) { /* do something with arg */ } This also introduces skip_to_optional_arg_default() for the few cases where something different should be done when the first argument is exactly "--key" than when it is exactly "--key=". In general it is better for UI consistency and simplicity if "--key" and "--key=" do the same thing though, so that using skip_to_optional_arg() should be encouraged compared to skip_to_optional_arg_default(). Note that these functions can be used to parse any "key=value" string where "key" is also considered as valid, not just command line options. Signed-off-by: Christian Couder Signed-off-by: Junio C Hamano --- strbuf.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'strbuf.c') diff --git a/strbuf.c b/strbuf.c index 323c49ceb..29169b8ef 100644 --- a/strbuf.c +++ b/strbuf.c @@ -11,6 +11,28 @@ int starts_with(const char *str, const char *prefix) return 0; } +int skip_to_optional_arg_default(const char *str, const char *prefix, + const char **arg, const char *def) +{ + const char *p; + + if (!skip_prefix(str, prefix, &p)) + return 0; + + if (!*p) { + if (arg) + *arg = def; + return 1; + } + + if (*p != '=') + return 0; + + if (arg) + *arg = p + 1; + return 1; +} + /* * Used as the default ->buf value, so that people can always assume * buf is non NULL and ->buf is NUL terminated even for a freshly -- cgit v1.2.1