config: inline git_color_default_config
[git.git] / config.c
blob2eeb66214219e5ee52bcf9d9e3a5aed02489e4ff
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 * Copyright (C) Johannes Schindelin, 2005
7 */
8 #include "git-compat-util.h"
9 #include "abspath.h"
10 #include "advice.h"
11 #include "alloc.h"
12 #include "date.h"
13 #include "branch.h"
14 #include "config.h"
15 #include "convert.h"
16 #include "environment.h"
17 #include "gettext.h"
18 #include "ident.h"
19 #include "repository.h"
20 #include "lockfile.h"
21 #include "mailmap.h"
22 #include "exec-cmd.h"
23 #include "strbuf.h"
24 #include "quote.h"
25 #include "hashmap.h"
26 #include "string-list.h"
27 #include "object-name.h"
28 #include "object-store.h"
29 #include "pager.h"
30 #include "utf8.h"
31 #include "dir.h"
32 #include "color.h"
33 #include "replace-object.h"
34 #include "refs.h"
35 #include "setup.h"
36 #include "trace2.h"
37 #include "worktree.h"
38 #include "ws.h"
39 #include "wrapper.h"
40 #include "write-or-die.h"
42 struct config_source {
43 struct config_source *prev;
44 union {
45 FILE *file;
46 struct config_buf {
47 const char *buf;
48 size_t len;
49 size_t pos;
50 } buf;
51 } u;
52 enum config_origin_type origin_type;
53 const char *name;
54 const char *path;
55 enum config_error_action default_error_action;
56 int linenr;
57 int eof;
58 size_t total_len;
59 struct strbuf value;
60 struct strbuf var;
61 unsigned subsection_case_sensitive : 1;
63 int (*do_fgetc)(struct config_source *c);
64 int (*do_ungetc)(int c, struct config_source *conf);
65 long (*do_ftell)(struct config_source *c);
67 #define CONFIG_SOURCE_INIT { 0 }
69 struct config_reader {
71 * These members record the "current" config source, which can be
72 * accessed by parsing callbacks.
74 * The "source" variable will be non-NULL only when we are actually
75 * parsing a real config source (file, blob, cmdline, etc).
77 * The "config_kvi" variable will be non-NULL only when we are feeding
78 * cached config from a configset into a callback.
80 * They cannot be non-NULL at the same time. If they are both NULL, then
81 * we aren't parsing anything (and depending on the function looking at
82 * the variables, it's either a bug for it to be called in the first
83 * place, or it's a function which can be reused for non-config
84 * purposes, and should fall back to some sane behavior).
86 struct config_source *source;
87 struct key_value_info *config_kvi;
89 * The "scope" of the current config source being parsed (repo, global,
90 * etc). Like "source", this is only set when parsing a config source.
91 * It's not part of "source" because it transcends a single file (i.e.,
92 * a file included from .git/config is still in "repo" scope).
94 * When iterating through a configset, the equivalent value is
95 * "config_kvi.scope" (see above).
97 enum config_scope parsing_scope;
100 * Where possible, prefer to accept "struct config_reader" as an arg than to use
101 * "the_reader". "the_reader" should only be used if that is infeasible, e.g. in
102 * a public function.
104 static struct config_reader the_reader;
106 static inline void config_reader_push_source(struct config_reader *reader,
107 struct config_source *top)
109 if (reader->config_kvi)
110 BUG("source should not be set while iterating a config set");
111 top->prev = reader->source;
112 reader->source = top;
115 static inline struct config_source *config_reader_pop_source(struct config_reader *reader)
117 struct config_source *ret;
118 if (!reader->source)
119 BUG("tried to pop config source, but we weren't reading config");
120 ret = reader->source;
121 reader->source = reader->source->prev;
122 return ret;
125 static inline void config_reader_set_kvi(struct config_reader *reader,
126 struct key_value_info *kvi)
128 if (kvi && (reader->source || reader->parsing_scope))
129 BUG("kvi should not be set while parsing a config source");
130 reader->config_kvi = kvi;
133 static inline void config_reader_set_scope(struct config_reader *reader,
134 enum config_scope scope)
136 if (scope && reader->config_kvi)
137 BUG("scope should only be set when iterating through a config source");
138 reader->parsing_scope = scope;
141 static int pack_compression_seen;
142 static int zlib_compression_seen;
145 * Config that comes from trusted scopes, namely:
146 * - CONFIG_SCOPE_SYSTEM (e.g. /etc/gitconfig)
147 * - CONFIG_SCOPE_GLOBAL (e.g. $HOME/.gitconfig, $XDG_CONFIG_HOME/git)
148 * - CONFIG_SCOPE_COMMAND (e.g. "-c" option, environment variables)
150 * This is declared here for code cleanliness, but unlike the other
151 * static variables, this does not hold config parser state.
153 static struct config_set protected_config;
155 static int config_file_fgetc(struct config_source *conf)
157 return getc_unlocked(conf->u.file);
160 static int config_file_ungetc(int c, struct config_source *conf)
162 return ungetc(c, conf->u.file);
165 static long config_file_ftell(struct config_source *conf)
167 return ftell(conf->u.file);
171 static int config_buf_fgetc(struct config_source *conf)
173 if (conf->u.buf.pos < conf->u.buf.len)
174 return conf->u.buf.buf[conf->u.buf.pos++];
176 return EOF;
179 static int config_buf_ungetc(int c, struct config_source *conf)
181 if (conf->u.buf.pos > 0) {
182 conf->u.buf.pos--;
183 if (conf->u.buf.buf[conf->u.buf.pos] != c)
184 BUG("config_buf can only ungetc the same character");
185 return c;
188 return EOF;
191 static long config_buf_ftell(struct config_source *conf)
193 return conf->u.buf.pos;
196 struct config_include_data {
197 int depth;
198 config_fn_t fn;
199 void *data;
200 const struct config_options *opts;
201 struct git_config_source *config_source;
202 struct repository *repo;
203 struct config_reader *config_reader;
206 * All remote URLs discovered when reading all config files.
208 struct string_list *remote_urls;
210 #define CONFIG_INCLUDE_INIT { 0 }
212 static int git_config_include(const char *var, const char *value, void *data);
214 #define MAX_INCLUDE_DEPTH 10
215 static const char include_depth_advice[] = N_(
216 "exceeded maximum include depth (%d) while including\n"
217 " %s\n"
218 "from\n"
219 " %s\n"
220 "This might be due to circular includes.");
221 static int handle_path_include(struct config_source *cs, const char *path,
222 struct config_include_data *inc)
224 int ret = 0;
225 struct strbuf buf = STRBUF_INIT;
226 char *expanded;
228 if (!path)
229 return config_error_nonbool("include.path");
231 expanded = interpolate_path(path, 0);
232 if (!expanded)
233 return error(_("could not expand include path '%s'"), path);
234 path = expanded;
237 * Use an absolute path as-is, but interpret relative paths
238 * based on the including config file.
240 if (!is_absolute_path(path)) {
241 char *slash;
243 if (!cs || !cs->path) {
244 ret = error(_("relative config includes must come from files"));
245 goto cleanup;
248 slash = find_last_dir_sep(cs->path);
249 if (slash)
250 strbuf_add(&buf, cs->path, slash - cs->path + 1);
251 strbuf_addstr(&buf, path);
252 path = buf.buf;
255 if (!access_or_die(path, R_OK, 0)) {
256 if (++inc->depth > MAX_INCLUDE_DEPTH)
257 die(_(include_depth_advice), MAX_INCLUDE_DEPTH, path,
258 !cs ? "<unknown>" :
259 cs->name ? cs->name :
260 "the command line");
261 ret = git_config_from_file(git_config_include, path, inc);
262 inc->depth--;
264 cleanup:
265 strbuf_release(&buf);
266 free(expanded);
267 return ret;
270 static void add_trailing_starstar_for_dir(struct strbuf *pat)
272 if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
273 strbuf_addstr(pat, "**");
276 static int prepare_include_condition_pattern(struct config_source *cs,
277 struct strbuf *pat)
279 struct strbuf path = STRBUF_INIT;
280 char *expanded;
281 int prefix = 0;
283 expanded = interpolate_path(pat->buf, 1);
284 if (expanded) {
285 strbuf_reset(pat);
286 strbuf_addstr(pat, expanded);
287 free(expanded);
290 if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
291 const char *slash;
293 if (!cs || !cs->path)
294 return error(_("relative config include "
295 "conditionals must come from files"));
297 strbuf_realpath(&path, cs->path, 1);
298 slash = find_last_dir_sep(path.buf);
299 if (!slash)
300 BUG("how is this possible?");
301 strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
302 prefix = slash - path.buf + 1 /* slash */;
303 } else if (!is_absolute_path(pat->buf))
304 strbuf_insertstr(pat, 0, "**/");
306 add_trailing_starstar_for_dir(pat);
308 strbuf_release(&path);
309 return prefix;
312 static int include_by_gitdir(struct config_source *cs,
313 const struct config_options *opts,
314 const char *cond, size_t cond_len, int icase)
316 struct strbuf text = STRBUF_INIT;
317 struct strbuf pattern = STRBUF_INIT;
318 int ret = 0, prefix;
319 const char *git_dir;
320 int already_tried_absolute = 0;
322 if (opts->git_dir)
323 git_dir = opts->git_dir;
324 else
325 goto done;
327 strbuf_realpath(&text, git_dir, 1);
328 strbuf_add(&pattern, cond, cond_len);
329 prefix = prepare_include_condition_pattern(cs, &pattern);
331 again:
332 if (prefix < 0)
333 goto done;
335 if (prefix > 0) {
337 * perform literal matching on the prefix part so that
338 * any wildcard character in it can't create side effects.
340 if (text.len < prefix)
341 goto done;
342 if (!icase && strncmp(pattern.buf, text.buf, prefix))
343 goto done;
344 if (icase && strncasecmp(pattern.buf, text.buf, prefix))
345 goto done;
348 ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
349 WM_PATHNAME | (icase ? WM_CASEFOLD : 0));
351 if (!ret && !already_tried_absolute) {
353 * We've tried e.g. matching gitdir:~/work, but if
354 * ~/work is a symlink to /mnt/storage/work
355 * strbuf_realpath() will expand it, so the rule won't
356 * match. Let's match against a
357 * strbuf_add_absolute_path() version of the path,
358 * which'll do the right thing
360 strbuf_reset(&text);
361 strbuf_add_absolute_path(&text, git_dir);
362 already_tried_absolute = 1;
363 goto again;
365 done:
366 strbuf_release(&pattern);
367 strbuf_release(&text);
368 return ret;
371 static int include_by_branch(const char *cond, size_t cond_len)
373 int flags;
374 int ret;
375 struct strbuf pattern = STRBUF_INIT;
376 const char *refname = !the_repository->gitdir ?
377 NULL : resolve_ref_unsafe("HEAD", 0, NULL, &flags);
378 const char *shortname;
380 if (!refname || !(flags & REF_ISSYMREF) ||
381 !skip_prefix(refname, "refs/heads/", &shortname))
382 return 0;
384 strbuf_add(&pattern, cond, cond_len);
385 add_trailing_starstar_for_dir(&pattern);
386 ret = !wildmatch(pattern.buf, shortname, WM_PATHNAME);
387 strbuf_release(&pattern);
388 return ret;
391 static int add_remote_url(const char *var, const char *value, void *data)
393 struct string_list *remote_urls = data;
394 const char *remote_name;
395 size_t remote_name_len;
396 const char *key;
398 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
399 &key) &&
400 remote_name &&
401 !strcmp(key, "url"))
402 string_list_append(remote_urls, value);
403 return 0;
406 static void populate_remote_urls(struct config_include_data *inc)
408 struct config_options opts;
410 enum config_scope store_scope = inc->config_reader->parsing_scope;
412 opts = *inc->opts;
413 opts.unconditional_remote_url = 1;
415 config_reader_set_scope(inc->config_reader, 0);
417 inc->remote_urls = xmalloc(sizeof(*inc->remote_urls));
418 string_list_init_dup(inc->remote_urls);
419 config_with_options(add_remote_url, inc->remote_urls,
420 inc->config_source, inc->repo, &opts);
422 config_reader_set_scope(inc->config_reader, store_scope);
425 static int forbid_remote_url(const char *var, const char *value UNUSED,
426 void *data UNUSED)
428 const char *remote_name;
429 size_t remote_name_len;
430 const char *key;
432 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
433 &key) &&
434 remote_name &&
435 !strcmp(key, "url"))
436 die(_("remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"));
437 return 0;
440 static int at_least_one_url_matches_glob(const char *glob, int glob_len,
441 struct string_list *remote_urls)
443 struct strbuf pattern = STRBUF_INIT;
444 struct string_list_item *url_item;
445 int found = 0;
447 strbuf_add(&pattern, glob, glob_len);
448 for_each_string_list_item(url_item, remote_urls) {
449 if (!wildmatch(pattern.buf, url_item->string, WM_PATHNAME)) {
450 found = 1;
451 break;
454 strbuf_release(&pattern);
455 return found;
458 static int include_by_remote_url(struct config_include_data *inc,
459 const char *cond, size_t cond_len)
461 if (inc->opts->unconditional_remote_url)
462 return 1;
463 if (!inc->remote_urls)
464 populate_remote_urls(inc);
465 return at_least_one_url_matches_glob(cond, cond_len,
466 inc->remote_urls);
469 static int include_condition_is_true(struct config_source *cs,
470 struct config_include_data *inc,
471 const char *cond, size_t cond_len)
473 const struct config_options *opts = inc->opts;
475 if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
476 return include_by_gitdir(cs, opts, cond, cond_len, 0);
477 else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
478 return include_by_gitdir(cs, opts, cond, cond_len, 1);
479 else if (skip_prefix_mem(cond, cond_len, "onbranch:", &cond, &cond_len))
480 return include_by_branch(cond, cond_len);
481 else if (skip_prefix_mem(cond, cond_len, "hasconfig:remote.*.url:", &cond,
482 &cond_len))
483 return include_by_remote_url(inc, cond, cond_len);
485 /* unknown conditionals are always false */
486 return 0;
489 static int git_config_include(const char *var, const char *value, void *data)
491 struct config_include_data *inc = data;
492 struct config_source *cs = inc->config_reader->source;
493 const char *cond, *key;
494 size_t cond_len;
495 int ret;
498 * Pass along all values, including "include" directives; this makes it
499 * possible to query information on the includes themselves.
501 ret = inc->fn(var, value, inc->data);
502 if (ret < 0)
503 return ret;
505 if (!strcmp(var, "include.path"))
506 ret = handle_path_include(cs, value, inc);
508 if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
509 cond && include_condition_is_true(cs, inc, cond, cond_len) &&
510 !strcmp(key, "path")) {
511 config_fn_t old_fn = inc->fn;
513 if (inc->opts->unconditional_remote_url)
514 inc->fn = forbid_remote_url;
515 ret = handle_path_include(cs, value, inc);
516 inc->fn = old_fn;
519 return ret;
522 static void git_config_push_split_parameter(const char *key, const char *value)
524 struct strbuf env = STRBUF_INIT;
525 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
526 if (old && *old) {
527 strbuf_addstr(&env, old);
528 strbuf_addch(&env, ' ');
530 sq_quote_buf(&env, key);
531 strbuf_addch(&env, '=');
532 if (value)
533 sq_quote_buf(&env, value);
534 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
535 strbuf_release(&env);
538 void git_config_push_parameter(const char *text)
540 const char *value;
543 * When we see:
545 * section.subsection=with=equals.key=value
547 * we cannot tell if it means:
549 * [section "subsection=with=equals"]
550 * key = value
552 * or:
554 * [section]
555 * subsection = with=equals.key=value
557 * We parse left-to-right for the first "=", meaning we'll prefer to
558 * keep the value intact over the subsection. This is historical, but
559 * also sensible since values are more likely to contain odd or
560 * untrusted input than a section name.
562 * A missing equals is explicitly allowed (as a bool-only entry).
564 value = strchr(text, '=');
565 if (value) {
566 char *key = xmemdupz(text, value - text);
567 git_config_push_split_parameter(key, value + 1);
568 free(key);
569 } else {
570 git_config_push_split_parameter(text, NULL);
574 void git_config_push_env(const char *spec)
576 char *key;
577 const char *env_name;
578 const char *env_value;
580 env_name = strrchr(spec, '=');
581 if (!env_name)
582 die(_("invalid config format: %s"), spec);
583 key = xmemdupz(spec, env_name - spec);
584 env_name++;
585 if (!*env_name)
586 die(_("missing environment variable name for configuration '%.*s'"),
587 (int)(env_name - spec - 1), spec);
589 env_value = getenv(env_name);
590 if (!env_value)
591 die(_("missing environment variable '%s' for configuration '%.*s'"),
592 env_name, (int)(env_name - spec - 1), spec);
594 git_config_push_split_parameter(key, env_value);
595 free(key);
598 static inline int iskeychar(int c)
600 return isalnum(c) || c == '-';
604 * Auxiliary function to sanity-check and split the key into the section
605 * identifier and variable name.
607 * Returns 0 on success, -1 when there is an invalid character in the key and
608 * -2 if there is no section name in the key.
610 * store_key - pointer to char* which will hold a copy of the key with
611 * lowercase section and variable name
612 * baselen - pointer to size_t which will hold the length of the
613 * section + subsection part, can be NULL
615 int git_config_parse_key(const char *key, char **store_key, size_t *baselen_)
617 size_t i, baselen;
618 int dot;
619 const char *last_dot = strrchr(key, '.');
622 * Since "key" actually contains the section name and the real
623 * key name separated by a dot, we have to know where the dot is.
626 if (last_dot == NULL || last_dot == key) {
627 error(_("key does not contain a section: %s"), key);
628 return -CONFIG_NO_SECTION_OR_NAME;
631 if (!last_dot[1]) {
632 error(_("key does not contain variable name: %s"), key);
633 return -CONFIG_NO_SECTION_OR_NAME;
636 baselen = last_dot - key;
637 if (baselen_)
638 *baselen_ = baselen;
641 * Validate the key and while at it, lower case it for matching.
643 *store_key = xmallocz(strlen(key));
645 dot = 0;
646 for (i = 0; key[i]; i++) {
647 unsigned char c = key[i];
648 if (c == '.')
649 dot = 1;
650 /* Leave the extended basename untouched.. */
651 if (!dot || i > baselen) {
652 if (!iskeychar(c) ||
653 (i == baselen + 1 && !isalpha(c))) {
654 error(_("invalid key: %s"), key);
655 goto out_free_ret_1;
657 c = tolower(c);
658 } else if (c == '\n') {
659 error(_("invalid key (newline): %s"), key);
660 goto out_free_ret_1;
662 (*store_key)[i] = c;
665 return 0;
667 out_free_ret_1:
668 FREE_AND_NULL(*store_key);
669 return -CONFIG_INVALID_KEY;
672 static int config_parse_pair(const char *key, const char *value,
673 config_fn_t fn, void *data)
675 char *canonical_name;
676 int ret;
678 if (!strlen(key))
679 return error(_("empty config key"));
680 if (git_config_parse_key(key, &canonical_name, NULL))
681 return -1;
683 ret = (fn(canonical_name, value, data) < 0) ? -1 : 0;
684 free(canonical_name);
685 return ret;
688 int git_config_parse_parameter(const char *text,
689 config_fn_t fn, void *data)
691 const char *value;
692 struct strbuf **pair;
693 int ret;
695 pair = strbuf_split_str(text, '=', 2);
696 if (!pair[0])
697 return error(_("bogus config parameter: %s"), text);
699 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
700 strbuf_setlen(pair[0], pair[0]->len - 1);
701 value = pair[1] ? pair[1]->buf : "";
702 } else {
703 value = NULL;
706 strbuf_trim(pair[0]);
707 if (!pair[0]->len) {
708 strbuf_list_free(pair);
709 return error(_("bogus config parameter: %s"), text);
712 ret = config_parse_pair(pair[0]->buf, value, fn, data);
713 strbuf_list_free(pair);
714 return ret;
717 static int parse_config_env_list(char *env, config_fn_t fn, void *data)
719 char *cur = env;
720 while (cur && *cur) {
721 const char *key = sq_dequote_step(cur, &cur);
722 if (!key)
723 return error(_("bogus format in %s"),
724 CONFIG_DATA_ENVIRONMENT);
726 if (!cur || isspace(*cur)) {
727 /* old-style 'key=value' */
728 if (git_config_parse_parameter(key, fn, data) < 0)
729 return -1;
731 else if (*cur == '=') {
732 /* new-style 'key'='value' */
733 const char *value;
735 cur++;
736 if (*cur == '\'') {
737 /* quoted value */
738 value = sq_dequote_step(cur, &cur);
739 if (!value || (cur && !isspace(*cur))) {
740 return error(_("bogus format in %s"),
741 CONFIG_DATA_ENVIRONMENT);
743 } else if (!*cur || isspace(*cur)) {
744 /* implicit bool: 'key'= */
745 value = NULL;
746 } else {
747 return error(_("bogus format in %s"),
748 CONFIG_DATA_ENVIRONMENT);
751 if (config_parse_pair(key, value, fn, data) < 0)
752 return -1;
754 else {
755 /* unknown format */
756 return error(_("bogus format in %s"),
757 CONFIG_DATA_ENVIRONMENT);
760 if (cur) {
761 while (isspace(*cur))
762 cur++;
765 return 0;
768 int git_config_from_parameters(config_fn_t fn, void *data)
770 const char *env;
771 struct strbuf envvar = STRBUF_INIT;
772 struct strvec to_free = STRVEC_INIT;
773 int ret = 0;
774 char *envw = NULL;
775 struct config_source source = CONFIG_SOURCE_INIT;
777 source.origin_type = CONFIG_ORIGIN_CMDLINE;
778 config_reader_push_source(&the_reader, &source);
780 env = getenv(CONFIG_COUNT_ENVIRONMENT);
781 if (env) {
782 unsigned long count;
783 char *endp;
784 int i;
786 count = strtoul(env, &endp, 10);
787 if (*endp) {
788 ret = error(_("bogus count in %s"), CONFIG_COUNT_ENVIRONMENT);
789 goto out;
791 if (count > INT_MAX) {
792 ret = error(_("too many entries in %s"), CONFIG_COUNT_ENVIRONMENT);
793 goto out;
796 for (i = 0; i < count; i++) {
797 const char *key, *value;
799 strbuf_addf(&envvar, "GIT_CONFIG_KEY_%d", i);
800 key = getenv_safe(&to_free, envvar.buf);
801 if (!key) {
802 ret = error(_("missing config key %s"), envvar.buf);
803 goto out;
805 strbuf_reset(&envvar);
807 strbuf_addf(&envvar, "GIT_CONFIG_VALUE_%d", i);
808 value = getenv_safe(&to_free, envvar.buf);
809 if (!value) {
810 ret = error(_("missing config value %s"), envvar.buf);
811 goto out;
813 strbuf_reset(&envvar);
815 if (config_parse_pair(key, value, fn, data) < 0) {
816 ret = -1;
817 goto out;
822 env = getenv(CONFIG_DATA_ENVIRONMENT);
823 if (env) {
824 /* sq_dequote will write over it */
825 envw = xstrdup(env);
826 if (parse_config_env_list(envw, fn, data) < 0) {
827 ret = -1;
828 goto out;
832 out:
833 strbuf_release(&envvar);
834 strvec_clear(&to_free);
835 free(envw);
836 config_reader_pop_source(&the_reader);
837 return ret;
840 static int get_next_char(struct config_source *cs)
842 int c = cs->do_fgetc(cs);
844 if (c == '\r') {
845 /* DOS like systems */
846 c = cs->do_fgetc(cs);
847 if (c != '\n') {
848 if (c != EOF)
849 cs->do_ungetc(c, cs);
850 c = '\r';
854 if (c != EOF && ++cs->total_len > INT_MAX) {
856 * This is an absurdly long config file; refuse to parse
857 * further in order to protect downstream code from integer
858 * overflows. Note that we can't return an error specifically,
859 * but we can mark EOF and put trash in the return value,
860 * which will trigger a parse error.
862 cs->eof = 1;
863 return 0;
866 if (c == '\n')
867 cs->linenr++;
868 if (c == EOF) {
869 cs->eof = 1;
870 cs->linenr++;
871 c = '\n';
873 return c;
876 static char *parse_value(struct config_source *cs)
878 int quote = 0, comment = 0, space = 0;
880 strbuf_reset(&cs->value);
881 for (;;) {
882 int c = get_next_char(cs);
883 if (c == '\n') {
884 if (quote) {
885 cs->linenr--;
886 return NULL;
888 return cs->value.buf;
890 if (comment)
891 continue;
892 if (isspace(c) && !quote) {
893 if (cs->value.len)
894 space++;
895 continue;
897 if (!quote) {
898 if (c == ';' || c == '#') {
899 comment = 1;
900 continue;
903 for (; space; space--)
904 strbuf_addch(&cs->value, ' ');
905 if (c == '\\') {
906 c = get_next_char(cs);
907 switch (c) {
908 case '\n':
909 continue;
910 case 't':
911 c = '\t';
912 break;
913 case 'b':
914 c = '\b';
915 break;
916 case 'n':
917 c = '\n';
918 break;
919 /* Some characters escape as themselves */
920 case '\\': case '"':
921 break;
922 /* Reject unknown escape sequences */
923 default:
924 return NULL;
926 strbuf_addch(&cs->value, c);
927 continue;
929 if (c == '"') {
930 quote = 1-quote;
931 continue;
933 strbuf_addch(&cs->value, c);
937 static int get_value(struct config_source *cs, config_fn_t fn, void *data,
938 struct strbuf *name)
940 int c;
941 char *value;
942 int ret;
944 /* Get the full name */
945 for (;;) {
946 c = get_next_char(cs);
947 if (cs->eof)
948 break;
949 if (!iskeychar(c))
950 break;
951 strbuf_addch(name, tolower(c));
954 while (c == ' ' || c == '\t')
955 c = get_next_char(cs);
957 value = NULL;
958 if (c != '\n') {
959 if (c != '=')
960 return -1;
961 value = parse_value(cs);
962 if (!value)
963 return -1;
966 * We already consumed the \n, but we need linenr to point to
967 * the line we just parsed during the call to fn to get
968 * accurate line number in error messages.
970 cs->linenr--;
971 ret = fn(name->buf, value, data);
972 if (ret >= 0)
973 cs->linenr++;
974 return ret;
977 static int get_extended_base_var(struct config_source *cs, struct strbuf *name,
978 int c)
980 cs->subsection_case_sensitive = 0;
981 do {
982 if (c == '\n')
983 goto error_incomplete_line;
984 c = get_next_char(cs);
985 } while (isspace(c));
987 /* We require the format to be '[base "extension"]' */
988 if (c != '"')
989 return -1;
990 strbuf_addch(name, '.');
992 for (;;) {
993 int c = get_next_char(cs);
994 if (c == '\n')
995 goto error_incomplete_line;
996 if (c == '"')
997 break;
998 if (c == '\\') {
999 c = get_next_char(cs);
1000 if (c == '\n')
1001 goto error_incomplete_line;
1003 strbuf_addch(name, c);
1006 /* Final ']' */
1007 if (get_next_char(cs) != ']')
1008 return -1;
1009 return 0;
1010 error_incomplete_line:
1011 cs->linenr--;
1012 return -1;
1015 static int get_base_var(struct config_source *cs, struct strbuf *name)
1017 cs->subsection_case_sensitive = 1;
1018 for (;;) {
1019 int c = get_next_char(cs);
1020 if (cs->eof)
1021 return -1;
1022 if (c == ']')
1023 return 0;
1024 if (isspace(c))
1025 return get_extended_base_var(cs, name, c);
1026 if (!iskeychar(c) && c != '.')
1027 return -1;
1028 strbuf_addch(name, tolower(c));
1032 struct parse_event_data {
1033 enum config_event_t previous_type;
1034 size_t previous_offset;
1035 const struct config_options *opts;
1038 static int do_event(struct config_source *cs, enum config_event_t type,
1039 struct parse_event_data *data)
1041 size_t offset;
1043 if (!data->opts || !data->opts->event_fn)
1044 return 0;
1046 if (type == CONFIG_EVENT_WHITESPACE &&
1047 data->previous_type == type)
1048 return 0;
1050 offset = cs->do_ftell(cs);
1052 * At EOF, the parser always "inserts" an extra '\n', therefore
1053 * the end offset of the event is the current file position, otherwise
1054 * we will already have advanced to the next event.
1056 if (type != CONFIG_EVENT_EOF)
1057 offset--;
1059 if (data->previous_type != CONFIG_EVENT_EOF &&
1060 data->opts->event_fn(data->previous_type, data->previous_offset,
1061 offset, data->opts->event_fn_data) < 0)
1062 return -1;
1064 data->previous_type = type;
1065 data->previous_offset = offset;
1067 return 0;
1070 static int git_parse_source(struct config_source *cs, config_fn_t fn,
1071 void *data, const struct config_options *opts)
1073 int comment = 0;
1074 size_t baselen = 0;
1075 struct strbuf *var = &cs->var;
1076 int error_return = 0;
1077 char *error_msg = NULL;
1079 /* U+FEFF Byte Order Mark in UTF8 */
1080 const char *bomptr = utf8_bom;
1082 /* For the parser event callback */
1083 struct parse_event_data event_data = {
1084 CONFIG_EVENT_EOF, 0, opts
1087 for (;;) {
1088 int c;
1090 c = get_next_char(cs);
1091 if (bomptr && *bomptr) {
1092 /* We are at the file beginning; skip UTF8-encoded BOM
1093 * if present. Sane editors won't put this in on their
1094 * own, but e.g. Windows Notepad will do it happily. */
1095 if (c == (*bomptr & 0377)) {
1096 bomptr++;
1097 continue;
1098 } else {
1099 /* Do not tolerate partial BOM. */
1100 if (bomptr != utf8_bom)
1101 break;
1102 /* No BOM at file beginning. Cool. */
1103 bomptr = NULL;
1106 if (c == '\n') {
1107 if (cs->eof) {
1108 if (do_event(cs, CONFIG_EVENT_EOF, &event_data) < 0)
1109 return -1;
1110 return 0;
1112 if (do_event(cs, CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1113 return -1;
1114 comment = 0;
1115 continue;
1117 if (comment)
1118 continue;
1119 if (isspace(c)) {
1120 if (do_event(cs, CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1121 return -1;
1122 continue;
1124 if (c == '#' || c == ';') {
1125 if (do_event(cs, CONFIG_EVENT_COMMENT, &event_data) < 0)
1126 return -1;
1127 comment = 1;
1128 continue;
1130 if (c == '[') {
1131 if (do_event(cs, CONFIG_EVENT_SECTION, &event_data) < 0)
1132 return -1;
1134 /* Reset prior to determining a new stem */
1135 strbuf_reset(var);
1136 if (get_base_var(cs, var) < 0 || var->len < 1)
1137 break;
1138 strbuf_addch(var, '.');
1139 baselen = var->len;
1140 continue;
1142 if (!isalpha(c))
1143 break;
1145 if (do_event(cs, CONFIG_EVENT_ENTRY, &event_data) < 0)
1146 return -1;
1149 * Truncate the var name back to the section header
1150 * stem prior to grabbing the suffix part of the name
1151 * and the value.
1153 strbuf_setlen(var, baselen);
1154 strbuf_addch(var, tolower(c));
1155 if (get_value(cs, fn, data, var) < 0)
1156 break;
1159 if (do_event(cs, CONFIG_EVENT_ERROR, &event_data) < 0)
1160 return -1;
1162 switch (cs->origin_type) {
1163 case CONFIG_ORIGIN_BLOB:
1164 error_msg = xstrfmt(_("bad config line %d in blob %s"),
1165 cs->linenr, cs->name);
1166 break;
1167 case CONFIG_ORIGIN_FILE:
1168 error_msg = xstrfmt(_("bad config line %d in file %s"),
1169 cs->linenr, cs->name);
1170 break;
1171 case CONFIG_ORIGIN_STDIN:
1172 error_msg = xstrfmt(_("bad config line %d in standard input"),
1173 cs->linenr);
1174 break;
1175 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1176 error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
1177 cs->linenr, cs->name);
1178 break;
1179 case CONFIG_ORIGIN_CMDLINE:
1180 error_msg = xstrfmt(_("bad config line %d in command line %s"),
1181 cs->linenr, cs->name);
1182 break;
1183 default:
1184 error_msg = xstrfmt(_("bad config line %d in %s"),
1185 cs->linenr, cs->name);
1188 switch (opts && opts->error_action ?
1189 opts->error_action :
1190 cs->default_error_action) {
1191 case CONFIG_ERROR_DIE:
1192 die("%s", error_msg);
1193 break;
1194 case CONFIG_ERROR_ERROR:
1195 error_return = error("%s", error_msg);
1196 break;
1197 case CONFIG_ERROR_SILENT:
1198 error_return = -1;
1199 break;
1200 case CONFIG_ERROR_UNSET:
1201 BUG("config error action unset");
1204 free(error_msg);
1205 return error_return;
1208 static uintmax_t get_unit_factor(const char *end)
1210 if (!*end)
1211 return 1;
1212 else if (!strcasecmp(end, "k"))
1213 return 1024;
1214 else if (!strcasecmp(end, "m"))
1215 return 1024 * 1024;
1216 else if (!strcasecmp(end, "g"))
1217 return 1024 * 1024 * 1024;
1218 return 0;
1221 static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
1223 if (value && *value) {
1224 char *end;
1225 intmax_t val;
1226 intmax_t factor;
1228 if (max < 0)
1229 BUG("max must be a positive integer");
1231 errno = 0;
1232 val = strtoimax(value, &end, 0);
1233 if (errno == ERANGE)
1234 return 0;
1235 if (end == value) {
1236 errno = EINVAL;
1237 return 0;
1239 factor = get_unit_factor(end);
1240 if (!factor) {
1241 errno = EINVAL;
1242 return 0;
1244 if ((val < 0 && -max / factor > val) ||
1245 (val > 0 && max / factor < val)) {
1246 errno = ERANGE;
1247 return 0;
1249 val *= factor;
1250 *ret = val;
1251 return 1;
1253 errno = EINVAL;
1254 return 0;
1257 static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
1259 if (value && *value) {
1260 char *end;
1261 uintmax_t val;
1262 uintmax_t factor;
1264 /* negative values would be accepted by strtoumax */
1265 if (strchr(value, '-')) {
1266 errno = EINVAL;
1267 return 0;
1269 errno = 0;
1270 val = strtoumax(value, &end, 0);
1271 if (errno == ERANGE)
1272 return 0;
1273 if (end == value) {
1274 errno = EINVAL;
1275 return 0;
1277 factor = get_unit_factor(end);
1278 if (!factor) {
1279 errno = EINVAL;
1280 return 0;
1282 if (unsigned_mult_overflows(factor, val) ||
1283 factor * val > max) {
1284 errno = ERANGE;
1285 return 0;
1287 val *= factor;
1288 *ret = val;
1289 return 1;
1291 errno = EINVAL;
1292 return 0;
1295 int git_parse_int(const char *value, int *ret)
1297 intmax_t tmp;
1298 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
1299 return 0;
1300 *ret = tmp;
1301 return 1;
1304 static int git_parse_int64(const char *value, int64_t *ret)
1306 intmax_t tmp;
1307 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
1308 return 0;
1309 *ret = tmp;
1310 return 1;
1313 int git_parse_ulong(const char *value, unsigned long *ret)
1315 uintmax_t tmp;
1316 if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
1317 return 0;
1318 *ret = tmp;
1319 return 1;
1322 int git_parse_ssize_t(const char *value, ssize_t *ret)
1324 intmax_t tmp;
1325 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(ssize_t)))
1326 return 0;
1327 *ret = tmp;
1328 return 1;
1331 static int reader_config_name(struct config_reader *reader, const char **out);
1332 static int reader_origin_type(struct config_reader *reader,
1333 enum config_origin_type *type);
1334 NORETURN
1335 static void die_bad_number(struct config_reader *reader, const char *name,
1336 const char *value)
1338 const char *error_type = (errno == ERANGE) ?
1339 N_("out of range") : N_("invalid unit");
1340 const char *bad_numeric = N_("bad numeric config value '%s' for '%s': %s");
1341 const char *config_name = NULL;
1342 enum config_origin_type config_origin = CONFIG_ORIGIN_UNKNOWN;
1344 if (!value)
1345 value = "";
1347 /* Ignoring the return value is okay since we handle missing values. */
1348 reader_config_name(reader, &config_name);
1349 reader_origin_type(reader, &config_origin);
1351 if (!config_name)
1352 die(_(bad_numeric), value, name, _(error_type));
1354 switch (config_origin) {
1355 case CONFIG_ORIGIN_BLOB:
1356 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
1357 value, name, config_name, _(error_type));
1358 case CONFIG_ORIGIN_FILE:
1359 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
1360 value, name, config_name, _(error_type));
1361 case CONFIG_ORIGIN_STDIN:
1362 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
1363 value, name, _(error_type));
1364 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1365 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
1366 value, name, config_name, _(error_type));
1367 case CONFIG_ORIGIN_CMDLINE:
1368 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
1369 value, name, config_name, _(error_type));
1370 default:
1371 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
1372 value, name, config_name, _(error_type));
1376 int git_config_int(const char *name, const char *value)
1378 int ret;
1379 if (!git_parse_int(value, &ret))
1380 die_bad_number(&the_reader, name, value);
1381 return ret;
1384 int64_t git_config_int64(const char *name, const char *value)
1386 int64_t ret;
1387 if (!git_parse_int64(value, &ret))
1388 die_bad_number(&the_reader, name, value);
1389 return ret;
1392 unsigned long git_config_ulong(const char *name, const char *value)
1394 unsigned long ret;
1395 if (!git_parse_ulong(value, &ret))
1396 die_bad_number(&the_reader, name, value);
1397 return ret;
1400 ssize_t git_config_ssize_t(const char *name, const char *value)
1402 ssize_t ret;
1403 if (!git_parse_ssize_t(value, &ret))
1404 die_bad_number(&the_reader, name, value);
1405 return ret;
1408 static int git_parse_maybe_bool_text(const char *value)
1410 if (!value)
1411 return 1;
1412 if (!*value)
1413 return 0;
1414 if (!strcasecmp(value, "true")
1415 || !strcasecmp(value, "yes")
1416 || !strcasecmp(value, "on"))
1417 return 1;
1418 if (!strcasecmp(value, "false")
1419 || !strcasecmp(value, "no")
1420 || !strcasecmp(value, "off"))
1421 return 0;
1422 return -1;
1425 static const struct fsync_component_name {
1426 const char *name;
1427 enum fsync_component component_bits;
1428 } fsync_component_names[] = {
1429 { "loose-object", FSYNC_COMPONENT_LOOSE_OBJECT },
1430 { "pack", FSYNC_COMPONENT_PACK },
1431 { "pack-metadata", FSYNC_COMPONENT_PACK_METADATA },
1432 { "commit-graph", FSYNC_COMPONENT_COMMIT_GRAPH },
1433 { "index", FSYNC_COMPONENT_INDEX },
1434 { "objects", FSYNC_COMPONENTS_OBJECTS },
1435 { "reference", FSYNC_COMPONENT_REFERENCE },
1436 { "derived-metadata", FSYNC_COMPONENTS_DERIVED_METADATA },
1437 { "committed", FSYNC_COMPONENTS_COMMITTED },
1438 { "added", FSYNC_COMPONENTS_ADDED },
1439 { "all", FSYNC_COMPONENTS_ALL },
1442 static enum fsync_component parse_fsync_components(const char *var, const char *string)
1444 enum fsync_component current = FSYNC_COMPONENTS_PLATFORM_DEFAULT;
1445 enum fsync_component positive = 0, negative = 0;
1447 while (string) {
1448 int i;
1449 size_t len;
1450 const char *ep;
1451 int negated = 0;
1452 int found = 0;
1454 string = string + strspn(string, ", \t\n\r");
1455 ep = strchrnul(string, ',');
1456 len = ep - string;
1457 if (!strcmp(string, "none")) {
1458 current = FSYNC_COMPONENT_NONE;
1459 goto next_name;
1462 if (*string == '-') {
1463 negated = 1;
1464 string++;
1465 len--;
1466 if (!len)
1467 warning(_("invalid value for variable %s"), var);
1470 if (!len)
1471 break;
1473 for (i = 0; i < ARRAY_SIZE(fsync_component_names); ++i) {
1474 const struct fsync_component_name *n = &fsync_component_names[i];
1476 if (strncmp(n->name, string, len))
1477 continue;
1479 found = 1;
1480 if (negated)
1481 negative |= n->component_bits;
1482 else
1483 positive |= n->component_bits;
1486 if (!found) {
1487 char *component = xstrndup(string, len);
1488 warning(_("ignoring unknown core.fsync component '%s'"), component);
1489 free(component);
1492 next_name:
1493 string = ep;
1496 return (current & ~negative) | positive;
1499 int git_parse_maybe_bool(const char *value)
1501 int v = git_parse_maybe_bool_text(value);
1502 if (0 <= v)
1503 return v;
1504 if (git_parse_int(value, &v))
1505 return !!v;
1506 return -1;
1509 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
1511 int v = git_parse_maybe_bool_text(value);
1512 if (0 <= v) {
1513 *is_bool = 1;
1514 return v;
1516 *is_bool = 0;
1517 return git_config_int(name, value);
1520 int git_config_bool(const char *name, const char *value)
1522 int v = git_parse_maybe_bool(value);
1523 if (v < 0)
1524 die(_("bad boolean config value '%s' for '%s'"), value, name);
1525 return v;
1528 int git_config_string(const char **dest, const char *var, const char *value)
1530 if (!value)
1531 return config_error_nonbool(var);
1532 *dest = xstrdup(value);
1533 return 0;
1536 int git_config_pathname(const char **dest, const char *var, const char *value)
1538 if (!value)
1539 return config_error_nonbool(var);
1540 *dest = interpolate_path(value, 0);
1541 if (!*dest)
1542 die(_("failed to expand user dir in: '%s'"), value);
1543 return 0;
1546 int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1548 if (!value)
1549 return config_error_nonbool(var);
1550 if (parse_expiry_date(value, timestamp))
1551 return error(_("'%s' for '%s' is not a valid timestamp"),
1552 value, var);
1553 return 0;
1556 int git_config_color(char *dest, const char *var, const char *value)
1558 if (!value)
1559 return config_error_nonbool(var);
1560 if (color_parse(value, dest) < 0)
1561 return -1;
1562 return 0;
1565 static int git_default_core_config(const char *var, const char *value, void *cb)
1567 /* This needs a better name */
1568 if (!strcmp(var, "core.filemode")) {
1569 trust_executable_bit = git_config_bool(var, value);
1570 return 0;
1572 if (!strcmp(var, "core.trustctime")) {
1573 trust_ctime = git_config_bool(var, value);
1574 return 0;
1576 if (!strcmp(var, "core.checkstat")) {
1577 if (!strcasecmp(value, "default"))
1578 check_stat = 1;
1579 else if (!strcasecmp(value, "minimal"))
1580 check_stat = 0;
1583 if (!strcmp(var, "core.quotepath")) {
1584 quote_path_fully = git_config_bool(var, value);
1585 return 0;
1588 if (!strcmp(var, "core.symlinks")) {
1589 has_symlinks = git_config_bool(var, value);
1590 return 0;
1593 if (!strcmp(var, "core.ignorecase")) {
1594 ignore_case = git_config_bool(var, value);
1595 return 0;
1598 if (!strcmp(var, "core.attributesfile"))
1599 return git_config_pathname(&git_attributes_file, var, value);
1601 if (!strcmp(var, "core.hookspath"))
1602 return git_config_pathname(&git_hooks_path, var, value);
1604 if (!strcmp(var, "core.bare")) {
1605 is_bare_repository_cfg = git_config_bool(var, value);
1606 return 0;
1609 if (!strcmp(var, "core.ignorestat")) {
1610 assume_unchanged = git_config_bool(var, value);
1611 return 0;
1614 if (!strcmp(var, "core.prefersymlinkrefs")) {
1615 prefer_symlink_refs = git_config_bool(var, value);
1616 return 0;
1619 if (!strcmp(var, "core.logallrefupdates")) {
1620 if (value && !strcasecmp(value, "always"))
1621 log_all_ref_updates = LOG_REFS_ALWAYS;
1622 else if (git_config_bool(var, value))
1623 log_all_ref_updates = LOG_REFS_NORMAL;
1624 else
1625 log_all_ref_updates = LOG_REFS_NONE;
1626 return 0;
1629 if (!strcmp(var, "core.warnambiguousrefs")) {
1630 warn_ambiguous_refs = git_config_bool(var, value);
1631 return 0;
1634 if (!strcmp(var, "core.abbrev")) {
1635 if (!value)
1636 return config_error_nonbool(var);
1637 if (!strcasecmp(value, "auto"))
1638 default_abbrev = -1;
1639 else if (!git_parse_maybe_bool_text(value))
1640 default_abbrev = the_hash_algo->hexsz;
1641 else {
1642 int abbrev = git_config_int(var, value);
1643 if (abbrev < minimum_abbrev || abbrev > the_hash_algo->hexsz)
1644 return error(_("abbrev length out of range: %d"), abbrev);
1645 default_abbrev = abbrev;
1647 return 0;
1650 if (!strcmp(var, "core.disambiguate"))
1651 return set_disambiguate_hint_config(var, value);
1653 if (!strcmp(var, "core.loosecompression")) {
1654 int level = git_config_int(var, value);
1655 if (level == -1)
1656 level = Z_DEFAULT_COMPRESSION;
1657 else if (level < 0 || level > Z_BEST_COMPRESSION)
1658 die(_("bad zlib compression level %d"), level);
1659 zlib_compression_level = level;
1660 zlib_compression_seen = 1;
1661 return 0;
1664 if (!strcmp(var, "core.compression")) {
1665 int level = git_config_int(var, value);
1666 if (level == -1)
1667 level = Z_DEFAULT_COMPRESSION;
1668 else if (level < 0 || level > Z_BEST_COMPRESSION)
1669 die(_("bad zlib compression level %d"), level);
1670 if (!zlib_compression_seen)
1671 zlib_compression_level = level;
1672 if (!pack_compression_seen)
1673 pack_compression_level = level;
1674 return 0;
1677 if (!strcmp(var, "core.packedgitwindowsize")) {
1678 int pgsz_x2 = getpagesize() * 2;
1679 packed_git_window_size = git_config_ulong(var, value);
1681 /* This value must be multiple of (pagesize * 2) */
1682 packed_git_window_size /= pgsz_x2;
1683 if (packed_git_window_size < 1)
1684 packed_git_window_size = 1;
1685 packed_git_window_size *= pgsz_x2;
1686 return 0;
1689 if (!strcmp(var, "core.bigfilethreshold")) {
1690 big_file_threshold = git_config_ulong(var, value);
1691 return 0;
1694 if (!strcmp(var, "core.packedgitlimit")) {
1695 packed_git_limit = git_config_ulong(var, value);
1696 return 0;
1699 if (!strcmp(var, "core.deltabasecachelimit")) {
1700 delta_base_cache_limit = git_config_ulong(var, value);
1701 return 0;
1704 if (!strcmp(var, "core.autocrlf")) {
1705 if (value && !strcasecmp(value, "input")) {
1706 auto_crlf = AUTO_CRLF_INPUT;
1707 return 0;
1709 auto_crlf = git_config_bool(var, value);
1710 return 0;
1713 if (!strcmp(var, "core.safecrlf")) {
1714 int eol_rndtrp_die;
1715 if (value && !strcasecmp(value, "warn")) {
1716 global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
1717 return 0;
1719 eol_rndtrp_die = git_config_bool(var, value);
1720 global_conv_flags_eol = eol_rndtrp_die ?
1721 CONV_EOL_RNDTRP_DIE : 0;
1722 return 0;
1725 if (!strcmp(var, "core.eol")) {
1726 if (value && !strcasecmp(value, "lf"))
1727 core_eol = EOL_LF;
1728 else if (value && !strcasecmp(value, "crlf"))
1729 core_eol = EOL_CRLF;
1730 else if (value && !strcasecmp(value, "native"))
1731 core_eol = EOL_NATIVE;
1732 else
1733 core_eol = EOL_UNSET;
1734 return 0;
1737 if (!strcmp(var, "core.checkroundtripencoding")) {
1738 check_roundtrip_encoding = xstrdup(value);
1739 return 0;
1742 if (!strcmp(var, "core.notesref")) {
1743 notes_ref_name = xstrdup(value);
1744 return 0;
1747 if (!strcmp(var, "core.editor"))
1748 return git_config_string(&editor_program, var, value);
1750 if (!strcmp(var, "core.commentchar")) {
1751 if (!value)
1752 return config_error_nonbool(var);
1753 else if (!strcasecmp(value, "auto"))
1754 auto_comment_line_char = 1;
1755 else if (value[0] && !value[1]) {
1756 comment_line_char = value[0];
1757 auto_comment_line_char = 0;
1758 } else
1759 return error(_("core.commentChar should only be one ASCII character"));
1760 return 0;
1763 if (!strcmp(var, "core.askpass"))
1764 return git_config_string(&askpass_program, var, value);
1766 if (!strcmp(var, "core.excludesfile"))
1767 return git_config_pathname(&excludes_file, var, value);
1769 if (!strcmp(var, "core.whitespace")) {
1770 if (!value)
1771 return config_error_nonbool(var);
1772 whitespace_rule_cfg = parse_whitespace_rule(value);
1773 return 0;
1776 if (!strcmp(var, "core.fsync")) {
1777 if (!value)
1778 return config_error_nonbool(var);
1779 fsync_components = parse_fsync_components(var, value);
1780 return 0;
1783 if (!strcmp(var, "core.fsyncmethod")) {
1784 if (!value)
1785 return config_error_nonbool(var);
1786 if (!strcmp(value, "fsync"))
1787 fsync_method = FSYNC_METHOD_FSYNC;
1788 else if (!strcmp(value, "writeout-only"))
1789 fsync_method = FSYNC_METHOD_WRITEOUT_ONLY;
1790 else if (!strcmp(value, "batch"))
1791 fsync_method = FSYNC_METHOD_BATCH;
1792 else
1793 warning(_("ignoring unknown core.fsyncMethod value '%s'"), value);
1797 if (!strcmp(var, "core.fsyncobjectfiles")) {
1798 if (fsync_object_files < 0)
1799 warning(_("core.fsyncObjectFiles is deprecated; use core.fsync instead"));
1800 fsync_object_files = git_config_bool(var, value);
1801 return 0;
1804 if (!strcmp(var, "core.preloadindex")) {
1805 core_preload_index = git_config_bool(var, value);
1806 return 0;
1809 if (!strcmp(var, "core.createobject")) {
1810 if (!strcmp(value, "rename"))
1811 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
1812 else if (!strcmp(value, "link"))
1813 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
1814 else
1815 die(_("invalid mode for object creation: %s"), value);
1816 return 0;
1819 if (!strcmp(var, "core.sparsecheckout")) {
1820 core_apply_sparse_checkout = git_config_bool(var, value);
1821 return 0;
1824 if (!strcmp(var, "core.sparsecheckoutcone")) {
1825 core_sparse_checkout_cone = git_config_bool(var, value);
1826 return 0;
1829 if (!strcmp(var, "core.precomposeunicode")) {
1830 precomposed_unicode = git_config_bool(var, value);
1831 return 0;
1834 if (!strcmp(var, "core.protecthfs")) {
1835 protect_hfs = git_config_bool(var, value);
1836 return 0;
1839 if (!strcmp(var, "core.protectntfs")) {
1840 protect_ntfs = git_config_bool(var, value);
1841 return 0;
1844 /* Add other config variables here and to Documentation/config.txt. */
1845 return platform_core_config(var, value, cb);
1848 static int git_default_sparse_config(const char *var, const char *value)
1850 if (!strcmp(var, "sparse.expectfilesoutsideofpatterns")) {
1851 sparse_expect_files_outside_of_patterns = git_config_bool(var, value);
1852 return 0;
1855 /* Add other config variables here and to Documentation/config/sparse.txt. */
1856 return 0;
1859 static int git_default_i18n_config(const char *var, const char *value)
1861 if (!strcmp(var, "i18n.commitencoding"))
1862 return git_config_string(&git_commit_encoding, var, value);
1864 if (!strcmp(var, "i18n.logoutputencoding"))
1865 return git_config_string(&git_log_output_encoding, var, value);
1867 /* Add other config variables here and to Documentation/config.txt. */
1868 return 0;
1871 static int git_default_branch_config(const char *var, const char *value)
1873 if (!strcmp(var, "branch.autosetupmerge")) {
1874 if (value && !strcmp(value, "always")) {
1875 git_branch_track = BRANCH_TRACK_ALWAYS;
1876 return 0;
1877 } else if (value && !strcmp(value, "inherit")) {
1878 git_branch_track = BRANCH_TRACK_INHERIT;
1879 return 0;
1880 } else if (value && !strcmp(value, "simple")) {
1881 git_branch_track = BRANCH_TRACK_SIMPLE;
1882 return 0;
1884 git_branch_track = git_config_bool(var, value);
1885 return 0;
1887 if (!strcmp(var, "branch.autosetuprebase")) {
1888 if (!value)
1889 return config_error_nonbool(var);
1890 else if (!strcmp(value, "never"))
1891 autorebase = AUTOREBASE_NEVER;
1892 else if (!strcmp(value, "local"))
1893 autorebase = AUTOREBASE_LOCAL;
1894 else if (!strcmp(value, "remote"))
1895 autorebase = AUTOREBASE_REMOTE;
1896 else if (!strcmp(value, "always"))
1897 autorebase = AUTOREBASE_ALWAYS;
1898 else
1899 return error(_("malformed value for %s"), var);
1900 return 0;
1903 /* Add other config variables here and to Documentation/config.txt. */
1904 return 0;
1907 static int git_default_push_config(const char *var, const char *value)
1909 if (!strcmp(var, "push.default")) {
1910 if (!value)
1911 return config_error_nonbool(var);
1912 else if (!strcmp(value, "nothing"))
1913 push_default = PUSH_DEFAULT_NOTHING;
1914 else if (!strcmp(value, "matching"))
1915 push_default = PUSH_DEFAULT_MATCHING;
1916 else if (!strcmp(value, "simple"))
1917 push_default = PUSH_DEFAULT_SIMPLE;
1918 else if (!strcmp(value, "upstream"))
1919 push_default = PUSH_DEFAULT_UPSTREAM;
1920 else if (!strcmp(value, "tracking")) /* deprecated */
1921 push_default = PUSH_DEFAULT_UPSTREAM;
1922 else if (!strcmp(value, "current"))
1923 push_default = PUSH_DEFAULT_CURRENT;
1924 else {
1925 error(_("malformed value for %s: %s"), var, value);
1926 return error(_("must be one of nothing, matching, simple, "
1927 "upstream or current"));
1929 return 0;
1932 /* Add other config variables here and to Documentation/config.txt. */
1933 return 0;
1936 static int git_default_mailmap_config(const char *var, const char *value)
1938 if (!strcmp(var, "mailmap.file"))
1939 return git_config_pathname(&git_mailmap_file, var, value);
1940 if (!strcmp(var, "mailmap.blob"))
1941 return git_config_string(&git_mailmap_blob, var, value);
1943 /* Add other config variables here and to Documentation/config.txt. */
1944 return 0;
1947 int git_default_config(const char *var, const char *value, void *cb)
1949 if (starts_with(var, "core."))
1950 return git_default_core_config(var, value, cb);
1952 if (starts_with(var, "user.") ||
1953 starts_with(var, "author.") ||
1954 starts_with(var, "committer."))
1955 return git_ident_config(var, value, cb);
1957 if (starts_with(var, "i18n."))
1958 return git_default_i18n_config(var, value);
1960 if (starts_with(var, "branch."))
1961 return git_default_branch_config(var, value);
1963 if (starts_with(var, "push."))
1964 return git_default_push_config(var, value);
1966 if (starts_with(var, "mailmap."))
1967 return git_default_mailmap_config(var, value);
1969 if (starts_with(var, "advice.") || starts_with(var, "color.advice"))
1970 return git_default_advice_config(var, value);
1972 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1973 pager_use_color = git_config_bool(var,value);
1974 return 0;
1977 if (!strcmp(var, "pack.packsizelimit")) {
1978 pack_size_limit_cfg = git_config_ulong(var, value);
1979 return 0;
1982 if (!strcmp(var, "pack.compression")) {
1983 int level = git_config_int(var, value);
1984 if (level == -1)
1985 level = Z_DEFAULT_COMPRESSION;
1986 else if (level < 0 || level > Z_BEST_COMPRESSION)
1987 die(_("bad pack compression level %d"), level);
1988 pack_compression_level = level;
1989 pack_compression_seen = 1;
1990 return 0;
1993 if (starts_with(var, "sparse."))
1994 return git_default_sparse_config(var, value);
1996 /* Add other config variables here and to Documentation/config.txt. */
1997 return 0;
2001 * All source specific fields in the union, die_on_error, name and the callbacks
2002 * fgetc, ungetc, ftell of top need to be initialized before calling
2003 * this function.
2005 static int do_config_from(struct config_reader *reader,
2006 struct config_source *top, config_fn_t fn, void *data,
2007 const struct config_options *opts)
2009 int ret;
2011 /* push config-file parsing state stack */
2012 top->linenr = 1;
2013 top->eof = 0;
2014 top->total_len = 0;
2015 strbuf_init(&top->value, 1024);
2016 strbuf_init(&top->var, 1024);
2017 config_reader_push_source(reader, top);
2019 ret = git_parse_source(top, fn, data, opts);
2021 /* pop config-file parsing state stack */
2022 strbuf_release(&top->value);
2023 strbuf_release(&top->var);
2024 config_reader_pop_source(reader);
2026 return ret;
2029 static int do_config_from_file(struct config_reader *reader,
2030 config_fn_t fn,
2031 const enum config_origin_type origin_type,
2032 const char *name, const char *path, FILE *f,
2033 void *data, const struct config_options *opts)
2035 struct config_source top = CONFIG_SOURCE_INIT;
2036 int ret;
2038 top.u.file = f;
2039 top.origin_type = origin_type;
2040 top.name = name;
2041 top.path = path;
2042 top.default_error_action = CONFIG_ERROR_DIE;
2043 top.do_fgetc = config_file_fgetc;
2044 top.do_ungetc = config_file_ungetc;
2045 top.do_ftell = config_file_ftell;
2047 flockfile(f);
2048 ret = do_config_from(reader, &top, fn, data, opts);
2049 funlockfile(f);
2050 return ret;
2053 static int git_config_from_stdin(config_fn_t fn, void *data)
2055 return do_config_from_file(&the_reader, fn, CONFIG_ORIGIN_STDIN, "",
2056 NULL, stdin, data, NULL);
2059 int git_config_from_file_with_options(config_fn_t fn, const char *filename,
2060 void *data,
2061 const struct config_options *opts)
2063 int ret = -1;
2064 FILE *f;
2066 if (!filename)
2067 BUG("filename cannot be NULL");
2068 f = fopen_or_warn(filename, "r");
2069 if (f) {
2070 ret = do_config_from_file(&the_reader, fn, CONFIG_ORIGIN_FILE,
2071 filename, filename, f, data, opts);
2072 fclose(f);
2074 return ret;
2077 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
2079 return git_config_from_file_with_options(fn, filename, data, NULL);
2082 int git_config_from_mem(config_fn_t fn,
2083 const enum config_origin_type origin_type,
2084 const char *name, const char *buf, size_t len,
2085 void *data, const struct config_options *opts)
2087 struct config_source top = CONFIG_SOURCE_INIT;
2089 top.u.buf.buf = buf;
2090 top.u.buf.len = len;
2091 top.u.buf.pos = 0;
2092 top.origin_type = origin_type;
2093 top.name = name;
2094 top.path = NULL;
2095 top.default_error_action = CONFIG_ERROR_ERROR;
2096 top.do_fgetc = config_buf_fgetc;
2097 top.do_ungetc = config_buf_ungetc;
2098 top.do_ftell = config_buf_ftell;
2100 return do_config_from(&the_reader, &top, fn, data, opts);
2103 int git_config_from_blob_oid(config_fn_t fn,
2104 const char *name,
2105 struct repository *repo,
2106 const struct object_id *oid,
2107 void *data)
2109 enum object_type type;
2110 char *buf;
2111 unsigned long size;
2112 int ret;
2114 buf = repo_read_object_file(repo, oid, &type, &size);
2115 if (!buf)
2116 return error(_("unable to load config blob object '%s'"), name);
2117 if (type != OBJ_BLOB) {
2118 free(buf);
2119 return error(_("reference '%s' does not point to a blob"), name);
2122 ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size,
2123 data, NULL);
2124 free(buf);
2126 return ret;
2129 static int git_config_from_blob_ref(config_fn_t fn,
2130 struct repository *repo,
2131 const char *name,
2132 void *data)
2134 struct object_id oid;
2136 if (repo_get_oid(repo, name, &oid) < 0)
2137 return error(_("unable to resolve config blob '%s'"), name);
2138 return git_config_from_blob_oid(fn, name, repo, &oid, data);
2141 char *git_system_config(void)
2143 char *system_config = xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
2144 if (!system_config)
2145 system_config = system_path(ETC_GITCONFIG);
2146 normalize_path_copy(system_config, system_config);
2147 return system_config;
2150 void git_global_config(char **user_out, char **xdg_out)
2152 char *user_config = xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
2153 char *xdg_config = NULL;
2155 if (!user_config) {
2156 user_config = interpolate_path("~/.gitconfig", 0);
2157 xdg_config = xdg_config_home("config");
2160 *user_out = user_config;
2161 *xdg_out = xdg_config;
2165 * Parse environment variable 'k' as a boolean (in various
2166 * possible spellings); if missing, use the default value 'def'.
2168 int git_env_bool(const char *k, int def)
2170 const char *v = getenv(k);
2171 return v ? git_config_bool(k, v) : def;
2175 * Parse environment variable 'k' as ulong with possibly a unit
2176 * suffix; if missing, use the default value 'val'.
2178 unsigned long git_env_ulong(const char *k, unsigned long val)
2180 const char *v = getenv(k);
2181 if (v && !git_parse_ulong(v, &val))
2182 die(_("failed to parse %s"), k);
2183 return val;
2186 int git_config_system(void)
2188 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
2191 static int do_git_config_sequence(struct config_reader *reader,
2192 const struct config_options *opts,
2193 const struct repository *repo,
2194 config_fn_t fn, void *data)
2196 int ret = 0;
2197 char *system_config = git_system_config();
2198 char *xdg_config = NULL;
2199 char *user_config = NULL;
2200 char *repo_config;
2201 char *worktree_config;
2202 enum config_scope prev_parsing_scope = reader->parsing_scope;
2205 * Ensure that either:
2206 * - the git_dir and commondir are both set, or
2207 * - the git_dir and commondir are both NULL
2209 if (!opts->git_dir != !opts->commondir)
2210 BUG("only one of commondir and git_dir is non-NULL");
2212 if (opts->commondir) {
2213 repo_config = mkpathdup("%s/config", opts->commondir);
2214 worktree_config = mkpathdup("%s/config.worktree", opts->git_dir);
2215 } else {
2216 repo_config = NULL;
2217 worktree_config = NULL;
2220 config_reader_set_scope(reader, CONFIG_SCOPE_SYSTEM);
2221 if (git_config_system() && system_config &&
2222 !access_or_die(system_config, R_OK,
2223 opts->system_gently ? ACCESS_EACCES_OK : 0))
2224 ret += git_config_from_file(fn, system_config, data);
2226 config_reader_set_scope(reader, CONFIG_SCOPE_GLOBAL);
2227 git_global_config(&user_config, &xdg_config);
2229 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
2230 ret += git_config_from_file(fn, xdg_config, data);
2232 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
2233 ret += git_config_from_file(fn, user_config, data);
2235 config_reader_set_scope(reader, CONFIG_SCOPE_LOCAL);
2236 if (!opts->ignore_repo && repo_config &&
2237 !access_or_die(repo_config, R_OK, 0))
2238 ret += git_config_from_file(fn, repo_config, data);
2240 config_reader_set_scope(reader, CONFIG_SCOPE_WORKTREE);
2241 if (!opts->ignore_worktree && worktree_config &&
2242 repo && repo->repository_format_worktree_config &&
2243 !access_or_die(worktree_config, R_OK, 0)) {
2244 ret += git_config_from_file(fn, worktree_config, data);
2247 config_reader_set_scope(reader, CONFIG_SCOPE_COMMAND);
2248 if (!opts->ignore_cmdline && git_config_from_parameters(fn, data) < 0)
2249 die(_("unable to parse command-line config"));
2251 config_reader_set_scope(reader, prev_parsing_scope);
2252 free(system_config);
2253 free(xdg_config);
2254 free(user_config);
2255 free(repo_config);
2256 free(worktree_config);
2257 return ret;
2260 int config_with_options(config_fn_t fn, void *data,
2261 struct git_config_source *config_source,
2262 struct repository *repo,
2263 const struct config_options *opts)
2265 struct config_include_data inc = CONFIG_INCLUDE_INIT;
2266 enum config_scope prev_scope = the_reader.parsing_scope;
2267 int ret;
2269 if (opts->respect_includes) {
2270 inc.fn = fn;
2271 inc.data = data;
2272 inc.opts = opts;
2273 inc.repo = repo;
2274 inc.config_source = config_source;
2275 inc.config_reader = &the_reader;
2276 fn = git_config_include;
2277 data = &inc;
2280 if (config_source)
2281 config_reader_set_scope(&the_reader, config_source->scope);
2284 * If we have a specific filename, use it. Otherwise, follow the
2285 * regular lookup sequence.
2287 if (config_source && config_source->use_stdin) {
2288 ret = git_config_from_stdin(fn, data);
2289 } else if (config_source && config_source->file) {
2290 ret = git_config_from_file(fn, config_source->file, data);
2291 } else if (config_source && config_source->blob) {
2292 ret = git_config_from_blob_ref(fn, repo, config_source->blob,
2293 data);
2294 } else {
2295 ret = do_git_config_sequence(&the_reader, opts, repo, fn, data);
2298 if (inc.remote_urls) {
2299 string_list_clear(inc.remote_urls, 0);
2300 FREE_AND_NULL(inc.remote_urls);
2302 config_reader_set_scope(&the_reader, prev_scope);
2303 return ret;
2306 static void configset_iter(struct config_reader *reader, struct config_set *set,
2307 config_fn_t fn, void *data)
2309 int i, value_index;
2310 struct string_list *values;
2311 struct config_set_element *entry;
2312 struct configset_list *list = &set->list;
2314 for (i = 0; i < list->nr; i++) {
2315 entry = list->items[i].e;
2316 value_index = list->items[i].value_index;
2317 values = &entry->value_list;
2319 config_reader_set_kvi(reader, values->items[value_index].util);
2321 if (fn(entry->key, values->items[value_index].string, data) < 0)
2322 git_die_config_linenr(entry->key,
2323 reader->config_kvi->filename,
2324 reader->config_kvi->linenr);
2326 config_reader_set_kvi(reader, NULL);
2330 void read_early_config(config_fn_t cb, void *data)
2332 struct config_options opts = {0};
2333 struct strbuf commondir = STRBUF_INIT;
2334 struct strbuf gitdir = STRBUF_INIT;
2336 opts.respect_includes = 1;
2338 if (have_git_dir()) {
2339 opts.commondir = get_git_common_dir();
2340 opts.git_dir = get_git_dir();
2342 * When setup_git_directory() was not yet asked to discover the
2343 * GIT_DIR, we ask discover_git_directory() to figure out whether there
2344 * is any repository config we should use (but unlike
2345 * setup_git_directory_gently(), no global state is changed, most
2346 * notably, the current working directory is still the same after the
2347 * call).
2349 } else if (!discover_git_directory(&commondir, &gitdir)) {
2350 opts.commondir = commondir.buf;
2351 opts.git_dir = gitdir.buf;
2354 config_with_options(cb, data, NULL, NULL, &opts);
2356 strbuf_release(&commondir);
2357 strbuf_release(&gitdir);
2361 * Read config but only enumerate system and global settings.
2362 * Omit any repo-local, worktree-local, or command-line settings.
2364 void read_very_early_config(config_fn_t cb, void *data)
2366 struct config_options opts = { 0 };
2368 opts.respect_includes = 1;
2369 opts.ignore_repo = 1;
2370 opts.ignore_worktree = 1;
2371 opts.ignore_cmdline = 1;
2372 opts.system_gently = 1;
2374 config_with_options(cb, data, NULL, NULL, &opts);
2377 RESULT_MUST_BE_USED
2378 static int configset_find_element(struct config_set *set, const char *key,
2379 struct config_set_element **dest)
2381 struct config_set_element k;
2382 struct config_set_element *found_entry;
2383 char *normalized_key;
2384 int ret;
2387 * `key` may come from the user, so normalize it before using it
2388 * for querying entries from the hashmap.
2390 ret = git_config_parse_key(key, &normalized_key, NULL);
2391 if (ret)
2392 return ret;
2394 hashmap_entry_init(&k.ent, strhash(normalized_key));
2395 k.key = normalized_key;
2396 found_entry = hashmap_get_entry(&set->config_hash, &k, ent, NULL);
2397 free(normalized_key);
2398 *dest = found_entry;
2399 return 0;
2402 static int configset_add_value(struct config_reader *reader,
2403 struct config_set *set, const char *key,
2404 const char *value)
2406 struct config_set_element *e;
2407 struct string_list_item *si;
2408 struct configset_list_item *l_item;
2409 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
2410 int ret;
2412 ret = configset_find_element(set, key, &e);
2413 if (ret)
2414 return ret;
2416 * Since the keys are being fed by git_config*() callback mechanism, they
2417 * are already normalized. So simply add them without any further munging.
2419 if (!e) {
2420 e = xmalloc(sizeof(*e));
2421 hashmap_entry_init(&e->ent, strhash(key));
2422 e->key = xstrdup(key);
2423 string_list_init_dup(&e->value_list);
2424 hashmap_add(&set->config_hash, &e->ent);
2426 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
2428 ALLOC_GROW(set->list.items, set->list.nr + 1, set->list.alloc);
2429 l_item = &set->list.items[set->list.nr++];
2430 l_item->e = e;
2431 l_item->value_index = e->value_list.nr - 1;
2433 if (!reader->source)
2434 BUG("configset_add_value has no source");
2435 if (reader->source->name) {
2436 kv_info->filename = strintern(reader->source->name);
2437 kv_info->linenr = reader->source->linenr;
2438 kv_info->origin_type = reader->source->origin_type;
2439 } else {
2440 /* for values read from `git_config_from_parameters()` */
2441 kv_info->filename = NULL;
2442 kv_info->linenr = -1;
2443 kv_info->origin_type = CONFIG_ORIGIN_CMDLINE;
2445 kv_info->scope = reader->parsing_scope;
2446 si->util = kv_info;
2448 return 0;
2451 static int config_set_element_cmp(const void *cmp_data UNUSED,
2452 const struct hashmap_entry *eptr,
2453 const struct hashmap_entry *entry_or_key,
2454 const void *keydata UNUSED)
2456 const struct config_set_element *e1, *e2;
2458 e1 = container_of(eptr, const struct config_set_element, ent);
2459 e2 = container_of(entry_or_key, const struct config_set_element, ent);
2461 return strcmp(e1->key, e2->key);
2464 void git_configset_init(struct config_set *set)
2466 hashmap_init(&set->config_hash, config_set_element_cmp, NULL, 0);
2467 set->hash_initialized = 1;
2468 set->list.nr = 0;
2469 set->list.alloc = 0;
2470 set->list.items = NULL;
2473 void git_configset_clear(struct config_set *set)
2475 struct config_set_element *entry;
2476 struct hashmap_iter iter;
2477 if (!set->hash_initialized)
2478 return;
2480 hashmap_for_each_entry(&set->config_hash, &iter, entry,
2481 ent /* member name */) {
2482 free(entry->key);
2483 string_list_clear(&entry->value_list, 1);
2485 hashmap_clear_and_free(&set->config_hash, struct config_set_element, ent);
2486 set->hash_initialized = 0;
2487 free(set->list.items);
2488 set->list.nr = 0;
2489 set->list.alloc = 0;
2490 set->list.items = NULL;
2493 struct configset_add_data {
2494 struct config_set *config_set;
2495 struct config_reader *config_reader;
2497 #define CONFIGSET_ADD_INIT { 0 }
2499 static int config_set_callback(const char *key, const char *value, void *cb)
2501 struct configset_add_data *data = cb;
2502 configset_add_value(data->config_reader, data->config_set, key, value);
2503 return 0;
2506 int git_configset_add_file(struct config_set *set, const char *filename)
2508 struct configset_add_data data = CONFIGSET_ADD_INIT;
2509 data.config_reader = &the_reader;
2510 data.config_set = set;
2511 return git_config_from_file(config_set_callback, filename, &data);
2514 int git_configset_get_value(struct config_set *set, const char *key, const char **value)
2516 const struct string_list *values = NULL;
2517 int ret;
2520 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
2521 * queried key in the files of the configset, the value returned will be the last
2522 * value in the value list for that key.
2524 if ((ret = git_configset_get_value_multi(set, key, &values)))
2525 return ret;
2527 assert(values->nr > 0);
2528 *value = values->items[values->nr - 1].string;
2529 return 0;
2532 int git_configset_get_value_multi(struct config_set *set, const char *key,
2533 const struct string_list **dest)
2535 struct config_set_element *e;
2536 int ret;
2538 if ((ret = configset_find_element(set, key, &e)))
2539 return ret;
2540 else if (!e)
2541 return 1;
2542 *dest = &e->value_list;
2544 return 0;
2547 static int check_multi_string(struct string_list_item *item, void *util)
2549 return item->string ? 0 : config_error_nonbool(util);
2552 int git_configset_get_string_multi(struct config_set *cs, const char *key,
2553 const struct string_list **dest)
2555 int ret;
2557 if ((ret = git_configset_get_value_multi(cs, key, dest)))
2558 return ret;
2559 if ((ret = for_each_string_list((struct string_list *)*dest,
2560 check_multi_string, (void *)key)))
2561 return ret;
2563 return 0;
2566 int git_configset_get(struct config_set *set, const char *key)
2568 struct config_set_element *e;
2569 int ret;
2571 if ((ret = configset_find_element(set, key, &e)))
2572 return ret;
2573 else if (!e)
2574 return 1;
2575 return 0;
2578 int git_configset_get_string(struct config_set *set, const char *key, char **dest)
2580 const char *value;
2581 if (!git_configset_get_value(set, key, &value))
2582 return git_config_string((const char **)dest, key, value);
2583 else
2584 return 1;
2587 static int git_configset_get_string_tmp(struct config_set *set, const char *key,
2588 const char **dest)
2590 const char *value;
2591 if (!git_configset_get_value(set, key, &value)) {
2592 if (!value)
2593 return config_error_nonbool(key);
2594 *dest = value;
2595 return 0;
2596 } else {
2597 return 1;
2601 int git_configset_get_int(struct config_set *set, const char *key, int *dest)
2603 const char *value;
2604 if (!git_configset_get_value(set, key, &value)) {
2605 *dest = git_config_int(key, value);
2606 return 0;
2607 } else
2608 return 1;
2611 int git_configset_get_ulong(struct config_set *set, const char *key, unsigned long *dest)
2613 const char *value;
2614 if (!git_configset_get_value(set, key, &value)) {
2615 *dest = git_config_ulong(key, value);
2616 return 0;
2617 } else
2618 return 1;
2621 int git_configset_get_bool(struct config_set *set, const char *key, int *dest)
2623 const char *value;
2624 if (!git_configset_get_value(set, key, &value)) {
2625 *dest = git_config_bool(key, value);
2626 return 0;
2627 } else
2628 return 1;
2631 int git_configset_get_bool_or_int(struct config_set *set, const char *key,
2632 int *is_bool, int *dest)
2634 const char *value;
2635 if (!git_configset_get_value(set, key, &value)) {
2636 *dest = git_config_bool_or_int(key, value, is_bool);
2637 return 0;
2638 } else
2639 return 1;
2642 int git_configset_get_maybe_bool(struct config_set *set, const char *key, int *dest)
2644 const char *value;
2645 if (!git_configset_get_value(set, key, &value)) {
2646 *dest = git_parse_maybe_bool(value);
2647 if (*dest == -1)
2648 return -1;
2649 return 0;
2650 } else
2651 return 1;
2654 int git_configset_get_pathname(struct config_set *set, const char *key, const char **dest)
2656 const char *value;
2657 if (!git_configset_get_value(set, key, &value))
2658 return git_config_pathname(dest, key, value);
2659 else
2660 return 1;
2663 /* Functions use to read configuration from a repository */
2664 static void repo_read_config(struct repository *repo)
2666 struct config_options opts = { 0 };
2667 struct configset_add_data data = CONFIGSET_ADD_INIT;
2669 opts.respect_includes = 1;
2670 opts.commondir = repo->commondir;
2671 opts.git_dir = repo->gitdir;
2673 if (!repo->config)
2674 CALLOC_ARRAY(repo->config, 1);
2675 else
2676 git_configset_clear(repo->config);
2678 git_configset_init(repo->config);
2679 data.config_set = repo->config;
2680 data.config_reader = &the_reader;
2682 if (config_with_options(config_set_callback, &data, NULL, repo, &opts) < 0)
2684 * config_with_options() normally returns only
2685 * zero, as most errors are fatal, and
2686 * non-fatal potential errors are guarded by "if"
2687 * statements that are entered only when no error is
2688 * possible.
2690 * If we ever encounter a non-fatal error, it means
2691 * something went really wrong and we should stop
2692 * immediately.
2694 die(_("unknown error occurred while reading the configuration files"));
2697 static void git_config_check_init(struct repository *repo)
2699 if (repo->config && repo->config->hash_initialized)
2700 return;
2701 repo_read_config(repo);
2704 static void repo_config_clear(struct repository *repo)
2706 if (!repo->config || !repo->config->hash_initialized)
2707 return;
2708 git_configset_clear(repo->config);
2711 void repo_config(struct repository *repo, config_fn_t fn, void *data)
2713 git_config_check_init(repo);
2714 configset_iter(&the_reader, repo->config, fn, data);
2717 int repo_config_get(struct repository *repo, const char *key)
2719 git_config_check_init(repo);
2720 return git_configset_get(repo->config, key);
2723 int repo_config_get_value(struct repository *repo,
2724 const char *key, const char **value)
2726 git_config_check_init(repo);
2727 return git_configset_get_value(repo->config, key, value);
2730 int repo_config_get_value_multi(struct repository *repo, const char *key,
2731 const struct string_list **dest)
2733 git_config_check_init(repo);
2734 return git_configset_get_value_multi(repo->config, key, dest);
2737 int repo_config_get_string_multi(struct repository *repo, const char *key,
2738 const struct string_list **dest)
2740 git_config_check_init(repo);
2741 return git_configset_get_string_multi(repo->config, key, dest);
2744 int repo_config_get_string(struct repository *repo,
2745 const char *key, char **dest)
2747 int ret;
2748 git_config_check_init(repo);
2749 ret = git_configset_get_string(repo->config, key, dest);
2750 if (ret < 0)
2751 git_die_config(key, NULL);
2752 return ret;
2755 int repo_config_get_string_tmp(struct repository *repo,
2756 const char *key, const char **dest)
2758 int ret;
2759 git_config_check_init(repo);
2760 ret = git_configset_get_string_tmp(repo->config, key, dest);
2761 if (ret < 0)
2762 git_die_config(key, NULL);
2763 return ret;
2766 int repo_config_get_int(struct repository *repo,
2767 const char *key, int *dest)
2769 git_config_check_init(repo);
2770 return git_configset_get_int(repo->config, key, dest);
2773 int repo_config_get_ulong(struct repository *repo,
2774 const char *key, unsigned long *dest)
2776 git_config_check_init(repo);
2777 return git_configset_get_ulong(repo->config, key, dest);
2780 int repo_config_get_bool(struct repository *repo,
2781 const char *key, int *dest)
2783 git_config_check_init(repo);
2784 return git_configset_get_bool(repo->config, key, dest);
2787 int repo_config_get_bool_or_int(struct repository *repo,
2788 const char *key, int *is_bool, int *dest)
2790 git_config_check_init(repo);
2791 return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2794 int repo_config_get_maybe_bool(struct repository *repo,
2795 const char *key, int *dest)
2797 git_config_check_init(repo);
2798 return git_configset_get_maybe_bool(repo->config, key, dest);
2801 int repo_config_get_pathname(struct repository *repo,
2802 const char *key, const char **dest)
2804 int ret;
2805 git_config_check_init(repo);
2806 ret = git_configset_get_pathname(repo->config, key, dest);
2807 if (ret < 0)
2808 git_die_config(key, NULL);
2809 return ret;
2812 /* Read values into protected_config. */
2813 static void read_protected_config(void)
2815 struct config_options opts = {
2816 .respect_includes = 1,
2817 .ignore_repo = 1,
2818 .ignore_worktree = 1,
2819 .system_gently = 1,
2821 struct configset_add_data data = CONFIGSET_ADD_INIT;
2823 git_configset_init(&protected_config);
2824 data.config_set = &protected_config;
2825 data.config_reader = &the_reader;
2826 config_with_options(config_set_callback, &data, NULL, NULL, &opts);
2829 void git_protected_config(config_fn_t fn, void *data)
2831 if (!protected_config.hash_initialized)
2832 read_protected_config();
2833 configset_iter(&the_reader, &protected_config, fn, data);
2836 /* Functions used historically to read configuration from 'the_repository' */
2837 void git_config(config_fn_t fn, void *data)
2839 repo_config(the_repository, fn, data);
2842 void git_config_clear(void)
2844 repo_config_clear(the_repository);
2847 int git_config_get(const char *key)
2849 return repo_config_get(the_repository, key);
2852 int git_config_get_value(const char *key, const char **value)
2854 return repo_config_get_value(the_repository, key, value);
2857 int git_config_get_value_multi(const char *key, const struct string_list **dest)
2859 return repo_config_get_value_multi(the_repository, key, dest);
2862 int git_config_get_string_multi(const char *key,
2863 const struct string_list **dest)
2865 return repo_config_get_string_multi(the_repository, key, dest);
2868 int git_config_get_string(const char *key, char **dest)
2870 return repo_config_get_string(the_repository, key, dest);
2873 int git_config_get_string_tmp(const char *key, const char **dest)
2875 return repo_config_get_string_tmp(the_repository, key, dest);
2878 int git_config_get_int(const char *key, int *dest)
2880 return repo_config_get_int(the_repository, key, dest);
2883 int git_config_get_ulong(const char *key, unsigned long *dest)
2885 return repo_config_get_ulong(the_repository, key, dest);
2888 int git_config_get_bool(const char *key, int *dest)
2890 return repo_config_get_bool(the_repository, key, dest);
2893 int git_config_get_bool_or_int(const char *key, int *is_bool, int *dest)
2895 return repo_config_get_bool_or_int(the_repository, key, is_bool, dest);
2898 int git_config_get_maybe_bool(const char *key, int *dest)
2900 return repo_config_get_maybe_bool(the_repository, key, dest);
2903 int git_config_get_pathname(const char *key, const char **dest)
2905 return repo_config_get_pathname(the_repository, key, dest);
2908 int git_config_get_expiry(const char *key, const char **output)
2910 int ret = git_config_get_string(key, (char **)output);
2911 if (ret)
2912 return ret;
2913 if (strcmp(*output, "now")) {
2914 timestamp_t now = approxidate("now");
2915 if (approxidate(*output) >= now)
2916 git_die_config(key, _("Invalid %s: '%s'"), key, *output);
2918 return ret;
2921 int git_config_get_expiry_in_days(const char *key, timestamp_t *expiry, timestamp_t now)
2923 const char *expiry_string;
2924 intmax_t days;
2925 timestamp_t when;
2927 if (git_config_get_string_tmp(key, &expiry_string))
2928 return 1; /* no such thing */
2930 if (git_parse_signed(expiry_string, &days, maximum_signed_value_of_type(int))) {
2931 const int scale = 86400;
2932 *expiry = now - days * scale;
2933 return 0;
2936 if (!parse_expiry_date(expiry_string, &when)) {
2937 *expiry = when;
2938 return 0;
2940 return -1; /* thing exists but cannot be parsed */
2943 int git_config_get_split_index(void)
2945 int val;
2947 if (!git_config_get_maybe_bool("core.splitindex", &val))
2948 return val;
2950 return -1; /* default value */
2953 int git_config_get_max_percent_split_change(void)
2955 int val = -1;
2957 if (!git_config_get_int("splitindex.maxpercentchange", &val)) {
2958 if (0 <= val && val <= 100)
2959 return val;
2961 return error(_("splitIndex.maxPercentChange value '%d' "
2962 "should be between 0 and 100"), val);
2965 return -1; /* default value */
2968 int git_config_get_index_threads(int *dest)
2970 int is_bool, val;
2972 val = git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2973 if (val) {
2974 *dest = val;
2975 return 0;
2978 if (!git_config_get_bool_or_int("index.threads", &is_bool, &val)) {
2979 if (is_bool)
2980 *dest = val ? 0 : 1;
2981 else
2982 *dest = val;
2983 return 0;
2986 return 1;
2989 NORETURN
2990 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2992 if (!filename)
2993 die(_("unable to parse '%s' from command-line config"), key);
2994 else
2995 die(_("bad config variable '%s' in file '%s' at line %d"),
2996 key, filename, linenr);
2999 NORETURN __attribute__((format(printf, 2, 3)))
3000 void git_die_config(const char *key, const char *err, ...)
3002 const struct string_list *values;
3003 struct key_value_info *kv_info;
3004 report_fn error_fn = get_error_routine();
3006 if (err) {
3007 va_list params;
3008 va_start(params, err);
3009 error_fn(err, params);
3010 va_end(params);
3012 if (git_config_get_value_multi(key, &values))
3013 BUG("for key '%s' we must have a value to report on", key);
3014 kv_info = values->items[values->nr - 1].util;
3015 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
3019 * Find all the stuff for git_config_set() below.
3022 struct config_store_data {
3023 struct config_reader *config_reader;
3024 size_t baselen;
3025 char *key;
3026 int do_not_match;
3027 const char *fixed_value;
3028 regex_t *value_pattern;
3029 int multi_replace;
3030 struct {
3031 size_t begin, end;
3032 enum config_event_t type;
3033 int is_keys_section;
3034 } *parsed;
3035 unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
3036 unsigned int key_seen:1, section_seen:1, is_keys_section:1;
3038 #define CONFIG_STORE_INIT { 0 }
3040 static void config_store_data_clear(struct config_store_data *store)
3042 free(store->key);
3043 if (store->value_pattern != NULL &&
3044 store->value_pattern != CONFIG_REGEX_NONE) {
3045 regfree(store->value_pattern);
3046 free(store->value_pattern);
3048 free(store->parsed);
3049 free(store->seen);
3050 memset(store, 0, sizeof(*store));
3053 static int matches(const char *key, const char *value,
3054 const struct config_store_data *store)
3056 if (strcmp(key, store->key))
3057 return 0; /* not ours */
3058 if (store->fixed_value)
3059 return !strcmp(store->fixed_value, value);
3060 if (!store->value_pattern)
3061 return 1; /* always matches */
3062 if (store->value_pattern == CONFIG_REGEX_NONE)
3063 return 0; /* never matches */
3065 return store->do_not_match ^
3066 (value && !regexec(store->value_pattern, value, 0, NULL, 0));
3069 static int store_aux_event(enum config_event_t type,
3070 size_t begin, size_t end, void *data)
3072 struct config_store_data *store = data;
3073 struct config_source *cs = store->config_reader->source;
3075 ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
3076 store->parsed[store->parsed_nr].begin = begin;
3077 store->parsed[store->parsed_nr].end = end;
3078 store->parsed[store->parsed_nr].type = type;
3080 if (type == CONFIG_EVENT_SECTION) {
3081 int (*cmpfn)(const char *, const char *, size_t);
3083 if (cs->var.len < 2 || cs->var.buf[cs->var.len - 1] != '.')
3084 return error(_("invalid section name '%s'"), cs->var.buf);
3086 if (cs->subsection_case_sensitive)
3087 cmpfn = strncasecmp;
3088 else
3089 cmpfn = strncmp;
3091 /* Is this the section we were looking for? */
3092 store->is_keys_section =
3093 store->parsed[store->parsed_nr].is_keys_section =
3094 cs->var.len - 1 == store->baselen &&
3095 !cmpfn(cs->var.buf, store->key, store->baselen);
3096 if (store->is_keys_section) {
3097 store->section_seen = 1;
3098 ALLOC_GROW(store->seen, store->seen_nr + 1,
3099 store->seen_alloc);
3100 store->seen[store->seen_nr] = store->parsed_nr;
3104 store->parsed_nr++;
3106 return 0;
3109 static int store_aux(const char *key, const char *value, void *cb)
3111 struct config_store_data *store = cb;
3113 if (store->key_seen) {
3114 if (matches(key, value, store)) {
3115 if (store->seen_nr == 1 && store->multi_replace == 0) {
3116 warning(_("%s has multiple values"), key);
3119 ALLOC_GROW(store->seen, store->seen_nr + 1,
3120 store->seen_alloc);
3122 store->seen[store->seen_nr] = store->parsed_nr;
3123 store->seen_nr++;
3125 } else if (store->is_keys_section) {
3127 * Do not increment matches yet: this may not be a match, but we
3128 * are in the desired section.
3130 ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
3131 store->seen[store->seen_nr] = store->parsed_nr;
3132 store->section_seen = 1;
3134 if (matches(key, value, store)) {
3135 store->seen_nr++;
3136 store->key_seen = 1;
3140 return 0;
3143 static int write_error(const char *filename)
3145 error(_("failed to write new configuration file %s"), filename);
3147 /* Same error code as "failed to rename". */
3148 return 4;
3151 static struct strbuf store_create_section(const char *key,
3152 const struct config_store_data *store)
3154 const char *dot;
3155 size_t i;
3156 struct strbuf sb = STRBUF_INIT;
3158 dot = memchr(key, '.', store->baselen);
3159 if (dot) {
3160 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
3161 for (i = dot - key + 1; i < store->baselen; i++) {
3162 if (key[i] == '"' || key[i] == '\\')
3163 strbuf_addch(&sb, '\\');
3164 strbuf_addch(&sb, key[i]);
3166 strbuf_addstr(&sb, "\"]\n");
3167 } else {
3168 strbuf_addch(&sb, '[');
3169 strbuf_add(&sb, key, store->baselen);
3170 strbuf_addstr(&sb, "]\n");
3173 return sb;
3176 static ssize_t write_section(int fd, const char *key,
3177 const struct config_store_data *store)
3179 struct strbuf sb = store_create_section(key, store);
3180 ssize_t ret;
3182 ret = write_in_full(fd, sb.buf, sb.len);
3183 strbuf_release(&sb);
3185 return ret;
3188 static ssize_t write_pair(int fd, const char *key, const char *value,
3189 const struct config_store_data *store)
3191 int i;
3192 ssize_t ret;
3193 const char *quote = "";
3194 struct strbuf sb = STRBUF_INIT;
3197 * Check to see if the value needs to be surrounded with a dq pair.
3198 * Note that problematic characters are always backslash-quoted; this
3199 * check is about not losing leading or trailing SP and strings that
3200 * follow beginning-of-comment characters (i.e. ';' and '#') by the
3201 * configuration parser.
3203 if (value[0] == ' ')
3204 quote = "\"";
3205 for (i = 0; value[i]; i++)
3206 if (value[i] == ';' || value[i] == '#')
3207 quote = "\"";
3208 if (i && value[i - 1] == ' ')
3209 quote = "\"";
3211 strbuf_addf(&sb, "\t%s = %s", key + store->baselen + 1, quote);
3213 for (i = 0; value[i]; i++)
3214 switch (value[i]) {
3215 case '\n':
3216 strbuf_addstr(&sb, "\\n");
3217 break;
3218 case '\t':
3219 strbuf_addstr(&sb, "\\t");
3220 break;
3221 case '"':
3222 case '\\':
3223 strbuf_addch(&sb, '\\');
3224 /* fallthrough */
3225 default:
3226 strbuf_addch(&sb, value[i]);
3227 break;
3229 strbuf_addf(&sb, "%s\n", quote);
3231 ret = write_in_full(fd, sb.buf, sb.len);
3232 strbuf_release(&sb);
3234 return ret;
3238 * If we are about to unset the last key(s) in a section, and if there are
3239 * no comments surrounding (or included in) the section, we will want to
3240 * extend begin/end to remove the entire section.
3242 * Note: the parameter `seen_ptr` points to the index into the store.seen
3243 * array. * This index may be incremented if a section has more than one
3244 * entry (which all are to be removed).
3246 static void maybe_remove_section(struct config_store_data *store,
3247 size_t *begin_offset, size_t *end_offset,
3248 int *seen_ptr)
3250 size_t begin;
3251 int i, seen, section_seen = 0;
3254 * First, ensure that this is the first key, and that there are no
3255 * comments before the entry nor before the section header.
3257 seen = *seen_ptr;
3258 for (i = store->seen[seen]; i > 0; i--) {
3259 enum config_event_t type = store->parsed[i - 1].type;
3261 if (type == CONFIG_EVENT_COMMENT)
3262 /* There is a comment before this entry or section */
3263 return;
3264 if (type == CONFIG_EVENT_ENTRY) {
3265 if (!section_seen)
3266 /* This is not the section's first entry. */
3267 return;
3268 /* We encountered no comment before the section. */
3269 break;
3271 if (type == CONFIG_EVENT_SECTION) {
3272 if (!store->parsed[i - 1].is_keys_section)
3273 break;
3274 section_seen = 1;
3277 begin = store->parsed[i].begin;
3280 * Next, make sure that we are removing the last key(s) in the section,
3281 * and that there are no comments that are possibly about the current
3282 * section.
3284 for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
3285 enum config_event_t type = store->parsed[i].type;
3287 if (type == CONFIG_EVENT_COMMENT)
3288 return;
3289 if (type == CONFIG_EVENT_SECTION) {
3290 if (store->parsed[i].is_keys_section)
3291 continue;
3292 break;
3294 if (type == CONFIG_EVENT_ENTRY) {
3295 if (++seen < store->seen_nr &&
3296 i == store->seen[seen])
3297 /* We want to remove this entry, too */
3298 continue;
3299 /* There is another entry in this section. */
3300 return;
3305 * We are really removing the last entry/entries from this section, and
3306 * there are no enclosed or surrounding comments. Remove the entire,
3307 * now-empty section.
3309 *seen_ptr = seen;
3310 *begin_offset = begin;
3311 if (i < store->parsed_nr)
3312 *end_offset = store->parsed[i].begin;
3313 else
3314 *end_offset = store->parsed[store->parsed_nr - 1].end;
3317 int git_config_set_in_file_gently(const char *config_filename,
3318 const char *key, const char *value)
3320 return git_config_set_multivar_in_file_gently(config_filename, key, value, NULL, 0);
3323 void git_config_set_in_file(const char *config_filename,
3324 const char *key, const char *value)
3326 git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
3329 int git_config_set_gently(const char *key, const char *value)
3331 return git_config_set_multivar_gently(key, value, NULL, 0);
3334 int repo_config_set_worktree_gently(struct repository *r,
3335 const char *key, const char *value)
3337 /* Only use worktree-specific config if it is already enabled. */
3338 if (r->repository_format_worktree_config) {
3339 char *file = repo_git_path(r, "config.worktree");
3340 int ret = git_config_set_multivar_in_file_gently(
3341 file, key, value, NULL, 0);
3342 free(file);
3343 return ret;
3345 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
3348 void git_config_set(const char *key, const char *value)
3350 git_config_set_multivar(key, value, NULL, 0);
3352 trace2_cmd_set_config(key, value);
3356 * If value==NULL, unset in (remove from) config,
3357 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
3358 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
3359 * (only add a new one)
3360 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3361 * key/values are removed before a single new pair is written. If the
3362 * flag is not present, then replace only the first match.
3364 * Returns 0 on success.
3366 * This function does this:
3368 * - it locks the config file by creating ".git/config.lock"
3370 * - it then parses the config using store_aux() as validator to find
3371 * the position on the key/value pair to replace. If it is to be unset,
3372 * it must be found exactly once.
3374 * - the config file is mmap()ed and the part before the match (if any) is
3375 * written to the lock file, then the changed part and the rest.
3377 * - the config file is removed and the lock file rename()d to it.
3380 int git_config_set_multivar_in_file_gently(const char *config_filename,
3381 const char *key, const char *value,
3382 const char *value_pattern,
3383 unsigned flags)
3385 int fd = -1, in_fd = -1;
3386 int ret;
3387 struct lock_file lock = LOCK_INIT;
3388 char *filename_buf = NULL;
3389 char *contents = NULL;
3390 size_t contents_sz;
3391 struct config_store_data store = CONFIG_STORE_INIT;
3393 store.config_reader = &the_reader;
3395 /* parse-key returns negative; flip the sign to feed exit(3) */
3396 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
3397 if (ret)
3398 goto out_free;
3400 store.multi_replace = (flags & CONFIG_FLAGS_MULTI_REPLACE) != 0;
3402 if (!config_filename)
3403 config_filename = filename_buf = git_pathdup("config");
3406 * The lock serves a purpose in addition to locking: the new
3407 * contents of .git/config will be written into it.
3409 fd = hold_lock_file_for_update(&lock, config_filename, 0);
3410 if (fd < 0) {
3411 error_errno(_("could not lock config file %s"), config_filename);
3412 ret = CONFIG_NO_LOCK;
3413 goto out_free;
3417 * If .git/config does not exist yet, write a minimal version.
3419 in_fd = open(config_filename, O_RDONLY);
3420 if ( in_fd < 0 ) {
3421 if ( ENOENT != errno ) {
3422 error_errno(_("opening %s"), config_filename);
3423 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
3424 goto out_free;
3426 /* if nothing to unset, error out */
3427 if (!value) {
3428 ret = CONFIG_NOTHING_SET;
3429 goto out_free;
3432 free(store.key);
3433 store.key = xstrdup(key);
3434 if (write_section(fd, key, &store) < 0 ||
3435 write_pair(fd, key, value, &store) < 0)
3436 goto write_err_out;
3437 } else {
3438 struct stat st;
3439 size_t copy_begin, copy_end;
3440 int i, new_line = 0;
3441 struct config_options opts;
3443 if (!value_pattern)
3444 store.value_pattern = NULL;
3445 else if (value_pattern == CONFIG_REGEX_NONE)
3446 store.value_pattern = CONFIG_REGEX_NONE;
3447 else if (flags & CONFIG_FLAGS_FIXED_VALUE)
3448 store.fixed_value = value_pattern;
3449 else {
3450 if (value_pattern[0] == '!') {
3451 store.do_not_match = 1;
3452 value_pattern++;
3453 } else
3454 store.do_not_match = 0;
3456 store.value_pattern = (regex_t*)xmalloc(sizeof(regex_t));
3457 if (regcomp(store.value_pattern, value_pattern,
3458 REG_EXTENDED)) {
3459 error(_("invalid pattern: %s"), value_pattern);
3460 FREE_AND_NULL(store.value_pattern);
3461 ret = CONFIG_INVALID_PATTERN;
3462 goto out_free;
3466 ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
3467 store.parsed[0].end = 0;
3469 memset(&opts, 0, sizeof(opts));
3470 opts.event_fn = store_aux_event;
3471 opts.event_fn_data = &store;
3474 * After this, store.parsed will contain offsets of all the
3475 * parsed elements, and store.seen will contain a list of
3476 * matches, as indices into store.parsed.
3478 * As a side effect, we make sure to transform only a valid
3479 * existing config file.
3481 if (git_config_from_file_with_options(store_aux,
3482 config_filename,
3483 &store, &opts)) {
3484 error(_("invalid config file %s"), config_filename);
3485 ret = CONFIG_INVALID_FILE;
3486 goto out_free;
3489 /* if nothing to unset, or too many matches, error out */
3490 if ((store.seen_nr == 0 && value == NULL) ||
3491 (store.seen_nr > 1 && !store.multi_replace)) {
3492 ret = CONFIG_NOTHING_SET;
3493 goto out_free;
3496 if (fstat(in_fd, &st) == -1) {
3497 error_errno(_("fstat on %s failed"), config_filename);
3498 ret = CONFIG_INVALID_FILE;
3499 goto out_free;
3502 contents_sz = xsize_t(st.st_size);
3503 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
3504 MAP_PRIVATE, in_fd, 0);
3505 if (contents == MAP_FAILED) {
3506 if (errno == ENODEV && S_ISDIR(st.st_mode))
3507 errno = EISDIR;
3508 error_errno(_("unable to mmap '%s'%s"),
3509 config_filename, mmap_os_err());
3510 ret = CONFIG_INVALID_FILE;
3511 contents = NULL;
3512 goto out_free;
3514 close(in_fd);
3515 in_fd = -1;
3517 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3518 error_errno(_("chmod on %s failed"), get_lock_file_path(&lock));
3519 ret = CONFIG_NO_WRITE;
3520 goto out_free;
3523 if (store.seen_nr == 0) {
3524 if (!store.seen_alloc) {
3525 /* Did not see key nor section */
3526 ALLOC_GROW(store.seen, 1, store.seen_alloc);
3527 store.seen[0] = store.parsed_nr
3528 - !!store.parsed_nr;
3530 store.seen_nr = 1;
3533 for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
3534 size_t replace_end;
3535 int j = store.seen[i];
3537 new_line = 0;
3538 if (!store.key_seen) {
3539 copy_end = store.parsed[j].end;
3540 /* include '\n' when copying section header */
3541 if (copy_end > 0 && copy_end < contents_sz &&
3542 contents[copy_end - 1] != '\n' &&
3543 contents[copy_end] == '\n')
3544 copy_end++;
3545 replace_end = copy_end;
3546 } else {
3547 replace_end = store.parsed[j].end;
3548 copy_end = store.parsed[j].begin;
3549 if (!value)
3550 maybe_remove_section(&store,
3551 &copy_end,
3552 &replace_end, &i);
3554 * Swallow preceding white-space on the same
3555 * line.
3557 while (copy_end > 0 ) {
3558 char c = contents[copy_end - 1];
3560 if (isspace(c) && c != '\n')
3561 copy_end--;
3562 else
3563 break;
3567 if (copy_end > 0 && contents[copy_end-1] != '\n')
3568 new_line = 1;
3570 /* write the first part of the config */
3571 if (copy_end > copy_begin) {
3572 if (write_in_full(fd, contents + copy_begin,
3573 copy_end - copy_begin) < 0)
3574 goto write_err_out;
3575 if (new_line &&
3576 write_str_in_full(fd, "\n") < 0)
3577 goto write_err_out;
3579 copy_begin = replace_end;
3582 /* write the pair (value == NULL means unset) */
3583 if (value) {
3584 if (!store.section_seen) {
3585 if (write_section(fd, key, &store) < 0)
3586 goto write_err_out;
3588 if (write_pair(fd, key, value, &store) < 0)
3589 goto write_err_out;
3592 /* write the rest of the config */
3593 if (copy_begin < contents_sz)
3594 if (write_in_full(fd, contents + copy_begin,
3595 contents_sz - copy_begin) < 0)
3596 goto write_err_out;
3598 munmap(contents, contents_sz);
3599 contents = NULL;
3602 if (commit_lock_file(&lock) < 0) {
3603 error_errno(_("could not write config file %s"), config_filename);
3604 ret = CONFIG_NO_WRITE;
3605 goto out_free;
3608 ret = 0;
3610 /* Invalidate the config cache */
3611 git_config_clear();
3613 out_free:
3614 rollback_lock_file(&lock);
3615 free(filename_buf);
3616 if (contents)
3617 munmap(contents, contents_sz);
3618 if (in_fd >= 0)
3619 close(in_fd);
3620 config_store_data_clear(&store);
3621 return ret;
3623 write_err_out:
3624 ret = write_error(get_lock_file_path(&lock));
3625 goto out_free;
3629 void git_config_set_multivar_in_file(const char *config_filename,
3630 const char *key, const char *value,
3631 const char *value_pattern, unsigned flags)
3633 if (!git_config_set_multivar_in_file_gently(config_filename, key, value,
3634 value_pattern, flags))
3635 return;
3636 if (value)
3637 die(_("could not set '%s' to '%s'"), key, value);
3638 else
3639 die(_("could not unset '%s'"), key);
3642 int git_config_set_multivar_gently(const char *key, const char *value,
3643 const char *value_pattern, unsigned flags)
3645 return repo_config_set_multivar_gently(the_repository, key, value,
3646 value_pattern, flags);
3649 int repo_config_set_multivar_gently(struct repository *r, const char *key,
3650 const char *value,
3651 const char *value_pattern, unsigned flags)
3653 char *file = repo_git_path(r, "config");
3654 int res = git_config_set_multivar_in_file_gently(file,
3655 key, value,
3656 value_pattern,
3657 flags);
3658 free(file);
3659 return res;
3662 void git_config_set_multivar(const char *key, const char *value,
3663 const char *value_pattern, unsigned flags)
3665 git_config_set_multivar_in_file(git_path("config"),
3666 key, value, value_pattern,
3667 flags);
3670 static size_t section_name_match (const char *buf, const char *name)
3672 size_t i = 0, j = 0;
3673 int dot = 0;
3674 if (buf[i] != '[')
3675 return 0;
3676 for (i = 1; buf[i] && buf[i] != ']'; i++) {
3677 if (!dot && isspace(buf[i])) {
3678 dot = 1;
3679 if (name[j++] != '.')
3680 break;
3681 for (i++; isspace(buf[i]); i++)
3682 ; /* do nothing */
3683 if (buf[i] != '"')
3684 break;
3685 continue;
3687 if (buf[i] == '\\' && dot)
3688 i++;
3689 else if (buf[i] == '"' && dot) {
3690 for (i++; isspace(buf[i]); i++)
3691 ; /* do_nothing */
3692 break;
3694 if (buf[i] != name[j++])
3695 break;
3697 if (buf[i] == ']' && name[j] == 0) {
3699 * We match, now just find the right length offset by
3700 * gobbling up any whitespace after it, as well
3702 i++;
3703 for (; buf[i] && isspace(buf[i]); i++)
3704 ; /* do nothing */
3705 return i;
3707 return 0;
3710 static int section_name_is_ok(const char *name)
3712 /* Empty section names are bogus. */
3713 if (!*name)
3714 return 0;
3717 * Before a dot, we must be alphanumeric or dash. After the first dot,
3718 * anything goes, so we can stop checking.
3720 for (; *name && *name != '.'; name++)
3721 if (*name != '-' && !isalnum(*name))
3722 return 0;
3723 return 1;
3726 #define GIT_CONFIG_MAX_LINE_LEN (512 * 1024)
3728 /* if new_name == NULL, the section is removed instead */
3729 static int git_config_copy_or_rename_section_in_file(const char *config_filename,
3730 const char *old_name,
3731 const char *new_name, int copy)
3733 int ret = 0, remove = 0;
3734 char *filename_buf = NULL;
3735 struct lock_file lock = LOCK_INIT;
3736 int out_fd;
3737 struct strbuf buf = STRBUF_INIT;
3738 FILE *config_file = NULL;
3739 struct stat st;
3740 struct strbuf copystr = STRBUF_INIT;
3741 struct config_store_data store;
3742 uint32_t line_nr = 0;
3744 memset(&store, 0, sizeof(store));
3746 if (new_name && !section_name_is_ok(new_name)) {
3747 ret = error(_("invalid section name: %s"), new_name);
3748 goto out_no_rollback;
3751 if (!config_filename)
3752 config_filename = filename_buf = git_pathdup("config");
3754 out_fd = hold_lock_file_for_update(&lock, config_filename, 0);
3755 if (out_fd < 0) {
3756 ret = error(_("could not lock config file %s"), config_filename);
3757 goto out;
3760 if (!(config_file = fopen(config_filename, "rb"))) {
3761 ret = warn_on_fopen_errors(config_filename);
3762 if (ret)
3763 goto out;
3764 /* no config file means nothing to rename, no error */
3765 goto commit_and_out;
3768 if (fstat(fileno(config_file), &st) == -1) {
3769 ret = error_errno(_("fstat on %s failed"), config_filename);
3770 goto out;
3773 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3774 ret = error_errno(_("chmod on %s failed"),
3775 get_lock_file_path(&lock));
3776 goto out;
3779 while (!strbuf_getwholeline(&buf, config_file, '\n')) {
3780 size_t i, length;
3781 int is_section = 0;
3782 char *output = buf.buf;
3784 line_nr++;
3786 if (buf.len >= GIT_CONFIG_MAX_LINE_LEN) {
3787 ret = error(_("refusing to work with overly long line "
3788 "in '%s' on line %"PRIuMAX),
3789 config_filename, (uintmax_t)line_nr);
3790 goto out;
3793 for (i = 0; buf.buf[i] && isspace(buf.buf[i]); i++)
3794 ; /* do nothing */
3795 if (buf.buf[i] == '[') {
3796 /* it's a section */
3797 size_t offset;
3798 is_section = 1;
3801 * When encountering a new section under -c we
3802 * need to flush out any section we're already
3803 * coping and begin anew. There might be
3804 * multiple [branch "$name"] sections.
3806 if (copystr.len > 0) {
3807 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3808 ret = write_error(get_lock_file_path(&lock));
3809 goto out;
3811 strbuf_reset(&copystr);
3814 offset = section_name_match(&buf.buf[i], old_name);
3815 if (offset > 0) {
3816 ret++;
3817 if (!new_name) {
3818 remove = 1;
3819 continue;
3821 store.baselen = strlen(new_name);
3822 if (!copy) {
3823 if (write_section(out_fd, new_name, &store) < 0) {
3824 ret = write_error(get_lock_file_path(&lock));
3825 goto out;
3828 * We wrote out the new section, with
3829 * a newline, now skip the old
3830 * section's length
3832 output += offset + i;
3833 if (strlen(output) > 0) {
3835 * More content means there's
3836 * a declaration to put on the
3837 * next line; indent with a
3838 * tab
3840 output -= 1;
3841 output[0] = '\t';
3843 } else {
3844 strbuf_release(&copystr);
3845 copystr = store_create_section(new_name, &store);
3848 remove = 0;
3850 if (remove)
3851 continue;
3852 length = strlen(output);
3854 if (!is_section && copystr.len > 0) {
3855 strbuf_add(&copystr, output, length);
3858 if (write_in_full(out_fd, output, length) < 0) {
3859 ret = write_error(get_lock_file_path(&lock));
3860 goto out;
3865 * Copy a trailing section at the end of the config, won't be
3866 * flushed by the usual "flush because we have a new section
3867 * logic in the loop above.
3869 if (copystr.len > 0) {
3870 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3871 ret = write_error(get_lock_file_path(&lock));
3872 goto out;
3874 strbuf_reset(&copystr);
3877 fclose(config_file);
3878 config_file = NULL;
3879 commit_and_out:
3880 if (commit_lock_file(&lock) < 0)
3881 ret = error_errno(_("could not write config file %s"),
3882 config_filename);
3883 out:
3884 if (config_file)
3885 fclose(config_file);
3886 rollback_lock_file(&lock);
3887 out_no_rollback:
3888 free(filename_buf);
3889 config_store_data_clear(&store);
3890 strbuf_release(&buf);
3891 strbuf_release(&copystr);
3892 return ret;
3895 int git_config_rename_section_in_file(const char *config_filename,
3896 const char *old_name, const char *new_name)
3898 return git_config_copy_or_rename_section_in_file(config_filename,
3899 old_name, new_name, 0);
3902 int git_config_rename_section(const char *old_name, const char *new_name)
3904 return git_config_rename_section_in_file(NULL, old_name, new_name);
3907 int git_config_copy_section_in_file(const char *config_filename,
3908 const char *old_name, const char *new_name)
3910 return git_config_copy_or_rename_section_in_file(config_filename,
3911 old_name, new_name, 1);
3914 int git_config_copy_section(const char *old_name, const char *new_name)
3916 return git_config_copy_section_in_file(NULL, old_name, new_name);
3920 * Call this to report error for your variable that should not
3921 * get a boolean value (i.e. "[my] var" means "true").
3923 #undef config_error_nonbool
3924 int config_error_nonbool(const char *var)
3926 return error(_("missing value for '%s'"), var);
3929 int parse_config_key(const char *var,
3930 const char *section,
3931 const char **subsection, size_t *subsection_len,
3932 const char **key)
3934 const char *dot;
3936 /* Does it start with "section." ? */
3937 if (!skip_prefix(var, section, &var) || *var != '.')
3938 return -1;
3941 * Find the key; we don't know yet if we have a subsection, but we must
3942 * parse backwards from the end, since the subsection may have dots in
3943 * it, too.
3945 dot = strrchr(var, '.');
3946 *key = dot + 1;
3948 /* Did we have a subsection at all? */
3949 if (dot == var) {
3950 if (subsection) {
3951 *subsection = NULL;
3952 *subsection_len = 0;
3955 else {
3956 if (!subsection)
3957 return -1;
3958 *subsection = var + 1;
3959 *subsection_len = dot - *subsection;
3962 return 0;
3965 static int reader_origin_type(struct config_reader *reader,
3966 enum config_origin_type *type)
3968 if (the_reader.config_kvi)
3969 *type = reader->config_kvi->origin_type;
3970 else if(the_reader.source)
3971 *type = reader->source->origin_type;
3972 else
3973 return 1;
3974 return 0;
3977 const char *current_config_origin_type(void)
3979 enum config_origin_type type = CONFIG_ORIGIN_UNKNOWN;
3981 if (reader_origin_type(&the_reader, &type))
3982 BUG("current_config_origin_type called outside config callback");
3984 switch (type) {
3985 case CONFIG_ORIGIN_BLOB:
3986 return "blob";
3987 case CONFIG_ORIGIN_FILE:
3988 return "file";
3989 case CONFIG_ORIGIN_STDIN:
3990 return "standard input";
3991 case CONFIG_ORIGIN_SUBMODULE_BLOB:
3992 return "submodule-blob";
3993 case CONFIG_ORIGIN_CMDLINE:
3994 return "command line";
3995 default:
3996 BUG("unknown config origin type");
4000 const char *config_scope_name(enum config_scope scope)
4002 switch (scope) {
4003 case CONFIG_SCOPE_SYSTEM:
4004 return "system";
4005 case CONFIG_SCOPE_GLOBAL:
4006 return "global";
4007 case CONFIG_SCOPE_LOCAL:
4008 return "local";
4009 case CONFIG_SCOPE_WORKTREE:
4010 return "worktree";
4011 case CONFIG_SCOPE_COMMAND:
4012 return "command";
4013 case CONFIG_SCOPE_SUBMODULE:
4014 return "submodule";
4015 default:
4016 return "unknown";
4020 static int reader_config_name(struct config_reader *reader, const char **out)
4022 if (the_reader.config_kvi)
4023 *out = reader->config_kvi->filename;
4024 else if (the_reader.source)
4025 *out = reader->source->name;
4026 else
4027 return 1;
4028 return 0;
4031 const char *current_config_name(void)
4033 const char *name;
4034 if (reader_config_name(&the_reader, &name))
4035 BUG("current_config_name called outside config callback");
4036 return name ? name : "";
4039 enum config_scope current_config_scope(void)
4041 if (the_reader.config_kvi)
4042 return the_reader.config_kvi->scope;
4043 else
4044 return the_reader.parsing_scope;
4047 int current_config_line(void)
4049 if (the_reader.config_kvi)
4050 return the_reader.config_kvi->linenr;
4051 else
4052 return the_reader.source->linenr;
4055 int lookup_config(const char **mapping, int nr_mapping, const char *var)
4057 int i;
4059 for (i = 0; i < nr_mapping; i++) {
4060 const char *name = mapping[i];
4062 if (name && !strcasecmp(var, name))
4063 return i;
4065 return -1;