Merge branch 'ak/doc-sparse-co-typofix'
[git/gitster.git] / config.c
blob1266eab08607155c1fd4ce2a9734243839d3f7bc
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 * Copyright (C) Johannes Schindelin, 2005
7 */
9 #define USE_THE_REPOSITORY_VARIABLE
11 #include "git-compat-util.h"
12 #include "abspath.h"
13 #include "advice.h"
14 #include "date.h"
15 #include "branch.h"
16 #include "config.h"
17 #include "parse.h"
18 #include "convert.h"
19 #include "environment.h"
20 #include "gettext.h"
21 #include "ident.h"
22 #include "repository.h"
23 #include "lockfile.h"
24 #include "mailmap.h"
25 #include "attr.h"
26 #include "exec-cmd.h"
27 #include "strbuf.h"
28 #include "quote.h"
29 #include "hashmap.h"
30 #include "string-list.h"
31 #include "object-name.h"
32 #include "object-store-ll.h"
33 #include "pager.h"
34 #include "path.h"
35 #include "utf8.h"
36 #include "color.h"
37 #include "refs.h"
38 #include "setup.h"
39 #include "strvec.h"
40 #include "trace2.h"
41 #include "wildmatch.h"
42 #include "ws.h"
43 #include "write-or-die.h"
45 struct config_source {
46 struct config_source *prev;
47 union {
48 FILE *file;
49 struct config_buf {
50 const char *buf;
51 size_t len;
52 size_t pos;
53 } buf;
54 } u;
55 enum config_origin_type origin_type;
56 const char *name;
57 const char *path;
58 enum config_error_action default_error_action;
59 int linenr;
60 int eof;
61 size_t total_len;
62 struct strbuf value;
63 struct strbuf var;
64 unsigned subsection_case_sensitive : 1;
66 int (*do_fgetc)(struct config_source *c);
67 int (*do_ungetc)(int c, struct config_source *conf);
68 long (*do_ftell)(struct config_source *c);
70 #define CONFIG_SOURCE_INIT { 0 }
72 static int pack_compression_seen;
73 static int zlib_compression_seen;
76 * Config that comes from trusted scopes, namely:
77 * - CONFIG_SCOPE_SYSTEM (e.g. /etc/gitconfig)
78 * - CONFIG_SCOPE_GLOBAL (e.g. $HOME/.gitconfig, $XDG_CONFIG_HOME/git)
79 * - CONFIG_SCOPE_COMMAND (e.g. "-c" option, environment variables)
81 * This is declared here for code cleanliness, but unlike the other
82 * static variables, this does not hold config parser state.
84 static struct config_set protected_config;
86 static int config_file_fgetc(struct config_source *conf)
88 return getc_unlocked(conf->u.file);
91 static int config_file_ungetc(int c, struct config_source *conf)
93 return ungetc(c, conf->u.file);
96 static long config_file_ftell(struct config_source *conf)
98 return ftell(conf->u.file);
101 static int config_buf_fgetc(struct config_source *conf)
103 if (conf->u.buf.pos < conf->u.buf.len)
104 return conf->u.buf.buf[conf->u.buf.pos++];
106 return EOF;
109 static int config_buf_ungetc(int c, struct config_source *conf)
111 if (conf->u.buf.pos > 0) {
112 conf->u.buf.pos--;
113 if (conf->u.buf.buf[conf->u.buf.pos] != c)
114 BUG("config_buf can only ungetc the same character");
115 return c;
118 return EOF;
121 static long config_buf_ftell(struct config_source *conf)
123 return conf->u.buf.pos;
126 struct config_include_data {
127 int depth;
128 config_fn_t fn;
129 void *data;
130 const struct config_options *opts;
131 const struct git_config_source *config_source;
132 struct repository *repo;
135 * All remote URLs discovered when reading all config files.
137 struct string_list *remote_urls;
139 #define CONFIG_INCLUDE_INIT { 0 }
141 static int git_config_include(const char *var, const char *value,
142 const struct config_context *ctx, void *data);
144 #define MAX_INCLUDE_DEPTH 10
145 static const char include_depth_advice[] = N_(
146 "exceeded maximum include depth (%d) while including\n"
147 " %s\n"
148 "from\n"
149 " %s\n"
150 "This might be due to circular includes.");
151 static int handle_path_include(const struct key_value_info *kvi,
152 const char *path,
153 struct config_include_data *inc)
155 int ret = 0;
156 struct strbuf buf = STRBUF_INIT;
157 char *expanded;
159 if (!path)
160 return config_error_nonbool("include.path");
162 expanded = interpolate_path(path, 0);
163 if (!expanded)
164 return error(_("could not expand include path '%s'"), path);
165 path = expanded;
168 * Use an absolute path as-is, but interpret relative paths
169 * based on the including config file.
171 if (!is_absolute_path(path)) {
172 char *slash;
174 if (!kvi || !kvi->path) {
175 ret = error(_("relative config includes must come from files"));
176 goto cleanup;
179 slash = find_last_dir_sep(kvi->path);
180 if (slash)
181 strbuf_add(&buf, kvi->path, slash - kvi->path + 1);
182 strbuf_addstr(&buf, path);
183 path = buf.buf;
186 if (!access_or_die(path, R_OK, 0)) {
187 if (++inc->depth > MAX_INCLUDE_DEPTH)
188 die(_(include_depth_advice), MAX_INCLUDE_DEPTH, path,
189 !kvi ? "<unknown>" :
190 kvi->filename ? kvi->filename :
191 "the command line");
192 ret = git_config_from_file_with_options(git_config_include, path, inc,
193 kvi->scope, NULL);
194 inc->depth--;
196 cleanup:
197 strbuf_release(&buf);
198 free(expanded);
199 return ret;
202 static void add_trailing_starstar_for_dir(struct strbuf *pat)
204 if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
205 strbuf_addstr(pat, "**");
208 static int prepare_include_condition_pattern(const struct key_value_info *kvi,
209 struct strbuf *pat)
211 struct strbuf path = STRBUF_INIT;
212 char *expanded;
213 int prefix = 0;
215 expanded = interpolate_path(pat->buf, 1);
216 if (expanded) {
217 strbuf_reset(pat);
218 strbuf_addstr(pat, expanded);
219 free(expanded);
222 if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
223 const char *slash;
225 if (!kvi || !kvi->path)
226 return error(_("relative config include "
227 "conditionals must come from files"));
229 strbuf_realpath(&path, kvi->path, 1);
230 slash = find_last_dir_sep(path.buf);
231 if (!slash)
232 BUG("how is this possible?");
233 strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
234 prefix = slash - path.buf + 1 /* slash */;
235 } else if (!is_absolute_path(pat->buf))
236 strbuf_insertstr(pat, 0, "**/");
238 add_trailing_starstar_for_dir(pat);
240 strbuf_release(&path);
241 return prefix;
244 static int include_by_gitdir(const struct key_value_info *kvi,
245 const struct config_options *opts,
246 const char *cond, size_t cond_len, int icase)
248 struct strbuf text = STRBUF_INIT;
249 struct strbuf pattern = STRBUF_INIT;
250 int ret = 0, prefix;
251 const char *git_dir;
252 int already_tried_absolute = 0;
254 if (opts->git_dir)
255 git_dir = opts->git_dir;
256 else
257 goto done;
259 strbuf_realpath(&text, git_dir, 1);
260 strbuf_add(&pattern, cond, cond_len);
261 prefix = prepare_include_condition_pattern(kvi, &pattern);
263 again:
264 if (prefix < 0)
265 goto done;
267 if (prefix > 0) {
269 * perform literal matching on the prefix part so that
270 * any wildcard character in it can't create side effects.
272 if (text.len < prefix)
273 goto done;
274 if (!icase && strncmp(pattern.buf, text.buf, prefix))
275 goto done;
276 if (icase && strncasecmp(pattern.buf, text.buf, prefix))
277 goto done;
280 ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
281 WM_PATHNAME | (icase ? WM_CASEFOLD : 0));
283 if (!ret && !already_tried_absolute) {
285 * We've tried e.g. matching gitdir:~/work, but if
286 * ~/work is a symlink to /mnt/storage/work
287 * strbuf_realpath() will expand it, so the rule won't
288 * match. Let's match against a
289 * strbuf_add_absolute_path() version of the path,
290 * which'll do the right thing
292 strbuf_reset(&text);
293 strbuf_add_absolute_path(&text, git_dir);
294 already_tried_absolute = 1;
295 goto again;
297 done:
298 strbuf_release(&pattern);
299 strbuf_release(&text);
300 return ret;
303 static int include_by_branch(struct config_include_data *data,
304 const char *cond, size_t cond_len)
306 int flags;
307 int ret;
308 struct strbuf pattern = STRBUF_INIT;
309 const char *refname = (!data->repo || !data->repo->gitdir) ?
310 NULL : refs_resolve_ref_unsafe(get_main_ref_store(data->repo),
311 "HEAD", 0, NULL, &flags);
312 const char *shortname;
314 if (!refname || !(flags & REF_ISSYMREF) ||
315 !skip_prefix(refname, "refs/heads/", &shortname))
316 return 0;
318 strbuf_add(&pattern, cond, cond_len);
319 add_trailing_starstar_for_dir(&pattern);
320 ret = !wildmatch(pattern.buf, shortname, WM_PATHNAME);
321 strbuf_release(&pattern);
322 return ret;
325 static int add_remote_url(const char *var, const char *value,
326 const struct config_context *ctx UNUSED, void *data)
328 struct string_list *remote_urls = data;
329 const char *remote_name;
330 size_t remote_name_len;
331 const char *key;
333 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
334 &key) &&
335 remote_name &&
336 !strcmp(key, "url"))
337 string_list_append(remote_urls, value);
338 return 0;
341 static void populate_remote_urls(struct config_include_data *inc)
343 struct config_options opts;
345 opts = *inc->opts;
346 opts.unconditional_remote_url = 1;
348 inc->remote_urls = xmalloc(sizeof(*inc->remote_urls));
349 string_list_init_dup(inc->remote_urls);
350 config_with_options(add_remote_url, inc->remote_urls,
351 inc->config_source, inc->repo, &opts);
354 static int forbid_remote_url(const char *var, const char *value UNUSED,
355 const struct config_context *ctx UNUSED,
356 void *data UNUSED)
358 const char *remote_name;
359 size_t remote_name_len;
360 const char *key;
362 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
363 &key) &&
364 remote_name &&
365 !strcmp(key, "url"))
366 die(_("remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"));
367 return 0;
370 static int at_least_one_url_matches_glob(const char *glob, int glob_len,
371 struct string_list *remote_urls)
373 struct strbuf pattern = STRBUF_INIT;
374 struct string_list_item *url_item;
375 int found = 0;
377 strbuf_add(&pattern, glob, glob_len);
378 for_each_string_list_item(url_item, remote_urls) {
379 if (!wildmatch(pattern.buf, url_item->string, WM_PATHNAME)) {
380 found = 1;
381 break;
384 strbuf_release(&pattern);
385 return found;
388 static int include_by_remote_url(struct config_include_data *inc,
389 const char *cond, size_t cond_len)
391 if (inc->opts->unconditional_remote_url)
392 return 1;
393 if (!inc->remote_urls)
394 populate_remote_urls(inc);
395 return at_least_one_url_matches_glob(cond, cond_len,
396 inc->remote_urls);
399 static int include_condition_is_true(const struct key_value_info *kvi,
400 struct config_include_data *inc,
401 const char *cond, size_t cond_len)
403 const struct config_options *opts = inc->opts;
405 if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
406 return include_by_gitdir(kvi, opts, cond, cond_len, 0);
407 else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
408 return include_by_gitdir(kvi, opts, cond, cond_len, 1);
409 else if (skip_prefix_mem(cond, cond_len, "onbranch:", &cond, &cond_len))
410 return include_by_branch(inc, cond, cond_len);
411 else if (skip_prefix_mem(cond, cond_len, "hasconfig:remote.*.url:", &cond,
412 &cond_len))
413 return include_by_remote_url(inc, cond, cond_len);
415 /* unknown conditionals are always false */
416 return 0;
419 static int git_config_include(const char *var, const char *value,
420 const struct config_context *ctx,
421 void *data)
423 struct config_include_data *inc = data;
424 const char *cond, *key;
425 size_t cond_len;
426 int ret;
429 * Pass along all values, including "include" directives; this makes it
430 * possible to query information on the includes themselves.
432 ret = inc->fn(var, value, ctx, inc->data);
433 if (ret < 0)
434 return ret;
436 if (!strcmp(var, "include.path"))
437 ret = handle_path_include(ctx->kvi, value, inc);
439 if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
440 cond && include_condition_is_true(ctx->kvi, inc, cond, cond_len) &&
441 !strcmp(key, "path")) {
442 config_fn_t old_fn = inc->fn;
444 if (inc->opts->unconditional_remote_url)
445 inc->fn = forbid_remote_url;
446 ret = handle_path_include(ctx->kvi, value, inc);
447 inc->fn = old_fn;
450 return ret;
453 static void git_config_push_split_parameter(const char *key, const char *value)
455 struct strbuf env = STRBUF_INIT;
456 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
457 if (old && *old) {
458 strbuf_addstr(&env, old);
459 strbuf_addch(&env, ' ');
461 sq_quote_buf(&env, key);
462 strbuf_addch(&env, '=');
463 if (value)
464 sq_quote_buf(&env, value);
465 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
466 strbuf_release(&env);
469 void git_config_push_parameter(const char *text)
471 const char *value;
474 * When we see:
476 * section.subsection=with=equals.key=value
478 * we cannot tell if it means:
480 * [section "subsection=with=equals"]
481 * key = value
483 * or:
485 * [section]
486 * subsection = with=equals.key=value
488 * We parse left-to-right for the first "=", meaning we'll prefer to
489 * keep the value intact over the subsection. This is historical, but
490 * also sensible since values are more likely to contain odd or
491 * untrusted input than a section name.
493 * A missing equals is explicitly allowed (as a bool-only entry).
495 value = strchr(text, '=');
496 if (value) {
497 char *key = xmemdupz(text, value - text);
498 git_config_push_split_parameter(key, value + 1);
499 free(key);
500 } else {
501 git_config_push_split_parameter(text, NULL);
505 void git_config_push_env(const char *spec)
507 char *key;
508 const char *env_name;
509 const char *env_value;
511 env_name = strrchr(spec, '=');
512 if (!env_name)
513 die(_("invalid config format: %s"), spec);
514 key = xmemdupz(spec, env_name - spec);
515 env_name++;
516 if (!*env_name)
517 die(_("missing environment variable name for configuration '%.*s'"),
518 (int)(env_name - spec - 1), spec);
520 env_value = getenv(env_name);
521 if (!env_value)
522 die(_("missing environment variable '%s' for configuration '%.*s'"),
523 env_name, (int)(env_name - spec - 1), spec);
525 git_config_push_split_parameter(key, env_value);
526 free(key);
529 static inline int iskeychar(int c)
531 return isalnum(c) || c == '-';
535 * Auxiliary function to sanity-check and split the key into the section
536 * identifier and variable name.
538 * Returns 0 on success, -1 when there is an invalid character in the key and
539 * -2 if there is no section name in the key.
541 * store_key - pointer to char* which will hold a copy of the key with
542 * lowercase section and variable name
543 * baselen - pointer to size_t which will hold the length of the
544 * section + subsection part, can be NULL
546 int git_config_parse_key(const char *key, char **store_key, size_t *baselen_)
548 size_t i, baselen;
549 int dot;
550 const char *last_dot = strrchr(key, '.');
553 * Since "key" actually contains the section name and the real
554 * key name separated by a dot, we have to know where the dot is.
557 if (last_dot == NULL || last_dot == key) {
558 error(_("key does not contain a section: %s"), key);
559 return -CONFIG_NO_SECTION_OR_NAME;
562 if (!last_dot[1]) {
563 error(_("key does not contain variable name: %s"), key);
564 return -CONFIG_NO_SECTION_OR_NAME;
567 baselen = last_dot - key;
568 if (baselen_)
569 *baselen_ = baselen;
572 * Validate the key and while at it, lower case it for matching.
574 *store_key = xmallocz(strlen(key));
576 dot = 0;
577 for (i = 0; key[i]; i++) {
578 unsigned char c = key[i];
579 if (c == '.')
580 dot = 1;
581 /* Leave the extended basename untouched.. */
582 if (!dot || i > baselen) {
583 if (!iskeychar(c) ||
584 (i == baselen + 1 && !isalpha(c))) {
585 error(_("invalid key: %s"), key);
586 goto out_free_ret_1;
588 c = tolower(c);
589 } else if (c == '\n') {
590 error(_("invalid key (newline): %s"), key);
591 goto out_free_ret_1;
593 (*store_key)[i] = c;
596 return 0;
598 out_free_ret_1:
599 FREE_AND_NULL(*store_key);
600 return -CONFIG_INVALID_KEY;
603 static int config_parse_pair(const char *key, const char *value,
604 struct key_value_info *kvi,
605 config_fn_t fn, void *data)
607 char *canonical_name;
608 int ret;
609 struct config_context ctx = {
610 .kvi = kvi,
613 if (!strlen(key))
614 return error(_("empty config key"));
615 if (git_config_parse_key(key, &canonical_name, NULL))
616 return -1;
618 ret = (fn(canonical_name, value, &ctx, data) < 0) ? -1 : 0;
619 free(canonical_name);
620 return ret;
624 /* for values read from `git_config_from_parameters()` */
625 void kvi_from_param(struct key_value_info *out)
627 out->filename = NULL;
628 out->linenr = -1;
629 out->origin_type = CONFIG_ORIGIN_CMDLINE;
630 out->scope = CONFIG_SCOPE_COMMAND;
631 out->path = NULL;
634 int git_config_parse_parameter(const char *text,
635 config_fn_t fn, void *data)
637 const char *value;
638 struct strbuf **pair;
639 int ret;
640 struct key_value_info kvi = KVI_INIT;
642 kvi_from_param(&kvi);
644 pair = strbuf_split_str(text, '=', 2);
645 if (!pair[0])
646 return error(_("bogus config parameter: %s"), text);
648 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
649 strbuf_setlen(pair[0], pair[0]->len - 1);
650 value = pair[1] ? pair[1]->buf : "";
651 } else {
652 value = NULL;
655 strbuf_trim(pair[0]);
656 if (!pair[0]->len) {
657 strbuf_list_free(pair);
658 return error(_("bogus config parameter: %s"), text);
661 ret = config_parse_pair(pair[0]->buf, value, &kvi, fn, data);
662 strbuf_list_free(pair);
663 return ret;
666 static int parse_config_env_list(char *env, struct key_value_info *kvi,
667 config_fn_t fn, void *data)
669 char *cur = env;
670 while (cur && *cur) {
671 const char *key = sq_dequote_step(cur, &cur);
672 if (!key)
673 return error(_("bogus format in %s"),
674 CONFIG_DATA_ENVIRONMENT);
676 if (!cur || isspace(*cur)) {
677 /* old-style 'key=value' */
678 if (git_config_parse_parameter(key, fn, data) < 0)
679 return -1;
681 else if (*cur == '=') {
682 /* new-style 'key'='value' */
683 const char *value;
685 cur++;
686 if (*cur == '\'') {
687 /* quoted value */
688 value = sq_dequote_step(cur, &cur);
689 if (!value || (cur && !isspace(*cur))) {
690 return error(_("bogus format in %s"),
691 CONFIG_DATA_ENVIRONMENT);
693 } else if (!*cur || isspace(*cur)) {
694 /* implicit bool: 'key'= */
695 value = NULL;
696 } else {
697 return error(_("bogus format in %s"),
698 CONFIG_DATA_ENVIRONMENT);
701 if (config_parse_pair(key, value, kvi, fn, data) < 0)
702 return -1;
704 else {
705 /* unknown format */
706 return error(_("bogus format in %s"),
707 CONFIG_DATA_ENVIRONMENT);
710 if (cur) {
711 while (isspace(*cur))
712 cur++;
715 return 0;
718 int git_config_from_parameters(config_fn_t fn, void *data)
720 const char *env;
721 struct strbuf envvar = STRBUF_INIT;
722 struct strvec to_free = STRVEC_INIT;
723 int ret = 0;
724 char *envw = NULL;
725 struct key_value_info kvi = KVI_INIT;
727 kvi_from_param(&kvi);
728 env = getenv(CONFIG_COUNT_ENVIRONMENT);
729 if (env) {
730 unsigned long count;
731 char *endp;
732 int i;
734 count = strtoul(env, &endp, 10);
735 if (*endp) {
736 ret = error(_("bogus count in %s"), CONFIG_COUNT_ENVIRONMENT);
737 goto out;
739 if (count > INT_MAX) {
740 ret = error(_("too many entries in %s"), CONFIG_COUNT_ENVIRONMENT);
741 goto out;
744 for (i = 0; i < count; i++) {
745 const char *key, *value;
747 strbuf_addf(&envvar, "GIT_CONFIG_KEY_%d", i);
748 key = getenv_safe(&to_free, envvar.buf);
749 if (!key) {
750 ret = error(_("missing config key %s"), envvar.buf);
751 goto out;
753 strbuf_reset(&envvar);
755 strbuf_addf(&envvar, "GIT_CONFIG_VALUE_%d", i);
756 value = getenv_safe(&to_free, envvar.buf);
757 if (!value) {
758 ret = error(_("missing config value %s"), envvar.buf);
759 goto out;
761 strbuf_reset(&envvar);
763 if (config_parse_pair(key, value, &kvi, fn, data) < 0) {
764 ret = -1;
765 goto out;
770 env = getenv(CONFIG_DATA_ENVIRONMENT);
771 if (env) {
772 /* sq_dequote will write over it */
773 envw = xstrdup(env);
774 if (parse_config_env_list(envw, &kvi, fn, data) < 0) {
775 ret = -1;
776 goto out;
780 out:
781 strbuf_release(&envvar);
782 strvec_clear(&to_free);
783 free(envw);
784 return ret;
787 static int get_next_char(struct config_source *cs)
789 int c = cs->do_fgetc(cs);
791 if (c == '\r') {
792 /* DOS like systems */
793 c = cs->do_fgetc(cs);
794 if (c != '\n') {
795 if (c != EOF)
796 cs->do_ungetc(c, cs);
797 c = '\r';
801 if (c != EOF && ++cs->total_len > INT_MAX) {
803 * This is an absurdly long config file; refuse to parse
804 * further in order to protect downstream code from integer
805 * overflows. Note that we can't return an error specifically,
806 * but we can mark EOF and put trash in the return value,
807 * which will trigger a parse error.
809 cs->eof = 1;
810 return 0;
813 if (c == '\n')
814 cs->linenr++;
815 if (c == EOF) {
816 cs->eof = 1;
817 cs->linenr++;
818 c = '\n';
820 return c;
823 static char *parse_value(struct config_source *cs)
825 int quote = 0, comment = 0;
826 size_t trim_len = 0;
828 strbuf_reset(&cs->value);
829 for (;;) {
830 int c = get_next_char(cs);
831 if (c == '\n') {
832 if (quote) {
833 cs->linenr--;
834 return NULL;
836 if (trim_len)
837 strbuf_setlen(&cs->value, trim_len);
838 return cs->value.buf;
840 if (comment)
841 continue;
842 if (isspace(c) && !quote) {
843 if (!trim_len)
844 trim_len = cs->value.len;
845 if (cs->value.len)
846 strbuf_addch(&cs->value, c);
847 continue;
849 if (!quote) {
850 if (c == ';' || c == '#') {
851 comment = 1;
852 continue;
855 if (trim_len)
856 trim_len = 0;
857 if (c == '\\') {
858 c = get_next_char(cs);
859 switch (c) {
860 case '\n':
861 continue;
862 case 't':
863 c = '\t';
864 break;
865 case 'b':
866 c = '\b';
867 break;
868 case 'n':
869 c = '\n';
870 break;
871 /* Some characters escape as themselves */
872 case '\\': case '"':
873 break;
874 /* Reject unknown escape sequences */
875 default:
876 return NULL;
878 strbuf_addch(&cs->value, c);
879 continue;
881 if (c == '"') {
882 quote = 1 - quote;
883 continue;
885 strbuf_addch(&cs->value, c);
889 static int get_value(struct config_source *cs, struct key_value_info *kvi,
890 config_fn_t fn, void *data, struct strbuf *name)
892 int c;
893 char *value;
894 int ret;
895 struct config_context ctx = {
896 .kvi = kvi,
899 /* Get the full name */
900 for (;;) {
901 c = get_next_char(cs);
902 if (cs->eof)
903 break;
904 if (!iskeychar(c))
905 break;
906 strbuf_addch(name, tolower(c));
909 while (c == ' ' || c == '\t')
910 c = get_next_char(cs);
912 value = NULL;
913 if (c != '\n') {
914 if (c != '=')
915 return -1;
916 value = parse_value(cs);
917 if (!value)
918 return -1;
921 * We already consumed the \n, but we need linenr to point to
922 * the line we just parsed during the call to fn to get
923 * accurate line number in error messages.
925 cs->linenr--;
926 kvi->linenr = cs->linenr;
927 ret = fn(name->buf, value, &ctx, data);
928 if (ret >= 0)
929 cs->linenr++;
930 return ret;
933 static int get_extended_base_var(struct config_source *cs, struct strbuf *name,
934 int c)
936 cs->subsection_case_sensitive = 0;
937 do {
938 if (c == '\n')
939 goto error_incomplete_line;
940 c = get_next_char(cs);
941 } while (isspace(c));
943 /* We require the format to be '[base "extension"]' */
944 if (c != '"')
945 return -1;
946 strbuf_addch(name, '.');
948 for (;;) {
949 int c = get_next_char(cs);
950 if (c == '\n')
951 goto error_incomplete_line;
952 if (c == '"')
953 break;
954 if (c == '\\') {
955 c = get_next_char(cs);
956 if (c == '\n')
957 goto error_incomplete_line;
959 strbuf_addch(name, c);
962 /* Final ']' */
963 if (get_next_char(cs) != ']')
964 return -1;
965 return 0;
966 error_incomplete_line:
967 cs->linenr--;
968 return -1;
971 static int get_base_var(struct config_source *cs, struct strbuf *name)
973 cs->subsection_case_sensitive = 1;
974 for (;;) {
975 int c = get_next_char(cs);
976 if (cs->eof)
977 return -1;
978 if (c == ']')
979 return 0;
980 if (isspace(c))
981 return get_extended_base_var(cs, name, c);
982 if (!iskeychar(c) && c != '.')
983 return -1;
984 strbuf_addch(name, tolower(c));
988 struct parse_event_data {
989 enum config_event_t previous_type;
990 size_t previous_offset;
991 const struct config_options *opts;
994 static int do_event(struct config_source *cs, enum config_event_t type,
995 struct parse_event_data *data)
997 size_t offset;
999 if (!data->opts || !data->opts->event_fn)
1000 return 0;
1002 if (type == CONFIG_EVENT_WHITESPACE &&
1003 data->previous_type == type)
1004 return 0;
1006 offset = cs->do_ftell(cs);
1008 * At EOF, the parser always "inserts" an extra '\n', therefore
1009 * the end offset of the event is the current file position, otherwise
1010 * we will already have advanced to the next event.
1012 if (type != CONFIG_EVENT_EOF)
1013 offset--;
1015 if (data->previous_type != CONFIG_EVENT_EOF &&
1016 data->opts->event_fn(data->previous_type, data->previous_offset,
1017 offset, cs, data->opts->event_fn_data) < 0)
1018 return -1;
1020 data->previous_type = type;
1021 data->previous_offset = offset;
1023 return 0;
1026 static void kvi_from_source(struct config_source *cs,
1027 enum config_scope scope,
1028 struct key_value_info *out)
1030 out->filename = strintern(cs->name);
1031 out->origin_type = cs->origin_type;
1032 out->linenr = cs->linenr;
1033 out->scope = scope;
1034 out->path = cs->path;
1037 static int git_parse_source(struct config_source *cs, config_fn_t fn,
1038 struct key_value_info *kvi, void *data,
1039 const struct config_options *opts)
1041 int comment = 0;
1042 size_t baselen = 0;
1043 struct strbuf *var = &cs->var;
1044 int error_return = 0;
1045 char *error_msg = NULL;
1047 /* U+FEFF Byte Order Mark in UTF8 */
1048 const char *bomptr = utf8_bom;
1050 /* For the parser event callback */
1051 struct parse_event_data event_data = {
1052 CONFIG_EVENT_EOF, 0, opts
1055 for (;;) {
1056 int c;
1058 c = get_next_char(cs);
1059 if (bomptr && *bomptr) {
1060 /* We are at the file beginning; skip UTF8-encoded BOM
1061 * if present. Sane editors won't put this in on their
1062 * own, but e.g. Windows Notepad will do it happily. */
1063 if (c == (*bomptr & 0377)) {
1064 bomptr++;
1065 continue;
1066 } else {
1067 /* Do not tolerate partial BOM. */
1068 if (bomptr != utf8_bom)
1069 break;
1070 /* No BOM at file beginning. Cool. */
1071 bomptr = NULL;
1074 if (c == '\n') {
1075 if (cs->eof) {
1076 if (do_event(cs, CONFIG_EVENT_EOF, &event_data) < 0)
1077 return -1;
1078 return 0;
1080 if (do_event(cs, CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1081 return -1;
1082 comment = 0;
1083 continue;
1085 if (comment)
1086 continue;
1087 if (isspace(c)) {
1088 if (do_event(cs, CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1089 return -1;
1090 continue;
1092 if (c == '#' || c == ';') {
1093 if (do_event(cs, CONFIG_EVENT_COMMENT, &event_data) < 0)
1094 return -1;
1095 comment = 1;
1096 continue;
1098 if (c == '[') {
1099 if (do_event(cs, CONFIG_EVENT_SECTION, &event_data) < 0)
1100 return -1;
1102 /* Reset prior to determining a new stem */
1103 strbuf_reset(var);
1104 if (get_base_var(cs, var) < 0 || var->len < 1)
1105 break;
1106 strbuf_addch(var, '.');
1107 baselen = var->len;
1108 continue;
1110 if (!isalpha(c))
1111 break;
1113 if (do_event(cs, CONFIG_EVENT_ENTRY, &event_data) < 0)
1114 return -1;
1117 * Truncate the var name back to the section header
1118 * stem prior to grabbing the suffix part of the name
1119 * and the value.
1121 strbuf_setlen(var, baselen);
1122 strbuf_addch(var, tolower(c));
1123 if (get_value(cs, kvi, fn, data, var) < 0)
1124 break;
1127 if (do_event(cs, CONFIG_EVENT_ERROR, &event_data) < 0)
1128 return -1;
1130 switch (cs->origin_type) {
1131 case CONFIG_ORIGIN_BLOB:
1132 error_msg = xstrfmt(_("bad config line %d in blob %s"),
1133 cs->linenr, cs->name);
1134 break;
1135 case CONFIG_ORIGIN_FILE:
1136 error_msg = xstrfmt(_("bad config line %d in file %s"),
1137 cs->linenr, cs->name);
1138 break;
1139 case CONFIG_ORIGIN_STDIN:
1140 error_msg = xstrfmt(_("bad config line %d in standard input"),
1141 cs->linenr);
1142 break;
1143 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1144 error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
1145 cs->linenr, cs->name);
1146 break;
1147 case CONFIG_ORIGIN_CMDLINE:
1148 error_msg = xstrfmt(_("bad config line %d in command line %s"),
1149 cs->linenr, cs->name);
1150 break;
1151 default:
1152 error_msg = xstrfmt(_("bad config line %d in %s"),
1153 cs->linenr, cs->name);
1156 switch (opts && opts->error_action ?
1157 opts->error_action :
1158 cs->default_error_action) {
1159 case CONFIG_ERROR_DIE:
1160 die("%s", error_msg);
1161 break;
1162 case CONFIG_ERROR_ERROR:
1163 error_return = error("%s", error_msg);
1164 break;
1165 case CONFIG_ERROR_SILENT:
1166 error_return = -1;
1167 break;
1168 case CONFIG_ERROR_UNSET:
1169 BUG("config error action unset");
1172 free(error_msg);
1173 return error_return;
1176 NORETURN
1177 static void die_bad_number(const char *name, const char *value,
1178 const struct key_value_info *kvi)
1180 const char *error_type = (errno == ERANGE) ?
1181 N_("out of range") : N_("invalid unit");
1182 const char *bad_numeric = N_("bad numeric config value '%s' for '%s': %s");
1184 if (!kvi)
1185 BUG("kvi should not be NULL");
1187 if (!value)
1188 value = "";
1190 if (!kvi->filename)
1191 die(_(bad_numeric), value, name, _(error_type));
1193 switch (kvi->origin_type) {
1194 case CONFIG_ORIGIN_BLOB:
1195 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
1196 value, name, kvi->filename, _(error_type));
1197 case CONFIG_ORIGIN_FILE:
1198 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
1199 value, name, kvi->filename, _(error_type));
1200 case CONFIG_ORIGIN_STDIN:
1201 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
1202 value, name, _(error_type));
1203 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1204 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
1205 value, name, kvi->filename, _(error_type));
1206 case CONFIG_ORIGIN_CMDLINE:
1207 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
1208 value, name, kvi->filename, _(error_type));
1209 default:
1210 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
1211 value, name, kvi->filename, _(error_type));
1215 int git_config_int(const char *name, const char *value,
1216 const struct key_value_info *kvi)
1218 int ret;
1219 if (!git_parse_int(value, &ret))
1220 die_bad_number(name, value, kvi);
1221 return ret;
1224 int64_t git_config_int64(const char *name, const char *value,
1225 const struct key_value_info *kvi)
1227 int64_t ret;
1228 if (!git_parse_int64(value, &ret))
1229 die_bad_number(name, value, kvi);
1230 return ret;
1233 unsigned long git_config_ulong(const char *name, const char *value,
1234 const struct key_value_info *kvi)
1236 unsigned long ret;
1237 if (!git_parse_ulong(value, &ret))
1238 die_bad_number(name, value, kvi);
1239 return ret;
1242 ssize_t git_config_ssize_t(const char *name, const char *value,
1243 const struct key_value_info *kvi)
1245 ssize_t ret;
1246 if (!git_parse_ssize_t(value, &ret))
1247 die_bad_number(name, value, kvi);
1248 return ret;
1251 double git_config_double(const char *name, const char *value,
1252 const struct key_value_info *kvi)
1254 double ret;
1255 if (!git_parse_double(value, &ret))
1256 die_bad_number(name, value, kvi);
1257 return ret;
1260 static const struct fsync_component_name {
1261 const char *name;
1262 enum fsync_component component_bits;
1263 } fsync_component_names[] = {
1264 { "loose-object", FSYNC_COMPONENT_LOOSE_OBJECT },
1265 { "pack", FSYNC_COMPONENT_PACK },
1266 { "pack-metadata", FSYNC_COMPONENT_PACK_METADATA },
1267 { "commit-graph", FSYNC_COMPONENT_COMMIT_GRAPH },
1268 { "index", FSYNC_COMPONENT_INDEX },
1269 { "objects", FSYNC_COMPONENTS_OBJECTS },
1270 { "reference", FSYNC_COMPONENT_REFERENCE },
1271 { "derived-metadata", FSYNC_COMPONENTS_DERIVED_METADATA },
1272 { "committed", FSYNC_COMPONENTS_COMMITTED },
1273 { "added", FSYNC_COMPONENTS_ADDED },
1274 { "all", FSYNC_COMPONENTS_ALL },
1277 static enum fsync_component parse_fsync_components(const char *var, const char *string)
1279 enum fsync_component current = FSYNC_COMPONENTS_PLATFORM_DEFAULT;
1280 enum fsync_component positive = 0, negative = 0;
1282 while (string) {
1283 int i;
1284 size_t len;
1285 const char *ep;
1286 int negated = 0;
1287 int found = 0;
1289 string = string + strspn(string, ", \t\n\r");
1290 ep = strchrnul(string, ',');
1291 len = ep - string;
1292 if (!strcmp(string, "none")) {
1293 current = FSYNC_COMPONENT_NONE;
1294 goto next_name;
1297 if (*string == '-') {
1298 negated = 1;
1299 string++;
1300 len--;
1301 if (!len)
1302 warning(_("invalid value for variable %s"), var);
1305 if (!len)
1306 break;
1308 for (i = 0; i < ARRAY_SIZE(fsync_component_names); ++i) {
1309 const struct fsync_component_name *n = &fsync_component_names[i];
1311 if (strncmp(n->name, string, len))
1312 continue;
1314 found = 1;
1315 if (negated)
1316 negative |= n->component_bits;
1317 else
1318 positive |= n->component_bits;
1321 if (!found) {
1322 char *component = xstrndup(string, len);
1323 warning(_("ignoring unknown core.fsync component '%s'"), component);
1324 free(component);
1327 next_name:
1328 string = ep;
1331 return (current & ~negative) | positive;
1334 int git_config_bool_or_int(const char *name, const char *value,
1335 const struct key_value_info *kvi, int *is_bool)
1337 int v = git_parse_maybe_bool_text(value);
1338 if (0 <= v) {
1339 *is_bool = 1;
1340 return v;
1342 *is_bool = 0;
1343 return git_config_int(name, value, kvi);
1346 int git_config_bool(const char *name, const char *value)
1348 int v = git_parse_maybe_bool(value);
1349 if (v < 0)
1350 die(_("bad boolean config value '%s' for '%s'"), value, name);
1351 return v;
1354 int git_config_string(char **dest, const char *var, const char *value)
1356 if (!value)
1357 return config_error_nonbool(var);
1358 *dest = xstrdup(value);
1359 return 0;
1362 int git_config_pathname(char **dest, const char *var, const char *value)
1364 if (!value)
1365 return config_error_nonbool(var);
1366 *dest = interpolate_path(value, 0);
1367 if (!*dest)
1368 die(_("failed to expand user dir in: '%s'"), value);
1369 return 0;
1372 int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1374 if (!value)
1375 return config_error_nonbool(var);
1376 if (parse_expiry_date(value, timestamp))
1377 return error(_("'%s' for '%s' is not a valid timestamp"),
1378 value, var);
1379 return 0;
1382 int git_config_color(char *dest, const char *var, const char *value)
1384 if (!value)
1385 return config_error_nonbool(var);
1386 if (color_parse(value, dest) < 0)
1387 return -1;
1388 return 0;
1391 static int git_default_core_config(const char *var, const char *value,
1392 const struct config_context *ctx, void *cb)
1394 /* This needs a better name */
1395 if (!strcmp(var, "core.filemode")) {
1396 trust_executable_bit = git_config_bool(var, value);
1397 return 0;
1399 if (!strcmp(var, "core.trustctime")) {
1400 trust_ctime = git_config_bool(var, value);
1401 return 0;
1403 if (!strcmp(var, "core.checkstat")) {
1404 if (!value)
1405 return config_error_nonbool(var);
1406 if (!strcasecmp(value, "default"))
1407 check_stat = 1;
1408 else if (!strcasecmp(value, "minimal"))
1409 check_stat = 0;
1410 else
1411 return error(_("invalid value for '%s': '%s'"),
1412 var, value);
1415 if (!strcmp(var, "core.quotepath")) {
1416 quote_path_fully = git_config_bool(var, value);
1417 return 0;
1420 if (!strcmp(var, "core.symlinks")) {
1421 has_symlinks = git_config_bool(var, value);
1422 return 0;
1425 if (!strcmp(var, "core.ignorecase")) {
1426 ignore_case = git_config_bool(var, value);
1427 return 0;
1430 if (!strcmp(var, "core.attributesfile")) {
1431 FREE_AND_NULL(git_attributes_file);
1432 return git_config_pathname(&git_attributes_file, var, value);
1435 if (!strcmp(var, "core.hookspath")) {
1436 FREE_AND_NULL(git_hooks_path);
1437 return git_config_pathname(&git_hooks_path, var, value);
1440 if (!strcmp(var, "core.bare")) {
1441 is_bare_repository_cfg = git_config_bool(var, value);
1442 return 0;
1445 if (!strcmp(var, "core.ignorestat")) {
1446 assume_unchanged = git_config_bool(var, value);
1447 return 0;
1450 if (!strcmp(var, "core.abbrev")) {
1451 if (!value)
1452 return config_error_nonbool(var);
1453 if (!strcasecmp(value, "auto"))
1454 default_abbrev = -1;
1455 else if (!git_parse_maybe_bool_text(value))
1456 default_abbrev = GIT_MAX_HEXSZ;
1457 else {
1458 int abbrev = git_config_int(var, value, ctx->kvi);
1459 if (abbrev < minimum_abbrev)
1460 return error(_("abbrev length out of range: %d"), abbrev);
1461 default_abbrev = abbrev;
1463 return 0;
1466 if (!strcmp(var, "core.disambiguate"))
1467 return set_disambiguate_hint_config(var, value);
1469 if (!strcmp(var, "core.loosecompression")) {
1470 int level = git_config_int(var, value, ctx->kvi);
1471 if (level == -1)
1472 level = Z_DEFAULT_COMPRESSION;
1473 else if (level < 0 || level > Z_BEST_COMPRESSION)
1474 die(_("bad zlib compression level %d"), level);
1475 zlib_compression_level = level;
1476 zlib_compression_seen = 1;
1477 return 0;
1480 if (!strcmp(var, "core.compression")) {
1481 int level = git_config_int(var, value, ctx->kvi);
1482 if (level == -1)
1483 level = Z_DEFAULT_COMPRESSION;
1484 else if (level < 0 || level > Z_BEST_COMPRESSION)
1485 die(_("bad zlib compression level %d"), level);
1486 if (!zlib_compression_seen)
1487 zlib_compression_level = level;
1488 if (!pack_compression_seen)
1489 pack_compression_level = level;
1490 return 0;
1493 if (!strcmp(var, "core.packedgitwindowsize")) {
1494 int pgsz_x2 = getpagesize() * 2;
1495 packed_git_window_size = git_config_ulong(var, value, ctx->kvi);
1497 /* This value must be multiple of (pagesize * 2) */
1498 packed_git_window_size /= pgsz_x2;
1499 if (packed_git_window_size < 1)
1500 packed_git_window_size = 1;
1501 packed_git_window_size *= pgsz_x2;
1502 return 0;
1505 if (!strcmp(var, "core.bigfilethreshold")) {
1506 big_file_threshold = git_config_ulong(var, value, ctx->kvi);
1507 return 0;
1510 if (!strcmp(var, "core.packedgitlimit")) {
1511 packed_git_limit = git_config_ulong(var, value, ctx->kvi);
1512 return 0;
1515 if (!strcmp(var, "core.deltabasecachelimit")) {
1516 delta_base_cache_limit = git_config_ulong(var, value, ctx->kvi);
1517 return 0;
1520 if (!strcmp(var, "core.autocrlf")) {
1521 if (value && !strcasecmp(value, "input")) {
1522 auto_crlf = AUTO_CRLF_INPUT;
1523 return 0;
1525 auto_crlf = git_config_bool(var, value);
1526 return 0;
1529 if (!strcmp(var, "core.safecrlf")) {
1530 int eol_rndtrp_die;
1531 if (value && !strcasecmp(value, "warn")) {
1532 global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
1533 return 0;
1535 eol_rndtrp_die = git_config_bool(var, value);
1536 global_conv_flags_eol = eol_rndtrp_die ?
1537 CONV_EOL_RNDTRP_DIE : 0;
1538 return 0;
1541 if (!strcmp(var, "core.eol")) {
1542 if (value && !strcasecmp(value, "lf"))
1543 core_eol = EOL_LF;
1544 else if (value && !strcasecmp(value, "crlf"))
1545 core_eol = EOL_CRLF;
1546 else if (value && !strcasecmp(value, "native"))
1547 core_eol = EOL_NATIVE;
1548 else
1549 core_eol = EOL_UNSET;
1550 return 0;
1553 if (!strcmp(var, "core.checkroundtripencoding")) {
1554 FREE_AND_NULL(check_roundtrip_encoding);
1555 return git_config_string(&check_roundtrip_encoding, var, value);
1558 if (!strcmp(var, "core.editor")) {
1559 FREE_AND_NULL(editor_program);
1560 return git_config_string(&editor_program, var, value);
1563 if (!strcmp(var, "core.commentchar") ||
1564 !strcmp(var, "core.commentstring")) {
1565 if (!value)
1566 return config_error_nonbool(var);
1567 else if (!strcasecmp(value, "auto"))
1568 auto_comment_line_char = 1;
1569 else if (value[0]) {
1570 if (strchr(value, '\n'))
1571 return error(_("%s cannot contain newline"), var);
1572 comment_line_str = value;
1573 FREE_AND_NULL(comment_line_str_to_free);
1574 auto_comment_line_char = 0;
1575 } else
1576 return error(_("%s must have at least one character"), var);
1577 return 0;
1580 if (!strcmp(var, "core.askpass")) {
1581 FREE_AND_NULL(askpass_program);
1582 return git_config_string(&askpass_program, var, value);
1585 if (!strcmp(var, "core.excludesfile")) {
1586 FREE_AND_NULL(excludes_file);
1587 return git_config_pathname(&excludes_file, var, value);
1590 if (!strcmp(var, "core.whitespace")) {
1591 if (!value)
1592 return config_error_nonbool(var);
1593 whitespace_rule_cfg = parse_whitespace_rule(value);
1594 return 0;
1597 if (!strcmp(var, "core.fsync")) {
1598 if (!value)
1599 return config_error_nonbool(var);
1600 fsync_components = parse_fsync_components(var, value);
1601 return 0;
1604 if (!strcmp(var, "core.fsyncmethod")) {
1605 if (!value)
1606 return config_error_nonbool(var);
1607 if (!strcmp(value, "fsync"))
1608 fsync_method = FSYNC_METHOD_FSYNC;
1609 else if (!strcmp(value, "writeout-only"))
1610 fsync_method = FSYNC_METHOD_WRITEOUT_ONLY;
1611 else if (!strcmp(value, "batch"))
1612 fsync_method = FSYNC_METHOD_BATCH;
1613 else
1614 warning(_("ignoring unknown core.fsyncMethod value '%s'"), value);
1618 if (!strcmp(var, "core.fsyncobjectfiles")) {
1619 if (fsync_object_files < 0)
1620 warning(_("core.fsyncObjectFiles is deprecated; use core.fsync instead"));
1621 fsync_object_files = git_config_bool(var, value);
1622 return 0;
1625 if (!strcmp(var, "core.preloadindex")) {
1626 core_preload_index = git_config_bool(var, value);
1627 return 0;
1630 if (!strcmp(var, "core.createobject")) {
1631 if (!value)
1632 return config_error_nonbool(var);
1633 if (!strcmp(value, "rename"))
1634 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
1635 else if (!strcmp(value, "link"))
1636 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
1637 else
1638 die(_("invalid mode for object creation: %s"), value);
1639 return 0;
1642 if (!strcmp(var, "core.sparsecheckout")) {
1643 core_apply_sparse_checkout = git_config_bool(var, value);
1644 return 0;
1647 if (!strcmp(var, "core.sparsecheckoutcone")) {
1648 core_sparse_checkout_cone = git_config_bool(var, value);
1649 return 0;
1652 if (!strcmp(var, "core.precomposeunicode")) {
1653 precomposed_unicode = git_config_bool(var, value);
1654 return 0;
1657 if (!strcmp(var, "core.protecthfs")) {
1658 protect_hfs = git_config_bool(var, value);
1659 return 0;
1662 if (!strcmp(var, "core.protectntfs")) {
1663 protect_ntfs = git_config_bool(var, value);
1664 return 0;
1667 if (!strcmp(var, "core.maxtreedepth")) {
1668 max_allowed_tree_depth = git_config_int(var, value, ctx->kvi);
1669 return 0;
1672 /* Add other config variables here and to Documentation/config.txt. */
1673 return platform_core_config(var, value, ctx, cb);
1676 static int git_default_sparse_config(const char *var, const char *value)
1678 if (!strcmp(var, "sparse.expectfilesoutsideofpatterns")) {
1679 sparse_expect_files_outside_of_patterns = git_config_bool(var, value);
1680 return 0;
1683 /* Add other config variables here and to Documentation/config/sparse.txt. */
1684 return 0;
1687 static int git_default_i18n_config(const char *var, const char *value)
1689 if (!strcmp(var, "i18n.commitencoding")) {
1690 FREE_AND_NULL(git_commit_encoding);
1691 return git_config_string(&git_commit_encoding, var, value);
1694 if (!strcmp(var, "i18n.logoutputencoding")) {
1695 FREE_AND_NULL(git_log_output_encoding);
1696 return git_config_string(&git_log_output_encoding, var, value);
1699 /* Add other config variables here and to Documentation/config.txt. */
1700 return 0;
1703 static int git_default_branch_config(const char *var, const char *value)
1705 if (!strcmp(var, "branch.autosetupmerge")) {
1706 if (value && !strcmp(value, "always")) {
1707 git_branch_track = BRANCH_TRACK_ALWAYS;
1708 return 0;
1709 } else if (value && !strcmp(value, "inherit")) {
1710 git_branch_track = BRANCH_TRACK_INHERIT;
1711 return 0;
1712 } else if (value && !strcmp(value, "simple")) {
1713 git_branch_track = BRANCH_TRACK_SIMPLE;
1714 return 0;
1716 git_branch_track = git_config_bool(var, value);
1717 return 0;
1719 if (!strcmp(var, "branch.autosetuprebase")) {
1720 if (!value)
1721 return config_error_nonbool(var);
1722 else if (!strcmp(value, "never"))
1723 autorebase = AUTOREBASE_NEVER;
1724 else if (!strcmp(value, "local"))
1725 autorebase = AUTOREBASE_LOCAL;
1726 else if (!strcmp(value, "remote"))
1727 autorebase = AUTOREBASE_REMOTE;
1728 else if (!strcmp(value, "always"))
1729 autorebase = AUTOREBASE_ALWAYS;
1730 else
1731 return error(_("malformed value for %s"), var);
1732 return 0;
1735 /* Add other config variables here and to Documentation/config.txt. */
1736 return 0;
1739 static int git_default_push_config(const char *var, const char *value)
1741 if (!strcmp(var, "push.default")) {
1742 if (!value)
1743 return config_error_nonbool(var);
1744 else if (!strcmp(value, "nothing"))
1745 push_default = PUSH_DEFAULT_NOTHING;
1746 else if (!strcmp(value, "matching"))
1747 push_default = PUSH_DEFAULT_MATCHING;
1748 else if (!strcmp(value, "simple"))
1749 push_default = PUSH_DEFAULT_SIMPLE;
1750 else if (!strcmp(value, "upstream"))
1751 push_default = PUSH_DEFAULT_UPSTREAM;
1752 else if (!strcmp(value, "tracking")) /* deprecated */
1753 push_default = PUSH_DEFAULT_UPSTREAM;
1754 else if (!strcmp(value, "current"))
1755 push_default = PUSH_DEFAULT_CURRENT;
1756 else {
1757 error(_("malformed value for %s: %s"), var, value);
1758 return error(_("must be one of nothing, matching, simple, "
1759 "upstream or current"));
1761 return 0;
1764 /* Add other config variables here and to Documentation/config.txt. */
1765 return 0;
1768 static int git_default_mailmap_config(const char *var, const char *value)
1770 if (!strcmp(var, "mailmap.file")) {
1771 FREE_AND_NULL(git_mailmap_file);
1772 return git_config_pathname(&git_mailmap_file, var, value);
1775 if (!strcmp(var, "mailmap.blob")) {
1776 FREE_AND_NULL(git_mailmap_blob);
1777 return git_config_string(&git_mailmap_blob, var, value);
1780 /* Add other config variables here and to Documentation/config.txt. */
1781 return 0;
1784 static int git_default_attr_config(const char *var, const char *value)
1786 if (!strcmp(var, "attr.tree")) {
1787 FREE_AND_NULL(git_attr_tree);
1788 return git_config_string(&git_attr_tree, var, value);
1792 * Add other attribute related config variables here and to
1793 * Documentation/config/attr.txt.
1795 return 0;
1798 int git_default_config(const char *var, const char *value,
1799 const struct config_context *ctx, void *cb)
1801 if (starts_with(var, "core."))
1802 return git_default_core_config(var, value, ctx, cb);
1804 if (starts_with(var, "user.") ||
1805 starts_with(var, "author.") ||
1806 starts_with(var, "committer."))
1807 return git_ident_config(var, value, ctx, cb);
1809 if (starts_with(var, "i18n."))
1810 return git_default_i18n_config(var, value);
1812 if (starts_with(var, "branch."))
1813 return git_default_branch_config(var, value);
1815 if (starts_with(var, "push."))
1816 return git_default_push_config(var, value);
1818 if (starts_with(var, "mailmap."))
1819 return git_default_mailmap_config(var, value);
1821 if (starts_with(var, "attr."))
1822 return git_default_attr_config(var, value);
1824 if (starts_with(var, "advice.") || starts_with(var, "color.advice"))
1825 return git_default_advice_config(var, value);
1827 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1828 pager_use_color = git_config_bool(var,value);
1829 return 0;
1832 if (!strcmp(var, "pack.packsizelimit")) {
1833 pack_size_limit_cfg = git_config_ulong(var, value, ctx->kvi);
1834 return 0;
1837 if (!strcmp(var, "pack.compression")) {
1838 int level = git_config_int(var, value, ctx->kvi);
1839 if (level == -1)
1840 level = Z_DEFAULT_COMPRESSION;
1841 else if (level < 0 || level > Z_BEST_COMPRESSION)
1842 die(_("bad pack compression level %d"), level);
1843 pack_compression_level = level;
1844 pack_compression_seen = 1;
1845 return 0;
1848 if (starts_with(var, "sparse."))
1849 return git_default_sparse_config(var, value);
1851 /* Add other config variables here and to Documentation/config.txt. */
1852 return 0;
1856 * All source specific fields in the union, die_on_error, name and the callbacks
1857 * fgetc, ungetc, ftell of top need to be initialized before calling
1858 * this function.
1860 static int do_config_from(struct config_source *top, config_fn_t fn,
1861 void *data, enum config_scope scope,
1862 const struct config_options *opts)
1864 struct key_value_info kvi = KVI_INIT;
1865 int ret;
1867 /* push config-file parsing state stack */
1868 top->linenr = 1;
1869 top->eof = 0;
1870 top->total_len = 0;
1871 strbuf_init(&top->value, 1024);
1872 strbuf_init(&top->var, 1024);
1873 kvi_from_source(top, scope, &kvi);
1875 ret = git_parse_source(top, fn, &kvi, data, opts);
1877 strbuf_release(&top->value);
1878 strbuf_release(&top->var);
1880 return ret;
1883 static int do_config_from_file(config_fn_t fn,
1884 const enum config_origin_type origin_type,
1885 const char *name, const char *path, FILE *f,
1886 void *data, enum config_scope scope,
1887 const struct config_options *opts)
1889 struct config_source top = CONFIG_SOURCE_INIT;
1890 int ret;
1892 top.u.file = f;
1893 top.origin_type = origin_type;
1894 top.name = name;
1895 top.path = path;
1896 top.default_error_action = CONFIG_ERROR_DIE;
1897 top.do_fgetc = config_file_fgetc;
1898 top.do_ungetc = config_file_ungetc;
1899 top.do_ftell = config_file_ftell;
1901 flockfile(f);
1902 ret = do_config_from(&top, fn, data, scope, opts);
1903 funlockfile(f);
1904 return ret;
1907 static int git_config_from_stdin(config_fn_t fn, void *data,
1908 enum config_scope scope)
1910 return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", NULL, stdin,
1911 data, scope, NULL);
1914 int git_config_from_file_with_options(config_fn_t fn, const char *filename,
1915 void *data, enum config_scope scope,
1916 const struct config_options *opts)
1918 int ret = -1;
1919 FILE *f;
1921 if (!filename)
1922 BUG("filename cannot be NULL");
1923 f = fopen_or_warn(filename, "r");
1924 if (f) {
1925 ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename,
1926 filename, f, data, scope, opts);
1927 fclose(f);
1929 return ret;
1932 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
1934 return git_config_from_file_with_options(fn, filename, data,
1935 CONFIG_SCOPE_UNKNOWN, NULL);
1938 int git_config_from_mem(config_fn_t fn,
1939 const enum config_origin_type origin_type,
1940 const char *name, const char *buf, size_t len,
1941 void *data, enum config_scope scope,
1942 const struct config_options *opts)
1944 struct config_source top = CONFIG_SOURCE_INIT;
1946 top.u.buf.buf = buf;
1947 top.u.buf.len = len;
1948 top.u.buf.pos = 0;
1949 top.origin_type = origin_type;
1950 top.name = name;
1951 top.path = NULL;
1952 top.default_error_action = CONFIG_ERROR_ERROR;
1953 top.do_fgetc = config_buf_fgetc;
1954 top.do_ungetc = config_buf_ungetc;
1955 top.do_ftell = config_buf_ftell;
1957 return do_config_from(&top, fn, data, scope, opts);
1960 int git_config_from_blob_oid(config_fn_t fn,
1961 const char *name,
1962 struct repository *repo,
1963 const struct object_id *oid,
1964 void *data,
1965 enum config_scope scope)
1967 enum object_type type;
1968 char *buf;
1969 unsigned long size;
1970 int ret;
1972 buf = repo_read_object_file(repo, oid, &type, &size);
1973 if (!buf)
1974 return error(_("unable to load config blob object '%s'"), name);
1975 if (type != OBJ_BLOB) {
1976 free(buf);
1977 return error(_("reference '%s' does not point to a blob"), name);
1980 ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size,
1981 data, scope, NULL);
1982 free(buf);
1984 return ret;
1987 static int git_config_from_blob_ref(config_fn_t fn,
1988 struct repository *repo,
1989 const char *name,
1990 void *data,
1991 enum config_scope scope)
1993 struct object_id oid;
1995 if (repo_get_oid(repo, name, &oid) < 0)
1996 return error(_("unable to resolve config blob '%s'"), name);
1997 return git_config_from_blob_oid(fn, name, repo, &oid, data, scope);
2000 char *git_system_config(void)
2002 char *system_config = xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
2003 if (!system_config)
2004 system_config = system_path(ETC_GITCONFIG);
2005 normalize_path_copy(system_config, system_config);
2006 return system_config;
2009 char *git_global_config(void)
2011 char *user_config, *xdg_config;
2013 git_global_config_paths(&user_config, &xdg_config);
2014 if (!user_config) {
2015 free(xdg_config);
2016 return NULL;
2019 if (access_or_warn(user_config, R_OK, 0) && xdg_config &&
2020 !access_or_warn(xdg_config, R_OK, 0)) {
2021 free(user_config);
2022 return xdg_config;
2023 } else {
2024 free(xdg_config);
2025 return user_config;
2029 void git_global_config_paths(char **user_out, char **xdg_out)
2031 char *user_config = xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
2032 char *xdg_config = NULL;
2034 if (!user_config) {
2035 user_config = interpolate_path("~/.gitconfig", 0);
2036 xdg_config = xdg_config_home("config");
2039 *user_out = user_config;
2040 *xdg_out = xdg_config;
2043 int git_config_system(void)
2045 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
2048 static int do_git_config_sequence(const struct config_options *opts,
2049 const struct repository *repo,
2050 config_fn_t fn, void *data)
2052 int ret = 0;
2053 char *system_config = git_system_config();
2054 char *xdg_config = NULL;
2055 char *user_config = NULL;
2056 char *repo_config;
2057 char *worktree_config;
2060 * Ensure that either:
2061 * - the git_dir and commondir are both set, or
2062 * - the git_dir and commondir are both NULL
2064 if (!opts->git_dir != !opts->commondir)
2065 BUG("only one of commondir and git_dir is non-NULL");
2067 if (opts->commondir) {
2068 repo_config = mkpathdup("%s/config", opts->commondir);
2069 worktree_config = mkpathdup("%s/config.worktree", opts->git_dir);
2070 } else {
2071 repo_config = NULL;
2072 worktree_config = NULL;
2075 if (git_config_system() && system_config &&
2076 !access_or_die(system_config, R_OK,
2077 opts->system_gently ? ACCESS_EACCES_OK : 0))
2078 ret += git_config_from_file_with_options(fn, system_config,
2079 data, CONFIG_SCOPE_SYSTEM,
2080 NULL);
2082 git_global_config_paths(&user_config, &xdg_config);
2084 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
2085 ret += git_config_from_file_with_options(fn, xdg_config, data,
2086 CONFIG_SCOPE_GLOBAL, NULL);
2088 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
2089 ret += git_config_from_file_with_options(fn, user_config, data,
2090 CONFIG_SCOPE_GLOBAL, NULL);
2092 if (!opts->ignore_repo && repo_config &&
2093 !access_or_die(repo_config, R_OK, 0))
2094 ret += git_config_from_file_with_options(fn, repo_config, data,
2095 CONFIG_SCOPE_LOCAL, NULL);
2097 if (!opts->ignore_worktree && worktree_config &&
2098 repo && repo->repository_format_worktree_config &&
2099 !access_or_die(worktree_config, R_OK, 0)) {
2100 ret += git_config_from_file_with_options(fn, worktree_config, data,
2101 CONFIG_SCOPE_WORKTREE,
2102 NULL);
2105 if (!opts->ignore_cmdline && git_config_from_parameters(fn, data) < 0)
2106 die(_("unable to parse command-line config"));
2108 free(system_config);
2109 free(xdg_config);
2110 free(user_config);
2111 free(repo_config);
2112 free(worktree_config);
2113 return ret;
2116 int config_with_options(config_fn_t fn, void *data,
2117 const struct git_config_source *config_source,
2118 struct repository *repo,
2119 const struct config_options *opts)
2121 struct config_include_data inc = CONFIG_INCLUDE_INIT;
2122 int ret;
2124 if (opts->respect_includes) {
2125 inc.fn = fn;
2126 inc.data = data;
2127 inc.opts = opts;
2128 inc.repo = repo;
2129 inc.config_source = config_source;
2130 fn = git_config_include;
2131 data = &inc;
2135 * If we have a specific filename, use it. Otherwise, follow the
2136 * regular lookup sequence.
2138 if (config_source && config_source->use_stdin) {
2139 ret = git_config_from_stdin(fn, data, config_source->scope);
2140 } else if (config_source && config_source->file) {
2141 ret = git_config_from_file_with_options(fn, config_source->file,
2142 data, config_source->scope,
2143 NULL);
2144 } else if (config_source && config_source->blob) {
2145 ret = git_config_from_blob_ref(fn, repo, config_source->blob,
2146 data, config_source->scope);
2147 } else {
2148 ret = do_git_config_sequence(opts, repo, fn, data);
2151 if (inc.remote_urls) {
2152 string_list_clear(inc.remote_urls, 0);
2153 FREE_AND_NULL(inc.remote_urls);
2155 return ret;
2158 static void configset_iter(struct config_set *set, config_fn_t fn, void *data)
2160 int i, value_index;
2161 struct string_list *values;
2162 struct config_set_element *entry;
2163 struct configset_list *list = &set->list;
2164 struct config_context ctx = CONFIG_CONTEXT_INIT;
2166 for (i = 0; i < list->nr; i++) {
2167 entry = list->items[i].e;
2168 value_index = list->items[i].value_index;
2169 values = &entry->value_list;
2171 ctx.kvi = values->items[value_index].util;
2172 if (fn(entry->key, values->items[value_index].string, &ctx, data) < 0)
2173 git_die_config_linenr(entry->key,
2174 ctx.kvi->filename,
2175 ctx.kvi->linenr);
2179 void read_early_config(struct repository *repo, config_fn_t cb, void *data)
2181 struct config_options opts = {0};
2182 struct strbuf commondir = STRBUF_INIT;
2183 struct strbuf gitdir = STRBUF_INIT;
2185 opts.respect_includes = 1;
2187 if (repo && repo->gitdir) {
2188 opts.commondir = repo_get_common_dir(repo);
2189 opts.git_dir = repo_get_git_dir(repo);
2191 * When setup_git_directory() was not yet asked to discover the
2192 * GIT_DIR, we ask discover_git_directory() to figure out whether there
2193 * is any repository config we should use (but unlike
2194 * setup_git_directory_gently(), no global state is changed, most
2195 * notably, the current working directory is still the same after the
2196 * call).
2198 } else if (!discover_git_directory(&commondir, &gitdir)) {
2199 opts.commondir = commondir.buf;
2200 opts.git_dir = gitdir.buf;
2203 config_with_options(cb, data, NULL, NULL, &opts);
2205 strbuf_release(&commondir);
2206 strbuf_release(&gitdir);
2209 void read_very_early_config(config_fn_t cb, void *data)
2211 struct config_options opts = { 0 };
2213 opts.respect_includes = 1;
2214 opts.ignore_repo = 1;
2215 opts.ignore_worktree = 1;
2216 opts.ignore_cmdline = 1;
2217 opts.system_gently = 1;
2219 config_with_options(cb, data, NULL, NULL, &opts);
2222 RESULT_MUST_BE_USED
2223 static int configset_find_element(struct config_set *set, const char *key,
2224 struct config_set_element **dest)
2226 struct config_set_element k;
2227 struct config_set_element *found_entry;
2228 char *normalized_key;
2229 int ret;
2232 * `key` may come from the user, so normalize it before using it
2233 * for querying entries from the hashmap.
2235 ret = git_config_parse_key(key, &normalized_key, NULL);
2236 if (ret)
2237 return ret;
2239 hashmap_entry_init(&k.ent, strhash(normalized_key));
2240 k.key = normalized_key;
2241 found_entry = hashmap_get_entry(&set->config_hash, &k, ent, NULL);
2242 free(normalized_key);
2243 *dest = found_entry;
2244 return 0;
2247 static int configset_add_value(const struct key_value_info *kvi_p,
2248 struct config_set *set, const char *key,
2249 const char *value)
2251 struct config_set_element *e;
2252 struct string_list_item *si;
2253 struct configset_list_item *l_item;
2254 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
2255 int ret;
2257 ret = configset_find_element(set, key, &e);
2258 if (ret)
2259 return ret;
2261 * Since the keys are being fed by git_config*() callback mechanism, they
2262 * are already normalized. So simply add them without any further munging.
2264 if (!e) {
2265 e = xmalloc(sizeof(*e));
2266 hashmap_entry_init(&e->ent, strhash(key));
2267 e->key = xstrdup(key);
2268 string_list_init_dup(&e->value_list);
2269 hashmap_add(&set->config_hash, &e->ent);
2271 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
2273 ALLOC_GROW(set->list.items, set->list.nr + 1, set->list.alloc);
2274 l_item = &set->list.items[set->list.nr++];
2275 l_item->e = e;
2276 l_item->value_index = e->value_list.nr - 1;
2278 *kv_info = *kvi_p;
2279 si->util = kv_info;
2281 return 0;
2284 static int config_set_element_cmp(const void *cmp_data UNUSED,
2285 const struct hashmap_entry *eptr,
2286 const struct hashmap_entry *entry_or_key,
2287 const void *keydata UNUSED)
2289 const struct config_set_element *e1, *e2;
2291 e1 = container_of(eptr, const struct config_set_element, ent);
2292 e2 = container_of(entry_or_key, const struct config_set_element, ent);
2294 return strcmp(e1->key, e2->key);
2297 void git_configset_init(struct config_set *set)
2299 hashmap_init(&set->config_hash, config_set_element_cmp, NULL, 0);
2300 set->hash_initialized = 1;
2301 set->list.nr = 0;
2302 set->list.alloc = 0;
2303 set->list.items = NULL;
2306 void git_configset_clear(struct config_set *set)
2308 struct config_set_element *entry;
2309 struct hashmap_iter iter;
2310 if (!set->hash_initialized)
2311 return;
2313 hashmap_for_each_entry(&set->config_hash, &iter, entry,
2314 ent /* member name */) {
2315 free(entry->key);
2316 string_list_clear(&entry->value_list, 1);
2318 hashmap_clear_and_free(&set->config_hash, struct config_set_element, ent);
2319 set->hash_initialized = 0;
2320 free(set->list.items);
2321 set->list.nr = 0;
2322 set->list.alloc = 0;
2323 set->list.items = NULL;
2326 static int config_set_callback(const char *key, const char *value,
2327 const struct config_context *ctx,
2328 void *cb)
2330 struct config_set *set = cb;
2331 configset_add_value(ctx->kvi, set, key, value);
2332 return 0;
2335 int git_configset_add_file(struct config_set *set, const char *filename)
2337 return git_config_from_file(config_set_callback, filename, set);
2340 int git_configset_get_value(struct config_set *set, const char *key,
2341 const char **value, struct key_value_info *kvi)
2343 const struct string_list *values = NULL;
2344 int ret;
2345 struct string_list_item item;
2347 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
2348 * queried key in the files of the configset, the value returned will be the last
2349 * value in the value list for that key.
2351 if ((ret = git_configset_get_value_multi(set, key, &values)))
2352 return ret;
2354 assert(values->nr > 0);
2355 item = values->items[values->nr - 1];
2356 *value = item.string;
2357 if (kvi)
2358 *kvi = *((struct key_value_info *)item.util);
2359 return 0;
2362 int git_configset_get_value_multi(struct config_set *set, const char *key,
2363 const struct string_list **dest)
2365 struct config_set_element *e;
2366 int ret;
2368 if ((ret = configset_find_element(set, key, &e)))
2369 return ret;
2370 else if (!e)
2371 return 1;
2372 *dest = &e->value_list;
2374 return 0;
2377 static int check_multi_string(struct string_list_item *item, void *util)
2379 return item->string ? 0 : config_error_nonbool(util);
2382 int git_configset_get_string_multi(struct config_set *cs, const char *key,
2383 const struct string_list **dest)
2385 int ret;
2387 if ((ret = git_configset_get_value_multi(cs, key, dest)))
2388 return ret;
2389 if ((ret = for_each_string_list((struct string_list *)*dest,
2390 check_multi_string, (void *)key)))
2391 return ret;
2393 return 0;
2396 int git_configset_get(struct config_set *set, const char *key)
2398 struct config_set_element *e;
2399 int ret;
2401 if ((ret = configset_find_element(set, key, &e)))
2402 return ret;
2403 else if (!e)
2404 return 1;
2405 return 0;
2408 int git_configset_get_string(struct config_set *set, const char *key, char **dest)
2410 const char *value;
2411 if (!git_configset_get_value(set, key, &value, NULL))
2412 return git_config_string(dest, key, value);
2413 else
2414 return 1;
2417 static int git_configset_get_string_tmp(struct config_set *set, const char *key,
2418 const char **dest)
2420 const char *value;
2421 if (!git_configset_get_value(set, key, &value, NULL)) {
2422 if (!value)
2423 return config_error_nonbool(key);
2424 *dest = value;
2425 return 0;
2426 } else {
2427 return 1;
2431 int git_configset_get_int(struct config_set *set, const char *key, int *dest)
2433 const char *value;
2434 struct key_value_info kvi;
2436 if (!git_configset_get_value(set, key, &value, &kvi)) {
2437 *dest = git_config_int(key, value, &kvi);
2438 return 0;
2439 } else
2440 return 1;
2443 int git_configset_get_ulong(struct config_set *set, const char *key, unsigned long *dest)
2445 const char *value;
2446 struct key_value_info kvi;
2448 if (!git_configset_get_value(set, key, &value, &kvi)) {
2449 *dest = git_config_ulong(key, value, &kvi);
2450 return 0;
2451 } else
2452 return 1;
2455 int git_configset_get_bool(struct config_set *set, const char *key, int *dest)
2457 const char *value;
2458 if (!git_configset_get_value(set, key, &value, NULL)) {
2459 *dest = git_config_bool(key, value);
2460 return 0;
2461 } else
2462 return 1;
2465 int git_configset_get_bool_or_int(struct config_set *set, const char *key,
2466 int *is_bool, int *dest)
2468 const char *value;
2469 struct key_value_info kvi;
2471 if (!git_configset_get_value(set, key, &value, &kvi)) {
2472 *dest = git_config_bool_or_int(key, value, &kvi, is_bool);
2473 return 0;
2474 } else
2475 return 1;
2478 int git_configset_get_maybe_bool(struct config_set *set, const char *key, int *dest)
2480 const char *value;
2481 if (!git_configset_get_value(set, key, &value, NULL)) {
2482 *dest = git_parse_maybe_bool(value);
2483 if (*dest == -1)
2484 return -1;
2485 return 0;
2486 } else
2487 return 1;
2490 int git_configset_get_pathname(struct config_set *set, const char *key, char **dest)
2492 const char *value;
2493 if (!git_configset_get_value(set, key, &value, NULL))
2494 return git_config_pathname(dest, key, value);
2495 else
2496 return 1;
2499 /* Functions use to read configuration from a repository */
2500 static void repo_read_config(struct repository *repo)
2502 struct config_options opts = { 0 };
2504 opts.respect_includes = 1;
2505 opts.commondir = repo->commondir;
2506 opts.git_dir = repo->gitdir;
2508 if (!repo->config)
2509 CALLOC_ARRAY(repo->config, 1);
2510 else
2511 git_configset_clear(repo->config);
2513 git_configset_init(repo->config);
2514 if (config_with_options(config_set_callback, repo->config, NULL,
2515 repo, &opts) < 0)
2517 * config_with_options() normally returns only
2518 * zero, as most errors are fatal, and
2519 * non-fatal potential errors are guarded by "if"
2520 * statements that are entered only when no error is
2521 * possible.
2523 * If we ever encounter a non-fatal error, it means
2524 * something went really wrong and we should stop
2525 * immediately.
2527 die(_("unknown error occurred while reading the configuration files"));
2530 static void git_config_check_init(struct repository *repo)
2532 if (repo->config && repo->config->hash_initialized)
2533 return;
2534 repo_read_config(repo);
2537 void repo_config_clear(struct repository *repo)
2539 if (!repo->config || !repo->config->hash_initialized)
2540 return;
2541 git_configset_clear(repo->config);
2544 void repo_config(struct repository *repo, config_fn_t fn, void *data)
2546 git_config_check_init(repo);
2547 configset_iter(repo->config, fn, data);
2550 int repo_config_get(struct repository *repo, const char *key)
2552 git_config_check_init(repo);
2553 return git_configset_get(repo->config, key);
2556 int repo_config_get_value(struct repository *repo,
2557 const char *key, const char **value)
2559 git_config_check_init(repo);
2560 return git_configset_get_value(repo->config, key, value, NULL);
2563 int repo_config_get_value_multi(struct repository *repo, const char *key,
2564 const struct string_list **dest)
2566 git_config_check_init(repo);
2567 return git_configset_get_value_multi(repo->config, key, dest);
2570 int repo_config_get_string_multi(struct repository *repo, const char *key,
2571 const struct string_list **dest)
2573 git_config_check_init(repo);
2574 return git_configset_get_string_multi(repo->config, key, dest);
2577 int repo_config_get_string(struct repository *repo,
2578 const char *key, char **dest)
2580 int ret;
2581 git_config_check_init(repo);
2582 ret = git_configset_get_string(repo->config, key, dest);
2583 if (ret < 0)
2584 git_die_config(repo, key, NULL);
2585 return ret;
2588 int repo_config_get_string_tmp(struct repository *repo,
2589 const char *key, const char **dest)
2591 int ret;
2592 git_config_check_init(repo);
2593 ret = git_configset_get_string_tmp(repo->config, key, dest);
2594 if (ret < 0)
2595 git_die_config(repo, key, NULL);
2596 return ret;
2599 int repo_config_get_int(struct repository *repo,
2600 const char *key, int *dest)
2602 git_config_check_init(repo);
2603 return git_configset_get_int(repo->config, key, dest);
2606 int repo_config_get_ulong(struct repository *repo,
2607 const char *key, unsigned long *dest)
2609 git_config_check_init(repo);
2610 return git_configset_get_ulong(repo->config, key, dest);
2613 int repo_config_get_bool(struct repository *repo,
2614 const char *key, int *dest)
2616 git_config_check_init(repo);
2617 return git_configset_get_bool(repo->config, key, dest);
2620 int repo_config_get_bool_or_int(struct repository *repo,
2621 const char *key, int *is_bool, int *dest)
2623 git_config_check_init(repo);
2624 return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2627 int repo_config_get_maybe_bool(struct repository *repo,
2628 const char *key, int *dest)
2630 git_config_check_init(repo);
2631 return git_configset_get_maybe_bool(repo->config, key, dest);
2634 int repo_config_get_pathname(struct repository *repo,
2635 const char *key, char **dest)
2637 int ret;
2638 git_config_check_init(repo);
2639 ret = git_configset_get_pathname(repo->config, key, dest);
2640 if (ret < 0)
2641 git_die_config(repo, key, NULL);
2642 return ret;
2645 /* Read values into protected_config. */
2646 static void read_protected_config(void)
2648 struct config_options opts = {
2649 .respect_includes = 1,
2650 .ignore_repo = 1,
2651 .ignore_worktree = 1,
2652 .system_gently = 1,
2655 git_configset_init(&protected_config);
2656 config_with_options(config_set_callback, &protected_config, NULL,
2657 NULL, &opts);
2660 void git_protected_config(config_fn_t fn, void *data)
2662 if (!protected_config.hash_initialized)
2663 read_protected_config();
2664 configset_iter(&protected_config, fn, data);
2667 int repo_config_get_expiry(struct repository *r, const char *key, char **output)
2669 int ret = repo_config_get_string(r, key, output);
2671 if (ret)
2672 return ret;
2673 if (strcmp(*output, "now")) {
2674 timestamp_t now = approxidate("now");
2675 if (approxidate(*output) >= now)
2676 git_die_config(r, key, _("Invalid %s: '%s'"), key, *output);
2678 return ret;
2681 int repo_config_get_expiry_in_days(struct repository *r, const char *key,
2682 timestamp_t *expiry, timestamp_t now)
2684 const char *expiry_string;
2685 intmax_t days;
2686 timestamp_t when;
2688 if (repo_config_get_string_tmp(r, key, &expiry_string))
2689 return 1; /* no such thing */
2691 if (git_parse_signed(expiry_string, &days, maximum_signed_value_of_type(int))) {
2692 const int scale = 86400;
2693 *expiry = now - days * scale;
2694 return 0;
2697 if (!parse_expiry_date(expiry_string, &when)) {
2698 *expiry = when;
2699 return 0;
2701 return -1; /* thing exists but cannot be parsed */
2704 int repo_config_get_split_index(struct repository *r)
2706 int val;
2708 if (!repo_config_get_maybe_bool(r, "core.splitindex", &val))
2709 return val;
2711 return -1; /* default value */
2714 int repo_config_get_max_percent_split_change(struct repository *r)
2716 int val = -1;
2718 if (!repo_config_get_int(r, "splitindex.maxpercentchange", &val)) {
2719 if (0 <= val && val <= 100)
2720 return val;
2722 return error(_("splitIndex.maxPercentChange value '%d' "
2723 "should be between 0 and 100"), val);
2726 return -1; /* default value */
2729 int repo_config_get_index_threads(struct repository *r, int *dest)
2731 int is_bool, val;
2733 val = git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2734 if (val) {
2735 *dest = val;
2736 return 0;
2739 if (!repo_config_get_bool_or_int(r, "index.threads", &is_bool, &val)) {
2740 if (is_bool)
2741 *dest = val ? 0 : 1;
2742 else
2743 *dest = val;
2744 return 0;
2747 return 1;
2750 NORETURN
2751 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2753 if (!filename)
2754 die(_("unable to parse '%s' from command-line config"), key);
2755 else
2756 die(_("bad config variable '%s' in file '%s' at line %d"),
2757 key, filename, linenr);
2760 void git_die_config(struct repository *r, const char *key, const char *err, ...)
2762 const struct string_list *values;
2763 struct key_value_info *kv_info;
2764 report_fn error_fn = get_error_routine();
2766 if (err) {
2767 va_list params;
2768 va_start(params, err);
2769 error_fn(err, params);
2770 va_end(params);
2772 if (repo_config_get_value_multi(r, key, &values))
2773 BUG("for key '%s' we must have a value to report on", key);
2774 kv_info = values->items[values->nr - 1].util;
2775 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
2779 * Find all the stuff for git_config_set() below.
2782 struct config_store_data {
2783 size_t baselen;
2784 char *key;
2785 int do_not_match;
2786 const char *fixed_value;
2787 regex_t *value_pattern;
2788 int multi_replace;
2789 struct {
2790 size_t begin, end;
2791 enum config_event_t type;
2792 int is_keys_section;
2793 } *parsed;
2794 unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
2795 unsigned int key_seen:1, section_seen:1, is_keys_section:1;
2797 #define CONFIG_STORE_INIT { 0 }
2799 static void config_store_data_clear(struct config_store_data *store)
2801 free(store->key);
2802 if (store->value_pattern != NULL &&
2803 store->value_pattern != CONFIG_REGEX_NONE) {
2804 regfree(store->value_pattern);
2805 free(store->value_pattern);
2807 free(store->parsed);
2808 free(store->seen);
2809 memset(store, 0, sizeof(*store));
2812 static int matches(const char *key, const char *value,
2813 const struct config_store_data *store)
2815 if (strcmp(key, store->key))
2816 return 0; /* not ours */
2817 if (store->fixed_value && value)
2818 return !strcmp(store->fixed_value, value);
2819 if (!store->value_pattern)
2820 return 1; /* always matches */
2821 if (store->value_pattern == CONFIG_REGEX_NONE)
2822 return 0; /* never matches */
2824 return store->do_not_match ^
2825 (value && !regexec(store->value_pattern, value, 0, NULL, 0));
2828 static int store_aux_event(enum config_event_t type, size_t begin, size_t end,
2829 struct config_source *cs, void *data)
2831 struct config_store_data *store = data;
2833 ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
2834 store->parsed[store->parsed_nr].begin = begin;
2835 store->parsed[store->parsed_nr].end = end;
2836 store->parsed[store->parsed_nr].type = type;
2838 if (type == CONFIG_EVENT_SECTION) {
2839 int (*cmpfn)(const char *, const char *, size_t);
2841 if (cs->var.len < 2 || cs->var.buf[cs->var.len - 1] != '.')
2842 return error(_("invalid section name '%s'"), cs->var.buf);
2844 if (cs->subsection_case_sensitive)
2845 cmpfn = strncasecmp;
2846 else
2847 cmpfn = strncmp;
2849 /* Is this the section we were looking for? */
2850 store->is_keys_section =
2851 store->parsed[store->parsed_nr].is_keys_section =
2852 cs->var.len - 1 == store->baselen &&
2853 !cmpfn(cs->var.buf, store->key, store->baselen);
2854 if (store->is_keys_section) {
2855 store->section_seen = 1;
2856 ALLOC_GROW(store->seen, store->seen_nr + 1,
2857 store->seen_alloc);
2858 store->seen[store->seen_nr] = store->parsed_nr;
2862 store->parsed_nr++;
2864 return 0;
2867 static int store_aux(const char *key, const char *value,
2868 const struct config_context *ctx UNUSED, void *cb)
2870 struct config_store_data *store = cb;
2872 if (store->key_seen) {
2873 if (matches(key, value, store)) {
2874 if (store->seen_nr == 1 && store->multi_replace == 0) {
2875 warning(_("%s has multiple values"), key);
2878 ALLOC_GROW(store->seen, store->seen_nr + 1,
2879 store->seen_alloc);
2881 store->seen[store->seen_nr] = store->parsed_nr;
2882 store->seen_nr++;
2884 } else if (store->is_keys_section) {
2886 * Do not increment matches yet: this may not be a match, but we
2887 * are in the desired section.
2889 ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
2890 store->seen[store->seen_nr] = store->parsed_nr;
2891 store->section_seen = 1;
2893 if (matches(key, value, store)) {
2894 store->seen_nr++;
2895 store->key_seen = 1;
2899 return 0;
2902 static int write_error(const char *filename)
2904 error(_("failed to write new configuration file %s"), filename);
2906 /* Same error code as "failed to rename". */
2907 return 4;
2910 static struct strbuf store_create_section(const char *key,
2911 const struct config_store_data *store)
2913 const char *dot;
2914 size_t i;
2915 struct strbuf sb = STRBUF_INIT;
2917 dot = memchr(key, '.', store->baselen);
2918 if (dot) {
2919 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
2920 for (i = dot - key + 1; i < store->baselen; i++) {
2921 if (key[i] == '"' || key[i] == '\\')
2922 strbuf_addch(&sb, '\\');
2923 strbuf_addch(&sb, key[i]);
2925 strbuf_addstr(&sb, "\"]\n");
2926 } else {
2927 strbuf_addch(&sb, '[');
2928 strbuf_add(&sb, key, store->baselen);
2929 strbuf_addstr(&sb, "]\n");
2932 return sb;
2935 static ssize_t write_section(int fd, const char *key,
2936 const struct config_store_data *store)
2938 struct strbuf sb = store_create_section(key, store);
2939 ssize_t ret;
2941 ret = write_in_full(fd, sb.buf, sb.len);
2942 strbuf_release(&sb);
2944 return ret;
2947 static ssize_t write_pair(int fd, const char *key, const char *value,
2948 const char *comment,
2949 const struct config_store_data *store)
2951 int i;
2952 ssize_t ret;
2953 const char *quote = "";
2954 struct strbuf sb = STRBUF_INIT;
2957 * Check to see if the value needs to be surrounded with a dq pair.
2958 * Note that problematic characters are always backslash-quoted; this
2959 * check is about not losing leading or trailing SP and strings that
2960 * follow beginning-of-comment characters (i.e. ';' and '#') by the
2961 * configuration parser.
2963 if (value[0] == ' ')
2964 quote = "\"";
2965 for (i = 0; value[i]; i++)
2966 if (value[i] == ';' || value[i] == '#')
2967 quote = "\"";
2968 if (i && value[i - 1] == ' ')
2969 quote = "\"";
2971 strbuf_addf(&sb, "\t%s = %s", key + store->baselen + 1, quote);
2973 for (i = 0; value[i]; i++)
2974 switch (value[i]) {
2975 case '\n':
2976 strbuf_addstr(&sb, "\\n");
2977 break;
2978 case '\t':
2979 strbuf_addstr(&sb, "\\t");
2980 break;
2981 case '"':
2982 case '\\':
2983 strbuf_addch(&sb, '\\');
2984 /* fallthrough */
2985 default:
2986 strbuf_addch(&sb, value[i]);
2987 break;
2990 if (comment)
2991 strbuf_addf(&sb, "%s%s\n", quote, comment);
2992 else
2993 strbuf_addf(&sb, "%s\n", quote);
2995 ret = write_in_full(fd, sb.buf, sb.len);
2996 strbuf_release(&sb);
2998 return ret;
3002 * If we are about to unset the last key(s) in a section, and if there are
3003 * no comments surrounding (or included in) the section, we will want to
3004 * extend begin/end to remove the entire section.
3006 * Note: the parameter `seen_ptr` points to the index into the store.seen
3007 * array. * This index may be incremented if a section has more than one
3008 * entry (which all are to be removed).
3010 static void maybe_remove_section(struct config_store_data *store,
3011 size_t *begin_offset, size_t *end_offset,
3012 int *seen_ptr)
3014 size_t begin;
3015 int i, seen, section_seen = 0;
3018 * First, ensure that this is the first key, and that there are no
3019 * comments before the entry nor before the section header.
3021 seen = *seen_ptr;
3022 for (i = store->seen[seen]; i > 0; i--) {
3023 enum config_event_t type = store->parsed[i - 1].type;
3025 if (type == CONFIG_EVENT_COMMENT)
3026 /* There is a comment before this entry or section */
3027 return;
3028 if (type == CONFIG_EVENT_ENTRY) {
3029 if (!section_seen)
3030 /* This is not the section's first entry. */
3031 return;
3032 /* We encountered no comment before the section. */
3033 break;
3035 if (type == CONFIG_EVENT_SECTION) {
3036 if (!store->parsed[i - 1].is_keys_section)
3037 break;
3038 section_seen = 1;
3041 begin = store->parsed[i].begin;
3044 * Next, make sure that we are removing the last key(s) in the section,
3045 * and that there are no comments that are possibly about the current
3046 * section.
3048 for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
3049 enum config_event_t type = store->parsed[i].type;
3051 if (type == CONFIG_EVENT_COMMENT)
3052 return;
3053 if (type == CONFIG_EVENT_SECTION) {
3054 if (store->parsed[i].is_keys_section)
3055 continue;
3056 break;
3058 if (type == CONFIG_EVENT_ENTRY) {
3059 if (++seen < store->seen_nr &&
3060 i == store->seen[seen])
3061 /* We want to remove this entry, too */
3062 continue;
3063 /* There is another entry in this section. */
3064 return;
3069 * We are really removing the last entry/entries from this section, and
3070 * there are no enclosed or surrounding comments. Remove the entire,
3071 * now-empty section.
3073 *seen_ptr = seen;
3074 *begin_offset = begin;
3075 if (i < store->parsed_nr)
3076 *end_offset = store->parsed[i].begin;
3077 else
3078 *end_offset = store->parsed[store->parsed_nr - 1].end;
3081 int repo_config_set_in_file_gently(struct repository *r, const char *config_filename,
3082 const char *key, const char *comment, const char *value)
3084 return repo_config_set_multivar_in_file_gently(r, config_filename, key, value, NULL, comment, 0);
3087 void repo_config_set_in_file(struct repository *r, const char *config_filename,
3088 const char *key, const char *value)
3090 repo_config_set_multivar_in_file(r, config_filename, key, value, NULL, 0);
3093 int repo_config_set_gently(struct repository *r, const char *key, const char *value)
3095 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
3098 int repo_config_set_worktree_gently(struct repository *r,
3099 const char *key, const char *value)
3101 /* Only use worktree-specific config if it is already enabled. */
3102 if (r->repository_format_worktree_config) {
3103 char *file = repo_git_path(r, "config.worktree");
3104 int ret = repo_config_set_multivar_in_file_gently(
3105 r, file, key, value, NULL, NULL, 0);
3106 free(file);
3107 return ret;
3109 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
3112 void repo_config_set(struct repository *r, const char *key, const char *value)
3114 repo_config_set_multivar(r, key, value, NULL, 0);
3116 trace2_cmd_set_config(key, value);
3119 char *git_config_prepare_comment_string(const char *comment)
3121 size_t leading_blanks;
3122 char *prepared;
3124 if (!comment)
3125 return NULL;
3127 if (strchr(comment, '\n'))
3128 die(_("no multi-line comment allowed: '%s'"), comment);
3131 * If it begins with one or more leading whitespace characters
3132 * followed by '#", the comment string is used as-is.
3134 * If it begins with '#', a SP is inserted between the comment
3135 * and the value the comment is about.
3137 * Otherwise, the value is followed by a SP followed by '#'
3138 * followed by SP and then the comment string comes.
3141 leading_blanks = strspn(comment, " \t");
3142 if (leading_blanks && comment[leading_blanks] == '#')
3143 prepared = xstrdup(comment); /* use it as-is */
3144 else if (comment[0] == '#')
3145 prepared = xstrfmt(" %s", comment);
3146 else
3147 prepared = xstrfmt(" # %s", comment);
3149 return prepared;
3152 static void validate_comment_string(const char *comment)
3154 size_t leading_blanks;
3156 if (!comment)
3157 return;
3159 * The front-end must have massaged the comment string
3160 * properly before calling us.
3162 if (strchr(comment, '\n'))
3163 BUG("multi-line comments are not permitted: '%s'", comment);
3165 leading_blanks = strspn(comment, " \t");
3166 if (!leading_blanks || comment[leading_blanks] != '#')
3167 BUG("comment must begin with one or more SP followed by '#': '%s'",
3168 comment);
3172 * If value==NULL, unset in (remove from) config,
3173 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
3174 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
3175 * (only add a new one)
3176 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3177 * key/values are removed before a single new pair is written. If the
3178 * flag is not present, then replace only the first match.
3180 * Returns 0 on success.
3182 * This function does this:
3184 * - it locks the config file by creating ".git/config.lock"
3186 * - it then parses the config using store_aux() as validator to find
3187 * the position on the key/value pair to replace. If it is to be unset,
3188 * it must be found exactly once.
3190 * - the config file is mmap()ed and the part before the match (if any) is
3191 * written to the lock file, then the changed part and the rest.
3193 * - the config file is removed and the lock file rename()d to it.
3196 int repo_config_set_multivar_in_file_gently(struct repository *r,
3197 const char *config_filename,
3198 const char *key, const char *value,
3199 const char *value_pattern,
3200 const char *comment,
3201 unsigned flags)
3203 int fd = -1, in_fd = -1;
3204 int ret;
3205 struct lock_file lock = LOCK_INIT;
3206 char *filename_buf = NULL;
3207 char *contents = NULL;
3208 size_t contents_sz;
3209 struct config_store_data store = CONFIG_STORE_INIT;
3211 validate_comment_string(comment);
3213 /* parse-key returns negative; flip the sign to feed exit(3) */
3214 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
3215 if (ret)
3216 goto out_free;
3218 store.multi_replace = (flags & CONFIG_FLAGS_MULTI_REPLACE) != 0;
3220 if (!config_filename)
3221 config_filename = filename_buf = repo_git_path(r, "config");
3224 * The lock serves a purpose in addition to locking: the new
3225 * contents of .git/config will be written into it.
3227 fd = hold_lock_file_for_update(&lock, config_filename, 0);
3228 if (fd < 0) {
3229 error_errno(_("could not lock config file %s"), config_filename);
3230 ret = CONFIG_NO_LOCK;
3231 goto out_free;
3235 * If .git/config does not exist yet, write a minimal version.
3237 in_fd = open(config_filename, O_RDONLY);
3238 if ( in_fd < 0 ) {
3239 if ( ENOENT != errno ) {
3240 error_errno(_("opening %s"), config_filename);
3241 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
3242 goto out_free;
3244 /* if nothing to unset, error out */
3245 if (!value) {
3246 ret = CONFIG_NOTHING_SET;
3247 goto out_free;
3250 free(store.key);
3251 store.key = xstrdup(key);
3252 if (write_section(fd, key, &store) < 0 ||
3253 write_pair(fd, key, value, comment, &store) < 0)
3254 goto write_err_out;
3255 } else {
3256 struct stat st;
3257 size_t copy_begin, copy_end;
3258 int i, new_line = 0;
3259 struct config_options opts;
3261 if (!value_pattern)
3262 store.value_pattern = NULL;
3263 else if (value_pattern == CONFIG_REGEX_NONE)
3264 store.value_pattern = CONFIG_REGEX_NONE;
3265 else if (flags & CONFIG_FLAGS_FIXED_VALUE)
3266 store.fixed_value = value_pattern;
3267 else {
3268 if (value_pattern[0] == '!') {
3269 store.do_not_match = 1;
3270 value_pattern++;
3271 } else
3272 store.do_not_match = 0;
3274 store.value_pattern = (regex_t*)xmalloc(sizeof(regex_t));
3275 if (regcomp(store.value_pattern, value_pattern,
3276 REG_EXTENDED)) {
3277 error(_("invalid pattern: %s"), value_pattern);
3278 FREE_AND_NULL(store.value_pattern);
3279 ret = CONFIG_INVALID_PATTERN;
3280 goto out_free;
3284 ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
3285 store.parsed[0].end = 0;
3287 memset(&opts, 0, sizeof(opts));
3288 opts.event_fn = store_aux_event;
3289 opts.event_fn_data = &store;
3292 * After this, store.parsed will contain offsets of all the
3293 * parsed elements, and store.seen will contain a list of
3294 * matches, as indices into store.parsed.
3296 * As a side effect, we make sure to transform only a valid
3297 * existing config file.
3299 if (git_config_from_file_with_options(store_aux,
3300 config_filename,
3301 &store, CONFIG_SCOPE_UNKNOWN,
3302 &opts)) {
3303 error(_("invalid config file %s"), config_filename);
3304 ret = CONFIG_INVALID_FILE;
3305 goto out_free;
3308 /* if nothing to unset, or too many matches, error out */
3309 if ((store.seen_nr == 0 && value == NULL) ||
3310 (store.seen_nr > 1 && !store.multi_replace)) {
3311 ret = CONFIG_NOTHING_SET;
3312 goto out_free;
3315 if (fstat(in_fd, &st) == -1) {
3316 error_errno(_("fstat on %s failed"), config_filename);
3317 ret = CONFIG_INVALID_FILE;
3318 goto out_free;
3321 contents_sz = xsize_t(st.st_size);
3322 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
3323 MAP_PRIVATE, in_fd, 0);
3324 if (contents == MAP_FAILED) {
3325 if (errno == ENODEV && S_ISDIR(st.st_mode))
3326 errno = EISDIR;
3327 error_errno(_("unable to mmap '%s'%s"),
3328 config_filename, mmap_os_err());
3329 ret = CONFIG_INVALID_FILE;
3330 contents = NULL;
3331 goto out_free;
3333 close(in_fd);
3334 in_fd = -1;
3336 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3337 error_errno(_("chmod on %s failed"), get_lock_file_path(&lock));
3338 ret = CONFIG_NO_WRITE;
3339 goto out_free;
3342 if (store.seen_nr == 0) {
3343 if (!store.seen_alloc) {
3344 /* Did not see key nor section */
3345 ALLOC_GROW(store.seen, 1, store.seen_alloc);
3346 store.seen[0] = store.parsed_nr
3347 - !!store.parsed_nr;
3349 store.seen_nr = 1;
3352 for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
3353 size_t replace_end;
3354 int j = store.seen[i];
3356 new_line = 0;
3357 if (!store.key_seen) {
3358 copy_end = store.parsed[j].end;
3359 /* include '\n' when copying section header */
3360 if (copy_end > 0 && copy_end < contents_sz &&
3361 contents[copy_end - 1] != '\n' &&
3362 contents[copy_end] == '\n')
3363 copy_end++;
3364 replace_end = copy_end;
3365 } else {
3366 replace_end = store.parsed[j].end;
3367 copy_end = store.parsed[j].begin;
3368 if (!value)
3369 maybe_remove_section(&store,
3370 &copy_end,
3371 &replace_end, &i);
3373 * Swallow preceding white-space on the same
3374 * line.
3376 while (copy_end > 0 ) {
3377 char c = contents[copy_end - 1];
3379 if (isspace(c) && c != '\n')
3380 copy_end--;
3381 else
3382 break;
3386 if (copy_end > 0 && contents[copy_end-1] != '\n')
3387 new_line = 1;
3389 /* write the first part of the config */
3390 if (copy_end > copy_begin) {
3391 if (write_in_full(fd, contents + copy_begin,
3392 copy_end - copy_begin) < 0)
3393 goto write_err_out;
3394 if (new_line &&
3395 write_str_in_full(fd, "\n") < 0)
3396 goto write_err_out;
3398 copy_begin = replace_end;
3401 /* write the pair (value == NULL means unset) */
3402 if (value) {
3403 if (!store.section_seen) {
3404 if (write_section(fd, key, &store) < 0)
3405 goto write_err_out;
3407 if (write_pair(fd, key, value, comment, &store) < 0)
3408 goto write_err_out;
3411 /* write the rest of the config */
3412 if (copy_begin < contents_sz)
3413 if (write_in_full(fd, contents + copy_begin,
3414 contents_sz - copy_begin) < 0)
3415 goto write_err_out;
3417 munmap(contents, contents_sz);
3418 contents = NULL;
3421 if (commit_lock_file(&lock) < 0) {
3422 error_errno(_("could not write config file %s"), config_filename);
3423 ret = CONFIG_NO_WRITE;
3424 goto out_free;
3427 ret = 0;
3429 /* Invalidate the config cache */
3430 repo_config_clear(r);
3432 out_free:
3433 rollback_lock_file(&lock);
3434 free(filename_buf);
3435 if (contents)
3436 munmap(contents, contents_sz);
3437 if (in_fd >= 0)
3438 close(in_fd);
3439 config_store_data_clear(&store);
3440 return ret;
3442 write_err_out:
3443 ret = write_error(get_lock_file_path(&lock));
3444 goto out_free;
3447 void repo_config_set_multivar_in_file(struct repository *r,
3448 const char *config_filename,
3449 const char *key, const char *value,
3450 const char *value_pattern, unsigned flags)
3452 if (!repo_config_set_multivar_in_file_gently(r, config_filename, key, value,
3453 value_pattern, NULL, flags))
3454 return;
3455 if (value)
3456 die(_("could not set '%s' to '%s'"), key, value);
3457 else
3458 die(_("could not unset '%s'"), key);
3461 int repo_config_set_multivar_gently(struct repository *r, const char *key,
3462 const char *value,
3463 const char *value_pattern, unsigned flags)
3465 char *file = repo_git_path(r, "config");
3466 int res = repo_config_set_multivar_in_file_gently(r, file,
3467 key, value,
3468 value_pattern,
3469 NULL, flags);
3470 free(file);
3471 return res;
3474 void repo_config_set_multivar(struct repository *r,
3475 const char *key, const char *value,
3476 const char *value_pattern, unsigned flags)
3478 char *file = repo_git_path(r, "config");
3479 repo_config_set_multivar_in_file(r, file, key, value,
3480 value_pattern, flags);
3481 free(file);
3484 static size_t section_name_match (const char *buf, const char *name)
3486 size_t i = 0, j = 0;
3487 int dot = 0;
3488 if (buf[i] != '[')
3489 return 0;
3490 for (i = 1; buf[i] && buf[i] != ']'; i++) {
3491 if (!dot && isspace(buf[i])) {
3492 dot = 1;
3493 if (name[j++] != '.')
3494 break;
3495 for (i++; isspace(buf[i]); i++)
3496 ; /* do nothing */
3497 if (buf[i] != '"')
3498 break;
3499 continue;
3501 if (buf[i] == '\\' && dot)
3502 i++;
3503 else if (buf[i] == '"' && dot) {
3504 for (i++; isspace(buf[i]); i++)
3505 ; /* do_nothing */
3506 break;
3508 if (buf[i] != name[j++])
3509 break;
3511 if (buf[i] == ']' && name[j] == 0) {
3513 * We match, now just find the right length offset by
3514 * gobbling up any whitespace after it, as well
3516 i++;
3517 for (; buf[i] && isspace(buf[i]); i++)
3518 ; /* do nothing */
3519 return i;
3521 return 0;
3524 static int section_name_is_ok(const char *name)
3526 /* Empty section names are bogus. */
3527 if (!*name)
3528 return 0;
3531 * Before a dot, we must be alphanumeric or dash. After the first dot,
3532 * anything goes, so we can stop checking.
3534 for (; *name && *name != '.'; name++)
3535 if (*name != '-' && !isalnum(*name))
3536 return 0;
3537 return 1;
3540 #define GIT_CONFIG_MAX_LINE_LEN (512 * 1024)
3542 /* if new_name == NULL, the section is removed instead */
3543 static int repo_config_copy_or_rename_section_in_file(
3544 struct repository *r,
3545 const char *config_filename,
3546 const char *old_name,
3547 const char *new_name, int copy)
3549 int ret = 0, remove = 0;
3550 char *filename_buf = NULL;
3551 struct lock_file lock = LOCK_INIT;
3552 int out_fd;
3553 struct strbuf buf = STRBUF_INIT;
3554 FILE *config_file = NULL;
3555 struct stat st;
3556 struct strbuf copystr = STRBUF_INIT;
3557 struct config_store_data store;
3558 uint32_t line_nr = 0;
3560 memset(&store, 0, sizeof(store));
3562 if (new_name && !section_name_is_ok(new_name)) {
3563 ret = error(_("invalid section name: %s"), new_name);
3564 goto out_no_rollback;
3567 if (!config_filename)
3568 config_filename = filename_buf = repo_git_path(r, "config");
3570 out_fd = hold_lock_file_for_update(&lock, config_filename, 0);
3571 if (out_fd < 0) {
3572 ret = error(_("could not lock config file %s"), config_filename);
3573 goto out;
3576 if (!(config_file = fopen(config_filename, "rb"))) {
3577 ret = warn_on_fopen_errors(config_filename);
3578 if (ret)
3579 goto out;
3580 /* no config file means nothing to rename, no error */
3581 goto commit_and_out;
3584 if (fstat(fileno(config_file), &st) == -1) {
3585 ret = error_errno(_("fstat on %s failed"), config_filename);
3586 goto out;
3589 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3590 ret = error_errno(_("chmod on %s failed"),
3591 get_lock_file_path(&lock));
3592 goto out;
3595 while (!strbuf_getwholeline(&buf, config_file, '\n')) {
3596 size_t i, length;
3597 int is_section = 0;
3598 char *output = buf.buf;
3600 line_nr++;
3602 if (buf.len >= GIT_CONFIG_MAX_LINE_LEN) {
3603 ret = error(_("refusing to work with overly long line "
3604 "in '%s' on line %"PRIuMAX),
3605 config_filename, (uintmax_t)line_nr);
3606 goto out;
3609 for (i = 0; buf.buf[i] && isspace(buf.buf[i]); i++)
3610 ; /* do nothing */
3611 if (buf.buf[i] == '[') {
3612 /* it's a section */
3613 size_t offset;
3614 is_section = 1;
3617 * When encountering a new section under -c we
3618 * need to flush out any section we're already
3619 * coping and begin anew. There might be
3620 * multiple [branch "$name"] sections.
3622 if (copystr.len > 0) {
3623 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3624 ret = write_error(get_lock_file_path(&lock));
3625 goto out;
3627 strbuf_reset(&copystr);
3630 offset = section_name_match(&buf.buf[i], old_name);
3631 if (offset > 0) {
3632 ret++;
3633 if (!new_name) {
3634 remove = 1;
3635 continue;
3637 store.baselen = strlen(new_name);
3638 if (!copy) {
3639 if (write_section(out_fd, new_name, &store) < 0) {
3640 ret = write_error(get_lock_file_path(&lock));
3641 goto out;
3644 * We wrote out the new section, with
3645 * a newline, now skip the old
3646 * section's length
3648 output += offset + i;
3649 if (strlen(output) > 0) {
3651 * More content means there's
3652 * a declaration to put on the
3653 * next line; indent with a
3654 * tab
3656 output -= 1;
3657 output[0] = '\t';
3659 } else {
3660 strbuf_release(&copystr);
3661 copystr = store_create_section(new_name, &store);
3664 remove = 0;
3666 if (remove)
3667 continue;
3668 length = strlen(output);
3670 if (!is_section && copystr.len > 0) {
3671 strbuf_add(&copystr, output, length);
3674 if (write_in_full(out_fd, output, length) < 0) {
3675 ret = write_error(get_lock_file_path(&lock));
3676 goto out;
3681 * Copy a trailing section at the end of the config, won't be
3682 * flushed by the usual "flush because we have a new section
3683 * logic in the loop above.
3685 if (copystr.len > 0) {
3686 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3687 ret = write_error(get_lock_file_path(&lock));
3688 goto out;
3690 strbuf_reset(&copystr);
3693 fclose(config_file);
3694 config_file = NULL;
3695 commit_and_out:
3696 if (commit_lock_file(&lock) < 0)
3697 ret = error_errno(_("could not write config file %s"),
3698 config_filename);
3699 out:
3700 if (config_file)
3701 fclose(config_file);
3702 rollback_lock_file(&lock);
3703 out_no_rollback:
3704 free(filename_buf);
3705 config_store_data_clear(&store);
3706 strbuf_release(&buf);
3707 strbuf_release(&copystr);
3708 return ret;
3711 int repo_config_rename_section_in_file(struct repository *r, const char *config_filename,
3712 const char *old_name, const char *new_name)
3714 return repo_config_copy_or_rename_section_in_file(r, config_filename,
3715 old_name, new_name, 0);
3718 int repo_config_rename_section(struct repository *r, const char *old_name, const char *new_name)
3720 return repo_config_rename_section_in_file(r, NULL, old_name, new_name);
3723 int repo_config_copy_section_in_file(struct repository *r, const char *config_filename,
3724 const char *old_name, const char *new_name)
3726 return repo_config_copy_or_rename_section_in_file(r, config_filename,
3727 old_name, new_name, 1);
3730 int repo_config_copy_section(struct repository *r, const char *old_name, const char *new_name)
3732 return repo_config_copy_section_in_file(r, NULL, old_name, new_name);
3736 * Call this to report error for your variable that should not
3737 * get a boolean value (i.e. "[my] var" means "true").
3739 #undef config_error_nonbool
3740 int config_error_nonbool(const char *var)
3742 return error(_("missing value for '%s'"), var);
3745 int parse_config_key(const char *var,
3746 const char *section,
3747 const char **subsection, size_t *subsection_len,
3748 const char **key)
3750 const char *dot;
3752 /* Does it start with "section." ? */
3753 if (!skip_prefix(var, section, &var) || *var != '.')
3754 return -1;
3757 * Find the key; we don't know yet if we have a subsection, but we must
3758 * parse backwards from the end, since the subsection may have dots in
3759 * it, too.
3761 dot = strrchr(var, '.');
3762 *key = dot + 1;
3764 /* Did we have a subsection at all? */
3765 if (dot == var) {
3766 if (subsection) {
3767 *subsection = NULL;
3768 *subsection_len = 0;
3771 else {
3772 if (!subsection)
3773 return -1;
3774 *subsection = var + 1;
3775 *subsection_len = dot - *subsection;
3778 return 0;
3781 const char *config_origin_type_name(enum config_origin_type type)
3783 switch (type) {
3784 case CONFIG_ORIGIN_BLOB:
3785 return "blob";
3786 case CONFIG_ORIGIN_FILE:
3787 return "file";
3788 case CONFIG_ORIGIN_STDIN:
3789 return "standard input";
3790 case CONFIG_ORIGIN_SUBMODULE_BLOB:
3791 return "submodule-blob";
3792 case CONFIG_ORIGIN_CMDLINE:
3793 return "command line";
3794 default:
3795 BUG("unknown config origin type");
3799 const char *config_scope_name(enum config_scope scope)
3801 switch (scope) {
3802 case CONFIG_SCOPE_SYSTEM:
3803 return "system";
3804 case CONFIG_SCOPE_GLOBAL:
3805 return "global";
3806 case CONFIG_SCOPE_LOCAL:
3807 return "local";
3808 case CONFIG_SCOPE_WORKTREE:
3809 return "worktree";
3810 case CONFIG_SCOPE_COMMAND:
3811 return "command";
3812 case CONFIG_SCOPE_SUBMODULE:
3813 return "submodule";
3814 default:
3815 return "unknown";
3819 int lookup_config(const char **mapping, int nr_mapping, const char *var)
3821 int i;
3823 for (i = 0; i < nr_mapping; i++) {
3824 const char *name = mapping[i];
3826 if (name && !strcasecmp(var, name))
3827 return i;
3829 return -1;