commit.h: reduce unnecessary includes
[alt-git.git] / config.c
blob2a9ed27efe5f1bbed1b85be217a1ebe05c9c62bc
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);
69 * These variables record the "current" config source, which
70 * can be accessed by parsing callbacks.
72 * The "cf" variable will be non-NULL only when we are actually parsing a real
73 * config source (file, blob, cmdline, etc).
75 * The "current_config_kvi" variable will be non-NULL only when we are feeding
76 * cached config from a configset into a callback.
78 * They should generally never be non-NULL at the same time. If they are both
79 * NULL, then we aren't parsing anything (and depending on the function looking
80 * at the variables, it's either a bug for it to be called in the first place,
81 * or it's a function which can be reused for non-config purposes, and should
82 * fall back to some sane behavior).
84 static struct config_source *cf;
85 static struct key_value_info *current_config_kvi;
88 * Similar to the variables above, this gives access to the "scope" of the
89 * current value (repo, global, etc). For cached values, it can be found via
90 * the current_config_kvi as above. During parsing, the current value can be
91 * found in this variable. It's not part of "cf" because it transcends a single
92 * file (i.e., a file included from .git/config is still in "repo" scope).
94 static enum config_scope current_parsing_scope;
96 static int pack_compression_seen;
97 static int zlib_compression_seen;
100 * Config that comes from trusted scopes, namely:
101 * - CONFIG_SCOPE_SYSTEM (e.g. /etc/gitconfig)
102 * - CONFIG_SCOPE_GLOBAL (e.g. $HOME/.gitconfig, $XDG_CONFIG_HOME/git)
103 * - CONFIG_SCOPE_COMMAND (e.g. "-c" option, environment variables)
105 * This is declared here for code cleanliness, but unlike the other
106 * static variables, this does not hold config parser state.
108 static struct config_set protected_config;
110 static int config_file_fgetc(struct config_source *conf)
112 return getc_unlocked(conf->u.file);
115 static int config_file_ungetc(int c, struct config_source *conf)
117 return ungetc(c, conf->u.file);
120 static long config_file_ftell(struct config_source *conf)
122 return ftell(conf->u.file);
126 static int config_buf_fgetc(struct config_source *conf)
128 if (conf->u.buf.pos < conf->u.buf.len)
129 return conf->u.buf.buf[conf->u.buf.pos++];
131 return EOF;
134 static int config_buf_ungetc(int c, struct config_source *conf)
136 if (conf->u.buf.pos > 0) {
137 conf->u.buf.pos--;
138 if (conf->u.buf.buf[conf->u.buf.pos] != c)
139 BUG("config_buf can only ungetc the same character");
140 return c;
143 return EOF;
146 static long config_buf_ftell(struct config_source *conf)
148 return conf->u.buf.pos;
151 struct config_include_data {
152 int depth;
153 config_fn_t fn;
154 void *data;
155 const struct config_options *opts;
156 struct git_config_source *config_source;
159 * All remote URLs discovered when reading all config files.
161 struct string_list *remote_urls;
163 #define CONFIG_INCLUDE_INIT { 0 }
165 static int git_config_include(const char *var, const char *value, void *data);
167 #define MAX_INCLUDE_DEPTH 10
168 static const char include_depth_advice[] = N_(
169 "exceeded maximum include depth (%d) while including\n"
170 " %s\n"
171 "from\n"
172 " %s\n"
173 "This might be due to circular includes.");
174 static int handle_path_include(const char *path, struct config_include_data *inc)
176 int ret = 0;
177 struct strbuf buf = STRBUF_INIT;
178 char *expanded;
180 if (!path)
181 return config_error_nonbool("include.path");
183 expanded = interpolate_path(path, 0);
184 if (!expanded)
185 return error(_("could not expand include path '%s'"), path);
186 path = expanded;
189 * Use an absolute path as-is, but interpret relative paths
190 * based on the including config file.
192 if (!is_absolute_path(path)) {
193 char *slash;
195 if (!cf || !cf->path) {
196 ret = error(_("relative config includes must come from files"));
197 goto cleanup;
200 slash = find_last_dir_sep(cf->path);
201 if (slash)
202 strbuf_add(&buf, cf->path, slash - cf->path + 1);
203 strbuf_addstr(&buf, path);
204 path = buf.buf;
207 if (!access_or_die(path, R_OK, 0)) {
208 if (++inc->depth > MAX_INCLUDE_DEPTH)
209 die(_(include_depth_advice), MAX_INCLUDE_DEPTH, path,
210 !cf ? "<unknown>" :
211 cf->name ? cf->name :
212 "the command line");
213 ret = git_config_from_file(git_config_include, path, inc);
214 inc->depth--;
216 cleanup:
217 strbuf_release(&buf);
218 free(expanded);
219 return ret;
222 static void add_trailing_starstar_for_dir(struct strbuf *pat)
224 if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
225 strbuf_addstr(pat, "**");
228 static int prepare_include_condition_pattern(struct strbuf *pat)
230 struct strbuf path = STRBUF_INIT;
231 char *expanded;
232 int prefix = 0;
234 expanded = interpolate_path(pat->buf, 1);
235 if (expanded) {
236 strbuf_reset(pat);
237 strbuf_addstr(pat, expanded);
238 free(expanded);
241 if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
242 const char *slash;
244 if (!cf || !cf->path)
245 return error(_("relative config include "
246 "conditionals must come from files"));
248 strbuf_realpath(&path, cf->path, 1);
249 slash = find_last_dir_sep(path.buf);
250 if (!slash)
251 BUG("how is this possible?");
252 strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
253 prefix = slash - path.buf + 1 /* slash */;
254 } else if (!is_absolute_path(pat->buf))
255 strbuf_insertstr(pat, 0, "**/");
257 add_trailing_starstar_for_dir(pat);
259 strbuf_release(&path);
260 return prefix;
263 static int include_by_gitdir(const struct config_options *opts,
264 const char *cond, size_t cond_len, int icase)
266 struct strbuf text = STRBUF_INIT;
267 struct strbuf pattern = STRBUF_INIT;
268 int ret = 0, prefix;
269 const char *git_dir;
270 int already_tried_absolute = 0;
272 if (opts->git_dir)
273 git_dir = opts->git_dir;
274 else
275 goto done;
277 strbuf_realpath(&text, git_dir, 1);
278 strbuf_add(&pattern, cond, cond_len);
279 prefix = prepare_include_condition_pattern(&pattern);
281 again:
282 if (prefix < 0)
283 goto done;
285 if (prefix > 0) {
287 * perform literal matching on the prefix part so that
288 * any wildcard character in it can't create side effects.
290 if (text.len < prefix)
291 goto done;
292 if (!icase && strncmp(pattern.buf, text.buf, prefix))
293 goto done;
294 if (icase && strncasecmp(pattern.buf, text.buf, prefix))
295 goto done;
298 ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
299 WM_PATHNAME | (icase ? WM_CASEFOLD : 0));
301 if (!ret && !already_tried_absolute) {
303 * We've tried e.g. matching gitdir:~/work, but if
304 * ~/work is a symlink to /mnt/storage/work
305 * strbuf_realpath() will expand it, so the rule won't
306 * match. Let's match against a
307 * strbuf_add_absolute_path() version of the path,
308 * which'll do the right thing
310 strbuf_reset(&text);
311 strbuf_add_absolute_path(&text, git_dir);
312 already_tried_absolute = 1;
313 goto again;
315 done:
316 strbuf_release(&pattern);
317 strbuf_release(&text);
318 return ret;
321 static int include_by_branch(const char *cond, size_t cond_len)
323 int flags;
324 int ret;
325 struct strbuf pattern = STRBUF_INIT;
326 const char *refname = !the_repository->gitdir ?
327 NULL : resolve_ref_unsafe("HEAD", 0, NULL, &flags);
328 const char *shortname;
330 if (!refname || !(flags & REF_ISSYMREF) ||
331 !skip_prefix(refname, "refs/heads/", &shortname))
332 return 0;
334 strbuf_add(&pattern, cond, cond_len);
335 add_trailing_starstar_for_dir(&pattern);
336 ret = !wildmatch(pattern.buf, shortname, WM_PATHNAME);
337 strbuf_release(&pattern);
338 return ret;
341 static int add_remote_url(const char *var, const char *value, void *data)
343 struct string_list *remote_urls = data;
344 const char *remote_name;
345 size_t remote_name_len;
346 const char *key;
348 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
349 &key) &&
350 remote_name &&
351 !strcmp(key, "url"))
352 string_list_append(remote_urls, value);
353 return 0;
356 static void populate_remote_urls(struct config_include_data *inc)
358 struct config_options opts;
360 struct config_source *store_cf = cf;
361 struct key_value_info *store_kvi = current_config_kvi;
362 enum config_scope store_scope = current_parsing_scope;
364 opts = *inc->opts;
365 opts.unconditional_remote_url = 1;
367 cf = NULL;
368 current_config_kvi = NULL;
369 current_parsing_scope = 0;
371 inc->remote_urls = xmalloc(sizeof(*inc->remote_urls));
372 string_list_init_dup(inc->remote_urls);
373 config_with_options(add_remote_url, inc->remote_urls, inc->config_source, &opts);
375 cf = store_cf;
376 current_config_kvi = store_kvi;
377 current_parsing_scope = store_scope;
380 static int forbid_remote_url(const char *var, const char *value UNUSED,
381 void *data UNUSED)
383 const char *remote_name;
384 size_t remote_name_len;
385 const char *key;
387 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
388 &key) &&
389 remote_name &&
390 !strcmp(key, "url"))
391 die(_("remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"));
392 return 0;
395 static int at_least_one_url_matches_glob(const char *glob, int glob_len,
396 struct string_list *remote_urls)
398 struct strbuf pattern = STRBUF_INIT;
399 struct string_list_item *url_item;
400 int found = 0;
402 strbuf_add(&pattern, glob, glob_len);
403 for_each_string_list_item(url_item, remote_urls) {
404 if (!wildmatch(pattern.buf, url_item->string, WM_PATHNAME)) {
405 found = 1;
406 break;
409 strbuf_release(&pattern);
410 return found;
413 static int include_by_remote_url(struct config_include_data *inc,
414 const char *cond, size_t cond_len)
416 if (inc->opts->unconditional_remote_url)
417 return 1;
418 if (!inc->remote_urls)
419 populate_remote_urls(inc);
420 return at_least_one_url_matches_glob(cond, cond_len,
421 inc->remote_urls);
424 static int include_condition_is_true(struct config_include_data *inc,
425 const char *cond, size_t cond_len)
427 const struct config_options *opts = inc->opts;
429 if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
430 return include_by_gitdir(opts, cond, cond_len, 0);
431 else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
432 return include_by_gitdir(opts, cond, cond_len, 1);
433 else if (skip_prefix_mem(cond, cond_len, "onbranch:", &cond, &cond_len))
434 return include_by_branch(cond, cond_len);
435 else if (skip_prefix_mem(cond, cond_len, "hasconfig:remote.*.url:", &cond,
436 &cond_len))
437 return include_by_remote_url(inc, cond, cond_len);
439 /* unknown conditionals are always false */
440 return 0;
443 static int git_config_include(const char *var, const char *value, void *data)
445 struct config_include_data *inc = data;
446 const char *cond, *key;
447 size_t cond_len;
448 int ret;
451 * Pass along all values, including "include" directives; this makes it
452 * possible to query information on the includes themselves.
454 ret = inc->fn(var, value, inc->data);
455 if (ret < 0)
456 return ret;
458 if (!strcmp(var, "include.path"))
459 ret = handle_path_include(value, inc);
461 if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
462 cond && include_condition_is_true(inc, cond, cond_len) &&
463 !strcmp(key, "path")) {
464 config_fn_t old_fn = inc->fn;
466 if (inc->opts->unconditional_remote_url)
467 inc->fn = forbid_remote_url;
468 ret = handle_path_include(value, inc);
469 inc->fn = old_fn;
472 return ret;
475 static void git_config_push_split_parameter(const char *key, const char *value)
477 struct strbuf env = STRBUF_INIT;
478 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
479 if (old && *old) {
480 strbuf_addstr(&env, old);
481 strbuf_addch(&env, ' ');
483 sq_quote_buf(&env, key);
484 strbuf_addch(&env, '=');
485 if (value)
486 sq_quote_buf(&env, value);
487 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
488 strbuf_release(&env);
491 void git_config_push_parameter(const char *text)
493 const char *value;
496 * When we see:
498 * section.subsection=with=equals.key=value
500 * we cannot tell if it means:
502 * [section "subsection=with=equals"]
503 * key = value
505 * or:
507 * [section]
508 * subsection = with=equals.key=value
510 * We parse left-to-right for the first "=", meaning we'll prefer to
511 * keep the value intact over the subsection. This is historical, but
512 * also sensible since values are more likely to contain odd or
513 * untrusted input than a section name.
515 * A missing equals is explicitly allowed (as a bool-only entry).
517 value = strchr(text, '=');
518 if (value) {
519 char *key = xmemdupz(text, value - text);
520 git_config_push_split_parameter(key, value + 1);
521 free(key);
522 } else {
523 git_config_push_split_parameter(text, NULL);
527 void git_config_push_env(const char *spec)
529 char *key;
530 const char *env_name;
531 const char *env_value;
533 env_name = strrchr(spec, '=');
534 if (!env_name)
535 die(_("invalid config format: %s"), spec);
536 key = xmemdupz(spec, env_name - spec);
537 env_name++;
538 if (!*env_name)
539 die(_("missing environment variable name for configuration '%.*s'"),
540 (int)(env_name - spec - 1), spec);
542 env_value = getenv(env_name);
543 if (!env_value)
544 die(_("missing environment variable '%s' for configuration '%.*s'"),
545 env_name, (int)(env_name - spec - 1), spec);
547 git_config_push_split_parameter(key, env_value);
548 free(key);
551 static inline int iskeychar(int c)
553 return isalnum(c) || c == '-';
557 * Auxiliary function to sanity-check and split the key into the section
558 * identifier and variable name.
560 * Returns 0 on success, -1 when there is an invalid character in the key and
561 * -2 if there is no section name in the key.
563 * store_key - pointer to char* which will hold a copy of the key with
564 * lowercase section and variable name
565 * baselen - pointer to size_t which will hold the length of the
566 * section + subsection part, can be NULL
568 int git_config_parse_key(const char *key, char **store_key, size_t *baselen_)
570 size_t i, baselen;
571 int dot;
572 const char *last_dot = strrchr(key, '.');
575 * Since "key" actually contains the section name and the real
576 * key name separated by a dot, we have to know where the dot is.
579 if (last_dot == NULL || last_dot == key) {
580 error(_("key does not contain a section: %s"), key);
581 return -CONFIG_NO_SECTION_OR_NAME;
584 if (!last_dot[1]) {
585 error(_("key does not contain variable name: %s"), key);
586 return -CONFIG_NO_SECTION_OR_NAME;
589 baselen = last_dot - key;
590 if (baselen_)
591 *baselen_ = baselen;
594 * Validate the key and while at it, lower case it for matching.
596 *store_key = xmallocz(strlen(key));
598 dot = 0;
599 for (i = 0; key[i]; i++) {
600 unsigned char c = key[i];
601 if (c == '.')
602 dot = 1;
603 /* Leave the extended basename untouched.. */
604 if (!dot || i > baselen) {
605 if (!iskeychar(c) ||
606 (i == baselen + 1 && !isalpha(c))) {
607 error(_("invalid key: %s"), key);
608 goto out_free_ret_1;
610 c = tolower(c);
611 } else if (c == '\n') {
612 error(_("invalid key (newline): %s"), key);
613 goto out_free_ret_1;
615 (*store_key)[i] = c;
618 return 0;
620 out_free_ret_1:
621 FREE_AND_NULL(*store_key);
622 return -CONFIG_INVALID_KEY;
625 static int config_parse_pair(const char *key, const char *value,
626 config_fn_t fn, void *data)
628 char *canonical_name;
629 int ret;
631 if (!strlen(key))
632 return error(_("empty config key"));
633 if (git_config_parse_key(key, &canonical_name, NULL))
634 return -1;
636 ret = (fn(canonical_name, value, data) < 0) ? -1 : 0;
637 free(canonical_name);
638 return ret;
641 int git_config_parse_parameter(const char *text,
642 config_fn_t fn, void *data)
644 const char *value;
645 struct strbuf **pair;
646 int ret;
648 pair = strbuf_split_str(text, '=', 2);
649 if (!pair[0])
650 return error(_("bogus config parameter: %s"), text);
652 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
653 strbuf_setlen(pair[0], pair[0]->len - 1);
654 value = pair[1] ? pair[1]->buf : "";
655 } else {
656 value = NULL;
659 strbuf_trim(pair[0]);
660 if (!pair[0]->len) {
661 strbuf_list_free(pair);
662 return error(_("bogus config parameter: %s"), text);
665 ret = config_parse_pair(pair[0]->buf, value, fn, data);
666 strbuf_list_free(pair);
667 return ret;
670 static int parse_config_env_list(char *env, config_fn_t fn, void *data)
672 char *cur = env;
673 while (cur && *cur) {
674 const char *key = sq_dequote_step(cur, &cur);
675 if (!key)
676 return error(_("bogus format in %s"),
677 CONFIG_DATA_ENVIRONMENT);
679 if (!cur || isspace(*cur)) {
680 /* old-style 'key=value' */
681 if (git_config_parse_parameter(key, fn, data) < 0)
682 return -1;
684 else if (*cur == '=') {
685 /* new-style 'key'='value' */
686 const char *value;
688 cur++;
689 if (*cur == '\'') {
690 /* quoted value */
691 value = sq_dequote_step(cur, &cur);
692 if (!value || (cur && !isspace(*cur))) {
693 return error(_("bogus format in %s"),
694 CONFIG_DATA_ENVIRONMENT);
696 } else if (!*cur || isspace(*cur)) {
697 /* implicit bool: 'key'= */
698 value = NULL;
699 } else {
700 return error(_("bogus format in %s"),
701 CONFIG_DATA_ENVIRONMENT);
704 if (config_parse_pair(key, value, fn, data) < 0)
705 return -1;
707 else {
708 /* unknown format */
709 return error(_("bogus format in %s"),
710 CONFIG_DATA_ENVIRONMENT);
713 if (cur) {
714 while (isspace(*cur))
715 cur++;
718 return 0;
721 int git_config_from_parameters(config_fn_t fn, void *data)
723 const char *env;
724 struct strbuf envvar = STRBUF_INIT;
725 struct strvec to_free = STRVEC_INIT;
726 int ret = 0;
727 char *envw = NULL;
728 struct config_source source;
730 memset(&source, 0, sizeof(source));
731 source.prev = cf;
732 source.origin_type = CONFIG_ORIGIN_CMDLINE;
733 cf = &source;
735 env = getenv(CONFIG_COUNT_ENVIRONMENT);
736 if (env) {
737 unsigned long count;
738 char *endp;
739 int i;
741 count = strtoul(env, &endp, 10);
742 if (*endp) {
743 ret = error(_("bogus count in %s"), CONFIG_COUNT_ENVIRONMENT);
744 goto out;
746 if (count > INT_MAX) {
747 ret = error(_("too many entries in %s"), CONFIG_COUNT_ENVIRONMENT);
748 goto out;
751 for (i = 0; i < count; i++) {
752 const char *key, *value;
754 strbuf_addf(&envvar, "GIT_CONFIG_KEY_%d", i);
755 key = getenv_safe(&to_free, envvar.buf);
756 if (!key) {
757 ret = error(_("missing config key %s"), envvar.buf);
758 goto out;
760 strbuf_reset(&envvar);
762 strbuf_addf(&envvar, "GIT_CONFIG_VALUE_%d", i);
763 value = getenv_safe(&to_free, envvar.buf);
764 if (!value) {
765 ret = error(_("missing config value %s"), envvar.buf);
766 goto out;
768 strbuf_reset(&envvar);
770 if (config_parse_pair(key, value, fn, data) < 0) {
771 ret = -1;
772 goto out;
777 env = getenv(CONFIG_DATA_ENVIRONMENT);
778 if (env) {
779 /* sq_dequote will write over it */
780 envw = xstrdup(env);
781 if (parse_config_env_list(envw, fn, data) < 0) {
782 ret = -1;
783 goto out;
787 out:
788 strbuf_release(&envvar);
789 strvec_clear(&to_free);
790 free(envw);
791 cf = source.prev;
792 return ret;
795 static int get_next_char(void)
797 int c = cf->do_fgetc(cf);
799 if (c == '\r') {
800 /* DOS like systems */
801 c = cf->do_fgetc(cf);
802 if (c != '\n') {
803 if (c != EOF)
804 cf->do_ungetc(c, cf);
805 c = '\r';
809 if (c != EOF && ++cf->total_len > INT_MAX) {
811 * This is an absurdly long config file; refuse to parse
812 * further in order to protect downstream code from integer
813 * overflows. Note that we can't return an error specifically,
814 * but we can mark EOF and put trash in the return value,
815 * which will trigger a parse error.
817 cf->eof = 1;
818 return 0;
821 if (c == '\n')
822 cf->linenr++;
823 if (c == EOF) {
824 cf->eof = 1;
825 cf->linenr++;
826 c = '\n';
828 return c;
831 static char *parse_value(void)
833 int quote = 0, comment = 0, space = 0;
835 strbuf_reset(&cf->value);
836 for (;;) {
837 int c = get_next_char();
838 if (c == '\n') {
839 if (quote) {
840 cf->linenr--;
841 return NULL;
843 return cf->value.buf;
845 if (comment)
846 continue;
847 if (isspace(c) && !quote) {
848 if (cf->value.len)
849 space++;
850 continue;
852 if (!quote) {
853 if (c == ';' || c == '#') {
854 comment = 1;
855 continue;
858 for (; space; space--)
859 strbuf_addch(&cf->value, ' ');
860 if (c == '\\') {
861 c = get_next_char();
862 switch (c) {
863 case '\n':
864 continue;
865 case 't':
866 c = '\t';
867 break;
868 case 'b':
869 c = '\b';
870 break;
871 case 'n':
872 c = '\n';
873 break;
874 /* Some characters escape as themselves */
875 case '\\': case '"':
876 break;
877 /* Reject unknown escape sequences */
878 default:
879 return NULL;
881 strbuf_addch(&cf->value, c);
882 continue;
884 if (c == '"') {
885 quote = 1-quote;
886 continue;
888 strbuf_addch(&cf->value, c);
892 static int get_value(config_fn_t fn, void *data, struct strbuf *name)
894 int c;
895 char *value;
896 int ret;
898 /* Get the full name */
899 for (;;) {
900 c = get_next_char();
901 if (cf->eof)
902 break;
903 if (!iskeychar(c))
904 break;
905 strbuf_addch(name, tolower(c));
908 while (c == ' ' || c == '\t')
909 c = get_next_char();
911 value = NULL;
912 if (c != '\n') {
913 if (c != '=')
914 return -1;
915 value = parse_value();
916 if (!value)
917 return -1;
920 * We already consumed the \n, but we need linenr to point to
921 * the line we just parsed during the call to fn to get
922 * accurate line number in error messages.
924 cf->linenr--;
925 ret = fn(name->buf, value, data);
926 if (ret >= 0)
927 cf->linenr++;
928 return ret;
931 static int get_extended_base_var(struct strbuf *name, int c)
933 cf->subsection_case_sensitive = 0;
934 do {
935 if (c == '\n')
936 goto error_incomplete_line;
937 c = get_next_char();
938 } while (isspace(c));
940 /* We require the format to be '[base "extension"]' */
941 if (c != '"')
942 return -1;
943 strbuf_addch(name, '.');
945 for (;;) {
946 int c = get_next_char();
947 if (c == '\n')
948 goto error_incomplete_line;
949 if (c == '"')
950 break;
951 if (c == '\\') {
952 c = get_next_char();
953 if (c == '\n')
954 goto error_incomplete_line;
956 strbuf_addch(name, c);
959 /* Final ']' */
960 if (get_next_char() != ']')
961 return -1;
962 return 0;
963 error_incomplete_line:
964 cf->linenr--;
965 return -1;
968 static int get_base_var(struct strbuf *name)
970 cf->subsection_case_sensitive = 1;
971 for (;;) {
972 int c = get_next_char();
973 if (cf->eof)
974 return -1;
975 if (c == ']')
976 return 0;
977 if (isspace(c))
978 return get_extended_base_var(name, c);
979 if (!iskeychar(c) && c != '.')
980 return -1;
981 strbuf_addch(name, tolower(c));
985 struct parse_event_data {
986 enum config_event_t previous_type;
987 size_t previous_offset;
988 const struct config_options *opts;
991 static int do_event(enum config_event_t type, struct parse_event_data *data)
993 size_t offset;
995 if (!data->opts || !data->opts->event_fn)
996 return 0;
998 if (type == CONFIG_EVENT_WHITESPACE &&
999 data->previous_type == type)
1000 return 0;
1002 offset = cf->do_ftell(cf);
1004 * At EOF, the parser always "inserts" an extra '\n', therefore
1005 * the end offset of the event is the current file position, otherwise
1006 * we will already have advanced to the next event.
1008 if (type != CONFIG_EVENT_EOF)
1009 offset--;
1011 if (data->previous_type != CONFIG_EVENT_EOF &&
1012 data->opts->event_fn(data->previous_type, data->previous_offset,
1013 offset, data->opts->event_fn_data) < 0)
1014 return -1;
1016 data->previous_type = type;
1017 data->previous_offset = offset;
1019 return 0;
1022 static int git_parse_source(config_fn_t fn, void *data,
1023 const struct config_options *opts)
1025 int comment = 0;
1026 size_t baselen = 0;
1027 struct strbuf *var = &cf->var;
1028 int error_return = 0;
1029 char *error_msg = NULL;
1031 /* U+FEFF Byte Order Mark in UTF8 */
1032 const char *bomptr = utf8_bom;
1034 /* For the parser event callback */
1035 struct parse_event_data event_data = {
1036 CONFIG_EVENT_EOF, 0, opts
1039 for (;;) {
1040 int c;
1042 c = get_next_char();
1043 if (bomptr && *bomptr) {
1044 /* We are at the file beginning; skip UTF8-encoded BOM
1045 * if present. Sane editors won't put this in on their
1046 * own, but e.g. Windows Notepad will do it happily. */
1047 if (c == (*bomptr & 0377)) {
1048 bomptr++;
1049 continue;
1050 } else {
1051 /* Do not tolerate partial BOM. */
1052 if (bomptr != utf8_bom)
1053 break;
1054 /* No BOM at file beginning. Cool. */
1055 bomptr = NULL;
1058 if (c == '\n') {
1059 if (cf->eof) {
1060 if (do_event(CONFIG_EVENT_EOF, &event_data) < 0)
1061 return -1;
1062 return 0;
1064 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1065 return -1;
1066 comment = 0;
1067 continue;
1069 if (comment)
1070 continue;
1071 if (isspace(c)) {
1072 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1073 return -1;
1074 continue;
1076 if (c == '#' || c == ';') {
1077 if (do_event(CONFIG_EVENT_COMMENT, &event_data) < 0)
1078 return -1;
1079 comment = 1;
1080 continue;
1082 if (c == '[') {
1083 if (do_event(CONFIG_EVENT_SECTION, &event_data) < 0)
1084 return -1;
1086 /* Reset prior to determining a new stem */
1087 strbuf_reset(var);
1088 if (get_base_var(var) < 0 || var->len < 1)
1089 break;
1090 strbuf_addch(var, '.');
1091 baselen = var->len;
1092 continue;
1094 if (!isalpha(c))
1095 break;
1097 if (do_event(CONFIG_EVENT_ENTRY, &event_data) < 0)
1098 return -1;
1101 * Truncate the var name back to the section header
1102 * stem prior to grabbing the suffix part of the name
1103 * and the value.
1105 strbuf_setlen(var, baselen);
1106 strbuf_addch(var, tolower(c));
1107 if (get_value(fn, data, var) < 0)
1108 break;
1111 if (do_event(CONFIG_EVENT_ERROR, &event_data) < 0)
1112 return -1;
1114 switch (cf->origin_type) {
1115 case CONFIG_ORIGIN_BLOB:
1116 error_msg = xstrfmt(_("bad config line %d in blob %s"),
1117 cf->linenr, cf->name);
1118 break;
1119 case CONFIG_ORIGIN_FILE:
1120 error_msg = xstrfmt(_("bad config line %d in file %s"),
1121 cf->linenr, cf->name);
1122 break;
1123 case CONFIG_ORIGIN_STDIN:
1124 error_msg = xstrfmt(_("bad config line %d in standard input"),
1125 cf->linenr);
1126 break;
1127 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1128 error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
1129 cf->linenr, cf->name);
1130 break;
1131 case CONFIG_ORIGIN_CMDLINE:
1132 error_msg = xstrfmt(_("bad config line %d in command line %s"),
1133 cf->linenr, cf->name);
1134 break;
1135 default:
1136 error_msg = xstrfmt(_("bad config line %d in %s"),
1137 cf->linenr, cf->name);
1140 switch (opts && opts->error_action ?
1141 opts->error_action :
1142 cf->default_error_action) {
1143 case CONFIG_ERROR_DIE:
1144 die("%s", error_msg);
1145 break;
1146 case CONFIG_ERROR_ERROR:
1147 error_return = error("%s", error_msg);
1148 break;
1149 case CONFIG_ERROR_SILENT:
1150 error_return = -1;
1151 break;
1152 case CONFIG_ERROR_UNSET:
1153 BUG("config error action unset");
1156 free(error_msg);
1157 return error_return;
1160 static uintmax_t get_unit_factor(const char *end)
1162 if (!*end)
1163 return 1;
1164 else if (!strcasecmp(end, "k"))
1165 return 1024;
1166 else if (!strcasecmp(end, "m"))
1167 return 1024 * 1024;
1168 else if (!strcasecmp(end, "g"))
1169 return 1024 * 1024 * 1024;
1170 return 0;
1173 static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
1175 if (value && *value) {
1176 char *end;
1177 intmax_t val;
1178 intmax_t factor;
1180 if (max < 0)
1181 BUG("max must be a positive integer");
1183 errno = 0;
1184 val = strtoimax(value, &end, 0);
1185 if (errno == ERANGE)
1186 return 0;
1187 if (end == value) {
1188 errno = EINVAL;
1189 return 0;
1191 factor = get_unit_factor(end);
1192 if (!factor) {
1193 errno = EINVAL;
1194 return 0;
1196 if ((val < 0 && -max / factor > val) ||
1197 (val > 0 && max / factor < val)) {
1198 errno = ERANGE;
1199 return 0;
1201 val *= factor;
1202 *ret = val;
1203 return 1;
1205 errno = EINVAL;
1206 return 0;
1209 static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
1211 if (value && *value) {
1212 char *end;
1213 uintmax_t val;
1214 uintmax_t factor;
1216 /* negative values would be accepted by strtoumax */
1217 if (strchr(value, '-')) {
1218 errno = EINVAL;
1219 return 0;
1221 errno = 0;
1222 val = strtoumax(value, &end, 0);
1223 if (errno == ERANGE)
1224 return 0;
1225 if (end == value) {
1226 errno = EINVAL;
1227 return 0;
1229 factor = get_unit_factor(end);
1230 if (!factor) {
1231 errno = EINVAL;
1232 return 0;
1234 if (unsigned_mult_overflows(factor, val) ||
1235 factor * val > max) {
1236 errno = ERANGE;
1237 return 0;
1239 val *= factor;
1240 *ret = val;
1241 return 1;
1243 errno = EINVAL;
1244 return 0;
1247 int git_parse_int(const char *value, int *ret)
1249 intmax_t tmp;
1250 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
1251 return 0;
1252 *ret = tmp;
1253 return 1;
1256 static int git_parse_int64(const char *value, int64_t *ret)
1258 intmax_t tmp;
1259 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
1260 return 0;
1261 *ret = tmp;
1262 return 1;
1265 int git_parse_ulong(const char *value, unsigned long *ret)
1267 uintmax_t tmp;
1268 if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
1269 return 0;
1270 *ret = tmp;
1271 return 1;
1274 int git_parse_ssize_t(const char *value, ssize_t *ret)
1276 intmax_t tmp;
1277 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(ssize_t)))
1278 return 0;
1279 *ret = tmp;
1280 return 1;
1283 NORETURN
1284 static void die_bad_number(const char *name, const char *value)
1286 const char *error_type = (errno == ERANGE) ?
1287 N_("out of range") : N_("invalid unit");
1288 const char *bad_numeric = N_("bad numeric config value '%s' for '%s': %s");
1290 if (!value)
1291 value = "";
1293 if (!(cf && cf->name))
1294 die(_(bad_numeric), value, name, _(error_type));
1296 switch (cf->origin_type) {
1297 case CONFIG_ORIGIN_BLOB:
1298 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
1299 value, name, cf->name, _(error_type));
1300 case CONFIG_ORIGIN_FILE:
1301 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
1302 value, name, cf->name, _(error_type));
1303 case CONFIG_ORIGIN_STDIN:
1304 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
1305 value, name, _(error_type));
1306 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1307 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
1308 value, name, cf->name, _(error_type));
1309 case CONFIG_ORIGIN_CMDLINE:
1310 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
1311 value, name, cf->name, _(error_type));
1312 default:
1313 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
1314 value, name, cf->name, _(error_type));
1318 int git_config_int(const char *name, const char *value)
1320 int ret;
1321 if (!git_parse_int(value, &ret))
1322 die_bad_number(name, value);
1323 return ret;
1326 int64_t git_config_int64(const char *name, const char *value)
1328 int64_t ret;
1329 if (!git_parse_int64(value, &ret))
1330 die_bad_number(name, value);
1331 return ret;
1334 unsigned long git_config_ulong(const char *name, const char *value)
1336 unsigned long ret;
1337 if (!git_parse_ulong(value, &ret))
1338 die_bad_number(name, value);
1339 return ret;
1342 ssize_t git_config_ssize_t(const char *name, const char *value)
1344 ssize_t ret;
1345 if (!git_parse_ssize_t(value, &ret))
1346 die_bad_number(name, value);
1347 return ret;
1350 static int git_parse_maybe_bool_text(const char *value)
1352 if (!value)
1353 return 1;
1354 if (!*value)
1355 return 0;
1356 if (!strcasecmp(value, "true")
1357 || !strcasecmp(value, "yes")
1358 || !strcasecmp(value, "on"))
1359 return 1;
1360 if (!strcasecmp(value, "false")
1361 || !strcasecmp(value, "no")
1362 || !strcasecmp(value, "off"))
1363 return 0;
1364 return -1;
1367 static const struct fsync_component_name {
1368 const char *name;
1369 enum fsync_component component_bits;
1370 } fsync_component_names[] = {
1371 { "loose-object", FSYNC_COMPONENT_LOOSE_OBJECT },
1372 { "pack", FSYNC_COMPONENT_PACK },
1373 { "pack-metadata", FSYNC_COMPONENT_PACK_METADATA },
1374 { "commit-graph", FSYNC_COMPONENT_COMMIT_GRAPH },
1375 { "index", FSYNC_COMPONENT_INDEX },
1376 { "objects", FSYNC_COMPONENTS_OBJECTS },
1377 { "reference", FSYNC_COMPONENT_REFERENCE },
1378 { "derived-metadata", FSYNC_COMPONENTS_DERIVED_METADATA },
1379 { "committed", FSYNC_COMPONENTS_COMMITTED },
1380 { "added", FSYNC_COMPONENTS_ADDED },
1381 { "all", FSYNC_COMPONENTS_ALL },
1384 static enum fsync_component parse_fsync_components(const char *var, const char *string)
1386 enum fsync_component current = FSYNC_COMPONENTS_PLATFORM_DEFAULT;
1387 enum fsync_component positive = 0, negative = 0;
1389 while (string) {
1390 int i;
1391 size_t len;
1392 const char *ep;
1393 int negated = 0;
1394 int found = 0;
1396 string = string + strspn(string, ", \t\n\r");
1397 ep = strchrnul(string, ',');
1398 len = ep - string;
1399 if (!strcmp(string, "none")) {
1400 current = FSYNC_COMPONENT_NONE;
1401 goto next_name;
1404 if (*string == '-') {
1405 negated = 1;
1406 string++;
1407 len--;
1408 if (!len)
1409 warning(_("invalid value for variable %s"), var);
1412 if (!len)
1413 break;
1415 for (i = 0; i < ARRAY_SIZE(fsync_component_names); ++i) {
1416 const struct fsync_component_name *n = &fsync_component_names[i];
1418 if (strncmp(n->name, string, len))
1419 continue;
1421 found = 1;
1422 if (negated)
1423 negative |= n->component_bits;
1424 else
1425 positive |= n->component_bits;
1428 if (!found) {
1429 char *component = xstrndup(string, len);
1430 warning(_("ignoring unknown core.fsync component '%s'"), component);
1431 free(component);
1434 next_name:
1435 string = ep;
1438 return (current & ~negative) | positive;
1441 int git_parse_maybe_bool(const char *value)
1443 int v = git_parse_maybe_bool_text(value);
1444 if (0 <= v)
1445 return v;
1446 if (git_parse_int(value, &v))
1447 return !!v;
1448 return -1;
1451 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
1453 int v = git_parse_maybe_bool_text(value);
1454 if (0 <= v) {
1455 *is_bool = 1;
1456 return v;
1458 *is_bool = 0;
1459 return git_config_int(name, value);
1462 int git_config_bool(const char *name, const char *value)
1464 int v = git_parse_maybe_bool(value);
1465 if (v < 0)
1466 die(_("bad boolean config value '%s' for '%s'"), value, name);
1467 return v;
1470 int git_config_string(const char **dest, const char *var, const char *value)
1472 if (!value)
1473 return config_error_nonbool(var);
1474 *dest = xstrdup(value);
1475 return 0;
1478 int git_config_pathname(const char **dest, const char *var, const char *value)
1480 if (!value)
1481 return config_error_nonbool(var);
1482 *dest = interpolate_path(value, 0);
1483 if (!*dest)
1484 die(_("failed to expand user dir in: '%s'"), value);
1485 return 0;
1488 int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1490 if (!value)
1491 return config_error_nonbool(var);
1492 if (parse_expiry_date(value, timestamp))
1493 return error(_("'%s' for '%s' is not a valid timestamp"),
1494 value, var);
1495 return 0;
1498 int git_config_color(char *dest, const char *var, const char *value)
1500 if (!value)
1501 return config_error_nonbool(var);
1502 if (color_parse(value, dest) < 0)
1503 return -1;
1504 return 0;
1507 static int git_default_core_config(const char *var, const char *value, void *cb)
1509 /* This needs a better name */
1510 if (!strcmp(var, "core.filemode")) {
1511 trust_executable_bit = git_config_bool(var, value);
1512 return 0;
1514 if (!strcmp(var, "core.trustctime")) {
1515 trust_ctime = git_config_bool(var, value);
1516 return 0;
1518 if (!strcmp(var, "core.checkstat")) {
1519 if (!strcasecmp(value, "default"))
1520 check_stat = 1;
1521 else if (!strcasecmp(value, "minimal"))
1522 check_stat = 0;
1525 if (!strcmp(var, "core.quotepath")) {
1526 quote_path_fully = git_config_bool(var, value);
1527 return 0;
1530 if (!strcmp(var, "core.symlinks")) {
1531 has_symlinks = git_config_bool(var, value);
1532 return 0;
1535 if (!strcmp(var, "core.ignorecase")) {
1536 ignore_case = git_config_bool(var, value);
1537 return 0;
1540 if (!strcmp(var, "core.attributesfile"))
1541 return git_config_pathname(&git_attributes_file, var, value);
1543 if (!strcmp(var, "core.hookspath"))
1544 return git_config_pathname(&git_hooks_path, var, value);
1546 if (!strcmp(var, "core.bare")) {
1547 is_bare_repository_cfg = git_config_bool(var, value);
1548 return 0;
1551 if (!strcmp(var, "core.ignorestat")) {
1552 assume_unchanged = git_config_bool(var, value);
1553 return 0;
1556 if (!strcmp(var, "core.prefersymlinkrefs")) {
1557 prefer_symlink_refs = git_config_bool(var, value);
1558 return 0;
1561 if (!strcmp(var, "core.logallrefupdates")) {
1562 if (value && !strcasecmp(value, "always"))
1563 log_all_ref_updates = LOG_REFS_ALWAYS;
1564 else if (git_config_bool(var, value))
1565 log_all_ref_updates = LOG_REFS_NORMAL;
1566 else
1567 log_all_ref_updates = LOG_REFS_NONE;
1568 return 0;
1571 if (!strcmp(var, "core.warnambiguousrefs")) {
1572 warn_ambiguous_refs = git_config_bool(var, value);
1573 return 0;
1576 if (!strcmp(var, "core.abbrev")) {
1577 if (!value)
1578 return config_error_nonbool(var);
1579 if (!strcasecmp(value, "auto"))
1580 default_abbrev = -1;
1581 else if (!git_parse_maybe_bool_text(value))
1582 default_abbrev = the_hash_algo->hexsz;
1583 else {
1584 int abbrev = git_config_int(var, value);
1585 if (abbrev < minimum_abbrev || abbrev > the_hash_algo->hexsz)
1586 return error(_("abbrev length out of range: %d"), abbrev);
1587 default_abbrev = abbrev;
1589 return 0;
1592 if (!strcmp(var, "core.disambiguate"))
1593 return set_disambiguate_hint_config(var, value);
1595 if (!strcmp(var, "core.loosecompression")) {
1596 int level = git_config_int(var, value);
1597 if (level == -1)
1598 level = Z_DEFAULT_COMPRESSION;
1599 else if (level < 0 || level > Z_BEST_COMPRESSION)
1600 die(_("bad zlib compression level %d"), level);
1601 zlib_compression_level = level;
1602 zlib_compression_seen = 1;
1603 return 0;
1606 if (!strcmp(var, "core.compression")) {
1607 int level = git_config_int(var, value);
1608 if (level == -1)
1609 level = Z_DEFAULT_COMPRESSION;
1610 else if (level < 0 || level > Z_BEST_COMPRESSION)
1611 die(_("bad zlib compression level %d"), level);
1612 if (!zlib_compression_seen)
1613 zlib_compression_level = level;
1614 if (!pack_compression_seen)
1615 pack_compression_level = level;
1616 return 0;
1619 if (!strcmp(var, "core.packedgitwindowsize")) {
1620 int pgsz_x2 = getpagesize() * 2;
1621 packed_git_window_size = git_config_ulong(var, value);
1623 /* This value must be multiple of (pagesize * 2) */
1624 packed_git_window_size /= pgsz_x2;
1625 if (packed_git_window_size < 1)
1626 packed_git_window_size = 1;
1627 packed_git_window_size *= pgsz_x2;
1628 return 0;
1631 if (!strcmp(var, "core.bigfilethreshold")) {
1632 big_file_threshold = git_config_ulong(var, value);
1633 return 0;
1636 if (!strcmp(var, "core.packedgitlimit")) {
1637 packed_git_limit = git_config_ulong(var, value);
1638 return 0;
1641 if (!strcmp(var, "core.deltabasecachelimit")) {
1642 delta_base_cache_limit = git_config_ulong(var, value);
1643 return 0;
1646 if (!strcmp(var, "core.autocrlf")) {
1647 if (value && !strcasecmp(value, "input")) {
1648 auto_crlf = AUTO_CRLF_INPUT;
1649 return 0;
1651 auto_crlf = git_config_bool(var, value);
1652 return 0;
1655 if (!strcmp(var, "core.safecrlf")) {
1656 int eol_rndtrp_die;
1657 if (value && !strcasecmp(value, "warn")) {
1658 global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
1659 return 0;
1661 eol_rndtrp_die = git_config_bool(var, value);
1662 global_conv_flags_eol = eol_rndtrp_die ?
1663 CONV_EOL_RNDTRP_DIE : 0;
1664 return 0;
1667 if (!strcmp(var, "core.eol")) {
1668 if (value && !strcasecmp(value, "lf"))
1669 core_eol = EOL_LF;
1670 else if (value && !strcasecmp(value, "crlf"))
1671 core_eol = EOL_CRLF;
1672 else if (value && !strcasecmp(value, "native"))
1673 core_eol = EOL_NATIVE;
1674 else
1675 core_eol = EOL_UNSET;
1676 return 0;
1679 if (!strcmp(var, "core.checkroundtripencoding")) {
1680 check_roundtrip_encoding = xstrdup(value);
1681 return 0;
1684 if (!strcmp(var, "core.notesref")) {
1685 notes_ref_name = xstrdup(value);
1686 return 0;
1689 if (!strcmp(var, "core.editor"))
1690 return git_config_string(&editor_program, var, value);
1692 if (!strcmp(var, "core.commentchar")) {
1693 if (!value)
1694 return config_error_nonbool(var);
1695 else if (!strcasecmp(value, "auto"))
1696 auto_comment_line_char = 1;
1697 else if (value[0] && !value[1]) {
1698 comment_line_char = value[0];
1699 auto_comment_line_char = 0;
1700 } else
1701 return error(_("core.commentChar should only be one character"));
1702 return 0;
1705 if (!strcmp(var, "core.askpass"))
1706 return git_config_string(&askpass_program, var, value);
1708 if (!strcmp(var, "core.excludesfile"))
1709 return git_config_pathname(&excludes_file, var, value);
1711 if (!strcmp(var, "core.whitespace")) {
1712 if (!value)
1713 return config_error_nonbool(var);
1714 whitespace_rule_cfg = parse_whitespace_rule(value);
1715 return 0;
1718 if (!strcmp(var, "core.fsync")) {
1719 if (!value)
1720 return config_error_nonbool(var);
1721 fsync_components = parse_fsync_components(var, value);
1722 return 0;
1725 if (!strcmp(var, "core.fsyncmethod")) {
1726 if (!value)
1727 return config_error_nonbool(var);
1728 if (!strcmp(value, "fsync"))
1729 fsync_method = FSYNC_METHOD_FSYNC;
1730 else if (!strcmp(value, "writeout-only"))
1731 fsync_method = FSYNC_METHOD_WRITEOUT_ONLY;
1732 else if (!strcmp(value, "batch"))
1733 fsync_method = FSYNC_METHOD_BATCH;
1734 else
1735 warning(_("ignoring unknown core.fsyncMethod value '%s'"), value);
1739 if (!strcmp(var, "core.fsyncobjectfiles")) {
1740 if (fsync_object_files < 0)
1741 warning(_("core.fsyncObjectFiles is deprecated; use core.fsync instead"));
1742 fsync_object_files = git_config_bool(var, value);
1743 return 0;
1746 if (!strcmp(var, "core.preloadindex")) {
1747 core_preload_index = git_config_bool(var, value);
1748 return 0;
1751 if (!strcmp(var, "core.createobject")) {
1752 if (!strcmp(value, "rename"))
1753 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
1754 else if (!strcmp(value, "link"))
1755 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
1756 else
1757 die(_("invalid mode for object creation: %s"), value);
1758 return 0;
1761 if (!strcmp(var, "core.sparsecheckout")) {
1762 core_apply_sparse_checkout = git_config_bool(var, value);
1763 return 0;
1766 if (!strcmp(var, "core.sparsecheckoutcone")) {
1767 core_sparse_checkout_cone = git_config_bool(var, value);
1768 return 0;
1771 if (!strcmp(var, "core.precomposeunicode")) {
1772 precomposed_unicode = git_config_bool(var, value);
1773 return 0;
1776 if (!strcmp(var, "core.protecthfs")) {
1777 protect_hfs = git_config_bool(var, value);
1778 return 0;
1781 if (!strcmp(var, "core.protectntfs")) {
1782 protect_ntfs = git_config_bool(var, value);
1783 return 0;
1786 if (!strcmp(var, "core.usereplacerefs")) {
1787 read_replace_refs = git_config_bool(var, value);
1788 return 0;
1791 /* Add other config variables here and to Documentation/config.txt. */
1792 return platform_core_config(var, value, cb);
1795 static int git_default_sparse_config(const char *var, const char *value)
1797 if (!strcmp(var, "sparse.expectfilesoutsideofpatterns")) {
1798 sparse_expect_files_outside_of_patterns = git_config_bool(var, value);
1799 return 0;
1802 /* Add other config variables here and to Documentation/config/sparse.txt. */
1803 return 0;
1806 static int git_default_i18n_config(const char *var, const char *value)
1808 if (!strcmp(var, "i18n.commitencoding"))
1809 return git_config_string(&git_commit_encoding, var, value);
1811 if (!strcmp(var, "i18n.logoutputencoding"))
1812 return git_config_string(&git_log_output_encoding, var, value);
1814 /* Add other config variables here and to Documentation/config.txt. */
1815 return 0;
1818 static int git_default_branch_config(const char *var, const char *value)
1820 if (!strcmp(var, "branch.autosetupmerge")) {
1821 if (value && !strcmp(value, "always")) {
1822 git_branch_track = BRANCH_TRACK_ALWAYS;
1823 return 0;
1824 } else if (value && !strcmp(value, "inherit")) {
1825 git_branch_track = BRANCH_TRACK_INHERIT;
1826 return 0;
1827 } else if (value && !strcmp(value, "simple")) {
1828 git_branch_track = BRANCH_TRACK_SIMPLE;
1829 return 0;
1831 git_branch_track = git_config_bool(var, value);
1832 return 0;
1834 if (!strcmp(var, "branch.autosetuprebase")) {
1835 if (!value)
1836 return config_error_nonbool(var);
1837 else if (!strcmp(value, "never"))
1838 autorebase = AUTOREBASE_NEVER;
1839 else if (!strcmp(value, "local"))
1840 autorebase = AUTOREBASE_LOCAL;
1841 else if (!strcmp(value, "remote"))
1842 autorebase = AUTOREBASE_REMOTE;
1843 else if (!strcmp(value, "always"))
1844 autorebase = AUTOREBASE_ALWAYS;
1845 else
1846 return error(_("malformed value for %s"), var);
1847 return 0;
1850 /* Add other config variables here and to Documentation/config.txt. */
1851 return 0;
1854 static int git_default_push_config(const char *var, const char *value)
1856 if (!strcmp(var, "push.default")) {
1857 if (!value)
1858 return config_error_nonbool(var);
1859 else if (!strcmp(value, "nothing"))
1860 push_default = PUSH_DEFAULT_NOTHING;
1861 else if (!strcmp(value, "matching"))
1862 push_default = PUSH_DEFAULT_MATCHING;
1863 else if (!strcmp(value, "simple"))
1864 push_default = PUSH_DEFAULT_SIMPLE;
1865 else if (!strcmp(value, "upstream"))
1866 push_default = PUSH_DEFAULT_UPSTREAM;
1867 else if (!strcmp(value, "tracking")) /* deprecated */
1868 push_default = PUSH_DEFAULT_UPSTREAM;
1869 else if (!strcmp(value, "current"))
1870 push_default = PUSH_DEFAULT_CURRENT;
1871 else {
1872 error(_("malformed value for %s: %s"), var, value);
1873 return error(_("must be one of nothing, matching, simple, "
1874 "upstream or current"));
1876 return 0;
1879 /* Add other config variables here and to Documentation/config.txt. */
1880 return 0;
1883 static int git_default_mailmap_config(const char *var, const char *value)
1885 if (!strcmp(var, "mailmap.file"))
1886 return git_config_pathname(&git_mailmap_file, var, value);
1887 if (!strcmp(var, "mailmap.blob"))
1888 return git_config_string(&git_mailmap_blob, var, value);
1890 /* Add other config variables here and to Documentation/config.txt. */
1891 return 0;
1894 int git_default_config(const char *var, const char *value, void *cb)
1896 if (starts_with(var, "core."))
1897 return git_default_core_config(var, value, cb);
1899 if (starts_with(var, "user.") ||
1900 starts_with(var, "author.") ||
1901 starts_with(var, "committer."))
1902 return git_ident_config(var, value, cb);
1904 if (starts_with(var, "i18n."))
1905 return git_default_i18n_config(var, value);
1907 if (starts_with(var, "branch."))
1908 return git_default_branch_config(var, value);
1910 if (starts_with(var, "push."))
1911 return git_default_push_config(var, value);
1913 if (starts_with(var, "mailmap."))
1914 return git_default_mailmap_config(var, value);
1916 if (starts_with(var, "advice.") || starts_with(var, "color.advice"))
1917 return git_default_advice_config(var, value);
1919 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1920 pager_use_color = git_config_bool(var,value);
1921 return 0;
1924 if (!strcmp(var, "pack.packsizelimit")) {
1925 pack_size_limit_cfg = git_config_ulong(var, value);
1926 return 0;
1929 if (!strcmp(var, "pack.compression")) {
1930 int level = git_config_int(var, value);
1931 if (level == -1)
1932 level = Z_DEFAULT_COMPRESSION;
1933 else if (level < 0 || level > Z_BEST_COMPRESSION)
1934 die(_("bad pack compression level %d"), level);
1935 pack_compression_level = level;
1936 pack_compression_seen = 1;
1937 return 0;
1940 if (starts_with(var, "sparse."))
1941 return git_default_sparse_config(var, value);
1943 /* Add other config variables here and to Documentation/config.txt. */
1944 return 0;
1948 * All source specific fields in the union, die_on_error, name and the callbacks
1949 * fgetc, ungetc, ftell of top need to be initialized before calling
1950 * this function.
1952 static int do_config_from(struct config_source *top, config_fn_t fn, void *data,
1953 const struct config_options *opts)
1955 int ret;
1957 /* push config-file parsing state stack */
1958 top->prev = cf;
1959 top->linenr = 1;
1960 top->eof = 0;
1961 top->total_len = 0;
1962 strbuf_init(&top->value, 1024);
1963 strbuf_init(&top->var, 1024);
1964 cf = top;
1966 ret = git_parse_source(fn, data, opts);
1968 /* pop config-file parsing state stack */
1969 strbuf_release(&top->value);
1970 strbuf_release(&top->var);
1971 cf = top->prev;
1973 return ret;
1976 static int do_config_from_file(config_fn_t fn,
1977 const enum config_origin_type origin_type,
1978 const char *name, const char *path, FILE *f,
1979 void *data, const struct config_options *opts)
1981 struct config_source top;
1982 int ret;
1984 top.u.file = f;
1985 top.origin_type = origin_type;
1986 top.name = name;
1987 top.path = path;
1988 top.default_error_action = CONFIG_ERROR_DIE;
1989 top.do_fgetc = config_file_fgetc;
1990 top.do_ungetc = config_file_ungetc;
1991 top.do_ftell = config_file_ftell;
1993 flockfile(f);
1994 ret = do_config_from(&top, fn, data, opts);
1995 funlockfile(f);
1996 return ret;
1999 static int git_config_from_stdin(config_fn_t fn, void *data)
2001 return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", NULL, stdin,
2002 data, NULL);
2005 int git_config_from_file_with_options(config_fn_t fn, const char *filename,
2006 void *data,
2007 const struct config_options *opts)
2009 int ret = -1;
2010 FILE *f;
2012 if (!filename)
2013 BUG("filename cannot be NULL");
2014 f = fopen_or_warn(filename, "r");
2015 if (f) {
2016 ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename,
2017 filename, f, data, opts);
2018 fclose(f);
2020 return ret;
2023 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
2025 return git_config_from_file_with_options(fn, filename, data, NULL);
2028 int git_config_from_mem(config_fn_t fn,
2029 const enum config_origin_type origin_type,
2030 const char *name, const char *buf, size_t len,
2031 void *data, const struct config_options *opts)
2033 struct config_source top;
2035 top.u.buf.buf = buf;
2036 top.u.buf.len = len;
2037 top.u.buf.pos = 0;
2038 top.origin_type = origin_type;
2039 top.name = name;
2040 top.path = NULL;
2041 top.default_error_action = CONFIG_ERROR_ERROR;
2042 top.do_fgetc = config_buf_fgetc;
2043 top.do_ungetc = config_buf_ungetc;
2044 top.do_ftell = config_buf_ftell;
2046 return do_config_from(&top, fn, data, opts);
2049 int git_config_from_blob_oid(config_fn_t fn,
2050 const char *name,
2051 struct repository *repo,
2052 const struct object_id *oid,
2053 void *data)
2055 enum object_type type;
2056 char *buf;
2057 unsigned long size;
2058 int ret;
2060 buf = repo_read_object_file(repo, oid, &type, &size);
2061 if (!buf)
2062 return error(_("unable to load config blob object '%s'"), name);
2063 if (type != OBJ_BLOB) {
2064 free(buf);
2065 return error(_("reference '%s' does not point to a blob"), name);
2068 ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size,
2069 data, NULL);
2070 free(buf);
2072 return ret;
2075 static int git_config_from_blob_ref(config_fn_t fn,
2076 struct repository *repo,
2077 const char *name,
2078 void *data)
2080 struct object_id oid;
2082 if (repo_get_oid(repo, name, &oid) < 0)
2083 return error(_("unable to resolve config blob '%s'"), name);
2084 return git_config_from_blob_oid(fn, name, repo, &oid, data);
2087 char *git_system_config(void)
2089 char *system_config = xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
2090 if (!system_config)
2091 system_config = system_path(ETC_GITCONFIG);
2092 normalize_path_copy(system_config, system_config);
2093 return system_config;
2096 void git_global_config(char **user_out, char **xdg_out)
2098 char *user_config = xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
2099 char *xdg_config = NULL;
2101 if (!user_config) {
2102 user_config = interpolate_path("~/.gitconfig", 0);
2103 xdg_config = xdg_config_home("config");
2106 *user_out = user_config;
2107 *xdg_out = xdg_config;
2111 * Parse environment variable 'k' as a boolean (in various
2112 * possible spellings); if missing, use the default value 'def'.
2114 int git_env_bool(const char *k, int def)
2116 const char *v = getenv(k);
2117 return v ? git_config_bool(k, v) : def;
2121 * Parse environment variable 'k' as ulong with possibly a unit
2122 * suffix; if missing, use the default value 'val'.
2124 unsigned long git_env_ulong(const char *k, unsigned long val)
2126 const char *v = getenv(k);
2127 if (v && !git_parse_ulong(v, &val))
2128 die(_("failed to parse %s"), k);
2129 return val;
2132 int git_config_system(void)
2134 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
2137 static int do_git_config_sequence(const struct config_options *opts,
2138 config_fn_t fn, void *data)
2140 int ret = 0;
2141 char *system_config = git_system_config();
2142 char *xdg_config = NULL;
2143 char *user_config = NULL;
2144 char *repo_config;
2145 enum config_scope prev_parsing_scope = current_parsing_scope;
2147 if (opts->commondir)
2148 repo_config = mkpathdup("%s/config", opts->commondir);
2149 else if (opts->git_dir)
2150 BUG("git_dir without commondir");
2151 else
2152 repo_config = NULL;
2154 current_parsing_scope = CONFIG_SCOPE_SYSTEM;
2155 if (git_config_system() && system_config &&
2156 !access_or_die(system_config, R_OK,
2157 opts->system_gently ? ACCESS_EACCES_OK : 0))
2158 ret += git_config_from_file(fn, system_config, data);
2160 current_parsing_scope = CONFIG_SCOPE_GLOBAL;
2161 git_global_config(&user_config, &xdg_config);
2163 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
2164 ret += git_config_from_file(fn, xdg_config, data);
2166 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
2167 ret += git_config_from_file(fn, user_config, data);
2169 current_parsing_scope = CONFIG_SCOPE_LOCAL;
2170 if (!opts->ignore_repo && repo_config &&
2171 !access_or_die(repo_config, R_OK, 0))
2172 ret += git_config_from_file(fn, repo_config, data);
2174 current_parsing_scope = CONFIG_SCOPE_WORKTREE;
2175 if (!opts->ignore_worktree && repository_format_worktree_config) {
2176 char *path = git_pathdup("config.worktree");
2177 if (!access_or_die(path, R_OK, 0))
2178 ret += git_config_from_file(fn, path, data);
2179 free(path);
2182 current_parsing_scope = CONFIG_SCOPE_COMMAND;
2183 if (!opts->ignore_cmdline && git_config_from_parameters(fn, data) < 0)
2184 die(_("unable to parse command-line config"));
2186 current_parsing_scope = prev_parsing_scope;
2187 free(system_config);
2188 free(xdg_config);
2189 free(user_config);
2190 free(repo_config);
2191 return ret;
2194 int config_with_options(config_fn_t fn, void *data,
2195 struct git_config_source *config_source,
2196 const struct config_options *opts)
2198 struct config_include_data inc = CONFIG_INCLUDE_INIT;
2199 int ret;
2201 if (opts->respect_includes) {
2202 inc.fn = fn;
2203 inc.data = data;
2204 inc.opts = opts;
2205 inc.config_source = config_source;
2206 fn = git_config_include;
2207 data = &inc;
2210 if (config_source)
2211 current_parsing_scope = config_source->scope;
2214 * If we have a specific filename, use it. Otherwise, follow the
2215 * regular lookup sequence.
2217 if (config_source && config_source->use_stdin) {
2218 ret = git_config_from_stdin(fn, data);
2219 } else if (config_source && config_source->file) {
2220 ret = git_config_from_file(fn, config_source->file, data);
2221 } else if (config_source && config_source->blob) {
2222 struct repository *repo = config_source->repo ?
2223 config_source->repo : the_repository;
2224 ret = git_config_from_blob_ref(fn, repo, config_source->blob,
2225 data);
2226 } else {
2227 ret = do_git_config_sequence(opts, fn, data);
2230 if (inc.remote_urls) {
2231 string_list_clear(inc.remote_urls, 0);
2232 FREE_AND_NULL(inc.remote_urls);
2234 return ret;
2237 static void configset_iter(struct config_set *cs, config_fn_t fn, void *data)
2239 int i, value_index;
2240 struct string_list *values;
2241 struct config_set_element *entry;
2242 struct configset_list *list = &cs->list;
2244 for (i = 0; i < list->nr; i++) {
2245 entry = list->items[i].e;
2246 value_index = list->items[i].value_index;
2247 values = &entry->value_list;
2249 current_config_kvi = values->items[value_index].util;
2251 if (fn(entry->key, values->items[value_index].string, data) < 0)
2252 git_die_config_linenr(entry->key,
2253 current_config_kvi->filename,
2254 current_config_kvi->linenr);
2256 current_config_kvi = NULL;
2260 void read_early_config(config_fn_t cb, void *data)
2262 struct config_options opts = {0};
2263 struct strbuf commondir = STRBUF_INIT;
2264 struct strbuf gitdir = STRBUF_INIT;
2266 opts.respect_includes = 1;
2268 if (have_git_dir()) {
2269 opts.commondir = get_git_common_dir();
2270 opts.git_dir = get_git_dir();
2272 * When setup_git_directory() was not yet asked to discover the
2273 * GIT_DIR, we ask discover_git_directory() to figure out whether there
2274 * is any repository config we should use (but unlike
2275 * setup_git_directory_gently(), no global state is changed, most
2276 * notably, the current working directory is still the same after the
2277 * call).
2279 } else if (!discover_git_directory(&commondir, &gitdir)) {
2280 opts.commondir = commondir.buf;
2281 opts.git_dir = gitdir.buf;
2284 config_with_options(cb, data, NULL, &opts);
2286 strbuf_release(&commondir);
2287 strbuf_release(&gitdir);
2291 * Read config but only enumerate system and global settings.
2292 * Omit any repo-local, worktree-local, or command-line settings.
2294 void read_very_early_config(config_fn_t cb, void *data)
2296 struct config_options opts = { 0 };
2298 opts.respect_includes = 1;
2299 opts.ignore_repo = 1;
2300 opts.ignore_worktree = 1;
2301 opts.ignore_cmdline = 1;
2302 opts.system_gently = 1;
2304 config_with_options(cb, data, NULL, &opts);
2307 static struct config_set_element *configset_find_element(struct config_set *cs, const char *key)
2309 struct config_set_element k;
2310 struct config_set_element *found_entry;
2311 char *normalized_key;
2313 * `key` may come from the user, so normalize it before using it
2314 * for querying entries from the hashmap.
2316 if (git_config_parse_key(key, &normalized_key, NULL))
2317 return NULL;
2319 hashmap_entry_init(&k.ent, strhash(normalized_key));
2320 k.key = normalized_key;
2321 found_entry = hashmap_get_entry(&cs->config_hash, &k, ent, NULL);
2322 free(normalized_key);
2323 return found_entry;
2326 static int configset_add_value(struct config_set *cs, const char *key, const char *value)
2328 struct config_set_element *e;
2329 struct string_list_item *si;
2330 struct configset_list_item *l_item;
2331 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
2333 e = configset_find_element(cs, key);
2335 * Since the keys are being fed by git_config*() callback mechanism, they
2336 * are already normalized. So simply add them without any further munging.
2338 if (!e) {
2339 e = xmalloc(sizeof(*e));
2340 hashmap_entry_init(&e->ent, strhash(key));
2341 e->key = xstrdup(key);
2342 string_list_init_dup(&e->value_list);
2343 hashmap_add(&cs->config_hash, &e->ent);
2345 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
2347 ALLOC_GROW(cs->list.items, cs->list.nr + 1, cs->list.alloc);
2348 l_item = &cs->list.items[cs->list.nr++];
2349 l_item->e = e;
2350 l_item->value_index = e->value_list.nr - 1;
2352 if (!cf)
2353 BUG("configset_add_value has no source");
2354 if (cf->name) {
2355 kv_info->filename = strintern(cf->name);
2356 kv_info->linenr = cf->linenr;
2357 kv_info->origin_type = cf->origin_type;
2358 } else {
2359 /* for values read from `git_config_from_parameters()` */
2360 kv_info->filename = NULL;
2361 kv_info->linenr = -1;
2362 kv_info->origin_type = CONFIG_ORIGIN_CMDLINE;
2364 kv_info->scope = current_parsing_scope;
2365 si->util = kv_info;
2367 return 0;
2370 static int config_set_element_cmp(const void *cmp_data UNUSED,
2371 const struct hashmap_entry *eptr,
2372 const struct hashmap_entry *entry_or_key,
2373 const void *keydata UNUSED)
2375 const struct config_set_element *e1, *e2;
2377 e1 = container_of(eptr, const struct config_set_element, ent);
2378 e2 = container_of(entry_or_key, const struct config_set_element, ent);
2380 return strcmp(e1->key, e2->key);
2383 void git_configset_init(struct config_set *cs)
2385 hashmap_init(&cs->config_hash, config_set_element_cmp, NULL, 0);
2386 cs->hash_initialized = 1;
2387 cs->list.nr = 0;
2388 cs->list.alloc = 0;
2389 cs->list.items = NULL;
2392 void git_configset_clear(struct config_set *cs)
2394 struct config_set_element *entry;
2395 struct hashmap_iter iter;
2396 if (!cs->hash_initialized)
2397 return;
2399 hashmap_for_each_entry(&cs->config_hash, &iter, entry,
2400 ent /* member name */) {
2401 free(entry->key);
2402 string_list_clear(&entry->value_list, 1);
2404 hashmap_clear_and_free(&cs->config_hash, struct config_set_element, ent);
2405 cs->hash_initialized = 0;
2406 free(cs->list.items);
2407 cs->list.nr = 0;
2408 cs->list.alloc = 0;
2409 cs->list.items = NULL;
2412 static int config_set_callback(const char *key, const char *value, void *cb)
2414 struct config_set *cs = cb;
2415 configset_add_value(cs, key, value);
2416 return 0;
2419 int git_configset_add_file(struct config_set *cs, const char *filename)
2421 return git_config_from_file(config_set_callback, filename, cs);
2424 int git_configset_get_value(struct config_set *cs, const char *key, const char **value)
2426 const struct string_list *values = NULL;
2428 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
2429 * queried key in the files of the configset, the value returned will be the last
2430 * value in the value list for that key.
2432 values = git_configset_get_value_multi(cs, key);
2434 if (!values)
2435 return 1;
2436 assert(values->nr > 0);
2437 *value = values->items[values->nr - 1].string;
2438 return 0;
2441 const struct string_list *git_configset_get_value_multi(struct config_set *cs, const char *key)
2443 struct config_set_element *e = configset_find_element(cs, key);
2444 return e ? &e->value_list : NULL;
2447 int git_configset_get_string(struct config_set *cs, const char *key, char **dest)
2449 const char *value;
2450 if (!git_configset_get_value(cs, key, &value))
2451 return git_config_string((const char **)dest, key, value);
2452 else
2453 return 1;
2456 static int git_configset_get_string_tmp(struct config_set *cs, const char *key,
2457 const char **dest)
2459 const char *value;
2460 if (!git_configset_get_value(cs, key, &value)) {
2461 if (!value)
2462 return config_error_nonbool(key);
2463 *dest = value;
2464 return 0;
2465 } else {
2466 return 1;
2470 int git_configset_get_int(struct config_set *cs, const char *key, int *dest)
2472 const char *value;
2473 if (!git_configset_get_value(cs, key, &value)) {
2474 *dest = git_config_int(key, value);
2475 return 0;
2476 } else
2477 return 1;
2480 int git_configset_get_ulong(struct config_set *cs, const char *key, unsigned long *dest)
2482 const char *value;
2483 if (!git_configset_get_value(cs, key, &value)) {
2484 *dest = git_config_ulong(key, value);
2485 return 0;
2486 } else
2487 return 1;
2490 int git_configset_get_bool(struct config_set *cs, const char *key, int *dest)
2492 const char *value;
2493 if (!git_configset_get_value(cs, key, &value)) {
2494 *dest = git_config_bool(key, value);
2495 return 0;
2496 } else
2497 return 1;
2500 int git_configset_get_bool_or_int(struct config_set *cs, const char *key,
2501 int *is_bool, int *dest)
2503 const char *value;
2504 if (!git_configset_get_value(cs, key, &value)) {
2505 *dest = git_config_bool_or_int(key, value, is_bool);
2506 return 0;
2507 } else
2508 return 1;
2511 int git_configset_get_maybe_bool(struct config_set *cs, const char *key, int *dest)
2513 const char *value;
2514 if (!git_configset_get_value(cs, key, &value)) {
2515 *dest = git_parse_maybe_bool(value);
2516 if (*dest == -1)
2517 return -1;
2518 return 0;
2519 } else
2520 return 1;
2523 int git_configset_get_pathname(struct config_set *cs, const char *key, const char **dest)
2525 const char *value;
2526 if (!git_configset_get_value(cs, key, &value))
2527 return git_config_pathname(dest, key, value);
2528 else
2529 return 1;
2532 /* Functions use to read configuration from a repository */
2533 static void repo_read_config(struct repository *repo)
2535 struct config_options opts = { 0 };
2537 opts.respect_includes = 1;
2538 opts.commondir = repo->commondir;
2539 opts.git_dir = repo->gitdir;
2541 if (!repo->config)
2542 CALLOC_ARRAY(repo->config, 1);
2543 else
2544 git_configset_clear(repo->config);
2546 git_configset_init(repo->config);
2548 if (config_with_options(config_set_callback, repo->config, NULL, &opts) < 0)
2550 * config_with_options() normally returns only
2551 * zero, as most errors are fatal, and
2552 * non-fatal potential errors are guarded by "if"
2553 * statements that are entered only when no error is
2554 * possible.
2556 * If we ever encounter a non-fatal error, it means
2557 * something went really wrong and we should stop
2558 * immediately.
2560 die(_("unknown error occurred while reading the configuration files"));
2563 static void git_config_check_init(struct repository *repo)
2565 if (repo->config && repo->config->hash_initialized)
2566 return;
2567 repo_read_config(repo);
2570 static void repo_config_clear(struct repository *repo)
2572 if (!repo->config || !repo->config->hash_initialized)
2573 return;
2574 git_configset_clear(repo->config);
2577 void repo_config(struct repository *repo, config_fn_t fn, void *data)
2579 git_config_check_init(repo);
2580 configset_iter(repo->config, fn, data);
2583 int repo_config_get_value(struct repository *repo,
2584 const char *key, const char **value)
2586 git_config_check_init(repo);
2587 return git_configset_get_value(repo->config, key, value);
2590 const struct string_list *repo_config_get_value_multi(struct repository *repo,
2591 const char *key)
2593 git_config_check_init(repo);
2594 return git_configset_get_value_multi(repo->config, key);
2597 int repo_config_get_string(struct repository *repo,
2598 const char *key, char **dest)
2600 int ret;
2601 git_config_check_init(repo);
2602 ret = git_configset_get_string(repo->config, key, dest);
2603 if (ret < 0)
2604 git_die_config(key, NULL);
2605 return ret;
2608 int repo_config_get_string_tmp(struct repository *repo,
2609 const char *key, const char **dest)
2611 int ret;
2612 git_config_check_init(repo);
2613 ret = git_configset_get_string_tmp(repo->config, key, dest);
2614 if (ret < 0)
2615 git_die_config(key, NULL);
2616 return ret;
2619 int repo_config_get_int(struct repository *repo,
2620 const char *key, int *dest)
2622 git_config_check_init(repo);
2623 return git_configset_get_int(repo->config, key, dest);
2626 int repo_config_get_ulong(struct repository *repo,
2627 const char *key, unsigned long *dest)
2629 git_config_check_init(repo);
2630 return git_configset_get_ulong(repo->config, key, dest);
2633 int repo_config_get_bool(struct repository *repo,
2634 const char *key, int *dest)
2636 git_config_check_init(repo);
2637 return git_configset_get_bool(repo->config, key, dest);
2640 int repo_config_get_bool_or_int(struct repository *repo,
2641 const char *key, int *is_bool, int *dest)
2643 git_config_check_init(repo);
2644 return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2647 int repo_config_get_maybe_bool(struct repository *repo,
2648 const char *key, int *dest)
2650 git_config_check_init(repo);
2651 return git_configset_get_maybe_bool(repo->config, key, dest);
2654 int repo_config_get_pathname(struct repository *repo,
2655 const char *key, const char **dest)
2657 int ret;
2658 git_config_check_init(repo);
2659 ret = git_configset_get_pathname(repo->config, key, dest);
2660 if (ret < 0)
2661 git_die_config(key, NULL);
2662 return ret;
2665 /* Read values into protected_config. */
2666 static void read_protected_config(void)
2668 struct config_options opts = {
2669 .respect_includes = 1,
2670 .ignore_repo = 1,
2671 .ignore_worktree = 1,
2672 .system_gently = 1,
2674 git_configset_init(&protected_config);
2675 config_with_options(config_set_callback, &protected_config,
2676 NULL, &opts);
2679 void git_protected_config(config_fn_t fn, void *data)
2681 if (!protected_config.hash_initialized)
2682 read_protected_config();
2683 configset_iter(&protected_config, fn, data);
2686 /* Functions used historically to read configuration from 'the_repository' */
2687 void git_config(config_fn_t fn, void *data)
2689 repo_config(the_repository, fn, data);
2692 void git_config_clear(void)
2694 repo_config_clear(the_repository);
2697 int git_config_get_value(const char *key, const char **value)
2699 return repo_config_get_value(the_repository, key, value);
2702 const struct string_list *git_config_get_value_multi(const char *key)
2704 return repo_config_get_value_multi(the_repository, key);
2707 int git_config_get_string(const char *key, char **dest)
2709 return repo_config_get_string(the_repository, key, dest);
2712 int git_config_get_string_tmp(const char *key, const char **dest)
2714 return repo_config_get_string_tmp(the_repository, key, dest);
2717 int git_config_get_int(const char *key, int *dest)
2719 return repo_config_get_int(the_repository, key, dest);
2722 int git_config_get_ulong(const char *key, unsigned long *dest)
2724 return repo_config_get_ulong(the_repository, key, dest);
2727 int git_config_get_bool(const char *key, int *dest)
2729 return repo_config_get_bool(the_repository, key, dest);
2732 int git_config_get_bool_or_int(const char *key, int *is_bool, int *dest)
2734 return repo_config_get_bool_or_int(the_repository, key, is_bool, dest);
2737 int git_config_get_maybe_bool(const char *key, int *dest)
2739 return repo_config_get_maybe_bool(the_repository, key, dest);
2742 int git_config_get_pathname(const char *key, const char **dest)
2744 return repo_config_get_pathname(the_repository, key, dest);
2747 int git_config_get_expiry(const char *key, const char **output)
2749 int ret = git_config_get_string(key, (char **)output);
2750 if (ret)
2751 return ret;
2752 if (strcmp(*output, "now")) {
2753 timestamp_t now = approxidate("now");
2754 if (approxidate(*output) >= now)
2755 git_die_config(key, _("Invalid %s: '%s'"), key, *output);
2757 return ret;
2760 int git_config_get_expiry_in_days(const char *key, timestamp_t *expiry, timestamp_t now)
2762 const char *expiry_string;
2763 intmax_t days;
2764 timestamp_t when;
2766 if (git_config_get_string_tmp(key, &expiry_string))
2767 return 1; /* no such thing */
2769 if (git_parse_signed(expiry_string, &days, maximum_signed_value_of_type(int))) {
2770 const int scale = 86400;
2771 *expiry = now - days * scale;
2772 return 0;
2775 if (!parse_expiry_date(expiry_string, &when)) {
2776 *expiry = when;
2777 return 0;
2779 return -1; /* thing exists but cannot be parsed */
2782 int git_config_get_split_index(void)
2784 int val;
2786 if (!git_config_get_maybe_bool("core.splitindex", &val))
2787 return val;
2789 return -1; /* default value */
2792 int git_config_get_max_percent_split_change(void)
2794 int val = -1;
2796 if (!git_config_get_int("splitindex.maxpercentchange", &val)) {
2797 if (0 <= val && val <= 100)
2798 return val;
2800 return error(_("splitIndex.maxPercentChange value '%d' "
2801 "should be between 0 and 100"), val);
2804 return -1; /* default value */
2807 int git_config_get_index_threads(int *dest)
2809 int is_bool, val;
2811 val = git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2812 if (val) {
2813 *dest = val;
2814 return 0;
2817 if (!git_config_get_bool_or_int("index.threads", &is_bool, &val)) {
2818 if (is_bool)
2819 *dest = val ? 0 : 1;
2820 else
2821 *dest = val;
2822 return 0;
2825 return 1;
2828 NORETURN
2829 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2831 if (!filename)
2832 die(_("unable to parse '%s' from command-line config"), key);
2833 else
2834 die(_("bad config variable '%s' in file '%s' at line %d"),
2835 key, filename, linenr);
2838 NORETURN __attribute__((format(printf, 2, 3)))
2839 void git_die_config(const char *key, const char *err, ...)
2841 const struct string_list *values;
2842 struct key_value_info *kv_info;
2843 report_fn error_fn = get_error_routine();
2845 if (err) {
2846 va_list params;
2847 va_start(params, err);
2848 error_fn(err, params);
2849 va_end(params);
2851 values = git_config_get_value_multi(key);
2852 kv_info = values->items[values->nr - 1].util;
2853 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
2857 * Find all the stuff for git_config_set() below.
2860 struct config_store_data {
2861 size_t baselen;
2862 char *key;
2863 int do_not_match;
2864 const char *fixed_value;
2865 regex_t *value_pattern;
2866 int multi_replace;
2867 struct {
2868 size_t begin, end;
2869 enum config_event_t type;
2870 int is_keys_section;
2871 } *parsed;
2872 unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
2873 unsigned int key_seen:1, section_seen:1, is_keys_section:1;
2876 static void config_store_data_clear(struct config_store_data *store)
2878 free(store->key);
2879 if (store->value_pattern != NULL &&
2880 store->value_pattern != CONFIG_REGEX_NONE) {
2881 regfree(store->value_pattern);
2882 free(store->value_pattern);
2884 free(store->parsed);
2885 free(store->seen);
2886 memset(store, 0, sizeof(*store));
2889 static int matches(const char *key, const char *value,
2890 const struct config_store_data *store)
2892 if (strcmp(key, store->key))
2893 return 0; /* not ours */
2894 if (store->fixed_value)
2895 return !strcmp(store->fixed_value, value);
2896 if (!store->value_pattern)
2897 return 1; /* always matches */
2898 if (store->value_pattern == CONFIG_REGEX_NONE)
2899 return 0; /* never matches */
2901 return store->do_not_match ^
2902 (value && !regexec(store->value_pattern, value, 0, NULL, 0));
2905 static int store_aux_event(enum config_event_t type,
2906 size_t begin, size_t end, void *data)
2908 struct config_store_data *store = data;
2910 ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
2911 store->parsed[store->parsed_nr].begin = begin;
2912 store->parsed[store->parsed_nr].end = end;
2913 store->parsed[store->parsed_nr].type = type;
2915 if (type == CONFIG_EVENT_SECTION) {
2916 int (*cmpfn)(const char *, const char *, size_t);
2918 if (cf->var.len < 2 || cf->var.buf[cf->var.len - 1] != '.')
2919 return error(_("invalid section name '%s'"), cf->var.buf);
2921 if (cf->subsection_case_sensitive)
2922 cmpfn = strncasecmp;
2923 else
2924 cmpfn = strncmp;
2926 /* Is this the section we were looking for? */
2927 store->is_keys_section =
2928 store->parsed[store->parsed_nr].is_keys_section =
2929 cf->var.len - 1 == store->baselen &&
2930 !cmpfn(cf->var.buf, store->key, store->baselen);
2931 if (store->is_keys_section) {
2932 store->section_seen = 1;
2933 ALLOC_GROW(store->seen, store->seen_nr + 1,
2934 store->seen_alloc);
2935 store->seen[store->seen_nr] = store->parsed_nr;
2939 store->parsed_nr++;
2941 return 0;
2944 static int store_aux(const char *key, const char *value, void *cb)
2946 struct config_store_data *store = cb;
2948 if (store->key_seen) {
2949 if (matches(key, value, store)) {
2950 if (store->seen_nr == 1 && store->multi_replace == 0) {
2951 warning(_("%s has multiple values"), key);
2954 ALLOC_GROW(store->seen, store->seen_nr + 1,
2955 store->seen_alloc);
2957 store->seen[store->seen_nr] = store->parsed_nr;
2958 store->seen_nr++;
2960 } else if (store->is_keys_section) {
2962 * Do not increment matches yet: this may not be a match, but we
2963 * are in the desired section.
2965 ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
2966 store->seen[store->seen_nr] = store->parsed_nr;
2967 store->section_seen = 1;
2969 if (matches(key, value, store)) {
2970 store->seen_nr++;
2971 store->key_seen = 1;
2975 return 0;
2978 static int write_error(const char *filename)
2980 error(_("failed to write new configuration file %s"), filename);
2982 /* Same error code as "failed to rename". */
2983 return 4;
2986 static struct strbuf store_create_section(const char *key,
2987 const struct config_store_data *store)
2989 const char *dot;
2990 size_t i;
2991 struct strbuf sb = STRBUF_INIT;
2993 dot = memchr(key, '.', store->baselen);
2994 if (dot) {
2995 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
2996 for (i = dot - key + 1; i < store->baselen; i++) {
2997 if (key[i] == '"' || key[i] == '\\')
2998 strbuf_addch(&sb, '\\');
2999 strbuf_addch(&sb, key[i]);
3001 strbuf_addstr(&sb, "\"]\n");
3002 } else {
3003 strbuf_addch(&sb, '[');
3004 strbuf_add(&sb, key, store->baselen);
3005 strbuf_addstr(&sb, "]\n");
3008 return sb;
3011 static ssize_t write_section(int fd, const char *key,
3012 const struct config_store_data *store)
3014 struct strbuf sb = store_create_section(key, store);
3015 ssize_t ret;
3017 ret = write_in_full(fd, sb.buf, sb.len);
3018 strbuf_release(&sb);
3020 return ret;
3023 static ssize_t write_pair(int fd, const char *key, const char *value,
3024 const struct config_store_data *store)
3026 int i;
3027 ssize_t ret;
3028 const char *quote = "";
3029 struct strbuf sb = STRBUF_INIT;
3032 * Check to see if the value needs to be surrounded with a dq pair.
3033 * Note that problematic characters are always backslash-quoted; this
3034 * check is about not losing leading or trailing SP and strings that
3035 * follow beginning-of-comment characters (i.e. ';' and '#') by the
3036 * configuration parser.
3038 if (value[0] == ' ')
3039 quote = "\"";
3040 for (i = 0; value[i]; i++)
3041 if (value[i] == ';' || value[i] == '#')
3042 quote = "\"";
3043 if (i && value[i - 1] == ' ')
3044 quote = "\"";
3046 strbuf_addf(&sb, "\t%s = %s", key + store->baselen + 1, quote);
3048 for (i = 0; value[i]; i++)
3049 switch (value[i]) {
3050 case '\n':
3051 strbuf_addstr(&sb, "\\n");
3052 break;
3053 case '\t':
3054 strbuf_addstr(&sb, "\\t");
3055 break;
3056 case '"':
3057 case '\\':
3058 strbuf_addch(&sb, '\\');
3059 /* fallthrough */
3060 default:
3061 strbuf_addch(&sb, value[i]);
3062 break;
3064 strbuf_addf(&sb, "%s\n", quote);
3066 ret = write_in_full(fd, sb.buf, sb.len);
3067 strbuf_release(&sb);
3069 return ret;
3073 * If we are about to unset the last key(s) in a section, and if there are
3074 * no comments surrounding (or included in) the section, we will want to
3075 * extend begin/end to remove the entire section.
3077 * Note: the parameter `seen_ptr` points to the index into the store.seen
3078 * array. * This index may be incremented if a section has more than one
3079 * entry (which all are to be removed).
3081 static void maybe_remove_section(struct config_store_data *store,
3082 size_t *begin_offset, size_t *end_offset,
3083 int *seen_ptr)
3085 size_t begin;
3086 int i, seen, section_seen = 0;
3089 * First, ensure that this is the first key, and that there are no
3090 * comments before the entry nor before the section header.
3092 seen = *seen_ptr;
3093 for (i = store->seen[seen]; i > 0; i--) {
3094 enum config_event_t type = store->parsed[i - 1].type;
3096 if (type == CONFIG_EVENT_COMMENT)
3097 /* There is a comment before this entry or section */
3098 return;
3099 if (type == CONFIG_EVENT_ENTRY) {
3100 if (!section_seen)
3101 /* This is not the section's first entry. */
3102 return;
3103 /* We encountered no comment before the section. */
3104 break;
3106 if (type == CONFIG_EVENT_SECTION) {
3107 if (!store->parsed[i - 1].is_keys_section)
3108 break;
3109 section_seen = 1;
3112 begin = store->parsed[i].begin;
3115 * Next, make sure that we are removing the last key(s) in the section,
3116 * and that there are no comments that are possibly about the current
3117 * section.
3119 for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
3120 enum config_event_t type = store->parsed[i].type;
3122 if (type == CONFIG_EVENT_COMMENT)
3123 return;
3124 if (type == CONFIG_EVENT_SECTION) {
3125 if (store->parsed[i].is_keys_section)
3126 continue;
3127 break;
3129 if (type == CONFIG_EVENT_ENTRY) {
3130 if (++seen < store->seen_nr &&
3131 i == store->seen[seen])
3132 /* We want to remove this entry, too */
3133 continue;
3134 /* There is another entry in this section. */
3135 return;
3140 * We are really removing the last entry/entries from this section, and
3141 * there are no enclosed or surrounding comments. Remove the entire,
3142 * now-empty section.
3144 *seen_ptr = seen;
3145 *begin_offset = begin;
3146 if (i < store->parsed_nr)
3147 *end_offset = store->parsed[i].begin;
3148 else
3149 *end_offset = store->parsed[store->parsed_nr - 1].end;
3152 int git_config_set_in_file_gently(const char *config_filename,
3153 const char *key, const char *value)
3155 return git_config_set_multivar_in_file_gently(config_filename, key, value, NULL, 0);
3158 void git_config_set_in_file(const char *config_filename,
3159 const char *key, const char *value)
3161 git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
3164 int git_config_set_gently(const char *key, const char *value)
3166 return git_config_set_multivar_gently(key, value, NULL, 0);
3169 int repo_config_set_worktree_gently(struct repository *r,
3170 const char *key, const char *value)
3172 /* Only use worktree-specific config if it is already enabled. */
3173 if (repository_format_worktree_config) {
3174 char *file = repo_git_path(r, "config.worktree");
3175 int ret = git_config_set_multivar_in_file_gently(
3176 file, key, value, NULL, 0);
3177 free(file);
3178 return ret;
3180 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
3183 void git_config_set(const char *key, const char *value)
3185 git_config_set_multivar(key, value, NULL, 0);
3187 trace2_cmd_set_config(key, value);
3191 * If value==NULL, unset in (remove from) config,
3192 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
3193 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
3194 * (only add a new one)
3195 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3196 * key/values are removed before a single new pair is written. If the
3197 * flag is not present, then replace only the first match.
3199 * Returns 0 on success.
3201 * This function does this:
3203 * - it locks the config file by creating ".git/config.lock"
3205 * - it then parses the config using store_aux() as validator to find
3206 * the position on the key/value pair to replace. If it is to be unset,
3207 * it must be found exactly once.
3209 * - the config file is mmap()ed and the part before the match (if any) is
3210 * written to the lock file, then the changed part and the rest.
3212 * - the config file is removed and the lock file rename()d to it.
3215 int git_config_set_multivar_in_file_gently(const char *config_filename,
3216 const char *key, const char *value,
3217 const char *value_pattern,
3218 unsigned flags)
3220 int fd = -1, in_fd = -1;
3221 int ret;
3222 struct lock_file lock = LOCK_INIT;
3223 char *filename_buf = NULL;
3224 char *contents = NULL;
3225 size_t contents_sz;
3226 struct config_store_data store;
3228 memset(&store, 0, sizeof(store));
3230 /* parse-key returns negative; flip the sign to feed exit(3) */
3231 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
3232 if (ret)
3233 goto out_free;
3235 store.multi_replace = (flags & CONFIG_FLAGS_MULTI_REPLACE) != 0;
3237 if (!config_filename)
3238 config_filename = filename_buf = git_pathdup("config");
3241 * The lock serves a purpose in addition to locking: the new
3242 * contents of .git/config will be written into it.
3244 fd = hold_lock_file_for_update(&lock, config_filename, 0);
3245 if (fd < 0) {
3246 error_errno(_("could not lock config file %s"), config_filename);
3247 ret = CONFIG_NO_LOCK;
3248 goto out_free;
3252 * If .git/config does not exist yet, write a minimal version.
3254 in_fd = open(config_filename, O_RDONLY);
3255 if ( in_fd < 0 ) {
3256 if ( ENOENT != errno ) {
3257 error_errno(_("opening %s"), config_filename);
3258 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
3259 goto out_free;
3261 /* if nothing to unset, error out */
3262 if (!value) {
3263 ret = CONFIG_NOTHING_SET;
3264 goto out_free;
3267 free(store.key);
3268 store.key = xstrdup(key);
3269 if (write_section(fd, key, &store) < 0 ||
3270 write_pair(fd, key, value, &store) < 0)
3271 goto write_err_out;
3272 } else {
3273 struct stat st;
3274 size_t copy_begin, copy_end;
3275 int i, new_line = 0;
3276 struct config_options opts;
3278 if (!value_pattern)
3279 store.value_pattern = NULL;
3280 else if (value_pattern == CONFIG_REGEX_NONE)
3281 store.value_pattern = CONFIG_REGEX_NONE;
3282 else if (flags & CONFIG_FLAGS_FIXED_VALUE)
3283 store.fixed_value = value_pattern;
3284 else {
3285 if (value_pattern[0] == '!') {
3286 store.do_not_match = 1;
3287 value_pattern++;
3288 } else
3289 store.do_not_match = 0;
3291 store.value_pattern = (regex_t*)xmalloc(sizeof(regex_t));
3292 if (regcomp(store.value_pattern, value_pattern,
3293 REG_EXTENDED)) {
3294 error(_("invalid pattern: %s"), value_pattern);
3295 FREE_AND_NULL(store.value_pattern);
3296 ret = CONFIG_INVALID_PATTERN;
3297 goto out_free;
3301 ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
3302 store.parsed[0].end = 0;
3304 memset(&opts, 0, sizeof(opts));
3305 opts.event_fn = store_aux_event;
3306 opts.event_fn_data = &store;
3309 * After this, store.parsed will contain offsets of all the
3310 * parsed elements, and store.seen will contain a list of
3311 * matches, as indices into store.parsed.
3313 * As a side effect, we make sure to transform only a valid
3314 * existing config file.
3316 if (git_config_from_file_with_options(store_aux,
3317 config_filename,
3318 &store, &opts)) {
3319 error(_("invalid config file %s"), config_filename);
3320 ret = CONFIG_INVALID_FILE;
3321 goto out_free;
3324 /* if nothing to unset, or too many matches, error out */
3325 if ((store.seen_nr == 0 && value == NULL) ||
3326 (store.seen_nr > 1 && !store.multi_replace)) {
3327 ret = CONFIG_NOTHING_SET;
3328 goto out_free;
3331 if (fstat(in_fd, &st) == -1) {
3332 error_errno(_("fstat on %s failed"), config_filename);
3333 ret = CONFIG_INVALID_FILE;
3334 goto out_free;
3337 contents_sz = xsize_t(st.st_size);
3338 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
3339 MAP_PRIVATE, in_fd, 0);
3340 if (contents == MAP_FAILED) {
3341 if (errno == ENODEV && S_ISDIR(st.st_mode))
3342 errno = EISDIR;
3343 error_errno(_("unable to mmap '%s'%s"),
3344 config_filename, mmap_os_err());
3345 ret = CONFIG_INVALID_FILE;
3346 contents = NULL;
3347 goto out_free;
3349 close(in_fd);
3350 in_fd = -1;
3352 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3353 error_errno(_("chmod on %s failed"), get_lock_file_path(&lock));
3354 ret = CONFIG_NO_WRITE;
3355 goto out_free;
3358 if (store.seen_nr == 0) {
3359 if (!store.seen_alloc) {
3360 /* Did not see key nor section */
3361 ALLOC_GROW(store.seen, 1, store.seen_alloc);
3362 store.seen[0] = store.parsed_nr
3363 - !!store.parsed_nr;
3365 store.seen_nr = 1;
3368 for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
3369 size_t replace_end;
3370 int j = store.seen[i];
3372 new_line = 0;
3373 if (!store.key_seen) {
3374 copy_end = store.parsed[j].end;
3375 /* include '\n' when copying section header */
3376 if (copy_end > 0 && copy_end < contents_sz &&
3377 contents[copy_end - 1] != '\n' &&
3378 contents[copy_end] == '\n')
3379 copy_end++;
3380 replace_end = copy_end;
3381 } else {
3382 replace_end = store.parsed[j].end;
3383 copy_end = store.parsed[j].begin;
3384 if (!value)
3385 maybe_remove_section(&store,
3386 &copy_end,
3387 &replace_end, &i);
3389 * Swallow preceding white-space on the same
3390 * line.
3392 while (copy_end > 0 ) {
3393 char c = contents[copy_end - 1];
3395 if (isspace(c) && c != '\n')
3396 copy_end--;
3397 else
3398 break;
3402 if (copy_end > 0 && contents[copy_end-1] != '\n')
3403 new_line = 1;
3405 /* write the first part of the config */
3406 if (copy_end > copy_begin) {
3407 if (write_in_full(fd, contents + copy_begin,
3408 copy_end - copy_begin) < 0)
3409 goto write_err_out;
3410 if (new_line &&
3411 write_str_in_full(fd, "\n") < 0)
3412 goto write_err_out;
3414 copy_begin = replace_end;
3417 /* write the pair (value == NULL means unset) */
3418 if (value) {
3419 if (!store.section_seen) {
3420 if (write_section(fd, key, &store) < 0)
3421 goto write_err_out;
3423 if (write_pair(fd, key, value, &store) < 0)
3424 goto write_err_out;
3427 /* write the rest of the config */
3428 if (copy_begin < contents_sz)
3429 if (write_in_full(fd, contents + copy_begin,
3430 contents_sz - copy_begin) < 0)
3431 goto write_err_out;
3433 munmap(contents, contents_sz);
3434 contents = NULL;
3437 if (commit_lock_file(&lock) < 0) {
3438 error_errno(_("could not write config file %s"), config_filename);
3439 ret = CONFIG_NO_WRITE;
3440 goto out_free;
3443 ret = 0;
3445 /* Invalidate the config cache */
3446 git_config_clear();
3448 out_free:
3449 rollback_lock_file(&lock);
3450 free(filename_buf);
3451 if (contents)
3452 munmap(contents, contents_sz);
3453 if (in_fd >= 0)
3454 close(in_fd);
3455 config_store_data_clear(&store);
3456 return ret;
3458 write_err_out:
3459 ret = write_error(get_lock_file_path(&lock));
3460 goto out_free;
3464 void git_config_set_multivar_in_file(const char *config_filename,
3465 const char *key, const char *value,
3466 const char *value_pattern, unsigned flags)
3468 if (!git_config_set_multivar_in_file_gently(config_filename, key, value,
3469 value_pattern, flags))
3470 return;
3471 if (value)
3472 die(_("could not set '%s' to '%s'"), key, value);
3473 else
3474 die(_("could not unset '%s'"), key);
3477 int git_config_set_multivar_gently(const char *key, const char *value,
3478 const char *value_pattern, unsigned flags)
3480 return repo_config_set_multivar_gently(the_repository, key, value,
3481 value_pattern, flags);
3484 int repo_config_set_multivar_gently(struct repository *r, const char *key,
3485 const char *value,
3486 const char *value_pattern, unsigned flags)
3488 char *file = repo_git_path(r, "config");
3489 int res = git_config_set_multivar_in_file_gently(file,
3490 key, value,
3491 value_pattern,
3492 flags);
3493 free(file);
3494 return res;
3497 void git_config_set_multivar(const char *key, const char *value,
3498 const char *value_pattern, unsigned flags)
3500 git_config_set_multivar_in_file(git_path("config"),
3501 key, value, value_pattern,
3502 flags);
3505 static int section_name_match (const char *buf, const char *name)
3507 int i = 0, j = 0, dot = 0;
3508 if (buf[i] != '[')
3509 return 0;
3510 for (i = 1; buf[i] && buf[i] != ']'; i++) {
3511 if (!dot && isspace(buf[i])) {
3512 dot = 1;
3513 if (name[j++] != '.')
3514 break;
3515 for (i++; isspace(buf[i]); i++)
3516 ; /* do nothing */
3517 if (buf[i] != '"')
3518 break;
3519 continue;
3521 if (buf[i] == '\\' && dot)
3522 i++;
3523 else if (buf[i] == '"' && dot) {
3524 for (i++; isspace(buf[i]); i++)
3525 ; /* do_nothing */
3526 break;
3528 if (buf[i] != name[j++])
3529 break;
3531 if (buf[i] == ']' && name[j] == 0) {
3533 * We match, now just find the right length offset by
3534 * gobbling up any whitespace after it, as well
3536 i++;
3537 for (; buf[i] && isspace(buf[i]); i++)
3538 ; /* do nothing */
3539 return i;
3541 return 0;
3544 static int section_name_is_ok(const char *name)
3546 /* Empty section names are bogus. */
3547 if (!*name)
3548 return 0;
3551 * Before a dot, we must be alphanumeric or dash. After the first dot,
3552 * anything goes, so we can stop checking.
3554 for (; *name && *name != '.'; name++)
3555 if (*name != '-' && !isalnum(*name))
3556 return 0;
3557 return 1;
3560 /* if new_name == NULL, the section is removed instead */
3561 static int git_config_copy_or_rename_section_in_file(const char *config_filename,
3562 const char *old_name,
3563 const char *new_name, int copy)
3565 int ret = 0, remove = 0;
3566 char *filename_buf = NULL;
3567 struct lock_file lock = LOCK_INIT;
3568 int out_fd;
3569 char buf[1024];
3570 FILE *config_file = NULL;
3571 struct stat st;
3572 struct strbuf copystr = STRBUF_INIT;
3573 struct config_store_data store;
3575 memset(&store, 0, sizeof(store));
3577 if (new_name && !section_name_is_ok(new_name)) {
3578 ret = error(_("invalid section name: %s"), new_name);
3579 goto out_no_rollback;
3582 if (!config_filename)
3583 config_filename = filename_buf = git_pathdup("config");
3585 out_fd = hold_lock_file_for_update(&lock, config_filename, 0);
3586 if (out_fd < 0) {
3587 ret = error(_("could not lock config file %s"), config_filename);
3588 goto out;
3591 if (!(config_file = fopen(config_filename, "rb"))) {
3592 ret = warn_on_fopen_errors(config_filename);
3593 if (ret)
3594 goto out;
3595 /* no config file means nothing to rename, no error */
3596 goto commit_and_out;
3599 if (fstat(fileno(config_file), &st) == -1) {
3600 ret = error_errno(_("fstat on %s failed"), config_filename);
3601 goto out;
3604 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3605 ret = error_errno(_("chmod on %s failed"),
3606 get_lock_file_path(&lock));
3607 goto out;
3610 while (fgets(buf, sizeof(buf), config_file)) {
3611 unsigned i;
3612 int length;
3613 int is_section = 0;
3614 char *output = buf;
3615 for (i = 0; buf[i] && isspace(buf[i]); i++)
3616 ; /* do nothing */
3617 if (buf[i] == '[') {
3618 /* it's a section */
3619 int offset;
3620 is_section = 1;
3623 * When encountering a new section under -c we
3624 * need to flush out any section we're already
3625 * coping and begin anew. There might be
3626 * multiple [branch "$name"] sections.
3628 if (copystr.len > 0) {
3629 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3630 ret = write_error(get_lock_file_path(&lock));
3631 goto out;
3633 strbuf_reset(&copystr);
3636 offset = section_name_match(&buf[i], old_name);
3637 if (offset > 0) {
3638 ret++;
3639 if (!new_name) {
3640 remove = 1;
3641 continue;
3643 store.baselen = strlen(new_name);
3644 if (!copy) {
3645 if (write_section(out_fd, new_name, &store) < 0) {
3646 ret = write_error(get_lock_file_path(&lock));
3647 goto out;
3650 * We wrote out the new section, with
3651 * a newline, now skip the old
3652 * section's length
3654 output += offset + i;
3655 if (strlen(output) > 0) {
3657 * More content means there's
3658 * a declaration to put on the
3659 * next line; indent with a
3660 * tab
3662 output -= 1;
3663 output[0] = '\t';
3665 } else {
3666 copystr = store_create_section(new_name, &store);
3669 remove = 0;
3671 if (remove)
3672 continue;
3673 length = strlen(output);
3675 if (!is_section && copystr.len > 0) {
3676 strbuf_add(&copystr, output, length);
3679 if (write_in_full(out_fd, output, length) < 0) {
3680 ret = write_error(get_lock_file_path(&lock));
3681 goto out;
3686 * Copy a trailing section at the end of the config, won't be
3687 * flushed by the usual "flush because we have a new section
3688 * logic in the loop above.
3690 if (copystr.len > 0) {
3691 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3692 ret = write_error(get_lock_file_path(&lock));
3693 goto out;
3695 strbuf_reset(&copystr);
3698 fclose(config_file);
3699 config_file = NULL;
3700 commit_and_out:
3701 if (commit_lock_file(&lock) < 0)
3702 ret = error_errno(_("could not write config file %s"),
3703 config_filename);
3704 out:
3705 if (config_file)
3706 fclose(config_file);
3707 rollback_lock_file(&lock);
3708 out_no_rollback:
3709 free(filename_buf);
3710 config_store_data_clear(&store);
3711 return ret;
3714 int git_config_rename_section_in_file(const char *config_filename,
3715 const char *old_name, const char *new_name)
3717 return git_config_copy_or_rename_section_in_file(config_filename,
3718 old_name, new_name, 0);
3721 int git_config_rename_section(const char *old_name, const char *new_name)
3723 return git_config_rename_section_in_file(NULL, old_name, new_name);
3726 int git_config_copy_section_in_file(const char *config_filename,
3727 const char *old_name, const char *new_name)
3729 return git_config_copy_or_rename_section_in_file(config_filename,
3730 old_name, new_name, 1);
3733 int git_config_copy_section(const char *old_name, const char *new_name)
3735 return git_config_copy_section_in_file(NULL, old_name, new_name);
3739 * Call this to report error for your variable that should not
3740 * get a boolean value (i.e. "[my] var" means "true").
3742 #undef config_error_nonbool
3743 int config_error_nonbool(const char *var)
3745 return error(_("missing value for '%s'"), var);
3748 int parse_config_key(const char *var,
3749 const char *section,
3750 const char **subsection, size_t *subsection_len,
3751 const char **key)
3753 const char *dot;
3755 /* Does it start with "section." ? */
3756 if (!skip_prefix(var, section, &var) || *var != '.')
3757 return -1;
3760 * Find the key; we don't know yet if we have a subsection, but we must
3761 * parse backwards from the end, since the subsection may have dots in
3762 * it, too.
3764 dot = strrchr(var, '.');
3765 *key = dot + 1;
3767 /* Did we have a subsection at all? */
3768 if (dot == var) {
3769 if (subsection) {
3770 *subsection = NULL;
3771 *subsection_len = 0;
3774 else {
3775 if (!subsection)
3776 return -1;
3777 *subsection = var + 1;
3778 *subsection_len = dot - *subsection;
3781 return 0;
3784 const char *current_config_origin_type(void)
3786 int type;
3787 if (current_config_kvi)
3788 type = current_config_kvi->origin_type;
3789 else if(cf)
3790 type = cf->origin_type;
3791 else
3792 BUG("current_config_origin_type called outside config callback");
3794 switch (type) {
3795 case CONFIG_ORIGIN_BLOB:
3796 return "blob";
3797 case CONFIG_ORIGIN_FILE:
3798 return "file";
3799 case CONFIG_ORIGIN_STDIN:
3800 return "standard input";
3801 case CONFIG_ORIGIN_SUBMODULE_BLOB:
3802 return "submodule-blob";
3803 case CONFIG_ORIGIN_CMDLINE:
3804 return "command line";
3805 default:
3806 BUG("unknown config origin type");
3810 const char *config_scope_name(enum config_scope scope)
3812 switch (scope) {
3813 case CONFIG_SCOPE_SYSTEM:
3814 return "system";
3815 case CONFIG_SCOPE_GLOBAL:
3816 return "global";
3817 case CONFIG_SCOPE_LOCAL:
3818 return "local";
3819 case CONFIG_SCOPE_WORKTREE:
3820 return "worktree";
3821 case CONFIG_SCOPE_COMMAND:
3822 return "command";
3823 case CONFIG_SCOPE_SUBMODULE:
3824 return "submodule";
3825 default:
3826 return "unknown";
3830 const char *current_config_name(void)
3832 const char *name;
3833 if (current_config_kvi)
3834 name = current_config_kvi->filename;
3835 else if (cf)
3836 name = cf->name;
3837 else
3838 BUG("current_config_name called outside config callback");
3839 return name ? name : "";
3842 enum config_scope current_config_scope(void)
3844 if (current_config_kvi)
3845 return current_config_kvi->scope;
3846 else
3847 return current_parsing_scope;
3850 int current_config_line(void)
3852 if (current_config_kvi)
3853 return current_config_kvi->linenr;
3854 else
3855 return cf->linenr;
3858 int lookup_config(const char **mapping, int nr_mapping, const char *var)
3860 int i;
3862 for (i = 0; i < nr_mapping; i++) {
3863 const char *name = mapping[i];
3865 if (name && !strcasecmp(var, name))
3866 return i;
3868 return -1;