Git 2.39.4
[git.git] / config.c
blob85b37f2ee09d0a8a1491fa95c66e26411899568d
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;
85 * Config that comes from trusted scopes, namely:
86 * - CONFIG_SCOPE_SYSTEM (e.g. /etc/gitconfig)
87 * - CONFIG_SCOPE_GLOBAL (e.g. $HOME/.gitconfig, $XDG_CONFIG_HOME/git)
88 * - CONFIG_SCOPE_COMMAND (e.g. "-c" option, environment variables)
90 * This is declared here for code cleanliness, but unlike the other
91 * static variables, this does not hold config parser state.
93 static struct config_set protected_config;
95 static int config_file_fgetc(struct config_source *conf)
97 return getc_unlocked(conf->u.file);
100 static int config_file_ungetc(int c, struct config_source *conf)
102 return ungetc(c, conf->u.file);
105 static long config_file_ftell(struct config_source *conf)
107 return ftell(conf->u.file);
111 static int config_buf_fgetc(struct config_source *conf)
113 if (conf->u.buf.pos < conf->u.buf.len)
114 return conf->u.buf.buf[conf->u.buf.pos++];
116 return EOF;
119 static int config_buf_ungetc(int c, struct config_source *conf)
121 if (conf->u.buf.pos > 0) {
122 conf->u.buf.pos--;
123 if (conf->u.buf.buf[conf->u.buf.pos] != c)
124 BUG("config_buf can only ungetc the same character");
125 return c;
128 return EOF;
131 static long config_buf_ftell(struct config_source *conf)
133 return conf->u.buf.pos;
136 struct config_include_data {
137 int depth;
138 config_fn_t fn;
139 void *data;
140 const struct config_options *opts;
141 struct git_config_source *config_source;
144 * All remote URLs discovered when reading all config files.
146 struct string_list *remote_urls;
148 #define CONFIG_INCLUDE_INIT { 0 }
150 static int git_config_include(const char *var, const char *value, void *data);
152 #define MAX_INCLUDE_DEPTH 10
153 static const char include_depth_advice[] = N_(
154 "exceeded maximum include depth (%d) while including\n"
155 " %s\n"
156 "from\n"
157 " %s\n"
158 "This might be due to circular includes.");
159 static int handle_path_include(const char *path, struct config_include_data *inc)
161 int ret = 0;
162 struct strbuf buf = STRBUF_INIT;
163 char *expanded;
165 if (!path)
166 return config_error_nonbool("include.path");
168 expanded = interpolate_path(path, 0);
169 if (!expanded)
170 return error(_("could not expand include path '%s'"), path);
171 path = expanded;
174 * Use an absolute path as-is, but interpret relative paths
175 * based on the including config file.
177 if (!is_absolute_path(path)) {
178 char *slash;
180 if (!cf || !cf->path) {
181 ret = error(_("relative config includes must come from files"));
182 goto cleanup;
185 slash = find_last_dir_sep(cf->path);
186 if (slash)
187 strbuf_add(&buf, cf->path, slash - cf->path + 1);
188 strbuf_addstr(&buf, path);
189 path = buf.buf;
192 if (!access_or_die(path, R_OK, 0)) {
193 if (++inc->depth > MAX_INCLUDE_DEPTH)
194 die(_(include_depth_advice), MAX_INCLUDE_DEPTH, path,
195 !cf ? "<unknown>" :
196 cf->name ? cf->name :
197 "the command line");
198 ret = git_config_from_file(git_config_include, path, inc);
199 inc->depth--;
201 cleanup:
202 strbuf_release(&buf);
203 free(expanded);
204 return ret;
207 static void add_trailing_starstar_for_dir(struct strbuf *pat)
209 if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
210 strbuf_addstr(pat, "**");
213 static int prepare_include_condition_pattern(struct strbuf *pat)
215 struct strbuf path = STRBUF_INIT;
216 char *expanded;
217 int prefix = 0;
219 expanded = interpolate_path(pat->buf, 1);
220 if (expanded) {
221 strbuf_reset(pat);
222 strbuf_addstr(pat, expanded);
223 free(expanded);
226 if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
227 const char *slash;
229 if (!cf || !cf->path)
230 return error(_("relative config include "
231 "conditionals must come from files"));
233 strbuf_realpath(&path, cf->path, 1);
234 slash = find_last_dir_sep(path.buf);
235 if (!slash)
236 BUG("how is this possible?");
237 strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
238 prefix = slash - path.buf + 1 /* slash */;
239 } else if (!is_absolute_path(pat->buf))
240 strbuf_insertstr(pat, 0, "**/");
242 add_trailing_starstar_for_dir(pat);
244 strbuf_release(&path);
245 return prefix;
248 static int include_by_gitdir(const struct config_options *opts,
249 const char *cond, size_t cond_len, int icase)
251 struct strbuf text = STRBUF_INIT;
252 struct strbuf pattern = STRBUF_INIT;
253 int ret = 0, prefix;
254 const char *git_dir;
255 int already_tried_absolute = 0;
257 if (opts->git_dir)
258 git_dir = opts->git_dir;
259 else
260 goto done;
262 strbuf_realpath(&text, git_dir, 1);
263 strbuf_add(&pattern, cond, cond_len);
264 prefix = prepare_include_condition_pattern(&pattern);
266 again:
267 if (prefix < 0)
268 goto done;
270 if (prefix > 0) {
272 * perform literal matching on the prefix part so that
273 * any wildcard character in it can't create side effects.
275 if (text.len < prefix)
276 goto done;
277 if (!icase && strncmp(pattern.buf, text.buf, prefix))
278 goto done;
279 if (icase && strncasecmp(pattern.buf, text.buf, prefix))
280 goto done;
283 ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
284 WM_PATHNAME | (icase ? WM_CASEFOLD : 0));
286 if (!ret && !already_tried_absolute) {
288 * We've tried e.g. matching gitdir:~/work, but if
289 * ~/work is a symlink to /mnt/storage/work
290 * strbuf_realpath() will expand it, so the rule won't
291 * match. Let's match against a
292 * strbuf_add_absolute_path() version of the path,
293 * which'll do the right thing
295 strbuf_reset(&text);
296 strbuf_add_absolute_path(&text, git_dir);
297 already_tried_absolute = 1;
298 goto again;
300 done:
301 strbuf_release(&pattern);
302 strbuf_release(&text);
303 return ret;
306 static int include_by_branch(const char *cond, size_t cond_len)
308 int flags;
309 int ret;
310 struct strbuf pattern = STRBUF_INIT;
311 const char *refname = !the_repository->gitdir ?
312 NULL : resolve_ref_unsafe("HEAD", 0, NULL, &flags);
313 const char *shortname;
315 if (!refname || !(flags & REF_ISSYMREF) ||
316 !skip_prefix(refname, "refs/heads/", &shortname))
317 return 0;
319 strbuf_add(&pattern, cond, cond_len);
320 add_trailing_starstar_for_dir(&pattern);
321 ret = !wildmatch(pattern.buf, shortname, WM_PATHNAME);
322 strbuf_release(&pattern);
323 return ret;
326 static int add_remote_url(const char *var, const char *value, void *data)
328 struct string_list *remote_urls = data;
329 const char *remote_name;
330 size_t remote_name_len;
331 const char *key;
333 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
334 &key) &&
335 remote_name &&
336 !strcmp(key, "url"))
337 string_list_append(remote_urls, value);
338 return 0;
341 static void populate_remote_urls(struct config_include_data *inc)
343 struct config_options opts;
345 struct config_source *store_cf = cf;
346 struct key_value_info *store_kvi = current_config_kvi;
347 enum config_scope store_scope = current_parsing_scope;
349 opts = *inc->opts;
350 opts.unconditional_remote_url = 1;
352 cf = NULL;
353 current_config_kvi = NULL;
354 current_parsing_scope = 0;
356 inc->remote_urls = xmalloc(sizeof(*inc->remote_urls));
357 string_list_init_dup(inc->remote_urls);
358 config_with_options(add_remote_url, inc->remote_urls, inc->config_source, &opts);
360 cf = store_cf;
361 current_config_kvi = store_kvi;
362 current_parsing_scope = store_scope;
365 static int forbid_remote_url(const char *var, const char *value UNUSED,
366 void *data UNUSED)
368 const char *remote_name;
369 size_t remote_name_len;
370 const char *key;
372 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
373 &key) &&
374 remote_name &&
375 !strcmp(key, "url"))
376 die(_("remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"));
377 return 0;
380 static int at_least_one_url_matches_glob(const char *glob, int glob_len,
381 struct string_list *remote_urls)
383 struct strbuf pattern = STRBUF_INIT;
384 struct string_list_item *url_item;
385 int found = 0;
387 strbuf_add(&pattern, glob, glob_len);
388 for_each_string_list_item(url_item, remote_urls) {
389 if (!wildmatch(pattern.buf, url_item->string, WM_PATHNAME)) {
390 found = 1;
391 break;
394 strbuf_release(&pattern);
395 return found;
398 static int include_by_remote_url(struct config_include_data *inc,
399 const char *cond, size_t cond_len)
401 if (inc->opts->unconditional_remote_url)
402 return 1;
403 if (!inc->remote_urls)
404 populate_remote_urls(inc);
405 return at_least_one_url_matches_glob(cond, cond_len,
406 inc->remote_urls);
409 static int include_condition_is_true(struct config_include_data *inc,
410 const char *cond, size_t cond_len)
412 const struct config_options *opts = inc->opts;
414 if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
415 return include_by_gitdir(opts, cond, cond_len, 0);
416 else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
417 return include_by_gitdir(opts, cond, cond_len, 1);
418 else if (skip_prefix_mem(cond, cond_len, "onbranch:", &cond, &cond_len))
419 return include_by_branch(cond, cond_len);
420 else if (skip_prefix_mem(cond, cond_len, "hasconfig:remote.*.url:", &cond,
421 &cond_len))
422 return include_by_remote_url(inc, cond, cond_len);
424 /* unknown conditionals are always false */
425 return 0;
428 static int git_config_include(const char *var, const char *value, void *data)
430 struct config_include_data *inc = data;
431 const char *cond, *key;
432 size_t cond_len;
433 int ret;
436 * Pass along all values, including "include" directives; this makes it
437 * possible to query information on the includes themselves.
439 ret = inc->fn(var, value, inc->data);
440 if (ret < 0)
441 return ret;
443 if (!strcmp(var, "include.path"))
444 ret = handle_path_include(value, inc);
446 if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
447 cond && include_condition_is_true(inc, cond, cond_len) &&
448 !strcmp(key, "path")) {
449 config_fn_t old_fn = inc->fn;
451 if (inc->opts->unconditional_remote_url)
452 inc->fn = forbid_remote_url;
453 ret = handle_path_include(value, inc);
454 inc->fn = old_fn;
457 return ret;
460 static void git_config_push_split_parameter(const char *key, const char *value)
462 struct strbuf env = STRBUF_INIT;
463 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
464 if (old && *old) {
465 strbuf_addstr(&env, old);
466 strbuf_addch(&env, ' ');
468 sq_quote_buf(&env, key);
469 strbuf_addch(&env, '=');
470 if (value)
471 sq_quote_buf(&env, value);
472 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
473 strbuf_release(&env);
476 void git_config_push_parameter(const char *text)
478 const char *value;
481 * When we see:
483 * section.subsection=with=equals.key=value
485 * we cannot tell if it means:
487 * [section "subsection=with=equals"]
488 * key = value
490 * or:
492 * [section]
493 * subsection = with=equals.key=value
495 * We parse left-to-right for the first "=", meaning we'll prefer to
496 * keep the value intact over the subsection. This is historical, but
497 * also sensible since values are more likely to contain odd or
498 * untrusted input than a section name.
500 * A missing equals is explicitly allowed (as a bool-only entry).
502 value = strchr(text, '=');
503 if (value) {
504 char *key = xmemdupz(text, value - text);
505 git_config_push_split_parameter(key, value + 1);
506 free(key);
507 } else {
508 git_config_push_split_parameter(text, NULL);
512 void git_config_push_env(const char *spec)
514 char *key;
515 const char *env_name;
516 const char *env_value;
518 env_name = strrchr(spec, '=');
519 if (!env_name)
520 die(_("invalid config format: %s"), spec);
521 key = xmemdupz(spec, env_name - spec);
522 env_name++;
523 if (!*env_name)
524 die(_("missing environment variable name for configuration '%.*s'"),
525 (int)(env_name - spec - 1), spec);
527 env_value = getenv(env_name);
528 if (!env_value)
529 die(_("missing environment variable '%s' for configuration '%.*s'"),
530 env_name, (int)(env_name - spec - 1), spec);
532 git_config_push_split_parameter(key, env_value);
533 free(key);
536 static inline int iskeychar(int c)
538 return isalnum(c) || c == '-';
542 * Auxiliary function to sanity-check and split the key into the section
543 * identifier and variable name.
545 * Returns 0 on success, -1 when there is an invalid character in the key and
546 * -2 if there is no section name in the key.
548 * store_key - pointer to char* which will hold a copy of the key with
549 * lowercase section and variable name
550 * baselen - pointer to size_t which will hold the length of the
551 * section + subsection part, can be NULL
553 int git_config_parse_key(const char *key, char **store_key, size_t *baselen_)
555 size_t i, baselen;
556 int dot;
557 const char *last_dot = strrchr(key, '.');
560 * Since "key" actually contains the section name and the real
561 * key name separated by a dot, we have to know where the dot is.
564 if (last_dot == NULL || last_dot == key) {
565 error(_("key does not contain a section: %s"), key);
566 return -CONFIG_NO_SECTION_OR_NAME;
569 if (!last_dot[1]) {
570 error(_("key does not contain variable name: %s"), key);
571 return -CONFIG_NO_SECTION_OR_NAME;
574 baselen = last_dot - key;
575 if (baselen_)
576 *baselen_ = baselen;
579 * Validate the key and while at it, lower case it for matching.
581 *store_key = xmallocz(strlen(key));
583 dot = 0;
584 for (i = 0; key[i]; i++) {
585 unsigned char c = key[i];
586 if (c == '.')
587 dot = 1;
588 /* Leave the extended basename untouched.. */
589 if (!dot || i > baselen) {
590 if (!iskeychar(c) ||
591 (i == baselen + 1 && !isalpha(c))) {
592 error(_("invalid key: %s"), key);
593 goto out_free_ret_1;
595 c = tolower(c);
596 } else if (c == '\n') {
597 error(_("invalid key (newline): %s"), key);
598 goto out_free_ret_1;
600 (*store_key)[i] = c;
603 return 0;
605 out_free_ret_1:
606 FREE_AND_NULL(*store_key);
607 return -CONFIG_INVALID_KEY;
610 static int config_parse_pair(const char *key, const char *value,
611 config_fn_t fn, void *data)
613 char *canonical_name;
614 int ret;
616 if (!strlen(key))
617 return error(_("empty config key"));
618 if (git_config_parse_key(key, &canonical_name, NULL))
619 return -1;
621 ret = (fn(canonical_name, value, data) < 0) ? -1 : 0;
622 free(canonical_name);
623 return ret;
626 int git_config_parse_parameter(const char *text,
627 config_fn_t fn, void *data)
629 const char *value;
630 struct strbuf **pair;
631 int ret;
633 pair = strbuf_split_str(text, '=', 2);
634 if (!pair[0])
635 return error(_("bogus config parameter: %s"), text);
637 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
638 strbuf_setlen(pair[0], pair[0]->len - 1);
639 value = pair[1] ? pair[1]->buf : "";
640 } else {
641 value = NULL;
644 strbuf_trim(pair[0]);
645 if (!pair[0]->len) {
646 strbuf_list_free(pair);
647 return error(_("bogus config parameter: %s"), text);
650 ret = config_parse_pair(pair[0]->buf, value, fn, data);
651 strbuf_list_free(pair);
652 return ret;
655 static int parse_config_env_list(char *env, config_fn_t fn, void *data)
657 char *cur = env;
658 while (cur && *cur) {
659 const char *key = sq_dequote_step(cur, &cur);
660 if (!key)
661 return error(_("bogus format in %s"),
662 CONFIG_DATA_ENVIRONMENT);
664 if (!cur || isspace(*cur)) {
665 /* old-style 'key=value' */
666 if (git_config_parse_parameter(key, fn, data) < 0)
667 return -1;
669 else if (*cur == '=') {
670 /* new-style 'key'='value' */
671 const char *value;
673 cur++;
674 if (*cur == '\'') {
675 /* quoted value */
676 value = sq_dequote_step(cur, &cur);
677 if (!value || (cur && !isspace(*cur))) {
678 return error(_("bogus format in %s"),
679 CONFIG_DATA_ENVIRONMENT);
681 } else if (!*cur || isspace(*cur)) {
682 /* implicit bool: 'key'= */
683 value = NULL;
684 } else {
685 return error(_("bogus format in %s"),
686 CONFIG_DATA_ENVIRONMENT);
689 if (config_parse_pair(key, value, fn, data) < 0)
690 return -1;
692 else {
693 /* unknown format */
694 return error(_("bogus format in %s"),
695 CONFIG_DATA_ENVIRONMENT);
698 if (cur) {
699 while (isspace(*cur))
700 cur++;
703 return 0;
706 int git_config_from_parameters(config_fn_t fn, void *data)
708 const char *env;
709 struct strbuf envvar = STRBUF_INIT;
710 struct strvec to_free = STRVEC_INIT;
711 int ret = 0;
712 char *envw = NULL;
713 struct config_source source;
715 memset(&source, 0, sizeof(source));
716 source.prev = cf;
717 source.origin_type = CONFIG_ORIGIN_CMDLINE;
718 cf = &source;
720 env = getenv(CONFIG_COUNT_ENVIRONMENT);
721 if (env) {
722 unsigned long count;
723 char *endp;
724 int i;
726 count = strtoul(env, &endp, 10);
727 if (*endp) {
728 ret = error(_("bogus count in %s"), CONFIG_COUNT_ENVIRONMENT);
729 goto out;
731 if (count > INT_MAX) {
732 ret = error(_("too many entries in %s"), CONFIG_COUNT_ENVIRONMENT);
733 goto out;
736 for (i = 0; i < count; i++) {
737 const char *key, *value;
739 strbuf_addf(&envvar, "GIT_CONFIG_KEY_%d", i);
740 key = getenv_safe(&to_free, envvar.buf);
741 if (!key) {
742 ret = error(_("missing config key %s"), envvar.buf);
743 goto out;
745 strbuf_reset(&envvar);
747 strbuf_addf(&envvar, "GIT_CONFIG_VALUE_%d", i);
748 value = getenv_safe(&to_free, envvar.buf);
749 if (!value) {
750 ret = error(_("missing config value %s"), envvar.buf);
751 goto out;
753 strbuf_reset(&envvar);
755 if (config_parse_pair(key, value, fn, data) < 0) {
756 ret = -1;
757 goto out;
762 env = getenv(CONFIG_DATA_ENVIRONMENT);
763 if (env) {
764 /* sq_dequote will write over it */
765 envw = xstrdup(env);
766 if (parse_config_env_list(envw, fn, data) < 0) {
767 ret = -1;
768 goto out;
772 out:
773 strbuf_release(&envvar);
774 strvec_clear(&to_free);
775 free(envw);
776 cf = source.prev;
777 return ret;
780 static int get_next_char(void)
782 int c = cf->do_fgetc(cf);
784 if (c == '\r') {
785 /* DOS like systems */
786 c = cf->do_fgetc(cf);
787 if (c != '\n') {
788 if (c != EOF)
789 cf->do_ungetc(c, cf);
790 c = '\r';
794 if (c != EOF && ++cf->total_len > INT_MAX) {
796 * This is an absurdly long config file; refuse to parse
797 * further in order to protect downstream code from integer
798 * overflows. Note that we can't return an error specifically,
799 * but we can mark EOF and put trash in the return value,
800 * which will trigger a parse error.
802 cf->eof = 1;
803 return 0;
806 if (c == '\n')
807 cf->linenr++;
808 if (c == EOF) {
809 cf->eof = 1;
810 cf->linenr++;
811 c = '\n';
813 return c;
816 static char *parse_value(void)
818 int quote = 0, comment = 0, space = 0;
820 strbuf_reset(&cf->value);
821 for (;;) {
822 int c = get_next_char();
823 if (c == '\n') {
824 if (quote) {
825 cf->linenr--;
826 return NULL;
828 return cf->value.buf;
830 if (comment)
831 continue;
832 if (isspace(c) && !quote) {
833 if (cf->value.len)
834 space++;
835 continue;
837 if (!quote) {
838 if (c == ';' || c == '#') {
839 comment = 1;
840 continue;
843 for (; space; space--)
844 strbuf_addch(&cf->value, ' ');
845 if (c == '\\') {
846 c = get_next_char();
847 switch (c) {
848 case '\n':
849 continue;
850 case 't':
851 c = '\t';
852 break;
853 case 'b':
854 c = '\b';
855 break;
856 case 'n':
857 c = '\n';
858 break;
859 /* Some characters escape as themselves */
860 case '\\': case '"':
861 break;
862 /* Reject unknown escape sequences */
863 default:
864 return NULL;
866 strbuf_addch(&cf->value, c);
867 continue;
869 if (c == '"') {
870 quote = 1-quote;
871 continue;
873 strbuf_addch(&cf->value, c);
877 static int get_value(config_fn_t fn, void *data, struct strbuf *name)
879 int c;
880 char *value;
881 int ret;
883 /* Get the full name */
884 for (;;) {
885 c = get_next_char();
886 if (cf->eof)
887 break;
888 if (!iskeychar(c))
889 break;
890 strbuf_addch(name, tolower(c));
893 while (c == ' ' || c == '\t')
894 c = get_next_char();
896 value = NULL;
897 if (c != '\n') {
898 if (c != '=')
899 return -1;
900 value = parse_value();
901 if (!value)
902 return -1;
905 * We already consumed the \n, but we need linenr to point to
906 * the line we just parsed during the call to fn to get
907 * accurate line number in error messages.
909 cf->linenr--;
910 ret = fn(name->buf, value, data);
911 if (ret >= 0)
912 cf->linenr++;
913 return ret;
916 static int get_extended_base_var(struct strbuf *name, int c)
918 cf->subsection_case_sensitive = 0;
919 do {
920 if (c == '\n')
921 goto error_incomplete_line;
922 c = get_next_char();
923 } while (isspace(c));
925 /* We require the format to be '[base "extension"]' */
926 if (c != '"')
927 return -1;
928 strbuf_addch(name, '.');
930 for (;;) {
931 int c = get_next_char();
932 if (c == '\n')
933 goto error_incomplete_line;
934 if (c == '"')
935 break;
936 if (c == '\\') {
937 c = get_next_char();
938 if (c == '\n')
939 goto error_incomplete_line;
941 strbuf_addch(name, c);
944 /* Final ']' */
945 if (get_next_char() != ']')
946 return -1;
947 return 0;
948 error_incomplete_line:
949 cf->linenr--;
950 return -1;
953 static int get_base_var(struct strbuf *name)
955 cf->subsection_case_sensitive = 1;
956 for (;;) {
957 int c = get_next_char();
958 if (cf->eof)
959 return -1;
960 if (c == ']')
961 return 0;
962 if (isspace(c))
963 return get_extended_base_var(name, c);
964 if (!iskeychar(c) && c != '.')
965 return -1;
966 strbuf_addch(name, tolower(c));
970 struct parse_event_data {
971 enum config_event_t previous_type;
972 size_t previous_offset;
973 const struct config_options *opts;
976 static int do_event(enum config_event_t type, struct parse_event_data *data)
978 size_t offset;
980 if (!data->opts || !data->opts->event_fn)
981 return 0;
983 if (type == CONFIG_EVENT_WHITESPACE &&
984 data->previous_type == type)
985 return 0;
987 offset = cf->do_ftell(cf);
989 * At EOF, the parser always "inserts" an extra '\n', therefore
990 * the end offset of the event is the current file position, otherwise
991 * we will already have advanced to the next event.
993 if (type != CONFIG_EVENT_EOF)
994 offset--;
996 if (data->previous_type != CONFIG_EVENT_EOF &&
997 data->opts->event_fn(data->previous_type, data->previous_offset,
998 offset, data->opts->event_fn_data) < 0)
999 return -1;
1001 data->previous_type = type;
1002 data->previous_offset = offset;
1004 return 0;
1007 static int git_parse_source(config_fn_t fn, void *data,
1008 const struct config_options *opts)
1010 int comment = 0;
1011 size_t baselen = 0;
1012 struct strbuf *var = &cf->var;
1013 int error_return = 0;
1014 char *error_msg = NULL;
1016 /* U+FEFF Byte Order Mark in UTF8 */
1017 const char *bomptr = utf8_bom;
1019 /* For the parser event callback */
1020 struct parse_event_data event_data = {
1021 CONFIG_EVENT_EOF, 0, opts
1024 for (;;) {
1025 int c;
1027 c = get_next_char();
1028 if (bomptr && *bomptr) {
1029 /* We are at the file beginning; skip UTF8-encoded BOM
1030 * if present. Sane editors won't put this in on their
1031 * own, but e.g. Windows Notepad will do it happily. */
1032 if (c == (*bomptr & 0377)) {
1033 bomptr++;
1034 continue;
1035 } else {
1036 /* Do not tolerate partial BOM. */
1037 if (bomptr != utf8_bom)
1038 break;
1039 /* No BOM at file beginning. Cool. */
1040 bomptr = NULL;
1043 if (c == '\n') {
1044 if (cf->eof) {
1045 if (do_event(CONFIG_EVENT_EOF, &event_data) < 0)
1046 return -1;
1047 return 0;
1049 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1050 return -1;
1051 comment = 0;
1052 continue;
1054 if (comment)
1055 continue;
1056 if (isspace(c)) {
1057 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1058 return -1;
1059 continue;
1061 if (c == '#' || c == ';') {
1062 if (do_event(CONFIG_EVENT_COMMENT, &event_data) < 0)
1063 return -1;
1064 comment = 1;
1065 continue;
1067 if (c == '[') {
1068 if (do_event(CONFIG_EVENT_SECTION, &event_data) < 0)
1069 return -1;
1071 /* Reset prior to determining a new stem */
1072 strbuf_reset(var);
1073 if (get_base_var(var) < 0 || var->len < 1)
1074 break;
1075 strbuf_addch(var, '.');
1076 baselen = var->len;
1077 continue;
1079 if (!isalpha(c))
1080 break;
1082 if (do_event(CONFIG_EVENT_ENTRY, &event_data) < 0)
1083 return -1;
1086 * Truncate the var name back to the section header
1087 * stem prior to grabbing the suffix part of the name
1088 * and the value.
1090 strbuf_setlen(var, baselen);
1091 strbuf_addch(var, tolower(c));
1092 if (get_value(fn, data, var) < 0)
1093 break;
1096 if (do_event(CONFIG_EVENT_ERROR, &event_data) < 0)
1097 return -1;
1099 switch (cf->origin_type) {
1100 case CONFIG_ORIGIN_BLOB:
1101 error_msg = xstrfmt(_("bad config line %d in blob %s"),
1102 cf->linenr, cf->name);
1103 break;
1104 case CONFIG_ORIGIN_FILE:
1105 error_msg = xstrfmt(_("bad config line %d in file %s"),
1106 cf->linenr, cf->name);
1107 break;
1108 case CONFIG_ORIGIN_STDIN:
1109 error_msg = xstrfmt(_("bad config line %d in standard input"),
1110 cf->linenr);
1111 break;
1112 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1113 error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
1114 cf->linenr, cf->name);
1115 break;
1116 case CONFIG_ORIGIN_CMDLINE:
1117 error_msg = xstrfmt(_("bad config line %d in command line %s"),
1118 cf->linenr, cf->name);
1119 break;
1120 default:
1121 error_msg = xstrfmt(_("bad config line %d in %s"),
1122 cf->linenr, cf->name);
1125 switch (opts && opts->error_action ?
1126 opts->error_action :
1127 cf->default_error_action) {
1128 case CONFIG_ERROR_DIE:
1129 die("%s", error_msg);
1130 break;
1131 case CONFIG_ERROR_ERROR:
1132 error_return = error("%s", error_msg);
1133 break;
1134 case CONFIG_ERROR_SILENT:
1135 error_return = -1;
1136 break;
1137 case CONFIG_ERROR_UNSET:
1138 BUG("config error action unset");
1141 free(error_msg);
1142 return error_return;
1145 static uintmax_t get_unit_factor(const char *end)
1147 if (!*end)
1148 return 1;
1149 else if (!strcasecmp(end, "k"))
1150 return 1024;
1151 else if (!strcasecmp(end, "m"))
1152 return 1024 * 1024;
1153 else if (!strcasecmp(end, "g"))
1154 return 1024 * 1024 * 1024;
1155 return 0;
1158 static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
1160 if (value && *value) {
1161 char *end;
1162 intmax_t val;
1163 intmax_t factor;
1165 if (max < 0)
1166 BUG("max must be a positive integer");
1168 errno = 0;
1169 val = strtoimax(value, &end, 0);
1170 if (errno == ERANGE)
1171 return 0;
1172 if (end == value) {
1173 errno = EINVAL;
1174 return 0;
1176 factor = get_unit_factor(end);
1177 if (!factor) {
1178 errno = EINVAL;
1179 return 0;
1181 if ((val < 0 && -max / factor > val) ||
1182 (val > 0 && max / factor < val)) {
1183 errno = ERANGE;
1184 return 0;
1186 val *= factor;
1187 *ret = val;
1188 return 1;
1190 errno = EINVAL;
1191 return 0;
1194 static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
1196 if (value && *value) {
1197 char *end;
1198 uintmax_t val;
1199 uintmax_t factor;
1201 /* negative values would be accepted by strtoumax */
1202 if (strchr(value, '-')) {
1203 errno = EINVAL;
1204 return 0;
1206 errno = 0;
1207 val = strtoumax(value, &end, 0);
1208 if (errno == ERANGE)
1209 return 0;
1210 if (end == value) {
1211 errno = EINVAL;
1212 return 0;
1214 factor = get_unit_factor(end);
1215 if (!factor) {
1216 errno = EINVAL;
1217 return 0;
1219 if (unsigned_mult_overflows(factor, val) ||
1220 factor * val > max) {
1221 errno = ERANGE;
1222 return 0;
1224 val *= factor;
1225 *ret = val;
1226 return 1;
1228 errno = EINVAL;
1229 return 0;
1232 int git_parse_int(const char *value, int *ret)
1234 intmax_t tmp;
1235 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
1236 return 0;
1237 *ret = tmp;
1238 return 1;
1241 static int git_parse_int64(const char *value, int64_t *ret)
1243 intmax_t tmp;
1244 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
1245 return 0;
1246 *ret = tmp;
1247 return 1;
1250 int git_parse_ulong(const char *value, unsigned long *ret)
1252 uintmax_t tmp;
1253 if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
1254 return 0;
1255 *ret = tmp;
1256 return 1;
1259 int git_parse_ssize_t(const char *value, ssize_t *ret)
1261 intmax_t tmp;
1262 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(ssize_t)))
1263 return 0;
1264 *ret = tmp;
1265 return 1;
1268 NORETURN
1269 static void die_bad_number(const char *name, const char *value)
1271 const char *error_type = (errno == ERANGE) ?
1272 N_("out of range") : N_("invalid unit");
1273 const char *bad_numeric = N_("bad numeric config value '%s' for '%s': %s");
1275 if (!value)
1276 value = "";
1278 if (!(cf && cf->name))
1279 die(_(bad_numeric), value, name, _(error_type));
1281 switch (cf->origin_type) {
1282 case CONFIG_ORIGIN_BLOB:
1283 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
1284 value, name, cf->name, _(error_type));
1285 case CONFIG_ORIGIN_FILE:
1286 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
1287 value, name, cf->name, _(error_type));
1288 case CONFIG_ORIGIN_STDIN:
1289 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
1290 value, name, _(error_type));
1291 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1292 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
1293 value, name, cf->name, _(error_type));
1294 case CONFIG_ORIGIN_CMDLINE:
1295 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
1296 value, name, cf->name, _(error_type));
1297 default:
1298 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
1299 value, name, cf->name, _(error_type));
1303 int git_config_int(const char *name, const char *value)
1305 int ret;
1306 if (!git_parse_int(value, &ret))
1307 die_bad_number(name, value);
1308 return ret;
1311 int64_t git_config_int64(const char *name, const char *value)
1313 int64_t ret;
1314 if (!git_parse_int64(value, &ret))
1315 die_bad_number(name, value);
1316 return ret;
1319 unsigned long git_config_ulong(const char *name, const char *value)
1321 unsigned long ret;
1322 if (!git_parse_ulong(value, &ret))
1323 die_bad_number(name, value);
1324 return ret;
1327 ssize_t git_config_ssize_t(const char *name, const char *value)
1329 ssize_t ret;
1330 if (!git_parse_ssize_t(value, &ret))
1331 die_bad_number(name, value);
1332 return ret;
1335 static int git_parse_maybe_bool_text(const char *value)
1337 if (!value)
1338 return 1;
1339 if (!*value)
1340 return 0;
1341 if (!strcasecmp(value, "true")
1342 || !strcasecmp(value, "yes")
1343 || !strcasecmp(value, "on"))
1344 return 1;
1345 if (!strcasecmp(value, "false")
1346 || !strcasecmp(value, "no")
1347 || !strcasecmp(value, "off"))
1348 return 0;
1349 return -1;
1352 static const struct fsync_component_name {
1353 const char *name;
1354 enum fsync_component component_bits;
1355 } fsync_component_names[] = {
1356 { "loose-object", FSYNC_COMPONENT_LOOSE_OBJECT },
1357 { "pack", FSYNC_COMPONENT_PACK },
1358 { "pack-metadata", FSYNC_COMPONENT_PACK_METADATA },
1359 { "commit-graph", FSYNC_COMPONENT_COMMIT_GRAPH },
1360 { "index", FSYNC_COMPONENT_INDEX },
1361 { "objects", FSYNC_COMPONENTS_OBJECTS },
1362 { "reference", FSYNC_COMPONENT_REFERENCE },
1363 { "derived-metadata", FSYNC_COMPONENTS_DERIVED_METADATA },
1364 { "committed", FSYNC_COMPONENTS_COMMITTED },
1365 { "added", FSYNC_COMPONENTS_ADDED },
1366 { "all", FSYNC_COMPONENTS_ALL },
1369 static enum fsync_component parse_fsync_components(const char *var, const char *string)
1371 enum fsync_component current = FSYNC_COMPONENTS_PLATFORM_DEFAULT;
1372 enum fsync_component positive = 0, negative = 0;
1374 while (string) {
1375 int i;
1376 size_t len;
1377 const char *ep;
1378 int negated = 0;
1379 int found = 0;
1381 string = string + strspn(string, ", \t\n\r");
1382 ep = strchrnul(string, ',');
1383 len = ep - string;
1384 if (!strcmp(string, "none")) {
1385 current = FSYNC_COMPONENT_NONE;
1386 goto next_name;
1389 if (*string == '-') {
1390 negated = 1;
1391 string++;
1392 len--;
1393 if (!len)
1394 warning(_("invalid value for variable %s"), var);
1397 if (!len)
1398 break;
1400 for (i = 0; i < ARRAY_SIZE(fsync_component_names); ++i) {
1401 const struct fsync_component_name *n = &fsync_component_names[i];
1403 if (strncmp(n->name, string, len))
1404 continue;
1406 found = 1;
1407 if (negated)
1408 negative |= n->component_bits;
1409 else
1410 positive |= n->component_bits;
1413 if (!found) {
1414 char *component = xstrndup(string, len);
1415 warning(_("ignoring unknown core.fsync component '%s'"), component);
1416 free(component);
1419 next_name:
1420 string = ep;
1423 return (current & ~negative) | positive;
1426 int git_parse_maybe_bool(const char *value)
1428 int v = git_parse_maybe_bool_text(value);
1429 if (0 <= v)
1430 return v;
1431 if (git_parse_int(value, &v))
1432 return !!v;
1433 return -1;
1436 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
1438 int v = git_parse_maybe_bool_text(value);
1439 if (0 <= v) {
1440 *is_bool = 1;
1441 return v;
1443 *is_bool = 0;
1444 return git_config_int(name, value);
1447 int git_config_bool(const char *name, const char *value)
1449 int v = git_parse_maybe_bool(value);
1450 if (v < 0)
1451 die(_("bad boolean config value '%s' for '%s'"), value, name);
1452 return v;
1455 int git_config_string(const char **dest, const char *var, const char *value)
1457 if (!value)
1458 return config_error_nonbool(var);
1459 *dest = xstrdup(value);
1460 return 0;
1463 int git_config_pathname(const char **dest, const char *var, const char *value)
1465 if (!value)
1466 return config_error_nonbool(var);
1467 *dest = interpolate_path(value, 0);
1468 if (!*dest)
1469 die(_("failed to expand user dir in: '%s'"), value);
1470 return 0;
1473 int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1475 if (!value)
1476 return config_error_nonbool(var);
1477 if (parse_expiry_date(value, timestamp))
1478 return error(_("'%s' for '%s' is not a valid timestamp"),
1479 value, var);
1480 return 0;
1483 int git_config_color(char *dest, const char *var, const char *value)
1485 if (!value)
1486 return config_error_nonbool(var);
1487 if (color_parse(value, dest) < 0)
1488 return -1;
1489 return 0;
1492 static int git_default_core_config(const char *var, const char *value, void *cb)
1494 /* This needs a better name */
1495 if (!strcmp(var, "core.filemode")) {
1496 trust_executable_bit = git_config_bool(var, value);
1497 return 0;
1499 if (!strcmp(var, "core.trustctime")) {
1500 trust_ctime = git_config_bool(var, value);
1501 return 0;
1503 if (!strcmp(var, "core.checkstat")) {
1504 if (!strcasecmp(value, "default"))
1505 check_stat = 1;
1506 else if (!strcasecmp(value, "minimal"))
1507 check_stat = 0;
1510 if (!strcmp(var, "core.quotepath")) {
1511 quote_path_fully = git_config_bool(var, value);
1512 return 0;
1515 if (!strcmp(var, "core.symlinks")) {
1516 has_symlinks = git_config_bool(var, value);
1517 return 0;
1520 if (!strcmp(var, "core.ignorecase")) {
1521 ignore_case = git_config_bool(var, value);
1522 return 0;
1525 if (!strcmp(var, "core.attributesfile"))
1526 return git_config_pathname(&git_attributes_file, var, value);
1528 if (!strcmp(var, "core.hookspath")) {
1529 if (current_config_scope() == CONFIG_SCOPE_LOCAL &&
1530 git_env_bool("GIT_CLONE_PROTECTION_ACTIVE", 0))
1531 die(_("active `core.hooksPath` found in the local "
1532 "repository config:\n\t%s\nFor security "
1533 "reasons, this is disallowed by default.\nIf "
1534 "this is intentional and the hook should "
1535 "actually be run, please\nrun the command "
1536 "again with "
1537 "`GIT_CLONE_PROTECTION_ACTIVE=false`"),
1538 value);
1539 return git_config_pathname(&git_hooks_path, var, value);
1542 if (!strcmp(var, "core.bare")) {
1543 is_bare_repository_cfg = git_config_bool(var, value);
1544 return 0;
1547 if (!strcmp(var, "core.ignorestat")) {
1548 assume_unchanged = git_config_bool(var, value);
1549 return 0;
1552 if (!strcmp(var, "core.prefersymlinkrefs")) {
1553 prefer_symlink_refs = git_config_bool(var, value);
1554 return 0;
1557 if (!strcmp(var, "core.logallrefupdates")) {
1558 if (value && !strcasecmp(value, "always"))
1559 log_all_ref_updates = LOG_REFS_ALWAYS;
1560 else if (git_config_bool(var, value))
1561 log_all_ref_updates = LOG_REFS_NORMAL;
1562 else
1563 log_all_ref_updates = LOG_REFS_NONE;
1564 return 0;
1567 if (!strcmp(var, "core.warnambiguousrefs")) {
1568 warn_ambiguous_refs = git_config_bool(var, value);
1569 return 0;
1572 if (!strcmp(var, "core.abbrev")) {
1573 if (!value)
1574 return config_error_nonbool(var);
1575 if (!strcasecmp(value, "auto"))
1576 default_abbrev = -1;
1577 else if (!git_parse_maybe_bool_text(value))
1578 default_abbrev = the_hash_algo->hexsz;
1579 else {
1580 int abbrev = git_config_int(var, value);
1581 if (abbrev < minimum_abbrev || abbrev > the_hash_algo->hexsz)
1582 return error(_("abbrev length out of range: %d"), abbrev);
1583 default_abbrev = abbrev;
1585 return 0;
1588 if (!strcmp(var, "core.disambiguate"))
1589 return set_disambiguate_hint_config(var, value);
1591 if (!strcmp(var, "core.loosecompression")) {
1592 int level = git_config_int(var, value);
1593 if (level == -1)
1594 level = Z_DEFAULT_COMPRESSION;
1595 else if (level < 0 || level > Z_BEST_COMPRESSION)
1596 die(_("bad zlib compression level %d"), level);
1597 zlib_compression_level = level;
1598 zlib_compression_seen = 1;
1599 return 0;
1602 if (!strcmp(var, "core.compression")) {
1603 int level = git_config_int(var, value);
1604 if (level == -1)
1605 level = Z_DEFAULT_COMPRESSION;
1606 else if (level < 0 || level > Z_BEST_COMPRESSION)
1607 die(_("bad zlib compression level %d"), level);
1608 if (!zlib_compression_seen)
1609 zlib_compression_level = level;
1610 if (!pack_compression_seen)
1611 pack_compression_level = level;
1612 return 0;
1615 if (!strcmp(var, "core.packedgitwindowsize")) {
1616 int pgsz_x2 = getpagesize() * 2;
1617 packed_git_window_size = git_config_ulong(var, value);
1619 /* This value must be multiple of (pagesize * 2) */
1620 packed_git_window_size /= pgsz_x2;
1621 if (packed_git_window_size < 1)
1622 packed_git_window_size = 1;
1623 packed_git_window_size *= pgsz_x2;
1624 return 0;
1627 if (!strcmp(var, "core.bigfilethreshold")) {
1628 big_file_threshold = git_config_ulong(var, value);
1629 return 0;
1632 if (!strcmp(var, "core.packedgitlimit")) {
1633 packed_git_limit = git_config_ulong(var, value);
1634 return 0;
1637 if (!strcmp(var, "core.deltabasecachelimit")) {
1638 delta_base_cache_limit = git_config_ulong(var, value);
1639 return 0;
1642 if (!strcmp(var, "core.autocrlf")) {
1643 if (value && !strcasecmp(value, "input")) {
1644 auto_crlf = AUTO_CRLF_INPUT;
1645 return 0;
1647 auto_crlf = git_config_bool(var, value);
1648 return 0;
1651 if (!strcmp(var, "core.safecrlf")) {
1652 int eol_rndtrp_die;
1653 if (value && !strcasecmp(value, "warn")) {
1654 global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
1655 return 0;
1657 eol_rndtrp_die = git_config_bool(var, value);
1658 global_conv_flags_eol = eol_rndtrp_die ?
1659 CONV_EOL_RNDTRP_DIE : 0;
1660 return 0;
1663 if (!strcmp(var, "core.eol")) {
1664 if (value && !strcasecmp(value, "lf"))
1665 core_eol = EOL_LF;
1666 else if (value && !strcasecmp(value, "crlf"))
1667 core_eol = EOL_CRLF;
1668 else if (value && !strcasecmp(value, "native"))
1669 core_eol = EOL_NATIVE;
1670 else
1671 core_eol = EOL_UNSET;
1672 return 0;
1675 if (!strcmp(var, "core.checkroundtripencoding")) {
1676 check_roundtrip_encoding = xstrdup(value);
1677 return 0;
1680 if (!strcmp(var, "core.notesref")) {
1681 notes_ref_name = xstrdup(value);
1682 return 0;
1685 if (!strcmp(var, "core.editor"))
1686 return git_config_string(&editor_program, var, value);
1688 if (!strcmp(var, "core.commentchar")) {
1689 if (!value)
1690 return config_error_nonbool(var);
1691 else if (!strcasecmp(value, "auto"))
1692 auto_comment_line_char = 1;
1693 else if (value[0] && !value[1]) {
1694 comment_line_char = value[0];
1695 auto_comment_line_char = 0;
1696 } else
1697 return error(_("core.commentChar should only be one character"));
1698 return 0;
1701 if (!strcmp(var, "core.askpass"))
1702 return git_config_string(&askpass_program, var, value);
1704 if (!strcmp(var, "core.excludesfile"))
1705 return git_config_pathname(&excludes_file, var, value);
1707 if (!strcmp(var, "core.whitespace")) {
1708 if (!value)
1709 return config_error_nonbool(var);
1710 whitespace_rule_cfg = parse_whitespace_rule(value);
1711 return 0;
1714 if (!strcmp(var, "core.fsync")) {
1715 if (!value)
1716 return config_error_nonbool(var);
1717 fsync_components = parse_fsync_components(var, value);
1718 return 0;
1721 if (!strcmp(var, "core.fsyncmethod")) {
1722 if (!value)
1723 return config_error_nonbool(var);
1724 if (!strcmp(value, "fsync"))
1725 fsync_method = FSYNC_METHOD_FSYNC;
1726 else if (!strcmp(value, "writeout-only"))
1727 fsync_method = FSYNC_METHOD_WRITEOUT_ONLY;
1728 else if (!strcmp(value, "batch"))
1729 fsync_method = FSYNC_METHOD_BATCH;
1730 else
1731 warning(_("ignoring unknown core.fsyncMethod value '%s'"), value);
1735 if (!strcmp(var, "core.fsyncobjectfiles")) {
1736 if (fsync_object_files < 0)
1737 warning(_("core.fsyncObjectFiles is deprecated; use core.fsync instead"));
1738 fsync_object_files = git_config_bool(var, value);
1739 return 0;
1742 if (!strcmp(var, "core.preloadindex")) {
1743 core_preload_index = git_config_bool(var, value);
1744 return 0;
1747 if (!strcmp(var, "core.createobject")) {
1748 if (!strcmp(value, "rename"))
1749 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
1750 else if (!strcmp(value, "link"))
1751 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
1752 else
1753 die(_("invalid mode for object creation: %s"), value);
1754 return 0;
1757 if (!strcmp(var, "core.sparsecheckout")) {
1758 core_apply_sparse_checkout = git_config_bool(var, value);
1759 return 0;
1762 if (!strcmp(var, "core.sparsecheckoutcone")) {
1763 core_sparse_checkout_cone = git_config_bool(var, value);
1764 return 0;
1767 if (!strcmp(var, "core.precomposeunicode")) {
1768 precomposed_unicode = git_config_bool(var, value);
1769 return 0;
1772 if (!strcmp(var, "core.protecthfs")) {
1773 protect_hfs = git_config_bool(var, value);
1774 return 0;
1777 if (!strcmp(var, "core.protectntfs")) {
1778 protect_ntfs = git_config_bool(var, value);
1779 return 0;
1782 if (!strcmp(var, "core.usereplacerefs")) {
1783 read_replace_refs = git_config_bool(var, value);
1784 return 0;
1787 /* Add other config variables here and to Documentation/config.txt. */
1788 return platform_core_config(var, value, cb);
1791 static int git_default_sparse_config(const char *var, const char *value)
1793 if (!strcmp(var, "sparse.expectfilesoutsideofpatterns")) {
1794 sparse_expect_files_outside_of_patterns = git_config_bool(var, value);
1795 return 0;
1798 /* Add other config variables here and to Documentation/config/sparse.txt. */
1799 return 0;
1802 static int git_default_i18n_config(const char *var, const char *value)
1804 if (!strcmp(var, "i18n.commitencoding"))
1805 return git_config_string(&git_commit_encoding, var, value);
1807 if (!strcmp(var, "i18n.logoutputencoding"))
1808 return git_config_string(&git_log_output_encoding, var, value);
1810 /* Add other config variables here and to Documentation/config.txt. */
1811 return 0;
1814 static int git_default_branch_config(const char *var, const char *value)
1816 if (!strcmp(var, "branch.autosetupmerge")) {
1817 if (value && !strcmp(value, "always")) {
1818 git_branch_track = BRANCH_TRACK_ALWAYS;
1819 return 0;
1820 } else if (value && !strcmp(value, "inherit")) {
1821 git_branch_track = BRANCH_TRACK_INHERIT;
1822 return 0;
1823 } else if (value && !strcmp(value, "simple")) {
1824 git_branch_track = BRANCH_TRACK_SIMPLE;
1825 return 0;
1827 git_branch_track = git_config_bool(var, value);
1828 return 0;
1830 if (!strcmp(var, "branch.autosetuprebase")) {
1831 if (!value)
1832 return config_error_nonbool(var);
1833 else if (!strcmp(value, "never"))
1834 autorebase = AUTOREBASE_NEVER;
1835 else if (!strcmp(value, "local"))
1836 autorebase = AUTOREBASE_LOCAL;
1837 else if (!strcmp(value, "remote"))
1838 autorebase = AUTOREBASE_REMOTE;
1839 else if (!strcmp(value, "always"))
1840 autorebase = AUTOREBASE_ALWAYS;
1841 else
1842 return error(_("malformed value for %s"), var);
1843 return 0;
1846 /* Add other config variables here and to Documentation/config.txt. */
1847 return 0;
1850 static int git_default_push_config(const char *var, const char *value)
1852 if (!strcmp(var, "push.default")) {
1853 if (!value)
1854 return config_error_nonbool(var);
1855 else if (!strcmp(value, "nothing"))
1856 push_default = PUSH_DEFAULT_NOTHING;
1857 else if (!strcmp(value, "matching"))
1858 push_default = PUSH_DEFAULT_MATCHING;
1859 else if (!strcmp(value, "simple"))
1860 push_default = PUSH_DEFAULT_SIMPLE;
1861 else if (!strcmp(value, "upstream"))
1862 push_default = PUSH_DEFAULT_UPSTREAM;
1863 else if (!strcmp(value, "tracking")) /* deprecated */
1864 push_default = PUSH_DEFAULT_UPSTREAM;
1865 else if (!strcmp(value, "current"))
1866 push_default = PUSH_DEFAULT_CURRENT;
1867 else {
1868 error(_("malformed value for %s: %s"), var, value);
1869 return error(_("must be one of nothing, matching, simple, "
1870 "upstream or current"));
1872 return 0;
1875 /* Add other config variables here and to Documentation/config.txt. */
1876 return 0;
1879 static int git_default_mailmap_config(const char *var, const char *value)
1881 if (!strcmp(var, "mailmap.file"))
1882 return git_config_pathname(&git_mailmap_file, var, value);
1883 if (!strcmp(var, "mailmap.blob"))
1884 return git_config_string(&git_mailmap_blob, var, value);
1886 /* Add other config variables here and to Documentation/config.txt. */
1887 return 0;
1890 int git_default_config(const char *var, const char *value, void *cb)
1892 if (starts_with(var, "core."))
1893 return git_default_core_config(var, value, cb);
1895 if (starts_with(var, "user.") ||
1896 starts_with(var, "author.") ||
1897 starts_with(var, "committer."))
1898 return git_ident_config(var, value, cb);
1900 if (starts_with(var, "i18n."))
1901 return git_default_i18n_config(var, value);
1903 if (starts_with(var, "branch."))
1904 return git_default_branch_config(var, value);
1906 if (starts_with(var, "push."))
1907 return git_default_push_config(var, value);
1909 if (starts_with(var, "mailmap."))
1910 return git_default_mailmap_config(var, value);
1912 if (starts_with(var, "advice.") || starts_with(var, "color.advice"))
1913 return git_default_advice_config(var, value);
1915 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1916 pager_use_color = git_config_bool(var,value);
1917 return 0;
1920 if (!strcmp(var, "pack.packsizelimit")) {
1921 pack_size_limit_cfg = git_config_ulong(var, value);
1922 return 0;
1925 if (!strcmp(var, "pack.compression")) {
1926 int level = git_config_int(var, value);
1927 if (level == -1)
1928 level = Z_DEFAULT_COMPRESSION;
1929 else if (level < 0 || level > Z_BEST_COMPRESSION)
1930 die(_("bad pack compression level %d"), level);
1931 pack_compression_level = level;
1932 pack_compression_seen = 1;
1933 return 0;
1936 if (starts_with(var, "sparse."))
1937 return git_default_sparse_config(var, value);
1939 /* Add other config variables here and to Documentation/config.txt. */
1940 return 0;
1944 * All source specific fields in the union, die_on_error, name and the callbacks
1945 * fgetc, ungetc, ftell of top need to be initialized before calling
1946 * this function.
1948 static int do_config_from(struct config_source *top, config_fn_t fn, void *data,
1949 const struct config_options *opts)
1951 int ret;
1953 /* push config-file parsing state stack */
1954 top->prev = cf;
1955 top->linenr = 1;
1956 top->eof = 0;
1957 top->total_len = 0;
1958 strbuf_init(&top->value, 1024);
1959 strbuf_init(&top->var, 1024);
1960 cf = top;
1962 ret = git_parse_source(fn, data, opts);
1964 /* pop config-file parsing state stack */
1965 strbuf_release(&top->value);
1966 strbuf_release(&top->var);
1967 cf = top->prev;
1969 return ret;
1972 static int do_config_from_file(config_fn_t fn,
1973 const enum config_origin_type origin_type,
1974 const char *name, const char *path, FILE *f,
1975 void *data, const struct config_options *opts)
1977 struct config_source top;
1978 int ret;
1980 top.u.file = f;
1981 top.origin_type = origin_type;
1982 top.name = name;
1983 top.path = path;
1984 top.default_error_action = CONFIG_ERROR_DIE;
1985 top.do_fgetc = config_file_fgetc;
1986 top.do_ungetc = config_file_ungetc;
1987 top.do_ftell = config_file_ftell;
1989 flockfile(f);
1990 ret = do_config_from(&top, fn, data, opts);
1991 funlockfile(f);
1992 return ret;
1995 static int git_config_from_stdin(config_fn_t fn, void *data)
1997 return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", NULL, stdin,
1998 data, NULL);
2001 int git_config_from_file_with_options(config_fn_t fn, const char *filename,
2002 void *data,
2003 const struct config_options *opts)
2005 int ret = -1;
2006 FILE *f;
2008 if (!filename)
2009 BUG("filename cannot be NULL");
2010 f = fopen_or_warn(filename, "r");
2011 if (f) {
2012 ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename,
2013 filename, f, data, opts);
2014 fclose(f);
2016 return ret;
2019 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
2021 return git_config_from_file_with_options(fn, filename, data, NULL);
2024 int git_config_from_mem(config_fn_t fn,
2025 const enum config_origin_type origin_type,
2026 const char *name, const char *buf, size_t len,
2027 void *data, const struct config_options *opts)
2029 struct config_source top;
2031 top.u.buf.buf = buf;
2032 top.u.buf.len = len;
2033 top.u.buf.pos = 0;
2034 top.origin_type = origin_type;
2035 top.name = name;
2036 top.path = NULL;
2037 top.default_error_action = CONFIG_ERROR_ERROR;
2038 top.do_fgetc = config_buf_fgetc;
2039 top.do_ungetc = config_buf_ungetc;
2040 top.do_ftell = config_buf_ftell;
2042 return do_config_from(&top, fn, data, opts);
2045 int git_config_from_blob_oid(config_fn_t fn,
2046 const char *name,
2047 struct repository *repo,
2048 const struct object_id *oid,
2049 void *data)
2051 enum object_type type;
2052 char *buf;
2053 unsigned long size;
2054 int ret;
2056 buf = repo_read_object_file(repo, oid, &type, &size);
2057 if (!buf)
2058 return error(_("unable to load config blob object '%s'"), name);
2059 if (type != OBJ_BLOB) {
2060 free(buf);
2061 return error(_("reference '%s' does not point to a blob"), name);
2064 ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size,
2065 data, NULL);
2066 free(buf);
2068 return ret;
2071 static int git_config_from_blob_ref(config_fn_t fn,
2072 struct repository *repo,
2073 const char *name,
2074 void *data)
2076 struct object_id oid;
2078 if (repo_get_oid(repo, name, &oid) < 0)
2079 return error(_("unable to resolve config blob '%s'"), name);
2080 return git_config_from_blob_oid(fn, name, repo, &oid, data);
2083 char *git_system_config(void)
2085 char *system_config = xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
2086 if (!system_config)
2087 system_config = system_path(ETC_GITCONFIG);
2088 normalize_path_copy(system_config, system_config);
2089 return system_config;
2092 void git_global_config(char **user_out, char **xdg_out)
2094 char *user_config = xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
2095 char *xdg_config = NULL;
2097 if (!user_config) {
2098 user_config = interpolate_path("~/.gitconfig", 0);
2099 xdg_config = xdg_config_home("config");
2102 *user_out = user_config;
2103 *xdg_out = xdg_config;
2107 * Parse environment variable 'k' as a boolean (in various
2108 * possible spellings); if missing, use the default value 'def'.
2110 int git_env_bool(const char *k, int def)
2112 const char *v = getenv(k);
2113 return v ? git_config_bool(k, v) : def;
2117 * Parse environment variable 'k' as ulong with possibly a unit
2118 * suffix; if missing, use the default value 'val'.
2120 unsigned long git_env_ulong(const char *k, unsigned long val)
2122 const char *v = getenv(k);
2123 if (v && !git_parse_ulong(v, &val))
2124 die(_("failed to parse %s"), k);
2125 return val;
2128 int git_config_system(void)
2130 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
2133 static int do_git_config_sequence(const struct config_options *opts,
2134 config_fn_t fn, void *data)
2136 int ret = 0;
2137 char *system_config = git_system_config();
2138 char *xdg_config = NULL;
2139 char *user_config = NULL;
2140 char *repo_config;
2141 enum config_scope prev_parsing_scope = current_parsing_scope;
2143 if (opts->commondir)
2144 repo_config = mkpathdup("%s/config", opts->commondir);
2145 else if (opts->git_dir)
2146 BUG("git_dir without commondir");
2147 else
2148 repo_config = NULL;
2150 current_parsing_scope = CONFIG_SCOPE_SYSTEM;
2151 if (git_config_system() && system_config &&
2152 !access_or_die(system_config, R_OK,
2153 opts->system_gently ? ACCESS_EACCES_OK : 0))
2154 ret += git_config_from_file(fn, system_config, data);
2156 current_parsing_scope = CONFIG_SCOPE_GLOBAL;
2157 git_global_config(&user_config, &xdg_config);
2159 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
2160 ret += git_config_from_file(fn, xdg_config, data);
2162 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
2163 ret += git_config_from_file(fn, user_config, data);
2165 current_parsing_scope = CONFIG_SCOPE_LOCAL;
2166 if (!opts->ignore_repo && repo_config &&
2167 !access_or_die(repo_config, R_OK, 0))
2168 ret += git_config_from_file(fn, repo_config, data);
2170 current_parsing_scope = CONFIG_SCOPE_WORKTREE;
2171 if (!opts->ignore_worktree && repository_format_worktree_config) {
2172 char *path = git_pathdup("config.worktree");
2173 if (!access_or_die(path, R_OK, 0))
2174 ret += git_config_from_file(fn, path, data);
2175 free(path);
2178 current_parsing_scope = CONFIG_SCOPE_COMMAND;
2179 if (!opts->ignore_cmdline && git_config_from_parameters(fn, data) < 0)
2180 die(_("unable to parse command-line config"));
2182 current_parsing_scope = prev_parsing_scope;
2183 free(system_config);
2184 free(xdg_config);
2185 free(user_config);
2186 free(repo_config);
2187 return ret;
2190 int config_with_options(config_fn_t fn, void *data,
2191 struct git_config_source *config_source,
2192 const struct config_options *opts)
2194 struct config_include_data inc = CONFIG_INCLUDE_INIT;
2195 int ret;
2197 if (opts->respect_includes) {
2198 inc.fn = fn;
2199 inc.data = data;
2200 inc.opts = opts;
2201 inc.config_source = config_source;
2202 fn = git_config_include;
2203 data = &inc;
2206 if (config_source)
2207 current_parsing_scope = config_source->scope;
2210 * If we have a specific filename, use it. Otherwise, follow the
2211 * regular lookup sequence.
2213 if (config_source && config_source->use_stdin) {
2214 ret = git_config_from_stdin(fn, data);
2215 } else if (config_source && config_source->file) {
2216 ret = git_config_from_file(fn, config_source->file, data);
2217 } else if (config_source && config_source->blob) {
2218 struct repository *repo = config_source->repo ?
2219 config_source->repo : the_repository;
2220 ret = git_config_from_blob_ref(fn, repo, config_source->blob,
2221 data);
2222 } else {
2223 ret = do_git_config_sequence(opts, fn, data);
2226 if (inc.remote_urls) {
2227 string_list_clear(inc.remote_urls, 0);
2228 FREE_AND_NULL(inc.remote_urls);
2230 return ret;
2233 static void configset_iter(struct config_set *cs, config_fn_t fn, void *data)
2235 int i, value_index;
2236 struct string_list *values;
2237 struct config_set_element *entry;
2238 struct configset_list *list = &cs->list;
2240 for (i = 0; i < list->nr; i++) {
2241 entry = list->items[i].e;
2242 value_index = list->items[i].value_index;
2243 values = &entry->value_list;
2245 current_config_kvi = values->items[value_index].util;
2247 if (fn(entry->key, values->items[value_index].string, data) < 0)
2248 git_die_config_linenr(entry->key,
2249 current_config_kvi->filename,
2250 current_config_kvi->linenr);
2252 current_config_kvi = NULL;
2256 void read_early_config(config_fn_t cb, void *data)
2258 struct config_options opts = {0};
2259 struct strbuf commondir = STRBUF_INIT;
2260 struct strbuf gitdir = STRBUF_INIT;
2262 opts.respect_includes = 1;
2264 if (have_git_dir()) {
2265 opts.commondir = get_git_common_dir();
2266 opts.git_dir = get_git_dir();
2268 * When setup_git_directory() was not yet asked to discover the
2269 * GIT_DIR, we ask discover_git_directory() to figure out whether there
2270 * is any repository config we should use (but unlike
2271 * setup_git_directory_gently(), no global state is changed, most
2272 * notably, the current working directory is still the same after the
2273 * call).
2275 } else if (!discover_git_directory(&commondir, &gitdir)) {
2276 opts.commondir = commondir.buf;
2277 opts.git_dir = gitdir.buf;
2280 config_with_options(cb, data, NULL, &opts);
2282 strbuf_release(&commondir);
2283 strbuf_release(&gitdir);
2287 * Read config but only enumerate system and global settings.
2288 * Omit any repo-local, worktree-local, or command-line settings.
2290 void read_very_early_config(config_fn_t cb, void *data)
2292 struct config_options opts = { 0 };
2294 opts.respect_includes = 1;
2295 opts.ignore_repo = 1;
2296 opts.ignore_worktree = 1;
2297 opts.ignore_cmdline = 1;
2298 opts.system_gently = 1;
2300 config_with_options(cb, data, NULL, &opts);
2303 static struct config_set_element *configset_find_element(struct config_set *cs, const char *key)
2305 struct config_set_element k;
2306 struct config_set_element *found_entry;
2307 char *normalized_key;
2309 * `key` may come from the user, so normalize it before using it
2310 * for querying entries from the hashmap.
2312 if (git_config_parse_key(key, &normalized_key, NULL))
2313 return NULL;
2315 hashmap_entry_init(&k.ent, strhash(normalized_key));
2316 k.key = normalized_key;
2317 found_entry = hashmap_get_entry(&cs->config_hash, &k, ent, NULL);
2318 free(normalized_key);
2319 return found_entry;
2322 static int configset_add_value(struct config_set *cs, const char *key, const char *value)
2324 struct config_set_element *e;
2325 struct string_list_item *si;
2326 struct configset_list_item *l_item;
2327 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
2329 e = configset_find_element(cs, key);
2331 * Since the keys are being fed by git_config*() callback mechanism, they
2332 * are already normalized. So simply add them without any further munging.
2334 if (!e) {
2335 e = xmalloc(sizeof(*e));
2336 hashmap_entry_init(&e->ent, strhash(key));
2337 e->key = xstrdup(key);
2338 string_list_init_dup(&e->value_list);
2339 hashmap_add(&cs->config_hash, &e->ent);
2341 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
2343 ALLOC_GROW(cs->list.items, cs->list.nr + 1, cs->list.alloc);
2344 l_item = &cs->list.items[cs->list.nr++];
2345 l_item->e = e;
2346 l_item->value_index = e->value_list.nr - 1;
2348 if (!cf)
2349 BUG("configset_add_value has no source");
2350 if (cf->name) {
2351 kv_info->filename = strintern(cf->name);
2352 kv_info->linenr = cf->linenr;
2353 kv_info->origin_type = cf->origin_type;
2354 } else {
2355 /* for values read from `git_config_from_parameters()` */
2356 kv_info->filename = NULL;
2357 kv_info->linenr = -1;
2358 kv_info->origin_type = CONFIG_ORIGIN_CMDLINE;
2360 kv_info->scope = current_parsing_scope;
2361 si->util = kv_info;
2363 return 0;
2366 static int config_set_element_cmp(const void *cmp_data UNUSED,
2367 const struct hashmap_entry *eptr,
2368 const struct hashmap_entry *entry_or_key,
2369 const void *keydata UNUSED)
2371 const struct config_set_element *e1, *e2;
2373 e1 = container_of(eptr, const struct config_set_element, ent);
2374 e2 = container_of(entry_or_key, const struct config_set_element, ent);
2376 return strcmp(e1->key, e2->key);
2379 void git_configset_init(struct config_set *cs)
2381 hashmap_init(&cs->config_hash, config_set_element_cmp, NULL, 0);
2382 cs->hash_initialized = 1;
2383 cs->list.nr = 0;
2384 cs->list.alloc = 0;
2385 cs->list.items = NULL;
2388 void git_configset_clear(struct config_set *cs)
2390 struct config_set_element *entry;
2391 struct hashmap_iter iter;
2392 if (!cs->hash_initialized)
2393 return;
2395 hashmap_for_each_entry(&cs->config_hash, &iter, entry,
2396 ent /* member name */) {
2397 free(entry->key);
2398 string_list_clear(&entry->value_list, 1);
2400 hashmap_clear_and_free(&cs->config_hash, struct config_set_element, ent);
2401 cs->hash_initialized = 0;
2402 free(cs->list.items);
2403 cs->list.nr = 0;
2404 cs->list.alloc = 0;
2405 cs->list.items = NULL;
2408 static int config_set_callback(const char *key, const char *value, void *cb)
2410 struct config_set *cs = cb;
2411 configset_add_value(cs, key, value);
2412 return 0;
2415 int git_configset_add_file(struct config_set *cs, const char *filename)
2417 return git_config_from_file(config_set_callback, filename, cs);
2420 int git_configset_get_value(struct config_set *cs, const char *key, const char **value)
2422 const struct string_list *values = NULL;
2424 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
2425 * queried key in the files of the configset, the value returned will be the last
2426 * value in the value list for that key.
2428 values = git_configset_get_value_multi(cs, key);
2430 if (!values)
2431 return 1;
2432 assert(values->nr > 0);
2433 *value = values->items[values->nr - 1].string;
2434 return 0;
2437 const struct string_list *git_configset_get_value_multi(struct config_set *cs, const char *key)
2439 struct config_set_element *e = configset_find_element(cs, key);
2440 return e ? &e->value_list : NULL;
2443 int git_configset_get_string(struct config_set *cs, const char *key, char **dest)
2445 const char *value;
2446 if (!git_configset_get_value(cs, key, &value))
2447 return git_config_string((const char **)dest, key, value);
2448 else
2449 return 1;
2452 static int git_configset_get_string_tmp(struct config_set *cs, const char *key,
2453 const char **dest)
2455 const char *value;
2456 if (!git_configset_get_value(cs, key, &value)) {
2457 if (!value)
2458 return config_error_nonbool(key);
2459 *dest = value;
2460 return 0;
2461 } else {
2462 return 1;
2466 int git_configset_get_int(struct config_set *cs, const char *key, int *dest)
2468 const char *value;
2469 if (!git_configset_get_value(cs, key, &value)) {
2470 *dest = git_config_int(key, value);
2471 return 0;
2472 } else
2473 return 1;
2476 int git_configset_get_ulong(struct config_set *cs, const char *key, unsigned long *dest)
2478 const char *value;
2479 if (!git_configset_get_value(cs, key, &value)) {
2480 *dest = git_config_ulong(key, value);
2481 return 0;
2482 } else
2483 return 1;
2486 int git_configset_get_bool(struct config_set *cs, const char *key, int *dest)
2488 const char *value;
2489 if (!git_configset_get_value(cs, key, &value)) {
2490 *dest = git_config_bool(key, value);
2491 return 0;
2492 } else
2493 return 1;
2496 int git_configset_get_bool_or_int(struct config_set *cs, const char *key,
2497 int *is_bool, int *dest)
2499 const char *value;
2500 if (!git_configset_get_value(cs, key, &value)) {
2501 *dest = git_config_bool_or_int(key, value, is_bool);
2502 return 0;
2503 } else
2504 return 1;
2507 int git_configset_get_maybe_bool(struct config_set *cs, const char *key, int *dest)
2509 const char *value;
2510 if (!git_configset_get_value(cs, key, &value)) {
2511 *dest = git_parse_maybe_bool(value);
2512 if (*dest == -1)
2513 return -1;
2514 return 0;
2515 } else
2516 return 1;
2519 int git_configset_get_pathname(struct config_set *cs, const char *key, const char **dest)
2521 const char *value;
2522 if (!git_configset_get_value(cs, key, &value))
2523 return git_config_pathname(dest, key, value);
2524 else
2525 return 1;
2528 /* Functions use to read configuration from a repository */
2529 static void repo_read_config(struct repository *repo)
2531 struct config_options opts = { 0 };
2533 opts.respect_includes = 1;
2534 opts.commondir = repo->commondir;
2535 opts.git_dir = repo->gitdir;
2537 if (!repo->config)
2538 CALLOC_ARRAY(repo->config, 1);
2539 else
2540 git_configset_clear(repo->config);
2542 git_configset_init(repo->config);
2544 if (config_with_options(config_set_callback, repo->config, NULL, &opts) < 0)
2546 * config_with_options() normally returns only
2547 * zero, as most errors are fatal, and
2548 * non-fatal potential errors are guarded by "if"
2549 * statements that are entered only when no error is
2550 * possible.
2552 * If we ever encounter a non-fatal error, it means
2553 * something went really wrong and we should stop
2554 * immediately.
2556 die(_("unknown error occurred while reading the configuration files"));
2559 static void git_config_check_init(struct repository *repo)
2561 if (repo->config && repo->config->hash_initialized)
2562 return;
2563 repo_read_config(repo);
2566 static void repo_config_clear(struct repository *repo)
2568 if (!repo->config || !repo->config->hash_initialized)
2569 return;
2570 git_configset_clear(repo->config);
2573 void repo_config(struct repository *repo, config_fn_t fn, void *data)
2575 git_config_check_init(repo);
2576 configset_iter(repo->config, fn, data);
2579 int repo_config_get_value(struct repository *repo,
2580 const char *key, const char **value)
2582 git_config_check_init(repo);
2583 return git_configset_get_value(repo->config, key, value);
2586 const struct string_list *repo_config_get_value_multi(struct repository *repo,
2587 const char *key)
2589 git_config_check_init(repo);
2590 return git_configset_get_value_multi(repo->config, key);
2593 int repo_config_get_string(struct repository *repo,
2594 const char *key, char **dest)
2596 int ret;
2597 git_config_check_init(repo);
2598 ret = git_configset_get_string(repo->config, key, dest);
2599 if (ret < 0)
2600 git_die_config(key, NULL);
2601 return ret;
2604 int repo_config_get_string_tmp(struct repository *repo,
2605 const char *key, const char **dest)
2607 int ret;
2608 git_config_check_init(repo);
2609 ret = git_configset_get_string_tmp(repo->config, key, dest);
2610 if (ret < 0)
2611 git_die_config(key, NULL);
2612 return ret;
2615 int repo_config_get_int(struct repository *repo,
2616 const char *key, int *dest)
2618 git_config_check_init(repo);
2619 return git_configset_get_int(repo->config, key, dest);
2622 int repo_config_get_ulong(struct repository *repo,
2623 const char *key, unsigned long *dest)
2625 git_config_check_init(repo);
2626 return git_configset_get_ulong(repo->config, key, dest);
2629 int repo_config_get_bool(struct repository *repo,
2630 const char *key, int *dest)
2632 git_config_check_init(repo);
2633 return git_configset_get_bool(repo->config, key, dest);
2636 int repo_config_get_bool_or_int(struct repository *repo,
2637 const char *key, int *is_bool, int *dest)
2639 git_config_check_init(repo);
2640 return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2643 int repo_config_get_maybe_bool(struct repository *repo,
2644 const char *key, int *dest)
2646 git_config_check_init(repo);
2647 return git_configset_get_maybe_bool(repo->config, key, dest);
2650 int repo_config_get_pathname(struct repository *repo,
2651 const char *key, const char **dest)
2653 int ret;
2654 git_config_check_init(repo);
2655 ret = git_configset_get_pathname(repo->config, key, dest);
2656 if (ret < 0)
2657 git_die_config(key, NULL);
2658 return ret;
2661 /* Read values into protected_config. */
2662 static void read_protected_config(void)
2664 struct config_options opts = {
2665 .respect_includes = 1,
2666 .ignore_repo = 1,
2667 .ignore_worktree = 1,
2668 .system_gently = 1,
2670 git_configset_init(&protected_config);
2671 config_with_options(config_set_callback, &protected_config,
2672 NULL, &opts);
2675 void git_protected_config(config_fn_t fn, void *data)
2677 if (!protected_config.hash_initialized)
2678 read_protected_config();
2679 configset_iter(&protected_config, fn, data);
2682 /* Functions used historically to read configuration from 'the_repository' */
2683 void git_config(config_fn_t fn, void *data)
2685 repo_config(the_repository, fn, data);
2688 void git_config_clear(void)
2690 repo_config_clear(the_repository);
2693 int git_config_get_value(const char *key, const char **value)
2695 return repo_config_get_value(the_repository, key, value);
2698 const struct string_list *git_config_get_value_multi(const char *key)
2700 return repo_config_get_value_multi(the_repository, key);
2703 int git_config_get_string(const char *key, char **dest)
2705 return repo_config_get_string(the_repository, key, dest);
2708 int git_config_get_string_tmp(const char *key, const char **dest)
2710 return repo_config_get_string_tmp(the_repository, key, dest);
2713 int git_config_get_int(const char *key, int *dest)
2715 return repo_config_get_int(the_repository, key, dest);
2718 int git_config_get_ulong(const char *key, unsigned long *dest)
2720 return repo_config_get_ulong(the_repository, key, dest);
2723 int git_config_get_bool(const char *key, int *dest)
2725 return repo_config_get_bool(the_repository, key, dest);
2728 int git_config_get_bool_or_int(const char *key, int *is_bool, int *dest)
2730 return repo_config_get_bool_or_int(the_repository, key, is_bool, dest);
2733 int git_config_get_maybe_bool(const char *key, int *dest)
2735 return repo_config_get_maybe_bool(the_repository, key, dest);
2738 int git_config_get_pathname(const char *key, const char **dest)
2740 return repo_config_get_pathname(the_repository, key, dest);
2743 int git_config_get_expiry(const char *key, const char **output)
2745 int ret = git_config_get_string(key, (char **)output);
2746 if (ret)
2747 return ret;
2748 if (strcmp(*output, "now")) {
2749 timestamp_t now = approxidate("now");
2750 if (approxidate(*output) >= now)
2751 git_die_config(key, _("Invalid %s: '%s'"), key, *output);
2753 return ret;
2756 int git_config_get_expiry_in_days(const char *key, timestamp_t *expiry, timestamp_t now)
2758 const char *expiry_string;
2759 intmax_t days;
2760 timestamp_t when;
2762 if (git_config_get_string_tmp(key, &expiry_string))
2763 return 1; /* no such thing */
2765 if (git_parse_signed(expiry_string, &days, maximum_signed_value_of_type(int))) {
2766 const int scale = 86400;
2767 *expiry = now - days * scale;
2768 return 0;
2771 if (!parse_expiry_date(expiry_string, &when)) {
2772 *expiry = when;
2773 return 0;
2775 return -1; /* thing exists but cannot be parsed */
2778 int git_config_get_split_index(void)
2780 int val;
2782 if (!git_config_get_maybe_bool("core.splitindex", &val))
2783 return val;
2785 return -1; /* default value */
2788 int git_config_get_max_percent_split_change(void)
2790 int val = -1;
2792 if (!git_config_get_int("splitindex.maxpercentchange", &val)) {
2793 if (0 <= val && val <= 100)
2794 return val;
2796 return error(_("splitIndex.maxPercentChange value '%d' "
2797 "should be between 0 and 100"), val);
2800 return -1; /* default value */
2803 int git_config_get_index_threads(int *dest)
2805 int is_bool, val;
2807 val = git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2808 if (val) {
2809 *dest = val;
2810 return 0;
2813 if (!git_config_get_bool_or_int("index.threads", &is_bool, &val)) {
2814 if (is_bool)
2815 *dest = val ? 0 : 1;
2816 else
2817 *dest = val;
2818 return 0;
2821 return 1;
2824 NORETURN
2825 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2827 if (!filename)
2828 die(_("unable to parse '%s' from command-line config"), key);
2829 else
2830 die(_("bad config variable '%s' in file '%s' at line %d"),
2831 key, filename, linenr);
2834 NORETURN __attribute__((format(printf, 2, 3)))
2835 void git_die_config(const char *key, const char *err, ...)
2837 const struct string_list *values;
2838 struct key_value_info *kv_info;
2839 report_fn error_fn = get_error_routine();
2841 if (err) {
2842 va_list params;
2843 va_start(params, err);
2844 error_fn(err, params);
2845 va_end(params);
2847 values = git_config_get_value_multi(key);
2848 kv_info = values->items[values->nr - 1].util;
2849 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
2853 * Find all the stuff for git_config_set() below.
2856 struct config_store_data {
2857 size_t baselen;
2858 char *key;
2859 int do_not_match;
2860 const char *fixed_value;
2861 regex_t *value_pattern;
2862 int multi_replace;
2863 struct {
2864 size_t begin, end;
2865 enum config_event_t type;
2866 int is_keys_section;
2867 } *parsed;
2868 unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
2869 unsigned int key_seen:1, section_seen:1, is_keys_section:1;
2872 static void config_store_data_clear(struct config_store_data *store)
2874 free(store->key);
2875 if (store->value_pattern != NULL &&
2876 store->value_pattern != CONFIG_REGEX_NONE) {
2877 regfree(store->value_pattern);
2878 free(store->value_pattern);
2880 free(store->parsed);
2881 free(store->seen);
2882 memset(store, 0, sizeof(*store));
2885 static int matches(const char *key, const char *value,
2886 const struct config_store_data *store)
2888 if (strcmp(key, store->key))
2889 return 0; /* not ours */
2890 if (store->fixed_value)
2891 return !strcmp(store->fixed_value, value);
2892 if (!store->value_pattern)
2893 return 1; /* always matches */
2894 if (store->value_pattern == CONFIG_REGEX_NONE)
2895 return 0; /* never matches */
2897 return store->do_not_match ^
2898 (value && !regexec(store->value_pattern, value, 0, NULL, 0));
2901 static int store_aux_event(enum config_event_t type,
2902 size_t begin, size_t end, void *data)
2904 struct config_store_data *store = data;
2906 ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
2907 store->parsed[store->parsed_nr].begin = begin;
2908 store->parsed[store->parsed_nr].end = end;
2909 store->parsed[store->parsed_nr].type = type;
2911 if (type == CONFIG_EVENT_SECTION) {
2912 int (*cmpfn)(const char *, const char *, size_t);
2914 if (cf->var.len < 2 || cf->var.buf[cf->var.len - 1] != '.')
2915 return error(_("invalid section name '%s'"), cf->var.buf);
2917 if (cf->subsection_case_sensitive)
2918 cmpfn = strncasecmp;
2919 else
2920 cmpfn = strncmp;
2922 /* Is this the section we were looking for? */
2923 store->is_keys_section =
2924 store->parsed[store->parsed_nr].is_keys_section =
2925 cf->var.len - 1 == store->baselen &&
2926 !cmpfn(cf->var.buf, store->key, store->baselen);
2927 if (store->is_keys_section) {
2928 store->section_seen = 1;
2929 ALLOC_GROW(store->seen, store->seen_nr + 1,
2930 store->seen_alloc);
2931 store->seen[store->seen_nr] = store->parsed_nr;
2935 store->parsed_nr++;
2937 return 0;
2940 static int store_aux(const char *key, const char *value, void *cb)
2942 struct config_store_data *store = cb;
2944 if (store->key_seen) {
2945 if (matches(key, value, store)) {
2946 if (store->seen_nr == 1 && store->multi_replace == 0) {
2947 warning(_("%s has multiple values"), key);
2950 ALLOC_GROW(store->seen, store->seen_nr + 1,
2951 store->seen_alloc);
2953 store->seen[store->seen_nr] = store->parsed_nr;
2954 store->seen_nr++;
2956 } else if (store->is_keys_section) {
2958 * Do not increment matches yet: this may not be a match, but we
2959 * are in the desired section.
2961 ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
2962 store->seen[store->seen_nr] = store->parsed_nr;
2963 store->section_seen = 1;
2965 if (matches(key, value, store)) {
2966 store->seen_nr++;
2967 store->key_seen = 1;
2971 return 0;
2974 static int write_error(const char *filename)
2976 error(_("failed to write new configuration file %s"), filename);
2978 /* Same error code as "failed to rename". */
2979 return 4;
2982 static struct strbuf store_create_section(const char *key,
2983 const struct config_store_data *store)
2985 const char *dot;
2986 size_t i;
2987 struct strbuf sb = STRBUF_INIT;
2989 dot = memchr(key, '.', store->baselen);
2990 if (dot) {
2991 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
2992 for (i = dot - key + 1; i < store->baselen; i++) {
2993 if (key[i] == '"' || key[i] == '\\')
2994 strbuf_addch(&sb, '\\');
2995 strbuf_addch(&sb, key[i]);
2997 strbuf_addstr(&sb, "\"]\n");
2998 } else {
2999 strbuf_addch(&sb, '[');
3000 strbuf_add(&sb, key, store->baselen);
3001 strbuf_addstr(&sb, "]\n");
3004 return sb;
3007 static ssize_t write_section(int fd, const char *key,
3008 const struct config_store_data *store)
3010 struct strbuf sb = store_create_section(key, store);
3011 ssize_t ret;
3013 ret = write_in_full(fd, sb.buf, sb.len);
3014 strbuf_release(&sb);
3016 return ret;
3019 static ssize_t write_pair(int fd, const char *key, const char *value,
3020 const struct config_store_data *store)
3022 int i;
3023 ssize_t ret;
3024 const char *quote = "";
3025 struct strbuf sb = STRBUF_INIT;
3028 * Check to see if the value needs to be surrounded with a dq pair.
3029 * Note that problematic characters are always backslash-quoted; this
3030 * check is about not losing leading or trailing SP and strings that
3031 * follow beginning-of-comment characters (i.e. ';' and '#') by the
3032 * configuration parser.
3034 if (value[0] == ' ')
3035 quote = "\"";
3036 for (i = 0; value[i]; i++)
3037 if (value[i] == ';' || value[i] == '#')
3038 quote = "\"";
3039 if (i && value[i - 1] == ' ')
3040 quote = "\"";
3042 strbuf_addf(&sb, "\t%s = %s", key + store->baselen + 1, quote);
3044 for (i = 0; value[i]; i++)
3045 switch (value[i]) {
3046 case '\n':
3047 strbuf_addstr(&sb, "\\n");
3048 break;
3049 case '\t':
3050 strbuf_addstr(&sb, "\\t");
3051 break;
3052 case '"':
3053 case '\\':
3054 strbuf_addch(&sb, '\\');
3055 /* fallthrough */
3056 default:
3057 strbuf_addch(&sb, value[i]);
3058 break;
3060 strbuf_addf(&sb, "%s\n", quote);
3062 ret = write_in_full(fd, sb.buf, sb.len);
3063 strbuf_release(&sb);
3065 return ret;
3069 * If we are about to unset the last key(s) in a section, and if there are
3070 * no comments surrounding (or included in) the section, we will want to
3071 * extend begin/end to remove the entire section.
3073 * Note: the parameter `seen_ptr` points to the index into the store.seen
3074 * array. * This index may be incremented if a section has more than one
3075 * entry (which all are to be removed).
3077 static void maybe_remove_section(struct config_store_data *store,
3078 size_t *begin_offset, size_t *end_offset,
3079 int *seen_ptr)
3081 size_t begin;
3082 int i, seen, section_seen = 0;
3085 * First, ensure that this is the first key, and that there are no
3086 * comments before the entry nor before the section header.
3088 seen = *seen_ptr;
3089 for (i = store->seen[seen]; i > 0; i--) {
3090 enum config_event_t type = store->parsed[i - 1].type;
3092 if (type == CONFIG_EVENT_COMMENT)
3093 /* There is a comment before this entry or section */
3094 return;
3095 if (type == CONFIG_EVENT_ENTRY) {
3096 if (!section_seen)
3097 /* This is not the section's first entry. */
3098 return;
3099 /* We encountered no comment before the section. */
3100 break;
3102 if (type == CONFIG_EVENT_SECTION) {
3103 if (!store->parsed[i - 1].is_keys_section)
3104 break;
3105 section_seen = 1;
3108 begin = store->parsed[i].begin;
3111 * Next, make sure that we are removing the last key(s) in the section,
3112 * and that there are no comments that are possibly about the current
3113 * section.
3115 for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
3116 enum config_event_t type = store->parsed[i].type;
3118 if (type == CONFIG_EVENT_COMMENT)
3119 return;
3120 if (type == CONFIG_EVENT_SECTION) {
3121 if (store->parsed[i].is_keys_section)
3122 continue;
3123 break;
3125 if (type == CONFIG_EVENT_ENTRY) {
3126 if (++seen < store->seen_nr &&
3127 i == store->seen[seen])
3128 /* We want to remove this entry, too */
3129 continue;
3130 /* There is another entry in this section. */
3131 return;
3136 * We are really removing the last entry/entries from this section, and
3137 * there are no enclosed or surrounding comments. Remove the entire,
3138 * now-empty section.
3140 *seen_ptr = seen;
3141 *begin_offset = begin;
3142 if (i < store->parsed_nr)
3143 *end_offset = store->parsed[i].begin;
3144 else
3145 *end_offset = store->parsed[store->parsed_nr - 1].end;
3148 int git_config_set_in_file_gently(const char *config_filename,
3149 const char *key, const char *value)
3151 return git_config_set_multivar_in_file_gently(config_filename, key, value, NULL, 0);
3154 void git_config_set_in_file(const char *config_filename,
3155 const char *key, const char *value)
3157 git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
3160 int git_config_set_gently(const char *key, const char *value)
3162 return git_config_set_multivar_gently(key, value, NULL, 0);
3165 int repo_config_set_worktree_gently(struct repository *r,
3166 const char *key, const char *value)
3168 /* Only use worktree-specific config if it is is already enabled. */
3169 if (repository_format_worktree_config) {
3170 char *file = repo_git_path(r, "config.worktree");
3171 int ret = git_config_set_multivar_in_file_gently(
3172 file, key, value, NULL, 0);
3173 free(file);
3174 return ret;
3176 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
3179 void git_config_set(const char *key, const char *value)
3181 git_config_set_multivar(key, value, NULL, 0);
3183 trace2_cmd_set_config(key, value);
3187 * If value==NULL, unset in (remove from) config,
3188 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
3189 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
3190 * (only add a new one)
3191 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3192 * key/values are removed before a single new pair is written. If the
3193 * flag is not present, then replace only the first match.
3195 * Returns 0 on success.
3197 * This function does this:
3199 * - it locks the config file by creating ".git/config.lock"
3201 * - it then parses the config using store_aux() as validator to find
3202 * the position on the key/value pair to replace. If it is to be unset,
3203 * it must be found exactly once.
3205 * - the config file is mmap()ed and the part before the match (if any) is
3206 * written to the lock file, then the changed part and the rest.
3208 * - the config file is removed and the lock file rename()d to it.
3211 int git_config_set_multivar_in_file_gently(const char *config_filename,
3212 const char *key, const char *value,
3213 const char *value_pattern,
3214 unsigned flags)
3216 int fd = -1, in_fd = -1;
3217 int ret;
3218 struct lock_file lock = LOCK_INIT;
3219 char *filename_buf = NULL;
3220 char *contents = NULL;
3221 size_t contents_sz;
3222 struct config_store_data store;
3224 memset(&store, 0, sizeof(store));
3226 /* parse-key returns negative; flip the sign to feed exit(3) */
3227 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
3228 if (ret)
3229 goto out_free;
3231 store.multi_replace = (flags & CONFIG_FLAGS_MULTI_REPLACE) != 0;
3233 if (!config_filename)
3234 config_filename = filename_buf = git_pathdup("config");
3237 * The lock serves a purpose in addition to locking: the new
3238 * contents of .git/config will be written into it.
3240 fd = hold_lock_file_for_update(&lock, config_filename, 0);
3241 if (fd < 0) {
3242 error_errno(_("could not lock config file %s"), config_filename);
3243 ret = CONFIG_NO_LOCK;
3244 goto out_free;
3248 * If .git/config does not exist yet, write a minimal version.
3250 in_fd = open(config_filename, O_RDONLY);
3251 if ( in_fd < 0 ) {
3252 if ( ENOENT != errno ) {
3253 error_errno(_("opening %s"), config_filename);
3254 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
3255 goto out_free;
3257 /* if nothing to unset, error out */
3258 if (!value) {
3259 ret = CONFIG_NOTHING_SET;
3260 goto out_free;
3263 free(store.key);
3264 store.key = xstrdup(key);
3265 if (write_section(fd, key, &store) < 0 ||
3266 write_pair(fd, key, value, &store) < 0)
3267 goto write_err_out;
3268 } else {
3269 struct stat st;
3270 size_t copy_begin, copy_end;
3271 int i, new_line = 0;
3272 struct config_options opts;
3274 if (!value_pattern)
3275 store.value_pattern = NULL;
3276 else if (value_pattern == CONFIG_REGEX_NONE)
3277 store.value_pattern = CONFIG_REGEX_NONE;
3278 else if (flags & CONFIG_FLAGS_FIXED_VALUE)
3279 store.fixed_value = value_pattern;
3280 else {
3281 if (value_pattern[0] == '!') {
3282 store.do_not_match = 1;
3283 value_pattern++;
3284 } else
3285 store.do_not_match = 0;
3287 store.value_pattern = (regex_t*)xmalloc(sizeof(regex_t));
3288 if (regcomp(store.value_pattern, value_pattern,
3289 REG_EXTENDED)) {
3290 error(_("invalid pattern: %s"), value_pattern);
3291 FREE_AND_NULL(store.value_pattern);
3292 ret = CONFIG_INVALID_PATTERN;
3293 goto out_free;
3297 ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
3298 store.parsed[0].end = 0;
3300 memset(&opts, 0, sizeof(opts));
3301 opts.event_fn = store_aux_event;
3302 opts.event_fn_data = &store;
3305 * After this, store.parsed will contain offsets of all the
3306 * parsed elements, and store.seen will contain a list of
3307 * matches, as indices into store.parsed.
3309 * As a side effect, we make sure to transform only a valid
3310 * existing config file.
3312 if (git_config_from_file_with_options(store_aux,
3313 config_filename,
3314 &store, &opts)) {
3315 error(_("invalid config file %s"), config_filename);
3316 ret = CONFIG_INVALID_FILE;
3317 goto out_free;
3320 /* if nothing to unset, or too many matches, error out */
3321 if ((store.seen_nr == 0 && value == NULL) ||
3322 (store.seen_nr > 1 && !store.multi_replace)) {
3323 ret = CONFIG_NOTHING_SET;
3324 goto out_free;
3327 if (fstat(in_fd, &st) == -1) {
3328 error_errno(_("fstat on %s failed"), config_filename);
3329 ret = CONFIG_INVALID_FILE;
3330 goto out_free;
3333 contents_sz = xsize_t(st.st_size);
3334 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
3335 MAP_PRIVATE, in_fd, 0);
3336 if (contents == MAP_FAILED) {
3337 if (errno == ENODEV && S_ISDIR(st.st_mode))
3338 errno = EISDIR;
3339 error_errno(_("unable to mmap '%s'%s"),
3340 config_filename, mmap_os_err());
3341 ret = CONFIG_INVALID_FILE;
3342 contents = NULL;
3343 goto out_free;
3345 close(in_fd);
3346 in_fd = -1;
3348 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3349 error_errno(_("chmod on %s failed"), get_lock_file_path(&lock));
3350 ret = CONFIG_NO_WRITE;
3351 goto out_free;
3354 if (store.seen_nr == 0) {
3355 if (!store.seen_alloc) {
3356 /* Did not see key nor section */
3357 ALLOC_GROW(store.seen, 1, store.seen_alloc);
3358 store.seen[0] = store.parsed_nr
3359 - !!store.parsed_nr;
3361 store.seen_nr = 1;
3364 for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
3365 size_t replace_end;
3366 int j = store.seen[i];
3368 new_line = 0;
3369 if (!store.key_seen) {
3370 copy_end = store.parsed[j].end;
3371 /* include '\n' when copying section header */
3372 if (copy_end > 0 && copy_end < contents_sz &&
3373 contents[copy_end - 1] != '\n' &&
3374 contents[copy_end] == '\n')
3375 copy_end++;
3376 replace_end = copy_end;
3377 } else {
3378 replace_end = store.parsed[j].end;
3379 copy_end = store.parsed[j].begin;
3380 if (!value)
3381 maybe_remove_section(&store,
3382 &copy_end,
3383 &replace_end, &i);
3385 * Swallow preceding white-space on the same
3386 * line.
3388 while (copy_end > 0 ) {
3389 char c = contents[copy_end - 1];
3391 if (isspace(c) && c != '\n')
3392 copy_end--;
3393 else
3394 break;
3398 if (copy_end > 0 && contents[copy_end-1] != '\n')
3399 new_line = 1;
3401 /* write the first part of the config */
3402 if (copy_end > copy_begin) {
3403 if (write_in_full(fd, contents + copy_begin,
3404 copy_end - copy_begin) < 0)
3405 goto write_err_out;
3406 if (new_line &&
3407 write_str_in_full(fd, "\n") < 0)
3408 goto write_err_out;
3410 copy_begin = replace_end;
3413 /* write the pair (value == NULL means unset) */
3414 if (value) {
3415 if (!store.section_seen) {
3416 if (write_section(fd, key, &store) < 0)
3417 goto write_err_out;
3419 if (write_pair(fd, key, value, &store) < 0)
3420 goto write_err_out;
3423 /* write the rest of the config */
3424 if (copy_begin < contents_sz)
3425 if (write_in_full(fd, contents + copy_begin,
3426 contents_sz - copy_begin) < 0)
3427 goto write_err_out;
3429 munmap(contents, contents_sz);
3430 contents = NULL;
3433 if (commit_lock_file(&lock) < 0) {
3434 error_errno(_("could not write config file %s"), config_filename);
3435 ret = CONFIG_NO_WRITE;
3436 goto out_free;
3439 ret = 0;
3441 /* Invalidate the config cache */
3442 git_config_clear();
3444 out_free:
3445 rollback_lock_file(&lock);
3446 free(filename_buf);
3447 if (contents)
3448 munmap(contents, contents_sz);
3449 if (in_fd >= 0)
3450 close(in_fd);
3451 config_store_data_clear(&store);
3452 return ret;
3454 write_err_out:
3455 ret = write_error(get_lock_file_path(&lock));
3456 goto out_free;
3460 void git_config_set_multivar_in_file(const char *config_filename,
3461 const char *key, const char *value,
3462 const char *value_pattern, unsigned flags)
3464 if (!git_config_set_multivar_in_file_gently(config_filename, key, value,
3465 value_pattern, flags))
3466 return;
3467 if (value)
3468 die(_("could not set '%s' to '%s'"), key, value);
3469 else
3470 die(_("could not unset '%s'"), key);
3473 int git_config_set_multivar_gently(const char *key, const char *value,
3474 const char *value_pattern, unsigned flags)
3476 return repo_config_set_multivar_gently(the_repository, key, value,
3477 value_pattern, flags);
3480 int repo_config_set_multivar_gently(struct repository *r, const char *key,
3481 const char *value,
3482 const char *value_pattern, unsigned flags)
3484 char *file = repo_git_path(r, "config");
3485 int res = git_config_set_multivar_in_file_gently(file,
3486 key, value,
3487 value_pattern,
3488 flags);
3489 free(file);
3490 return res;
3493 void git_config_set_multivar(const char *key, const char *value,
3494 const char *value_pattern, unsigned flags)
3496 git_config_set_multivar_in_file(git_path("config"),
3497 key, value, value_pattern,
3498 flags);
3501 static size_t section_name_match (const char *buf, const char *name)
3503 size_t i = 0, j = 0;
3504 int dot = 0;
3505 if (buf[i] != '[')
3506 return 0;
3507 for (i = 1; buf[i] && buf[i] != ']'; i++) {
3508 if (!dot && isspace(buf[i])) {
3509 dot = 1;
3510 if (name[j++] != '.')
3511 break;
3512 for (i++; isspace(buf[i]); i++)
3513 ; /* do nothing */
3514 if (buf[i] != '"')
3515 break;
3516 continue;
3518 if (buf[i] == '\\' && dot)
3519 i++;
3520 else if (buf[i] == '"' && dot) {
3521 for (i++; isspace(buf[i]); i++)
3522 ; /* do_nothing */
3523 break;
3525 if (buf[i] != name[j++])
3526 break;
3528 if (buf[i] == ']' && name[j] == 0) {
3530 * We match, now just find the right length offset by
3531 * gobbling up any whitespace after it, as well
3533 i++;
3534 for (; buf[i] && isspace(buf[i]); i++)
3535 ; /* do nothing */
3536 return i;
3538 return 0;
3541 static int section_name_is_ok(const char *name)
3543 /* Empty section names are bogus. */
3544 if (!*name)
3545 return 0;
3548 * Before a dot, we must be alphanumeric or dash. After the first dot,
3549 * anything goes, so we can stop checking.
3551 for (; *name && *name != '.'; name++)
3552 if (*name != '-' && !isalnum(*name))
3553 return 0;
3554 return 1;
3557 #define GIT_CONFIG_MAX_LINE_LEN (512 * 1024)
3559 /* if new_name == NULL, the section is removed instead */
3560 static int git_config_copy_or_rename_section_in_file(const char *config_filename,
3561 const char *old_name,
3562 const char *new_name, int copy)
3564 int ret = 0, remove = 0;
3565 char *filename_buf = NULL;
3566 struct lock_file lock = LOCK_INIT;
3567 int out_fd;
3568 struct strbuf buf = STRBUF_INIT;
3569 FILE *config_file = NULL;
3570 struct stat st;
3571 struct strbuf copystr = STRBUF_INIT;
3572 struct config_store_data store;
3573 uint32_t line_nr = 0;
3575 memset(&store, 0, sizeof(store));
3577 if (new_name && !section_name_is_ok(new_name)) {
3578 ret = error(_("invalid section name: %s"), new_name);
3579 goto out_no_rollback;
3582 if (!config_filename)
3583 config_filename = filename_buf = git_pathdup("config");
3585 out_fd = hold_lock_file_for_update(&lock, config_filename, 0);
3586 if (out_fd < 0) {
3587 ret = error(_("could not lock config file %s"), config_filename);
3588 goto out;
3591 if (!(config_file = fopen(config_filename, "rb"))) {
3592 ret = warn_on_fopen_errors(config_filename);
3593 if (ret)
3594 goto out;
3595 /* no config file means nothing to rename, no error */
3596 goto commit_and_out;
3599 if (fstat(fileno(config_file), &st) == -1) {
3600 ret = error_errno(_("fstat on %s failed"), config_filename);
3601 goto out;
3604 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3605 ret = error_errno(_("chmod on %s failed"),
3606 get_lock_file_path(&lock));
3607 goto out;
3610 while (!strbuf_getwholeline(&buf, config_file, '\n')) {
3611 size_t i, length;
3612 int is_section = 0;
3613 char *output = buf.buf;
3615 line_nr++;
3617 if (buf.len >= GIT_CONFIG_MAX_LINE_LEN) {
3618 ret = error(_("refusing to work with overly long line "
3619 "in '%s' on line %"PRIuMAX),
3620 config_filename, (uintmax_t)line_nr);
3621 goto out;
3624 for (i = 0; buf.buf[i] && isspace(buf.buf[i]); i++)
3625 ; /* do nothing */
3626 if (buf.buf[i] == '[') {
3627 /* it's a section */
3628 size_t offset;
3629 is_section = 1;
3632 * When encountering a new section under -c we
3633 * need to flush out any section we're already
3634 * coping and begin anew. There might be
3635 * multiple [branch "$name"] sections.
3637 if (copystr.len > 0) {
3638 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3639 ret = write_error(get_lock_file_path(&lock));
3640 goto out;
3642 strbuf_reset(&copystr);
3645 offset = section_name_match(&buf.buf[i], old_name);
3646 if (offset > 0) {
3647 ret++;
3648 if (!new_name) {
3649 remove = 1;
3650 continue;
3652 store.baselen = strlen(new_name);
3653 if (!copy) {
3654 if (write_section(out_fd, new_name, &store) < 0) {
3655 ret = write_error(get_lock_file_path(&lock));
3656 goto out;
3659 * We wrote out the new section, with
3660 * a newline, now skip the old
3661 * section's length
3663 output += offset + i;
3664 if (strlen(output) > 0) {
3666 * More content means there's
3667 * a declaration to put on the
3668 * next line; indent with a
3669 * tab
3671 output -= 1;
3672 output[0] = '\t';
3674 } else {
3675 copystr = store_create_section(new_name, &store);
3678 remove = 0;
3680 if (remove)
3681 continue;
3682 length = strlen(output);
3684 if (!is_section && copystr.len > 0) {
3685 strbuf_add(&copystr, output, length);
3688 if (write_in_full(out_fd, output, length) < 0) {
3689 ret = write_error(get_lock_file_path(&lock));
3690 goto out;
3695 * Copy a trailing section at the end of the config, won't be
3696 * flushed by the usual "flush because we have a new section
3697 * logic in the loop above.
3699 if (copystr.len > 0) {
3700 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3701 ret = write_error(get_lock_file_path(&lock));
3702 goto out;
3704 strbuf_reset(&copystr);
3707 fclose(config_file);
3708 config_file = NULL;
3709 commit_and_out:
3710 if (commit_lock_file(&lock) < 0)
3711 ret = error_errno(_("could not write config file %s"),
3712 config_filename);
3713 out:
3714 if (config_file)
3715 fclose(config_file);
3716 rollback_lock_file(&lock);
3717 out_no_rollback:
3718 free(filename_buf);
3719 config_store_data_clear(&store);
3720 strbuf_release(&buf);
3721 return ret;
3724 int git_config_rename_section_in_file(const char *config_filename,
3725 const char *old_name, const char *new_name)
3727 return git_config_copy_or_rename_section_in_file(config_filename,
3728 old_name, new_name, 0);
3731 int git_config_rename_section(const char *old_name, const char *new_name)
3733 return git_config_rename_section_in_file(NULL, old_name, new_name);
3736 int git_config_copy_section_in_file(const char *config_filename,
3737 const char *old_name, const char *new_name)
3739 return git_config_copy_or_rename_section_in_file(config_filename,
3740 old_name, new_name, 1);
3743 int git_config_copy_section(const char *old_name, const char *new_name)
3745 return git_config_copy_section_in_file(NULL, old_name, new_name);
3749 * Call this to report error for your variable that should not
3750 * get a boolean value (i.e. "[my] var" means "true").
3752 #undef config_error_nonbool
3753 int config_error_nonbool(const char *var)
3755 return error(_("missing value for '%s'"), var);
3758 int parse_config_key(const char *var,
3759 const char *section,
3760 const char **subsection, size_t *subsection_len,
3761 const char **key)
3763 const char *dot;
3765 /* Does it start with "section." ? */
3766 if (!skip_prefix(var, section, &var) || *var != '.')
3767 return -1;
3770 * Find the key; we don't know yet if we have a subsection, but we must
3771 * parse backwards from the end, since the subsection may have dots in
3772 * it, too.
3774 dot = strrchr(var, '.');
3775 *key = dot + 1;
3777 /* Did we have a subsection at all? */
3778 if (dot == var) {
3779 if (subsection) {
3780 *subsection = NULL;
3781 *subsection_len = 0;
3784 else {
3785 if (!subsection)
3786 return -1;
3787 *subsection = var + 1;
3788 *subsection_len = dot - *subsection;
3791 return 0;
3794 const char *current_config_origin_type(void)
3796 int type;
3797 if (current_config_kvi)
3798 type = current_config_kvi->origin_type;
3799 else if(cf)
3800 type = cf->origin_type;
3801 else
3802 BUG("current_config_origin_type called outside config callback");
3804 switch (type) {
3805 case CONFIG_ORIGIN_BLOB:
3806 return "blob";
3807 case CONFIG_ORIGIN_FILE:
3808 return "file";
3809 case CONFIG_ORIGIN_STDIN:
3810 return "standard input";
3811 case CONFIG_ORIGIN_SUBMODULE_BLOB:
3812 return "submodule-blob";
3813 case CONFIG_ORIGIN_CMDLINE:
3814 return "command line";
3815 default:
3816 BUG("unknown config origin type");
3820 const char *config_scope_name(enum config_scope scope)
3822 switch (scope) {
3823 case CONFIG_SCOPE_SYSTEM:
3824 return "system";
3825 case CONFIG_SCOPE_GLOBAL:
3826 return "global";
3827 case CONFIG_SCOPE_LOCAL:
3828 return "local";
3829 case CONFIG_SCOPE_WORKTREE:
3830 return "worktree";
3831 case CONFIG_SCOPE_COMMAND:
3832 return "command";
3833 case CONFIG_SCOPE_SUBMODULE:
3834 return "submodule";
3835 default:
3836 return "unknown";
3840 const char *current_config_name(void)
3842 const char *name;
3843 if (current_config_kvi)
3844 name = current_config_kvi->filename;
3845 else if (cf)
3846 name = cf->name;
3847 else
3848 BUG("current_config_name called outside config callback");
3849 return name ? name : "";
3852 enum config_scope current_config_scope(void)
3854 if (current_config_kvi)
3855 return current_config_kvi->scope;
3856 else
3857 return current_parsing_scope;
3860 int current_config_line(void)
3862 if (current_config_kvi)
3863 return current_config_kvi->linenr;
3864 else
3865 return cf->linenr;
3868 int lookup_config(const char **mapping, int nr_mapping, const char *var)
3870 int i;
3872 for (i = 0; i < nr_mapping; i++) {
3873 const char *name = mapping[i];
3875 if (name && !strcasecmp(var, name))
3876 return i;
3878 return -1;