config.c: remove current_config_kvi
[git.git] / config.c
blob71ee36f069b263e6791ed4e5f9c6f0d91a9927bf
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 * Copyright (C) Johannes Schindelin, 2005
7 */
8 #include "cache.h"
9 #include "date.h"
10 #include "branch.h"
11 #include "config.h"
12 #include "environment.h"
13 #include "repository.h"
14 #include "lockfile.h"
15 #include "exec-cmd.h"
16 #include "strbuf.h"
17 #include "quote.h"
18 #include "hashmap.h"
19 #include "string-list.h"
20 #include "object-store.h"
21 #include "utf8.h"
22 #include "dir.h"
23 #include "color.h"
24 #include "refs.h"
25 #include "worktree.h"
27 struct config_source {
28 struct config_source *prev;
29 union {
30 FILE *file;
31 struct config_buf {
32 const char *buf;
33 size_t len;
34 size_t pos;
35 } buf;
36 } u;
37 enum config_origin_type origin_type;
38 const char *name;
39 const char *path;
40 enum config_error_action default_error_action;
41 int linenr;
42 int eof;
43 size_t total_len;
44 struct strbuf value;
45 struct strbuf var;
46 unsigned subsection_case_sensitive : 1;
48 int (*do_fgetc)(struct config_source *c);
49 int (*do_ungetc)(int c, struct config_source *conf);
50 long (*do_ftell)(struct config_source *c);
52 #define CONFIG_SOURCE_INIT { 0 }
54 struct config_reader {
56 * These members record the "current" config source, which can be
57 * accessed by parsing callbacks.
59 * The "source" variable will be non-NULL only when we are actually
60 * parsing a real config source (file, blob, cmdline, etc).
62 * The "config_kvi" variable will be non-NULL only when we are feeding
63 * cached config from a configset into a callback.
65 * They cannot be non-NULL at the same time. If they are both NULL, then
66 * we aren't parsing anything (and depending on the function looking at
67 * the variables, it's either a bug for it to be called in the first
68 * place, or it's a function which can be reused for non-config
69 * purposes, and should fall back to some sane behavior).
71 struct config_source *source;
72 struct key_value_info *config_kvi;
75 * Where possible, prefer to accept "struct config_reader" as an arg than to use
76 * "the_reader". "the_reader" should only be used if that is infeasible, e.g. in
77 * a public function.
79 static struct config_reader the_reader;
82 * Similar to the variables above, this gives access to the "scope" of the
83 * current value (repo, global, etc). For cached values, it can be found via
84 * the current_config_kvi as above. During parsing, the current value can be
85 * found in this variable. It's not part of "cf_global" because it transcends a
86 * single file (i.e., a file included from .git/config is still in "repo"
87 * scope).
89 static enum config_scope current_parsing_scope;
91 static inline void config_reader_push_source(struct config_reader *reader,
92 struct config_source *top)
94 if (reader->config_kvi)
95 BUG("source should not be set while iterating a config set");
96 top->prev = reader->source;
97 reader->source = top;
100 static inline struct config_source *config_reader_pop_source(struct config_reader *reader)
102 struct config_source *ret;
103 if (!reader->source)
104 BUG("tried to pop config source, but we weren't reading config");
105 ret = reader->source;
106 reader->source = reader->source->prev;
107 return ret;
110 static inline void config_reader_set_kvi(struct config_reader *reader,
111 struct key_value_info *kvi)
113 if (kvi && reader->source)
114 BUG("kvi should not be set while parsing a config source");
115 reader->config_kvi = kvi;
118 static int pack_compression_seen;
119 static int zlib_compression_seen;
122 * Config that comes from trusted scopes, namely:
123 * - CONFIG_SCOPE_SYSTEM (e.g. /etc/gitconfig)
124 * - CONFIG_SCOPE_GLOBAL (e.g. $HOME/.gitconfig, $XDG_CONFIG_HOME/git)
125 * - CONFIG_SCOPE_COMMAND (e.g. "-c" option, environment variables)
127 * This is declared here for code cleanliness, but unlike the other
128 * static variables, this does not hold config parser state.
130 static struct config_set protected_config;
132 static int config_file_fgetc(struct config_source *conf)
134 return getc_unlocked(conf->u.file);
137 static int config_file_ungetc(int c, struct config_source *conf)
139 return ungetc(c, conf->u.file);
142 static long config_file_ftell(struct config_source *conf)
144 return ftell(conf->u.file);
148 static int config_buf_fgetc(struct config_source *conf)
150 if (conf->u.buf.pos < conf->u.buf.len)
151 return conf->u.buf.buf[conf->u.buf.pos++];
153 return EOF;
156 static int config_buf_ungetc(int c, struct config_source *conf)
158 if (conf->u.buf.pos > 0) {
159 conf->u.buf.pos--;
160 if (conf->u.buf.buf[conf->u.buf.pos] != c)
161 BUG("config_buf can only ungetc the same character");
162 return c;
165 return EOF;
168 static long config_buf_ftell(struct config_source *conf)
170 return conf->u.buf.pos;
173 struct config_include_data {
174 int depth;
175 config_fn_t fn;
176 void *data;
177 const struct config_options *opts;
178 struct git_config_source *config_source;
179 struct config_reader *config_reader;
182 * All remote URLs discovered when reading all config files.
184 struct string_list *remote_urls;
186 #define CONFIG_INCLUDE_INIT { 0 }
188 static int git_config_include(const char *var, const char *value, void *data);
190 #define MAX_INCLUDE_DEPTH 10
191 static const char include_depth_advice[] = N_(
192 "exceeded maximum include depth (%d) while including\n"
193 " %s\n"
194 "from\n"
195 " %s\n"
196 "This might be due to circular includes.");
197 static int handle_path_include(struct config_source *cf, const char *path,
198 struct config_include_data *inc)
200 int ret = 0;
201 struct strbuf buf = STRBUF_INIT;
202 char *expanded;
204 if (!path)
205 return config_error_nonbool("include.path");
207 expanded = interpolate_path(path, 0);
208 if (!expanded)
209 return error(_("could not expand include path '%s'"), path);
210 path = expanded;
213 * Use an absolute path as-is, but interpret relative paths
214 * based on the including config file.
216 if (!is_absolute_path(path)) {
217 char *slash;
219 if (!cf || !cf->path) {
220 ret = error(_("relative config includes must come from files"));
221 goto cleanup;
224 slash = find_last_dir_sep(cf->path);
225 if (slash)
226 strbuf_add(&buf, cf->path, slash - cf->path + 1);
227 strbuf_addstr(&buf, path);
228 path = buf.buf;
231 if (!access_or_die(path, R_OK, 0)) {
232 if (++inc->depth > MAX_INCLUDE_DEPTH)
233 die(_(include_depth_advice), MAX_INCLUDE_DEPTH, path,
234 !cf ? "<unknown>" :
235 cf->name ? cf->name :
236 "the command line");
237 ret = git_config_from_file(git_config_include, path, inc);
238 inc->depth--;
240 cleanup:
241 strbuf_release(&buf);
242 free(expanded);
243 return ret;
246 static void add_trailing_starstar_for_dir(struct strbuf *pat)
248 if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
249 strbuf_addstr(pat, "**");
252 static int prepare_include_condition_pattern(struct config_source *cf,
253 struct strbuf *pat)
255 struct strbuf path = STRBUF_INIT;
256 char *expanded;
257 int prefix = 0;
259 expanded = interpolate_path(pat->buf, 1);
260 if (expanded) {
261 strbuf_reset(pat);
262 strbuf_addstr(pat, expanded);
263 free(expanded);
266 if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
267 const char *slash;
269 if (!cf || !cf->path)
270 return error(_("relative config include "
271 "conditionals must come from files"));
273 strbuf_realpath(&path, cf->path, 1);
274 slash = find_last_dir_sep(path.buf);
275 if (!slash)
276 BUG("how is this possible?");
277 strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
278 prefix = slash - path.buf + 1 /* slash */;
279 } else if (!is_absolute_path(pat->buf))
280 strbuf_insertstr(pat, 0, "**/");
282 add_trailing_starstar_for_dir(pat);
284 strbuf_release(&path);
285 return prefix;
288 static int include_by_gitdir(struct config_source *cf,
289 const struct config_options *opts,
290 const char *cond, size_t cond_len, int icase)
292 struct strbuf text = STRBUF_INIT;
293 struct strbuf pattern = STRBUF_INIT;
294 int ret = 0, prefix;
295 const char *git_dir;
296 int already_tried_absolute = 0;
298 if (opts->git_dir)
299 git_dir = opts->git_dir;
300 else
301 goto done;
303 strbuf_realpath(&text, git_dir, 1);
304 strbuf_add(&pattern, cond, cond_len);
305 prefix = prepare_include_condition_pattern(cf, &pattern);
307 again:
308 if (prefix < 0)
309 goto done;
311 if (prefix > 0) {
313 * perform literal matching on the prefix part so that
314 * any wildcard character in it can't create side effects.
316 if (text.len < prefix)
317 goto done;
318 if (!icase && strncmp(pattern.buf, text.buf, prefix))
319 goto done;
320 if (icase && strncasecmp(pattern.buf, text.buf, prefix))
321 goto done;
324 ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
325 WM_PATHNAME | (icase ? WM_CASEFOLD : 0));
327 if (!ret && !already_tried_absolute) {
329 * We've tried e.g. matching gitdir:~/work, but if
330 * ~/work is a symlink to /mnt/storage/work
331 * strbuf_realpath() will expand it, so the rule won't
332 * match. Let's match against a
333 * strbuf_add_absolute_path() version of the path,
334 * which'll do the right thing
336 strbuf_reset(&text);
337 strbuf_add_absolute_path(&text, git_dir);
338 already_tried_absolute = 1;
339 goto again;
341 done:
342 strbuf_release(&pattern);
343 strbuf_release(&text);
344 return ret;
347 static int include_by_branch(const char *cond, size_t cond_len)
349 int flags;
350 int ret;
351 struct strbuf pattern = STRBUF_INIT;
352 const char *refname = !the_repository->gitdir ?
353 NULL : resolve_ref_unsafe("HEAD", 0, NULL, &flags);
354 const char *shortname;
356 if (!refname || !(flags & REF_ISSYMREF) ||
357 !skip_prefix(refname, "refs/heads/", &shortname))
358 return 0;
360 strbuf_add(&pattern, cond, cond_len);
361 add_trailing_starstar_for_dir(&pattern);
362 ret = !wildmatch(pattern.buf, shortname, WM_PATHNAME);
363 strbuf_release(&pattern);
364 return ret;
367 static int add_remote_url(const char *var, const char *value, void *data)
369 struct string_list *remote_urls = data;
370 const char *remote_name;
371 size_t remote_name_len;
372 const char *key;
374 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
375 &key) &&
376 remote_name &&
377 !strcmp(key, "url"))
378 string_list_append(remote_urls, value);
379 return 0;
382 static void populate_remote_urls(struct config_include_data *inc)
384 struct config_options opts;
386 enum config_scope store_scope = current_parsing_scope;
388 opts = *inc->opts;
389 opts.unconditional_remote_url = 1;
391 current_parsing_scope = 0;
393 inc->remote_urls = xmalloc(sizeof(*inc->remote_urls));
394 string_list_init_dup(inc->remote_urls);
395 config_with_options(add_remote_url, inc->remote_urls, inc->config_source, &opts);
397 current_parsing_scope = store_scope;
400 static int forbid_remote_url(const char *var, const char *value UNUSED,
401 void *data UNUSED)
403 const char *remote_name;
404 size_t remote_name_len;
405 const char *key;
407 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
408 &key) &&
409 remote_name &&
410 !strcmp(key, "url"))
411 die(_("remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"));
412 return 0;
415 static int at_least_one_url_matches_glob(const char *glob, int glob_len,
416 struct string_list *remote_urls)
418 struct strbuf pattern = STRBUF_INIT;
419 struct string_list_item *url_item;
420 int found = 0;
422 strbuf_add(&pattern, glob, glob_len);
423 for_each_string_list_item(url_item, remote_urls) {
424 if (!wildmatch(pattern.buf, url_item->string, WM_PATHNAME)) {
425 found = 1;
426 break;
429 strbuf_release(&pattern);
430 return found;
433 static int include_by_remote_url(struct config_include_data *inc,
434 const char *cond, size_t cond_len)
436 if (inc->opts->unconditional_remote_url)
437 return 1;
438 if (!inc->remote_urls)
439 populate_remote_urls(inc);
440 return at_least_one_url_matches_glob(cond, cond_len,
441 inc->remote_urls);
444 static int include_condition_is_true(struct config_source *cf,
445 struct config_include_data *inc,
446 const char *cond, size_t cond_len)
448 const struct config_options *opts = inc->opts;
450 if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
451 return include_by_gitdir(cf, opts, cond, cond_len, 0);
452 else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
453 return include_by_gitdir(cf, opts, cond, cond_len, 1);
454 else if (skip_prefix_mem(cond, cond_len, "onbranch:", &cond, &cond_len))
455 return include_by_branch(cond, cond_len);
456 else if (skip_prefix_mem(cond, cond_len, "hasconfig:remote.*.url:", &cond,
457 &cond_len))
458 return include_by_remote_url(inc, cond, cond_len);
460 /* unknown conditionals are always false */
461 return 0;
464 static int git_config_include(const char *var, const char *value, void *data)
466 struct config_include_data *inc = data;
467 struct config_source *cf = inc->config_reader->source;
468 const char *cond, *key;
469 size_t cond_len;
470 int ret;
473 * Pass along all values, including "include" directives; this makes it
474 * possible to query information on the includes themselves.
476 ret = inc->fn(var, value, inc->data);
477 if (ret < 0)
478 return ret;
480 if (!strcmp(var, "include.path"))
481 ret = handle_path_include(cf, value, inc);
483 if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
484 cond && include_condition_is_true(cf, inc, cond, cond_len) &&
485 !strcmp(key, "path")) {
486 config_fn_t old_fn = inc->fn;
488 if (inc->opts->unconditional_remote_url)
489 inc->fn = forbid_remote_url;
490 ret = handle_path_include(cf, value, inc);
491 inc->fn = old_fn;
494 return ret;
497 static void git_config_push_split_parameter(const char *key, const char *value)
499 struct strbuf env = STRBUF_INIT;
500 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
501 if (old && *old) {
502 strbuf_addstr(&env, old);
503 strbuf_addch(&env, ' ');
505 sq_quote_buf(&env, key);
506 strbuf_addch(&env, '=');
507 if (value)
508 sq_quote_buf(&env, value);
509 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
510 strbuf_release(&env);
513 void git_config_push_parameter(const char *text)
515 const char *value;
518 * When we see:
520 * section.subsection=with=equals.key=value
522 * we cannot tell if it means:
524 * [section "subsection=with=equals"]
525 * key = value
527 * or:
529 * [section]
530 * subsection = with=equals.key=value
532 * We parse left-to-right for the first "=", meaning we'll prefer to
533 * keep the value intact over the subsection. This is historical, but
534 * also sensible since values are more likely to contain odd or
535 * untrusted input than a section name.
537 * A missing equals is explicitly allowed (as a bool-only entry).
539 value = strchr(text, '=');
540 if (value) {
541 char *key = xmemdupz(text, value - text);
542 git_config_push_split_parameter(key, value + 1);
543 free(key);
544 } else {
545 git_config_push_split_parameter(text, NULL);
549 void git_config_push_env(const char *spec)
551 char *key;
552 const char *env_name;
553 const char *env_value;
555 env_name = strrchr(spec, '=');
556 if (!env_name)
557 die(_("invalid config format: %s"), spec);
558 key = xmemdupz(spec, env_name - spec);
559 env_name++;
560 if (!*env_name)
561 die(_("missing environment variable name for configuration '%.*s'"),
562 (int)(env_name - spec - 1), spec);
564 env_value = getenv(env_name);
565 if (!env_value)
566 die(_("missing environment variable '%s' for configuration '%.*s'"),
567 env_name, (int)(env_name - spec - 1), spec);
569 git_config_push_split_parameter(key, env_value);
570 free(key);
573 static inline int iskeychar(int c)
575 return isalnum(c) || c == '-';
579 * Auxiliary function to sanity-check and split the key into the section
580 * identifier and variable name.
582 * Returns 0 on success, -1 when there is an invalid character in the key and
583 * -2 if there is no section name in the key.
585 * store_key - pointer to char* which will hold a copy of the key with
586 * lowercase section and variable name
587 * baselen - pointer to size_t which will hold the length of the
588 * section + subsection part, can be NULL
590 int git_config_parse_key(const char *key, char **store_key, size_t *baselen_)
592 size_t i, baselen;
593 int dot;
594 const char *last_dot = strrchr(key, '.');
597 * Since "key" actually contains the section name and the real
598 * key name separated by a dot, we have to know where the dot is.
601 if (last_dot == NULL || last_dot == key) {
602 error(_("key does not contain a section: %s"), key);
603 return -CONFIG_NO_SECTION_OR_NAME;
606 if (!last_dot[1]) {
607 error(_("key does not contain variable name: %s"), key);
608 return -CONFIG_NO_SECTION_OR_NAME;
611 baselen = last_dot - key;
612 if (baselen_)
613 *baselen_ = baselen;
616 * Validate the key and while at it, lower case it for matching.
618 *store_key = xmallocz(strlen(key));
620 dot = 0;
621 for (i = 0; key[i]; i++) {
622 unsigned char c = key[i];
623 if (c == '.')
624 dot = 1;
625 /* Leave the extended basename untouched.. */
626 if (!dot || i > baselen) {
627 if (!iskeychar(c) ||
628 (i == baselen + 1 && !isalpha(c))) {
629 error(_("invalid key: %s"), key);
630 goto out_free_ret_1;
632 c = tolower(c);
633 } else if (c == '\n') {
634 error(_("invalid key (newline): %s"), key);
635 goto out_free_ret_1;
637 (*store_key)[i] = c;
640 return 0;
642 out_free_ret_1:
643 FREE_AND_NULL(*store_key);
644 return -CONFIG_INVALID_KEY;
647 static int config_parse_pair(const char *key, const char *value,
648 config_fn_t fn, void *data)
650 char *canonical_name;
651 int ret;
653 if (!strlen(key))
654 return error(_("empty config key"));
655 if (git_config_parse_key(key, &canonical_name, NULL))
656 return -1;
658 ret = (fn(canonical_name, value, data) < 0) ? -1 : 0;
659 free(canonical_name);
660 return ret;
663 int git_config_parse_parameter(const char *text,
664 config_fn_t fn, void *data)
666 const char *value;
667 struct strbuf **pair;
668 int ret;
670 pair = strbuf_split_str(text, '=', 2);
671 if (!pair[0])
672 return error(_("bogus config parameter: %s"), text);
674 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
675 strbuf_setlen(pair[0], pair[0]->len - 1);
676 value = pair[1] ? pair[1]->buf : "";
677 } else {
678 value = NULL;
681 strbuf_trim(pair[0]);
682 if (!pair[0]->len) {
683 strbuf_list_free(pair);
684 return error(_("bogus config parameter: %s"), text);
687 ret = config_parse_pair(pair[0]->buf, value, fn, data);
688 strbuf_list_free(pair);
689 return ret;
692 static int parse_config_env_list(char *env, config_fn_t fn, void *data)
694 char *cur = env;
695 while (cur && *cur) {
696 const char *key = sq_dequote_step(cur, &cur);
697 if (!key)
698 return error(_("bogus format in %s"),
699 CONFIG_DATA_ENVIRONMENT);
701 if (!cur || isspace(*cur)) {
702 /* old-style 'key=value' */
703 if (git_config_parse_parameter(key, fn, data) < 0)
704 return -1;
706 else if (*cur == '=') {
707 /* new-style 'key'='value' */
708 const char *value;
710 cur++;
711 if (*cur == '\'') {
712 /* quoted value */
713 value = sq_dequote_step(cur, &cur);
714 if (!value || (cur && !isspace(*cur))) {
715 return error(_("bogus format in %s"),
716 CONFIG_DATA_ENVIRONMENT);
718 } else if (!*cur || isspace(*cur)) {
719 /* implicit bool: 'key'= */
720 value = NULL;
721 } else {
722 return error(_("bogus format in %s"),
723 CONFIG_DATA_ENVIRONMENT);
726 if (config_parse_pair(key, value, fn, data) < 0)
727 return -1;
729 else {
730 /* unknown format */
731 return error(_("bogus format in %s"),
732 CONFIG_DATA_ENVIRONMENT);
735 if (cur) {
736 while (isspace(*cur))
737 cur++;
740 return 0;
743 int git_config_from_parameters(config_fn_t fn, void *data)
745 const char *env;
746 struct strbuf envvar = STRBUF_INIT;
747 struct strvec to_free = STRVEC_INIT;
748 int ret = 0;
749 char *envw = NULL;
750 struct config_source source = CONFIG_SOURCE_INIT;
752 source.origin_type = CONFIG_ORIGIN_CMDLINE;
753 config_reader_push_source(&the_reader, &source);
755 env = getenv(CONFIG_COUNT_ENVIRONMENT);
756 if (env) {
757 unsigned long count;
758 char *endp;
759 int i;
761 count = strtoul(env, &endp, 10);
762 if (*endp) {
763 ret = error(_("bogus count in %s"), CONFIG_COUNT_ENVIRONMENT);
764 goto out;
766 if (count > INT_MAX) {
767 ret = error(_("too many entries in %s"), CONFIG_COUNT_ENVIRONMENT);
768 goto out;
771 for (i = 0; i < count; i++) {
772 const char *key, *value;
774 strbuf_addf(&envvar, "GIT_CONFIG_KEY_%d", i);
775 key = getenv_safe(&to_free, envvar.buf);
776 if (!key) {
777 ret = error(_("missing config key %s"), envvar.buf);
778 goto out;
780 strbuf_reset(&envvar);
782 strbuf_addf(&envvar, "GIT_CONFIG_VALUE_%d", i);
783 value = getenv_safe(&to_free, envvar.buf);
784 if (!value) {
785 ret = error(_("missing config value %s"), envvar.buf);
786 goto out;
788 strbuf_reset(&envvar);
790 if (config_parse_pair(key, value, fn, data) < 0) {
791 ret = -1;
792 goto out;
797 env = getenv(CONFIG_DATA_ENVIRONMENT);
798 if (env) {
799 /* sq_dequote will write over it */
800 envw = xstrdup(env);
801 if (parse_config_env_list(envw, fn, data) < 0) {
802 ret = -1;
803 goto out;
807 out:
808 strbuf_release(&envvar);
809 strvec_clear(&to_free);
810 free(envw);
811 config_reader_pop_source(&the_reader);
812 return ret;
815 static int get_next_char(struct config_source *cf)
817 int c = cf->do_fgetc(cf);
819 if (c == '\r') {
820 /* DOS like systems */
821 c = cf->do_fgetc(cf);
822 if (c != '\n') {
823 if (c != EOF)
824 cf->do_ungetc(c, cf);
825 c = '\r';
829 if (c != EOF && ++cf->total_len > INT_MAX) {
831 * This is an absurdly long config file; refuse to parse
832 * further in order to protect downstream code from integer
833 * overflows. Note that we can't return an error specifically,
834 * but we can mark EOF and put trash in the return value,
835 * which will trigger a parse error.
837 cf->eof = 1;
838 return 0;
841 if (c == '\n')
842 cf->linenr++;
843 if (c == EOF) {
844 cf->eof = 1;
845 cf->linenr++;
846 c = '\n';
848 return c;
851 static char *parse_value(struct config_source *cf)
853 int quote = 0, comment = 0, space = 0;
855 strbuf_reset(&cf->value);
856 for (;;) {
857 int c = get_next_char(cf);
858 if (c == '\n') {
859 if (quote) {
860 cf->linenr--;
861 return NULL;
863 return cf->value.buf;
865 if (comment)
866 continue;
867 if (isspace(c) && !quote) {
868 if (cf->value.len)
869 space++;
870 continue;
872 if (!quote) {
873 if (c == ';' || c == '#') {
874 comment = 1;
875 continue;
878 for (; space; space--)
879 strbuf_addch(&cf->value, ' ');
880 if (c == '\\') {
881 c = get_next_char(cf);
882 switch (c) {
883 case '\n':
884 continue;
885 case 't':
886 c = '\t';
887 break;
888 case 'b':
889 c = '\b';
890 break;
891 case 'n':
892 c = '\n';
893 break;
894 /* Some characters escape as themselves */
895 case '\\': case '"':
896 break;
897 /* Reject unknown escape sequences */
898 default:
899 return NULL;
901 strbuf_addch(&cf->value, c);
902 continue;
904 if (c == '"') {
905 quote = 1-quote;
906 continue;
908 strbuf_addch(&cf->value, c);
912 static int get_value(struct config_source *cf, config_fn_t fn, void *data,
913 struct strbuf *name)
915 int c;
916 char *value;
917 int ret;
919 /* Get the full name */
920 for (;;) {
921 c = get_next_char(cf);
922 if (cf->eof)
923 break;
924 if (!iskeychar(c))
925 break;
926 strbuf_addch(name, tolower(c));
929 while (c == ' ' || c == '\t')
930 c = get_next_char(cf);
932 value = NULL;
933 if (c != '\n') {
934 if (c != '=')
935 return -1;
936 value = parse_value(cf);
937 if (!value)
938 return -1;
941 * We already consumed the \n, but we need linenr to point to
942 * the line we just parsed during the call to fn to get
943 * accurate line number in error messages.
945 cf->linenr--;
946 ret = fn(name->buf, value, data);
947 if (ret >= 0)
948 cf->linenr++;
949 return ret;
952 static int get_extended_base_var(struct config_source *cf, struct strbuf *name,
953 int c)
955 cf->subsection_case_sensitive = 0;
956 do {
957 if (c == '\n')
958 goto error_incomplete_line;
959 c = get_next_char(cf);
960 } while (isspace(c));
962 /* We require the format to be '[base "extension"]' */
963 if (c != '"')
964 return -1;
965 strbuf_addch(name, '.');
967 for (;;) {
968 int c = get_next_char(cf);
969 if (c == '\n')
970 goto error_incomplete_line;
971 if (c == '"')
972 break;
973 if (c == '\\') {
974 c = get_next_char(cf);
975 if (c == '\n')
976 goto error_incomplete_line;
978 strbuf_addch(name, c);
981 /* Final ']' */
982 if (get_next_char(cf) != ']')
983 return -1;
984 return 0;
985 error_incomplete_line:
986 cf->linenr--;
987 return -1;
990 static int get_base_var(struct config_source *cf, struct strbuf *name)
992 cf->subsection_case_sensitive = 1;
993 for (;;) {
994 int c = get_next_char(cf);
995 if (cf->eof)
996 return -1;
997 if (c == ']')
998 return 0;
999 if (isspace(c))
1000 return get_extended_base_var(cf, name, c);
1001 if (!iskeychar(c) && c != '.')
1002 return -1;
1003 strbuf_addch(name, tolower(c));
1007 struct parse_event_data {
1008 enum config_event_t previous_type;
1009 size_t previous_offset;
1010 const struct config_options *opts;
1013 static int do_event(struct config_source *cf, enum config_event_t type,
1014 struct parse_event_data *data)
1016 size_t offset;
1018 if (!data->opts || !data->opts->event_fn)
1019 return 0;
1021 if (type == CONFIG_EVENT_WHITESPACE &&
1022 data->previous_type == type)
1023 return 0;
1025 offset = cf->do_ftell(cf);
1027 * At EOF, the parser always "inserts" an extra '\n', therefore
1028 * the end offset of the event is the current file position, otherwise
1029 * we will already have advanced to the next event.
1031 if (type != CONFIG_EVENT_EOF)
1032 offset--;
1034 if (data->previous_type != CONFIG_EVENT_EOF &&
1035 data->opts->event_fn(data->previous_type, data->previous_offset,
1036 offset, data->opts->event_fn_data) < 0)
1037 return -1;
1039 data->previous_type = type;
1040 data->previous_offset = offset;
1042 return 0;
1045 static int git_parse_source(struct config_source *cf, config_fn_t fn,
1046 void *data, const struct config_options *opts)
1048 int comment = 0;
1049 size_t baselen = 0;
1050 struct strbuf *var = &cf->var;
1051 int error_return = 0;
1052 char *error_msg = NULL;
1054 /* U+FEFF Byte Order Mark in UTF8 */
1055 const char *bomptr = utf8_bom;
1057 /* For the parser event callback */
1058 struct parse_event_data event_data = {
1059 CONFIG_EVENT_EOF, 0, opts
1062 for (;;) {
1063 int c;
1065 c = get_next_char(cf);
1066 if (bomptr && *bomptr) {
1067 /* We are at the file beginning; skip UTF8-encoded BOM
1068 * if present. Sane editors won't put this in on their
1069 * own, but e.g. Windows Notepad will do it happily. */
1070 if (c == (*bomptr & 0377)) {
1071 bomptr++;
1072 continue;
1073 } else {
1074 /* Do not tolerate partial BOM. */
1075 if (bomptr != utf8_bom)
1076 break;
1077 /* No BOM at file beginning. Cool. */
1078 bomptr = NULL;
1081 if (c == '\n') {
1082 if (cf->eof) {
1083 if (do_event(cf, CONFIG_EVENT_EOF, &event_data) < 0)
1084 return -1;
1085 return 0;
1087 if (do_event(cf, CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1088 return -1;
1089 comment = 0;
1090 continue;
1092 if (comment)
1093 continue;
1094 if (isspace(c)) {
1095 if (do_event(cf, CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1096 return -1;
1097 continue;
1099 if (c == '#' || c == ';') {
1100 if (do_event(cf, CONFIG_EVENT_COMMENT, &event_data) < 0)
1101 return -1;
1102 comment = 1;
1103 continue;
1105 if (c == '[') {
1106 if (do_event(cf, CONFIG_EVENT_SECTION, &event_data) < 0)
1107 return -1;
1109 /* Reset prior to determining a new stem */
1110 strbuf_reset(var);
1111 if (get_base_var(cf, var) < 0 || var->len < 1)
1112 break;
1113 strbuf_addch(var, '.');
1114 baselen = var->len;
1115 continue;
1117 if (!isalpha(c))
1118 break;
1120 if (do_event(cf, CONFIG_EVENT_ENTRY, &event_data) < 0)
1121 return -1;
1124 * Truncate the var name back to the section header
1125 * stem prior to grabbing the suffix part of the name
1126 * and the value.
1128 strbuf_setlen(var, baselen);
1129 strbuf_addch(var, tolower(c));
1130 if (get_value(cf, fn, data, var) < 0)
1131 break;
1134 if (do_event(cf, CONFIG_EVENT_ERROR, &event_data) < 0)
1135 return -1;
1137 switch (cf->origin_type) {
1138 case CONFIG_ORIGIN_BLOB:
1139 error_msg = xstrfmt(_("bad config line %d in blob %s"),
1140 cf->linenr, cf->name);
1141 break;
1142 case CONFIG_ORIGIN_FILE:
1143 error_msg = xstrfmt(_("bad config line %d in file %s"),
1144 cf->linenr, cf->name);
1145 break;
1146 case CONFIG_ORIGIN_STDIN:
1147 error_msg = xstrfmt(_("bad config line %d in standard input"),
1148 cf->linenr);
1149 break;
1150 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1151 error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
1152 cf->linenr, cf->name);
1153 break;
1154 case CONFIG_ORIGIN_CMDLINE:
1155 error_msg = xstrfmt(_("bad config line %d in command line %s"),
1156 cf->linenr, cf->name);
1157 break;
1158 default:
1159 error_msg = xstrfmt(_("bad config line %d in %s"),
1160 cf->linenr, cf->name);
1163 switch (opts && opts->error_action ?
1164 opts->error_action :
1165 cf->default_error_action) {
1166 case CONFIG_ERROR_DIE:
1167 die("%s", error_msg);
1168 break;
1169 case CONFIG_ERROR_ERROR:
1170 error_return = error("%s", error_msg);
1171 break;
1172 case CONFIG_ERROR_SILENT:
1173 error_return = -1;
1174 break;
1175 case CONFIG_ERROR_UNSET:
1176 BUG("config error action unset");
1179 free(error_msg);
1180 return error_return;
1183 static uintmax_t get_unit_factor(const char *end)
1185 if (!*end)
1186 return 1;
1187 else if (!strcasecmp(end, "k"))
1188 return 1024;
1189 else if (!strcasecmp(end, "m"))
1190 return 1024 * 1024;
1191 else if (!strcasecmp(end, "g"))
1192 return 1024 * 1024 * 1024;
1193 return 0;
1196 static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
1198 if (value && *value) {
1199 char *end;
1200 intmax_t val;
1201 intmax_t factor;
1203 if (max < 0)
1204 BUG("max must be a positive integer");
1206 errno = 0;
1207 val = strtoimax(value, &end, 0);
1208 if (errno == ERANGE)
1209 return 0;
1210 if (end == value) {
1211 errno = EINVAL;
1212 return 0;
1214 factor = get_unit_factor(end);
1215 if (!factor) {
1216 errno = EINVAL;
1217 return 0;
1219 if ((val < 0 && -max / factor > val) ||
1220 (val > 0 && max / factor < val)) {
1221 errno = ERANGE;
1222 return 0;
1224 val *= factor;
1225 *ret = val;
1226 return 1;
1228 errno = EINVAL;
1229 return 0;
1232 static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
1234 if (value && *value) {
1235 char *end;
1236 uintmax_t val;
1237 uintmax_t factor;
1239 /* negative values would be accepted by strtoumax */
1240 if (strchr(value, '-')) {
1241 errno = EINVAL;
1242 return 0;
1244 errno = 0;
1245 val = strtoumax(value, &end, 0);
1246 if (errno == ERANGE)
1247 return 0;
1248 if (end == value) {
1249 errno = EINVAL;
1250 return 0;
1252 factor = get_unit_factor(end);
1253 if (!factor) {
1254 errno = EINVAL;
1255 return 0;
1257 if (unsigned_mult_overflows(factor, val) ||
1258 factor * val > max) {
1259 errno = ERANGE;
1260 return 0;
1262 val *= factor;
1263 *ret = val;
1264 return 1;
1266 errno = EINVAL;
1267 return 0;
1270 int git_parse_int(const char *value, int *ret)
1272 intmax_t tmp;
1273 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
1274 return 0;
1275 *ret = tmp;
1276 return 1;
1279 static int git_parse_int64(const char *value, int64_t *ret)
1281 intmax_t tmp;
1282 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
1283 return 0;
1284 *ret = tmp;
1285 return 1;
1288 int git_parse_ulong(const char *value, unsigned long *ret)
1290 uintmax_t tmp;
1291 if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
1292 return 0;
1293 *ret = tmp;
1294 return 1;
1297 int git_parse_ssize_t(const char *value, ssize_t *ret)
1299 intmax_t tmp;
1300 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(ssize_t)))
1301 return 0;
1302 *ret = tmp;
1303 return 1;
1306 NORETURN
1307 static void die_bad_number(struct config_source *cf, const char *name,
1308 const char *value)
1310 const char *error_type = (errno == ERANGE) ?
1311 N_("out of range") : N_("invalid unit");
1312 const char *bad_numeric = N_("bad numeric config value '%s' for '%s': %s");
1314 if (!value)
1315 value = "";
1317 if (!(cf && cf->name))
1318 die(_(bad_numeric), value, name, _(error_type));
1320 switch (cf->origin_type) {
1321 case CONFIG_ORIGIN_BLOB:
1322 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
1323 value, name, cf->name, _(error_type));
1324 case CONFIG_ORIGIN_FILE:
1325 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
1326 value, name, cf->name, _(error_type));
1327 case CONFIG_ORIGIN_STDIN:
1328 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
1329 value, name, _(error_type));
1330 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1331 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
1332 value, name, cf->name, _(error_type));
1333 case CONFIG_ORIGIN_CMDLINE:
1334 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
1335 value, name, cf->name, _(error_type));
1336 default:
1337 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
1338 value, name, cf->name, _(error_type));
1342 int git_config_int(const char *name, const char *value)
1344 int ret;
1345 if (!git_parse_int(value, &ret))
1346 die_bad_number(the_reader.source, name, value);
1347 return ret;
1350 int64_t git_config_int64(const char *name, const char *value)
1352 int64_t ret;
1353 if (!git_parse_int64(value, &ret))
1354 die_bad_number(the_reader.source, name, value);
1355 return ret;
1358 unsigned long git_config_ulong(const char *name, const char *value)
1360 unsigned long ret;
1361 if (!git_parse_ulong(value, &ret))
1362 die_bad_number(the_reader.source, name, value);
1363 return ret;
1366 ssize_t git_config_ssize_t(const char *name, const char *value)
1368 ssize_t ret;
1369 if (!git_parse_ssize_t(value, &ret))
1370 die_bad_number(the_reader.source, name, value);
1371 return ret;
1374 static int git_parse_maybe_bool_text(const char *value)
1376 if (!value)
1377 return 1;
1378 if (!*value)
1379 return 0;
1380 if (!strcasecmp(value, "true")
1381 || !strcasecmp(value, "yes")
1382 || !strcasecmp(value, "on"))
1383 return 1;
1384 if (!strcasecmp(value, "false")
1385 || !strcasecmp(value, "no")
1386 || !strcasecmp(value, "off"))
1387 return 0;
1388 return -1;
1391 static const struct fsync_component_name {
1392 const char *name;
1393 enum fsync_component component_bits;
1394 } fsync_component_names[] = {
1395 { "loose-object", FSYNC_COMPONENT_LOOSE_OBJECT },
1396 { "pack", FSYNC_COMPONENT_PACK },
1397 { "pack-metadata", FSYNC_COMPONENT_PACK_METADATA },
1398 { "commit-graph", FSYNC_COMPONENT_COMMIT_GRAPH },
1399 { "index", FSYNC_COMPONENT_INDEX },
1400 { "objects", FSYNC_COMPONENTS_OBJECTS },
1401 { "reference", FSYNC_COMPONENT_REFERENCE },
1402 { "derived-metadata", FSYNC_COMPONENTS_DERIVED_METADATA },
1403 { "committed", FSYNC_COMPONENTS_COMMITTED },
1404 { "added", FSYNC_COMPONENTS_ADDED },
1405 { "all", FSYNC_COMPONENTS_ALL },
1408 static enum fsync_component parse_fsync_components(const char *var, const char *string)
1410 enum fsync_component current = FSYNC_COMPONENTS_PLATFORM_DEFAULT;
1411 enum fsync_component positive = 0, negative = 0;
1413 while (string) {
1414 int i;
1415 size_t len;
1416 const char *ep;
1417 int negated = 0;
1418 int found = 0;
1420 string = string + strspn(string, ", \t\n\r");
1421 ep = strchrnul(string, ',');
1422 len = ep - string;
1423 if (!strcmp(string, "none")) {
1424 current = FSYNC_COMPONENT_NONE;
1425 goto next_name;
1428 if (*string == '-') {
1429 negated = 1;
1430 string++;
1431 len--;
1432 if (!len)
1433 warning(_("invalid value for variable %s"), var);
1436 if (!len)
1437 break;
1439 for (i = 0; i < ARRAY_SIZE(fsync_component_names); ++i) {
1440 const struct fsync_component_name *n = &fsync_component_names[i];
1442 if (strncmp(n->name, string, len))
1443 continue;
1445 found = 1;
1446 if (negated)
1447 negative |= n->component_bits;
1448 else
1449 positive |= n->component_bits;
1452 if (!found) {
1453 char *component = xstrndup(string, len);
1454 warning(_("ignoring unknown core.fsync component '%s'"), component);
1455 free(component);
1458 next_name:
1459 string = ep;
1462 return (current & ~negative) | positive;
1465 int git_parse_maybe_bool(const char *value)
1467 int v = git_parse_maybe_bool_text(value);
1468 if (0 <= v)
1469 return v;
1470 if (git_parse_int(value, &v))
1471 return !!v;
1472 return -1;
1475 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
1477 int v = git_parse_maybe_bool_text(value);
1478 if (0 <= v) {
1479 *is_bool = 1;
1480 return v;
1482 *is_bool = 0;
1483 return git_config_int(name, value);
1486 int git_config_bool(const char *name, const char *value)
1488 int v = git_parse_maybe_bool(value);
1489 if (v < 0)
1490 die(_("bad boolean config value '%s' for '%s'"), value, name);
1491 return v;
1494 int git_config_string(const char **dest, const char *var, const char *value)
1496 if (!value)
1497 return config_error_nonbool(var);
1498 *dest = xstrdup(value);
1499 return 0;
1502 int git_config_pathname(const char **dest, const char *var, const char *value)
1504 if (!value)
1505 return config_error_nonbool(var);
1506 *dest = interpolate_path(value, 0);
1507 if (!*dest)
1508 die(_("failed to expand user dir in: '%s'"), value);
1509 return 0;
1512 int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1514 if (!value)
1515 return config_error_nonbool(var);
1516 if (parse_expiry_date(value, timestamp))
1517 return error(_("'%s' for '%s' is not a valid timestamp"),
1518 value, var);
1519 return 0;
1522 int git_config_color(char *dest, const char *var, const char *value)
1524 if (!value)
1525 return config_error_nonbool(var);
1526 if (color_parse(value, dest) < 0)
1527 return -1;
1528 return 0;
1531 static int git_default_core_config(const char *var, const char *value, void *cb)
1533 /* This needs a better name */
1534 if (!strcmp(var, "core.filemode")) {
1535 trust_executable_bit = git_config_bool(var, value);
1536 return 0;
1538 if (!strcmp(var, "core.trustctime")) {
1539 trust_ctime = git_config_bool(var, value);
1540 return 0;
1542 if (!strcmp(var, "core.checkstat")) {
1543 if (!strcasecmp(value, "default"))
1544 check_stat = 1;
1545 else if (!strcasecmp(value, "minimal"))
1546 check_stat = 0;
1549 if (!strcmp(var, "core.quotepath")) {
1550 quote_path_fully = git_config_bool(var, value);
1551 return 0;
1554 if (!strcmp(var, "core.symlinks")) {
1555 has_symlinks = git_config_bool(var, value);
1556 return 0;
1559 if (!strcmp(var, "core.ignorecase")) {
1560 ignore_case = git_config_bool(var, value);
1561 return 0;
1564 if (!strcmp(var, "core.attributesfile"))
1565 return git_config_pathname(&git_attributes_file, var, value);
1567 if (!strcmp(var, "core.hookspath"))
1568 return git_config_pathname(&git_hooks_path, var, value);
1570 if (!strcmp(var, "core.bare")) {
1571 is_bare_repository_cfg = git_config_bool(var, value);
1572 return 0;
1575 if (!strcmp(var, "core.ignorestat")) {
1576 assume_unchanged = git_config_bool(var, value);
1577 return 0;
1580 if (!strcmp(var, "core.prefersymlinkrefs")) {
1581 prefer_symlink_refs = git_config_bool(var, value);
1582 return 0;
1585 if (!strcmp(var, "core.logallrefupdates")) {
1586 if (value && !strcasecmp(value, "always"))
1587 log_all_ref_updates = LOG_REFS_ALWAYS;
1588 else if (git_config_bool(var, value))
1589 log_all_ref_updates = LOG_REFS_NORMAL;
1590 else
1591 log_all_ref_updates = LOG_REFS_NONE;
1592 return 0;
1595 if (!strcmp(var, "core.warnambiguousrefs")) {
1596 warn_ambiguous_refs = git_config_bool(var, value);
1597 return 0;
1600 if (!strcmp(var, "core.abbrev")) {
1601 if (!value)
1602 return config_error_nonbool(var);
1603 if (!strcasecmp(value, "auto"))
1604 default_abbrev = -1;
1605 else if (!git_parse_maybe_bool_text(value))
1606 default_abbrev = the_hash_algo->hexsz;
1607 else {
1608 int abbrev = git_config_int(var, value);
1609 if (abbrev < minimum_abbrev || abbrev > the_hash_algo->hexsz)
1610 return error(_("abbrev length out of range: %d"), abbrev);
1611 default_abbrev = abbrev;
1613 return 0;
1616 if (!strcmp(var, "core.disambiguate"))
1617 return set_disambiguate_hint_config(var, value);
1619 if (!strcmp(var, "core.loosecompression")) {
1620 int level = git_config_int(var, value);
1621 if (level == -1)
1622 level = Z_DEFAULT_COMPRESSION;
1623 else if (level < 0 || level > Z_BEST_COMPRESSION)
1624 die(_("bad zlib compression level %d"), level);
1625 zlib_compression_level = level;
1626 zlib_compression_seen = 1;
1627 return 0;
1630 if (!strcmp(var, "core.compression")) {
1631 int level = git_config_int(var, value);
1632 if (level == -1)
1633 level = Z_DEFAULT_COMPRESSION;
1634 else if (level < 0 || level > Z_BEST_COMPRESSION)
1635 die(_("bad zlib compression level %d"), level);
1636 if (!zlib_compression_seen)
1637 zlib_compression_level = level;
1638 if (!pack_compression_seen)
1639 pack_compression_level = level;
1640 return 0;
1643 if (!strcmp(var, "core.packedgitwindowsize")) {
1644 int pgsz_x2 = getpagesize() * 2;
1645 packed_git_window_size = git_config_ulong(var, value);
1647 /* This value must be multiple of (pagesize * 2) */
1648 packed_git_window_size /= pgsz_x2;
1649 if (packed_git_window_size < 1)
1650 packed_git_window_size = 1;
1651 packed_git_window_size *= pgsz_x2;
1652 return 0;
1655 if (!strcmp(var, "core.bigfilethreshold")) {
1656 big_file_threshold = git_config_ulong(var, value);
1657 return 0;
1660 if (!strcmp(var, "core.packedgitlimit")) {
1661 packed_git_limit = git_config_ulong(var, value);
1662 return 0;
1665 if (!strcmp(var, "core.deltabasecachelimit")) {
1666 delta_base_cache_limit = git_config_ulong(var, value);
1667 return 0;
1670 if (!strcmp(var, "core.autocrlf")) {
1671 if (value && !strcasecmp(value, "input")) {
1672 auto_crlf = AUTO_CRLF_INPUT;
1673 return 0;
1675 auto_crlf = git_config_bool(var, value);
1676 return 0;
1679 if (!strcmp(var, "core.safecrlf")) {
1680 int eol_rndtrp_die;
1681 if (value && !strcasecmp(value, "warn")) {
1682 global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
1683 return 0;
1685 eol_rndtrp_die = git_config_bool(var, value);
1686 global_conv_flags_eol = eol_rndtrp_die ?
1687 CONV_EOL_RNDTRP_DIE : 0;
1688 return 0;
1691 if (!strcmp(var, "core.eol")) {
1692 if (value && !strcasecmp(value, "lf"))
1693 core_eol = EOL_LF;
1694 else if (value && !strcasecmp(value, "crlf"))
1695 core_eol = EOL_CRLF;
1696 else if (value && !strcasecmp(value, "native"))
1697 core_eol = EOL_NATIVE;
1698 else
1699 core_eol = EOL_UNSET;
1700 return 0;
1703 if (!strcmp(var, "core.checkroundtripencoding")) {
1704 check_roundtrip_encoding = xstrdup(value);
1705 return 0;
1708 if (!strcmp(var, "core.notesref")) {
1709 notes_ref_name = xstrdup(value);
1710 return 0;
1713 if (!strcmp(var, "core.editor"))
1714 return git_config_string(&editor_program, var, value);
1716 if (!strcmp(var, "core.commentchar")) {
1717 if (!value)
1718 return config_error_nonbool(var);
1719 else if (!strcasecmp(value, "auto"))
1720 auto_comment_line_char = 1;
1721 else if (value[0] && !value[1]) {
1722 comment_line_char = value[0];
1723 auto_comment_line_char = 0;
1724 } else
1725 return error(_("core.commentChar should only be one character"));
1726 return 0;
1729 if (!strcmp(var, "core.askpass"))
1730 return git_config_string(&askpass_program, var, value);
1732 if (!strcmp(var, "core.excludesfile"))
1733 return git_config_pathname(&excludes_file, var, value);
1735 if (!strcmp(var, "core.whitespace")) {
1736 if (!value)
1737 return config_error_nonbool(var);
1738 whitespace_rule_cfg = parse_whitespace_rule(value);
1739 return 0;
1742 if (!strcmp(var, "core.fsync")) {
1743 if (!value)
1744 return config_error_nonbool(var);
1745 fsync_components = parse_fsync_components(var, value);
1746 return 0;
1749 if (!strcmp(var, "core.fsyncmethod")) {
1750 if (!value)
1751 return config_error_nonbool(var);
1752 if (!strcmp(value, "fsync"))
1753 fsync_method = FSYNC_METHOD_FSYNC;
1754 else if (!strcmp(value, "writeout-only"))
1755 fsync_method = FSYNC_METHOD_WRITEOUT_ONLY;
1756 else if (!strcmp(value, "batch"))
1757 fsync_method = FSYNC_METHOD_BATCH;
1758 else
1759 warning(_("ignoring unknown core.fsyncMethod value '%s'"), value);
1763 if (!strcmp(var, "core.fsyncobjectfiles")) {
1764 if (fsync_object_files < 0)
1765 warning(_("core.fsyncObjectFiles is deprecated; use core.fsync instead"));
1766 fsync_object_files = git_config_bool(var, value);
1767 return 0;
1770 if (!strcmp(var, "core.preloadindex")) {
1771 core_preload_index = git_config_bool(var, value);
1772 return 0;
1775 if (!strcmp(var, "core.createobject")) {
1776 if (!strcmp(value, "rename"))
1777 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
1778 else if (!strcmp(value, "link"))
1779 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
1780 else
1781 die(_("invalid mode for object creation: %s"), value);
1782 return 0;
1785 if (!strcmp(var, "core.sparsecheckout")) {
1786 core_apply_sparse_checkout = git_config_bool(var, value);
1787 return 0;
1790 if (!strcmp(var, "core.sparsecheckoutcone")) {
1791 core_sparse_checkout_cone = git_config_bool(var, value);
1792 return 0;
1795 if (!strcmp(var, "core.precomposeunicode")) {
1796 precomposed_unicode = git_config_bool(var, value);
1797 return 0;
1800 if (!strcmp(var, "core.protecthfs")) {
1801 protect_hfs = git_config_bool(var, value);
1802 return 0;
1805 if (!strcmp(var, "core.protectntfs")) {
1806 protect_ntfs = git_config_bool(var, value);
1807 return 0;
1810 if (!strcmp(var, "core.usereplacerefs")) {
1811 read_replace_refs = git_config_bool(var, value);
1812 return 0;
1815 /* Add other config variables here and to Documentation/config.txt. */
1816 return platform_core_config(var, value, cb);
1819 static int git_default_sparse_config(const char *var, const char *value)
1821 if (!strcmp(var, "sparse.expectfilesoutsideofpatterns")) {
1822 sparse_expect_files_outside_of_patterns = git_config_bool(var, value);
1823 return 0;
1826 /* Add other config variables here and to Documentation/config/sparse.txt. */
1827 return 0;
1830 static int git_default_i18n_config(const char *var, const char *value)
1832 if (!strcmp(var, "i18n.commitencoding"))
1833 return git_config_string(&git_commit_encoding, var, value);
1835 if (!strcmp(var, "i18n.logoutputencoding"))
1836 return git_config_string(&git_log_output_encoding, var, value);
1838 /* Add other config variables here and to Documentation/config.txt. */
1839 return 0;
1842 static int git_default_branch_config(const char *var, const char *value)
1844 if (!strcmp(var, "branch.autosetupmerge")) {
1845 if (value && !strcmp(value, "always")) {
1846 git_branch_track = BRANCH_TRACK_ALWAYS;
1847 return 0;
1848 } else if (value && !strcmp(value, "inherit")) {
1849 git_branch_track = BRANCH_TRACK_INHERIT;
1850 return 0;
1851 } else if (value && !strcmp(value, "simple")) {
1852 git_branch_track = BRANCH_TRACK_SIMPLE;
1853 return 0;
1855 git_branch_track = git_config_bool(var, value);
1856 return 0;
1858 if (!strcmp(var, "branch.autosetuprebase")) {
1859 if (!value)
1860 return config_error_nonbool(var);
1861 else if (!strcmp(value, "never"))
1862 autorebase = AUTOREBASE_NEVER;
1863 else if (!strcmp(value, "local"))
1864 autorebase = AUTOREBASE_LOCAL;
1865 else if (!strcmp(value, "remote"))
1866 autorebase = AUTOREBASE_REMOTE;
1867 else if (!strcmp(value, "always"))
1868 autorebase = AUTOREBASE_ALWAYS;
1869 else
1870 return error(_("malformed value for %s"), var);
1871 return 0;
1874 /* Add other config variables here and to Documentation/config.txt. */
1875 return 0;
1878 static int git_default_push_config(const char *var, const char *value)
1880 if (!strcmp(var, "push.default")) {
1881 if (!value)
1882 return config_error_nonbool(var);
1883 else if (!strcmp(value, "nothing"))
1884 push_default = PUSH_DEFAULT_NOTHING;
1885 else if (!strcmp(value, "matching"))
1886 push_default = PUSH_DEFAULT_MATCHING;
1887 else if (!strcmp(value, "simple"))
1888 push_default = PUSH_DEFAULT_SIMPLE;
1889 else if (!strcmp(value, "upstream"))
1890 push_default = PUSH_DEFAULT_UPSTREAM;
1891 else if (!strcmp(value, "tracking")) /* deprecated */
1892 push_default = PUSH_DEFAULT_UPSTREAM;
1893 else if (!strcmp(value, "current"))
1894 push_default = PUSH_DEFAULT_CURRENT;
1895 else {
1896 error(_("malformed value for %s: %s"), var, value);
1897 return error(_("must be one of nothing, matching, simple, "
1898 "upstream or current"));
1900 return 0;
1903 /* Add other config variables here and to Documentation/config.txt. */
1904 return 0;
1907 static int git_default_mailmap_config(const char *var, const char *value)
1909 if (!strcmp(var, "mailmap.file"))
1910 return git_config_pathname(&git_mailmap_file, var, value);
1911 if (!strcmp(var, "mailmap.blob"))
1912 return git_config_string(&git_mailmap_blob, var, value);
1914 /* Add other config variables here and to Documentation/config.txt. */
1915 return 0;
1918 int git_default_config(const char *var, const char *value, void *cb)
1920 if (starts_with(var, "core."))
1921 return git_default_core_config(var, value, cb);
1923 if (starts_with(var, "user.") ||
1924 starts_with(var, "author.") ||
1925 starts_with(var, "committer."))
1926 return git_ident_config(var, value, cb);
1928 if (starts_with(var, "i18n."))
1929 return git_default_i18n_config(var, value);
1931 if (starts_with(var, "branch."))
1932 return git_default_branch_config(var, value);
1934 if (starts_with(var, "push."))
1935 return git_default_push_config(var, value);
1937 if (starts_with(var, "mailmap."))
1938 return git_default_mailmap_config(var, value);
1940 if (starts_with(var, "advice.") || starts_with(var, "color.advice"))
1941 return git_default_advice_config(var, value);
1943 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1944 pager_use_color = git_config_bool(var,value);
1945 return 0;
1948 if (!strcmp(var, "pack.packsizelimit")) {
1949 pack_size_limit_cfg = git_config_ulong(var, value);
1950 return 0;
1953 if (!strcmp(var, "pack.compression")) {
1954 int level = git_config_int(var, value);
1955 if (level == -1)
1956 level = Z_DEFAULT_COMPRESSION;
1957 else if (level < 0 || level > Z_BEST_COMPRESSION)
1958 die(_("bad pack compression level %d"), level);
1959 pack_compression_level = level;
1960 pack_compression_seen = 1;
1961 return 0;
1964 if (starts_with(var, "sparse."))
1965 return git_default_sparse_config(var, value);
1967 /* Add other config variables here and to Documentation/config.txt. */
1968 return 0;
1972 * All source specific fields in the union, die_on_error, name and the callbacks
1973 * fgetc, ungetc, ftell of top need to be initialized before calling
1974 * this function.
1976 static int do_config_from(struct config_reader *reader,
1977 struct config_source *top, config_fn_t fn, void *data,
1978 const struct config_options *opts)
1980 int ret;
1982 /* push config-file parsing state stack */
1983 top->linenr = 1;
1984 top->eof = 0;
1985 top->total_len = 0;
1986 strbuf_init(&top->value, 1024);
1987 strbuf_init(&top->var, 1024);
1988 config_reader_push_source(reader, top);
1990 ret = git_parse_source(top, fn, data, opts);
1992 /* pop config-file parsing state stack */
1993 strbuf_release(&top->value);
1994 strbuf_release(&top->var);
1995 config_reader_pop_source(reader);
1997 return ret;
2000 static int do_config_from_file(struct config_reader *reader,
2001 config_fn_t fn,
2002 const enum config_origin_type origin_type,
2003 const char *name, const char *path, FILE *f,
2004 void *data, const struct config_options *opts)
2006 struct config_source top = CONFIG_SOURCE_INIT;
2007 int ret;
2009 top.u.file = f;
2010 top.origin_type = origin_type;
2011 top.name = name;
2012 top.path = path;
2013 top.default_error_action = CONFIG_ERROR_DIE;
2014 top.do_fgetc = config_file_fgetc;
2015 top.do_ungetc = config_file_ungetc;
2016 top.do_ftell = config_file_ftell;
2018 flockfile(f);
2019 ret = do_config_from(reader, &top, fn, data, opts);
2020 funlockfile(f);
2021 return ret;
2024 static int git_config_from_stdin(config_fn_t fn, void *data)
2026 return do_config_from_file(&the_reader, fn, CONFIG_ORIGIN_STDIN, "",
2027 NULL, stdin, data, NULL);
2030 int git_config_from_file_with_options(config_fn_t fn, const char *filename,
2031 void *data,
2032 const struct config_options *opts)
2034 int ret = -1;
2035 FILE *f;
2037 if (!filename)
2038 BUG("filename cannot be NULL");
2039 f = fopen_or_warn(filename, "r");
2040 if (f) {
2041 ret = do_config_from_file(&the_reader, fn, CONFIG_ORIGIN_FILE,
2042 filename, filename, f, data, opts);
2043 fclose(f);
2045 return ret;
2048 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
2050 return git_config_from_file_with_options(fn, filename, data, NULL);
2053 int git_config_from_mem(config_fn_t fn,
2054 const enum config_origin_type origin_type,
2055 const char *name, const char *buf, size_t len,
2056 void *data, const struct config_options *opts)
2058 struct config_source top = CONFIG_SOURCE_INIT;
2060 top.u.buf.buf = buf;
2061 top.u.buf.len = len;
2062 top.u.buf.pos = 0;
2063 top.origin_type = origin_type;
2064 top.name = name;
2065 top.path = NULL;
2066 top.default_error_action = CONFIG_ERROR_ERROR;
2067 top.do_fgetc = config_buf_fgetc;
2068 top.do_ungetc = config_buf_ungetc;
2069 top.do_ftell = config_buf_ftell;
2071 return do_config_from(&the_reader, &top, fn, data, opts);
2074 int git_config_from_blob_oid(config_fn_t fn,
2075 const char *name,
2076 struct repository *repo,
2077 const struct object_id *oid,
2078 void *data)
2080 enum object_type type;
2081 char *buf;
2082 unsigned long size;
2083 int ret;
2085 buf = repo_read_object_file(repo, oid, &type, &size);
2086 if (!buf)
2087 return error(_("unable to load config blob object '%s'"), name);
2088 if (type != OBJ_BLOB) {
2089 free(buf);
2090 return error(_("reference '%s' does not point to a blob"), name);
2093 ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size,
2094 data, NULL);
2095 free(buf);
2097 return ret;
2100 static int git_config_from_blob_ref(config_fn_t fn,
2101 struct repository *repo,
2102 const char *name,
2103 void *data)
2105 struct object_id oid;
2107 if (repo_get_oid(repo, name, &oid) < 0)
2108 return error(_("unable to resolve config blob '%s'"), name);
2109 return git_config_from_blob_oid(fn, name, repo, &oid, data);
2112 char *git_system_config(void)
2114 char *system_config = xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
2115 if (!system_config)
2116 system_config = system_path(ETC_GITCONFIG);
2117 normalize_path_copy(system_config, system_config);
2118 return system_config;
2121 void git_global_config(char **user_out, char **xdg_out)
2123 char *user_config = xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
2124 char *xdg_config = NULL;
2126 if (!user_config) {
2127 user_config = interpolate_path("~/.gitconfig", 0);
2128 xdg_config = xdg_config_home("config");
2131 *user_out = user_config;
2132 *xdg_out = xdg_config;
2136 * Parse environment variable 'k' as a boolean (in various
2137 * possible spellings); if missing, use the default value 'def'.
2139 int git_env_bool(const char *k, int def)
2141 const char *v = getenv(k);
2142 return v ? git_config_bool(k, v) : def;
2146 * Parse environment variable 'k' as ulong with possibly a unit
2147 * suffix; if missing, use the default value 'val'.
2149 unsigned long git_env_ulong(const char *k, unsigned long val)
2151 const char *v = getenv(k);
2152 if (v && !git_parse_ulong(v, &val))
2153 die(_("failed to parse %s"), k);
2154 return val;
2157 int git_config_system(void)
2159 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
2162 static int do_git_config_sequence(const struct config_options *opts,
2163 config_fn_t fn, void *data)
2165 int ret = 0;
2166 char *system_config = git_system_config();
2167 char *xdg_config = NULL;
2168 char *user_config = NULL;
2169 char *repo_config;
2170 enum config_scope prev_parsing_scope = current_parsing_scope;
2172 if (opts->commondir)
2173 repo_config = mkpathdup("%s/config", opts->commondir);
2174 else if (opts->git_dir)
2175 BUG("git_dir without commondir");
2176 else
2177 repo_config = NULL;
2179 current_parsing_scope = CONFIG_SCOPE_SYSTEM;
2180 if (git_config_system() && system_config &&
2181 !access_or_die(system_config, R_OK,
2182 opts->system_gently ? ACCESS_EACCES_OK : 0))
2183 ret += git_config_from_file(fn, system_config, data);
2185 current_parsing_scope = CONFIG_SCOPE_GLOBAL;
2186 git_global_config(&user_config, &xdg_config);
2188 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
2189 ret += git_config_from_file(fn, xdg_config, data);
2191 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
2192 ret += git_config_from_file(fn, user_config, data);
2194 current_parsing_scope = CONFIG_SCOPE_LOCAL;
2195 if (!opts->ignore_repo && repo_config &&
2196 !access_or_die(repo_config, R_OK, 0))
2197 ret += git_config_from_file(fn, repo_config, data);
2199 current_parsing_scope = CONFIG_SCOPE_WORKTREE;
2200 if (!opts->ignore_worktree && repository_format_worktree_config) {
2201 char *path = git_pathdup("config.worktree");
2202 if (!access_or_die(path, R_OK, 0))
2203 ret += git_config_from_file(fn, path, data);
2204 free(path);
2207 current_parsing_scope = CONFIG_SCOPE_COMMAND;
2208 if (!opts->ignore_cmdline && git_config_from_parameters(fn, data) < 0)
2209 die(_("unable to parse command-line config"));
2211 current_parsing_scope = prev_parsing_scope;
2212 free(system_config);
2213 free(xdg_config);
2214 free(user_config);
2215 free(repo_config);
2216 return ret;
2219 int config_with_options(config_fn_t fn, void *data,
2220 struct git_config_source *config_source,
2221 const struct config_options *opts)
2223 struct config_include_data inc = CONFIG_INCLUDE_INIT;
2224 int ret;
2226 if (opts->respect_includes) {
2227 inc.fn = fn;
2228 inc.data = data;
2229 inc.opts = opts;
2230 inc.config_source = config_source;
2231 inc.config_reader = &the_reader;
2232 fn = git_config_include;
2233 data = &inc;
2236 if (config_source)
2237 current_parsing_scope = config_source->scope;
2240 * If we have a specific filename, use it. Otherwise, follow the
2241 * regular lookup sequence.
2243 if (config_source && config_source->use_stdin) {
2244 ret = git_config_from_stdin(fn, data);
2245 } else if (config_source && config_source->file) {
2246 ret = git_config_from_file(fn, config_source->file, data);
2247 } else if (config_source && config_source->blob) {
2248 struct repository *repo = config_source->repo ?
2249 config_source->repo : the_repository;
2250 ret = git_config_from_blob_ref(fn, repo, config_source->blob,
2251 data);
2252 } else {
2253 ret = do_git_config_sequence(opts, fn, data);
2256 if (inc.remote_urls) {
2257 string_list_clear(inc.remote_urls, 0);
2258 FREE_AND_NULL(inc.remote_urls);
2260 return ret;
2263 static void configset_iter(struct config_reader *reader, struct config_set *cs,
2264 config_fn_t fn, void *data)
2266 int i, value_index;
2267 struct string_list *values;
2268 struct config_set_element *entry;
2269 struct configset_list *list = &cs->list;
2271 for (i = 0; i < list->nr; i++) {
2272 entry = list->items[i].e;
2273 value_index = list->items[i].value_index;
2274 values = &entry->value_list;
2276 config_reader_set_kvi(reader, values->items[value_index].util);
2278 if (fn(entry->key, values->items[value_index].string, data) < 0)
2279 git_die_config_linenr(entry->key,
2280 reader->config_kvi->filename,
2281 reader->config_kvi->linenr);
2283 config_reader_set_kvi(reader, NULL);
2287 void read_early_config(config_fn_t cb, void *data)
2289 struct config_options opts = {0};
2290 struct strbuf commondir = STRBUF_INIT;
2291 struct strbuf gitdir = STRBUF_INIT;
2293 opts.respect_includes = 1;
2295 if (have_git_dir()) {
2296 opts.commondir = get_git_common_dir();
2297 opts.git_dir = get_git_dir();
2299 * When setup_git_directory() was not yet asked to discover the
2300 * GIT_DIR, we ask discover_git_directory() to figure out whether there
2301 * is any repository config we should use (but unlike
2302 * setup_git_directory_gently(), no global state is changed, most
2303 * notably, the current working directory is still the same after the
2304 * call).
2306 } else if (!discover_git_directory(&commondir, &gitdir)) {
2307 opts.commondir = commondir.buf;
2308 opts.git_dir = gitdir.buf;
2311 config_with_options(cb, data, NULL, &opts);
2313 strbuf_release(&commondir);
2314 strbuf_release(&gitdir);
2318 * Read config but only enumerate system and global settings.
2319 * Omit any repo-local, worktree-local, or command-line settings.
2321 void read_very_early_config(config_fn_t cb, void *data)
2323 struct config_options opts = { 0 };
2325 opts.respect_includes = 1;
2326 opts.ignore_repo = 1;
2327 opts.ignore_worktree = 1;
2328 opts.ignore_cmdline = 1;
2329 opts.system_gently = 1;
2331 config_with_options(cb, data, NULL, &opts);
2334 static struct config_set_element *configset_find_element(struct config_set *cs, const char *key)
2336 struct config_set_element k;
2337 struct config_set_element *found_entry;
2338 char *normalized_key;
2340 * `key` may come from the user, so normalize it before using it
2341 * for querying entries from the hashmap.
2343 if (git_config_parse_key(key, &normalized_key, NULL))
2344 return NULL;
2346 hashmap_entry_init(&k.ent, strhash(normalized_key));
2347 k.key = normalized_key;
2348 found_entry = hashmap_get_entry(&cs->config_hash, &k, ent, NULL);
2349 free(normalized_key);
2350 return found_entry;
2353 static int configset_add_value(struct config_reader *reader,
2354 struct config_set *cs, const char *key,
2355 const char *value)
2357 struct config_set_element *e;
2358 struct string_list_item *si;
2359 struct configset_list_item *l_item;
2360 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
2362 e = configset_find_element(cs, key);
2364 * Since the keys are being fed by git_config*() callback mechanism, they
2365 * are already normalized. So simply add them without any further munging.
2367 if (!e) {
2368 e = xmalloc(sizeof(*e));
2369 hashmap_entry_init(&e->ent, strhash(key));
2370 e->key = xstrdup(key);
2371 string_list_init_dup(&e->value_list);
2372 hashmap_add(&cs->config_hash, &e->ent);
2374 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
2376 ALLOC_GROW(cs->list.items, cs->list.nr + 1, cs->list.alloc);
2377 l_item = &cs->list.items[cs->list.nr++];
2378 l_item->e = e;
2379 l_item->value_index = e->value_list.nr - 1;
2381 if (!reader->source)
2382 BUG("configset_add_value has no source");
2383 if (reader->source->name) {
2384 kv_info->filename = strintern(reader->source->name);
2385 kv_info->linenr = reader->source->linenr;
2386 kv_info->origin_type = reader->source->origin_type;
2387 } else {
2388 /* for values read from `git_config_from_parameters()` */
2389 kv_info->filename = NULL;
2390 kv_info->linenr = -1;
2391 kv_info->origin_type = CONFIG_ORIGIN_CMDLINE;
2393 kv_info->scope = current_parsing_scope;
2394 si->util = kv_info;
2396 return 0;
2399 static int config_set_element_cmp(const void *cmp_data UNUSED,
2400 const struct hashmap_entry *eptr,
2401 const struct hashmap_entry *entry_or_key,
2402 const void *keydata UNUSED)
2404 const struct config_set_element *e1, *e2;
2406 e1 = container_of(eptr, const struct config_set_element, ent);
2407 e2 = container_of(entry_or_key, const struct config_set_element, ent);
2409 return strcmp(e1->key, e2->key);
2412 void git_configset_init(struct config_set *cs)
2414 hashmap_init(&cs->config_hash, config_set_element_cmp, NULL, 0);
2415 cs->hash_initialized = 1;
2416 cs->list.nr = 0;
2417 cs->list.alloc = 0;
2418 cs->list.items = NULL;
2421 void git_configset_clear(struct config_set *cs)
2423 struct config_set_element *entry;
2424 struct hashmap_iter iter;
2425 if (!cs->hash_initialized)
2426 return;
2428 hashmap_for_each_entry(&cs->config_hash, &iter, entry,
2429 ent /* member name */) {
2430 free(entry->key);
2431 string_list_clear(&entry->value_list, 1);
2433 hashmap_clear_and_free(&cs->config_hash, struct config_set_element, ent);
2434 cs->hash_initialized = 0;
2435 free(cs->list.items);
2436 cs->list.nr = 0;
2437 cs->list.alloc = 0;
2438 cs->list.items = NULL;
2441 struct configset_add_data {
2442 struct config_set *config_set;
2443 struct config_reader *config_reader;
2445 #define CONFIGSET_ADD_INIT { 0 }
2447 static int config_set_callback(const char *key, const char *value, void *cb)
2449 struct configset_add_data *data = cb;
2450 configset_add_value(data->config_reader, data->config_set, key, value);
2451 return 0;
2454 int git_configset_add_file(struct config_set *cs, const char *filename)
2456 struct configset_add_data data = CONFIGSET_ADD_INIT;
2457 data.config_reader = &the_reader;
2458 data.config_set = cs;
2459 return git_config_from_file(config_set_callback, filename, &data);
2462 int git_configset_get_value(struct config_set *cs, const char *key, const char **value)
2464 const struct string_list *values = NULL;
2466 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
2467 * queried key in the files of the configset, the value returned will be the last
2468 * value in the value list for that key.
2470 values = git_configset_get_value_multi(cs, key);
2472 if (!values)
2473 return 1;
2474 assert(values->nr > 0);
2475 *value = values->items[values->nr - 1].string;
2476 return 0;
2479 const struct string_list *git_configset_get_value_multi(struct config_set *cs, const char *key)
2481 struct config_set_element *e = configset_find_element(cs, key);
2482 return e ? &e->value_list : NULL;
2485 int git_configset_get_string(struct config_set *cs, const char *key, char **dest)
2487 const char *value;
2488 if (!git_configset_get_value(cs, key, &value))
2489 return git_config_string((const char **)dest, key, value);
2490 else
2491 return 1;
2494 static int git_configset_get_string_tmp(struct config_set *cs, const char *key,
2495 const char **dest)
2497 const char *value;
2498 if (!git_configset_get_value(cs, key, &value)) {
2499 if (!value)
2500 return config_error_nonbool(key);
2501 *dest = value;
2502 return 0;
2503 } else {
2504 return 1;
2508 int git_configset_get_int(struct config_set *cs, const char *key, int *dest)
2510 const char *value;
2511 if (!git_configset_get_value(cs, key, &value)) {
2512 *dest = git_config_int(key, value);
2513 return 0;
2514 } else
2515 return 1;
2518 int git_configset_get_ulong(struct config_set *cs, const char *key, unsigned long *dest)
2520 const char *value;
2521 if (!git_configset_get_value(cs, key, &value)) {
2522 *dest = git_config_ulong(key, value);
2523 return 0;
2524 } else
2525 return 1;
2528 int git_configset_get_bool(struct config_set *cs, const char *key, int *dest)
2530 const char *value;
2531 if (!git_configset_get_value(cs, key, &value)) {
2532 *dest = git_config_bool(key, value);
2533 return 0;
2534 } else
2535 return 1;
2538 int git_configset_get_bool_or_int(struct config_set *cs, const char *key,
2539 int *is_bool, int *dest)
2541 const char *value;
2542 if (!git_configset_get_value(cs, key, &value)) {
2543 *dest = git_config_bool_or_int(key, value, is_bool);
2544 return 0;
2545 } else
2546 return 1;
2549 int git_configset_get_maybe_bool(struct config_set *cs, const char *key, int *dest)
2551 const char *value;
2552 if (!git_configset_get_value(cs, key, &value)) {
2553 *dest = git_parse_maybe_bool(value);
2554 if (*dest == -1)
2555 return -1;
2556 return 0;
2557 } else
2558 return 1;
2561 int git_configset_get_pathname(struct config_set *cs, const char *key, const char **dest)
2563 const char *value;
2564 if (!git_configset_get_value(cs, key, &value))
2565 return git_config_pathname(dest, key, value);
2566 else
2567 return 1;
2570 /* Functions use to read configuration from a repository */
2571 static void repo_read_config(struct repository *repo)
2573 struct config_options opts = { 0 };
2574 struct configset_add_data data = CONFIGSET_ADD_INIT;
2576 opts.respect_includes = 1;
2577 opts.commondir = repo->commondir;
2578 opts.git_dir = repo->gitdir;
2580 if (!repo->config)
2581 CALLOC_ARRAY(repo->config, 1);
2582 else
2583 git_configset_clear(repo->config);
2585 git_configset_init(repo->config);
2586 data.config_set = repo->config;
2587 data.config_reader = &the_reader;
2589 if (config_with_options(config_set_callback, &data, NULL, &opts) < 0)
2591 * config_with_options() normally returns only
2592 * zero, as most errors are fatal, and
2593 * non-fatal potential errors are guarded by "if"
2594 * statements that are entered only when no error is
2595 * possible.
2597 * If we ever encounter a non-fatal error, it means
2598 * something went really wrong and we should stop
2599 * immediately.
2601 die(_("unknown error occurred while reading the configuration files"));
2604 static void git_config_check_init(struct repository *repo)
2606 if (repo->config && repo->config->hash_initialized)
2607 return;
2608 repo_read_config(repo);
2611 static void repo_config_clear(struct repository *repo)
2613 if (!repo->config || !repo->config->hash_initialized)
2614 return;
2615 git_configset_clear(repo->config);
2618 void repo_config(struct repository *repo, config_fn_t fn, void *data)
2620 git_config_check_init(repo);
2621 configset_iter(&the_reader, repo->config, fn, data);
2624 int repo_config_get_value(struct repository *repo,
2625 const char *key, const char **value)
2627 git_config_check_init(repo);
2628 return git_configset_get_value(repo->config, key, value);
2631 const struct string_list *repo_config_get_value_multi(struct repository *repo,
2632 const char *key)
2634 git_config_check_init(repo);
2635 return git_configset_get_value_multi(repo->config, key);
2638 int repo_config_get_string(struct repository *repo,
2639 const char *key, char **dest)
2641 int ret;
2642 git_config_check_init(repo);
2643 ret = git_configset_get_string(repo->config, key, dest);
2644 if (ret < 0)
2645 git_die_config(key, NULL);
2646 return ret;
2649 int repo_config_get_string_tmp(struct repository *repo,
2650 const char *key, const char **dest)
2652 int ret;
2653 git_config_check_init(repo);
2654 ret = git_configset_get_string_tmp(repo->config, key, dest);
2655 if (ret < 0)
2656 git_die_config(key, NULL);
2657 return ret;
2660 int repo_config_get_int(struct repository *repo,
2661 const char *key, int *dest)
2663 git_config_check_init(repo);
2664 return git_configset_get_int(repo->config, key, dest);
2667 int repo_config_get_ulong(struct repository *repo,
2668 const char *key, unsigned long *dest)
2670 git_config_check_init(repo);
2671 return git_configset_get_ulong(repo->config, key, dest);
2674 int repo_config_get_bool(struct repository *repo,
2675 const char *key, int *dest)
2677 git_config_check_init(repo);
2678 return git_configset_get_bool(repo->config, key, dest);
2681 int repo_config_get_bool_or_int(struct repository *repo,
2682 const char *key, int *is_bool, int *dest)
2684 git_config_check_init(repo);
2685 return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2688 int repo_config_get_maybe_bool(struct repository *repo,
2689 const char *key, int *dest)
2691 git_config_check_init(repo);
2692 return git_configset_get_maybe_bool(repo->config, key, dest);
2695 int repo_config_get_pathname(struct repository *repo,
2696 const char *key, const char **dest)
2698 int ret;
2699 git_config_check_init(repo);
2700 ret = git_configset_get_pathname(repo->config, key, dest);
2701 if (ret < 0)
2702 git_die_config(key, NULL);
2703 return ret;
2706 /* Read values into protected_config. */
2707 static void read_protected_config(void)
2709 struct config_options opts = {
2710 .respect_includes = 1,
2711 .ignore_repo = 1,
2712 .ignore_worktree = 1,
2713 .system_gently = 1,
2715 struct configset_add_data data = CONFIGSET_ADD_INIT;
2717 git_configset_init(&protected_config);
2718 data.config_set = &protected_config;
2719 data.config_reader = &the_reader;
2720 config_with_options(config_set_callback, &data, NULL, &opts);
2723 void git_protected_config(config_fn_t fn, void *data)
2725 if (!protected_config.hash_initialized)
2726 read_protected_config();
2727 configset_iter(&the_reader, &protected_config, fn, data);
2730 /* Functions used historically to read configuration from 'the_repository' */
2731 void git_config(config_fn_t fn, void *data)
2733 repo_config(the_repository, fn, data);
2736 void git_config_clear(void)
2738 repo_config_clear(the_repository);
2741 int git_config_get_value(const char *key, const char **value)
2743 return repo_config_get_value(the_repository, key, value);
2746 const struct string_list *git_config_get_value_multi(const char *key)
2748 return repo_config_get_value_multi(the_repository, key);
2751 int git_config_get_string(const char *key, char **dest)
2753 return repo_config_get_string(the_repository, key, dest);
2756 int git_config_get_string_tmp(const char *key, const char **dest)
2758 return repo_config_get_string_tmp(the_repository, key, dest);
2761 int git_config_get_int(const char *key, int *dest)
2763 return repo_config_get_int(the_repository, key, dest);
2766 int git_config_get_ulong(const char *key, unsigned long *dest)
2768 return repo_config_get_ulong(the_repository, key, dest);
2771 int git_config_get_bool(const char *key, int *dest)
2773 return repo_config_get_bool(the_repository, key, dest);
2776 int git_config_get_bool_or_int(const char *key, int *is_bool, int *dest)
2778 return repo_config_get_bool_or_int(the_repository, key, is_bool, dest);
2781 int git_config_get_maybe_bool(const char *key, int *dest)
2783 return repo_config_get_maybe_bool(the_repository, key, dest);
2786 int git_config_get_pathname(const char *key, const char **dest)
2788 return repo_config_get_pathname(the_repository, key, dest);
2791 int git_config_get_expiry(const char *key, const char **output)
2793 int ret = git_config_get_string(key, (char **)output);
2794 if (ret)
2795 return ret;
2796 if (strcmp(*output, "now")) {
2797 timestamp_t now = approxidate("now");
2798 if (approxidate(*output) >= now)
2799 git_die_config(key, _("Invalid %s: '%s'"), key, *output);
2801 return ret;
2804 int git_config_get_expiry_in_days(const char *key, timestamp_t *expiry, timestamp_t now)
2806 const char *expiry_string;
2807 intmax_t days;
2808 timestamp_t when;
2810 if (git_config_get_string_tmp(key, &expiry_string))
2811 return 1; /* no such thing */
2813 if (git_parse_signed(expiry_string, &days, maximum_signed_value_of_type(int))) {
2814 const int scale = 86400;
2815 *expiry = now - days * scale;
2816 return 0;
2819 if (!parse_expiry_date(expiry_string, &when)) {
2820 *expiry = when;
2821 return 0;
2823 return -1; /* thing exists but cannot be parsed */
2826 int git_config_get_split_index(void)
2828 int val;
2830 if (!git_config_get_maybe_bool("core.splitindex", &val))
2831 return val;
2833 return -1; /* default value */
2836 int git_config_get_max_percent_split_change(void)
2838 int val = -1;
2840 if (!git_config_get_int("splitindex.maxpercentchange", &val)) {
2841 if (0 <= val && val <= 100)
2842 return val;
2844 return error(_("splitIndex.maxPercentChange value '%d' "
2845 "should be between 0 and 100"), val);
2848 return -1; /* default value */
2851 int git_config_get_index_threads(int *dest)
2853 int is_bool, val;
2855 val = git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2856 if (val) {
2857 *dest = val;
2858 return 0;
2861 if (!git_config_get_bool_or_int("index.threads", &is_bool, &val)) {
2862 if (is_bool)
2863 *dest = val ? 0 : 1;
2864 else
2865 *dest = val;
2866 return 0;
2869 return 1;
2872 NORETURN
2873 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2875 if (!filename)
2876 die(_("unable to parse '%s' from command-line config"), key);
2877 else
2878 die(_("bad config variable '%s' in file '%s' at line %d"),
2879 key, filename, linenr);
2882 NORETURN __attribute__((format(printf, 2, 3)))
2883 void git_die_config(const char *key, const char *err, ...)
2885 const struct string_list *values;
2886 struct key_value_info *kv_info;
2887 report_fn error_fn = get_error_routine();
2889 if (err) {
2890 va_list params;
2891 va_start(params, err);
2892 error_fn(err, params);
2893 va_end(params);
2895 values = git_config_get_value_multi(key);
2896 kv_info = values->items[values->nr - 1].util;
2897 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
2901 * Find all the stuff for git_config_set() below.
2904 struct config_store_data {
2905 struct config_reader *config_reader;
2906 size_t baselen;
2907 char *key;
2908 int do_not_match;
2909 const char *fixed_value;
2910 regex_t *value_pattern;
2911 int multi_replace;
2912 struct {
2913 size_t begin, end;
2914 enum config_event_t type;
2915 int is_keys_section;
2916 } *parsed;
2917 unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
2918 unsigned int key_seen:1, section_seen:1, is_keys_section:1;
2920 #define CONFIG_STORE_INIT { 0 }
2922 static void config_store_data_clear(struct config_store_data *store)
2924 free(store->key);
2925 if (store->value_pattern != NULL &&
2926 store->value_pattern != CONFIG_REGEX_NONE) {
2927 regfree(store->value_pattern);
2928 free(store->value_pattern);
2930 free(store->parsed);
2931 free(store->seen);
2932 memset(store, 0, sizeof(*store));
2935 static int matches(const char *key, const char *value,
2936 const struct config_store_data *store)
2938 if (strcmp(key, store->key))
2939 return 0; /* not ours */
2940 if (store->fixed_value)
2941 return !strcmp(store->fixed_value, value);
2942 if (!store->value_pattern)
2943 return 1; /* always matches */
2944 if (store->value_pattern == CONFIG_REGEX_NONE)
2945 return 0; /* never matches */
2947 return store->do_not_match ^
2948 (value && !regexec(store->value_pattern, value, 0, NULL, 0));
2951 static int store_aux_event(enum config_event_t type,
2952 size_t begin, size_t end, void *data)
2954 struct config_store_data *store = data;
2955 struct config_source *cf = store->config_reader->source;
2957 ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
2958 store->parsed[store->parsed_nr].begin = begin;
2959 store->parsed[store->parsed_nr].end = end;
2960 store->parsed[store->parsed_nr].type = type;
2962 if (type == CONFIG_EVENT_SECTION) {
2963 int (*cmpfn)(const char *, const char *, size_t);
2965 if (cf->var.len < 2 || cf->var.buf[cf->var.len - 1] != '.')
2966 return error(_("invalid section name '%s'"), cf->var.buf);
2968 if (cf->subsection_case_sensitive)
2969 cmpfn = strncasecmp;
2970 else
2971 cmpfn = strncmp;
2973 /* Is this the section we were looking for? */
2974 store->is_keys_section =
2975 store->parsed[store->parsed_nr].is_keys_section =
2976 cf->var.len - 1 == store->baselen &&
2977 !cmpfn(cf->var.buf, store->key, store->baselen);
2978 if (store->is_keys_section) {
2979 store->section_seen = 1;
2980 ALLOC_GROW(store->seen, store->seen_nr + 1,
2981 store->seen_alloc);
2982 store->seen[store->seen_nr] = store->parsed_nr;
2986 store->parsed_nr++;
2988 return 0;
2991 static int store_aux(const char *key, const char *value, void *cb)
2993 struct config_store_data *store = cb;
2995 if (store->key_seen) {
2996 if (matches(key, value, store)) {
2997 if (store->seen_nr == 1 && store->multi_replace == 0) {
2998 warning(_("%s has multiple values"), key);
3001 ALLOC_GROW(store->seen, store->seen_nr + 1,
3002 store->seen_alloc);
3004 store->seen[store->seen_nr] = store->parsed_nr;
3005 store->seen_nr++;
3007 } else if (store->is_keys_section) {
3009 * Do not increment matches yet: this may not be a match, but we
3010 * are in the desired section.
3012 ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
3013 store->seen[store->seen_nr] = store->parsed_nr;
3014 store->section_seen = 1;
3016 if (matches(key, value, store)) {
3017 store->seen_nr++;
3018 store->key_seen = 1;
3022 return 0;
3025 static int write_error(const char *filename)
3027 error(_("failed to write new configuration file %s"), filename);
3029 /* Same error code as "failed to rename". */
3030 return 4;
3033 static struct strbuf store_create_section(const char *key,
3034 const struct config_store_data *store)
3036 const char *dot;
3037 size_t i;
3038 struct strbuf sb = STRBUF_INIT;
3040 dot = memchr(key, '.', store->baselen);
3041 if (dot) {
3042 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
3043 for (i = dot - key + 1; i < store->baselen; i++) {
3044 if (key[i] == '"' || key[i] == '\\')
3045 strbuf_addch(&sb, '\\');
3046 strbuf_addch(&sb, key[i]);
3048 strbuf_addstr(&sb, "\"]\n");
3049 } else {
3050 strbuf_addch(&sb, '[');
3051 strbuf_add(&sb, key, store->baselen);
3052 strbuf_addstr(&sb, "]\n");
3055 return sb;
3058 static ssize_t write_section(int fd, const char *key,
3059 const struct config_store_data *store)
3061 struct strbuf sb = store_create_section(key, store);
3062 ssize_t ret;
3064 ret = write_in_full(fd, sb.buf, sb.len);
3065 strbuf_release(&sb);
3067 return ret;
3070 static ssize_t write_pair(int fd, const char *key, const char *value,
3071 const struct config_store_data *store)
3073 int i;
3074 ssize_t ret;
3075 const char *quote = "";
3076 struct strbuf sb = STRBUF_INIT;
3079 * Check to see if the value needs to be surrounded with a dq pair.
3080 * Note that problematic characters are always backslash-quoted; this
3081 * check is about not losing leading or trailing SP and strings that
3082 * follow beginning-of-comment characters (i.e. ';' and '#') by the
3083 * configuration parser.
3085 if (value[0] == ' ')
3086 quote = "\"";
3087 for (i = 0; value[i]; i++)
3088 if (value[i] == ';' || value[i] == '#')
3089 quote = "\"";
3090 if (i && value[i - 1] == ' ')
3091 quote = "\"";
3093 strbuf_addf(&sb, "\t%s = %s", key + store->baselen + 1, quote);
3095 for (i = 0; value[i]; i++)
3096 switch (value[i]) {
3097 case '\n':
3098 strbuf_addstr(&sb, "\\n");
3099 break;
3100 case '\t':
3101 strbuf_addstr(&sb, "\\t");
3102 break;
3103 case '"':
3104 case '\\':
3105 strbuf_addch(&sb, '\\');
3106 /* fallthrough */
3107 default:
3108 strbuf_addch(&sb, value[i]);
3109 break;
3111 strbuf_addf(&sb, "%s\n", quote);
3113 ret = write_in_full(fd, sb.buf, sb.len);
3114 strbuf_release(&sb);
3116 return ret;
3120 * If we are about to unset the last key(s) in a section, and if there are
3121 * no comments surrounding (or included in) the section, we will want to
3122 * extend begin/end to remove the entire section.
3124 * Note: the parameter `seen_ptr` points to the index into the store.seen
3125 * array. * This index may be incremented if a section has more than one
3126 * entry (which all are to be removed).
3128 static void maybe_remove_section(struct config_store_data *store,
3129 size_t *begin_offset, size_t *end_offset,
3130 int *seen_ptr)
3132 size_t begin;
3133 int i, seen, section_seen = 0;
3136 * First, ensure that this is the first key, and that there are no
3137 * comments before the entry nor before the section header.
3139 seen = *seen_ptr;
3140 for (i = store->seen[seen]; i > 0; i--) {
3141 enum config_event_t type = store->parsed[i - 1].type;
3143 if (type == CONFIG_EVENT_COMMENT)
3144 /* There is a comment before this entry or section */
3145 return;
3146 if (type == CONFIG_EVENT_ENTRY) {
3147 if (!section_seen)
3148 /* This is not the section's first entry. */
3149 return;
3150 /* We encountered no comment before the section. */
3151 break;
3153 if (type == CONFIG_EVENT_SECTION) {
3154 if (!store->parsed[i - 1].is_keys_section)
3155 break;
3156 section_seen = 1;
3159 begin = store->parsed[i].begin;
3162 * Next, make sure that we are removing the last key(s) in the section,
3163 * and that there are no comments that are possibly about the current
3164 * section.
3166 for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
3167 enum config_event_t type = store->parsed[i].type;
3169 if (type == CONFIG_EVENT_COMMENT)
3170 return;
3171 if (type == CONFIG_EVENT_SECTION) {
3172 if (store->parsed[i].is_keys_section)
3173 continue;
3174 break;
3176 if (type == CONFIG_EVENT_ENTRY) {
3177 if (++seen < store->seen_nr &&
3178 i == store->seen[seen])
3179 /* We want to remove this entry, too */
3180 continue;
3181 /* There is another entry in this section. */
3182 return;
3187 * We are really removing the last entry/entries from this section, and
3188 * there are no enclosed or surrounding comments. Remove the entire,
3189 * now-empty section.
3191 *seen_ptr = seen;
3192 *begin_offset = begin;
3193 if (i < store->parsed_nr)
3194 *end_offset = store->parsed[i].begin;
3195 else
3196 *end_offset = store->parsed[store->parsed_nr - 1].end;
3199 int git_config_set_in_file_gently(const char *config_filename,
3200 const char *key, const char *value)
3202 return git_config_set_multivar_in_file_gently(config_filename, key, value, NULL, 0);
3205 void git_config_set_in_file(const char *config_filename,
3206 const char *key, const char *value)
3208 git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
3211 int git_config_set_gently(const char *key, const char *value)
3213 return git_config_set_multivar_gently(key, value, NULL, 0);
3216 int repo_config_set_worktree_gently(struct repository *r,
3217 const char *key, const char *value)
3219 /* Only use worktree-specific config if it is already enabled. */
3220 if (repository_format_worktree_config) {
3221 char *file = repo_git_path(r, "config.worktree");
3222 int ret = git_config_set_multivar_in_file_gently(
3223 file, key, value, NULL, 0);
3224 free(file);
3225 return ret;
3227 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
3230 void git_config_set(const char *key, const char *value)
3232 git_config_set_multivar(key, value, NULL, 0);
3234 trace2_cmd_set_config(key, value);
3238 * If value==NULL, unset in (remove from) config,
3239 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
3240 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
3241 * (only add a new one)
3242 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3243 * key/values are removed before a single new pair is written. If the
3244 * flag is not present, then replace only the first match.
3246 * Returns 0 on success.
3248 * This function does this:
3250 * - it locks the config file by creating ".git/config.lock"
3252 * - it then parses the config using store_aux() as validator to find
3253 * the position on the key/value pair to replace. If it is to be unset,
3254 * it must be found exactly once.
3256 * - the config file is mmap()ed and the part before the match (if any) is
3257 * written to the lock file, then the changed part and the rest.
3259 * - the config file is removed and the lock file rename()d to it.
3262 int git_config_set_multivar_in_file_gently(const char *config_filename,
3263 const char *key, const char *value,
3264 const char *value_pattern,
3265 unsigned flags)
3267 int fd = -1, in_fd = -1;
3268 int ret;
3269 struct lock_file lock = LOCK_INIT;
3270 char *filename_buf = NULL;
3271 char *contents = NULL;
3272 size_t contents_sz;
3273 struct config_store_data store = CONFIG_STORE_INIT;
3275 store.config_reader = &the_reader;
3277 /* parse-key returns negative; flip the sign to feed exit(3) */
3278 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
3279 if (ret)
3280 goto out_free;
3282 store.multi_replace = (flags & CONFIG_FLAGS_MULTI_REPLACE) != 0;
3284 if (!config_filename)
3285 config_filename = filename_buf = git_pathdup("config");
3288 * The lock serves a purpose in addition to locking: the new
3289 * contents of .git/config will be written into it.
3291 fd = hold_lock_file_for_update(&lock, config_filename, 0);
3292 if (fd < 0) {
3293 error_errno(_("could not lock config file %s"), config_filename);
3294 ret = CONFIG_NO_LOCK;
3295 goto out_free;
3299 * If .git/config does not exist yet, write a minimal version.
3301 in_fd = open(config_filename, O_RDONLY);
3302 if ( in_fd < 0 ) {
3303 if ( ENOENT != errno ) {
3304 error_errno(_("opening %s"), config_filename);
3305 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
3306 goto out_free;
3308 /* if nothing to unset, error out */
3309 if (!value) {
3310 ret = CONFIG_NOTHING_SET;
3311 goto out_free;
3314 free(store.key);
3315 store.key = xstrdup(key);
3316 if (write_section(fd, key, &store) < 0 ||
3317 write_pair(fd, key, value, &store) < 0)
3318 goto write_err_out;
3319 } else {
3320 struct stat st;
3321 size_t copy_begin, copy_end;
3322 int i, new_line = 0;
3323 struct config_options opts;
3325 if (!value_pattern)
3326 store.value_pattern = NULL;
3327 else if (value_pattern == CONFIG_REGEX_NONE)
3328 store.value_pattern = CONFIG_REGEX_NONE;
3329 else if (flags & CONFIG_FLAGS_FIXED_VALUE)
3330 store.fixed_value = value_pattern;
3331 else {
3332 if (value_pattern[0] == '!') {
3333 store.do_not_match = 1;
3334 value_pattern++;
3335 } else
3336 store.do_not_match = 0;
3338 store.value_pattern = (regex_t*)xmalloc(sizeof(regex_t));
3339 if (regcomp(store.value_pattern, value_pattern,
3340 REG_EXTENDED)) {
3341 error(_("invalid pattern: %s"), value_pattern);
3342 FREE_AND_NULL(store.value_pattern);
3343 ret = CONFIG_INVALID_PATTERN;
3344 goto out_free;
3348 ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
3349 store.parsed[0].end = 0;
3351 memset(&opts, 0, sizeof(opts));
3352 opts.event_fn = store_aux_event;
3353 opts.event_fn_data = &store;
3356 * After this, store.parsed will contain offsets of all the
3357 * parsed elements, and store.seen will contain a list of
3358 * matches, as indices into store.parsed.
3360 * As a side effect, we make sure to transform only a valid
3361 * existing config file.
3363 if (git_config_from_file_with_options(store_aux,
3364 config_filename,
3365 &store, &opts)) {
3366 error(_("invalid config file %s"), config_filename);
3367 ret = CONFIG_INVALID_FILE;
3368 goto out_free;
3371 /* if nothing to unset, or too many matches, error out */
3372 if ((store.seen_nr == 0 && value == NULL) ||
3373 (store.seen_nr > 1 && !store.multi_replace)) {
3374 ret = CONFIG_NOTHING_SET;
3375 goto out_free;
3378 if (fstat(in_fd, &st) == -1) {
3379 error_errno(_("fstat on %s failed"), config_filename);
3380 ret = CONFIG_INVALID_FILE;
3381 goto out_free;
3384 contents_sz = xsize_t(st.st_size);
3385 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
3386 MAP_PRIVATE, in_fd, 0);
3387 if (contents == MAP_FAILED) {
3388 if (errno == ENODEV && S_ISDIR(st.st_mode))
3389 errno = EISDIR;
3390 error_errno(_("unable to mmap '%s'%s"),
3391 config_filename, mmap_os_err());
3392 ret = CONFIG_INVALID_FILE;
3393 contents = NULL;
3394 goto out_free;
3396 close(in_fd);
3397 in_fd = -1;
3399 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3400 error_errno(_("chmod on %s failed"), get_lock_file_path(&lock));
3401 ret = CONFIG_NO_WRITE;
3402 goto out_free;
3405 if (store.seen_nr == 0) {
3406 if (!store.seen_alloc) {
3407 /* Did not see key nor section */
3408 ALLOC_GROW(store.seen, 1, store.seen_alloc);
3409 store.seen[0] = store.parsed_nr
3410 - !!store.parsed_nr;
3412 store.seen_nr = 1;
3415 for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
3416 size_t replace_end;
3417 int j = store.seen[i];
3419 new_line = 0;
3420 if (!store.key_seen) {
3421 copy_end = store.parsed[j].end;
3422 /* include '\n' when copying section header */
3423 if (copy_end > 0 && copy_end < contents_sz &&
3424 contents[copy_end - 1] != '\n' &&
3425 contents[copy_end] == '\n')
3426 copy_end++;
3427 replace_end = copy_end;
3428 } else {
3429 replace_end = store.parsed[j].end;
3430 copy_end = store.parsed[j].begin;
3431 if (!value)
3432 maybe_remove_section(&store,
3433 &copy_end,
3434 &replace_end, &i);
3436 * Swallow preceding white-space on the same
3437 * line.
3439 while (copy_end > 0 ) {
3440 char c = contents[copy_end - 1];
3442 if (isspace(c) && c != '\n')
3443 copy_end--;
3444 else
3445 break;
3449 if (copy_end > 0 && contents[copy_end-1] != '\n')
3450 new_line = 1;
3452 /* write the first part of the config */
3453 if (copy_end > copy_begin) {
3454 if (write_in_full(fd, contents + copy_begin,
3455 copy_end - copy_begin) < 0)
3456 goto write_err_out;
3457 if (new_line &&
3458 write_str_in_full(fd, "\n") < 0)
3459 goto write_err_out;
3461 copy_begin = replace_end;
3464 /* write the pair (value == NULL means unset) */
3465 if (value) {
3466 if (!store.section_seen) {
3467 if (write_section(fd, key, &store) < 0)
3468 goto write_err_out;
3470 if (write_pair(fd, key, value, &store) < 0)
3471 goto write_err_out;
3474 /* write the rest of the config */
3475 if (copy_begin < contents_sz)
3476 if (write_in_full(fd, contents + copy_begin,
3477 contents_sz - copy_begin) < 0)
3478 goto write_err_out;
3480 munmap(contents, contents_sz);
3481 contents = NULL;
3484 if (commit_lock_file(&lock) < 0) {
3485 error_errno(_("could not write config file %s"), config_filename);
3486 ret = CONFIG_NO_WRITE;
3487 goto out_free;
3490 ret = 0;
3492 /* Invalidate the config cache */
3493 git_config_clear();
3495 out_free:
3496 rollback_lock_file(&lock);
3497 free(filename_buf);
3498 if (contents)
3499 munmap(contents, contents_sz);
3500 if (in_fd >= 0)
3501 close(in_fd);
3502 config_store_data_clear(&store);
3503 return ret;
3505 write_err_out:
3506 ret = write_error(get_lock_file_path(&lock));
3507 goto out_free;
3511 void git_config_set_multivar_in_file(const char *config_filename,
3512 const char *key, const char *value,
3513 const char *value_pattern, unsigned flags)
3515 if (!git_config_set_multivar_in_file_gently(config_filename, key, value,
3516 value_pattern, flags))
3517 return;
3518 if (value)
3519 die(_("could not set '%s' to '%s'"), key, value);
3520 else
3521 die(_("could not unset '%s'"), key);
3524 int git_config_set_multivar_gently(const char *key, const char *value,
3525 const char *value_pattern, unsigned flags)
3527 return repo_config_set_multivar_gently(the_repository, key, value,
3528 value_pattern, flags);
3531 int repo_config_set_multivar_gently(struct repository *r, const char *key,
3532 const char *value,
3533 const char *value_pattern, unsigned flags)
3535 char *file = repo_git_path(r, "config");
3536 int res = git_config_set_multivar_in_file_gently(file,
3537 key, value,
3538 value_pattern,
3539 flags);
3540 free(file);
3541 return res;
3544 void git_config_set_multivar(const char *key, const char *value,
3545 const char *value_pattern, unsigned flags)
3547 git_config_set_multivar_in_file(git_path("config"),
3548 key, value, value_pattern,
3549 flags);
3552 static int section_name_match (const char *buf, const char *name)
3554 int i = 0, j = 0, dot = 0;
3555 if (buf[i] != '[')
3556 return 0;
3557 for (i = 1; buf[i] && buf[i] != ']'; i++) {
3558 if (!dot && isspace(buf[i])) {
3559 dot = 1;
3560 if (name[j++] != '.')
3561 break;
3562 for (i++; isspace(buf[i]); i++)
3563 ; /* do nothing */
3564 if (buf[i] != '"')
3565 break;
3566 continue;
3568 if (buf[i] == '\\' && dot)
3569 i++;
3570 else if (buf[i] == '"' && dot) {
3571 for (i++; isspace(buf[i]); i++)
3572 ; /* do_nothing */
3573 break;
3575 if (buf[i] != name[j++])
3576 break;
3578 if (buf[i] == ']' && name[j] == 0) {
3580 * We match, now just find the right length offset by
3581 * gobbling up any whitespace after it, as well
3583 i++;
3584 for (; buf[i] && isspace(buf[i]); i++)
3585 ; /* do nothing */
3586 return i;
3588 return 0;
3591 static int section_name_is_ok(const char *name)
3593 /* Empty section names are bogus. */
3594 if (!*name)
3595 return 0;
3598 * Before a dot, we must be alphanumeric or dash. After the first dot,
3599 * anything goes, so we can stop checking.
3601 for (; *name && *name != '.'; name++)
3602 if (*name != '-' && !isalnum(*name))
3603 return 0;
3604 return 1;
3607 /* if new_name == NULL, the section is removed instead */
3608 static int git_config_copy_or_rename_section_in_file(const char *config_filename,
3609 const char *old_name,
3610 const char *new_name, int copy)
3612 int ret = 0, remove = 0;
3613 char *filename_buf = NULL;
3614 struct lock_file lock = LOCK_INIT;
3615 int out_fd;
3616 char buf[1024];
3617 FILE *config_file = NULL;
3618 struct stat st;
3619 struct strbuf copystr = STRBUF_INIT;
3620 struct config_store_data store;
3622 memset(&store, 0, sizeof(store));
3624 if (new_name && !section_name_is_ok(new_name)) {
3625 ret = error(_("invalid section name: %s"), new_name);
3626 goto out_no_rollback;
3629 if (!config_filename)
3630 config_filename = filename_buf = git_pathdup("config");
3632 out_fd = hold_lock_file_for_update(&lock, config_filename, 0);
3633 if (out_fd < 0) {
3634 ret = error(_("could not lock config file %s"), config_filename);
3635 goto out;
3638 if (!(config_file = fopen(config_filename, "rb"))) {
3639 ret = warn_on_fopen_errors(config_filename);
3640 if (ret)
3641 goto out;
3642 /* no config file means nothing to rename, no error */
3643 goto commit_and_out;
3646 if (fstat(fileno(config_file), &st) == -1) {
3647 ret = error_errno(_("fstat on %s failed"), config_filename);
3648 goto out;
3651 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3652 ret = error_errno(_("chmod on %s failed"),
3653 get_lock_file_path(&lock));
3654 goto out;
3657 while (fgets(buf, sizeof(buf), config_file)) {
3658 unsigned i;
3659 int length;
3660 int is_section = 0;
3661 char *output = buf;
3662 for (i = 0; buf[i] && isspace(buf[i]); i++)
3663 ; /* do nothing */
3664 if (buf[i] == '[') {
3665 /* it's a section */
3666 int offset;
3667 is_section = 1;
3670 * When encountering a new section under -c we
3671 * need to flush out any section we're already
3672 * coping and begin anew. There might be
3673 * multiple [branch "$name"] sections.
3675 if (copystr.len > 0) {
3676 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3677 ret = write_error(get_lock_file_path(&lock));
3678 goto out;
3680 strbuf_reset(&copystr);
3683 offset = section_name_match(&buf[i], old_name);
3684 if (offset > 0) {
3685 ret++;
3686 if (!new_name) {
3687 remove = 1;
3688 continue;
3690 store.baselen = strlen(new_name);
3691 if (!copy) {
3692 if (write_section(out_fd, new_name, &store) < 0) {
3693 ret = write_error(get_lock_file_path(&lock));
3694 goto out;
3697 * We wrote out the new section, with
3698 * a newline, now skip the old
3699 * section's length
3701 output += offset + i;
3702 if (strlen(output) > 0) {
3704 * More content means there's
3705 * a declaration to put on the
3706 * next line; indent with a
3707 * tab
3709 output -= 1;
3710 output[0] = '\t';
3712 } else {
3713 copystr = store_create_section(new_name, &store);
3716 remove = 0;
3718 if (remove)
3719 continue;
3720 length = strlen(output);
3722 if (!is_section && copystr.len > 0) {
3723 strbuf_add(&copystr, output, length);
3726 if (write_in_full(out_fd, output, length) < 0) {
3727 ret = write_error(get_lock_file_path(&lock));
3728 goto out;
3733 * Copy a trailing section at the end of the config, won't be
3734 * flushed by the usual "flush because we have a new section
3735 * logic in the loop above.
3737 if (copystr.len > 0) {
3738 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3739 ret = write_error(get_lock_file_path(&lock));
3740 goto out;
3742 strbuf_reset(&copystr);
3745 fclose(config_file);
3746 config_file = NULL;
3747 commit_and_out:
3748 if (commit_lock_file(&lock) < 0)
3749 ret = error_errno(_("could not write config file %s"),
3750 config_filename);
3751 out:
3752 if (config_file)
3753 fclose(config_file);
3754 rollback_lock_file(&lock);
3755 out_no_rollback:
3756 free(filename_buf);
3757 config_store_data_clear(&store);
3758 return ret;
3761 int git_config_rename_section_in_file(const char *config_filename,
3762 const char *old_name, const char *new_name)
3764 return git_config_copy_or_rename_section_in_file(config_filename,
3765 old_name, new_name, 0);
3768 int git_config_rename_section(const char *old_name, const char *new_name)
3770 return git_config_rename_section_in_file(NULL, old_name, new_name);
3773 int git_config_copy_section_in_file(const char *config_filename,
3774 const char *old_name, const char *new_name)
3776 return git_config_copy_or_rename_section_in_file(config_filename,
3777 old_name, new_name, 1);
3780 int git_config_copy_section(const char *old_name, const char *new_name)
3782 return git_config_copy_section_in_file(NULL, old_name, new_name);
3786 * Call this to report error for your variable that should not
3787 * get a boolean value (i.e. "[my] var" means "true").
3789 #undef config_error_nonbool
3790 int config_error_nonbool(const char *var)
3792 return error(_("missing value for '%s'"), var);
3795 int parse_config_key(const char *var,
3796 const char *section,
3797 const char **subsection, size_t *subsection_len,
3798 const char **key)
3800 const char *dot;
3802 /* Does it start with "section." ? */
3803 if (!skip_prefix(var, section, &var) || *var != '.')
3804 return -1;
3807 * Find the key; we don't know yet if we have a subsection, but we must
3808 * parse backwards from the end, since the subsection may have dots in
3809 * it, too.
3811 dot = strrchr(var, '.');
3812 *key = dot + 1;
3814 /* Did we have a subsection at all? */
3815 if (dot == var) {
3816 if (subsection) {
3817 *subsection = NULL;
3818 *subsection_len = 0;
3821 else {
3822 if (!subsection)
3823 return -1;
3824 *subsection = var + 1;
3825 *subsection_len = dot - *subsection;
3828 return 0;
3831 const char *current_config_origin_type(void)
3833 int type;
3834 if (the_reader.config_kvi)
3835 type = the_reader.config_kvi->origin_type;
3836 else if(the_reader.source)
3837 type = the_reader.source->origin_type;
3838 else
3839 BUG("current_config_origin_type called outside config callback");
3841 switch (type) {
3842 case CONFIG_ORIGIN_BLOB:
3843 return "blob";
3844 case CONFIG_ORIGIN_FILE:
3845 return "file";
3846 case CONFIG_ORIGIN_STDIN:
3847 return "standard input";
3848 case CONFIG_ORIGIN_SUBMODULE_BLOB:
3849 return "submodule-blob";
3850 case CONFIG_ORIGIN_CMDLINE:
3851 return "command line";
3852 default:
3853 BUG("unknown config origin type");
3857 const char *config_scope_name(enum config_scope scope)
3859 switch (scope) {
3860 case CONFIG_SCOPE_SYSTEM:
3861 return "system";
3862 case CONFIG_SCOPE_GLOBAL:
3863 return "global";
3864 case CONFIG_SCOPE_LOCAL:
3865 return "local";
3866 case CONFIG_SCOPE_WORKTREE:
3867 return "worktree";
3868 case CONFIG_SCOPE_COMMAND:
3869 return "command";
3870 case CONFIG_SCOPE_SUBMODULE:
3871 return "submodule";
3872 default:
3873 return "unknown";
3877 const char *current_config_name(void)
3879 const char *name;
3880 if (the_reader.config_kvi)
3881 name = the_reader.config_kvi->filename;
3882 else if (the_reader.source)
3883 name = the_reader.source->name;
3884 else
3885 BUG("current_config_name called outside config callback");
3886 return name ? name : "";
3889 enum config_scope current_config_scope(void)
3891 if (the_reader.config_kvi)
3892 return the_reader.config_kvi->scope;
3893 else
3894 return current_parsing_scope;
3897 int current_config_line(void)
3899 if (the_reader.config_kvi)
3900 return the_reader.config_kvi->linenr;
3901 else
3902 return the_reader.source->linenr;
3905 int lookup_config(const char **mapping, int nr_mapping, const char *var)
3907 int i;
3909 for (i = 0; i < nr_mapping; i++) {
3910 const char *name = mapping[i];
3912 if (name && !strcasecmp(var, name))
3913 return i;
3915 return -1;