mingw: do not hide bare repositories
[git/dscho.git] / config.c
blobd05f2898a0b51d2cb139e34bf3b2509d66ba9638
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 #define MAXNAME (256)
15 typedef struct config_file {
16 struct config_file *prev;
17 FILE *f;
18 const char *name;
19 int linenr;
20 int eof;
21 struct strbuf value;
22 char var[MAXNAME];
23 } config_file;
25 static config_file *cf;
27 static int zlib_compression_seen;
29 const char *config_exclusive_filename = NULL;
31 #define MAX_INCLUDE_DEPTH 10
32 static const char include_depth_advice[] =
33 "exceeded maximum include depth (%d) while including\n"
34 " %s\n"
35 "from\n"
36 " %s\n"
37 "Do you have circular includes?";
38 static int handle_path_include(const char *path, struct config_include_data *inc)
40 int ret = 0;
41 struct strbuf buf = STRBUF_INIT;
44 * Use an absolute path as-is, but interpret relative paths
45 * based on the including config file.
47 if (!is_absolute_path(path)) {
48 char *slash;
50 if (!cf || !cf->name)
51 return error("relative config includes must come from files");
53 slash = find_last_dir_sep(cf->name);
54 if (slash)
55 strbuf_add(&buf, cf->name, slash - cf->name + 1);
56 strbuf_addstr(&buf, path);
57 path = buf.buf;
60 if (!access(path, R_OK)) {
61 if (++inc->depth > MAX_INCLUDE_DEPTH)
62 die(include_depth_advice, MAX_INCLUDE_DEPTH, path,
63 cf && cf->name ? cf->name : "the command line");
64 ret = git_config_from_file(git_config_include, path, inc);
65 inc->depth--;
67 strbuf_release(&buf);
68 return ret;
71 int git_config_include(const char *var, const char *value, void *data)
73 struct config_include_data *inc = data;
74 const char *type;
75 int ret;
78 * Pass along all values, including "include" directives; this makes it
79 * possible to query information on the includes themselves.
81 ret = inc->fn(var, value, inc->data);
82 if (ret < 0)
83 return ret;
85 type = skip_prefix(var, "include.");
86 if (!type)
87 return ret;
89 if (!strcmp(type, "path"))
90 ret = handle_path_include(value, inc);
91 return ret;
94 static void lowercase(char *p)
96 for (; *p; p++)
97 *p = tolower(*p);
100 void git_config_push_parameter(const char *text)
102 struct strbuf env = STRBUF_INIT;
103 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
104 if (old) {
105 strbuf_addstr(&env, old);
106 strbuf_addch(&env, ' ');
108 sq_quote_buf(&env, text);
109 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
110 strbuf_release(&env);
113 int git_config_parse_parameter(const char *text,
114 config_fn_t fn, void *data)
116 struct strbuf **pair;
117 pair = strbuf_split_str(text, '=', 2);
118 if (!pair[0])
119 return error("bogus config parameter: %s", text);
120 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=')
121 strbuf_setlen(pair[0], pair[0]->len - 1);
122 strbuf_trim(pair[0]);
123 if (!pair[0]->len) {
124 strbuf_list_free(pair);
125 return error("bogus config parameter: %s", text);
127 lowercase(pair[0]->buf);
128 if (fn(pair[0]->buf, pair[1] ? pair[1]->buf : NULL, data) < 0) {
129 strbuf_list_free(pair);
130 return -1;
132 strbuf_list_free(pair);
133 return 0;
136 int git_config_from_parameters(config_fn_t fn, void *data)
138 const char *env = getenv(CONFIG_DATA_ENVIRONMENT);
139 char *envw;
140 const char **argv = NULL;
141 int nr = 0, alloc = 0;
142 int i;
144 if (!env)
145 return 0;
146 /* sq_dequote will write over it */
147 envw = xstrdup(env);
149 if (sq_dequote_to_argv(envw, &argv, &nr, &alloc) < 0) {
150 free(envw);
151 return error("bogus format in " CONFIG_DATA_ENVIRONMENT);
154 for (i = 0; i < nr; i++) {
155 if (git_config_parse_parameter(argv[i], fn, data) < 0) {
156 free(argv);
157 free(envw);
158 return -1;
162 free(argv);
163 free(envw);
164 return nr > 0;
167 static int get_next_char(void)
169 int c;
170 FILE *f;
172 c = '\n';
173 if (cf && ((f = cf->f) != NULL)) {
174 c = fgetc(f);
175 if (c == '\r') {
176 /* DOS like systems */
177 c = fgetc(f);
178 if (c != '\n') {
179 ungetc(c, f);
180 c = '\r';
183 if (c == '\n')
184 cf->linenr++;
185 if (c == EOF) {
186 cf->eof = 1;
187 c = '\n';
190 return c;
193 static char *parse_value(void)
195 int quote = 0, comment = 0, space = 0;
197 strbuf_reset(&cf->value);
198 for (;;) {
199 int c = get_next_char();
200 if (c == '\n') {
201 if (quote)
202 return NULL;
203 return cf->value.buf;
205 if (comment)
206 continue;
207 if (isspace(c) && !quote) {
208 if (cf->value.len)
209 space++;
210 continue;
212 if (!quote) {
213 if (c == ';' || c == '#') {
214 comment = 1;
215 continue;
218 for (; space; space--)
219 strbuf_addch(&cf->value, ' ');
220 if (c == '\\') {
221 c = get_next_char();
222 switch (c) {
223 case '\n':
224 continue;
225 case 't':
226 c = '\t';
227 break;
228 case 'b':
229 c = '\b';
230 break;
231 case 'n':
232 c = '\n';
233 break;
234 /* Some characters escape as themselves */
235 case '\\': case '"':
236 break;
237 /* Reject unknown escape sequences */
238 default:
239 return NULL;
241 strbuf_addch(&cf->value, c);
242 continue;
244 if (c == '"') {
245 quote = 1-quote;
246 continue;
248 strbuf_addch(&cf->value, c);
252 static inline int iskeychar(int c)
254 return isalnum(c) || c == '-';
257 static int get_value(config_fn_t fn, void *data, char *name, unsigned int len)
259 int c;
260 char *value;
262 /* Get the full name */
263 for (;;) {
264 c = get_next_char();
265 if (cf->eof)
266 break;
267 if (!iskeychar(c))
268 break;
269 name[len++] = tolower(c);
270 if (len >= MAXNAME)
271 return -1;
273 name[len] = 0;
274 while (c == ' ' || c == '\t')
275 c = get_next_char();
277 value = NULL;
278 if (c != '\n') {
279 if (c != '=')
280 return -1;
281 value = parse_value();
282 if (!value)
283 return -1;
285 return fn(name, value, data);
288 static int get_extended_base_var(char *name, int baselen, int c)
290 do {
291 if (c == '\n')
292 return -1;
293 c = get_next_char();
294 } while (isspace(c));
296 /* We require the format to be '[base "extension"]' */
297 if (c != '"')
298 return -1;
299 name[baselen++] = '.';
301 for (;;) {
302 int c = get_next_char();
303 if (c == '\n')
304 return -1;
305 if (c == '"')
306 break;
307 if (c == '\\') {
308 c = get_next_char();
309 if (c == '\n')
310 return -1;
312 name[baselen++] = c;
313 if (baselen > MAXNAME / 2)
314 return -1;
317 /* Final ']' */
318 if (get_next_char() != ']')
319 return -1;
320 return baselen;
323 static int get_base_var(char *name)
325 int baselen = 0;
327 for (;;) {
328 int c = get_next_char();
329 if (cf->eof)
330 return -1;
331 if (c == ']')
332 return baselen;
333 if (isspace(c))
334 return get_extended_base_var(name, baselen, c);
335 if (!iskeychar(c) && c != '.')
336 return -1;
337 if (baselen > MAXNAME / 2)
338 return -1;
339 name[baselen++] = tolower(c);
343 static int git_parse_file(config_fn_t fn, void *data)
345 int comment = 0;
346 int baselen = 0;
347 char *var = cf->var;
349 /* U+FEFF Byte Order Mark in UTF8 */
350 static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
351 const unsigned char *bomptr = utf8_bom;
353 for (;;) {
354 int c = get_next_char();
355 if (bomptr && *bomptr) {
356 /* We are at the file beginning; skip UTF8-encoded BOM
357 * if present. Sane editors won't put this in on their
358 * own, but e.g. Windows Notepad will do it happily. */
359 if ((unsigned char) c == *bomptr) {
360 bomptr++;
361 continue;
362 } else {
363 /* Do not tolerate partial BOM. */
364 if (bomptr != utf8_bom)
365 break;
366 /* No BOM at file beginning. Cool. */
367 bomptr = NULL;
370 if (c == '\n') {
371 if (cf->eof)
372 return 0;
373 comment = 0;
374 continue;
376 if (comment || isspace(c))
377 continue;
378 if (c == '#' || c == ';') {
379 comment = 1;
380 continue;
382 if (c == '[') {
383 baselen = get_base_var(var);
384 if (baselen <= 0)
385 break;
386 var[baselen++] = '.';
387 var[baselen] = 0;
388 continue;
390 if (!isalpha(c))
391 break;
392 var[baselen] = tolower(c);
393 if (get_value(fn, data, var, baselen+1) < 0)
394 break;
396 die("bad config file line %d in %s", cf->linenr, cf->name);
399 static int parse_unit_factor(const char *end, uintmax_t *val)
401 if (!*end)
402 return 1;
403 else if (!strcasecmp(end, "k")) {
404 *val *= 1024;
405 return 1;
407 else if (!strcasecmp(end, "m")) {
408 *val *= 1024 * 1024;
409 return 1;
411 else if (!strcasecmp(end, "g")) {
412 *val *= 1024 * 1024 * 1024;
413 return 1;
415 return 0;
418 static int git_parse_long(const char *value, long *ret)
420 if (value && *value) {
421 char *end;
422 intmax_t val;
423 uintmax_t uval;
424 uintmax_t factor = 1;
426 errno = 0;
427 val = strtoimax(value, &end, 0);
428 if (errno == ERANGE)
429 return 0;
430 if (!parse_unit_factor(end, &factor))
431 return 0;
432 uval = abs(val);
433 uval *= factor;
434 if ((uval > maximum_signed_value_of_type(long)) ||
435 (abs(val) > uval))
436 return 0;
437 val *= factor;
438 *ret = val;
439 return 1;
441 return 0;
444 int git_parse_ulong(const char *value, unsigned long *ret)
446 if (value && *value) {
447 char *end;
448 uintmax_t val;
449 uintmax_t oldval;
451 errno = 0;
452 val = strtoumax(value, &end, 0);
453 if (errno == ERANGE)
454 return 0;
455 oldval = val;
456 if (!parse_unit_factor(end, &val))
457 return 0;
458 if ((val > maximum_unsigned_value_of_type(long)) ||
459 (oldval > val))
460 return 0;
461 *ret = val;
462 return 1;
464 return 0;
467 static void die_bad_config(const char *name)
469 if (cf && cf->name)
470 die("bad config value for '%s' in %s", name, cf->name);
471 die("bad config value for '%s'", name);
474 int git_config_int(const char *name, const char *value)
476 long ret = 0;
477 if (!git_parse_long(value, &ret))
478 die_bad_config(name);
479 return ret;
482 unsigned long git_config_ulong(const char *name, const char *value)
484 unsigned long ret;
485 if (!git_parse_ulong(value, &ret))
486 die_bad_config(name);
487 return ret;
490 static int git_config_maybe_bool_text(const char *name, const char *value)
492 if (!value)
493 return 1;
494 if (!*value)
495 return 0;
496 if (!strcasecmp(value, "true")
497 || !strcasecmp(value, "yes")
498 || !strcasecmp(value, "on"))
499 return 1;
500 if (!strcasecmp(value, "false")
501 || !strcasecmp(value, "no")
502 || !strcasecmp(value, "off"))
503 return 0;
504 return -1;
507 int git_config_maybe_bool(const char *name, const char *value)
509 long v = git_config_maybe_bool_text(name, value);
510 if (0 <= v)
511 return v;
512 if (git_parse_long(value, &v))
513 return !!v;
514 return -1;
517 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
519 int v = git_config_maybe_bool_text(name, value);
520 if (0 <= v) {
521 *is_bool = 1;
522 return v;
524 *is_bool = 0;
525 return git_config_int(name, value);
528 int git_config_bool(const char *name, const char *value)
530 int discard;
531 return !!git_config_bool_or_int(name, value, &discard);
534 int git_config_string(const char **dest, const char *var, const char *value)
536 if (!value)
537 return config_error_nonbool(var);
538 *dest = xstrdup(value);
539 return 0;
542 int git_config_pathname(const char **dest, const char *var, const char *value)
544 if (!value)
545 return config_error_nonbool(var);
546 *dest = expand_user_path(value);
547 if (!*dest)
548 die("Failed to expand user dir in: '%s'", value);
549 return 0;
552 static int git_default_core_config(const char *var, const char *value)
554 /* This needs a better name */
555 if (!strcmp(var, "core.filemode")) {
556 trust_executable_bit = git_config_bool(var, value);
557 return 0;
559 if (!strcmp(var, "core.trustctime")) {
560 trust_ctime = git_config_bool(var, value);
561 return 0;
564 if (!strcmp(var, "core.quotepath")) {
565 quote_path_fully = git_config_bool(var, value);
566 return 0;
569 if (!strcmp(var, "core.symlinks")) {
570 has_symlinks = git_config_bool(var, value);
571 return 0;
574 if (!strcmp(var, "core.ignorecase")) {
575 ignore_case = git_config_bool(var, value);
576 return 0;
579 if (!strcmp(var, "core.attributesfile"))
580 return git_config_pathname(&git_attributes_file, var, value);
582 if (!strcmp(var, "core.bare")) {
583 is_bare_repository_cfg = git_config_bool(var, value);
584 return 0;
587 if (!strcmp(var, "core.ignorestat")) {
588 assume_unchanged = git_config_bool(var, value);
589 return 0;
592 if (!strcmp(var, "core.prefersymlinkrefs")) {
593 prefer_symlink_refs = git_config_bool(var, value);
594 return 0;
597 if (!strcmp(var, "core.logallrefupdates")) {
598 log_all_ref_updates = git_config_bool(var, value);
599 return 0;
602 if (!strcmp(var, "core.warnambiguousrefs")) {
603 warn_ambiguous_refs = git_config_bool(var, value);
604 return 0;
607 if (!strcmp(var, "core.abbrev")) {
608 int abbrev = git_config_int(var, value);
609 if (abbrev < minimum_abbrev || abbrev > 40)
610 return -1;
611 default_abbrev = abbrev;
612 return 0;
615 if (!strcmp(var, "core.loosecompression")) {
616 int level = git_config_int(var, value);
617 if (level == -1)
618 level = Z_DEFAULT_COMPRESSION;
619 else if (level < 0 || level > Z_BEST_COMPRESSION)
620 die("bad zlib compression level %d", level);
621 zlib_compression_level = level;
622 zlib_compression_seen = 1;
623 return 0;
626 if (!strcmp(var, "core.compression")) {
627 int level = git_config_int(var, value);
628 if (level == -1)
629 level = Z_DEFAULT_COMPRESSION;
630 else if (level < 0 || level > Z_BEST_COMPRESSION)
631 die("bad zlib compression level %d", level);
632 core_compression_level = level;
633 core_compression_seen = 1;
634 if (!zlib_compression_seen)
635 zlib_compression_level = level;
636 return 0;
639 if (!strcmp(var, "core.packedgitwindowsize")) {
640 int pgsz_x2 = getpagesize() * 2;
641 packed_git_window_size = git_config_ulong(var, value);
643 /* This value must be multiple of (pagesize * 2) */
644 packed_git_window_size /= pgsz_x2;
645 if (packed_git_window_size < 1)
646 packed_git_window_size = 1;
647 packed_git_window_size *= pgsz_x2;
648 return 0;
651 if (!strcmp(var, "core.bigfilethreshold")) {
652 big_file_threshold = git_config_ulong(var, value);
653 return 0;
656 if (!strcmp(var, "core.packedgitlimit")) {
657 packed_git_limit = git_config_ulong(var, value);
658 return 0;
661 if (!strcmp(var, "core.deltabasecachelimit")) {
662 delta_base_cache_limit = git_config_ulong(var, value);
663 return 0;
666 if (!strcmp(var, "core.logpackaccess"))
667 return git_config_string(&log_pack_access, var, value);
669 if (!strcmp(var, "core.autocrlf")) {
670 if (value && !strcasecmp(value, "input")) {
671 if (core_eol == EOL_CRLF)
672 return error("core.autocrlf=input conflicts with core.eol=crlf");
673 auto_crlf = AUTO_CRLF_INPUT;
674 return 0;
676 auto_crlf = git_config_bool(var, value);
677 return 0;
680 if (!strcmp(var, "core.safecrlf")) {
681 if (value && !strcasecmp(value, "warn")) {
682 safe_crlf = SAFE_CRLF_WARN;
683 return 0;
685 safe_crlf = git_config_bool(var, value);
686 return 0;
689 if (!strcmp(var, "core.eol")) {
690 if (value && !strcasecmp(value, "lf"))
691 core_eol = EOL_LF;
692 else if (value && !strcasecmp(value, "crlf"))
693 core_eol = EOL_CRLF;
694 else if (value && !strcasecmp(value, "native"))
695 core_eol = EOL_NATIVE;
696 else
697 core_eol = EOL_UNSET;
698 if (core_eol == EOL_CRLF && auto_crlf == AUTO_CRLF_INPUT)
699 return error("core.autocrlf=input conflicts with core.eol=crlf");
700 return 0;
703 if (!strcmp(var, "core.notesref")) {
704 notes_ref_name = xstrdup(value);
705 return 0;
708 if (!strcmp(var, "core.pager"))
709 return git_config_string(&pager_program, var, value);
711 if (!strcmp(var, "core.editor"))
712 return git_config_string(&editor_program, var, value);
714 if (!strcmp(var, "core.askpass"))
715 return git_config_string(&askpass_program, var, value);
717 if (!strcmp(var, "core.excludesfile"))
718 return git_config_pathname(&excludes_file, var, value);
720 if (!strcmp(var, "core.whitespace")) {
721 if (!value)
722 return config_error_nonbool(var);
723 whitespace_rule_cfg = parse_whitespace_rule(value);
724 return 0;
727 if (!strcmp(var, "core.fsyncobjectfiles")) {
728 fsync_object_files = git_config_bool(var, value);
729 return 0;
732 if (!strcmp(var, "core.preloadindex")) {
733 core_preload_index = git_config_bool(var, value);
734 return 0;
737 if (!strcmp(var, "core.createobject")) {
738 if (!strcmp(value, "rename"))
739 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
740 else if (!strcmp(value, "link"))
741 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
742 else
743 die("Invalid mode for object creation: %s", value);
744 return 0;
747 if (!strcmp(var, "core.sparsecheckout")) {
748 core_apply_sparse_checkout = git_config_bool(var, value);
749 return 0;
752 if (!strcmp(var, "core.hidedotfiles")) {
753 if (value && !strcasecmp(value, "dotgitonly")) {
754 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
755 return 0;
757 hide_dotfiles = git_config_bool(var, value);
758 return 0;
761 /* Add other config variables here and to Documentation/config.txt. */
762 return 0;
765 static int git_default_user_config(const char *var, const char *value)
767 if (!strcmp(var, "user.name")) {
768 if (!value)
769 return config_error_nonbool(var);
770 strlcpy(git_default_name, value, sizeof(git_default_name));
771 user_ident_explicitly_given |= IDENT_NAME_GIVEN;
772 return 0;
775 if (!strcmp(var, "user.email")) {
776 if (!value)
777 return config_error_nonbool(var);
778 strlcpy(git_default_email, value, sizeof(git_default_email));
779 user_ident_explicitly_given |= IDENT_MAIL_GIVEN;
780 return 0;
783 /* Add other config variables here and to Documentation/config.txt. */
784 return 0;
787 static int git_default_i18n_config(const char *var, const char *value)
789 if (!strcmp(var, "i18n.commitencoding"))
790 return git_config_string(&git_commit_encoding, var, value);
792 if (!strcmp(var, "i18n.logoutputencoding"))
793 return git_config_string(&git_log_output_encoding, var, value);
795 /* Add other config variables here and to Documentation/config.txt. */
796 return 0;
799 static int git_default_branch_config(const char *var, const char *value)
801 if (!strcmp(var, "branch.autosetupmerge")) {
802 if (value && !strcasecmp(value, "always")) {
803 git_branch_track = BRANCH_TRACK_ALWAYS;
804 return 0;
806 git_branch_track = git_config_bool(var, value);
807 return 0;
809 if (!strcmp(var, "branch.autosetuprebase")) {
810 if (!value)
811 return config_error_nonbool(var);
812 else if (!strcmp(value, "never"))
813 autorebase = AUTOREBASE_NEVER;
814 else if (!strcmp(value, "local"))
815 autorebase = AUTOREBASE_LOCAL;
816 else if (!strcmp(value, "remote"))
817 autorebase = AUTOREBASE_REMOTE;
818 else if (!strcmp(value, "always"))
819 autorebase = AUTOREBASE_ALWAYS;
820 else
821 return error("Malformed value for %s", var);
822 return 0;
825 /* Add other config variables here and to Documentation/config.txt. */
826 return 0;
829 static int git_default_push_config(const char *var, const char *value)
831 if (!strcmp(var, "push.default")) {
832 if (!value)
833 return config_error_nonbool(var);
834 else if (!strcmp(value, "nothing"))
835 push_default = PUSH_DEFAULT_NOTHING;
836 else if (!strcmp(value, "matching"))
837 push_default = PUSH_DEFAULT_MATCHING;
838 else if (!strcmp(value, "upstream"))
839 push_default = PUSH_DEFAULT_UPSTREAM;
840 else if (!strcmp(value, "tracking")) /* deprecated */
841 push_default = PUSH_DEFAULT_UPSTREAM;
842 else if (!strcmp(value, "current"))
843 push_default = PUSH_DEFAULT_CURRENT;
844 else {
845 error("Malformed value for %s: %s", var, value);
846 return error("Must be one of nothing, matching, "
847 "tracking or current.");
849 return 0;
852 /* Add other config variables here and to Documentation/config.txt. */
853 return 0;
856 static int git_default_mailmap_config(const char *var, const char *value)
858 if (!strcmp(var, "mailmap.file"))
859 return git_config_string(&git_mailmap_file, var, value);
861 /* Add other config variables here and to Documentation/config.txt. */
862 return 0;
865 int git_default_config(const char *var, const char *value, void *dummy)
867 if (!prefixcmp(var, "core."))
868 return git_default_core_config(var, value);
870 if (!prefixcmp(var, "user."))
871 return git_default_user_config(var, value);
873 if (!prefixcmp(var, "i18n."))
874 return git_default_i18n_config(var, value);
876 if (!prefixcmp(var, "branch."))
877 return git_default_branch_config(var, value);
879 if (!prefixcmp(var, "push."))
880 return git_default_push_config(var, value);
882 if (!prefixcmp(var, "mailmap."))
883 return git_default_mailmap_config(var, value);
885 if (!prefixcmp(var, "advice."))
886 return git_default_advice_config(var, value);
888 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
889 pager_use_color = git_config_bool(var,value);
890 return 0;
893 if (!strcmp(var, "pack.packsizelimit")) {
894 pack_size_limit_cfg = git_config_ulong(var, value);
895 return 0;
897 /* Add other config variables here and to Documentation/config.txt. */
898 return 0;
901 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
903 int ret;
904 FILE *f = fopen(filename, "r");
906 ret = -1;
907 if (f) {
908 config_file top;
910 /* push config-file parsing state stack */
911 top.prev = cf;
912 top.f = f;
913 top.name = filename;
914 top.linenr = 1;
915 top.eof = 0;
916 strbuf_init(&top.value, 1024);
917 cf = &top;
919 ret = git_parse_file(fn, data);
921 /* pop config-file parsing state stack */
922 strbuf_release(&top.value);
923 cf = top.prev;
925 fclose(f);
927 return ret;
930 const char *git_etc_gitconfig(void)
932 static const char *system_wide;
933 if (!system_wide)
934 system_wide = system_path(ETC_GITCONFIG);
935 return system_wide;
938 int git_env_bool(const char *k, int def)
940 const char *v = getenv(k);
941 return v ? git_config_bool(k, v) : def;
944 int git_config_system(void)
946 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
949 int git_config_early(config_fn_t fn, void *data, const char *repo_config)
951 int ret = 0, found = 0;
952 const char *home = NULL;
954 /* Setting $GIT_CONFIG makes git read _only_ the given config file. */
955 if (config_exclusive_filename)
956 return git_config_from_file(fn, config_exclusive_filename, data);
957 if (git_config_system() && !access(git_etc_gitconfig(), R_OK)) {
958 ret += git_config_from_file(fn, git_etc_gitconfig(),
959 data);
960 found += 1;
963 home = get_home_directory();
964 if (home) {
965 char buf[PATH_MAX];
966 char *user_config = mksnpath(buf, sizeof(buf), "%s/.gitconfig", home);
967 if (!access(user_config, R_OK)) {
968 ret += git_config_from_file(fn, user_config, data);
969 found += 1;
973 if (repo_config && !access(repo_config, R_OK)) {
974 ret += git_config_from_file(fn, repo_config, data);
975 found += 1;
978 switch (git_config_from_parameters(fn, data)) {
979 case -1: /* error */
980 die("unable to parse command-line config");
981 break;
982 case 0: /* found nothing */
983 break;
984 default: /* found at least one item */
985 found++;
986 break;
989 return ret == 0 ? found : ret;
992 int git_config(config_fn_t fn, void *data)
994 char *repo_config = NULL;
995 int ret;
996 struct config_include_data inc = CONFIG_INCLUDE_INIT;
998 inc.fn = fn;
999 inc.data = data;
1001 repo_config = git_pathdup("config");
1002 ret = git_config_early(git_config_include, &inc, repo_config);
1003 if (repo_config)
1004 free(repo_config);
1005 return ret;
1009 * Find all the stuff for git_config_set() below.
1012 #define MAX_MATCHES 512
1014 static struct {
1015 int baselen;
1016 char *key;
1017 int do_not_match;
1018 regex_t *value_regex;
1019 int multi_replace;
1020 size_t offset[MAX_MATCHES];
1021 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
1022 int seen;
1023 } store;
1025 static int matches(const char *key, const char *value)
1027 return !strcmp(key, store.key) &&
1028 (store.value_regex == NULL ||
1029 (store.do_not_match ^
1030 !regexec(store.value_regex, value, 0, NULL, 0)));
1033 static int store_aux(const char *key, const char *value, void *cb)
1035 const char *ep;
1036 size_t section_len;
1037 FILE *f = cf->f;
1039 switch (store.state) {
1040 case KEY_SEEN:
1041 if (matches(key, value)) {
1042 if (store.seen == 1 && store.multi_replace == 0) {
1043 warning("%s has multiple values", key);
1044 } else if (store.seen >= MAX_MATCHES) {
1045 error("too many matches for %s", key);
1046 return 1;
1049 store.offset[store.seen] = ftell(f);
1050 store.seen++;
1052 break;
1053 case SECTION_SEEN:
1055 * What we are looking for is in store.key (both
1056 * section and var), and its section part is baselen
1057 * long. We found key (again, both section and var).
1058 * We would want to know if this key is in the same
1059 * section as what we are looking for. We already
1060 * know we are in the same section as what should
1061 * hold store.key.
1063 ep = strrchr(key, '.');
1064 section_len = ep - key;
1066 if ((section_len != store.baselen) ||
1067 memcmp(key, store.key, section_len+1)) {
1068 store.state = SECTION_END_SEEN;
1069 break;
1073 * Do not increment matches: this is no match, but we
1074 * just made sure we are in the desired section.
1076 store.offset[store.seen] = ftell(f);
1077 /* fallthru */
1078 case SECTION_END_SEEN:
1079 case START:
1080 if (matches(key, value)) {
1081 store.offset[store.seen] = ftell(f);
1082 store.state = KEY_SEEN;
1083 store.seen++;
1084 } else {
1085 if (strrchr(key, '.') - key == store.baselen &&
1086 !strncmp(key, store.key, store.baselen)) {
1087 store.state = SECTION_SEEN;
1088 store.offset[store.seen] = ftell(f);
1092 return 0;
1095 static int write_error(const char *filename)
1097 error("failed to write new configuration file %s", filename);
1099 /* Same error code as "failed to rename". */
1100 return 4;
1103 static int store_write_section(int fd, const char *key)
1105 const char *dot;
1106 int i, success;
1107 struct strbuf sb = STRBUF_INIT;
1109 dot = memchr(key, '.', store.baselen);
1110 if (dot) {
1111 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
1112 for (i = dot - key + 1; i < store.baselen; i++) {
1113 if (key[i] == '"' || key[i] == '\\')
1114 strbuf_addch(&sb, '\\');
1115 strbuf_addch(&sb, key[i]);
1117 strbuf_addstr(&sb, "\"]\n");
1118 } else {
1119 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
1122 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1123 strbuf_release(&sb);
1125 return success;
1128 static int store_write_pair(int fd, const char *key, const char *value)
1130 int i, success;
1131 int length = strlen(key + store.baselen + 1);
1132 const char *quote = "";
1133 struct strbuf sb = STRBUF_INIT;
1136 * Check to see if the value needs to be surrounded with a dq pair.
1137 * Note that problematic characters are always backslash-quoted; this
1138 * check is about not losing leading or trailing SP and strings that
1139 * follow beginning-of-comment characters (i.e. ';' and '#') by the
1140 * configuration parser.
1142 if (value[0] == ' ')
1143 quote = "\"";
1144 for (i = 0; value[i]; i++)
1145 if (value[i] == ';' || value[i] == '#')
1146 quote = "\"";
1147 if (i && value[i - 1] == ' ')
1148 quote = "\"";
1150 strbuf_addf(&sb, "\t%.*s = %s",
1151 length, key + store.baselen + 1, quote);
1153 for (i = 0; value[i]; i++)
1154 switch (value[i]) {
1155 case '\n':
1156 strbuf_addstr(&sb, "\\n");
1157 break;
1158 case '\t':
1159 strbuf_addstr(&sb, "\\t");
1160 break;
1161 case '"':
1162 case '\\':
1163 strbuf_addch(&sb, '\\');
1164 default:
1165 strbuf_addch(&sb, value[i]);
1166 break;
1168 strbuf_addf(&sb, "%s\n", quote);
1170 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1171 strbuf_release(&sb);
1173 return success;
1176 static ssize_t find_beginning_of_line(const char *contents, size_t size,
1177 size_t offset_, int *found_bracket)
1179 size_t equal_offset = size, bracket_offset = size;
1180 ssize_t offset;
1182 contline:
1183 for (offset = offset_-2; offset > 0
1184 && contents[offset] != '\n'; offset--)
1185 switch (contents[offset]) {
1186 case '=': equal_offset = offset; break;
1187 case ']': bracket_offset = offset; break;
1189 if (offset > 0 && contents[offset-1] == '\\') {
1190 offset_ = offset;
1191 goto contline;
1193 if (bracket_offset < equal_offset) {
1194 *found_bracket = 1;
1195 offset = bracket_offset+1;
1196 } else
1197 offset++;
1199 return offset;
1202 int git_config_set_in_file(const char *config_filename,
1203 const char *key, const char *value)
1205 return git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
1208 int git_config_set(const char *key, const char *value)
1210 return git_config_set_multivar(key, value, NULL, 0);
1214 * Auxiliary function to sanity-check and split the key into the section
1215 * identifier and variable name.
1217 * Returns 0 on success, -1 when there is an invalid character in the key and
1218 * -2 if there is no section name in the key.
1220 * store_key - pointer to char* which will hold a copy of the key with
1221 * lowercase section and variable name
1222 * baselen - pointer to int which will hold the length of the
1223 * section + subsection part, can be NULL
1225 int git_config_parse_key(const char *key, char **store_key, int *baselen_)
1227 int i, dot, baselen;
1228 const char *last_dot = strrchr(key, '.');
1231 * Since "key" actually contains the section name and the real
1232 * key name separated by a dot, we have to know where the dot is.
1235 if (last_dot == NULL || last_dot == key) {
1236 error("key does not contain a section: %s", key);
1237 return -CONFIG_NO_SECTION_OR_NAME;
1240 if (!last_dot[1]) {
1241 error("key does not contain variable name: %s", key);
1242 return -CONFIG_NO_SECTION_OR_NAME;
1245 baselen = last_dot - key;
1246 if (baselen_)
1247 *baselen_ = baselen;
1250 * Validate the key and while at it, lower case it for matching.
1252 *store_key = xmalloc(strlen(key) + 1);
1254 dot = 0;
1255 for (i = 0; key[i]; i++) {
1256 unsigned char c = key[i];
1257 if (c == '.')
1258 dot = 1;
1259 /* Leave the extended basename untouched.. */
1260 if (!dot || i > baselen) {
1261 if (!iskeychar(c) ||
1262 (i == baselen + 1 && !isalpha(c))) {
1263 error("invalid key: %s", key);
1264 goto out_free_ret_1;
1266 c = tolower(c);
1267 } else if (c == '\n') {
1268 error("invalid key (newline): %s", key);
1269 goto out_free_ret_1;
1271 (*store_key)[i] = c;
1273 (*store_key)[i] = 0;
1275 return 0;
1277 out_free_ret_1:
1278 free(*store_key);
1279 return -CONFIG_INVALID_KEY;
1283 * If value==NULL, unset in (remove from) config,
1284 * if value_regex!=NULL, disregard key/value pairs where value does not match.
1285 * if multi_replace==0, nothing, or only one matching key/value is replaced,
1286 * else all matching key/values (regardless how many) are removed,
1287 * before the new pair is written.
1289 * Returns 0 on success.
1291 * This function does this:
1293 * - it locks the config file by creating ".git/config.lock"
1295 * - it then parses the config using store_aux() as validator to find
1296 * the position on the key/value pair to replace. If it is to be unset,
1297 * it must be found exactly once.
1299 * - the config file is mmap()ed and the part before the match (if any) is
1300 * written to the lock file, then the changed part and the rest.
1302 * - the config file is removed and the lock file rename()d to it.
1305 int git_config_set_multivar_in_file(const char *config_filename,
1306 const char *key, const char *value,
1307 const char *value_regex, int multi_replace)
1309 int fd = -1, in_fd;
1310 int ret;
1311 struct lock_file *lock = NULL;
1313 /* parse-key returns negative; flip the sign to feed exit(3) */
1314 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
1315 if (ret)
1316 goto out_free;
1318 store.multi_replace = multi_replace;
1322 * The lock serves a purpose in addition to locking: the new
1323 * contents of .git/config will be written into it.
1325 lock = xcalloc(sizeof(struct lock_file), 1);
1326 fd = hold_lock_file_for_update(lock, config_filename, 0);
1327 if (fd < 0) {
1328 error("could not lock config file %s: %s", config_filename, strerror(errno));
1329 free(store.key);
1330 ret = CONFIG_NO_LOCK;
1331 goto out_free;
1335 * If .git/config does not exist yet, write a minimal version.
1337 in_fd = open(config_filename, O_RDONLY);
1338 if ( in_fd < 0 ) {
1339 free(store.key);
1341 if ( ENOENT != errno ) {
1342 error("opening %s: %s", config_filename,
1343 strerror(errno));
1344 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
1345 goto out_free;
1347 /* if nothing to unset, error out */
1348 if (value == NULL) {
1349 ret = CONFIG_NOTHING_SET;
1350 goto out_free;
1353 store.key = (char *)key;
1354 if (!store_write_section(fd, key) ||
1355 !store_write_pair(fd, key, value))
1356 goto write_err_out;
1357 } else {
1358 struct stat st;
1359 char *contents;
1360 size_t contents_sz, copy_begin, copy_end;
1361 int i, new_line = 0;
1363 if (value_regex == NULL)
1364 store.value_regex = NULL;
1365 else {
1366 if (value_regex[0] == '!') {
1367 store.do_not_match = 1;
1368 value_regex++;
1369 } else
1370 store.do_not_match = 0;
1372 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1373 if (regcomp(store.value_regex, value_regex,
1374 REG_EXTENDED)) {
1375 error("invalid pattern: %s", value_regex);
1376 free(store.value_regex);
1377 ret = CONFIG_INVALID_PATTERN;
1378 goto out_free;
1382 store.offset[0] = 0;
1383 store.state = START;
1384 store.seen = 0;
1387 * After this, store.offset will contain the *end* offset
1388 * of the last match, or remain at 0 if no match was found.
1389 * As a side effect, we make sure to transform only a valid
1390 * existing config file.
1392 if (git_config_from_file(store_aux, config_filename, NULL)) {
1393 error("invalid config file %s", config_filename);
1394 free(store.key);
1395 if (store.value_regex != NULL) {
1396 regfree(store.value_regex);
1397 free(store.value_regex);
1399 ret = CONFIG_INVALID_FILE;
1400 goto out_free;
1403 free(store.key);
1404 if (store.value_regex != NULL) {
1405 regfree(store.value_regex);
1406 free(store.value_regex);
1409 /* if nothing to unset, or too many matches, error out */
1410 if ((store.seen == 0 && value == NULL) ||
1411 (store.seen > 1 && multi_replace == 0)) {
1412 ret = CONFIG_NOTHING_SET;
1413 goto out_free;
1416 fstat(in_fd, &st);
1417 contents_sz = xsize_t(st.st_size);
1418 contents = xmmap(NULL, contents_sz, PROT_READ,
1419 MAP_PRIVATE, in_fd, 0);
1420 close(in_fd);
1422 if (store.seen == 0)
1423 store.seen = 1;
1425 for (i = 0, copy_begin = 0; i < store.seen; i++) {
1426 if (store.offset[i] == 0) {
1427 store.offset[i] = copy_end = contents_sz;
1428 } else if (store.state != KEY_SEEN) {
1429 copy_end = store.offset[i];
1430 } else
1431 copy_end = find_beginning_of_line(
1432 contents, contents_sz,
1433 store.offset[i]-2, &new_line);
1435 if (copy_end > 0 && contents[copy_end-1] != '\n')
1436 new_line = 1;
1438 /* write the first part of the config */
1439 if (copy_end > copy_begin) {
1440 if (write_in_full(fd, contents + copy_begin,
1441 copy_end - copy_begin) <
1442 copy_end - copy_begin)
1443 goto write_err_out;
1444 if (new_line &&
1445 write_str_in_full(fd, "\n") != 1)
1446 goto write_err_out;
1448 copy_begin = store.offset[i];
1451 /* write the pair (value == NULL means unset) */
1452 if (value != NULL) {
1453 if (store.state == START) {
1454 if (!store_write_section(fd, key))
1455 goto write_err_out;
1457 if (!store_write_pair(fd, key, value))
1458 goto write_err_out;
1461 /* write the rest of the config */
1462 if (copy_begin < contents_sz)
1463 if (write_in_full(fd, contents + copy_begin,
1464 contents_sz - copy_begin) <
1465 contents_sz - copy_begin)
1466 goto write_err_out;
1468 munmap(contents, contents_sz);
1471 if (commit_lock_file(lock) < 0) {
1472 error("could not commit config file %s", config_filename);
1473 ret = CONFIG_NO_WRITE;
1474 goto out_free;
1478 * lock is committed, so don't try to roll it back below.
1479 * NOTE: Since lockfile.c keeps a linked list of all created
1480 * lock_file structures, it isn't safe to free(lock). It's
1481 * better to just leave it hanging around.
1483 lock = NULL;
1484 ret = 0;
1486 out_free:
1487 if (lock)
1488 rollback_lock_file(lock);
1489 return ret;
1491 write_err_out:
1492 ret = write_error(lock->filename);
1493 goto out_free;
1497 int git_config_set_multivar(const char *key, const char *value,
1498 const char *value_regex, int multi_replace)
1500 const char *config_filename;
1501 char *buf = NULL;
1502 int ret;
1504 if (config_exclusive_filename)
1505 config_filename = config_exclusive_filename;
1506 else
1507 config_filename = buf = git_pathdup("config");
1509 ret = git_config_set_multivar_in_file(config_filename, key, value,
1510 value_regex, multi_replace);
1511 free(buf);
1512 return ret;
1515 static int section_name_match (const char *buf, const char *name)
1517 int i = 0, j = 0, dot = 0;
1518 if (buf[i] != '[')
1519 return 0;
1520 for (i = 1; buf[i] && buf[i] != ']'; i++) {
1521 if (!dot && isspace(buf[i])) {
1522 dot = 1;
1523 if (name[j++] != '.')
1524 break;
1525 for (i++; isspace(buf[i]); i++)
1526 ; /* do nothing */
1527 if (buf[i] != '"')
1528 break;
1529 continue;
1531 if (buf[i] == '\\' && dot)
1532 i++;
1533 else if (buf[i] == '"' && dot) {
1534 for (i++; isspace(buf[i]); i++)
1535 ; /* do_nothing */
1536 break;
1538 if (buf[i] != name[j++])
1539 break;
1541 if (buf[i] == ']' && name[j] == 0) {
1543 * We match, now just find the right length offset by
1544 * gobbling up any whitespace after it, as well
1546 i++;
1547 for (; buf[i] && isspace(buf[i]); i++)
1548 ; /* do nothing */
1549 return i;
1551 return 0;
1554 /* if new_name == NULL, the section is removed instead */
1555 int git_config_rename_section(const char *old_name, const char *new_name)
1557 int ret = 0, remove = 0;
1558 char *config_filename;
1559 struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1560 int out_fd;
1561 char buf[1024];
1562 FILE *config_file;
1564 if (config_exclusive_filename)
1565 config_filename = xstrdup(config_exclusive_filename);
1566 else
1567 config_filename = git_pathdup("config");
1568 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1569 if (out_fd < 0) {
1570 ret = error("could not lock config file %s", config_filename);
1571 goto out;
1574 if (!(config_file = fopen(config_filename, "rb"))) {
1575 /* no config file means nothing to rename, no error */
1576 goto unlock_and_out;
1579 while (fgets(buf, sizeof(buf), config_file)) {
1580 int i;
1581 int length;
1582 char *output = buf;
1583 for (i = 0; buf[i] && isspace(buf[i]); i++)
1584 ; /* do nothing */
1585 if (buf[i] == '[') {
1586 /* it's a section */
1587 int offset = section_name_match(&buf[i], old_name);
1588 if (offset > 0) {
1589 ret++;
1590 if (new_name == NULL) {
1591 remove = 1;
1592 continue;
1594 store.baselen = strlen(new_name);
1595 if (!store_write_section(out_fd, new_name)) {
1596 ret = write_error(lock->filename);
1597 goto out;
1600 * We wrote out the new section, with
1601 * a newline, now skip the old
1602 * section's length
1604 output += offset + i;
1605 if (strlen(output) > 0) {
1607 * More content means there's
1608 * a declaration to put on the
1609 * next line; indent with a
1610 * tab
1612 output -= 1;
1613 output[0] = '\t';
1616 remove = 0;
1618 if (remove)
1619 continue;
1620 length = strlen(output);
1621 if (write_in_full(out_fd, output, length) != length) {
1622 ret = write_error(lock->filename);
1623 goto out;
1626 fclose(config_file);
1627 unlock_and_out:
1628 if (commit_lock_file(lock) < 0)
1629 ret = error("could not commit config file %s", config_filename);
1630 out:
1631 free(config_filename);
1632 return ret;
1636 * Call this to report error for your variable that should not
1637 * get a boolean value (i.e. "[my] var" means "true").
1639 int config_error_nonbool(const char *var)
1641 return error("Missing value for '%s'", var);