config: fix case sensitive subsection names on writing
[git.git] / config.c
blob27e800c7ce8b343923433e9d1f6f96ff12ad4065
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 "config.h"
10 #include "repository.h"
11 #include "lockfile.h"
12 #include "exec_cmd.h"
13 #include "strbuf.h"
14 #include "quote.h"
15 #include "hashmap.h"
16 #include "string-list.h"
17 #include "utf8.h"
18 #include "dir.h"
20 struct config_source {
21 struct config_source *prev;
22 union {
23 FILE *file;
24 struct config_buf {
25 const char *buf;
26 size_t len;
27 size_t pos;
28 } buf;
29 } u;
30 enum config_origin_type origin_type;
31 const char *name;
32 const char *path;
33 int die_on_error;
34 int linenr;
35 int eof;
36 struct strbuf value;
37 struct strbuf var;
38 unsigned subsection_case_sensitive : 1;
40 int (*do_fgetc)(struct config_source *c);
41 int (*do_ungetc)(int c, struct config_source *conf);
42 long (*do_ftell)(struct config_source *c);
46 * These variables record the "current" config source, which
47 * can be accessed by parsing callbacks.
49 * The "cf" variable will be non-NULL only when we are actually parsing a real
50 * config source (file, blob, cmdline, etc).
52 * The "current_config_kvi" variable will be non-NULL only when we are feeding
53 * cached config from a configset into a callback.
55 * They should generally never be non-NULL at the same time. If they are both
56 * NULL, then we aren't parsing anything (and depending on the function looking
57 * at the variables, it's either a bug for it to be called in the first place,
58 * or it's a function which can be reused for non-config purposes, and should
59 * fall back to some sane behavior).
61 static struct config_source *cf;
62 static struct key_value_info *current_config_kvi;
65 * Similar to the variables above, this gives access to the "scope" of the
66 * current value (repo, global, etc). For cached values, it can be found via
67 * the current_config_kvi as above. During parsing, the current value can be
68 * found in this variable. It's not part of "cf" because it transcends a single
69 * file (i.e., a file included from .git/config is still in "repo" scope).
71 static enum config_scope current_parsing_scope;
73 static int core_compression_seen;
74 static int pack_compression_seen;
75 static int zlib_compression_seen;
77 static int config_file_fgetc(struct config_source *conf)
79 return getc_unlocked(conf->u.file);
82 static int config_file_ungetc(int c, struct config_source *conf)
84 return ungetc(c, conf->u.file);
87 static long config_file_ftell(struct config_source *conf)
89 return ftell(conf->u.file);
93 static int config_buf_fgetc(struct config_source *conf)
95 if (conf->u.buf.pos < conf->u.buf.len)
96 return conf->u.buf.buf[conf->u.buf.pos++];
98 return EOF;
101 static int config_buf_ungetc(int c, struct config_source *conf)
103 if (conf->u.buf.pos > 0) {
104 conf->u.buf.pos--;
105 if (conf->u.buf.buf[conf->u.buf.pos] != c)
106 die("BUG: config_buf can only ungetc the same character");
107 return c;
110 return EOF;
113 static long config_buf_ftell(struct config_source *conf)
115 return conf->u.buf.pos;
118 #define MAX_INCLUDE_DEPTH 10
119 static const char include_depth_advice[] =
120 "exceeded maximum include depth (%d) while including\n"
121 " %s\n"
122 "from\n"
123 " %s\n"
124 "Do you have circular includes?";
125 static int handle_path_include(const char *path, struct config_include_data *inc)
127 int ret = 0;
128 struct strbuf buf = STRBUF_INIT;
129 char *expanded;
131 if (!path)
132 return config_error_nonbool("include.path");
134 expanded = expand_user_path(path, 0);
135 if (!expanded)
136 return error("could not expand include path '%s'", path);
137 path = expanded;
140 * Use an absolute path as-is, but interpret relative paths
141 * based on the including config file.
143 if (!is_absolute_path(path)) {
144 char *slash;
146 if (!cf || !cf->path)
147 return error("relative config includes must come from files");
149 slash = find_last_dir_sep(cf->path);
150 if (slash)
151 strbuf_add(&buf, cf->path, slash - cf->path + 1);
152 strbuf_addstr(&buf, path);
153 path = buf.buf;
156 if (!access_or_die(path, R_OK, 0)) {
157 if (++inc->depth > MAX_INCLUDE_DEPTH)
158 die(include_depth_advice, MAX_INCLUDE_DEPTH, path,
159 !cf ? "<unknown>" :
160 cf->name ? cf->name :
161 "the command line");
162 ret = git_config_from_file(git_config_include, path, inc);
163 inc->depth--;
165 strbuf_release(&buf);
166 free(expanded);
167 return ret;
170 static int prepare_include_condition_pattern(struct strbuf *pat)
172 struct strbuf path = STRBUF_INIT;
173 char *expanded;
174 int prefix = 0;
176 expanded = expand_user_path(pat->buf, 1);
177 if (expanded) {
178 strbuf_reset(pat);
179 strbuf_addstr(pat, expanded);
180 free(expanded);
183 if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
184 const char *slash;
186 if (!cf || !cf->path)
187 return error(_("relative config include "
188 "conditionals must come from files"));
190 strbuf_realpath(&path, cf->path, 1);
191 slash = find_last_dir_sep(path.buf);
192 if (!slash)
193 die("BUG: how is this possible?");
194 strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
195 prefix = slash - path.buf + 1 /* slash */;
196 } else if (!is_absolute_path(pat->buf))
197 strbuf_insert(pat, 0, "**/", 3);
199 if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
200 strbuf_addstr(pat, "**");
202 strbuf_release(&path);
203 return prefix;
206 static int include_by_gitdir(const struct config_options *opts,
207 const char *cond, size_t cond_len, int icase)
209 struct strbuf text = STRBUF_INIT;
210 struct strbuf pattern = STRBUF_INIT;
211 int ret = 0, prefix;
212 const char *git_dir;
213 int already_tried_absolute = 0;
215 if (opts->git_dir)
216 git_dir = opts->git_dir;
217 else
218 goto done;
220 strbuf_realpath(&text, git_dir, 1);
221 strbuf_add(&pattern, cond, cond_len);
222 prefix = prepare_include_condition_pattern(&pattern);
224 again:
225 if (prefix < 0)
226 goto done;
228 if (prefix > 0) {
230 * perform literal matching on the prefix part so that
231 * any wildcard character in it can't create side effects.
233 if (text.len < prefix)
234 goto done;
235 if (!icase && strncmp(pattern.buf, text.buf, prefix))
236 goto done;
237 if (icase && strncasecmp(pattern.buf, text.buf, prefix))
238 goto done;
241 ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
242 icase ? WM_CASEFOLD : 0);
244 if (!ret && !already_tried_absolute) {
246 * We've tried e.g. matching gitdir:~/work, but if
247 * ~/work is a symlink to /mnt/storage/work
248 * strbuf_realpath() will expand it, so the rule won't
249 * match. Let's match against a
250 * strbuf_add_absolute_path() version of the path,
251 * which'll do the right thing
253 strbuf_reset(&text);
254 strbuf_add_absolute_path(&text, git_dir);
255 already_tried_absolute = 1;
256 goto again;
258 done:
259 strbuf_release(&pattern);
260 strbuf_release(&text);
261 return ret;
264 static int include_condition_is_true(const struct config_options *opts,
265 const char *cond, size_t cond_len)
268 if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
269 return include_by_gitdir(opts, cond, cond_len, 0);
270 else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
271 return include_by_gitdir(opts, cond, cond_len, 1);
273 /* unknown conditionals are always false */
274 return 0;
277 int git_config_include(const char *var, const char *value, void *data)
279 struct config_include_data *inc = data;
280 const char *cond, *key;
281 int cond_len;
282 int ret;
285 * Pass along all values, including "include" directives; this makes it
286 * possible to query information on the includes themselves.
288 ret = inc->fn(var, value, inc->data);
289 if (ret < 0)
290 return ret;
292 if (!strcmp(var, "include.path"))
293 ret = handle_path_include(value, inc);
295 if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
296 (cond && include_condition_is_true(inc->opts, cond, cond_len)) &&
297 !strcmp(key, "path"))
298 ret = handle_path_include(value, inc);
300 return ret;
303 void git_config_push_parameter(const char *text)
305 struct strbuf env = STRBUF_INIT;
306 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
307 if (old && *old) {
308 strbuf_addstr(&env, old);
309 strbuf_addch(&env, ' ');
311 sq_quote_buf(&env, text);
312 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
313 strbuf_release(&env);
316 static inline int iskeychar(int c)
318 return isalnum(c) || c == '-';
322 * Auxiliary function to sanity-check and split the key into the section
323 * identifier and variable name.
325 * Returns 0 on success, -1 when there is an invalid character in the key and
326 * -2 if there is no section name in the key.
328 * store_key - pointer to char* which will hold a copy of the key with
329 * lowercase section and variable name
330 * baselen - pointer to int which will hold the length of the
331 * section + subsection part, can be NULL
333 static int git_config_parse_key_1(const char *key, char **store_key, int *baselen_, int quiet)
335 int i, dot, baselen;
336 const char *last_dot = strrchr(key, '.');
339 * Since "key" actually contains the section name and the real
340 * key name separated by a dot, we have to know where the dot is.
343 if (last_dot == NULL || last_dot == key) {
344 if (!quiet)
345 error("key does not contain a section: %s", key);
346 return -CONFIG_NO_SECTION_OR_NAME;
349 if (!last_dot[1]) {
350 if (!quiet)
351 error("key does not contain variable name: %s", key);
352 return -CONFIG_NO_SECTION_OR_NAME;
355 baselen = last_dot - key;
356 if (baselen_)
357 *baselen_ = baselen;
360 * Validate the key and while at it, lower case it for matching.
362 if (store_key)
363 *store_key = xmallocz(strlen(key));
365 dot = 0;
366 for (i = 0; key[i]; i++) {
367 unsigned char c = key[i];
368 if (c == '.')
369 dot = 1;
370 /* Leave the extended basename untouched.. */
371 if (!dot || i > baselen) {
372 if (!iskeychar(c) ||
373 (i == baselen + 1 && !isalpha(c))) {
374 if (!quiet)
375 error("invalid key: %s", key);
376 goto out_free_ret_1;
378 c = tolower(c);
379 } else if (c == '\n') {
380 if (!quiet)
381 error("invalid key (newline): %s", key);
382 goto out_free_ret_1;
384 if (store_key)
385 (*store_key)[i] = c;
388 return 0;
390 out_free_ret_1:
391 if (store_key) {
392 FREE_AND_NULL(*store_key);
394 return -CONFIG_INVALID_KEY;
397 int git_config_parse_key(const char *key, char **store_key, int *baselen)
399 return git_config_parse_key_1(key, store_key, baselen, 0);
402 int git_config_key_is_valid(const char *key)
404 return !git_config_parse_key_1(key, NULL, NULL, 1);
407 int git_config_parse_parameter(const char *text,
408 config_fn_t fn, void *data)
410 const char *value;
411 char *canonical_name;
412 struct strbuf **pair;
413 int ret;
415 pair = strbuf_split_str(text, '=', 2);
416 if (!pair[0])
417 return error("bogus config parameter: %s", text);
419 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
420 strbuf_setlen(pair[0], pair[0]->len - 1);
421 value = pair[1] ? pair[1]->buf : "";
422 } else {
423 value = NULL;
426 strbuf_trim(pair[0]);
427 if (!pair[0]->len) {
428 strbuf_list_free(pair);
429 return error("bogus config parameter: %s", text);
432 if (git_config_parse_key(pair[0]->buf, &canonical_name, NULL)) {
433 ret = -1;
434 } else {
435 ret = (fn(canonical_name, value, data) < 0) ? -1 : 0;
436 free(canonical_name);
438 strbuf_list_free(pair);
439 return ret;
442 int git_config_from_parameters(config_fn_t fn, void *data)
444 const char *env = getenv(CONFIG_DATA_ENVIRONMENT);
445 int ret = 0;
446 char *envw;
447 const char **argv = NULL;
448 int nr = 0, alloc = 0;
449 int i;
450 struct config_source source;
452 if (!env)
453 return 0;
455 memset(&source, 0, sizeof(source));
456 source.prev = cf;
457 source.origin_type = CONFIG_ORIGIN_CMDLINE;
458 cf = &source;
460 /* sq_dequote will write over it */
461 envw = xstrdup(env);
463 if (sq_dequote_to_argv(envw, &argv, &nr, &alloc) < 0) {
464 ret = error("bogus format in " CONFIG_DATA_ENVIRONMENT);
465 goto out;
468 for (i = 0; i < nr; i++) {
469 if (git_config_parse_parameter(argv[i], fn, data) < 0) {
470 ret = -1;
471 goto out;
475 out:
476 free(argv);
477 free(envw);
478 cf = source.prev;
479 return ret;
482 static int get_next_char(void)
484 int c = cf->do_fgetc(cf);
486 if (c == '\r') {
487 /* DOS like systems */
488 c = cf->do_fgetc(cf);
489 if (c != '\n') {
490 if (c != EOF)
491 cf->do_ungetc(c, cf);
492 c = '\r';
495 if (c == '\n')
496 cf->linenr++;
497 if (c == EOF) {
498 cf->eof = 1;
499 cf->linenr++;
500 c = '\n';
502 return c;
505 static char *parse_value(void)
507 int quote = 0, comment = 0, space = 0;
509 strbuf_reset(&cf->value);
510 for (;;) {
511 int c = get_next_char();
512 if (c == '\n') {
513 if (quote) {
514 cf->linenr--;
515 return NULL;
517 return cf->value.buf;
519 if (comment)
520 continue;
521 if (isspace(c) && !quote) {
522 if (cf->value.len)
523 space++;
524 continue;
526 if (!quote) {
527 if (c == ';' || c == '#') {
528 comment = 1;
529 continue;
532 for (; space; space--)
533 strbuf_addch(&cf->value, ' ');
534 if (c == '\\') {
535 c = get_next_char();
536 switch (c) {
537 case '\n':
538 continue;
539 case 't':
540 c = '\t';
541 break;
542 case 'b':
543 c = '\b';
544 break;
545 case 'n':
546 c = '\n';
547 break;
548 /* Some characters escape as themselves */
549 case '\\': case '"':
550 break;
551 /* Reject unknown escape sequences */
552 default:
553 return NULL;
555 strbuf_addch(&cf->value, c);
556 continue;
558 if (c == '"') {
559 quote = 1-quote;
560 continue;
562 strbuf_addch(&cf->value, c);
566 static int get_value(config_fn_t fn, void *data, struct strbuf *name)
568 int c;
569 char *value;
570 int ret;
572 /* Get the full name */
573 for (;;) {
574 c = get_next_char();
575 if (cf->eof)
576 break;
577 if (!iskeychar(c))
578 break;
579 strbuf_addch(name, tolower(c));
582 while (c == ' ' || c == '\t')
583 c = get_next_char();
585 value = NULL;
586 if (c != '\n') {
587 if (c != '=')
588 return -1;
589 value = parse_value();
590 if (!value)
591 return -1;
594 * We already consumed the \n, but we need linenr to point to
595 * the line we just parsed during the call to fn to get
596 * accurate line number in error messages.
598 cf->linenr--;
599 ret = fn(name->buf, value, data);
600 if (ret >= 0)
601 cf->linenr++;
602 return ret;
605 static int get_extended_base_var(struct strbuf *name, int c)
607 cf->subsection_case_sensitive = 0;
608 do {
609 if (c == '\n')
610 goto error_incomplete_line;
611 c = get_next_char();
612 } while (isspace(c));
614 /* We require the format to be '[base "extension"]' */
615 if (c != '"')
616 return -1;
617 strbuf_addch(name, '.');
619 for (;;) {
620 int c = get_next_char();
621 if (c == '\n')
622 goto error_incomplete_line;
623 if (c == '"')
624 break;
625 if (c == '\\') {
626 c = get_next_char();
627 if (c == '\n')
628 goto error_incomplete_line;
630 strbuf_addch(name, c);
633 /* Final ']' */
634 if (get_next_char() != ']')
635 return -1;
636 return 0;
637 error_incomplete_line:
638 cf->linenr--;
639 return -1;
642 static int get_base_var(struct strbuf *name)
644 cf->subsection_case_sensitive = 1;
645 for (;;) {
646 int c = get_next_char();
647 if (cf->eof)
648 return -1;
649 if (c == ']')
650 return 0;
651 if (isspace(c))
652 return get_extended_base_var(name, c);
653 if (!iskeychar(c) && c != '.')
654 return -1;
655 strbuf_addch(name, tolower(c));
659 struct parse_event_data {
660 enum config_event_t previous_type;
661 size_t previous_offset;
662 const struct config_options *opts;
665 static int do_event(enum config_event_t type, struct parse_event_data *data)
667 size_t offset;
669 if (!data->opts || !data->opts->event_fn)
670 return 0;
672 if (type == CONFIG_EVENT_WHITESPACE &&
673 data->previous_type == type)
674 return 0;
676 offset = cf->do_ftell(cf);
678 * At EOF, the parser always "inserts" an extra '\n', therefore
679 * the end offset of the event is the current file position, otherwise
680 * we will already have advanced to the next event.
682 if (type != CONFIG_EVENT_EOF)
683 offset--;
685 if (data->previous_type != CONFIG_EVENT_EOF &&
686 data->opts->event_fn(data->previous_type, data->previous_offset,
687 offset, data->opts->event_fn_data) < 0)
688 return -1;
690 data->previous_type = type;
691 data->previous_offset = offset;
693 return 0;
696 static int git_parse_source(config_fn_t fn, void *data,
697 const struct config_options *opts)
699 int comment = 0;
700 int baselen = 0;
701 struct strbuf *var = &cf->var;
702 int error_return = 0;
703 char *error_msg = NULL;
705 /* U+FEFF Byte Order Mark in UTF8 */
706 const char *bomptr = utf8_bom;
708 /* For the parser event callback */
709 struct parse_event_data event_data = {
710 CONFIG_EVENT_EOF, 0, opts
713 for (;;) {
714 int c;
716 c = get_next_char();
717 if (bomptr && *bomptr) {
718 /* We are at the file beginning; skip UTF8-encoded BOM
719 * if present. Sane editors won't put this in on their
720 * own, but e.g. Windows Notepad will do it happily. */
721 if (c == (*bomptr & 0377)) {
722 bomptr++;
723 continue;
724 } else {
725 /* Do not tolerate partial BOM. */
726 if (bomptr != utf8_bom)
727 break;
728 /* No BOM at file beginning. Cool. */
729 bomptr = NULL;
732 if (c == '\n') {
733 if (cf->eof) {
734 if (do_event(CONFIG_EVENT_EOF, &event_data) < 0)
735 return -1;
736 return 0;
738 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
739 return -1;
740 comment = 0;
741 continue;
743 if (comment)
744 continue;
745 if (isspace(c)) {
746 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
747 return -1;
748 continue;
750 if (c == '#' || c == ';') {
751 if (do_event(CONFIG_EVENT_COMMENT, &event_data) < 0)
752 return -1;
753 comment = 1;
754 continue;
756 if (c == '[') {
757 if (do_event(CONFIG_EVENT_SECTION, &event_data) < 0)
758 return -1;
760 /* Reset prior to determining a new stem */
761 strbuf_reset(var);
762 if (get_base_var(var) < 0 || var->len < 1)
763 break;
764 strbuf_addch(var, '.');
765 baselen = var->len;
766 continue;
768 if (!isalpha(c))
769 break;
771 if (do_event(CONFIG_EVENT_ENTRY, &event_data) < 0)
772 return -1;
775 * Truncate the var name back to the section header
776 * stem prior to grabbing the suffix part of the name
777 * and the value.
779 strbuf_setlen(var, baselen);
780 strbuf_addch(var, tolower(c));
781 if (get_value(fn, data, var) < 0)
782 break;
785 if (do_event(CONFIG_EVENT_ERROR, &event_data) < 0)
786 return -1;
788 switch (cf->origin_type) {
789 case CONFIG_ORIGIN_BLOB:
790 error_msg = xstrfmt(_("bad config line %d in blob %s"),
791 cf->linenr, cf->name);
792 break;
793 case CONFIG_ORIGIN_FILE:
794 error_msg = xstrfmt(_("bad config line %d in file %s"),
795 cf->linenr, cf->name);
796 break;
797 case CONFIG_ORIGIN_STDIN:
798 error_msg = xstrfmt(_("bad config line %d in standard input"),
799 cf->linenr);
800 break;
801 case CONFIG_ORIGIN_SUBMODULE_BLOB:
802 error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
803 cf->linenr, cf->name);
804 break;
805 case CONFIG_ORIGIN_CMDLINE:
806 error_msg = xstrfmt(_("bad config line %d in command line %s"),
807 cf->linenr, cf->name);
808 break;
809 default:
810 error_msg = xstrfmt(_("bad config line %d in %s"),
811 cf->linenr, cf->name);
814 if (cf->die_on_error)
815 die("%s", error_msg);
816 else
817 error_return = error("%s", error_msg);
819 free(error_msg);
820 return error_return;
823 static int parse_unit_factor(const char *end, uintmax_t *val)
825 if (!*end)
826 return 1;
827 else if (!strcasecmp(end, "k")) {
828 *val *= 1024;
829 return 1;
831 else if (!strcasecmp(end, "m")) {
832 *val *= 1024 * 1024;
833 return 1;
835 else if (!strcasecmp(end, "g")) {
836 *val *= 1024 * 1024 * 1024;
837 return 1;
839 return 0;
842 static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
844 if (value && *value) {
845 char *end;
846 intmax_t val;
847 uintmax_t uval;
848 uintmax_t factor = 1;
850 errno = 0;
851 val = strtoimax(value, &end, 0);
852 if (errno == ERANGE)
853 return 0;
854 if (!parse_unit_factor(end, &factor)) {
855 errno = EINVAL;
856 return 0;
858 uval = labs(val);
859 uval *= factor;
860 if (uval > max || labs(val) > uval) {
861 errno = ERANGE;
862 return 0;
864 val *= factor;
865 *ret = val;
866 return 1;
868 errno = EINVAL;
869 return 0;
872 static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
874 if (value && *value) {
875 char *end;
876 uintmax_t val;
877 uintmax_t oldval;
879 errno = 0;
880 val = strtoumax(value, &end, 0);
881 if (errno == ERANGE)
882 return 0;
883 oldval = val;
884 if (!parse_unit_factor(end, &val)) {
885 errno = EINVAL;
886 return 0;
888 if (val > max || oldval > val) {
889 errno = ERANGE;
890 return 0;
892 *ret = val;
893 return 1;
895 errno = EINVAL;
896 return 0;
899 static int git_parse_int(const char *value, int *ret)
901 intmax_t tmp;
902 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
903 return 0;
904 *ret = tmp;
905 return 1;
908 static int git_parse_int64(const char *value, int64_t *ret)
910 intmax_t tmp;
911 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
912 return 0;
913 *ret = tmp;
914 return 1;
917 int git_parse_ulong(const char *value, unsigned long *ret)
919 uintmax_t tmp;
920 if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
921 return 0;
922 *ret = tmp;
923 return 1;
926 static int git_parse_ssize_t(const char *value, ssize_t *ret)
928 intmax_t tmp;
929 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(ssize_t)))
930 return 0;
931 *ret = tmp;
932 return 1;
935 NORETURN
936 static void die_bad_number(const char *name, const char *value)
938 const char * error_type = (errno == ERANGE)? _("out of range"):_("invalid unit");
940 if (!value)
941 value = "";
943 if (!(cf && cf->name))
944 die(_("bad numeric config value '%s' for '%s': %s"),
945 value, name, error_type);
947 switch (cf->origin_type) {
948 case CONFIG_ORIGIN_BLOB:
949 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
950 value, name, cf->name, error_type);
951 case CONFIG_ORIGIN_FILE:
952 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
953 value, name, cf->name, error_type);
954 case CONFIG_ORIGIN_STDIN:
955 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
956 value, name, error_type);
957 case CONFIG_ORIGIN_SUBMODULE_BLOB:
958 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
959 value, name, cf->name, error_type);
960 case CONFIG_ORIGIN_CMDLINE:
961 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
962 value, name, cf->name, error_type);
963 default:
964 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
965 value, name, cf->name, error_type);
969 int git_config_int(const char *name, const char *value)
971 int ret;
972 if (!git_parse_int(value, &ret))
973 die_bad_number(name, value);
974 return ret;
977 int64_t git_config_int64(const char *name, const char *value)
979 int64_t ret;
980 if (!git_parse_int64(value, &ret))
981 die_bad_number(name, value);
982 return ret;
985 unsigned long git_config_ulong(const char *name, const char *value)
987 unsigned long ret;
988 if (!git_parse_ulong(value, &ret))
989 die_bad_number(name, value);
990 return ret;
993 ssize_t git_config_ssize_t(const char *name, const char *value)
995 ssize_t ret;
996 if (!git_parse_ssize_t(value, &ret))
997 die_bad_number(name, value);
998 return ret;
1001 static int git_parse_maybe_bool_text(const char *value)
1003 if (!value)
1004 return 1;
1005 if (!*value)
1006 return 0;
1007 if (!strcasecmp(value, "true")
1008 || !strcasecmp(value, "yes")
1009 || !strcasecmp(value, "on"))
1010 return 1;
1011 if (!strcasecmp(value, "false")
1012 || !strcasecmp(value, "no")
1013 || !strcasecmp(value, "off"))
1014 return 0;
1015 return -1;
1018 int git_parse_maybe_bool(const char *value)
1020 int v = git_parse_maybe_bool_text(value);
1021 if (0 <= v)
1022 return v;
1023 if (git_parse_int(value, &v))
1024 return !!v;
1025 return -1;
1028 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
1030 int v = git_parse_maybe_bool_text(value);
1031 if (0 <= v) {
1032 *is_bool = 1;
1033 return v;
1035 *is_bool = 0;
1036 return git_config_int(name, value);
1039 int git_config_bool(const char *name, const char *value)
1041 int discard;
1042 return !!git_config_bool_or_int(name, value, &discard);
1045 int git_config_string(const char **dest, const char *var, const char *value)
1047 if (!value)
1048 return config_error_nonbool(var);
1049 *dest = xstrdup(value);
1050 return 0;
1053 int git_config_pathname(const char **dest, const char *var, const char *value)
1055 if (!value)
1056 return config_error_nonbool(var);
1057 *dest = expand_user_path(value, 0);
1058 if (!*dest)
1059 die(_("failed to expand user dir in: '%s'"), value);
1060 return 0;
1063 int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1065 if (!value)
1066 return config_error_nonbool(var);
1067 if (parse_expiry_date(value, timestamp))
1068 return error(_("'%s' for '%s' is not a valid timestamp"),
1069 value, var);
1070 return 0;
1073 static int git_default_core_config(const char *var, const char *value)
1075 /* This needs a better name */
1076 if (!strcmp(var, "core.filemode")) {
1077 trust_executable_bit = git_config_bool(var, value);
1078 return 0;
1080 if (!strcmp(var, "core.trustctime")) {
1081 trust_ctime = git_config_bool(var, value);
1082 return 0;
1084 if (!strcmp(var, "core.checkstat")) {
1085 if (!strcasecmp(value, "default"))
1086 check_stat = 1;
1087 else if (!strcasecmp(value, "minimal"))
1088 check_stat = 0;
1091 if (!strcmp(var, "core.quotepath")) {
1092 quote_path_fully = git_config_bool(var, value);
1093 return 0;
1096 if (!strcmp(var, "core.symlinks")) {
1097 has_symlinks = git_config_bool(var, value);
1098 return 0;
1101 if (!strcmp(var, "core.ignorecase")) {
1102 ignore_case = git_config_bool(var, value);
1103 return 0;
1106 if (!strcmp(var, "core.attributesfile"))
1107 return git_config_pathname(&git_attributes_file, var, value);
1109 if (!strcmp(var, "core.hookspath"))
1110 return git_config_pathname(&git_hooks_path, var, value);
1112 if (!strcmp(var, "core.bare")) {
1113 is_bare_repository_cfg = git_config_bool(var, value);
1114 return 0;
1117 if (!strcmp(var, "core.ignorestat")) {
1118 assume_unchanged = git_config_bool(var, value);
1119 return 0;
1122 if (!strcmp(var, "core.prefersymlinkrefs")) {
1123 prefer_symlink_refs = git_config_bool(var, value);
1124 return 0;
1127 if (!strcmp(var, "core.logallrefupdates")) {
1128 if (value && !strcasecmp(value, "always"))
1129 log_all_ref_updates = LOG_REFS_ALWAYS;
1130 else if (git_config_bool(var, value))
1131 log_all_ref_updates = LOG_REFS_NORMAL;
1132 else
1133 log_all_ref_updates = LOG_REFS_NONE;
1134 return 0;
1137 if (!strcmp(var, "core.warnambiguousrefs")) {
1138 warn_ambiguous_refs = git_config_bool(var, value);
1139 return 0;
1142 if (!strcmp(var, "core.abbrev")) {
1143 if (!value)
1144 return config_error_nonbool(var);
1145 if (!strcasecmp(value, "auto"))
1146 default_abbrev = -1;
1147 else {
1148 int abbrev = git_config_int(var, value);
1149 if (abbrev < minimum_abbrev || abbrev > 40)
1150 return error("abbrev length out of range: %d", abbrev);
1151 default_abbrev = abbrev;
1153 return 0;
1156 if (!strcmp(var, "core.disambiguate"))
1157 return set_disambiguate_hint_config(var, value);
1159 if (!strcmp(var, "core.loosecompression")) {
1160 int level = git_config_int(var, value);
1161 if (level == -1)
1162 level = Z_DEFAULT_COMPRESSION;
1163 else if (level < 0 || level > Z_BEST_COMPRESSION)
1164 die(_("bad zlib compression level %d"), level);
1165 zlib_compression_level = level;
1166 zlib_compression_seen = 1;
1167 return 0;
1170 if (!strcmp(var, "core.compression")) {
1171 int level = git_config_int(var, value);
1172 if (level == -1)
1173 level = Z_DEFAULT_COMPRESSION;
1174 else if (level < 0 || level > Z_BEST_COMPRESSION)
1175 die(_("bad zlib compression level %d"), level);
1176 core_compression_level = level;
1177 core_compression_seen = 1;
1178 if (!zlib_compression_seen)
1179 zlib_compression_level = level;
1180 if (!pack_compression_seen)
1181 pack_compression_level = level;
1182 return 0;
1185 if (!strcmp(var, "core.packedgitwindowsize")) {
1186 int pgsz_x2 = getpagesize() * 2;
1187 packed_git_window_size = git_config_ulong(var, value);
1189 /* This value must be multiple of (pagesize * 2) */
1190 packed_git_window_size /= pgsz_x2;
1191 if (packed_git_window_size < 1)
1192 packed_git_window_size = 1;
1193 packed_git_window_size *= pgsz_x2;
1194 return 0;
1197 if (!strcmp(var, "core.bigfilethreshold")) {
1198 big_file_threshold = git_config_ulong(var, value);
1199 return 0;
1202 if (!strcmp(var, "core.packedgitlimit")) {
1203 packed_git_limit = git_config_ulong(var, value);
1204 return 0;
1207 if (!strcmp(var, "core.deltabasecachelimit")) {
1208 delta_base_cache_limit = git_config_ulong(var, value);
1209 return 0;
1212 if (!strcmp(var, "core.autocrlf")) {
1213 if (value && !strcasecmp(value, "input")) {
1214 auto_crlf = AUTO_CRLF_INPUT;
1215 return 0;
1217 auto_crlf = git_config_bool(var, value);
1218 return 0;
1221 if (!strcmp(var, "core.safecrlf")) {
1222 if (value && !strcasecmp(value, "warn")) {
1223 safe_crlf = SAFE_CRLF_WARN;
1224 return 0;
1226 safe_crlf = git_config_bool(var, value);
1227 return 0;
1230 if (!strcmp(var, "core.eol")) {
1231 if (value && !strcasecmp(value, "lf"))
1232 core_eol = EOL_LF;
1233 else if (value && !strcasecmp(value, "crlf"))
1234 core_eol = EOL_CRLF;
1235 else if (value && !strcasecmp(value, "native"))
1236 core_eol = EOL_NATIVE;
1237 else
1238 core_eol = EOL_UNSET;
1239 return 0;
1242 if (!strcmp(var, "core.notesref")) {
1243 notes_ref_name = xstrdup(value);
1244 return 0;
1247 if (!strcmp(var, "core.editor"))
1248 return git_config_string(&editor_program, var, value);
1250 if (!strcmp(var, "core.commentchar")) {
1251 if (!value)
1252 return config_error_nonbool(var);
1253 else if (!strcasecmp(value, "auto"))
1254 auto_comment_line_char = 1;
1255 else if (value[0] && !value[1]) {
1256 comment_line_char = value[0];
1257 auto_comment_line_char = 0;
1258 } else
1259 return error("core.commentChar should only be one character");
1260 return 0;
1263 if (!strcmp(var, "core.askpass"))
1264 return git_config_string(&askpass_program, var, value);
1266 if (!strcmp(var, "core.excludesfile"))
1267 return git_config_pathname(&excludes_file, var, value);
1269 if (!strcmp(var, "core.whitespace")) {
1270 if (!value)
1271 return config_error_nonbool(var);
1272 whitespace_rule_cfg = parse_whitespace_rule(value);
1273 return 0;
1276 if (!strcmp(var, "core.fsyncobjectfiles")) {
1277 fsync_object_files = git_config_bool(var, value);
1278 return 0;
1281 if (!strcmp(var, "core.preloadindex")) {
1282 core_preload_index = git_config_bool(var, value);
1283 return 0;
1286 if (!strcmp(var, "core.createobject")) {
1287 if (!strcmp(value, "rename"))
1288 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
1289 else if (!strcmp(value, "link"))
1290 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
1291 else
1292 die(_("invalid mode for object creation: %s"), value);
1293 return 0;
1296 if (!strcmp(var, "core.sparsecheckout")) {
1297 core_apply_sparse_checkout = git_config_bool(var, value);
1298 return 0;
1301 if (!strcmp(var, "core.precomposeunicode")) {
1302 precomposed_unicode = git_config_bool(var, value);
1303 return 0;
1306 if (!strcmp(var, "core.protecthfs")) {
1307 protect_hfs = git_config_bool(var, value);
1308 return 0;
1311 if (!strcmp(var, "core.protectntfs")) {
1312 protect_ntfs = git_config_bool(var, value);
1313 return 0;
1316 if (!strcmp(var, "core.hidedotfiles")) {
1317 if (value && !strcasecmp(value, "dotgitonly"))
1318 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
1319 else
1320 hide_dotfiles = git_config_bool(var, value);
1321 return 0;
1324 /* Add other config variables here and to Documentation/config.txt. */
1325 return 0;
1328 static int git_default_i18n_config(const char *var, const char *value)
1330 if (!strcmp(var, "i18n.commitencoding"))
1331 return git_config_string(&git_commit_encoding, var, value);
1333 if (!strcmp(var, "i18n.logoutputencoding"))
1334 return git_config_string(&git_log_output_encoding, var, value);
1336 /* Add other config variables here and to Documentation/config.txt. */
1337 return 0;
1340 static int git_default_branch_config(const char *var, const char *value)
1342 if (!strcmp(var, "branch.autosetupmerge")) {
1343 if (value && !strcasecmp(value, "always")) {
1344 git_branch_track = BRANCH_TRACK_ALWAYS;
1345 return 0;
1347 git_branch_track = git_config_bool(var, value);
1348 return 0;
1350 if (!strcmp(var, "branch.autosetuprebase")) {
1351 if (!value)
1352 return config_error_nonbool(var);
1353 else if (!strcmp(value, "never"))
1354 autorebase = AUTOREBASE_NEVER;
1355 else if (!strcmp(value, "local"))
1356 autorebase = AUTOREBASE_LOCAL;
1357 else if (!strcmp(value, "remote"))
1358 autorebase = AUTOREBASE_REMOTE;
1359 else if (!strcmp(value, "always"))
1360 autorebase = AUTOREBASE_ALWAYS;
1361 else
1362 return error("malformed value for %s", var);
1363 return 0;
1366 /* Add other config variables here and to Documentation/config.txt. */
1367 return 0;
1370 static int git_default_push_config(const char *var, const char *value)
1372 if (!strcmp(var, "push.default")) {
1373 if (!value)
1374 return config_error_nonbool(var);
1375 else if (!strcmp(value, "nothing"))
1376 push_default = PUSH_DEFAULT_NOTHING;
1377 else if (!strcmp(value, "matching"))
1378 push_default = PUSH_DEFAULT_MATCHING;
1379 else if (!strcmp(value, "simple"))
1380 push_default = PUSH_DEFAULT_SIMPLE;
1381 else if (!strcmp(value, "upstream"))
1382 push_default = PUSH_DEFAULT_UPSTREAM;
1383 else if (!strcmp(value, "tracking")) /* deprecated */
1384 push_default = PUSH_DEFAULT_UPSTREAM;
1385 else if (!strcmp(value, "current"))
1386 push_default = PUSH_DEFAULT_CURRENT;
1387 else {
1388 error("malformed value for %s: %s", var, value);
1389 return error("Must be one of nothing, matching, simple, "
1390 "upstream or current.");
1392 return 0;
1395 /* Add other config variables here and to Documentation/config.txt. */
1396 return 0;
1399 static int git_default_mailmap_config(const char *var, const char *value)
1401 if (!strcmp(var, "mailmap.file"))
1402 return git_config_pathname(&git_mailmap_file, var, value);
1403 if (!strcmp(var, "mailmap.blob"))
1404 return git_config_string(&git_mailmap_blob, var, value);
1406 /* Add other config variables here and to Documentation/config.txt. */
1407 return 0;
1410 int git_default_config(const char *var, const char *value, void *dummy)
1412 if (starts_with(var, "core."))
1413 return git_default_core_config(var, value);
1415 if (starts_with(var, "user."))
1416 return git_ident_config(var, value, dummy);
1418 if (starts_with(var, "i18n."))
1419 return git_default_i18n_config(var, value);
1421 if (starts_with(var, "branch."))
1422 return git_default_branch_config(var, value);
1424 if (starts_with(var, "push."))
1425 return git_default_push_config(var, value);
1427 if (starts_with(var, "mailmap."))
1428 return git_default_mailmap_config(var, value);
1430 if (starts_with(var, "advice."))
1431 return git_default_advice_config(var, value);
1433 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1434 pager_use_color = git_config_bool(var,value);
1435 return 0;
1438 if (!strcmp(var, "pack.packsizelimit")) {
1439 pack_size_limit_cfg = git_config_ulong(var, value);
1440 return 0;
1443 if (!strcmp(var, "pack.compression")) {
1444 int level = git_config_int(var, value);
1445 if (level == -1)
1446 level = Z_DEFAULT_COMPRESSION;
1447 else if (level < 0 || level > Z_BEST_COMPRESSION)
1448 die(_("bad pack compression level %d"), level);
1449 pack_compression_level = level;
1450 pack_compression_seen = 1;
1451 return 0;
1454 /* Add other config variables here and to Documentation/config.txt. */
1455 return 0;
1459 * All source specific fields in the union, die_on_error, name and the callbacks
1460 * fgetc, ungetc, ftell of top need to be initialized before calling
1461 * this function.
1463 static int do_config_from(struct config_source *top, config_fn_t fn, void *data,
1464 const struct config_options *opts)
1466 int ret;
1468 /* push config-file parsing state stack */
1469 top->prev = cf;
1470 top->linenr = 1;
1471 top->eof = 0;
1472 strbuf_init(&top->value, 1024);
1473 strbuf_init(&top->var, 1024);
1474 cf = top;
1476 ret = git_parse_source(fn, data, opts);
1478 /* pop config-file parsing state stack */
1479 strbuf_release(&top->value);
1480 strbuf_release(&top->var);
1481 cf = top->prev;
1483 return ret;
1486 static int do_config_from_file(config_fn_t fn,
1487 const enum config_origin_type origin_type,
1488 const char *name, const char *path, FILE *f,
1489 void *data, const struct config_options *opts)
1491 struct config_source top;
1493 top.u.file = f;
1494 top.origin_type = origin_type;
1495 top.name = name;
1496 top.path = path;
1497 top.die_on_error = 1;
1498 top.do_fgetc = config_file_fgetc;
1499 top.do_ungetc = config_file_ungetc;
1500 top.do_ftell = config_file_ftell;
1502 return do_config_from(&top, fn, data, opts);
1505 static int git_config_from_stdin(config_fn_t fn, void *data)
1507 return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", NULL, stdin,
1508 data, NULL);
1511 int git_config_from_file_with_options(config_fn_t fn, const char *filename,
1512 void *data,
1513 const struct config_options *opts)
1515 int ret = -1;
1516 FILE *f;
1518 f = fopen_or_warn(filename, "r");
1519 if (f) {
1520 flockfile(f);
1521 ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename,
1522 filename, f, data, opts);
1523 funlockfile(f);
1524 fclose(f);
1526 return ret;
1529 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
1531 return git_config_from_file_with_options(fn, filename, data, NULL);
1534 int git_config_from_mem(config_fn_t fn, const enum config_origin_type origin_type,
1535 const char *name, const char *buf, size_t len, void *data)
1537 struct config_source top;
1539 top.u.buf.buf = buf;
1540 top.u.buf.len = len;
1541 top.u.buf.pos = 0;
1542 top.origin_type = origin_type;
1543 top.name = name;
1544 top.path = NULL;
1545 top.die_on_error = 0;
1546 top.do_fgetc = config_buf_fgetc;
1547 top.do_ungetc = config_buf_ungetc;
1548 top.do_ftell = config_buf_ftell;
1550 return do_config_from(&top, fn, data, NULL);
1553 int git_config_from_blob_oid(config_fn_t fn,
1554 const char *name,
1555 const struct object_id *oid,
1556 void *data)
1558 enum object_type type;
1559 char *buf;
1560 unsigned long size;
1561 int ret;
1563 buf = read_sha1_file(oid->hash, &type, &size);
1564 if (!buf)
1565 return error("unable to load config blob object '%s'", name);
1566 if (type != OBJ_BLOB) {
1567 free(buf);
1568 return error("reference '%s' does not point to a blob", name);
1571 ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size, data);
1572 free(buf);
1574 return ret;
1577 static int git_config_from_blob_ref(config_fn_t fn,
1578 const char *name,
1579 void *data)
1581 struct object_id oid;
1583 if (get_oid(name, &oid) < 0)
1584 return error("unable to resolve config blob '%s'", name);
1585 return git_config_from_blob_oid(fn, name, &oid, data);
1588 const char *git_etc_gitconfig(void)
1590 static const char *system_wide;
1591 if (!system_wide)
1592 system_wide = system_path(ETC_GITCONFIG);
1593 return system_wide;
1597 * Parse environment variable 'k' as a boolean (in various
1598 * possible spellings); if missing, use the default value 'def'.
1600 int git_env_bool(const char *k, int def)
1602 const char *v = getenv(k);
1603 return v ? git_config_bool(k, v) : def;
1607 * Parse environment variable 'k' as ulong with possibly a unit
1608 * suffix; if missing, use the default value 'val'.
1610 unsigned long git_env_ulong(const char *k, unsigned long val)
1612 const char *v = getenv(k);
1613 if (v && !git_parse_ulong(v, &val))
1614 die("failed to parse %s", k);
1615 return val;
1618 int git_config_system(void)
1620 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
1623 static int do_git_config_sequence(const struct config_options *opts,
1624 config_fn_t fn, void *data)
1626 int ret = 0;
1627 char *xdg_config = xdg_config_home("config");
1628 char *user_config = expand_user_path("~/.gitconfig", 0);
1629 char *repo_config;
1631 if (opts->commondir)
1632 repo_config = mkpathdup("%s/config", opts->commondir);
1633 else
1634 repo_config = NULL;
1636 current_parsing_scope = CONFIG_SCOPE_SYSTEM;
1637 if (git_config_system() && !access_or_die(git_etc_gitconfig(), R_OK, 0))
1638 ret += git_config_from_file(fn, git_etc_gitconfig(),
1639 data);
1641 current_parsing_scope = CONFIG_SCOPE_GLOBAL;
1642 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
1643 ret += git_config_from_file(fn, xdg_config, data);
1645 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
1646 ret += git_config_from_file(fn, user_config, data);
1648 current_parsing_scope = CONFIG_SCOPE_REPO;
1649 if (repo_config && !access_or_die(repo_config, R_OK, 0))
1650 ret += git_config_from_file(fn, repo_config, data);
1652 current_parsing_scope = CONFIG_SCOPE_CMDLINE;
1653 if (git_config_from_parameters(fn, data) < 0)
1654 die(_("unable to parse command-line config"));
1656 current_parsing_scope = CONFIG_SCOPE_UNKNOWN;
1657 free(xdg_config);
1658 free(user_config);
1659 free(repo_config);
1660 return ret;
1663 int config_with_options(config_fn_t fn, void *data,
1664 struct git_config_source *config_source,
1665 const struct config_options *opts)
1667 struct config_include_data inc = CONFIG_INCLUDE_INIT;
1669 if (opts->respect_includes) {
1670 inc.fn = fn;
1671 inc.data = data;
1672 inc.opts = opts;
1673 fn = git_config_include;
1674 data = &inc;
1678 * If we have a specific filename, use it. Otherwise, follow the
1679 * regular lookup sequence.
1681 if (config_source && config_source->use_stdin)
1682 return git_config_from_stdin(fn, data);
1683 else if (config_source && config_source->file)
1684 return git_config_from_file(fn, config_source->file, data);
1685 else if (config_source && config_source->blob)
1686 return git_config_from_blob_ref(fn, config_source->blob, data);
1688 return do_git_config_sequence(opts, fn, data);
1691 static void configset_iter(struct config_set *cs, config_fn_t fn, void *data)
1693 int i, value_index;
1694 struct string_list *values;
1695 struct config_set_element *entry;
1696 struct configset_list *list = &cs->list;
1698 for (i = 0; i < list->nr; i++) {
1699 entry = list->items[i].e;
1700 value_index = list->items[i].value_index;
1701 values = &entry->value_list;
1703 current_config_kvi = values->items[value_index].util;
1705 if (fn(entry->key, values->items[value_index].string, data) < 0)
1706 git_die_config_linenr(entry->key,
1707 current_config_kvi->filename,
1708 current_config_kvi->linenr);
1710 current_config_kvi = NULL;
1714 void read_early_config(config_fn_t cb, void *data)
1716 struct config_options opts = {0};
1717 struct strbuf commondir = STRBUF_INIT;
1718 struct strbuf gitdir = STRBUF_INIT;
1720 opts.respect_includes = 1;
1722 if (have_git_dir()) {
1723 opts.commondir = get_git_common_dir();
1724 opts.git_dir = get_git_dir();
1726 * When setup_git_directory() was not yet asked to discover the
1727 * GIT_DIR, we ask discover_git_directory() to figure out whether there
1728 * is any repository config we should use (but unlike
1729 * setup_git_directory_gently(), no global state is changed, most
1730 * notably, the current working directory is still the same after the
1731 * call).
1733 } else if (!discover_git_directory(&commondir, &gitdir)) {
1734 opts.commondir = commondir.buf;
1735 opts.git_dir = gitdir.buf;
1738 config_with_options(cb, data, NULL, &opts);
1740 strbuf_release(&commondir);
1741 strbuf_release(&gitdir);
1744 static struct config_set_element *configset_find_element(struct config_set *cs, const char *key)
1746 struct config_set_element k;
1747 struct config_set_element *found_entry;
1748 char *normalized_key;
1750 * `key` may come from the user, so normalize it before using it
1751 * for querying entries from the hashmap.
1753 if (git_config_parse_key(key, &normalized_key, NULL))
1754 return NULL;
1756 hashmap_entry_init(&k, strhash(normalized_key));
1757 k.key = normalized_key;
1758 found_entry = hashmap_get(&cs->config_hash, &k, NULL);
1759 free(normalized_key);
1760 return found_entry;
1763 static int configset_add_value(struct config_set *cs, const char *key, const char *value)
1765 struct config_set_element *e;
1766 struct string_list_item *si;
1767 struct configset_list_item *l_item;
1768 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
1770 e = configset_find_element(cs, key);
1772 * Since the keys are being fed by git_config*() callback mechanism, they
1773 * are already normalized. So simply add them without any further munging.
1775 if (!e) {
1776 e = xmalloc(sizeof(*e));
1777 hashmap_entry_init(e, strhash(key));
1778 e->key = xstrdup(key);
1779 string_list_init(&e->value_list, 1);
1780 hashmap_add(&cs->config_hash, e);
1782 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
1784 ALLOC_GROW(cs->list.items, cs->list.nr + 1, cs->list.alloc);
1785 l_item = &cs->list.items[cs->list.nr++];
1786 l_item->e = e;
1787 l_item->value_index = e->value_list.nr - 1;
1789 if (!cf)
1790 die("BUG: configset_add_value has no source");
1791 if (cf->name) {
1792 kv_info->filename = strintern(cf->name);
1793 kv_info->linenr = cf->linenr;
1794 kv_info->origin_type = cf->origin_type;
1795 } else {
1796 /* for values read from `git_config_from_parameters()` */
1797 kv_info->filename = NULL;
1798 kv_info->linenr = -1;
1799 kv_info->origin_type = CONFIG_ORIGIN_CMDLINE;
1801 kv_info->scope = current_parsing_scope;
1802 si->util = kv_info;
1804 return 0;
1807 static int config_set_element_cmp(const void *unused_cmp_data,
1808 const void *entry,
1809 const void *entry_or_key,
1810 const void *unused_keydata)
1812 const struct config_set_element *e1 = entry;
1813 const struct config_set_element *e2 = entry_or_key;
1815 return strcmp(e1->key, e2->key);
1818 void git_configset_init(struct config_set *cs)
1820 hashmap_init(&cs->config_hash, config_set_element_cmp, NULL, 0);
1821 cs->hash_initialized = 1;
1822 cs->list.nr = 0;
1823 cs->list.alloc = 0;
1824 cs->list.items = NULL;
1827 void git_configset_clear(struct config_set *cs)
1829 struct config_set_element *entry;
1830 struct hashmap_iter iter;
1831 if (!cs->hash_initialized)
1832 return;
1834 hashmap_iter_init(&cs->config_hash, &iter);
1835 while ((entry = hashmap_iter_next(&iter))) {
1836 free(entry->key);
1837 string_list_clear(&entry->value_list, 1);
1839 hashmap_free(&cs->config_hash, 1);
1840 cs->hash_initialized = 0;
1841 free(cs->list.items);
1842 cs->list.nr = 0;
1843 cs->list.alloc = 0;
1844 cs->list.items = NULL;
1847 static int config_set_callback(const char *key, const char *value, void *cb)
1849 struct config_set *cs = cb;
1850 configset_add_value(cs, key, value);
1851 return 0;
1854 int git_configset_add_file(struct config_set *cs, const char *filename)
1856 return git_config_from_file(config_set_callback, filename, cs);
1859 int git_configset_get_value(struct config_set *cs, const char *key, const char **value)
1861 const struct string_list *values = NULL;
1863 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
1864 * queried key in the files of the configset, the value returned will be the last
1865 * value in the value list for that key.
1867 values = git_configset_get_value_multi(cs, key);
1869 if (!values)
1870 return 1;
1871 assert(values->nr > 0);
1872 *value = values->items[values->nr - 1].string;
1873 return 0;
1876 const struct string_list *git_configset_get_value_multi(struct config_set *cs, const char *key)
1878 struct config_set_element *e = configset_find_element(cs, key);
1879 return e ? &e->value_list : NULL;
1882 int git_configset_get_string_const(struct config_set *cs, const char *key, const char **dest)
1884 const char *value;
1885 if (!git_configset_get_value(cs, key, &value))
1886 return git_config_string(dest, key, value);
1887 else
1888 return 1;
1891 int git_configset_get_string(struct config_set *cs, const char *key, char **dest)
1893 return git_configset_get_string_const(cs, key, (const char **)dest);
1896 int git_configset_get_int(struct config_set *cs, const char *key, int *dest)
1898 const char *value;
1899 if (!git_configset_get_value(cs, key, &value)) {
1900 *dest = git_config_int(key, value);
1901 return 0;
1902 } else
1903 return 1;
1906 int git_configset_get_ulong(struct config_set *cs, const char *key, unsigned long *dest)
1908 const char *value;
1909 if (!git_configset_get_value(cs, key, &value)) {
1910 *dest = git_config_ulong(key, value);
1911 return 0;
1912 } else
1913 return 1;
1916 int git_configset_get_bool(struct config_set *cs, const char *key, int *dest)
1918 const char *value;
1919 if (!git_configset_get_value(cs, key, &value)) {
1920 *dest = git_config_bool(key, value);
1921 return 0;
1922 } else
1923 return 1;
1926 int git_configset_get_bool_or_int(struct config_set *cs, const char *key,
1927 int *is_bool, int *dest)
1929 const char *value;
1930 if (!git_configset_get_value(cs, key, &value)) {
1931 *dest = git_config_bool_or_int(key, value, is_bool);
1932 return 0;
1933 } else
1934 return 1;
1937 int git_configset_get_maybe_bool(struct config_set *cs, const char *key, int *dest)
1939 const char *value;
1940 if (!git_configset_get_value(cs, key, &value)) {
1941 *dest = git_parse_maybe_bool(value);
1942 if (*dest == -1)
1943 return -1;
1944 return 0;
1945 } else
1946 return 1;
1949 int git_configset_get_pathname(struct config_set *cs, const char *key, const char **dest)
1951 const char *value;
1952 if (!git_configset_get_value(cs, key, &value))
1953 return git_config_pathname(dest, key, value);
1954 else
1955 return 1;
1958 /* Functions use to read configuration from a repository */
1959 static void repo_read_config(struct repository *repo)
1961 struct config_options opts;
1963 opts.respect_includes = 1;
1964 opts.commondir = repo->commondir;
1965 opts.git_dir = repo->gitdir;
1967 if (!repo->config)
1968 repo->config = xcalloc(1, sizeof(struct config_set));
1969 else
1970 git_configset_clear(repo->config);
1972 git_configset_init(repo->config);
1974 if (config_with_options(config_set_callback, repo->config, NULL, &opts) < 0)
1976 * config_with_options() normally returns only
1977 * zero, as most errors are fatal, and
1978 * non-fatal potential errors are guarded by "if"
1979 * statements that are entered only when no error is
1980 * possible.
1982 * If we ever encounter a non-fatal error, it means
1983 * something went really wrong and we should stop
1984 * immediately.
1986 die(_("unknown error occurred while reading the configuration files"));
1989 static void git_config_check_init(struct repository *repo)
1991 if (repo->config && repo->config->hash_initialized)
1992 return;
1993 repo_read_config(repo);
1996 static void repo_config_clear(struct repository *repo)
1998 if (!repo->config || !repo->config->hash_initialized)
1999 return;
2000 git_configset_clear(repo->config);
2003 void repo_config(struct repository *repo, config_fn_t fn, void *data)
2005 git_config_check_init(repo);
2006 configset_iter(repo->config, fn, data);
2009 int repo_config_get_value(struct repository *repo,
2010 const char *key, const char **value)
2012 git_config_check_init(repo);
2013 return git_configset_get_value(repo->config, key, value);
2016 const struct string_list *repo_config_get_value_multi(struct repository *repo,
2017 const char *key)
2019 git_config_check_init(repo);
2020 return git_configset_get_value_multi(repo->config, key);
2023 int repo_config_get_string_const(struct repository *repo,
2024 const char *key, const char **dest)
2026 int ret;
2027 git_config_check_init(repo);
2028 ret = git_configset_get_string_const(repo->config, key, dest);
2029 if (ret < 0)
2030 git_die_config(key, NULL);
2031 return ret;
2034 int repo_config_get_string(struct repository *repo,
2035 const char *key, char **dest)
2037 git_config_check_init(repo);
2038 return repo_config_get_string_const(repo, key, (const char **)dest);
2041 int repo_config_get_int(struct repository *repo,
2042 const char *key, int *dest)
2044 git_config_check_init(repo);
2045 return git_configset_get_int(repo->config, key, dest);
2048 int repo_config_get_ulong(struct repository *repo,
2049 const char *key, unsigned long *dest)
2051 git_config_check_init(repo);
2052 return git_configset_get_ulong(repo->config, key, dest);
2055 int repo_config_get_bool(struct repository *repo,
2056 const char *key, int *dest)
2058 git_config_check_init(repo);
2059 return git_configset_get_bool(repo->config, key, dest);
2062 int repo_config_get_bool_or_int(struct repository *repo,
2063 const char *key, int *is_bool, int *dest)
2065 git_config_check_init(repo);
2066 return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2069 int repo_config_get_maybe_bool(struct repository *repo,
2070 const char *key, int *dest)
2072 git_config_check_init(repo);
2073 return git_configset_get_maybe_bool(repo->config, key, dest);
2076 int repo_config_get_pathname(struct repository *repo,
2077 const char *key, const char **dest)
2079 int ret;
2080 git_config_check_init(repo);
2081 ret = git_configset_get_pathname(repo->config, key, dest);
2082 if (ret < 0)
2083 git_die_config(key, NULL);
2084 return ret;
2087 /* Functions used historically to read configuration from 'the_repository' */
2088 void git_config(config_fn_t fn, void *data)
2090 repo_config(the_repository, fn, data);
2093 void git_config_clear(void)
2095 repo_config_clear(the_repository);
2098 int git_config_get_value(const char *key, const char **value)
2100 return repo_config_get_value(the_repository, key, value);
2103 const struct string_list *git_config_get_value_multi(const char *key)
2105 return repo_config_get_value_multi(the_repository, key);
2108 int git_config_get_string_const(const char *key, const char **dest)
2110 return repo_config_get_string_const(the_repository, key, dest);
2113 int git_config_get_string(const char *key, char **dest)
2115 return repo_config_get_string(the_repository, key, dest);
2118 int git_config_get_int(const char *key, int *dest)
2120 return repo_config_get_int(the_repository, key, dest);
2123 int git_config_get_ulong(const char *key, unsigned long *dest)
2125 return repo_config_get_ulong(the_repository, key, dest);
2128 int git_config_get_bool(const char *key, int *dest)
2130 return repo_config_get_bool(the_repository, key, dest);
2133 int git_config_get_bool_or_int(const char *key, int *is_bool, int *dest)
2135 return repo_config_get_bool_or_int(the_repository, key, is_bool, dest);
2138 int git_config_get_maybe_bool(const char *key, int *dest)
2140 return repo_config_get_maybe_bool(the_repository, key, dest);
2143 int git_config_get_pathname(const char *key, const char **dest)
2145 return repo_config_get_pathname(the_repository, key, dest);
2149 * Note: This function exists solely to maintain backward compatibility with
2150 * 'fetch' and 'update_clone' storing configuration in '.gitmodules' and should
2151 * NOT be used anywhere else.
2153 * Runs the provided config function on the '.gitmodules' file found in the
2154 * working directory.
2156 void config_from_gitmodules(config_fn_t fn, void *data)
2158 if (the_repository->worktree) {
2159 char *file = repo_worktree_path(the_repository, GITMODULES_FILE);
2160 git_config_from_file(fn, file, data);
2161 free(file);
2165 int git_config_get_expiry(const char *key, const char **output)
2167 int ret = git_config_get_string_const(key, output);
2168 if (ret)
2169 return ret;
2170 if (strcmp(*output, "now")) {
2171 timestamp_t now = approxidate("now");
2172 if (approxidate(*output) >= now)
2173 git_die_config(key, _("Invalid %s: '%s'"), key, *output);
2175 return ret;
2178 int git_config_get_expiry_in_days(const char *key, timestamp_t *expiry, timestamp_t now)
2180 char *expiry_string;
2181 intmax_t days;
2182 timestamp_t when;
2184 if (git_config_get_string(key, &expiry_string))
2185 return 1; /* no such thing */
2187 if (git_parse_signed(expiry_string, &days, maximum_signed_value_of_type(int))) {
2188 const int scale = 86400;
2189 *expiry = now - days * scale;
2190 return 0;
2193 if (!parse_expiry_date(expiry_string, &when)) {
2194 *expiry = when;
2195 return 0;
2197 return -1; /* thing exists but cannot be parsed */
2200 int git_config_get_untracked_cache(void)
2202 int val = -1;
2203 const char *v;
2205 /* Hack for test programs like test-dump-untracked-cache */
2206 if (ignore_untracked_cache_config)
2207 return -1;
2209 if (!git_config_get_maybe_bool("core.untrackedcache", &val))
2210 return val;
2212 if (!git_config_get_value("core.untrackedcache", &v)) {
2213 if (!strcasecmp(v, "keep"))
2214 return -1;
2216 error(_("unknown core.untrackedCache value '%s'; "
2217 "using 'keep' default value"), v);
2218 return -1;
2221 return -1; /* default value */
2224 int git_config_get_split_index(void)
2226 int val;
2228 if (!git_config_get_maybe_bool("core.splitindex", &val))
2229 return val;
2231 return -1; /* default value */
2234 int git_config_get_max_percent_split_change(void)
2236 int val = -1;
2238 if (!git_config_get_int("splitindex.maxpercentchange", &val)) {
2239 if (0 <= val && val <= 100)
2240 return val;
2242 return error(_("splitIndex.maxPercentChange value '%d' "
2243 "should be between 0 and 100"), val);
2246 return -1; /* default value */
2249 int git_config_get_fsmonitor(void)
2251 if (git_config_get_pathname("core.fsmonitor", &core_fsmonitor))
2252 core_fsmonitor = getenv("GIT_FSMONITOR_TEST");
2254 if (core_fsmonitor && !*core_fsmonitor)
2255 core_fsmonitor = NULL;
2257 if (core_fsmonitor)
2258 return 1;
2260 return 0;
2263 NORETURN
2264 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2266 if (!filename)
2267 die(_("unable to parse '%s' from command-line config"), key);
2268 else
2269 die(_("bad config variable '%s' in file '%s' at line %d"),
2270 key, filename, linenr);
2273 NORETURN __attribute__((format(printf, 2, 3)))
2274 void git_die_config(const char *key, const char *err, ...)
2276 const struct string_list *values;
2277 struct key_value_info *kv_info;
2279 if (err) {
2280 va_list params;
2281 va_start(params, err);
2282 vreportf("error: ", err, params);
2283 va_end(params);
2285 values = git_config_get_value_multi(key);
2286 kv_info = values->items[values->nr - 1].util;
2287 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
2291 * Find all the stuff for git_config_set() below.
2294 struct config_store_data {
2295 int baselen;
2296 char *key;
2297 int do_not_match;
2298 regex_t *value_regex;
2299 int multi_replace;
2300 struct {
2301 size_t begin, end;
2302 enum config_event_t type;
2303 int is_keys_section;
2304 } *parsed;
2305 unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
2306 unsigned int key_seen:1, section_seen:1, is_keys_section:1;
2309 static int matches(const char *key, const char *value,
2310 const struct config_store_data *store)
2312 if (strcmp(key, store->key))
2313 return 0; /* not ours */
2314 if (!store->value_regex)
2315 return 1; /* always matches */
2316 if (store->value_regex == CONFIG_REGEX_NONE)
2317 return 0; /* never matches */
2319 return store->do_not_match ^
2320 (value && !regexec(store->value_regex, value, 0, NULL, 0));
2323 static int store_aux_event(enum config_event_t type,
2324 size_t begin, size_t end, void *data)
2326 struct config_store_data *store = data;
2328 ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
2329 store->parsed[store->parsed_nr].begin = begin;
2330 store->parsed[store->parsed_nr].end = end;
2331 store->parsed[store->parsed_nr].type = type;
2333 if (type == CONFIG_EVENT_SECTION) {
2334 int (*cmpfn)(const char *, const char *, size_t);
2336 if (cf->var.len < 2 || cf->var.buf[cf->var.len - 1] != '.')
2337 return error("invalid section name '%s'", cf->var.buf);
2339 if (cf->subsection_case_sensitive)
2340 cmpfn = strncasecmp;
2341 else
2342 cmpfn = strncmp;
2344 /* Is this the section we were looking for? */
2345 store->is_keys_section =
2346 store->parsed[store->parsed_nr].is_keys_section =
2347 cf->var.len - 1 == store->baselen &&
2348 !cmpfn(cf->var.buf, store->key, store->baselen);
2349 if (store->is_keys_section) {
2350 store->section_seen = 1;
2351 ALLOC_GROW(store->seen, store->seen_nr + 1,
2352 store->seen_alloc);
2353 store->seen[store->seen_nr] = store->parsed_nr;
2357 store->parsed_nr++;
2359 return 0;
2362 static int store_aux(const char *key, const char *value, void *cb)
2364 struct config_store_data *store = cb;
2366 if (store->key_seen) {
2367 if (matches(key, value, store)) {
2368 if (store->seen_nr == 1 && store->multi_replace == 0) {
2369 warning(_("%s has multiple values"), key);
2372 ALLOC_GROW(store->seen, store->seen_nr + 1,
2373 store->seen_alloc);
2375 store->seen[store->seen_nr] = store->parsed_nr;
2376 store->seen_nr++;
2378 } else if (store->is_keys_section) {
2380 * Do not increment matches yet: this may not be a match, but we
2381 * are in the desired section.
2383 ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
2384 store->seen[store->seen_nr] = store->parsed_nr;
2385 store->section_seen = 1;
2387 if (matches(key, value, store)) {
2388 store->seen_nr++;
2389 store->key_seen = 1;
2393 return 0;
2396 static int write_error(const char *filename)
2398 error("failed to write new configuration file %s", filename);
2400 /* Same error code as "failed to rename". */
2401 return 4;
2404 static struct strbuf store_create_section(const char *key,
2405 const struct config_store_data *store)
2407 const char *dot;
2408 int i;
2409 struct strbuf sb = STRBUF_INIT;
2411 dot = memchr(key, '.', store->baselen);
2412 if (dot) {
2413 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
2414 for (i = dot - key + 1; i < store->baselen; i++) {
2415 if (key[i] == '"' || key[i] == '\\')
2416 strbuf_addch(&sb, '\\');
2417 strbuf_addch(&sb, key[i]);
2419 strbuf_addstr(&sb, "\"]\n");
2420 } else {
2421 strbuf_addf(&sb, "[%.*s]\n", store->baselen, key);
2424 return sb;
2427 static ssize_t write_section(int fd, const char *key,
2428 const struct config_store_data *store)
2430 struct strbuf sb = store_create_section(key, store);
2431 ssize_t ret;
2433 ret = write_in_full(fd, sb.buf, sb.len);
2434 strbuf_release(&sb);
2436 return ret;
2439 static ssize_t write_pair(int fd, const char *key, const char *value,
2440 const struct config_store_data *store)
2442 int i;
2443 ssize_t ret;
2444 int length = strlen(key + store->baselen + 1);
2445 const char *quote = "";
2446 struct strbuf sb = STRBUF_INIT;
2449 * Check to see if the value needs to be surrounded with a dq pair.
2450 * Note that problematic characters are always backslash-quoted; this
2451 * check is about not losing leading or trailing SP and strings that
2452 * follow beginning-of-comment characters (i.e. ';' and '#') by the
2453 * configuration parser.
2455 if (value[0] == ' ')
2456 quote = "\"";
2457 for (i = 0; value[i]; i++)
2458 if (value[i] == ';' || value[i] == '#')
2459 quote = "\"";
2460 if (i && value[i - 1] == ' ')
2461 quote = "\"";
2463 strbuf_addf(&sb, "\t%.*s = %s",
2464 length, key + store->baselen + 1, quote);
2466 for (i = 0; value[i]; i++)
2467 switch (value[i]) {
2468 case '\n':
2469 strbuf_addstr(&sb, "\\n");
2470 break;
2471 case '\t':
2472 strbuf_addstr(&sb, "\\t");
2473 break;
2474 case '"':
2475 case '\\':
2476 strbuf_addch(&sb, '\\');
2477 /* fallthrough */
2478 default:
2479 strbuf_addch(&sb, value[i]);
2480 break;
2482 strbuf_addf(&sb, "%s\n", quote);
2484 ret = write_in_full(fd, sb.buf, sb.len);
2485 strbuf_release(&sb);
2487 return ret;
2491 * If we are about to unset the last key(s) in a section, and if there are
2492 * no comments surrounding (or included in) the section, we will want to
2493 * extend begin/end to remove the entire section.
2495 * Note: the parameter `seen_ptr` points to the index into the store.seen
2496 * array. * This index may be incremented if a section has more than one
2497 * entry (which all are to be removed).
2499 static void maybe_remove_section(struct config_store_data *store,
2500 const char *contents,
2501 size_t *begin_offset, size_t *end_offset,
2502 int *seen_ptr)
2504 size_t begin;
2505 int i, seen, section_seen = 0;
2508 * First, ensure that this is the first key, and that there are no
2509 * comments before the entry nor before the section header.
2511 seen = *seen_ptr;
2512 for (i = store->seen[seen]; i > 0; i--) {
2513 enum config_event_t type = store->parsed[i - 1].type;
2515 if (type == CONFIG_EVENT_COMMENT)
2516 /* There is a comment before this entry or section */
2517 return;
2518 if (type == CONFIG_EVENT_ENTRY) {
2519 if (!section_seen)
2520 /* This is not the section's first entry. */
2521 return;
2522 /* We encountered no comment before the section. */
2523 break;
2525 if (type == CONFIG_EVENT_SECTION) {
2526 if (!store->parsed[i - 1].is_keys_section)
2527 break;
2528 section_seen = 1;
2531 begin = store->parsed[i].begin;
2534 * Next, make sure that we are removing he last key(s) in the section,
2535 * and that there are no comments that are possibly about the current
2536 * section.
2538 for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
2539 enum config_event_t type = store->parsed[i].type;
2541 if (type == CONFIG_EVENT_COMMENT)
2542 return;
2543 if (type == CONFIG_EVENT_SECTION) {
2544 if (store->parsed[i].is_keys_section)
2545 continue;
2546 break;
2548 if (type == CONFIG_EVENT_ENTRY) {
2549 if (++seen < store->seen_nr &&
2550 i == store->seen[seen])
2551 /* We want to remove this entry, too */
2552 continue;
2553 /* There is another entry in this section. */
2554 return;
2559 * We are really removing the last entry/entries from this section, and
2560 * there are no enclosed or surrounding comments. Remove the entire,
2561 * now-empty section.
2563 *seen_ptr = seen;
2564 *begin_offset = begin;
2565 if (i < store->parsed_nr)
2566 *end_offset = store->parsed[i].begin;
2567 else
2568 *end_offset = store->parsed[store->parsed_nr - 1].end;
2571 int git_config_set_in_file_gently(const char *config_filename,
2572 const char *key, const char *value)
2574 return git_config_set_multivar_in_file_gently(config_filename, key, value, NULL, 0);
2577 void git_config_set_in_file(const char *config_filename,
2578 const char *key, const char *value)
2580 git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
2583 int git_config_set_gently(const char *key, const char *value)
2585 return git_config_set_multivar_gently(key, value, NULL, 0);
2588 void git_config_set(const char *key, const char *value)
2590 git_config_set_multivar(key, value, NULL, 0);
2594 * If value==NULL, unset in (remove from) config,
2595 * if value_regex!=NULL, disregard key/value pairs where value does not match.
2596 * if value_regex==CONFIG_REGEX_NONE, do not match any existing values
2597 * (only add a new one)
2598 * if multi_replace==0, nothing, or only one matching key/value is replaced,
2599 * else all matching key/values (regardless how many) are removed,
2600 * before the new pair is written.
2602 * Returns 0 on success.
2604 * This function does this:
2606 * - it locks the config file by creating ".git/config.lock"
2608 * - it then parses the config using store_aux() as validator to find
2609 * the position on the key/value pair to replace. If it is to be unset,
2610 * it must be found exactly once.
2612 * - the config file is mmap()ed and the part before the match (if any) is
2613 * written to the lock file, then the changed part and the rest.
2615 * - the config file is removed and the lock file rename()d to it.
2618 int git_config_set_multivar_in_file_gently(const char *config_filename,
2619 const char *key, const char *value,
2620 const char *value_regex,
2621 int multi_replace)
2623 int fd = -1, in_fd = -1;
2624 int ret;
2625 struct lock_file lock = LOCK_INIT;
2626 char *filename_buf = NULL;
2627 char *contents = NULL;
2628 size_t contents_sz;
2629 struct config_store_data store;
2631 memset(&store, 0, sizeof(store));
2633 /* parse-key returns negative; flip the sign to feed exit(3) */
2634 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
2635 if (ret)
2636 goto out_free;
2638 store.multi_replace = multi_replace;
2640 if (!config_filename)
2641 config_filename = filename_buf = git_pathdup("config");
2644 * The lock serves a purpose in addition to locking: the new
2645 * contents of .git/config will be written into it.
2647 fd = hold_lock_file_for_update(&lock, config_filename, 0);
2648 if (fd < 0) {
2649 error_errno("could not lock config file %s", config_filename);
2650 free(store.key);
2651 ret = CONFIG_NO_LOCK;
2652 goto out_free;
2656 * If .git/config does not exist yet, write a minimal version.
2658 in_fd = open(config_filename, O_RDONLY);
2659 if ( in_fd < 0 ) {
2660 free(store.key);
2662 if ( ENOENT != errno ) {
2663 error_errno("opening %s", config_filename);
2664 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
2665 goto out_free;
2667 /* if nothing to unset, error out */
2668 if (value == NULL) {
2669 ret = CONFIG_NOTHING_SET;
2670 goto out_free;
2673 store.key = (char *)key;
2674 if (write_section(fd, key, &store) < 0 ||
2675 write_pair(fd, key, value, &store) < 0)
2676 goto write_err_out;
2677 } else {
2678 struct stat st;
2679 size_t copy_begin, copy_end;
2680 int i, new_line = 0;
2681 struct config_options opts;
2683 if (value_regex == NULL)
2684 store.value_regex = NULL;
2685 else if (value_regex == CONFIG_REGEX_NONE)
2686 store.value_regex = CONFIG_REGEX_NONE;
2687 else {
2688 if (value_regex[0] == '!') {
2689 store.do_not_match = 1;
2690 value_regex++;
2691 } else
2692 store.do_not_match = 0;
2694 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
2695 if (regcomp(store.value_regex, value_regex,
2696 REG_EXTENDED)) {
2697 error("invalid pattern: %s", value_regex);
2698 free(store.value_regex);
2699 ret = CONFIG_INVALID_PATTERN;
2700 goto out_free;
2704 ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
2705 store.parsed[0].end = 0;
2707 memset(&opts, 0, sizeof(opts));
2708 opts.event_fn = store_aux_event;
2709 opts.event_fn_data = &store;
2712 * After this, store.parsed will contain offsets of all the
2713 * parsed elements, and store.seen will contain a list of
2714 * matches, as indices into store.parsed.
2716 * As a side effect, we make sure to transform only a valid
2717 * existing config file.
2719 if (git_config_from_file_with_options(store_aux,
2720 config_filename,
2721 &store, &opts)) {
2722 error("invalid config file %s", config_filename);
2723 free(store.key);
2724 if (store.value_regex != NULL &&
2725 store.value_regex != CONFIG_REGEX_NONE) {
2726 regfree(store.value_regex);
2727 free(store.value_regex);
2729 ret = CONFIG_INVALID_FILE;
2730 goto out_free;
2733 free(store.key);
2734 if (store.value_regex != NULL &&
2735 store.value_regex != CONFIG_REGEX_NONE) {
2736 regfree(store.value_regex);
2737 free(store.value_regex);
2740 /* if nothing to unset, or too many matches, error out */
2741 if ((store.seen_nr == 0 && value == NULL) ||
2742 (store.seen_nr > 1 && multi_replace == 0)) {
2743 ret = CONFIG_NOTHING_SET;
2744 goto out_free;
2747 if (fstat(in_fd, &st) == -1) {
2748 error_errno(_("fstat on %s failed"), config_filename);
2749 ret = CONFIG_INVALID_FILE;
2750 goto out_free;
2753 contents_sz = xsize_t(st.st_size);
2754 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
2755 MAP_PRIVATE, in_fd, 0);
2756 if (contents == MAP_FAILED) {
2757 if (errno == ENODEV && S_ISDIR(st.st_mode))
2758 errno = EISDIR;
2759 error_errno("unable to mmap '%s'", config_filename);
2760 ret = CONFIG_INVALID_FILE;
2761 contents = NULL;
2762 goto out_free;
2764 close(in_fd);
2765 in_fd = -1;
2767 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
2768 error_errno("chmod on %s failed", get_lock_file_path(&lock));
2769 ret = CONFIG_NO_WRITE;
2770 goto out_free;
2773 if (store.seen_nr == 0) {
2774 if (!store.seen_alloc) {
2775 /* Did not see key nor section */
2776 ALLOC_GROW(store.seen, 1, store.seen_alloc);
2777 store.seen[0] = store.parsed_nr
2778 - !!store.parsed_nr;
2780 store.seen_nr = 1;
2783 for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
2784 size_t replace_end;
2785 int j = store.seen[i];
2787 new_line = 0;
2788 if (!store.key_seen) {
2789 copy_end = store.parsed[j].end;
2790 /* include '\n' when copying section header */
2791 if (copy_end > 0 && copy_end < contents_sz &&
2792 contents[copy_end - 1] != '\n' &&
2793 contents[copy_end] == '\n')
2794 copy_end++;
2795 replace_end = copy_end;
2796 } else {
2797 replace_end = store.parsed[j].end;
2798 copy_end = store.parsed[j].begin;
2799 if (!value)
2800 maybe_remove_section(&store, contents,
2801 &copy_end,
2802 &replace_end, &i);
2804 * Swallow preceding white-space on the same
2805 * line.
2807 while (copy_end > 0 ) {
2808 char c = contents[copy_end - 1];
2810 if (isspace(c) && c != '\n')
2811 copy_end--;
2812 else
2813 break;
2817 if (copy_end > 0 && contents[copy_end-1] != '\n')
2818 new_line = 1;
2820 /* write the first part of the config */
2821 if (copy_end > copy_begin) {
2822 if (write_in_full(fd, contents + copy_begin,
2823 copy_end - copy_begin) < 0)
2824 goto write_err_out;
2825 if (new_line &&
2826 write_str_in_full(fd, "\n") < 0)
2827 goto write_err_out;
2829 copy_begin = replace_end;
2832 /* write the pair (value == NULL means unset) */
2833 if (value != NULL) {
2834 if (!store.section_seen) {
2835 if (write_section(fd, key, &store) < 0)
2836 goto write_err_out;
2838 if (write_pair(fd, key, value, &store) < 0)
2839 goto write_err_out;
2842 /* write the rest of the config */
2843 if (copy_begin < contents_sz)
2844 if (write_in_full(fd, contents + copy_begin,
2845 contents_sz - copy_begin) < 0)
2846 goto write_err_out;
2848 munmap(contents, contents_sz);
2849 contents = NULL;
2852 if (commit_lock_file(&lock) < 0) {
2853 error_errno("could not write config file %s", config_filename);
2854 ret = CONFIG_NO_WRITE;
2855 goto out_free;
2858 ret = 0;
2860 /* Invalidate the config cache */
2861 git_config_clear();
2863 out_free:
2864 rollback_lock_file(&lock);
2865 free(filename_buf);
2866 if (contents)
2867 munmap(contents, contents_sz);
2868 if (in_fd >= 0)
2869 close(in_fd);
2870 return ret;
2872 write_err_out:
2873 ret = write_error(get_lock_file_path(&lock));
2874 goto out_free;
2878 void git_config_set_multivar_in_file(const char *config_filename,
2879 const char *key, const char *value,
2880 const char *value_regex, int multi_replace)
2882 if (!git_config_set_multivar_in_file_gently(config_filename, key, value,
2883 value_regex, multi_replace))
2884 return;
2885 if (value)
2886 die(_("could not set '%s' to '%s'"), key, value);
2887 else
2888 die(_("could not unset '%s'"), key);
2891 int git_config_set_multivar_gently(const char *key, const char *value,
2892 const char *value_regex, int multi_replace)
2894 return git_config_set_multivar_in_file_gently(NULL, key, value, value_regex,
2895 multi_replace);
2898 void git_config_set_multivar(const char *key, const char *value,
2899 const char *value_regex, int multi_replace)
2901 git_config_set_multivar_in_file(NULL, key, value, value_regex,
2902 multi_replace);
2905 static int section_name_match (const char *buf, const char *name)
2907 int i = 0, j = 0, dot = 0;
2908 if (buf[i] != '[')
2909 return 0;
2910 for (i = 1; buf[i] && buf[i] != ']'; i++) {
2911 if (!dot && isspace(buf[i])) {
2912 dot = 1;
2913 if (name[j++] != '.')
2914 break;
2915 for (i++; isspace(buf[i]); i++)
2916 ; /* do nothing */
2917 if (buf[i] != '"')
2918 break;
2919 continue;
2921 if (buf[i] == '\\' && dot)
2922 i++;
2923 else if (buf[i] == '"' && dot) {
2924 for (i++; isspace(buf[i]); i++)
2925 ; /* do_nothing */
2926 break;
2928 if (buf[i] != name[j++])
2929 break;
2931 if (buf[i] == ']' && name[j] == 0) {
2933 * We match, now just find the right length offset by
2934 * gobbling up any whitespace after it, as well
2936 i++;
2937 for (; buf[i] && isspace(buf[i]); i++)
2938 ; /* do nothing */
2939 return i;
2941 return 0;
2944 static int section_name_is_ok(const char *name)
2946 /* Empty section names are bogus. */
2947 if (!*name)
2948 return 0;
2951 * Before a dot, we must be alphanumeric or dash. After the first dot,
2952 * anything goes, so we can stop checking.
2954 for (; *name && *name != '.'; name++)
2955 if (*name != '-' && !isalnum(*name))
2956 return 0;
2957 return 1;
2960 /* if new_name == NULL, the section is removed instead */
2961 static int git_config_copy_or_rename_section_in_file(const char *config_filename,
2962 const char *old_name,
2963 const char *new_name, int copy)
2965 int ret = 0, remove = 0;
2966 char *filename_buf = NULL;
2967 struct lock_file lock = LOCK_INIT;
2968 int out_fd;
2969 char buf[1024];
2970 FILE *config_file = NULL;
2971 struct stat st;
2972 struct strbuf copystr = STRBUF_INIT;
2973 struct config_store_data store;
2975 memset(&store, 0, sizeof(store));
2977 if (new_name && !section_name_is_ok(new_name)) {
2978 ret = error("invalid section name: %s", new_name);
2979 goto out_no_rollback;
2982 if (!config_filename)
2983 config_filename = filename_buf = git_pathdup("config");
2985 out_fd = hold_lock_file_for_update(&lock, config_filename, 0);
2986 if (out_fd < 0) {
2987 ret = error("could not lock config file %s", config_filename);
2988 goto out;
2991 if (!(config_file = fopen(config_filename, "rb"))) {
2992 ret = warn_on_fopen_errors(config_filename);
2993 if (ret)
2994 goto out;
2995 /* no config file means nothing to rename, no error */
2996 goto commit_and_out;
2999 if (fstat(fileno(config_file), &st) == -1) {
3000 ret = error_errno(_("fstat on %s failed"), config_filename);
3001 goto out;
3004 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3005 ret = error_errno("chmod on %s failed",
3006 get_lock_file_path(&lock));
3007 goto out;
3010 while (fgets(buf, sizeof(buf), config_file)) {
3011 int i;
3012 int length;
3013 int is_section = 0;
3014 char *output = buf;
3015 for (i = 0; buf[i] && isspace(buf[i]); i++)
3016 ; /* do nothing */
3017 if (buf[i] == '[') {
3018 /* it's a section */
3019 int offset;
3020 is_section = 1;
3023 * When encountering a new section under -c we
3024 * need to flush out any section we're already
3025 * coping and begin anew. There might be
3026 * multiple [branch "$name"] sections.
3028 if (copystr.len > 0) {
3029 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3030 ret = write_error(get_lock_file_path(&lock));
3031 goto out;
3033 strbuf_reset(&copystr);
3036 offset = section_name_match(&buf[i], old_name);
3037 if (offset > 0) {
3038 ret++;
3039 if (new_name == NULL) {
3040 remove = 1;
3041 continue;
3043 store.baselen = strlen(new_name);
3044 if (!copy) {
3045 if (write_section(out_fd, new_name, &store) < 0) {
3046 ret = write_error(get_lock_file_path(&lock));
3047 goto out;
3050 * We wrote out the new section, with
3051 * a newline, now skip the old
3052 * section's length
3054 output += offset + i;
3055 if (strlen(output) > 0) {
3057 * More content means there's
3058 * a declaration to put on the
3059 * next line; indent with a
3060 * tab
3062 output -= 1;
3063 output[0] = '\t';
3065 } else {
3066 copystr = store_create_section(new_name, &store);
3069 remove = 0;
3071 if (remove)
3072 continue;
3073 length = strlen(output);
3075 if (!is_section && copystr.len > 0) {
3076 strbuf_add(&copystr, output, length);
3079 if (write_in_full(out_fd, output, length) < 0) {
3080 ret = write_error(get_lock_file_path(&lock));
3081 goto out;
3086 * Copy a trailing section at the end of the config, won't be
3087 * flushed by the usual "flush because we have a new section
3088 * logic in the loop above.
3090 if (copystr.len > 0) {
3091 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3092 ret = write_error(get_lock_file_path(&lock));
3093 goto out;
3095 strbuf_reset(&copystr);
3098 fclose(config_file);
3099 config_file = NULL;
3100 commit_and_out:
3101 if (commit_lock_file(&lock) < 0)
3102 ret = error_errno("could not write config file %s",
3103 config_filename);
3104 out:
3105 if (config_file)
3106 fclose(config_file);
3107 rollback_lock_file(&lock);
3108 out_no_rollback:
3109 free(filename_buf);
3110 return ret;
3113 int git_config_rename_section_in_file(const char *config_filename,
3114 const char *old_name, const char *new_name)
3116 return git_config_copy_or_rename_section_in_file(config_filename,
3117 old_name, new_name, 0);
3120 int git_config_rename_section(const char *old_name, const char *new_name)
3122 return git_config_rename_section_in_file(NULL, old_name, new_name);
3125 int git_config_copy_section_in_file(const char *config_filename,
3126 const char *old_name, const char *new_name)
3128 return git_config_copy_or_rename_section_in_file(config_filename,
3129 old_name, new_name, 1);
3132 int git_config_copy_section(const char *old_name, const char *new_name)
3134 return git_config_copy_section_in_file(NULL, old_name, new_name);
3138 * Call this to report error for your variable that should not
3139 * get a boolean value (i.e. "[my] var" means "true").
3141 #undef config_error_nonbool
3142 int config_error_nonbool(const char *var)
3144 return error("missing value for '%s'", var);
3147 int parse_config_key(const char *var,
3148 const char *section,
3149 const char **subsection, int *subsection_len,
3150 const char **key)
3152 const char *dot;
3154 /* Does it start with "section." ? */
3155 if (!skip_prefix(var, section, &var) || *var != '.')
3156 return -1;
3159 * Find the key; we don't know yet if we have a subsection, but we must
3160 * parse backwards from the end, since the subsection may have dots in
3161 * it, too.
3163 dot = strrchr(var, '.');
3164 *key = dot + 1;
3166 /* Did we have a subsection at all? */
3167 if (dot == var) {
3168 if (subsection) {
3169 *subsection = NULL;
3170 *subsection_len = 0;
3173 else {
3174 if (!subsection)
3175 return -1;
3176 *subsection = var + 1;
3177 *subsection_len = dot - *subsection;
3180 return 0;
3183 const char *current_config_origin_type(void)
3185 int type;
3186 if (current_config_kvi)
3187 type = current_config_kvi->origin_type;
3188 else if(cf)
3189 type = cf->origin_type;
3190 else
3191 die("BUG: current_config_origin_type called outside config callback");
3193 switch (type) {
3194 case CONFIG_ORIGIN_BLOB:
3195 return "blob";
3196 case CONFIG_ORIGIN_FILE:
3197 return "file";
3198 case CONFIG_ORIGIN_STDIN:
3199 return "standard input";
3200 case CONFIG_ORIGIN_SUBMODULE_BLOB:
3201 return "submodule-blob";
3202 case CONFIG_ORIGIN_CMDLINE:
3203 return "command line";
3204 default:
3205 die("BUG: unknown config origin type");
3209 const char *current_config_name(void)
3211 const char *name;
3212 if (current_config_kvi)
3213 name = current_config_kvi->filename;
3214 else if (cf)
3215 name = cf->name;
3216 else
3217 die("BUG: current_config_name called outside config callback");
3218 return name ? name : "";
3221 enum config_scope current_config_scope(void)
3223 if (current_config_kvi)
3224 return current_config_kvi->scope;
3225 else
3226 return current_parsing_scope;