config: support values longer than 1023 bytes
[git/dscho.git] / config.c
blob5a1db4ff0b975445ded2cb9365ad1bb681025548
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"
11 #define MAXNAME (256)
13 static FILE *config_file;
14 static const char *config_file_name;
15 static int config_linenr;
16 static int config_file_eof;
17 static int zlib_compression_seen;
19 const char *config_exclusive_filename = NULL;
21 static int get_next_char(void)
23 int c;
24 FILE *f;
26 c = '\n';
27 if ((f = config_file) != NULL) {
28 c = fgetc(f);
29 if (c == '\r') {
30 /* DOS like systems */
31 c = fgetc(f);
32 if (c != '\n') {
33 ungetc(c, f);
34 c = '\r';
37 if (c == '\n')
38 config_linenr++;
39 if (c == EOF) {
40 config_file_eof = 1;
41 c = '\n';
44 return c;
47 static char *parse_value(void)
49 static struct strbuf value = STRBUF_INIT;
50 int quote = 0, comment = 0, space = 0;
52 strbuf_reset(&value);
53 for (;;) {
54 int c = get_next_char();
55 if (c == '\n') {
56 if (quote)
57 return NULL;
58 return value.buf;
60 if (comment)
61 continue;
62 if (isspace(c) && !quote) {
63 if (value.len)
64 space++;
65 continue;
67 if (!quote) {
68 if (c == ';' || c == '#') {
69 comment = 1;
70 continue;
73 for (; space; space--)
74 strbuf_addch(&value, ' ');
75 if (c == '\\') {
76 c = get_next_char();
77 switch (c) {
78 case '\n':
79 continue;
80 case 't':
81 c = '\t';
82 break;
83 case 'b':
84 c = '\b';
85 break;
86 case 'n':
87 c = '\n';
88 break;
89 /* Some characters escape as themselves */
90 case '\\': case '"':
91 break;
92 /* Reject unknown escape sequences */
93 default:
94 return NULL;
96 strbuf_addch(&value, c);
97 continue;
99 if (c == '"') {
100 quote = 1-quote;
101 continue;
103 strbuf_addch(&value, c);
107 static inline int iskeychar(int c)
109 return isalnum(c) || c == '-';
112 static int get_value(config_fn_t fn, void *data, char *name, unsigned int len)
114 int c;
115 char *value;
117 /* Get the full name */
118 for (;;) {
119 c = get_next_char();
120 if (config_file_eof)
121 break;
122 if (!iskeychar(c))
123 break;
124 name[len++] = tolower(c);
125 if (len >= MAXNAME)
126 return -1;
128 name[len] = 0;
129 while (c == ' ' || c == '\t')
130 c = get_next_char();
132 value = NULL;
133 if (c != '\n') {
134 if (c != '=')
135 return -1;
136 value = parse_value();
137 if (!value)
138 return -1;
140 return fn(name, value, data);
143 static int get_extended_base_var(char *name, int baselen, int c)
145 do {
146 if (c == '\n')
147 return -1;
148 c = get_next_char();
149 } while (isspace(c));
151 /* We require the format to be '[base "extension"]' */
152 if (c != '"')
153 return -1;
154 name[baselen++] = '.';
156 for (;;) {
157 int c = get_next_char();
158 if (c == '\n')
159 return -1;
160 if (c == '"')
161 break;
162 if (c == '\\') {
163 c = get_next_char();
164 if (c == '\n')
165 return -1;
167 name[baselen++] = c;
168 if (baselen > MAXNAME / 2)
169 return -1;
172 /* Final ']' */
173 if (get_next_char() != ']')
174 return -1;
175 return baselen;
178 static int get_base_var(char *name)
180 int baselen = 0;
182 for (;;) {
183 int c = get_next_char();
184 if (config_file_eof)
185 return -1;
186 if (c == ']')
187 return baselen;
188 if (isspace(c))
189 return get_extended_base_var(name, baselen, c);
190 if (!iskeychar(c) && c != '.')
191 return -1;
192 if (baselen > MAXNAME / 2)
193 return -1;
194 name[baselen++] = tolower(c);
198 static int git_parse_file(config_fn_t fn, void *data)
200 int comment = 0;
201 int baselen = 0;
202 static char var[MAXNAME];
204 /* U+FEFF Byte Order Mark in UTF8 */
205 static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
206 const unsigned char *bomptr = utf8_bom;
208 for (;;) {
209 int c = get_next_char();
210 if (bomptr && *bomptr) {
211 /* We are at the file beginning; skip UTF8-encoded BOM
212 * if present. Sane editors won't put this in on their
213 * own, but e.g. Windows Notepad will do it happily. */
214 if ((unsigned char) c == *bomptr) {
215 bomptr++;
216 continue;
217 } else {
218 /* Do not tolerate partial BOM. */
219 if (bomptr != utf8_bom)
220 break;
221 /* No BOM at file beginning. Cool. */
222 bomptr = NULL;
225 if (c == '\n') {
226 if (config_file_eof)
227 return 0;
228 comment = 0;
229 continue;
231 if (comment || isspace(c))
232 continue;
233 if (c == '#' || c == ';') {
234 comment = 1;
235 continue;
237 if (c == '[') {
238 baselen = get_base_var(var);
239 if (baselen <= 0)
240 break;
241 var[baselen++] = '.';
242 var[baselen] = 0;
243 continue;
245 if (!isalpha(c))
246 break;
247 var[baselen] = tolower(c);
248 if (get_value(fn, data, var, baselen+1) < 0)
249 break;
251 die("bad config file line %d in %s", config_linenr, config_file_name);
254 static int parse_unit_factor(const char *end, unsigned long *val)
256 if (!*end)
257 return 1;
258 else if (!strcasecmp(end, "k")) {
259 *val *= 1024;
260 return 1;
262 else if (!strcasecmp(end, "m")) {
263 *val *= 1024 * 1024;
264 return 1;
266 else if (!strcasecmp(end, "g")) {
267 *val *= 1024 * 1024 * 1024;
268 return 1;
270 return 0;
273 static int git_parse_long(const char *value, long *ret)
275 if (value && *value) {
276 char *end;
277 long val = strtol(value, &end, 0);
278 unsigned long factor = 1;
279 if (!parse_unit_factor(end, &factor))
280 return 0;
281 *ret = val * factor;
282 return 1;
284 return 0;
287 int git_parse_ulong(const char *value, unsigned long *ret)
289 if (value && *value) {
290 char *end;
291 unsigned long val = strtoul(value, &end, 0);
292 if (!parse_unit_factor(end, &val))
293 return 0;
294 *ret = val;
295 return 1;
297 return 0;
300 static void die_bad_config(const char *name)
302 if (config_file_name)
303 die("bad config value for '%s' in %s", name, config_file_name);
304 die("bad config value for '%s'", name);
307 int git_config_int(const char *name, const char *value)
309 long ret = 0;
310 if (!git_parse_long(value, &ret))
311 die_bad_config(name);
312 return ret;
315 unsigned long git_config_ulong(const char *name, const char *value)
317 unsigned long ret;
318 if (!git_parse_ulong(value, &ret))
319 die_bad_config(name);
320 return ret;
323 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
325 *is_bool = 1;
326 if (!value)
327 return 1;
328 if (!*value)
329 return 0;
330 if (!strcasecmp(value, "true") || !strcasecmp(value, "yes") || !strcasecmp(value, "on"))
331 return 1;
332 if (!strcasecmp(value, "false") || !strcasecmp(value, "no") || !strcasecmp(value, "off"))
333 return 0;
334 *is_bool = 0;
335 return git_config_int(name, value);
338 int git_config_bool(const char *name, const char *value)
340 int discard;
341 return !!git_config_bool_or_int(name, value, &discard);
344 int git_config_string(const char **dest, const char *var, const char *value)
346 if (!value)
347 return config_error_nonbool(var);
348 *dest = xstrdup(value);
349 return 0;
352 int git_config_pathname(const char **dest, const char *var, const char *value)
354 if (!value)
355 return config_error_nonbool(var);
356 *dest = expand_user_path(value);
357 if (!*dest)
358 die("Failed to expand user dir in: '%s'", value);
359 return 0;
362 static int git_default_core_config(const char *var, const char *value)
364 /* This needs a better name */
365 if (!strcmp(var, "core.filemode")) {
366 trust_executable_bit = git_config_bool(var, value);
367 return 0;
369 if (!strcmp(var, "core.trustctime")) {
370 trust_ctime = git_config_bool(var, value);
371 return 0;
374 if (!strcmp(var, "core.quotepath")) {
375 quote_path_fully = git_config_bool(var, value);
376 return 0;
379 if (!strcmp(var, "core.symlinks")) {
380 has_symlinks = git_config_bool(var, value);
381 return 0;
384 if (!strcmp(var, "core.ignorecase")) {
385 ignore_case = git_config_bool(var, value);
386 return 0;
389 if (!strcmp(var, "core.bare")) {
390 is_bare_repository_cfg = git_config_bool(var, value);
391 return 0;
394 if (!strcmp(var, "core.ignorestat")) {
395 assume_unchanged = git_config_bool(var, value);
396 return 0;
399 if (!strcmp(var, "core.prefersymlinkrefs")) {
400 prefer_symlink_refs = git_config_bool(var, value);
401 return 0;
404 if (!strcmp(var, "core.logallrefupdates")) {
405 log_all_ref_updates = git_config_bool(var, value);
406 return 0;
409 if (!strcmp(var, "core.warnambiguousrefs")) {
410 warn_ambiguous_refs = git_config_bool(var, value);
411 return 0;
414 if (!strcmp(var, "core.loosecompression")) {
415 int level = git_config_int(var, value);
416 if (level == -1)
417 level = Z_DEFAULT_COMPRESSION;
418 else if (level < 0 || level > Z_BEST_COMPRESSION)
419 die("bad zlib compression level %d", level);
420 zlib_compression_level = level;
421 zlib_compression_seen = 1;
422 return 0;
425 if (!strcmp(var, "core.compression")) {
426 int level = git_config_int(var, value);
427 if (level == -1)
428 level = Z_DEFAULT_COMPRESSION;
429 else if (level < 0 || level > Z_BEST_COMPRESSION)
430 die("bad zlib compression level %d", level);
431 core_compression_level = level;
432 core_compression_seen = 1;
433 if (!zlib_compression_seen)
434 zlib_compression_level = level;
435 return 0;
438 if (!strcmp(var, "core.packedgitwindowsize")) {
439 int pgsz_x2 = getpagesize() * 2;
440 packed_git_window_size = git_config_int(var, value);
442 /* This value must be multiple of (pagesize * 2) */
443 packed_git_window_size /= pgsz_x2;
444 if (packed_git_window_size < 1)
445 packed_git_window_size = 1;
446 packed_git_window_size *= pgsz_x2;
447 return 0;
450 if (!strcmp(var, "core.packedgitlimit")) {
451 packed_git_limit = git_config_int(var, value);
452 return 0;
455 if (!strcmp(var, "core.deltabasecachelimit")) {
456 delta_base_cache_limit = git_config_int(var, value);
457 return 0;
460 if (!strcmp(var, "core.autocrlf")) {
461 if (value && !strcasecmp(value, "input")) {
462 auto_crlf = -1;
463 return 0;
465 auto_crlf = git_config_bool(var, value);
466 return 0;
469 if (!strcmp(var, "core.safecrlf")) {
470 if (value && !strcasecmp(value, "warn")) {
471 safe_crlf = SAFE_CRLF_WARN;
472 return 0;
474 safe_crlf = git_config_bool(var, value);
475 return 0;
478 if (!strcmp(var, "core.notesref")) {
479 notes_ref_name = xstrdup(value);
480 return 0;
483 if (!strcmp(var, "core.pager"))
484 return git_config_string(&pager_program, var, value);
486 if (!strcmp(var, "core.editor"))
487 return git_config_string(&editor_program, var, value);
489 if (!strcmp(var, "core.excludesfile"))
490 return git_config_pathname(&excludes_file, var, value);
492 if (!strcmp(var, "core.whitespace")) {
493 if (!value)
494 return config_error_nonbool(var);
495 whitespace_rule_cfg = parse_whitespace_rule(value);
496 return 0;
499 if (!strcmp(var, "core.fsyncobjectfiles")) {
500 fsync_object_files = git_config_bool(var, value);
501 return 0;
504 if (!strcmp(var, "core.preloadindex")) {
505 core_preload_index = git_config_bool(var, value);
506 return 0;
509 if (!strcmp(var, "core.createobject")) {
510 if (!strcmp(value, "rename"))
511 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
512 else if (!strcmp(value, "link"))
513 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
514 else
515 die("Invalid mode for object creation: %s", value);
516 return 0;
519 if (!strcmp(var, "core.sparsecheckout")) {
520 core_apply_sparse_checkout = git_config_bool(var, value);
521 return 0;
524 /* Add other config variables here and to Documentation/config.txt. */
525 return 0;
528 static int git_default_user_config(const char *var, const char *value)
530 if (!strcmp(var, "user.name")) {
531 if (!value)
532 return config_error_nonbool(var);
533 strlcpy(git_default_name, value, sizeof(git_default_name));
534 user_ident_explicitly_given |= IDENT_NAME_GIVEN;
535 return 0;
538 if (!strcmp(var, "user.email")) {
539 if (!value)
540 return config_error_nonbool(var);
541 strlcpy(git_default_email, value, sizeof(git_default_email));
542 user_ident_explicitly_given |= IDENT_MAIL_GIVEN;
543 return 0;
546 /* Add other config variables here and to Documentation/config.txt. */
547 return 0;
550 static int git_default_i18n_config(const char *var, const char *value)
552 if (!strcmp(var, "i18n.commitencoding"))
553 return git_config_string(&git_commit_encoding, var, value);
555 if (!strcmp(var, "i18n.logoutputencoding"))
556 return git_config_string(&git_log_output_encoding, var, value);
558 /* Add other config variables here and to Documentation/config.txt. */
559 return 0;
562 static int git_default_branch_config(const char *var, const char *value)
564 if (!strcmp(var, "branch.autosetupmerge")) {
565 if (value && !strcasecmp(value, "always")) {
566 git_branch_track = BRANCH_TRACK_ALWAYS;
567 return 0;
569 git_branch_track = git_config_bool(var, value);
570 return 0;
572 if (!strcmp(var, "branch.autosetuprebase")) {
573 if (!value)
574 return config_error_nonbool(var);
575 else if (!strcmp(value, "never"))
576 autorebase = AUTOREBASE_NEVER;
577 else if (!strcmp(value, "local"))
578 autorebase = AUTOREBASE_LOCAL;
579 else if (!strcmp(value, "remote"))
580 autorebase = AUTOREBASE_REMOTE;
581 else if (!strcmp(value, "always"))
582 autorebase = AUTOREBASE_ALWAYS;
583 else
584 return error("Malformed value for %s", var);
585 return 0;
588 /* Add other config variables here and to Documentation/config.txt. */
589 return 0;
592 static int git_default_push_config(const char *var, const char *value)
594 if (!strcmp(var, "push.default")) {
595 if (!value)
596 return config_error_nonbool(var);
597 else if (!strcmp(value, "nothing"))
598 push_default = PUSH_DEFAULT_NOTHING;
599 else if (!strcmp(value, "matching"))
600 push_default = PUSH_DEFAULT_MATCHING;
601 else if (!strcmp(value, "tracking"))
602 push_default = PUSH_DEFAULT_TRACKING;
603 else if (!strcmp(value, "current"))
604 push_default = PUSH_DEFAULT_CURRENT;
605 else {
606 error("Malformed value for %s: %s", var, value);
607 return error("Must be one of nothing, matching, "
608 "tracking or current.");
610 return 0;
613 /* Add other config variables here and to Documentation/config.txt. */
614 return 0;
617 static int git_default_mailmap_config(const char *var, const char *value)
619 if (!strcmp(var, "mailmap.file"))
620 return git_config_string(&git_mailmap_file, var, value);
622 /* Add other config variables here and to Documentation/config.txt. */
623 return 0;
626 int git_default_config(const char *var, const char *value, void *dummy)
628 if (!prefixcmp(var, "core."))
629 return git_default_core_config(var, value);
631 if (!prefixcmp(var, "user."))
632 return git_default_user_config(var, value);
634 if (!prefixcmp(var, "i18n."))
635 return git_default_i18n_config(var, value);
637 if (!prefixcmp(var, "branch."))
638 return git_default_branch_config(var, value);
640 if (!prefixcmp(var, "push."))
641 return git_default_push_config(var, value);
643 if (!prefixcmp(var, "mailmap."))
644 return git_default_mailmap_config(var, value);
646 if (!prefixcmp(var, "advice."))
647 return git_default_advice_config(var, value);
649 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
650 pager_use_color = git_config_bool(var,value);
651 return 0;
654 /* Add other config variables here and to Documentation/config.txt. */
655 return 0;
658 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
660 int ret;
661 FILE *f = fopen(filename, "r");
663 ret = -1;
664 if (f) {
665 config_file = f;
666 config_file_name = filename;
667 config_linenr = 1;
668 config_file_eof = 0;
669 ret = git_parse_file(fn, data);
670 fclose(f);
671 config_file_name = NULL;
673 return ret;
676 const char *git_etc_gitconfig(void)
678 static const char *system_wide;
679 if (!system_wide)
680 system_wide = system_path(ETC_GITCONFIG);
681 return system_wide;
684 static int git_env_bool(const char *k, int def)
686 const char *v = getenv(k);
687 return v ? git_config_bool(k, v) : def;
690 int git_config_system(void)
692 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
695 int git_config_global(void)
697 return !git_env_bool("GIT_CONFIG_NOGLOBAL", 0);
700 int git_config(config_fn_t fn, void *data)
702 int ret = 0, found = 0;
703 char *repo_config = NULL;
704 const char *home = NULL;
706 /* Setting $GIT_CONFIG makes git read _only_ the given config file. */
707 if (config_exclusive_filename)
708 return git_config_from_file(fn, config_exclusive_filename, data);
709 if (git_config_system() && !access(git_etc_gitconfig(), R_OK)) {
710 ret += git_config_from_file(fn, git_etc_gitconfig(),
711 data);
712 found += 1;
715 home = getenv("HOME");
716 if (git_config_global() && home) {
717 char *user_config = xstrdup(mkpath("%s/.gitconfig", home));
718 if (!access(user_config, R_OK)) {
719 ret += git_config_from_file(fn, user_config, data);
720 found += 1;
722 free(user_config);
725 repo_config = git_pathdup("config");
726 if (!access(repo_config, R_OK)) {
727 ret += git_config_from_file(fn, repo_config, data);
728 found += 1;
730 free(repo_config);
731 if (found == 0)
732 return -1;
733 return ret;
737 * Find all the stuff for git_config_set() below.
740 #define MAX_MATCHES 512
742 static struct {
743 int baselen;
744 char *key;
745 int do_not_match;
746 regex_t *value_regex;
747 int multi_replace;
748 size_t offset[MAX_MATCHES];
749 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
750 int seen;
751 } store;
753 static int matches(const char *key, const char *value)
755 return !strcmp(key, store.key) &&
756 (store.value_regex == NULL ||
757 (store.do_not_match ^
758 !regexec(store.value_regex, value, 0, NULL, 0)));
761 static int store_aux(const char *key, const char *value, void *cb)
763 const char *ep;
764 size_t section_len;
766 switch (store.state) {
767 case KEY_SEEN:
768 if (matches(key, value)) {
769 if (store.seen == 1 && store.multi_replace == 0) {
770 warning("%s has multiple values", key);
771 } else if (store.seen >= MAX_MATCHES) {
772 error("too many matches for %s", key);
773 return 1;
776 store.offset[store.seen] = ftell(config_file);
777 store.seen++;
779 break;
780 case SECTION_SEEN:
782 * What we are looking for is in store.key (both
783 * section and var), and its section part is baselen
784 * long. We found key (again, both section and var).
785 * We would want to know if this key is in the same
786 * section as what we are looking for. We already
787 * know we are in the same section as what should
788 * hold store.key.
790 ep = strrchr(key, '.');
791 section_len = ep - key;
793 if ((section_len != store.baselen) ||
794 memcmp(key, store.key, section_len+1)) {
795 store.state = SECTION_END_SEEN;
796 break;
800 * Do not increment matches: this is no match, but we
801 * just made sure we are in the desired section.
803 store.offset[store.seen] = ftell(config_file);
804 /* fallthru */
805 case SECTION_END_SEEN:
806 case START:
807 if (matches(key, value)) {
808 store.offset[store.seen] = ftell(config_file);
809 store.state = KEY_SEEN;
810 store.seen++;
811 } else {
812 if (strrchr(key, '.') - key == store.baselen &&
813 !strncmp(key, store.key, store.baselen)) {
814 store.state = SECTION_SEEN;
815 store.offset[store.seen] = ftell(config_file);
819 return 0;
822 static int write_error(const char *filename)
824 error("failed to write new configuration file %s", filename);
826 /* Same error code as "failed to rename". */
827 return 4;
830 static int store_write_section(int fd, const char *key)
832 const char *dot;
833 int i, success;
834 struct strbuf sb = STRBUF_INIT;
836 dot = memchr(key, '.', store.baselen);
837 if (dot) {
838 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
839 for (i = dot - key + 1; i < store.baselen; i++) {
840 if (key[i] == '"' || key[i] == '\\')
841 strbuf_addch(&sb, '\\');
842 strbuf_addch(&sb, key[i]);
844 strbuf_addstr(&sb, "\"]\n");
845 } else {
846 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
849 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
850 strbuf_release(&sb);
852 return success;
855 static int store_write_pair(int fd, const char *key, const char *value)
857 int i, success;
858 int length = strlen(key + store.baselen + 1);
859 const char *quote = "";
860 struct strbuf sb = STRBUF_INIT;
863 * Check to see if the value needs to be surrounded with a dq pair.
864 * Note that problematic characters are always backslash-quoted; this
865 * check is about not losing leading or trailing SP and strings that
866 * follow beginning-of-comment characters (i.e. ';' and '#') by the
867 * configuration parser.
869 if (value[0] == ' ')
870 quote = "\"";
871 for (i = 0; value[i]; i++)
872 if (value[i] == ';' || value[i] == '#')
873 quote = "\"";
874 if (i && value[i - 1] == ' ')
875 quote = "\"";
877 strbuf_addf(&sb, "\t%.*s = %s",
878 length, key + store.baselen + 1, quote);
880 for (i = 0; value[i]; i++)
881 switch (value[i]) {
882 case '\n':
883 strbuf_addstr(&sb, "\\n");
884 break;
885 case '\t':
886 strbuf_addstr(&sb, "\\t");
887 break;
888 case '"':
889 case '\\':
890 strbuf_addch(&sb, '\\');
891 default:
892 strbuf_addch(&sb, value[i]);
893 break;
895 strbuf_addf(&sb, "%s\n", quote);
897 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
898 strbuf_release(&sb);
900 return success;
903 static ssize_t find_beginning_of_line(const char *contents, size_t size,
904 size_t offset_, int *found_bracket)
906 size_t equal_offset = size, bracket_offset = size;
907 ssize_t offset;
909 contline:
910 for (offset = offset_-2; offset > 0
911 && contents[offset] != '\n'; offset--)
912 switch (contents[offset]) {
913 case '=': equal_offset = offset; break;
914 case ']': bracket_offset = offset; break;
916 if (offset > 0 && contents[offset-1] == '\\') {
917 offset_ = offset;
918 goto contline;
920 if (bracket_offset < equal_offset) {
921 *found_bracket = 1;
922 offset = bracket_offset+1;
923 } else
924 offset++;
926 return offset;
929 int git_config_set(const char *key, const char *value)
931 return git_config_set_multivar(key, value, NULL, 0);
935 * If value==NULL, unset in (remove from) config,
936 * if value_regex!=NULL, disregard key/value pairs where value does not match.
937 * if multi_replace==0, nothing, or only one matching key/value is replaced,
938 * else all matching key/values (regardless how many) are removed,
939 * before the new pair is written.
941 * Returns 0 on success.
943 * This function does this:
945 * - it locks the config file by creating ".git/config.lock"
947 * - it then parses the config using store_aux() as validator to find
948 * the position on the key/value pair to replace. If it is to be unset,
949 * it must be found exactly once.
951 * - the config file is mmap()ed and the part before the match (if any) is
952 * written to the lock file, then the changed part and the rest.
954 * - the config file is removed and the lock file rename()d to it.
957 int git_config_set_multivar(const char *key, const char *value,
958 const char *value_regex, int multi_replace)
960 int i, dot;
961 int fd = -1, in_fd;
962 int ret;
963 char *config_filename;
964 struct lock_file *lock = NULL;
965 const char *last_dot = strrchr(key, '.');
967 if (config_exclusive_filename)
968 config_filename = xstrdup(config_exclusive_filename);
969 else
970 config_filename = git_pathdup("config");
973 * Since "key" actually contains the section name and the real
974 * key name separated by a dot, we have to know where the dot is.
977 if (last_dot == NULL) {
978 error("key does not contain a section: %s", key);
979 ret = 2;
980 goto out_free;
982 store.baselen = last_dot - key;
984 store.multi_replace = multi_replace;
987 * Validate the key and while at it, lower case it for matching.
989 store.key = xmalloc(strlen(key) + 1);
990 dot = 0;
991 for (i = 0; key[i]; i++) {
992 unsigned char c = key[i];
993 if (c == '.')
994 dot = 1;
995 /* Leave the extended basename untouched.. */
996 if (!dot || i > store.baselen) {
997 if (!iskeychar(c) || (i == store.baselen+1 && !isalpha(c))) {
998 error("invalid key: %s", key);
999 free(store.key);
1000 ret = 1;
1001 goto out_free;
1003 c = tolower(c);
1004 } else if (c == '\n') {
1005 error("invalid key (newline): %s", key);
1006 free(store.key);
1007 ret = 1;
1008 goto out_free;
1010 store.key[i] = c;
1012 store.key[i] = 0;
1015 * The lock serves a purpose in addition to locking: the new
1016 * contents of .git/config will be written into it.
1018 lock = xcalloc(sizeof(struct lock_file), 1);
1019 fd = hold_lock_file_for_update(lock, config_filename, 0);
1020 if (fd < 0) {
1021 error("could not lock config file %s: %s", config_filename, strerror(errno));
1022 free(store.key);
1023 ret = -1;
1024 goto out_free;
1028 * If .git/config does not exist yet, write a minimal version.
1030 in_fd = open(config_filename, O_RDONLY);
1031 if ( in_fd < 0 ) {
1032 free(store.key);
1034 if ( ENOENT != errno ) {
1035 error("opening %s: %s", config_filename,
1036 strerror(errno));
1037 ret = 3; /* same as "invalid config file" */
1038 goto out_free;
1040 /* if nothing to unset, error out */
1041 if (value == NULL) {
1042 ret = 5;
1043 goto out_free;
1046 store.key = (char *)key;
1047 if (!store_write_section(fd, key) ||
1048 !store_write_pair(fd, key, value))
1049 goto write_err_out;
1050 } else {
1051 struct stat st;
1052 char *contents;
1053 size_t contents_sz, copy_begin, copy_end;
1054 int i, new_line = 0;
1056 if (value_regex == NULL)
1057 store.value_regex = NULL;
1058 else {
1059 if (value_regex[0] == '!') {
1060 store.do_not_match = 1;
1061 value_regex++;
1062 } else
1063 store.do_not_match = 0;
1065 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1066 if (regcomp(store.value_regex, value_regex,
1067 REG_EXTENDED)) {
1068 error("invalid pattern: %s", value_regex);
1069 free(store.value_regex);
1070 ret = 6;
1071 goto out_free;
1075 store.offset[0] = 0;
1076 store.state = START;
1077 store.seen = 0;
1080 * After this, store.offset will contain the *end* offset
1081 * of the last match, or remain at 0 if no match was found.
1082 * As a side effect, we make sure to transform only a valid
1083 * existing config file.
1085 if (git_config_from_file(store_aux, config_filename, NULL)) {
1086 error("invalid config file %s", config_filename);
1087 free(store.key);
1088 if (store.value_regex != NULL) {
1089 regfree(store.value_regex);
1090 free(store.value_regex);
1092 ret = 3;
1093 goto out_free;
1096 free(store.key);
1097 if (store.value_regex != NULL) {
1098 regfree(store.value_regex);
1099 free(store.value_regex);
1102 /* if nothing to unset, or too many matches, error out */
1103 if ((store.seen == 0 && value == NULL) ||
1104 (store.seen > 1 && multi_replace == 0)) {
1105 ret = 5;
1106 goto out_free;
1109 fstat(in_fd, &st);
1110 contents_sz = xsize_t(st.st_size);
1111 contents = xmmap(NULL, contents_sz, PROT_READ,
1112 MAP_PRIVATE, in_fd, 0);
1113 close(in_fd);
1115 if (store.seen == 0)
1116 store.seen = 1;
1118 for (i = 0, copy_begin = 0; i < store.seen; i++) {
1119 if (store.offset[i] == 0) {
1120 store.offset[i] = copy_end = contents_sz;
1121 } else if (store.state != KEY_SEEN) {
1122 copy_end = store.offset[i];
1123 } else
1124 copy_end = find_beginning_of_line(
1125 contents, contents_sz,
1126 store.offset[i]-2, &new_line);
1128 if (copy_end > 0 && contents[copy_end-1] != '\n')
1129 new_line = 1;
1131 /* write the first part of the config */
1132 if (copy_end > copy_begin) {
1133 if (write_in_full(fd, contents + copy_begin,
1134 copy_end - copy_begin) <
1135 copy_end - copy_begin)
1136 goto write_err_out;
1137 if (new_line &&
1138 write_str_in_full(fd, "\n") != 1)
1139 goto write_err_out;
1141 copy_begin = store.offset[i];
1144 /* write the pair (value == NULL means unset) */
1145 if (value != NULL) {
1146 if (store.state == START) {
1147 if (!store_write_section(fd, key))
1148 goto write_err_out;
1150 if (!store_write_pair(fd, key, value))
1151 goto write_err_out;
1154 /* write the rest of the config */
1155 if (copy_begin < contents_sz)
1156 if (write_in_full(fd, contents + copy_begin,
1157 contents_sz - copy_begin) <
1158 contents_sz - copy_begin)
1159 goto write_err_out;
1161 munmap(contents, contents_sz);
1164 if (commit_lock_file(lock) < 0) {
1165 error("could not commit config file %s", config_filename);
1166 ret = 4;
1167 goto out_free;
1171 * lock is committed, so don't try to roll it back below.
1172 * NOTE: Since lockfile.c keeps a linked list of all created
1173 * lock_file structures, it isn't safe to free(lock). It's
1174 * better to just leave it hanging around.
1176 lock = NULL;
1177 ret = 0;
1179 out_free:
1180 if (lock)
1181 rollback_lock_file(lock);
1182 free(config_filename);
1183 return ret;
1185 write_err_out:
1186 ret = write_error(lock->filename);
1187 goto out_free;
1191 static int section_name_match (const char *buf, const char *name)
1193 int i = 0, j = 0, dot = 0;
1194 if (buf[i] != '[')
1195 return 0;
1196 for (i = 1; buf[i] && buf[i] != ']'; i++) {
1197 if (!dot && isspace(buf[i])) {
1198 dot = 1;
1199 if (name[j++] != '.')
1200 break;
1201 for (i++; isspace(buf[i]); i++)
1202 ; /* do nothing */
1203 if (buf[i] != '"')
1204 break;
1205 continue;
1207 if (buf[i] == '\\' && dot)
1208 i++;
1209 else if (buf[i] == '"' && dot) {
1210 for (i++; isspace(buf[i]); i++)
1211 ; /* do_nothing */
1212 break;
1214 if (buf[i] != name[j++])
1215 break;
1217 if (buf[i] == ']' && name[j] == 0) {
1219 * We match, now just find the right length offset by
1220 * gobbling up any whitespace after it, as well
1222 i++;
1223 for (; buf[i] && isspace(buf[i]); i++)
1224 ; /* do nothing */
1225 return i;
1227 return 0;
1230 /* if new_name == NULL, the section is removed instead */
1231 int git_config_rename_section(const char *old_name, const char *new_name)
1233 int ret = 0, remove = 0;
1234 char *config_filename;
1235 struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1236 int out_fd;
1237 char buf[1024];
1239 if (config_exclusive_filename)
1240 config_filename = xstrdup(config_exclusive_filename);
1241 else
1242 config_filename = git_pathdup("config");
1243 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1244 if (out_fd < 0) {
1245 ret = error("could not lock config file %s", config_filename);
1246 goto out;
1249 if (!(config_file = fopen(config_filename, "rb"))) {
1250 /* no config file means nothing to rename, no error */
1251 goto unlock_and_out;
1254 while (fgets(buf, sizeof(buf), config_file)) {
1255 int i;
1256 int length;
1257 char *output = buf;
1258 for (i = 0; buf[i] && isspace(buf[i]); i++)
1259 ; /* do nothing */
1260 if (buf[i] == '[') {
1261 /* it's a section */
1262 int offset = section_name_match(&buf[i], old_name);
1263 if (offset > 0) {
1264 ret++;
1265 if (new_name == NULL) {
1266 remove = 1;
1267 continue;
1269 store.baselen = strlen(new_name);
1270 if (!store_write_section(out_fd, new_name)) {
1271 ret = write_error(lock->filename);
1272 goto out;
1275 * We wrote out the new section, with
1276 * a newline, now skip the old
1277 * section's length
1279 output += offset + i;
1280 if (strlen(output) > 0) {
1282 * More content means there's
1283 * a declaration to put on the
1284 * next line; indent with a
1285 * tab
1287 output -= 1;
1288 output[0] = '\t';
1291 remove = 0;
1293 if (remove)
1294 continue;
1295 length = strlen(output);
1296 if (write_in_full(out_fd, output, length) != length) {
1297 ret = write_error(lock->filename);
1298 goto out;
1301 fclose(config_file);
1302 unlock_and_out:
1303 if (commit_lock_file(lock) < 0)
1304 ret = error("could not commit config file %s", config_filename);
1305 out:
1306 free(config_filename);
1307 return ret;
1311 * Call this to report error for your variable that should not
1312 * get a boolean value (i.e. "[my] var" means "true").
1314 int config_error_nonbool(const char *var)
1316 return error("Missing value for '%s'", var);