Merge branch 'mt/pkt-line-comment-tweak' into maint
[git/debian.git] / config.c
blob9b0e9c93285fb33a69ab3ee0b20ae95ad2e202e1
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 "date.h"
10 #include "branch.h"
11 #include "config.h"
12 #include "environment.h"
13 #include "repository.h"
14 #include "lockfile.h"
15 #include "exec-cmd.h"
16 #include "strbuf.h"
17 #include "quote.h"
18 #include "hashmap.h"
19 #include "string-list.h"
20 #include "object-store.h"
21 #include "utf8.h"
22 #include "dir.h"
23 #include "color.h"
24 #include "refs.h"
25 #include "worktree.h"
27 struct config_source {
28 struct config_source *prev;
29 union {
30 FILE *file;
31 struct config_buf {
32 const char *buf;
33 size_t len;
34 size_t pos;
35 } buf;
36 } u;
37 enum config_origin_type origin_type;
38 const char *name;
39 const char *path;
40 enum config_error_action default_error_action;
41 int linenr;
42 int eof;
43 size_t total_len;
44 struct strbuf value;
45 struct strbuf var;
46 unsigned subsection_case_sensitive : 1;
48 int (*do_fgetc)(struct config_source *c);
49 int (*do_ungetc)(int c, struct config_source *conf);
50 long (*do_ftell)(struct config_source *c);
54 * These variables record the "current" config source, which
55 * can be accessed by parsing callbacks.
57 * The "cf" variable will be non-NULL only when we are actually parsing a real
58 * config source (file, blob, cmdline, etc).
60 * The "current_config_kvi" variable will be non-NULL only when we are feeding
61 * cached config from a configset into a callback.
63 * They should generally never be non-NULL at the same time. If they are both
64 * NULL, then we aren't parsing anything (and depending on the function looking
65 * at the variables, it's either a bug for it to be called in the first place,
66 * or it's a function which can be reused for non-config purposes, and should
67 * fall back to some sane behavior).
69 static struct config_source *cf;
70 static struct key_value_info *current_config_kvi;
73 * Similar to the variables above, this gives access to the "scope" of the
74 * current value (repo, global, etc). For cached values, it can be found via
75 * the current_config_kvi as above. During parsing, the current value can be
76 * found in this variable. It's not part of "cf" because it transcends a single
77 * file (i.e., a file included from .git/config is still in "repo" scope).
79 static enum config_scope current_parsing_scope;
81 static int pack_compression_seen;
82 static int zlib_compression_seen;
84 static int config_file_fgetc(struct config_source *conf)
86 return getc_unlocked(conf->u.file);
89 static int config_file_ungetc(int c, struct config_source *conf)
91 return ungetc(c, conf->u.file);
94 static long config_file_ftell(struct config_source *conf)
96 return ftell(conf->u.file);
100 static int config_buf_fgetc(struct config_source *conf)
102 if (conf->u.buf.pos < conf->u.buf.len)
103 return conf->u.buf.buf[conf->u.buf.pos++];
105 return EOF;
108 static int config_buf_ungetc(int c, struct config_source *conf)
110 if (conf->u.buf.pos > 0) {
111 conf->u.buf.pos--;
112 if (conf->u.buf.buf[conf->u.buf.pos] != c)
113 BUG("config_buf can only ungetc the same character");
114 return c;
117 return EOF;
120 static long config_buf_ftell(struct config_source *conf)
122 return conf->u.buf.pos;
125 struct config_include_data {
126 int depth;
127 config_fn_t fn;
128 void *data;
129 const struct config_options *opts;
130 struct git_config_source *config_source;
133 * All remote URLs discovered when reading all config files.
135 struct string_list *remote_urls;
137 #define CONFIG_INCLUDE_INIT { 0 }
139 static int git_config_include(const char *var, const char *value, void *data);
141 #define MAX_INCLUDE_DEPTH 10
142 static const char include_depth_advice[] = N_(
143 "exceeded maximum include depth (%d) while including\n"
144 " %s\n"
145 "from\n"
146 " %s\n"
147 "This might be due to circular includes.");
148 static int handle_path_include(const char *path, struct config_include_data *inc)
150 int ret = 0;
151 struct strbuf buf = STRBUF_INIT;
152 char *expanded;
154 if (!path)
155 return config_error_nonbool("include.path");
157 expanded = interpolate_path(path, 0);
158 if (!expanded)
159 return error(_("could not expand include path '%s'"), path);
160 path = expanded;
163 * Use an absolute path as-is, but interpret relative paths
164 * based on the including config file.
166 if (!is_absolute_path(path)) {
167 char *slash;
169 if (!cf || !cf->path) {
170 ret = error(_("relative config includes must come from files"));
171 goto cleanup;
174 slash = find_last_dir_sep(cf->path);
175 if (slash)
176 strbuf_add(&buf, cf->path, slash - cf->path + 1);
177 strbuf_addstr(&buf, path);
178 path = buf.buf;
181 if (!access_or_die(path, R_OK, 0)) {
182 if (++inc->depth > MAX_INCLUDE_DEPTH)
183 die(_(include_depth_advice), MAX_INCLUDE_DEPTH, path,
184 !cf ? "<unknown>" :
185 cf->name ? cf->name :
186 "the command line");
187 ret = git_config_from_file(git_config_include, path, inc);
188 inc->depth--;
190 cleanup:
191 strbuf_release(&buf);
192 free(expanded);
193 return ret;
196 static void add_trailing_starstar_for_dir(struct strbuf *pat)
198 if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
199 strbuf_addstr(pat, "**");
202 static int prepare_include_condition_pattern(struct strbuf *pat)
204 struct strbuf path = STRBUF_INIT;
205 char *expanded;
206 int prefix = 0;
208 expanded = interpolate_path(pat->buf, 1);
209 if (expanded) {
210 strbuf_reset(pat);
211 strbuf_addstr(pat, expanded);
212 free(expanded);
215 if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
216 const char *slash;
218 if (!cf || !cf->path)
219 return error(_("relative config include "
220 "conditionals must come from files"));
222 strbuf_realpath(&path, cf->path, 1);
223 slash = find_last_dir_sep(path.buf);
224 if (!slash)
225 BUG("how is this possible?");
226 strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
227 prefix = slash - path.buf + 1 /* slash */;
228 } else if (!is_absolute_path(pat->buf))
229 strbuf_insertstr(pat, 0, "**/");
231 add_trailing_starstar_for_dir(pat);
233 strbuf_release(&path);
234 return prefix;
237 static int include_by_gitdir(const struct config_options *opts,
238 const char *cond, size_t cond_len, int icase)
240 struct strbuf text = STRBUF_INIT;
241 struct strbuf pattern = STRBUF_INIT;
242 int ret = 0, prefix;
243 const char *git_dir;
244 int already_tried_absolute = 0;
246 if (opts->git_dir)
247 git_dir = opts->git_dir;
248 else
249 goto done;
251 strbuf_realpath(&text, git_dir, 1);
252 strbuf_add(&pattern, cond, cond_len);
253 prefix = prepare_include_condition_pattern(&pattern);
255 again:
256 if (prefix < 0)
257 goto done;
259 if (prefix > 0) {
261 * perform literal matching on the prefix part so that
262 * any wildcard character in it can't create side effects.
264 if (text.len < prefix)
265 goto done;
266 if (!icase && strncmp(pattern.buf, text.buf, prefix))
267 goto done;
268 if (icase && strncasecmp(pattern.buf, text.buf, prefix))
269 goto done;
272 ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
273 WM_PATHNAME | (icase ? WM_CASEFOLD : 0));
275 if (!ret && !already_tried_absolute) {
277 * We've tried e.g. matching gitdir:~/work, but if
278 * ~/work is a symlink to /mnt/storage/work
279 * strbuf_realpath() will expand it, so the rule won't
280 * match. Let's match against a
281 * strbuf_add_absolute_path() version of the path,
282 * which'll do the right thing
284 strbuf_reset(&text);
285 strbuf_add_absolute_path(&text, git_dir);
286 already_tried_absolute = 1;
287 goto again;
289 done:
290 strbuf_release(&pattern);
291 strbuf_release(&text);
292 return ret;
295 static int include_by_branch(const char *cond, size_t cond_len)
297 int flags;
298 int ret;
299 struct strbuf pattern = STRBUF_INIT;
300 const char *refname = !the_repository->gitdir ?
301 NULL : resolve_ref_unsafe("HEAD", 0, NULL, &flags);
302 const char *shortname;
304 if (!refname || !(flags & REF_ISSYMREF) ||
305 !skip_prefix(refname, "refs/heads/", &shortname))
306 return 0;
308 strbuf_add(&pattern, cond, cond_len);
309 add_trailing_starstar_for_dir(&pattern);
310 ret = !wildmatch(pattern.buf, shortname, WM_PATHNAME);
311 strbuf_release(&pattern);
312 return ret;
315 static int add_remote_url(const char *var, const char *value, void *data)
317 struct string_list *remote_urls = data;
318 const char *remote_name;
319 size_t remote_name_len;
320 const char *key;
322 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
323 &key) &&
324 remote_name &&
325 !strcmp(key, "url"))
326 string_list_append(remote_urls, value);
327 return 0;
330 static void populate_remote_urls(struct config_include_data *inc)
332 struct config_options opts;
334 struct config_source *store_cf = cf;
335 struct key_value_info *store_kvi = current_config_kvi;
336 enum config_scope store_scope = current_parsing_scope;
338 opts = *inc->opts;
339 opts.unconditional_remote_url = 1;
341 cf = NULL;
342 current_config_kvi = NULL;
343 current_parsing_scope = 0;
345 inc->remote_urls = xmalloc(sizeof(*inc->remote_urls));
346 string_list_init_dup(inc->remote_urls);
347 config_with_options(add_remote_url, inc->remote_urls, inc->config_source, &opts);
349 cf = store_cf;
350 current_config_kvi = store_kvi;
351 current_parsing_scope = store_scope;
354 static int forbid_remote_url(const char *var, const char *value, void *data)
356 const char *remote_name;
357 size_t remote_name_len;
358 const char *key;
360 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
361 &key) &&
362 remote_name &&
363 !strcmp(key, "url"))
364 die(_("remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"));
365 return 0;
368 static int at_least_one_url_matches_glob(const char *glob, int glob_len,
369 struct string_list *remote_urls)
371 struct strbuf pattern = STRBUF_INIT;
372 struct string_list_item *url_item;
373 int found = 0;
375 strbuf_add(&pattern, glob, glob_len);
376 for_each_string_list_item(url_item, remote_urls) {
377 if (!wildmatch(pattern.buf, url_item->string, WM_PATHNAME)) {
378 found = 1;
379 break;
382 strbuf_release(&pattern);
383 return found;
386 static int include_by_remote_url(struct config_include_data *inc,
387 const char *cond, size_t cond_len)
389 if (inc->opts->unconditional_remote_url)
390 return 1;
391 if (!inc->remote_urls)
392 populate_remote_urls(inc);
393 return at_least_one_url_matches_glob(cond, cond_len,
394 inc->remote_urls);
397 static int include_condition_is_true(struct config_include_data *inc,
398 const char *cond, size_t cond_len)
400 const struct config_options *opts = inc->opts;
402 if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
403 return include_by_gitdir(opts, cond, cond_len, 0);
404 else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
405 return include_by_gitdir(opts, cond, cond_len, 1);
406 else if (skip_prefix_mem(cond, cond_len, "onbranch:", &cond, &cond_len))
407 return include_by_branch(cond, cond_len);
408 else if (skip_prefix_mem(cond, cond_len, "hasconfig:remote.*.url:", &cond,
409 &cond_len))
410 return include_by_remote_url(inc, cond, cond_len);
412 /* unknown conditionals are always false */
413 return 0;
416 static int git_config_include(const char *var, const char *value, void *data)
418 struct config_include_data *inc = data;
419 const char *cond, *key;
420 size_t cond_len;
421 int ret;
424 * Pass along all values, including "include" directives; this makes it
425 * possible to query information on the includes themselves.
427 ret = inc->fn(var, value, inc->data);
428 if (ret < 0)
429 return ret;
431 if (!strcmp(var, "include.path"))
432 ret = handle_path_include(value, inc);
434 if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
435 cond && include_condition_is_true(inc, cond, cond_len) &&
436 !strcmp(key, "path")) {
437 config_fn_t old_fn = inc->fn;
439 if (inc->opts->unconditional_remote_url)
440 inc->fn = forbid_remote_url;
441 ret = handle_path_include(value, inc);
442 inc->fn = old_fn;
445 return ret;
448 static void git_config_push_split_parameter(const char *key, const char *value)
450 struct strbuf env = STRBUF_INIT;
451 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
452 if (old && *old) {
453 strbuf_addstr(&env, old);
454 strbuf_addch(&env, ' ');
456 sq_quote_buf(&env, key);
457 strbuf_addch(&env, '=');
458 if (value)
459 sq_quote_buf(&env, value);
460 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
461 strbuf_release(&env);
464 void git_config_push_parameter(const char *text)
466 const char *value;
469 * When we see:
471 * section.subsection=with=equals.key=value
473 * we cannot tell if it means:
475 * [section "subsection=with=equals"]
476 * key = value
478 * or:
480 * [section]
481 * subsection = with=equals.key=value
483 * We parse left-to-right for the first "=", meaning we'll prefer to
484 * keep the value intact over the subsection. This is historical, but
485 * also sensible since values are more likely to contain odd or
486 * untrusted input than a section name.
488 * A missing equals is explicitly allowed (as a bool-only entry).
490 value = strchr(text, '=');
491 if (value) {
492 char *key = xmemdupz(text, value - text);
493 git_config_push_split_parameter(key, value + 1);
494 free(key);
495 } else {
496 git_config_push_split_parameter(text, NULL);
500 void git_config_push_env(const char *spec)
502 char *key;
503 const char *env_name;
504 const char *env_value;
506 env_name = strrchr(spec, '=');
507 if (!env_name)
508 die(_("invalid config format: %s"), spec);
509 key = xmemdupz(spec, env_name - spec);
510 env_name++;
511 if (!*env_name)
512 die(_("missing environment variable name for configuration '%.*s'"),
513 (int)(env_name - spec - 1), spec);
515 env_value = getenv(env_name);
516 if (!env_value)
517 die(_("missing environment variable '%s' for configuration '%.*s'"),
518 env_name, (int)(env_name - spec - 1), spec);
520 git_config_push_split_parameter(key, env_value);
521 free(key);
524 static inline int iskeychar(int c)
526 return isalnum(c) || c == '-';
530 * Auxiliary function to sanity-check and split the key into the section
531 * identifier and variable name.
533 * Returns 0 on success, -1 when there is an invalid character in the key and
534 * -2 if there is no section name in the key.
536 * store_key - pointer to char* which will hold a copy of the key with
537 * lowercase section and variable name
538 * baselen - pointer to size_t which will hold the length of the
539 * section + subsection part, can be NULL
541 int git_config_parse_key(const char *key, char **store_key, size_t *baselen_)
543 size_t i, baselen;
544 int dot;
545 const char *last_dot = strrchr(key, '.');
548 * Since "key" actually contains the section name and the real
549 * key name separated by a dot, we have to know where the dot is.
552 if (last_dot == NULL || last_dot == key) {
553 error(_("key does not contain a section: %s"), key);
554 return -CONFIG_NO_SECTION_OR_NAME;
557 if (!last_dot[1]) {
558 error(_("key does not contain variable name: %s"), key);
559 return -CONFIG_NO_SECTION_OR_NAME;
562 baselen = last_dot - key;
563 if (baselen_)
564 *baselen_ = baselen;
567 * Validate the key and while at it, lower case it for matching.
569 *store_key = xmallocz(strlen(key));
571 dot = 0;
572 for (i = 0; key[i]; i++) {
573 unsigned char c = key[i];
574 if (c == '.')
575 dot = 1;
576 /* Leave the extended basename untouched.. */
577 if (!dot || i > baselen) {
578 if (!iskeychar(c) ||
579 (i == baselen + 1 && !isalpha(c))) {
580 error(_("invalid key: %s"), key);
581 goto out_free_ret_1;
583 c = tolower(c);
584 } else if (c == '\n') {
585 error(_("invalid key (newline): %s"), key);
586 goto out_free_ret_1;
588 (*store_key)[i] = c;
591 return 0;
593 out_free_ret_1:
594 FREE_AND_NULL(*store_key);
595 return -CONFIG_INVALID_KEY;
598 static int config_parse_pair(const char *key, const char *value,
599 config_fn_t fn, void *data)
601 char *canonical_name;
602 int ret;
604 if (!strlen(key))
605 return error(_("empty config key"));
606 if (git_config_parse_key(key, &canonical_name, NULL))
607 return -1;
609 ret = (fn(canonical_name, value, data) < 0) ? -1 : 0;
610 free(canonical_name);
611 return ret;
614 int git_config_parse_parameter(const char *text,
615 config_fn_t fn, void *data)
617 const char *value;
618 struct strbuf **pair;
619 int ret;
621 pair = strbuf_split_str(text, '=', 2);
622 if (!pair[0])
623 return error(_("bogus config parameter: %s"), text);
625 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
626 strbuf_setlen(pair[0], pair[0]->len - 1);
627 value = pair[1] ? pair[1]->buf : "";
628 } else {
629 value = NULL;
632 strbuf_trim(pair[0]);
633 if (!pair[0]->len) {
634 strbuf_list_free(pair);
635 return error(_("bogus config parameter: %s"), text);
638 ret = config_parse_pair(pair[0]->buf, value, fn, data);
639 strbuf_list_free(pair);
640 return ret;
643 static int parse_config_env_list(char *env, config_fn_t fn, void *data)
645 char *cur = env;
646 while (cur && *cur) {
647 const char *key = sq_dequote_step(cur, &cur);
648 if (!key)
649 return error(_("bogus format in %s"),
650 CONFIG_DATA_ENVIRONMENT);
652 if (!cur || isspace(*cur)) {
653 /* old-style 'key=value' */
654 if (git_config_parse_parameter(key, fn, data) < 0)
655 return -1;
657 else if (*cur == '=') {
658 /* new-style 'key'='value' */
659 const char *value;
661 cur++;
662 if (*cur == '\'') {
663 /* quoted value */
664 value = sq_dequote_step(cur, &cur);
665 if (!value || (cur && !isspace(*cur))) {
666 return error(_("bogus format in %s"),
667 CONFIG_DATA_ENVIRONMENT);
669 } else if (!*cur || isspace(*cur)) {
670 /* implicit bool: 'key'= */
671 value = NULL;
672 } else {
673 return error(_("bogus format in %s"),
674 CONFIG_DATA_ENVIRONMENT);
677 if (config_parse_pair(key, value, fn, data) < 0)
678 return -1;
680 else {
681 /* unknown format */
682 return error(_("bogus format in %s"),
683 CONFIG_DATA_ENVIRONMENT);
686 if (cur) {
687 while (isspace(*cur))
688 cur++;
691 return 0;
694 int git_config_from_parameters(config_fn_t fn, void *data)
696 const char *env;
697 struct strbuf envvar = STRBUF_INIT;
698 struct strvec to_free = STRVEC_INIT;
699 int ret = 0;
700 char *envw = NULL;
701 struct config_source source;
703 memset(&source, 0, sizeof(source));
704 source.prev = cf;
705 source.origin_type = CONFIG_ORIGIN_CMDLINE;
706 cf = &source;
708 env = getenv(CONFIG_COUNT_ENVIRONMENT);
709 if (env) {
710 unsigned long count;
711 char *endp;
712 int i;
714 count = strtoul(env, &endp, 10);
715 if (*endp) {
716 ret = error(_("bogus count in %s"), CONFIG_COUNT_ENVIRONMENT);
717 goto out;
719 if (count > INT_MAX) {
720 ret = error(_("too many entries in %s"), CONFIG_COUNT_ENVIRONMENT);
721 goto out;
724 for (i = 0; i < count; i++) {
725 const char *key, *value;
727 strbuf_addf(&envvar, "GIT_CONFIG_KEY_%d", i);
728 key = getenv_safe(&to_free, envvar.buf);
729 if (!key) {
730 ret = error(_("missing config key %s"), envvar.buf);
731 goto out;
733 strbuf_reset(&envvar);
735 strbuf_addf(&envvar, "GIT_CONFIG_VALUE_%d", i);
736 value = getenv_safe(&to_free, envvar.buf);
737 if (!value) {
738 ret = error(_("missing config value %s"), envvar.buf);
739 goto out;
741 strbuf_reset(&envvar);
743 if (config_parse_pair(key, value, fn, data) < 0) {
744 ret = -1;
745 goto out;
750 env = getenv(CONFIG_DATA_ENVIRONMENT);
751 if (env) {
752 /* sq_dequote will write over it */
753 envw = xstrdup(env);
754 if (parse_config_env_list(envw, fn, data) < 0) {
755 ret = -1;
756 goto out;
760 out:
761 strbuf_release(&envvar);
762 strvec_clear(&to_free);
763 free(envw);
764 cf = source.prev;
765 return ret;
768 static int get_next_char(void)
770 int c = cf->do_fgetc(cf);
772 if (c == '\r') {
773 /* DOS like systems */
774 c = cf->do_fgetc(cf);
775 if (c != '\n') {
776 if (c != EOF)
777 cf->do_ungetc(c, cf);
778 c = '\r';
782 if (c != EOF && ++cf->total_len > INT_MAX) {
784 * This is an absurdly long config file; refuse to parse
785 * further in order to protect downstream code from integer
786 * overflows. Note that we can't return an error specifically,
787 * but we can mark EOF and put trash in the return value,
788 * which will trigger a parse error.
790 cf->eof = 1;
791 return 0;
794 if (c == '\n')
795 cf->linenr++;
796 if (c == EOF) {
797 cf->eof = 1;
798 cf->linenr++;
799 c = '\n';
801 return c;
804 static char *parse_value(void)
806 int quote = 0, comment = 0, space = 0;
808 strbuf_reset(&cf->value);
809 for (;;) {
810 int c = get_next_char();
811 if (c == '\n') {
812 if (quote) {
813 cf->linenr--;
814 return NULL;
816 return cf->value.buf;
818 if (comment)
819 continue;
820 if (isspace(c) && !quote) {
821 if (cf->value.len)
822 space++;
823 continue;
825 if (!quote) {
826 if (c == ';' || c == '#') {
827 comment = 1;
828 continue;
831 for (; space; space--)
832 strbuf_addch(&cf->value, ' ');
833 if (c == '\\') {
834 c = get_next_char();
835 switch (c) {
836 case '\n':
837 continue;
838 case 't':
839 c = '\t';
840 break;
841 case 'b':
842 c = '\b';
843 break;
844 case 'n':
845 c = '\n';
846 break;
847 /* Some characters escape as themselves */
848 case '\\': case '"':
849 break;
850 /* Reject unknown escape sequences */
851 default:
852 return NULL;
854 strbuf_addch(&cf->value, c);
855 continue;
857 if (c == '"') {
858 quote = 1-quote;
859 continue;
861 strbuf_addch(&cf->value, c);
865 static int get_value(config_fn_t fn, void *data, struct strbuf *name)
867 int c;
868 char *value;
869 int ret;
871 /* Get the full name */
872 for (;;) {
873 c = get_next_char();
874 if (cf->eof)
875 break;
876 if (!iskeychar(c))
877 break;
878 strbuf_addch(name, tolower(c));
881 while (c == ' ' || c == '\t')
882 c = get_next_char();
884 value = NULL;
885 if (c != '\n') {
886 if (c != '=')
887 return -1;
888 value = parse_value();
889 if (!value)
890 return -1;
893 * We already consumed the \n, but we need linenr to point to
894 * the line we just parsed during the call to fn to get
895 * accurate line number in error messages.
897 cf->linenr--;
898 ret = fn(name->buf, value, data);
899 if (ret >= 0)
900 cf->linenr++;
901 return ret;
904 static int get_extended_base_var(struct strbuf *name, int c)
906 cf->subsection_case_sensitive = 0;
907 do {
908 if (c == '\n')
909 goto error_incomplete_line;
910 c = get_next_char();
911 } while (isspace(c));
913 /* We require the format to be '[base "extension"]' */
914 if (c != '"')
915 return -1;
916 strbuf_addch(name, '.');
918 for (;;) {
919 int c = get_next_char();
920 if (c == '\n')
921 goto error_incomplete_line;
922 if (c == '"')
923 break;
924 if (c == '\\') {
925 c = get_next_char();
926 if (c == '\n')
927 goto error_incomplete_line;
929 strbuf_addch(name, c);
932 /* Final ']' */
933 if (get_next_char() != ']')
934 return -1;
935 return 0;
936 error_incomplete_line:
937 cf->linenr--;
938 return -1;
941 static int get_base_var(struct strbuf *name)
943 cf->subsection_case_sensitive = 1;
944 for (;;) {
945 int c = get_next_char();
946 if (cf->eof)
947 return -1;
948 if (c == ']')
949 return 0;
950 if (isspace(c))
951 return get_extended_base_var(name, c);
952 if (!iskeychar(c) && c != '.')
953 return -1;
954 strbuf_addch(name, tolower(c));
958 struct parse_event_data {
959 enum config_event_t previous_type;
960 size_t previous_offset;
961 const struct config_options *opts;
964 static int do_event(enum config_event_t type, struct parse_event_data *data)
966 size_t offset;
968 if (!data->opts || !data->opts->event_fn)
969 return 0;
971 if (type == CONFIG_EVENT_WHITESPACE &&
972 data->previous_type == type)
973 return 0;
975 offset = cf->do_ftell(cf);
977 * At EOF, the parser always "inserts" an extra '\n', therefore
978 * the end offset of the event is the current file position, otherwise
979 * we will already have advanced to the next event.
981 if (type != CONFIG_EVENT_EOF)
982 offset--;
984 if (data->previous_type != CONFIG_EVENT_EOF &&
985 data->opts->event_fn(data->previous_type, data->previous_offset,
986 offset, data->opts->event_fn_data) < 0)
987 return -1;
989 data->previous_type = type;
990 data->previous_offset = offset;
992 return 0;
995 static int git_parse_source(config_fn_t fn, void *data,
996 const struct config_options *opts)
998 int comment = 0;
999 size_t baselen = 0;
1000 struct strbuf *var = &cf->var;
1001 int error_return = 0;
1002 char *error_msg = NULL;
1004 /* U+FEFF Byte Order Mark in UTF8 */
1005 const char *bomptr = utf8_bom;
1007 /* For the parser event callback */
1008 struct parse_event_data event_data = {
1009 CONFIG_EVENT_EOF, 0, opts
1012 for (;;) {
1013 int c;
1015 c = get_next_char();
1016 if (bomptr && *bomptr) {
1017 /* We are at the file beginning; skip UTF8-encoded BOM
1018 * if present. Sane editors won't put this in on their
1019 * own, but e.g. Windows Notepad will do it happily. */
1020 if (c == (*bomptr & 0377)) {
1021 bomptr++;
1022 continue;
1023 } else {
1024 /* Do not tolerate partial BOM. */
1025 if (bomptr != utf8_bom)
1026 break;
1027 /* No BOM at file beginning. Cool. */
1028 bomptr = NULL;
1031 if (c == '\n') {
1032 if (cf->eof) {
1033 if (do_event(CONFIG_EVENT_EOF, &event_data) < 0)
1034 return -1;
1035 return 0;
1037 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1038 return -1;
1039 comment = 0;
1040 continue;
1042 if (comment)
1043 continue;
1044 if (isspace(c)) {
1045 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1046 return -1;
1047 continue;
1049 if (c == '#' || c == ';') {
1050 if (do_event(CONFIG_EVENT_COMMENT, &event_data) < 0)
1051 return -1;
1052 comment = 1;
1053 continue;
1055 if (c == '[') {
1056 if (do_event(CONFIG_EVENT_SECTION, &event_data) < 0)
1057 return -1;
1059 /* Reset prior to determining a new stem */
1060 strbuf_reset(var);
1061 if (get_base_var(var) < 0 || var->len < 1)
1062 break;
1063 strbuf_addch(var, '.');
1064 baselen = var->len;
1065 continue;
1067 if (!isalpha(c))
1068 break;
1070 if (do_event(CONFIG_EVENT_ENTRY, &event_data) < 0)
1071 return -1;
1074 * Truncate the var name back to the section header
1075 * stem prior to grabbing the suffix part of the name
1076 * and the value.
1078 strbuf_setlen(var, baselen);
1079 strbuf_addch(var, tolower(c));
1080 if (get_value(fn, data, var) < 0)
1081 break;
1084 if (do_event(CONFIG_EVENT_ERROR, &event_data) < 0)
1085 return -1;
1087 switch (cf->origin_type) {
1088 case CONFIG_ORIGIN_BLOB:
1089 error_msg = xstrfmt(_("bad config line %d in blob %s"),
1090 cf->linenr, cf->name);
1091 break;
1092 case CONFIG_ORIGIN_FILE:
1093 error_msg = xstrfmt(_("bad config line %d in file %s"),
1094 cf->linenr, cf->name);
1095 break;
1096 case CONFIG_ORIGIN_STDIN:
1097 error_msg = xstrfmt(_("bad config line %d in standard input"),
1098 cf->linenr);
1099 break;
1100 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1101 error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
1102 cf->linenr, cf->name);
1103 break;
1104 case CONFIG_ORIGIN_CMDLINE:
1105 error_msg = xstrfmt(_("bad config line %d in command line %s"),
1106 cf->linenr, cf->name);
1107 break;
1108 default:
1109 error_msg = xstrfmt(_("bad config line %d in %s"),
1110 cf->linenr, cf->name);
1113 switch (opts && opts->error_action ?
1114 opts->error_action :
1115 cf->default_error_action) {
1116 case CONFIG_ERROR_DIE:
1117 die("%s", error_msg);
1118 break;
1119 case CONFIG_ERROR_ERROR:
1120 error_return = error("%s", error_msg);
1121 break;
1122 case CONFIG_ERROR_SILENT:
1123 error_return = -1;
1124 break;
1125 case CONFIG_ERROR_UNSET:
1126 BUG("config error action unset");
1129 free(error_msg);
1130 return error_return;
1133 static uintmax_t get_unit_factor(const char *end)
1135 if (!*end)
1136 return 1;
1137 else if (!strcasecmp(end, "k"))
1138 return 1024;
1139 else if (!strcasecmp(end, "m"))
1140 return 1024 * 1024;
1141 else if (!strcasecmp(end, "g"))
1142 return 1024 * 1024 * 1024;
1143 return 0;
1146 static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
1148 if (value && *value) {
1149 char *end;
1150 intmax_t val;
1151 uintmax_t uval;
1152 uintmax_t factor;
1154 errno = 0;
1155 val = strtoimax(value, &end, 0);
1156 if (errno == ERANGE)
1157 return 0;
1158 factor = get_unit_factor(end);
1159 if (!factor) {
1160 errno = EINVAL;
1161 return 0;
1163 uval = val < 0 ? -val : val;
1164 if (unsigned_mult_overflows(factor, uval) ||
1165 factor * uval > max) {
1166 errno = ERANGE;
1167 return 0;
1169 val *= factor;
1170 *ret = val;
1171 return 1;
1173 errno = EINVAL;
1174 return 0;
1177 static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
1179 if (value && *value) {
1180 char *end;
1181 uintmax_t val;
1182 uintmax_t factor;
1184 errno = 0;
1185 val = strtoumax(value, &end, 0);
1186 if (errno == ERANGE)
1187 return 0;
1188 factor = get_unit_factor(end);
1189 if (!factor) {
1190 errno = EINVAL;
1191 return 0;
1193 if (unsigned_mult_overflows(factor, val) ||
1194 factor * val > max) {
1195 errno = ERANGE;
1196 return 0;
1198 val *= factor;
1199 *ret = val;
1200 return 1;
1202 errno = EINVAL;
1203 return 0;
1206 static int git_parse_int(const char *value, int *ret)
1208 intmax_t tmp;
1209 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
1210 return 0;
1211 *ret = tmp;
1212 return 1;
1215 static int git_parse_int64(const char *value, int64_t *ret)
1217 intmax_t tmp;
1218 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
1219 return 0;
1220 *ret = tmp;
1221 return 1;
1224 int git_parse_ulong(const char *value, unsigned long *ret)
1226 uintmax_t tmp;
1227 if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
1228 return 0;
1229 *ret = tmp;
1230 return 1;
1233 int git_parse_ssize_t(const char *value, ssize_t *ret)
1235 intmax_t tmp;
1236 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(ssize_t)))
1237 return 0;
1238 *ret = tmp;
1239 return 1;
1242 NORETURN
1243 static void die_bad_number(const char *name, const char *value)
1245 const char *error_type = (errno == ERANGE) ?
1246 N_("out of range") : N_("invalid unit");
1247 const char *bad_numeric = N_("bad numeric config value '%s' for '%s': %s");
1249 if (!value)
1250 value = "";
1252 if (!(cf && cf->name))
1253 die(_(bad_numeric), value, name, _(error_type));
1255 switch (cf->origin_type) {
1256 case CONFIG_ORIGIN_BLOB:
1257 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
1258 value, name, cf->name, _(error_type));
1259 case CONFIG_ORIGIN_FILE:
1260 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
1261 value, name, cf->name, _(error_type));
1262 case CONFIG_ORIGIN_STDIN:
1263 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
1264 value, name, _(error_type));
1265 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1266 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
1267 value, name, cf->name, _(error_type));
1268 case CONFIG_ORIGIN_CMDLINE:
1269 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
1270 value, name, cf->name, _(error_type));
1271 default:
1272 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
1273 value, name, cf->name, _(error_type));
1277 int git_config_int(const char *name, const char *value)
1279 int ret;
1280 if (!git_parse_int(value, &ret))
1281 die_bad_number(name, value);
1282 return ret;
1285 int64_t git_config_int64(const char *name, const char *value)
1287 int64_t ret;
1288 if (!git_parse_int64(value, &ret))
1289 die_bad_number(name, value);
1290 return ret;
1293 unsigned long git_config_ulong(const char *name, const char *value)
1295 unsigned long ret;
1296 if (!git_parse_ulong(value, &ret))
1297 die_bad_number(name, value);
1298 return ret;
1301 ssize_t git_config_ssize_t(const char *name, const char *value)
1303 ssize_t ret;
1304 if (!git_parse_ssize_t(value, &ret))
1305 die_bad_number(name, value);
1306 return ret;
1309 static int git_parse_maybe_bool_text(const char *value)
1311 if (!value)
1312 return 1;
1313 if (!*value)
1314 return 0;
1315 if (!strcasecmp(value, "true")
1316 || !strcasecmp(value, "yes")
1317 || !strcasecmp(value, "on"))
1318 return 1;
1319 if (!strcasecmp(value, "false")
1320 || !strcasecmp(value, "no")
1321 || !strcasecmp(value, "off"))
1322 return 0;
1323 return -1;
1326 static const struct fsync_component_name {
1327 const char *name;
1328 enum fsync_component component_bits;
1329 } fsync_component_names[] = {
1330 { "loose-object", FSYNC_COMPONENT_LOOSE_OBJECT },
1331 { "pack", FSYNC_COMPONENT_PACK },
1332 { "pack-metadata", FSYNC_COMPONENT_PACK_METADATA },
1333 { "commit-graph", FSYNC_COMPONENT_COMMIT_GRAPH },
1334 { "index", FSYNC_COMPONENT_INDEX },
1335 { "objects", FSYNC_COMPONENTS_OBJECTS },
1336 { "reference", FSYNC_COMPONENT_REFERENCE },
1337 { "derived-metadata", FSYNC_COMPONENTS_DERIVED_METADATA },
1338 { "committed", FSYNC_COMPONENTS_COMMITTED },
1339 { "added", FSYNC_COMPONENTS_ADDED },
1340 { "all", FSYNC_COMPONENTS_ALL },
1343 static enum fsync_component parse_fsync_components(const char *var, const char *string)
1345 enum fsync_component current = FSYNC_COMPONENTS_PLATFORM_DEFAULT;
1346 enum fsync_component positive = 0, negative = 0;
1348 while (string) {
1349 int i;
1350 size_t len;
1351 const char *ep;
1352 int negated = 0;
1353 int found = 0;
1355 string = string + strspn(string, ", \t\n\r");
1356 ep = strchrnul(string, ',');
1357 len = ep - string;
1358 if (!strcmp(string, "none")) {
1359 current = FSYNC_COMPONENT_NONE;
1360 goto next_name;
1363 if (*string == '-') {
1364 negated = 1;
1365 string++;
1366 len--;
1367 if (!len)
1368 warning(_("invalid value for variable %s"), var);
1371 if (!len)
1372 break;
1374 for (i = 0; i < ARRAY_SIZE(fsync_component_names); ++i) {
1375 const struct fsync_component_name *n = &fsync_component_names[i];
1377 if (strncmp(n->name, string, len))
1378 continue;
1380 found = 1;
1381 if (negated)
1382 negative |= n->component_bits;
1383 else
1384 positive |= n->component_bits;
1387 if (!found) {
1388 char *component = xstrndup(string, len);
1389 warning(_("ignoring unknown core.fsync component '%s'"), component);
1390 free(component);
1393 next_name:
1394 string = ep;
1397 return (current & ~negative) | positive;
1400 int git_parse_maybe_bool(const char *value)
1402 int v = git_parse_maybe_bool_text(value);
1403 if (0 <= v)
1404 return v;
1405 if (git_parse_int(value, &v))
1406 return !!v;
1407 return -1;
1410 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
1412 int v = git_parse_maybe_bool_text(value);
1413 if (0 <= v) {
1414 *is_bool = 1;
1415 return v;
1417 *is_bool = 0;
1418 return git_config_int(name, value);
1421 int git_config_bool(const char *name, const char *value)
1423 int v = git_parse_maybe_bool(value);
1424 if (v < 0)
1425 die(_("bad boolean config value '%s' for '%s'"), value, name);
1426 return v;
1429 int git_config_string(const char **dest, const char *var, const char *value)
1431 if (!value)
1432 return config_error_nonbool(var);
1433 *dest = xstrdup(value);
1434 return 0;
1437 int git_config_pathname(const char **dest, const char *var, const char *value)
1439 if (!value)
1440 return config_error_nonbool(var);
1441 *dest = interpolate_path(value, 0);
1442 if (!*dest)
1443 die(_("failed to expand user dir in: '%s'"), value);
1444 return 0;
1447 int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1449 if (!value)
1450 return config_error_nonbool(var);
1451 if (parse_expiry_date(value, timestamp))
1452 return error(_("'%s' for '%s' is not a valid timestamp"),
1453 value, var);
1454 return 0;
1457 int git_config_color(char *dest, const char *var, const char *value)
1459 if (!value)
1460 return config_error_nonbool(var);
1461 if (color_parse(value, dest) < 0)
1462 return -1;
1463 return 0;
1466 static int git_default_core_config(const char *var, const char *value, void *cb)
1468 /* This needs a better name */
1469 if (!strcmp(var, "core.filemode")) {
1470 trust_executable_bit = git_config_bool(var, value);
1471 return 0;
1473 if (!strcmp(var, "core.trustctime")) {
1474 trust_ctime = git_config_bool(var, value);
1475 return 0;
1477 if (!strcmp(var, "core.checkstat")) {
1478 if (!strcasecmp(value, "default"))
1479 check_stat = 1;
1480 else if (!strcasecmp(value, "minimal"))
1481 check_stat = 0;
1484 if (!strcmp(var, "core.quotepath")) {
1485 quote_path_fully = git_config_bool(var, value);
1486 return 0;
1489 if (!strcmp(var, "core.symlinks")) {
1490 has_symlinks = git_config_bool(var, value);
1491 return 0;
1494 if (!strcmp(var, "core.ignorecase")) {
1495 ignore_case = git_config_bool(var, value);
1496 return 0;
1499 if (!strcmp(var, "core.attributesfile"))
1500 return git_config_pathname(&git_attributes_file, var, value);
1502 if (!strcmp(var, "core.hookspath"))
1503 return git_config_pathname(&git_hooks_path, var, value);
1505 if (!strcmp(var, "core.bare")) {
1506 is_bare_repository_cfg = git_config_bool(var, value);
1507 return 0;
1510 if (!strcmp(var, "core.ignorestat")) {
1511 assume_unchanged = git_config_bool(var, value);
1512 return 0;
1515 if (!strcmp(var, "core.prefersymlinkrefs")) {
1516 prefer_symlink_refs = git_config_bool(var, value);
1517 return 0;
1520 if (!strcmp(var, "core.logallrefupdates")) {
1521 if (value && !strcasecmp(value, "always"))
1522 log_all_ref_updates = LOG_REFS_ALWAYS;
1523 else if (git_config_bool(var, value))
1524 log_all_ref_updates = LOG_REFS_NORMAL;
1525 else
1526 log_all_ref_updates = LOG_REFS_NONE;
1527 return 0;
1530 if (!strcmp(var, "core.warnambiguousrefs")) {
1531 warn_ambiguous_refs = git_config_bool(var, value);
1532 return 0;
1535 if (!strcmp(var, "core.abbrev")) {
1536 if (!value)
1537 return config_error_nonbool(var);
1538 if (!strcasecmp(value, "auto"))
1539 default_abbrev = -1;
1540 else if (!git_parse_maybe_bool_text(value))
1541 default_abbrev = the_hash_algo->hexsz;
1542 else {
1543 int abbrev = git_config_int(var, value);
1544 if (abbrev < minimum_abbrev || abbrev > the_hash_algo->hexsz)
1545 return error(_("abbrev length out of range: %d"), abbrev);
1546 default_abbrev = abbrev;
1548 return 0;
1551 if (!strcmp(var, "core.disambiguate"))
1552 return set_disambiguate_hint_config(var, value);
1554 if (!strcmp(var, "core.loosecompression")) {
1555 int level = git_config_int(var, value);
1556 if (level == -1)
1557 level = Z_DEFAULT_COMPRESSION;
1558 else if (level < 0 || level > Z_BEST_COMPRESSION)
1559 die(_("bad zlib compression level %d"), level);
1560 zlib_compression_level = level;
1561 zlib_compression_seen = 1;
1562 return 0;
1565 if (!strcmp(var, "core.compression")) {
1566 int level = git_config_int(var, value);
1567 if (level == -1)
1568 level = Z_DEFAULT_COMPRESSION;
1569 else if (level < 0 || level > Z_BEST_COMPRESSION)
1570 die(_("bad zlib compression level %d"), level);
1571 if (!zlib_compression_seen)
1572 zlib_compression_level = level;
1573 if (!pack_compression_seen)
1574 pack_compression_level = level;
1575 return 0;
1578 if (!strcmp(var, "core.packedgitwindowsize")) {
1579 int pgsz_x2 = getpagesize() * 2;
1580 packed_git_window_size = git_config_ulong(var, value);
1582 /* This value must be multiple of (pagesize * 2) */
1583 packed_git_window_size /= pgsz_x2;
1584 if (packed_git_window_size < 1)
1585 packed_git_window_size = 1;
1586 packed_git_window_size *= pgsz_x2;
1587 return 0;
1590 if (!strcmp(var, "core.bigfilethreshold")) {
1591 big_file_threshold = git_config_ulong(var, value);
1592 return 0;
1595 if (!strcmp(var, "core.packedgitlimit")) {
1596 packed_git_limit = git_config_ulong(var, value);
1597 return 0;
1600 if (!strcmp(var, "core.deltabasecachelimit")) {
1601 delta_base_cache_limit = git_config_ulong(var, value);
1602 return 0;
1605 if (!strcmp(var, "core.autocrlf")) {
1606 if (value && !strcasecmp(value, "input")) {
1607 auto_crlf = AUTO_CRLF_INPUT;
1608 return 0;
1610 auto_crlf = git_config_bool(var, value);
1611 return 0;
1614 if (!strcmp(var, "core.safecrlf")) {
1615 int eol_rndtrp_die;
1616 if (value && !strcasecmp(value, "warn")) {
1617 global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
1618 return 0;
1620 eol_rndtrp_die = git_config_bool(var, value);
1621 global_conv_flags_eol = eol_rndtrp_die ?
1622 CONV_EOL_RNDTRP_DIE : 0;
1623 return 0;
1626 if (!strcmp(var, "core.eol")) {
1627 if (value && !strcasecmp(value, "lf"))
1628 core_eol = EOL_LF;
1629 else if (value && !strcasecmp(value, "crlf"))
1630 core_eol = EOL_CRLF;
1631 else if (value && !strcasecmp(value, "native"))
1632 core_eol = EOL_NATIVE;
1633 else
1634 core_eol = EOL_UNSET;
1635 return 0;
1638 if (!strcmp(var, "core.checkroundtripencoding")) {
1639 check_roundtrip_encoding = xstrdup(value);
1640 return 0;
1643 if (!strcmp(var, "core.notesref")) {
1644 notes_ref_name = xstrdup(value);
1645 return 0;
1648 if (!strcmp(var, "core.editor"))
1649 return git_config_string(&editor_program, var, value);
1651 if (!strcmp(var, "core.commentchar")) {
1652 if (!value)
1653 return config_error_nonbool(var);
1654 else if (!strcasecmp(value, "auto"))
1655 auto_comment_line_char = 1;
1656 else if (value[0] && !value[1]) {
1657 comment_line_char = value[0];
1658 auto_comment_line_char = 0;
1659 } else
1660 return error(_("core.commentChar should only be one character"));
1661 return 0;
1664 if (!strcmp(var, "core.askpass"))
1665 return git_config_string(&askpass_program, var, value);
1667 if (!strcmp(var, "core.excludesfile"))
1668 return git_config_pathname(&excludes_file, var, value);
1670 if (!strcmp(var, "core.whitespace")) {
1671 if (!value)
1672 return config_error_nonbool(var);
1673 whitespace_rule_cfg = parse_whitespace_rule(value);
1674 return 0;
1677 if (!strcmp(var, "core.fsync")) {
1678 if (!value)
1679 return config_error_nonbool(var);
1680 fsync_components = parse_fsync_components(var, value);
1681 return 0;
1684 if (!strcmp(var, "core.fsyncmethod")) {
1685 if (!value)
1686 return config_error_nonbool(var);
1687 if (!strcmp(value, "fsync"))
1688 fsync_method = FSYNC_METHOD_FSYNC;
1689 else if (!strcmp(value, "writeout-only"))
1690 fsync_method = FSYNC_METHOD_WRITEOUT_ONLY;
1691 else if (!strcmp(value, "batch"))
1692 fsync_method = FSYNC_METHOD_BATCH;
1693 else
1694 warning(_("ignoring unknown core.fsyncMethod value '%s'"), value);
1698 if (!strcmp(var, "core.fsyncobjectfiles")) {
1699 if (fsync_object_files < 0)
1700 warning(_("core.fsyncObjectFiles is deprecated; use core.fsync instead"));
1701 fsync_object_files = git_config_bool(var, value);
1702 return 0;
1705 if (!strcmp(var, "core.preloadindex")) {
1706 core_preload_index = git_config_bool(var, value);
1707 return 0;
1710 if (!strcmp(var, "core.createobject")) {
1711 if (!strcmp(value, "rename"))
1712 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
1713 else if (!strcmp(value, "link"))
1714 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
1715 else
1716 die(_("invalid mode for object creation: %s"), value);
1717 return 0;
1720 if (!strcmp(var, "core.sparsecheckout")) {
1721 core_apply_sparse_checkout = git_config_bool(var, value);
1722 return 0;
1725 if (!strcmp(var, "core.sparsecheckoutcone")) {
1726 core_sparse_checkout_cone = git_config_bool(var, value);
1727 return 0;
1730 if (!strcmp(var, "core.precomposeunicode")) {
1731 precomposed_unicode = git_config_bool(var, value);
1732 return 0;
1735 if (!strcmp(var, "core.protecthfs")) {
1736 protect_hfs = git_config_bool(var, value);
1737 return 0;
1740 if (!strcmp(var, "core.protectntfs")) {
1741 protect_ntfs = git_config_bool(var, value);
1742 return 0;
1745 if (!strcmp(var, "core.usereplacerefs")) {
1746 read_replace_refs = git_config_bool(var, value);
1747 return 0;
1750 /* Add other config variables here and to Documentation/config.txt. */
1751 return platform_core_config(var, value, cb);
1754 static int git_default_sparse_config(const char *var, const char *value)
1756 if (!strcmp(var, "sparse.expectfilesoutsideofpatterns")) {
1757 sparse_expect_files_outside_of_patterns = git_config_bool(var, value);
1758 return 0;
1761 /* Add other config variables here and to Documentation/config/sparse.txt. */
1762 return 0;
1765 static int git_default_i18n_config(const char *var, const char *value)
1767 if (!strcmp(var, "i18n.commitencoding"))
1768 return git_config_string(&git_commit_encoding, var, value);
1770 if (!strcmp(var, "i18n.logoutputencoding"))
1771 return git_config_string(&git_log_output_encoding, var, value);
1773 /* Add other config variables here and to Documentation/config.txt. */
1774 return 0;
1777 static int git_default_branch_config(const char *var, const char *value)
1779 if (!strcmp(var, "branch.autosetupmerge")) {
1780 if (value && !strcmp(value, "always")) {
1781 git_branch_track = BRANCH_TRACK_ALWAYS;
1782 return 0;
1783 } else if (value && !strcmp(value, "inherit")) {
1784 git_branch_track = BRANCH_TRACK_INHERIT;
1785 return 0;
1786 } else if (value && !strcmp(value, "simple")) {
1787 git_branch_track = BRANCH_TRACK_SIMPLE;
1788 return 0;
1790 git_branch_track = git_config_bool(var, value);
1791 return 0;
1793 if (!strcmp(var, "branch.autosetuprebase")) {
1794 if (!value)
1795 return config_error_nonbool(var);
1796 else if (!strcmp(value, "never"))
1797 autorebase = AUTOREBASE_NEVER;
1798 else if (!strcmp(value, "local"))
1799 autorebase = AUTOREBASE_LOCAL;
1800 else if (!strcmp(value, "remote"))
1801 autorebase = AUTOREBASE_REMOTE;
1802 else if (!strcmp(value, "always"))
1803 autorebase = AUTOREBASE_ALWAYS;
1804 else
1805 return error(_("malformed value for %s"), var);
1806 return 0;
1809 /* Add other config variables here and to Documentation/config.txt. */
1810 return 0;
1813 static int git_default_push_config(const char *var, const char *value)
1815 if (!strcmp(var, "push.default")) {
1816 if (!value)
1817 return config_error_nonbool(var);
1818 else if (!strcmp(value, "nothing"))
1819 push_default = PUSH_DEFAULT_NOTHING;
1820 else if (!strcmp(value, "matching"))
1821 push_default = PUSH_DEFAULT_MATCHING;
1822 else if (!strcmp(value, "simple"))
1823 push_default = PUSH_DEFAULT_SIMPLE;
1824 else if (!strcmp(value, "upstream"))
1825 push_default = PUSH_DEFAULT_UPSTREAM;
1826 else if (!strcmp(value, "tracking")) /* deprecated */
1827 push_default = PUSH_DEFAULT_UPSTREAM;
1828 else if (!strcmp(value, "current"))
1829 push_default = PUSH_DEFAULT_CURRENT;
1830 else {
1831 error(_("malformed value for %s: %s"), var, value);
1832 return error(_("must be one of nothing, matching, simple, "
1833 "upstream or current"));
1835 return 0;
1838 /* Add other config variables here and to Documentation/config.txt. */
1839 return 0;
1842 static int git_default_mailmap_config(const char *var, const char *value)
1844 if (!strcmp(var, "mailmap.file"))
1845 return git_config_pathname(&git_mailmap_file, var, value);
1846 if (!strcmp(var, "mailmap.blob"))
1847 return git_config_string(&git_mailmap_blob, var, value);
1849 /* Add other config variables here and to Documentation/config.txt. */
1850 return 0;
1853 int git_default_config(const char *var, const char *value, void *cb)
1855 if (starts_with(var, "core."))
1856 return git_default_core_config(var, value, cb);
1858 if (starts_with(var, "user.") ||
1859 starts_with(var, "author.") ||
1860 starts_with(var, "committer."))
1861 return git_ident_config(var, value, cb);
1863 if (starts_with(var, "i18n."))
1864 return git_default_i18n_config(var, value);
1866 if (starts_with(var, "branch."))
1867 return git_default_branch_config(var, value);
1869 if (starts_with(var, "push."))
1870 return git_default_push_config(var, value);
1872 if (starts_with(var, "mailmap."))
1873 return git_default_mailmap_config(var, value);
1875 if (starts_with(var, "advice.") || starts_with(var, "color.advice"))
1876 return git_default_advice_config(var, value);
1878 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1879 pager_use_color = git_config_bool(var,value);
1880 return 0;
1883 if (!strcmp(var, "pack.packsizelimit")) {
1884 pack_size_limit_cfg = git_config_ulong(var, value);
1885 return 0;
1888 if (!strcmp(var, "pack.compression")) {
1889 int level = git_config_int(var, value);
1890 if (level == -1)
1891 level = Z_DEFAULT_COMPRESSION;
1892 else if (level < 0 || level > Z_BEST_COMPRESSION)
1893 die(_("bad pack compression level %d"), level);
1894 pack_compression_level = level;
1895 pack_compression_seen = 1;
1896 return 0;
1899 if (starts_with(var, "sparse."))
1900 return git_default_sparse_config(var, value);
1902 /* Add other config variables here and to Documentation/config.txt. */
1903 return 0;
1907 * All source specific fields in the union, die_on_error, name and the callbacks
1908 * fgetc, ungetc, ftell of top need to be initialized before calling
1909 * this function.
1911 static int do_config_from(struct config_source *top, config_fn_t fn, void *data,
1912 const struct config_options *opts)
1914 int ret;
1916 /* push config-file parsing state stack */
1917 top->prev = cf;
1918 top->linenr = 1;
1919 top->eof = 0;
1920 top->total_len = 0;
1921 strbuf_init(&top->value, 1024);
1922 strbuf_init(&top->var, 1024);
1923 cf = top;
1925 ret = git_parse_source(fn, data, opts);
1927 /* pop config-file parsing state stack */
1928 strbuf_release(&top->value);
1929 strbuf_release(&top->var);
1930 cf = top->prev;
1932 return ret;
1935 static int do_config_from_file(config_fn_t fn,
1936 const enum config_origin_type origin_type,
1937 const char *name, const char *path, FILE *f,
1938 void *data, const struct config_options *opts)
1940 struct config_source top;
1941 int ret;
1943 top.u.file = f;
1944 top.origin_type = origin_type;
1945 top.name = name;
1946 top.path = path;
1947 top.default_error_action = CONFIG_ERROR_DIE;
1948 top.do_fgetc = config_file_fgetc;
1949 top.do_ungetc = config_file_ungetc;
1950 top.do_ftell = config_file_ftell;
1952 flockfile(f);
1953 ret = do_config_from(&top, fn, data, opts);
1954 funlockfile(f);
1955 return ret;
1958 static int git_config_from_stdin(config_fn_t fn, void *data)
1960 return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", NULL, stdin,
1961 data, NULL);
1964 int git_config_from_file_with_options(config_fn_t fn, const char *filename,
1965 void *data,
1966 const struct config_options *opts)
1968 int ret = -1;
1969 FILE *f;
1971 f = fopen_or_warn(filename, "r");
1972 if (f) {
1973 ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename,
1974 filename, f, data, opts);
1975 fclose(f);
1977 return ret;
1980 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
1982 return git_config_from_file_with_options(fn, filename, data, NULL);
1985 int git_config_from_mem(config_fn_t fn,
1986 const enum config_origin_type origin_type,
1987 const char *name, const char *buf, size_t len,
1988 void *data, const struct config_options *opts)
1990 struct config_source top;
1992 top.u.buf.buf = buf;
1993 top.u.buf.len = len;
1994 top.u.buf.pos = 0;
1995 top.origin_type = origin_type;
1996 top.name = name;
1997 top.path = NULL;
1998 top.default_error_action = CONFIG_ERROR_ERROR;
1999 top.do_fgetc = config_buf_fgetc;
2000 top.do_ungetc = config_buf_ungetc;
2001 top.do_ftell = config_buf_ftell;
2003 return do_config_from(&top, fn, data, opts);
2006 int git_config_from_blob_oid(config_fn_t fn,
2007 const char *name,
2008 struct repository *repo,
2009 const struct object_id *oid,
2010 void *data)
2012 enum object_type type;
2013 char *buf;
2014 unsigned long size;
2015 int ret;
2017 buf = repo_read_object_file(repo, oid, &type, &size);
2018 if (!buf)
2019 return error(_("unable to load config blob object '%s'"), name);
2020 if (type != OBJ_BLOB) {
2021 free(buf);
2022 return error(_("reference '%s' does not point to a blob"), name);
2025 ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size,
2026 data, NULL);
2027 free(buf);
2029 return ret;
2032 static int git_config_from_blob_ref(config_fn_t fn,
2033 struct repository *repo,
2034 const char *name,
2035 void *data)
2037 struct object_id oid;
2039 if (repo_get_oid(repo, name, &oid) < 0)
2040 return error(_("unable to resolve config blob '%s'"), name);
2041 return git_config_from_blob_oid(fn, name, repo, &oid, data);
2044 char *git_system_config(void)
2046 char *system_config = xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
2047 if (!system_config)
2048 system_config = system_path(ETC_GITCONFIG);
2049 normalize_path_copy(system_config, system_config);
2050 return system_config;
2053 void git_global_config(char **user_out, char **xdg_out)
2055 char *user_config = xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
2056 char *xdg_config = NULL;
2058 if (!user_config) {
2059 user_config = interpolate_path("~/.gitconfig", 0);
2060 xdg_config = xdg_config_home("config");
2063 *user_out = user_config;
2064 *xdg_out = xdg_config;
2068 * Parse environment variable 'k' as a boolean (in various
2069 * possible spellings); if missing, use the default value 'def'.
2071 int git_env_bool(const char *k, int def)
2073 const char *v = getenv(k);
2074 return v ? git_config_bool(k, v) : def;
2078 * Parse environment variable 'k' as ulong with possibly a unit
2079 * suffix; if missing, use the default value 'val'.
2081 unsigned long git_env_ulong(const char *k, unsigned long val)
2083 const char *v = getenv(k);
2084 if (v && !git_parse_ulong(v, &val))
2085 die(_("failed to parse %s"), k);
2086 return val;
2089 int git_config_system(void)
2091 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
2094 static int do_git_config_sequence(const struct config_options *opts,
2095 config_fn_t fn, void *data)
2097 int ret = 0;
2098 char *system_config = git_system_config();
2099 char *xdg_config = NULL;
2100 char *user_config = NULL;
2101 char *repo_config;
2102 enum config_scope prev_parsing_scope = current_parsing_scope;
2104 if (opts->commondir)
2105 repo_config = mkpathdup("%s/config", opts->commondir);
2106 else if (opts->git_dir)
2107 BUG("git_dir without commondir");
2108 else
2109 repo_config = NULL;
2111 current_parsing_scope = CONFIG_SCOPE_SYSTEM;
2112 if (git_config_system() && system_config &&
2113 !access_or_die(system_config, R_OK,
2114 opts->system_gently ? ACCESS_EACCES_OK : 0))
2115 ret += git_config_from_file(fn, system_config, data);
2117 current_parsing_scope = CONFIG_SCOPE_GLOBAL;
2118 git_global_config(&user_config, &xdg_config);
2120 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
2121 ret += git_config_from_file(fn, xdg_config, data);
2123 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
2124 ret += git_config_from_file(fn, user_config, data);
2126 current_parsing_scope = CONFIG_SCOPE_LOCAL;
2127 if (!opts->ignore_repo && repo_config &&
2128 !access_or_die(repo_config, R_OK, 0))
2129 ret += git_config_from_file(fn, repo_config, data);
2131 current_parsing_scope = CONFIG_SCOPE_WORKTREE;
2132 if (!opts->ignore_worktree && repository_format_worktree_config) {
2133 char *path = git_pathdup("config.worktree");
2134 if (!access_or_die(path, R_OK, 0))
2135 ret += git_config_from_file(fn, path, data);
2136 free(path);
2139 current_parsing_scope = CONFIG_SCOPE_COMMAND;
2140 if (!opts->ignore_cmdline && git_config_from_parameters(fn, data) < 0)
2141 die(_("unable to parse command-line config"));
2143 current_parsing_scope = prev_parsing_scope;
2144 free(system_config);
2145 free(xdg_config);
2146 free(user_config);
2147 free(repo_config);
2148 return ret;
2151 int config_with_options(config_fn_t fn, void *data,
2152 struct git_config_source *config_source,
2153 const struct config_options *opts)
2155 struct config_include_data inc = CONFIG_INCLUDE_INIT;
2156 int ret;
2158 if (opts->respect_includes) {
2159 inc.fn = fn;
2160 inc.data = data;
2161 inc.opts = opts;
2162 inc.config_source = config_source;
2163 fn = git_config_include;
2164 data = &inc;
2167 if (config_source)
2168 current_parsing_scope = config_source->scope;
2171 * If we have a specific filename, use it. Otherwise, follow the
2172 * regular lookup sequence.
2174 if (config_source && config_source->use_stdin) {
2175 ret = git_config_from_stdin(fn, data);
2176 } else if (config_source && config_source->file) {
2177 ret = git_config_from_file(fn, config_source->file, data);
2178 } else if (config_source && config_source->blob) {
2179 struct repository *repo = config_source->repo ?
2180 config_source->repo : the_repository;
2181 ret = git_config_from_blob_ref(fn, repo, config_source->blob,
2182 data);
2183 } else {
2184 ret = do_git_config_sequence(opts, fn, data);
2187 if (inc.remote_urls) {
2188 string_list_clear(inc.remote_urls, 0);
2189 FREE_AND_NULL(inc.remote_urls);
2191 return ret;
2194 static void configset_iter(struct config_set *cs, config_fn_t fn, void *data)
2196 int i, value_index;
2197 struct string_list *values;
2198 struct config_set_element *entry;
2199 struct configset_list *list = &cs->list;
2201 for (i = 0; i < list->nr; i++) {
2202 entry = list->items[i].e;
2203 value_index = list->items[i].value_index;
2204 values = &entry->value_list;
2206 current_config_kvi = values->items[value_index].util;
2208 if (fn(entry->key, values->items[value_index].string, data) < 0)
2209 git_die_config_linenr(entry->key,
2210 current_config_kvi->filename,
2211 current_config_kvi->linenr);
2213 current_config_kvi = NULL;
2217 void read_early_config(config_fn_t cb, void *data)
2219 struct config_options opts = {0};
2220 struct strbuf commondir = STRBUF_INIT;
2221 struct strbuf gitdir = STRBUF_INIT;
2223 opts.respect_includes = 1;
2225 if (have_git_dir()) {
2226 opts.commondir = get_git_common_dir();
2227 opts.git_dir = get_git_dir();
2229 * When setup_git_directory() was not yet asked to discover the
2230 * GIT_DIR, we ask discover_git_directory() to figure out whether there
2231 * is any repository config we should use (but unlike
2232 * setup_git_directory_gently(), no global state is changed, most
2233 * notably, the current working directory is still the same after the
2234 * call).
2236 } else if (!discover_git_directory(&commondir, &gitdir)) {
2237 opts.commondir = commondir.buf;
2238 opts.git_dir = gitdir.buf;
2241 config_with_options(cb, data, NULL, &opts);
2243 strbuf_release(&commondir);
2244 strbuf_release(&gitdir);
2248 * Read config but only enumerate system and global settings.
2249 * Omit any repo-local, worktree-local, or command-line settings.
2251 void read_very_early_config(config_fn_t cb, void *data)
2253 struct config_options opts = { 0 };
2255 opts.respect_includes = 1;
2256 opts.ignore_repo = 1;
2257 opts.ignore_worktree = 1;
2258 opts.ignore_cmdline = 1;
2259 opts.system_gently = 1;
2261 config_with_options(cb, data, NULL, &opts);
2264 static struct config_set_element *configset_find_element(struct config_set *cs, const char *key)
2266 struct config_set_element k;
2267 struct config_set_element *found_entry;
2268 char *normalized_key;
2270 * `key` may come from the user, so normalize it before using it
2271 * for querying entries from the hashmap.
2273 if (git_config_parse_key(key, &normalized_key, NULL))
2274 return NULL;
2276 hashmap_entry_init(&k.ent, strhash(normalized_key));
2277 k.key = normalized_key;
2278 found_entry = hashmap_get_entry(&cs->config_hash, &k, ent, NULL);
2279 free(normalized_key);
2280 return found_entry;
2283 static int configset_add_value(struct config_set *cs, const char *key, const char *value)
2285 struct config_set_element *e;
2286 struct string_list_item *si;
2287 struct configset_list_item *l_item;
2288 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
2290 e = configset_find_element(cs, key);
2292 * Since the keys are being fed by git_config*() callback mechanism, they
2293 * are already normalized. So simply add them without any further munging.
2295 if (!e) {
2296 e = xmalloc(sizeof(*e));
2297 hashmap_entry_init(&e->ent, strhash(key));
2298 e->key = xstrdup(key);
2299 string_list_init_dup(&e->value_list);
2300 hashmap_add(&cs->config_hash, &e->ent);
2302 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
2304 ALLOC_GROW(cs->list.items, cs->list.nr + 1, cs->list.alloc);
2305 l_item = &cs->list.items[cs->list.nr++];
2306 l_item->e = e;
2307 l_item->value_index = e->value_list.nr - 1;
2309 if (!cf)
2310 BUG("configset_add_value has no source");
2311 if (cf->name) {
2312 kv_info->filename = strintern(cf->name);
2313 kv_info->linenr = cf->linenr;
2314 kv_info->origin_type = cf->origin_type;
2315 } else {
2316 /* for values read from `git_config_from_parameters()` */
2317 kv_info->filename = NULL;
2318 kv_info->linenr = -1;
2319 kv_info->origin_type = CONFIG_ORIGIN_CMDLINE;
2321 kv_info->scope = current_parsing_scope;
2322 si->util = kv_info;
2324 return 0;
2327 static int config_set_element_cmp(const void *unused_cmp_data,
2328 const struct hashmap_entry *eptr,
2329 const struct hashmap_entry *entry_or_key,
2330 const void *unused_keydata)
2332 const struct config_set_element *e1, *e2;
2334 e1 = container_of(eptr, const struct config_set_element, ent);
2335 e2 = container_of(entry_or_key, const struct config_set_element, ent);
2337 return strcmp(e1->key, e2->key);
2340 void git_configset_init(struct config_set *cs)
2342 hashmap_init(&cs->config_hash, config_set_element_cmp, NULL, 0);
2343 cs->hash_initialized = 1;
2344 cs->list.nr = 0;
2345 cs->list.alloc = 0;
2346 cs->list.items = NULL;
2349 void git_configset_clear(struct config_set *cs)
2351 struct config_set_element *entry;
2352 struct hashmap_iter iter;
2353 if (!cs->hash_initialized)
2354 return;
2356 hashmap_for_each_entry(&cs->config_hash, &iter, entry,
2357 ent /* member name */) {
2358 free(entry->key);
2359 string_list_clear(&entry->value_list, 1);
2361 hashmap_clear_and_free(&cs->config_hash, struct config_set_element, ent);
2362 cs->hash_initialized = 0;
2363 free(cs->list.items);
2364 cs->list.nr = 0;
2365 cs->list.alloc = 0;
2366 cs->list.items = NULL;
2369 static int config_set_callback(const char *key, const char *value, void *cb)
2371 struct config_set *cs = cb;
2372 configset_add_value(cs, key, value);
2373 return 0;
2376 int git_configset_add_file(struct config_set *cs, const char *filename)
2378 return git_config_from_file(config_set_callback, filename, cs);
2381 int git_configset_get_value(struct config_set *cs, const char *key, const char **value)
2383 const struct string_list *values = NULL;
2385 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
2386 * queried key in the files of the configset, the value returned will be the last
2387 * value in the value list for that key.
2389 values = git_configset_get_value_multi(cs, key);
2391 if (!values)
2392 return 1;
2393 assert(values->nr > 0);
2394 *value = values->items[values->nr - 1].string;
2395 return 0;
2398 const struct string_list *git_configset_get_value_multi(struct config_set *cs, const char *key)
2400 struct config_set_element *e = configset_find_element(cs, key);
2401 return e ? &e->value_list : NULL;
2404 int git_configset_get_string(struct config_set *cs, const char *key, char **dest)
2406 const char *value;
2407 if (!git_configset_get_value(cs, key, &value))
2408 return git_config_string((const char **)dest, key, value);
2409 else
2410 return 1;
2413 static int git_configset_get_string_tmp(struct config_set *cs, const char *key,
2414 const char **dest)
2416 const char *value;
2417 if (!git_configset_get_value(cs, key, &value)) {
2418 if (!value)
2419 return config_error_nonbool(key);
2420 *dest = value;
2421 return 0;
2422 } else {
2423 return 1;
2427 int git_configset_get_int(struct config_set *cs, const char *key, int *dest)
2429 const char *value;
2430 if (!git_configset_get_value(cs, key, &value)) {
2431 *dest = git_config_int(key, value);
2432 return 0;
2433 } else
2434 return 1;
2437 int git_configset_get_ulong(struct config_set *cs, const char *key, unsigned long *dest)
2439 const char *value;
2440 if (!git_configset_get_value(cs, key, &value)) {
2441 *dest = git_config_ulong(key, value);
2442 return 0;
2443 } else
2444 return 1;
2447 int git_configset_get_bool(struct config_set *cs, const char *key, int *dest)
2449 const char *value;
2450 if (!git_configset_get_value(cs, key, &value)) {
2451 *dest = git_config_bool(key, value);
2452 return 0;
2453 } else
2454 return 1;
2457 int git_configset_get_bool_or_int(struct config_set *cs, const char *key,
2458 int *is_bool, int *dest)
2460 const char *value;
2461 if (!git_configset_get_value(cs, key, &value)) {
2462 *dest = git_config_bool_or_int(key, value, is_bool);
2463 return 0;
2464 } else
2465 return 1;
2468 int git_configset_get_maybe_bool(struct config_set *cs, const char *key, int *dest)
2470 const char *value;
2471 if (!git_configset_get_value(cs, key, &value)) {
2472 *dest = git_parse_maybe_bool(value);
2473 if (*dest == -1)
2474 return -1;
2475 return 0;
2476 } else
2477 return 1;
2480 int git_configset_get_pathname(struct config_set *cs, const char *key, const char **dest)
2482 const char *value;
2483 if (!git_configset_get_value(cs, key, &value))
2484 return git_config_pathname(dest, key, value);
2485 else
2486 return 1;
2489 /* Functions use to read configuration from a repository */
2490 static void repo_read_config(struct repository *repo)
2492 struct config_options opts = { 0 };
2494 opts.respect_includes = 1;
2495 opts.commondir = repo->commondir;
2496 opts.git_dir = repo->gitdir;
2498 if (!repo->config)
2499 CALLOC_ARRAY(repo->config, 1);
2500 else
2501 git_configset_clear(repo->config);
2503 git_configset_init(repo->config);
2505 if (config_with_options(config_set_callback, repo->config, NULL, &opts) < 0)
2507 * config_with_options() normally returns only
2508 * zero, as most errors are fatal, and
2509 * non-fatal potential errors are guarded by "if"
2510 * statements that are entered only when no error is
2511 * possible.
2513 * If we ever encounter a non-fatal error, it means
2514 * something went really wrong and we should stop
2515 * immediately.
2517 die(_("unknown error occurred while reading the configuration files"));
2520 static void git_config_check_init(struct repository *repo)
2522 if (repo->config && repo->config->hash_initialized)
2523 return;
2524 repo_read_config(repo);
2527 static void repo_config_clear(struct repository *repo)
2529 if (!repo->config || !repo->config->hash_initialized)
2530 return;
2531 git_configset_clear(repo->config);
2534 void repo_config(struct repository *repo, config_fn_t fn, void *data)
2536 git_config_check_init(repo);
2537 configset_iter(repo->config, fn, data);
2540 int repo_config_get_value(struct repository *repo,
2541 const char *key, const char **value)
2543 git_config_check_init(repo);
2544 return git_configset_get_value(repo->config, key, value);
2547 const struct string_list *repo_config_get_value_multi(struct repository *repo,
2548 const char *key)
2550 git_config_check_init(repo);
2551 return git_configset_get_value_multi(repo->config, key);
2554 int repo_config_get_string(struct repository *repo,
2555 const char *key, char **dest)
2557 int ret;
2558 git_config_check_init(repo);
2559 ret = git_configset_get_string(repo->config, key, dest);
2560 if (ret < 0)
2561 git_die_config(key, NULL);
2562 return ret;
2565 int repo_config_get_string_tmp(struct repository *repo,
2566 const char *key, const char **dest)
2568 int ret;
2569 git_config_check_init(repo);
2570 ret = git_configset_get_string_tmp(repo->config, key, dest);
2571 if (ret < 0)
2572 git_die_config(key, NULL);
2573 return ret;
2576 int repo_config_get_int(struct repository *repo,
2577 const char *key, int *dest)
2579 git_config_check_init(repo);
2580 return git_configset_get_int(repo->config, key, dest);
2583 int repo_config_get_ulong(struct repository *repo,
2584 const char *key, unsigned long *dest)
2586 git_config_check_init(repo);
2587 return git_configset_get_ulong(repo->config, key, dest);
2590 int repo_config_get_bool(struct repository *repo,
2591 const char *key, int *dest)
2593 git_config_check_init(repo);
2594 return git_configset_get_bool(repo->config, key, dest);
2597 int repo_config_get_bool_or_int(struct repository *repo,
2598 const char *key, int *is_bool, int *dest)
2600 git_config_check_init(repo);
2601 return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2604 int repo_config_get_maybe_bool(struct repository *repo,
2605 const char *key, int *dest)
2607 git_config_check_init(repo);
2608 return git_configset_get_maybe_bool(repo->config, key, dest);
2611 int repo_config_get_pathname(struct repository *repo,
2612 const char *key, const char **dest)
2614 int ret;
2615 git_config_check_init(repo);
2616 ret = git_configset_get_pathname(repo->config, key, dest);
2617 if (ret < 0)
2618 git_die_config(key, NULL);
2619 return ret;
2622 /* Functions used historically to read configuration from 'the_repository' */
2623 void git_config(config_fn_t fn, void *data)
2625 repo_config(the_repository, fn, data);
2628 void git_config_clear(void)
2630 repo_config_clear(the_repository);
2633 int git_config_get_value(const char *key, const char **value)
2635 return repo_config_get_value(the_repository, key, value);
2638 const struct string_list *git_config_get_value_multi(const char *key)
2640 return repo_config_get_value_multi(the_repository, key);
2643 int git_config_get_string(const char *key, char **dest)
2645 return repo_config_get_string(the_repository, key, dest);
2648 int git_config_get_string_tmp(const char *key, const char **dest)
2650 return repo_config_get_string_tmp(the_repository, key, dest);
2653 int git_config_get_int(const char *key, int *dest)
2655 return repo_config_get_int(the_repository, key, dest);
2658 int git_config_get_ulong(const char *key, unsigned long *dest)
2660 return repo_config_get_ulong(the_repository, key, dest);
2663 int git_config_get_bool(const char *key, int *dest)
2665 return repo_config_get_bool(the_repository, key, dest);
2668 int git_config_get_bool_or_int(const char *key, int *is_bool, int *dest)
2670 return repo_config_get_bool_or_int(the_repository, key, is_bool, dest);
2673 int git_config_get_maybe_bool(const char *key, int *dest)
2675 return repo_config_get_maybe_bool(the_repository, key, dest);
2678 int git_config_get_pathname(const char *key, const char **dest)
2680 return repo_config_get_pathname(the_repository, key, dest);
2683 int git_config_get_expiry(const char *key, const char **output)
2685 int ret = git_config_get_string(key, (char **)output);
2686 if (ret)
2687 return ret;
2688 if (strcmp(*output, "now")) {
2689 timestamp_t now = approxidate("now");
2690 if (approxidate(*output) >= now)
2691 git_die_config(key, _("Invalid %s: '%s'"), key, *output);
2693 return ret;
2696 int git_config_get_expiry_in_days(const char *key, timestamp_t *expiry, timestamp_t now)
2698 const char *expiry_string;
2699 intmax_t days;
2700 timestamp_t when;
2702 if (git_config_get_string_tmp(key, &expiry_string))
2703 return 1; /* no such thing */
2705 if (git_parse_signed(expiry_string, &days, maximum_signed_value_of_type(int))) {
2706 const int scale = 86400;
2707 *expiry = now - days * scale;
2708 return 0;
2711 if (!parse_expiry_date(expiry_string, &when)) {
2712 *expiry = when;
2713 return 0;
2715 return -1; /* thing exists but cannot be parsed */
2718 int git_config_get_split_index(void)
2720 int val;
2722 if (!git_config_get_maybe_bool("core.splitindex", &val))
2723 return val;
2725 return -1; /* default value */
2728 int git_config_get_max_percent_split_change(void)
2730 int val = -1;
2732 if (!git_config_get_int("splitindex.maxpercentchange", &val)) {
2733 if (0 <= val && val <= 100)
2734 return val;
2736 return error(_("splitIndex.maxPercentChange value '%d' "
2737 "should be between 0 and 100"), val);
2740 return -1; /* default value */
2743 int git_config_get_index_threads(int *dest)
2745 int is_bool, val;
2747 val = git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2748 if (val) {
2749 *dest = val;
2750 return 0;
2753 if (!git_config_get_bool_or_int("index.threads", &is_bool, &val)) {
2754 if (is_bool)
2755 *dest = val ? 0 : 1;
2756 else
2757 *dest = val;
2758 return 0;
2761 return 1;
2764 NORETURN
2765 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2767 if (!filename)
2768 die(_("unable to parse '%s' from command-line config"), key);
2769 else
2770 die(_("bad config variable '%s' in file '%s' at line %d"),
2771 key, filename, linenr);
2774 NORETURN __attribute__((format(printf, 2, 3)))
2775 void git_die_config(const char *key, const char *err, ...)
2777 const struct string_list *values;
2778 struct key_value_info *kv_info;
2779 report_fn error_fn = get_error_routine();
2781 if (err) {
2782 va_list params;
2783 va_start(params, err);
2784 error_fn(err, params);
2785 va_end(params);
2787 values = git_config_get_value_multi(key);
2788 kv_info = values->items[values->nr - 1].util;
2789 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
2793 * Find all the stuff for git_config_set() below.
2796 struct config_store_data {
2797 size_t baselen;
2798 char *key;
2799 int do_not_match;
2800 const char *fixed_value;
2801 regex_t *value_pattern;
2802 int multi_replace;
2803 struct {
2804 size_t begin, end;
2805 enum config_event_t type;
2806 int is_keys_section;
2807 } *parsed;
2808 unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
2809 unsigned int key_seen:1, section_seen:1, is_keys_section:1;
2812 static void config_store_data_clear(struct config_store_data *store)
2814 free(store->key);
2815 if (store->value_pattern != NULL &&
2816 store->value_pattern != CONFIG_REGEX_NONE) {
2817 regfree(store->value_pattern);
2818 free(store->value_pattern);
2820 free(store->parsed);
2821 free(store->seen);
2822 memset(store, 0, sizeof(*store));
2825 static int matches(const char *key, const char *value,
2826 const struct config_store_data *store)
2828 if (strcmp(key, store->key))
2829 return 0; /* not ours */
2830 if (store->fixed_value)
2831 return !strcmp(store->fixed_value, value);
2832 if (!store->value_pattern)
2833 return 1; /* always matches */
2834 if (store->value_pattern == CONFIG_REGEX_NONE)
2835 return 0; /* never matches */
2837 return store->do_not_match ^
2838 (value && !regexec(store->value_pattern, value, 0, NULL, 0));
2841 static int store_aux_event(enum config_event_t type,
2842 size_t begin, size_t end, void *data)
2844 struct config_store_data *store = data;
2846 ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
2847 store->parsed[store->parsed_nr].begin = begin;
2848 store->parsed[store->parsed_nr].end = end;
2849 store->parsed[store->parsed_nr].type = type;
2851 if (type == CONFIG_EVENT_SECTION) {
2852 int (*cmpfn)(const char *, const char *, size_t);
2854 if (cf->var.len < 2 || cf->var.buf[cf->var.len - 1] != '.')
2855 return error(_("invalid section name '%s'"), cf->var.buf);
2857 if (cf->subsection_case_sensitive)
2858 cmpfn = strncasecmp;
2859 else
2860 cmpfn = strncmp;
2862 /* Is this the section we were looking for? */
2863 store->is_keys_section =
2864 store->parsed[store->parsed_nr].is_keys_section =
2865 cf->var.len - 1 == store->baselen &&
2866 !cmpfn(cf->var.buf, store->key, store->baselen);
2867 if (store->is_keys_section) {
2868 store->section_seen = 1;
2869 ALLOC_GROW(store->seen, store->seen_nr + 1,
2870 store->seen_alloc);
2871 store->seen[store->seen_nr] = store->parsed_nr;
2875 store->parsed_nr++;
2877 return 0;
2880 static int store_aux(const char *key, const char *value, void *cb)
2882 struct config_store_data *store = cb;
2884 if (store->key_seen) {
2885 if (matches(key, value, store)) {
2886 if (store->seen_nr == 1 && store->multi_replace == 0) {
2887 warning(_("%s has multiple values"), key);
2890 ALLOC_GROW(store->seen, store->seen_nr + 1,
2891 store->seen_alloc);
2893 store->seen[store->seen_nr] = store->parsed_nr;
2894 store->seen_nr++;
2896 } else if (store->is_keys_section) {
2898 * Do not increment matches yet: this may not be a match, but we
2899 * are in the desired section.
2901 ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
2902 store->seen[store->seen_nr] = store->parsed_nr;
2903 store->section_seen = 1;
2905 if (matches(key, value, store)) {
2906 store->seen_nr++;
2907 store->key_seen = 1;
2911 return 0;
2914 static int write_error(const char *filename)
2916 error(_("failed to write new configuration file %s"), filename);
2918 /* Same error code as "failed to rename". */
2919 return 4;
2922 static struct strbuf store_create_section(const char *key,
2923 const struct config_store_data *store)
2925 const char *dot;
2926 size_t i;
2927 struct strbuf sb = STRBUF_INIT;
2929 dot = memchr(key, '.', store->baselen);
2930 if (dot) {
2931 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
2932 for (i = dot - key + 1; i < store->baselen; i++) {
2933 if (key[i] == '"' || key[i] == '\\')
2934 strbuf_addch(&sb, '\\');
2935 strbuf_addch(&sb, key[i]);
2937 strbuf_addstr(&sb, "\"]\n");
2938 } else {
2939 strbuf_addch(&sb, '[');
2940 strbuf_add(&sb, key, store->baselen);
2941 strbuf_addstr(&sb, "]\n");
2944 return sb;
2947 static ssize_t write_section(int fd, const char *key,
2948 const struct config_store_data *store)
2950 struct strbuf sb = store_create_section(key, store);
2951 ssize_t ret;
2953 ret = write_in_full(fd, sb.buf, sb.len);
2954 strbuf_release(&sb);
2956 return ret;
2959 static ssize_t write_pair(int fd, const char *key, const char *value,
2960 const struct config_store_data *store)
2962 int i;
2963 ssize_t ret;
2964 const char *quote = "";
2965 struct strbuf sb = STRBUF_INIT;
2968 * Check to see if the value needs to be surrounded with a dq pair.
2969 * Note that problematic characters are always backslash-quoted; this
2970 * check is about not losing leading or trailing SP and strings that
2971 * follow beginning-of-comment characters (i.e. ';' and '#') by the
2972 * configuration parser.
2974 if (value[0] == ' ')
2975 quote = "\"";
2976 for (i = 0; value[i]; i++)
2977 if (value[i] == ';' || value[i] == '#')
2978 quote = "\"";
2979 if (i && value[i - 1] == ' ')
2980 quote = "\"";
2982 strbuf_addf(&sb, "\t%s = %s", key + store->baselen + 1, quote);
2984 for (i = 0; value[i]; i++)
2985 switch (value[i]) {
2986 case '\n':
2987 strbuf_addstr(&sb, "\\n");
2988 break;
2989 case '\t':
2990 strbuf_addstr(&sb, "\\t");
2991 break;
2992 case '"':
2993 case '\\':
2994 strbuf_addch(&sb, '\\');
2995 /* fallthrough */
2996 default:
2997 strbuf_addch(&sb, value[i]);
2998 break;
3000 strbuf_addf(&sb, "%s\n", quote);
3002 ret = write_in_full(fd, sb.buf, sb.len);
3003 strbuf_release(&sb);
3005 return ret;
3009 * If we are about to unset the last key(s) in a section, and if there are
3010 * no comments surrounding (or included in) the section, we will want to
3011 * extend begin/end to remove the entire section.
3013 * Note: the parameter `seen_ptr` points to the index into the store.seen
3014 * array. * This index may be incremented if a section has more than one
3015 * entry (which all are to be removed).
3017 static void maybe_remove_section(struct config_store_data *store,
3018 size_t *begin_offset, size_t *end_offset,
3019 int *seen_ptr)
3021 size_t begin;
3022 int i, seen, section_seen = 0;
3025 * First, ensure that this is the first key, and that there are no
3026 * comments before the entry nor before the section header.
3028 seen = *seen_ptr;
3029 for (i = store->seen[seen]; i > 0; i--) {
3030 enum config_event_t type = store->parsed[i - 1].type;
3032 if (type == CONFIG_EVENT_COMMENT)
3033 /* There is a comment before this entry or section */
3034 return;
3035 if (type == CONFIG_EVENT_ENTRY) {
3036 if (!section_seen)
3037 /* This is not the section's first entry. */
3038 return;
3039 /* We encountered no comment before the section. */
3040 break;
3042 if (type == CONFIG_EVENT_SECTION) {
3043 if (!store->parsed[i - 1].is_keys_section)
3044 break;
3045 section_seen = 1;
3048 begin = store->parsed[i].begin;
3051 * Next, make sure that we are removing the last key(s) in the section,
3052 * and that there are no comments that are possibly about the current
3053 * section.
3055 for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
3056 enum config_event_t type = store->parsed[i].type;
3058 if (type == CONFIG_EVENT_COMMENT)
3059 return;
3060 if (type == CONFIG_EVENT_SECTION) {
3061 if (store->parsed[i].is_keys_section)
3062 continue;
3063 break;
3065 if (type == CONFIG_EVENT_ENTRY) {
3066 if (++seen < store->seen_nr &&
3067 i == store->seen[seen])
3068 /* We want to remove this entry, too */
3069 continue;
3070 /* There is another entry in this section. */
3071 return;
3076 * We are really removing the last entry/entries from this section, and
3077 * there are no enclosed or surrounding comments. Remove the entire,
3078 * now-empty section.
3080 *seen_ptr = seen;
3081 *begin_offset = begin;
3082 if (i < store->parsed_nr)
3083 *end_offset = store->parsed[i].begin;
3084 else
3085 *end_offset = store->parsed[store->parsed_nr - 1].end;
3088 int git_config_set_in_file_gently(const char *config_filename,
3089 const char *key, const char *value)
3091 return git_config_set_multivar_in_file_gently(config_filename, key, value, NULL, 0);
3094 void git_config_set_in_file(const char *config_filename,
3095 const char *key, const char *value)
3097 git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
3100 int git_config_set_gently(const char *key, const char *value)
3102 return git_config_set_multivar_gently(key, value, NULL, 0);
3105 int repo_config_set_worktree_gently(struct repository *r,
3106 const char *key, const char *value)
3108 /* Only use worktree-specific config if it is is already enabled. */
3109 if (repository_format_worktree_config) {
3110 char *file = repo_git_path(r, "config.worktree");
3111 int ret = git_config_set_multivar_in_file_gently(
3112 file, key, value, NULL, 0);
3113 free(file);
3114 return ret;
3116 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
3119 void git_config_set(const char *key, const char *value)
3121 git_config_set_multivar(key, value, NULL, 0);
3123 trace2_cmd_set_config(key, value);
3127 * If value==NULL, unset in (remove from) config,
3128 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
3129 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
3130 * (only add a new one)
3131 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3132 * key/values are removed before a single new pair is written. If the
3133 * flag is not present, then replace only the first match.
3135 * Returns 0 on success.
3137 * This function does this:
3139 * - it locks the config file by creating ".git/config.lock"
3141 * - it then parses the config using store_aux() as validator to find
3142 * the position on the key/value pair to replace. If it is to be unset,
3143 * it must be found exactly once.
3145 * - the config file is mmap()ed and the part before the match (if any) is
3146 * written to the lock file, then the changed part and the rest.
3148 * - the config file is removed and the lock file rename()d to it.
3151 int git_config_set_multivar_in_file_gently(const char *config_filename,
3152 const char *key, const char *value,
3153 const char *value_pattern,
3154 unsigned flags)
3156 int fd = -1, in_fd = -1;
3157 int ret;
3158 struct lock_file lock = LOCK_INIT;
3159 char *filename_buf = NULL;
3160 char *contents = NULL;
3161 size_t contents_sz;
3162 struct config_store_data store;
3164 memset(&store, 0, sizeof(store));
3166 /* parse-key returns negative; flip the sign to feed exit(3) */
3167 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
3168 if (ret)
3169 goto out_free;
3171 store.multi_replace = (flags & CONFIG_FLAGS_MULTI_REPLACE) != 0;
3173 if (!config_filename)
3174 config_filename = filename_buf = git_pathdup("config");
3177 * The lock serves a purpose in addition to locking: the new
3178 * contents of .git/config will be written into it.
3180 fd = hold_lock_file_for_update(&lock, config_filename, 0);
3181 if (fd < 0) {
3182 error_errno(_("could not lock config file %s"), config_filename);
3183 ret = CONFIG_NO_LOCK;
3184 goto out_free;
3188 * If .git/config does not exist yet, write a minimal version.
3190 in_fd = open(config_filename, O_RDONLY);
3191 if ( in_fd < 0 ) {
3192 if ( ENOENT != errno ) {
3193 error_errno(_("opening %s"), config_filename);
3194 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
3195 goto out_free;
3197 /* if nothing to unset, error out */
3198 if (!value) {
3199 ret = CONFIG_NOTHING_SET;
3200 goto out_free;
3203 free(store.key);
3204 store.key = xstrdup(key);
3205 if (write_section(fd, key, &store) < 0 ||
3206 write_pair(fd, key, value, &store) < 0)
3207 goto write_err_out;
3208 } else {
3209 struct stat st;
3210 size_t copy_begin, copy_end;
3211 int i, new_line = 0;
3212 struct config_options opts;
3214 if (!value_pattern)
3215 store.value_pattern = NULL;
3216 else if (value_pattern == CONFIG_REGEX_NONE)
3217 store.value_pattern = CONFIG_REGEX_NONE;
3218 else if (flags & CONFIG_FLAGS_FIXED_VALUE)
3219 store.fixed_value = value_pattern;
3220 else {
3221 if (value_pattern[0] == '!') {
3222 store.do_not_match = 1;
3223 value_pattern++;
3224 } else
3225 store.do_not_match = 0;
3227 store.value_pattern = (regex_t*)xmalloc(sizeof(regex_t));
3228 if (regcomp(store.value_pattern, value_pattern,
3229 REG_EXTENDED)) {
3230 error(_("invalid pattern: %s"), value_pattern);
3231 FREE_AND_NULL(store.value_pattern);
3232 ret = CONFIG_INVALID_PATTERN;
3233 goto out_free;
3237 ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
3238 store.parsed[0].end = 0;
3240 memset(&opts, 0, sizeof(opts));
3241 opts.event_fn = store_aux_event;
3242 opts.event_fn_data = &store;
3245 * After this, store.parsed will contain offsets of all the
3246 * parsed elements, and store.seen will contain a list of
3247 * matches, as indices into store.parsed.
3249 * As a side effect, we make sure to transform only a valid
3250 * existing config file.
3252 if (git_config_from_file_with_options(store_aux,
3253 config_filename,
3254 &store, &opts)) {
3255 error(_("invalid config file %s"), config_filename);
3256 ret = CONFIG_INVALID_FILE;
3257 goto out_free;
3260 /* if nothing to unset, or too many matches, error out */
3261 if ((store.seen_nr == 0 && value == NULL) ||
3262 (store.seen_nr > 1 && !store.multi_replace)) {
3263 ret = CONFIG_NOTHING_SET;
3264 goto out_free;
3267 if (fstat(in_fd, &st) == -1) {
3268 error_errno(_("fstat on %s failed"), config_filename);
3269 ret = CONFIG_INVALID_FILE;
3270 goto out_free;
3273 contents_sz = xsize_t(st.st_size);
3274 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
3275 MAP_PRIVATE, in_fd, 0);
3276 if (contents == MAP_FAILED) {
3277 if (errno == ENODEV && S_ISDIR(st.st_mode))
3278 errno = EISDIR;
3279 error_errno(_("unable to mmap '%s'%s"),
3280 config_filename, mmap_os_err());
3281 ret = CONFIG_INVALID_FILE;
3282 contents = NULL;
3283 goto out_free;
3285 close(in_fd);
3286 in_fd = -1;
3288 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3289 error_errno(_("chmod on %s failed"), get_lock_file_path(&lock));
3290 ret = CONFIG_NO_WRITE;
3291 goto out_free;
3294 if (store.seen_nr == 0) {
3295 if (!store.seen_alloc) {
3296 /* Did not see key nor section */
3297 ALLOC_GROW(store.seen, 1, store.seen_alloc);
3298 store.seen[0] = store.parsed_nr
3299 - !!store.parsed_nr;
3301 store.seen_nr = 1;
3304 for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
3305 size_t replace_end;
3306 int j = store.seen[i];
3308 new_line = 0;
3309 if (!store.key_seen) {
3310 copy_end = store.parsed[j].end;
3311 /* include '\n' when copying section header */
3312 if (copy_end > 0 && copy_end < contents_sz &&
3313 contents[copy_end - 1] != '\n' &&
3314 contents[copy_end] == '\n')
3315 copy_end++;
3316 replace_end = copy_end;
3317 } else {
3318 replace_end = store.parsed[j].end;
3319 copy_end = store.parsed[j].begin;
3320 if (!value)
3321 maybe_remove_section(&store,
3322 &copy_end,
3323 &replace_end, &i);
3325 * Swallow preceding white-space on the same
3326 * line.
3328 while (copy_end > 0 ) {
3329 char c = contents[copy_end - 1];
3331 if (isspace(c) && c != '\n')
3332 copy_end--;
3333 else
3334 break;
3338 if (copy_end > 0 && contents[copy_end-1] != '\n')
3339 new_line = 1;
3341 /* write the first part of the config */
3342 if (copy_end > copy_begin) {
3343 if (write_in_full(fd, contents + copy_begin,
3344 copy_end - copy_begin) < 0)
3345 goto write_err_out;
3346 if (new_line &&
3347 write_str_in_full(fd, "\n") < 0)
3348 goto write_err_out;
3350 copy_begin = replace_end;
3353 /* write the pair (value == NULL means unset) */
3354 if (value) {
3355 if (!store.section_seen) {
3356 if (write_section(fd, key, &store) < 0)
3357 goto write_err_out;
3359 if (write_pair(fd, key, value, &store) < 0)
3360 goto write_err_out;
3363 /* write the rest of the config */
3364 if (copy_begin < contents_sz)
3365 if (write_in_full(fd, contents + copy_begin,
3366 contents_sz - copy_begin) < 0)
3367 goto write_err_out;
3369 munmap(contents, contents_sz);
3370 contents = NULL;
3373 if (commit_lock_file(&lock) < 0) {
3374 error_errno(_("could not write config file %s"), config_filename);
3375 ret = CONFIG_NO_WRITE;
3376 goto out_free;
3379 ret = 0;
3381 /* Invalidate the config cache */
3382 git_config_clear();
3384 out_free:
3385 rollback_lock_file(&lock);
3386 free(filename_buf);
3387 if (contents)
3388 munmap(contents, contents_sz);
3389 if (in_fd >= 0)
3390 close(in_fd);
3391 config_store_data_clear(&store);
3392 return ret;
3394 write_err_out:
3395 ret = write_error(get_lock_file_path(&lock));
3396 goto out_free;
3400 void git_config_set_multivar_in_file(const char *config_filename,
3401 const char *key, const char *value,
3402 const char *value_pattern, unsigned flags)
3404 if (!git_config_set_multivar_in_file_gently(config_filename, key, value,
3405 value_pattern, flags))
3406 return;
3407 if (value)
3408 die(_("could not set '%s' to '%s'"), key, value);
3409 else
3410 die(_("could not unset '%s'"), key);
3413 int git_config_set_multivar_gently(const char *key, const char *value,
3414 const char *value_pattern, unsigned flags)
3416 return repo_config_set_multivar_gently(the_repository, key, value,
3417 value_pattern, flags);
3420 int repo_config_set_multivar_gently(struct repository *r, const char *key,
3421 const char *value,
3422 const char *value_pattern, unsigned flags)
3424 char *file = repo_git_path(r, "config");
3425 int res = git_config_set_multivar_in_file_gently(file,
3426 key, value,
3427 value_pattern,
3428 flags);
3429 free(file);
3430 return res;
3433 void git_config_set_multivar(const char *key, const char *value,
3434 const char *value_pattern, unsigned flags)
3436 git_config_set_multivar_in_file(git_path("config"),
3437 key, value, value_pattern,
3438 flags);
3441 static int section_name_match (const char *buf, const char *name)
3443 int i = 0, j = 0, dot = 0;
3444 if (buf[i] != '[')
3445 return 0;
3446 for (i = 1; buf[i] && buf[i] != ']'; i++) {
3447 if (!dot && isspace(buf[i])) {
3448 dot = 1;
3449 if (name[j++] != '.')
3450 break;
3451 for (i++; isspace(buf[i]); i++)
3452 ; /* do nothing */
3453 if (buf[i] != '"')
3454 break;
3455 continue;
3457 if (buf[i] == '\\' && dot)
3458 i++;
3459 else if (buf[i] == '"' && dot) {
3460 for (i++; isspace(buf[i]); i++)
3461 ; /* do_nothing */
3462 break;
3464 if (buf[i] != name[j++])
3465 break;
3467 if (buf[i] == ']' && name[j] == 0) {
3469 * We match, now just find the right length offset by
3470 * gobbling up any whitespace after it, as well
3472 i++;
3473 for (; buf[i] && isspace(buf[i]); i++)
3474 ; /* do nothing */
3475 return i;
3477 return 0;
3480 static int section_name_is_ok(const char *name)
3482 /* Empty section names are bogus. */
3483 if (!*name)
3484 return 0;
3487 * Before a dot, we must be alphanumeric or dash. After the first dot,
3488 * anything goes, so we can stop checking.
3490 for (; *name && *name != '.'; name++)
3491 if (*name != '-' && !isalnum(*name))
3492 return 0;
3493 return 1;
3496 /* if new_name == NULL, the section is removed instead */
3497 static int git_config_copy_or_rename_section_in_file(const char *config_filename,
3498 const char *old_name,
3499 const char *new_name, int copy)
3501 int ret = 0, remove = 0;
3502 char *filename_buf = NULL;
3503 struct lock_file lock = LOCK_INIT;
3504 int out_fd;
3505 char buf[1024];
3506 FILE *config_file = NULL;
3507 struct stat st;
3508 struct strbuf copystr = STRBUF_INIT;
3509 struct config_store_data store;
3511 memset(&store, 0, sizeof(store));
3513 if (new_name && !section_name_is_ok(new_name)) {
3514 ret = error(_("invalid section name: %s"), new_name);
3515 goto out_no_rollback;
3518 if (!config_filename)
3519 config_filename = filename_buf = git_pathdup("config");
3521 out_fd = hold_lock_file_for_update(&lock, config_filename, 0);
3522 if (out_fd < 0) {
3523 ret = error(_("could not lock config file %s"), config_filename);
3524 goto out;
3527 if (!(config_file = fopen(config_filename, "rb"))) {
3528 ret = warn_on_fopen_errors(config_filename);
3529 if (ret)
3530 goto out;
3531 /* no config file means nothing to rename, no error */
3532 goto commit_and_out;
3535 if (fstat(fileno(config_file), &st) == -1) {
3536 ret = error_errno(_("fstat on %s failed"), config_filename);
3537 goto out;
3540 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3541 ret = error_errno(_("chmod on %s failed"),
3542 get_lock_file_path(&lock));
3543 goto out;
3546 while (fgets(buf, sizeof(buf), config_file)) {
3547 unsigned i;
3548 int length;
3549 int is_section = 0;
3550 char *output = buf;
3551 for (i = 0; buf[i] && isspace(buf[i]); i++)
3552 ; /* do nothing */
3553 if (buf[i] == '[') {
3554 /* it's a section */
3555 int offset;
3556 is_section = 1;
3559 * When encountering a new section under -c we
3560 * need to flush out any section we're already
3561 * coping and begin anew. There might be
3562 * multiple [branch "$name"] sections.
3564 if (copystr.len > 0) {
3565 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3566 ret = write_error(get_lock_file_path(&lock));
3567 goto out;
3569 strbuf_reset(&copystr);
3572 offset = section_name_match(&buf[i], old_name);
3573 if (offset > 0) {
3574 ret++;
3575 if (!new_name) {
3576 remove = 1;
3577 continue;
3579 store.baselen = strlen(new_name);
3580 if (!copy) {
3581 if (write_section(out_fd, new_name, &store) < 0) {
3582 ret = write_error(get_lock_file_path(&lock));
3583 goto out;
3586 * We wrote out the new section, with
3587 * a newline, now skip the old
3588 * section's length
3590 output += offset + i;
3591 if (strlen(output) > 0) {
3593 * More content means there's
3594 * a declaration to put on the
3595 * next line; indent with a
3596 * tab
3598 output -= 1;
3599 output[0] = '\t';
3601 } else {
3602 copystr = store_create_section(new_name, &store);
3605 remove = 0;
3607 if (remove)
3608 continue;
3609 length = strlen(output);
3611 if (!is_section && copystr.len > 0) {
3612 strbuf_add(&copystr, output, length);
3615 if (write_in_full(out_fd, output, length) < 0) {
3616 ret = write_error(get_lock_file_path(&lock));
3617 goto out;
3622 * Copy a trailing section at the end of the config, won't be
3623 * flushed by the usual "flush because we have a new section
3624 * logic in the loop above.
3626 if (copystr.len > 0) {
3627 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3628 ret = write_error(get_lock_file_path(&lock));
3629 goto out;
3631 strbuf_reset(&copystr);
3634 fclose(config_file);
3635 config_file = NULL;
3636 commit_and_out:
3637 if (commit_lock_file(&lock) < 0)
3638 ret = error_errno(_("could not write config file %s"),
3639 config_filename);
3640 out:
3641 if (config_file)
3642 fclose(config_file);
3643 rollback_lock_file(&lock);
3644 out_no_rollback:
3645 free(filename_buf);
3646 config_store_data_clear(&store);
3647 return ret;
3650 int git_config_rename_section_in_file(const char *config_filename,
3651 const char *old_name, const char *new_name)
3653 return git_config_copy_or_rename_section_in_file(config_filename,
3654 old_name, new_name, 0);
3657 int git_config_rename_section(const char *old_name, const char *new_name)
3659 return git_config_rename_section_in_file(NULL, old_name, new_name);
3662 int git_config_copy_section_in_file(const char *config_filename,
3663 const char *old_name, const char *new_name)
3665 return git_config_copy_or_rename_section_in_file(config_filename,
3666 old_name, new_name, 1);
3669 int git_config_copy_section(const char *old_name, const char *new_name)
3671 return git_config_copy_section_in_file(NULL, old_name, new_name);
3675 * Call this to report error for your variable that should not
3676 * get a boolean value (i.e. "[my] var" means "true").
3678 #undef config_error_nonbool
3679 int config_error_nonbool(const char *var)
3681 return error(_("missing value for '%s'"), var);
3684 int parse_config_key(const char *var,
3685 const char *section,
3686 const char **subsection, size_t *subsection_len,
3687 const char **key)
3689 const char *dot;
3691 /* Does it start with "section." ? */
3692 if (!skip_prefix(var, section, &var) || *var != '.')
3693 return -1;
3696 * Find the key; we don't know yet if we have a subsection, but we must
3697 * parse backwards from the end, since the subsection may have dots in
3698 * it, too.
3700 dot = strrchr(var, '.');
3701 *key = dot + 1;
3703 /* Did we have a subsection at all? */
3704 if (dot == var) {
3705 if (subsection) {
3706 *subsection = NULL;
3707 *subsection_len = 0;
3710 else {
3711 if (!subsection)
3712 return -1;
3713 *subsection = var + 1;
3714 *subsection_len = dot - *subsection;
3717 return 0;
3720 const char *current_config_origin_type(void)
3722 int type;
3723 if (current_config_kvi)
3724 type = current_config_kvi->origin_type;
3725 else if(cf)
3726 type = cf->origin_type;
3727 else
3728 BUG("current_config_origin_type called outside config callback");
3730 switch (type) {
3731 case CONFIG_ORIGIN_BLOB:
3732 return "blob";
3733 case CONFIG_ORIGIN_FILE:
3734 return "file";
3735 case CONFIG_ORIGIN_STDIN:
3736 return "standard input";
3737 case CONFIG_ORIGIN_SUBMODULE_BLOB:
3738 return "submodule-blob";
3739 case CONFIG_ORIGIN_CMDLINE:
3740 return "command line";
3741 default:
3742 BUG("unknown config origin type");
3746 const char *config_scope_name(enum config_scope scope)
3748 switch (scope) {
3749 case CONFIG_SCOPE_SYSTEM:
3750 return "system";
3751 case CONFIG_SCOPE_GLOBAL:
3752 return "global";
3753 case CONFIG_SCOPE_LOCAL:
3754 return "local";
3755 case CONFIG_SCOPE_WORKTREE:
3756 return "worktree";
3757 case CONFIG_SCOPE_COMMAND:
3758 return "command";
3759 case CONFIG_SCOPE_SUBMODULE:
3760 return "submodule";
3761 default:
3762 return "unknown";
3766 const char *current_config_name(void)
3768 const char *name;
3769 if (current_config_kvi)
3770 name = current_config_kvi->filename;
3771 else if (cf)
3772 name = cf->name;
3773 else
3774 BUG("current_config_name called outside config callback");
3775 return name ? name : "";
3778 enum config_scope current_config_scope(void)
3780 if (current_config_kvi)
3781 return current_config_kvi->scope;
3782 else
3783 return current_parsing_scope;
3786 int current_config_line(void)
3788 if (current_config_kvi)
3789 return current_config_kvi->linenr;
3790 else
3791 return cf->linenr;
3794 int lookup_config(const char **mapping, int nr_mapping, const char *var)
3796 int i;
3798 for (i = 0; i < nr_mapping; i++) {
3799 const char *name = mapping[i];
3801 if (name && !strcasecmp(var, name))
3802 return i;
3804 return -1;