handle_path_include: don't look at NULL value
[git.git] / config.c
blob47ce8d8b8eadb965f33044a1d19cb17e1c2875cb
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 typedef struct config_file {
16 struct config_file *prev;
17 FILE *f;
18 const char *name;
19 int linenr;
20 int eof;
21 struct strbuf value;
22 char var[MAXNAME];
23 } config_file;
25 static config_file *cf;
27 static int zlib_compression_seen;
29 #define MAX_INCLUDE_DEPTH 10
30 static const char include_depth_advice[] =
31 "exceeded maximum include depth (%d) while including\n"
32 " %s\n"
33 "from\n"
34 " %s\n"
35 "Do you have circular includes?";
36 static int handle_path_include(const char *path, struct config_include_data *inc)
38 int ret = 0;
39 struct strbuf buf = STRBUF_INIT;
40 char *expanded;
42 if (!path)
43 return config_error_nonbool("include.path");
45 expanded = expand_user_path(path);
46 if (!expanded)
47 return error("Could not expand include path '%s'", path);
48 path = expanded;
51 * Use an absolute path as-is, but interpret relative paths
52 * based on the including config file.
54 if (!is_absolute_path(path)) {
55 char *slash;
57 if (!cf || !cf->name)
58 return error("relative config includes must come from files");
60 slash = find_last_dir_sep(cf->name);
61 if (slash)
62 strbuf_add(&buf, cf->name, slash - cf->name + 1);
63 strbuf_addstr(&buf, path);
64 path = buf.buf;
67 if (!access(path, R_OK)) {
68 if (++inc->depth > MAX_INCLUDE_DEPTH)
69 die(include_depth_advice, MAX_INCLUDE_DEPTH, path,
70 cf && cf->name ? cf->name : "the command line");
71 ret = git_config_from_file(git_config_include, path, inc);
72 inc->depth--;
74 strbuf_release(&buf);
75 free(expanded);
76 return ret;
79 int git_config_include(const char *var, const char *value, void *data)
81 struct config_include_data *inc = data;
82 const char *type;
83 int ret;
86 * Pass along all values, including "include" directives; this makes it
87 * possible to query information on the includes themselves.
89 ret = inc->fn(var, value, inc->data);
90 if (ret < 0)
91 return ret;
93 type = skip_prefix(var, "include.");
94 if (!type)
95 return ret;
97 if (!strcmp(type, "path"))
98 ret = handle_path_include(value, inc);
99 return ret;
102 static void lowercase(char *p)
104 for (; *p; p++)
105 *p = tolower(*p);
108 void git_config_push_parameter(const char *text)
110 struct strbuf env = STRBUF_INIT;
111 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
112 if (old) {
113 strbuf_addstr(&env, old);
114 strbuf_addch(&env, ' ');
116 sq_quote_buf(&env, text);
117 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
118 strbuf_release(&env);
121 int git_config_parse_parameter(const char *text,
122 config_fn_t fn, void *data)
124 struct strbuf **pair;
125 pair = strbuf_split_str(text, '=', 2);
126 if (!pair[0])
127 return error("bogus config parameter: %s", text);
128 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=')
129 strbuf_setlen(pair[0], pair[0]->len - 1);
130 strbuf_trim(pair[0]);
131 if (!pair[0]->len) {
132 strbuf_list_free(pair);
133 return error("bogus config parameter: %s", text);
135 lowercase(pair[0]->buf);
136 if (fn(pair[0]->buf, pair[1] ? pair[1]->buf : NULL, data) < 0) {
137 strbuf_list_free(pair);
138 return -1;
140 strbuf_list_free(pair);
141 return 0;
144 int git_config_from_parameters(config_fn_t fn, void *data)
146 const char *env = getenv(CONFIG_DATA_ENVIRONMENT);
147 char *envw;
148 const char **argv = NULL;
149 int nr = 0, alloc = 0;
150 int i;
152 if (!env)
153 return 0;
154 /* sq_dequote will write over it */
155 envw = xstrdup(env);
157 if (sq_dequote_to_argv(envw, &argv, &nr, &alloc) < 0) {
158 free(envw);
159 return error("bogus format in " CONFIG_DATA_ENVIRONMENT);
162 for (i = 0; i < nr; i++) {
163 if (git_config_parse_parameter(argv[i], fn, data) < 0) {
164 free(argv);
165 free(envw);
166 return -1;
170 free(argv);
171 free(envw);
172 return nr > 0;
175 static int get_next_char(void)
177 int c;
178 FILE *f;
180 c = '\n';
181 if (cf && ((f = cf->f) != NULL)) {
182 c = fgetc(f);
183 if (c == '\r') {
184 /* DOS like systems */
185 c = fgetc(f);
186 if (c != '\n') {
187 ungetc(c, f);
188 c = '\r';
191 if (c == '\n')
192 cf->linenr++;
193 if (c == EOF) {
194 cf->eof = 1;
195 c = '\n';
198 return c;
201 static char *parse_value(void)
203 int quote = 0, comment = 0, space = 0;
205 strbuf_reset(&cf->value);
206 for (;;) {
207 int c = get_next_char();
208 if (c == '\n') {
209 if (quote) {
210 cf->linenr--;
211 return NULL;
213 return cf->value.buf;
215 if (comment)
216 continue;
217 if (isspace(c) && !quote) {
218 if (cf->value.len)
219 space++;
220 continue;
222 if (!quote) {
223 if (c == ';' || c == '#') {
224 comment = 1;
225 continue;
228 for (; space; space--)
229 strbuf_addch(&cf->value, ' ');
230 if (c == '\\') {
231 c = get_next_char();
232 switch (c) {
233 case '\n':
234 continue;
235 case 't':
236 c = '\t';
237 break;
238 case 'b':
239 c = '\b';
240 break;
241 case 'n':
242 c = '\n';
243 break;
244 /* Some characters escape as themselves */
245 case '\\': case '"':
246 break;
247 /* Reject unknown escape sequences */
248 default:
249 return NULL;
251 strbuf_addch(&cf->value, c);
252 continue;
254 if (c == '"') {
255 quote = 1-quote;
256 continue;
258 strbuf_addch(&cf->value, c);
262 static inline int iskeychar(int c)
264 return isalnum(c) || c == '-';
267 static int get_value(config_fn_t fn, void *data, char *name, unsigned int len)
269 int c;
270 char *value;
272 /* Get the full name */
273 for (;;) {
274 c = get_next_char();
275 if (cf->eof)
276 break;
277 if (!iskeychar(c))
278 break;
279 name[len++] = tolower(c);
280 if (len >= MAXNAME)
281 return -1;
283 name[len] = 0;
284 while (c == ' ' || c == '\t')
285 c = get_next_char();
287 value = NULL;
288 if (c != '\n') {
289 if (c != '=')
290 return -1;
291 value = parse_value();
292 if (!value)
293 return -1;
295 return fn(name, value, data);
298 static int get_extended_base_var(char *name, int baselen, int c)
300 do {
301 if (c == '\n')
302 goto error_incomplete_line;
303 c = get_next_char();
304 } while (isspace(c));
306 /* We require the format to be '[base "extension"]' */
307 if (c != '"')
308 return -1;
309 name[baselen++] = '.';
311 for (;;) {
312 int c = get_next_char();
313 if (c == '\n')
314 goto error_incomplete_line;
315 if (c == '"')
316 break;
317 if (c == '\\') {
318 c = get_next_char();
319 if (c == '\n')
320 goto error_incomplete_line;
322 name[baselen++] = c;
323 if (baselen > MAXNAME / 2)
324 return -1;
327 /* Final ']' */
328 if (get_next_char() != ']')
329 return -1;
330 return baselen;
331 error_incomplete_line:
332 cf->linenr--;
333 return -1;
336 static int get_base_var(char *name)
338 int baselen = 0;
340 for (;;) {
341 int c = get_next_char();
342 if (cf->eof)
343 return -1;
344 if (c == ']')
345 return baselen;
346 if (isspace(c))
347 return get_extended_base_var(name, baselen, c);
348 if (!iskeychar(c) && c != '.')
349 return -1;
350 if (baselen > MAXNAME / 2)
351 return -1;
352 name[baselen++] = tolower(c);
356 static int git_parse_file(config_fn_t fn, void *data)
358 int comment = 0;
359 int baselen = 0;
360 char *var = cf->var;
362 /* U+FEFF Byte Order Mark in UTF8 */
363 static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
364 const unsigned char *bomptr = utf8_bom;
366 for (;;) {
367 int c = get_next_char();
368 if (bomptr && *bomptr) {
369 /* We are at the file beginning; skip UTF8-encoded BOM
370 * if present. Sane editors won't put this in on their
371 * own, but e.g. Windows Notepad will do it happily. */
372 if ((unsigned char) c == *bomptr) {
373 bomptr++;
374 continue;
375 } else {
376 /* Do not tolerate partial BOM. */
377 if (bomptr != utf8_bom)
378 break;
379 /* No BOM at file beginning. Cool. */
380 bomptr = NULL;
383 if (c == '\n') {
384 if (cf->eof)
385 return 0;
386 comment = 0;
387 continue;
389 if (comment || isspace(c))
390 continue;
391 if (c == '#' || c == ';') {
392 comment = 1;
393 continue;
395 if (c == '[') {
396 baselen = get_base_var(var);
397 if (baselen <= 0)
398 break;
399 var[baselen++] = '.';
400 var[baselen] = 0;
401 continue;
403 if (!isalpha(c))
404 break;
405 var[baselen] = tolower(c);
406 if (get_value(fn, data, var, baselen+1) < 0)
407 break;
409 die("bad config file line %d in %s", cf->linenr, cf->name);
412 static int parse_unit_factor(const char *end, uintmax_t *val)
414 if (!*end)
415 return 1;
416 else if (!strcasecmp(end, "k")) {
417 *val *= 1024;
418 return 1;
420 else if (!strcasecmp(end, "m")) {
421 *val *= 1024 * 1024;
422 return 1;
424 else if (!strcasecmp(end, "g")) {
425 *val *= 1024 * 1024 * 1024;
426 return 1;
428 return 0;
431 static int git_parse_long(const char *value, long *ret)
433 if (value && *value) {
434 char *end;
435 intmax_t val;
436 uintmax_t uval;
437 uintmax_t factor = 1;
439 errno = 0;
440 val = strtoimax(value, &end, 0);
441 if (errno == ERANGE)
442 return 0;
443 if (!parse_unit_factor(end, &factor))
444 return 0;
445 uval = abs(val);
446 uval *= factor;
447 if ((uval > maximum_signed_value_of_type(long)) ||
448 (abs(val) > uval))
449 return 0;
450 val *= factor;
451 *ret = val;
452 return 1;
454 return 0;
457 int git_parse_ulong(const char *value, unsigned long *ret)
459 if (value && *value) {
460 char *end;
461 uintmax_t val;
462 uintmax_t oldval;
464 errno = 0;
465 val = strtoumax(value, &end, 0);
466 if (errno == ERANGE)
467 return 0;
468 oldval = val;
469 if (!parse_unit_factor(end, &val))
470 return 0;
471 if ((val > maximum_unsigned_value_of_type(long)) ||
472 (oldval > val))
473 return 0;
474 *ret = val;
475 return 1;
477 return 0;
480 static void die_bad_config(const char *name)
482 if (cf && cf->name)
483 die("bad config value for '%s' in %s", name, cf->name);
484 die("bad config value for '%s'", name);
487 int git_config_int(const char *name, const char *value)
489 long ret = 0;
490 if (!git_parse_long(value, &ret))
491 die_bad_config(name);
492 return ret;
495 unsigned long git_config_ulong(const char *name, const char *value)
497 unsigned long ret;
498 if (!git_parse_ulong(value, &ret))
499 die_bad_config(name);
500 return ret;
503 static int git_config_maybe_bool_text(const char *name, const char *value)
505 if (!value)
506 return 1;
507 if (!*value)
508 return 0;
509 if (!strcasecmp(value, "true")
510 || !strcasecmp(value, "yes")
511 || !strcasecmp(value, "on"))
512 return 1;
513 if (!strcasecmp(value, "false")
514 || !strcasecmp(value, "no")
515 || !strcasecmp(value, "off"))
516 return 0;
517 return -1;
520 int git_config_maybe_bool(const char *name, const char *value)
522 long v = git_config_maybe_bool_text(name, value);
523 if (0 <= v)
524 return v;
525 if (git_parse_long(value, &v))
526 return !!v;
527 return -1;
530 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
532 int v = git_config_maybe_bool_text(name, value);
533 if (0 <= v) {
534 *is_bool = 1;
535 return v;
537 *is_bool = 0;
538 return git_config_int(name, value);
541 int git_config_bool(const char *name, const char *value)
543 int discard;
544 return !!git_config_bool_or_int(name, value, &discard);
547 int git_config_string(const char **dest, const char *var, const char *value)
549 if (!value)
550 return config_error_nonbool(var);
551 *dest = xstrdup(value);
552 return 0;
555 int git_config_pathname(const char **dest, const char *var, const char *value)
557 if (!value)
558 return config_error_nonbool(var);
559 *dest = expand_user_path(value);
560 if (!*dest)
561 die("Failed to expand user dir in: '%s'", value);
562 return 0;
565 static int git_default_core_config(const char *var, const char *value)
567 /* This needs a better name */
568 if (!strcmp(var, "core.filemode")) {
569 trust_executable_bit = git_config_bool(var, value);
570 return 0;
572 if (!strcmp(var, "core.trustctime")) {
573 trust_ctime = git_config_bool(var, value);
574 return 0;
577 if (!strcmp(var, "core.quotepath")) {
578 quote_path_fully = git_config_bool(var, value);
579 return 0;
582 if (!strcmp(var, "core.symlinks")) {
583 has_symlinks = git_config_bool(var, value);
584 return 0;
587 if (!strcmp(var, "core.ignorecase")) {
588 ignore_case = git_config_bool(var, value);
589 return 0;
592 if (!strcmp(var, "core.attributesfile"))
593 return git_config_pathname(&git_attributes_file, var, value);
595 if (!strcmp(var, "core.bare")) {
596 is_bare_repository_cfg = git_config_bool(var, value);
597 return 0;
600 if (!strcmp(var, "core.ignorestat")) {
601 assume_unchanged = git_config_bool(var, value);
602 return 0;
605 if (!strcmp(var, "core.prefersymlinkrefs")) {
606 prefer_symlink_refs = git_config_bool(var, value);
607 return 0;
610 if (!strcmp(var, "core.logallrefupdates")) {
611 log_all_ref_updates = git_config_bool(var, value);
612 return 0;
615 if (!strcmp(var, "core.warnambiguousrefs")) {
616 warn_ambiguous_refs = git_config_bool(var, value);
617 return 0;
620 if (!strcmp(var, "core.abbrev")) {
621 int abbrev = git_config_int(var, value);
622 if (abbrev < minimum_abbrev || abbrev > 40)
623 return -1;
624 default_abbrev = abbrev;
625 return 0;
628 if (!strcmp(var, "core.loosecompression")) {
629 int level = git_config_int(var, value);
630 if (level == -1)
631 level = Z_DEFAULT_COMPRESSION;
632 else if (level < 0 || level > Z_BEST_COMPRESSION)
633 die("bad zlib compression level %d", level);
634 zlib_compression_level = level;
635 zlib_compression_seen = 1;
636 return 0;
639 if (!strcmp(var, "core.compression")) {
640 int level = git_config_int(var, value);
641 if (level == -1)
642 level = Z_DEFAULT_COMPRESSION;
643 else if (level < 0 || level > Z_BEST_COMPRESSION)
644 die("bad zlib compression level %d", level);
645 core_compression_level = level;
646 core_compression_seen = 1;
647 if (!zlib_compression_seen)
648 zlib_compression_level = level;
649 return 0;
652 if (!strcmp(var, "core.packedgitwindowsize")) {
653 int pgsz_x2 = getpagesize() * 2;
654 packed_git_window_size = git_config_ulong(var, value);
656 /* This value must be multiple of (pagesize * 2) */
657 packed_git_window_size /= pgsz_x2;
658 if (packed_git_window_size < 1)
659 packed_git_window_size = 1;
660 packed_git_window_size *= pgsz_x2;
661 return 0;
664 if (!strcmp(var, "core.bigfilethreshold")) {
665 big_file_threshold = git_config_ulong(var, value);
666 return 0;
669 if (!strcmp(var, "core.packedgitlimit")) {
670 packed_git_limit = git_config_ulong(var, value);
671 return 0;
674 if (!strcmp(var, "core.deltabasecachelimit")) {
675 delta_base_cache_limit = git_config_ulong(var, value);
676 return 0;
679 if (!strcmp(var, "core.logpackaccess"))
680 return git_config_string(&log_pack_access, var, value);
682 if (!strcmp(var, "core.autocrlf")) {
683 if (value && !strcasecmp(value, "input")) {
684 if (core_eol == EOL_CRLF)
685 return error("core.autocrlf=input conflicts with core.eol=crlf");
686 auto_crlf = AUTO_CRLF_INPUT;
687 return 0;
689 auto_crlf = git_config_bool(var, value);
690 return 0;
693 if (!strcmp(var, "core.safecrlf")) {
694 if (value && !strcasecmp(value, "warn")) {
695 safe_crlf = SAFE_CRLF_WARN;
696 return 0;
698 safe_crlf = git_config_bool(var, value);
699 return 0;
702 if (!strcmp(var, "core.eol")) {
703 if (value && !strcasecmp(value, "lf"))
704 core_eol = EOL_LF;
705 else if (value && !strcasecmp(value, "crlf"))
706 core_eol = EOL_CRLF;
707 else if (value && !strcasecmp(value, "native"))
708 core_eol = EOL_NATIVE;
709 else
710 core_eol = EOL_UNSET;
711 if (core_eol == EOL_CRLF && auto_crlf == AUTO_CRLF_INPUT)
712 return error("core.autocrlf=input conflicts with core.eol=crlf");
713 return 0;
716 if (!strcmp(var, "core.notesref")) {
717 notes_ref_name = xstrdup(value);
718 return 0;
721 if (!strcmp(var, "core.pager"))
722 return git_config_string(&pager_program, var, value);
724 if (!strcmp(var, "core.editor"))
725 return git_config_string(&editor_program, var, value);
727 if (!strcmp(var, "core.askpass"))
728 return git_config_string(&askpass_program, var, value);
730 if (!strcmp(var, "core.excludesfile"))
731 return git_config_pathname(&excludes_file, var, value);
733 if (!strcmp(var, "core.whitespace")) {
734 if (!value)
735 return config_error_nonbool(var);
736 whitespace_rule_cfg = parse_whitespace_rule(value);
737 return 0;
740 if (!strcmp(var, "core.fsyncobjectfiles")) {
741 fsync_object_files = git_config_bool(var, value);
742 return 0;
745 if (!strcmp(var, "core.preloadindex")) {
746 core_preload_index = git_config_bool(var, value);
747 return 0;
750 if (!strcmp(var, "core.createobject")) {
751 if (!strcmp(value, "rename"))
752 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
753 else if (!strcmp(value, "link"))
754 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
755 else
756 die("Invalid mode for object creation: %s", value);
757 return 0;
760 if (!strcmp(var, "core.sparsecheckout")) {
761 core_apply_sparse_checkout = git_config_bool(var, value);
762 return 0;
765 /* Add other config variables here and to Documentation/config.txt. */
766 return 0;
769 static int git_default_user_config(const char *var, const char *value)
771 if (!strcmp(var, "user.name")) {
772 if (!value)
773 return config_error_nonbool(var);
774 strlcpy(git_default_name, value, sizeof(git_default_name));
775 user_ident_explicitly_given |= IDENT_NAME_GIVEN;
776 return 0;
779 if (!strcmp(var, "user.email")) {
780 if (!value)
781 return config_error_nonbool(var);
782 strlcpy(git_default_email, value, sizeof(git_default_email));
783 user_ident_explicitly_given |= IDENT_MAIL_GIVEN;
784 return 0;
787 /* Add other config variables here and to Documentation/config.txt. */
788 return 0;
791 static int git_default_i18n_config(const char *var, const char *value)
793 if (!strcmp(var, "i18n.commitencoding"))
794 return git_config_string(&git_commit_encoding, var, value);
796 if (!strcmp(var, "i18n.logoutputencoding"))
797 return git_config_string(&git_log_output_encoding, var, value);
799 /* Add other config variables here and to Documentation/config.txt. */
800 return 0;
803 static int git_default_branch_config(const char *var, const char *value)
805 if (!strcmp(var, "branch.autosetupmerge")) {
806 if (value && !strcasecmp(value, "always")) {
807 git_branch_track = BRANCH_TRACK_ALWAYS;
808 return 0;
810 git_branch_track = git_config_bool(var, value);
811 return 0;
813 if (!strcmp(var, "branch.autosetuprebase")) {
814 if (!value)
815 return config_error_nonbool(var);
816 else if (!strcmp(value, "never"))
817 autorebase = AUTOREBASE_NEVER;
818 else if (!strcmp(value, "local"))
819 autorebase = AUTOREBASE_LOCAL;
820 else if (!strcmp(value, "remote"))
821 autorebase = AUTOREBASE_REMOTE;
822 else if (!strcmp(value, "always"))
823 autorebase = AUTOREBASE_ALWAYS;
824 else
825 return error("Malformed value for %s", var);
826 return 0;
829 /* Add other config variables here and to Documentation/config.txt. */
830 return 0;
833 static int git_default_push_config(const char *var, const char *value)
835 if (!strcmp(var, "push.default")) {
836 if (!value)
837 return config_error_nonbool(var);
838 else if (!strcmp(value, "nothing"))
839 push_default = PUSH_DEFAULT_NOTHING;
840 else if (!strcmp(value, "matching"))
841 push_default = PUSH_DEFAULT_MATCHING;
842 else if (!strcmp(value, "upstream"))
843 push_default = PUSH_DEFAULT_UPSTREAM;
844 else if (!strcmp(value, "tracking")) /* deprecated */
845 push_default = PUSH_DEFAULT_UPSTREAM;
846 else if (!strcmp(value, "current"))
847 push_default = PUSH_DEFAULT_CURRENT;
848 else {
849 error("Malformed value for %s: %s", var, value);
850 return error("Must be one of nothing, matching, "
851 "tracking or current.");
853 return 0;
856 /* Add other config variables here and to Documentation/config.txt. */
857 return 0;
860 static int git_default_mailmap_config(const char *var, const char *value)
862 if (!strcmp(var, "mailmap.file"))
863 return git_config_string(&git_mailmap_file, var, value);
865 /* Add other config variables here and to Documentation/config.txt. */
866 return 0;
869 int git_default_config(const char *var, const char *value, void *dummy)
871 if (!prefixcmp(var, "core."))
872 return git_default_core_config(var, value);
874 if (!prefixcmp(var, "user."))
875 return git_default_user_config(var, value);
877 if (!prefixcmp(var, "i18n."))
878 return git_default_i18n_config(var, value);
880 if (!prefixcmp(var, "branch."))
881 return git_default_branch_config(var, value);
883 if (!prefixcmp(var, "push."))
884 return git_default_push_config(var, value);
886 if (!prefixcmp(var, "mailmap."))
887 return git_default_mailmap_config(var, value);
889 if (!prefixcmp(var, "advice."))
890 return git_default_advice_config(var, value);
892 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
893 pager_use_color = git_config_bool(var,value);
894 return 0;
897 if (!strcmp(var, "pack.packsizelimit")) {
898 pack_size_limit_cfg = git_config_ulong(var, value);
899 return 0;
901 /* Add other config variables here and to Documentation/config.txt. */
902 return 0;
905 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
907 int ret;
908 FILE *f = fopen(filename, "r");
910 ret = -1;
911 if (f) {
912 config_file top;
914 /* push config-file parsing state stack */
915 top.prev = cf;
916 top.f = f;
917 top.name = filename;
918 top.linenr = 1;
919 top.eof = 0;
920 strbuf_init(&top.value, 1024);
921 cf = &top;
923 ret = git_parse_file(fn, data);
925 /* pop config-file parsing state stack */
926 strbuf_release(&top.value);
927 cf = top.prev;
929 fclose(f);
931 return ret;
934 const char *git_etc_gitconfig(void)
936 static const char *system_wide;
937 if (!system_wide)
938 system_wide = system_path(ETC_GITCONFIG);
939 return system_wide;
942 int git_env_bool(const char *k, int def)
944 const char *v = getenv(k);
945 return v ? git_config_bool(k, v) : def;
948 int git_config_system(void)
950 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
953 int git_config_early(config_fn_t fn, void *data, const char *repo_config)
955 int ret = 0, found = 0;
956 const char *home = NULL;
958 if (git_config_system() && !access(git_etc_gitconfig(), R_OK)) {
959 ret += git_config_from_file(fn, git_etc_gitconfig(),
960 data);
961 found += 1;
964 home = getenv("HOME");
965 if (home) {
966 char buf[PATH_MAX];
967 char *user_config = mksnpath(buf, sizeof(buf), "%s/.gitconfig", home);
968 if (!access(user_config, R_OK)) {
969 ret += git_config_from_file(fn, user_config, data);
970 found += 1;
974 if (repo_config && !access(repo_config, R_OK)) {
975 ret += git_config_from_file(fn, repo_config, data);
976 found += 1;
979 switch (git_config_from_parameters(fn, data)) {
980 case -1: /* error */
981 die("unable to parse command-line config");
982 break;
983 case 0: /* found nothing */
984 break;
985 default: /* found at least one item */
986 found++;
987 break;
990 return ret == 0 ? found : ret;
993 int git_config_with_options(config_fn_t fn, void *data,
994 const char *filename, int respect_includes)
996 char *repo_config = NULL;
997 int ret;
998 struct config_include_data inc = CONFIG_INCLUDE_INIT;
1000 if (respect_includes) {
1001 inc.fn = fn;
1002 inc.data = data;
1003 fn = git_config_include;
1004 data = &inc;
1008 * If we have a specific filename, use it. Otherwise, follow the
1009 * regular lookup sequence.
1011 if (filename)
1012 return git_config_from_file(fn, filename, data);
1014 repo_config = git_pathdup("config");
1015 ret = git_config_early(fn, data, repo_config);
1016 if (repo_config)
1017 free(repo_config);
1018 return ret;
1021 int git_config(config_fn_t fn, void *data)
1023 return git_config_with_options(fn, data, NULL, 1);
1027 * Find all the stuff for git_config_set() below.
1030 #define MAX_MATCHES 512
1032 static struct {
1033 int baselen;
1034 char *key;
1035 int do_not_match;
1036 regex_t *value_regex;
1037 int multi_replace;
1038 size_t offset[MAX_MATCHES];
1039 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
1040 int seen;
1041 } store;
1043 static int matches(const char *key, const char *value)
1045 return !strcmp(key, store.key) &&
1046 (store.value_regex == NULL ||
1047 (store.do_not_match ^
1048 !regexec(store.value_regex, value, 0, NULL, 0)));
1051 static int store_aux(const char *key, const char *value, void *cb)
1053 const char *ep;
1054 size_t section_len;
1055 FILE *f = cf->f;
1057 switch (store.state) {
1058 case KEY_SEEN:
1059 if (matches(key, value)) {
1060 if (store.seen == 1 && store.multi_replace == 0) {
1061 warning("%s has multiple values", key);
1062 } else if (store.seen >= MAX_MATCHES) {
1063 error("too many matches for %s", key);
1064 return 1;
1067 store.offset[store.seen] = ftell(f);
1068 store.seen++;
1070 break;
1071 case SECTION_SEEN:
1073 * What we are looking for is in store.key (both
1074 * section and var), and its section part is baselen
1075 * long. We found key (again, both section and var).
1076 * We would want to know if this key is in the same
1077 * section as what we are looking for. We already
1078 * know we are in the same section as what should
1079 * hold store.key.
1081 ep = strrchr(key, '.');
1082 section_len = ep - key;
1084 if ((section_len != store.baselen) ||
1085 memcmp(key, store.key, section_len+1)) {
1086 store.state = SECTION_END_SEEN;
1087 break;
1091 * Do not increment matches: this is no match, but we
1092 * just made sure we are in the desired section.
1094 store.offset[store.seen] = ftell(f);
1095 /* fallthru */
1096 case SECTION_END_SEEN:
1097 case START:
1098 if (matches(key, value)) {
1099 store.offset[store.seen] = ftell(f);
1100 store.state = KEY_SEEN;
1101 store.seen++;
1102 } else {
1103 if (strrchr(key, '.') - key == store.baselen &&
1104 !strncmp(key, store.key, store.baselen)) {
1105 store.state = SECTION_SEEN;
1106 store.offset[store.seen] = ftell(f);
1110 return 0;
1113 static int write_error(const char *filename)
1115 error("failed to write new configuration file %s", filename);
1117 /* Same error code as "failed to rename". */
1118 return 4;
1121 static int store_write_section(int fd, const char *key)
1123 const char *dot;
1124 int i, success;
1125 struct strbuf sb = STRBUF_INIT;
1127 dot = memchr(key, '.', store.baselen);
1128 if (dot) {
1129 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
1130 for (i = dot - key + 1; i < store.baselen; i++) {
1131 if (key[i] == '"' || key[i] == '\\')
1132 strbuf_addch(&sb, '\\');
1133 strbuf_addch(&sb, key[i]);
1135 strbuf_addstr(&sb, "\"]\n");
1136 } else {
1137 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
1140 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1141 strbuf_release(&sb);
1143 return success;
1146 static int store_write_pair(int fd, const char *key, const char *value)
1148 int i, success;
1149 int length = strlen(key + store.baselen + 1);
1150 const char *quote = "";
1151 struct strbuf sb = STRBUF_INIT;
1154 * Check to see if the value needs to be surrounded with a dq pair.
1155 * Note that problematic characters are always backslash-quoted; this
1156 * check is about not losing leading or trailing SP and strings that
1157 * follow beginning-of-comment characters (i.e. ';' and '#') by the
1158 * configuration parser.
1160 if (value[0] == ' ')
1161 quote = "\"";
1162 for (i = 0; value[i]; i++)
1163 if (value[i] == ';' || value[i] == '#')
1164 quote = "\"";
1165 if (i && value[i - 1] == ' ')
1166 quote = "\"";
1168 strbuf_addf(&sb, "\t%.*s = %s",
1169 length, key + store.baselen + 1, quote);
1171 for (i = 0; value[i]; i++)
1172 switch (value[i]) {
1173 case '\n':
1174 strbuf_addstr(&sb, "\\n");
1175 break;
1176 case '\t':
1177 strbuf_addstr(&sb, "\\t");
1178 break;
1179 case '"':
1180 case '\\':
1181 strbuf_addch(&sb, '\\');
1182 default:
1183 strbuf_addch(&sb, value[i]);
1184 break;
1186 strbuf_addf(&sb, "%s\n", quote);
1188 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1189 strbuf_release(&sb);
1191 return success;
1194 static ssize_t find_beginning_of_line(const char *contents, size_t size,
1195 size_t offset_, int *found_bracket)
1197 size_t equal_offset = size, bracket_offset = size;
1198 ssize_t offset;
1200 contline:
1201 for (offset = offset_-2; offset > 0
1202 && contents[offset] != '\n'; offset--)
1203 switch (contents[offset]) {
1204 case '=': equal_offset = offset; break;
1205 case ']': bracket_offset = offset; break;
1207 if (offset > 0 && contents[offset-1] == '\\') {
1208 offset_ = offset;
1209 goto contline;
1211 if (bracket_offset < equal_offset) {
1212 *found_bracket = 1;
1213 offset = bracket_offset+1;
1214 } else
1215 offset++;
1217 return offset;
1220 int git_config_set_in_file(const char *config_filename,
1221 const char *key, const char *value)
1223 return git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
1226 int git_config_set(const char *key, const char *value)
1228 return git_config_set_multivar(key, value, NULL, 0);
1232 * Auxiliary function to sanity-check and split the key into the section
1233 * identifier and variable name.
1235 * Returns 0 on success, -1 when there is an invalid character in the key and
1236 * -2 if there is no section name in the key.
1238 * store_key - pointer to char* which will hold a copy of the key with
1239 * lowercase section and variable name
1240 * baselen - pointer to int which will hold the length of the
1241 * section + subsection part, can be NULL
1243 int git_config_parse_key(const char *key, char **store_key, int *baselen_)
1245 int i, dot, baselen;
1246 const char *last_dot = strrchr(key, '.');
1249 * Since "key" actually contains the section name and the real
1250 * key name separated by a dot, we have to know where the dot is.
1253 if (last_dot == NULL || last_dot == key) {
1254 error("key does not contain a section: %s", key);
1255 return -CONFIG_NO_SECTION_OR_NAME;
1258 if (!last_dot[1]) {
1259 error("key does not contain variable name: %s", key);
1260 return -CONFIG_NO_SECTION_OR_NAME;
1263 baselen = last_dot - key;
1264 if (baselen_)
1265 *baselen_ = baselen;
1268 * Validate the key and while at it, lower case it for matching.
1270 *store_key = xmalloc(strlen(key) + 1);
1272 dot = 0;
1273 for (i = 0; key[i]; i++) {
1274 unsigned char c = key[i];
1275 if (c == '.')
1276 dot = 1;
1277 /* Leave the extended basename untouched.. */
1278 if (!dot || i > baselen) {
1279 if (!iskeychar(c) ||
1280 (i == baselen + 1 && !isalpha(c))) {
1281 error("invalid key: %s", key);
1282 goto out_free_ret_1;
1284 c = tolower(c);
1285 } else if (c == '\n') {
1286 error("invalid key (newline): %s", key);
1287 goto out_free_ret_1;
1289 (*store_key)[i] = c;
1291 (*store_key)[i] = 0;
1293 return 0;
1295 out_free_ret_1:
1296 free(*store_key);
1297 return -CONFIG_INVALID_KEY;
1301 * If value==NULL, unset in (remove from) config,
1302 * if value_regex!=NULL, disregard key/value pairs where value does not match.
1303 * if multi_replace==0, nothing, or only one matching key/value is replaced,
1304 * else all matching key/values (regardless how many) are removed,
1305 * before the new pair is written.
1307 * Returns 0 on success.
1309 * This function does this:
1311 * - it locks the config file by creating ".git/config.lock"
1313 * - it then parses the config using store_aux() as validator to find
1314 * the position on the key/value pair to replace. If it is to be unset,
1315 * it must be found exactly once.
1317 * - the config file is mmap()ed and the part before the match (if any) is
1318 * written to the lock file, then the changed part and the rest.
1320 * - the config file is removed and the lock file rename()d to it.
1323 int git_config_set_multivar_in_file(const char *config_filename,
1324 const char *key, const char *value,
1325 const char *value_regex, int multi_replace)
1327 int fd = -1, in_fd;
1328 int ret;
1329 struct lock_file *lock = NULL;
1330 char *filename_buf = NULL;
1332 /* parse-key returns negative; flip the sign to feed exit(3) */
1333 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
1334 if (ret)
1335 goto out_free;
1337 store.multi_replace = multi_replace;
1339 if (!config_filename)
1340 config_filename = filename_buf = git_pathdup("config");
1343 * The lock serves a purpose in addition to locking: the new
1344 * contents of .git/config will be written into it.
1346 lock = xcalloc(sizeof(struct lock_file), 1);
1347 fd = hold_lock_file_for_update(lock, config_filename, 0);
1348 if (fd < 0) {
1349 error("could not lock config file %s: %s", config_filename, strerror(errno));
1350 free(store.key);
1351 ret = CONFIG_NO_LOCK;
1352 goto out_free;
1356 * If .git/config does not exist yet, write a minimal version.
1358 in_fd = open(config_filename, O_RDONLY);
1359 if ( in_fd < 0 ) {
1360 free(store.key);
1362 if ( ENOENT != errno ) {
1363 error("opening %s: %s", config_filename,
1364 strerror(errno));
1365 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
1366 goto out_free;
1368 /* if nothing to unset, error out */
1369 if (value == NULL) {
1370 ret = CONFIG_NOTHING_SET;
1371 goto out_free;
1374 store.key = (char *)key;
1375 if (!store_write_section(fd, key) ||
1376 !store_write_pair(fd, key, value))
1377 goto write_err_out;
1378 } else {
1379 struct stat st;
1380 char *contents;
1381 size_t contents_sz, copy_begin, copy_end;
1382 int i, new_line = 0;
1384 if (value_regex == NULL)
1385 store.value_regex = NULL;
1386 else {
1387 if (value_regex[0] == '!') {
1388 store.do_not_match = 1;
1389 value_regex++;
1390 } else
1391 store.do_not_match = 0;
1393 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1394 if (regcomp(store.value_regex, value_regex,
1395 REG_EXTENDED)) {
1396 error("invalid pattern: %s", value_regex);
1397 free(store.value_regex);
1398 ret = CONFIG_INVALID_PATTERN;
1399 goto out_free;
1403 store.offset[0] = 0;
1404 store.state = START;
1405 store.seen = 0;
1408 * After this, store.offset will contain the *end* offset
1409 * of the last match, or remain at 0 if no match was found.
1410 * As a side effect, we make sure to transform only a valid
1411 * existing config file.
1413 if (git_config_from_file(store_aux, config_filename, NULL)) {
1414 error("invalid config file %s", config_filename);
1415 free(store.key);
1416 if (store.value_regex != NULL) {
1417 regfree(store.value_regex);
1418 free(store.value_regex);
1420 ret = CONFIG_INVALID_FILE;
1421 goto out_free;
1424 free(store.key);
1425 if (store.value_regex != NULL) {
1426 regfree(store.value_regex);
1427 free(store.value_regex);
1430 /* if nothing to unset, or too many matches, error out */
1431 if ((store.seen == 0 && value == NULL) ||
1432 (store.seen > 1 && multi_replace == 0)) {
1433 ret = CONFIG_NOTHING_SET;
1434 goto out_free;
1437 fstat(in_fd, &st);
1438 contents_sz = xsize_t(st.st_size);
1439 contents = xmmap(NULL, contents_sz, PROT_READ,
1440 MAP_PRIVATE, in_fd, 0);
1441 close(in_fd);
1443 if (store.seen == 0)
1444 store.seen = 1;
1446 for (i = 0, copy_begin = 0; i < store.seen; i++) {
1447 if (store.offset[i] == 0) {
1448 store.offset[i] = copy_end = contents_sz;
1449 } else if (store.state != KEY_SEEN) {
1450 copy_end = store.offset[i];
1451 } else
1452 copy_end = find_beginning_of_line(
1453 contents, contents_sz,
1454 store.offset[i]-2, &new_line);
1456 if (copy_end > 0 && contents[copy_end-1] != '\n')
1457 new_line = 1;
1459 /* write the first part of the config */
1460 if (copy_end > copy_begin) {
1461 if (write_in_full(fd, contents + copy_begin,
1462 copy_end - copy_begin) <
1463 copy_end - copy_begin)
1464 goto write_err_out;
1465 if (new_line &&
1466 write_str_in_full(fd, "\n") != 1)
1467 goto write_err_out;
1469 copy_begin = store.offset[i];
1472 /* write the pair (value == NULL means unset) */
1473 if (value != NULL) {
1474 if (store.state == START) {
1475 if (!store_write_section(fd, key))
1476 goto write_err_out;
1478 if (!store_write_pair(fd, key, value))
1479 goto write_err_out;
1482 /* write the rest of the config */
1483 if (copy_begin < contents_sz)
1484 if (write_in_full(fd, contents + copy_begin,
1485 contents_sz - copy_begin) <
1486 contents_sz - copy_begin)
1487 goto write_err_out;
1489 munmap(contents, contents_sz);
1492 if (commit_lock_file(lock) < 0) {
1493 error("could not commit config file %s", config_filename);
1494 ret = CONFIG_NO_WRITE;
1495 goto out_free;
1499 * lock is committed, so don't try to roll it back below.
1500 * NOTE: Since lockfile.c keeps a linked list of all created
1501 * lock_file structures, it isn't safe to free(lock). It's
1502 * better to just leave it hanging around.
1504 lock = NULL;
1505 ret = 0;
1507 out_free:
1508 if (lock)
1509 rollback_lock_file(lock);
1510 free(filename_buf);
1511 return ret;
1513 write_err_out:
1514 ret = write_error(lock->filename);
1515 goto out_free;
1519 int git_config_set_multivar(const char *key, const char *value,
1520 const char *value_regex, int multi_replace)
1522 return git_config_set_multivar_in_file(NULL, key, value, value_regex,
1523 multi_replace);
1526 static int section_name_match (const char *buf, const char *name)
1528 int i = 0, j = 0, dot = 0;
1529 if (buf[i] != '[')
1530 return 0;
1531 for (i = 1; buf[i] && buf[i] != ']'; i++) {
1532 if (!dot && isspace(buf[i])) {
1533 dot = 1;
1534 if (name[j++] != '.')
1535 break;
1536 for (i++; isspace(buf[i]); i++)
1537 ; /* do nothing */
1538 if (buf[i] != '"')
1539 break;
1540 continue;
1542 if (buf[i] == '\\' && dot)
1543 i++;
1544 else if (buf[i] == '"' && dot) {
1545 for (i++; isspace(buf[i]); i++)
1546 ; /* do_nothing */
1547 break;
1549 if (buf[i] != name[j++])
1550 break;
1552 if (buf[i] == ']' && name[j] == 0) {
1554 * We match, now just find the right length offset by
1555 * gobbling up any whitespace after it, as well
1557 i++;
1558 for (; buf[i] && isspace(buf[i]); i++)
1559 ; /* do nothing */
1560 return i;
1562 return 0;
1565 /* if new_name == NULL, the section is removed instead */
1566 int git_config_rename_section_in_file(const char *config_filename,
1567 const char *old_name, const char *new_name)
1569 int ret = 0, remove = 0;
1570 char *filename_buf = NULL;
1571 struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1572 int out_fd;
1573 char buf[1024];
1574 FILE *config_file;
1576 if (!config_filename)
1577 config_filename = filename_buf = git_pathdup("config");
1579 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1580 if (out_fd < 0) {
1581 ret = error("could not lock config file %s", config_filename);
1582 goto out;
1585 if (!(config_file = fopen(config_filename, "rb"))) {
1586 /* no config file means nothing to rename, no error */
1587 goto unlock_and_out;
1590 while (fgets(buf, sizeof(buf), config_file)) {
1591 int i;
1592 int length;
1593 char *output = buf;
1594 for (i = 0; buf[i] && isspace(buf[i]); i++)
1595 ; /* do nothing */
1596 if (buf[i] == '[') {
1597 /* it's a section */
1598 int offset = section_name_match(&buf[i], old_name);
1599 if (offset > 0) {
1600 ret++;
1601 if (new_name == NULL) {
1602 remove = 1;
1603 continue;
1605 store.baselen = strlen(new_name);
1606 if (!store_write_section(out_fd, new_name)) {
1607 ret = write_error(lock->filename);
1608 goto out;
1611 * We wrote out the new section, with
1612 * a newline, now skip the old
1613 * section's length
1615 output += offset + i;
1616 if (strlen(output) > 0) {
1618 * More content means there's
1619 * a declaration to put on the
1620 * next line; indent with a
1621 * tab
1623 output -= 1;
1624 output[0] = '\t';
1627 remove = 0;
1629 if (remove)
1630 continue;
1631 length = strlen(output);
1632 if (write_in_full(out_fd, output, length) != length) {
1633 ret = write_error(lock->filename);
1634 goto out;
1637 fclose(config_file);
1638 unlock_and_out:
1639 if (commit_lock_file(lock) < 0)
1640 ret = error("could not commit config file %s", config_filename);
1641 out:
1642 free(filename_buf);
1643 return ret;
1646 int git_config_rename_section(const char *old_name, const char *new_name)
1648 return git_config_rename_section_in_file(NULL, old_name, new_name);
1652 * Call this to report error for your variable that should not
1653 * get a boolean value (i.e. "[my] var" means "true").
1655 int config_error_nonbool(const char *var)
1657 return error("Missing value for '%s'", var);