gitk: Second try to work around the command line limit on Windows
[git/dscho.git] / config.c
blob535eed8c7543e1f2bbb89cfd49848e936cc508d9
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_maybe_bool(const char *name, const char *value)
327 if (!value)
328 return 1;
329 if (!*value)
330 return 0;
331 if (!strcasecmp(value, "true")
332 || !strcasecmp(value, "yes")
333 || !strcasecmp(value, "on"))
334 return 1;
335 if (!strcasecmp(value, "false")
336 || !strcasecmp(value, "no")
337 || !strcasecmp(value, "off"))
338 return 0;
339 return -1;
342 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
344 int v = git_config_maybe_bool(name, value);
345 if (0 <= v) {
346 *is_bool = 1;
347 return v;
349 *is_bool = 0;
350 return git_config_int(name, value);
353 int git_config_bool(const char *name, const char *value)
355 int discard;
356 return !!git_config_bool_or_int(name, value, &discard);
359 int git_config_string(const char **dest, const char *var, const char *value)
361 if (!value)
362 return config_error_nonbool(var);
363 *dest = xstrdup(value);
364 return 0;
367 int git_config_pathname(const char **dest, const char *var, const char *value)
369 if (!value)
370 return config_error_nonbool(var);
371 *dest = expand_user_path(value);
372 if (!*dest)
373 die("Failed to expand user dir in: '%s'", value);
374 return 0;
377 static int git_default_core_config(const char *var, const char *value)
379 /* This needs a better name */
380 if (!strcmp(var, "core.filemode")) {
381 trust_executable_bit = git_config_bool(var, value);
382 return 0;
384 if (!strcmp(var, "core.trustctime")) {
385 trust_ctime = git_config_bool(var, value);
386 return 0;
389 if (!strcmp(var, "core.quotepath")) {
390 quote_path_fully = git_config_bool(var, value);
391 return 0;
394 if (!strcmp(var, "core.symlinks")) {
395 has_symlinks = git_config_bool(var, value);
396 return 0;
399 if (!strcmp(var, "core.ignorecase")) {
400 ignore_case = git_config_bool(var, value);
401 return 0;
404 if (!strcmp(var, "core.bare")) {
405 is_bare_repository_cfg = git_config_bool(var, value);
406 return 0;
409 if (!strcmp(var, "core.ignorestat")) {
410 assume_unchanged = git_config_bool(var, value);
411 return 0;
414 if (!strcmp(var, "core.prefersymlinkrefs")) {
415 prefer_symlink_refs = git_config_bool(var, value);
416 return 0;
419 if (!strcmp(var, "core.logallrefupdates")) {
420 log_all_ref_updates = git_config_bool(var, value);
421 return 0;
424 if (!strcmp(var, "core.warnambiguousrefs")) {
425 warn_ambiguous_refs = git_config_bool(var, value);
426 return 0;
429 if (!strcmp(var, "core.loosecompression")) {
430 int level = git_config_int(var, value);
431 if (level == -1)
432 level = Z_DEFAULT_COMPRESSION;
433 else if (level < 0 || level > Z_BEST_COMPRESSION)
434 die("bad zlib compression level %d", level);
435 zlib_compression_level = level;
436 zlib_compression_seen = 1;
437 return 0;
440 if (!strcmp(var, "core.compression")) {
441 int level = git_config_int(var, value);
442 if (level == -1)
443 level = Z_DEFAULT_COMPRESSION;
444 else if (level < 0 || level > Z_BEST_COMPRESSION)
445 die("bad zlib compression level %d", level);
446 core_compression_level = level;
447 core_compression_seen = 1;
448 if (!zlib_compression_seen)
449 zlib_compression_level = level;
450 return 0;
453 if (!strcmp(var, "core.packedgitwindowsize")) {
454 int pgsz_x2 = getpagesize() * 2;
455 packed_git_window_size = git_config_int(var, value);
457 /* This value must be multiple of (pagesize * 2) */
458 packed_git_window_size /= pgsz_x2;
459 if (packed_git_window_size < 1)
460 packed_git_window_size = 1;
461 packed_git_window_size *= pgsz_x2;
462 return 0;
465 if (!strcmp(var, "core.packedgitlimit")) {
466 packed_git_limit = git_config_int(var, value);
467 return 0;
470 if (!strcmp(var, "core.deltabasecachelimit")) {
471 delta_base_cache_limit = git_config_int(var, value);
472 return 0;
475 if (!strcmp(var, "core.autocrlf")) {
476 if (value && !strcasecmp(value, "input")) {
477 auto_crlf = -1;
478 return 0;
480 auto_crlf = git_config_bool(var, value);
481 return 0;
484 if (!strcmp(var, "core.safecrlf")) {
485 if (value && !strcasecmp(value, "warn")) {
486 safe_crlf = SAFE_CRLF_WARN;
487 return 0;
489 safe_crlf = git_config_bool(var, value);
490 return 0;
493 if (!strcmp(var, "core.notesref")) {
494 notes_ref_name = xstrdup(value);
495 return 0;
498 if (!strcmp(var, "core.pager"))
499 return git_config_string(&pager_program, var, value);
501 if (!strcmp(var, "core.editor"))
502 return git_config_string(&editor_program, var, value);
504 if (!strcmp(var, "core.excludesfile"))
505 return git_config_pathname(&excludes_file, var, value);
507 if (!strcmp(var, "core.whitespace")) {
508 if (!value)
509 return config_error_nonbool(var);
510 whitespace_rule_cfg = parse_whitespace_rule(value);
511 return 0;
514 if (!strcmp(var, "core.fsyncobjectfiles")) {
515 fsync_object_files = git_config_bool(var, value);
516 return 0;
519 if (!strcmp(var, "core.preloadindex")) {
520 core_preload_index = git_config_bool(var, value);
521 return 0;
524 if (!strcmp(var, "core.createobject")) {
525 if (!strcmp(value, "rename"))
526 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
527 else if (!strcmp(value, "link"))
528 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
529 else
530 die("Invalid mode for object creation: %s", value);
531 return 0;
534 if (!strcmp(var, "core.sparsecheckout")) {
535 core_apply_sparse_checkout = git_config_bool(var, value);
536 return 0;
539 if (!strcmp(var, "core.hidedotfiles")) {
540 if (value && !strcasecmp(value, "dotgitonly")) {
541 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
542 return 0;
544 hide_dotfiles = git_config_bool(var, value);
545 return 0;
548 /* Add other config variables here and to Documentation/config.txt. */
549 return 0;
552 static int git_default_user_config(const char *var, const char *value)
554 if (!strcmp(var, "user.name")) {
555 if (!value)
556 return config_error_nonbool(var);
557 strlcpy(git_default_name, value, sizeof(git_default_name));
558 user_ident_explicitly_given |= IDENT_NAME_GIVEN;
559 return 0;
562 if (!strcmp(var, "user.email")) {
563 if (!value)
564 return config_error_nonbool(var);
565 strlcpy(git_default_email, value, sizeof(git_default_email));
566 user_ident_explicitly_given |= IDENT_MAIL_GIVEN;
567 return 0;
570 /* Add other config variables here and to Documentation/config.txt. */
571 return 0;
574 static int git_default_i18n_config(const char *var, const char *value)
576 if (!strcmp(var, "i18n.commitencoding"))
577 return git_config_string(&git_commit_encoding, var, value);
579 if (!strcmp(var, "i18n.logoutputencoding"))
580 return git_config_string(&git_log_output_encoding, var, value);
582 /* Add other config variables here and to Documentation/config.txt. */
583 return 0;
586 static int git_default_branch_config(const char *var, const char *value)
588 if (!strcmp(var, "branch.autosetupmerge")) {
589 if (value && !strcasecmp(value, "always")) {
590 git_branch_track = BRANCH_TRACK_ALWAYS;
591 return 0;
593 git_branch_track = git_config_bool(var, value);
594 return 0;
596 if (!strcmp(var, "branch.autosetuprebase")) {
597 if (!value)
598 return config_error_nonbool(var);
599 else if (!strcmp(value, "never"))
600 autorebase = AUTOREBASE_NEVER;
601 else if (!strcmp(value, "local"))
602 autorebase = AUTOREBASE_LOCAL;
603 else if (!strcmp(value, "remote"))
604 autorebase = AUTOREBASE_REMOTE;
605 else if (!strcmp(value, "always"))
606 autorebase = AUTOREBASE_ALWAYS;
607 else
608 return error("Malformed value for %s", var);
609 return 0;
612 /* Add other config variables here and to Documentation/config.txt. */
613 return 0;
616 static int git_default_push_config(const char *var, const char *value)
618 if (!strcmp(var, "push.default")) {
619 if (!value)
620 return config_error_nonbool(var);
621 else if (!strcmp(value, "nothing"))
622 push_default = PUSH_DEFAULT_NOTHING;
623 else if (!strcmp(value, "matching"))
624 push_default = PUSH_DEFAULT_MATCHING;
625 else if (!strcmp(value, "tracking"))
626 push_default = PUSH_DEFAULT_TRACKING;
627 else if (!strcmp(value, "current"))
628 push_default = PUSH_DEFAULT_CURRENT;
629 else {
630 error("Malformed value for %s: %s", var, value);
631 return error("Must be one of nothing, matching, "
632 "tracking or current.");
634 return 0;
637 /* Add other config variables here and to Documentation/config.txt. */
638 return 0;
641 static int git_default_mailmap_config(const char *var, const char *value)
643 if (!strcmp(var, "mailmap.file"))
644 return git_config_string(&git_mailmap_file, var, value);
646 /* Add other config variables here and to Documentation/config.txt. */
647 return 0;
650 int git_default_config(const char *var, const char *value, void *dummy)
652 if (!prefixcmp(var, "core."))
653 return git_default_core_config(var, value);
655 if (!prefixcmp(var, "user."))
656 return git_default_user_config(var, value);
658 if (!prefixcmp(var, "i18n."))
659 return git_default_i18n_config(var, value);
661 if (!prefixcmp(var, "branch."))
662 return git_default_branch_config(var, value);
664 if (!prefixcmp(var, "push."))
665 return git_default_push_config(var, value);
667 if (!prefixcmp(var, "mailmap."))
668 return git_default_mailmap_config(var, value);
670 if (!prefixcmp(var, "advice."))
671 return git_default_advice_config(var, value);
673 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
674 pager_use_color = git_config_bool(var,value);
675 return 0;
678 /* Add other config variables here and to Documentation/config.txt. */
679 return 0;
682 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
684 int ret;
685 FILE *f = fopen(filename, "r");
687 ret = -1;
688 if (f) {
689 config_file = f;
690 config_file_name = filename;
691 config_linenr = 1;
692 config_file_eof = 0;
693 ret = git_parse_file(fn, data);
694 fclose(f);
695 config_file_name = NULL;
697 return ret;
700 const char *git_etc_gitconfig(void)
702 static const char *system_wide;
703 if (!system_wide)
704 system_wide = system_path(ETC_GITCONFIG);
705 return system_wide;
708 static int git_env_bool(const char *k, int def)
710 const char *v = getenv(k);
711 return v ? git_config_bool(k, v) : def;
714 int git_config_system(void)
716 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
719 int git_config_global(void)
721 return !git_env_bool("GIT_CONFIG_NOGLOBAL", 0);
724 int git_config(config_fn_t fn, void *data)
726 int ret = 0, found = 0;
727 char *repo_config = NULL;
728 const char *home = NULL;
730 /* Setting $GIT_CONFIG makes git read _only_ the given config file. */
731 if (config_exclusive_filename)
732 return git_config_from_file(fn, config_exclusive_filename, data);
733 if (git_config_system() && !access(git_etc_gitconfig(), R_OK)) {
734 ret += git_config_from_file(fn, git_etc_gitconfig(),
735 data);
736 found += 1;
739 home = getenv("HOME");
740 if (git_config_global() && home) {
741 char *user_config = xstrdup(mkpath("%s/.gitconfig", home));
742 if (!access(user_config, R_OK)) {
743 ret += git_config_from_file(fn, user_config, data);
744 found += 1;
746 free(user_config);
749 repo_config = git_pathdup("config");
750 if (!access(repo_config, R_OK)) {
751 ret += git_config_from_file(fn, repo_config, data);
752 found += 1;
754 free(repo_config);
755 if (found == 0)
756 return -1;
757 return ret;
761 * Find all the stuff for git_config_set() below.
764 #define MAX_MATCHES 512
766 static struct {
767 int baselen;
768 char *key;
769 int do_not_match;
770 regex_t *value_regex;
771 int multi_replace;
772 size_t offset[MAX_MATCHES];
773 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
774 int seen;
775 } store;
777 static int matches(const char *key, const char *value)
779 return !strcmp(key, store.key) &&
780 (store.value_regex == NULL ||
781 (store.do_not_match ^
782 !regexec(store.value_regex, value, 0, NULL, 0)));
785 static int store_aux(const char *key, const char *value, void *cb)
787 const char *ep;
788 size_t section_len;
790 switch (store.state) {
791 case KEY_SEEN:
792 if (matches(key, value)) {
793 if (store.seen == 1 && store.multi_replace == 0) {
794 warning("%s has multiple values", key);
795 } else if (store.seen >= MAX_MATCHES) {
796 error("too many matches for %s", key);
797 return 1;
800 store.offset[store.seen] = ftell(config_file);
801 store.seen++;
803 break;
804 case SECTION_SEEN:
806 * What we are looking for is in store.key (both
807 * section and var), and its section part is baselen
808 * long. We found key (again, both section and var).
809 * We would want to know if this key is in the same
810 * section as what we are looking for. We already
811 * know we are in the same section as what should
812 * hold store.key.
814 ep = strrchr(key, '.');
815 section_len = ep - key;
817 if ((section_len != store.baselen) ||
818 memcmp(key, store.key, section_len+1)) {
819 store.state = SECTION_END_SEEN;
820 break;
824 * Do not increment matches: this is no match, but we
825 * just made sure we are in the desired section.
827 store.offset[store.seen] = ftell(config_file);
828 /* fallthru */
829 case SECTION_END_SEEN:
830 case START:
831 if (matches(key, value)) {
832 store.offset[store.seen] = ftell(config_file);
833 store.state = KEY_SEEN;
834 store.seen++;
835 } else {
836 if (strrchr(key, '.') - key == store.baselen &&
837 !strncmp(key, store.key, store.baselen)) {
838 store.state = SECTION_SEEN;
839 store.offset[store.seen] = ftell(config_file);
843 return 0;
846 static int write_error(const char *filename)
848 error("failed to write new configuration file %s", filename);
850 /* Same error code as "failed to rename". */
851 return 4;
854 static int store_write_section(int fd, const char *key)
856 const char *dot;
857 int i, success;
858 struct strbuf sb = STRBUF_INIT;
860 dot = memchr(key, '.', store.baselen);
861 if (dot) {
862 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
863 for (i = dot - key + 1; i < store.baselen; i++) {
864 if (key[i] == '"' || key[i] == '\\')
865 strbuf_addch(&sb, '\\');
866 strbuf_addch(&sb, key[i]);
868 strbuf_addstr(&sb, "\"]\n");
869 } else {
870 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
873 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
874 strbuf_release(&sb);
876 return success;
879 static int store_write_pair(int fd, const char *key, const char *value)
881 int i, success;
882 int length = strlen(key + store.baselen + 1);
883 const char *quote = "";
884 struct strbuf sb = STRBUF_INIT;
887 * Check to see if the value needs to be surrounded with a dq pair.
888 * Note that problematic characters are always backslash-quoted; this
889 * check is about not losing leading or trailing SP and strings that
890 * follow beginning-of-comment characters (i.e. ';' and '#') by the
891 * configuration parser.
893 if (value[0] == ' ')
894 quote = "\"";
895 for (i = 0; value[i]; i++)
896 if (value[i] == ';' || value[i] == '#')
897 quote = "\"";
898 if (i && value[i - 1] == ' ')
899 quote = "\"";
901 strbuf_addf(&sb, "\t%.*s = %s",
902 length, key + store.baselen + 1, quote);
904 for (i = 0; value[i]; i++)
905 switch (value[i]) {
906 case '\n':
907 strbuf_addstr(&sb, "\\n");
908 break;
909 case '\t':
910 strbuf_addstr(&sb, "\\t");
911 break;
912 case '"':
913 case '\\':
914 strbuf_addch(&sb, '\\');
915 default:
916 strbuf_addch(&sb, value[i]);
917 break;
919 strbuf_addf(&sb, "%s\n", quote);
921 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
922 strbuf_release(&sb);
924 return success;
927 static ssize_t find_beginning_of_line(const char *contents, size_t size,
928 size_t offset_, int *found_bracket)
930 size_t equal_offset = size, bracket_offset = size;
931 ssize_t offset;
933 contline:
934 for (offset = offset_-2; offset > 0
935 && contents[offset] != '\n'; offset--)
936 switch (contents[offset]) {
937 case '=': equal_offset = offset; break;
938 case ']': bracket_offset = offset; break;
940 if (offset > 0 && contents[offset-1] == '\\') {
941 offset_ = offset;
942 goto contline;
944 if (bracket_offset < equal_offset) {
945 *found_bracket = 1;
946 offset = bracket_offset+1;
947 } else
948 offset++;
950 return offset;
953 int git_config_set(const char *key, const char *value)
955 return git_config_set_multivar(key, value, NULL, 0);
959 * If value==NULL, unset in (remove from) config,
960 * if value_regex!=NULL, disregard key/value pairs where value does not match.
961 * if multi_replace==0, nothing, or only one matching key/value is replaced,
962 * else all matching key/values (regardless how many) are removed,
963 * before the new pair is written.
965 * Returns 0 on success.
967 * This function does this:
969 * - it locks the config file by creating ".git/config.lock"
971 * - it then parses the config using store_aux() as validator to find
972 * the position on the key/value pair to replace. If it is to be unset,
973 * it must be found exactly once.
975 * - the config file is mmap()ed and the part before the match (if any) is
976 * written to the lock file, then the changed part and the rest.
978 * - the config file is removed and the lock file rename()d to it.
981 int git_config_set_multivar(const char *key, const char *value,
982 const char *value_regex, int multi_replace)
984 int i, dot;
985 int fd = -1, in_fd;
986 int ret;
987 char *config_filename;
988 struct lock_file *lock = NULL;
989 const char *last_dot = strrchr(key, '.');
991 if (config_exclusive_filename)
992 config_filename = xstrdup(config_exclusive_filename);
993 else
994 config_filename = git_pathdup("config");
997 * Since "key" actually contains the section name and the real
998 * key name separated by a dot, we have to know where the dot is.
1001 if (last_dot == NULL) {
1002 error("key does not contain a section: %s", key);
1003 ret = 2;
1004 goto out_free;
1006 store.baselen = last_dot - key;
1008 store.multi_replace = multi_replace;
1011 * Validate the key and while at it, lower case it for matching.
1013 store.key = xmalloc(strlen(key) + 1);
1014 dot = 0;
1015 for (i = 0; key[i]; i++) {
1016 unsigned char c = key[i];
1017 if (c == '.')
1018 dot = 1;
1019 /* Leave the extended basename untouched.. */
1020 if (!dot || i > store.baselen) {
1021 if (!iskeychar(c) || (i == store.baselen+1 && !isalpha(c))) {
1022 error("invalid key: %s", key);
1023 free(store.key);
1024 ret = 1;
1025 goto out_free;
1027 c = tolower(c);
1028 } else if (c == '\n') {
1029 error("invalid key (newline): %s", key);
1030 free(store.key);
1031 ret = 1;
1032 goto out_free;
1034 store.key[i] = c;
1036 store.key[i] = 0;
1039 * The lock serves a purpose in addition to locking: the new
1040 * contents of .git/config will be written into it.
1042 lock = xcalloc(sizeof(struct lock_file), 1);
1043 fd = hold_lock_file_for_update(lock, config_filename, 0);
1044 if (fd < 0) {
1045 error("could not lock config file %s: %s", config_filename, strerror(errno));
1046 free(store.key);
1047 ret = -1;
1048 goto out_free;
1052 * If .git/config does not exist yet, write a minimal version.
1054 in_fd = open(config_filename, O_RDONLY);
1055 if ( in_fd < 0 ) {
1056 free(store.key);
1058 if ( ENOENT != errno ) {
1059 error("opening %s: %s", config_filename,
1060 strerror(errno));
1061 ret = 3; /* same as "invalid config file" */
1062 goto out_free;
1064 /* if nothing to unset, error out */
1065 if (value == NULL) {
1066 ret = 5;
1067 goto out_free;
1070 store.key = (char *)key;
1071 if (!store_write_section(fd, key) ||
1072 !store_write_pair(fd, key, value))
1073 goto write_err_out;
1074 } else {
1075 struct stat st;
1076 char *contents;
1077 size_t contents_sz, copy_begin, copy_end;
1078 int i, new_line = 0;
1080 if (value_regex == NULL)
1081 store.value_regex = NULL;
1082 else {
1083 if (value_regex[0] == '!') {
1084 store.do_not_match = 1;
1085 value_regex++;
1086 } else
1087 store.do_not_match = 0;
1089 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1090 if (regcomp(store.value_regex, value_regex,
1091 REG_EXTENDED)) {
1092 error("invalid pattern: %s", value_regex);
1093 free(store.value_regex);
1094 ret = 6;
1095 goto out_free;
1099 store.offset[0] = 0;
1100 store.state = START;
1101 store.seen = 0;
1104 * After this, store.offset will contain the *end* offset
1105 * of the last match, or remain at 0 if no match was found.
1106 * As a side effect, we make sure to transform only a valid
1107 * existing config file.
1109 if (git_config_from_file(store_aux, config_filename, NULL)) {
1110 error("invalid config file %s", config_filename);
1111 free(store.key);
1112 if (store.value_regex != NULL) {
1113 regfree(store.value_regex);
1114 free(store.value_regex);
1116 ret = 3;
1117 goto out_free;
1120 free(store.key);
1121 if (store.value_regex != NULL) {
1122 regfree(store.value_regex);
1123 free(store.value_regex);
1126 /* if nothing to unset, or too many matches, error out */
1127 if ((store.seen == 0 && value == NULL) ||
1128 (store.seen > 1 && multi_replace == 0)) {
1129 ret = 5;
1130 goto out_free;
1133 fstat(in_fd, &st);
1134 contents_sz = xsize_t(st.st_size);
1135 contents = xmmap(NULL, contents_sz, PROT_READ,
1136 MAP_PRIVATE, in_fd, 0);
1137 close(in_fd);
1139 if (store.seen == 0)
1140 store.seen = 1;
1142 for (i = 0, copy_begin = 0; i < store.seen; i++) {
1143 if (store.offset[i] == 0) {
1144 store.offset[i] = copy_end = contents_sz;
1145 } else if (store.state != KEY_SEEN) {
1146 copy_end = store.offset[i];
1147 } else
1148 copy_end = find_beginning_of_line(
1149 contents, contents_sz,
1150 store.offset[i]-2, &new_line);
1152 if (copy_end > 0 && contents[copy_end-1] != '\n')
1153 new_line = 1;
1155 /* write the first part of the config */
1156 if (copy_end > copy_begin) {
1157 if (write_in_full(fd, contents + copy_begin,
1158 copy_end - copy_begin) <
1159 copy_end - copy_begin)
1160 goto write_err_out;
1161 if (new_line &&
1162 write_str_in_full(fd, "\n") != 1)
1163 goto write_err_out;
1165 copy_begin = store.offset[i];
1168 /* write the pair (value == NULL means unset) */
1169 if (value != NULL) {
1170 if (store.state == START) {
1171 if (!store_write_section(fd, key))
1172 goto write_err_out;
1174 if (!store_write_pair(fd, key, value))
1175 goto write_err_out;
1178 /* write the rest of the config */
1179 if (copy_begin < contents_sz)
1180 if (write_in_full(fd, contents + copy_begin,
1181 contents_sz - copy_begin) <
1182 contents_sz - copy_begin)
1183 goto write_err_out;
1185 munmap(contents, contents_sz);
1188 if (commit_lock_file(lock) < 0) {
1189 error("could not commit config file %s", config_filename);
1190 ret = 4;
1191 goto out_free;
1195 * lock is committed, so don't try to roll it back below.
1196 * NOTE: Since lockfile.c keeps a linked list of all created
1197 * lock_file structures, it isn't safe to free(lock). It's
1198 * better to just leave it hanging around.
1200 lock = NULL;
1201 ret = 0;
1203 out_free:
1204 if (lock)
1205 rollback_lock_file(lock);
1206 free(config_filename);
1207 return ret;
1209 write_err_out:
1210 ret = write_error(lock->filename);
1211 goto out_free;
1215 static int section_name_match (const char *buf, const char *name)
1217 int i = 0, j = 0, dot = 0;
1218 if (buf[i] != '[')
1219 return 0;
1220 for (i = 1; buf[i] && buf[i] != ']'; i++) {
1221 if (!dot && isspace(buf[i])) {
1222 dot = 1;
1223 if (name[j++] != '.')
1224 break;
1225 for (i++; isspace(buf[i]); i++)
1226 ; /* do nothing */
1227 if (buf[i] != '"')
1228 break;
1229 continue;
1231 if (buf[i] == '\\' && dot)
1232 i++;
1233 else if (buf[i] == '"' && dot) {
1234 for (i++; isspace(buf[i]); i++)
1235 ; /* do_nothing */
1236 break;
1238 if (buf[i] != name[j++])
1239 break;
1241 if (buf[i] == ']' && name[j] == 0) {
1243 * We match, now just find the right length offset by
1244 * gobbling up any whitespace after it, as well
1246 i++;
1247 for (; buf[i] && isspace(buf[i]); i++)
1248 ; /* do nothing */
1249 return i;
1251 return 0;
1254 /* if new_name == NULL, the section is removed instead */
1255 int git_config_rename_section(const char *old_name, const char *new_name)
1257 int ret = 0, remove = 0;
1258 char *config_filename;
1259 struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1260 int out_fd;
1261 char buf[1024];
1263 if (config_exclusive_filename)
1264 config_filename = xstrdup(config_exclusive_filename);
1265 else
1266 config_filename = git_pathdup("config");
1267 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1268 if (out_fd < 0) {
1269 ret = error("could not lock config file %s", config_filename);
1270 goto out;
1273 if (!(config_file = fopen(config_filename, "rb"))) {
1274 /* no config file means nothing to rename, no error */
1275 goto unlock_and_out;
1278 while (fgets(buf, sizeof(buf), config_file)) {
1279 int i;
1280 int length;
1281 char *output = buf;
1282 for (i = 0; buf[i] && isspace(buf[i]); i++)
1283 ; /* do nothing */
1284 if (buf[i] == '[') {
1285 /* it's a section */
1286 int offset = section_name_match(&buf[i], old_name);
1287 if (offset > 0) {
1288 ret++;
1289 if (new_name == NULL) {
1290 remove = 1;
1291 continue;
1293 store.baselen = strlen(new_name);
1294 if (!store_write_section(out_fd, new_name)) {
1295 ret = write_error(lock->filename);
1296 goto out;
1299 * We wrote out the new section, with
1300 * a newline, now skip the old
1301 * section's length
1303 output += offset + i;
1304 if (strlen(output) > 0) {
1306 * More content means there's
1307 * a declaration to put on the
1308 * next line; indent with a
1309 * tab
1311 output -= 1;
1312 output[0] = '\t';
1315 remove = 0;
1317 if (remove)
1318 continue;
1319 length = strlen(output);
1320 if (write_in_full(out_fd, output, length) != length) {
1321 ret = write_error(lock->filename);
1322 goto out;
1325 fclose(config_file);
1326 unlock_and_out:
1327 if (commit_lock_file(lock) < 0)
1328 ret = error("could not commit config file %s", config_filename);
1329 out:
1330 free(config_filename);
1331 return ret;
1335 * Call this to report error for your variable that should not
1336 * get a boolean value (i.e. "[my] var" means "true").
1338 int config_error_nonbool(const char *var)
1340 return error("Missing value for '%s'", var);