Merge branch 'ab/config-based-hooks-2'
[git/debian.git] / config.c
blobe0c03d154c916225d30fd87d7008c91582ac4409
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 * Copyright (C) Johannes Schindelin, 2005
7 */
8 #include "cache.h"
9 #include "branch.h"
10 #include "config.h"
11 #include "environment.h"
12 #include "repository.h"
13 #include "lockfile.h"
14 #include "exec-cmd.h"
15 #include "strbuf.h"
16 #include "quote.h"
17 #include "hashmap.h"
18 #include "string-list.h"
19 #include "object-store.h"
20 #include "utf8.h"
21 #include "dir.h"
22 #include "color.h"
23 #include "refs.h"
25 struct config_source {
26 struct config_source *prev;
27 union {
28 FILE *file;
29 struct config_buf {
30 const char *buf;
31 size_t len;
32 size_t pos;
33 } buf;
34 } u;
35 enum config_origin_type origin_type;
36 const char *name;
37 const char *path;
38 enum config_error_action default_error_action;
39 int linenr;
40 int eof;
41 size_t total_len;
42 struct strbuf value;
43 struct strbuf var;
44 unsigned subsection_case_sensitive : 1;
46 int (*do_fgetc)(struct config_source *c);
47 int (*do_ungetc)(int c, struct config_source *conf);
48 long (*do_ftell)(struct config_source *c);
52 * These variables record the "current" config source, which
53 * can be accessed by parsing callbacks.
55 * The "cf" variable will be non-NULL only when we are actually parsing a real
56 * config source (file, blob, cmdline, etc).
58 * The "current_config_kvi" variable will be non-NULL only when we are feeding
59 * cached config from a configset into a callback.
61 * They should generally never be non-NULL at the same time. If they are both
62 * NULL, then we aren't parsing anything (and depending on the function looking
63 * at the variables, it's either a bug for it to be called in the first place,
64 * or it's a function which can be reused for non-config purposes, and should
65 * fall back to some sane behavior).
67 static struct config_source *cf;
68 static struct key_value_info *current_config_kvi;
71 * Similar to the variables above, this gives access to the "scope" of the
72 * current value (repo, global, etc). For cached values, it can be found via
73 * the current_config_kvi as above. During parsing, the current value can be
74 * found in this variable. It's not part of "cf" because it transcends a single
75 * file (i.e., a file included from .git/config is still in "repo" scope).
77 static enum config_scope current_parsing_scope;
79 static int pack_compression_seen;
80 static int zlib_compression_seen;
82 static int config_file_fgetc(struct config_source *conf)
84 return getc_unlocked(conf->u.file);
87 static int config_file_ungetc(int c, struct config_source *conf)
89 return ungetc(c, conf->u.file);
92 static long config_file_ftell(struct config_source *conf)
94 return ftell(conf->u.file);
98 static int config_buf_fgetc(struct config_source *conf)
100 if (conf->u.buf.pos < conf->u.buf.len)
101 return conf->u.buf.buf[conf->u.buf.pos++];
103 return EOF;
106 static int config_buf_ungetc(int c, struct config_source *conf)
108 if (conf->u.buf.pos > 0) {
109 conf->u.buf.pos--;
110 if (conf->u.buf.buf[conf->u.buf.pos] != c)
111 BUG("config_buf can only ungetc the same character");
112 return c;
115 return EOF;
118 static long config_buf_ftell(struct config_source *conf)
120 return conf->u.buf.pos;
123 struct config_include_data {
124 int depth;
125 config_fn_t fn;
126 void *data;
127 const struct config_options *opts;
128 struct git_config_source *config_source;
131 * All remote URLs discovered when reading all config files.
133 struct string_list *remote_urls;
135 #define CONFIG_INCLUDE_INIT { 0 }
137 static int git_config_include(const char *var, const char *value, void *data);
139 #define MAX_INCLUDE_DEPTH 10
140 static const char include_depth_advice[] = N_(
141 "exceeded maximum include depth (%d) while including\n"
142 " %s\n"
143 "from\n"
144 " %s\n"
145 "This might be due to circular includes.");
146 static int handle_path_include(const char *path, struct config_include_data *inc)
148 int ret = 0;
149 struct strbuf buf = STRBUF_INIT;
150 char *expanded;
152 if (!path)
153 return config_error_nonbool("include.path");
155 expanded = interpolate_path(path, 0);
156 if (!expanded)
157 return error(_("could not expand include path '%s'"), path);
158 path = expanded;
161 * Use an absolute path as-is, but interpret relative paths
162 * based on the including config file.
164 if (!is_absolute_path(path)) {
165 char *slash;
167 if (!cf || !cf->path) {
168 ret = error(_("relative config includes must come from files"));
169 goto cleanup;
172 slash = find_last_dir_sep(cf->path);
173 if (slash)
174 strbuf_add(&buf, cf->path, slash - cf->path + 1);
175 strbuf_addstr(&buf, path);
176 path = buf.buf;
179 if (!access_or_die(path, R_OK, 0)) {
180 if (++inc->depth > MAX_INCLUDE_DEPTH)
181 die(_(include_depth_advice), MAX_INCLUDE_DEPTH, path,
182 !cf ? "<unknown>" :
183 cf->name ? cf->name :
184 "the command line");
185 ret = git_config_from_file(git_config_include, path, inc);
186 inc->depth--;
188 cleanup:
189 strbuf_release(&buf);
190 free(expanded);
191 return ret;
194 static void add_trailing_starstar_for_dir(struct strbuf *pat)
196 if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
197 strbuf_addstr(pat, "**");
200 static int prepare_include_condition_pattern(struct strbuf *pat)
202 struct strbuf path = STRBUF_INIT;
203 char *expanded;
204 int prefix = 0;
206 expanded = interpolate_path(pat->buf, 1);
207 if (expanded) {
208 strbuf_reset(pat);
209 strbuf_addstr(pat, expanded);
210 free(expanded);
213 if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
214 const char *slash;
216 if (!cf || !cf->path)
217 return error(_("relative config include "
218 "conditionals must come from files"));
220 strbuf_realpath(&path, cf->path, 1);
221 slash = find_last_dir_sep(path.buf);
222 if (!slash)
223 BUG("how is this possible?");
224 strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
225 prefix = slash - path.buf + 1 /* slash */;
226 } else if (!is_absolute_path(pat->buf))
227 strbuf_insertstr(pat, 0, "**/");
229 add_trailing_starstar_for_dir(pat);
231 strbuf_release(&path);
232 return prefix;
235 static int include_by_gitdir(const struct config_options *opts,
236 const char *cond, size_t cond_len, int icase)
238 struct strbuf text = STRBUF_INIT;
239 struct strbuf pattern = STRBUF_INIT;
240 int ret = 0, prefix;
241 const char *git_dir;
242 int already_tried_absolute = 0;
244 if (opts->git_dir)
245 git_dir = opts->git_dir;
246 else
247 goto done;
249 strbuf_realpath(&text, git_dir, 1);
250 strbuf_add(&pattern, cond, cond_len);
251 prefix = prepare_include_condition_pattern(&pattern);
253 again:
254 if (prefix < 0)
255 goto done;
257 if (prefix > 0) {
259 * perform literal matching on the prefix part so that
260 * any wildcard character in it can't create side effects.
262 if (text.len < prefix)
263 goto done;
264 if (!icase && strncmp(pattern.buf, text.buf, prefix))
265 goto done;
266 if (icase && strncasecmp(pattern.buf, text.buf, prefix))
267 goto done;
270 ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
271 WM_PATHNAME | (icase ? WM_CASEFOLD : 0));
273 if (!ret && !already_tried_absolute) {
275 * We've tried e.g. matching gitdir:~/work, but if
276 * ~/work is a symlink to /mnt/storage/work
277 * strbuf_realpath() will expand it, so the rule won't
278 * match. Let's match against a
279 * strbuf_add_absolute_path() version of the path,
280 * which'll do the right thing
282 strbuf_reset(&text);
283 strbuf_add_absolute_path(&text, git_dir);
284 already_tried_absolute = 1;
285 goto again;
287 done:
288 strbuf_release(&pattern);
289 strbuf_release(&text);
290 return ret;
293 static int include_by_branch(const char *cond, size_t cond_len)
295 int flags;
296 int ret;
297 struct strbuf pattern = STRBUF_INIT;
298 const char *refname = !the_repository->gitdir ?
299 NULL : resolve_ref_unsafe("HEAD", 0, NULL, &flags);
300 const char *shortname;
302 if (!refname || !(flags & REF_ISSYMREF) ||
303 !skip_prefix(refname, "refs/heads/", &shortname))
304 return 0;
306 strbuf_add(&pattern, cond, cond_len);
307 add_trailing_starstar_for_dir(&pattern);
308 ret = !wildmatch(pattern.buf, shortname, WM_PATHNAME);
309 strbuf_release(&pattern);
310 return ret;
313 static int add_remote_url(const char *var, const char *value, void *data)
315 struct string_list *remote_urls = data;
316 const char *remote_name;
317 size_t remote_name_len;
318 const char *key;
320 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
321 &key) &&
322 remote_name &&
323 !strcmp(key, "url"))
324 string_list_append(remote_urls, value);
325 return 0;
328 static void populate_remote_urls(struct config_include_data *inc)
330 struct config_options opts;
332 struct config_source *store_cf = cf;
333 struct key_value_info *store_kvi = current_config_kvi;
334 enum config_scope store_scope = current_parsing_scope;
336 opts = *inc->opts;
337 opts.unconditional_remote_url = 1;
339 cf = NULL;
340 current_config_kvi = NULL;
341 current_parsing_scope = 0;
343 inc->remote_urls = xmalloc(sizeof(*inc->remote_urls));
344 string_list_init_dup(inc->remote_urls);
345 config_with_options(add_remote_url, inc->remote_urls, inc->config_source, &opts);
347 cf = store_cf;
348 current_config_kvi = store_kvi;
349 current_parsing_scope = store_scope;
352 static int forbid_remote_url(const char *var, const char *value, void *data)
354 const char *remote_name;
355 size_t remote_name_len;
356 const char *key;
358 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
359 &key) &&
360 remote_name &&
361 !strcmp(key, "url"))
362 die(_("remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"));
363 return 0;
366 static int at_least_one_url_matches_glob(const char *glob, int glob_len,
367 struct string_list *remote_urls)
369 struct strbuf pattern = STRBUF_INIT;
370 struct string_list_item *url_item;
371 int found = 0;
373 strbuf_add(&pattern, glob, glob_len);
374 for_each_string_list_item(url_item, remote_urls) {
375 if (!wildmatch(pattern.buf, url_item->string, WM_PATHNAME)) {
376 found = 1;
377 break;
380 strbuf_release(&pattern);
381 return found;
384 static int include_by_remote_url(struct config_include_data *inc,
385 const char *cond, size_t cond_len)
387 if (inc->opts->unconditional_remote_url)
388 return 1;
389 if (!inc->remote_urls)
390 populate_remote_urls(inc);
391 return at_least_one_url_matches_glob(cond, cond_len,
392 inc->remote_urls);
395 static int include_condition_is_true(struct config_include_data *inc,
396 const char *cond, size_t cond_len)
398 const struct config_options *opts = inc->opts;
400 if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
401 return include_by_gitdir(opts, cond, cond_len, 0);
402 else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
403 return include_by_gitdir(opts, cond, cond_len, 1);
404 else if (skip_prefix_mem(cond, cond_len, "onbranch:", &cond, &cond_len))
405 return include_by_branch(cond, cond_len);
406 else if (skip_prefix_mem(cond, cond_len, "hasconfig:remote.*.url:", &cond,
407 &cond_len))
408 return include_by_remote_url(inc, cond, cond_len);
410 /* unknown conditionals are always false */
411 return 0;
414 static int git_config_include(const char *var, const char *value, void *data)
416 struct config_include_data *inc = data;
417 const char *cond, *key;
418 size_t cond_len;
419 int ret;
422 * Pass along all values, including "include" directives; this makes it
423 * possible to query information on the includes themselves.
425 ret = inc->fn(var, value, inc->data);
426 if (ret < 0)
427 return ret;
429 if (!strcmp(var, "include.path"))
430 ret = handle_path_include(value, inc);
432 if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
433 cond && include_condition_is_true(inc, cond, cond_len) &&
434 !strcmp(key, "path")) {
435 config_fn_t old_fn = inc->fn;
437 if (inc->opts->unconditional_remote_url)
438 inc->fn = forbid_remote_url;
439 ret = handle_path_include(value, inc);
440 inc->fn = old_fn;
443 return ret;
446 static void git_config_push_split_parameter(const char *key, const char *value)
448 struct strbuf env = STRBUF_INIT;
449 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
450 if (old && *old) {
451 strbuf_addstr(&env, old);
452 strbuf_addch(&env, ' ');
454 sq_quote_buf(&env, key);
455 strbuf_addch(&env, '=');
456 if (value)
457 sq_quote_buf(&env, value);
458 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
459 strbuf_release(&env);
462 void git_config_push_parameter(const char *text)
464 const char *value;
467 * When we see:
469 * section.subsection=with=equals.key=value
471 * we cannot tell if it means:
473 * [section "subsection=with=equals"]
474 * key = value
476 * or:
478 * [section]
479 * subsection = with=equals.key=value
481 * We parse left-to-right for the first "=", meaning we'll prefer to
482 * keep the value intact over the subsection. This is historical, but
483 * also sensible since values are more likely to contain odd or
484 * untrusted input than a section name.
486 * A missing equals is explicitly allowed (as a bool-only entry).
488 value = strchr(text, '=');
489 if (value) {
490 char *key = xmemdupz(text, value - text);
491 git_config_push_split_parameter(key, value + 1);
492 free(key);
493 } else {
494 git_config_push_split_parameter(text, NULL);
498 void git_config_push_env(const char *spec)
500 char *key;
501 const char *env_name;
502 const char *env_value;
504 env_name = strrchr(spec, '=');
505 if (!env_name)
506 die(_("invalid config format: %s"), spec);
507 key = xmemdupz(spec, env_name - spec);
508 env_name++;
509 if (!*env_name)
510 die(_("missing environment variable name for configuration '%.*s'"),
511 (int)(env_name - spec - 1), spec);
513 env_value = getenv(env_name);
514 if (!env_value)
515 die(_("missing environment variable '%s' for configuration '%.*s'"),
516 env_name, (int)(env_name - spec - 1), spec);
518 git_config_push_split_parameter(key, env_value);
519 free(key);
522 static inline int iskeychar(int c)
524 return isalnum(c) || c == '-';
528 * Auxiliary function to sanity-check and split the key into the section
529 * identifier and variable name.
531 * Returns 0 on success, -1 when there is an invalid character in the key and
532 * -2 if there is no section name in the key.
534 * store_key - pointer to char* which will hold a copy of the key with
535 * lowercase section and variable name
536 * baselen - pointer to size_t which will hold the length of the
537 * section + subsection part, can be NULL
539 int git_config_parse_key(const char *key, char **store_key, size_t *baselen_)
541 size_t i, baselen;
542 int dot;
543 const char *last_dot = strrchr(key, '.');
546 * Since "key" actually contains the section name and the real
547 * key name separated by a dot, we have to know where the dot is.
550 if (last_dot == NULL || last_dot == key) {
551 error(_("key does not contain a section: %s"), key);
552 return -CONFIG_NO_SECTION_OR_NAME;
555 if (!last_dot[1]) {
556 error(_("key does not contain variable name: %s"), key);
557 return -CONFIG_NO_SECTION_OR_NAME;
560 baselen = last_dot - key;
561 if (baselen_)
562 *baselen_ = baselen;
565 * Validate the key and while at it, lower case it for matching.
567 *store_key = xmallocz(strlen(key));
569 dot = 0;
570 for (i = 0; key[i]; i++) {
571 unsigned char c = key[i];
572 if (c == '.')
573 dot = 1;
574 /* Leave the extended basename untouched.. */
575 if (!dot || i > baselen) {
576 if (!iskeychar(c) ||
577 (i == baselen + 1 && !isalpha(c))) {
578 error(_("invalid key: %s"), key);
579 goto out_free_ret_1;
581 c = tolower(c);
582 } else if (c == '\n') {
583 error(_("invalid key (newline): %s"), key);
584 goto out_free_ret_1;
586 (*store_key)[i] = c;
589 return 0;
591 out_free_ret_1:
592 FREE_AND_NULL(*store_key);
593 return -CONFIG_INVALID_KEY;
596 static int config_parse_pair(const char *key, const char *value,
597 config_fn_t fn, void *data)
599 char *canonical_name;
600 int ret;
602 if (!strlen(key))
603 return error(_("empty config key"));
604 if (git_config_parse_key(key, &canonical_name, NULL))
605 return -1;
607 ret = (fn(canonical_name, value, data) < 0) ? -1 : 0;
608 free(canonical_name);
609 return ret;
612 int git_config_parse_parameter(const char *text,
613 config_fn_t fn, void *data)
615 const char *value;
616 struct strbuf **pair;
617 int ret;
619 pair = strbuf_split_str(text, '=', 2);
620 if (!pair[0])
621 return error(_("bogus config parameter: %s"), text);
623 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
624 strbuf_setlen(pair[0], pair[0]->len - 1);
625 value = pair[1] ? pair[1]->buf : "";
626 } else {
627 value = NULL;
630 strbuf_trim(pair[0]);
631 if (!pair[0]->len) {
632 strbuf_list_free(pair);
633 return error(_("bogus config parameter: %s"), text);
636 ret = config_parse_pair(pair[0]->buf, value, fn, data);
637 strbuf_list_free(pair);
638 return ret;
641 static int parse_config_env_list(char *env, config_fn_t fn, void *data)
643 char *cur = env;
644 while (cur && *cur) {
645 const char *key = sq_dequote_step(cur, &cur);
646 if (!key)
647 return error(_("bogus format in %s"),
648 CONFIG_DATA_ENVIRONMENT);
650 if (!cur || isspace(*cur)) {
651 /* old-style 'key=value' */
652 if (git_config_parse_parameter(key, fn, data) < 0)
653 return -1;
655 else if (*cur == '=') {
656 /* new-style 'key'='value' */
657 const char *value;
659 cur++;
660 if (*cur == '\'') {
661 /* quoted value */
662 value = sq_dequote_step(cur, &cur);
663 if (!value || (cur && !isspace(*cur))) {
664 return error(_("bogus format in %s"),
665 CONFIG_DATA_ENVIRONMENT);
667 } else if (!*cur || isspace(*cur)) {
668 /* implicit bool: 'key'= */
669 value = NULL;
670 } else {
671 return error(_("bogus format in %s"),
672 CONFIG_DATA_ENVIRONMENT);
675 if (config_parse_pair(key, value, fn, data) < 0)
676 return -1;
678 else {
679 /* unknown format */
680 return error(_("bogus format in %s"),
681 CONFIG_DATA_ENVIRONMENT);
684 if (cur) {
685 while (isspace(*cur))
686 cur++;
689 return 0;
692 int git_config_from_parameters(config_fn_t fn, void *data)
694 const char *env;
695 struct strbuf envvar = STRBUF_INIT;
696 struct strvec to_free = STRVEC_INIT;
697 int ret = 0;
698 char *envw = NULL;
699 struct config_source source;
701 memset(&source, 0, sizeof(source));
702 source.prev = cf;
703 source.origin_type = CONFIG_ORIGIN_CMDLINE;
704 cf = &source;
706 env = getenv(CONFIG_COUNT_ENVIRONMENT);
707 if (env) {
708 unsigned long count;
709 char *endp;
710 int i;
712 count = strtoul(env, &endp, 10);
713 if (*endp) {
714 ret = error(_("bogus count in %s"), CONFIG_COUNT_ENVIRONMENT);
715 goto out;
717 if (count > INT_MAX) {
718 ret = error(_("too many entries in %s"), CONFIG_COUNT_ENVIRONMENT);
719 goto out;
722 for (i = 0; i < count; i++) {
723 const char *key, *value;
725 strbuf_addf(&envvar, "GIT_CONFIG_KEY_%d", i);
726 key = getenv_safe(&to_free, envvar.buf);
727 if (!key) {
728 ret = error(_("missing config key %s"), envvar.buf);
729 goto out;
731 strbuf_reset(&envvar);
733 strbuf_addf(&envvar, "GIT_CONFIG_VALUE_%d", i);
734 value = getenv_safe(&to_free, envvar.buf);
735 if (!value) {
736 ret = error(_("missing config value %s"), envvar.buf);
737 goto out;
739 strbuf_reset(&envvar);
741 if (config_parse_pair(key, value, fn, data) < 0) {
742 ret = -1;
743 goto out;
748 env = getenv(CONFIG_DATA_ENVIRONMENT);
749 if (env) {
750 /* sq_dequote will write over it */
751 envw = xstrdup(env);
752 if (parse_config_env_list(envw, fn, data) < 0) {
753 ret = -1;
754 goto out;
758 out:
759 strbuf_release(&envvar);
760 strvec_clear(&to_free);
761 free(envw);
762 cf = source.prev;
763 return ret;
766 static int get_next_char(void)
768 int c = cf->do_fgetc(cf);
770 if (c == '\r') {
771 /* DOS like systems */
772 c = cf->do_fgetc(cf);
773 if (c != '\n') {
774 if (c != EOF)
775 cf->do_ungetc(c, cf);
776 c = '\r';
780 if (c != EOF && ++cf->total_len > INT_MAX) {
782 * This is an absurdly long config file; refuse to parse
783 * further in order to protect downstream code from integer
784 * overflows. Note that we can't return an error specifically,
785 * but we can mark EOF and put trash in the return value,
786 * which will trigger a parse error.
788 cf->eof = 1;
789 return 0;
792 if (c == '\n')
793 cf->linenr++;
794 if (c == EOF) {
795 cf->eof = 1;
796 cf->linenr++;
797 c = '\n';
799 return c;
802 static char *parse_value(void)
804 int quote = 0, comment = 0, space = 0;
806 strbuf_reset(&cf->value);
807 for (;;) {
808 int c = get_next_char();
809 if (c == '\n') {
810 if (quote) {
811 cf->linenr--;
812 return NULL;
814 return cf->value.buf;
816 if (comment)
817 continue;
818 if (isspace(c) && !quote) {
819 if (cf->value.len)
820 space++;
821 continue;
823 if (!quote) {
824 if (c == ';' || c == '#') {
825 comment = 1;
826 continue;
829 for (; space; space--)
830 strbuf_addch(&cf->value, ' ');
831 if (c == '\\') {
832 c = get_next_char();
833 switch (c) {
834 case '\n':
835 continue;
836 case 't':
837 c = '\t';
838 break;
839 case 'b':
840 c = '\b';
841 break;
842 case 'n':
843 c = '\n';
844 break;
845 /* Some characters escape as themselves */
846 case '\\': case '"':
847 break;
848 /* Reject unknown escape sequences */
849 default:
850 return NULL;
852 strbuf_addch(&cf->value, c);
853 continue;
855 if (c == '"') {
856 quote = 1-quote;
857 continue;
859 strbuf_addch(&cf->value, c);
863 static int get_value(config_fn_t fn, void *data, struct strbuf *name)
865 int c;
866 char *value;
867 int ret;
869 /* Get the full name */
870 for (;;) {
871 c = get_next_char();
872 if (cf->eof)
873 break;
874 if (!iskeychar(c))
875 break;
876 strbuf_addch(name, tolower(c));
879 while (c == ' ' || c == '\t')
880 c = get_next_char();
882 value = NULL;
883 if (c != '\n') {
884 if (c != '=')
885 return -1;
886 value = parse_value();
887 if (!value)
888 return -1;
891 * We already consumed the \n, but we need linenr to point to
892 * the line we just parsed during the call to fn to get
893 * accurate line number in error messages.
895 cf->linenr--;
896 ret = fn(name->buf, value, data);
897 if (ret >= 0)
898 cf->linenr++;
899 return ret;
902 static int get_extended_base_var(struct strbuf *name, int c)
904 cf->subsection_case_sensitive = 0;
905 do {
906 if (c == '\n')
907 goto error_incomplete_line;
908 c = get_next_char();
909 } while (isspace(c));
911 /* We require the format to be '[base "extension"]' */
912 if (c != '"')
913 return -1;
914 strbuf_addch(name, '.');
916 for (;;) {
917 int c = get_next_char();
918 if (c == '\n')
919 goto error_incomplete_line;
920 if (c == '"')
921 break;
922 if (c == '\\') {
923 c = get_next_char();
924 if (c == '\n')
925 goto error_incomplete_line;
927 strbuf_addch(name, c);
930 /* Final ']' */
931 if (get_next_char() != ']')
932 return -1;
933 return 0;
934 error_incomplete_line:
935 cf->linenr--;
936 return -1;
939 static int get_base_var(struct strbuf *name)
941 cf->subsection_case_sensitive = 1;
942 for (;;) {
943 int c = get_next_char();
944 if (cf->eof)
945 return -1;
946 if (c == ']')
947 return 0;
948 if (isspace(c))
949 return get_extended_base_var(name, c);
950 if (!iskeychar(c) && c != '.')
951 return -1;
952 strbuf_addch(name, tolower(c));
956 struct parse_event_data {
957 enum config_event_t previous_type;
958 size_t previous_offset;
959 const struct config_options *opts;
962 static int do_event(enum config_event_t type, struct parse_event_data *data)
964 size_t offset;
966 if (!data->opts || !data->opts->event_fn)
967 return 0;
969 if (type == CONFIG_EVENT_WHITESPACE &&
970 data->previous_type == type)
971 return 0;
973 offset = cf->do_ftell(cf);
975 * At EOF, the parser always "inserts" an extra '\n', therefore
976 * the end offset of the event is the current file position, otherwise
977 * we will already have advanced to the next event.
979 if (type != CONFIG_EVENT_EOF)
980 offset--;
982 if (data->previous_type != CONFIG_EVENT_EOF &&
983 data->opts->event_fn(data->previous_type, data->previous_offset,
984 offset, data->opts->event_fn_data) < 0)
985 return -1;
987 data->previous_type = type;
988 data->previous_offset = offset;
990 return 0;
993 static int git_parse_source(config_fn_t fn, void *data,
994 const struct config_options *opts)
996 int comment = 0;
997 size_t baselen = 0;
998 struct strbuf *var = &cf->var;
999 int error_return = 0;
1000 char *error_msg = NULL;
1002 /* U+FEFF Byte Order Mark in UTF8 */
1003 const char *bomptr = utf8_bom;
1005 /* For the parser event callback */
1006 struct parse_event_data event_data = {
1007 CONFIG_EVENT_EOF, 0, opts
1010 for (;;) {
1011 int c;
1013 c = get_next_char();
1014 if (bomptr && *bomptr) {
1015 /* We are at the file beginning; skip UTF8-encoded BOM
1016 * if present. Sane editors won't put this in on their
1017 * own, but e.g. Windows Notepad will do it happily. */
1018 if (c == (*bomptr & 0377)) {
1019 bomptr++;
1020 continue;
1021 } else {
1022 /* Do not tolerate partial BOM. */
1023 if (bomptr != utf8_bom)
1024 break;
1025 /* No BOM at file beginning. Cool. */
1026 bomptr = NULL;
1029 if (c == '\n') {
1030 if (cf->eof) {
1031 if (do_event(CONFIG_EVENT_EOF, &event_data) < 0)
1032 return -1;
1033 return 0;
1035 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1036 return -1;
1037 comment = 0;
1038 continue;
1040 if (comment)
1041 continue;
1042 if (isspace(c)) {
1043 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1044 return -1;
1045 continue;
1047 if (c == '#' || c == ';') {
1048 if (do_event(CONFIG_EVENT_COMMENT, &event_data) < 0)
1049 return -1;
1050 comment = 1;
1051 continue;
1053 if (c == '[') {
1054 if (do_event(CONFIG_EVENT_SECTION, &event_data) < 0)
1055 return -1;
1057 /* Reset prior to determining a new stem */
1058 strbuf_reset(var);
1059 if (get_base_var(var) < 0 || var->len < 1)
1060 break;
1061 strbuf_addch(var, '.');
1062 baselen = var->len;
1063 continue;
1065 if (!isalpha(c))
1066 break;
1068 if (do_event(CONFIG_EVENT_ENTRY, &event_data) < 0)
1069 return -1;
1072 * Truncate the var name back to the section header
1073 * stem prior to grabbing the suffix part of the name
1074 * and the value.
1076 strbuf_setlen(var, baselen);
1077 strbuf_addch(var, tolower(c));
1078 if (get_value(fn, data, var) < 0)
1079 break;
1082 if (do_event(CONFIG_EVENT_ERROR, &event_data) < 0)
1083 return -1;
1085 switch (cf->origin_type) {
1086 case CONFIG_ORIGIN_BLOB:
1087 error_msg = xstrfmt(_("bad config line %d in blob %s"),
1088 cf->linenr, cf->name);
1089 break;
1090 case CONFIG_ORIGIN_FILE:
1091 error_msg = xstrfmt(_("bad config line %d in file %s"),
1092 cf->linenr, cf->name);
1093 break;
1094 case CONFIG_ORIGIN_STDIN:
1095 error_msg = xstrfmt(_("bad config line %d in standard input"),
1096 cf->linenr);
1097 break;
1098 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1099 error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
1100 cf->linenr, cf->name);
1101 break;
1102 case CONFIG_ORIGIN_CMDLINE:
1103 error_msg = xstrfmt(_("bad config line %d in command line %s"),
1104 cf->linenr, cf->name);
1105 break;
1106 default:
1107 error_msg = xstrfmt(_("bad config line %d in %s"),
1108 cf->linenr, cf->name);
1111 switch (opts && opts->error_action ?
1112 opts->error_action :
1113 cf->default_error_action) {
1114 case CONFIG_ERROR_DIE:
1115 die("%s", error_msg);
1116 break;
1117 case CONFIG_ERROR_ERROR:
1118 error_return = error("%s", error_msg);
1119 break;
1120 case CONFIG_ERROR_SILENT:
1121 error_return = -1;
1122 break;
1123 case CONFIG_ERROR_UNSET:
1124 BUG("config error action unset");
1127 free(error_msg);
1128 return error_return;
1131 static uintmax_t get_unit_factor(const char *end)
1133 if (!*end)
1134 return 1;
1135 else if (!strcasecmp(end, "k"))
1136 return 1024;
1137 else if (!strcasecmp(end, "m"))
1138 return 1024 * 1024;
1139 else if (!strcasecmp(end, "g"))
1140 return 1024 * 1024 * 1024;
1141 return 0;
1144 static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
1146 if (value && *value) {
1147 char *end;
1148 intmax_t val;
1149 uintmax_t uval;
1150 uintmax_t factor;
1152 errno = 0;
1153 val = strtoimax(value, &end, 0);
1154 if (errno == ERANGE)
1155 return 0;
1156 factor = get_unit_factor(end);
1157 if (!factor) {
1158 errno = EINVAL;
1159 return 0;
1161 uval = val < 0 ? -val : val;
1162 if (unsigned_mult_overflows(factor, uval) ||
1163 factor * uval > max) {
1164 errno = ERANGE;
1165 return 0;
1167 val *= factor;
1168 *ret = val;
1169 return 1;
1171 errno = EINVAL;
1172 return 0;
1175 static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
1177 if (value && *value) {
1178 char *end;
1179 uintmax_t val;
1180 uintmax_t factor;
1182 errno = 0;
1183 val = strtoumax(value, &end, 0);
1184 if (errno == ERANGE)
1185 return 0;
1186 factor = get_unit_factor(end);
1187 if (!factor) {
1188 errno = EINVAL;
1189 return 0;
1191 if (unsigned_mult_overflows(factor, val) ||
1192 factor * val > max) {
1193 errno = ERANGE;
1194 return 0;
1196 val *= factor;
1197 *ret = val;
1198 return 1;
1200 errno = EINVAL;
1201 return 0;
1204 static int git_parse_int(const char *value, int *ret)
1206 intmax_t tmp;
1207 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
1208 return 0;
1209 *ret = tmp;
1210 return 1;
1213 static int git_parse_int64(const char *value, int64_t *ret)
1215 intmax_t tmp;
1216 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
1217 return 0;
1218 *ret = tmp;
1219 return 1;
1222 int git_parse_ulong(const char *value, unsigned long *ret)
1224 uintmax_t tmp;
1225 if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
1226 return 0;
1227 *ret = tmp;
1228 return 1;
1231 int git_parse_ssize_t(const char *value, ssize_t *ret)
1233 intmax_t tmp;
1234 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(ssize_t)))
1235 return 0;
1236 *ret = tmp;
1237 return 1;
1240 NORETURN
1241 static void die_bad_number(const char *name, const char *value)
1243 const char *error_type = (errno == ERANGE) ?
1244 N_("out of range") : N_("invalid unit");
1245 const char *bad_numeric = N_("bad numeric config value '%s' for '%s': %s");
1247 if (!value)
1248 value = "";
1250 if (!(cf && cf->name))
1251 die(_(bad_numeric), value, name, _(error_type));
1253 switch (cf->origin_type) {
1254 case CONFIG_ORIGIN_BLOB:
1255 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
1256 value, name, cf->name, _(error_type));
1257 case CONFIG_ORIGIN_FILE:
1258 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
1259 value, name, cf->name, _(error_type));
1260 case CONFIG_ORIGIN_STDIN:
1261 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
1262 value, name, _(error_type));
1263 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1264 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
1265 value, name, cf->name, _(error_type));
1266 case CONFIG_ORIGIN_CMDLINE:
1267 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
1268 value, name, cf->name, _(error_type));
1269 default:
1270 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
1271 value, name, cf->name, _(error_type));
1275 int git_config_int(const char *name, const char *value)
1277 int ret;
1278 if (!git_parse_int(value, &ret))
1279 die_bad_number(name, value);
1280 return ret;
1283 int64_t git_config_int64(const char *name, const char *value)
1285 int64_t ret;
1286 if (!git_parse_int64(value, &ret))
1287 die_bad_number(name, value);
1288 return ret;
1291 unsigned long git_config_ulong(const char *name, const char *value)
1293 unsigned long ret;
1294 if (!git_parse_ulong(value, &ret))
1295 die_bad_number(name, value);
1296 return ret;
1299 ssize_t git_config_ssize_t(const char *name, const char *value)
1301 ssize_t ret;
1302 if (!git_parse_ssize_t(value, &ret))
1303 die_bad_number(name, value);
1304 return ret;
1307 static int git_parse_maybe_bool_text(const char *value)
1309 if (!value)
1310 return 1;
1311 if (!*value)
1312 return 0;
1313 if (!strcasecmp(value, "true")
1314 || !strcasecmp(value, "yes")
1315 || !strcasecmp(value, "on"))
1316 return 1;
1317 if (!strcasecmp(value, "false")
1318 || !strcasecmp(value, "no")
1319 || !strcasecmp(value, "off"))
1320 return 0;
1321 return -1;
1324 int git_parse_maybe_bool(const char *value)
1326 int v = git_parse_maybe_bool_text(value);
1327 if (0 <= v)
1328 return v;
1329 if (git_parse_int(value, &v))
1330 return !!v;
1331 return -1;
1334 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
1336 int v = git_parse_maybe_bool_text(value);
1337 if (0 <= v) {
1338 *is_bool = 1;
1339 return v;
1341 *is_bool = 0;
1342 return git_config_int(name, value);
1345 int git_config_bool(const char *name, const char *value)
1347 int v = git_parse_maybe_bool(value);
1348 if (v < 0)
1349 die(_("bad boolean config value '%s' for '%s'"), value, name);
1350 return v;
1353 int git_config_string(const char **dest, const char *var, const char *value)
1355 if (!value)
1356 return config_error_nonbool(var);
1357 *dest = xstrdup(value);
1358 return 0;
1361 int git_config_pathname(const char **dest, const char *var, const char *value)
1363 if (!value)
1364 return config_error_nonbool(var);
1365 *dest = interpolate_path(value, 0);
1366 if (!*dest)
1367 die(_("failed to expand user dir in: '%s'"), value);
1368 return 0;
1371 int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1373 if (!value)
1374 return config_error_nonbool(var);
1375 if (parse_expiry_date(value, timestamp))
1376 return error(_("'%s' for '%s' is not a valid timestamp"),
1377 value, var);
1378 return 0;
1381 int git_config_color(char *dest, const char *var, const char *value)
1383 if (!value)
1384 return config_error_nonbool(var);
1385 if (color_parse(value, dest) < 0)
1386 return -1;
1387 return 0;
1390 static int git_default_core_config(const char *var, const char *value, void *cb)
1392 /* This needs a better name */
1393 if (!strcmp(var, "core.filemode")) {
1394 trust_executable_bit = git_config_bool(var, value);
1395 return 0;
1397 if (!strcmp(var, "core.trustctime")) {
1398 trust_ctime = git_config_bool(var, value);
1399 return 0;
1401 if (!strcmp(var, "core.checkstat")) {
1402 if (!strcasecmp(value, "default"))
1403 check_stat = 1;
1404 else if (!strcasecmp(value, "minimal"))
1405 check_stat = 0;
1408 if (!strcmp(var, "core.quotepath")) {
1409 quote_path_fully = git_config_bool(var, value);
1410 return 0;
1413 if (!strcmp(var, "core.symlinks")) {
1414 has_symlinks = git_config_bool(var, value);
1415 return 0;
1418 if (!strcmp(var, "core.ignorecase")) {
1419 ignore_case = git_config_bool(var, value);
1420 return 0;
1423 if (!strcmp(var, "core.attributesfile"))
1424 return git_config_pathname(&git_attributes_file, var, value);
1426 if (!strcmp(var, "core.hookspath"))
1427 return git_config_pathname(&git_hooks_path, var, value);
1429 if (!strcmp(var, "core.bare")) {
1430 is_bare_repository_cfg = git_config_bool(var, value);
1431 return 0;
1434 if (!strcmp(var, "core.ignorestat")) {
1435 assume_unchanged = git_config_bool(var, value);
1436 return 0;
1439 if (!strcmp(var, "core.prefersymlinkrefs")) {
1440 prefer_symlink_refs = git_config_bool(var, value);
1441 return 0;
1444 if (!strcmp(var, "core.logallrefupdates")) {
1445 if (value && !strcasecmp(value, "always"))
1446 log_all_ref_updates = LOG_REFS_ALWAYS;
1447 else if (git_config_bool(var, value))
1448 log_all_ref_updates = LOG_REFS_NORMAL;
1449 else
1450 log_all_ref_updates = LOG_REFS_NONE;
1451 return 0;
1454 if (!strcmp(var, "core.warnambiguousrefs")) {
1455 warn_ambiguous_refs = git_config_bool(var, value);
1456 return 0;
1459 if (!strcmp(var, "core.abbrev")) {
1460 if (!value)
1461 return config_error_nonbool(var);
1462 if (!strcasecmp(value, "auto"))
1463 default_abbrev = -1;
1464 else if (!git_parse_maybe_bool_text(value))
1465 default_abbrev = the_hash_algo->hexsz;
1466 else {
1467 int abbrev = git_config_int(var, value);
1468 if (abbrev < minimum_abbrev || abbrev > the_hash_algo->hexsz)
1469 return error(_("abbrev length out of range: %d"), abbrev);
1470 default_abbrev = abbrev;
1472 return 0;
1475 if (!strcmp(var, "core.disambiguate"))
1476 return set_disambiguate_hint_config(var, value);
1478 if (!strcmp(var, "core.loosecompression")) {
1479 int level = git_config_int(var, value);
1480 if (level == -1)
1481 level = Z_DEFAULT_COMPRESSION;
1482 else if (level < 0 || level > Z_BEST_COMPRESSION)
1483 die(_("bad zlib compression level %d"), level);
1484 zlib_compression_level = level;
1485 zlib_compression_seen = 1;
1486 return 0;
1489 if (!strcmp(var, "core.compression")) {
1490 int level = git_config_int(var, value);
1491 if (level == -1)
1492 level = Z_DEFAULT_COMPRESSION;
1493 else if (level < 0 || level > Z_BEST_COMPRESSION)
1494 die(_("bad zlib compression level %d"), level);
1495 if (!zlib_compression_seen)
1496 zlib_compression_level = level;
1497 if (!pack_compression_seen)
1498 pack_compression_level = level;
1499 return 0;
1502 if (!strcmp(var, "core.packedgitwindowsize")) {
1503 int pgsz_x2 = getpagesize() * 2;
1504 packed_git_window_size = git_config_ulong(var, value);
1506 /* This value must be multiple of (pagesize * 2) */
1507 packed_git_window_size /= pgsz_x2;
1508 if (packed_git_window_size < 1)
1509 packed_git_window_size = 1;
1510 packed_git_window_size *= pgsz_x2;
1511 return 0;
1514 if (!strcmp(var, "core.bigfilethreshold")) {
1515 big_file_threshold = git_config_ulong(var, value);
1516 return 0;
1519 if (!strcmp(var, "core.packedgitlimit")) {
1520 packed_git_limit = git_config_ulong(var, value);
1521 return 0;
1524 if (!strcmp(var, "core.deltabasecachelimit")) {
1525 delta_base_cache_limit = git_config_ulong(var, value);
1526 return 0;
1529 if (!strcmp(var, "core.autocrlf")) {
1530 if (value && !strcasecmp(value, "input")) {
1531 auto_crlf = AUTO_CRLF_INPUT;
1532 return 0;
1534 auto_crlf = git_config_bool(var, value);
1535 return 0;
1538 if (!strcmp(var, "core.safecrlf")) {
1539 int eol_rndtrp_die;
1540 if (value && !strcasecmp(value, "warn")) {
1541 global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
1542 return 0;
1544 eol_rndtrp_die = git_config_bool(var, value);
1545 global_conv_flags_eol = eol_rndtrp_die ?
1546 CONV_EOL_RNDTRP_DIE : 0;
1547 return 0;
1550 if (!strcmp(var, "core.eol")) {
1551 if (value && !strcasecmp(value, "lf"))
1552 core_eol = EOL_LF;
1553 else if (value && !strcasecmp(value, "crlf"))
1554 core_eol = EOL_CRLF;
1555 else if (value && !strcasecmp(value, "native"))
1556 core_eol = EOL_NATIVE;
1557 else
1558 core_eol = EOL_UNSET;
1559 return 0;
1562 if (!strcmp(var, "core.checkroundtripencoding")) {
1563 check_roundtrip_encoding = xstrdup(value);
1564 return 0;
1567 if (!strcmp(var, "core.notesref")) {
1568 notes_ref_name = xstrdup(value);
1569 return 0;
1572 if (!strcmp(var, "core.editor"))
1573 return git_config_string(&editor_program, var, value);
1575 if (!strcmp(var, "core.commentchar")) {
1576 if (!value)
1577 return config_error_nonbool(var);
1578 else if (!strcasecmp(value, "auto"))
1579 auto_comment_line_char = 1;
1580 else if (value[0] && !value[1]) {
1581 comment_line_char = value[0];
1582 auto_comment_line_char = 0;
1583 } else
1584 return error(_("core.commentChar should only be one character"));
1585 return 0;
1588 if (!strcmp(var, "core.askpass"))
1589 return git_config_string(&askpass_program, var, value);
1591 if (!strcmp(var, "core.excludesfile"))
1592 return git_config_pathname(&excludes_file, var, value);
1594 if (!strcmp(var, "core.whitespace")) {
1595 if (!value)
1596 return config_error_nonbool(var);
1597 whitespace_rule_cfg = parse_whitespace_rule(value);
1598 return 0;
1601 if (!strcmp(var, "core.fsyncobjectfiles")) {
1602 fsync_object_files = git_config_bool(var, value);
1603 return 0;
1606 if (!strcmp(var, "core.preloadindex")) {
1607 core_preload_index = git_config_bool(var, value);
1608 return 0;
1611 if (!strcmp(var, "core.createobject")) {
1612 if (!strcmp(value, "rename"))
1613 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
1614 else if (!strcmp(value, "link"))
1615 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
1616 else
1617 die(_("invalid mode for object creation: %s"), value);
1618 return 0;
1621 if (!strcmp(var, "core.sparsecheckout")) {
1622 core_apply_sparse_checkout = git_config_bool(var, value);
1623 return 0;
1626 if (!strcmp(var, "core.sparsecheckoutcone")) {
1627 core_sparse_checkout_cone = git_config_bool(var, value);
1628 return 0;
1631 if (!strcmp(var, "core.precomposeunicode")) {
1632 precomposed_unicode = git_config_bool(var, value);
1633 return 0;
1636 if (!strcmp(var, "core.protecthfs")) {
1637 protect_hfs = git_config_bool(var, value);
1638 return 0;
1641 if (!strcmp(var, "core.protectntfs")) {
1642 protect_ntfs = git_config_bool(var, value);
1643 return 0;
1646 if (!strcmp(var, "core.usereplacerefs")) {
1647 read_replace_refs = git_config_bool(var, value);
1648 return 0;
1651 /* Add other config variables here and to Documentation/config.txt. */
1652 return platform_core_config(var, value, cb);
1655 static int git_default_i18n_config(const char *var, const char *value)
1657 if (!strcmp(var, "i18n.commitencoding"))
1658 return git_config_string(&git_commit_encoding, var, value);
1660 if (!strcmp(var, "i18n.logoutputencoding"))
1661 return git_config_string(&git_log_output_encoding, var, value);
1663 /* Add other config variables here and to Documentation/config.txt. */
1664 return 0;
1667 static int git_default_branch_config(const char *var, const char *value)
1669 if (!strcmp(var, "branch.autosetupmerge")) {
1670 if (value && !strcmp(value, "always")) {
1671 git_branch_track = BRANCH_TRACK_ALWAYS;
1672 return 0;
1673 } else if (value && !strcmp(value, "inherit")) {
1674 git_branch_track = BRANCH_TRACK_INHERIT;
1675 return 0;
1677 git_branch_track = git_config_bool(var, value);
1678 return 0;
1680 if (!strcmp(var, "branch.autosetuprebase")) {
1681 if (!value)
1682 return config_error_nonbool(var);
1683 else if (!strcmp(value, "never"))
1684 autorebase = AUTOREBASE_NEVER;
1685 else if (!strcmp(value, "local"))
1686 autorebase = AUTOREBASE_LOCAL;
1687 else if (!strcmp(value, "remote"))
1688 autorebase = AUTOREBASE_REMOTE;
1689 else if (!strcmp(value, "always"))
1690 autorebase = AUTOREBASE_ALWAYS;
1691 else
1692 return error(_("malformed value for %s"), var);
1693 return 0;
1696 /* Add other config variables here and to Documentation/config.txt. */
1697 return 0;
1700 static int git_default_push_config(const char *var, const char *value)
1702 if (!strcmp(var, "push.default")) {
1703 if (!value)
1704 return config_error_nonbool(var);
1705 else if (!strcmp(value, "nothing"))
1706 push_default = PUSH_DEFAULT_NOTHING;
1707 else if (!strcmp(value, "matching"))
1708 push_default = PUSH_DEFAULT_MATCHING;
1709 else if (!strcmp(value, "simple"))
1710 push_default = PUSH_DEFAULT_SIMPLE;
1711 else if (!strcmp(value, "upstream"))
1712 push_default = PUSH_DEFAULT_UPSTREAM;
1713 else if (!strcmp(value, "tracking")) /* deprecated */
1714 push_default = PUSH_DEFAULT_UPSTREAM;
1715 else if (!strcmp(value, "current"))
1716 push_default = PUSH_DEFAULT_CURRENT;
1717 else {
1718 error(_("malformed value for %s: %s"), var, value);
1719 return error(_("must be one of nothing, matching, simple, "
1720 "upstream or current"));
1722 return 0;
1725 /* Add other config variables here and to Documentation/config.txt. */
1726 return 0;
1729 static int git_default_mailmap_config(const char *var, const char *value)
1731 if (!strcmp(var, "mailmap.file"))
1732 return git_config_pathname(&git_mailmap_file, var, value);
1733 if (!strcmp(var, "mailmap.blob"))
1734 return git_config_string(&git_mailmap_blob, var, value);
1736 /* Add other config variables here and to Documentation/config.txt. */
1737 return 0;
1740 int git_default_config(const char *var, const char *value, void *cb)
1742 if (starts_with(var, "core."))
1743 return git_default_core_config(var, value, cb);
1745 if (starts_with(var, "user.") ||
1746 starts_with(var, "author.") ||
1747 starts_with(var, "committer."))
1748 return git_ident_config(var, value, cb);
1750 if (starts_with(var, "i18n."))
1751 return git_default_i18n_config(var, value);
1753 if (starts_with(var, "branch."))
1754 return git_default_branch_config(var, value);
1756 if (starts_with(var, "push."))
1757 return git_default_push_config(var, value);
1759 if (starts_with(var, "mailmap."))
1760 return git_default_mailmap_config(var, value);
1762 if (starts_with(var, "advice.") || starts_with(var, "color.advice"))
1763 return git_default_advice_config(var, value);
1765 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1766 pager_use_color = git_config_bool(var,value);
1767 return 0;
1770 if (!strcmp(var, "pack.packsizelimit")) {
1771 pack_size_limit_cfg = git_config_ulong(var, value);
1772 return 0;
1775 if (!strcmp(var, "pack.compression")) {
1776 int level = git_config_int(var, value);
1777 if (level == -1)
1778 level = Z_DEFAULT_COMPRESSION;
1779 else if (level < 0 || level > Z_BEST_COMPRESSION)
1780 die(_("bad pack compression level %d"), level);
1781 pack_compression_level = level;
1782 pack_compression_seen = 1;
1783 return 0;
1786 /* Add other config variables here and to Documentation/config.txt. */
1787 return 0;
1791 * All source specific fields in the union, die_on_error, name and the callbacks
1792 * fgetc, ungetc, ftell of top need to be initialized before calling
1793 * this function.
1795 static int do_config_from(struct config_source *top, config_fn_t fn, void *data,
1796 const struct config_options *opts)
1798 int ret;
1800 /* push config-file parsing state stack */
1801 top->prev = cf;
1802 top->linenr = 1;
1803 top->eof = 0;
1804 top->total_len = 0;
1805 strbuf_init(&top->value, 1024);
1806 strbuf_init(&top->var, 1024);
1807 cf = top;
1809 ret = git_parse_source(fn, data, opts);
1811 /* pop config-file parsing state stack */
1812 strbuf_release(&top->value);
1813 strbuf_release(&top->var);
1814 cf = top->prev;
1816 return ret;
1819 static int do_config_from_file(config_fn_t fn,
1820 const enum config_origin_type origin_type,
1821 const char *name, const char *path, FILE *f,
1822 void *data, const struct config_options *opts)
1824 struct config_source top;
1825 int ret;
1827 top.u.file = f;
1828 top.origin_type = origin_type;
1829 top.name = name;
1830 top.path = path;
1831 top.default_error_action = CONFIG_ERROR_DIE;
1832 top.do_fgetc = config_file_fgetc;
1833 top.do_ungetc = config_file_ungetc;
1834 top.do_ftell = config_file_ftell;
1836 flockfile(f);
1837 ret = do_config_from(&top, fn, data, opts);
1838 funlockfile(f);
1839 return ret;
1842 static int git_config_from_stdin(config_fn_t fn, void *data)
1844 return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", NULL, stdin,
1845 data, NULL);
1848 int git_config_from_file_with_options(config_fn_t fn, const char *filename,
1849 void *data,
1850 const struct config_options *opts)
1852 int ret = -1;
1853 FILE *f;
1855 f = fopen_or_warn(filename, "r");
1856 if (f) {
1857 ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename,
1858 filename, f, data, opts);
1859 fclose(f);
1861 return ret;
1864 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
1866 return git_config_from_file_with_options(fn, filename, data, NULL);
1869 int git_config_from_mem(config_fn_t fn,
1870 const enum config_origin_type origin_type,
1871 const char *name, const char *buf, size_t len,
1872 void *data, const struct config_options *opts)
1874 struct config_source top;
1876 top.u.buf.buf = buf;
1877 top.u.buf.len = len;
1878 top.u.buf.pos = 0;
1879 top.origin_type = origin_type;
1880 top.name = name;
1881 top.path = NULL;
1882 top.default_error_action = CONFIG_ERROR_ERROR;
1883 top.do_fgetc = config_buf_fgetc;
1884 top.do_ungetc = config_buf_ungetc;
1885 top.do_ftell = config_buf_ftell;
1887 return do_config_from(&top, fn, data, opts);
1890 int git_config_from_blob_oid(config_fn_t fn,
1891 const char *name,
1892 struct repository *repo,
1893 const struct object_id *oid,
1894 void *data)
1896 enum object_type type;
1897 char *buf;
1898 unsigned long size;
1899 int ret;
1901 buf = repo_read_object_file(repo, oid, &type, &size);
1902 if (!buf)
1903 return error(_("unable to load config blob object '%s'"), name);
1904 if (type != OBJ_BLOB) {
1905 free(buf);
1906 return error(_("reference '%s' does not point to a blob"), name);
1909 ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size,
1910 data, NULL);
1911 free(buf);
1913 return ret;
1916 static int git_config_from_blob_ref(config_fn_t fn,
1917 struct repository *repo,
1918 const char *name,
1919 void *data)
1921 struct object_id oid;
1923 if (repo_get_oid(repo, name, &oid) < 0)
1924 return error(_("unable to resolve config blob '%s'"), name);
1925 return git_config_from_blob_oid(fn, name, repo, &oid, data);
1928 char *git_system_config(void)
1930 char *system_config = xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
1931 if (!system_config)
1932 system_config = system_path(ETC_GITCONFIG);
1933 normalize_path_copy(system_config, system_config);
1934 return system_config;
1937 void git_global_config(char **user_out, char **xdg_out)
1939 char *user_config = xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
1940 char *xdg_config = NULL;
1942 if (!user_config) {
1943 user_config = interpolate_path("~/.gitconfig", 0);
1944 xdg_config = xdg_config_home("config");
1947 *user_out = user_config;
1948 *xdg_out = xdg_config;
1952 * Parse environment variable 'k' as a boolean (in various
1953 * possible spellings); if missing, use the default value 'def'.
1955 int git_env_bool(const char *k, int def)
1957 const char *v = getenv(k);
1958 return v ? git_config_bool(k, v) : def;
1962 * Parse environment variable 'k' as ulong with possibly a unit
1963 * suffix; if missing, use the default value 'val'.
1965 unsigned long git_env_ulong(const char *k, unsigned long val)
1967 const char *v = getenv(k);
1968 if (v && !git_parse_ulong(v, &val))
1969 die(_("failed to parse %s"), k);
1970 return val;
1973 int git_config_system(void)
1975 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
1978 static int do_git_config_sequence(const struct config_options *opts,
1979 config_fn_t fn, void *data)
1981 int ret = 0;
1982 char *system_config = git_system_config();
1983 char *xdg_config = NULL;
1984 char *user_config = NULL;
1985 char *repo_config;
1986 enum config_scope prev_parsing_scope = current_parsing_scope;
1988 if (opts->commondir)
1989 repo_config = mkpathdup("%s/config", opts->commondir);
1990 else if (opts->git_dir)
1991 BUG("git_dir without commondir");
1992 else
1993 repo_config = NULL;
1995 current_parsing_scope = CONFIG_SCOPE_SYSTEM;
1996 if (git_config_system() && system_config &&
1997 !access_or_die(system_config, R_OK,
1998 opts->system_gently ? ACCESS_EACCES_OK : 0))
1999 ret += git_config_from_file(fn, system_config, data);
2001 current_parsing_scope = CONFIG_SCOPE_GLOBAL;
2002 git_global_config(&user_config, &xdg_config);
2004 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
2005 ret += git_config_from_file(fn, xdg_config, data);
2007 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
2008 ret += git_config_from_file(fn, user_config, data);
2010 current_parsing_scope = CONFIG_SCOPE_LOCAL;
2011 if (!opts->ignore_repo && repo_config &&
2012 !access_or_die(repo_config, R_OK, 0))
2013 ret += git_config_from_file(fn, repo_config, data);
2015 current_parsing_scope = CONFIG_SCOPE_WORKTREE;
2016 if (!opts->ignore_worktree && repository_format_worktree_config) {
2017 char *path = git_pathdup("config.worktree");
2018 if (!access_or_die(path, R_OK, 0))
2019 ret += git_config_from_file(fn, path, data);
2020 free(path);
2023 current_parsing_scope = CONFIG_SCOPE_COMMAND;
2024 if (!opts->ignore_cmdline && git_config_from_parameters(fn, data) < 0)
2025 die(_("unable to parse command-line config"));
2027 current_parsing_scope = prev_parsing_scope;
2028 free(system_config);
2029 free(xdg_config);
2030 free(user_config);
2031 free(repo_config);
2032 return ret;
2035 int config_with_options(config_fn_t fn, void *data,
2036 struct git_config_source *config_source,
2037 const struct config_options *opts)
2039 struct config_include_data inc = CONFIG_INCLUDE_INIT;
2040 int ret;
2042 if (opts->respect_includes) {
2043 inc.fn = fn;
2044 inc.data = data;
2045 inc.opts = opts;
2046 inc.config_source = config_source;
2047 fn = git_config_include;
2048 data = &inc;
2051 if (config_source)
2052 current_parsing_scope = config_source->scope;
2055 * If we have a specific filename, use it. Otherwise, follow the
2056 * regular lookup sequence.
2058 if (config_source && config_source->use_stdin) {
2059 ret = git_config_from_stdin(fn, data);
2060 } else if (config_source && config_source->file) {
2061 ret = git_config_from_file(fn, config_source->file, data);
2062 } else if (config_source && config_source->blob) {
2063 struct repository *repo = config_source->repo ?
2064 config_source->repo : the_repository;
2065 ret = git_config_from_blob_ref(fn, repo, config_source->blob,
2066 data);
2067 } else {
2068 ret = do_git_config_sequence(opts, fn, data);
2071 if (inc.remote_urls) {
2072 string_list_clear(inc.remote_urls, 0);
2073 FREE_AND_NULL(inc.remote_urls);
2075 return ret;
2078 static void configset_iter(struct config_set *cs, config_fn_t fn, void *data)
2080 int i, value_index;
2081 struct string_list *values;
2082 struct config_set_element *entry;
2083 struct configset_list *list = &cs->list;
2085 for (i = 0; i < list->nr; i++) {
2086 entry = list->items[i].e;
2087 value_index = list->items[i].value_index;
2088 values = &entry->value_list;
2090 current_config_kvi = values->items[value_index].util;
2092 if (fn(entry->key, values->items[value_index].string, data) < 0)
2093 git_die_config_linenr(entry->key,
2094 current_config_kvi->filename,
2095 current_config_kvi->linenr);
2097 current_config_kvi = NULL;
2101 void read_early_config(config_fn_t cb, void *data)
2103 struct config_options opts = {0};
2104 struct strbuf commondir = STRBUF_INIT;
2105 struct strbuf gitdir = STRBUF_INIT;
2107 opts.respect_includes = 1;
2109 if (have_git_dir()) {
2110 opts.commondir = get_git_common_dir();
2111 opts.git_dir = get_git_dir();
2113 * When setup_git_directory() was not yet asked to discover the
2114 * GIT_DIR, we ask discover_git_directory() to figure out whether there
2115 * is any repository config we should use (but unlike
2116 * setup_git_directory_gently(), no global state is changed, most
2117 * notably, the current working directory is still the same after the
2118 * call).
2120 } else if (!discover_git_directory(&commondir, &gitdir)) {
2121 opts.commondir = commondir.buf;
2122 opts.git_dir = gitdir.buf;
2125 config_with_options(cb, data, NULL, &opts);
2127 strbuf_release(&commondir);
2128 strbuf_release(&gitdir);
2132 * Read config but only enumerate system and global settings.
2133 * Omit any repo-local, worktree-local, or command-line settings.
2135 void read_very_early_config(config_fn_t cb, void *data)
2137 struct config_options opts = { 0 };
2139 opts.respect_includes = 1;
2140 opts.ignore_repo = 1;
2141 opts.ignore_worktree = 1;
2142 opts.ignore_cmdline = 1;
2143 opts.system_gently = 1;
2145 config_with_options(cb, data, NULL, &opts);
2148 static struct config_set_element *configset_find_element(struct config_set *cs, const char *key)
2150 struct config_set_element k;
2151 struct config_set_element *found_entry;
2152 char *normalized_key;
2154 * `key` may come from the user, so normalize it before using it
2155 * for querying entries from the hashmap.
2157 if (git_config_parse_key(key, &normalized_key, NULL))
2158 return NULL;
2160 hashmap_entry_init(&k.ent, strhash(normalized_key));
2161 k.key = normalized_key;
2162 found_entry = hashmap_get_entry(&cs->config_hash, &k, ent, NULL);
2163 free(normalized_key);
2164 return found_entry;
2167 static int configset_add_value(struct config_set *cs, const char *key, const char *value)
2169 struct config_set_element *e;
2170 struct string_list_item *si;
2171 struct configset_list_item *l_item;
2172 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
2174 e = configset_find_element(cs, key);
2176 * Since the keys are being fed by git_config*() callback mechanism, they
2177 * are already normalized. So simply add them without any further munging.
2179 if (!e) {
2180 e = xmalloc(sizeof(*e));
2181 hashmap_entry_init(&e->ent, strhash(key));
2182 e->key = xstrdup(key);
2183 string_list_init_dup(&e->value_list);
2184 hashmap_add(&cs->config_hash, &e->ent);
2186 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
2188 ALLOC_GROW(cs->list.items, cs->list.nr + 1, cs->list.alloc);
2189 l_item = &cs->list.items[cs->list.nr++];
2190 l_item->e = e;
2191 l_item->value_index = e->value_list.nr - 1;
2193 if (!cf)
2194 BUG("configset_add_value has no source");
2195 if (cf->name) {
2196 kv_info->filename = strintern(cf->name);
2197 kv_info->linenr = cf->linenr;
2198 kv_info->origin_type = cf->origin_type;
2199 } else {
2200 /* for values read from `git_config_from_parameters()` */
2201 kv_info->filename = NULL;
2202 kv_info->linenr = -1;
2203 kv_info->origin_type = CONFIG_ORIGIN_CMDLINE;
2205 kv_info->scope = current_parsing_scope;
2206 si->util = kv_info;
2208 return 0;
2211 static int config_set_element_cmp(const void *unused_cmp_data,
2212 const struct hashmap_entry *eptr,
2213 const struct hashmap_entry *entry_or_key,
2214 const void *unused_keydata)
2216 const struct config_set_element *e1, *e2;
2218 e1 = container_of(eptr, const struct config_set_element, ent);
2219 e2 = container_of(entry_or_key, const struct config_set_element, ent);
2221 return strcmp(e1->key, e2->key);
2224 void git_configset_init(struct config_set *cs)
2226 hashmap_init(&cs->config_hash, config_set_element_cmp, NULL, 0);
2227 cs->hash_initialized = 1;
2228 cs->list.nr = 0;
2229 cs->list.alloc = 0;
2230 cs->list.items = NULL;
2233 void git_configset_clear(struct config_set *cs)
2235 struct config_set_element *entry;
2236 struct hashmap_iter iter;
2237 if (!cs->hash_initialized)
2238 return;
2240 hashmap_for_each_entry(&cs->config_hash, &iter, entry,
2241 ent /* member name */) {
2242 free(entry->key);
2243 string_list_clear(&entry->value_list, 1);
2245 hashmap_clear_and_free(&cs->config_hash, struct config_set_element, ent);
2246 cs->hash_initialized = 0;
2247 free(cs->list.items);
2248 cs->list.nr = 0;
2249 cs->list.alloc = 0;
2250 cs->list.items = NULL;
2253 static int config_set_callback(const char *key, const char *value, void *cb)
2255 struct config_set *cs = cb;
2256 configset_add_value(cs, key, value);
2257 return 0;
2260 int git_configset_add_file(struct config_set *cs, const char *filename)
2262 return git_config_from_file(config_set_callback, filename, cs);
2265 int git_configset_get_value(struct config_set *cs, const char *key, const char **value)
2267 const struct string_list *values = NULL;
2269 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
2270 * queried key in the files of the configset, the value returned will be the last
2271 * value in the value list for that key.
2273 values = git_configset_get_value_multi(cs, key);
2275 if (!values)
2276 return 1;
2277 assert(values->nr > 0);
2278 *value = values->items[values->nr - 1].string;
2279 return 0;
2282 const struct string_list *git_configset_get_value_multi(struct config_set *cs, const char *key)
2284 struct config_set_element *e = configset_find_element(cs, key);
2285 return e ? &e->value_list : NULL;
2288 int git_configset_get_string(struct config_set *cs, const char *key, char **dest)
2290 const char *value;
2291 if (!git_configset_get_value(cs, key, &value))
2292 return git_config_string((const char **)dest, key, value);
2293 else
2294 return 1;
2297 int git_configset_get_string_tmp(struct config_set *cs, const char *key,
2298 const char **dest)
2300 const char *value;
2301 if (!git_configset_get_value(cs, key, &value)) {
2302 if (!value)
2303 return config_error_nonbool(key);
2304 *dest = value;
2305 return 0;
2306 } else {
2307 return 1;
2311 int git_configset_get_int(struct config_set *cs, const char *key, int *dest)
2313 const char *value;
2314 if (!git_configset_get_value(cs, key, &value)) {
2315 *dest = git_config_int(key, value);
2316 return 0;
2317 } else
2318 return 1;
2321 int git_configset_get_ulong(struct config_set *cs, const char *key, unsigned long *dest)
2323 const char *value;
2324 if (!git_configset_get_value(cs, key, &value)) {
2325 *dest = git_config_ulong(key, value);
2326 return 0;
2327 } else
2328 return 1;
2331 int git_configset_get_bool(struct config_set *cs, const char *key, int *dest)
2333 const char *value;
2334 if (!git_configset_get_value(cs, key, &value)) {
2335 *dest = git_config_bool(key, value);
2336 return 0;
2337 } else
2338 return 1;
2341 int git_configset_get_bool_or_int(struct config_set *cs, const char *key,
2342 int *is_bool, int *dest)
2344 const char *value;
2345 if (!git_configset_get_value(cs, key, &value)) {
2346 *dest = git_config_bool_or_int(key, value, is_bool);
2347 return 0;
2348 } else
2349 return 1;
2352 int git_configset_get_maybe_bool(struct config_set *cs, const char *key, int *dest)
2354 const char *value;
2355 if (!git_configset_get_value(cs, key, &value)) {
2356 *dest = git_parse_maybe_bool(value);
2357 if (*dest == -1)
2358 return -1;
2359 return 0;
2360 } else
2361 return 1;
2364 int git_configset_get_pathname(struct config_set *cs, const char *key, const char **dest)
2366 const char *value;
2367 if (!git_configset_get_value(cs, key, &value))
2368 return git_config_pathname(dest, key, value);
2369 else
2370 return 1;
2373 /* Functions use to read configuration from a repository */
2374 static void repo_read_config(struct repository *repo)
2376 struct config_options opts = { 0 };
2378 opts.respect_includes = 1;
2379 opts.commondir = repo->commondir;
2380 opts.git_dir = repo->gitdir;
2382 if (!repo->config)
2383 CALLOC_ARRAY(repo->config, 1);
2384 else
2385 git_configset_clear(repo->config);
2387 git_configset_init(repo->config);
2389 if (config_with_options(config_set_callback, repo->config, NULL, &opts) < 0)
2391 * config_with_options() normally returns only
2392 * zero, as most errors are fatal, and
2393 * non-fatal potential errors are guarded by "if"
2394 * statements that are entered only when no error is
2395 * possible.
2397 * If we ever encounter a non-fatal error, it means
2398 * something went really wrong and we should stop
2399 * immediately.
2401 die(_("unknown error occurred while reading the configuration files"));
2404 static void git_config_check_init(struct repository *repo)
2406 if (repo->config && repo->config->hash_initialized)
2407 return;
2408 repo_read_config(repo);
2411 static void repo_config_clear(struct repository *repo)
2413 if (!repo->config || !repo->config->hash_initialized)
2414 return;
2415 git_configset_clear(repo->config);
2418 void repo_config(struct repository *repo, config_fn_t fn, void *data)
2420 git_config_check_init(repo);
2421 configset_iter(repo->config, fn, data);
2424 int repo_config_get_value(struct repository *repo,
2425 const char *key, const char **value)
2427 git_config_check_init(repo);
2428 return git_configset_get_value(repo->config, key, value);
2431 const struct string_list *repo_config_get_value_multi(struct repository *repo,
2432 const char *key)
2434 git_config_check_init(repo);
2435 return git_configset_get_value_multi(repo->config, key);
2438 int repo_config_get_string(struct repository *repo,
2439 const char *key, char **dest)
2441 int ret;
2442 git_config_check_init(repo);
2443 ret = git_configset_get_string(repo->config, key, dest);
2444 if (ret < 0)
2445 git_die_config(key, NULL);
2446 return ret;
2449 int repo_config_get_string_tmp(struct repository *repo,
2450 const char *key, const char **dest)
2452 int ret;
2453 git_config_check_init(repo);
2454 ret = git_configset_get_string_tmp(repo->config, key, dest);
2455 if (ret < 0)
2456 git_die_config(key, NULL);
2457 return ret;
2460 int repo_config_get_int(struct repository *repo,
2461 const char *key, int *dest)
2463 git_config_check_init(repo);
2464 return git_configset_get_int(repo->config, key, dest);
2467 int repo_config_get_ulong(struct repository *repo,
2468 const char *key, unsigned long *dest)
2470 git_config_check_init(repo);
2471 return git_configset_get_ulong(repo->config, key, dest);
2474 int repo_config_get_bool(struct repository *repo,
2475 const char *key, int *dest)
2477 git_config_check_init(repo);
2478 return git_configset_get_bool(repo->config, key, dest);
2481 int repo_config_get_bool_or_int(struct repository *repo,
2482 const char *key, int *is_bool, int *dest)
2484 git_config_check_init(repo);
2485 return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2488 int repo_config_get_maybe_bool(struct repository *repo,
2489 const char *key, int *dest)
2491 git_config_check_init(repo);
2492 return git_configset_get_maybe_bool(repo->config, key, dest);
2495 int repo_config_get_pathname(struct repository *repo,
2496 const char *key, const char **dest)
2498 int ret;
2499 git_config_check_init(repo);
2500 ret = git_configset_get_pathname(repo->config, key, dest);
2501 if (ret < 0)
2502 git_die_config(key, NULL);
2503 return ret;
2506 /* Functions used historically to read configuration from 'the_repository' */
2507 void git_config(config_fn_t fn, void *data)
2509 repo_config(the_repository, fn, data);
2512 void git_config_clear(void)
2514 repo_config_clear(the_repository);
2517 int git_config_get_value(const char *key, const char **value)
2519 return repo_config_get_value(the_repository, key, value);
2522 const struct string_list *git_config_get_value_multi(const char *key)
2524 return repo_config_get_value_multi(the_repository, key);
2527 int git_config_get_string(const char *key, char **dest)
2529 return repo_config_get_string(the_repository, key, dest);
2532 int git_config_get_string_tmp(const char *key, const char **dest)
2534 return repo_config_get_string_tmp(the_repository, key, dest);
2537 int git_config_get_int(const char *key, int *dest)
2539 return repo_config_get_int(the_repository, key, dest);
2542 int git_config_get_ulong(const char *key, unsigned long *dest)
2544 return repo_config_get_ulong(the_repository, key, dest);
2547 int git_config_get_bool(const char *key, int *dest)
2549 return repo_config_get_bool(the_repository, key, dest);
2552 int git_config_get_bool_or_int(const char *key, int *is_bool, int *dest)
2554 return repo_config_get_bool_or_int(the_repository, key, is_bool, dest);
2557 int git_config_get_maybe_bool(const char *key, int *dest)
2559 return repo_config_get_maybe_bool(the_repository, key, dest);
2562 int git_config_get_pathname(const char *key, const char **dest)
2564 return repo_config_get_pathname(the_repository, key, dest);
2567 int git_config_get_expiry(const char *key, const char **output)
2569 int ret = git_config_get_string(key, (char **)output);
2570 if (ret)
2571 return ret;
2572 if (strcmp(*output, "now")) {
2573 timestamp_t now = approxidate("now");
2574 if (approxidate(*output) >= now)
2575 git_die_config(key, _("Invalid %s: '%s'"), key, *output);
2577 return ret;
2580 int git_config_get_expiry_in_days(const char *key, timestamp_t *expiry, timestamp_t now)
2582 const char *expiry_string;
2583 intmax_t days;
2584 timestamp_t when;
2586 if (git_config_get_string_tmp(key, &expiry_string))
2587 return 1; /* no such thing */
2589 if (git_parse_signed(expiry_string, &days, maximum_signed_value_of_type(int))) {
2590 const int scale = 86400;
2591 *expiry = now - days * scale;
2592 return 0;
2595 if (!parse_expiry_date(expiry_string, &when)) {
2596 *expiry = when;
2597 return 0;
2599 return -1; /* thing exists but cannot be parsed */
2602 int git_config_get_split_index(void)
2604 int val;
2606 if (!git_config_get_maybe_bool("core.splitindex", &val))
2607 return val;
2609 return -1; /* default value */
2612 int git_config_get_max_percent_split_change(void)
2614 int val = -1;
2616 if (!git_config_get_int("splitindex.maxpercentchange", &val)) {
2617 if (0 <= val && val <= 100)
2618 return val;
2620 return error(_("splitIndex.maxPercentChange value '%d' "
2621 "should be between 0 and 100"), val);
2624 return -1; /* default value */
2627 int git_config_get_fsmonitor(void)
2629 if (git_config_get_pathname("core.fsmonitor", &core_fsmonitor))
2630 core_fsmonitor = getenv("GIT_TEST_FSMONITOR");
2632 if (core_fsmonitor && !*core_fsmonitor)
2633 core_fsmonitor = NULL;
2635 if (core_fsmonitor)
2636 return 1;
2638 return 0;
2641 int git_config_get_index_threads(int *dest)
2643 int is_bool, val;
2645 val = git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2646 if (val) {
2647 *dest = val;
2648 return 0;
2651 if (!git_config_get_bool_or_int("index.threads", &is_bool, &val)) {
2652 if (is_bool)
2653 *dest = val ? 0 : 1;
2654 else
2655 *dest = val;
2656 return 0;
2659 return 1;
2662 NORETURN
2663 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2665 if (!filename)
2666 die(_("unable to parse '%s' from command-line config"), key);
2667 else
2668 die(_("bad config variable '%s' in file '%s' at line %d"),
2669 key, filename, linenr);
2672 NORETURN __attribute__((format(printf, 2, 3)))
2673 void git_die_config(const char *key, const char *err, ...)
2675 const struct string_list *values;
2676 struct key_value_info *kv_info;
2677 report_fn error_fn = get_error_routine();
2679 if (err) {
2680 va_list params;
2681 va_start(params, err);
2682 error_fn(err, params);
2683 va_end(params);
2685 values = git_config_get_value_multi(key);
2686 kv_info = values->items[values->nr - 1].util;
2687 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
2691 * Find all the stuff for git_config_set() below.
2694 struct config_store_data {
2695 size_t baselen;
2696 char *key;
2697 int do_not_match;
2698 const char *fixed_value;
2699 regex_t *value_pattern;
2700 int multi_replace;
2701 struct {
2702 size_t begin, end;
2703 enum config_event_t type;
2704 int is_keys_section;
2705 } *parsed;
2706 unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
2707 unsigned int key_seen:1, section_seen:1, is_keys_section:1;
2710 static void config_store_data_clear(struct config_store_data *store)
2712 free(store->key);
2713 if (store->value_pattern != NULL &&
2714 store->value_pattern != CONFIG_REGEX_NONE) {
2715 regfree(store->value_pattern);
2716 free(store->value_pattern);
2718 free(store->parsed);
2719 free(store->seen);
2720 memset(store, 0, sizeof(*store));
2723 static int matches(const char *key, const char *value,
2724 const struct config_store_data *store)
2726 if (strcmp(key, store->key))
2727 return 0; /* not ours */
2728 if (store->fixed_value)
2729 return !strcmp(store->fixed_value, value);
2730 if (!store->value_pattern)
2731 return 1; /* always matches */
2732 if (store->value_pattern == CONFIG_REGEX_NONE)
2733 return 0; /* never matches */
2735 return store->do_not_match ^
2736 (value && !regexec(store->value_pattern, value, 0, NULL, 0));
2739 static int store_aux_event(enum config_event_t type,
2740 size_t begin, size_t end, void *data)
2742 struct config_store_data *store = data;
2744 ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
2745 store->parsed[store->parsed_nr].begin = begin;
2746 store->parsed[store->parsed_nr].end = end;
2747 store->parsed[store->parsed_nr].type = type;
2749 if (type == CONFIG_EVENT_SECTION) {
2750 int (*cmpfn)(const char *, const char *, size_t);
2752 if (cf->var.len < 2 || cf->var.buf[cf->var.len - 1] != '.')
2753 return error(_("invalid section name '%s'"), cf->var.buf);
2755 if (cf->subsection_case_sensitive)
2756 cmpfn = strncasecmp;
2757 else
2758 cmpfn = strncmp;
2760 /* Is this the section we were looking for? */
2761 store->is_keys_section =
2762 store->parsed[store->parsed_nr].is_keys_section =
2763 cf->var.len - 1 == store->baselen &&
2764 !cmpfn(cf->var.buf, store->key, store->baselen);
2765 if (store->is_keys_section) {
2766 store->section_seen = 1;
2767 ALLOC_GROW(store->seen, store->seen_nr + 1,
2768 store->seen_alloc);
2769 store->seen[store->seen_nr] = store->parsed_nr;
2773 store->parsed_nr++;
2775 return 0;
2778 static int store_aux(const char *key, const char *value, void *cb)
2780 struct config_store_data *store = cb;
2782 if (store->key_seen) {
2783 if (matches(key, value, store)) {
2784 if (store->seen_nr == 1 && store->multi_replace == 0) {
2785 warning(_("%s has multiple values"), key);
2788 ALLOC_GROW(store->seen, store->seen_nr + 1,
2789 store->seen_alloc);
2791 store->seen[store->seen_nr] = store->parsed_nr;
2792 store->seen_nr++;
2794 } else if (store->is_keys_section) {
2796 * Do not increment matches yet: this may not be a match, but we
2797 * are in the desired section.
2799 ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
2800 store->seen[store->seen_nr] = store->parsed_nr;
2801 store->section_seen = 1;
2803 if (matches(key, value, store)) {
2804 store->seen_nr++;
2805 store->key_seen = 1;
2809 return 0;
2812 static int write_error(const char *filename)
2814 error(_("failed to write new configuration file %s"), filename);
2816 /* Same error code as "failed to rename". */
2817 return 4;
2820 static struct strbuf store_create_section(const char *key,
2821 const struct config_store_data *store)
2823 const char *dot;
2824 size_t i;
2825 struct strbuf sb = STRBUF_INIT;
2827 dot = memchr(key, '.', store->baselen);
2828 if (dot) {
2829 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
2830 for (i = dot - key + 1; i < store->baselen; i++) {
2831 if (key[i] == '"' || key[i] == '\\')
2832 strbuf_addch(&sb, '\\');
2833 strbuf_addch(&sb, key[i]);
2835 strbuf_addstr(&sb, "\"]\n");
2836 } else {
2837 strbuf_addch(&sb, '[');
2838 strbuf_add(&sb, key, store->baselen);
2839 strbuf_addstr(&sb, "]\n");
2842 return sb;
2845 static ssize_t write_section(int fd, const char *key,
2846 const struct config_store_data *store)
2848 struct strbuf sb = store_create_section(key, store);
2849 ssize_t ret;
2851 ret = write_in_full(fd, sb.buf, sb.len);
2852 strbuf_release(&sb);
2854 return ret;
2857 static ssize_t write_pair(int fd, const char *key, const char *value,
2858 const struct config_store_data *store)
2860 int i;
2861 ssize_t ret;
2862 const char *quote = "";
2863 struct strbuf sb = STRBUF_INIT;
2866 * Check to see if the value needs to be surrounded with a dq pair.
2867 * Note that problematic characters are always backslash-quoted; this
2868 * check is about not losing leading or trailing SP and strings that
2869 * follow beginning-of-comment characters (i.e. ';' and '#') by the
2870 * configuration parser.
2872 if (value[0] == ' ')
2873 quote = "\"";
2874 for (i = 0; value[i]; i++)
2875 if (value[i] == ';' || value[i] == '#')
2876 quote = "\"";
2877 if (i && value[i - 1] == ' ')
2878 quote = "\"";
2880 strbuf_addf(&sb, "\t%s = %s", key + store->baselen + 1, quote);
2882 for (i = 0; value[i]; i++)
2883 switch (value[i]) {
2884 case '\n':
2885 strbuf_addstr(&sb, "\\n");
2886 break;
2887 case '\t':
2888 strbuf_addstr(&sb, "\\t");
2889 break;
2890 case '"':
2891 case '\\':
2892 strbuf_addch(&sb, '\\');
2893 /* fallthrough */
2894 default:
2895 strbuf_addch(&sb, value[i]);
2896 break;
2898 strbuf_addf(&sb, "%s\n", quote);
2900 ret = write_in_full(fd, sb.buf, sb.len);
2901 strbuf_release(&sb);
2903 return ret;
2907 * If we are about to unset the last key(s) in a section, and if there are
2908 * no comments surrounding (or included in) the section, we will want to
2909 * extend begin/end to remove the entire section.
2911 * Note: the parameter `seen_ptr` points to the index into the store.seen
2912 * array. * This index may be incremented if a section has more than one
2913 * entry (which all are to be removed).
2915 static void maybe_remove_section(struct config_store_data *store,
2916 size_t *begin_offset, size_t *end_offset,
2917 int *seen_ptr)
2919 size_t begin;
2920 int i, seen, section_seen = 0;
2923 * First, ensure that this is the first key, and that there are no
2924 * comments before the entry nor before the section header.
2926 seen = *seen_ptr;
2927 for (i = store->seen[seen]; i > 0; i--) {
2928 enum config_event_t type = store->parsed[i - 1].type;
2930 if (type == CONFIG_EVENT_COMMENT)
2931 /* There is a comment before this entry or section */
2932 return;
2933 if (type == CONFIG_EVENT_ENTRY) {
2934 if (!section_seen)
2935 /* This is not the section's first entry. */
2936 return;
2937 /* We encountered no comment before the section. */
2938 break;
2940 if (type == CONFIG_EVENT_SECTION) {
2941 if (!store->parsed[i - 1].is_keys_section)
2942 break;
2943 section_seen = 1;
2946 begin = store->parsed[i].begin;
2949 * Next, make sure that we are removing the last key(s) in the section,
2950 * and that there are no comments that are possibly about the current
2951 * section.
2953 for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
2954 enum config_event_t type = store->parsed[i].type;
2956 if (type == CONFIG_EVENT_COMMENT)
2957 return;
2958 if (type == CONFIG_EVENT_SECTION) {
2959 if (store->parsed[i].is_keys_section)
2960 continue;
2961 break;
2963 if (type == CONFIG_EVENT_ENTRY) {
2964 if (++seen < store->seen_nr &&
2965 i == store->seen[seen])
2966 /* We want to remove this entry, too */
2967 continue;
2968 /* There is another entry in this section. */
2969 return;
2974 * We are really removing the last entry/entries from this section, and
2975 * there are no enclosed or surrounding comments. Remove the entire,
2976 * now-empty section.
2978 *seen_ptr = seen;
2979 *begin_offset = begin;
2980 if (i < store->parsed_nr)
2981 *end_offset = store->parsed[i].begin;
2982 else
2983 *end_offset = store->parsed[store->parsed_nr - 1].end;
2986 int git_config_set_in_file_gently(const char *config_filename,
2987 const char *key, const char *value)
2989 return git_config_set_multivar_in_file_gently(config_filename, key, value, NULL, 0);
2992 void git_config_set_in_file(const char *config_filename,
2993 const char *key, const char *value)
2995 git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
2998 int git_config_set_gently(const char *key, const char *value)
3000 return git_config_set_multivar_gently(key, value, NULL, 0);
3003 void git_config_set(const char *key, const char *value)
3005 git_config_set_multivar(key, value, NULL, 0);
3007 trace2_cmd_set_config(key, value);
3011 * If value==NULL, unset in (remove from) config,
3012 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
3013 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
3014 * (only add a new one)
3015 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3016 * key/values are removed before a single new pair is written. If the
3017 * flag is not present, then replace only the first match.
3019 * Returns 0 on success.
3021 * This function does this:
3023 * - it locks the config file by creating ".git/config.lock"
3025 * - it then parses the config using store_aux() as validator to find
3026 * the position on the key/value pair to replace. If it is to be unset,
3027 * it must be found exactly once.
3029 * - the config file is mmap()ed and the part before the match (if any) is
3030 * written to the lock file, then the changed part and the rest.
3032 * - the config file is removed and the lock file rename()d to it.
3035 int git_config_set_multivar_in_file_gently(const char *config_filename,
3036 const char *key, const char *value,
3037 const char *value_pattern,
3038 unsigned flags)
3040 int fd = -1, in_fd = -1;
3041 int ret;
3042 struct lock_file lock = LOCK_INIT;
3043 char *filename_buf = NULL;
3044 char *contents = NULL;
3045 size_t contents_sz;
3046 struct config_store_data store;
3048 memset(&store, 0, sizeof(store));
3050 /* parse-key returns negative; flip the sign to feed exit(3) */
3051 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
3052 if (ret)
3053 goto out_free;
3055 store.multi_replace = (flags & CONFIG_FLAGS_MULTI_REPLACE) != 0;
3057 if (!config_filename)
3058 config_filename = filename_buf = git_pathdup("config");
3061 * The lock serves a purpose in addition to locking: the new
3062 * contents of .git/config will be written into it.
3064 fd = hold_lock_file_for_update(&lock, config_filename, 0);
3065 if (fd < 0) {
3066 error_errno(_("could not lock config file %s"), config_filename);
3067 ret = CONFIG_NO_LOCK;
3068 goto out_free;
3072 * If .git/config does not exist yet, write a minimal version.
3074 in_fd = open(config_filename, O_RDONLY);
3075 if ( in_fd < 0 ) {
3076 if ( ENOENT != errno ) {
3077 error_errno(_("opening %s"), config_filename);
3078 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
3079 goto out_free;
3081 /* if nothing to unset, error out */
3082 if (value == NULL) {
3083 ret = CONFIG_NOTHING_SET;
3084 goto out_free;
3087 free(store.key);
3088 store.key = xstrdup(key);
3089 if (write_section(fd, key, &store) < 0 ||
3090 write_pair(fd, key, value, &store) < 0)
3091 goto write_err_out;
3092 } else {
3093 struct stat st;
3094 size_t copy_begin, copy_end;
3095 int i, new_line = 0;
3096 struct config_options opts;
3098 if (value_pattern == NULL)
3099 store.value_pattern = NULL;
3100 else if (value_pattern == CONFIG_REGEX_NONE)
3101 store.value_pattern = CONFIG_REGEX_NONE;
3102 else if (flags & CONFIG_FLAGS_FIXED_VALUE)
3103 store.fixed_value = value_pattern;
3104 else {
3105 if (value_pattern[0] == '!') {
3106 store.do_not_match = 1;
3107 value_pattern++;
3108 } else
3109 store.do_not_match = 0;
3111 store.value_pattern = (regex_t*)xmalloc(sizeof(regex_t));
3112 if (regcomp(store.value_pattern, value_pattern,
3113 REG_EXTENDED)) {
3114 error(_("invalid pattern: %s"), value_pattern);
3115 FREE_AND_NULL(store.value_pattern);
3116 ret = CONFIG_INVALID_PATTERN;
3117 goto out_free;
3121 ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
3122 store.parsed[0].end = 0;
3124 memset(&opts, 0, sizeof(opts));
3125 opts.event_fn = store_aux_event;
3126 opts.event_fn_data = &store;
3129 * After this, store.parsed will contain offsets of all the
3130 * parsed elements, and store.seen will contain a list of
3131 * matches, as indices into store.parsed.
3133 * As a side effect, we make sure to transform only a valid
3134 * existing config file.
3136 if (git_config_from_file_with_options(store_aux,
3137 config_filename,
3138 &store, &opts)) {
3139 error(_("invalid config file %s"), config_filename);
3140 ret = CONFIG_INVALID_FILE;
3141 goto out_free;
3144 /* if nothing to unset, or too many matches, error out */
3145 if ((store.seen_nr == 0 && value == NULL) ||
3146 (store.seen_nr > 1 && !store.multi_replace)) {
3147 ret = CONFIG_NOTHING_SET;
3148 goto out_free;
3151 if (fstat(in_fd, &st) == -1) {
3152 error_errno(_("fstat on %s failed"), config_filename);
3153 ret = CONFIG_INVALID_FILE;
3154 goto out_free;
3157 contents_sz = xsize_t(st.st_size);
3158 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
3159 MAP_PRIVATE, in_fd, 0);
3160 if (contents == MAP_FAILED) {
3161 if (errno == ENODEV && S_ISDIR(st.st_mode))
3162 errno = EISDIR;
3163 error_errno(_("unable to mmap '%s'%s"),
3164 config_filename, mmap_os_err());
3165 ret = CONFIG_INVALID_FILE;
3166 contents = NULL;
3167 goto out_free;
3169 close(in_fd);
3170 in_fd = -1;
3172 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3173 error_errno(_("chmod on %s failed"), get_lock_file_path(&lock));
3174 ret = CONFIG_NO_WRITE;
3175 goto out_free;
3178 if (store.seen_nr == 0) {
3179 if (!store.seen_alloc) {
3180 /* Did not see key nor section */
3181 ALLOC_GROW(store.seen, 1, store.seen_alloc);
3182 store.seen[0] = store.parsed_nr
3183 - !!store.parsed_nr;
3185 store.seen_nr = 1;
3188 for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
3189 size_t replace_end;
3190 int j = store.seen[i];
3192 new_line = 0;
3193 if (!store.key_seen) {
3194 copy_end = store.parsed[j].end;
3195 /* include '\n' when copying section header */
3196 if (copy_end > 0 && copy_end < contents_sz &&
3197 contents[copy_end - 1] != '\n' &&
3198 contents[copy_end] == '\n')
3199 copy_end++;
3200 replace_end = copy_end;
3201 } else {
3202 replace_end = store.parsed[j].end;
3203 copy_end = store.parsed[j].begin;
3204 if (!value)
3205 maybe_remove_section(&store,
3206 &copy_end,
3207 &replace_end, &i);
3209 * Swallow preceding white-space on the same
3210 * line.
3212 while (copy_end > 0 ) {
3213 char c = contents[copy_end - 1];
3215 if (isspace(c) && c != '\n')
3216 copy_end--;
3217 else
3218 break;
3222 if (copy_end > 0 && contents[copy_end-1] != '\n')
3223 new_line = 1;
3225 /* write the first part of the config */
3226 if (copy_end > copy_begin) {
3227 if (write_in_full(fd, contents + copy_begin,
3228 copy_end - copy_begin) < 0)
3229 goto write_err_out;
3230 if (new_line &&
3231 write_str_in_full(fd, "\n") < 0)
3232 goto write_err_out;
3234 copy_begin = replace_end;
3237 /* write the pair (value == NULL means unset) */
3238 if (value != NULL) {
3239 if (!store.section_seen) {
3240 if (write_section(fd, key, &store) < 0)
3241 goto write_err_out;
3243 if (write_pair(fd, key, value, &store) < 0)
3244 goto write_err_out;
3247 /* write the rest of the config */
3248 if (copy_begin < contents_sz)
3249 if (write_in_full(fd, contents + copy_begin,
3250 contents_sz - copy_begin) < 0)
3251 goto write_err_out;
3253 munmap(contents, contents_sz);
3254 contents = NULL;
3257 if (commit_lock_file(&lock) < 0) {
3258 error_errno(_("could not write config file %s"), config_filename);
3259 ret = CONFIG_NO_WRITE;
3260 goto out_free;
3263 ret = 0;
3265 /* Invalidate the config cache */
3266 git_config_clear();
3268 out_free:
3269 rollback_lock_file(&lock);
3270 free(filename_buf);
3271 if (contents)
3272 munmap(contents, contents_sz);
3273 if (in_fd >= 0)
3274 close(in_fd);
3275 config_store_data_clear(&store);
3276 return ret;
3278 write_err_out:
3279 ret = write_error(get_lock_file_path(&lock));
3280 goto out_free;
3284 void git_config_set_multivar_in_file(const char *config_filename,
3285 const char *key, const char *value,
3286 const char *value_pattern, unsigned flags)
3288 if (!git_config_set_multivar_in_file_gently(config_filename, key, value,
3289 value_pattern, flags))
3290 return;
3291 if (value)
3292 die(_("could not set '%s' to '%s'"), key, value);
3293 else
3294 die(_("could not unset '%s'"), key);
3297 int git_config_set_multivar_gently(const char *key, const char *value,
3298 const char *value_pattern, unsigned flags)
3300 return git_config_set_multivar_in_file_gently(NULL, key, value, value_pattern,
3301 flags);
3304 void git_config_set_multivar(const char *key, const char *value,
3305 const char *value_pattern, unsigned flags)
3307 git_config_set_multivar_in_file(NULL, key, value, value_pattern,
3308 flags);
3311 static int section_name_match (const char *buf, const char *name)
3313 int i = 0, j = 0, dot = 0;
3314 if (buf[i] != '[')
3315 return 0;
3316 for (i = 1; buf[i] && buf[i] != ']'; i++) {
3317 if (!dot && isspace(buf[i])) {
3318 dot = 1;
3319 if (name[j++] != '.')
3320 break;
3321 for (i++; isspace(buf[i]); i++)
3322 ; /* do nothing */
3323 if (buf[i] != '"')
3324 break;
3325 continue;
3327 if (buf[i] == '\\' && dot)
3328 i++;
3329 else if (buf[i] == '"' && dot) {
3330 for (i++; isspace(buf[i]); i++)
3331 ; /* do_nothing */
3332 break;
3334 if (buf[i] != name[j++])
3335 break;
3337 if (buf[i] == ']' && name[j] == 0) {
3339 * We match, now just find the right length offset by
3340 * gobbling up any whitespace after it, as well
3342 i++;
3343 for (; buf[i] && isspace(buf[i]); i++)
3344 ; /* do nothing */
3345 return i;
3347 return 0;
3350 static int section_name_is_ok(const char *name)
3352 /* Empty section names are bogus. */
3353 if (!*name)
3354 return 0;
3357 * Before a dot, we must be alphanumeric or dash. After the first dot,
3358 * anything goes, so we can stop checking.
3360 for (; *name && *name != '.'; name++)
3361 if (*name != '-' && !isalnum(*name))
3362 return 0;
3363 return 1;
3366 /* if new_name == NULL, the section is removed instead */
3367 static int git_config_copy_or_rename_section_in_file(const char *config_filename,
3368 const char *old_name,
3369 const char *new_name, int copy)
3371 int ret = 0, remove = 0;
3372 char *filename_buf = NULL;
3373 struct lock_file lock = LOCK_INIT;
3374 int out_fd;
3375 char buf[1024];
3376 FILE *config_file = NULL;
3377 struct stat st;
3378 struct strbuf copystr = STRBUF_INIT;
3379 struct config_store_data store;
3381 memset(&store, 0, sizeof(store));
3383 if (new_name && !section_name_is_ok(new_name)) {
3384 ret = error(_("invalid section name: %s"), new_name);
3385 goto out_no_rollback;
3388 if (!config_filename)
3389 config_filename = filename_buf = git_pathdup("config");
3391 out_fd = hold_lock_file_for_update(&lock, config_filename, 0);
3392 if (out_fd < 0) {
3393 ret = error(_("could not lock config file %s"), config_filename);
3394 goto out;
3397 if (!(config_file = fopen(config_filename, "rb"))) {
3398 ret = warn_on_fopen_errors(config_filename);
3399 if (ret)
3400 goto out;
3401 /* no config file means nothing to rename, no error */
3402 goto commit_and_out;
3405 if (fstat(fileno(config_file), &st) == -1) {
3406 ret = error_errno(_("fstat on %s failed"), config_filename);
3407 goto out;
3410 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3411 ret = error_errno(_("chmod on %s failed"),
3412 get_lock_file_path(&lock));
3413 goto out;
3416 while (fgets(buf, sizeof(buf), config_file)) {
3417 unsigned i;
3418 int length;
3419 int is_section = 0;
3420 char *output = buf;
3421 for (i = 0; buf[i] && isspace(buf[i]); i++)
3422 ; /* do nothing */
3423 if (buf[i] == '[') {
3424 /* it's a section */
3425 int offset;
3426 is_section = 1;
3429 * When encountering a new section under -c we
3430 * need to flush out any section we're already
3431 * coping and begin anew. There might be
3432 * multiple [branch "$name"] sections.
3434 if (copystr.len > 0) {
3435 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3436 ret = write_error(get_lock_file_path(&lock));
3437 goto out;
3439 strbuf_reset(&copystr);
3442 offset = section_name_match(&buf[i], old_name);
3443 if (offset > 0) {
3444 ret++;
3445 if (new_name == NULL) {
3446 remove = 1;
3447 continue;
3449 store.baselen = strlen(new_name);
3450 if (!copy) {
3451 if (write_section(out_fd, new_name, &store) < 0) {
3452 ret = write_error(get_lock_file_path(&lock));
3453 goto out;
3456 * We wrote out the new section, with
3457 * a newline, now skip the old
3458 * section's length
3460 output += offset + i;
3461 if (strlen(output) > 0) {
3463 * More content means there's
3464 * a declaration to put on the
3465 * next line; indent with a
3466 * tab
3468 output -= 1;
3469 output[0] = '\t';
3471 } else {
3472 copystr = store_create_section(new_name, &store);
3475 remove = 0;
3477 if (remove)
3478 continue;
3479 length = strlen(output);
3481 if (!is_section && copystr.len > 0) {
3482 strbuf_add(&copystr, output, length);
3485 if (write_in_full(out_fd, output, length) < 0) {
3486 ret = write_error(get_lock_file_path(&lock));
3487 goto out;
3492 * Copy a trailing section at the end of the config, won't be
3493 * flushed by the usual "flush because we have a new section
3494 * logic in the loop above.
3496 if (copystr.len > 0) {
3497 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3498 ret = write_error(get_lock_file_path(&lock));
3499 goto out;
3501 strbuf_reset(&copystr);
3504 fclose(config_file);
3505 config_file = NULL;
3506 commit_and_out:
3507 if (commit_lock_file(&lock) < 0)
3508 ret = error_errno(_("could not write config file %s"),
3509 config_filename);
3510 out:
3511 if (config_file)
3512 fclose(config_file);
3513 rollback_lock_file(&lock);
3514 out_no_rollback:
3515 free(filename_buf);
3516 config_store_data_clear(&store);
3517 return ret;
3520 int git_config_rename_section_in_file(const char *config_filename,
3521 const char *old_name, const char *new_name)
3523 return git_config_copy_or_rename_section_in_file(config_filename,
3524 old_name, new_name, 0);
3527 int git_config_rename_section(const char *old_name, const char *new_name)
3529 return git_config_rename_section_in_file(NULL, old_name, new_name);
3532 int git_config_copy_section_in_file(const char *config_filename,
3533 const char *old_name, const char *new_name)
3535 return git_config_copy_or_rename_section_in_file(config_filename,
3536 old_name, new_name, 1);
3539 int git_config_copy_section(const char *old_name, const char *new_name)
3541 return git_config_copy_section_in_file(NULL, old_name, new_name);
3545 * Call this to report error for your variable that should not
3546 * get a boolean value (i.e. "[my] var" means "true").
3548 #undef config_error_nonbool
3549 int config_error_nonbool(const char *var)
3551 return error(_("missing value for '%s'"), var);
3554 int parse_config_key(const char *var,
3555 const char *section,
3556 const char **subsection, size_t *subsection_len,
3557 const char **key)
3559 const char *dot;
3561 /* Does it start with "section." ? */
3562 if (!skip_prefix(var, section, &var) || *var != '.')
3563 return -1;
3566 * Find the key; we don't know yet if we have a subsection, but we must
3567 * parse backwards from the end, since the subsection may have dots in
3568 * it, too.
3570 dot = strrchr(var, '.');
3571 *key = dot + 1;
3573 /* Did we have a subsection at all? */
3574 if (dot == var) {
3575 if (subsection) {
3576 *subsection = NULL;
3577 *subsection_len = 0;
3580 else {
3581 if (!subsection)
3582 return -1;
3583 *subsection = var + 1;
3584 *subsection_len = dot - *subsection;
3587 return 0;
3590 const char *current_config_origin_type(void)
3592 int type;
3593 if (current_config_kvi)
3594 type = current_config_kvi->origin_type;
3595 else if(cf)
3596 type = cf->origin_type;
3597 else
3598 BUG("current_config_origin_type called outside config callback");
3600 switch (type) {
3601 case CONFIG_ORIGIN_BLOB:
3602 return "blob";
3603 case CONFIG_ORIGIN_FILE:
3604 return "file";
3605 case CONFIG_ORIGIN_STDIN:
3606 return "standard input";
3607 case CONFIG_ORIGIN_SUBMODULE_BLOB:
3608 return "submodule-blob";
3609 case CONFIG_ORIGIN_CMDLINE:
3610 return "command line";
3611 default:
3612 BUG("unknown config origin type");
3616 const char *config_scope_name(enum config_scope scope)
3618 switch (scope) {
3619 case CONFIG_SCOPE_SYSTEM:
3620 return "system";
3621 case CONFIG_SCOPE_GLOBAL:
3622 return "global";
3623 case CONFIG_SCOPE_LOCAL:
3624 return "local";
3625 case CONFIG_SCOPE_WORKTREE:
3626 return "worktree";
3627 case CONFIG_SCOPE_COMMAND:
3628 return "command";
3629 case CONFIG_SCOPE_SUBMODULE:
3630 return "submodule";
3631 default:
3632 return "unknown";
3636 const char *current_config_name(void)
3638 const char *name;
3639 if (current_config_kvi)
3640 name = current_config_kvi->filename;
3641 else if (cf)
3642 name = cf->name;
3643 else
3644 BUG("current_config_name called outside config callback");
3645 return name ? name : "";
3648 enum config_scope current_config_scope(void)
3650 if (current_config_kvi)
3651 return current_config_kvi->scope;
3652 else
3653 return current_parsing_scope;
3656 int current_config_line(void)
3658 if (current_config_kvi)
3659 return current_config_kvi->linenr;
3660 else
3661 return cf->linenr;
3664 int lookup_config(const char **mapping, int nr_mapping, const char *var)
3666 int i;
3668 for (i = 0; i < nr_mapping; i++) {
3669 const char *name = mapping[i];
3671 if (name && !strcasecmp(var, name))
3672 return i;
3674 return -1;