Merge branch 'add-uk-initial-l10n' of github.com:arkid15r/git-ukrainian-l10n
[alt-git.git] / config.c
blobb79baf83e35beb902acae4c902f619cf7eca21ef
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 * Copyright (C) Johannes Schindelin, 2005
7 */
8 #include "git-compat-util.h"
9 #include "abspath.h"
10 #include "advice.h"
11 #include "alloc.h"
12 #include "date.h"
13 #include "branch.h"
14 #include "config.h"
15 #include "convert.h"
16 #include "environment.h"
17 #include "gettext.h"
18 #include "ident.h"
19 #include "repository.h"
20 #include "lockfile.h"
21 #include "mailmap.h"
22 #include "exec-cmd.h"
23 #include "strbuf.h"
24 #include "quote.h"
25 #include "hashmap.h"
26 #include "string-list.h"
27 #include "object-name.h"
28 #include "object-store.h"
29 #include "pager.h"
30 #include "utf8.h"
31 #include "dir.h"
32 #include "color.h"
33 #include "replace-object.h"
34 #include "refs.h"
35 #include "setup.h"
36 #include "trace2.h"
37 #include "worktree.h"
38 #include "ws.h"
39 #include "wrapper.h"
40 #include "write-or-die.h"
42 struct config_source {
43 struct config_source *prev;
44 union {
45 FILE *file;
46 struct config_buf {
47 const char *buf;
48 size_t len;
49 size_t pos;
50 } buf;
51 } u;
52 enum config_origin_type origin_type;
53 const char *name;
54 const char *path;
55 enum config_error_action default_error_action;
56 int linenr;
57 int eof;
58 size_t total_len;
59 struct strbuf value;
60 struct strbuf var;
61 unsigned subsection_case_sensitive : 1;
63 int (*do_fgetc)(struct config_source *c);
64 int (*do_ungetc)(int c, struct config_source *conf);
65 long (*do_ftell)(struct config_source *c);
67 #define CONFIG_SOURCE_INIT { 0 }
69 struct config_reader {
71 * These members record the "current" config source, which can be
72 * accessed by parsing callbacks.
74 * The "source" variable will be non-NULL only when we are actually
75 * parsing a real config source (file, blob, cmdline, etc).
77 * The "config_kvi" variable will be non-NULL only when we are feeding
78 * cached config from a configset into a callback.
80 * They cannot be non-NULL at the same time. If they are both NULL, then
81 * we aren't parsing anything (and depending on the function looking at
82 * the variables, it's either a bug for it to be called in the first
83 * place, or it's a function which can be reused for non-config
84 * purposes, and should fall back to some sane behavior).
86 struct config_source *source;
87 struct key_value_info *config_kvi;
89 * The "scope" of the current config source being parsed (repo, global,
90 * etc). Like "source", this is only set when parsing a config source.
91 * It's not part of "source" because it transcends a single file (i.e.,
92 * a file included from .git/config is still in "repo" scope).
94 * When iterating through a configset, the equivalent value is
95 * "config_kvi.scope" (see above).
97 enum config_scope parsing_scope;
100 * Where possible, prefer to accept "struct config_reader" as an arg than to use
101 * "the_reader". "the_reader" should only be used if that is infeasible, e.g. in
102 * a public function.
104 static struct config_reader the_reader;
106 static inline void config_reader_push_source(struct config_reader *reader,
107 struct config_source *top)
109 if (reader->config_kvi)
110 BUG("source should not be set while iterating a config set");
111 top->prev = reader->source;
112 reader->source = top;
115 static inline struct config_source *config_reader_pop_source(struct config_reader *reader)
117 struct config_source *ret;
118 if (!reader->source)
119 BUG("tried to pop config source, but we weren't reading config");
120 ret = reader->source;
121 reader->source = reader->source->prev;
122 return ret;
125 static inline void config_reader_set_kvi(struct config_reader *reader,
126 struct key_value_info *kvi)
128 if (kvi && (reader->source || reader->parsing_scope))
129 BUG("kvi should not be set while parsing a config source");
130 reader->config_kvi = kvi;
133 static inline void config_reader_set_scope(struct config_reader *reader,
134 enum config_scope scope)
136 if (scope && reader->config_kvi)
137 BUG("scope should only be set when iterating through a config source");
138 reader->parsing_scope = scope;
141 static int pack_compression_seen;
142 static int zlib_compression_seen;
145 * Config that comes from trusted scopes, namely:
146 * - CONFIG_SCOPE_SYSTEM (e.g. /etc/gitconfig)
147 * - CONFIG_SCOPE_GLOBAL (e.g. $HOME/.gitconfig, $XDG_CONFIG_HOME/git)
148 * - CONFIG_SCOPE_COMMAND (e.g. "-c" option, environment variables)
150 * This is declared here for code cleanliness, but unlike the other
151 * static variables, this does not hold config parser state.
153 static struct config_set protected_config;
155 static int config_file_fgetc(struct config_source *conf)
157 return getc_unlocked(conf->u.file);
160 static int config_file_ungetc(int c, struct config_source *conf)
162 return ungetc(c, conf->u.file);
165 static long config_file_ftell(struct config_source *conf)
167 return ftell(conf->u.file);
171 static int config_buf_fgetc(struct config_source *conf)
173 if (conf->u.buf.pos < conf->u.buf.len)
174 return conf->u.buf.buf[conf->u.buf.pos++];
176 return EOF;
179 static int config_buf_ungetc(int c, struct config_source *conf)
181 if (conf->u.buf.pos > 0) {
182 conf->u.buf.pos--;
183 if (conf->u.buf.buf[conf->u.buf.pos] != c)
184 BUG("config_buf can only ungetc the same character");
185 return c;
188 return EOF;
191 static long config_buf_ftell(struct config_source *conf)
193 return conf->u.buf.pos;
196 struct config_include_data {
197 int depth;
198 config_fn_t fn;
199 void *data;
200 const struct config_options *opts;
201 struct git_config_source *config_source;
202 struct config_reader *config_reader;
205 * All remote URLs discovered when reading all config files.
207 struct string_list *remote_urls;
209 #define CONFIG_INCLUDE_INIT { 0 }
211 static int git_config_include(const char *var, const char *value, void *data);
213 #define MAX_INCLUDE_DEPTH 10
214 static const char include_depth_advice[] = N_(
215 "exceeded maximum include depth (%d) while including\n"
216 " %s\n"
217 "from\n"
218 " %s\n"
219 "This might be due to circular includes.");
220 static int handle_path_include(struct config_source *cs, const char *path,
221 struct config_include_data *inc)
223 int ret = 0;
224 struct strbuf buf = STRBUF_INIT;
225 char *expanded;
227 if (!path)
228 return config_error_nonbool("include.path");
230 expanded = interpolate_path(path, 0);
231 if (!expanded)
232 return error(_("could not expand include path '%s'"), path);
233 path = expanded;
236 * Use an absolute path as-is, but interpret relative paths
237 * based on the including config file.
239 if (!is_absolute_path(path)) {
240 char *slash;
242 if (!cs || !cs->path) {
243 ret = error(_("relative config includes must come from files"));
244 goto cleanup;
247 slash = find_last_dir_sep(cs->path);
248 if (slash)
249 strbuf_add(&buf, cs->path, slash - cs->path + 1);
250 strbuf_addstr(&buf, path);
251 path = buf.buf;
254 if (!access_or_die(path, R_OK, 0)) {
255 if (++inc->depth > MAX_INCLUDE_DEPTH)
256 die(_(include_depth_advice), MAX_INCLUDE_DEPTH, path,
257 !cs ? "<unknown>" :
258 cs->name ? cs->name :
259 "the command line");
260 ret = git_config_from_file(git_config_include, path, inc);
261 inc->depth--;
263 cleanup:
264 strbuf_release(&buf);
265 free(expanded);
266 return ret;
269 static void add_trailing_starstar_for_dir(struct strbuf *pat)
271 if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
272 strbuf_addstr(pat, "**");
275 static int prepare_include_condition_pattern(struct config_source *cs,
276 struct strbuf *pat)
278 struct strbuf path = STRBUF_INIT;
279 char *expanded;
280 int prefix = 0;
282 expanded = interpolate_path(pat->buf, 1);
283 if (expanded) {
284 strbuf_reset(pat);
285 strbuf_addstr(pat, expanded);
286 free(expanded);
289 if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
290 const char *slash;
292 if (!cs || !cs->path)
293 return error(_("relative config include "
294 "conditionals must come from files"));
296 strbuf_realpath(&path, cs->path, 1);
297 slash = find_last_dir_sep(path.buf);
298 if (!slash)
299 BUG("how is this possible?");
300 strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
301 prefix = slash - path.buf + 1 /* slash */;
302 } else if (!is_absolute_path(pat->buf))
303 strbuf_insertstr(pat, 0, "**/");
305 add_trailing_starstar_for_dir(pat);
307 strbuf_release(&path);
308 return prefix;
311 static int include_by_gitdir(struct config_source *cs,
312 const struct config_options *opts,
313 const char *cond, size_t cond_len, int icase)
315 struct strbuf text = STRBUF_INIT;
316 struct strbuf pattern = STRBUF_INIT;
317 int ret = 0, prefix;
318 const char *git_dir;
319 int already_tried_absolute = 0;
321 if (opts->git_dir)
322 git_dir = opts->git_dir;
323 else
324 goto done;
326 strbuf_realpath(&text, git_dir, 1);
327 strbuf_add(&pattern, cond, cond_len);
328 prefix = prepare_include_condition_pattern(cs, &pattern);
330 again:
331 if (prefix < 0)
332 goto done;
334 if (prefix > 0) {
336 * perform literal matching on the prefix part so that
337 * any wildcard character in it can't create side effects.
339 if (text.len < prefix)
340 goto done;
341 if (!icase && strncmp(pattern.buf, text.buf, prefix))
342 goto done;
343 if (icase && strncasecmp(pattern.buf, text.buf, prefix))
344 goto done;
347 ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
348 WM_PATHNAME | (icase ? WM_CASEFOLD : 0));
350 if (!ret && !already_tried_absolute) {
352 * We've tried e.g. matching gitdir:~/work, but if
353 * ~/work is a symlink to /mnt/storage/work
354 * strbuf_realpath() will expand it, so the rule won't
355 * match. Let's match against a
356 * strbuf_add_absolute_path() version of the path,
357 * which'll do the right thing
359 strbuf_reset(&text);
360 strbuf_add_absolute_path(&text, git_dir);
361 already_tried_absolute = 1;
362 goto again;
364 done:
365 strbuf_release(&pattern);
366 strbuf_release(&text);
367 return ret;
370 static int include_by_branch(const char *cond, size_t cond_len)
372 int flags;
373 int ret;
374 struct strbuf pattern = STRBUF_INIT;
375 const char *refname = !the_repository->gitdir ?
376 NULL : resolve_ref_unsafe("HEAD", 0, NULL, &flags);
377 const char *shortname;
379 if (!refname || !(flags & REF_ISSYMREF) ||
380 !skip_prefix(refname, "refs/heads/", &shortname))
381 return 0;
383 strbuf_add(&pattern, cond, cond_len);
384 add_trailing_starstar_for_dir(&pattern);
385 ret = !wildmatch(pattern.buf, shortname, WM_PATHNAME);
386 strbuf_release(&pattern);
387 return ret;
390 static int add_remote_url(const char *var, const char *value, void *data)
392 struct string_list *remote_urls = data;
393 const char *remote_name;
394 size_t remote_name_len;
395 const char *key;
397 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
398 &key) &&
399 remote_name &&
400 !strcmp(key, "url"))
401 string_list_append(remote_urls, value);
402 return 0;
405 static void populate_remote_urls(struct config_include_data *inc)
407 struct config_options opts;
409 enum config_scope store_scope = inc->config_reader->parsing_scope;
411 opts = *inc->opts;
412 opts.unconditional_remote_url = 1;
414 config_reader_set_scope(inc->config_reader, 0);
416 inc->remote_urls = xmalloc(sizeof(*inc->remote_urls));
417 string_list_init_dup(inc->remote_urls);
418 config_with_options(add_remote_url, inc->remote_urls, inc->config_source, &opts);
420 config_reader_set_scope(inc->config_reader, store_scope);
423 static int forbid_remote_url(const char *var, const char *value UNUSED,
424 void *data UNUSED)
426 const char *remote_name;
427 size_t remote_name_len;
428 const char *key;
430 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
431 &key) &&
432 remote_name &&
433 !strcmp(key, "url"))
434 die(_("remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"));
435 return 0;
438 static int at_least_one_url_matches_glob(const char *glob, int glob_len,
439 struct string_list *remote_urls)
441 struct strbuf pattern = STRBUF_INIT;
442 struct string_list_item *url_item;
443 int found = 0;
445 strbuf_add(&pattern, glob, glob_len);
446 for_each_string_list_item(url_item, remote_urls) {
447 if (!wildmatch(pattern.buf, url_item->string, WM_PATHNAME)) {
448 found = 1;
449 break;
452 strbuf_release(&pattern);
453 return found;
456 static int include_by_remote_url(struct config_include_data *inc,
457 const char *cond, size_t cond_len)
459 if (inc->opts->unconditional_remote_url)
460 return 1;
461 if (!inc->remote_urls)
462 populate_remote_urls(inc);
463 return at_least_one_url_matches_glob(cond, cond_len,
464 inc->remote_urls);
467 static int include_condition_is_true(struct config_source *cs,
468 struct config_include_data *inc,
469 const char *cond, size_t cond_len)
471 const struct config_options *opts = inc->opts;
473 if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
474 return include_by_gitdir(cs, opts, cond, cond_len, 0);
475 else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
476 return include_by_gitdir(cs, opts, cond, cond_len, 1);
477 else if (skip_prefix_mem(cond, cond_len, "onbranch:", &cond, &cond_len))
478 return include_by_branch(cond, cond_len);
479 else if (skip_prefix_mem(cond, cond_len, "hasconfig:remote.*.url:", &cond,
480 &cond_len))
481 return include_by_remote_url(inc, cond, cond_len);
483 /* unknown conditionals are always false */
484 return 0;
487 static int git_config_include(const char *var, const char *value, void *data)
489 struct config_include_data *inc = data;
490 struct config_source *cs = inc->config_reader->source;
491 const char *cond, *key;
492 size_t cond_len;
493 int ret;
496 * Pass along all values, including "include" directives; this makes it
497 * possible to query information on the includes themselves.
499 ret = inc->fn(var, value, inc->data);
500 if (ret < 0)
501 return ret;
503 if (!strcmp(var, "include.path"))
504 ret = handle_path_include(cs, value, inc);
506 if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
507 cond && include_condition_is_true(cs, inc, cond, cond_len) &&
508 !strcmp(key, "path")) {
509 config_fn_t old_fn = inc->fn;
511 if (inc->opts->unconditional_remote_url)
512 inc->fn = forbid_remote_url;
513 ret = handle_path_include(cs, value, inc);
514 inc->fn = old_fn;
517 return ret;
520 static void git_config_push_split_parameter(const char *key, const char *value)
522 struct strbuf env = STRBUF_INIT;
523 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
524 if (old && *old) {
525 strbuf_addstr(&env, old);
526 strbuf_addch(&env, ' ');
528 sq_quote_buf(&env, key);
529 strbuf_addch(&env, '=');
530 if (value)
531 sq_quote_buf(&env, value);
532 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
533 strbuf_release(&env);
536 void git_config_push_parameter(const char *text)
538 const char *value;
541 * When we see:
543 * section.subsection=with=equals.key=value
545 * we cannot tell if it means:
547 * [section "subsection=with=equals"]
548 * key = value
550 * or:
552 * [section]
553 * subsection = with=equals.key=value
555 * We parse left-to-right for the first "=", meaning we'll prefer to
556 * keep the value intact over the subsection. This is historical, but
557 * also sensible since values are more likely to contain odd or
558 * untrusted input than a section name.
560 * A missing equals is explicitly allowed (as a bool-only entry).
562 value = strchr(text, '=');
563 if (value) {
564 char *key = xmemdupz(text, value - text);
565 git_config_push_split_parameter(key, value + 1);
566 free(key);
567 } else {
568 git_config_push_split_parameter(text, NULL);
572 void git_config_push_env(const char *spec)
574 char *key;
575 const char *env_name;
576 const char *env_value;
578 env_name = strrchr(spec, '=');
579 if (!env_name)
580 die(_("invalid config format: %s"), spec);
581 key = xmemdupz(spec, env_name - spec);
582 env_name++;
583 if (!*env_name)
584 die(_("missing environment variable name for configuration '%.*s'"),
585 (int)(env_name - spec - 1), spec);
587 env_value = getenv(env_name);
588 if (!env_value)
589 die(_("missing environment variable '%s' for configuration '%.*s'"),
590 env_name, (int)(env_name - spec - 1), spec);
592 git_config_push_split_parameter(key, env_value);
593 free(key);
596 static inline int iskeychar(int c)
598 return isalnum(c) || c == '-';
602 * Auxiliary function to sanity-check and split the key into the section
603 * identifier and variable name.
605 * Returns 0 on success, -1 when there is an invalid character in the key and
606 * -2 if there is no section name in the key.
608 * store_key - pointer to char* which will hold a copy of the key with
609 * lowercase section and variable name
610 * baselen - pointer to size_t which will hold the length of the
611 * section + subsection part, can be NULL
613 int git_config_parse_key(const char *key, char **store_key, size_t *baselen_)
615 size_t i, baselen;
616 int dot;
617 const char *last_dot = strrchr(key, '.');
620 * Since "key" actually contains the section name and the real
621 * key name separated by a dot, we have to know where the dot is.
624 if (last_dot == NULL || last_dot == key) {
625 error(_("key does not contain a section: %s"), key);
626 return -CONFIG_NO_SECTION_OR_NAME;
629 if (!last_dot[1]) {
630 error(_("key does not contain variable name: %s"), key);
631 return -CONFIG_NO_SECTION_OR_NAME;
634 baselen = last_dot - key;
635 if (baselen_)
636 *baselen_ = baselen;
639 * Validate the key and while at it, lower case it for matching.
641 *store_key = xmallocz(strlen(key));
643 dot = 0;
644 for (i = 0; key[i]; i++) {
645 unsigned char c = key[i];
646 if (c == '.')
647 dot = 1;
648 /* Leave the extended basename untouched.. */
649 if (!dot || i > baselen) {
650 if (!iskeychar(c) ||
651 (i == baselen + 1 && !isalpha(c))) {
652 error(_("invalid key: %s"), key);
653 goto out_free_ret_1;
655 c = tolower(c);
656 } else if (c == '\n') {
657 error(_("invalid key (newline): %s"), key);
658 goto out_free_ret_1;
660 (*store_key)[i] = c;
663 return 0;
665 out_free_ret_1:
666 FREE_AND_NULL(*store_key);
667 return -CONFIG_INVALID_KEY;
670 static int config_parse_pair(const char *key, const char *value,
671 config_fn_t fn, void *data)
673 char *canonical_name;
674 int ret;
676 if (!strlen(key))
677 return error(_("empty config key"));
678 if (git_config_parse_key(key, &canonical_name, NULL))
679 return -1;
681 ret = (fn(canonical_name, value, data) < 0) ? -1 : 0;
682 free(canonical_name);
683 return ret;
686 int git_config_parse_parameter(const char *text,
687 config_fn_t fn, void *data)
689 const char *value;
690 struct strbuf **pair;
691 int ret;
693 pair = strbuf_split_str(text, '=', 2);
694 if (!pair[0])
695 return error(_("bogus config parameter: %s"), text);
697 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
698 strbuf_setlen(pair[0], pair[0]->len - 1);
699 value = pair[1] ? pair[1]->buf : "";
700 } else {
701 value = NULL;
704 strbuf_trim(pair[0]);
705 if (!pair[0]->len) {
706 strbuf_list_free(pair);
707 return error(_("bogus config parameter: %s"), text);
710 ret = config_parse_pair(pair[0]->buf, value, fn, data);
711 strbuf_list_free(pair);
712 return ret;
715 static int parse_config_env_list(char *env, config_fn_t fn, void *data)
717 char *cur = env;
718 while (cur && *cur) {
719 const char *key = sq_dequote_step(cur, &cur);
720 if (!key)
721 return error(_("bogus format in %s"),
722 CONFIG_DATA_ENVIRONMENT);
724 if (!cur || isspace(*cur)) {
725 /* old-style 'key=value' */
726 if (git_config_parse_parameter(key, fn, data) < 0)
727 return -1;
729 else if (*cur == '=') {
730 /* new-style 'key'='value' */
731 const char *value;
733 cur++;
734 if (*cur == '\'') {
735 /* quoted value */
736 value = sq_dequote_step(cur, &cur);
737 if (!value || (cur && !isspace(*cur))) {
738 return error(_("bogus format in %s"),
739 CONFIG_DATA_ENVIRONMENT);
741 } else if (!*cur || isspace(*cur)) {
742 /* implicit bool: 'key'= */
743 value = NULL;
744 } else {
745 return error(_("bogus format in %s"),
746 CONFIG_DATA_ENVIRONMENT);
749 if (config_parse_pair(key, value, fn, data) < 0)
750 return -1;
752 else {
753 /* unknown format */
754 return error(_("bogus format in %s"),
755 CONFIG_DATA_ENVIRONMENT);
758 if (cur) {
759 while (isspace(*cur))
760 cur++;
763 return 0;
766 int git_config_from_parameters(config_fn_t fn, void *data)
768 const char *env;
769 struct strbuf envvar = STRBUF_INIT;
770 struct strvec to_free = STRVEC_INIT;
771 int ret = 0;
772 char *envw = NULL;
773 struct config_source source = CONFIG_SOURCE_INIT;
775 source.origin_type = CONFIG_ORIGIN_CMDLINE;
776 config_reader_push_source(&the_reader, &source);
778 env = getenv(CONFIG_COUNT_ENVIRONMENT);
779 if (env) {
780 unsigned long count;
781 char *endp;
782 int i;
784 count = strtoul(env, &endp, 10);
785 if (*endp) {
786 ret = error(_("bogus count in %s"), CONFIG_COUNT_ENVIRONMENT);
787 goto out;
789 if (count > INT_MAX) {
790 ret = error(_("too many entries in %s"), CONFIG_COUNT_ENVIRONMENT);
791 goto out;
794 for (i = 0; i < count; i++) {
795 const char *key, *value;
797 strbuf_addf(&envvar, "GIT_CONFIG_KEY_%d", i);
798 key = getenv_safe(&to_free, envvar.buf);
799 if (!key) {
800 ret = error(_("missing config key %s"), envvar.buf);
801 goto out;
803 strbuf_reset(&envvar);
805 strbuf_addf(&envvar, "GIT_CONFIG_VALUE_%d", i);
806 value = getenv_safe(&to_free, envvar.buf);
807 if (!value) {
808 ret = error(_("missing config value %s"), envvar.buf);
809 goto out;
811 strbuf_reset(&envvar);
813 if (config_parse_pair(key, value, fn, data) < 0) {
814 ret = -1;
815 goto out;
820 env = getenv(CONFIG_DATA_ENVIRONMENT);
821 if (env) {
822 /* sq_dequote will write over it */
823 envw = xstrdup(env);
824 if (parse_config_env_list(envw, fn, data) < 0) {
825 ret = -1;
826 goto out;
830 out:
831 strbuf_release(&envvar);
832 strvec_clear(&to_free);
833 free(envw);
834 config_reader_pop_source(&the_reader);
835 return ret;
838 static int get_next_char(struct config_source *cs)
840 int c = cs->do_fgetc(cs);
842 if (c == '\r') {
843 /* DOS like systems */
844 c = cs->do_fgetc(cs);
845 if (c != '\n') {
846 if (c != EOF)
847 cs->do_ungetc(c, cs);
848 c = '\r';
852 if (c != EOF && ++cs->total_len > INT_MAX) {
854 * This is an absurdly long config file; refuse to parse
855 * further in order to protect downstream code from integer
856 * overflows. Note that we can't return an error specifically,
857 * but we can mark EOF and put trash in the return value,
858 * which will trigger a parse error.
860 cs->eof = 1;
861 return 0;
864 if (c == '\n')
865 cs->linenr++;
866 if (c == EOF) {
867 cs->eof = 1;
868 cs->linenr++;
869 c = '\n';
871 return c;
874 static char *parse_value(struct config_source *cs)
876 int quote = 0, comment = 0, space = 0;
878 strbuf_reset(&cs->value);
879 for (;;) {
880 int c = get_next_char(cs);
881 if (c == '\n') {
882 if (quote) {
883 cs->linenr--;
884 return NULL;
886 return cs->value.buf;
888 if (comment)
889 continue;
890 if (isspace(c) && !quote) {
891 if (cs->value.len)
892 space++;
893 continue;
895 if (!quote) {
896 if (c == ';' || c == '#') {
897 comment = 1;
898 continue;
901 for (; space; space--)
902 strbuf_addch(&cs->value, ' ');
903 if (c == '\\') {
904 c = get_next_char(cs);
905 switch (c) {
906 case '\n':
907 continue;
908 case 't':
909 c = '\t';
910 break;
911 case 'b':
912 c = '\b';
913 break;
914 case 'n':
915 c = '\n';
916 break;
917 /* Some characters escape as themselves */
918 case '\\': case '"':
919 break;
920 /* Reject unknown escape sequences */
921 default:
922 return NULL;
924 strbuf_addch(&cs->value, c);
925 continue;
927 if (c == '"') {
928 quote = 1-quote;
929 continue;
931 strbuf_addch(&cs->value, c);
935 static int get_value(struct config_source *cs, config_fn_t fn, void *data,
936 struct strbuf *name)
938 int c;
939 char *value;
940 int ret;
942 /* Get the full name */
943 for (;;) {
944 c = get_next_char(cs);
945 if (cs->eof)
946 break;
947 if (!iskeychar(c))
948 break;
949 strbuf_addch(name, tolower(c));
952 while (c == ' ' || c == '\t')
953 c = get_next_char(cs);
955 value = NULL;
956 if (c != '\n') {
957 if (c != '=')
958 return -1;
959 value = parse_value(cs);
960 if (!value)
961 return -1;
964 * We already consumed the \n, but we need linenr to point to
965 * the line we just parsed during the call to fn to get
966 * accurate line number in error messages.
968 cs->linenr--;
969 ret = fn(name->buf, value, data);
970 if (ret >= 0)
971 cs->linenr++;
972 return ret;
975 static int get_extended_base_var(struct config_source *cs, struct strbuf *name,
976 int c)
978 cs->subsection_case_sensitive = 0;
979 do {
980 if (c == '\n')
981 goto error_incomplete_line;
982 c = get_next_char(cs);
983 } while (isspace(c));
985 /* We require the format to be '[base "extension"]' */
986 if (c != '"')
987 return -1;
988 strbuf_addch(name, '.');
990 for (;;) {
991 int c = get_next_char(cs);
992 if (c == '\n')
993 goto error_incomplete_line;
994 if (c == '"')
995 break;
996 if (c == '\\') {
997 c = get_next_char(cs);
998 if (c == '\n')
999 goto error_incomplete_line;
1001 strbuf_addch(name, c);
1004 /* Final ']' */
1005 if (get_next_char(cs) != ']')
1006 return -1;
1007 return 0;
1008 error_incomplete_line:
1009 cs->linenr--;
1010 return -1;
1013 static int get_base_var(struct config_source *cs, struct strbuf *name)
1015 cs->subsection_case_sensitive = 1;
1016 for (;;) {
1017 int c = get_next_char(cs);
1018 if (cs->eof)
1019 return -1;
1020 if (c == ']')
1021 return 0;
1022 if (isspace(c))
1023 return get_extended_base_var(cs, name, c);
1024 if (!iskeychar(c) && c != '.')
1025 return -1;
1026 strbuf_addch(name, tolower(c));
1030 struct parse_event_data {
1031 enum config_event_t previous_type;
1032 size_t previous_offset;
1033 const struct config_options *opts;
1036 static int do_event(struct config_source *cs, enum config_event_t type,
1037 struct parse_event_data *data)
1039 size_t offset;
1041 if (!data->opts || !data->opts->event_fn)
1042 return 0;
1044 if (type == CONFIG_EVENT_WHITESPACE &&
1045 data->previous_type == type)
1046 return 0;
1048 offset = cs->do_ftell(cs);
1050 * At EOF, the parser always "inserts" an extra '\n', therefore
1051 * the end offset of the event is the current file position, otherwise
1052 * we will already have advanced to the next event.
1054 if (type != CONFIG_EVENT_EOF)
1055 offset--;
1057 if (data->previous_type != CONFIG_EVENT_EOF &&
1058 data->opts->event_fn(data->previous_type, data->previous_offset,
1059 offset, data->opts->event_fn_data) < 0)
1060 return -1;
1062 data->previous_type = type;
1063 data->previous_offset = offset;
1065 return 0;
1068 static int git_parse_source(struct config_source *cs, config_fn_t fn,
1069 void *data, const struct config_options *opts)
1071 int comment = 0;
1072 size_t baselen = 0;
1073 struct strbuf *var = &cs->var;
1074 int error_return = 0;
1075 char *error_msg = NULL;
1077 /* U+FEFF Byte Order Mark in UTF8 */
1078 const char *bomptr = utf8_bom;
1080 /* For the parser event callback */
1081 struct parse_event_data event_data = {
1082 CONFIG_EVENT_EOF, 0, opts
1085 for (;;) {
1086 int c;
1088 c = get_next_char(cs);
1089 if (bomptr && *bomptr) {
1090 /* We are at the file beginning; skip UTF8-encoded BOM
1091 * if present. Sane editors won't put this in on their
1092 * own, but e.g. Windows Notepad will do it happily. */
1093 if (c == (*bomptr & 0377)) {
1094 bomptr++;
1095 continue;
1096 } else {
1097 /* Do not tolerate partial BOM. */
1098 if (bomptr != utf8_bom)
1099 break;
1100 /* No BOM at file beginning. Cool. */
1101 bomptr = NULL;
1104 if (c == '\n') {
1105 if (cs->eof) {
1106 if (do_event(cs, CONFIG_EVENT_EOF, &event_data) < 0)
1107 return -1;
1108 return 0;
1110 if (do_event(cs, CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1111 return -1;
1112 comment = 0;
1113 continue;
1115 if (comment)
1116 continue;
1117 if (isspace(c)) {
1118 if (do_event(cs, CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1119 return -1;
1120 continue;
1122 if (c == '#' || c == ';') {
1123 if (do_event(cs, CONFIG_EVENT_COMMENT, &event_data) < 0)
1124 return -1;
1125 comment = 1;
1126 continue;
1128 if (c == '[') {
1129 if (do_event(cs, CONFIG_EVENT_SECTION, &event_data) < 0)
1130 return -1;
1132 /* Reset prior to determining a new stem */
1133 strbuf_reset(var);
1134 if (get_base_var(cs, var) < 0 || var->len < 1)
1135 break;
1136 strbuf_addch(var, '.');
1137 baselen = var->len;
1138 continue;
1140 if (!isalpha(c))
1141 break;
1143 if (do_event(cs, CONFIG_EVENT_ENTRY, &event_data) < 0)
1144 return -1;
1147 * Truncate the var name back to the section header
1148 * stem prior to grabbing the suffix part of the name
1149 * and the value.
1151 strbuf_setlen(var, baselen);
1152 strbuf_addch(var, tolower(c));
1153 if (get_value(cs, fn, data, var) < 0)
1154 break;
1157 if (do_event(cs, CONFIG_EVENT_ERROR, &event_data) < 0)
1158 return -1;
1160 switch (cs->origin_type) {
1161 case CONFIG_ORIGIN_BLOB:
1162 error_msg = xstrfmt(_("bad config line %d in blob %s"),
1163 cs->linenr, cs->name);
1164 break;
1165 case CONFIG_ORIGIN_FILE:
1166 error_msg = xstrfmt(_("bad config line %d in file %s"),
1167 cs->linenr, cs->name);
1168 break;
1169 case CONFIG_ORIGIN_STDIN:
1170 error_msg = xstrfmt(_("bad config line %d in standard input"),
1171 cs->linenr);
1172 break;
1173 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1174 error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
1175 cs->linenr, cs->name);
1176 break;
1177 case CONFIG_ORIGIN_CMDLINE:
1178 error_msg = xstrfmt(_("bad config line %d in command line %s"),
1179 cs->linenr, cs->name);
1180 break;
1181 default:
1182 error_msg = xstrfmt(_("bad config line %d in %s"),
1183 cs->linenr, cs->name);
1186 switch (opts && opts->error_action ?
1187 opts->error_action :
1188 cs->default_error_action) {
1189 case CONFIG_ERROR_DIE:
1190 die("%s", error_msg);
1191 break;
1192 case CONFIG_ERROR_ERROR:
1193 error_return = error("%s", error_msg);
1194 break;
1195 case CONFIG_ERROR_SILENT:
1196 error_return = -1;
1197 break;
1198 case CONFIG_ERROR_UNSET:
1199 BUG("config error action unset");
1202 free(error_msg);
1203 return error_return;
1206 static uintmax_t get_unit_factor(const char *end)
1208 if (!*end)
1209 return 1;
1210 else if (!strcasecmp(end, "k"))
1211 return 1024;
1212 else if (!strcasecmp(end, "m"))
1213 return 1024 * 1024;
1214 else if (!strcasecmp(end, "g"))
1215 return 1024 * 1024 * 1024;
1216 return 0;
1219 static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
1221 if (value && *value) {
1222 char *end;
1223 intmax_t val;
1224 intmax_t factor;
1226 if (max < 0)
1227 BUG("max must be a positive integer");
1229 errno = 0;
1230 val = strtoimax(value, &end, 0);
1231 if (errno == ERANGE)
1232 return 0;
1233 if (end == value) {
1234 errno = EINVAL;
1235 return 0;
1237 factor = get_unit_factor(end);
1238 if (!factor) {
1239 errno = EINVAL;
1240 return 0;
1242 if ((val < 0 && -max / factor > val) ||
1243 (val > 0 && max / factor < val)) {
1244 errno = ERANGE;
1245 return 0;
1247 val *= factor;
1248 *ret = val;
1249 return 1;
1251 errno = EINVAL;
1252 return 0;
1255 static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
1257 if (value && *value) {
1258 char *end;
1259 uintmax_t val;
1260 uintmax_t factor;
1262 /* negative values would be accepted by strtoumax */
1263 if (strchr(value, '-')) {
1264 errno = EINVAL;
1265 return 0;
1267 errno = 0;
1268 val = strtoumax(value, &end, 0);
1269 if (errno == ERANGE)
1270 return 0;
1271 if (end == value) {
1272 errno = EINVAL;
1273 return 0;
1275 factor = get_unit_factor(end);
1276 if (!factor) {
1277 errno = EINVAL;
1278 return 0;
1280 if (unsigned_mult_overflows(factor, val) ||
1281 factor * val > max) {
1282 errno = ERANGE;
1283 return 0;
1285 val *= factor;
1286 *ret = val;
1287 return 1;
1289 errno = EINVAL;
1290 return 0;
1293 int git_parse_int(const char *value, int *ret)
1295 intmax_t tmp;
1296 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
1297 return 0;
1298 *ret = tmp;
1299 return 1;
1302 static int git_parse_int64(const char *value, int64_t *ret)
1304 intmax_t tmp;
1305 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
1306 return 0;
1307 *ret = tmp;
1308 return 1;
1311 int git_parse_ulong(const char *value, unsigned long *ret)
1313 uintmax_t tmp;
1314 if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
1315 return 0;
1316 *ret = tmp;
1317 return 1;
1320 int git_parse_ssize_t(const char *value, ssize_t *ret)
1322 intmax_t tmp;
1323 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(ssize_t)))
1324 return 0;
1325 *ret = tmp;
1326 return 1;
1329 static int reader_config_name(struct config_reader *reader, const char **out);
1330 static int reader_origin_type(struct config_reader *reader,
1331 enum config_origin_type *type);
1332 NORETURN
1333 static void die_bad_number(struct config_reader *reader, const char *name,
1334 const char *value)
1336 const char *error_type = (errno == ERANGE) ?
1337 N_("out of range") : N_("invalid unit");
1338 const char *bad_numeric = N_("bad numeric config value '%s' for '%s': %s");
1339 const char *config_name = NULL;
1340 enum config_origin_type config_origin = CONFIG_ORIGIN_UNKNOWN;
1342 if (!value)
1343 value = "";
1345 /* Ignoring the return value is okay since we handle missing values. */
1346 reader_config_name(reader, &config_name);
1347 reader_origin_type(reader, &config_origin);
1349 if (!config_name)
1350 die(_(bad_numeric), value, name, _(error_type));
1352 switch (config_origin) {
1353 case CONFIG_ORIGIN_BLOB:
1354 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
1355 value, name, config_name, _(error_type));
1356 case CONFIG_ORIGIN_FILE:
1357 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
1358 value, name, config_name, _(error_type));
1359 case CONFIG_ORIGIN_STDIN:
1360 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
1361 value, name, _(error_type));
1362 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1363 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
1364 value, name, config_name, _(error_type));
1365 case CONFIG_ORIGIN_CMDLINE:
1366 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
1367 value, name, config_name, _(error_type));
1368 default:
1369 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
1370 value, name, config_name, _(error_type));
1374 int git_config_int(const char *name, const char *value)
1376 int ret;
1377 if (!git_parse_int(value, &ret))
1378 die_bad_number(&the_reader, name, value);
1379 return ret;
1382 int64_t git_config_int64(const char *name, const char *value)
1384 int64_t ret;
1385 if (!git_parse_int64(value, &ret))
1386 die_bad_number(&the_reader, name, value);
1387 return ret;
1390 unsigned long git_config_ulong(const char *name, const char *value)
1392 unsigned long ret;
1393 if (!git_parse_ulong(value, &ret))
1394 die_bad_number(&the_reader, name, value);
1395 return ret;
1398 ssize_t git_config_ssize_t(const char *name, const char *value)
1400 ssize_t ret;
1401 if (!git_parse_ssize_t(value, &ret))
1402 die_bad_number(&the_reader, name, value);
1403 return ret;
1406 static int git_parse_maybe_bool_text(const char *value)
1408 if (!value)
1409 return 1;
1410 if (!*value)
1411 return 0;
1412 if (!strcasecmp(value, "true")
1413 || !strcasecmp(value, "yes")
1414 || !strcasecmp(value, "on"))
1415 return 1;
1416 if (!strcasecmp(value, "false")
1417 || !strcasecmp(value, "no")
1418 || !strcasecmp(value, "off"))
1419 return 0;
1420 return -1;
1423 static const struct fsync_component_name {
1424 const char *name;
1425 enum fsync_component component_bits;
1426 } fsync_component_names[] = {
1427 { "loose-object", FSYNC_COMPONENT_LOOSE_OBJECT },
1428 { "pack", FSYNC_COMPONENT_PACK },
1429 { "pack-metadata", FSYNC_COMPONENT_PACK_METADATA },
1430 { "commit-graph", FSYNC_COMPONENT_COMMIT_GRAPH },
1431 { "index", FSYNC_COMPONENT_INDEX },
1432 { "objects", FSYNC_COMPONENTS_OBJECTS },
1433 { "reference", FSYNC_COMPONENT_REFERENCE },
1434 { "derived-metadata", FSYNC_COMPONENTS_DERIVED_METADATA },
1435 { "committed", FSYNC_COMPONENTS_COMMITTED },
1436 { "added", FSYNC_COMPONENTS_ADDED },
1437 { "all", FSYNC_COMPONENTS_ALL },
1440 static enum fsync_component parse_fsync_components(const char *var, const char *string)
1442 enum fsync_component current = FSYNC_COMPONENTS_PLATFORM_DEFAULT;
1443 enum fsync_component positive = 0, negative = 0;
1445 while (string) {
1446 int i;
1447 size_t len;
1448 const char *ep;
1449 int negated = 0;
1450 int found = 0;
1452 string = string + strspn(string, ", \t\n\r");
1453 ep = strchrnul(string, ',');
1454 len = ep - string;
1455 if (!strcmp(string, "none")) {
1456 current = FSYNC_COMPONENT_NONE;
1457 goto next_name;
1460 if (*string == '-') {
1461 negated = 1;
1462 string++;
1463 len--;
1464 if (!len)
1465 warning(_("invalid value for variable %s"), var);
1468 if (!len)
1469 break;
1471 for (i = 0; i < ARRAY_SIZE(fsync_component_names); ++i) {
1472 const struct fsync_component_name *n = &fsync_component_names[i];
1474 if (strncmp(n->name, string, len))
1475 continue;
1477 found = 1;
1478 if (negated)
1479 negative |= n->component_bits;
1480 else
1481 positive |= n->component_bits;
1484 if (!found) {
1485 char *component = xstrndup(string, len);
1486 warning(_("ignoring unknown core.fsync component '%s'"), component);
1487 free(component);
1490 next_name:
1491 string = ep;
1494 return (current & ~negative) | positive;
1497 int git_parse_maybe_bool(const char *value)
1499 int v = git_parse_maybe_bool_text(value);
1500 if (0 <= v)
1501 return v;
1502 if (git_parse_int(value, &v))
1503 return !!v;
1504 return -1;
1507 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
1509 int v = git_parse_maybe_bool_text(value);
1510 if (0 <= v) {
1511 *is_bool = 1;
1512 return v;
1514 *is_bool = 0;
1515 return git_config_int(name, value);
1518 int git_config_bool(const char *name, const char *value)
1520 int v = git_parse_maybe_bool(value);
1521 if (v < 0)
1522 die(_("bad boolean config value '%s' for '%s'"), value, name);
1523 return v;
1526 int git_config_string(const char **dest, const char *var, const char *value)
1528 if (!value)
1529 return config_error_nonbool(var);
1530 *dest = xstrdup(value);
1531 return 0;
1534 int git_config_pathname(const char **dest, const char *var, const char *value)
1536 if (!value)
1537 return config_error_nonbool(var);
1538 *dest = interpolate_path(value, 0);
1539 if (!*dest)
1540 die(_("failed to expand user dir in: '%s'"), value);
1541 return 0;
1544 int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1546 if (!value)
1547 return config_error_nonbool(var);
1548 if (parse_expiry_date(value, timestamp))
1549 return error(_("'%s' for '%s' is not a valid timestamp"),
1550 value, var);
1551 return 0;
1554 int git_config_color(char *dest, const char *var, const char *value)
1556 if (!value)
1557 return config_error_nonbool(var);
1558 if (color_parse(value, dest) < 0)
1559 return -1;
1560 return 0;
1563 static int git_default_core_config(const char *var, const char *value, void *cb)
1565 /* This needs a better name */
1566 if (!strcmp(var, "core.filemode")) {
1567 trust_executable_bit = git_config_bool(var, value);
1568 return 0;
1570 if (!strcmp(var, "core.trustctime")) {
1571 trust_ctime = git_config_bool(var, value);
1572 return 0;
1574 if (!strcmp(var, "core.checkstat")) {
1575 if (!strcasecmp(value, "default"))
1576 check_stat = 1;
1577 else if (!strcasecmp(value, "minimal"))
1578 check_stat = 0;
1581 if (!strcmp(var, "core.quotepath")) {
1582 quote_path_fully = git_config_bool(var, value);
1583 return 0;
1586 if (!strcmp(var, "core.symlinks")) {
1587 has_symlinks = git_config_bool(var, value);
1588 return 0;
1591 if (!strcmp(var, "core.ignorecase")) {
1592 ignore_case = git_config_bool(var, value);
1593 return 0;
1596 if (!strcmp(var, "core.attributesfile"))
1597 return git_config_pathname(&git_attributes_file, var, value);
1599 if (!strcmp(var, "core.hookspath"))
1600 return git_config_pathname(&git_hooks_path, var, value);
1602 if (!strcmp(var, "core.bare")) {
1603 is_bare_repository_cfg = git_config_bool(var, value);
1604 return 0;
1607 if (!strcmp(var, "core.ignorestat")) {
1608 assume_unchanged = git_config_bool(var, value);
1609 return 0;
1612 if (!strcmp(var, "core.prefersymlinkrefs")) {
1613 prefer_symlink_refs = git_config_bool(var, value);
1614 return 0;
1617 if (!strcmp(var, "core.logallrefupdates")) {
1618 if (value && !strcasecmp(value, "always"))
1619 log_all_ref_updates = LOG_REFS_ALWAYS;
1620 else if (git_config_bool(var, value))
1621 log_all_ref_updates = LOG_REFS_NORMAL;
1622 else
1623 log_all_ref_updates = LOG_REFS_NONE;
1624 return 0;
1627 if (!strcmp(var, "core.warnambiguousrefs")) {
1628 warn_ambiguous_refs = git_config_bool(var, value);
1629 return 0;
1632 if (!strcmp(var, "core.abbrev")) {
1633 if (!value)
1634 return config_error_nonbool(var);
1635 if (!strcasecmp(value, "auto"))
1636 default_abbrev = -1;
1637 else if (!git_parse_maybe_bool_text(value))
1638 default_abbrev = the_hash_algo->hexsz;
1639 else {
1640 int abbrev = git_config_int(var, value);
1641 if (abbrev < minimum_abbrev || abbrev > the_hash_algo->hexsz)
1642 return error(_("abbrev length out of range: %d"), abbrev);
1643 default_abbrev = abbrev;
1645 return 0;
1648 if (!strcmp(var, "core.disambiguate"))
1649 return set_disambiguate_hint_config(var, value);
1651 if (!strcmp(var, "core.loosecompression")) {
1652 int level = git_config_int(var, value);
1653 if (level == -1)
1654 level = Z_DEFAULT_COMPRESSION;
1655 else if (level < 0 || level > Z_BEST_COMPRESSION)
1656 die(_("bad zlib compression level %d"), level);
1657 zlib_compression_level = level;
1658 zlib_compression_seen = 1;
1659 return 0;
1662 if (!strcmp(var, "core.compression")) {
1663 int level = git_config_int(var, value);
1664 if (level == -1)
1665 level = Z_DEFAULT_COMPRESSION;
1666 else if (level < 0 || level > Z_BEST_COMPRESSION)
1667 die(_("bad zlib compression level %d"), level);
1668 if (!zlib_compression_seen)
1669 zlib_compression_level = level;
1670 if (!pack_compression_seen)
1671 pack_compression_level = level;
1672 return 0;
1675 if (!strcmp(var, "core.packedgitwindowsize")) {
1676 int pgsz_x2 = getpagesize() * 2;
1677 packed_git_window_size = git_config_ulong(var, value);
1679 /* This value must be multiple of (pagesize * 2) */
1680 packed_git_window_size /= pgsz_x2;
1681 if (packed_git_window_size < 1)
1682 packed_git_window_size = 1;
1683 packed_git_window_size *= pgsz_x2;
1684 return 0;
1687 if (!strcmp(var, "core.bigfilethreshold")) {
1688 big_file_threshold = git_config_ulong(var, value);
1689 return 0;
1692 if (!strcmp(var, "core.packedgitlimit")) {
1693 packed_git_limit = git_config_ulong(var, value);
1694 return 0;
1697 if (!strcmp(var, "core.deltabasecachelimit")) {
1698 delta_base_cache_limit = git_config_ulong(var, value);
1699 return 0;
1702 if (!strcmp(var, "core.autocrlf")) {
1703 if (value && !strcasecmp(value, "input")) {
1704 auto_crlf = AUTO_CRLF_INPUT;
1705 return 0;
1707 auto_crlf = git_config_bool(var, value);
1708 return 0;
1711 if (!strcmp(var, "core.safecrlf")) {
1712 int eol_rndtrp_die;
1713 if (value && !strcasecmp(value, "warn")) {
1714 global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
1715 return 0;
1717 eol_rndtrp_die = git_config_bool(var, value);
1718 global_conv_flags_eol = eol_rndtrp_die ?
1719 CONV_EOL_RNDTRP_DIE : 0;
1720 return 0;
1723 if (!strcmp(var, "core.eol")) {
1724 if (value && !strcasecmp(value, "lf"))
1725 core_eol = EOL_LF;
1726 else if (value && !strcasecmp(value, "crlf"))
1727 core_eol = EOL_CRLF;
1728 else if (value && !strcasecmp(value, "native"))
1729 core_eol = EOL_NATIVE;
1730 else
1731 core_eol = EOL_UNSET;
1732 return 0;
1735 if (!strcmp(var, "core.checkroundtripencoding")) {
1736 check_roundtrip_encoding = xstrdup(value);
1737 return 0;
1740 if (!strcmp(var, "core.notesref")) {
1741 notes_ref_name = xstrdup(value);
1742 return 0;
1745 if (!strcmp(var, "core.editor"))
1746 return git_config_string(&editor_program, var, value);
1748 if (!strcmp(var, "core.commentchar")) {
1749 if (!value)
1750 return config_error_nonbool(var);
1751 else if (!strcasecmp(value, "auto"))
1752 auto_comment_line_char = 1;
1753 else if (value[0] && !value[1]) {
1754 comment_line_char = value[0];
1755 auto_comment_line_char = 0;
1756 } else
1757 return error(_("core.commentChar should only be one ASCII character"));
1758 return 0;
1761 if (!strcmp(var, "core.askpass"))
1762 return git_config_string(&askpass_program, var, value);
1764 if (!strcmp(var, "core.excludesfile"))
1765 return git_config_pathname(&excludes_file, var, value);
1767 if (!strcmp(var, "core.whitespace")) {
1768 if (!value)
1769 return config_error_nonbool(var);
1770 whitespace_rule_cfg = parse_whitespace_rule(value);
1771 return 0;
1774 if (!strcmp(var, "core.fsync")) {
1775 if (!value)
1776 return config_error_nonbool(var);
1777 fsync_components = parse_fsync_components(var, value);
1778 return 0;
1781 if (!strcmp(var, "core.fsyncmethod")) {
1782 if (!value)
1783 return config_error_nonbool(var);
1784 if (!strcmp(value, "fsync"))
1785 fsync_method = FSYNC_METHOD_FSYNC;
1786 else if (!strcmp(value, "writeout-only"))
1787 fsync_method = FSYNC_METHOD_WRITEOUT_ONLY;
1788 else if (!strcmp(value, "batch"))
1789 fsync_method = FSYNC_METHOD_BATCH;
1790 else
1791 warning(_("ignoring unknown core.fsyncMethod value '%s'"), value);
1795 if (!strcmp(var, "core.fsyncobjectfiles")) {
1796 if (fsync_object_files < 0)
1797 warning(_("core.fsyncObjectFiles is deprecated; use core.fsync instead"));
1798 fsync_object_files = git_config_bool(var, value);
1799 return 0;
1802 if (!strcmp(var, "core.preloadindex")) {
1803 core_preload_index = git_config_bool(var, value);
1804 return 0;
1807 if (!strcmp(var, "core.createobject")) {
1808 if (!strcmp(value, "rename"))
1809 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
1810 else if (!strcmp(value, "link"))
1811 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
1812 else
1813 die(_("invalid mode for object creation: %s"), value);
1814 return 0;
1817 if (!strcmp(var, "core.sparsecheckout")) {
1818 core_apply_sparse_checkout = git_config_bool(var, value);
1819 return 0;
1822 if (!strcmp(var, "core.sparsecheckoutcone")) {
1823 core_sparse_checkout_cone = git_config_bool(var, value);
1824 return 0;
1827 if (!strcmp(var, "core.precomposeunicode")) {
1828 precomposed_unicode = git_config_bool(var, value);
1829 return 0;
1832 if (!strcmp(var, "core.protecthfs")) {
1833 protect_hfs = git_config_bool(var, value);
1834 return 0;
1837 if (!strcmp(var, "core.protectntfs")) {
1838 protect_ntfs = git_config_bool(var, value);
1839 return 0;
1842 if (!strcmp(var, "core.usereplacerefs")) {
1843 read_replace_refs = git_config_bool(var, value);
1844 return 0;
1847 /* Add other config variables here and to Documentation/config.txt. */
1848 return platform_core_config(var, value, cb);
1851 static int git_default_sparse_config(const char *var, const char *value)
1853 if (!strcmp(var, "sparse.expectfilesoutsideofpatterns")) {
1854 sparse_expect_files_outside_of_patterns = git_config_bool(var, value);
1855 return 0;
1858 /* Add other config variables here and to Documentation/config/sparse.txt. */
1859 return 0;
1862 static int git_default_i18n_config(const char *var, const char *value)
1864 if (!strcmp(var, "i18n.commitencoding"))
1865 return git_config_string(&git_commit_encoding, var, value);
1867 if (!strcmp(var, "i18n.logoutputencoding"))
1868 return git_config_string(&git_log_output_encoding, var, value);
1870 /* Add other config variables here and to Documentation/config.txt. */
1871 return 0;
1874 static int git_default_branch_config(const char *var, const char *value)
1876 if (!strcmp(var, "branch.autosetupmerge")) {
1877 if (value && !strcmp(value, "always")) {
1878 git_branch_track = BRANCH_TRACK_ALWAYS;
1879 return 0;
1880 } else if (value && !strcmp(value, "inherit")) {
1881 git_branch_track = BRANCH_TRACK_INHERIT;
1882 return 0;
1883 } else if (value && !strcmp(value, "simple")) {
1884 git_branch_track = BRANCH_TRACK_SIMPLE;
1885 return 0;
1887 git_branch_track = git_config_bool(var, value);
1888 return 0;
1890 if (!strcmp(var, "branch.autosetuprebase")) {
1891 if (!value)
1892 return config_error_nonbool(var);
1893 else if (!strcmp(value, "never"))
1894 autorebase = AUTOREBASE_NEVER;
1895 else if (!strcmp(value, "local"))
1896 autorebase = AUTOREBASE_LOCAL;
1897 else if (!strcmp(value, "remote"))
1898 autorebase = AUTOREBASE_REMOTE;
1899 else if (!strcmp(value, "always"))
1900 autorebase = AUTOREBASE_ALWAYS;
1901 else
1902 return error(_("malformed value for %s"), var);
1903 return 0;
1906 /* Add other config variables here and to Documentation/config.txt. */
1907 return 0;
1910 static int git_default_push_config(const char *var, const char *value)
1912 if (!strcmp(var, "push.default")) {
1913 if (!value)
1914 return config_error_nonbool(var);
1915 else if (!strcmp(value, "nothing"))
1916 push_default = PUSH_DEFAULT_NOTHING;
1917 else if (!strcmp(value, "matching"))
1918 push_default = PUSH_DEFAULT_MATCHING;
1919 else if (!strcmp(value, "simple"))
1920 push_default = PUSH_DEFAULT_SIMPLE;
1921 else if (!strcmp(value, "upstream"))
1922 push_default = PUSH_DEFAULT_UPSTREAM;
1923 else if (!strcmp(value, "tracking")) /* deprecated */
1924 push_default = PUSH_DEFAULT_UPSTREAM;
1925 else if (!strcmp(value, "current"))
1926 push_default = PUSH_DEFAULT_CURRENT;
1927 else {
1928 error(_("malformed value for %s: %s"), var, value);
1929 return error(_("must be one of nothing, matching, simple, "
1930 "upstream or current"));
1932 return 0;
1935 /* Add other config variables here and to Documentation/config.txt. */
1936 return 0;
1939 static int git_default_mailmap_config(const char *var, const char *value)
1941 if (!strcmp(var, "mailmap.file"))
1942 return git_config_pathname(&git_mailmap_file, var, value);
1943 if (!strcmp(var, "mailmap.blob"))
1944 return git_config_string(&git_mailmap_blob, var, value);
1946 /* Add other config variables here and to Documentation/config.txt. */
1947 return 0;
1950 int git_default_config(const char *var, const char *value, void *cb)
1952 if (starts_with(var, "core."))
1953 return git_default_core_config(var, value, cb);
1955 if (starts_with(var, "user.") ||
1956 starts_with(var, "author.") ||
1957 starts_with(var, "committer."))
1958 return git_ident_config(var, value, cb);
1960 if (starts_with(var, "i18n."))
1961 return git_default_i18n_config(var, value);
1963 if (starts_with(var, "branch."))
1964 return git_default_branch_config(var, value);
1966 if (starts_with(var, "push."))
1967 return git_default_push_config(var, value);
1969 if (starts_with(var, "mailmap."))
1970 return git_default_mailmap_config(var, value);
1972 if (starts_with(var, "advice.") || starts_with(var, "color.advice"))
1973 return git_default_advice_config(var, value);
1975 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1976 pager_use_color = git_config_bool(var,value);
1977 return 0;
1980 if (!strcmp(var, "pack.packsizelimit")) {
1981 pack_size_limit_cfg = git_config_ulong(var, value);
1982 return 0;
1985 if (!strcmp(var, "pack.compression")) {
1986 int level = git_config_int(var, value);
1987 if (level == -1)
1988 level = Z_DEFAULT_COMPRESSION;
1989 else if (level < 0 || level > Z_BEST_COMPRESSION)
1990 die(_("bad pack compression level %d"), level);
1991 pack_compression_level = level;
1992 pack_compression_seen = 1;
1993 return 0;
1996 if (starts_with(var, "sparse."))
1997 return git_default_sparse_config(var, value);
1999 /* Add other config variables here and to Documentation/config.txt. */
2000 return 0;
2004 * All source specific fields in the union, die_on_error, name and the callbacks
2005 * fgetc, ungetc, ftell of top need to be initialized before calling
2006 * this function.
2008 static int do_config_from(struct config_reader *reader,
2009 struct config_source *top, config_fn_t fn, void *data,
2010 const struct config_options *opts)
2012 int ret;
2014 /* push config-file parsing state stack */
2015 top->linenr = 1;
2016 top->eof = 0;
2017 top->total_len = 0;
2018 strbuf_init(&top->value, 1024);
2019 strbuf_init(&top->var, 1024);
2020 config_reader_push_source(reader, top);
2022 ret = git_parse_source(top, fn, data, opts);
2024 /* pop config-file parsing state stack */
2025 strbuf_release(&top->value);
2026 strbuf_release(&top->var);
2027 config_reader_pop_source(reader);
2029 return ret;
2032 static int do_config_from_file(struct config_reader *reader,
2033 config_fn_t fn,
2034 const enum config_origin_type origin_type,
2035 const char *name, const char *path, FILE *f,
2036 void *data, const struct config_options *opts)
2038 struct config_source top = CONFIG_SOURCE_INIT;
2039 int ret;
2041 top.u.file = f;
2042 top.origin_type = origin_type;
2043 top.name = name;
2044 top.path = path;
2045 top.default_error_action = CONFIG_ERROR_DIE;
2046 top.do_fgetc = config_file_fgetc;
2047 top.do_ungetc = config_file_ungetc;
2048 top.do_ftell = config_file_ftell;
2050 flockfile(f);
2051 ret = do_config_from(reader, &top, fn, data, opts);
2052 funlockfile(f);
2053 return ret;
2056 static int git_config_from_stdin(config_fn_t fn, void *data)
2058 return do_config_from_file(&the_reader, fn, CONFIG_ORIGIN_STDIN, "",
2059 NULL, stdin, data, NULL);
2062 int git_config_from_file_with_options(config_fn_t fn, const char *filename,
2063 void *data,
2064 const struct config_options *opts)
2066 int ret = -1;
2067 FILE *f;
2069 if (!filename)
2070 BUG("filename cannot be NULL");
2071 f = fopen_or_warn(filename, "r");
2072 if (f) {
2073 ret = do_config_from_file(&the_reader, fn, CONFIG_ORIGIN_FILE,
2074 filename, filename, f, data, opts);
2075 fclose(f);
2077 return ret;
2080 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
2082 return git_config_from_file_with_options(fn, filename, data, NULL);
2085 int git_config_from_mem(config_fn_t fn,
2086 const enum config_origin_type origin_type,
2087 const char *name, const char *buf, size_t len,
2088 void *data, const struct config_options *opts)
2090 struct config_source top = CONFIG_SOURCE_INIT;
2092 top.u.buf.buf = buf;
2093 top.u.buf.len = len;
2094 top.u.buf.pos = 0;
2095 top.origin_type = origin_type;
2096 top.name = name;
2097 top.path = NULL;
2098 top.default_error_action = CONFIG_ERROR_ERROR;
2099 top.do_fgetc = config_buf_fgetc;
2100 top.do_ungetc = config_buf_ungetc;
2101 top.do_ftell = config_buf_ftell;
2103 return do_config_from(&the_reader, &top, fn, data, opts);
2106 int git_config_from_blob_oid(config_fn_t fn,
2107 const char *name,
2108 struct repository *repo,
2109 const struct object_id *oid,
2110 void *data)
2112 enum object_type type;
2113 char *buf;
2114 unsigned long size;
2115 int ret;
2117 buf = repo_read_object_file(repo, oid, &type, &size);
2118 if (!buf)
2119 return error(_("unable to load config blob object '%s'"), name);
2120 if (type != OBJ_BLOB) {
2121 free(buf);
2122 return error(_("reference '%s' does not point to a blob"), name);
2125 ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size,
2126 data, NULL);
2127 free(buf);
2129 return ret;
2132 static int git_config_from_blob_ref(config_fn_t fn,
2133 struct repository *repo,
2134 const char *name,
2135 void *data)
2137 struct object_id oid;
2139 if (repo_get_oid(repo, name, &oid) < 0)
2140 return error(_("unable to resolve config blob '%s'"), name);
2141 return git_config_from_blob_oid(fn, name, repo, &oid, data);
2144 char *git_system_config(void)
2146 char *system_config = xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
2147 if (!system_config)
2148 system_config = system_path(ETC_GITCONFIG);
2149 normalize_path_copy(system_config, system_config);
2150 return system_config;
2153 void git_global_config(char **user_out, char **xdg_out)
2155 char *user_config = xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
2156 char *xdg_config = NULL;
2158 if (!user_config) {
2159 user_config = interpolate_path("~/.gitconfig", 0);
2160 xdg_config = xdg_config_home("config");
2163 *user_out = user_config;
2164 *xdg_out = xdg_config;
2168 * Parse environment variable 'k' as a boolean (in various
2169 * possible spellings); if missing, use the default value 'def'.
2171 int git_env_bool(const char *k, int def)
2173 const char *v = getenv(k);
2174 return v ? git_config_bool(k, v) : def;
2178 * Parse environment variable 'k' as ulong with possibly a unit
2179 * suffix; if missing, use the default value 'val'.
2181 unsigned long git_env_ulong(const char *k, unsigned long val)
2183 const char *v = getenv(k);
2184 if (v && !git_parse_ulong(v, &val))
2185 die(_("failed to parse %s"), k);
2186 return val;
2189 int git_config_system(void)
2191 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
2194 static int do_git_config_sequence(struct config_reader *reader,
2195 const struct config_options *opts,
2196 config_fn_t fn, void *data)
2198 int ret = 0;
2199 char *system_config = git_system_config();
2200 char *xdg_config = NULL;
2201 char *user_config = NULL;
2202 char *repo_config;
2203 enum config_scope prev_parsing_scope = reader->parsing_scope;
2205 if (opts->commondir)
2206 repo_config = mkpathdup("%s/config", opts->commondir);
2207 else if (opts->git_dir)
2208 BUG("git_dir without commondir");
2209 else
2210 repo_config = NULL;
2212 config_reader_set_scope(reader, CONFIG_SCOPE_SYSTEM);
2213 if (git_config_system() && system_config &&
2214 !access_or_die(system_config, R_OK,
2215 opts->system_gently ? ACCESS_EACCES_OK : 0))
2216 ret += git_config_from_file(fn, system_config, data);
2218 config_reader_set_scope(reader, CONFIG_SCOPE_GLOBAL);
2219 git_global_config(&user_config, &xdg_config);
2221 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
2222 ret += git_config_from_file(fn, xdg_config, data);
2224 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
2225 ret += git_config_from_file(fn, user_config, data);
2227 config_reader_set_scope(reader, CONFIG_SCOPE_LOCAL);
2228 if (!opts->ignore_repo && repo_config &&
2229 !access_or_die(repo_config, R_OK, 0))
2230 ret += git_config_from_file(fn, repo_config, data);
2232 config_reader_set_scope(reader, CONFIG_SCOPE_WORKTREE);
2233 if (!opts->ignore_worktree && repository_format_worktree_config) {
2234 char *path = git_pathdup("config.worktree");
2235 if (!access_or_die(path, R_OK, 0))
2236 ret += git_config_from_file(fn, path, data);
2237 free(path);
2240 config_reader_set_scope(reader, CONFIG_SCOPE_COMMAND);
2241 if (!opts->ignore_cmdline && git_config_from_parameters(fn, data) < 0)
2242 die(_("unable to parse command-line config"));
2244 config_reader_set_scope(reader, prev_parsing_scope);
2245 free(system_config);
2246 free(xdg_config);
2247 free(user_config);
2248 free(repo_config);
2249 return ret;
2252 int config_with_options(config_fn_t fn, void *data,
2253 struct git_config_source *config_source,
2254 const struct config_options *opts)
2256 struct config_include_data inc = CONFIG_INCLUDE_INIT;
2257 enum config_scope prev_scope = the_reader.parsing_scope;
2258 int ret;
2260 if (opts->respect_includes) {
2261 inc.fn = fn;
2262 inc.data = data;
2263 inc.opts = opts;
2264 inc.config_source = config_source;
2265 inc.config_reader = &the_reader;
2266 fn = git_config_include;
2267 data = &inc;
2270 if (config_source)
2271 config_reader_set_scope(&the_reader, config_source->scope);
2274 * If we have a specific filename, use it. Otherwise, follow the
2275 * regular lookup sequence.
2277 if (config_source && config_source->use_stdin) {
2278 ret = git_config_from_stdin(fn, data);
2279 } else if (config_source && config_source->file) {
2280 ret = git_config_from_file(fn, config_source->file, data);
2281 } else if (config_source && config_source->blob) {
2282 struct repository *repo = config_source->repo ?
2283 config_source->repo : the_repository;
2284 ret = git_config_from_blob_ref(fn, repo, config_source->blob,
2285 data);
2286 } else {
2287 ret = do_git_config_sequence(&the_reader, opts, fn, data);
2290 if (inc.remote_urls) {
2291 string_list_clear(inc.remote_urls, 0);
2292 FREE_AND_NULL(inc.remote_urls);
2294 config_reader_set_scope(&the_reader, prev_scope);
2295 return ret;
2298 static void configset_iter(struct config_reader *reader, struct config_set *set,
2299 config_fn_t fn, void *data)
2301 int i, value_index;
2302 struct string_list *values;
2303 struct config_set_element *entry;
2304 struct configset_list *list = &set->list;
2306 for (i = 0; i < list->nr; i++) {
2307 entry = list->items[i].e;
2308 value_index = list->items[i].value_index;
2309 values = &entry->value_list;
2311 config_reader_set_kvi(reader, values->items[value_index].util);
2313 if (fn(entry->key, values->items[value_index].string, data) < 0)
2314 git_die_config_linenr(entry->key,
2315 reader->config_kvi->filename,
2316 reader->config_kvi->linenr);
2318 config_reader_set_kvi(reader, NULL);
2322 void read_early_config(config_fn_t cb, void *data)
2324 struct config_options opts = {0};
2325 struct strbuf commondir = STRBUF_INIT;
2326 struct strbuf gitdir = STRBUF_INIT;
2328 opts.respect_includes = 1;
2330 if (have_git_dir()) {
2331 opts.commondir = get_git_common_dir();
2332 opts.git_dir = get_git_dir();
2334 * When setup_git_directory() was not yet asked to discover the
2335 * GIT_DIR, we ask discover_git_directory() to figure out whether there
2336 * is any repository config we should use (but unlike
2337 * setup_git_directory_gently(), no global state is changed, most
2338 * notably, the current working directory is still the same after the
2339 * call).
2341 } else if (!discover_git_directory(&commondir, &gitdir)) {
2342 opts.commondir = commondir.buf;
2343 opts.git_dir = gitdir.buf;
2346 config_with_options(cb, data, NULL, &opts);
2348 strbuf_release(&commondir);
2349 strbuf_release(&gitdir);
2353 * Read config but only enumerate system and global settings.
2354 * Omit any repo-local, worktree-local, or command-line settings.
2356 void read_very_early_config(config_fn_t cb, void *data)
2358 struct config_options opts = { 0 };
2360 opts.respect_includes = 1;
2361 opts.ignore_repo = 1;
2362 opts.ignore_worktree = 1;
2363 opts.ignore_cmdline = 1;
2364 opts.system_gently = 1;
2366 config_with_options(cb, data, NULL, &opts);
2369 RESULT_MUST_BE_USED
2370 static int configset_find_element(struct config_set *set, const char *key,
2371 struct config_set_element **dest)
2373 struct config_set_element k;
2374 struct config_set_element *found_entry;
2375 char *normalized_key;
2376 int ret;
2379 * `key` may come from the user, so normalize it before using it
2380 * for querying entries from the hashmap.
2382 ret = git_config_parse_key(key, &normalized_key, NULL);
2383 if (ret)
2384 return ret;
2386 hashmap_entry_init(&k.ent, strhash(normalized_key));
2387 k.key = normalized_key;
2388 found_entry = hashmap_get_entry(&set->config_hash, &k, ent, NULL);
2389 free(normalized_key);
2390 *dest = found_entry;
2391 return 0;
2394 static int configset_add_value(struct config_reader *reader,
2395 struct config_set *set, const char *key,
2396 const char *value)
2398 struct config_set_element *e;
2399 struct string_list_item *si;
2400 struct configset_list_item *l_item;
2401 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
2402 int ret;
2404 ret = configset_find_element(set, key, &e);
2405 if (ret)
2406 return ret;
2408 * Since the keys are being fed by git_config*() callback mechanism, they
2409 * are already normalized. So simply add them without any further munging.
2411 if (!e) {
2412 e = xmalloc(sizeof(*e));
2413 hashmap_entry_init(&e->ent, strhash(key));
2414 e->key = xstrdup(key);
2415 string_list_init_dup(&e->value_list);
2416 hashmap_add(&set->config_hash, &e->ent);
2418 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
2420 ALLOC_GROW(set->list.items, set->list.nr + 1, set->list.alloc);
2421 l_item = &set->list.items[set->list.nr++];
2422 l_item->e = e;
2423 l_item->value_index = e->value_list.nr - 1;
2425 if (!reader->source)
2426 BUG("configset_add_value has no source");
2427 if (reader->source->name) {
2428 kv_info->filename = strintern(reader->source->name);
2429 kv_info->linenr = reader->source->linenr;
2430 kv_info->origin_type = reader->source->origin_type;
2431 } else {
2432 /* for values read from `git_config_from_parameters()` */
2433 kv_info->filename = NULL;
2434 kv_info->linenr = -1;
2435 kv_info->origin_type = CONFIG_ORIGIN_CMDLINE;
2437 kv_info->scope = reader->parsing_scope;
2438 si->util = kv_info;
2440 return 0;
2443 static int config_set_element_cmp(const void *cmp_data UNUSED,
2444 const struct hashmap_entry *eptr,
2445 const struct hashmap_entry *entry_or_key,
2446 const void *keydata UNUSED)
2448 const struct config_set_element *e1, *e2;
2450 e1 = container_of(eptr, const struct config_set_element, ent);
2451 e2 = container_of(entry_or_key, const struct config_set_element, ent);
2453 return strcmp(e1->key, e2->key);
2456 void git_configset_init(struct config_set *set)
2458 hashmap_init(&set->config_hash, config_set_element_cmp, NULL, 0);
2459 set->hash_initialized = 1;
2460 set->list.nr = 0;
2461 set->list.alloc = 0;
2462 set->list.items = NULL;
2465 void git_configset_clear(struct config_set *set)
2467 struct config_set_element *entry;
2468 struct hashmap_iter iter;
2469 if (!set->hash_initialized)
2470 return;
2472 hashmap_for_each_entry(&set->config_hash, &iter, entry,
2473 ent /* member name */) {
2474 free(entry->key);
2475 string_list_clear(&entry->value_list, 1);
2477 hashmap_clear_and_free(&set->config_hash, struct config_set_element, ent);
2478 set->hash_initialized = 0;
2479 free(set->list.items);
2480 set->list.nr = 0;
2481 set->list.alloc = 0;
2482 set->list.items = NULL;
2485 struct configset_add_data {
2486 struct config_set *config_set;
2487 struct config_reader *config_reader;
2489 #define CONFIGSET_ADD_INIT { 0 }
2491 static int config_set_callback(const char *key, const char *value, void *cb)
2493 struct configset_add_data *data = cb;
2494 configset_add_value(data->config_reader, data->config_set, key, value);
2495 return 0;
2498 int git_configset_add_file(struct config_set *set, const char *filename)
2500 struct configset_add_data data = CONFIGSET_ADD_INIT;
2501 data.config_reader = &the_reader;
2502 data.config_set = set;
2503 return git_config_from_file(config_set_callback, filename, &data);
2506 int git_configset_get_value(struct config_set *set, const char *key, const char **value)
2508 const struct string_list *values = NULL;
2509 int ret;
2512 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
2513 * queried key in the files of the configset, the value returned will be the last
2514 * value in the value list for that key.
2516 if ((ret = git_configset_get_value_multi(set, key, &values)))
2517 return ret;
2519 assert(values->nr > 0);
2520 *value = values->items[values->nr - 1].string;
2521 return 0;
2524 int git_configset_get_value_multi(struct config_set *set, const char *key,
2525 const struct string_list **dest)
2527 struct config_set_element *e;
2528 int ret;
2530 if ((ret = configset_find_element(set, key, &e)))
2531 return ret;
2532 else if (!e)
2533 return 1;
2534 *dest = &e->value_list;
2536 return 0;
2539 static int check_multi_string(struct string_list_item *item, void *util)
2541 return item->string ? 0 : config_error_nonbool(util);
2544 int git_configset_get_string_multi(struct config_set *cs, const char *key,
2545 const struct string_list **dest)
2547 int ret;
2549 if ((ret = git_configset_get_value_multi(cs, key, dest)))
2550 return ret;
2551 if ((ret = for_each_string_list((struct string_list *)*dest,
2552 check_multi_string, (void *)key)))
2553 return ret;
2555 return 0;
2558 int git_configset_get(struct config_set *set, const char *key)
2560 struct config_set_element *e;
2561 int ret;
2563 if ((ret = configset_find_element(set, key, &e)))
2564 return ret;
2565 else if (!e)
2566 return 1;
2567 return 0;
2570 int git_configset_get_string(struct config_set *set, const char *key, char **dest)
2572 const char *value;
2573 if (!git_configset_get_value(set, key, &value))
2574 return git_config_string((const char **)dest, key, value);
2575 else
2576 return 1;
2579 static int git_configset_get_string_tmp(struct config_set *set, const char *key,
2580 const char **dest)
2582 const char *value;
2583 if (!git_configset_get_value(set, key, &value)) {
2584 if (!value)
2585 return config_error_nonbool(key);
2586 *dest = value;
2587 return 0;
2588 } else {
2589 return 1;
2593 int git_configset_get_int(struct config_set *set, const char *key, int *dest)
2595 const char *value;
2596 if (!git_configset_get_value(set, key, &value)) {
2597 *dest = git_config_int(key, value);
2598 return 0;
2599 } else
2600 return 1;
2603 int git_configset_get_ulong(struct config_set *set, const char *key, unsigned long *dest)
2605 const char *value;
2606 if (!git_configset_get_value(set, key, &value)) {
2607 *dest = git_config_ulong(key, value);
2608 return 0;
2609 } else
2610 return 1;
2613 int git_configset_get_bool(struct config_set *set, const char *key, int *dest)
2615 const char *value;
2616 if (!git_configset_get_value(set, key, &value)) {
2617 *dest = git_config_bool(key, value);
2618 return 0;
2619 } else
2620 return 1;
2623 int git_configset_get_bool_or_int(struct config_set *set, const char *key,
2624 int *is_bool, int *dest)
2626 const char *value;
2627 if (!git_configset_get_value(set, key, &value)) {
2628 *dest = git_config_bool_or_int(key, value, is_bool);
2629 return 0;
2630 } else
2631 return 1;
2634 int git_configset_get_maybe_bool(struct config_set *set, const char *key, int *dest)
2636 const char *value;
2637 if (!git_configset_get_value(set, key, &value)) {
2638 *dest = git_parse_maybe_bool(value);
2639 if (*dest == -1)
2640 return -1;
2641 return 0;
2642 } else
2643 return 1;
2646 int git_configset_get_pathname(struct config_set *set, const char *key, const char **dest)
2648 const char *value;
2649 if (!git_configset_get_value(set, key, &value))
2650 return git_config_pathname(dest, key, value);
2651 else
2652 return 1;
2655 /* Functions use to read configuration from a repository */
2656 static void repo_read_config(struct repository *repo)
2658 struct config_options opts = { 0 };
2659 struct configset_add_data data = CONFIGSET_ADD_INIT;
2661 opts.respect_includes = 1;
2662 opts.commondir = repo->commondir;
2663 opts.git_dir = repo->gitdir;
2665 if (!repo->config)
2666 CALLOC_ARRAY(repo->config, 1);
2667 else
2668 git_configset_clear(repo->config);
2670 git_configset_init(repo->config);
2671 data.config_set = repo->config;
2672 data.config_reader = &the_reader;
2674 if (config_with_options(config_set_callback, &data, NULL, &opts) < 0)
2676 * config_with_options() normally returns only
2677 * zero, as most errors are fatal, and
2678 * non-fatal potential errors are guarded by "if"
2679 * statements that are entered only when no error is
2680 * possible.
2682 * If we ever encounter a non-fatal error, it means
2683 * something went really wrong and we should stop
2684 * immediately.
2686 die(_("unknown error occurred while reading the configuration files"));
2689 static void git_config_check_init(struct repository *repo)
2691 if (repo->config && repo->config->hash_initialized)
2692 return;
2693 repo_read_config(repo);
2696 static void repo_config_clear(struct repository *repo)
2698 if (!repo->config || !repo->config->hash_initialized)
2699 return;
2700 git_configset_clear(repo->config);
2703 void repo_config(struct repository *repo, config_fn_t fn, void *data)
2705 git_config_check_init(repo);
2706 configset_iter(&the_reader, repo->config, fn, data);
2709 int repo_config_get(struct repository *repo, const char *key)
2711 git_config_check_init(repo);
2712 return git_configset_get(repo->config, key);
2715 int repo_config_get_value(struct repository *repo,
2716 const char *key, const char **value)
2718 git_config_check_init(repo);
2719 return git_configset_get_value(repo->config, key, value);
2722 int repo_config_get_value_multi(struct repository *repo, const char *key,
2723 const struct string_list **dest)
2725 git_config_check_init(repo);
2726 return git_configset_get_value_multi(repo->config, key, dest);
2729 int repo_config_get_string_multi(struct repository *repo, const char *key,
2730 const struct string_list **dest)
2732 git_config_check_init(repo);
2733 return git_configset_get_string_multi(repo->config, key, dest);
2736 int repo_config_get_string(struct repository *repo,
2737 const char *key, char **dest)
2739 int ret;
2740 git_config_check_init(repo);
2741 ret = git_configset_get_string(repo->config, key, dest);
2742 if (ret < 0)
2743 git_die_config(key, NULL);
2744 return ret;
2747 int repo_config_get_string_tmp(struct repository *repo,
2748 const char *key, const char **dest)
2750 int ret;
2751 git_config_check_init(repo);
2752 ret = git_configset_get_string_tmp(repo->config, key, dest);
2753 if (ret < 0)
2754 git_die_config(key, NULL);
2755 return ret;
2758 int repo_config_get_int(struct repository *repo,
2759 const char *key, int *dest)
2761 git_config_check_init(repo);
2762 return git_configset_get_int(repo->config, key, dest);
2765 int repo_config_get_ulong(struct repository *repo,
2766 const char *key, unsigned long *dest)
2768 git_config_check_init(repo);
2769 return git_configset_get_ulong(repo->config, key, dest);
2772 int repo_config_get_bool(struct repository *repo,
2773 const char *key, int *dest)
2775 git_config_check_init(repo);
2776 return git_configset_get_bool(repo->config, key, dest);
2779 int repo_config_get_bool_or_int(struct repository *repo,
2780 const char *key, int *is_bool, int *dest)
2782 git_config_check_init(repo);
2783 return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2786 int repo_config_get_maybe_bool(struct repository *repo,
2787 const char *key, int *dest)
2789 git_config_check_init(repo);
2790 return git_configset_get_maybe_bool(repo->config, key, dest);
2793 int repo_config_get_pathname(struct repository *repo,
2794 const char *key, const char **dest)
2796 int ret;
2797 git_config_check_init(repo);
2798 ret = git_configset_get_pathname(repo->config, key, dest);
2799 if (ret < 0)
2800 git_die_config(key, NULL);
2801 return ret;
2804 /* Read values into protected_config. */
2805 static void read_protected_config(void)
2807 struct config_options opts = {
2808 .respect_includes = 1,
2809 .ignore_repo = 1,
2810 .ignore_worktree = 1,
2811 .system_gently = 1,
2813 struct configset_add_data data = CONFIGSET_ADD_INIT;
2815 git_configset_init(&protected_config);
2816 data.config_set = &protected_config;
2817 data.config_reader = &the_reader;
2818 config_with_options(config_set_callback, &data, NULL, &opts);
2821 void git_protected_config(config_fn_t fn, void *data)
2823 if (!protected_config.hash_initialized)
2824 read_protected_config();
2825 configset_iter(&the_reader, &protected_config, fn, data);
2828 /* Functions used historically to read configuration from 'the_repository' */
2829 void git_config(config_fn_t fn, void *data)
2831 repo_config(the_repository, fn, data);
2834 void git_config_clear(void)
2836 repo_config_clear(the_repository);
2839 int git_config_get(const char *key)
2841 return repo_config_get(the_repository, key);
2844 int git_config_get_value(const char *key, const char **value)
2846 return repo_config_get_value(the_repository, key, value);
2849 int git_config_get_value_multi(const char *key, const struct string_list **dest)
2851 return repo_config_get_value_multi(the_repository, key, dest);
2854 int git_config_get_string_multi(const char *key,
2855 const struct string_list **dest)
2857 return repo_config_get_string_multi(the_repository, key, dest);
2860 int git_config_get_string(const char *key, char **dest)
2862 return repo_config_get_string(the_repository, key, dest);
2865 int git_config_get_string_tmp(const char *key, const char **dest)
2867 return repo_config_get_string_tmp(the_repository, key, dest);
2870 int git_config_get_int(const char *key, int *dest)
2872 return repo_config_get_int(the_repository, key, dest);
2875 int git_config_get_ulong(const char *key, unsigned long *dest)
2877 return repo_config_get_ulong(the_repository, key, dest);
2880 int git_config_get_bool(const char *key, int *dest)
2882 return repo_config_get_bool(the_repository, key, dest);
2885 int git_config_get_bool_or_int(const char *key, int *is_bool, int *dest)
2887 return repo_config_get_bool_or_int(the_repository, key, is_bool, dest);
2890 int git_config_get_maybe_bool(const char *key, int *dest)
2892 return repo_config_get_maybe_bool(the_repository, key, dest);
2895 int git_config_get_pathname(const char *key, const char **dest)
2897 return repo_config_get_pathname(the_repository, key, dest);
2900 int git_config_get_expiry(const char *key, const char **output)
2902 int ret = git_config_get_string(key, (char **)output);
2903 if (ret)
2904 return ret;
2905 if (strcmp(*output, "now")) {
2906 timestamp_t now = approxidate("now");
2907 if (approxidate(*output) >= now)
2908 git_die_config(key, _("Invalid %s: '%s'"), key, *output);
2910 return ret;
2913 int git_config_get_expiry_in_days(const char *key, timestamp_t *expiry, timestamp_t now)
2915 const char *expiry_string;
2916 intmax_t days;
2917 timestamp_t when;
2919 if (git_config_get_string_tmp(key, &expiry_string))
2920 return 1; /* no such thing */
2922 if (git_parse_signed(expiry_string, &days, maximum_signed_value_of_type(int))) {
2923 const int scale = 86400;
2924 *expiry = now - days * scale;
2925 return 0;
2928 if (!parse_expiry_date(expiry_string, &when)) {
2929 *expiry = when;
2930 return 0;
2932 return -1; /* thing exists but cannot be parsed */
2935 int git_config_get_split_index(void)
2937 int val;
2939 if (!git_config_get_maybe_bool("core.splitindex", &val))
2940 return val;
2942 return -1; /* default value */
2945 int git_config_get_max_percent_split_change(void)
2947 int val = -1;
2949 if (!git_config_get_int("splitindex.maxpercentchange", &val)) {
2950 if (0 <= val && val <= 100)
2951 return val;
2953 return error(_("splitIndex.maxPercentChange value '%d' "
2954 "should be between 0 and 100"), val);
2957 return -1; /* default value */
2960 int git_config_get_index_threads(int *dest)
2962 int is_bool, val;
2964 val = git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2965 if (val) {
2966 *dest = val;
2967 return 0;
2970 if (!git_config_get_bool_or_int("index.threads", &is_bool, &val)) {
2971 if (is_bool)
2972 *dest = val ? 0 : 1;
2973 else
2974 *dest = val;
2975 return 0;
2978 return 1;
2981 NORETURN
2982 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2984 if (!filename)
2985 die(_("unable to parse '%s' from command-line config"), key);
2986 else
2987 die(_("bad config variable '%s' in file '%s' at line %d"),
2988 key, filename, linenr);
2991 NORETURN __attribute__((format(printf, 2, 3)))
2992 void git_die_config(const char *key, const char *err, ...)
2994 const struct string_list *values;
2995 struct key_value_info *kv_info;
2996 report_fn error_fn = get_error_routine();
2998 if (err) {
2999 va_list params;
3000 va_start(params, err);
3001 error_fn(err, params);
3002 va_end(params);
3004 if (git_config_get_value_multi(key, &values))
3005 BUG("for key '%s' we must have a value to report on", key);
3006 kv_info = values->items[values->nr - 1].util;
3007 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
3011 * Find all the stuff for git_config_set() below.
3014 struct config_store_data {
3015 struct config_reader *config_reader;
3016 size_t baselen;
3017 char *key;
3018 int do_not_match;
3019 const char *fixed_value;
3020 regex_t *value_pattern;
3021 int multi_replace;
3022 struct {
3023 size_t begin, end;
3024 enum config_event_t type;
3025 int is_keys_section;
3026 } *parsed;
3027 unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
3028 unsigned int key_seen:1, section_seen:1, is_keys_section:1;
3030 #define CONFIG_STORE_INIT { 0 }
3032 static void config_store_data_clear(struct config_store_data *store)
3034 free(store->key);
3035 if (store->value_pattern != NULL &&
3036 store->value_pattern != CONFIG_REGEX_NONE) {
3037 regfree(store->value_pattern);
3038 free(store->value_pattern);
3040 free(store->parsed);
3041 free(store->seen);
3042 memset(store, 0, sizeof(*store));
3045 static int matches(const char *key, const char *value,
3046 const struct config_store_data *store)
3048 if (strcmp(key, store->key))
3049 return 0; /* not ours */
3050 if (store->fixed_value)
3051 return !strcmp(store->fixed_value, value);
3052 if (!store->value_pattern)
3053 return 1; /* always matches */
3054 if (store->value_pattern == CONFIG_REGEX_NONE)
3055 return 0; /* never matches */
3057 return store->do_not_match ^
3058 (value && !regexec(store->value_pattern, value, 0, NULL, 0));
3061 static int store_aux_event(enum config_event_t type,
3062 size_t begin, size_t end, void *data)
3064 struct config_store_data *store = data;
3065 struct config_source *cs = store->config_reader->source;
3067 ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
3068 store->parsed[store->parsed_nr].begin = begin;
3069 store->parsed[store->parsed_nr].end = end;
3070 store->parsed[store->parsed_nr].type = type;
3072 if (type == CONFIG_EVENT_SECTION) {
3073 int (*cmpfn)(const char *, const char *, size_t);
3075 if (cs->var.len < 2 || cs->var.buf[cs->var.len - 1] != '.')
3076 return error(_("invalid section name '%s'"), cs->var.buf);
3078 if (cs->subsection_case_sensitive)
3079 cmpfn = strncasecmp;
3080 else
3081 cmpfn = strncmp;
3083 /* Is this the section we were looking for? */
3084 store->is_keys_section =
3085 store->parsed[store->parsed_nr].is_keys_section =
3086 cs->var.len - 1 == store->baselen &&
3087 !cmpfn(cs->var.buf, store->key, store->baselen);
3088 if (store->is_keys_section) {
3089 store->section_seen = 1;
3090 ALLOC_GROW(store->seen, store->seen_nr + 1,
3091 store->seen_alloc);
3092 store->seen[store->seen_nr] = store->parsed_nr;
3096 store->parsed_nr++;
3098 return 0;
3101 static int store_aux(const char *key, const char *value, void *cb)
3103 struct config_store_data *store = cb;
3105 if (store->key_seen) {
3106 if (matches(key, value, store)) {
3107 if (store->seen_nr == 1 && store->multi_replace == 0) {
3108 warning(_("%s has multiple values"), key);
3111 ALLOC_GROW(store->seen, store->seen_nr + 1,
3112 store->seen_alloc);
3114 store->seen[store->seen_nr] = store->parsed_nr;
3115 store->seen_nr++;
3117 } else if (store->is_keys_section) {
3119 * Do not increment matches yet: this may not be a match, but we
3120 * are in the desired section.
3122 ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
3123 store->seen[store->seen_nr] = store->parsed_nr;
3124 store->section_seen = 1;
3126 if (matches(key, value, store)) {
3127 store->seen_nr++;
3128 store->key_seen = 1;
3132 return 0;
3135 static int write_error(const char *filename)
3137 error(_("failed to write new configuration file %s"), filename);
3139 /* Same error code as "failed to rename". */
3140 return 4;
3143 static struct strbuf store_create_section(const char *key,
3144 const struct config_store_data *store)
3146 const char *dot;
3147 size_t i;
3148 struct strbuf sb = STRBUF_INIT;
3150 dot = memchr(key, '.', store->baselen);
3151 if (dot) {
3152 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
3153 for (i = dot - key + 1; i < store->baselen; i++) {
3154 if (key[i] == '"' || key[i] == '\\')
3155 strbuf_addch(&sb, '\\');
3156 strbuf_addch(&sb, key[i]);
3158 strbuf_addstr(&sb, "\"]\n");
3159 } else {
3160 strbuf_addch(&sb, '[');
3161 strbuf_add(&sb, key, store->baselen);
3162 strbuf_addstr(&sb, "]\n");
3165 return sb;
3168 static ssize_t write_section(int fd, const char *key,
3169 const struct config_store_data *store)
3171 struct strbuf sb = store_create_section(key, store);
3172 ssize_t ret;
3174 ret = write_in_full(fd, sb.buf, sb.len);
3175 strbuf_release(&sb);
3177 return ret;
3180 static ssize_t write_pair(int fd, const char *key, const char *value,
3181 const struct config_store_data *store)
3183 int i;
3184 ssize_t ret;
3185 const char *quote = "";
3186 struct strbuf sb = STRBUF_INIT;
3189 * Check to see if the value needs to be surrounded with a dq pair.
3190 * Note that problematic characters are always backslash-quoted; this
3191 * check is about not losing leading or trailing SP and strings that
3192 * follow beginning-of-comment characters (i.e. ';' and '#') by the
3193 * configuration parser.
3195 if (value[0] == ' ')
3196 quote = "\"";
3197 for (i = 0; value[i]; i++)
3198 if (value[i] == ';' || value[i] == '#')
3199 quote = "\"";
3200 if (i && value[i - 1] == ' ')
3201 quote = "\"";
3203 strbuf_addf(&sb, "\t%s = %s", key + store->baselen + 1, quote);
3205 for (i = 0; value[i]; i++)
3206 switch (value[i]) {
3207 case '\n':
3208 strbuf_addstr(&sb, "\\n");
3209 break;
3210 case '\t':
3211 strbuf_addstr(&sb, "\\t");
3212 break;
3213 case '"':
3214 case '\\':
3215 strbuf_addch(&sb, '\\');
3216 /* fallthrough */
3217 default:
3218 strbuf_addch(&sb, value[i]);
3219 break;
3221 strbuf_addf(&sb, "%s\n", quote);
3223 ret = write_in_full(fd, sb.buf, sb.len);
3224 strbuf_release(&sb);
3226 return ret;
3230 * If we are about to unset the last key(s) in a section, and if there are
3231 * no comments surrounding (or included in) the section, we will want to
3232 * extend begin/end to remove the entire section.
3234 * Note: the parameter `seen_ptr` points to the index into the store.seen
3235 * array. * This index may be incremented if a section has more than one
3236 * entry (which all are to be removed).
3238 static void maybe_remove_section(struct config_store_data *store,
3239 size_t *begin_offset, size_t *end_offset,
3240 int *seen_ptr)
3242 size_t begin;
3243 int i, seen, section_seen = 0;
3246 * First, ensure that this is the first key, and that there are no
3247 * comments before the entry nor before the section header.
3249 seen = *seen_ptr;
3250 for (i = store->seen[seen]; i > 0; i--) {
3251 enum config_event_t type = store->parsed[i - 1].type;
3253 if (type == CONFIG_EVENT_COMMENT)
3254 /* There is a comment before this entry or section */
3255 return;
3256 if (type == CONFIG_EVENT_ENTRY) {
3257 if (!section_seen)
3258 /* This is not the section's first entry. */
3259 return;
3260 /* We encountered no comment before the section. */
3261 break;
3263 if (type == CONFIG_EVENT_SECTION) {
3264 if (!store->parsed[i - 1].is_keys_section)
3265 break;
3266 section_seen = 1;
3269 begin = store->parsed[i].begin;
3272 * Next, make sure that we are removing the last key(s) in the section,
3273 * and that there are no comments that are possibly about the current
3274 * section.
3276 for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
3277 enum config_event_t type = store->parsed[i].type;
3279 if (type == CONFIG_EVENT_COMMENT)
3280 return;
3281 if (type == CONFIG_EVENT_SECTION) {
3282 if (store->parsed[i].is_keys_section)
3283 continue;
3284 break;
3286 if (type == CONFIG_EVENT_ENTRY) {
3287 if (++seen < store->seen_nr &&
3288 i == store->seen[seen])
3289 /* We want to remove this entry, too */
3290 continue;
3291 /* There is another entry in this section. */
3292 return;
3297 * We are really removing the last entry/entries from this section, and
3298 * there are no enclosed or surrounding comments. Remove the entire,
3299 * now-empty section.
3301 *seen_ptr = seen;
3302 *begin_offset = begin;
3303 if (i < store->parsed_nr)
3304 *end_offset = store->parsed[i].begin;
3305 else
3306 *end_offset = store->parsed[store->parsed_nr - 1].end;
3309 int git_config_set_in_file_gently(const char *config_filename,
3310 const char *key, const char *value)
3312 return git_config_set_multivar_in_file_gently(config_filename, key, value, NULL, 0);
3315 void git_config_set_in_file(const char *config_filename,
3316 const char *key, const char *value)
3318 git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
3321 int git_config_set_gently(const char *key, const char *value)
3323 return git_config_set_multivar_gently(key, value, NULL, 0);
3326 int repo_config_set_worktree_gently(struct repository *r,
3327 const char *key, const char *value)
3329 /* Only use worktree-specific config if it is already enabled. */
3330 if (repository_format_worktree_config) {
3331 char *file = repo_git_path(r, "config.worktree");
3332 int ret = git_config_set_multivar_in_file_gently(
3333 file, key, value, NULL, 0);
3334 free(file);
3335 return ret;
3337 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
3340 void git_config_set(const char *key, const char *value)
3342 git_config_set_multivar(key, value, NULL, 0);
3344 trace2_cmd_set_config(key, value);
3348 * If value==NULL, unset in (remove from) config,
3349 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
3350 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
3351 * (only add a new one)
3352 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3353 * key/values are removed before a single new pair is written. If the
3354 * flag is not present, then replace only the first match.
3356 * Returns 0 on success.
3358 * This function does this:
3360 * - it locks the config file by creating ".git/config.lock"
3362 * - it then parses the config using store_aux() as validator to find
3363 * the position on the key/value pair to replace. If it is to be unset,
3364 * it must be found exactly once.
3366 * - the config file is mmap()ed and the part before the match (if any) is
3367 * written to the lock file, then the changed part and the rest.
3369 * - the config file is removed and the lock file rename()d to it.
3372 int git_config_set_multivar_in_file_gently(const char *config_filename,
3373 const char *key, const char *value,
3374 const char *value_pattern,
3375 unsigned flags)
3377 int fd = -1, in_fd = -1;
3378 int ret;
3379 struct lock_file lock = LOCK_INIT;
3380 char *filename_buf = NULL;
3381 char *contents = NULL;
3382 size_t contents_sz;
3383 struct config_store_data store = CONFIG_STORE_INIT;
3385 store.config_reader = &the_reader;
3387 /* parse-key returns negative; flip the sign to feed exit(3) */
3388 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
3389 if (ret)
3390 goto out_free;
3392 store.multi_replace = (flags & CONFIG_FLAGS_MULTI_REPLACE) != 0;
3394 if (!config_filename)
3395 config_filename = filename_buf = git_pathdup("config");
3398 * The lock serves a purpose in addition to locking: the new
3399 * contents of .git/config will be written into it.
3401 fd = hold_lock_file_for_update(&lock, config_filename, 0);
3402 if (fd < 0) {
3403 error_errno(_("could not lock config file %s"), config_filename);
3404 ret = CONFIG_NO_LOCK;
3405 goto out_free;
3409 * If .git/config does not exist yet, write a minimal version.
3411 in_fd = open(config_filename, O_RDONLY);
3412 if ( in_fd < 0 ) {
3413 if ( ENOENT != errno ) {
3414 error_errno(_("opening %s"), config_filename);
3415 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
3416 goto out_free;
3418 /* if nothing to unset, error out */
3419 if (!value) {
3420 ret = CONFIG_NOTHING_SET;
3421 goto out_free;
3424 free(store.key);
3425 store.key = xstrdup(key);
3426 if (write_section(fd, key, &store) < 0 ||
3427 write_pair(fd, key, value, &store) < 0)
3428 goto write_err_out;
3429 } else {
3430 struct stat st;
3431 size_t copy_begin, copy_end;
3432 int i, new_line = 0;
3433 struct config_options opts;
3435 if (!value_pattern)
3436 store.value_pattern = NULL;
3437 else if (value_pattern == CONFIG_REGEX_NONE)
3438 store.value_pattern = CONFIG_REGEX_NONE;
3439 else if (flags & CONFIG_FLAGS_FIXED_VALUE)
3440 store.fixed_value = value_pattern;
3441 else {
3442 if (value_pattern[0] == '!') {
3443 store.do_not_match = 1;
3444 value_pattern++;
3445 } else
3446 store.do_not_match = 0;
3448 store.value_pattern = (regex_t*)xmalloc(sizeof(regex_t));
3449 if (regcomp(store.value_pattern, value_pattern,
3450 REG_EXTENDED)) {
3451 error(_("invalid pattern: %s"), value_pattern);
3452 FREE_AND_NULL(store.value_pattern);
3453 ret = CONFIG_INVALID_PATTERN;
3454 goto out_free;
3458 ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
3459 store.parsed[0].end = 0;
3461 memset(&opts, 0, sizeof(opts));
3462 opts.event_fn = store_aux_event;
3463 opts.event_fn_data = &store;
3466 * After this, store.parsed will contain offsets of all the
3467 * parsed elements, and store.seen will contain a list of
3468 * matches, as indices into store.parsed.
3470 * As a side effect, we make sure to transform only a valid
3471 * existing config file.
3473 if (git_config_from_file_with_options(store_aux,
3474 config_filename,
3475 &store, &opts)) {
3476 error(_("invalid config file %s"), config_filename);
3477 ret = CONFIG_INVALID_FILE;
3478 goto out_free;
3481 /* if nothing to unset, or too many matches, error out */
3482 if ((store.seen_nr == 0 && value == NULL) ||
3483 (store.seen_nr > 1 && !store.multi_replace)) {
3484 ret = CONFIG_NOTHING_SET;
3485 goto out_free;
3488 if (fstat(in_fd, &st) == -1) {
3489 error_errno(_("fstat on %s failed"), config_filename);
3490 ret = CONFIG_INVALID_FILE;
3491 goto out_free;
3494 contents_sz = xsize_t(st.st_size);
3495 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
3496 MAP_PRIVATE, in_fd, 0);
3497 if (contents == MAP_FAILED) {
3498 if (errno == ENODEV && S_ISDIR(st.st_mode))
3499 errno = EISDIR;
3500 error_errno(_("unable to mmap '%s'%s"),
3501 config_filename, mmap_os_err());
3502 ret = CONFIG_INVALID_FILE;
3503 contents = NULL;
3504 goto out_free;
3506 close(in_fd);
3507 in_fd = -1;
3509 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3510 error_errno(_("chmod on %s failed"), get_lock_file_path(&lock));
3511 ret = CONFIG_NO_WRITE;
3512 goto out_free;
3515 if (store.seen_nr == 0) {
3516 if (!store.seen_alloc) {
3517 /* Did not see key nor section */
3518 ALLOC_GROW(store.seen, 1, store.seen_alloc);
3519 store.seen[0] = store.parsed_nr
3520 - !!store.parsed_nr;
3522 store.seen_nr = 1;
3525 for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
3526 size_t replace_end;
3527 int j = store.seen[i];
3529 new_line = 0;
3530 if (!store.key_seen) {
3531 copy_end = store.parsed[j].end;
3532 /* include '\n' when copying section header */
3533 if (copy_end > 0 && copy_end < contents_sz &&
3534 contents[copy_end - 1] != '\n' &&
3535 contents[copy_end] == '\n')
3536 copy_end++;
3537 replace_end = copy_end;
3538 } else {
3539 replace_end = store.parsed[j].end;
3540 copy_end = store.parsed[j].begin;
3541 if (!value)
3542 maybe_remove_section(&store,
3543 &copy_end,
3544 &replace_end, &i);
3546 * Swallow preceding white-space on the same
3547 * line.
3549 while (copy_end > 0 ) {
3550 char c = contents[copy_end - 1];
3552 if (isspace(c) && c != '\n')
3553 copy_end--;
3554 else
3555 break;
3559 if (copy_end > 0 && contents[copy_end-1] != '\n')
3560 new_line = 1;
3562 /* write the first part of the config */
3563 if (copy_end > copy_begin) {
3564 if (write_in_full(fd, contents + copy_begin,
3565 copy_end - copy_begin) < 0)
3566 goto write_err_out;
3567 if (new_line &&
3568 write_str_in_full(fd, "\n") < 0)
3569 goto write_err_out;
3571 copy_begin = replace_end;
3574 /* write the pair (value == NULL means unset) */
3575 if (value) {
3576 if (!store.section_seen) {
3577 if (write_section(fd, key, &store) < 0)
3578 goto write_err_out;
3580 if (write_pair(fd, key, value, &store) < 0)
3581 goto write_err_out;
3584 /* write the rest of the config */
3585 if (copy_begin < contents_sz)
3586 if (write_in_full(fd, contents + copy_begin,
3587 contents_sz - copy_begin) < 0)
3588 goto write_err_out;
3590 munmap(contents, contents_sz);
3591 contents = NULL;
3594 if (commit_lock_file(&lock) < 0) {
3595 error_errno(_("could not write config file %s"), config_filename);
3596 ret = CONFIG_NO_WRITE;
3597 goto out_free;
3600 ret = 0;
3602 /* Invalidate the config cache */
3603 git_config_clear();
3605 out_free:
3606 rollback_lock_file(&lock);
3607 free(filename_buf);
3608 if (contents)
3609 munmap(contents, contents_sz);
3610 if (in_fd >= 0)
3611 close(in_fd);
3612 config_store_data_clear(&store);
3613 return ret;
3615 write_err_out:
3616 ret = write_error(get_lock_file_path(&lock));
3617 goto out_free;
3621 void git_config_set_multivar_in_file(const char *config_filename,
3622 const char *key, const char *value,
3623 const char *value_pattern, unsigned flags)
3625 if (!git_config_set_multivar_in_file_gently(config_filename, key, value,
3626 value_pattern, flags))
3627 return;
3628 if (value)
3629 die(_("could not set '%s' to '%s'"), key, value);
3630 else
3631 die(_("could not unset '%s'"), key);
3634 int git_config_set_multivar_gently(const char *key, const char *value,
3635 const char *value_pattern, unsigned flags)
3637 return repo_config_set_multivar_gently(the_repository, key, value,
3638 value_pattern, flags);
3641 int repo_config_set_multivar_gently(struct repository *r, const char *key,
3642 const char *value,
3643 const char *value_pattern, unsigned flags)
3645 char *file = repo_git_path(r, "config");
3646 int res = git_config_set_multivar_in_file_gently(file,
3647 key, value,
3648 value_pattern,
3649 flags);
3650 free(file);
3651 return res;
3654 void git_config_set_multivar(const char *key, const char *value,
3655 const char *value_pattern, unsigned flags)
3657 git_config_set_multivar_in_file(git_path("config"),
3658 key, value, value_pattern,
3659 flags);
3662 static size_t section_name_match (const char *buf, const char *name)
3664 size_t i = 0, j = 0;
3665 int dot = 0;
3666 if (buf[i] != '[')
3667 return 0;
3668 for (i = 1; buf[i] && buf[i] != ']'; i++) {
3669 if (!dot && isspace(buf[i])) {
3670 dot = 1;
3671 if (name[j++] != '.')
3672 break;
3673 for (i++; isspace(buf[i]); i++)
3674 ; /* do nothing */
3675 if (buf[i] != '"')
3676 break;
3677 continue;
3679 if (buf[i] == '\\' && dot)
3680 i++;
3681 else if (buf[i] == '"' && dot) {
3682 for (i++; isspace(buf[i]); i++)
3683 ; /* do_nothing */
3684 break;
3686 if (buf[i] != name[j++])
3687 break;
3689 if (buf[i] == ']' && name[j] == 0) {
3691 * We match, now just find the right length offset by
3692 * gobbling up any whitespace after it, as well
3694 i++;
3695 for (; buf[i] && isspace(buf[i]); i++)
3696 ; /* do nothing */
3697 return i;
3699 return 0;
3702 static int section_name_is_ok(const char *name)
3704 /* Empty section names are bogus. */
3705 if (!*name)
3706 return 0;
3709 * Before a dot, we must be alphanumeric or dash. After the first dot,
3710 * anything goes, so we can stop checking.
3712 for (; *name && *name != '.'; name++)
3713 if (*name != '-' && !isalnum(*name))
3714 return 0;
3715 return 1;
3718 #define GIT_CONFIG_MAX_LINE_LEN (512 * 1024)
3720 /* if new_name == NULL, the section is removed instead */
3721 static int git_config_copy_or_rename_section_in_file(const char *config_filename,
3722 const char *old_name,
3723 const char *new_name, int copy)
3725 int ret = 0, remove = 0;
3726 char *filename_buf = NULL;
3727 struct lock_file lock = LOCK_INIT;
3728 int out_fd;
3729 struct strbuf buf = STRBUF_INIT;
3730 FILE *config_file = NULL;
3731 struct stat st;
3732 struct strbuf copystr = STRBUF_INIT;
3733 struct config_store_data store;
3734 uint32_t line_nr = 0;
3736 memset(&store, 0, sizeof(store));
3738 if (new_name && !section_name_is_ok(new_name)) {
3739 ret = error(_("invalid section name: %s"), new_name);
3740 goto out_no_rollback;
3743 if (!config_filename)
3744 config_filename = filename_buf = git_pathdup("config");
3746 out_fd = hold_lock_file_for_update(&lock, config_filename, 0);
3747 if (out_fd < 0) {
3748 ret = error(_("could not lock config file %s"), config_filename);
3749 goto out;
3752 if (!(config_file = fopen(config_filename, "rb"))) {
3753 ret = warn_on_fopen_errors(config_filename);
3754 if (ret)
3755 goto out;
3756 /* no config file means nothing to rename, no error */
3757 goto commit_and_out;
3760 if (fstat(fileno(config_file), &st) == -1) {
3761 ret = error_errno(_("fstat on %s failed"), config_filename);
3762 goto out;
3765 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3766 ret = error_errno(_("chmod on %s failed"),
3767 get_lock_file_path(&lock));
3768 goto out;
3771 while (!strbuf_getwholeline(&buf, config_file, '\n')) {
3772 size_t i, length;
3773 int is_section = 0;
3774 char *output = buf.buf;
3776 line_nr++;
3778 if (buf.len >= GIT_CONFIG_MAX_LINE_LEN) {
3779 ret = error(_("refusing to work with overly long line "
3780 "in '%s' on line %"PRIuMAX),
3781 config_filename, (uintmax_t)line_nr);
3782 goto out;
3785 for (i = 0; buf.buf[i] && isspace(buf.buf[i]); i++)
3786 ; /* do nothing */
3787 if (buf.buf[i] == '[') {
3788 /* it's a section */
3789 size_t offset;
3790 is_section = 1;
3793 * When encountering a new section under -c we
3794 * need to flush out any section we're already
3795 * coping and begin anew. There might be
3796 * multiple [branch "$name"] sections.
3798 if (copystr.len > 0) {
3799 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3800 ret = write_error(get_lock_file_path(&lock));
3801 goto out;
3803 strbuf_reset(&copystr);
3806 offset = section_name_match(&buf.buf[i], old_name);
3807 if (offset > 0) {
3808 ret++;
3809 if (!new_name) {
3810 remove = 1;
3811 continue;
3813 store.baselen = strlen(new_name);
3814 if (!copy) {
3815 if (write_section(out_fd, new_name, &store) < 0) {
3816 ret = write_error(get_lock_file_path(&lock));
3817 goto out;
3820 * We wrote out the new section, with
3821 * a newline, now skip the old
3822 * section's length
3824 output += offset + i;
3825 if (strlen(output) > 0) {
3827 * More content means there's
3828 * a declaration to put on the
3829 * next line; indent with a
3830 * tab
3832 output -= 1;
3833 output[0] = '\t';
3835 } else {
3836 copystr = store_create_section(new_name, &store);
3839 remove = 0;
3841 if (remove)
3842 continue;
3843 length = strlen(output);
3845 if (!is_section && copystr.len > 0) {
3846 strbuf_add(&copystr, output, length);
3849 if (write_in_full(out_fd, output, length) < 0) {
3850 ret = write_error(get_lock_file_path(&lock));
3851 goto out;
3856 * Copy a trailing section at the end of the config, won't be
3857 * flushed by the usual "flush because we have a new section
3858 * logic in the loop above.
3860 if (copystr.len > 0) {
3861 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3862 ret = write_error(get_lock_file_path(&lock));
3863 goto out;
3865 strbuf_reset(&copystr);
3868 fclose(config_file);
3869 config_file = NULL;
3870 commit_and_out:
3871 if (commit_lock_file(&lock) < 0)
3872 ret = error_errno(_("could not write config file %s"),
3873 config_filename);
3874 out:
3875 if (config_file)
3876 fclose(config_file);
3877 rollback_lock_file(&lock);
3878 out_no_rollback:
3879 free(filename_buf);
3880 config_store_data_clear(&store);
3881 strbuf_release(&buf);
3882 return ret;
3885 int git_config_rename_section_in_file(const char *config_filename,
3886 const char *old_name, const char *new_name)
3888 return git_config_copy_or_rename_section_in_file(config_filename,
3889 old_name, new_name, 0);
3892 int git_config_rename_section(const char *old_name, const char *new_name)
3894 return git_config_rename_section_in_file(NULL, old_name, new_name);
3897 int git_config_copy_section_in_file(const char *config_filename,
3898 const char *old_name, const char *new_name)
3900 return git_config_copy_or_rename_section_in_file(config_filename,
3901 old_name, new_name, 1);
3904 int git_config_copy_section(const char *old_name, const char *new_name)
3906 return git_config_copy_section_in_file(NULL, old_name, new_name);
3910 * Call this to report error for your variable that should not
3911 * get a boolean value (i.e. "[my] var" means "true").
3913 #undef config_error_nonbool
3914 int config_error_nonbool(const char *var)
3916 return error(_("missing value for '%s'"), var);
3919 int parse_config_key(const char *var,
3920 const char *section,
3921 const char **subsection, size_t *subsection_len,
3922 const char **key)
3924 const char *dot;
3926 /* Does it start with "section." ? */
3927 if (!skip_prefix(var, section, &var) || *var != '.')
3928 return -1;
3931 * Find the key; we don't know yet if we have a subsection, but we must
3932 * parse backwards from the end, since the subsection may have dots in
3933 * it, too.
3935 dot = strrchr(var, '.');
3936 *key = dot + 1;
3938 /* Did we have a subsection at all? */
3939 if (dot == var) {
3940 if (subsection) {
3941 *subsection = NULL;
3942 *subsection_len = 0;
3945 else {
3946 if (!subsection)
3947 return -1;
3948 *subsection = var + 1;
3949 *subsection_len = dot - *subsection;
3952 return 0;
3955 static int reader_origin_type(struct config_reader *reader,
3956 enum config_origin_type *type)
3958 if (the_reader.config_kvi)
3959 *type = reader->config_kvi->origin_type;
3960 else if(the_reader.source)
3961 *type = reader->source->origin_type;
3962 else
3963 return 1;
3964 return 0;
3967 const char *current_config_origin_type(void)
3969 enum config_origin_type type = CONFIG_ORIGIN_UNKNOWN;
3971 if (reader_origin_type(&the_reader, &type))
3972 BUG("current_config_origin_type called outside config callback");
3974 switch (type) {
3975 case CONFIG_ORIGIN_BLOB:
3976 return "blob";
3977 case CONFIG_ORIGIN_FILE:
3978 return "file";
3979 case CONFIG_ORIGIN_STDIN:
3980 return "standard input";
3981 case CONFIG_ORIGIN_SUBMODULE_BLOB:
3982 return "submodule-blob";
3983 case CONFIG_ORIGIN_CMDLINE:
3984 return "command line";
3985 default:
3986 BUG("unknown config origin type");
3990 const char *config_scope_name(enum config_scope scope)
3992 switch (scope) {
3993 case CONFIG_SCOPE_SYSTEM:
3994 return "system";
3995 case CONFIG_SCOPE_GLOBAL:
3996 return "global";
3997 case CONFIG_SCOPE_LOCAL:
3998 return "local";
3999 case CONFIG_SCOPE_WORKTREE:
4000 return "worktree";
4001 case CONFIG_SCOPE_COMMAND:
4002 return "command";
4003 case CONFIG_SCOPE_SUBMODULE:
4004 return "submodule";
4005 default:
4006 return "unknown";
4010 static int reader_config_name(struct config_reader *reader, const char **out)
4012 if (the_reader.config_kvi)
4013 *out = reader->config_kvi->filename;
4014 else if (the_reader.source)
4015 *out = reader->source->name;
4016 else
4017 return 1;
4018 return 0;
4021 const char *current_config_name(void)
4023 const char *name;
4024 if (reader_config_name(&the_reader, &name))
4025 BUG("current_config_name called outside config callback");
4026 return name ? name : "";
4029 enum config_scope current_config_scope(void)
4031 if (the_reader.config_kvi)
4032 return the_reader.config_kvi->scope;
4033 else
4034 return the_reader.parsing_scope;
4037 int current_config_line(void)
4039 if (the_reader.config_kvi)
4040 return the_reader.config_kvi->linenr;
4041 else
4042 return the_reader.source->linenr;
4045 int lookup_config(const char **mapping, int nr_mapping, const char *var)
4047 int i;
4049 for (i = 0; i < nr_mapping; i++) {
4050 const char *name = mapping[i];
4052 if (name && !strcasecmp(var, name))
4053 return i;
4055 return -1;