git-gui: Avoid using the <<Copy>> binding as a menu accelerator on win32
[git/platforms.git] / config.c
blob358c420c0f1b60ad3cfcca557ab088ef89136e87
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.notesref")) {
481 notes_ref_name = xstrdup(value);
482 return 0;
485 if (!strcmp(var, "core.pager"))
486 return git_config_string(&pager_program, var, value);
488 if (!strcmp(var, "core.editor"))
489 return git_config_string(&editor_program, var, value);
491 if (!strcmp(var, "core.excludesfile"))
492 return git_config_pathname(&excludes_file, var, value);
494 if (!strcmp(var, "core.whitespace")) {
495 if (!value)
496 return config_error_nonbool(var);
497 whitespace_rule_cfg = parse_whitespace_rule(value);
498 return 0;
501 if (!strcmp(var, "core.fsyncobjectfiles")) {
502 fsync_object_files = git_config_bool(var, value);
503 return 0;
506 if (!strcmp(var, "core.preloadindex")) {
507 core_preload_index = git_config_bool(var, value);
508 return 0;
511 if (!strcmp(var, "core.createobject")) {
512 if (!strcmp(value, "rename"))
513 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
514 else if (!strcmp(value, "link"))
515 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
516 else
517 die("Invalid mode for object creation: %s", value);
518 return 0;
521 if (!strcmp(var, "core.hidedotfiles")) {
522 if (value && !strcasecmp(value, "dotgitonly")) {
523 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
524 return 0;
526 hide_dotfiles = git_config_bool(var, value);
527 return 0;
530 if (!strcmp(var, "core.sparsecheckout")) {
531 core_apply_sparse_checkout = git_config_bool(var, value);
532 return 0;
535 /* Add other config variables here and to Documentation/config.txt. */
536 return 0;
539 static int git_default_user_config(const char *var, const char *value)
541 if (!strcmp(var, "user.name")) {
542 if (!value)
543 return config_error_nonbool(var);
544 strlcpy(git_default_name, value, sizeof(git_default_name));
545 user_ident_explicitly_given |= IDENT_NAME_GIVEN;
546 return 0;
549 if (!strcmp(var, "user.email")) {
550 if (!value)
551 return config_error_nonbool(var);
552 strlcpy(git_default_email, value, sizeof(git_default_email));
553 user_ident_explicitly_given |= IDENT_MAIL_GIVEN;
554 return 0;
557 /* Add other config variables here and to Documentation/config.txt. */
558 return 0;
561 static int git_default_i18n_config(const char *var, const char *value)
563 if (!strcmp(var, "i18n.commitencoding"))
564 return git_config_string(&git_commit_encoding, var, value);
566 if (!strcmp(var, "i18n.logoutputencoding"))
567 return git_config_string(&git_log_output_encoding, var, value);
569 /* Add other config variables here and to Documentation/config.txt. */
570 return 0;
573 static int git_default_branch_config(const char *var, const char *value)
575 if (!strcmp(var, "branch.autosetupmerge")) {
576 if (value && !strcasecmp(value, "always")) {
577 git_branch_track = BRANCH_TRACK_ALWAYS;
578 return 0;
580 git_branch_track = git_config_bool(var, value);
581 return 0;
583 if (!strcmp(var, "branch.autosetuprebase")) {
584 if (!value)
585 return config_error_nonbool(var);
586 else if (!strcmp(value, "never"))
587 autorebase = AUTOREBASE_NEVER;
588 else if (!strcmp(value, "local"))
589 autorebase = AUTOREBASE_LOCAL;
590 else if (!strcmp(value, "remote"))
591 autorebase = AUTOREBASE_REMOTE;
592 else if (!strcmp(value, "always"))
593 autorebase = AUTOREBASE_ALWAYS;
594 else
595 return error("Malformed value for %s", var);
596 return 0;
599 /* Add other config variables here and to Documentation/config.txt. */
600 return 0;
603 static int git_default_push_config(const char *var, const char *value)
605 if (!strcmp(var, "push.default")) {
606 if (!value)
607 return config_error_nonbool(var);
608 else if (!strcmp(value, "nothing"))
609 push_default = PUSH_DEFAULT_NOTHING;
610 else if (!strcmp(value, "matching"))
611 push_default = PUSH_DEFAULT_MATCHING;
612 else if (!strcmp(value, "tracking"))
613 push_default = PUSH_DEFAULT_TRACKING;
614 else if (!strcmp(value, "current"))
615 push_default = PUSH_DEFAULT_CURRENT;
616 else {
617 error("Malformed value for %s: %s", var, value);
618 return error("Must be one of nothing, matching, "
619 "tracking or current.");
621 return 0;
624 /* Add other config variables here and to Documentation/config.txt. */
625 return 0;
628 static int git_default_mailmap_config(const char *var, const char *value)
630 if (!strcmp(var, "mailmap.file"))
631 return git_config_string(&git_mailmap_file, var, value);
633 /* Add other config variables here and to Documentation/config.txt. */
634 return 0;
637 int git_default_config(const char *var, const char *value, void *dummy)
639 if (!prefixcmp(var, "core."))
640 return git_default_core_config(var, value);
642 if (!prefixcmp(var, "user."))
643 return git_default_user_config(var, value);
645 if (!prefixcmp(var, "i18n."))
646 return git_default_i18n_config(var, value);
648 if (!prefixcmp(var, "branch."))
649 return git_default_branch_config(var, value);
651 if (!prefixcmp(var, "push."))
652 return git_default_push_config(var, value);
654 if (!prefixcmp(var, "mailmap."))
655 return git_default_mailmap_config(var, value);
657 if (!prefixcmp(var, "advice."))
658 return git_default_advice_config(var, value);
660 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
661 pager_use_color = git_config_bool(var,value);
662 return 0;
665 /* Add other config variables here and to Documentation/config.txt. */
666 return 0;
669 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
671 int ret;
672 FILE *f = fopen(filename, "r");
674 ret = -1;
675 if (f) {
676 config_file = f;
677 config_file_name = filename;
678 config_linenr = 1;
679 config_file_eof = 0;
680 ret = git_parse_file(fn, data);
681 fclose(f);
682 config_file_name = NULL;
684 return ret;
687 const char *git_etc_gitconfig(void)
689 static const char *system_wide;
690 if (!system_wide)
691 system_wide = system_path(ETC_GITCONFIG);
692 return system_wide;
695 static int git_env_bool(const char *k, int def)
697 const char *v = getenv(k);
698 return v ? git_config_bool(k, v) : def;
701 int git_config_system(void)
703 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
706 int git_config_global(void)
708 return !git_env_bool("GIT_CONFIG_NOGLOBAL", 0);
711 int git_config(config_fn_t fn, void *data)
713 int ret = 0, found = 0;
714 char *repo_config = NULL;
715 const char *home = NULL;
717 /* Setting $GIT_CONFIG makes git read _only_ the given config file. */
718 if (config_exclusive_filename)
719 return git_config_from_file(fn, config_exclusive_filename, data);
720 if (git_config_system() && !access(git_etc_gitconfig(), R_OK)) {
721 ret += git_config_from_file(fn, git_etc_gitconfig(),
722 data);
723 found += 1;
726 home = getenv("HOME");
727 if (git_config_global() && home) {
728 char *user_config = xstrdup(mkpath("%s/.gitconfig", home));
729 if (!access(user_config, R_OK)) {
730 ret += git_config_from_file(fn, user_config, data);
731 found += 1;
733 free(user_config);
736 repo_config = git_pathdup("config");
737 if (!access(repo_config, R_OK)) {
738 ret += git_config_from_file(fn, repo_config, data);
739 found += 1;
741 free(repo_config);
742 if (found == 0)
743 return -1;
744 return ret;
748 * Find all the stuff for git_config_set() below.
751 #define MAX_MATCHES 512
753 static struct {
754 int baselen;
755 char *key;
756 int do_not_match;
757 regex_t *value_regex;
758 int multi_replace;
759 size_t offset[MAX_MATCHES];
760 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
761 int seen;
762 } store;
764 static int matches(const char *key, const char *value)
766 return !strcmp(key, store.key) &&
767 (store.value_regex == NULL ||
768 (store.do_not_match ^
769 !regexec(store.value_regex, value, 0, NULL, 0)));
772 static int store_aux(const char *key, const char *value, void *cb)
774 const char *ep;
775 size_t section_len;
777 switch (store.state) {
778 case KEY_SEEN:
779 if (matches(key, value)) {
780 if (store.seen == 1 && store.multi_replace == 0) {
781 warning("%s has multiple values", key);
782 } else if (store.seen >= MAX_MATCHES) {
783 error("too many matches for %s", key);
784 return 1;
787 store.offset[store.seen] = ftell(config_file);
788 store.seen++;
790 break;
791 case SECTION_SEEN:
793 * What we are looking for is in store.key (both
794 * section and var), and its section part is baselen
795 * long. We found key (again, both section and var).
796 * We would want to know if this key is in the same
797 * section as what we are looking for. We already
798 * know we are in the same section as what should
799 * hold store.key.
801 ep = strrchr(key, '.');
802 section_len = ep - key;
804 if ((section_len != store.baselen) ||
805 memcmp(key, store.key, section_len+1)) {
806 store.state = SECTION_END_SEEN;
807 break;
811 * Do not increment matches: this is no match, but we
812 * just made sure we are in the desired section.
814 store.offset[store.seen] = ftell(config_file);
815 /* fallthru */
816 case SECTION_END_SEEN:
817 case START:
818 if (matches(key, value)) {
819 store.offset[store.seen] = ftell(config_file);
820 store.state = KEY_SEEN;
821 store.seen++;
822 } else {
823 if (strrchr(key, '.') - key == store.baselen &&
824 !strncmp(key, store.key, store.baselen)) {
825 store.state = SECTION_SEEN;
826 store.offset[store.seen] = ftell(config_file);
830 return 0;
833 static int write_error(const char *filename)
835 error("failed to write new configuration file %s", filename);
837 /* Same error code as "failed to rename". */
838 return 4;
841 static int store_write_section(int fd, const char *key)
843 const char *dot;
844 int i, success;
845 struct strbuf sb = STRBUF_INIT;
847 dot = memchr(key, '.', store.baselen);
848 if (dot) {
849 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
850 for (i = dot - key + 1; i < store.baselen; i++) {
851 if (key[i] == '"' || key[i] == '\\')
852 strbuf_addch(&sb, '\\');
853 strbuf_addch(&sb, key[i]);
855 strbuf_addstr(&sb, "\"]\n");
856 } else {
857 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
860 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
861 strbuf_release(&sb);
863 return success;
866 static int store_write_pair(int fd, const char *key, const char *value)
868 int i, success;
869 int length = strlen(key + store.baselen + 1);
870 const char *quote = "";
871 struct strbuf sb = STRBUF_INIT;
874 * Check to see if the value needs to be surrounded with a dq pair.
875 * Note that problematic characters are always backslash-quoted; this
876 * check is about not losing leading or trailing SP and strings that
877 * follow beginning-of-comment characters (i.e. ';' and '#') by the
878 * configuration parser.
880 if (value[0] == ' ')
881 quote = "\"";
882 for (i = 0; value[i]; i++)
883 if (value[i] == ';' || value[i] == '#')
884 quote = "\"";
885 if (i && value[i - 1] == ' ')
886 quote = "\"";
888 strbuf_addf(&sb, "\t%.*s = %s",
889 length, key + store.baselen + 1, quote);
891 for (i = 0; value[i]; i++)
892 switch (value[i]) {
893 case '\n':
894 strbuf_addstr(&sb, "\\n");
895 break;
896 case '\t':
897 strbuf_addstr(&sb, "\\t");
898 break;
899 case '"':
900 case '\\':
901 strbuf_addch(&sb, '\\');
902 default:
903 strbuf_addch(&sb, value[i]);
904 break;
906 strbuf_addf(&sb, "%s\n", quote);
908 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
909 strbuf_release(&sb);
911 return success;
914 static ssize_t find_beginning_of_line(const char *contents, size_t size,
915 size_t offset_, int *found_bracket)
917 size_t equal_offset = size, bracket_offset = size;
918 ssize_t offset;
920 contline:
921 for (offset = offset_-2; offset > 0
922 && contents[offset] != '\n'; offset--)
923 switch (contents[offset]) {
924 case '=': equal_offset = offset; break;
925 case ']': bracket_offset = offset; break;
927 if (offset > 0 && contents[offset-1] == '\\') {
928 offset_ = offset;
929 goto contline;
931 if (bracket_offset < equal_offset) {
932 *found_bracket = 1;
933 offset = bracket_offset+1;
934 } else
935 offset++;
937 return offset;
940 int git_config_set(const char *key, const char *value)
942 return git_config_set_multivar(key, value, NULL, 0);
946 * If value==NULL, unset in (remove from) config,
947 * if value_regex!=NULL, disregard key/value pairs where value does not match.
948 * if multi_replace==0, nothing, or only one matching key/value is replaced,
949 * else all matching key/values (regardless how many) are removed,
950 * before the new pair is written.
952 * Returns 0 on success.
954 * This function does this:
956 * - it locks the config file by creating ".git/config.lock"
958 * - it then parses the config using store_aux() as validator to find
959 * the position on the key/value pair to replace. If it is to be unset,
960 * it must be found exactly once.
962 * - the config file is mmap()ed and the part before the match (if any) is
963 * written to the lock file, then the changed part and the rest.
965 * - the config file is removed and the lock file rename()d to it.
968 int git_config_set_multivar(const char *key, const char *value,
969 const char *value_regex, int multi_replace)
971 int i, dot;
972 int fd = -1, in_fd;
973 int ret;
974 char *config_filename;
975 struct lock_file *lock = NULL;
976 const char *last_dot = strrchr(key, '.');
978 if (config_exclusive_filename)
979 config_filename = xstrdup(config_exclusive_filename);
980 else
981 config_filename = git_pathdup("config");
984 * Since "key" actually contains the section name and the real
985 * key name separated by a dot, we have to know where the dot is.
988 if (last_dot == NULL) {
989 error("key does not contain a section: %s", key);
990 ret = 2;
991 goto out_free;
993 store.baselen = last_dot - key;
995 store.multi_replace = multi_replace;
998 * Validate the key and while at it, lower case it for matching.
1000 store.key = xmalloc(strlen(key) + 1);
1001 dot = 0;
1002 for (i = 0; key[i]; i++) {
1003 unsigned char c = key[i];
1004 if (c == '.')
1005 dot = 1;
1006 /* Leave the extended basename untouched.. */
1007 if (!dot || i > store.baselen) {
1008 if (!iskeychar(c) || (i == store.baselen+1 && !isalpha(c))) {
1009 error("invalid key: %s", key);
1010 free(store.key);
1011 ret = 1;
1012 goto out_free;
1014 c = tolower(c);
1015 } else if (c == '\n') {
1016 error("invalid key (newline): %s", key);
1017 free(store.key);
1018 ret = 1;
1019 goto out_free;
1021 store.key[i] = c;
1023 store.key[i] = 0;
1026 * The lock serves a purpose in addition to locking: the new
1027 * contents of .git/config will be written into it.
1029 lock = xcalloc(sizeof(struct lock_file), 1);
1030 fd = hold_lock_file_for_update(lock, config_filename, 0);
1031 if (fd < 0) {
1032 error("could not lock config file %s: %s", config_filename, strerror(errno));
1033 free(store.key);
1034 ret = -1;
1035 goto out_free;
1039 * If .git/config does not exist yet, write a minimal version.
1041 in_fd = open(config_filename, O_RDONLY);
1042 if ( in_fd < 0 ) {
1043 free(store.key);
1045 if ( ENOENT != errno ) {
1046 error("opening %s: %s", config_filename,
1047 strerror(errno));
1048 ret = 3; /* same as "invalid config file" */
1049 goto out_free;
1051 /* if nothing to unset, error out */
1052 if (value == NULL) {
1053 ret = 5;
1054 goto out_free;
1057 store.key = (char *)key;
1058 if (!store_write_section(fd, key) ||
1059 !store_write_pair(fd, key, value))
1060 goto write_err_out;
1061 } else {
1062 struct stat st;
1063 char *contents;
1064 size_t contents_sz, copy_begin, copy_end;
1065 int i, new_line = 0;
1067 if (value_regex == NULL)
1068 store.value_regex = NULL;
1069 else {
1070 if (value_regex[0] == '!') {
1071 store.do_not_match = 1;
1072 value_regex++;
1073 } else
1074 store.do_not_match = 0;
1076 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1077 if (regcomp(store.value_regex, value_regex,
1078 REG_EXTENDED)) {
1079 error("invalid pattern: %s", value_regex);
1080 free(store.value_regex);
1081 ret = 6;
1082 goto out_free;
1086 store.offset[0] = 0;
1087 store.state = START;
1088 store.seen = 0;
1091 * After this, store.offset will contain the *end* offset
1092 * of the last match, or remain at 0 if no match was found.
1093 * As a side effect, we make sure to transform only a valid
1094 * existing config file.
1096 if (git_config_from_file(store_aux, config_filename, NULL)) {
1097 error("invalid config file %s", config_filename);
1098 free(store.key);
1099 if (store.value_regex != NULL) {
1100 regfree(store.value_regex);
1101 free(store.value_regex);
1103 ret = 3;
1104 goto out_free;
1107 free(store.key);
1108 if (store.value_regex != NULL) {
1109 regfree(store.value_regex);
1110 free(store.value_regex);
1113 /* if nothing to unset, or too many matches, error out */
1114 if ((store.seen == 0 && value == NULL) ||
1115 (store.seen > 1 && multi_replace == 0)) {
1116 ret = 5;
1117 goto out_free;
1120 fstat(in_fd, &st);
1121 contents_sz = xsize_t(st.st_size);
1122 contents = xmmap(NULL, contents_sz, PROT_READ,
1123 MAP_PRIVATE, in_fd, 0);
1124 close(in_fd);
1126 if (store.seen == 0)
1127 store.seen = 1;
1129 for (i = 0, copy_begin = 0; i < store.seen; i++) {
1130 if (store.offset[i] == 0) {
1131 store.offset[i] = copy_end = contents_sz;
1132 } else if (store.state != KEY_SEEN) {
1133 copy_end = store.offset[i];
1134 } else
1135 copy_end = find_beginning_of_line(
1136 contents, contents_sz,
1137 store.offset[i]-2, &new_line);
1139 if (copy_end > 0 && contents[copy_end-1] != '\n')
1140 new_line = 1;
1142 /* write the first part of the config */
1143 if (copy_end > copy_begin) {
1144 if (write_in_full(fd, contents + copy_begin,
1145 copy_end - copy_begin) <
1146 copy_end - copy_begin)
1147 goto write_err_out;
1148 if (new_line &&
1149 write_str_in_full(fd, "\n") != 1)
1150 goto write_err_out;
1152 copy_begin = store.offset[i];
1155 /* write the pair (value == NULL means unset) */
1156 if (value != NULL) {
1157 if (store.state == START) {
1158 if (!store_write_section(fd, key))
1159 goto write_err_out;
1161 if (!store_write_pair(fd, key, value))
1162 goto write_err_out;
1165 /* write the rest of the config */
1166 if (copy_begin < contents_sz)
1167 if (write_in_full(fd, contents + copy_begin,
1168 contents_sz - copy_begin) <
1169 contents_sz - copy_begin)
1170 goto write_err_out;
1172 munmap(contents, contents_sz);
1175 if (commit_lock_file(lock) < 0) {
1176 error("could not commit config file %s", config_filename);
1177 ret = 4;
1178 goto out_free;
1182 * lock is committed, so don't try to roll it back below.
1183 * NOTE: Since lockfile.c keeps a linked list of all created
1184 * lock_file structures, it isn't safe to free(lock). It's
1185 * better to just leave it hanging around.
1187 lock = NULL;
1188 ret = 0;
1190 out_free:
1191 if (lock)
1192 rollback_lock_file(lock);
1193 free(config_filename);
1194 return ret;
1196 write_err_out:
1197 ret = write_error(lock->filename);
1198 goto out_free;
1202 static int section_name_match (const char *buf, const char *name)
1204 int i = 0, j = 0, dot = 0;
1205 if (buf[i] != '[')
1206 return 0;
1207 for (i = 1; buf[i] && buf[i] != ']'; i++) {
1208 if (!dot && isspace(buf[i])) {
1209 dot = 1;
1210 if (name[j++] != '.')
1211 break;
1212 for (i++; isspace(buf[i]); i++)
1213 ; /* do nothing */
1214 if (buf[i] != '"')
1215 break;
1216 continue;
1218 if (buf[i] == '\\' && dot)
1219 i++;
1220 else if (buf[i] == '"' && dot) {
1221 for (i++; isspace(buf[i]); i++)
1222 ; /* do_nothing */
1223 break;
1225 if (buf[i] != name[j++])
1226 break;
1228 if (buf[i] == ']' && name[j] == 0) {
1230 * We match, now just find the right length offset by
1231 * gobbling up any whitespace after it, as well
1233 i++;
1234 for (; buf[i] && isspace(buf[i]); i++)
1235 ; /* do nothing */
1236 return i;
1238 return 0;
1241 /* if new_name == NULL, the section is removed instead */
1242 int git_config_rename_section(const char *old_name, const char *new_name)
1244 int ret = 0, remove = 0;
1245 char *config_filename;
1246 struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1247 int out_fd;
1248 char buf[1024];
1250 if (config_exclusive_filename)
1251 config_filename = xstrdup(config_exclusive_filename);
1252 else
1253 config_filename = git_pathdup("config");
1254 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1255 if (out_fd < 0) {
1256 ret = error("could not lock config file %s", config_filename);
1257 goto out;
1260 if (!(config_file = fopen(config_filename, "rb"))) {
1261 /* no config file means nothing to rename, no error */
1262 goto unlock_and_out;
1265 while (fgets(buf, sizeof(buf), config_file)) {
1266 int i;
1267 int length;
1268 char *output = buf;
1269 for (i = 0; buf[i] && isspace(buf[i]); i++)
1270 ; /* do nothing */
1271 if (buf[i] == '[') {
1272 /* it's a section */
1273 int offset = section_name_match(&buf[i], old_name);
1274 if (offset > 0) {
1275 ret++;
1276 if (new_name == NULL) {
1277 remove = 1;
1278 continue;
1280 store.baselen = strlen(new_name);
1281 if (!store_write_section(out_fd, new_name)) {
1282 ret = write_error(lock->filename);
1283 goto out;
1286 * We wrote out the new section, with
1287 * a newline, now skip the old
1288 * section's length
1290 output += offset + i;
1291 if (strlen(output) > 0) {
1293 * More content means there's
1294 * a declaration to put on the
1295 * next line; indent with a
1296 * tab
1298 output -= 1;
1299 output[0] = '\t';
1302 remove = 0;
1304 if (remove)
1305 continue;
1306 length = strlen(output);
1307 if (write_in_full(out_fd, output, length) != length) {
1308 ret = write_error(lock->filename);
1309 goto out;
1312 fclose(config_file);
1313 unlock_and_out:
1314 if (commit_lock_file(lock) < 0)
1315 ret = error("could not commit config file %s", config_filename);
1316 out:
1317 free(config_filename);
1318 return ret;
1322 * Call this to report error for your variable that should not
1323 * get a boolean value (i.e. "[my] var" means "true").
1325 int config_error_nonbool(const char *var)
1327 return error("Missing value for '%s'", var);