Git 1.6.5.8
[git/dscho.git] / config.c
blobb3d1ff4e7cc3eb6ec72aa2d5140def5de5c6966b
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 char value[1024];
50 int quote = 0, comment = 0, len = 0, space = 0;
52 for (;;) {
53 int c = get_next_char();
54 if (len >= sizeof(value) - 1)
55 return NULL;
56 if (c == '\n') {
57 if (quote)
58 return NULL;
59 value[len] = 0;
60 return value;
62 if (comment)
63 continue;
64 if (isspace(c) && !quote) {
65 if (len)
66 space++;
67 continue;
69 if (!quote) {
70 if (c == ';' || c == '#') {
71 comment = 1;
72 continue;
75 for (; space; space--)
76 value[len++] = ' ';
77 if (c == '\\') {
78 c = get_next_char();
79 switch (c) {
80 case '\n':
81 continue;
82 case 't':
83 c = '\t';
84 break;
85 case 'b':
86 c = '\b';
87 break;
88 case 'n':
89 c = '\n';
90 break;
91 /* Some characters escape as themselves */
92 case '\\': case '"':
93 break;
94 /* Reject unknown escape sequences */
95 default:
96 return NULL;
98 value[len++] = c;
99 continue;
101 if (c == '"') {
102 quote = 1-quote;
103 continue;
105 value[len++] = c;
109 static inline int iskeychar(int c)
111 return isalnum(c) || c == '-';
114 static int get_value(config_fn_t fn, void *data, char *name, unsigned int len)
116 int c;
117 char *value;
119 /* Get the full name */
120 for (;;) {
121 c = get_next_char();
122 if (config_file_eof)
123 break;
124 if (!iskeychar(c))
125 break;
126 name[len++] = tolower(c);
127 if (len >= MAXNAME)
128 return -1;
130 name[len] = 0;
131 while (c == ' ' || c == '\t')
132 c = get_next_char();
134 value = NULL;
135 if (c != '\n') {
136 if (c != '=')
137 return -1;
138 value = parse_value();
139 if (!value)
140 return -1;
142 return fn(name, value, data);
145 static int get_extended_base_var(char *name, int baselen, int c)
147 do {
148 if (c == '\n')
149 return -1;
150 c = get_next_char();
151 } while (isspace(c));
153 /* We require the format to be '[base "extension"]' */
154 if (c != '"')
155 return -1;
156 name[baselen++] = '.';
158 for (;;) {
159 int c = get_next_char();
160 if (c == '\n')
161 return -1;
162 if (c == '"')
163 break;
164 if (c == '\\') {
165 c = get_next_char();
166 if (c == '\n')
167 return -1;
169 name[baselen++] = c;
170 if (baselen > MAXNAME / 2)
171 return -1;
174 /* Final ']' */
175 if (get_next_char() != ']')
176 return -1;
177 return baselen;
180 static int get_base_var(char *name)
182 int baselen = 0;
184 for (;;) {
185 int c = get_next_char();
186 if (config_file_eof)
187 return -1;
188 if (c == ']')
189 return baselen;
190 if (isspace(c))
191 return get_extended_base_var(name, baselen, c);
192 if (!iskeychar(c) && c != '.')
193 return -1;
194 if (baselen > MAXNAME / 2)
195 return -1;
196 name[baselen++] = tolower(c);
200 static int git_parse_file(config_fn_t fn, void *data)
202 int comment = 0;
203 int baselen = 0;
204 static char var[MAXNAME];
206 /* U+FEFF Byte Order Mark in UTF8 */
207 static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
208 const unsigned char *bomptr = utf8_bom;
210 for (;;) {
211 int c = get_next_char();
212 if (bomptr && *bomptr) {
213 /* We are at the file beginning; skip UTF8-encoded BOM
214 * if present. Sane editors won't put this in on their
215 * own, but e.g. Windows Notepad will do it happily. */
216 if ((unsigned char) c == *bomptr) {
217 bomptr++;
218 continue;
219 } else {
220 /* Do not tolerate partial BOM. */
221 if (bomptr != utf8_bom)
222 break;
223 /* No BOM at file beginning. Cool. */
224 bomptr = NULL;
227 if (c == '\n') {
228 if (config_file_eof)
229 return 0;
230 comment = 0;
231 continue;
233 if (comment || isspace(c))
234 continue;
235 if (c == '#' || c == ';') {
236 comment = 1;
237 continue;
239 if (c == '[') {
240 baselen = get_base_var(var);
241 if (baselen <= 0)
242 break;
243 var[baselen++] = '.';
244 var[baselen] = 0;
245 continue;
247 if (!isalpha(c))
248 break;
249 var[baselen] = tolower(c);
250 if (get_value(fn, data, var, baselen+1) < 0)
251 break;
253 die("bad config file line %d in %s", config_linenr, config_file_name);
256 static int parse_unit_factor(const char *end, unsigned long *val)
258 if (!*end)
259 return 1;
260 else if (!strcasecmp(end, "k")) {
261 *val *= 1024;
262 return 1;
264 else if (!strcasecmp(end, "m")) {
265 *val *= 1024 * 1024;
266 return 1;
268 else if (!strcasecmp(end, "g")) {
269 *val *= 1024 * 1024 * 1024;
270 return 1;
272 return 0;
275 static int git_parse_long(const char *value, long *ret)
277 if (value && *value) {
278 char *end;
279 long val = strtol(value, &end, 0);
280 unsigned long factor = 1;
281 if (!parse_unit_factor(end, &factor))
282 return 0;
283 *ret = val * factor;
284 return 1;
286 return 0;
289 int git_parse_ulong(const char *value, unsigned long *ret)
291 if (value && *value) {
292 char *end;
293 unsigned long val = strtoul(value, &end, 0);
294 if (!parse_unit_factor(end, &val))
295 return 0;
296 *ret = val;
297 return 1;
299 return 0;
302 static void die_bad_config(const char *name)
304 if (config_file_name)
305 die("bad config value for '%s' in %s", name, config_file_name);
306 die("bad config value for '%s'", name);
309 int git_config_int(const char *name, const char *value)
311 long ret = 0;
312 if (!git_parse_long(value, &ret))
313 die_bad_config(name);
314 return ret;
317 unsigned long git_config_ulong(const char *name, const char *value)
319 unsigned long ret;
320 if (!git_parse_ulong(value, &ret))
321 die_bad_config(name);
322 return ret;
325 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
327 *is_bool = 1;
328 if (!value)
329 return 1;
330 if (!*value)
331 return 0;
332 if (!strcasecmp(value, "true") || !strcasecmp(value, "yes") || !strcasecmp(value, "on"))
333 return 1;
334 if (!strcasecmp(value, "false") || !strcasecmp(value, "no") || !strcasecmp(value, "off"))
335 return 0;
336 *is_bool = 0;
337 return git_config_int(name, value);
340 int git_config_bool(const char *name, const char *value)
342 int discard;
343 return !!git_config_bool_or_int(name, value, &discard);
346 int git_config_string(const char **dest, const char *var, const char *value)
348 if (!value)
349 return config_error_nonbool(var);
350 *dest = xstrdup(value);
351 return 0;
354 int git_config_pathname(const char **dest, const char *var, const char *value)
356 if (!value)
357 return config_error_nonbool(var);
358 *dest = expand_user_path(value);
359 if (!*dest)
360 die("Failed to expand user dir in: '%s'", value);
361 return 0;
364 static int git_default_core_config(const char *var, const char *value)
366 /* This needs a better name */
367 if (!strcmp(var, "core.filemode")) {
368 trust_executable_bit = git_config_bool(var, value);
369 return 0;
371 if (!strcmp(var, "core.trustctime")) {
372 trust_ctime = git_config_bool(var, value);
373 return 0;
376 if (!strcmp(var, "core.quotepath")) {
377 quote_path_fully = git_config_bool(var, value);
378 return 0;
381 if (!strcmp(var, "core.symlinks")) {
382 has_symlinks = git_config_bool(var, value);
383 return 0;
386 if (!strcmp(var, "core.ignorecase")) {
387 ignore_case = git_config_bool(var, value);
388 return 0;
391 if (!strcmp(var, "core.bare")) {
392 is_bare_repository_cfg = git_config_bool(var, value);
393 return 0;
396 if (!strcmp(var, "core.ignorestat")) {
397 assume_unchanged = git_config_bool(var, value);
398 return 0;
401 if (!strcmp(var, "core.prefersymlinkrefs")) {
402 prefer_symlink_refs = git_config_bool(var, value);
403 return 0;
406 if (!strcmp(var, "core.logallrefupdates")) {
407 log_all_ref_updates = git_config_bool(var, value);
408 return 0;
411 if (!strcmp(var, "core.warnambiguousrefs")) {
412 warn_ambiguous_refs = git_config_bool(var, value);
413 return 0;
416 if (!strcmp(var, "core.loosecompression")) {
417 int level = git_config_int(var, value);
418 if (level == -1)
419 level = Z_DEFAULT_COMPRESSION;
420 else if (level < 0 || level > Z_BEST_COMPRESSION)
421 die("bad zlib compression level %d", level);
422 zlib_compression_level = level;
423 zlib_compression_seen = 1;
424 return 0;
427 if (!strcmp(var, "core.compression")) {
428 int level = git_config_int(var, value);
429 if (level == -1)
430 level = Z_DEFAULT_COMPRESSION;
431 else if (level < 0 || level > Z_BEST_COMPRESSION)
432 die("bad zlib compression level %d", level);
433 core_compression_level = level;
434 core_compression_seen = 1;
435 if (!zlib_compression_seen)
436 zlib_compression_level = level;
437 return 0;
440 if (!strcmp(var, "core.packedgitwindowsize")) {
441 int pgsz_x2 = getpagesize() * 2;
442 packed_git_window_size = git_config_int(var, value);
444 /* This value must be multiple of (pagesize * 2) */
445 packed_git_window_size /= pgsz_x2;
446 if (packed_git_window_size < 1)
447 packed_git_window_size = 1;
448 packed_git_window_size *= pgsz_x2;
449 return 0;
452 if (!strcmp(var, "core.packedgitlimit")) {
453 packed_git_limit = git_config_int(var, value);
454 return 0;
457 if (!strcmp(var, "core.deltabasecachelimit")) {
458 delta_base_cache_limit = git_config_int(var, value);
459 return 0;
462 if (!strcmp(var, "core.autocrlf")) {
463 if (value && !strcasecmp(value, "input")) {
464 auto_crlf = -1;
465 return 0;
467 auto_crlf = git_config_bool(var, value);
468 return 0;
471 if (!strcmp(var, "core.safecrlf")) {
472 if (value && !strcasecmp(value, "warn")) {
473 safe_crlf = SAFE_CRLF_WARN;
474 return 0;
476 safe_crlf = git_config_bool(var, value);
477 return 0;
480 if (!strcmp(var, "core.pager"))
481 return git_config_string(&pager_program, var, value);
483 if (!strcmp(var, "core.editor"))
484 return git_config_string(&editor_program, var, value);
486 if (!strcmp(var, "core.excludesfile"))
487 return git_config_pathname(&excludes_file, var, value);
489 if (!strcmp(var, "core.whitespace")) {
490 if (!value)
491 return config_error_nonbool(var);
492 whitespace_rule_cfg = parse_whitespace_rule(value);
493 return 0;
496 if (!strcmp(var, "core.fsyncobjectfiles")) {
497 fsync_object_files = git_config_bool(var, value);
498 return 0;
501 if (!strcmp(var, "core.preloadindex")) {
502 core_preload_index = git_config_bool(var, value);
503 return 0;
506 if (!strcmp(var, "core.createobject")) {
507 if (!strcmp(value, "rename"))
508 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
509 else if (!strcmp(value, "link"))
510 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
511 else
512 die("Invalid mode for object creation: %s", value);
513 return 0;
516 /* Add other config variables here and to Documentation/config.txt. */
517 return 0;
520 static int git_default_user_config(const char *var, const char *value)
522 if (!strcmp(var, "user.name")) {
523 if (!value)
524 return config_error_nonbool(var);
525 strlcpy(git_default_name, value, sizeof(git_default_name));
526 if (git_default_email[0])
527 user_ident_explicitly_given = 1;
528 return 0;
531 if (!strcmp(var, "user.email")) {
532 if (!value)
533 return config_error_nonbool(var);
534 strlcpy(git_default_email, value, sizeof(git_default_email));
535 if (git_default_name[0])
536 user_ident_explicitly_given = 1;
537 return 0;
540 /* Add other config variables here and to Documentation/config.txt. */
541 return 0;
544 static int git_default_i18n_config(const char *var, const char *value)
546 if (!strcmp(var, "i18n.commitencoding"))
547 return git_config_string(&git_commit_encoding, var, value);
549 if (!strcmp(var, "i18n.logoutputencoding"))
550 return git_config_string(&git_log_output_encoding, var, value);
552 /* Add other config variables here and to Documentation/config.txt. */
553 return 0;
556 static int git_default_branch_config(const char *var, const char *value)
558 if (!strcmp(var, "branch.autosetupmerge")) {
559 if (value && !strcasecmp(value, "always")) {
560 git_branch_track = BRANCH_TRACK_ALWAYS;
561 return 0;
563 git_branch_track = git_config_bool(var, value);
564 return 0;
566 if (!strcmp(var, "branch.autosetuprebase")) {
567 if (!value)
568 return config_error_nonbool(var);
569 else if (!strcmp(value, "never"))
570 autorebase = AUTOREBASE_NEVER;
571 else if (!strcmp(value, "local"))
572 autorebase = AUTOREBASE_LOCAL;
573 else if (!strcmp(value, "remote"))
574 autorebase = AUTOREBASE_REMOTE;
575 else if (!strcmp(value, "always"))
576 autorebase = AUTOREBASE_ALWAYS;
577 else
578 return error("Malformed value for %s", var);
579 return 0;
582 /* Add other config variables here and to Documentation/config.txt. */
583 return 0;
586 static int git_default_push_config(const char *var, const char *value)
588 if (!strcmp(var, "push.default")) {
589 if (!value)
590 return config_error_nonbool(var);
591 else if (!strcmp(value, "nothing"))
592 push_default = PUSH_DEFAULT_NOTHING;
593 else if (!strcmp(value, "matching"))
594 push_default = PUSH_DEFAULT_MATCHING;
595 else if (!strcmp(value, "tracking"))
596 push_default = PUSH_DEFAULT_TRACKING;
597 else if (!strcmp(value, "current"))
598 push_default = PUSH_DEFAULT_CURRENT;
599 else {
600 error("Malformed value for %s: %s", var, value);
601 return error("Must be one of nothing, matching, "
602 "tracking or current.");
604 return 0;
607 /* Add other config variables here and to Documentation/config.txt. */
608 return 0;
611 static int git_default_mailmap_config(const char *var, const char *value)
613 if (!strcmp(var, "mailmap.file"))
614 return git_config_string(&git_mailmap_file, var, value);
616 /* Add other config variables here and to Documentation/config.txt. */
617 return 0;
620 int git_default_config(const char *var, const char *value, void *dummy)
622 if (!prefixcmp(var, "core."))
623 return git_default_core_config(var, value);
625 if (!prefixcmp(var, "user."))
626 return git_default_user_config(var, value);
628 if (!prefixcmp(var, "i18n."))
629 return git_default_i18n_config(var, value);
631 if (!prefixcmp(var, "branch."))
632 return git_default_branch_config(var, value);
634 if (!prefixcmp(var, "push."))
635 return git_default_push_config(var, value);
637 if (!prefixcmp(var, "mailmap."))
638 return git_default_mailmap_config(var, value);
640 if (!prefixcmp(var, "advice."))
641 return git_default_advice_config(var, value);
643 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
644 pager_use_color = git_config_bool(var,value);
645 return 0;
648 /* Add other config variables here and to Documentation/config.txt. */
649 return 0;
652 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
654 int ret;
655 FILE *f = fopen(filename, "r");
657 ret = -1;
658 if (f) {
659 config_file = f;
660 config_file_name = filename;
661 config_linenr = 1;
662 config_file_eof = 0;
663 ret = git_parse_file(fn, data);
664 fclose(f);
665 config_file_name = NULL;
667 return ret;
670 const char *git_etc_gitconfig(void)
672 static const char *system_wide;
673 if (!system_wide)
674 system_wide = system_path(ETC_GITCONFIG);
675 return system_wide;
678 static int git_env_bool(const char *k, int def)
680 const char *v = getenv(k);
681 return v ? git_config_bool(k, v) : def;
684 int git_config_system(void)
686 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
689 int git_config_global(void)
691 return !git_env_bool("GIT_CONFIG_NOGLOBAL", 0);
694 int git_config(config_fn_t fn, void *data)
696 int ret = 0, found = 0;
697 char *repo_config = NULL;
698 const char *home = NULL;
700 /* Setting $GIT_CONFIG makes git read _only_ the given config file. */
701 if (config_exclusive_filename)
702 return git_config_from_file(fn, config_exclusive_filename, data);
703 if (git_config_system() && !access(git_etc_gitconfig(), R_OK)) {
704 ret += git_config_from_file(fn, git_etc_gitconfig(),
705 data);
706 found += 1;
709 home = getenv("HOME");
710 if (git_config_global() && home) {
711 char *user_config = xstrdup(mkpath("%s/.gitconfig", home));
712 if (!access(user_config, R_OK)) {
713 ret += git_config_from_file(fn, user_config, data);
714 found += 1;
716 free(user_config);
719 repo_config = git_pathdup("config");
720 if (!access(repo_config, R_OK)) {
721 ret += git_config_from_file(fn, repo_config, data);
722 found += 1;
724 free(repo_config);
725 if (found == 0)
726 return -1;
727 return ret;
731 * Find all the stuff for git_config_set() below.
734 #define MAX_MATCHES 512
736 static struct {
737 int baselen;
738 char *key;
739 int do_not_match;
740 regex_t *value_regex;
741 int multi_replace;
742 size_t offset[MAX_MATCHES];
743 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
744 int seen;
745 } store;
747 static int matches(const char *key, const char *value)
749 return !strcmp(key, store.key) &&
750 (store.value_regex == NULL ||
751 (store.do_not_match ^
752 !regexec(store.value_regex, value, 0, NULL, 0)));
755 static int store_aux(const char *key, const char *value, void *cb)
757 const char *ep;
758 size_t section_len;
760 switch (store.state) {
761 case KEY_SEEN:
762 if (matches(key, value)) {
763 if (store.seen == 1 && store.multi_replace == 0) {
764 warning("%s has multiple values", key);
765 } else if (store.seen >= MAX_MATCHES) {
766 error("too many matches for %s", key);
767 return 1;
770 store.offset[store.seen] = ftell(config_file);
771 store.seen++;
773 break;
774 case SECTION_SEEN:
776 * What we are looking for is in store.key (both
777 * section and var), and its section part is baselen
778 * long. We found key (again, both section and var).
779 * We would want to know if this key is in the same
780 * section as what we are looking for. We already
781 * know we are in the same section as what should
782 * hold store.key.
784 ep = strrchr(key, '.');
785 section_len = ep - key;
787 if ((section_len != store.baselen) ||
788 memcmp(key, store.key, section_len+1)) {
789 store.state = SECTION_END_SEEN;
790 break;
794 * Do not increment matches: this is no match, but we
795 * just made sure we are in the desired section.
797 store.offset[store.seen] = ftell(config_file);
798 /* fallthru */
799 case SECTION_END_SEEN:
800 case START:
801 if (matches(key, value)) {
802 store.offset[store.seen] = ftell(config_file);
803 store.state = KEY_SEEN;
804 store.seen++;
805 } else {
806 if (strrchr(key, '.') - key == store.baselen &&
807 !strncmp(key, store.key, store.baselen)) {
808 store.state = SECTION_SEEN;
809 store.offset[store.seen] = ftell(config_file);
813 return 0;
816 static int write_error(const char *filename)
818 error("failed to write new configuration file %s", filename);
820 /* Same error code as "failed to rename". */
821 return 4;
824 static int store_write_section(int fd, const char *key)
826 const char *dot;
827 int i, success;
828 struct strbuf sb = STRBUF_INIT;
830 dot = memchr(key, '.', store.baselen);
831 if (dot) {
832 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
833 for (i = dot - key + 1; i < store.baselen; i++) {
834 if (key[i] == '"' || key[i] == '\\')
835 strbuf_addch(&sb, '\\');
836 strbuf_addch(&sb, key[i]);
838 strbuf_addstr(&sb, "\"]\n");
839 } else {
840 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
843 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
844 strbuf_release(&sb);
846 return success;
849 static int store_write_pair(int fd, const char *key, const char *value)
851 int i, success;
852 int length = strlen(key + store.baselen + 1);
853 const char *quote = "";
854 struct strbuf sb = STRBUF_INIT;
857 * Check to see if the value needs to be surrounded with a dq pair.
858 * Note that problematic characters are always backslash-quoted; this
859 * check is about not losing leading or trailing SP and strings that
860 * follow beginning-of-comment characters (i.e. ';' and '#') by the
861 * configuration parser.
863 if (value[0] == ' ')
864 quote = "\"";
865 for (i = 0; value[i]; i++)
866 if (value[i] == ';' || value[i] == '#')
867 quote = "\"";
868 if (i && value[i - 1] == ' ')
869 quote = "\"";
871 strbuf_addf(&sb, "\t%.*s = %s",
872 length, key + store.baselen + 1, quote);
874 for (i = 0; value[i]; i++)
875 switch (value[i]) {
876 case '\n':
877 strbuf_addstr(&sb, "\\n");
878 break;
879 case '\t':
880 strbuf_addstr(&sb, "\\t");
881 break;
882 case '"':
883 case '\\':
884 strbuf_addch(&sb, '\\');
885 default:
886 strbuf_addch(&sb, value[i]);
887 break;
889 strbuf_addf(&sb, "%s\n", quote);
891 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
892 strbuf_release(&sb);
894 return success;
897 static ssize_t find_beginning_of_line(const char *contents, size_t size,
898 size_t offset_, int *found_bracket)
900 size_t equal_offset = size, bracket_offset = size;
901 ssize_t offset;
903 contline:
904 for (offset = offset_-2; offset > 0
905 && contents[offset] != '\n'; offset--)
906 switch (contents[offset]) {
907 case '=': equal_offset = offset; break;
908 case ']': bracket_offset = offset; break;
910 if (offset > 0 && contents[offset-1] == '\\') {
911 offset_ = offset;
912 goto contline;
914 if (bracket_offset < equal_offset) {
915 *found_bracket = 1;
916 offset = bracket_offset+1;
917 } else
918 offset++;
920 return offset;
923 int git_config_set(const char *key, const char *value)
925 return git_config_set_multivar(key, value, NULL, 0);
929 * If value==NULL, unset in (remove from) config,
930 * if value_regex!=NULL, disregard key/value pairs where value does not match.
931 * if multi_replace==0, nothing, or only one matching key/value is replaced,
932 * else all matching key/values (regardless how many) are removed,
933 * before the new pair is written.
935 * Returns 0 on success.
937 * This function does this:
939 * - it locks the config file by creating ".git/config.lock"
941 * - it then parses the config using store_aux() as validator to find
942 * the position on the key/value pair to replace. If it is to be unset,
943 * it must be found exactly once.
945 * - the config file is mmap()ed and the part before the match (if any) is
946 * written to the lock file, then the changed part and the rest.
948 * - the config file is removed and the lock file rename()d to it.
951 int git_config_set_multivar(const char *key, const char *value,
952 const char *value_regex, int multi_replace)
954 int i, dot;
955 int fd = -1, in_fd;
956 int ret;
957 char *config_filename;
958 struct lock_file *lock = NULL;
959 const char *last_dot = strrchr(key, '.');
961 if (config_exclusive_filename)
962 config_filename = xstrdup(config_exclusive_filename);
963 else
964 config_filename = git_pathdup("config");
967 * Since "key" actually contains the section name and the real
968 * key name separated by a dot, we have to know where the dot is.
971 if (last_dot == NULL) {
972 error("key does not contain a section: %s", key);
973 ret = 2;
974 goto out_free;
976 store.baselen = last_dot - key;
978 store.multi_replace = multi_replace;
981 * Validate the key and while at it, lower case it for matching.
983 store.key = xmalloc(strlen(key) + 1);
984 dot = 0;
985 for (i = 0; key[i]; i++) {
986 unsigned char c = key[i];
987 if (c == '.')
988 dot = 1;
989 /* Leave the extended basename untouched.. */
990 if (!dot || i > store.baselen) {
991 if (!iskeychar(c) || (i == store.baselen+1 && !isalpha(c))) {
992 error("invalid key: %s", key);
993 free(store.key);
994 ret = 1;
995 goto out_free;
997 c = tolower(c);
998 } else if (c == '\n') {
999 error("invalid key (newline): %s", key);
1000 free(store.key);
1001 ret = 1;
1002 goto out_free;
1004 store.key[i] = c;
1006 store.key[i] = 0;
1009 * The lock serves a purpose in addition to locking: the new
1010 * contents of .git/config will be written into it.
1012 lock = xcalloc(sizeof(struct lock_file), 1);
1013 fd = hold_lock_file_for_update(lock, config_filename, 0);
1014 if (fd < 0) {
1015 error("could not lock config file %s: %s", config_filename, strerror(errno));
1016 free(store.key);
1017 ret = -1;
1018 goto out_free;
1022 * If .git/config does not exist yet, write a minimal version.
1024 in_fd = open(config_filename, O_RDONLY);
1025 if ( in_fd < 0 ) {
1026 free(store.key);
1028 if ( ENOENT != errno ) {
1029 error("opening %s: %s", config_filename,
1030 strerror(errno));
1031 ret = 3; /* same as "invalid config file" */
1032 goto out_free;
1034 /* if nothing to unset, error out */
1035 if (value == NULL) {
1036 ret = 5;
1037 goto out_free;
1040 store.key = (char *)key;
1041 if (!store_write_section(fd, key) ||
1042 !store_write_pair(fd, key, value))
1043 goto write_err_out;
1044 } else {
1045 struct stat st;
1046 char *contents;
1047 size_t contents_sz, copy_begin, copy_end;
1048 int i, new_line = 0;
1050 if (value_regex == NULL)
1051 store.value_regex = NULL;
1052 else {
1053 if (value_regex[0] == '!') {
1054 store.do_not_match = 1;
1055 value_regex++;
1056 } else
1057 store.do_not_match = 0;
1059 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1060 if (regcomp(store.value_regex, value_regex,
1061 REG_EXTENDED)) {
1062 error("invalid pattern: %s", value_regex);
1063 free(store.value_regex);
1064 ret = 6;
1065 goto out_free;
1069 store.offset[0] = 0;
1070 store.state = START;
1071 store.seen = 0;
1074 * After this, store.offset will contain the *end* offset
1075 * of the last match, or remain at 0 if no match was found.
1076 * As a side effect, we make sure to transform only a valid
1077 * existing config file.
1079 if (git_config_from_file(store_aux, config_filename, NULL)) {
1080 error("invalid config file %s", config_filename);
1081 free(store.key);
1082 if (store.value_regex != NULL) {
1083 regfree(store.value_regex);
1084 free(store.value_regex);
1086 ret = 3;
1087 goto out_free;
1090 free(store.key);
1091 if (store.value_regex != NULL) {
1092 regfree(store.value_regex);
1093 free(store.value_regex);
1096 /* if nothing to unset, or too many matches, error out */
1097 if ((store.seen == 0 && value == NULL) ||
1098 (store.seen > 1 && multi_replace == 0)) {
1099 ret = 5;
1100 goto out_free;
1103 fstat(in_fd, &st);
1104 contents_sz = xsize_t(st.st_size);
1105 contents = xmmap(NULL, contents_sz, PROT_READ,
1106 MAP_PRIVATE, in_fd, 0);
1107 close(in_fd);
1109 if (store.seen == 0)
1110 store.seen = 1;
1112 for (i = 0, copy_begin = 0; i < store.seen; i++) {
1113 if (store.offset[i] == 0) {
1114 store.offset[i] = copy_end = contents_sz;
1115 } else if (store.state != KEY_SEEN) {
1116 copy_end = store.offset[i];
1117 } else
1118 copy_end = find_beginning_of_line(
1119 contents, contents_sz,
1120 store.offset[i]-2, &new_line);
1122 if (copy_end > 0 && contents[copy_end-1] != '\n')
1123 new_line = 1;
1125 /* write the first part of the config */
1126 if (copy_end > copy_begin) {
1127 if (write_in_full(fd, contents + copy_begin,
1128 copy_end - copy_begin) <
1129 copy_end - copy_begin)
1130 goto write_err_out;
1131 if (new_line &&
1132 write_str_in_full(fd, "\n") != 1)
1133 goto write_err_out;
1135 copy_begin = store.offset[i];
1138 /* write the pair (value == NULL means unset) */
1139 if (value != NULL) {
1140 if (store.state == START) {
1141 if (!store_write_section(fd, key))
1142 goto write_err_out;
1144 if (!store_write_pair(fd, key, value))
1145 goto write_err_out;
1148 /* write the rest of the config */
1149 if (copy_begin < contents_sz)
1150 if (write_in_full(fd, contents + copy_begin,
1151 contents_sz - copy_begin) <
1152 contents_sz - copy_begin)
1153 goto write_err_out;
1155 munmap(contents, contents_sz);
1158 if (commit_lock_file(lock) < 0) {
1159 error("could not commit config file %s", config_filename);
1160 ret = 4;
1161 goto out_free;
1165 * lock is committed, so don't try to roll it back below.
1166 * NOTE: Since lockfile.c keeps a linked list of all created
1167 * lock_file structures, it isn't safe to free(lock). It's
1168 * better to just leave it hanging around.
1170 lock = NULL;
1171 ret = 0;
1173 out_free:
1174 if (lock)
1175 rollback_lock_file(lock);
1176 free(config_filename);
1177 return ret;
1179 write_err_out:
1180 ret = write_error(lock->filename);
1181 goto out_free;
1185 static int section_name_match (const char *buf, const char *name)
1187 int i = 0, j = 0, dot = 0;
1188 if (buf[i] != '[')
1189 return 0;
1190 for (i = 1; buf[i] && buf[i] != ']'; i++) {
1191 if (!dot && isspace(buf[i])) {
1192 dot = 1;
1193 if (name[j++] != '.')
1194 break;
1195 for (i++; isspace(buf[i]); i++)
1196 ; /* do nothing */
1197 if (buf[i] != '"')
1198 break;
1199 continue;
1201 if (buf[i] == '\\' && dot)
1202 i++;
1203 else if (buf[i] == '"' && dot) {
1204 for (i++; isspace(buf[i]); i++)
1205 ; /* do_nothing */
1206 break;
1208 if (buf[i] != name[j++])
1209 break;
1211 if (buf[i] == ']' && name[j] == 0) {
1213 * We match, now just find the right length offset by
1214 * gobbling up any whitespace after it, as well
1216 i++;
1217 for (; buf[i] && isspace(buf[i]); i++)
1218 ; /* do nothing */
1219 return i;
1221 return 0;
1224 /* if new_name == NULL, the section is removed instead */
1225 int git_config_rename_section(const char *old_name, const char *new_name)
1227 int ret = 0, remove = 0;
1228 char *config_filename;
1229 struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1230 int out_fd;
1231 char buf[1024];
1233 if (config_exclusive_filename)
1234 config_filename = xstrdup(config_exclusive_filename);
1235 else
1236 config_filename = git_pathdup("config");
1237 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1238 if (out_fd < 0) {
1239 ret = error("could not lock config file %s", config_filename);
1240 goto out;
1243 if (!(config_file = fopen(config_filename, "rb"))) {
1244 /* no config file means nothing to rename, no error */
1245 goto unlock_and_out;
1248 while (fgets(buf, sizeof(buf), config_file)) {
1249 int i;
1250 int length;
1251 char *output = buf;
1252 for (i = 0; buf[i] && isspace(buf[i]); i++)
1253 ; /* do nothing */
1254 if (buf[i] == '[') {
1255 /* it's a section */
1256 int offset = section_name_match(&buf[i], old_name);
1257 if (offset > 0) {
1258 ret++;
1259 if (new_name == NULL) {
1260 remove = 1;
1261 continue;
1263 store.baselen = strlen(new_name);
1264 if (!store_write_section(out_fd, new_name)) {
1265 ret = write_error(lock->filename);
1266 goto out;
1269 * We wrote out the new section, with
1270 * a newline, now skip the old
1271 * section's length
1273 output += offset + i;
1274 if (strlen(output) > 0) {
1276 * More content means there's
1277 * a declaration to put on the
1278 * next line; indent with a
1279 * tab
1281 output -= 1;
1282 output[0] = '\t';
1285 remove = 0;
1287 if (remove)
1288 continue;
1289 length = strlen(output);
1290 if (write_in_full(out_fd, output, length) != length) {
1291 ret = write_error(lock->filename);
1292 goto out;
1295 fclose(config_file);
1296 unlock_and_out:
1297 if (commit_lock_file(lock) < 0)
1298 ret = error("could not commit config file %s", config_filename);
1299 out:
1300 free(config_filename);
1301 return ret;
1305 * Call this to report error for your variable that should not
1306 * get a boolean value (i.e. "[my] var" means "true").
1308 int config_error_nonbool(const char *var)
1310 return error("Missing value for '%s'", var);