config: make parsing stack struct independent from actual data source
[git/mingw.git] / config.c
blobfc2796771b689e85daf0a400488eeae3f7a48cd9
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 "exec_cmd.h"
10 #include "strbuf.h"
11 #include "quote.h"
13 struct config_source {
14 struct config_source *prev;
15 union {
16 FILE *file;
17 } u;
18 const char *name;
19 int linenr;
20 int eof;
21 struct strbuf value;
22 struct strbuf var;
24 int (*fgetc)(struct config_source *c);
25 int (*ungetc)(int c, struct config_source *conf);
26 long (*ftell)(struct config_source *c);
29 static struct config_source *cf;
31 static int zlib_compression_seen;
33 static int config_file_fgetc(struct config_source *conf)
35 return fgetc(conf->u.file);
38 static int config_file_ungetc(int c, struct config_source *conf)
40 return ungetc(c, conf->u.file);
43 static long config_file_ftell(struct config_source *conf)
45 return ftell(conf->u.file);
48 #define MAX_INCLUDE_DEPTH 10
49 static const char include_depth_advice[] =
50 "exceeded maximum include depth (%d) while including\n"
51 " %s\n"
52 "from\n"
53 " %s\n"
54 "Do you have circular includes?";
55 static int handle_path_include(const char *path, struct config_include_data *inc)
57 int ret = 0;
58 struct strbuf buf = STRBUF_INIT;
59 char *expanded = expand_user_path(path);
61 if (!expanded)
62 return error("Could not expand include path '%s'", path);
63 path = expanded;
66 * Use an absolute path as-is, but interpret relative paths
67 * based on the including config file.
69 if (!is_absolute_path(path)) {
70 char *slash;
72 if (!cf || !cf->name)
73 return error("relative config includes must come from files");
75 slash = find_last_dir_sep(cf->name);
76 if (slash)
77 strbuf_add(&buf, cf->name, slash - cf->name + 1);
78 strbuf_addstr(&buf, path);
79 path = buf.buf;
82 if (!access_or_die(path, R_OK)) {
83 if (++inc->depth > MAX_INCLUDE_DEPTH)
84 die(include_depth_advice, MAX_INCLUDE_DEPTH, path,
85 cf && cf->name ? cf->name : "the command line");
86 ret = git_config_from_file(git_config_include, path, inc);
87 inc->depth--;
89 strbuf_release(&buf);
90 free(expanded);
91 return ret;
94 int git_config_include(const char *var, const char *value, void *data)
96 struct config_include_data *inc = data;
97 const char *type;
98 int ret;
101 * Pass along all values, including "include" directives; this makes it
102 * possible to query information on the includes themselves.
104 ret = inc->fn(var, value, inc->data);
105 if (ret < 0)
106 return ret;
108 type = skip_prefix(var, "include.");
109 if (!type)
110 return ret;
112 if (!strcmp(type, "path"))
113 ret = handle_path_include(value, inc);
114 return ret;
117 static void lowercase(char *p)
119 for (; *p; p++)
120 *p = tolower(*p);
123 void git_config_push_parameter(const char *text)
125 struct strbuf env = STRBUF_INIT;
126 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
127 if (old) {
128 strbuf_addstr(&env, old);
129 strbuf_addch(&env, ' ');
131 sq_quote_buf(&env, text);
132 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
133 strbuf_release(&env);
136 int git_config_parse_parameter(const char *text,
137 config_fn_t fn, void *data)
139 struct strbuf **pair;
140 pair = strbuf_split_str(text, '=', 2);
141 if (!pair[0])
142 return error("bogus config parameter: %s", text);
143 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=')
144 strbuf_setlen(pair[0], pair[0]->len - 1);
145 strbuf_trim(pair[0]);
146 if (!pair[0]->len) {
147 strbuf_list_free(pair);
148 return error("bogus config parameter: %s", text);
150 lowercase(pair[0]->buf);
151 if (fn(pair[0]->buf, pair[1] ? pair[1]->buf : NULL, data) < 0) {
152 strbuf_list_free(pair);
153 return -1;
155 strbuf_list_free(pair);
156 return 0;
159 int git_config_from_parameters(config_fn_t fn, void *data)
161 const char *env = getenv(CONFIG_DATA_ENVIRONMENT);
162 char *envw;
163 const char **argv = NULL;
164 int nr = 0, alloc = 0;
165 int i;
167 if (!env)
168 return 0;
169 /* sq_dequote will write over it */
170 envw = xstrdup(env);
172 if (sq_dequote_to_argv(envw, &argv, &nr, &alloc) < 0) {
173 free(envw);
174 return error("bogus format in " CONFIG_DATA_ENVIRONMENT);
177 for (i = 0; i < nr; i++) {
178 if (git_config_parse_parameter(argv[i], fn, data) < 0) {
179 free(argv);
180 free(envw);
181 return -1;
185 free(argv);
186 free(envw);
187 return nr > 0;
190 static int get_next_char(void)
192 int c = cf->fgetc(cf);
194 if (c == '\r') {
195 /* DOS like systems */
196 c = cf->fgetc(cf);
197 if (c != '\n') {
198 cf->ungetc(c, cf);
199 c = '\r';
202 if (c == '\n')
203 cf->linenr++;
204 if (c == EOF) {
205 cf->eof = 1;
206 c = '\n';
208 return c;
211 static char *parse_value(void)
213 int quote = 0, comment = 0, space = 0;
215 strbuf_reset(&cf->value);
216 for (;;) {
217 int c = get_next_char();
218 if (c == '\n') {
219 if (quote) {
220 cf->linenr--;
221 return NULL;
223 return cf->value.buf;
225 if (comment)
226 continue;
227 if (isspace(c) && !quote) {
228 if (cf->value.len)
229 space++;
230 continue;
232 if (!quote) {
233 if (c == ';' || c == '#') {
234 comment = 1;
235 continue;
238 for (; space; space--)
239 strbuf_addch(&cf->value, ' ');
240 if (c == '\\') {
241 c = get_next_char();
242 switch (c) {
243 case '\n':
244 continue;
245 case 't':
246 c = '\t';
247 break;
248 case 'b':
249 c = '\b';
250 break;
251 case 'n':
252 c = '\n';
253 break;
254 /* Some characters escape as themselves */
255 case '\\': case '"':
256 break;
257 /* Reject unknown escape sequences */
258 default:
259 return NULL;
261 strbuf_addch(&cf->value, c);
262 continue;
264 if (c == '"') {
265 quote = 1-quote;
266 continue;
268 strbuf_addch(&cf->value, c);
272 static inline int iskeychar(int c)
274 return isalnum(c) || c == '-';
277 static int get_value(config_fn_t fn, void *data, struct strbuf *name)
279 int c;
280 char *value;
282 /* Get the full name */
283 for (;;) {
284 c = get_next_char();
285 if (cf->eof)
286 break;
287 if (!iskeychar(c))
288 break;
289 strbuf_addch(name, tolower(c));
292 while (c == ' ' || c == '\t')
293 c = get_next_char();
295 value = NULL;
296 if (c != '\n') {
297 if (c != '=')
298 return -1;
299 value = parse_value();
300 if (!value)
301 return -1;
303 return fn(name->buf, value, data);
306 static int get_extended_base_var(struct strbuf *name, int c)
308 do {
309 if (c == '\n')
310 goto error_incomplete_line;
311 c = get_next_char();
312 } while (isspace(c));
314 /* We require the format to be '[base "extension"]' */
315 if (c != '"')
316 return -1;
317 strbuf_addch(name, '.');
319 for (;;) {
320 int c = get_next_char();
321 if (c == '\n')
322 goto error_incomplete_line;
323 if (c == '"')
324 break;
325 if (c == '\\') {
326 c = get_next_char();
327 if (c == '\n')
328 goto error_incomplete_line;
330 strbuf_addch(name, c);
333 /* Final ']' */
334 if (get_next_char() != ']')
335 return -1;
336 return 0;
337 error_incomplete_line:
338 cf->linenr--;
339 return -1;
342 static int get_base_var(struct strbuf *name)
344 for (;;) {
345 int c = get_next_char();
346 if (cf->eof)
347 return -1;
348 if (c == ']')
349 return 0;
350 if (isspace(c))
351 return get_extended_base_var(name, c);
352 if (!iskeychar(c) && c != '.')
353 return -1;
354 strbuf_addch(name, tolower(c));
358 static int git_parse_source(config_fn_t fn, void *data)
360 int comment = 0;
361 int baselen = 0;
362 struct strbuf *var = &cf->var;
364 /* U+FEFF Byte Order Mark in UTF8 */
365 static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
366 const unsigned char *bomptr = utf8_bom;
368 for (;;) {
369 int c = get_next_char();
370 if (bomptr && *bomptr) {
371 /* We are at the file beginning; skip UTF8-encoded BOM
372 * if present. Sane editors won't put this in on their
373 * own, but e.g. Windows Notepad will do it happily. */
374 if ((unsigned char) c == *bomptr) {
375 bomptr++;
376 continue;
377 } else {
378 /* Do not tolerate partial BOM. */
379 if (bomptr != utf8_bom)
380 break;
381 /* No BOM at file beginning. Cool. */
382 bomptr = NULL;
385 if (c == '\n') {
386 if (cf->eof)
387 return 0;
388 comment = 0;
389 continue;
391 if (comment || isspace(c))
392 continue;
393 if (c == '#' || c == ';') {
394 comment = 1;
395 continue;
397 if (c == '[') {
398 /* Reset prior to determining a new stem */
399 strbuf_reset(var);
400 if (get_base_var(var) < 0 || var->len < 1)
401 break;
402 strbuf_addch(var, '.');
403 baselen = var->len;
404 continue;
406 if (!isalpha(c))
407 break;
409 * Truncate the var name back to the section header
410 * stem prior to grabbing the suffix part of the name
411 * and the value.
413 strbuf_setlen(var, baselen);
414 strbuf_addch(var, tolower(c));
415 if (get_value(fn, data, var) < 0)
416 break;
418 die("bad config file line %d in %s", cf->linenr, cf->name);
421 static int parse_unit_factor(const char *end, uintmax_t *val)
423 if (!*end)
424 return 1;
425 else if (!strcasecmp(end, "k")) {
426 *val *= 1024;
427 return 1;
429 else if (!strcasecmp(end, "m")) {
430 *val *= 1024 * 1024;
431 return 1;
433 else if (!strcasecmp(end, "g")) {
434 *val *= 1024 * 1024 * 1024;
435 return 1;
437 return 0;
440 static int git_parse_long(const char *value, long *ret)
442 if (value && *value) {
443 char *end;
444 intmax_t val;
445 uintmax_t uval;
446 uintmax_t factor = 1;
448 errno = 0;
449 val = strtoimax(value, &end, 0);
450 if (errno == ERANGE)
451 return 0;
452 if (!parse_unit_factor(end, &factor))
453 return 0;
454 uval = abs(val);
455 uval *= factor;
456 if ((uval > maximum_signed_value_of_type(long)) ||
457 (abs(val) > uval))
458 return 0;
459 val *= factor;
460 *ret = val;
461 return 1;
463 return 0;
466 int git_parse_ulong(const char *value, unsigned long *ret)
468 if (value && *value) {
469 char *end;
470 uintmax_t val;
471 uintmax_t oldval;
473 errno = 0;
474 val = strtoumax(value, &end, 0);
475 if (errno == ERANGE)
476 return 0;
477 oldval = val;
478 if (!parse_unit_factor(end, &val))
479 return 0;
480 if ((val > maximum_unsigned_value_of_type(long)) ||
481 (oldval > val))
482 return 0;
483 *ret = val;
484 return 1;
486 return 0;
489 static void die_bad_config(const char *name)
491 if (cf && cf->name)
492 die("bad config value for '%s' in %s", name, cf->name);
493 die("bad config value for '%s'", name);
496 int git_config_int(const char *name, const char *value)
498 long ret = 0;
499 if (!git_parse_long(value, &ret))
500 die_bad_config(name);
501 return ret;
504 unsigned long git_config_ulong(const char *name, const char *value)
506 unsigned long ret;
507 if (!git_parse_ulong(value, &ret))
508 die_bad_config(name);
509 return ret;
512 static int git_config_maybe_bool_text(const char *name, const char *value)
514 if (!value)
515 return 1;
516 if (!*value)
517 return 0;
518 if (!strcasecmp(value, "true")
519 || !strcasecmp(value, "yes")
520 || !strcasecmp(value, "on"))
521 return 1;
522 if (!strcasecmp(value, "false")
523 || !strcasecmp(value, "no")
524 || !strcasecmp(value, "off"))
525 return 0;
526 return -1;
529 int git_config_maybe_bool(const char *name, const char *value)
531 long v = git_config_maybe_bool_text(name, value);
532 if (0 <= v)
533 return v;
534 if (git_parse_long(value, &v))
535 return !!v;
536 return -1;
539 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
541 int v = git_config_maybe_bool_text(name, value);
542 if (0 <= v) {
543 *is_bool = 1;
544 return v;
546 *is_bool = 0;
547 return git_config_int(name, value);
550 int git_config_bool(const char *name, const char *value)
552 int discard;
553 return !!git_config_bool_or_int(name, value, &discard);
556 int git_config_string(const char **dest, const char *var, const char *value)
558 if (!value)
559 return config_error_nonbool(var);
560 *dest = xstrdup(value);
561 return 0;
564 int git_config_pathname(const char **dest, const char *var, const char *value)
566 if (!value)
567 return config_error_nonbool(var);
568 *dest = expand_user_path(value);
569 if (!*dest)
570 die("Failed to expand user dir in: '%s'", value);
571 return 0;
574 static int git_default_core_config(const char *var, const char *value)
576 /* This needs a better name */
577 if (!strcmp(var, "core.filemode")) {
578 trust_executable_bit = git_config_bool(var, value);
579 return 0;
581 if (!strcmp(var, "core.trustctime")) {
582 trust_ctime = git_config_bool(var, value);
583 return 0;
585 if (!strcmp(var, "core.statinfo")) {
586 if (!strcasecmp(value, "default"))
587 check_stat = 1;
588 else if (!strcasecmp(value, "minimal"))
589 check_stat = 0;
592 if (!strcmp(var, "core.quotepath")) {
593 quote_path_fully = git_config_bool(var, value);
594 return 0;
597 if (!strcmp(var, "core.symlinks")) {
598 has_symlinks = git_config_bool(var, value);
599 return 0;
602 if (!strcmp(var, "core.ignorecase")) {
603 ignore_case = git_config_bool(var, value);
604 return 0;
607 if (!strcmp(var, "core.attributesfile"))
608 return git_config_pathname(&git_attributes_file, var, value);
610 if (!strcmp(var, "core.bare")) {
611 is_bare_repository_cfg = git_config_bool(var, value);
612 return 0;
615 if (!strcmp(var, "core.ignorestat")) {
616 assume_unchanged = git_config_bool(var, value);
617 return 0;
620 if (!strcmp(var, "core.prefersymlinkrefs")) {
621 prefer_symlink_refs = git_config_bool(var, value);
622 return 0;
625 if (!strcmp(var, "core.logallrefupdates")) {
626 log_all_ref_updates = git_config_bool(var, value);
627 return 0;
630 if (!strcmp(var, "core.warnambiguousrefs")) {
631 warn_ambiguous_refs = git_config_bool(var, value);
632 return 0;
635 if (!strcmp(var, "core.abbrev")) {
636 int abbrev = git_config_int(var, value);
637 if (abbrev < minimum_abbrev || abbrev > 40)
638 return -1;
639 default_abbrev = abbrev;
640 return 0;
643 if (!strcmp(var, "core.loosecompression")) {
644 int level = git_config_int(var, value);
645 if (level == -1)
646 level = Z_DEFAULT_COMPRESSION;
647 else if (level < 0 || level > Z_BEST_COMPRESSION)
648 die("bad zlib compression level %d", level);
649 zlib_compression_level = level;
650 zlib_compression_seen = 1;
651 return 0;
654 if (!strcmp(var, "core.compression")) {
655 int level = git_config_int(var, value);
656 if (level == -1)
657 level = Z_DEFAULT_COMPRESSION;
658 else if (level < 0 || level > Z_BEST_COMPRESSION)
659 die("bad zlib compression level %d", level);
660 core_compression_level = level;
661 core_compression_seen = 1;
662 if (!zlib_compression_seen)
663 zlib_compression_level = level;
664 return 0;
667 if (!strcmp(var, "core.packedgitwindowsize")) {
668 int pgsz_x2 = getpagesize() * 2;
669 packed_git_window_size = git_config_ulong(var, value);
671 /* This value must be multiple of (pagesize * 2) */
672 packed_git_window_size /= pgsz_x2;
673 if (packed_git_window_size < 1)
674 packed_git_window_size = 1;
675 packed_git_window_size *= pgsz_x2;
676 return 0;
679 if (!strcmp(var, "core.bigfilethreshold")) {
680 big_file_threshold = git_config_ulong(var, value);
681 return 0;
684 if (!strcmp(var, "core.packedgitlimit")) {
685 packed_git_limit = git_config_ulong(var, value);
686 return 0;
689 if (!strcmp(var, "core.deltabasecachelimit")) {
690 delta_base_cache_limit = git_config_ulong(var, value);
691 return 0;
694 if (!strcmp(var, "core.logpackaccess"))
695 return git_config_string(&log_pack_access, var, value);
697 if (!strcmp(var, "core.autocrlf")) {
698 if (value && !strcasecmp(value, "input")) {
699 if (core_eol == EOL_CRLF)
700 return error("core.autocrlf=input conflicts with core.eol=crlf");
701 auto_crlf = AUTO_CRLF_INPUT;
702 return 0;
704 auto_crlf = git_config_bool(var, value);
705 return 0;
708 if (!strcmp(var, "core.safecrlf")) {
709 if (value && !strcasecmp(value, "warn")) {
710 safe_crlf = SAFE_CRLF_WARN;
711 return 0;
713 safe_crlf = git_config_bool(var, value);
714 return 0;
717 if (!strcmp(var, "core.eol")) {
718 if (value && !strcasecmp(value, "lf"))
719 core_eol = EOL_LF;
720 else if (value && !strcasecmp(value, "crlf"))
721 core_eol = EOL_CRLF;
722 else if (value && !strcasecmp(value, "native"))
723 core_eol = EOL_NATIVE;
724 else
725 core_eol = EOL_UNSET;
726 if (core_eol == EOL_CRLF && auto_crlf == AUTO_CRLF_INPUT)
727 return error("core.autocrlf=input conflicts with core.eol=crlf");
728 return 0;
731 if (!strcmp(var, "core.notesref")) {
732 notes_ref_name = xstrdup(value);
733 return 0;
736 if (!strcmp(var, "core.pager"))
737 return git_config_string(&pager_program, var, value);
739 if (!strcmp(var, "core.editor"))
740 return git_config_string(&editor_program, var, value);
742 if (!strcmp(var, "core.commentchar")) {
743 const char *comment;
744 int ret = git_config_string(&comment, var, value);
745 if (!ret)
746 comment_line_char = comment[0];
747 return ret;
750 if (!strcmp(var, "core.askpass"))
751 return git_config_string(&askpass_program, var, value);
753 if (!strcmp(var, "core.excludesfile"))
754 return git_config_pathname(&excludes_file, var, value);
756 if (!strcmp(var, "core.whitespace")) {
757 if (!value)
758 return config_error_nonbool(var);
759 whitespace_rule_cfg = parse_whitespace_rule(value);
760 return 0;
763 if (!strcmp(var, "core.fsyncobjectfiles")) {
764 fsync_object_files = git_config_bool(var, value);
765 return 0;
768 if (!strcmp(var, "core.preloadindex")) {
769 core_preload_index = git_config_bool(var, value);
770 return 0;
773 if (!strcmp(var, "core.createobject")) {
774 if (!strcmp(value, "rename"))
775 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
776 else if (!strcmp(value, "link"))
777 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
778 else
779 die("Invalid mode for object creation: %s", value);
780 return 0;
783 if (!strcmp(var, "core.sparsecheckout")) {
784 core_apply_sparse_checkout = git_config_bool(var, value);
785 return 0;
788 if (!strcmp(var, "core.precomposeunicode")) {
789 precomposed_unicode = git_config_bool(var, value);
790 return 0;
793 /* Add other config variables here and to Documentation/config.txt. */
794 return 0;
797 static int git_default_i18n_config(const char *var, const char *value)
799 if (!strcmp(var, "i18n.commitencoding"))
800 return git_config_string(&git_commit_encoding, var, value);
802 if (!strcmp(var, "i18n.logoutputencoding"))
803 return git_config_string(&git_log_output_encoding, var, value);
805 /* Add other config variables here and to Documentation/config.txt. */
806 return 0;
809 static int git_default_branch_config(const char *var, const char *value)
811 if (!strcmp(var, "branch.autosetupmerge")) {
812 if (value && !strcasecmp(value, "always")) {
813 git_branch_track = BRANCH_TRACK_ALWAYS;
814 return 0;
816 git_branch_track = git_config_bool(var, value);
817 return 0;
819 if (!strcmp(var, "branch.autosetuprebase")) {
820 if (!value)
821 return config_error_nonbool(var);
822 else if (!strcmp(value, "never"))
823 autorebase = AUTOREBASE_NEVER;
824 else if (!strcmp(value, "local"))
825 autorebase = AUTOREBASE_LOCAL;
826 else if (!strcmp(value, "remote"))
827 autorebase = AUTOREBASE_REMOTE;
828 else if (!strcmp(value, "always"))
829 autorebase = AUTOREBASE_ALWAYS;
830 else
831 return error("Malformed value for %s", var);
832 return 0;
835 /* Add other config variables here and to Documentation/config.txt. */
836 return 0;
839 static int git_default_push_config(const char *var, const char *value)
841 if (!strcmp(var, "push.default")) {
842 if (!value)
843 return config_error_nonbool(var);
844 else if (!strcmp(value, "nothing"))
845 push_default = PUSH_DEFAULT_NOTHING;
846 else if (!strcmp(value, "matching"))
847 push_default = PUSH_DEFAULT_MATCHING;
848 else if (!strcmp(value, "simple"))
849 push_default = PUSH_DEFAULT_SIMPLE;
850 else if (!strcmp(value, "upstream"))
851 push_default = PUSH_DEFAULT_UPSTREAM;
852 else if (!strcmp(value, "tracking")) /* deprecated */
853 push_default = PUSH_DEFAULT_UPSTREAM;
854 else if (!strcmp(value, "current"))
855 push_default = PUSH_DEFAULT_CURRENT;
856 else {
857 error("Malformed value for %s: %s", var, value);
858 return error("Must be one of nothing, matching, simple, "
859 "upstream or current.");
861 return 0;
864 /* Add other config variables here and to Documentation/config.txt. */
865 return 0;
868 static int git_default_mailmap_config(const char *var, const char *value)
870 if (!strcmp(var, "mailmap.file"))
871 return git_config_string(&git_mailmap_file, var, value);
872 if (!strcmp(var, "mailmap.blob"))
873 return git_config_string(&git_mailmap_blob, var, value);
875 /* Add other config variables here and to Documentation/config.txt. */
876 return 0;
879 int git_default_config(const char *var, const char *value, void *dummy)
881 if (!prefixcmp(var, "core."))
882 return git_default_core_config(var, value);
884 if (!prefixcmp(var, "user."))
885 return git_ident_config(var, value, dummy);
887 if (!prefixcmp(var, "i18n."))
888 return git_default_i18n_config(var, value);
890 if (!prefixcmp(var, "branch."))
891 return git_default_branch_config(var, value);
893 if (!prefixcmp(var, "push."))
894 return git_default_push_config(var, value);
896 if (!prefixcmp(var, "mailmap."))
897 return git_default_mailmap_config(var, value);
899 if (!prefixcmp(var, "advice."))
900 return git_default_advice_config(var, value);
902 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
903 pager_use_color = git_config_bool(var,value);
904 return 0;
907 if (!strcmp(var, "pack.packsizelimit")) {
908 pack_size_limit_cfg = git_config_ulong(var, value);
909 return 0;
911 /* Add other config variables here and to Documentation/config.txt. */
912 return 0;
916 * All source specific fields in the union, name and the callbacks
917 * fgetc, ungetc, ftell of top need to be initialized before calling
918 * this function.
920 static int do_config_from(struct config_source *top, config_fn_t fn, void *data)
922 int ret;
924 /* push config-file parsing state stack */
925 top->prev = cf;
926 top->linenr = 1;
927 top->eof = 0;
928 strbuf_init(&top->value, 1024);
929 strbuf_init(&top->var, 1024);
930 cf = top;
932 ret = git_parse_source(fn, data);
934 /* pop config-file parsing state stack */
935 strbuf_release(&top->value);
936 strbuf_release(&top->var);
937 cf = top->prev;
939 return ret;
942 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
944 int ret;
945 FILE *f = fopen(filename, "r");
947 ret = -1;
948 if (f) {
949 struct config_source top;
951 top.u.file = f;
952 top.name = filename;
953 top.fgetc = config_file_fgetc;
954 top.ungetc = config_file_ungetc;
955 top.ftell = config_file_ftell;
957 ret = do_config_from(&top, fn, data);
959 fclose(f);
961 return ret;
964 const char *git_etc_gitconfig(void)
966 static const char *system_wide;
967 if (!system_wide)
968 system_wide = system_path(ETC_GITCONFIG);
969 return system_wide;
972 int git_env_bool(const char *k, int def)
974 const char *v = getenv(k);
975 return v ? git_config_bool(k, v) : def;
978 int git_config_system(void)
980 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
983 int git_config_early(config_fn_t fn, void *data, const char *repo_config)
985 int ret = 0, found = 0;
986 char *xdg_config = NULL;
987 char *user_config = NULL;
989 home_config_paths(&user_config, &xdg_config, "config");
991 if (git_config_system() && !access_or_die(git_etc_gitconfig(), R_OK)) {
992 ret += git_config_from_file(fn, git_etc_gitconfig(),
993 data);
994 found += 1;
997 if (xdg_config && !access_or_die(xdg_config, R_OK)) {
998 ret += git_config_from_file(fn, xdg_config, data);
999 found += 1;
1002 if (user_config && !access_or_die(user_config, R_OK)) {
1003 ret += git_config_from_file(fn, user_config, data);
1004 found += 1;
1007 if (repo_config && !access_or_die(repo_config, R_OK)) {
1008 ret += git_config_from_file(fn, repo_config, data);
1009 found += 1;
1012 switch (git_config_from_parameters(fn, data)) {
1013 case -1: /* error */
1014 die("unable to parse command-line config");
1015 break;
1016 case 0: /* found nothing */
1017 break;
1018 default: /* found at least one item */
1019 found++;
1020 break;
1023 free(xdg_config);
1024 free(user_config);
1025 return ret == 0 ? found : ret;
1028 int git_config_with_options(config_fn_t fn, void *data,
1029 const char *filename, int respect_includes)
1031 char *repo_config = NULL;
1032 int ret;
1033 struct config_include_data inc = CONFIG_INCLUDE_INIT;
1035 if (respect_includes) {
1036 inc.fn = fn;
1037 inc.data = data;
1038 fn = git_config_include;
1039 data = &inc;
1043 * If we have a specific filename, use it. Otherwise, follow the
1044 * regular lookup sequence.
1046 if (filename)
1047 return git_config_from_file(fn, filename, data);
1049 repo_config = git_pathdup("config");
1050 ret = git_config_early(fn, data, repo_config);
1051 if (repo_config)
1052 free(repo_config);
1053 return ret;
1056 int git_config(config_fn_t fn, void *data)
1058 return git_config_with_options(fn, data, NULL, 1);
1062 * Find all the stuff for git_config_set() below.
1065 #define MAX_MATCHES 512
1067 static struct {
1068 int baselen;
1069 char *key;
1070 int do_not_match;
1071 regex_t *value_regex;
1072 int multi_replace;
1073 size_t offset[MAX_MATCHES];
1074 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
1075 int seen;
1076 } store;
1078 static int matches(const char *key, const char *value)
1080 return !strcmp(key, store.key) &&
1081 (store.value_regex == NULL ||
1082 (store.do_not_match ^
1083 !regexec(store.value_regex, value, 0, NULL, 0)));
1086 static int store_aux(const char *key, const char *value, void *cb)
1088 const char *ep;
1089 size_t section_len;
1091 switch (store.state) {
1092 case KEY_SEEN:
1093 if (matches(key, value)) {
1094 if (store.seen == 1 && store.multi_replace == 0) {
1095 warning("%s has multiple values", key);
1096 } else if (store.seen >= MAX_MATCHES) {
1097 error("too many matches for %s", key);
1098 return 1;
1101 store.offset[store.seen] = cf->ftell(cf);
1102 store.seen++;
1104 break;
1105 case SECTION_SEEN:
1107 * What we are looking for is in store.key (both
1108 * section and var), and its section part is baselen
1109 * long. We found key (again, both section and var).
1110 * We would want to know if this key is in the same
1111 * section as what we are looking for. We already
1112 * know we are in the same section as what should
1113 * hold store.key.
1115 ep = strrchr(key, '.');
1116 section_len = ep - key;
1118 if ((section_len != store.baselen) ||
1119 memcmp(key, store.key, section_len+1)) {
1120 store.state = SECTION_END_SEEN;
1121 break;
1125 * Do not increment matches: this is no match, but we
1126 * just made sure we are in the desired section.
1128 store.offset[store.seen] = cf->ftell(cf);
1129 /* fallthru */
1130 case SECTION_END_SEEN:
1131 case START:
1132 if (matches(key, value)) {
1133 store.offset[store.seen] = cf->ftell(cf);
1134 store.state = KEY_SEEN;
1135 store.seen++;
1136 } else {
1137 if (strrchr(key, '.') - key == store.baselen &&
1138 !strncmp(key, store.key, store.baselen)) {
1139 store.state = SECTION_SEEN;
1140 store.offset[store.seen] = cf->ftell(cf);
1144 return 0;
1147 static int write_error(const char *filename)
1149 error("failed to write new configuration file %s", filename);
1151 /* Same error code as "failed to rename". */
1152 return 4;
1155 static int store_write_section(int fd, const char *key)
1157 const char *dot;
1158 int i, success;
1159 struct strbuf sb = STRBUF_INIT;
1161 dot = memchr(key, '.', store.baselen);
1162 if (dot) {
1163 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
1164 for (i = dot - key + 1; i < store.baselen; i++) {
1165 if (key[i] == '"' || key[i] == '\\')
1166 strbuf_addch(&sb, '\\');
1167 strbuf_addch(&sb, key[i]);
1169 strbuf_addstr(&sb, "\"]\n");
1170 } else {
1171 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
1174 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1175 strbuf_release(&sb);
1177 return success;
1180 static int store_write_pair(int fd, const char *key, const char *value)
1182 int i, success;
1183 int length = strlen(key + store.baselen + 1);
1184 const char *quote = "";
1185 struct strbuf sb = STRBUF_INIT;
1188 * Check to see if the value needs to be surrounded with a dq pair.
1189 * Note that problematic characters are always backslash-quoted; this
1190 * check is about not losing leading or trailing SP and strings that
1191 * follow beginning-of-comment characters (i.e. ';' and '#') by the
1192 * configuration parser.
1194 if (value[0] == ' ')
1195 quote = "\"";
1196 for (i = 0; value[i]; i++)
1197 if (value[i] == ';' || value[i] == '#')
1198 quote = "\"";
1199 if (i && value[i - 1] == ' ')
1200 quote = "\"";
1202 strbuf_addf(&sb, "\t%.*s = %s",
1203 length, key + store.baselen + 1, quote);
1205 for (i = 0; value[i]; i++)
1206 switch (value[i]) {
1207 case '\n':
1208 strbuf_addstr(&sb, "\\n");
1209 break;
1210 case '\t':
1211 strbuf_addstr(&sb, "\\t");
1212 break;
1213 case '"':
1214 case '\\':
1215 strbuf_addch(&sb, '\\');
1216 default:
1217 strbuf_addch(&sb, value[i]);
1218 break;
1220 strbuf_addf(&sb, "%s\n", quote);
1222 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1223 strbuf_release(&sb);
1225 return success;
1228 static ssize_t find_beginning_of_line(const char *contents, size_t size,
1229 size_t offset_, int *found_bracket)
1231 size_t equal_offset = size, bracket_offset = size;
1232 ssize_t offset;
1234 contline:
1235 for (offset = offset_-2; offset > 0
1236 && contents[offset] != '\n'; offset--)
1237 switch (contents[offset]) {
1238 case '=': equal_offset = offset; break;
1239 case ']': bracket_offset = offset; break;
1241 if (offset > 0 && contents[offset-1] == '\\') {
1242 offset_ = offset;
1243 goto contline;
1245 if (bracket_offset < equal_offset) {
1246 *found_bracket = 1;
1247 offset = bracket_offset+1;
1248 } else
1249 offset++;
1251 return offset;
1254 int git_config_set_in_file(const char *config_filename,
1255 const char *key, const char *value)
1257 return git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
1260 int git_config_set(const char *key, const char *value)
1262 return git_config_set_multivar(key, value, NULL, 0);
1266 * Auxiliary function to sanity-check and split the key into the section
1267 * identifier and variable name.
1269 * Returns 0 on success, -1 when there is an invalid character in the key and
1270 * -2 if there is no section name in the key.
1272 * store_key - pointer to char* which will hold a copy of the key with
1273 * lowercase section and variable name
1274 * baselen - pointer to int which will hold the length of the
1275 * section + subsection part, can be NULL
1277 int git_config_parse_key(const char *key, char **store_key, int *baselen_)
1279 int i, dot, baselen;
1280 const char *last_dot = strrchr(key, '.');
1283 * Since "key" actually contains the section name and the real
1284 * key name separated by a dot, we have to know where the dot is.
1287 if (last_dot == NULL || last_dot == key) {
1288 error("key does not contain a section: %s", key);
1289 return -CONFIG_NO_SECTION_OR_NAME;
1292 if (!last_dot[1]) {
1293 error("key does not contain variable name: %s", key);
1294 return -CONFIG_NO_SECTION_OR_NAME;
1297 baselen = last_dot - key;
1298 if (baselen_)
1299 *baselen_ = baselen;
1302 * Validate the key and while at it, lower case it for matching.
1304 *store_key = xmalloc(strlen(key) + 1);
1306 dot = 0;
1307 for (i = 0; key[i]; i++) {
1308 unsigned char c = key[i];
1309 if (c == '.')
1310 dot = 1;
1311 /* Leave the extended basename untouched.. */
1312 if (!dot || i > baselen) {
1313 if (!iskeychar(c) ||
1314 (i == baselen + 1 && !isalpha(c))) {
1315 error("invalid key: %s", key);
1316 goto out_free_ret_1;
1318 c = tolower(c);
1319 } else if (c == '\n') {
1320 error("invalid key (newline): %s", key);
1321 goto out_free_ret_1;
1323 (*store_key)[i] = c;
1325 (*store_key)[i] = 0;
1327 return 0;
1329 out_free_ret_1:
1330 free(*store_key);
1331 *store_key = NULL;
1332 return -CONFIG_INVALID_KEY;
1336 * If value==NULL, unset in (remove from) config,
1337 * if value_regex!=NULL, disregard key/value pairs where value does not match.
1338 * if multi_replace==0, nothing, or only one matching key/value is replaced,
1339 * else all matching key/values (regardless how many) are removed,
1340 * before the new pair is written.
1342 * Returns 0 on success.
1344 * This function does this:
1346 * - it locks the config file by creating ".git/config.lock"
1348 * - it then parses the config using store_aux() as validator to find
1349 * the position on the key/value pair to replace. If it is to be unset,
1350 * it must be found exactly once.
1352 * - the config file is mmap()ed and the part before the match (if any) is
1353 * written to the lock file, then the changed part and the rest.
1355 * - the config file is removed and the lock file rename()d to it.
1358 int git_config_set_multivar_in_file(const char *config_filename,
1359 const char *key, const char *value,
1360 const char *value_regex, int multi_replace)
1362 int fd = -1, in_fd;
1363 int ret;
1364 struct lock_file *lock = NULL;
1365 char *filename_buf = NULL;
1367 /* parse-key returns negative; flip the sign to feed exit(3) */
1368 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
1369 if (ret)
1370 goto out_free;
1372 store.multi_replace = multi_replace;
1374 if (!config_filename)
1375 config_filename = filename_buf = git_pathdup("config");
1378 * The lock serves a purpose in addition to locking: the new
1379 * contents of .git/config will be written into it.
1381 lock = xcalloc(sizeof(struct lock_file), 1);
1382 fd = hold_lock_file_for_update(lock, config_filename, 0);
1383 if (fd < 0) {
1384 error("could not lock config file %s: %s", config_filename, strerror(errno));
1385 free(store.key);
1386 ret = CONFIG_NO_LOCK;
1387 goto out_free;
1391 * If .git/config does not exist yet, write a minimal version.
1393 in_fd = open(config_filename, O_RDONLY);
1394 if ( in_fd < 0 ) {
1395 free(store.key);
1397 if ( ENOENT != errno ) {
1398 error("opening %s: %s", config_filename,
1399 strerror(errno));
1400 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
1401 goto out_free;
1403 /* if nothing to unset, error out */
1404 if (value == NULL) {
1405 ret = CONFIG_NOTHING_SET;
1406 goto out_free;
1409 store.key = (char *)key;
1410 if (!store_write_section(fd, key) ||
1411 !store_write_pair(fd, key, value))
1412 goto write_err_out;
1413 } else {
1414 struct stat st;
1415 char *contents;
1416 size_t contents_sz, copy_begin, copy_end;
1417 int i, new_line = 0;
1419 if (value_regex == NULL)
1420 store.value_regex = NULL;
1421 else {
1422 if (value_regex[0] == '!') {
1423 store.do_not_match = 1;
1424 value_regex++;
1425 } else
1426 store.do_not_match = 0;
1428 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1429 if (regcomp(store.value_regex, value_regex,
1430 REG_EXTENDED)) {
1431 error("invalid pattern: %s", value_regex);
1432 free(store.value_regex);
1433 ret = CONFIG_INVALID_PATTERN;
1434 goto out_free;
1438 store.offset[0] = 0;
1439 store.state = START;
1440 store.seen = 0;
1443 * After this, store.offset will contain the *end* offset
1444 * of the last match, or remain at 0 if no match was found.
1445 * As a side effect, we make sure to transform only a valid
1446 * existing config file.
1448 if (git_config_from_file(store_aux, config_filename, NULL)) {
1449 error("invalid config file %s", config_filename);
1450 free(store.key);
1451 if (store.value_regex != NULL) {
1452 regfree(store.value_regex);
1453 free(store.value_regex);
1455 ret = CONFIG_INVALID_FILE;
1456 goto out_free;
1459 free(store.key);
1460 if (store.value_regex != NULL) {
1461 regfree(store.value_regex);
1462 free(store.value_regex);
1465 /* if nothing to unset, or too many matches, error out */
1466 if ((store.seen == 0 && value == NULL) ||
1467 (store.seen > 1 && multi_replace == 0)) {
1468 ret = CONFIG_NOTHING_SET;
1469 goto out_free;
1472 fstat(in_fd, &st);
1473 contents_sz = xsize_t(st.st_size);
1474 contents = xmmap(NULL, contents_sz, PROT_READ,
1475 MAP_PRIVATE, in_fd, 0);
1476 close(in_fd);
1478 if (store.seen == 0)
1479 store.seen = 1;
1481 for (i = 0, copy_begin = 0; i < store.seen; i++) {
1482 if (store.offset[i] == 0) {
1483 store.offset[i] = copy_end = contents_sz;
1484 } else if (store.state != KEY_SEEN) {
1485 copy_end = store.offset[i];
1486 } else
1487 copy_end = find_beginning_of_line(
1488 contents, contents_sz,
1489 store.offset[i]-2, &new_line);
1491 if (copy_end > 0 && contents[copy_end-1] != '\n')
1492 new_line = 1;
1494 /* write the first part of the config */
1495 if (copy_end > copy_begin) {
1496 if (write_in_full(fd, contents + copy_begin,
1497 copy_end - copy_begin) <
1498 copy_end - copy_begin)
1499 goto write_err_out;
1500 if (new_line &&
1501 write_str_in_full(fd, "\n") != 1)
1502 goto write_err_out;
1504 copy_begin = store.offset[i];
1507 /* write the pair (value == NULL means unset) */
1508 if (value != NULL) {
1509 if (store.state == START) {
1510 if (!store_write_section(fd, key))
1511 goto write_err_out;
1513 if (!store_write_pair(fd, key, value))
1514 goto write_err_out;
1517 /* write the rest of the config */
1518 if (copy_begin < contents_sz)
1519 if (write_in_full(fd, contents + copy_begin,
1520 contents_sz - copy_begin) <
1521 contents_sz - copy_begin)
1522 goto write_err_out;
1524 munmap(contents, contents_sz);
1527 if (commit_lock_file(lock) < 0) {
1528 error("could not commit config file %s", config_filename);
1529 ret = CONFIG_NO_WRITE;
1530 goto out_free;
1534 * lock is committed, so don't try to roll it back below.
1535 * NOTE: Since lockfile.c keeps a linked list of all created
1536 * lock_file structures, it isn't safe to free(lock). It's
1537 * better to just leave it hanging around.
1539 lock = NULL;
1540 ret = 0;
1542 out_free:
1543 if (lock)
1544 rollback_lock_file(lock);
1545 free(filename_buf);
1546 return ret;
1548 write_err_out:
1549 ret = write_error(lock->filename);
1550 goto out_free;
1554 int git_config_set_multivar(const char *key, const char *value,
1555 const char *value_regex, int multi_replace)
1557 return git_config_set_multivar_in_file(NULL, key, value, value_regex,
1558 multi_replace);
1561 static int section_name_match (const char *buf, const char *name)
1563 int i = 0, j = 0, dot = 0;
1564 if (buf[i] != '[')
1565 return 0;
1566 for (i = 1; buf[i] && buf[i] != ']'; i++) {
1567 if (!dot && isspace(buf[i])) {
1568 dot = 1;
1569 if (name[j++] != '.')
1570 break;
1571 for (i++; isspace(buf[i]); i++)
1572 ; /* do nothing */
1573 if (buf[i] != '"')
1574 break;
1575 continue;
1577 if (buf[i] == '\\' && dot)
1578 i++;
1579 else if (buf[i] == '"' && dot) {
1580 for (i++; isspace(buf[i]); i++)
1581 ; /* do_nothing */
1582 break;
1584 if (buf[i] != name[j++])
1585 break;
1587 if (buf[i] == ']' && name[j] == 0) {
1589 * We match, now just find the right length offset by
1590 * gobbling up any whitespace after it, as well
1592 i++;
1593 for (; buf[i] && isspace(buf[i]); i++)
1594 ; /* do nothing */
1595 return i;
1597 return 0;
1600 static int section_name_is_ok(const char *name)
1602 /* Empty section names are bogus. */
1603 if (!*name)
1604 return 0;
1607 * Before a dot, we must be alphanumeric or dash. After the first dot,
1608 * anything goes, so we can stop checking.
1610 for (; *name && *name != '.'; name++)
1611 if (*name != '-' && !isalnum(*name))
1612 return 0;
1613 return 1;
1616 /* if new_name == NULL, the section is removed instead */
1617 int git_config_rename_section_in_file(const char *config_filename,
1618 const char *old_name, const char *new_name)
1620 int ret = 0, remove = 0;
1621 char *filename_buf = NULL;
1622 struct lock_file *lock;
1623 int out_fd;
1624 char buf[1024];
1625 FILE *config_file;
1627 if (new_name && !section_name_is_ok(new_name)) {
1628 ret = error("invalid section name: %s", new_name);
1629 goto out;
1632 if (!config_filename)
1633 config_filename = filename_buf = git_pathdup("config");
1635 lock = xcalloc(sizeof(struct lock_file), 1);
1636 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1637 if (out_fd < 0) {
1638 ret = error("could not lock config file %s", config_filename);
1639 goto out;
1642 if (!(config_file = fopen(config_filename, "rb"))) {
1643 /* no config file means nothing to rename, no error */
1644 goto unlock_and_out;
1647 while (fgets(buf, sizeof(buf), config_file)) {
1648 int i;
1649 int length;
1650 char *output = buf;
1651 for (i = 0; buf[i] && isspace(buf[i]); i++)
1652 ; /* do nothing */
1653 if (buf[i] == '[') {
1654 /* it's a section */
1655 int offset = section_name_match(&buf[i], old_name);
1656 if (offset > 0) {
1657 ret++;
1658 if (new_name == NULL) {
1659 remove = 1;
1660 continue;
1662 store.baselen = strlen(new_name);
1663 if (!store_write_section(out_fd, new_name)) {
1664 ret = write_error(lock->filename);
1665 goto out;
1668 * We wrote out the new section, with
1669 * a newline, now skip the old
1670 * section's length
1672 output += offset + i;
1673 if (strlen(output) > 0) {
1675 * More content means there's
1676 * a declaration to put on the
1677 * next line; indent with a
1678 * tab
1680 output -= 1;
1681 output[0] = '\t';
1684 remove = 0;
1686 if (remove)
1687 continue;
1688 length = strlen(output);
1689 if (write_in_full(out_fd, output, length) != length) {
1690 ret = write_error(lock->filename);
1691 goto out;
1694 fclose(config_file);
1695 unlock_and_out:
1696 if (commit_lock_file(lock) < 0)
1697 ret = error("could not commit config file %s", config_filename);
1698 out:
1699 free(filename_buf);
1700 return ret;
1703 int git_config_rename_section(const char *old_name, const char *new_name)
1705 return git_config_rename_section_in_file(NULL, old_name, new_name);
1709 * Call this to report error for your variable that should not
1710 * get a boolean value (i.e. "[my] var" means "true").
1712 #undef config_error_nonbool
1713 int config_error_nonbool(const char *var)
1715 return error("Missing value for '%s'", var);
1718 int parse_config_key(const char *var,
1719 const char *section,
1720 const char **subsection, int *subsection_len,
1721 const char **key)
1723 int section_len = strlen(section);
1724 const char *dot;
1726 /* Does it start with "section." ? */
1727 if (prefixcmp(var, section) || var[section_len] != '.')
1728 return -1;
1731 * Find the key; we don't know yet if we have a subsection, but we must
1732 * parse backwards from the end, since the subsection may have dots in
1733 * it, too.
1735 dot = strrchr(var, '.');
1736 *key = dot + 1;
1738 /* Did we have a subsection at all? */
1739 if (dot == var + section_len) {
1740 *subsection = NULL;
1741 *subsection_len = 0;
1743 else {
1744 *subsection = var + section_len + 1;
1745 *subsection_len = dot - *subsection;
1748 return 0;