config: add helper function for parsing key names

The config callback functions get keys of the general form: section.subsection.key (where the subsection may be contain arbitrary data, or may be missing). For matching keys without subsections, it is simple enough to call "strcmp". Matching keys with subsections is a little more complicated, and each callback does it in an ad-hoc way, usually involving error-prone pointer arithmetic. Let's provide a helper that keeps the pointer arithmetic all in one place. Signed-off-by: Jeff King <peff@peff.net> Reviewed-by: Jonathan Nieder <jrnieder@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Jan 23, 2013 at 01:23 UTC 1b86bbb0ade4641c2da0dc74ebca1c09ec772bb4
2 files changed +48
cache.h
+15
@@ -1164,6 +1164,21 @@ struct config_include_data {
1164 #define CONFIG_INCLUDE_INIT { 0 }
1165 extern int git_config_include(const char *name, const char *value, void *data);
1166
1167 +/*
1168 + * Match and parse a config key of the form:
1169 + *
1170 + * section.(subsection.)?key
1171 + *
1172 + * (i.e., what gets handed to a config_fn_t). The caller provides the section;
1173 + * we return -1 if it does not match, 0 otherwise. The subsection and key
1174 + * out-parameters are filled by the function (and subsection is NULL if it is
1175 + * missing).
1176 + */
1177 +extern int parse_config_key(const char *var,
1178 + const char *section,
1179 + const char **subsection, int *subsection_len,
1180 + const char **key);
1181 +
1182 extern int committer_ident_sufficiently_given(void);
1183 extern int author_ident_sufficiently_given(void);
1184
config.c
+33
@@ -1667,3 +1667,36 @@ int config_error_nonbool(const char *var)
1667 {
1668 return error("Missing value for '%s'", var);
1669 }
1670 +
1671 +int parse_config_key(const char *var,
1672 + const char *section,
1673 + const char **subsection, int *subsection_len,
1674 + const char **key)
1675 +{
1676 + int section_len = strlen(section);
1677 + const char *dot;
1678 +
1679 + /* Does it start with "section." ? */
1680 + if (prefixcmp(var, section) || var[section_len] != '.')
1681 + return -1;
1682 +
1683 + /*
1684 + * Find the key; we don't know yet if we have a subsection, but we must
1685 + * parse backwards from the end, since the subsection may have dots in
1686 + * it, too.
1687 + */
1688 + dot = strrchr(var, '.');
1689 + *key = dot + 1;
1690 +
1691 + /* Did we have a subsection at all? */
1692 + if (dot == var + section_len) {
1693 + *subsection = NULL;
1694 + *subsection_len = 0;
1695 + }
1696 + else {
1697 + *subsection = var + section_len + 1;
1698 + *subsection_len = dot - *subsection;
1699 + }
1700 +
1701 + return 0;
1702 +}