config: eliminate config_exclusive_filename
[git/dscho.git] / config.c
blob1e30ad9d18dc51eeaee72e33b6cc133e6ead1c99
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 static void lowercase(char *p)
31 for (; *p; p++)
32 *p = tolower(*p);
35 void git_config_push_parameter(const char *text)
37 struct strbuf env = STRBUF_INIT;
38 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
39 if (old) {
40 strbuf_addstr(&env, old);
41 strbuf_addch(&env, ' ');
43 sq_quote_buf(&env, text);
44 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
45 strbuf_release(&env);
48 int git_config_parse_parameter(const char *text,
49 config_fn_t fn, void *data)
51 struct strbuf **pair;
52 pair = strbuf_split_str(text, '=', 2);
53 if (!pair[0])
54 return error("bogus config parameter: %s", text);
55 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=')
56 strbuf_setlen(pair[0], pair[0]->len - 1);
57 strbuf_trim(pair[0]);
58 if (!pair[0]->len) {
59 strbuf_list_free(pair);
60 return error("bogus config parameter: %s", text);
62 lowercase(pair[0]->buf);
63 if (fn(pair[0]->buf, pair[1] ? pair[1]->buf : NULL, data) < 0) {
64 strbuf_list_free(pair);
65 return -1;
67 strbuf_list_free(pair);
68 return 0;
71 int git_config_from_parameters(config_fn_t fn, void *data)
73 const char *env = getenv(CONFIG_DATA_ENVIRONMENT);
74 char *envw;
75 const char **argv = NULL;
76 int nr = 0, alloc = 0;
77 int i;
79 if (!env)
80 return 0;
81 /* sq_dequote will write over it */
82 envw = xstrdup(env);
84 if (sq_dequote_to_argv(envw, &argv, &nr, &alloc) < 0) {
85 free(envw);
86 return error("bogus format in " CONFIG_DATA_ENVIRONMENT);
89 for (i = 0; i < nr; i++) {
90 if (git_config_parse_parameter(argv[i], fn, data) < 0) {
91 free(argv);
92 free(envw);
93 return -1;
97 free(argv);
98 free(envw);
99 return nr > 0;
102 static int get_next_char(void)
104 int c;
105 FILE *f;
107 c = '\n';
108 if (cf && ((f = cf->f) != NULL)) {
109 c = fgetc(f);
110 if (c == '\r') {
111 /* DOS like systems */
112 c = fgetc(f);
113 if (c != '\n') {
114 ungetc(c, f);
115 c = '\r';
118 if (c == '\n')
119 cf->linenr++;
120 if (c == EOF) {
121 cf->eof = 1;
122 c = '\n';
125 return c;
128 static char *parse_value(void)
130 int quote = 0, comment = 0, space = 0;
132 strbuf_reset(&cf->value);
133 for (;;) {
134 int c = get_next_char();
135 if (c == '\n') {
136 if (quote)
137 return NULL;
138 return cf->value.buf;
140 if (comment)
141 continue;
142 if (isspace(c) && !quote) {
143 if (cf->value.len)
144 space++;
145 continue;
147 if (!quote) {
148 if (c == ';' || c == '#') {
149 comment = 1;
150 continue;
153 for (; space; space--)
154 strbuf_addch(&cf->value, ' ');
155 if (c == '\\') {
156 c = get_next_char();
157 switch (c) {
158 case '\n':
159 continue;
160 case 't':
161 c = '\t';
162 break;
163 case 'b':
164 c = '\b';
165 break;
166 case 'n':
167 c = '\n';
168 break;
169 /* Some characters escape as themselves */
170 case '\\': case '"':
171 break;
172 /* Reject unknown escape sequences */
173 default:
174 return NULL;
176 strbuf_addch(&cf->value, c);
177 continue;
179 if (c == '"') {
180 quote = 1-quote;
181 continue;
183 strbuf_addch(&cf->value, c);
187 static inline int iskeychar(int c)
189 return isalnum(c) || c == '-';
192 static int get_value(config_fn_t fn, void *data, char *name, unsigned int len)
194 int c;
195 char *value;
197 /* Get the full name */
198 for (;;) {
199 c = get_next_char();
200 if (cf->eof)
201 break;
202 if (!iskeychar(c))
203 break;
204 name[len++] = tolower(c);
205 if (len >= MAXNAME)
206 return -1;
208 name[len] = 0;
209 while (c == ' ' || c == '\t')
210 c = get_next_char();
212 value = NULL;
213 if (c != '\n') {
214 if (c != '=')
215 return -1;
216 value = parse_value();
217 if (!value)
218 return -1;
220 return fn(name, value, data);
223 static int get_extended_base_var(char *name, int baselen, int c)
225 do {
226 if (c == '\n')
227 return -1;
228 c = get_next_char();
229 } while (isspace(c));
231 /* We require the format to be '[base "extension"]' */
232 if (c != '"')
233 return -1;
234 name[baselen++] = '.';
236 for (;;) {
237 int c = get_next_char();
238 if (c == '\n')
239 return -1;
240 if (c == '"')
241 break;
242 if (c == '\\') {
243 c = get_next_char();
244 if (c == '\n')
245 return -1;
247 name[baselen++] = c;
248 if (baselen > MAXNAME / 2)
249 return -1;
252 /* Final ']' */
253 if (get_next_char() != ']')
254 return -1;
255 return baselen;
258 static int get_base_var(char *name)
260 int baselen = 0;
262 for (;;) {
263 int c = get_next_char();
264 if (cf->eof)
265 return -1;
266 if (c == ']')
267 return baselen;
268 if (isspace(c))
269 return get_extended_base_var(name, baselen, c);
270 if (!iskeychar(c) && c != '.')
271 return -1;
272 if (baselen > MAXNAME / 2)
273 return -1;
274 name[baselen++] = tolower(c);
278 static int git_parse_file(config_fn_t fn, void *data)
280 int comment = 0;
281 int baselen = 0;
282 char *var = cf->var;
284 /* U+FEFF Byte Order Mark in UTF8 */
285 static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
286 const unsigned char *bomptr = utf8_bom;
288 for (;;) {
289 int c = get_next_char();
290 if (bomptr && *bomptr) {
291 /* We are at the file beginning; skip UTF8-encoded BOM
292 * if present. Sane editors won't put this in on their
293 * own, but e.g. Windows Notepad will do it happily. */
294 if ((unsigned char) c == *bomptr) {
295 bomptr++;
296 continue;
297 } else {
298 /* Do not tolerate partial BOM. */
299 if (bomptr != utf8_bom)
300 break;
301 /* No BOM at file beginning. Cool. */
302 bomptr = NULL;
305 if (c == '\n') {
306 if (cf->eof)
307 return 0;
308 comment = 0;
309 continue;
311 if (comment || isspace(c))
312 continue;
313 if (c == '#' || c == ';') {
314 comment = 1;
315 continue;
317 if (c == '[') {
318 baselen = get_base_var(var);
319 if (baselen <= 0)
320 break;
321 var[baselen++] = '.';
322 var[baselen] = 0;
323 continue;
325 if (!isalpha(c))
326 break;
327 var[baselen] = tolower(c);
328 if (get_value(fn, data, var, baselen+1) < 0)
329 break;
331 die("bad config file line %d in %s", cf->linenr, cf->name);
334 static int parse_unit_factor(const char *end, uintmax_t *val)
336 if (!*end)
337 return 1;
338 else if (!strcasecmp(end, "k")) {
339 *val *= 1024;
340 return 1;
342 else if (!strcasecmp(end, "m")) {
343 *val *= 1024 * 1024;
344 return 1;
346 else if (!strcasecmp(end, "g")) {
347 *val *= 1024 * 1024 * 1024;
348 return 1;
350 return 0;
353 static int git_parse_long(const char *value, long *ret)
355 if (value && *value) {
356 char *end;
357 intmax_t val;
358 uintmax_t uval;
359 uintmax_t factor = 1;
361 errno = 0;
362 val = strtoimax(value, &end, 0);
363 if (errno == ERANGE)
364 return 0;
365 if (!parse_unit_factor(end, &factor))
366 return 0;
367 uval = abs(val);
368 uval *= factor;
369 if ((uval > maximum_signed_value_of_type(long)) ||
370 (abs(val) > uval))
371 return 0;
372 val *= factor;
373 *ret = val;
374 return 1;
376 return 0;
379 int git_parse_ulong(const char *value, unsigned long *ret)
381 if (value && *value) {
382 char *end;
383 uintmax_t val;
384 uintmax_t oldval;
386 errno = 0;
387 val = strtoumax(value, &end, 0);
388 if (errno == ERANGE)
389 return 0;
390 oldval = val;
391 if (!parse_unit_factor(end, &val))
392 return 0;
393 if ((val > maximum_unsigned_value_of_type(long)) ||
394 (oldval > val))
395 return 0;
396 *ret = val;
397 return 1;
399 return 0;
402 static void die_bad_config(const char *name)
404 if (cf && cf->name)
405 die("bad config value for '%s' in %s", name, cf->name);
406 die("bad config value for '%s'", name);
409 int git_config_int(const char *name, const char *value)
411 long ret = 0;
412 if (!git_parse_long(value, &ret))
413 die_bad_config(name);
414 return ret;
417 unsigned long git_config_ulong(const char *name, const char *value)
419 unsigned long ret;
420 if (!git_parse_ulong(value, &ret))
421 die_bad_config(name);
422 return ret;
425 static int git_config_maybe_bool_text(const char *name, const char *value)
427 if (!value)
428 return 1;
429 if (!*value)
430 return 0;
431 if (!strcasecmp(value, "true")
432 || !strcasecmp(value, "yes")
433 || !strcasecmp(value, "on"))
434 return 1;
435 if (!strcasecmp(value, "false")
436 || !strcasecmp(value, "no")
437 || !strcasecmp(value, "off"))
438 return 0;
439 return -1;
442 int git_config_maybe_bool(const char *name, const char *value)
444 long v = git_config_maybe_bool_text(name, value);
445 if (0 <= v)
446 return v;
447 if (git_parse_long(value, &v))
448 return !!v;
449 return -1;
452 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
454 int v = git_config_maybe_bool_text(name, value);
455 if (0 <= v) {
456 *is_bool = 1;
457 return v;
459 *is_bool = 0;
460 return git_config_int(name, value);
463 int git_config_bool(const char *name, const char *value)
465 int discard;
466 return !!git_config_bool_or_int(name, value, &discard);
469 int git_config_string(const char **dest, const char *var, const char *value)
471 if (!value)
472 return config_error_nonbool(var);
473 *dest = xstrdup(value);
474 return 0;
477 int git_config_pathname(const char **dest, const char *var, const char *value)
479 if (!value)
480 return config_error_nonbool(var);
481 *dest = expand_user_path(value);
482 if (!*dest)
483 die("Failed to expand user dir in: '%s'", value);
484 return 0;
487 static int git_default_core_config(const char *var, const char *value)
489 /* This needs a better name */
490 if (!strcmp(var, "core.filemode")) {
491 trust_executable_bit = git_config_bool(var, value);
492 return 0;
494 if (!strcmp(var, "core.trustctime")) {
495 trust_ctime = git_config_bool(var, value);
496 return 0;
499 if (!strcmp(var, "core.quotepath")) {
500 quote_path_fully = git_config_bool(var, value);
501 return 0;
504 if (!strcmp(var, "core.symlinks")) {
505 has_symlinks = git_config_bool(var, value);
506 return 0;
509 if (!strcmp(var, "core.ignorecase")) {
510 ignore_case = git_config_bool(var, value);
511 return 0;
514 if (!strcmp(var, "core.attributesfile"))
515 return git_config_pathname(&git_attributes_file, var, value);
517 if (!strcmp(var, "core.bare")) {
518 is_bare_repository_cfg = git_config_bool(var, value);
519 return 0;
522 if (!strcmp(var, "core.ignorestat")) {
523 assume_unchanged = git_config_bool(var, value);
524 return 0;
527 if (!strcmp(var, "core.prefersymlinkrefs")) {
528 prefer_symlink_refs = git_config_bool(var, value);
529 return 0;
532 if (!strcmp(var, "core.logallrefupdates")) {
533 log_all_ref_updates = git_config_bool(var, value);
534 return 0;
537 if (!strcmp(var, "core.warnambiguousrefs")) {
538 warn_ambiguous_refs = git_config_bool(var, value);
539 return 0;
542 if (!strcmp(var, "core.abbrev")) {
543 int abbrev = git_config_int(var, value);
544 if (abbrev < minimum_abbrev || abbrev > 40)
545 return -1;
546 default_abbrev = abbrev;
547 return 0;
550 if (!strcmp(var, "core.loosecompression")) {
551 int level = git_config_int(var, value);
552 if (level == -1)
553 level = Z_DEFAULT_COMPRESSION;
554 else if (level < 0 || level > Z_BEST_COMPRESSION)
555 die("bad zlib compression level %d", level);
556 zlib_compression_level = level;
557 zlib_compression_seen = 1;
558 return 0;
561 if (!strcmp(var, "core.compression")) {
562 int level = git_config_int(var, value);
563 if (level == -1)
564 level = Z_DEFAULT_COMPRESSION;
565 else if (level < 0 || level > Z_BEST_COMPRESSION)
566 die("bad zlib compression level %d", level);
567 core_compression_level = level;
568 core_compression_seen = 1;
569 if (!zlib_compression_seen)
570 zlib_compression_level = level;
571 return 0;
574 if (!strcmp(var, "core.packedgitwindowsize")) {
575 int pgsz_x2 = getpagesize() * 2;
576 packed_git_window_size = git_config_ulong(var, value);
578 /* This value must be multiple of (pagesize * 2) */
579 packed_git_window_size /= pgsz_x2;
580 if (packed_git_window_size < 1)
581 packed_git_window_size = 1;
582 packed_git_window_size *= pgsz_x2;
583 return 0;
586 if (!strcmp(var, "core.bigfilethreshold")) {
587 big_file_threshold = git_config_ulong(var, value);
588 return 0;
591 if (!strcmp(var, "core.packedgitlimit")) {
592 packed_git_limit = git_config_ulong(var, value);
593 return 0;
596 if (!strcmp(var, "core.deltabasecachelimit")) {
597 delta_base_cache_limit = git_config_ulong(var, value);
598 return 0;
601 if (!strcmp(var, "core.logpackaccess"))
602 return git_config_string(&log_pack_access, var, value);
604 if (!strcmp(var, "core.autocrlf")) {
605 if (value && !strcasecmp(value, "input")) {
606 if (core_eol == EOL_CRLF)
607 return error("core.autocrlf=input conflicts with core.eol=crlf");
608 auto_crlf = AUTO_CRLF_INPUT;
609 return 0;
611 auto_crlf = git_config_bool(var, value);
612 return 0;
615 if (!strcmp(var, "core.safecrlf")) {
616 if (value && !strcasecmp(value, "warn")) {
617 safe_crlf = SAFE_CRLF_WARN;
618 return 0;
620 safe_crlf = git_config_bool(var, value);
621 return 0;
624 if (!strcmp(var, "core.eol")) {
625 if (value && !strcasecmp(value, "lf"))
626 core_eol = EOL_LF;
627 else if (value && !strcasecmp(value, "crlf"))
628 core_eol = EOL_CRLF;
629 else if (value && !strcasecmp(value, "native"))
630 core_eol = EOL_NATIVE;
631 else
632 core_eol = EOL_UNSET;
633 if (core_eol == EOL_CRLF && auto_crlf == AUTO_CRLF_INPUT)
634 return error("core.autocrlf=input conflicts with core.eol=crlf");
635 return 0;
638 if (!strcmp(var, "core.notesref")) {
639 notes_ref_name = xstrdup(value);
640 return 0;
643 if (!strcmp(var, "core.pager"))
644 return git_config_string(&pager_program, var, value);
646 if (!strcmp(var, "core.editor"))
647 return git_config_string(&editor_program, var, value);
649 if (!strcmp(var, "core.askpass"))
650 return git_config_string(&askpass_program, var, value);
652 if (!strcmp(var, "core.excludesfile"))
653 return git_config_pathname(&excludes_file, var, value);
655 if (!strcmp(var, "core.whitespace")) {
656 if (!value)
657 return config_error_nonbool(var);
658 whitespace_rule_cfg = parse_whitespace_rule(value);
659 return 0;
662 if (!strcmp(var, "core.fsyncobjectfiles")) {
663 fsync_object_files = git_config_bool(var, value);
664 return 0;
667 if (!strcmp(var, "core.preloadindex")) {
668 core_preload_index = git_config_bool(var, value);
669 return 0;
672 if (!strcmp(var, "core.createobject")) {
673 if (!strcmp(value, "rename"))
674 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
675 else if (!strcmp(value, "link"))
676 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
677 else
678 die("Invalid mode for object creation: %s", value);
679 return 0;
682 if (!strcmp(var, "core.sparsecheckout")) {
683 core_apply_sparse_checkout = git_config_bool(var, value);
684 return 0;
687 /* Add other config variables here and to Documentation/config.txt. */
688 return 0;
691 static int git_default_user_config(const char *var, const char *value)
693 if (!strcmp(var, "user.name")) {
694 if (!value)
695 return config_error_nonbool(var);
696 strlcpy(git_default_name, value, sizeof(git_default_name));
697 user_ident_explicitly_given |= IDENT_NAME_GIVEN;
698 return 0;
701 if (!strcmp(var, "user.email")) {
702 if (!value)
703 return config_error_nonbool(var);
704 strlcpy(git_default_email, value, sizeof(git_default_email));
705 user_ident_explicitly_given |= IDENT_MAIL_GIVEN;
706 return 0;
709 /* Add other config variables here and to Documentation/config.txt. */
710 return 0;
713 static int git_default_i18n_config(const char *var, const char *value)
715 if (!strcmp(var, "i18n.commitencoding"))
716 return git_config_string(&git_commit_encoding, var, value);
718 if (!strcmp(var, "i18n.logoutputencoding"))
719 return git_config_string(&git_log_output_encoding, var, value);
721 /* Add other config variables here and to Documentation/config.txt. */
722 return 0;
725 static int git_default_branch_config(const char *var, const char *value)
727 if (!strcmp(var, "branch.autosetupmerge")) {
728 if (value && !strcasecmp(value, "always")) {
729 git_branch_track = BRANCH_TRACK_ALWAYS;
730 return 0;
732 git_branch_track = git_config_bool(var, value);
733 return 0;
735 if (!strcmp(var, "branch.autosetuprebase")) {
736 if (!value)
737 return config_error_nonbool(var);
738 else if (!strcmp(value, "never"))
739 autorebase = AUTOREBASE_NEVER;
740 else if (!strcmp(value, "local"))
741 autorebase = AUTOREBASE_LOCAL;
742 else if (!strcmp(value, "remote"))
743 autorebase = AUTOREBASE_REMOTE;
744 else if (!strcmp(value, "always"))
745 autorebase = AUTOREBASE_ALWAYS;
746 else
747 return error("Malformed value for %s", var);
748 return 0;
751 /* Add other config variables here and to Documentation/config.txt. */
752 return 0;
755 static int git_default_push_config(const char *var, const char *value)
757 if (!strcmp(var, "push.default")) {
758 if (!value)
759 return config_error_nonbool(var);
760 else if (!strcmp(value, "nothing"))
761 push_default = PUSH_DEFAULT_NOTHING;
762 else if (!strcmp(value, "matching"))
763 push_default = PUSH_DEFAULT_MATCHING;
764 else if (!strcmp(value, "upstream"))
765 push_default = PUSH_DEFAULT_UPSTREAM;
766 else if (!strcmp(value, "tracking")) /* deprecated */
767 push_default = PUSH_DEFAULT_UPSTREAM;
768 else if (!strcmp(value, "current"))
769 push_default = PUSH_DEFAULT_CURRENT;
770 else {
771 error("Malformed value for %s: %s", var, value);
772 return error("Must be one of nothing, matching, "
773 "tracking or current.");
775 return 0;
778 /* Add other config variables here and to Documentation/config.txt. */
779 return 0;
782 static int git_default_mailmap_config(const char *var, const char *value)
784 if (!strcmp(var, "mailmap.file"))
785 return git_config_string(&git_mailmap_file, var, value);
787 /* Add other config variables here and to Documentation/config.txt. */
788 return 0;
791 int git_default_config(const char *var, const char *value, void *dummy)
793 if (!prefixcmp(var, "core."))
794 return git_default_core_config(var, value);
796 if (!prefixcmp(var, "user."))
797 return git_default_user_config(var, value);
799 if (!prefixcmp(var, "i18n."))
800 return git_default_i18n_config(var, value);
802 if (!prefixcmp(var, "branch."))
803 return git_default_branch_config(var, value);
805 if (!prefixcmp(var, "push."))
806 return git_default_push_config(var, value);
808 if (!prefixcmp(var, "mailmap."))
809 return git_default_mailmap_config(var, value);
811 if (!prefixcmp(var, "advice."))
812 return git_default_advice_config(var, value);
814 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
815 pager_use_color = git_config_bool(var,value);
816 return 0;
819 if (!strcmp(var, "pack.packsizelimit")) {
820 pack_size_limit_cfg = git_config_ulong(var, value);
821 return 0;
823 /* Add other config variables here and to Documentation/config.txt. */
824 return 0;
827 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
829 int ret;
830 FILE *f = fopen(filename, "r");
832 ret = -1;
833 if (f) {
834 config_file top;
836 /* push config-file parsing state stack */
837 top.prev = cf;
838 top.f = f;
839 top.name = filename;
840 top.linenr = 1;
841 top.eof = 0;
842 strbuf_init(&top.value, 1024);
843 cf = &top;
845 ret = git_parse_file(fn, data);
847 /* pop config-file parsing state stack */
848 strbuf_release(&top.value);
849 cf = top.prev;
851 fclose(f);
853 return ret;
856 const char *git_etc_gitconfig(void)
858 static const char *system_wide;
859 if (!system_wide)
860 system_wide = system_path(ETC_GITCONFIG);
861 return system_wide;
864 int git_env_bool(const char *k, int def)
866 const char *v = getenv(k);
867 return v ? git_config_bool(k, v) : def;
870 int git_config_system(void)
872 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
875 int git_config_early(config_fn_t fn, void *data, const char *repo_config)
877 int ret = 0, found = 0;
878 const char *home = NULL;
880 if (git_config_system() && !access(git_etc_gitconfig(), R_OK)) {
881 ret += git_config_from_file(fn, git_etc_gitconfig(),
882 data);
883 found += 1;
886 home = getenv("HOME");
887 if (home) {
888 char buf[PATH_MAX];
889 char *user_config = mksnpath(buf, sizeof(buf), "%s/.gitconfig", home);
890 if (!access(user_config, R_OK)) {
891 ret += git_config_from_file(fn, user_config, data);
892 found += 1;
896 if (repo_config && !access(repo_config, R_OK)) {
897 ret += git_config_from_file(fn, repo_config, data);
898 found += 1;
901 switch (git_config_from_parameters(fn, data)) {
902 case -1: /* error */
903 die("unable to parse command-line config");
904 break;
905 case 0: /* found nothing */
906 break;
907 default: /* found at least one item */
908 found++;
909 break;
912 return ret == 0 ? found : ret;
915 int git_config_with_options(config_fn_t fn, void *data,
916 const char *filename)
918 char *repo_config = NULL;
919 int ret;
922 * If we have a specific filename, use it. Otherwise, follow the
923 * regular lookup sequence.
925 if (filename)
926 return git_config_from_file(fn, filename, data);
928 repo_config = git_pathdup("config");
929 ret = git_config_early(fn, data, repo_config);
930 if (repo_config)
931 free(repo_config);
932 return ret;
935 int git_config(config_fn_t fn, void *data)
937 return git_config_with_options(fn, data, NULL);
941 * Find all the stuff for git_config_set() below.
944 #define MAX_MATCHES 512
946 static struct {
947 int baselen;
948 char *key;
949 int do_not_match;
950 regex_t *value_regex;
951 int multi_replace;
952 size_t offset[MAX_MATCHES];
953 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
954 int seen;
955 } store;
957 static int matches(const char *key, const char *value)
959 return !strcmp(key, store.key) &&
960 (store.value_regex == NULL ||
961 (store.do_not_match ^
962 !regexec(store.value_regex, value, 0, NULL, 0)));
965 static int store_aux(const char *key, const char *value, void *cb)
967 const char *ep;
968 size_t section_len;
969 FILE *f = cf->f;
971 switch (store.state) {
972 case KEY_SEEN:
973 if (matches(key, value)) {
974 if (store.seen == 1 && store.multi_replace == 0) {
975 warning("%s has multiple values", key);
976 } else if (store.seen >= MAX_MATCHES) {
977 error("too many matches for %s", key);
978 return 1;
981 store.offset[store.seen] = ftell(f);
982 store.seen++;
984 break;
985 case SECTION_SEEN:
987 * What we are looking for is in store.key (both
988 * section and var), and its section part is baselen
989 * long. We found key (again, both section and var).
990 * We would want to know if this key is in the same
991 * section as what we are looking for. We already
992 * know we are in the same section as what should
993 * hold store.key.
995 ep = strrchr(key, '.');
996 section_len = ep - key;
998 if ((section_len != store.baselen) ||
999 memcmp(key, store.key, section_len+1)) {
1000 store.state = SECTION_END_SEEN;
1001 break;
1005 * Do not increment matches: this is no match, but we
1006 * just made sure we are in the desired section.
1008 store.offset[store.seen] = ftell(f);
1009 /* fallthru */
1010 case SECTION_END_SEEN:
1011 case START:
1012 if (matches(key, value)) {
1013 store.offset[store.seen] = ftell(f);
1014 store.state = KEY_SEEN;
1015 store.seen++;
1016 } else {
1017 if (strrchr(key, '.') - key == store.baselen &&
1018 !strncmp(key, store.key, store.baselen)) {
1019 store.state = SECTION_SEEN;
1020 store.offset[store.seen] = ftell(f);
1024 return 0;
1027 static int write_error(const char *filename)
1029 error("failed to write new configuration file %s", filename);
1031 /* Same error code as "failed to rename". */
1032 return 4;
1035 static int store_write_section(int fd, const char *key)
1037 const char *dot;
1038 int i, success;
1039 struct strbuf sb = STRBUF_INIT;
1041 dot = memchr(key, '.', store.baselen);
1042 if (dot) {
1043 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
1044 for (i = dot - key + 1; i < store.baselen; i++) {
1045 if (key[i] == '"' || key[i] == '\\')
1046 strbuf_addch(&sb, '\\');
1047 strbuf_addch(&sb, key[i]);
1049 strbuf_addstr(&sb, "\"]\n");
1050 } else {
1051 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
1054 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1055 strbuf_release(&sb);
1057 return success;
1060 static int store_write_pair(int fd, const char *key, const char *value)
1062 int i, success;
1063 int length = strlen(key + store.baselen + 1);
1064 const char *quote = "";
1065 struct strbuf sb = STRBUF_INIT;
1068 * Check to see if the value needs to be surrounded with a dq pair.
1069 * Note that problematic characters are always backslash-quoted; this
1070 * check is about not losing leading or trailing SP and strings that
1071 * follow beginning-of-comment characters (i.e. ';' and '#') by the
1072 * configuration parser.
1074 if (value[0] == ' ')
1075 quote = "\"";
1076 for (i = 0; value[i]; i++)
1077 if (value[i] == ';' || value[i] == '#')
1078 quote = "\"";
1079 if (i && value[i - 1] == ' ')
1080 quote = "\"";
1082 strbuf_addf(&sb, "\t%.*s = %s",
1083 length, key + store.baselen + 1, quote);
1085 for (i = 0; value[i]; i++)
1086 switch (value[i]) {
1087 case '\n':
1088 strbuf_addstr(&sb, "\\n");
1089 break;
1090 case '\t':
1091 strbuf_addstr(&sb, "\\t");
1092 break;
1093 case '"':
1094 case '\\':
1095 strbuf_addch(&sb, '\\');
1096 default:
1097 strbuf_addch(&sb, value[i]);
1098 break;
1100 strbuf_addf(&sb, "%s\n", quote);
1102 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1103 strbuf_release(&sb);
1105 return success;
1108 static ssize_t find_beginning_of_line(const char *contents, size_t size,
1109 size_t offset_, int *found_bracket)
1111 size_t equal_offset = size, bracket_offset = size;
1112 ssize_t offset;
1114 contline:
1115 for (offset = offset_-2; offset > 0
1116 && contents[offset] != '\n'; offset--)
1117 switch (contents[offset]) {
1118 case '=': equal_offset = offset; break;
1119 case ']': bracket_offset = offset; break;
1121 if (offset > 0 && contents[offset-1] == '\\') {
1122 offset_ = offset;
1123 goto contline;
1125 if (bracket_offset < equal_offset) {
1126 *found_bracket = 1;
1127 offset = bracket_offset+1;
1128 } else
1129 offset++;
1131 return offset;
1134 int git_config_set_in_file(const char *config_filename,
1135 const char *key, const char *value)
1137 return git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
1140 int git_config_set(const char *key, const char *value)
1142 return git_config_set_multivar(key, value, NULL, 0);
1146 * Auxiliary function to sanity-check and split the key into the section
1147 * identifier and variable name.
1149 * Returns 0 on success, -1 when there is an invalid character in the key and
1150 * -2 if there is no section name in the key.
1152 * store_key - pointer to char* which will hold a copy of the key with
1153 * lowercase section and variable name
1154 * baselen - pointer to int which will hold the length of the
1155 * section + subsection part, can be NULL
1157 int git_config_parse_key(const char *key, char **store_key, int *baselen_)
1159 int i, dot, baselen;
1160 const char *last_dot = strrchr(key, '.');
1163 * Since "key" actually contains the section name and the real
1164 * key name separated by a dot, we have to know where the dot is.
1167 if (last_dot == NULL || last_dot == key) {
1168 error("key does not contain a section: %s", key);
1169 return -CONFIG_NO_SECTION_OR_NAME;
1172 if (!last_dot[1]) {
1173 error("key does not contain variable name: %s", key);
1174 return -CONFIG_NO_SECTION_OR_NAME;
1177 baselen = last_dot - key;
1178 if (baselen_)
1179 *baselen_ = baselen;
1182 * Validate the key and while at it, lower case it for matching.
1184 *store_key = xmalloc(strlen(key) + 1);
1186 dot = 0;
1187 for (i = 0; key[i]; i++) {
1188 unsigned char c = key[i];
1189 if (c == '.')
1190 dot = 1;
1191 /* Leave the extended basename untouched.. */
1192 if (!dot || i > baselen) {
1193 if (!iskeychar(c) ||
1194 (i == baselen + 1 && !isalpha(c))) {
1195 error("invalid key: %s", key);
1196 goto out_free_ret_1;
1198 c = tolower(c);
1199 } else if (c == '\n') {
1200 error("invalid key (newline): %s", key);
1201 goto out_free_ret_1;
1203 (*store_key)[i] = c;
1205 (*store_key)[i] = 0;
1207 return 0;
1209 out_free_ret_1:
1210 free(*store_key);
1211 return -CONFIG_INVALID_KEY;
1215 * If value==NULL, unset in (remove from) config,
1216 * if value_regex!=NULL, disregard key/value pairs where value does not match.
1217 * if multi_replace==0, nothing, or only one matching key/value is replaced,
1218 * else all matching key/values (regardless how many) are removed,
1219 * before the new pair is written.
1221 * Returns 0 on success.
1223 * This function does this:
1225 * - it locks the config file by creating ".git/config.lock"
1227 * - it then parses the config using store_aux() as validator to find
1228 * the position on the key/value pair to replace. If it is to be unset,
1229 * it must be found exactly once.
1231 * - the config file is mmap()ed and the part before the match (if any) is
1232 * written to the lock file, then the changed part and the rest.
1234 * - the config file is removed and the lock file rename()d to it.
1237 int git_config_set_multivar_in_file(const char *config_filename,
1238 const char *key, const char *value,
1239 const char *value_regex, int multi_replace)
1241 int fd = -1, in_fd;
1242 int ret;
1243 struct lock_file *lock = NULL;
1244 char *filename_buf = NULL;
1246 /* parse-key returns negative; flip the sign to feed exit(3) */
1247 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
1248 if (ret)
1249 goto out_free;
1251 store.multi_replace = multi_replace;
1253 if (!config_filename)
1254 config_filename = filename_buf = git_pathdup("config");
1257 * The lock serves a purpose in addition to locking: the new
1258 * contents of .git/config will be written into it.
1260 lock = xcalloc(sizeof(struct lock_file), 1);
1261 fd = hold_lock_file_for_update(lock, config_filename, 0);
1262 if (fd < 0) {
1263 error("could not lock config file %s: %s", config_filename, strerror(errno));
1264 free(store.key);
1265 ret = CONFIG_NO_LOCK;
1266 goto out_free;
1270 * If .git/config does not exist yet, write a minimal version.
1272 in_fd = open(config_filename, O_RDONLY);
1273 if ( in_fd < 0 ) {
1274 free(store.key);
1276 if ( ENOENT != errno ) {
1277 error("opening %s: %s", config_filename,
1278 strerror(errno));
1279 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
1280 goto out_free;
1282 /* if nothing to unset, error out */
1283 if (value == NULL) {
1284 ret = CONFIG_NOTHING_SET;
1285 goto out_free;
1288 store.key = (char *)key;
1289 if (!store_write_section(fd, key) ||
1290 !store_write_pair(fd, key, value))
1291 goto write_err_out;
1292 } else {
1293 struct stat st;
1294 char *contents;
1295 size_t contents_sz, copy_begin, copy_end;
1296 int i, new_line = 0;
1298 if (value_regex == NULL)
1299 store.value_regex = NULL;
1300 else {
1301 if (value_regex[0] == '!') {
1302 store.do_not_match = 1;
1303 value_regex++;
1304 } else
1305 store.do_not_match = 0;
1307 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1308 if (regcomp(store.value_regex, value_regex,
1309 REG_EXTENDED)) {
1310 error("invalid pattern: %s", value_regex);
1311 free(store.value_regex);
1312 ret = CONFIG_INVALID_PATTERN;
1313 goto out_free;
1317 store.offset[0] = 0;
1318 store.state = START;
1319 store.seen = 0;
1322 * After this, store.offset will contain the *end* offset
1323 * of the last match, or remain at 0 if no match was found.
1324 * As a side effect, we make sure to transform only a valid
1325 * existing config file.
1327 if (git_config_from_file(store_aux, config_filename, NULL)) {
1328 error("invalid config file %s", config_filename);
1329 free(store.key);
1330 if (store.value_regex != NULL) {
1331 regfree(store.value_regex);
1332 free(store.value_regex);
1334 ret = CONFIG_INVALID_FILE;
1335 goto out_free;
1338 free(store.key);
1339 if (store.value_regex != NULL) {
1340 regfree(store.value_regex);
1341 free(store.value_regex);
1344 /* if nothing to unset, or too many matches, error out */
1345 if ((store.seen == 0 && value == NULL) ||
1346 (store.seen > 1 && multi_replace == 0)) {
1347 ret = CONFIG_NOTHING_SET;
1348 goto out_free;
1351 fstat(in_fd, &st);
1352 contents_sz = xsize_t(st.st_size);
1353 contents = xmmap(NULL, contents_sz, PROT_READ,
1354 MAP_PRIVATE, in_fd, 0);
1355 close(in_fd);
1357 if (store.seen == 0)
1358 store.seen = 1;
1360 for (i = 0, copy_begin = 0; i < store.seen; i++) {
1361 if (store.offset[i] == 0) {
1362 store.offset[i] = copy_end = contents_sz;
1363 } else if (store.state != KEY_SEEN) {
1364 copy_end = store.offset[i];
1365 } else
1366 copy_end = find_beginning_of_line(
1367 contents, contents_sz,
1368 store.offset[i]-2, &new_line);
1370 if (copy_end > 0 && contents[copy_end-1] != '\n')
1371 new_line = 1;
1373 /* write the first part of the config */
1374 if (copy_end > copy_begin) {
1375 if (write_in_full(fd, contents + copy_begin,
1376 copy_end - copy_begin) <
1377 copy_end - copy_begin)
1378 goto write_err_out;
1379 if (new_line &&
1380 write_str_in_full(fd, "\n") != 1)
1381 goto write_err_out;
1383 copy_begin = store.offset[i];
1386 /* write the pair (value == NULL means unset) */
1387 if (value != NULL) {
1388 if (store.state == START) {
1389 if (!store_write_section(fd, key))
1390 goto write_err_out;
1392 if (!store_write_pair(fd, key, value))
1393 goto write_err_out;
1396 /* write the rest of the config */
1397 if (copy_begin < contents_sz)
1398 if (write_in_full(fd, contents + copy_begin,
1399 contents_sz - copy_begin) <
1400 contents_sz - copy_begin)
1401 goto write_err_out;
1403 munmap(contents, contents_sz);
1406 if (commit_lock_file(lock) < 0) {
1407 error("could not commit config file %s", config_filename);
1408 ret = CONFIG_NO_WRITE;
1409 goto out_free;
1413 * lock is committed, so don't try to roll it back below.
1414 * NOTE: Since lockfile.c keeps a linked list of all created
1415 * lock_file structures, it isn't safe to free(lock). It's
1416 * better to just leave it hanging around.
1418 lock = NULL;
1419 ret = 0;
1421 out_free:
1422 if (lock)
1423 rollback_lock_file(lock);
1424 free(filename_buf);
1425 return ret;
1427 write_err_out:
1428 ret = write_error(lock->filename);
1429 goto out_free;
1433 int git_config_set_multivar(const char *key, const char *value,
1434 const char *value_regex, int multi_replace)
1436 return git_config_set_multivar_in_file(NULL, key, value, value_regex,
1437 multi_replace);
1440 static int section_name_match (const char *buf, const char *name)
1442 int i = 0, j = 0, dot = 0;
1443 if (buf[i] != '[')
1444 return 0;
1445 for (i = 1; buf[i] && buf[i] != ']'; i++) {
1446 if (!dot && isspace(buf[i])) {
1447 dot = 1;
1448 if (name[j++] != '.')
1449 break;
1450 for (i++; isspace(buf[i]); i++)
1451 ; /* do nothing */
1452 if (buf[i] != '"')
1453 break;
1454 continue;
1456 if (buf[i] == '\\' && dot)
1457 i++;
1458 else if (buf[i] == '"' && dot) {
1459 for (i++; isspace(buf[i]); i++)
1460 ; /* do_nothing */
1461 break;
1463 if (buf[i] != name[j++])
1464 break;
1466 if (buf[i] == ']' && name[j] == 0) {
1468 * We match, now just find the right length offset by
1469 * gobbling up any whitespace after it, as well
1471 i++;
1472 for (; buf[i] && isspace(buf[i]); i++)
1473 ; /* do nothing */
1474 return i;
1476 return 0;
1479 /* if new_name == NULL, the section is removed instead */
1480 int git_config_rename_section_in_file(const char *config_filename,
1481 const char *old_name, const char *new_name)
1483 int ret = 0, remove = 0;
1484 char *filename_buf = NULL;
1485 struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1486 int out_fd;
1487 char buf[1024];
1488 FILE *config_file;
1490 if (!config_filename)
1491 config_filename = filename_buf = git_pathdup("config");
1493 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1494 if (out_fd < 0) {
1495 ret = error("could not lock config file %s", config_filename);
1496 goto out;
1499 if (!(config_file = fopen(config_filename, "rb"))) {
1500 /* no config file means nothing to rename, no error */
1501 goto unlock_and_out;
1504 while (fgets(buf, sizeof(buf), config_file)) {
1505 int i;
1506 int length;
1507 char *output = buf;
1508 for (i = 0; buf[i] && isspace(buf[i]); i++)
1509 ; /* do nothing */
1510 if (buf[i] == '[') {
1511 /* it's a section */
1512 int offset = section_name_match(&buf[i], old_name);
1513 if (offset > 0) {
1514 ret++;
1515 if (new_name == NULL) {
1516 remove = 1;
1517 continue;
1519 store.baselen = strlen(new_name);
1520 if (!store_write_section(out_fd, new_name)) {
1521 ret = write_error(lock->filename);
1522 goto out;
1525 * We wrote out the new section, with
1526 * a newline, now skip the old
1527 * section's length
1529 output += offset + i;
1530 if (strlen(output) > 0) {
1532 * More content means there's
1533 * a declaration to put on the
1534 * next line; indent with a
1535 * tab
1537 output -= 1;
1538 output[0] = '\t';
1541 remove = 0;
1543 if (remove)
1544 continue;
1545 length = strlen(output);
1546 if (write_in_full(out_fd, output, length) != length) {
1547 ret = write_error(lock->filename);
1548 goto out;
1551 fclose(config_file);
1552 unlock_and_out:
1553 if (commit_lock_file(lock) < 0)
1554 ret = error("could not commit config file %s", config_filename);
1555 out:
1556 free(filename_buf);
1557 return ret;
1560 int git_config_rename_section(const char *old_name, const char *new_name)
1562 return git_config_rename_section_in_file(NULL, old_name, new_name);
1566 * Call this to report error for your variable that should not
1567 * get a boolean value (i.e. "[my] var" means "true").
1569 int config_error_nonbool(const char *var)
1571 return error("Missing value for '%s'", var);