fetch: Also fetch submodules in subdirectories in on-demand mode
[git/debian.git] / config.c
blob61de4d6a178ec8c2886331daefead68e762362db
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"
11 #include "quote.h"
13 #define MAXNAME (256)
15 static FILE *config_file;
16 static const char *config_file_name;
17 static int config_linenr;
18 static int config_file_eof;
19 static int zlib_compression_seen;
21 const char *config_exclusive_filename = NULL;
23 static void lowercase(char *p)
25 for (; *p; p++)
26 *p = tolower(*p);
29 void git_config_push_parameter(const char *text)
31 struct strbuf env = STRBUF_INIT;
32 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
33 if (old) {
34 strbuf_addstr(&env, old);
35 strbuf_addch(&env, ' ');
37 sq_quote_buf(&env, text);
38 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
39 strbuf_release(&env);
42 static int git_config_parse_parameter(const char *text,
43 config_fn_t fn, void *data)
45 struct strbuf tmp = STRBUF_INIT;
46 struct strbuf **pair;
47 strbuf_addstr(&tmp, text);
48 pair = strbuf_split(&tmp, '=');
49 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=')
50 strbuf_setlen(pair[0], pair[0]->len - 1);
51 strbuf_trim(pair[0]);
52 if (!pair[0]->len) {
53 strbuf_list_free(pair);
54 return error("bogus config parameter: %s", text);
56 lowercase(pair[0]->buf);
57 if (fn(pair[0]->buf, pair[1] ? pair[1]->buf : NULL, data) < 0) {
58 strbuf_list_free(pair);
59 return -1;
61 strbuf_list_free(pair);
62 return 0;
65 int git_config_from_parameters(config_fn_t fn, void *data)
67 const char *env = getenv(CONFIG_DATA_ENVIRONMENT);
68 char *envw;
69 const char **argv = NULL;
70 int nr = 0, alloc = 0;
71 int i;
73 if (!env)
74 return 0;
75 /* sq_dequote will write over it */
76 envw = xstrdup(env);
78 if (sq_dequote_to_argv(envw, &argv, &nr, &alloc) < 0) {
79 free(envw);
80 return error("bogus format in " CONFIG_DATA_ENVIRONMENT);
83 for (i = 0; i < nr; i++) {
84 if (git_config_parse_parameter(argv[i], fn, data) < 0) {
85 free(argv);
86 free(envw);
87 return -1;
91 free(argv);
92 free(envw);
93 return nr > 0;
96 static int get_next_char(void)
98 int c;
99 FILE *f;
101 c = '\n';
102 if ((f = config_file) != NULL) {
103 c = fgetc(f);
104 if (c == '\r') {
105 /* DOS like systems */
106 c = fgetc(f);
107 if (c != '\n') {
108 ungetc(c, f);
109 c = '\r';
112 if (c == '\n')
113 config_linenr++;
114 if (c == EOF) {
115 config_file_eof = 1;
116 c = '\n';
119 return c;
122 static char *parse_value(void)
124 static char value[1024];
125 int quote = 0, comment = 0, len = 0, space = 0;
127 for (;;) {
128 int c = get_next_char();
129 if (len >= sizeof(value) - 1)
130 return NULL;
131 if (c == '\n') {
132 if (quote)
133 return NULL;
134 value[len] = 0;
135 return value;
137 if (comment)
138 continue;
139 if (isspace(c) && !quote) {
140 if (len)
141 space++;
142 continue;
144 if (!quote) {
145 if (c == ';' || c == '#') {
146 comment = 1;
147 continue;
150 for (; space; space--)
151 value[len++] = ' ';
152 if (c == '\\') {
153 c = get_next_char();
154 switch (c) {
155 case '\n':
156 continue;
157 case 't':
158 c = '\t';
159 break;
160 case 'b':
161 c = '\b';
162 break;
163 case 'n':
164 c = '\n';
165 break;
166 /* Some characters escape as themselves */
167 case '\\': case '"':
168 break;
169 /* Reject unknown escape sequences */
170 default:
171 return NULL;
173 value[len++] = c;
174 continue;
176 if (c == '"') {
177 quote = 1-quote;
178 continue;
180 value[len++] = c;
184 static inline int iskeychar(int c)
186 return isalnum(c) || c == '-';
189 static int get_value(config_fn_t fn, void *data, char *name, unsigned int len)
191 int c;
192 char *value;
194 /* Get the full name */
195 for (;;) {
196 c = get_next_char();
197 if (config_file_eof)
198 break;
199 if (!iskeychar(c))
200 break;
201 name[len++] = tolower(c);
202 if (len >= MAXNAME)
203 return -1;
205 name[len] = 0;
206 while (c == ' ' || c == '\t')
207 c = get_next_char();
209 value = NULL;
210 if (c != '\n') {
211 if (c != '=')
212 return -1;
213 value = parse_value();
214 if (!value)
215 return -1;
217 return fn(name, value, data);
220 static int get_extended_base_var(char *name, int baselen, int c)
222 do {
223 if (c == '\n')
224 return -1;
225 c = get_next_char();
226 } while (isspace(c));
228 /* We require the format to be '[base "extension"]' */
229 if (c != '"')
230 return -1;
231 name[baselen++] = '.';
233 for (;;) {
234 int c = get_next_char();
235 if (c == '\n')
236 return -1;
237 if (c == '"')
238 break;
239 if (c == '\\') {
240 c = get_next_char();
241 if (c == '\n')
242 return -1;
244 name[baselen++] = c;
245 if (baselen > MAXNAME / 2)
246 return -1;
249 /* Final ']' */
250 if (get_next_char() != ']')
251 return -1;
252 return baselen;
255 static int get_base_var(char *name)
257 int baselen = 0;
259 for (;;) {
260 int c = get_next_char();
261 if (config_file_eof)
262 return -1;
263 if (c == ']')
264 return baselen;
265 if (isspace(c))
266 return get_extended_base_var(name, baselen, c);
267 if (!iskeychar(c) && c != '.')
268 return -1;
269 if (baselen > MAXNAME / 2)
270 return -1;
271 name[baselen++] = tolower(c);
275 static int git_parse_file(config_fn_t fn, void *data)
277 int comment = 0;
278 int baselen = 0;
279 static char var[MAXNAME];
281 /* U+FEFF Byte Order Mark in UTF8 */
282 static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
283 const unsigned char *bomptr = utf8_bom;
285 for (;;) {
286 int c = get_next_char();
287 if (bomptr && *bomptr) {
288 /* We are at the file beginning; skip UTF8-encoded BOM
289 * if present. Sane editors won't put this in on their
290 * own, but e.g. Windows Notepad will do it happily. */
291 if ((unsigned char) c == *bomptr) {
292 bomptr++;
293 continue;
294 } else {
295 /* Do not tolerate partial BOM. */
296 if (bomptr != utf8_bom)
297 break;
298 /* No BOM at file beginning. Cool. */
299 bomptr = NULL;
302 if (c == '\n') {
303 if (config_file_eof)
304 return 0;
305 comment = 0;
306 continue;
308 if (comment || isspace(c))
309 continue;
310 if (c == '#' || c == ';') {
311 comment = 1;
312 continue;
314 if (c == '[') {
315 baselen = get_base_var(var);
316 if (baselen <= 0)
317 break;
318 var[baselen++] = '.';
319 var[baselen] = 0;
320 continue;
322 if (!isalpha(c))
323 break;
324 var[baselen] = tolower(c);
325 if (get_value(fn, data, var, baselen+1) < 0)
326 break;
328 die("bad config file line %d in %s", config_linenr, config_file_name);
331 static int parse_unit_factor(const char *end, unsigned long *val)
333 if (!*end)
334 return 1;
335 else if (!strcasecmp(end, "k")) {
336 *val *= 1024;
337 return 1;
339 else if (!strcasecmp(end, "m")) {
340 *val *= 1024 * 1024;
341 return 1;
343 else if (!strcasecmp(end, "g")) {
344 *val *= 1024 * 1024 * 1024;
345 return 1;
347 return 0;
350 static int git_parse_long(const char *value, long *ret)
352 if (value && *value) {
353 char *end;
354 long val = strtol(value, &end, 0);
355 unsigned long factor = 1;
356 if (!parse_unit_factor(end, &factor))
357 return 0;
358 *ret = val * factor;
359 return 1;
361 return 0;
364 int git_parse_ulong(const char *value, unsigned long *ret)
366 if (value && *value) {
367 char *end;
368 unsigned long val = strtoul(value, &end, 0);
369 if (!parse_unit_factor(end, &val))
370 return 0;
371 *ret = val;
372 return 1;
374 return 0;
377 static void die_bad_config(const char *name)
379 if (config_file_name)
380 die("bad config value for '%s' in %s", name, config_file_name);
381 die("bad config value for '%s'", name);
384 int git_config_int(const char *name, const char *value)
386 long ret = 0;
387 if (!git_parse_long(value, &ret))
388 die_bad_config(name);
389 return ret;
392 unsigned long git_config_ulong(const char *name, const char *value)
394 unsigned long ret;
395 if (!git_parse_ulong(value, &ret))
396 die_bad_config(name);
397 return ret;
400 static int git_config_maybe_bool_text(const char *name, const char *value)
402 if (!value)
403 return 1;
404 if (!*value)
405 return 0;
406 if (!strcasecmp(value, "true")
407 || !strcasecmp(value, "yes")
408 || !strcasecmp(value, "on"))
409 return 1;
410 if (!strcasecmp(value, "false")
411 || !strcasecmp(value, "no")
412 || !strcasecmp(value, "off"))
413 return 0;
414 return -1;
417 int git_config_maybe_bool(const char *name, const char *value)
419 long v = git_config_maybe_bool_text(name, value);
420 if (0 <= v)
421 return v;
422 if (git_parse_long(value, &v))
423 return !!v;
424 return -1;
427 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
429 int v = git_config_maybe_bool_text(name, value);
430 if (0 <= v) {
431 *is_bool = 1;
432 return v;
434 *is_bool = 0;
435 return git_config_int(name, value);
438 int git_config_bool(const char *name, const char *value)
440 int discard;
441 return !!git_config_bool_or_int(name, value, &discard);
444 int git_config_string(const char **dest, const char *var, const char *value)
446 if (!value)
447 return config_error_nonbool(var);
448 *dest = xstrdup(value);
449 return 0;
452 int git_config_pathname(const char **dest, const char *var, const char *value)
454 if (!value)
455 return config_error_nonbool(var);
456 *dest = expand_user_path(value);
457 if (!*dest)
458 die("Failed to expand user dir in: '%s'", value);
459 return 0;
462 static int git_default_core_config(const char *var, const char *value)
464 /* This needs a better name */
465 if (!strcmp(var, "core.filemode")) {
466 trust_executable_bit = git_config_bool(var, value);
467 return 0;
469 if (!strcmp(var, "core.trustctime")) {
470 trust_ctime = git_config_bool(var, value);
471 return 0;
474 if (!strcmp(var, "core.quotepath")) {
475 quote_path_fully = git_config_bool(var, value);
476 return 0;
479 if (!strcmp(var, "core.symlinks")) {
480 has_symlinks = git_config_bool(var, value);
481 return 0;
484 if (!strcmp(var, "core.ignorecase")) {
485 ignore_case = git_config_bool(var, value);
486 return 0;
489 if (!strcmp(var, "core.bare")) {
490 is_bare_repository_cfg = git_config_bool(var, value);
491 return 0;
494 if (!strcmp(var, "core.ignorestat")) {
495 assume_unchanged = git_config_bool(var, value);
496 return 0;
499 if (!strcmp(var, "core.prefersymlinkrefs")) {
500 prefer_symlink_refs = git_config_bool(var, value);
501 return 0;
504 if (!strcmp(var, "core.logallrefupdates")) {
505 log_all_ref_updates = git_config_bool(var, value);
506 return 0;
509 if (!strcmp(var, "core.warnambiguousrefs")) {
510 warn_ambiguous_refs = git_config_bool(var, value);
511 return 0;
514 if (!strcmp(var, "core.abbrev")) {
515 int abbrev = git_config_int(var, value);
516 if (abbrev < minimum_abbrev || abbrev > 40)
517 return -1;
518 default_abbrev = abbrev;
519 return 0;
522 if (!strcmp(var, "core.loosecompression")) {
523 int level = git_config_int(var, value);
524 if (level == -1)
525 level = Z_DEFAULT_COMPRESSION;
526 else if (level < 0 || level > Z_BEST_COMPRESSION)
527 die("bad zlib compression level %d", level);
528 zlib_compression_level = level;
529 zlib_compression_seen = 1;
530 return 0;
533 if (!strcmp(var, "core.compression")) {
534 int level = git_config_int(var, value);
535 if (level == -1)
536 level = Z_DEFAULT_COMPRESSION;
537 else if (level < 0 || level > Z_BEST_COMPRESSION)
538 die("bad zlib compression level %d", level);
539 core_compression_level = level;
540 core_compression_seen = 1;
541 if (!zlib_compression_seen)
542 zlib_compression_level = level;
543 return 0;
546 if (!strcmp(var, "core.packedgitwindowsize")) {
547 int pgsz_x2 = getpagesize() * 2;
548 packed_git_window_size = git_config_int(var, value);
550 /* This value must be multiple of (pagesize * 2) */
551 packed_git_window_size /= pgsz_x2;
552 if (packed_git_window_size < 1)
553 packed_git_window_size = 1;
554 packed_git_window_size *= pgsz_x2;
555 return 0;
558 if (!strcmp(var, "core.bigfilethreshold")) {
559 long n = git_config_int(var, value);
560 big_file_threshold = 0 < n ? n : 0;
561 return 0;
564 if (!strcmp(var, "core.packedgitlimit")) {
565 packed_git_limit = git_config_int(var, value);
566 return 0;
569 if (!strcmp(var, "core.deltabasecachelimit")) {
570 delta_base_cache_limit = git_config_int(var, value);
571 return 0;
574 if (!strcmp(var, "core.autocrlf")) {
575 if (value && !strcasecmp(value, "input")) {
576 if (eol == EOL_CRLF)
577 return error("core.autocrlf=input conflicts with core.eol=crlf");
578 auto_crlf = AUTO_CRLF_INPUT;
579 return 0;
581 auto_crlf = git_config_bool(var, value);
582 return 0;
585 if (!strcmp(var, "core.safecrlf")) {
586 if (value && !strcasecmp(value, "warn")) {
587 safe_crlf = SAFE_CRLF_WARN;
588 return 0;
590 safe_crlf = git_config_bool(var, value);
591 return 0;
594 if (!strcmp(var, "core.eol")) {
595 if (value && !strcasecmp(value, "lf"))
596 eol = EOL_LF;
597 else if (value && !strcasecmp(value, "crlf"))
598 eol = EOL_CRLF;
599 else if (value && !strcasecmp(value, "native"))
600 eol = EOL_NATIVE;
601 else
602 eol = EOL_UNSET;
603 if (eol == EOL_CRLF && auto_crlf == AUTO_CRLF_INPUT)
604 return error("core.autocrlf=input conflicts with core.eol=crlf");
605 return 0;
608 if (!strcmp(var, "core.notesref")) {
609 notes_ref_name = xstrdup(value);
610 return 0;
613 if (!strcmp(var, "core.pager"))
614 return git_config_string(&pager_program, var, value);
616 if (!strcmp(var, "core.editor"))
617 return git_config_string(&editor_program, var, value);
619 if (!strcmp(var, "core.askpass"))
620 return git_config_string(&askpass_program, var, value);
622 if (!strcmp(var, "core.excludesfile"))
623 return git_config_pathname(&excludes_file, var, value);
625 if (!strcmp(var, "core.whitespace")) {
626 if (!value)
627 return config_error_nonbool(var);
628 whitespace_rule_cfg = parse_whitespace_rule(value);
629 return 0;
632 if (!strcmp(var, "core.fsyncobjectfiles")) {
633 fsync_object_files = git_config_bool(var, value);
634 return 0;
637 if (!strcmp(var, "core.preloadindex")) {
638 core_preload_index = git_config_bool(var, value);
639 return 0;
642 if (!strcmp(var, "core.createobject")) {
643 if (!strcmp(value, "rename"))
644 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
645 else if (!strcmp(value, "link"))
646 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
647 else
648 die("Invalid mode for object creation: %s", value);
649 return 0;
652 if (!strcmp(var, "core.sparsecheckout")) {
653 core_apply_sparse_checkout = git_config_bool(var, value);
654 return 0;
657 /* Add other config variables here and to Documentation/config.txt. */
658 return 0;
661 static int git_default_user_config(const char *var, const char *value)
663 if (!strcmp(var, "user.name")) {
664 if (!value)
665 return config_error_nonbool(var);
666 strlcpy(git_default_name, value, sizeof(git_default_name));
667 user_ident_explicitly_given |= IDENT_NAME_GIVEN;
668 return 0;
671 if (!strcmp(var, "user.email")) {
672 if (!value)
673 return config_error_nonbool(var);
674 strlcpy(git_default_email, value, sizeof(git_default_email));
675 user_ident_explicitly_given |= IDENT_MAIL_GIVEN;
676 return 0;
679 /* Add other config variables here and to Documentation/config.txt. */
680 return 0;
683 static int git_default_i18n_config(const char *var, const char *value)
685 if (!strcmp(var, "i18n.commitencoding"))
686 return git_config_string(&git_commit_encoding, var, value);
688 if (!strcmp(var, "i18n.logoutputencoding"))
689 return git_config_string(&git_log_output_encoding, var, value);
691 /* Add other config variables here and to Documentation/config.txt. */
692 return 0;
695 static int git_default_branch_config(const char *var, const char *value)
697 if (!strcmp(var, "branch.autosetupmerge")) {
698 if (value && !strcasecmp(value, "always")) {
699 git_branch_track = BRANCH_TRACK_ALWAYS;
700 return 0;
702 git_branch_track = git_config_bool(var, value);
703 return 0;
705 if (!strcmp(var, "branch.autosetuprebase")) {
706 if (!value)
707 return config_error_nonbool(var);
708 else if (!strcmp(value, "never"))
709 autorebase = AUTOREBASE_NEVER;
710 else if (!strcmp(value, "local"))
711 autorebase = AUTOREBASE_LOCAL;
712 else if (!strcmp(value, "remote"))
713 autorebase = AUTOREBASE_REMOTE;
714 else if (!strcmp(value, "always"))
715 autorebase = AUTOREBASE_ALWAYS;
716 else
717 return error("Malformed value for %s", var);
718 return 0;
721 /* Add other config variables here and to Documentation/config.txt. */
722 return 0;
725 static int git_default_push_config(const char *var, const char *value)
727 if (!strcmp(var, "push.default")) {
728 if (!value)
729 return config_error_nonbool(var);
730 else if (!strcmp(value, "nothing"))
731 push_default = PUSH_DEFAULT_NOTHING;
732 else if (!strcmp(value, "matching"))
733 push_default = PUSH_DEFAULT_MATCHING;
734 else if (!strcmp(value, "upstream"))
735 push_default = PUSH_DEFAULT_UPSTREAM;
736 else if (!strcmp(value, "tracking")) /* deprecated */
737 push_default = PUSH_DEFAULT_UPSTREAM;
738 else if (!strcmp(value, "current"))
739 push_default = PUSH_DEFAULT_CURRENT;
740 else {
741 error("Malformed value for %s: %s", var, value);
742 return error("Must be one of nothing, matching, "
743 "tracking or current.");
745 return 0;
748 /* Add other config variables here and to Documentation/config.txt. */
749 return 0;
752 static int git_default_mailmap_config(const char *var, const char *value)
754 if (!strcmp(var, "mailmap.file"))
755 return git_config_string(&git_mailmap_file, var, value);
757 /* Add other config variables here and to Documentation/config.txt. */
758 return 0;
761 int git_default_config(const char *var, const char *value, void *dummy)
763 if (!prefixcmp(var, "core."))
764 return git_default_core_config(var, value);
766 if (!prefixcmp(var, "user."))
767 return git_default_user_config(var, value);
769 if (!prefixcmp(var, "i18n."))
770 return git_default_i18n_config(var, value);
772 if (!prefixcmp(var, "branch."))
773 return git_default_branch_config(var, value);
775 if (!prefixcmp(var, "push."))
776 return git_default_push_config(var, value);
778 if (!prefixcmp(var, "mailmap."))
779 return git_default_mailmap_config(var, value);
781 if (!prefixcmp(var, "advice."))
782 return git_default_advice_config(var, value);
784 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
785 pager_use_color = git_config_bool(var,value);
786 return 0;
789 /* Add other config variables here and to Documentation/config.txt. */
790 return 0;
793 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
795 int ret;
796 FILE *f = fopen(filename, "r");
798 ret = -1;
799 if (f) {
800 config_file = f;
801 config_file_name = filename;
802 config_linenr = 1;
803 config_file_eof = 0;
804 ret = git_parse_file(fn, data);
805 fclose(f);
806 config_file_name = NULL;
808 return ret;
811 const char *git_etc_gitconfig(void)
813 static const char *system_wide;
814 if (!system_wide)
815 system_wide = system_path(ETC_GITCONFIG);
816 return system_wide;
819 int git_env_bool(const char *k, int def)
821 const char *v = getenv(k);
822 return v ? git_config_bool(k, v) : def;
825 int git_config_system(void)
827 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
830 int git_config_early(config_fn_t fn, void *data, const char *repo_config)
832 int ret = 0, found = 0;
833 const char *home = NULL;
835 /* Setting $GIT_CONFIG makes git read _only_ the given config file. */
836 if (config_exclusive_filename)
837 return git_config_from_file(fn, config_exclusive_filename, data);
838 if (git_config_system() && !access(git_etc_gitconfig(), R_OK)) {
839 ret += git_config_from_file(fn, git_etc_gitconfig(),
840 data);
841 found += 1;
844 home = getenv("HOME");
845 if (home) {
846 char *user_config = xstrdup(mkpath("%s/.gitconfig", home));
847 if (!access(user_config, R_OK)) {
848 ret += git_config_from_file(fn, user_config, data);
849 found += 1;
851 free(user_config);
854 if (repo_config && !access(repo_config, R_OK)) {
855 ret += git_config_from_file(fn, repo_config, data);
856 found += 1;
859 switch (git_config_from_parameters(fn, data)) {
860 case -1: /* error */
861 ret--;
862 break;
863 case 0: /* found nothing */
864 break;
865 default: /* found at least one item */
866 found++;
867 break;
870 return ret == 0 ? found : ret;
873 int git_config(config_fn_t fn, void *data)
875 char *repo_config = NULL;
876 int ret;
878 repo_config = git_pathdup("config");
879 ret = git_config_early(fn, data, repo_config);
880 if (repo_config)
881 free(repo_config);
882 return ret;
886 * Find all the stuff for git_config_set() below.
889 #define MAX_MATCHES 512
891 static struct {
892 int baselen;
893 char *key;
894 int do_not_match;
895 regex_t *value_regex;
896 int multi_replace;
897 size_t offset[MAX_MATCHES];
898 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
899 int seen;
900 } store;
902 static int matches(const char *key, const char *value)
904 return !strcmp(key, store.key) &&
905 (store.value_regex == NULL ||
906 (store.do_not_match ^
907 !regexec(store.value_regex, value, 0, NULL, 0)));
910 static int store_aux(const char *key, const char *value, void *cb)
912 const char *ep;
913 size_t section_len;
915 switch (store.state) {
916 case KEY_SEEN:
917 if (matches(key, value)) {
918 if (store.seen == 1 && store.multi_replace == 0) {
919 warning("%s has multiple values", key);
920 } else if (store.seen >= MAX_MATCHES) {
921 error("too many matches for %s", key);
922 return 1;
925 store.offset[store.seen] = ftell(config_file);
926 store.seen++;
928 break;
929 case SECTION_SEEN:
931 * What we are looking for is in store.key (both
932 * section and var), and its section part is baselen
933 * long. We found key (again, both section and var).
934 * We would want to know if this key is in the same
935 * section as what we are looking for. We already
936 * know we are in the same section as what should
937 * hold store.key.
939 ep = strrchr(key, '.');
940 section_len = ep - key;
942 if ((section_len != store.baselen) ||
943 memcmp(key, store.key, section_len+1)) {
944 store.state = SECTION_END_SEEN;
945 break;
949 * Do not increment matches: this is no match, but we
950 * just made sure we are in the desired section.
952 store.offset[store.seen] = ftell(config_file);
953 /* fallthru */
954 case SECTION_END_SEEN:
955 case START:
956 if (matches(key, value)) {
957 store.offset[store.seen] = ftell(config_file);
958 store.state = KEY_SEEN;
959 store.seen++;
960 } else {
961 if (strrchr(key, '.') - key == store.baselen &&
962 !strncmp(key, store.key, store.baselen)) {
963 store.state = SECTION_SEEN;
964 store.offset[store.seen] = ftell(config_file);
968 return 0;
971 static int write_error(const char *filename)
973 error("failed to write new configuration file %s", filename);
975 /* Same error code as "failed to rename". */
976 return 4;
979 static int store_write_section(int fd, const char *key)
981 const char *dot;
982 int i, success;
983 struct strbuf sb = STRBUF_INIT;
985 dot = memchr(key, '.', store.baselen);
986 if (dot) {
987 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
988 for (i = dot - key + 1; i < store.baselen; i++) {
989 if (key[i] == '"' || key[i] == '\\')
990 strbuf_addch(&sb, '\\');
991 strbuf_addch(&sb, key[i]);
993 strbuf_addstr(&sb, "\"]\n");
994 } else {
995 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
998 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
999 strbuf_release(&sb);
1001 return success;
1004 static int store_write_pair(int fd, const char *key, const char *value)
1006 int i, success;
1007 int length = strlen(key + store.baselen + 1);
1008 const char *quote = "";
1009 struct strbuf sb = STRBUF_INIT;
1012 * Check to see if the value needs to be surrounded with a dq pair.
1013 * Note that problematic characters are always backslash-quoted; this
1014 * check is about not losing leading or trailing SP and strings that
1015 * follow beginning-of-comment characters (i.e. ';' and '#') by the
1016 * configuration parser.
1018 if (value[0] == ' ')
1019 quote = "\"";
1020 for (i = 0; value[i]; i++)
1021 if (value[i] == ';' || value[i] == '#')
1022 quote = "\"";
1023 if (i && value[i - 1] == ' ')
1024 quote = "\"";
1026 strbuf_addf(&sb, "\t%.*s = %s",
1027 length, key + store.baselen + 1, quote);
1029 for (i = 0; value[i]; i++)
1030 switch (value[i]) {
1031 case '\n':
1032 strbuf_addstr(&sb, "\\n");
1033 break;
1034 case '\t':
1035 strbuf_addstr(&sb, "\\t");
1036 break;
1037 case '"':
1038 case '\\':
1039 strbuf_addch(&sb, '\\');
1040 default:
1041 strbuf_addch(&sb, value[i]);
1042 break;
1044 strbuf_addf(&sb, "%s\n", quote);
1046 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1047 strbuf_release(&sb);
1049 return success;
1052 static ssize_t find_beginning_of_line(const char *contents, size_t size,
1053 size_t offset_, int *found_bracket)
1055 size_t equal_offset = size, bracket_offset = size;
1056 ssize_t offset;
1058 contline:
1059 for (offset = offset_-2; offset > 0
1060 && contents[offset] != '\n'; offset--)
1061 switch (contents[offset]) {
1062 case '=': equal_offset = offset; break;
1063 case ']': bracket_offset = offset; break;
1065 if (offset > 0 && contents[offset-1] == '\\') {
1066 offset_ = offset;
1067 goto contline;
1069 if (bracket_offset < equal_offset) {
1070 *found_bracket = 1;
1071 offset = bracket_offset+1;
1072 } else
1073 offset++;
1075 return offset;
1078 int git_config_set(const char *key, const char *value)
1080 return git_config_set_multivar(key, value, NULL, 0);
1084 * Auxiliary function to sanity-check and split the key into the section
1085 * identifier and variable name.
1087 * Returns 0 on success, -1 when there is an invalid character in the key and
1088 * -2 if there is no section name in the key.
1090 * store_key - pointer to char* which will hold a copy of the key with
1091 * lowercase section and variable name
1092 * baselen - pointer to int which will hold the length of the
1093 * section + subsection part, can be NULL
1095 int git_config_parse_key(const char *key, char **store_key, int *baselen_)
1097 int i, dot, baselen;
1098 const char *last_dot = strrchr(key, '.');
1101 * Since "key" actually contains the section name and the real
1102 * key name separated by a dot, we have to know where the dot is.
1105 if (last_dot == NULL || last_dot == key) {
1106 error("key does not contain a section: %s", key);
1107 return -2;
1110 if (!last_dot[1]) {
1111 error("key does not contain variable name: %s", key);
1112 return -2;
1115 baselen = last_dot - key;
1116 if (baselen_)
1117 *baselen_ = baselen;
1120 * Validate the key and while at it, lower case it for matching.
1122 *store_key = xmalloc(strlen(key) + 1);
1124 dot = 0;
1125 for (i = 0; key[i]; i++) {
1126 unsigned char c = key[i];
1127 if (c == '.')
1128 dot = 1;
1129 /* Leave the extended basename untouched.. */
1130 if (!dot || i > baselen) {
1131 if (!iskeychar(c) ||
1132 (i == baselen + 1 && !isalpha(c))) {
1133 error("invalid key: %s", key);
1134 goto out_free_ret_1;
1136 c = tolower(c);
1137 } else if (c == '\n') {
1138 error("invalid key (newline): %s", key);
1139 goto out_free_ret_1;
1141 (*store_key)[i] = c;
1143 (*store_key)[i] = 0;
1145 return 0;
1147 out_free_ret_1:
1148 free(*store_key);
1149 return -1;
1153 * If value==NULL, unset in (remove from) config,
1154 * if value_regex!=NULL, disregard key/value pairs where value does not match.
1155 * if multi_replace==0, nothing, or only one matching key/value is replaced,
1156 * else all matching key/values (regardless how many) are removed,
1157 * before the new pair is written.
1159 * Returns 0 on success.
1161 * This function does this:
1163 * - it locks the config file by creating ".git/config.lock"
1165 * - it then parses the config using store_aux() as validator to find
1166 * the position on the key/value pair to replace. If it is to be unset,
1167 * it must be found exactly once.
1169 * - the config file is mmap()ed and the part before the match (if any) is
1170 * written to the lock file, then the changed part and the rest.
1172 * - the config file is removed and the lock file rename()d to it.
1175 int git_config_set_multivar(const char *key, const char *value,
1176 const char *value_regex, int multi_replace)
1178 int fd = -1, in_fd;
1179 int ret;
1180 char *config_filename;
1181 struct lock_file *lock = NULL;
1183 if (config_exclusive_filename)
1184 config_filename = xstrdup(config_exclusive_filename);
1185 else
1186 config_filename = git_pathdup("config");
1188 /* parse-key returns negative; flip the sign to feed exit(3) */
1189 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
1190 if (ret)
1191 goto out_free;
1193 store.multi_replace = multi_replace;
1197 * The lock serves a purpose in addition to locking: the new
1198 * contents of .git/config will be written into it.
1200 lock = xcalloc(sizeof(struct lock_file), 1);
1201 fd = hold_lock_file_for_update(lock, config_filename, 0);
1202 if (fd < 0) {
1203 error("could not lock config file %s: %s", config_filename, strerror(errno));
1204 free(store.key);
1205 ret = -1;
1206 goto out_free;
1210 * If .git/config does not exist yet, write a minimal version.
1212 in_fd = open(config_filename, O_RDONLY);
1213 if ( in_fd < 0 ) {
1214 free(store.key);
1216 if ( ENOENT != errno ) {
1217 error("opening %s: %s", config_filename,
1218 strerror(errno));
1219 ret = 3; /* same as "invalid config file" */
1220 goto out_free;
1222 /* if nothing to unset, error out */
1223 if (value == NULL) {
1224 ret = 5;
1225 goto out_free;
1228 store.key = (char *)key;
1229 if (!store_write_section(fd, key) ||
1230 !store_write_pair(fd, key, value))
1231 goto write_err_out;
1232 } else {
1233 struct stat st;
1234 char *contents;
1235 size_t contents_sz, copy_begin, copy_end;
1236 int i, new_line = 0;
1238 if (value_regex == NULL)
1239 store.value_regex = NULL;
1240 else {
1241 if (value_regex[0] == '!') {
1242 store.do_not_match = 1;
1243 value_regex++;
1244 } else
1245 store.do_not_match = 0;
1247 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1248 if (regcomp(store.value_regex, value_regex,
1249 REG_EXTENDED)) {
1250 error("invalid pattern: %s", value_regex);
1251 free(store.value_regex);
1252 ret = 6;
1253 goto out_free;
1257 store.offset[0] = 0;
1258 store.state = START;
1259 store.seen = 0;
1262 * After this, store.offset will contain the *end* offset
1263 * of the last match, or remain at 0 if no match was found.
1264 * As a side effect, we make sure to transform only a valid
1265 * existing config file.
1267 if (git_config_from_file(store_aux, config_filename, NULL)) {
1268 error("invalid config file %s", config_filename);
1269 free(store.key);
1270 if (store.value_regex != NULL) {
1271 regfree(store.value_regex);
1272 free(store.value_regex);
1274 ret = 3;
1275 goto out_free;
1278 free(store.key);
1279 if (store.value_regex != NULL) {
1280 regfree(store.value_regex);
1281 free(store.value_regex);
1284 /* if nothing to unset, or too many matches, error out */
1285 if ((store.seen == 0 && value == NULL) ||
1286 (store.seen > 1 && multi_replace == 0)) {
1287 ret = 5;
1288 goto out_free;
1291 fstat(in_fd, &st);
1292 contents_sz = xsize_t(st.st_size);
1293 contents = xmmap(NULL, contents_sz, PROT_READ,
1294 MAP_PRIVATE, in_fd, 0);
1295 close(in_fd);
1297 if (store.seen == 0)
1298 store.seen = 1;
1300 for (i = 0, copy_begin = 0; i < store.seen; i++) {
1301 if (store.offset[i] == 0) {
1302 store.offset[i] = copy_end = contents_sz;
1303 } else if (store.state != KEY_SEEN) {
1304 copy_end = store.offset[i];
1305 } else
1306 copy_end = find_beginning_of_line(
1307 contents, contents_sz,
1308 store.offset[i]-2, &new_line);
1310 if (copy_end > 0 && contents[copy_end-1] != '\n')
1311 new_line = 1;
1313 /* write the first part of the config */
1314 if (copy_end > copy_begin) {
1315 if (write_in_full(fd, contents + copy_begin,
1316 copy_end - copy_begin) <
1317 copy_end - copy_begin)
1318 goto write_err_out;
1319 if (new_line &&
1320 write_str_in_full(fd, "\n") != 1)
1321 goto write_err_out;
1323 copy_begin = store.offset[i];
1326 /* write the pair (value == NULL means unset) */
1327 if (value != NULL) {
1328 if (store.state == START) {
1329 if (!store_write_section(fd, key))
1330 goto write_err_out;
1332 if (!store_write_pair(fd, key, value))
1333 goto write_err_out;
1336 /* write the rest of the config */
1337 if (copy_begin < contents_sz)
1338 if (write_in_full(fd, contents + copy_begin,
1339 contents_sz - copy_begin) <
1340 contents_sz - copy_begin)
1341 goto write_err_out;
1343 munmap(contents, contents_sz);
1346 if (commit_lock_file(lock) < 0) {
1347 error("could not commit config file %s", config_filename);
1348 ret = 4;
1349 goto out_free;
1353 * lock is committed, so don't try to roll it back below.
1354 * NOTE: Since lockfile.c keeps a linked list of all created
1355 * lock_file structures, it isn't safe to free(lock). It's
1356 * better to just leave it hanging around.
1358 lock = NULL;
1359 ret = 0;
1361 out_free:
1362 if (lock)
1363 rollback_lock_file(lock);
1364 free(config_filename);
1365 return ret;
1367 write_err_out:
1368 ret = write_error(lock->filename);
1369 goto out_free;
1373 static int section_name_match (const char *buf, const char *name)
1375 int i = 0, j = 0, dot = 0;
1376 if (buf[i] != '[')
1377 return 0;
1378 for (i = 1; buf[i] && buf[i] != ']'; i++) {
1379 if (!dot && isspace(buf[i])) {
1380 dot = 1;
1381 if (name[j++] != '.')
1382 break;
1383 for (i++; isspace(buf[i]); i++)
1384 ; /* do nothing */
1385 if (buf[i] != '"')
1386 break;
1387 continue;
1389 if (buf[i] == '\\' && dot)
1390 i++;
1391 else if (buf[i] == '"' && dot) {
1392 for (i++; isspace(buf[i]); i++)
1393 ; /* do_nothing */
1394 break;
1396 if (buf[i] != name[j++])
1397 break;
1399 if (buf[i] == ']' && name[j] == 0) {
1401 * We match, now just find the right length offset by
1402 * gobbling up any whitespace after it, as well
1404 i++;
1405 for (; buf[i] && isspace(buf[i]); i++)
1406 ; /* do nothing */
1407 return i;
1409 return 0;
1412 /* if new_name == NULL, the section is removed instead */
1413 int git_config_rename_section(const char *old_name, const char *new_name)
1415 int ret = 0, remove = 0;
1416 char *config_filename;
1417 struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1418 int out_fd;
1419 char buf[1024];
1421 if (config_exclusive_filename)
1422 config_filename = xstrdup(config_exclusive_filename);
1423 else
1424 config_filename = git_pathdup("config");
1425 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1426 if (out_fd < 0) {
1427 ret = error("could not lock config file %s", config_filename);
1428 goto out;
1431 if (!(config_file = fopen(config_filename, "rb"))) {
1432 /* no config file means nothing to rename, no error */
1433 goto unlock_and_out;
1436 while (fgets(buf, sizeof(buf), config_file)) {
1437 int i;
1438 int length;
1439 char *output = buf;
1440 for (i = 0; buf[i] && isspace(buf[i]); i++)
1441 ; /* do nothing */
1442 if (buf[i] == '[') {
1443 /* it's a section */
1444 int offset = section_name_match(&buf[i], old_name);
1445 if (offset > 0) {
1446 ret++;
1447 if (new_name == NULL) {
1448 remove = 1;
1449 continue;
1451 store.baselen = strlen(new_name);
1452 if (!store_write_section(out_fd, new_name)) {
1453 ret = write_error(lock->filename);
1454 goto out;
1457 * We wrote out the new section, with
1458 * a newline, now skip the old
1459 * section's length
1461 output += offset + i;
1462 if (strlen(output) > 0) {
1464 * More content means there's
1465 * a declaration to put on the
1466 * next line; indent with a
1467 * tab
1469 output -= 1;
1470 output[0] = '\t';
1473 remove = 0;
1475 if (remove)
1476 continue;
1477 length = strlen(output);
1478 if (write_in_full(out_fd, output, length) != length) {
1479 ret = write_error(lock->filename);
1480 goto out;
1483 fclose(config_file);
1484 unlock_and_out:
1485 if (commit_lock_file(lock) < 0)
1486 ret = error("could not commit config file %s", config_filename);
1487 out:
1488 free(config_filename);
1489 return ret;
1493 * Call this to report error for your variable that should not
1494 * get a boolean value (i.e. "[my] var" means "true").
1496 int config_error_nonbool(const char *var)
1498 return error("Missing value for '%s'", var);