Merge branch 'en/header-cleanup'
[git/debian.git] / config.c
blobd0aff55fa66b7f57f29a958092ce898034547ec3
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 * Copyright (C) Johannes Schindelin, 2005
7 */
8 #include "git-compat-util.h"
9 #include "alloc.h"
10 #include "date.h"
11 #include "branch.h"
12 #include "config.h"
13 #include "environment.h"
14 #include "ident.h"
15 #include "repository.h"
16 #include "lockfile.h"
17 #include "exec-cmd.h"
18 #include "strbuf.h"
19 #include "quote.h"
20 #include "hashmap.h"
21 #include "string-list.h"
22 #include "object-store.h"
23 #include "utf8.h"
24 #include "dir.h"
25 #include "color.h"
26 #include "replace-object.h"
27 #include "refs.h"
28 #include "worktree.h"
30 struct config_source {
31 struct config_source *prev;
32 union {
33 FILE *file;
34 struct config_buf {
35 const char *buf;
36 size_t len;
37 size_t pos;
38 } buf;
39 } u;
40 enum config_origin_type origin_type;
41 const char *name;
42 const char *path;
43 enum config_error_action default_error_action;
44 int linenr;
45 int eof;
46 size_t total_len;
47 struct strbuf value;
48 struct strbuf var;
49 unsigned subsection_case_sensitive : 1;
51 int (*do_fgetc)(struct config_source *c);
52 int (*do_ungetc)(int c, struct config_source *conf);
53 long (*do_ftell)(struct config_source *c);
57 * These variables record the "current" config source, which
58 * can be accessed by parsing callbacks.
60 * The "cf" variable will be non-NULL only when we are actually parsing a real
61 * config source (file, blob, cmdline, etc).
63 * The "current_config_kvi" variable will be non-NULL only when we are feeding
64 * cached config from a configset into a callback.
66 * They should generally never be non-NULL at the same time. If they are both
67 * NULL, then we aren't parsing anything (and depending on the function looking
68 * at the variables, it's either a bug for it to be called in the first place,
69 * or it's a function which can be reused for non-config purposes, and should
70 * fall back to some sane behavior).
72 static struct config_source *cf;
73 static struct key_value_info *current_config_kvi;
76 * Similar to the variables above, this gives access to the "scope" of the
77 * current value (repo, global, etc). For cached values, it can be found via
78 * the current_config_kvi as above. During parsing, the current value can be
79 * found in this variable. It's not part of "cf" because it transcends a single
80 * file (i.e., a file included from .git/config is still in "repo" scope).
82 static enum config_scope current_parsing_scope;
84 static int pack_compression_seen;
85 static int zlib_compression_seen;
88 * Config that comes from trusted scopes, namely:
89 * - CONFIG_SCOPE_SYSTEM (e.g. /etc/gitconfig)
90 * - CONFIG_SCOPE_GLOBAL (e.g. $HOME/.gitconfig, $XDG_CONFIG_HOME/git)
91 * - CONFIG_SCOPE_COMMAND (e.g. "-c" option, environment variables)
93 * This is declared here for code cleanliness, but unlike the other
94 * static variables, this does not hold config parser state.
96 static struct config_set protected_config;
98 static int config_file_fgetc(struct config_source *conf)
100 return getc_unlocked(conf->u.file);
103 static int config_file_ungetc(int c, struct config_source *conf)
105 return ungetc(c, conf->u.file);
108 static long config_file_ftell(struct config_source *conf)
110 return ftell(conf->u.file);
114 static int config_buf_fgetc(struct config_source *conf)
116 if (conf->u.buf.pos < conf->u.buf.len)
117 return conf->u.buf.buf[conf->u.buf.pos++];
119 return EOF;
122 static int config_buf_ungetc(int c, struct config_source *conf)
124 if (conf->u.buf.pos > 0) {
125 conf->u.buf.pos--;
126 if (conf->u.buf.buf[conf->u.buf.pos] != c)
127 BUG("config_buf can only ungetc the same character");
128 return c;
131 return EOF;
134 static long config_buf_ftell(struct config_source *conf)
136 return conf->u.buf.pos;
139 struct config_include_data {
140 int depth;
141 config_fn_t fn;
142 void *data;
143 const struct config_options *opts;
144 struct git_config_source *config_source;
147 * All remote URLs discovered when reading all config files.
149 struct string_list *remote_urls;
151 #define CONFIG_INCLUDE_INIT { 0 }
153 static int git_config_include(const char *var, const char *value, void *data);
155 #define MAX_INCLUDE_DEPTH 10
156 static const char include_depth_advice[] = N_(
157 "exceeded maximum include depth (%d) while including\n"
158 " %s\n"
159 "from\n"
160 " %s\n"
161 "This might be due to circular includes.");
162 static int handle_path_include(const char *path, struct config_include_data *inc)
164 int ret = 0;
165 struct strbuf buf = STRBUF_INIT;
166 char *expanded;
168 if (!path)
169 return config_error_nonbool("include.path");
171 expanded = interpolate_path(path, 0);
172 if (!expanded)
173 return error(_("could not expand include path '%s'"), path);
174 path = expanded;
177 * Use an absolute path as-is, but interpret relative paths
178 * based on the including config file.
180 if (!is_absolute_path(path)) {
181 char *slash;
183 if (!cf || !cf->path) {
184 ret = error(_("relative config includes must come from files"));
185 goto cleanup;
188 slash = find_last_dir_sep(cf->path);
189 if (slash)
190 strbuf_add(&buf, cf->path, slash - cf->path + 1);
191 strbuf_addstr(&buf, path);
192 path = buf.buf;
195 if (!access_or_die(path, R_OK, 0)) {
196 if (++inc->depth > MAX_INCLUDE_DEPTH)
197 die(_(include_depth_advice), MAX_INCLUDE_DEPTH, path,
198 !cf ? "<unknown>" :
199 cf->name ? cf->name :
200 "the command line");
201 ret = git_config_from_file(git_config_include, path, inc);
202 inc->depth--;
204 cleanup:
205 strbuf_release(&buf);
206 free(expanded);
207 return ret;
210 static void add_trailing_starstar_for_dir(struct strbuf *pat)
212 if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
213 strbuf_addstr(pat, "**");
216 static int prepare_include_condition_pattern(struct strbuf *pat)
218 struct strbuf path = STRBUF_INIT;
219 char *expanded;
220 int prefix = 0;
222 expanded = interpolate_path(pat->buf, 1);
223 if (expanded) {
224 strbuf_reset(pat);
225 strbuf_addstr(pat, expanded);
226 free(expanded);
229 if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
230 const char *slash;
232 if (!cf || !cf->path)
233 return error(_("relative config include "
234 "conditionals must come from files"));
236 strbuf_realpath(&path, cf->path, 1);
237 slash = find_last_dir_sep(path.buf);
238 if (!slash)
239 BUG("how is this possible?");
240 strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
241 prefix = slash - path.buf + 1 /* slash */;
242 } else if (!is_absolute_path(pat->buf))
243 strbuf_insertstr(pat, 0, "**/");
245 add_trailing_starstar_for_dir(pat);
247 strbuf_release(&path);
248 return prefix;
251 static int include_by_gitdir(const struct config_options *opts,
252 const char *cond, size_t cond_len, int icase)
254 struct strbuf text = STRBUF_INIT;
255 struct strbuf pattern = STRBUF_INIT;
256 int ret = 0, prefix;
257 const char *git_dir;
258 int already_tried_absolute = 0;
260 if (opts->git_dir)
261 git_dir = opts->git_dir;
262 else
263 goto done;
265 strbuf_realpath(&text, git_dir, 1);
266 strbuf_add(&pattern, cond, cond_len);
267 prefix = prepare_include_condition_pattern(&pattern);
269 again:
270 if (prefix < 0)
271 goto done;
273 if (prefix > 0) {
275 * perform literal matching on the prefix part so that
276 * any wildcard character in it can't create side effects.
278 if (text.len < prefix)
279 goto done;
280 if (!icase && strncmp(pattern.buf, text.buf, prefix))
281 goto done;
282 if (icase && strncasecmp(pattern.buf, text.buf, prefix))
283 goto done;
286 ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
287 WM_PATHNAME | (icase ? WM_CASEFOLD : 0));
289 if (!ret && !already_tried_absolute) {
291 * We've tried e.g. matching gitdir:~/work, but if
292 * ~/work is a symlink to /mnt/storage/work
293 * strbuf_realpath() will expand it, so the rule won't
294 * match. Let's match against a
295 * strbuf_add_absolute_path() version of the path,
296 * which'll do the right thing
298 strbuf_reset(&text);
299 strbuf_add_absolute_path(&text, git_dir);
300 already_tried_absolute = 1;
301 goto again;
303 done:
304 strbuf_release(&pattern);
305 strbuf_release(&text);
306 return ret;
309 static int include_by_branch(const char *cond, size_t cond_len)
311 int flags;
312 int ret;
313 struct strbuf pattern = STRBUF_INIT;
314 const char *refname = !the_repository->gitdir ?
315 NULL : resolve_ref_unsafe("HEAD", 0, NULL, &flags);
316 const char *shortname;
318 if (!refname || !(flags & REF_ISSYMREF) ||
319 !skip_prefix(refname, "refs/heads/", &shortname))
320 return 0;
322 strbuf_add(&pattern, cond, cond_len);
323 add_trailing_starstar_for_dir(&pattern);
324 ret = !wildmatch(pattern.buf, shortname, WM_PATHNAME);
325 strbuf_release(&pattern);
326 return ret;
329 static int add_remote_url(const char *var, const char *value, void *data)
331 struct string_list *remote_urls = data;
332 const char *remote_name;
333 size_t remote_name_len;
334 const char *key;
336 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
337 &key) &&
338 remote_name &&
339 !strcmp(key, "url"))
340 string_list_append(remote_urls, value);
341 return 0;
344 static void populate_remote_urls(struct config_include_data *inc)
346 struct config_options opts;
348 struct config_source *store_cf = cf;
349 struct key_value_info *store_kvi = current_config_kvi;
350 enum config_scope store_scope = current_parsing_scope;
352 opts = *inc->opts;
353 opts.unconditional_remote_url = 1;
355 cf = NULL;
356 current_config_kvi = NULL;
357 current_parsing_scope = 0;
359 inc->remote_urls = xmalloc(sizeof(*inc->remote_urls));
360 string_list_init_dup(inc->remote_urls);
361 config_with_options(add_remote_url, inc->remote_urls, inc->config_source, &opts);
363 cf = store_cf;
364 current_config_kvi = store_kvi;
365 current_parsing_scope = store_scope;
368 static int forbid_remote_url(const char *var, const char *value UNUSED,
369 void *data UNUSED)
371 const char *remote_name;
372 size_t remote_name_len;
373 const char *key;
375 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
376 &key) &&
377 remote_name &&
378 !strcmp(key, "url"))
379 die(_("remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"));
380 return 0;
383 static int at_least_one_url_matches_glob(const char *glob, int glob_len,
384 struct string_list *remote_urls)
386 struct strbuf pattern = STRBUF_INIT;
387 struct string_list_item *url_item;
388 int found = 0;
390 strbuf_add(&pattern, glob, glob_len);
391 for_each_string_list_item(url_item, remote_urls) {
392 if (!wildmatch(pattern.buf, url_item->string, WM_PATHNAME)) {
393 found = 1;
394 break;
397 strbuf_release(&pattern);
398 return found;
401 static int include_by_remote_url(struct config_include_data *inc,
402 const char *cond, size_t cond_len)
404 if (inc->opts->unconditional_remote_url)
405 return 1;
406 if (!inc->remote_urls)
407 populate_remote_urls(inc);
408 return at_least_one_url_matches_glob(cond, cond_len,
409 inc->remote_urls);
412 static int include_condition_is_true(struct config_include_data *inc,
413 const char *cond, size_t cond_len)
415 const struct config_options *opts = inc->opts;
417 if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
418 return include_by_gitdir(opts, cond, cond_len, 0);
419 else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
420 return include_by_gitdir(opts, cond, cond_len, 1);
421 else if (skip_prefix_mem(cond, cond_len, "onbranch:", &cond, &cond_len))
422 return include_by_branch(cond, cond_len);
423 else if (skip_prefix_mem(cond, cond_len, "hasconfig:remote.*.url:", &cond,
424 &cond_len))
425 return include_by_remote_url(inc, cond, cond_len);
427 /* unknown conditionals are always false */
428 return 0;
431 static int git_config_include(const char *var, const char *value, void *data)
433 struct config_include_data *inc = data;
434 const char *cond, *key;
435 size_t cond_len;
436 int ret;
439 * Pass along all values, including "include" directives; this makes it
440 * possible to query information on the includes themselves.
442 ret = inc->fn(var, value, inc->data);
443 if (ret < 0)
444 return ret;
446 if (!strcmp(var, "include.path"))
447 ret = handle_path_include(value, inc);
449 if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
450 cond && include_condition_is_true(inc, cond, cond_len) &&
451 !strcmp(key, "path")) {
452 config_fn_t old_fn = inc->fn;
454 if (inc->opts->unconditional_remote_url)
455 inc->fn = forbid_remote_url;
456 ret = handle_path_include(value, inc);
457 inc->fn = old_fn;
460 return ret;
463 static void git_config_push_split_parameter(const char *key, const char *value)
465 struct strbuf env = STRBUF_INIT;
466 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
467 if (old && *old) {
468 strbuf_addstr(&env, old);
469 strbuf_addch(&env, ' ');
471 sq_quote_buf(&env, key);
472 strbuf_addch(&env, '=');
473 if (value)
474 sq_quote_buf(&env, value);
475 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
476 strbuf_release(&env);
479 void git_config_push_parameter(const char *text)
481 const char *value;
484 * When we see:
486 * section.subsection=with=equals.key=value
488 * we cannot tell if it means:
490 * [section "subsection=with=equals"]
491 * key = value
493 * or:
495 * [section]
496 * subsection = with=equals.key=value
498 * We parse left-to-right for the first "=", meaning we'll prefer to
499 * keep the value intact over the subsection. This is historical, but
500 * also sensible since values are more likely to contain odd or
501 * untrusted input than a section name.
503 * A missing equals is explicitly allowed (as a bool-only entry).
505 value = strchr(text, '=');
506 if (value) {
507 char *key = xmemdupz(text, value - text);
508 git_config_push_split_parameter(key, value + 1);
509 free(key);
510 } else {
511 git_config_push_split_parameter(text, NULL);
515 void git_config_push_env(const char *spec)
517 char *key;
518 const char *env_name;
519 const char *env_value;
521 env_name = strrchr(spec, '=');
522 if (!env_name)
523 die(_("invalid config format: %s"), spec);
524 key = xmemdupz(spec, env_name - spec);
525 env_name++;
526 if (!*env_name)
527 die(_("missing environment variable name for configuration '%.*s'"),
528 (int)(env_name - spec - 1), spec);
530 env_value = getenv(env_name);
531 if (!env_value)
532 die(_("missing environment variable '%s' for configuration '%.*s'"),
533 env_name, (int)(env_name - spec - 1), spec);
535 git_config_push_split_parameter(key, env_value);
536 free(key);
539 static inline int iskeychar(int c)
541 return isalnum(c) || c == '-';
545 * Auxiliary function to sanity-check and split the key into the section
546 * identifier and variable name.
548 * Returns 0 on success, -1 when there is an invalid character in the key and
549 * -2 if there is no section name in the key.
551 * store_key - pointer to char* which will hold a copy of the key with
552 * lowercase section and variable name
553 * baselen - pointer to size_t which will hold the length of the
554 * section + subsection part, can be NULL
556 int git_config_parse_key(const char *key, char **store_key, size_t *baselen_)
558 size_t i, baselen;
559 int dot;
560 const char *last_dot = strrchr(key, '.');
563 * Since "key" actually contains the section name and the real
564 * key name separated by a dot, we have to know where the dot is.
567 if (last_dot == NULL || last_dot == key) {
568 error(_("key does not contain a section: %s"), key);
569 return -CONFIG_NO_SECTION_OR_NAME;
572 if (!last_dot[1]) {
573 error(_("key does not contain variable name: %s"), key);
574 return -CONFIG_NO_SECTION_OR_NAME;
577 baselen = last_dot - key;
578 if (baselen_)
579 *baselen_ = baselen;
582 * Validate the key and while at it, lower case it for matching.
584 *store_key = xmallocz(strlen(key));
586 dot = 0;
587 for (i = 0; key[i]; i++) {
588 unsigned char c = key[i];
589 if (c == '.')
590 dot = 1;
591 /* Leave the extended basename untouched.. */
592 if (!dot || i > baselen) {
593 if (!iskeychar(c) ||
594 (i == baselen + 1 && !isalpha(c))) {
595 error(_("invalid key: %s"), key);
596 goto out_free_ret_1;
598 c = tolower(c);
599 } else if (c == '\n') {
600 error(_("invalid key (newline): %s"), key);
601 goto out_free_ret_1;
603 (*store_key)[i] = c;
606 return 0;
608 out_free_ret_1:
609 FREE_AND_NULL(*store_key);
610 return -CONFIG_INVALID_KEY;
613 static int config_parse_pair(const char *key, const char *value,
614 config_fn_t fn, void *data)
616 char *canonical_name;
617 int ret;
619 if (!strlen(key))
620 return error(_("empty config key"));
621 if (git_config_parse_key(key, &canonical_name, NULL))
622 return -1;
624 ret = (fn(canonical_name, value, data) < 0) ? -1 : 0;
625 free(canonical_name);
626 return ret;
629 int git_config_parse_parameter(const char *text,
630 config_fn_t fn, void *data)
632 const char *value;
633 struct strbuf **pair;
634 int ret;
636 pair = strbuf_split_str(text, '=', 2);
637 if (!pair[0])
638 return error(_("bogus config parameter: %s"), text);
640 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
641 strbuf_setlen(pair[0], pair[0]->len - 1);
642 value = pair[1] ? pair[1]->buf : "";
643 } else {
644 value = NULL;
647 strbuf_trim(pair[0]);
648 if (!pair[0]->len) {
649 strbuf_list_free(pair);
650 return error(_("bogus config parameter: %s"), text);
653 ret = config_parse_pair(pair[0]->buf, value, fn, data);
654 strbuf_list_free(pair);
655 return ret;
658 static int parse_config_env_list(char *env, config_fn_t fn, void *data)
660 char *cur = env;
661 while (cur && *cur) {
662 const char *key = sq_dequote_step(cur, &cur);
663 if (!key)
664 return error(_("bogus format in %s"),
665 CONFIG_DATA_ENVIRONMENT);
667 if (!cur || isspace(*cur)) {
668 /* old-style 'key=value' */
669 if (git_config_parse_parameter(key, fn, data) < 0)
670 return -1;
672 else if (*cur == '=') {
673 /* new-style 'key'='value' */
674 const char *value;
676 cur++;
677 if (*cur == '\'') {
678 /* quoted value */
679 value = sq_dequote_step(cur, &cur);
680 if (!value || (cur && !isspace(*cur))) {
681 return error(_("bogus format in %s"),
682 CONFIG_DATA_ENVIRONMENT);
684 } else if (!*cur || isspace(*cur)) {
685 /* implicit bool: 'key'= */
686 value = NULL;
687 } else {
688 return error(_("bogus format in %s"),
689 CONFIG_DATA_ENVIRONMENT);
692 if (config_parse_pair(key, value, fn, data) < 0)
693 return -1;
695 else {
696 /* unknown format */
697 return error(_("bogus format in %s"),
698 CONFIG_DATA_ENVIRONMENT);
701 if (cur) {
702 while (isspace(*cur))
703 cur++;
706 return 0;
709 int git_config_from_parameters(config_fn_t fn, void *data)
711 const char *env;
712 struct strbuf envvar = STRBUF_INIT;
713 struct strvec to_free = STRVEC_INIT;
714 int ret = 0;
715 char *envw = NULL;
716 struct config_source source;
718 memset(&source, 0, sizeof(source));
719 source.prev = cf;
720 source.origin_type = CONFIG_ORIGIN_CMDLINE;
721 cf = &source;
723 env = getenv(CONFIG_COUNT_ENVIRONMENT);
724 if (env) {
725 unsigned long count;
726 char *endp;
727 int i;
729 count = strtoul(env, &endp, 10);
730 if (*endp) {
731 ret = error(_("bogus count in %s"), CONFIG_COUNT_ENVIRONMENT);
732 goto out;
734 if (count > INT_MAX) {
735 ret = error(_("too many entries in %s"), CONFIG_COUNT_ENVIRONMENT);
736 goto out;
739 for (i = 0; i < count; i++) {
740 const char *key, *value;
742 strbuf_addf(&envvar, "GIT_CONFIG_KEY_%d", i);
743 key = getenv_safe(&to_free, envvar.buf);
744 if (!key) {
745 ret = error(_("missing config key %s"), envvar.buf);
746 goto out;
748 strbuf_reset(&envvar);
750 strbuf_addf(&envvar, "GIT_CONFIG_VALUE_%d", i);
751 value = getenv_safe(&to_free, envvar.buf);
752 if (!value) {
753 ret = error(_("missing config value %s"), envvar.buf);
754 goto out;
756 strbuf_reset(&envvar);
758 if (config_parse_pair(key, value, fn, data) < 0) {
759 ret = -1;
760 goto out;
765 env = getenv(CONFIG_DATA_ENVIRONMENT);
766 if (env) {
767 /* sq_dequote will write over it */
768 envw = xstrdup(env);
769 if (parse_config_env_list(envw, fn, data) < 0) {
770 ret = -1;
771 goto out;
775 out:
776 strbuf_release(&envvar);
777 strvec_clear(&to_free);
778 free(envw);
779 cf = source.prev;
780 return ret;
783 static int get_next_char(void)
785 int c = cf->do_fgetc(cf);
787 if (c == '\r') {
788 /* DOS like systems */
789 c = cf->do_fgetc(cf);
790 if (c != '\n') {
791 if (c != EOF)
792 cf->do_ungetc(c, cf);
793 c = '\r';
797 if (c != EOF && ++cf->total_len > INT_MAX) {
799 * This is an absurdly long config file; refuse to parse
800 * further in order to protect downstream code from integer
801 * overflows. Note that we can't return an error specifically,
802 * but we can mark EOF and put trash in the return value,
803 * which will trigger a parse error.
805 cf->eof = 1;
806 return 0;
809 if (c == '\n')
810 cf->linenr++;
811 if (c == EOF) {
812 cf->eof = 1;
813 cf->linenr++;
814 c = '\n';
816 return c;
819 static char *parse_value(void)
821 int quote = 0, comment = 0, space = 0;
823 strbuf_reset(&cf->value);
824 for (;;) {
825 int c = get_next_char();
826 if (c == '\n') {
827 if (quote) {
828 cf->linenr--;
829 return NULL;
831 return cf->value.buf;
833 if (comment)
834 continue;
835 if (isspace(c) && !quote) {
836 if (cf->value.len)
837 space++;
838 continue;
840 if (!quote) {
841 if (c == ';' || c == '#') {
842 comment = 1;
843 continue;
846 for (; space; space--)
847 strbuf_addch(&cf->value, ' ');
848 if (c == '\\') {
849 c = get_next_char();
850 switch (c) {
851 case '\n':
852 continue;
853 case 't':
854 c = '\t';
855 break;
856 case 'b':
857 c = '\b';
858 break;
859 case 'n':
860 c = '\n';
861 break;
862 /* Some characters escape as themselves */
863 case '\\': case '"':
864 break;
865 /* Reject unknown escape sequences */
866 default:
867 return NULL;
869 strbuf_addch(&cf->value, c);
870 continue;
872 if (c == '"') {
873 quote = 1-quote;
874 continue;
876 strbuf_addch(&cf->value, c);
880 static int get_value(config_fn_t fn, void *data, struct strbuf *name)
882 int c;
883 char *value;
884 int ret;
886 /* Get the full name */
887 for (;;) {
888 c = get_next_char();
889 if (cf->eof)
890 break;
891 if (!iskeychar(c))
892 break;
893 strbuf_addch(name, tolower(c));
896 while (c == ' ' || c == '\t')
897 c = get_next_char();
899 value = NULL;
900 if (c != '\n') {
901 if (c != '=')
902 return -1;
903 value = parse_value();
904 if (!value)
905 return -1;
908 * We already consumed the \n, but we need linenr to point to
909 * the line we just parsed during the call to fn to get
910 * accurate line number in error messages.
912 cf->linenr--;
913 ret = fn(name->buf, value, data);
914 if (ret >= 0)
915 cf->linenr++;
916 return ret;
919 static int get_extended_base_var(struct strbuf *name, int c)
921 cf->subsection_case_sensitive = 0;
922 do {
923 if (c == '\n')
924 goto error_incomplete_line;
925 c = get_next_char();
926 } while (isspace(c));
928 /* We require the format to be '[base "extension"]' */
929 if (c != '"')
930 return -1;
931 strbuf_addch(name, '.');
933 for (;;) {
934 int c = get_next_char();
935 if (c == '\n')
936 goto error_incomplete_line;
937 if (c == '"')
938 break;
939 if (c == '\\') {
940 c = get_next_char();
941 if (c == '\n')
942 goto error_incomplete_line;
944 strbuf_addch(name, c);
947 /* Final ']' */
948 if (get_next_char() != ']')
949 return -1;
950 return 0;
951 error_incomplete_line:
952 cf->linenr--;
953 return -1;
956 static int get_base_var(struct strbuf *name)
958 cf->subsection_case_sensitive = 1;
959 for (;;) {
960 int c = get_next_char();
961 if (cf->eof)
962 return -1;
963 if (c == ']')
964 return 0;
965 if (isspace(c))
966 return get_extended_base_var(name, c);
967 if (!iskeychar(c) && c != '.')
968 return -1;
969 strbuf_addch(name, tolower(c));
973 struct parse_event_data {
974 enum config_event_t previous_type;
975 size_t previous_offset;
976 const struct config_options *opts;
979 static int do_event(enum config_event_t type, struct parse_event_data *data)
981 size_t offset;
983 if (!data->opts || !data->opts->event_fn)
984 return 0;
986 if (type == CONFIG_EVENT_WHITESPACE &&
987 data->previous_type == type)
988 return 0;
990 offset = cf->do_ftell(cf);
992 * At EOF, the parser always "inserts" an extra '\n', therefore
993 * the end offset of the event is the current file position, otherwise
994 * we will already have advanced to the next event.
996 if (type != CONFIG_EVENT_EOF)
997 offset--;
999 if (data->previous_type != CONFIG_EVENT_EOF &&
1000 data->opts->event_fn(data->previous_type, data->previous_offset,
1001 offset, data->opts->event_fn_data) < 0)
1002 return -1;
1004 data->previous_type = type;
1005 data->previous_offset = offset;
1007 return 0;
1010 static int git_parse_source(config_fn_t fn, void *data,
1011 const struct config_options *opts)
1013 int comment = 0;
1014 size_t baselen = 0;
1015 struct strbuf *var = &cf->var;
1016 int error_return = 0;
1017 char *error_msg = NULL;
1019 /* U+FEFF Byte Order Mark in UTF8 */
1020 const char *bomptr = utf8_bom;
1022 /* For the parser event callback */
1023 struct parse_event_data event_data = {
1024 CONFIG_EVENT_EOF, 0, opts
1027 for (;;) {
1028 int c;
1030 c = get_next_char();
1031 if (bomptr && *bomptr) {
1032 /* We are at the file beginning; skip UTF8-encoded BOM
1033 * if present. Sane editors won't put this in on their
1034 * own, but e.g. Windows Notepad will do it happily. */
1035 if (c == (*bomptr & 0377)) {
1036 bomptr++;
1037 continue;
1038 } else {
1039 /* Do not tolerate partial BOM. */
1040 if (bomptr != utf8_bom)
1041 break;
1042 /* No BOM at file beginning. Cool. */
1043 bomptr = NULL;
1046 if (c == '\n') {
1047 if (cf->eof) {
1048 if (do_event(CONFIG_EVENT_EOF, &event_data) < 0)
1049 return -1;
1050 return 0;
1052 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1053 return -1;
1054 comment = 0;
1055 continue;
1057 if (comment)
1058 continue;
1059 if (isspace(c)) {
1060 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1061 return -1;
1062 continue;
1064 if (c == '#' || c == ';') {
1065 if (do_event(CONFIG_EVENT_COMMENT, &event_data) < 0)
1066 return -1;
1067 comment = 1;
1068 continue;
1070 if (c == '[') {
1071 if (do_event(CONFIG_EVENT_SECTION, &event_data) < 0)
1072 return -1;
1074 /* Reset prior to determining a new stem */
1075 strbuf_reset(var);
1076 if (get_base_var(var) < 0 || var->len < 1)
1077 break;
1078 strbuf_addch(var, '.');
1079 baselen = var->len;
1080 continue;
1082 if (!isalpha(c))
1083 break;
1085 if (do_event(CONFIG_EVENT_ENTRY, &event_data) < 0)
1086 return -1;
1089 * Truncate the var name back to the section header
1090 * stem prior to grabbing the suffix part of the name
1091 * and the value.
1093 strbuf_setlen(var, baselen);
1094 strbuf_addch(var, tolower(c));
1095 if (get_value(fn, data, var) < 0)
1096 break;
1099 if (do_event(CONFIG_EVENT_ERROR, &event_data) < 0)
1100 return -1;
1102 switch (cf->origin_type) {
1103 case CONFIG_ORIGIN_BLOB:
1104 error_msg = xstrfmt(_("bad config line %d in blob %s"),
1105 cf->linenr, cf->name);
1106 break;
1107 case CONFIG_ORIGIN_FILE:
1108 error_msg = xstrfmt(_("bad config line %d in file %s"),
1109 cf->linenr, cf->name);
1110 break;
1111 case CONFIG_ORIGIN_STDIN:
1112 error_msg = xstrfmt(_("bad config line %d in standard input"),
1113 cf->linenr);
1114 break;
1115 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1116 error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
1117 cf->linenr, cf->name);
1118 break;
1119 case CONFIG_ORIGIN_CMDLINE:
1120 error_msg = xstrfmt(_("bad config line %d in command line %s"),
1121 cf->linenr, cf->name);
1122 break;
1123 default:
1124 error_msg = xstrfmt(_("bad config line %d in %s"),
1125 cf->linenr, cf->name);
1128 switch (opts && opts->error_action ?
1129 opts->error_action :
1130 cf->default_error_action) {
1131 case CONFIG_ERROR_DIE:
1132 die("%s", error_msg);
1133 break;
1134 case CONFIG_ERROR_ERROR:
1135 error_return = error("%s", error_msg);
1136 break;
1137 case CONFIG_ERROR_SILENT:
1138 error_return = -1;
1139 break;
1140 case CONFIG_ERROR_UNSET:
1141 BUG("config error action unset");
1144 free(error_msg);
1145 return error_return;
1148 static uintmax_t get_unit_factor(const char *end)
1150 if (!*end)
1151 return 1;
1152 else if (!strcasecmp(end, "k"))
1153 return 1024;
1154 else if (!strcasecmp(end, "m"))
1155 return 1024 * 1024;
1156 else if (!strcasecmp(end, "g"))
1157 return 1024 * 1024 * 1024;
1158 return 0;
1161 static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
1163 if (value && *value) {
1164 char *end;
1165 intmax_t val;
1166 intmax_t factor;
1168 if (max < 0)
1169 BUG("max must be a positive integer");
1171 errno = 0;
1172 val = strtoimax(value, &end, 0);
1173 if (errno == ERANGE)
1174 return 0;
1175 if (end == value) {
1176 errno = EINVAL;
1177 return 0;
1179 factor = get_unit_factor(end);
1180 if (!factor) {
1181 errno = EINVAL;
1182 return 0;
1184 if ((val < 0 && -max / factor > val) ||
1185 (val > 0 && max / factor < val)) {
1186 errno = ERANGE;
1187 return 0;
1189 val *= factor;
1190 *ret = val;
1191 return 1;
1193 errno = EINVAL;
1194 return 0;
1197 static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
1199 if (value && *value) {
1200 char *end;
1201 uintmax_t val;
1202 uintmax_t factor;
1204 /* negative values would be accepted by strtoumax */
1205 if (strchr(value, '-')) {
1206 errno = EINVAL;
1207 return 0;
1209 errno = 0;
1210 val = strtoumax(value, &end, 0);
1211 if (errno == ERANGE)
1212 return 0;
1213 if (end == value) {
1214 errno = EINVAL;
1215 return 0;
1217 factor = get_unit_factor(end);
1218 if (!factor) {
1219 errno = EINVAL;
1220 return 0;
1222 if (unsigned_mult_overflows(factor, val) ||
1223 factor * val > max) {
1224 errno = ERANGE;
1225 return 0;
1227 val *= factor;
1228 *ret = val;
1229 return 1;
1231 errno = EINVAL;
1232 return 0;
1235 int git_parse_int(const char *value, int *ret)
1237 intmax_t tmp;
1238 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
1239 return 0;
1240 *ret = tmp;
1241 return 1;
1244 static int git_parse_int64(const char *value, int64_t *ret)
1246 intmax_t tmp;
1247 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
1248 return 0;
1249 *ret = tmp;
1250 return 1;
1253 int git_parse_ulong(const char *value, unsigned long *ret)
1255 uintmax_t tmp;
1256 if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
1257 return 0;
1258 *ret = tmp;
1259 return 1;
1262 int git_parse_ssize_t(const char *value, ssize_t *ret)
1264 intmax_t tmp;
1265 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(ssize_t)))
1266 return 0;
1267 *ret = tmp;
1268 return 1;
1271 NORETURN
1272 static void die_bad_number(const char *name, const char *value)
1274 const char *error_type = (errno == ERANGE) ?
1275 N_("out of range") : N_("invalid unit");
1276 const char *bad_numeric = N_("bad numeric config value '%s' for '%s': %s");
1278 if (!value)
1279 value = "";
1281 if (!(cf && cf->name))
1282 die(_(bad_numeric), value, name, _(error_type));
1284 switch (cf->origin_type) {
1285 case CONFIG_ORIGIN_BLOB:
1286 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
1287 value, name, cf->name, _(error_type));
1288 case CONFIG_ORIGIN_FILE:
1289 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
1290 value, name, cf->name, _(error_type));
1291 case CONFIG_ORIGIN_STDIN:
1292 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
1293 value, name, _(error_type));
1294 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1295 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
1296 value, name, cf->name, _(error_type));
1297 case CONFIG_ORIGIN_CMDLINE:
1298 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
1299 value, name, cf->name, _(error_type));
1300 default:
1301 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
1302 value, name, cf->name, _(error_type));
1306 int git_config_int(const char *name, const char *value)
1308 int ret;
1309 if (!git_parse_int(value, &ret))
1310 die_bad_number(name, value);
1311 return ret;
1314 int64_t git_config_int64(const char *name, const char *value)
1316 int64_t ret;
1317 if (!git_parse_int64(value, &ret))
1318 die_bad_number(name, value);
1319 return ret;
1322 unsigned long git_config_ulong(const char *name, const char *value)
1324 unsigned long ret;
1325 if (!git_parse_ulong(value, &ret))
1326 die_bad_number(name, value);
1327 return ret;
1330 ssize_t git_config_ssize_t(const char *name, const char *value)
1332 ssize_t ret;
1333 if (!git_parse_ssize_t(value, &ret))
1334 die_bad_number(name, value);
1335 return ret;
1338 static int git_parse_maybe_bool_text(const char *value)
1340 if (!value)
1341 return 1;
1342 if (!*value)
1343 return 0;
1344 if (!strcasecmp(value, "true")
1345 || !strcasecmp(value, "yes")
1346 || !strcasecmp(value, "on"))
1347 return 1;
1348 if (!strcasecmp(value, "false")
1349 || !strcasecmp(value, "no")
1350 || !strcasecmp(value, "off"))
1351 return 0;
1352 return -1;
1355 static const struct fsync_component_name {
1356 const char *name;
1357 enum fsync_component component_bits;
1358 } fsync_component_names[] = {
1359 { "loose-object", FSYNC_COMPONENT_LOOSE_OBJECT },
1360 { "pack", FSYNC_COMPONENT_PACK },
1361 { "pack-metadata", FSYNC_COMPONENT_PACK_METADATA },
1362 { "commit-graph", FSYNC_COMPONENT_COMMIT_GRAPH },
1363 { "index", FSYNC_COMPONENT_INDEX },
1364 { "objects", FSYNC_COMPONENTS_OBJECTS },
1365 { "reference", FSYNC_COMPONENT_REFERENCE },
1366 { "derived-metadata", FSYNC_COMPONENTS_DERIVED_METADATA },
1367 { "committed", FSYNC_COMPONENTS_COMMITTED },
1368 { "added", FSYNC_COMPONENTS_ADDED },
1369 { "all", FSYNC_COMPONENTS_ALL },
1372 static enum fsync_component parse_fsync_components(const char *var, const char *string)
1374 enum fsync_component current = FSYNC_COMPONENTS_PLATFORM_DEFAULT;
1375 enum fsync_component positive = 0, negative = 0;
1377 while (string) {
1378 int i;
1379 size_t len;
1380 const char *ep;
1381 int negated = 0;
1382 int found = 0;
1384 string = string + strspn(string, ", \t\n\r");
1385 ep = strchrnul(string, ',');
1386 len = ep - string;
1387 if (!strcmp(string, "none")) {
1388 current = FSYNC_COMPONENT_NONE;
1389 goto next_name;
1392 if (*string == '-') {
1393 negated = 1;
1394 string++;
1395 len--;
1396 if (!len)
1397 warning(_("invalid value for variable %s"), var);
1400 if (!len)
1401 break;
1403 for (i = 0; i < ARRAY_SIZE(fsync_component_names); ++i) {
1404 const struct fsync_component_name *n = &fsync_component_names[i];
1406 if (strncmp(n->name, string, len))
1407 continue;
1409 found = 1;
1410 if (negated)
1411 negative |= n->component_bits;
1412 else
1413 positive |= n->component_bits;
1416 if (!found) {
1417 char *component = xstrndup(string, len);
1418 warning(_("ignoring unknown core.fsync component '%s'"), component);
1419 free(component);
1422 next_name:
1423 string = ep;
1426 return (current & ~negative) | positive;
1429 int git_parse_maybe_bool(const char *value)
1431 int v = git_parse_maybe_bool_text(value);
1432 if (0 <= v)
1433 return v;
1434 if (git_parse_int(value, &v))
1435 return !!v;
1436 return -1;
1439 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
1441 int v = git_parse_maybe_bool_text(value);
1442 if (0 <= v) {
1443 *is_bool = 1;
1444 return v;
1446 *is_bool = 0;
1447 return git_config_int(name, value);
1450 int git_config_bool(const char *name, const char *value)
1452 int v = git_parse_maybe_bool(value);
1453 if (v < 0)
1454 die(_("bad boolean config value '%s' for '%s'"), value, name);
1455 return v;
1458 int git_config_string(const char **dest, const char *var, const char *value)
1460 if (!value)
1461 return config_error_nonbool(var);
1462 *dest = xstrdup(value);
1463 return 0;
1466 int git_config_pathname(const char **dest, const char *var, const char *value)
1468 if (!value)
1469 return config_error_nonbool(var);
1470 *dest = interpolate_path(value, 0);
1471 if (!*dest)
1472 die(_("failed to expand user dir in: '%s'"), value);
1473 return 0;
1476 int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1478 if (!value)
1479 return config_error_nonbool(var);
1480 if (parse_expiry_date(value, timestamp))
1481 return error(_("'%s' for '%s' is not a valid timestamp"),
1482 value, var);
1483 return 0;
1486 int git_config_color(char *dest, const char *var, const char *value)
1488 if (!value)
1489 return config_error_nonbool(var);
1490 if (color_parse(value, dest) < 0)
1491 return -1;
1492 return 0;
1495 static int git_default_core_config(const char *var, const char *value, void *cb)
1497 /* This needs a better name */
1498 if (!strcmp(var, "core.filemode")) {
1499 trust_executable_bit = git_config_bool(var, value);
1500 return 0;
1502 if (!strcmp(var, "core.trustctime")) {
1503 trust_ctime = git_config_bool(var, value);
1504 return 0;
1506 if (!strcmp(var, "core.checkstat")) {
1507 if (!strcasecmp(value, "default"))
1508 check_stat = 1;
1509 else if (!strcasecmp(value, "minimal"))
1510 check_stat = 0;
1513 if (!strcmp(var, "core.quotepath")) {
1514 quote_path_fully = git_config_bool(var, value);
1515 return 0;
1518 if (!strcmp(var, "core.symlinks")) {
1519 has_symlinks = git_config_bool(var, value);
1520 return 0;
1523 if (!strcmp(var, "core.ignorecase")) {
1524 ignore_case = git_config_bool(var, value);
1525 return 0;
1528 if (!strcmp(var, "core.attributesfile"))
1529 return git_config_pathname(&git_attributes_file, var, value);
1531 if (!strcmp(var, "core.hookspath"))
1532 return git_config_pathname(&git_hooks_path, var, value);
1534 if (!strcmp(var, "core.bare")) {
1535 is_bare_repository_cfg = git_config_bool(var, value);
1536 return 0;
1539 if (!strcmp(var, "core.ignorestat")) {
1540 assume_unchanged = git_config_bool(var, value);
1541 return 0;
1544 if (!strcmp(var, "core.prefersymlinkrefs")) {
1545 prefer_symlink_refs = git_config_bool(var, value);
1546 return 0;
1549 if (!strcmp(var, "core.logallrefupdates")) {
1550 if (value && !strcasecmp(value, "always"))
1551 log_all_ref_updates = LOG_REFS_ALWAYS;
1552 else if (git_config_bool(var, value))
1553 log_all_ref_updates = LOG_REFS_NORMAL;
1554 else
1555 log_all_ref_updates = LOG_REFS_NONE;
1556 return 0;
1559 if (!strcmp(var, "core.warnambiguousrefs")) {
1560 warn_ambiguous_refs = git_config_bool(var, value);
1561 return 0;
1564 if (!strcmp(var, "core.abbrev")) {
1565 if (!value)
1566 return config_error_nonbool(var);
1567 if (!strcasecmp(value, "auto"))
1568 default_abbrev = -1;
1569 else if (!git_parse_maybe_bool_text(value))
1570 default_abbrev = the_hash_algo->hexsz;
1571 else {
1572 int abbrev = git_config_int(var, value);
1573 if (abbrev < minimum_abbrev || abbrev > the_hash_algo->hexsz)
1574 return error(_("abbrev length out of range: %d"), abbrev);
1575 default_abbrev = abbrev;
1577 return 0;
1580 if (!strcmp(var, "core.disambiguate"))
1581 return set_disambiguate_hint_config(var, value);
1583 if (!strcmp(var, "core.loosecompression")) {
1584 int level = git_config_int(var, value);
1585 if (level == -1)
1586 level = Z_DEFAULT_COMPRESSION;
1587 else if (level < 0 || level > Z_BEST_COMPRESSION)
1588 die(_("bad zlib compression level %d"), level);
1589 zlib_compression_level = level;
1590 zlib_compression_seen = 1;
1591 return 0;
1594 if (!strcmp(var, "core.compression")) {
1595 int level = git_config_int(var, value);
1596 if (level == -1)
1597 level = Z_DEFAULT_COMPRESSION;
1598 else if (level < 0 || level > Z_BEST_COMPRESSION)
1599 die(_("bad zlib compression level %d"), level);
1600 if (!zlib_compression_seen)
1601 zlib_compression_level = level;
1602 if (!pack_compression_seen)
1603 pack_compression_level = level;
1604 return 0;
1607 if (!strcmp(var, "core.packedgitwindowsize")) {
1608 int pgsz_x2 = getpagesize() * 2;
1609 packed_git_window_size = git_config_ulong(var, value);
1611 /* This value must be multiple of (pagesize * 2) */
1612 packed_git_window_size /= pgsz_x2;
1613 if (packed_git_window_size < 1)
1614 packed_git_window_size = 1;
1615 packed_git_window_size *= pgsz_x2;
1616 return 0;
1619 if (!strcmp(var, "core.bigfilethreshold")) {
1620 big_file_threshold = git_config_ulong(var, value);
1621 return 0;
1624 if (!strcmp(var, "core.packedgitlimit")) {
1625 packed_git_limit = git_config_ulong(var, value);
1626 return 0;
1629 if (!strcmp(var, "core.deltabasecachelimit")) {
1630 delta_base_cache_limit = git_config_ulong(var, value);
1631 return 0;
1634 if (!strcmp(var, "core.autocrlf")) {
1635 if (value && !strcasecmp(value, "input")) {
1636 auto_crlf = AUTO_CRLF_INPUT;
1637 return 0;
1639 auto_crlf = git_config_bool(var, value);
1640 return 0;
1643 if (!strcmp(var, "core.safecrlf")) {
1644 int eol_rndtrp_die;
1645 if (value && !strcasecmp(value, "warn")) {
1646 global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
1647 return 0;
1649 eol_rndtrp_die = git_config_bool(var, value);
1650 global_conv_flags_eol = eol_rndtrp_die ?
1651 CONV_EOL_RNDTRP_DIE : 0;
1652 return 0;
1655 if (!strcmp(var, "core.eol")) {
1656 if (value && !strcasecmp(value, "lf"))
1657 core_eol = EOL_LF;
1658 else if (value && !strcasecmp(value, "crlf"))
1659 core_eol = EOL_CRLF;
1660 else if (value && !strcasecmp(value, "native"))
1661 core_eol = EOL_NATIVE;
1662 else
1663 core_eol = EOL_UNSET;
1664 return 0;
1667 if (!strcmp(var, "core.checkroundtripencoding")) {
1668 check_roundtrip_encoding = xstrdup(value);
1669 return 0;
1672 if (!strcmp(var, "core.notesref")) {
1673 notes_ref_name = xstrdup(value);
1674 return 0;
1677 if (!strcmp(var, "core.editor"))
1678 return git_config_string(&editor_program, var, value);
1680 if (!strcmp(var, "core.commentchar")) {
1681 if (!value)
1682 return config_error_nonbool(var);
1683 else if (!strcasecmp(value, "auto"))
1684 auto_comment_line_char = 1;
1685 else if (value[0] && !value[1]) {
1686 comment_line_char = value[0];
1687 auto_comment_line_char = 0;
1688 } else
1689 return error(_("core.commentChar should only be one character"));
1690 return 0;
1693 if (!strcmp(var, "core.askpass"))
1694 return git_config_string(&askpass_program, var, value);
1696 if (!strcmp(var, "core.excludesfile"))
1697 return git_config_pathname(&excludes_file, var, value);
1699 if (!strcmp(var, "core.whitespace")) {
1700 if (!value)
1701 return config_error_nonbool(var);
1702 whitespace_rule_cfg = parse_whitespace_rule(value);
1703 return 0;
1706 if (!strcmp(var, "core.fsync")) {
1707 if (!value)
1708 return config_error_nonbool(var);
1709 fsync_components = parse_fsync_components(var, value);
1710 return 0;
1713 if (!strcmp(var, "core.fsyncmethod")) {
1714 if (!value)
1715 return config_error_nonbool(var);
1716 if (!strcmp(value, "fsync"))
1717 fsync_method = FSYNC_METHOD_FSYNC;
1718 else if (!strcmp(value, "writeout-only"))
1719 fsync_method = FSYNC_METHOD_WRITEOUT_ONLY;
1720 else if (!strcmp(value, "batch"))
1721 fsync_method = FSYNC_METHOD_BATCH;
1722 else
1723 warning(_("ignoring unknown core.fsyncMethod value '%s'"), value);
1727 if (!strcmp(var, "core.fsyncobjectfiles")) {
1728 if (fsync_object_files < 0)
1729 warning(_("core.fsyncObjectFiles is deprecated; use core.fsync instead"));
1730 fsync_object_files = git_config_bool(var, value);
1731 return 0;
1734 if (!strcmp(var, "core.preloadindex")) {
1735 core_preload_index = git_config_bool(var, value);
1736 return 0;
1739 if (!strcmp(var, "core.createobject")) {
1740 if (!strcmp(value, "rename"))
1741 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
1742 else if (!strcmp(value, "link"))
1743 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
1744 else
1745 die(_("invalid mode for object creation: %s"), value);
1746 return 0;
1749 if (!strcmp(var, "core.sparsecheckout")) {
1750 core_apply_sparse_checkout = git_config_bool(var, value);
1751 return 0;
1754 if (!strcmp(var, "core.sparsecheckoutcone")) {
1755 core_sparse_checkout_cone = git_config_bool(var, value);
1756 return 0;
1759 if (!strcmp(var, "core.precomposeunicode")) {
1760 precomposed_unicode = git_config_bool(var, value);
1761 return 0;
1764 if (!strcmp(var, "core.protecthfs")) {
1765 protect_hfs = git_config_bool(var, value);
1766 return 0;
1769 if (!strcmp(var, "core.protectntfs")) {
1770 protect_ntfs = git_config_bool(var, value);
1771 return 0;
1774 if (!strcmp(var, "core.usereplacerefs")) {
1775 read_replace_refs = git_config_bool(var, value);
1776 return 0;
1779 /* Add other config variables here and to Documentation/config.txt. */
1780 return platform_core_config(var, value, cb);
1783 static int git_default_sparse_config(const char *var, const char *value)
1785 if (!strcmp(var, "sparse.expectfilesoutsideofpatterns")) {
1786 sparse_expect_files_outside_of_patterns = git_config_bool(var, value);
1787 return 0;
1790 /* Add other config variables here and to Documentation/config/sparse.txt. */
1791 return 0;
1794 static int git_default_i18n_config(const char *var, const char *value)
1796 if (!strcmp(var, "i18n.commitencoding"))
1797 return git_config_string(&git_commit_encoding, var, value);
1799 if (!strcmp(var, "i18n.logoutputencoding"))
1800 return git_config_string(&git_log_output_encoding, var, value);
1802 /* Add other config variables here and to Documentation/config.txt. */
1803 return 0;
1806 static int git_default_branch_config(const char *var, const char *value)
1808 if (!strcmp(var, "branch.autosetupmerge")) {
1809 if (value && !strcmp(value, "always")) {
1810 git_branch_track = BRANCH_TRACK_ALWAYS;
1811 return 0;
1812 } else if (value && !strcmp(value, "inherit")) {
1813 git_branch_track = BRANCH_TRACK_INHERIT;
1814 return 0;
1815 } else if (value && !strcmp(value, "simple")) {
1816 git_branch_track = BRANCH_TRACK_SIMPLE;
1817 return 0;
1819 git_branch_track = git_config_bool(var, value);
1820 return 0;
1822 if (!strcmp(var, "branch.autosetuprebase")) {
1823 if (!value)
1824 return config_error_nonbool(var);
1825 else if (!strcmp(value, "never"))
1826 autorebase = AUTOREBASE_NEVER;
1827 else if (!strcmp(value, "local"))
1828 autorebase = AUTOREBASE_LOCAL;
1829 else if (!strcmp(value, "remote"))
1830 autorebase = AUTOREBASE_REMOTE;
1831 else if (!strcmp(value, "always"))
1832 autorebase = AUTOREBASE_ALWAYS;
1833 else
1834 return error(_("malformed value for %s"), var);
1835 return 0;
1838 /* Add other config variables here and to Documentation/config.txt. */
1839 return 0;
1842 static int git_default_push_config(const char *var, const char *value)
1844 if (!strcmp(var, "push.default")) {
1845 if (!value)
1846 return config_error_nonbool(var);
1847 else if (!strcmp(value, "nothing"))
1848 push_default = PUSH_DEFAULT_NOTHING;
1849 else if (!strcmp(value, "matching"))
1850 push_default = PUSH_DEFAULT_MATCHING;
1851 else if (!strcmp(value, "simple"))
1852 push_default = PUSH_DEFAULT_SIMPLE;
1853 else if (!strcmp(value, "upstream"))
1854 push_default = PUSH_DEFAULT_UPSTREAM;
1855 else if (!strcmp(value, "tracking")) /* deprecated */
1856 push_default = PUSH_DEFAULT_UPSTREAM;
1857 else if (!strcmp(value, "current"))
1858 push_default = PUSH_DEFAULT_CURRENT;
1859 else {
1860 error(_("malformed value for %s: %s"), var, value);
1861 return error(_("must be one of nothing, matching, simple, "
1862 "upstream or current"));
1864 return 0;
1867 /* Add other config variables here and to Documentation/config.txt. */
1868 return 0;
1871 static int git_default_mailmap_config(const char *var, const char *value)
1873 if (!strcmp(var, "mailmap.file"))
1874 return git_config_pathname(&git_mailmap_file, var, value);
1875 if (!strcmp(var, "mailmap.blob"))
1876 return git_config_string(&git_mailmap_blob, var, value);
1878 /* Add other config variables here and to Documentation/config.txt. */
1879 return 0;
1882 int git_default_config(const char *var, const char *value, void *cb)
1884 if (starts_with(var, "core."))
1885 return git_default_core_config(var, value, cb);
1887 if (starts_with(var, "user.") ||
1888 starts_with(var, "author.") ||
1889 starts_with(var, "committer."))
1890 return git_ident_config(var, value, cb);
1892 if (starts_with(var, "i18n."))
1893 return git_default_i18n_config(var, value);
1895 if (starts_with(var, "branch."))
1896 return git_default_branch_config(var, value);
1898 if (starts_with(var, "push."))
1899 return git_default_push_config(var, value);
1901 if (starts_with(var, "mailmap."))
1902 return git_default_mailmap_config(var, value);
1904 if (starts_with(var, "advice.") || starts_with(var, "color.advice"))
1905 return git_default_advice_config(var, value);
1907 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1908 pager_use_color = git_config_bool(var,value);
1909 return 0;
1912 if (!strcmp(var, "pack.packsizelimit")) {
1913 pack_size_limit_cfg = git_config_ulong(var, value);
1914 return 0;
1917 if (!strcmp(var, "pack.compression")) {
1918 int level = git_config_int(var, value);
1919 if (level == -1)
1920 level = Z_DEFAULT_COMPRESSION;
1921 else if (level < 0 || level > Z_BEST_COMPRESSION)
1922 die(_("bad pack compression level %d"), level);
1923 pack_compression_level = level;
1924 pack_compression_seen = 1;
1925 return 0;
1928 if (starts_with(var, "sparse."))
1929 return git_default_sparse_config(var, value);
1931 /* Add other config variables here and to Documentation/config.txt. */
1932 return 0;
1936 * All source specific fields in the union, die_on_error, name and the callbacks
1937 * fgetc, ungetc, ftell of top need to be initialized before calling
1938 * this function.
1940 static int do_config_from(struct config_source *top, config_fn_t fn, void *data,
1941 const struct config_options *opts)
1943 int ret;
1945 /* push config-file parsing state stack */
1946 top->prev = cf;
1947 top->linenr = 1;
1948 top->eof = 0;
1949 top->total_len = 0;
1950 strbuf_init(&top->value, 1024);
1951 strbuf_init(&top->var, 1024);
1952 cf = top;
1954 ret = git_parse_source(fn, data, opts);
1956 /* pop config-file parsing state stack */
1957 strbuf_release(&top->value);
1958 strbuf_release(&top->var);
1959 cf = top->prev;
1961 return ret;
1964 static int do_config_from_file(config_fn_t fn,
1965 const enum config_origin_type origin_type,
1966 const char *name, const char *path, FILE *f,
1967 void *data, const struct config_options *opts)
1969 struct config_source top;
1970 int ret;
1972 top.u.file = f;
1973 top.origin_type = origin_type;
1974 top.name = name;
1975 top.path = path;
1976 top.default_error_action = CONFIG_ERROR_DIE;
1977 top.do_fgetc = config_file_fgetc;
1978 top.do_ungetc = config_file_ungetc;
1979 top.do_ftell = config_file_ftell;
1981 flockfile(f);
1982 ret = do_config_from(&top, fn, data, opts);
1983 funlockfile(f);
1984 return ret;
1987 static int git_config_from_stdin(config_fn_t fn, void *data)
1989 return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", NULL, stdin,
1990 data, NULL);
1993 int git_config_from_file_with_options(config_fn_t fn, const char *filename,
1994 void *data,
1995 const struct config_options *opts)
1997 int ret = -1;
1998 FILE *f;
2000 if (!filename)
2001 BUG("filename cannot be NULL");
2002 f = fopen_or_warn(filename, "r");
2003 if (f) {
2004 ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename,
2005 filename, f, data, opts);
2006 fclose(f);
2008 return ret;
2011 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
2013 return git_config_from_file_with_options(fn, filename, data, NULL);
2016 int git_config_from_mem(config_fn_t fn,
2017 const enum config_origin_type origin_type,
2018 const char *name, const char *buf, size_t len,
2019 void *data, const struct config_options *opts)
2021 struct config_source top;
2023 top.u.buf.buf = buf;
2024 top.u.buf.len = len;
2025 top.u.buf.pos = 0;
2026 top.origin_type = origin_type;
2027 top.name = name;
2028 top.path = NULL;
2029 top.default_error_action = CONFIG_ERROR_ERROR;
2030 top.do_fgetc = config_buf_fgetc;
2031 top.do_ungetc = config_buf_ungetc;
2032 top.do_ftell = config_buf_ftell;
2034 return do_config_from(&top, fn, data, opts);
2037 int git_config_from_blob_oid(config_fn_t fn,
2038 const char *name,
2039 struct repository *repo,
2040 const struct object_id *oid,
2041 void *data)
2043 enum object_type type;
2044 char *buf;
2045 unsigned long size;
2046 int ret;
2048 buf = repo_read_object_file(repo, oid, &type, &size);
2049 if (!buf)
2050 return error(_("unable to load config blob object '%s'"), name);
2051 if (type != OBJ_BLOB) {
2052 free(buf);
2053 return error(_("reference '%s' does not point to a blob"), name);
2056 ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size,
2057 data, NULL);
2058 free(buf);
2060 return ret;
2063 static int git_config_from_blob_ref(config_fn_t fn,
2064 struct repository *repo,
2065 const char *name,
2066 void *data)
2068 struct object_id oid;
2070 if (repo_get_oid(repo, name, &oid) < 0)
2071 return error(_("unable to resolve config blob '%s'"), name);
2072 return git_config_from_blob_oid(fn, name, repo, &oid, data);
2075 char *git_system_config(void)
2077 char *system_config = xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
2078 if (!system_config)
2079 system_config = system_path(ETC_GITCONFIG);
2080 normalize_path_copy(system_config, system_config);
2081 return system_config;
2084 void git_global_config(char **user_out, char **xdg_out)
2086 char *user_config = xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
2087 char *xdg_config = NULL;
2089 if (!user_config) {
2090 user_config = interpolate_path("~/.gitconfig", 0);
2091 xdg_config = xdg_config_home("config");
2094 *user_out = user_config;
2095 *xdg_out = xdg_config;
2099 * Parse environment variable 'k' as a boolean (in various
2100 * possible spellings); if missing, use the default value 'def'.
2102 int git_env_bool(const char *k, int def)
2104 const char *v = getenv(k);
2105 return v ? git_config_bool(k, v) : def;
2109 * Parse environment variable 'k' as ulong with possibly a unit
2110 * suffix; if missing, use the default value 'val'.
2112 unsigned long git_env_ulong(const char *k, unsigned long val)
2114 const char *v = getenv(k);
2115 if (v && !git_parse_ulong(v, &val))
2116 die(_("failed to parse %s"), k);
2117 return val;
2120 int git_config_system(void)
2122 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
2125 static int do_git_config_sequence(const struct config_options *opts,
2126 config_fn_t fn, void *data)
2128 int ret = 0;
2129 char *system_config = git_system_config();
2130 char *xdg_config = NULL;
2131 char *user_config = NULL;
2132 char *repo_config;
2133 enum config_scope prev_parsing_scope = current_parsing_scope;
2135 if (opts->commondir)
2136 repo_config = mkpathdup("%s/config", opts->commondir);
2137 else if (opts->git_dir)
2138 BUG("git_dir without commondir");
2139 else
2140 repo_config = NULL;
2142 current_parsing_scope = CONFIG_SCOPE_SYSTEM;
2143 if (git_config_system() && system_config &&
2144 !access_or_die(system_config, R_OK,
2145 opts->system_gently ? ACCESS_EACCES_OK : 0))
2146 ret += git_config_from_file(fn, system_config, data);
2148 current_parsing_scope = CONFIG_SCOPE_GLOBAL;
2149 git_global_config(&user_config, &xdg_config);
2151 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
2152 ret += git_config_from_file(fn, xdg_config, data);
2154 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
2155 ret += git_config_from_file(fn, user_config, data);
2157 current_parsing_scope = CONFIG_SCOPE_LOCAL;
2158 if (!opts->ignore_repo && repo_config &&
2159 !access_or_die(repo_config, R_OK, 0))
2160 ret += git_config_from_file(fn, repo_config, data);
2162 current_parsing_scope = CONFIG_SCOPE_WORKTREE;
2163 if (!opts->ignore_worktree && repository_format_worktree_config) {
2164 char *path = git_pathdup("config.worktree");
2165 if (!access_or_die(path, R_OK, 0))
2166 ret += git_config_from_file(fn, path, data);
2167 free(path);
2170 current_parsing_scope = CONFIG_SCOPE_COMMAND;
2171 if (!opts->ignore_cmdline && git_config_from_parameters(fn, data) < 0)
2172 die(_("unable to parse command-line config"));
2174 current_parsing_scope = prev_parsing_scope;
2175 free(system_config);
2176 free(xdg_config);
2177 free(user_config);
2178 free(repo_config);
2179 return ret;
2182 int config_with_options(config_fn_t fn, void *data,
2183 struct git_config_source *config_source,
2184 const struct config_options *opts)
2186 struct config_include_data inc = CONFIG_INCLUDE_INIT;
2187 int ret;
2189 if (opts->respect_includes) {
2190 inc.fn = fn;
2191 inc.data = data;
2192 inc.opts = opts;
2193 inc.config_source = config_source;
2194 fn = git_config_include;
2195 data = &inc;
2198 if (config_source)
2199 current_parsing_scope = config_source->scope;
2202 * If we have a specific filename, use it. Otherwise, follow the
2203 * regular lookup sequence.
2205 if (config_source && config_source->use_stdin) {
2206 ret = git_config_from_stdin(fn, data);
2207 } else if (config_source && config_source->file) {
2208 ret = git_config_from_file(fn, config_source->file, data);
2209 } else if (config_source && config_source->blob) {
2210 struct repository *repo = config_source->repo ?
2211 config_source->repo : the_repository;
2212 ret = git_config_from_blob_ref(fn, repo, config_source->blob,
2213 data);
2214 } else {
2215 ret = do_git_config_sequence(opts, fn, data);
2218 if (inc.remote_urls) {
2219 string_list_clear(inc.remote_urls, 0);
2220 FREE_AND_NULL(inc.remote_urls);
2222 return ret;
2225 static void configset_iter(struct config_set *cs, config_fn_t fn, void *data)
2227 int i, value_index;
2228 struct string_list *values;
2229 struct config_set_element *entry;
2230 struct configset_list *list = &cs->list;
2232 for (i = 0; i < list->nr; i++) {
2233 entry = list->items[i].e;
2234 value_index = list->items[i].value_index;
2235 values = &entry->value_list;
2237 current_config_kvi = values->items[value_index].util;
2239 if (fn(entry->key, values->items[value_index].string, data) < 0)
2240 git_die_config_linenr(entry->key,
2241 current_config_kvi->filename,
2242 current_config_kvi->linenr);
2244 current_config_kvi = NULL;
2248 void read_early_config(config_fn_t cb, void *data)
2250 struct config_options opts = {0};
2251 struct strbuf commondir = STRBUF_INIT;
2252 struct strbuf gitdir = STRBUF_INIT;
2254 opts.respect_includes = 1;
2256 if (have_git_dir()) {
2257 opts.commondir = get_git_common_dir();
2258 opts.git_dir = get_git_dir();
2260 * When setup_git_directory() was not yet asked to discover the
2261 * GIT_DIR, we ask discover_git_directory() to figure out whether there
2262 * is any repository config we should use (but unlike
2263 * setup_git_directory_gently(), no global state is changed, most
2264 * notably, the current working directory is still the same after the
2265 * call).
2267 } else if (!discover_git_directory(&commondir, &gitdir)) {
2268 opts.commondir = commondir.buf;
2269 opts.git_dir = gitdir.buf;
2272 config_with_options(cb, data, NULL, &opts);
2274 strbuf_release(&commondir);
2275 strbuf_release(&gitdir);
2279 * Read config but only enumerate system and global settings.
2280 * Omit any repo-local, worktree-local, or command-line settings.
2282 void read_very_early_config(config_fn_t cb, void *data)
2284 struct config_options opts = { 0 };
2286 opts.respect_includes = 1;
2287 opts.ignore_repo = 1;
2288 opts.ignore_worktree = 1;
2289 opts.ignore_cmdline = 1;
2290 opts.system_gently = 1;
2292 config_with_options(cb, data, NULL, &opts);
2295 static struct config_set_element *configset_find_element(struct config_set *cs, const char *key)
2297 struct config_set_element k;
2298 struct config_set_element *found_entry;
2299 char *normalized_key;
2301 * `key` may come from the user, so normalize it before using it
2302 * for querying entries from the hashmap.
2304 if (git_config_parse_key(key, &normalized_key, NULL))
2305 return NULL;
2307 hashmap_entry_init(&k.ent, strhash(normalized_key));
2308 k.key = normalized_key;
2309 found_entry = hashmap_get_entry(&cs->config_hash, &k, ent, NULL);
2310 free(normalized_key);
2311 return found_entry;
2314 static int configset_add_value(struct config_set *cs, const char *key, const char *value)
2316 struct config_set_element *e;
2317 struct string_list_item *si;
2318 struct configset_list_item *l_item;
2319 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
2321 e = configset_find_element(cs, key);
2323 * Since the keys are being fed by git_config*() callback mechanism, they
2324 * are already normalized. So simply add them without any further munging.
2326 if (!e) {
2327 e = xmalloc(sizeof(*e));
2328 hashmap_entry_init(&e->ent, strhash(key));
2329 e->key = xstrdup(key);
2330 string_list_init_dup(&e->value_list);
2331 hashmap_add(&cs->config_hash, &e->ent);
2333 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
2335 ALLOC_GROW(cs->list.items, cs->list.nr + 1, cs->list.alloc);
2336 l_item = &cs->list.items[cs->list.nr++];
2337 l_item->e = e;
2338 l_item->value_index = e->value_list.nr - 1;
2340 if (!cf)
2341 BUG("configset_add_value has no source");
2342 if (cf->name) {
2343 kv_info->filename = strintern(cf->name);
2344 kv_info->linenr = cf->linenr;
2345 kv_info->origin_type = cf->origin_type;
2346 } else {
2347 /* for values read from `git_config_from_parameters()` */
2348 kv_info->filename = NULL;
2349 kv_info->linenr = -1;
2350 kv_info->origin_type = CONFIG_ORIGIN_CMDLINE;
2352 kv_info->scope = current_parsing_scope;
2353 si->util = kv_info;
2355 return 0;
2358 static int config_set_element_cmp(const void *cmp_data UNUSED,
2359 const struct hashmap_entry *eptr,
2360 const struct hashmap_entry *entry_or_key,
2361 const void *keydata UNUSED)
2363 const struct config_set_element *e1, *e2;
2365 e1 = container_of(eptr, const struct config_set_element, ent);
2366 e2 = container_of(entry_or_key, const struct config_set_element, ent);
2368 return strcmp(e1->key, e2->key);
2371 void git_configset_init(struct config_set *cs)
2373 hashmap_init(&cs->config_hash, config_set_element_cmp, NULL, 0);
2374 cs->hash_initialized = 1;
2375 cs->list.nr = 0;
2376 cs->list.alloc = 0;
2377 cs->list.items = NULL;
2380 void git_configset_clear(struct config_set *cs)
2382 struct config_set_element *entry;
2383 struct hashmap_iter iter;
2384 if (!cs->hash_initialized)
2385 return;
2387 hashmap_for_each_entry(&cs->config_hash, &iter, entry,
2388 ent /* member name */) {
2389 free(entry->key);
2390 string_list_clear(&entry->value_list, 1);
2392 hashmap_clear_and_free(&cs->config_hash, struct config_set_element, ent);
2393 cs->hash_initialized = 0;
2394 free(cs->list.items);
2395 cs->list.nr = 0;
2396 cs->list.alloc = 0;
2397 cs->list.items = NULL;
2400 static int config_set_callback(const char *key, const char *value, void *cb)
2402 struct config_set *cs = cb;
2403 configset_add_value(cs, key, value);
2404 return 0;
2407 int git_configset_add_file(struct config_set *cs, const char *filename)
2409 return git_config_from_file(config_set_callback, filename, cs);
2412 int git_configset_get_value(struct config_set *cs, const char *key, const char **value)
2414 const struct string_list *values = NULL;
2416 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
2417 * queried key in the files of the configset, the value returned will be the last
2418 * value in the value list for that key.
2420 values = git_configset_get_value_multi(cs, key);
2422 if (!values)
2423 return 1;
2424 assert(values->nr > 0);
2425 *value = values->items[values->nr - 1].string;
2426 return 0;
2429 const struct string_list *git_configset_get_value_multi(struct config_set *cs, const char *key)
2431 struct config_set_element *e = configset_find_element(cs, key);
2432 return e ? &e->value_list : NULL;
2435 int git_configset_get_string(struct config_set *cs, const char *key, char **dest)
2437 const char *value;
2438 if (!git_configset_get_value(cs, key, &value))
2439 return git_config_string((const char **)dest, key, value);
2440 else
2441 return 1;
2444 static int git_configset_get_string_tmp(struct config_set *cs, const char *key,
2445 const char **dest)
2447 const char *value;
2448 if (!git_configset_get_value(cs, key, &value)) {
2449 if (!value)
2450 return config_error_nonbool(key);
2451 *dest = value;
2452 return 0;
2453 } else {
2454 return 1;
2458 int git_configset_get_int(struct config_set *cs, const char *key, int *dest)
2460 const char *value;
2461 if (!git_configset_get_value(cs, key, &value)) {
2462 *dest = git_config_int(key, value);
2463 return 0;
2464 } else
2465 return 1;
2468 int git_configset_get_ulong(struct config_set *cs, const char *key, unsigned long *dest)
2470 const char *value;
2471 if (!git_configset_get_value(cs, key, &value)) {
2472 *dest = git_config_ulong(key, value);
2473 return 0;
2474 } else
2475 return 1;
2478 int git_configset_get_bool(struct config_set *cs, const char *key, int *dest)
2480 const char *value;
2481 if (!git_configset_get_value(cs, key, &value)) {
2482 *dest = git_config_bool(key, value);
2483 return 0;
2484 } else
2485 return 1;
2488 int git_configset_get_bool_or_int(struct config_set *cs, const char *key,
2489 int *is_bool, int *dest)
2491 const char *value;
2492 if (!git_configset_get_value(cs, key, &value)) {
2493 *dest = git_config_bool_or_int(key, value, is_bool);
2494 return 0;
2495 } else
2496 return 1;
2499 int git_configset_get_maybe_bool(struct config_set *cs, const char *key, int *dest)
2501 const char *value;
2502 if (!git_configset_get_value(cs, key, &value)) {
2503 *dest = git_parse_maybe_bool(value);
2504 if (*dest == -1)
2505 return -1;
2506 return 0;
2507 } else
2508 return 1;
2511 int git_configset_get_pathname(struct config_set *cs, const char *key, const char **dest)
2513 const char *value;
2514 if (!git_configset_get_value(cs, key, &value))
2515 return git_config_pathname(dest, key, value);
2516 else
2517 return 1;
2520 /* Functions use to read configuration from a repository */
2521 static void repo_read_config(struct repository *repo)
2523 struct config_options opts = { 0 };
2525 opts.respect_includes = 1;
2526 opts.commondir = repo->commondir;
2527 opts.git_dir = repo->gitdir;
2529 if (!repo->config)
2530 CALLOC_ARRAY(repo->config, 1);
2531 else
2532 git_configset_clear(repo->config);
2534 git_configset_init(repo->config);
2536 if (config_with_options(config_set_callback, repo->config, NULL, &opts) < 0)
2538 * config_with_options() normally returns only
2539 * zero, as most errors are fatal, and
2540 * non-fatal potential errors are guarded by "if"
2541 * statements that are entered only when no error is
2542 * possible.
2544 * If we ever encounter a non-fatal error, it means
2545 * something went really wrong and we should stop
2546 * immediately.
2548 die(_("unknown error occurred while reading the configuration files"));
2551 static void git_config_check_init(struct repository *repo)
2553 if (repo->config && repo->config->hash_initialized)
2554 return;
2555 repo_read_config(repo);
2558 static void repo_config_clear(struct repository *repo)
2560 if (!repo->config || !repo->config->hash_initialized)
2561 return;
2562 git_configset_clear(repo->config);
2565 void repo_config(struct repository *repo, config_fn_t fn, void *data)
2567 git_config_check_init(repo);
2568 configset_iter(repo->config, fn, data);
2571 int repo_config_get_value(struct repository *repo,
2572 const char *key, const char **value)
2574 git_config_check_init(repo);
2575 return git_configset_get_value(repo->config, key, value);
2578 const struct string_list *repo_config_get_value_multi(struct repository *repo,
2579 const char *key)
2581 git_config_check_init(repo);
2582 return git_configset_get_value_multi(repo->config, key);
2585 int repo_config_get_string(struct repository *repo,
2586 const char *key, char **dest)
2588 int ret;
2589 git_config_check_init(repo);
2590 ret = git_configset_get_string(repo->config, key, dest);
2591 if (ret < 0)
2592 git_die_config(key, NULL);
2593 return ret;
2596 int repo_config_get_string_tmp(struct repository *repo,
2597 const char *key, const char **dest)
2599 int ret;
2600 git_config_check_init(repo);
2601 ret = git_configset_get_string_tmp(repo->config, key, dest);
2602 if (ret < 0)
2603 git_die_config(key, NULL);
2604 return ret;
2607 int repo_config_get_int(struct repository *repo,
2608 const char *key, int *dest)
2610 git_config_check_init(repo);
2611 return git_configset_get_int(repo->config, key, dest);
2614 int repo_config_get_ulong(struct repository *repo,
2615 const char *key, unsigned long *dest)
2617 git_config_check_init(repo);
2618 return git_configset_get_ulong(repo->config, key, dest);
2621 int repo_config_get_bool(struct repository *repo,
2622 const char *key, int *dest)
2624 git_config_check_init(repo);
2625 return git_configset_get_bool(repo->config, key, dest);
2628 int repo_config_get_bool_or_int(struct repository *repo,
2629 const char *key, int *is_bool, int *dest)
2631 git_config_check_init(repo);
2632 return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2635 int repo_config_get_maybe_bool(struct repository *repo,
2636 const char *key, int *dest)
2638 git_config_check_init(repo);
2639 return git_configset_get_maybe_bool(repo->config, key, dest);
2642 int repo_config_get_pathname(struct repository *repo,
2643 const char *key, const char **dest)
2645 int ret;
2646 git_config_check_init(repo);
2647 ret = git_configset_get_pathname(repo->config, key, dest);
2648 if (ret < 0)
2649 git_die_config(key, NULL);
2650 return ret;
2653 /* Read values into protected_config. */
2654 static void read_protected_config(void)
2656 struct config_options opts = {
2657 .respect_includes = 1,
2658 .ignore_repo = 1,
2659 .ignore_worktree = 1,
2660 .system_gently = 1,
2662 git_configset_init(&protected_config);
2663 config_with_options(config_set_callback, &protected_config,
2664 NULL, &opts);
2667 void git_protected_config(config_fn_t fn, void *data)
2669 if (!protected_config.hash_initialized)
2670 read_protected_config();
2671 configset_iter(&protected_config, fn, data);
2674 /* Functions used historically to read configuration from 'the_repository' */
2675 void git_config(config_fn_t fn, void *data)
2677 repo_config(the_repository, fn, data);
2680 void git_config_clear(void)
2682 repo_config_clear(the_repository);
2685 int git_config_get_value(const char *key, const char **value)
2687 return repo_config_get_value(the_repository, key, value);
2690 const struct string_list *git_config_get_value_multi(const char *key)
2692 return repo_config_get_value_multi(the_repository, key);
2695 int git_config_get_string(const char *key, char **dest)
2697 return repo_config_get_string(the_repository, key, dest);
2700 int git_config_get_string_tmp(const char *key, const char **dest)
2702 return repo_config_get_string_tmp(the_repository, key, dest);
2705 int git_config_get_int(const char *key, int *dest)
2707 return repo_config_get_int(the_repository, key, dest);
2710 int git_config_get_ulong(const char *key, unsigned long *dest)
2712 return repo_config_get_ulong(the_repository, key, dest);
2715 int git_config_get_bool(const char *key, int *dest)
2717 return repo_config_get_bool(the_repository, key, dest);
2720 int git_config_get_bool_or_int(const char *key, int *is_bool, int *dest)
2722 return repo_config_get_bool_or_int(the_repository, key, is_bool, dest);
2725 int git_config_get_maybe_bool(const char *key, int *dest)
2727 return repo_config_get_maybe_bool(the_repository, key, dest);
2730 int git_config_get_pathname(const char *key, const char **dest)
2732 return repo_config_get_pathname(the_repository, key, dest);
2735 int git_config_get_expiry(const char *key, const char **output)
2737 int ret = git_config_get_string(key, (char **)output);
2738 if (ret)
2739 return ret;
2740 if (strcmp(*output, "now")) {
2741 timestamp_t now = approxidate("now");
2742 if (approxidate(*output) >= now)
2743 git_die_config(key, _("Invalid %s: '%s'"), key, *output);
2745 return ret;
2748 int git_config_get_expiry_in_days(const char *key, timestamp_t *expiry, timestamp_t now)
2750 const char *expiry_string;
2751 intmax_t days;
2752 timestamp_t when;
2754 if (git_config_get_string_tmp(key, &expiry_string))
2755 return 1; /* no such thing */
2757 if (git_parse_signed(expiry_string, &days, maximum_signed_value_of_type(int))) {
2758 const int scale = 86400;
2759 *expiry = now - days * scale;
2760 return 0;
2763 if (!parse_expiry_date(expiry_string, &when)) {
2764 *expiry = when;
2765 return 0;
2767 return -1; /* thing exists but cannot be parsed */
2770 int git_config_get_split_index(void)
2772 int val;
2774 if (!git_config_get_maybe_bool("core.splitindex", &val))
2775 return val;
2777 return -1; /* default value */
2780 int git_config_get_max_percent_split_change(void)
2782 int val = -1;
2784 if (!git_config_get_int("splitindex.maxpercentchange", &val)) {
2785 if (0 <= val && val <= 100)
2786 return val;
2788 return error(_("splitIndex.maxPercentChange value '%d' "
2789 "should be between 0 and 100"), val);
2792 return -1; /* default value */
2795 int git_config_get_index_threads(int *dest)
2797 int is_bool, val;
2799 val = git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2800 if (val) {
2801 *dest = val;
2802 return 0;
2805 if (!git_config_get_bool_or_int("index.threads", &is_bool, &val)) {
2806 if (is_bool)
2807 *dest = val ? 0 : 1;
2808 else
2809 *dest = val;
2810 return 0;
2813 return 1;
2816 NORETURN
2817 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2819 if (!filename)
2820 die(_("unable to parse '%s' from command-line config"), key);
2821 else
2822 die(_("bad config variable '%s' in file '%s' at line %d"),
2823 key, filename, linenr);
2826 NORETURN __attribute__((format(printf, 2, 3)))
2827 void git_die_config(const char *key, const char *err, ...)
2829 const struct string_list *values;
2830 struct key_value_info *kv_info;
2831 report_fn error_fn = get_error_routine();
2833 if (err) {
2834 va_list params;
2835 va_start(params, err);
2836 error_fn(err, params);
2837 va_end(params);
2839 values = git_config_get_value_multi(key);
2840 kv_info = values->items[values->nr - 1].util;
2841 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
2845 * Find all the stuff for git_config_set() below.
2848 struct config_store_data {
2849 size_t baselen;
2850 char *key;
2851 int do_not_match;
2852 const char *fixed_value;
2853 regex_t *value_pattern;
2854 int multi_replace;
2855 struct {
2856 size_t begin, end;
2857 enum config_event_t type;
2858 int is_keys_section;
2859 } *parsed;
2860 unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
2861 unsigned int key_seen:1, section_seen:1, is_keys_section:1;
2864 static void config_store_data_clear(struct config_store_data *store)
2866 free(store->key);
2867 if (store->value_pattern != NULL &&
2868 store->value_pattern != CONFIG_REGEX_NONE) {
2869 regfree(store->value_pattern);
2870 free(store->value_pattern);
2872 free(store->parsed);
2873 free(store->seen);
2874 memset(store, 0, sizeof(*store));
2877 static int matches(const char *key, const char *value,
2878 const struct config_store_data *store)
2880 if (strcmp(key, store->key))
2881 return 0; /* not ours */
2882 if (store->fixed_value)
2883 return !strcmp(store->fixed_value, value);
2884 if (!store->value_pattern)
2885 return 1; /* always matches */
2886 if (store->value_pattern == CONFIG_REGEX_NONE)
2887 return 0; /* never matches */
2889 return store->do_not_match ^
2890 (value && !regexec(store->value_pattern, value, 0, NULL, 0));
2893 static int store_aux_event(enum config_event_t type,
2894 size_t begin, size_t end, void *data)
2896 struct config_store_data *store = data;
2898 ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
2899 store->parsed[store->parsed_nr].begin = begin;
2900 store->parsed[store->parsed_nr].end = end;
2901 store->parsed[store->parsed_nr].type = type;
2903 if (type == CONFIG_EVENT_SECTION) {
2904 int (*cmpfn)(const char *, const char *, size_t);
2906 if (cf->var.len < 2 || cf->var.buf[cf->var.len - 1] != '.')
2907 return error(_("invalid section name '%s'"), cf->var.buf);
2909 if (cf->subsection_case_sensitive)
2910 cmpfn = strncasecmp;
2911 else
2912 cmpfn = strncmp;
2914 /* Is this the section we were looking for? */
2915 store->is_keys_section =
2916 store->parsed[store->parsed_nr].is_keys_section =
2917 cf->var.len - 1 == store->baselen &&
2918 !cmpfn(cf->var.buf, store->key, store->baselen);
2919 if (store->is_keys_section) {
2920 store->section_seen = 1;
2921 ALLOC_GROW(store->seen, store->seen_nr + 1,
2922 store->seen_alloc);
2923 store->seen[store->seen_nr] = store->parsed_nr;
2927 store->parsed_nr++;
2929 return 0;
2932 static int store_aux(const char *key, const char *value, void *cb)
2934 struct config_store_data *store = cb;
2936 if (store->key_seen) {
2937 if (matches(key, value, store)) {
2938 if (store->seen_nr == 1 && store->multi_replace == 0) {
2939 warning(_("%s has multiple values"), key);
2942 ALLOC_GROW(store->seen, store->seen_nr + 1,
2943 store->seen_alloc);
2945 store->seen[store->seen_nr] = store->parsed_nr;
2946 store->seen_nr++;
2948 } else if (store->is_keys_section) {
2950 * Do not increment matches yet: this may not be a match, but we
2951 * are in the desired section.
2953 ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
2954 store->seen[store->seen_nr] = store->parsed_nr;
2955 store->section_seen = 1;
2957 if (matches(key, value, store)) {
2958 store->seen_nr++;
2959 store->key_seen = 1;
2963 return 0;
2966 static int write_error(const char *filename)
2968 error(_("failed to write new configuration file %s"), filename);
2970 /* Same error code as "failed to rename". */
2971 return 4;
2974 static struct strbuf store_create_section(const char *key,
2975 const struct config_store_data *store)
2977 const char *dot;
2978 size_t i;
2979 struct strbuf sb = STRBUF_INIT;
2981 dot = memchr(key, '.', store->baselen);
2982 if (dot) {
2983 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
2984 for (i = dot - key + 1; i < store->baselen; i++) {
2985 if (key[i] == '"' || key[i] == '\\')
2986 strbuf_addch(&sb, '\\');
2987 strbuf_addch(&sb, key[i]);
2989 strbuf_addstr(&sb, "\"]\n");
2990 } else {
2991 strbuf_addch(&sb, '[');
2992 strbuf_add(&sb, key, store->baselen);
2993 strbuf_addstr(&sb, "]\n");
2996 return sb;
2999 static ssize_t write_section(int fd, const char *key,
3000 const struct config_store_data *store)
3002 struct strbuf sb = store_create_section(key, store);
3003 ssize_t ret;
3005 ret = write_in_full(fd, sb.buf, sb.len);
3006 strbuf_release(&sb);
3008 return ret;
3011 static ssize_t write_pair(int fd, const char *key, const char *value,
3012 const struct config_store_data *store)
3014 int i;
3015 ssize_t ret;
3016 const char *quote = "";
3017 struct strbuf sb = STRBUF_INIT;
3020 * Check to see if the value needs to be surrounded with a dq pair.
3021 * Note that problematic characters are always backslash-quoted; this
3022 * check is about not losing leading or trailing SP and strings that
3023 * follow beginning-of-comment characters (i.e. ';' and '#') by the
3024 * configuration parser.
3026 if (value[0] == ' ')
3027 quote = "\"";
3028 for (i = 0; value[i]; i++)
3029 if (value[i] == ';' || value[i] == '#')
3030 quote = "\"";
3031 if (i && value[i - 1] == ' ')
3032 quote = "\"";
3034 strbuf_addf(&sb, "\t%s = %s", key + store->baselen + 1, quote);
3036 for (i = 0; value[i]; i++)
3037 switch (value[i]) {
3038 case '\n':
3039 strbuf_addstr(&sb, "\\n");
3040 break;
3041 case '\t':
3042 strbuf_addstr(&sb, "\\t");
3043 break;
3044 case '"':
3045 case '\\':
3046 strbuf_addch(&sb, '\\');
3047 /* fallthrough */
3048 default:
3049 strbuf_addch(&sb, value[i]);
3050 break;
3052 strbuf_addf(&sb, "%s\n", quote);
3054 ret = write_in_full(fd, sb.buf, sb.len);
3055 strbuf_release(&sb);
3057 return ret;
3061 * If we are about to unset the last key(s) in a section, and if there are
3062 * no comments surrounding (or included in) the section, we will want to
3063 * extend begin/end to remove the entire section.
3065 * Note: the parameter `seen_ptr` points to the index into the store.seen
3066 * array. * This index may be incremented if a section has more than one
3067 * entry (which all are to be removed).
3069 static void maybe_remove_section(struct config_store_data *store,
3070 size_t *begin_offset, size_t *end_offset,
3071 int *seen_ptr)
3073 size_t begin;
3074 int i, seen, section_seen = 0;
3077 * First, ensure that this is the first key, and that there are no
3078 * comments before the entry nor before the section header.
3080 seen = *seen_ptr;
3081 for (i = store->seen[seen]; i > 0; i--) {
3082 enum config_event_t type = store->parsed[i - 1].type;
3084 if (type == CONFIG_EVENT_COMMENT)
3085 /* There is a comment before this entry or section */
3086 return;
3087 if (type == CONFIG_EVENT_ENTRY) {
3088 if (!section_seen)
3089 /* This is not the section's first entry. */
3090 return;
3091 /* We encountered no comment before the section. */
3092 break;
3094 if (type == CONFIG_EVENT_SECTION) {
3095 if (!store->parsed[i - 1].is_keys_section)
3096 break;
3097 section_seen = 1;
3100 begin = store->parsed[i].begin;
3103 * Next, make sure that we are removing the last key(s) in the section,
3104 * and that there are no comments that are possibly about the current
3105 * section.
3107 for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
3108 enum config_event_t type = store->parsed[i].type;
3110 if (type == CONFIG_EVENT_COMMENT)
3111 return;
3112 if (type == CONFIG_EVENT_SECTION) {
3113 if (store->parsed[i].is_keys_section)
3114 continue;
3115 break;
3117 if (type == CONFIG_EVENT_ENTRY) {
3118 if (++seen < store->seen_nr &&
3119 i == store->seen[seen])
3120 /* We want to remove this entry, too */
3121 continue;
3122 /* There is another entry in this section. */
3123 return;
3128 * We are really removing the last entry/entries from this section, and
3129 * there are no enclosed or surrounding comments. Remove the entire,
3130 * now-empty section.
3132 *seen_ptr = seen;
3133 *begin_offset = begin;
3134 if (i < store->parsed_nr)
3135 *end_offset = store->parsed[i].begin;
3136 else
3137 *end_offset = store->parsed[store->parsed_nr - 1].end;
3140 int git_config_set_in_file_gently(const char *config_filename,
3141 const char *key, const char *value)
3143 return git_config_set_multivar_in_file_gently(config_filename, key, value, NULL, 0);
3146 void git_config_set_in_file(const char *config_filename,
3147 const char *key, const char *value)
3149 git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
3152 int git_config_set_gently(const char *key, const char *value)
3154 return git_config_set_multivar_gently(key, value, NULL, 0);
3157 int repo_config_set_worktree_gently(struct repository *r,
3158 const char *key, const char *value)
3160 /* Only use worktree-specific config if it is already enabled. */
3161 if (repository_format_worktree_config) {
3162 char *file = repo_git_path(r, "config.worktree");
3163 int ret = git_config_set_multivar_in_file_gently(
3164 file, key, value, NULL, 0);
3165 free(file);
3166 return ret;
3168 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
3171 void git_config_set(const char *key, const char *value)
3173 git_config_set_multivar(key, value, NULL, 0);
3175 trace2_cmd_set_config(key, value);
3179 * If value==NULL, unset in (remove from) config,
3180 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
3181 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
3182 * (only add a new one)
3183 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3184 * key/values are removed before a single new pair is written. If the
3185 * flag is not present, then replace only the first match.
3187 * Returns 0 on success.
3189 * This function does this:
3191 * - it locks the config file by creating ".git/config.lock"
3193 * - it then parses the config using store_aux() as validator to find
3194 * the position on the key/value pair to replace. If it is to be unset,
3195 * it must be found exactly once.
3197 * - the config file is mmap()ed and the part before the match (if any) is
3198 * written to the lock file, then the changed part and the rest.
3200 * - the config file is removed and the lock file rename()d to it.
3203 int git_config_set_multivar_in_file_gently(const char *config_filename,
3204 const char *key, const char *value,
3205 const char *value_pattern,
3206 unsigned flags)
3208 int fd = -1, in_fd = -1;
3209 int ret;
3210 struct lock_file lock = LOCK_INIT;
3211 char *filename_buf = NULL;
3212 char *contents = NULL;
3213 size_t contents_sz;
3214 struct config_store_data store;
3216 memset(&store, 0, sizeof(store));
3218 /* parse-key returns negative; flip the sign to feed exit(3) */
3219 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
3220 if (ret)
3221 goto out_free;
3223 store.multi_replace = (flags & CONFIG_FLAGS_MULTI_REPLACE) != 0;
3225 if (!config_filename)
3226 config_filename = filename_buf = git_pathdup("config");
3229 * The lock serves a purpose in addition to locking: the new
3230 * contents of .git/config will be written into it.
3232 fd = hold_lock_file_for_update(&lock, config_filename, 0);
3233 if (fd < 0) {
3234 error_errno(_("could not lock config file %s"), config_filename);
3235 ret = CONFIG_NO_LOCK;
3236 goto out_free;
3240 * If .git/config does not exist yet, write a minimal version.
3242 in_fd = open(config_filename, O_RDONLY);
3243 if ( in_fd < 0 ) {
3244 if ( ENOENT != errno ) {
3245 error_errno(_("opening %s"), config_filename);
3246 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
3247 goto out_free;
3249 /* if nothing to unset, error out */
3250 if (!value) {
3251 ret = CONFIG_NOTHING_SET;
3252 goto out_free;
3255 free(store.key);
3256 store.key = xstrdup(key);
3257 if (write_section(fd, key, &store) < 0 ||
3258 write_pair(fd, key, value, &store) < 0)
3259 goto write_err_out;
3260 } else {
3261 struct stat st;
3262 size_t copy_begin, copy_end;
3263 int i, new_line = 0;
3264 struct config_options opts;
3266 if (!value_pattern)
3267 store.value_pattern = NULL;
3268 else if (value_pattern == CONFIG_REGEX_NONE)
3269 store.value_pattern = CONFIG_REGEX_NONE;
3270 else if (flags & CONFIG_FLAGS_FIXED_VALUE)
3271 store.fixed_value = value_pattern;
3272 else {
3273 if (value_pattern[0] == '!') {
3274 store.do_not_match = 1;
3275 value_pattern++;
3276 } else
3277 store.do_not_match = 0;
3279 store.value_pattern = (regex_t*)xmalloc(sizeof(regex_t));
3280 if (regcomp(store.value_pattern, value_pattern,
3281 REG_EXTENDED)) {
3282 error(_("invalid pattern: %s"), value_pattern);
3283 FREE_AND_NULL(store.value_pattern);
3284 ret = CONFIG_INVALID_PATTERN;
3285 goto out_free;
3289 ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
3290 store.parsed[0].end = 0;
3292 memset(&opts, 0, sizeof(opts));
3293 opts.event_fn = store_aux_event;
3294 opts.event_fn_data = &store;
3297 * After this, store.parsed will contain offsets of all the
3298 * parsed elements, and store.seen will contain a list of
3299 * matches, as indices into store.parsed.
3301 * As a side effect, we make sure to transform only a valid
3302 * existing config file.
3304 if (git_config_from_file_with_options(store_aux,
3305 config_filename,
3306 &store, &opts)) {
3307 error(_("invalid config file %s"), config_filename);
3308 ret = CONFIG_INVALID_FILE;
3309 goto out_free;
3312 /* if nothing to unset, or too many matches, error out */
3313 if ((store.seen_nr == 0 && value == NULL) ||
3314 (store.seen_nr > 1 && !store.multi_replace)) {
3315 ret = CONFIG_NOTHING_SET;
3316 goto out_free;
3319 if (fstat(in_fd, &st) == -1) {
3320 error_errno(_("fstat on %s failed"), config_filename);
3321 ret = CONFIG_INVALID_FILE;
3322 goto out_free;
3325 contents_sz = xsize_t(st.st_size);
3326 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
3327 MAP_PRIVATE, in_fd, 0);
3328 if (contents == MAP_FAILED) {
3329 if (errno == ENODEV && S_ISDIR(st.st_mode))
3330 errno = EISDIR;
3331 error_errno(_("unable to mmap '%s'%s"),
3332 config_filename, mmap_os_err());
3333 ret = CONFIG_INVALID_FILE;
3334 contents = NULL;
3335 goto out_free;
3337 close(in_fd);
3338 in_fd = -1;
3340 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3341 error_errno(_("chmod on %s failed"), get_lock_file_path(&lock));
3342 ret = CONFIG_NO_WRITE;
3343 goto out_free;
3346 if (store.seen_nr == 0) {
3347 if (!store.seen_alloc) {
3348 /* Did not see key nor section */
3349 ALLOC_GROW(store.seen, 1, store.seen_alloc);
3350 store.seen[0] = store.parsed_nr
3351 - !!store.parsed_nr;
3353 store.seen_nr = 1;
3356 for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
3357 size_t replace_end;
3358 int j = store.seen[i];
3360 new_line = 0;
3361 if (!store.key_seen) {
3362 copy_end = store.parsed[j].end;
3363 /* include '\n' when copying section header */
3364 if (copy_end > 0 && copy_end < contents_sz &&
3365 contents[copy_end - 1] != '\n' &&
3366 contents[copy_end] == '\n')
3367 copy_end++;
3368 replace_end = copy_end;
3369 } else {
3370 replace_end = store.parsed[j].end;
3371 copy_end = store.parsed[j].begin;
3372 if (!value)
3373 maybe_remove_section(&store,
3374 &copy_end,
3375 &replace_end, &i);
3377 * Swallow preceding white-space on the same
3378 * line.
3380 while (copy_end > 0 ) {
3381 char c = contents[copy_end - 1];
3383 if (isspace(c) && c != '\n')
3384 copy_end--;
3385 else
3386 break;
3390 if (copy_end > 0 && contents[copy_end-1] != '\n')
3391 new_line = 1;
3393 /* write the first part of the config */
3394 if (copy_end > copy_begin) {
3395 if (write_in_full(fd, contents + copy_begin,
3396 copy_end - copy_begin) < 0)
3397 goto write_err_out;
3398 if (new_line &&
3399 write_str_in_full(fd, "\n") < 0)
3400 goto write_err_out;
3402 copy_begin = replace_end;
3405 /* write the pair (value == NULL means unset) */
3406 if (value) {
3407 if (!store.section_seen) {
3408 if (write_section(fd, key, &store) < 0)
3409 goto write_err_out;
3411 if (write_pair(fd, key, value, &store) < 0)
3412 goto write_err_out;
3415 /* write the rest of the config */
3416 if (copy_begin < contents_sz)
3417 if (write_in_full(fd, contents + copy_begin,
3418 contents_sz - copy_begin) < 0)
3419 goto write_err_out;
3421 munmap(contents, contents_sz);
3422 contents = NULL;
3425 if (commit_lock_file(&lock) < 0) {
3426 error_errno(_("could not write config file %s"), config_filename);
3427 ret = CONFIG_NO_WRITE;
3428 goto out_free;
3431 ret = 0;
3433 /* Invalidate the config cache */
3434 git_config_clear();
3436 out_free:
3437 rollback_lock_file(&lock);
3438 free(filename_buf);
3439 if (contents)
3440 munmap(contents, contents_sz);
3441 if (in_fd >= 0)
3442 close(in_fd);
3443 config_store_data_clear(&store);
3444 return ret;
3446 write_err_out:
3447 ret = write_error(get_lock_file_path(&lock));
3448 goto out_free;
3452 void git_config_set_multivar_in_file(const char *config_filename,
3453 const char *key, const char *value,
3454 const char *value_pattern, unsigned flags)
3456 if (!git_config_set_multivar_in_file_gently(config_filename, key, value,
3457 value_pattern, flags))
3458 return;
3459 if (value)
3460 die(_("could not set '%s' to '%s'"), key, value);
3461 else
3462 die(_("could not unset '%s'"), key);
3465 int git_config_set_multivar_gently(const char *key, const char *value,
3466 const char *value_pattern, unsigned flags)
3468 return repo_config_set_multivar_gently(the_repository, key, value,
3469 value_pattern, flags);
3472 int repo_config_set_multivar_gently(struct repository *r, const char *key,
3473 const char *value,
3474 const char *value_pattern, unsigned flags)
3476 char *file = repo_git_path(r, "config");
3477 int res = git_config_set_multivar_in_file_gently(file,
3478 key, value,
3479 value_pattern,
3480 flags);
3481 free(file);
3482 return res;
3485 void git_config_set_multivar(const char *key, const char *value,
3486 const char *value_pattern, unsigned flags)
3488 git_config_set_multivar_in_file(git_path("config"),
3489 key, value, value_pattern,
3490 flags);
3493 static int section_name_match (const char *buf, const char *name)
3495 int i = 0, j = 0, dot = 0;
3496 if (buf[i] != '[')
3497 return 0;
3498 for (i = 1; buf[i] && buf[i] != ']'; i++) {
3499 if (!dot && isspace(buf[i])) {
3500 dot = 1;
3501 if (name[j++] != '.')
3502 break;
3503 for (i++; isspace(buf[i]); i++)
3504 ; /* do nothing */
3505 if (buf[i] != '"')
3506 break;
3507 continue;
3509 if (buf[i] == '\\' && dot)
3510 i++;
3511 else if (buf[i] == '"' && dot) {
3512 for (i++; isspace(buf[i]); i++)
3513 ; /* do_nothing */
3514 break;
3516 if (buf[i] != name[j++])
3517 break;
3519 if (buf[i] == ']' && name[j] == 0) {
3521 * We match, now just find the right length offset by
3522 * gobbling up any whitespace after it, as well
3524 i++;
3525 for (; buf[i] && isspace(buf[i]); i++)
3526 ; /* do nothing */
3527 return i;
3529 return 0;
3532 static int section_name_is_ok(const char *name)
3534 /* Empty section names are bogus. */
3535 if (!*name)
3536 return 0;
3539 * Before a dot, we must be alphanumeric or dash. After the first dot,
3540 * anything goes, so we can stop checking.
3542 for (; *name && *name != '.'; name++)
3543 if (*name != '-' && !isalnum(*name))
3544 return 0;
3545 return 1;
3548 /* if new_name == NULL, the section is removed instead */
3549 static int git_config_copy_or_rename_section_in_file(const char *config_filename,
3550 const char *old_name,
3551 const char *new_name, int copy)
3553 int ret = 0, remove = 0;
3554 char *filename_buf = NULL;
3555 struct lock_file lock = LOCK_INIT;
3556 int out_fd;
3557 char buf[1024];
3558 FILE *config_file = NULL;
3559 struct stat st;
3560 struct strbuf copystr = STRBUF_INIT;
3561 struct config_store_data store;
3563 memset(&store, 0, sizeof(store));
3565 if (new_name && !section_name_is_ok(new_name)) {
3566 ret = error(_("invalid section name: %s"), new_name);
3567 goto out_no_rollback;
3570 if (!config_filename)
3571 config_filename = filename_buf = git_pathdup("config");
3573 out_fd = hold_lock_file_for_update(&lock, config_filename, 0);
3574 if (out_fd < 0) {
3575 ret = error(_("could not lock config file %s"), config_filename);
3576 goto out;
3579 if (!(config_file = fopen(config_filename, "rb"))) {
3580 ret = warn_on_fopen_errors(config_filename);
3581 if (ret)
3582 goto out;
3583 /* no config file means nothing to rename, no error */
3584 goto commit_and_out;
3587 if (fstat(fileno(config_file), &st) == -1) {
3588 ret = error_errno(_("fstat on %s failed"), config_filename);
3589 goto out;
3592 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3593 ret = error_errno(_("chmod on %s failed"),
3594 get_lock_file_path(&lock));
3595 goto out;
3598 while (fgets(buf, sizeof(buf), config_file)) {
3599 unsigned i;
3600 int length;
3601 int is_section = 0;
3602 char *output = buf;
3603 for (i = 0; buf[i] && isspace(buf[i]); i++)
3604 ; /* do nothing */
3605 if (buf[i] == '[') {
3606 /* it's a section */
3607 int offset;
3608 is_section = 1;
3611 * When encountering a new section under -c we
3612 * need to flush out any section we're already
3613 * coping and begin anew. There might be
3614 * multiple [branch "$name"] sections.
3616 if (copystr.len > 0) {
3617 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3618 ret = write_error(get_lock_file_path(&lock));
3619 goto out;
3621 strbuf_reset(&copystr);
3624 offset = section_name_match(&buf[i], old_name);
3625 if (offset > 0) {
3626 ret++;
3627 if (!new_name) {
3628 remove = 1;
3629 continue;
3631 store.baselen = strlen(new_name);
3632 if (!copy) {
3633 if (write_section(out_fd, new_name, &store) < 0) {
3634 ret = write_error(get_lock_file_path(&lock));
3635 goto out;
3638 * We wrote out the new section, with
3639 * a newline, now skip the old
3640 * section's length
3642 output += offset + i;
3643 if (strlen(output) > 0) {
3645 * More content means there's
3646 * a declaration to put on the
3647 * next line; indent with a
3648 * tab
3650 output -= 1;
3651 output[0] = '\t';
3653 } else {
3654 copystr = store_create_section(new_name, &store);
3657 remove = 0;
3659 if (remove)
3660 continue;
3661 length = strlen(output);
3663 if (!is_section && copystr.len > 0) {
3664 strbuf_add(&copystr, output, length);
3667 if (write_in_full(out_fd, output, length) < 0) {
3668 ret = write_error(get_lock_file_path(&lock));
3669 goto out;
3674 * Copy a trailing section at the end of the config, won't be
3675 * flushed by the usual "flush because we have a new section
3676 * logic in the loop above.
3678 if (copystr.len > 0) {
3679 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3680 ret = write_error(get_lock_file_path(&lock));
3681 goto out;
3683 strbuf_reset(&copystr);
3686 fclose(config_file);
3687 config_file = NULL;
3688 commit_and_out:
3689 if (commit_lock_file(&lock) < 0)
3690 ret = error_errno(_("could not write config file %s"),
3691 config_filename);
3692 out:
3693 if (config_file)
3694 fclose(config_file);
3695 rollback_lock_file(&lock);
3696 out_no_rollback:
3697 free(filename_buf);
3698 config_store_data_clear(&store);
3699 return ret;
3702 int git_config_rename_section_in_file(const char *config_filename,
3703 const char *old_name, const char *new_name)
3705 return git_config_copy_or_rename_section_in_file(config_filename,
3706 old_name, new_name, 0);
3709 int git_config_rename_section(const char *old_name, const char *new_name)
3711 return git_config_rename_section_in_file(NULL, old_name, new_name);
3714 int git_config_copy_section_in_file(const char *config_filename,
3715 const char *old_name, const char *new_name)
3717 return git_config_copy_or_rename_section_in_file(config_filename,
3718 old_name, new_name, 1);
3721 int git_config_copy_section(const char *old_name, const char *new_name)
3723 return git_config_copy_section_in_file(NULL, old_name, new_name);
3727 * Call this to report error for your variable that should not
3728 * get a boolean value (i.e. "[my] var" means "true").
3730 #undef config_error_nonbool
3731 int config_error_nonbool(const char *var)
3733 return error(_("missing value for '%s'"), var);
3736 int parse_config_key(const char *var,
3737 const char *section,
3738 const char **subsection, size_t *subsection_len,
3739 const char **key)
3741 const char *dot;
3743 /* Does it start with "section." ? */
3744 if (!skip_prefix(var, section, &var) || *var != '.')
3745 return -1;
3748 * Find the key; we don't know yet if we have a subsection, but we must
3749 * parse backwards from the end, since the subsection may have dots in
3750 * it, too.
3752 dot = strrchr(var, '.');
3753 *key = dot + 1;
3755 /* Did we have a subsection at all? */
3756 if (dot == var) {
3757 if (subsection) {
3758 *subsection = NULL;
3759 *subsection_len = 0;
3762 else {
3763 if (!subsection)
3764 return -1;
3765 *subsection = var + 1;
3766 *subsection_len = dot - *subsection;
3769 return 0;
3772 const char *current_config_origin_type(void)
3774 int type;
3775 if (current_config_kvi)
3776 type = current_config_kvi->origin_type;
3777 else if(cf)
3778 type = cf->origin_type;
3779 else
3780 BUG("current_config_origin_type called outside config callback");
3782 switch (type) {
3783 case CONFIG_ORIGIN_BLOB:
3784 return "blob";
3785 case CONFIG_ORIGIN_FILE:
3786 return "file";
3787 case CONFIG_ORIGIN_STDIN:
3788 return "standard input";
3789 case CONFIG_ORIGIN_SUBMODULE_BLOB:
3790 return "submodule-blob";
3791 case CONFIG_ORIGIN_CMDLINE:
3792 return "command line";
3793 default:
3794 BUG("unknown config origin type");
3798 const char *config_scope_name(enum config_scope scope)
3800 switch (scope) {
3801 case CONFIG_SCOPE_SYSTEM:
3802 return "system";
3803 case CONFIG_SCOPE_GLOBAL:
3804 return "global";
3805 case CONFIG_SCOPE_LOCAL:
3806 return "local";
3807 case CONFIG_SCOPE_WORKTREE:
3808 return "worktree";
3809 case CONFIG_SCOPE_COMMAND:
3810 return "command";
3811 case CONFIG_SCOPE_SUBMODULE:
3812 return "submodule";
3813 default:
3814 return "unknown";
3818 const char *current_config_name(void)
3820 const char *name;
3821 if (current_config_kvi)
3822 name = current_config_kvi->filename;
3823 else if (cf)
3824 name = cf->name;
3825 else
3826 BUG("current_config_name called outside config callback");
3827 return name ? name : "";
3830 enum config_scope current_config_scope(void)
3832 if (current_config_kvi)
3833 return current_config_kvi->scope;
3834 else
3835 return current_parsing_scope;
3838 int current_config_line(void)
3840 if (current_config_kvi)
3841 return current_config_kvi->linenr;
3842 else
3843 return cf->linenr;
3846 int lookup_config(const char **mapping, int nr_mapping, const char *var)
3848 int i;
3850 for (i = 0; i < nr_mapping; i++) {
3851 const char *name = mapping[i];
3853 if (name && !strcasecmp(var, name))
3854 return i;
3856 return -1;