fix mingw stat() and lstat() implementations for handling symlinks
[git/dscho.git] / config.c
blob42e94f991bae5ce3c7041f81b92b68f5ba3b8240
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 * Copyright (C) Johannes Schindelin, 2005
7 */
8 #include "cache.h"
9 #include "exec_cmd.h"
10 #include "strbuf.h"
12 #define MAXNAME (256)
14 static FILE *config_file;
15 static const char *config_file_name;
16 static int config_linenr;
17 static int config_file_eof;
18 static int zlib_compression_seen;
20 const char *config_exclusive_filename = NULL;
22 struct config_item
24 struct config_item *next;
25 char *name;
26 char *value;
28 static struct config_item *config_parameters;
29 static struct config_item **config_parameters_tail = &config_parameters;
31 static void lowercase(char *p)
33 for (; *p; p++)
34 *p = tolower(*p);
37 int git_config_parse_parameter(const char *text)
39 struct config_item *ct;
40 struct strbuf tmp = STRBUF_INIT;
41 struct strbuf **pair;
42 strbuf_addstr(&tmp, text);
43 pair = strbuf_split(&tmp, '=');
44 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=')
45 strbuf_setlen(pair[0], pair[0]->len - 1);
46 strbuf_trim(pair[0]);
47 if (!pair[0]->len) {
48 strbuf_list_free(pair);
49 return -1;
51 ct = xcalloc(1, sizeof(struct config_item));
52 ct->name = strbuf_detach(pair[0], NULL);
53 if (pair[1]) {
54 strbuf_trim(pair[1]);
55 ct->value = strbuf_detach(pair[1], NULL);
57 strbuf_list_free(pair);
58 lowercase(ct->name);
59 *config_parameters_tail = ct;
60 config_parameters_tail = &ct->next;
61 return 0;
64 static int get_next_char(void)
66 int c;
67 FILE *f;
69 c = '\n';
70 if ((f = config_file) != NULL) {
71 c = fgetc(f);
72 if (c == '\r') {
73 /* DOS like systems */
74 c = fgetc(f);
75 if (c != '\n') {
76 ungetc(c, f);
77 c = '\r';
80 if (c == '\n')
81 config_linenr++;
82 if (c == EOF) {
83 config_file_eof = 1;
84 c = '\n';
87 return c;
90 static char *parse_value(void)
92 static char value[1024];
93 int quote = 0, comment = 0, len = 0, space = 0;
95 for (;;) {
96 int c = get_next_char();
97 if (len >= sizeof(value) - 1)
98 return NULL;
99 if (c == '\n') {
100 if (quote)
101 return NULL;
102 value[len] = 0;
103 return value;
105 if (comment)
106 continue;
107 if (isspace(c) && !quote) {
108 if (len)
109 space++;
110 continue;
112 if (!quote) {
113 if (c == ';' || c == '#') {
114 comment = 1;
115 continue;
118 for (; space; space--)
119 value[len++] = ' ';
120 if (c == '\\') {
121 c = get_next_char();
122 switch (c) {
123 case '\n':
124 continue;
125 case 't':
126 c = '\t';
127 break;
128 case 'b':
129 c = '\b';
130 break;
131 case 'n':
132 c = '\n';
133 break;
134 /* Some characters escape as themselves */
135 case '\\': case '"':
136 break;
137 /* Reject unknown escape sequences */
138 default:
139 return NULL;
141 value[len++] = c;
142 continue;
144 if (c == '"') {
145 quote = 1-quote;
146 continue;
148 value[len++] = c;
152 static inline int iskeychar(int c)
154 return isalnum(c) || c == '-';
157 static int get_value(config_fn_t fn, void *data, char *name, unsigned int len)
159 int c;
160 char *value;
162 /* Get the full name */
163 for (;;) {
164 c = get_next_char();
165 if (config_file_eof)
166 break;
167 if (!iskeychar(c))
168 break;
169 name[len++] = tolower(c);
170 if (len >= MAXNAME)
171 return -1;
173 name[len] = 0;
174 while (c == ' ' || c == '\t')
175 c = get_next_char();
177 value = NULL;
178 if (c != '\n') {
179 if (c != '=')
180 return -1;
181 value = parse_value();
182 if (!value)
183 return -1;
185 return fn(name, value, data);
188 static int get_extended_base_var(char *name, int baselen, int c)
190 do {
191 if (c == '\n')
192 return -1;
193 c = get_next_char();
194 } while (isspace(c));
196 /* We require the format to be '[base "extension"]' */
197 if (c != '"')
198 return -1;
199 name[baselen++] = '.';
201 for (;;) {
202 int c = get_next_char();
203 if (c == '\n')
204 return -1;
205 if (c == '"')
206 break;
207 if (c == '\\') {
208 c = get_next_char();
209 if (c == '\n')
210 return -1;
212 name[baselen++] = c;
213 if (baselen > MAXNAME / 2)
214 return -1;
217 /* Final ']' */
218 if (get_next_char() != ']')
219 return -1;
220 return baselen;
223 static int get_base_var(char *name)
225 int baselen = 0;
227 for (;;) {
228 int c = get_next_char();
229 if (config_file_eof)
230 return -1;
231 if (c == ']')
232 return baselen;
233 if (isspace(c))
234 return get_extended_base_var(name, baselen, c);
235 if (!iskeychar(c) && c != '.')
236 return -1;
237 if (baselen > MAXNAME / 2)
238 return -1;
239 name[baselen++] = tolower(c);
243 static int git_parse_file(config_fn_t fn, void *data)
245 int comment = 0;
246 int baselen = 0;
247 static char var[MAXNAME];
249 /* U+FEFF Byte Order Mark in UTF8 */
250 static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
251 const unsigned char *bomptr = utf8_bom;
253 for (;;) {
254 int c = get_next_char();
255 if (bomptr && *bomptr) {
256 /* We are at the file beginning; skip UTF8-encoded BOM
257 * if present. Sane editors won't put this in on their
258 * own, but e.g. Windows Notepad will do it happily. */
259 if ((unsigned char) c == *bomptr) {
260 bomptr++;
261 continue;
262 } else {
263 /* Do not tolerate partial BOM. */
264 if (bomptr != utf8_bom)
265 break;
266 /* No BOM at file beginning. Cool. */
267 bomptr = NULL;
270 if (c == '\n') {
271 if (config_file_eof)
272 return 0;
273 comment = 0;
274 continue;
276 if (comment || isspace(c))
277 continue;
278 if (c == '#' || c == ';') {
279 comment = 1;
280 continue;
282 if (c == '[') {
283 baselen = get_base_var(var);
284 if (baselen <= 0)
285 break;
286 var[baselen++] = '.';
287 var[baselen] = 0;
288 continue;
290 if (!isalpha(c))
291 break;
292 var[baselen] = tolower(c);
293 if (get_value(fn, data, var, baselen+1) < 0)
294 break;
296 die("bad config file line %d in %s", config_linenr, config_file_name);
299 static int parse_unit_factor(const char *end, unsigned long *val)
301 if (!*end)
302 return 1;
303 else if (!strcasecmp(end, "k")) {
304 *val *= 1024;
305 return 1;
307 else if (!strcasecmp(end, "m")) {
308 *val *= 1024 * 1024;
309 return 1;
311 else if (!strcasecmp(end, "g")) {
312 *val *= 1024 * 1024 * 1024;
313 return 1;
315 return 0;
318 static int git_parse_long(const char *value, long *ret)
320 if (value && *value) {
321 char *end;
322 long val = strtol(value, &end, 0);
323 unsigned long factor = 1;
324 if (!parse_unit_factor(end, &factor))
325 return 0;
326 *ret = val * factor;
327 return 1;
329 return 0;
332 int git_parse_ulong(const char *value, unsigned long *ret)
334 if (value && *value) {
335 char *end;
336 unsigned long val = strtoul(value, &end, 0);
337 if (!parse_unit_factor(end, &val))
338 return 0;
339 *ret = val;
340 return 1;
342 return 0;
345 static void die_bad_config(const char *name)
347 if (config_file_name)
348 die("bad config value for '%s' in %s", name, config_file_name);
349 die("bad config value for '%s'", name);
352 int git_config_int(const char *name, const char *value)
354 long ret = 0;
355 if (!git_parse_long(value, &ret))
356 die_bad_config(name);
357 return ret;
360 unsigned long git_config_ulong(const char *name, const char *value)
362 unsigned long ret;
363 if (!git_parse_ulong(value, &ret))
364 die_bad_config(name);
365 return ret;
368 int git_config_maybe_bool(const char *name, const char *value)
370 if (!value)
371 return 1;
372 if (!*value)
373 return 0;
374 if (!strcasecmp(value, "true")
375 || !strcasecmp(value, "yes")
376 || !strcasecmp(value, "on"))
377 return 1;
378 if (!strcasecmp(value, "false")
379 || !strcasecmp(value, "no")
380 || !strcasecmp(value, "off"))
381 return 0;
382 return -1;
385 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
387 int v = git_config_maybe_bool(name, value);
388 if (0 <= v) {
389 *is_bool = 1;
390 return v;
392 *is_bool = 0;
393 return git_config_int(name, value);
396 int git_config_bool(const char *name, const char *value)
398 int discard;
399 return !!git_config_bool_or_int(name, value, &discard);
402 int git_config_string(const char **dest, const char *var, const char *value)
404 if (!value)
405 return config_error_nonbool(var);
406 *dest = xstrdup(value);
407 return 0;
410 int git_config_pathname(const char **dest, const char *var, const char *value)
412 if (!value)
413 return config_error_nonbool(var);
414 *dest = expand_user_path(value);
415 if (!*dest)
416 die("Failed to expand user dir in: '%s'", value);
417 return 0;
420 static int git_default_core_config(const char *var, const char *value)
422 /* This needs a better name */
423 if (!strcmp(var, "core.filemode")) {
424 trust_executable_bit = git_config_bool(var, value);
425 return 0;
427 if (!strcmp(var, "core.trustctime")) {
428 trust_ctime = git_config_bool(var, value);
429 return 0;
432 if (!strcmp(var, "core.quotepath")) {
433 quote_path_fully = git_config_bool(var, value);
434 return 0;
437 if (!strcmp(var, "core.symlinks")) {
438 has_symlinks = git_config_bool(var, value);
439 return 0;
442 if (!strcmp(var, "core.ignorecase")) {
443 ignore_case = git_config_bool(var, value);
444 return 0;
447 if (!strcmp(var, "core.bare")) {
448 is_bare_repository_cfg = git_config_bool(var, value);
449 return 0;
452 if (!strcmp(var, "core.ignorestat")) {
453 assume_unchanged = git_config_bool(var, value);
454 return 0;
457 if (!strcmp(var, "core.prefersymlinkrefs")) {
458 prefer_symlink_refs = git_config_bool(var, value);
459 return 0;
462 if (!strcmp(var, "core.logallrefupdates")) {
463 log_all_ref_updates = git_config_bool(var, value);
464 return 0;
467 if (!strcmp(var, "core.warnambiguousrefs")) {
468 warn_ambiguous_refs = git_config_bool(var, value);
469 return 0;
472 if (!strcmp(var, "core.loosecompression")) {
473 int level = git_config_int(var, value);
474 if (level == -1)
475 level = Z_DEFAULT_COMPRESSION;
476 else if (level < 0 || level > Z_BEST_COMPRESSION)
477 die("bad zlib compression level %d", level);
478 zlib_compression_level = level;
479 zlib_compression_seen = 1;
480 return 0;
483 if (!strcmp(var, "core.compression")) {
484 int level = git_config_int(var, value);
485 if (level == -1)
486 level = Z_DEFAULT_COMPRESSION;
487 else if (level < 0 || level > Z_BEST_COMPRESSION)
488 die("bad zlib compression level %d", level);
489 core_compression_level = level;
490 core_compression_seen = 1;
491 if (!zlib_compression_seen)
492 zlib_compression_level = level;
493 return 0;
496 if (!strcmp(var, "core.packedgitwindowsize")) {
497 int pgsz_x2 = getpagesize() * 2;
498 packed_git_window_size = git_config_int(var, value);
500 /* This value must be multiple of (pagesize * 2) */
501 packed_git_window_size /= pgsz_x2;
502 if (packed_git_window_size < 1)
503 packed_git_window_size = 1;
504 packed_git_window_size *= pgsz_x2;
505 return 0;
508 if (!strcmp(var, "core.packedgitlimit")) {
509 packed_git_limit = git_config_int(var, value);
510 return 0;
513 if (!strcmp(var, "core.deltabasecachelimit")) {
514 delta_base_cache_limit = git_config_int(var, value);
515 return 0;
518 if (!strcmp(var, "core.autocrlf")) {
519 if (value && !strcasecmp(value, "input")) {
520 if (eol == EOL_CRLF)
521 return error("core.autocrlf=input conflicts with core.eol=crlf");
522 auto_crlf = AUTO_CRLF_INPUT;
523 return 0;
525 auto_crlf = git_config_bool(var, value);
526 return 0;
529 if (!strcmp(var, "core.safecrlf")) {
530 if (value && !strcasecmp(value, "warn")) {
531 safe_crlf = SAFE_CRLF_WARN;
532 return 0;
534 safe_crlf = git_config_bool(var, value);
535 return 0;
538 if (!strcmp(var, "core.eol")) {
539 if (value && !strcasecmp(value, "lf"))
540 eol = EOL_LF;
541 else if (value && !strcasecmp(value, "crlf"))
542 eol = EOL_CRLF;
543 else if (value && !strcasecmp(value, "native"))
544 eol = EOL_NATIVE;
545 else
546 eol = EOL_UNSET;
547 if (eol == EOL_CRLF && auto_crlf == AUTO_CRLF_INPUT)
548 return error("core.autocrlf=input conflicts with core.eol=crlf");
549 return 0;
552 if (!strcmp(var, "core.notesref")) {
553 notes_ref_name = xstrdup(value);
554 return 0;
557 if (!strcmp(var, "core.pager"))
558 return git_config_string(&pager_program, var, value);
560 if (!strcmp(var, "core.editor"))
561 return git_config_string(&editor_program, var, value);
563 if (!strcmp(var, "core.excludesfile"))
564 return git_config_pathname(&excludes_file, var, value);
566 if (!strcmp(var, "core.whitespace")) {
567 if (!value)
568 return config_error_nonbool(var);
569 whitespace_rule_cfg = parse_whitespace_rule(value);
570 return 0;
573 if (!strcmp(var, "core.fsyncobjectfiles")) {
574 fsync_object_files = git_config_bool(var, value);
575 return 0;
578 if (!strcmp(var, "core.preloadindex")) {
579 core_preload_index = git_config_bool(var, value);
580 return 0;
583 if (!strcmp(var, "core.createobject")) {
584 if (!strcmp(value, "rename"))
585 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
586 else if (!strcmp(value, "link"))
587 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
588 else
589 die("Invalid mode for object creation: %s", value);
590 return 0;
593 if (!strcmp(var, "core.sparsecheckout")) {
594 core_apply_sparse_checkout = git_config_bool(var, value);
595 return 0;
598 if (!strcmp(var, "core.hidedotfiles")) {
599 if (value && !strcasecmp(value, "dotgitonly")) {
600 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
601 return 0;
603 hide_dotfiles = git_config_bool(var, value);
604 return 0;
607 /* Add other config variables here and to Documentation/config.txt. */
608 return 0;
611 static int git_default_user_config(const char *var, const char *value)
613 if (!strcmp(var, "user.name")) {
614 if (!value)
615 return config_error_nonbool(var);
616 strlcpy(git_default_name, value, sizeof(git_default_name));
617 user_ident_explicitly_given |= IDENT_NAME_GIVEN;
618 return 0;
621 if (!strcmp(var, "user.email")) {
622 if (!value)
623 return config_error_nonbool(var);
624 strlcpy(git_default_email, value, sizeof(git_default_email));
625 user_ident_explicitly_given |= IDENT_MAIL_GIVEN;
626 return 0;
629 /* Add other config variables here and to Documentation/config.txt. */
630 return 0;
633 static int git_default_i18n_config(const char *var, const char *value)
635 if (!strcmp(var, "i18n.commitencoding"))
636 return git_config_string(&git_commit_encoding, var, value);
638 if (!strcmp(var, "i18n.logoutputencoding"))
639 return git_config_string(&git_log_output_encoding, var, value);
641 /* Add other config variables here and to Documentation/config.txt. */
642 return 0;
645 static int git_default_branch_config(const char *var, const char *value)
647 if (!strcmp(var, "branch.autosetupmerge")) {
648 if (value && !strcasecmp(value, "always")) {
649 git_branch_track = BRANCH_TRACK_ALWAYS;
650 return 0;
652 git_branch_track = git_config_bool(var, value);
653 return 0;
655 if (!strcmp(var, "branch.autosetuprebase")) {
656 if (!value)
657 return config_error_nonbool(var);
658 else if (!strcmp(value, "never"))
659 autorebase = AUTOREBASE_NEVER;
660 else if (!strcmp(value, "local"))
661 autorebase = AUTOREBASE_LOCAL;
662 else if (!strcmp(value, "remote"))
663 autorebase = AUTOREBASE_REMOTE;
664 else if (!strcmp(value, "always"))
665 autorebase = AUTOREBASE_ALWAYS;
666 else
667 return error("Malformed value for %s", var);
668 return 0;
671 /* Add other config variables here and to Documentation/config.txt. */
672 return 0;
675 static int git_default_push_config(const char *var, const char *value)
677 if (!strcmp(var, "push.default")) {
678 if (!value)
679 return config_error_nonbool(var);
680 else if (!strcmp(value, "nothing"))
681 push_default = PUSH_DEFAULT_NOTHING;
682 else if (!strcmp(value, "matching"))
683 push_default = PUSH_DEFAULT_MATCHING;
684 else if (!strcmp(value, "tracking"))
685 push_default = PUSH_DEFAULT_TRACKING;
686 else if (!strcmp(value, "current"))
687 push_default = PUSH_DEFAULT_CURRENT;
688 else {
689 error("Malformed value for %s: %s", var, value);
690 return error("Must be one of nothing, matching, "
691 "tracking or current.");
693 return 0;
696 /* Add other config variables here and to Documentation/config.txt. */
697 return 0;
700 static int git_default_mailmap_config(const char *var, const char *value)
702 if (!strcmp(var, "mailmap.file"))
703 return git_config_string(&git_mailmap_file, var, value);
705 /* Add other config variables here and to Documentation/config.txt. */
706 return 0;
709 int git_default_config(const char *var, const char *value, void *dummy)
711 if (!prefixcmp(var, "core."))
712 return git_default_core_config(var, value);
714 if (!prefixcmp(var, "user."))
715 return git_default_user_config(var, value);
717 if (!prefixcmp(var, "i18n."))
718 return git_default_i18n_config(var, value);
720 if (!prefixcmp(var, "branch."))
721 return git_default_branch_config(var, value);
723 if (!prefixcmp(var, "push."))
724 return git_default_push_config(var, value);
726 if (!prefixcmp(var, "mailmap."))
727 return git_default_mailmap_config(var, value);
729 if (!prefixcmp(var, "advice."))
730 return git_default_advice_config(var, value);
732 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
733 pager_use_color = git_config_bool(var,value);
734 return 0;
737 /* Add other config variables here and to Documentation/config.txt. */
738 return 0;
741 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
743 int ret;
744 FILE *f = fopen(filename, "r");
746 ret = -1;
747 if (f) {
748 config_file = f;
749 config_file_name = filename;
750 config_linenr = 1;
751 config_file_eof = 0;
752 ret = git_parse_file(fn, data);
753 fclose(f);
754 config_file_name = NULL;
756 return ret;
759 const char *git_etc_gitconfig(void)
761 static const char *system_wide;
762 if (!system_wide)
763 system_wide = system_path(ETC_GITCONFIG);
764 return system_wide;
767 int git_env_bool(const char *k, int def)
769 const char *v = getenv(k);
770 return v ? git_config_bool(k, v) : def;
773 int git_config_system(void)
775 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
778 int git_config_global(void)
780 return !git_env_bool("GIT_CONFIG_NOGLOBAL", 0);
783 int git_config_from_parameters(config_fn_t fn, void *data)
785 const struct config_item *ct;
786 for (ct = config_parameters; ct; ct = ct->next)
787 if (fn(ct->name, ct->value, data) < 0)
788 return -1;
789 return 0;
792 int git_config(config_fn_t fn, void *data)
794 int ret = 0, found = 0;
795 char *repo_config = NULL;
796 const char *home = NULL;
798 /* Setting $GIT_CONFIG makes git read _only_ the given config file. */
799 if (config_exclusive_filename)
800 return git_config_from_file(fn, config_exclusive_filename, data);
801 if (git_config_system() && !access(git_etc_gitconfig(), R_OK)) {
802 ret += git_config_from_file(fn, git_etc_gitconfig(),
803 data);
804 found += 1;
807 home = getenv("HOME");
808 if (git_config_global() && home) {
809 char *user_config = xstrdup(mkpath("%s/.gitconfig", home));
810 if (!access(user_config, R_OK)) {
811 ret += git_config_from_file(fn, user_config, data);
812 found += 1;
814 free(user_config);
817 repo_config = git_pathdup("config");
818 if (!access(repo_config, R_OK)) {
819 ret += git_config_from_file(fn, repo_config, data);
820 found += 1;
822 free(repo_config);
824 if (config_parameters) {
825 ret += git_config_from_parameters(fn, data);
826 found += 1;
829 if (found == 0)
830 return -1;
831 return ret;
835 * Find all the stuff for git_config_set() below.
838 #define MAX_MATCHES 512
840 static struct {
841 int baselen;
842 char *key;
843 int do_not_match;
844 regex_t *value_regex;
845 int multi_replace;
846 size_t offset[MAX_MATCHES];
847 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
848 int seen;
849 } store;
851 static int matches(const char *key, const char *value)
853 return !strcmp(key, store.key) &&
854 (store.value_regex == NULL ||
855 (store.do_not_match ^
856 !regexec(store.value_regex, value, 0, NULL, 0)));
859 static int store_aux(const char *key, const char *value, void *cb)
861 const char *ep;
862 size_t section_len;
864 switch (store.state) {
865 case KEY_SEEN:
866 if (matches(key, value)) {
867 if (store.seen == 1 && store.multi_replace == 0) {
868 warning("%s has multiple values", key);
869 } else if (store.seen >= MAX_MATCHES) {
870 error("too many matches for %s", key);
871 return 1;
874 store.offset[store.seen] = ftell(config_file);
875 store.seen++;
877 break;
878 case SECTION_SEEN:
880 * What we are looking for is in store.key (both
881 * section and var), and its section part is baselen
882 * long. We found key (again, both section and var).
883 * We would want to know if this key is in the same
884 * section as what we are looking for. We already
885 * know we are in the same section as what should
886 * hold store.key.
888 ep = strrchr(key, '.');
889 section_len = ep - key;
891 if ((section_len != store.baselen) ||
892 memcmp(key, store.key, section_len+1)) {
893 store.state = SECTION_END_SEEN;
894 break;
898 * Do not increment matches: this is no match, but we
899 * just made sure we are in the desired section.
901 store.offset[store.seen] = ftell(config_file);
902 /* fallthru */
903 case SECTION_END_SEEN:
904 case START:
905 if (matches(key, value)) {
906 store.offset[store.seen] = ftell(config_file);
907 store.state = KEY_SEEN;
908 store.seen++;
909 } else {
910 if (strrchr(key, '.') - key == store.baselen &&
911 !strncmp(key, store.key, store.baselen)) {
912 store.state = SECTION_SEEN;
913 store.offset[store.seen] = ftell(config_file);
917 return 0;
920 static int write_error(const char *filename)
922 error("failed to write new configuration file %s", filename);
924 /* Same error code as "failed to rename". */
925 return 4;
928 static int store_write_section(int fd, const char *key)
930 const char *dot;
931 int i, success;
932 struct strbuf sb = STRBUF_INIT;
934 dot = memchr(key, '.', store.baselen);
935 if (dot) {
936 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
937 for (i = dot - key + 1; i < store.baselen; i++) {
938 if (key[i] == '"' || key[i] == '\\')
939 strbuf_addch(&sb, '\\');
940 strbuf_addch(&sb, key[i]);
942 strbuf_addstr(&sb, "\"]\n");
943 } else {
944 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
947 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
948 strbuf_release(&sb);
950 return success;
953 static int store_write_pair(int fd, const char *key, const char *value)
955 int i, success;
956 int length = strlen(key + store.baselen + 1);
957 const char *quote = "";
958 struct strbuf sb = STRBUF_INIT;
961 * Check to see if the value needs to be surrounded with a dq pair.
962 * Note that problematic characters are always backslash-quoted; this
963 * check is about not losing leading or trailing SP and strings that
964 * follow beginning-of-comment characters (i.e. ';' and '#') by the
965 * configuration parser.
967 if (value[0] == ' ')
968 quote = "\"";
969 for (i = 0; value[i]; i++)
970 if (value[i] == ';' || value[i] == '#')
971 quote = "\"";
972 if (i && value[i - 1] == ' ')
973 quote = "\"";
975 strbuf_addf(&sb, "\t%.*s = %s",
976 length, key + store.baselen + 1, quote);
978 for (i = 0; value[i]; i++)
979 switch (value[i]) {
980 case '\n':
981 strbuf_addstr(&sb, "\\n");
982 break;
983 case '\t':
984 strbuf_addstr(&sb, "\\t");
985 break;
986 case '"':
987 case '\\':
988 strbuf_addch(&sb, '\\');
989 default:
990 strbuf_addch(&sb, value[i]);
991 break;
993 strbuf_addf(&sb, "%s\n", quote);
995 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
996 strbuf_release(&sb);
998 return success;
1001 static ssize_t find_beginning_of_line(const char *contents, size_t size,
1002 size_t offset_, int *found_bracket)
1004 size_t equal_offset = size, bracket_offset = size;
1005 ssize_t offset;
1007 contline:
1008 for (offset = offset_-2; offset > 0
1009 && contents[offset] != '\n'; offset--)
1010 switch (contents[offset]) {
1011 case '=': equal_offset = offset; break;
1012 case ']': bracket_offset = offset; break;
1014 if (offset > 0 && contents[offset-1] == '\\') {
1015 offset_ = offset;
1016 goto contline;
1018 if (bracket_offset < equal_offset) {
1019 *found_bracket = 1;
1020 offset = bracket_offset+1;
1021 } else
1022 offset++;
1024 return offset;
1027 int git_config_set(const char *key, const char *value)
1029 return git_config_set_multivar(key, value, NULL, 0);
1033 * If value==NULL, unset in (remove from) config,
1034 * if value_regex!=NULL, disregard key/value pairs where value does not match.
1035 * if multi_replace==0, nothing, or only one matching key/value is replaced,
1036 * else all matching key/values (regardless how many) are removed,
1037 * before the new pair is written.
1039 * Returns 0 on success.
1041 * This function does this:
1043 * - it locks the config file by creating ".git/config.lock"
1045 * - it then parses the config using store_aux() as validator to find
1046 * the position on the key/value pair to replace. If it is to be unset,
1047 * it must be found exactly once.
1049 * - the config file is mmap()ed and the part before the match (if any) is
1050 * written to the lock file, then the changed part and the rest.
1052 * - the config file is removed and the lock file rename()d to it.
1055 int git_config_set_multivar(const char *key, const char *value,
1056 const char *value_regex, int multi_replace)
1058 int i, dot;
1059 int fd = -1, in_fd;
1060 int ret;
1061 char *config_filename;
1062 struct lock_file *lock = NULL;
1063 const char *last_dot = strrchr(key, '.');
1065 if (config_exclusive_filename)
1066 config_filename = xstrdup(config_exclusive_filename);
1067 else
1068 config_filename = git_pathdup("config");
1071 * Since "key" actually contains the section name and the real
1072 * key name separated by a dot, we have to know where the dot is.
1075 if (last_dot == NULL) {
1076 error("key does not contain a section: %s", key);
1077 ret = 2;
1078 goto out_free;
1080 store.baselen = last_dot - key;
1082 store.multi_replace = multi_replace;
1085 * Validate the key and while at it, lower case it for matching.
1087 store.key = xmalloc(strlen(key) + 1);
1088 dot = 0;
1089 for (i = 0; key[i]; i++) {
1090 unsigned char c = key[i];
1091 if (c == '.')
1092 dot = 1;
1093 /* Leave the extended basename untouched.. */
1094 if (!dot || i > store.baselen) {
1095 if (!iskeychar(c) || (i == store.baselen+1 && !isalpha(c))) {
1096 error("invalid key: %s", key);
1097 free(store.key);
1098 ret = 1;
1099 goto out_free;
1101 c = tolower(c);
1102 } else if (c == '\n') {
1103 error("invalid key (newline): %s", key);
1104 free(store.key);
1105 ret = 1;
1106 goto out_free;
1108 store.key[i] = c;
1110 store.key[i] = 0;
1113 * The lock serves a purpose in addition to locking: the new
1114 * contents of .git/config will be written into it.
1116 lock = xcalloc(sizeof(struct lock_file), 1);
1117 fd = hold_lock_file_for_update(lock, config_filename, 0);
1118 if (fd < 0) {
1119 error("could not lock config file %s: %s", config_filename, strerror(errno));
1120 free(store.key);
1121 ret = -1;
1122 goto out_free;
1126 * If .git/config does not exist yet, write a minimal version.
1128 in_fd = open(config_filename, O_RDONLY);
1129 if ( in_fd < 0 ) {
1130 free(store.key);
1132 if ( ENOENT != errno ) {
1133 error("opening %s: %s", config_filename,
1134 strerror(errno));
1135 ret = 3; /* same as "invalid config file" */
1136 goto out_free;
1138 /* if nothing to unset, error out */
1139 if (value == NULL) {
1140 ret = 5;
1141 goto out_free;
1144 store.key = (char *)key;
1145 if (!store_write_section(fd, key) ||
1146 !store_write_pair(fd, key, value))
1147 goto write_err_out;
1148 } else {
1149 struct stat st;
1150 char *contents;
1151 size_t contents_sz, copy_begin, copy_end;
1152 int i, new_line = 0;
1154 if (value_regex == NULL)
1155 store.value_regex = NULL;
1156 else {
1157 if (value_regex[0] == '!') {
1158 store.do_not_match = 1;
1159 value_regex++;
1160 } else
1161 store.do_not_match = 0;
1163 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1164 if (regcomp(store.value_regex, value_regex,
1165 REG_EXTENDED)) {
1166 error("invalid pattern: %s", value_regex);
1167 free(store.value_regex);
1168 ret = 6;
1169 goto out_free;
1173 store.offset[0] = 0;
1174 store.state = START;
1175 store.seen = 0;
1178 * After this, store.offset will contain the *end* offset
1179 * of the last match, or remain at 0 if no match was found.
1180 * As a side effect, we make sure to transform only a valid
1181 * existing config file.
1183 if (git_config_from_file(store_aux, config_filename, NULL)) {
1184 error("invalid config file %s", config_filename);
1185 free(store.key);
1186 if (store.value_regex != NULL) {
1187 regfree(store.value_regex);
1188 free(store.value_regex);
1190 ret = 3;
1191 goto out_free;
1194 free(store.key);
1195 if (store.value_regex != NULL) {
1196 regfree(store.value_regex);
1197 free(store.value_regex);
1200 /* if nothing to unset, or too many matches, error out */
1201 if ((store.seen == 0 && value == NULL) ||
1202 (store.seen > 1 && multi_replace == 0)) {
1203 ret = 5;
1204 goto out_free;
1207 fstat(in_fd, &st);
1208 contents_sz = xsize_t(st.st_size);
1209 contents = xmmap(NULL, contents_sz, PROT_READ,
1210 MAP_PRIVATE, in_fd, 0);
1211 close(in_fd);
1213 if (store.seen == 0)
1214 store.seen = 1;
1216 for (i = 0, copy_begin = 0; i < store.seen; i++) {
1217 if (store.offset[i] == 0) {
1218 store.offset[i] = copy_end = contents_sz;
1219 } else if (store.state != KEY_SEEN) {
1220 copy_end = store.offset[i];
1221 } else
1222 copy_end = find_beginning_of_line(
1223 contents, contents_sz,
1224 store.offset[i]-2, &new_line);
1226 if (copy_end > 0 && contents[copy_end-1] != '\n')
1227 new_line = 1;
1229 /* write the first part of the config */
1230 if (copy_end > copy_begin) {
1231 if (write_in_full(fd, contents + copy_begin,
1232 copy_end - copy_begin) <
1233 copy_end - copy_begin)
1234 goto write_err_out;
1235 if (new_line &&
1236 write_str_in_full(fd, "\n") != 1)
1237 goto write_err_out;
1239 copy_begin = store.offset[i];
1242 /* write the pair (value == NULL means unset) */
1243 if (value != NULL) {
1244 if (store.state == START) {
1245 if (!store_write_section(fd, key))
1246 goto write_err_out;
1248 if (!store_write_pair(fd, key, value))
1249 goto write_err_out;
1252 /* write the rest of the config */
1253 if (copy_begin < contents_sz)
1254 if (write_in_full(fd, contents + copy_begin,
1255 contents_sz - copy_begin) <
1256 contents_sz - copy_begin)
1257 goto write_err_out;
1259 munmap(contents, contents_sz);
1262 if (commit_lock_file(lock) < 0) {
1263 error("could not commit config file %s", config_filename);
1264 ret = 4;
1265 goto out_free;
1269 * lock is committed, so don't try to roll it back below.
1270 * NOTE: Since lockfile.c keeps a linked list of all created
1271 * lock_file structures, it isn't safe to free(lock). It's
1272 * better to just leave it hanging around.
1274 lock = NULL;
1275 ret = 0;
1277 out_free:
1278 if (lock)
1279 rollback_lock_file(lock);
1280 free(config_filename);
1281 return ret;
1283 write_err_out:
1284 ret = write_error(lock->filename);
1285 goto out_free;
1289 static int section_name_match (const char *buf, const char *name)
1291 int i = 0, j = 0, dot = 0;
1292 if (buf[i] != '[')
1293 return 0;
1294 for (i = 1; buf[i] && buf[i] != ']'; i++) {
1295 if (!dot && isspace(buf[i])) {
1296 dot = 1;
1297 if (name[j++] != '.')
1298 break;
1299 for (i++; isspace(buf[i]); i++)
1300 ; /* do nothing */
1301 if (buf[i] != '"')
1302 break;
1303 continue;
1305 if (buf[i] == '\\' && dot)
1306 i++;
1307 else if (buf[i] == '"' && dot) {
1308 for (i++; isspace(buf[i]); i++)
1309 ; /* do_nothing */
1310 break;
1312 if (buf[i] != name[j++])
1313 break;
1315 if (buf[i] == ']' && name[j] == 0) {
1317 * We match, now just find the right length offset by
1318 * gobbling up any whitespace after it, as well
1320 i++;
1321 for (; buf[i] && isspace(buf[i]); i++)
1322 ; /* do nothing */
1323 return i;
1325 return 0;
1328 /* if new_name == NULL, the section is removed instead */
1329 int git_config_rename_section(const char *old_name, const char *new_name)
1331 int ret = 0, remove = 0;
1332 char *config_filename;
1333 struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1334 int out_fd;
1335 char buf[1024];
1337 if (config_exclusive_filename)
1338 config_filename = xstrdup(config_exclusive_filename);
1339 else
1340 config_filename = git_pathdup("config");
1341 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1342 if (out_fd < 0) {
1343 ret = error("could not lock config file %s", config_filename);
1344 goto out;
1347 if (!(config_file = fopen(config_filename, "rb"))) {
1348 /* no config file means nothing to rename, no error */
1349 goto unlock_and_out;
1352 while (fgets(buf, sizeof(buf), config_file)) {
1353 int i;
1354 int length;
1355 char *output = buf;
1356 for (i = 0; buf[i] && isspace(buf[i]); i++)
1357 ; /* do nothing */
1358 if (buf[i] == '[') {
1359 /* it's a section */
1360 int offset = section_name_match(&buf[i], old_name);
1361 if (offset > 0) {
1362 ret++;
1363 if (new_name == NULL) {
1364 remove = 1;
1365 continue;
1367 store.baselen = strlen(new_name);
1368 if (!store_write_section(out_fd, new_name)) {
1369 ret = write_error(lock->filename);
1370 goto out;
1373 * We wrote out the new section, with
1374 * a newline, now skip the old
1375 * section's length
1377 output += offset + i;
1378 if (strlen(output) > 0) {
1380 * More content means there's
1381 * a declaration to put on the
1382 * next line; indent with a
1383 * tab
1385 output -= 1;
1386 output[0] = '\t';
1389 remove = 0;
1391 if (remove)
1392 continue;
1393 length = strlen(output);
1394 if (write_in_full(out_fd, output, length) != length) {
1395 ret = write_error(lock->filename);
1396 goto out;
1399 fclose(config_file);
1400 unlock_and_out:
1401 if (commit_lock_file(lock) < 0)
1402 ret = error("could not commit config file %s", config_filename);
1403 out:
1404 free(config_filename);
1405 return ret;
1409 * Call this to report error for your variable that should not
1410 * get a boolean value (i.e. "[my] var" means "true").
1412 int config_error_nonbool(const char *var)
1414 return error("Missing value for '%s'", var);