Merge branch 'lt/pull-no-edit' into next
[git/dscho.git] / config.c
blobe3fcf7553ca9ba70b465a6b61131cab848d5737b
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 const char *config_exclusive_filename = NULL;
31 #define MAX_INCLUDE_DEPTH 10
32 static const char include_depth_advice[] =
33 "exceeded maximum include depth (%d) while including\n"
34 " %s\n"
35 "from\n"
36 " %s\n"
37 "Do you have circular includes?";
38 static int handle_path_include(const char *path, struct config_include_data *inc)
40 int ret = 0;
41 struct strbuf buf = STRBUF_INIT;
44 * Use an absolute path as-is, but interpret relative paths
45 * based on the including config file.
47 if (!is_absolute_path(path)) {
48 char *slash;
50 if (!cf || !cf->name)
51 return error("relative config includes must come from files");
53 slash = find_last_dir_sep(cf->name);
54 if (slash)
55 strbuf_add(&buf, cf->name, slash - cf->name + 1);
56 strbuf_addstr(&buf, path);
57 path = buf.buf;
60 if (!access(path, R_OK)) {
61 if (++inc->depth > MAX_INCLUDE_DEPTH)
62 die(include_depth_advice, MAX_INCLUDE_DEPTH, path,
63 cf && cf->name ? cf->name : "the command line");
64 ret = git_config_from_file(git_config_include, path, inc);
65 inc->depth--;
67 strbuf_release(&buf);
68 return ret;
71 int git_config_include(const char *var, const char *value, void *data)
73 struct config_include_data *inc = data;
74 const char *type;
75 int ret;
78 * Pass along all values, including "include" directives; this makes it
79 * possible to query information on the includes themselves.
81 ret = inc->fn(var, value, inc->data);
82 if (ret < 0)
83 return ret;
85 type = skip_prefix(var, "include.");
86 if (!type)
87 return ret;
89 if (!strcmp(type, "path"))
90 ret = handle_path_include(value, inc);
91 return ret;
94 static void lowercase(char *p)
96 for (; *p; p++)
97 *p = tolower(*p);
100 void git_config_push_parameter(const char *text)
102 struct strbuf env = STRBUF_INIT;
103 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
104 if (old) {
105 strbuf_addstr(&env, old);
106 strbuf_addch(&env, ' ');
108 sq_quote_buf(&env, text);
109 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
110 strbuf_release(&env);
113 int git_config_parse_parameter(const char *text,
114 config_fn_t fn, void *data)
116 struct strbuf **pair;
117 pair = strbuf_split_str(text, '=', 2);
118 if (!pair[0])
119 return error("bogus config parameter: %s", text);
120 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=')
121 strbuf_setlen(pair[0], pair[0]->len - 1);
122 strbuf_trim(pair[0]);
123 if (!pair[0]->len) {
124 strbuf_list_free(pair);
125 return error("bogus config parameter: %s", text);
127 lowercase(pair[0]->buf);
128 if (fn(pair[0]->buf, pair[1] ? pair[1]->buf : NULL, data) < 0) {
129 strbuf_list_free(pair);
130 return -1;
132 strbuf_list_free(pair);
133 return 0;
136 int git_config_from_parameters(config_fn_t fn, void *data)
138 const char *env = getenv(CONFIG_DATA_ENVIRONMENT);
139 char *envw;
140 const char **argv = NULL;
141 int nr = 0, alloc = 0;
142 int i;
144 if (!env)
145 return 0;
146 /* sq_dequote will write over it */
147 envw = xstrdup(env);
149 if (sq_dequote_to_argv(envw, &argv, &nr, &alloc) < 0) {
150 free(envw);
151 return error("bogus format in " CONFIG_DATA_ENVIRONMENT);
154 for (i = 0; i < nr; i++) {
155 if (git_config_parse_parameter(argv[i], fn, data) < 0) {
156 free(argv);
157 free(envw);
158 return -1;
162 free(argv);
163 free(envw);
164 return nr > 0;
167 static int get_next_char(void)
169 int c;
170 FILE *f;
172 c = '\n';
173 if (cf && ((f = cf->f) != NULL)) {
174 c = fgetc(f);
175 if (c == '\r') {
176 /* DOS like systems */
177 c = fgetc(f);
178 if (c != '\n') {
179 ungetc(c, f);
180 c = '\r';
183 if (c == '\n')
184 cf->linenr++;
185 if (c == EOF) {
186 cf->eof = 1;
187 c = '\n';
190 return c;
193 static char *parse_value(void)
195 int quote = 0, comment = 0, space = 0;
197 strbuf_reset(&cf->value);
198 for (;;) {
199 int c = get_next_char();
200 if (c == '\n') {
201 if (quote)
202 return NULL;
203 return cf->value.buf;
205 if (comment)
206 continue;
207 if (isspace(c) && !quote) {
208 if (cf->value.len)
209 space++;
210 continue;
212 if (!quote) {
213 if (c == ';' || c == '#') {
214 comment = 1;
215 continue;
218 for (; space; space--)
219 strbuf_addch(&cf->value, ' ');
220 if (c == '\\') {
221 c = get_next_char();
222 switch (c) {
223 case '\n':
224 continue;
225 case 't':
226 c = '\t';
227 break;
228 case 'b':
229 c = '\b';
230 break;
231 case 'n':
232 c = '\n';
233 break;
234 /* Some characters escape as themselves */
235 case '\\': case '"':
236 break;
237 /* Reject unknown escape sequences */
238 default:
239 return NULL;
241 strbuf_addch(&cf->value, c);
242 continue;
244 if (c == '"') {
245 quote = 1-quote;
246 continue;
248 strbuf_addch(&cf->value, c);
252 static inline int iskeychar(int c)
254 return isalnum(c) || c == '-';
257 static int get_value(config_fn_t fn, void *data, char *name, unsigned int len)
259 int c;
260 char *value;
262 /* Get the full name */
263 for (;;) {
264 c = get_next_char();
265 if (cf->eof)
266 break;
267 if (!iskeychar(c))
268 break;
269 name[len++] = tolower(c);
270 if (len >= MAXNAME)
271 return -1;
273 name[len] = 0;
274 while (c == ' ' || c == '\t')
275 c = get_next_char();
277 value = NULL;
278 if (c != '\n') {
279 if (c != '=')
280 return -1;
281 value = parse_value();
282 if (!value)
283 return -1;
285 return fn(name, value, data);
288 static int get_extended_base_var(char *name, int baselen, int c)
290 do {
291 if (c == '\n')
292 return -1;
293 c = get_next_char();
294 } while (isspace(c));
296 /* We require the format to be '[base "extension"]' */
297 if (c != '"')
298 return -1;
299 name[baselen++] = '.';
301 for (;;) {
302 int c = get_next_char();
303 if (c == '\n')
304 return -1;
305 if (c == '"')
306 break;
307 if (c == '\\') {
308 c = get_next_char();
309 if (c == '\n')
310 return -1;
312 name[baselen++] = c;
313 if (baselen > MAXNAME / 2)
314 return -1;
317 /* Final ']' */
318 if (get_next_char() != ']')
319 return -1;
320 return baselen;
323 static int get_base_var(char *name)
325 int baselen = 0;
327 for (;;) {
328 int c = get_next_char();
329 if (cf->eof)
330 return -1;
331 if (c == ']')
332 return baselen;
333 if (isspace(c))
334 return get_extended_base_var(name, baselen, c);
335 if (!iskeychar(c) && c != '.')
336 return -1;
337 if (baselen > MAXNAME / 2)
338 return -1;
339 name[baselen++] = tolower(c);
343 static int git_parse_file(config_fn_t fn, void *data)
345 int comment = 0;
346 int baselen = 0;
347 char *var = cf->var;
349 /* U+FEFF Byte Order Mark in UTF8 */
350 static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
351 const unsigned char *bomptr = utf8_bom;
353 for (;;) {
354 int c = get_next_char();
355 if (bomptr && *bomptr) {
356 /* We are at the file beginning; skip UTF8-encoded BOM
357 * if present. Sane editors won't put this in on their
358 * own, but e.g. Windows Notepad will do it happily. */
359 if ((unsigned char) c == *bomptr) {
360 bomptr++;
361 continue;
362 } else {
363 /* Do not tolerate partial BOM. */
364 if (bomptr != utf8_bom)
365 break;
366 /* No BOM at file beginning. Cool. */
367 bomptr = NULL;
370 if (c == '\n') {
371 if (cf->eof)
372 return 0;
373 comment = 0;
374 continue;
376 if (comment || isspace(c))
377 continue;
378 if (c == '#' || c == ';') {
379 comment = 1;
380 continue;
382 if (c == '[') {
383 baselen = get_base_var(var);
384 if (baselen <= 0)
385 break;
386 var[baselen++] = '.';
387 var[baselen] = 0;
388 continue;
390 if (!isalpha(c))
391 break;
392 var[baselen] = tolower(c);
393 if (get_value(fn, data, var, baselen+1) < 0)
394 break;
396 die("bad config file line %d in %s", cf->linenr, cf->name);
399 static int parse_unit_factor(const char *end, uintmax_t *val)
401 if (!*end)
402 return 1;
403 else if (!strcasecmp(end, "k")) {
404 *val *= 1024;
405 return 1;
407 else if (!strcasecmp(end, "m")) {
408 *val *= 1024 * 1024;
409 return 1;
411 else if (!strcasecmp(end, "g")) {
412 *val *= 1024 * 1024 * 1024;
413 return 1;
415 return 0;
418 static int git_parse_long(const char *value, long *ret)
420 if (value && *value) {
421 char *end;
422 intmax_t val;
423 uintmax_t uval;
424 uintmax_t factor = 1;
426 errno = 0;
427 val = strtoimax(value, &end, 0);
428 if (errno == ERANGE)
429 return 0;
430 if (!parse_unit_factor(end, &factor))
431 return 0;
432 uval = abs(val);
433 uval *= factor;
434 if ((uval > maximum_signed_value_of_type(long)) ||
435 (abs(val) > uval))
436 return 0;
437 val *= factor;
438 *ret = val;
439 return 1;
441 return 0;
444 int git_parse_ulong(const char *value, unsigned long *ret)
446 if (value && *value) {
447 char *end;
448 uintmax_t val;
449 uintmax_t oldval;
451 errno = 0;
452 val = strtoumax(value, &end, 0);
453 if (errno == ERANGE)
454 return 0;
455 oldval = val;
456 if (!parse_unit_factor(end, &val))
457 return 0;
458 if ((val > maximum_unsigned_value_of_type(long)) ||
459 (oldval > val))
460 return 0;
461 *ret = val;
462 return 1;
464 return 0;
467 static void die_bad_config(const char *name)
469 if (cf && cf->name)
470 die("bad config value for '%s' in %s", name, cf->name);
471 die("bad config value for '%s'", name);
474 int git_config_int(const char *name, const char *value)
476 long ret = 0;
477 if (!git_parse_long(value, &ret))
478 die_bad_config(name);
479 return ret;
482 unsigned long git_config_ulong(const char *name, const char *value)
484 unsigned long ret;
485 if (!git_parse_ulong(value, &ret))
486 die_bad_config(name);
487 return ret;
490 static int git_config_maybe_bool_text(const char *name, const char *value)
492 if (!value)
493 return 1;
494 if (!*value)
495 return 0;
496 if (!strcasecmp(value, "true")
497 || !strcasecmp(value, "yes")
498 || !strcasecmp(value, "on"))
499 return 1;
500 if (!strcasecmp(value, "false")
501 || !strcasecmp(value, "no")
502 || !strcasecmp(value, "off"))
503 return 0;
504 return -1;
507 int git_config_maybe_bool(const char *name, const char *value)
509 long v = git_config_maybe_bool_text(name, value);
510 if (0 <= v)
511 return v;
512 if (git_parse_long(value, &v))
513 return !!v;
514 return -1;
517 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
519 int v = git_config_maybe_bool_text(name, value);
520 if (0 <= v) {
521 *is_bool = 1;
522 return v;
524 *is_bool = 0;
525 return git_config_int(name, value);
528 int git_config_bool(const char *name, const char *value)
530 int discard;
531 return !!git_config_bool_or_int(name, value, &discard);
534 int git_config_string(const char **dest, const char *var, const char *value)
536 if (!value)
537 return config_error_nonbool(var);
538 *dest = xstrdup(value);
539 return 0;
542 int git_config_pathname(const char **dest, const char *var, const char *value)
544 if (!value)
545 return config_error_nonbool(var);
546 *dest = expand_user_path(value);
547 if (!*dest)
548 die("Failed to expand user dir in: '%s'", value);
549 return 0;
552 static int git_default_core_config(const char *var, const char *value)
554 /* This needs a better name */
555 if (!strcmp(var, "core.filemode")) {
556 trust_executable_bit = git_config_bool(var, value);
557 return 0;
559 if (!strcmp(var, "core.trustctime")) {
560 trust_ctime = git_config_bool(var, value);
561 return 0;
564 if (!strcmp(var, "core.quotepath")) {
565 quote_path_fully = git_config_bool(var, value);
566 return 0;
569 if (!strcmp(var, "core.symlinks")) {
570 has_symlinks = git_config_bool(var, value);
571 return 0;
574 if (!strcmp(var, "core.ignorecase")) {
575 ignore_case = git_config_bool(var, value);
576 return 0;
579 if (!strcmp(var, "core.attributesfile"))
580 return git_config_pathname(&git_attributes_file, var, value);
582 if (!strcmp(var, "core.bare")) {
583 is_bare_repository_cfg = git_config_bool(var, value);
584 return 0;
587 if (!strcmp(var, "core.ignorestat")) {
588 assume_unchanged = git_config_bool(var, value);
589 return 0;
592 if (!strcmp(var, "core.prefersymlinkrefs")) {
593 prefer_symlink_refs = git_config_bool(var, value);
594 return 0;
597 if (!strcmp(var, "core.logallrefupdates")) {
598 log_all_ref_updates = git_config_bool(var, value);
599 return 0;
602 if (!strcmp(var, "core.warnambiguousrefs")) {
603 warn_ambiguous_refs = git_config_bool(var, value);
604 return 0;
607 if (!strcmp(var, "core.abbrev")) {
608 int abbrev = git_config_int(var, value);
609 if (abbrev < minimum_abbrev || abbrev > 40)
610 return -1;
611 default_abbrev = abbrev;
612 return 0;
615 if (!strcmp(var, "core.loosecompression")) {
616 int level = git_config_int(var, value);
617 if (level == -1)
618 level = Z_DEFAULT_COMPRESSION;
619 else if (level < 0 || level > Z_BEST_COMPRESSION)
620 die("bad zlib compression level %d", level);
621 zlib_compression_level = level;
622 zlib_compression_seen = 1;
623 return 0;
626 if (!strcmp(var, "core.compression")) {
627 int level = git_config_int(var, value);
628 if (level == -1)
629 level = Z_DEFAULT_COMPRESSION;
630 else if (level < 0 || level > Z_BEST_COMPRESSION)
631 die("bad zlib compression level %d", level);
632 core_compression_level = level;
633 core_compression_seen = 1;
634 if (!zlib_compression_seen)
635 zlib_compression_level = level;
636 return 0;
639 if (!strcmp(var, "core.packedgitwindowsize")) {
640 int pgsz_x2 = getpagesize() * 2;
641 packed_git_window_size = git_config_ulong(var, value);
643 /* This value must be multiple of (pagesize * 2) */
644 packed_git_window_size /= pgsz_x2;
645 if (packed_git_window_size < 1)
646 packed_git_window_size = 1;
647 packed_git_window_size *= pgsz_x2;
648 return 0;
651 if (!strcmp(var, "core.bigfilethreshold")) {
652 big_file_threshold = git_config_ulong(var, value);
653 return 0;
656 if (!strcmp(var, "core.packedgitlimit")) {
657 packed_git_limit = git_config_ulong(var, value);
658 return 0;
661 if (!strcmp(var, "core.deltabasecachelimit")) {
662 delta_base_cache_limit = git_config_ulong(var, value);
663 return 0;
666 if (!strcmp(var, "core.logpackaccess"))
667 return git_config_string(&log_pack_access, var, value);
669 if (!strcmp(var, "core.autocrlf")) {
670 if (value && !strcasecmp(value, "input")) {
671 if (core_eol == EOL_CRLF)
672 return error("core.autocrlf=input conflicts with core.eol=crlf");
673 auto_crlf = AUTO_CRLF_INPUT;
674 return 0;
676 auto_crlf = git_config_bool(var, value);
677 return 0;
680 if (!strcmp(var, "core.safecrlf")) {
681 if (value && !strcasecmp(value, "warn")) {
682 safe_crlf = SAFE_CRLF_WARN;
683 return 0;
685 safe_crlf = git_config_bool(var, value);
686 return 0;
689 if (!strcmp(var, "core.eol")) {
690 if (value && !strcasecmp(value, "lf"))
691 core_eol = EOL_LF;
692 else if (value && !strcasecmp(value, "crlf"))
693 core_eol = EOL_CRLF;
694 else if (value && !strcasecmp(value, "native"))
695 core_eol = EOL_NATIVE;
696 else
697 core_eol = EOL_UNSET;
698 if (core_eol == EOL_CRLF && auto_crlf == AUTO_CRLF_INPUT)
699 return error("core.autocrlf=input conflicts with core.eol=crlf");
700 return 0;
703 if (!strcmp(var, "core.notesref")) {
704 notes_ref_name = xstrdup(value);
705 return 0;
708 if (!strcmp(var, "core.pager"))
709 return git_config_string(&pager_program, var, value);
711 if (!strcmp(var, "core.editor"))
712 return git_config_string(&editor_program, var, value);
714 if (!strcmp(var, "core.askpass"))
715 return git_config_string(&askpass_program, var, value);
717 if (!strcmp(var, "core.excludesfile"))
718 return git_config_pathname(&excludes_file, var, value);
720 if (!strcmp(var, "core.whitespace")) {
721 if (!value)
722 return config_error_nonbool(var);
723 whitespace_rule_cfg = parse_whitespace_rule(value);
724 return 0;
727 if (!strcmp(var, "core.fsyncobjectfiles")) {
728 fsync_object_files = git_config_bool(var, value);
729 return 0;
732 if (!strcmp(var, "core.preloadindex")) {
733 core_preload_index = git_config_bool(var, value);
734 return 0;
737 if (!strcmp(var, "core.createobject")) {
738 if (!strcmp(value, "rename"))
739 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
740 else if (!strcmp(value, "link"))
741 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
742 else
743 die("Invalid mode for object creation: %s", value);
744 return 0;
747 if (!strcmp(var, "core.sparsecheckout")) {
748 core_apply_sparse_checkout = git_config_bool(var, value);
749 return 0;
752 /* Add other config variables here and to Documentation/config.txt. */
753 return 0;
756 static int git_default_user_config(const char *var, const char *value)
758 if (!strcmp(var, "user.name")) {
759 if (!value)
760 return config_error_nonbool(var);
761 strlcpy(git_default_name, value, sizeof(git_default_name));
762 user_ident_explicitly_given |= IDENT_NAME_GIVEN;
763 return 0;
766 if (!strcmp(var, "user.email")) {
767 if (!value)
768 return config_error_nonbool(var);
769 strlcpy(git_default_email, value, sizeof(git_default_email));
770 user_ident_explicitly_given |= IDENT_MAIL_GIVEN;
771 return 0;
774 /* Add other config variables here and to Documentation/config.txt. */
775 return 0;
778 static int git_default_i18n_config(const char *var, const char *value)
780 if (!strcmp(var, "i18n.commitencoding"))
781 return git_config_string(&git_commit_encoding, var, value);
783 if (!strcmp(var, "i18n.logoutputencoding"))
784 return git_config_string(&git_log_output_encoding, var, value);
786 /* Add other config variables here and to Documentation/config.txt. */
787 return 0;
790 static int git_default_branch_config(const char *var, const char *value)
792 if (!strcmp(var, "branch.autosetupmerge")) {
793 if (value && !strcasecmp(value, "always")) {
794 git_branch_track = BRANCH_TRACK_ALWAYS;
795 return 0;
797 git_branch_track = git_config_bool(var, value);
798 return 0;
800 if (!strcmp(var, "branch.autosetuprebase")) {
801 if (!value)
802 return config_error_nonbool(var);
803 else if (!strcmp(value, "never"))
804 autorebase = AUTOREBASE_NEVER;
805 else if (!strcmp(value, "local"))
806 autorebase = AUTOREBASE_LOCAL;
807 else if (!strcmp(value, "remote"))
808 autorebase = AUTOREBASE_REMOTE;
809 else if (!strcmp(value, "always"))
810 autorebase = AUTOREBASE_ALWAYS;
811 else
812 return error("Malformed value for %s", var);
813 return 0;
816 /* Add other config variables here and to Documentation/config.txt. */
817 return 0;
820 static int git_default_push_config(const char *var, const char *value)
822 if (!strcmp(var, "push.default")) {
823 if (!value)
824 return config_error_nonbool(var);
825 else if (!strcmp(value, "nothing"))
826 push_default = PUSH_DEFAULT_NOTHING;
827 else if (!strcmp(value, "matching"))
828 push_default = PUSH_DEFAULT_MATCHING;
829 else if (!strcmp(value, "upstream"))
830 push_default = PUSH_DEFAULT_UPSTREAM;
831 else if (!strcmp(value, "tracking")) /* deprecated */
832 push_default = PUSH_DEFAULT_UPSTREAM;
833 else if (!strcmp(value, "current"))
834 push_default = PUSH_DEFAULT_CURRENT;
835 else {
836 error("Malformed value for %s: %s", var, value);
837 return error("Must be one of nothing, matching, "
838 "tracking or current.");
840 return 0;
843 /* Add other config variables here and to Documentation/config.txt. */
844 return 0;
847 static int git_default_mailmap_config(const char *var, const char *value)
849 if (!strcmp(var, "mailmap.file"))
850 return git_config_string(&git_mailmap_file, var, value);
852 /* Add other config variables here and to Documentation/config.txt. */
853 return 0;
856 int git_default_config(const char *var, const char *value, void *dummy)
858 if (!prefixcmp(var, "core."))
859 return git_default_core_config(var, value);
861 if (!prefixcmp(var, "user."))
862 return git_default_user_config(var, value);
864 if (!prefixcmp(var, "i18n."))
865 return git_default_i18n_config(var, value);
867 if (!prefixcmp(var, "branch."))
868 return git_default_branch_config(var, value);
870 if (!prefixcmp(var, "push."))
871 return git_default_push_config(var, value);
873 if (!prefixcmp(var, "mailmap."))
874 return git_default_mailmap_config(var, value);
876 if (!prefixcmp(var, "advice."))
877 return git_default_advice_config(var, value);
879 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
880 pager_use_color = git_config_bool(var,value);
881 return 0;
884 if (!strcmp(var, "pack.packsizelimit")) {
885 pack_size_limit_cfg = git_config_ulong(var, value);
886 return 0;
888 /* Add other config variables here and to Documentation/config.txt. */
889 return 0;
892 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
894 int ret;
895 FILE *f = fopen(filename, "r");
897 ret = -1;
898 if (f) {
899 config_file top;
901 /* push config-file parsing state stack */
902 top.prev = cf;
903 top.f = f;
904 top.name = filename;
905 top.linenr = 1;
906 top.eof = 0;
907 strbuf_init(&top.value, 1024);
908 cf = &top;
910 ret = git_parse_file(fn, data);
912 /* pop config-file parsing state stack */
913 strbuf_release(&top.value);
914 cf = top.prev;
916 fclose(f);
918 return ret;
921 const char *git_etc_gitconfig(void)
923 static const char *system_wide;
924 if (!system_wide)
925 system_wide = system_path(ETC_GITCONFIG);
926 return system_wide;
929 int git_env_bool(const char *k, int def)
931 const char *v = getenv(k);
932 return v ? git_config_bool(k, v) : def;
935 int git_config_system(void)
937 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
940 int git_config_early(config_fn_t fn, void *data, const char *repo_config)
942 int ret = 0, found = 0;
943 const char *home = NULL;
945 /* Setting $GIT_CONFIG makes git read _only_ the given config file. */
946 if (config_exclusive_filename)
947 return git_config_from_file(fn, config_exclusive_filename, data);
948 if (git_config_system() && !access(git_etc_gitconfig(), R_OK)) {
949 ret += git_config_from_file(fn, git_etc_gitconfig(),
950 data);
951 found += 1;
954 home = getenv("HOME");
955 if (home) {
956 char buf[PATH_MAX];
957 char *user_config = mksnpath(buf, sizeof(buf), "%s/.gitconfig", home);
958 if (!access(user_config, R_OK)) {
959 ret += git_config_from_file(fn, user_config, data);
960 found += 1;
964 if (repo_config && !access(repo_config, R_OK)) {
965 ret += git_config_from_file(fn, repo_config, data);
966 found += 1;
969 switch (git_config_from_parameters(fn, data)) {
970 case -1: /* error */
971 die("unable to parse command-line config");
972 break;
973 case 0: /* found nothing */
974 break;
975 default: /* found at least one item */
976 found++;
977 break;
980 return ret == 0 ? found : ret;
983 int git_config(config_fn_t fn, void *data)
985 char *repo_config = NULL;
986 int ret;
987 struct config_include_data inc = CONFIG_INCLUDE_INIT;
989 inc.fn = fn;
990 inc.data = data;
992 repo_config = git_pathdup("config");
993 ret = git_config_early(git_config_include, &inc, repo_config);
994 if (repo_config)
995 free(repo_config);
996 return ret;
1000 * Find all the stuff for git_config_set() below.
1003 #define MAX_MATCHES 512
1005 static struct {
1006 int baselen;
1007 char *key;
1008 int do_not_match;
1009 regex_t *value_regex;
1010 int multi_replace;
1011 size_t offset[MAX_MATCHES];
1012 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
1013 int seen;
1014 } store;
1016 static int matches(const char *key, const char *value)
1018 return !strcmp(key, store.key) &&
1019 (store.value_regex == NULL ||
1020 (store.do_not_match ^
1021 !regexec(store.value_regex, value, 0, NULL, 0)));
1024 static int store_aux(const char *key, const char *value, void *cb)
1026 const char *ep;
1027 size_t section_len;
1028 FILE *f = cf->f;
1030 switch (store.state) {
1031 case KEY_SEEN:
1032 if (matches(key, value)) {
1033 if (store.seen == 1 && store.multi_replace == 0) {
1034 warning("%s has multiple values", key);
1035 } else if (store.seen >= MAX_MATCHES) {
1036 error("too many matches for %s", key);
1037 return 1;
1040 store.offset[store.seen] = ftell(f);
1041 store.seen++;
1043 break;
1044 case SECTION_SEEN:
1046 * What we are looking for is in store.key (both
1047 * section and var), and its section part is baselen
1048 * long. We found key (again, both section and var).
1049 * We would want to know if this key is in the same
1050 * section as what we are looking for. We already
1051 * know we are in the same section as what should
1052 * hold store.key.
1054 ep = strrchr(key, '.');
1055 section_len = ep - key;
1057 if ((section_len != store.baselen) ||
1058 memcmp(key, store.key, section_len+1)) {
1059 store.state = SECTION_END_SEEN;
1060 break;
1064 * Do not increment matches: this is no match, but we
1065 * just made sure we are in the desired section.
1067 store.offset[store.seen] = ftell(f);
1068 /* fallthru */
1069 case SECTION_END_SEEN:
1070 case START:
1071 if (matches(key, value)) {
1072 store.offset[store.seen] = ftell(f);
1073 store.state = KEY_SEEN;
1074 store.seen++;
1075 } else {
1076 if (strrchr(key, '.') - key == store.baselen &&
1077 !strncmp(key, store.key, store.baselen)) {
1078 store.state = SECTION_SEEN;
1079 store.offset[store.seen] = ftell(f);
1083 return 0;
1086 static int write_error(const char *filename)
1088 error("failed to write new configuration file %s", filename);
1090 /* Same error code as "failed to rename". */
1091 return 4;
1094 static int store_write_section(int fd, const char *key)
1096 const char *dot;
1097 int i, success;
1098 struct strbuf sb = STRBUF_INIT;
1100 dot = memchr(key, '.', store.baselen);
1101 if (dot) {
1102 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
1103 for (i = dot - key + 1; i < store.baselen; i++) {
1104 if (key[i] == '"' || key[i] == '\\')
1105 strbuf_addch(&sb, '\\');
1106 strbuf_addch(&sb, key[i]);
1108 strbuf_addstr(&sb, "\"]\n");
1109 } else {
1110 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
1113 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1114 strbuf_release(&sb);
1116 return success;
1119 static int store_write_pair(int fd, const char *key, const char *value)
1121 int i, success;
1122 int length = strlen(key + store.baselen + 1);
1123 const char *quote = "";
1124 struct strbuf sb = STRBUF_INIT;
1127 * Check to see if the value needs to be surrounded with a dq pair.
1128 * Note that problematic characters are always backslash-quoted; this
1129 * check is about not losing leading or trailing SP and strings that
1130 * follow beginning-of-comment characters (i.e. ';' and '#') by the
1131 * configuration parser.
1133 if (value[0] == ' ')
1134 quote = "\"";
1135 for (i = 0; value[i]; i++)
1136 if (value[i] == ';' || value[i] == '#')
1137 quote = "\"";
1138 if (i && value[i - 1] == ' ')
1139 quote = "\"";
1141 strbuf_addf(&sb, "\t%.*s = %s",
1142 length, key + store.baselen + 1, quote);
1144 for (i = 0; value[i]; i++)
1145 switch (value[i]) {
1146 case '\n':
1147 strbuf_addstr(&sb, "\\n");
1148 break;
1149 case '\t':
1150 strbuf_addstr(&sb, "\\t");
1151 break;
1152 case '"':
1153 case '\\':
1154 strbuf_addch(&sb, '\\');
1155 default:
1156 strbuf_addch(&sb, value[i]);
1157 break;
1159 strbuf_addf(&sb, "%s\n", quote);
1161 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1162 strbuf_release(&sb);
1164 return success;
1167 static ssize_t find_beginning_of_line(const char *contents, size_t size,
1168 size_t offset_, int *found_bracket)
1170 size_t equal_offset = size, bracket_offset = size;
1171 ssize_t offset;
1173 contline:
1174 for (offset = offset_-2; offset > 0
1175 && contents[offset] != '\n'; offset--)
1176 switch (contents[offset]) {
1177 case '=': equal_offset = offset; break;
1178 case ']': bracket_offset = offset; break;
1180 if (offset > 0 && contents[offset-1] == '\\') {
1181 offset_ = offset;
1182 goto contline;
1184 if (bracket_offset < equal_offset) {
1185 *found_bracket = 1;
1186 offset = bracket_offset+1;
1187 } else
1188 offset++;
1190 return offset;
1193 int git_config_set_in_file(const char *config_filename,
1194 const char *key, const char *value)
1196 return git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
1199 int git_config_set(const char *key, const char *value)
1201 return git_config_set_multivar(key, value, NULL, 0);
1205 * Auxiliary function to sanity-check and split the key into the section
1206 * identifier and variable name.
1208 * Returns 0 on success, -1 when there is an invalid character in the key and
1209 * -2 if there is no section name in the key.
1211 * store_key - pointer to char* which will hold a copy of the key with
1212 * lowercase section and variable name
1213 * baselen - pointer to int which will hold the length of the
1214 * section + subsection part, can be NULL
1216 int git_config_parse_key(const char *key, char **store_key, int *baselen_)
1218 int i, dot, baselen;
1219 const char *last_dot = strrchr(key, '.');
1222 * Since "key" actually contains the section name and the real
1223 * key name separated by a dot, we have to know where the dot is.
1226 if (last_dot == NULL || last_dot == key) {
1227 error("key does not contain a section: %s", key);
1228 return -CONFIG_NO_SECTION_OR_NAME;
1231 if (!last_dot[1]) {
1232 error("key does not contain variable name: %s", key);
1233 return -CONFIG_NO_SECTION_OR_NAME;
1236 baselen = last_dot - key;
1237 if (baselen_)
1238 *baselen_ = baselen;
1241 * Validate the key and while at it, lower case it for matching.
1243 *store_key = xmalloc(strlen(key) + 1);
1245 dot = 0;
1246 for (i = 0; key[i]; i++) {
1247 unsigned char c = key[i];
1248 if (c == '.')
1249 dot = 1;
1250 /* Leave the extended basename untouched.. */
1251 if (!dot || i > baselen) {
1252 if (!iskeychar(c) ||
1253 (i == baselen + 1 && !isalpha(c))) {
1254 error("invalid key: %s", key);
1255 goto out_free_ret_1;
1257 c = tolower(c);
1258 } else if (c == '\n') {
1259 error("invalid key (newline): %s", key);
1260 goto out_free_ret_1;
1262 (*store_key)[i] = c;
1264 (*store_key)[i] = 0;
1266 return 0;
1268 out_free_ret_1:
1269 free(*store_key);
1270 return -CONFIG_INVALID_KEY;
1274 * If value==NULL, unset in (remove from) config,
1275 * if value_regex!=NULL, disregard key/value pairs where value does not match.
1276 * if multi_replace==0, nothing, or only one matching key/value is replaced,
1277 * else all matching key/values (regardless how many) are removed,
1278 * before the new pair is written.
1280 * Returns 0 on success.
1282 * This function does this:
1284 * - it locks the config file by creating ".git/config.lock"
1286 * - it then parses the config using store_aux() as validator to find
1287 * the position on the key/value pair to replace. If it is to be unset,
1288 * it must be found exactly once.
1290 * - the config file is mmap()ed and the part before the match (if any) is
1291 * written to the lock file, then the changed part and the rest.
1293 * - the config file is removed and the lock file rename()d to it.
1296 int git_config_set_multivar_in_file(const char *config_filename,
1297 const char *key, const char *value,
1298 const char *value_regex, int multi_replace)
1300 int fd = -1, in_fd;
1301 int ret;
1302 struct lock_file *lock = NULL;
1304 /* parse-key returns negative; flip the sign to feed exit(3) */
1305 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
1306 if (ret)
1307 goto out_free;
1309 store.multi_replace = multi_replace;
1313 * The lock serves a purpose in addition to locking: the new
1314 * contents of .git/config will be written into it.
1316 lock = xcalloc(sizeof(struct lock_file), 1);
1317 fd = hold_lock_file_for_update(lock, config_filename, 0);
1318 if (fd < 0) {
1319 error("could not lock config file %s: %s", config_filename, strerror(errno));
1320 free(store.key);
1321 ret = CONFIG_NO_LOCK;
1322 goto out_free;
1326 * If .git/config does not exist yet, write a minimal version.
1328 in_fd = open(config_filename, O_RDONLY);
1329 if ( in_fd < 0 ) {
1330 free(store.key);
1332 if ( ENOENT != errno ) {
1333 error("opening %s: %s", config_filename,
1334 strerror(errno));
1335 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
1336 goto out_free;
1338 /* if nothing to unset, error out */
1339 if (value == NULL) {
1340 ret = CONFIG_NOTHING_SET;
1341 goto out_free;
1344 store.key = (char *)key;
1345 if (!store_write_section(fd, key) ||
1346 !store_write_pair(fd, key, value))
1347 goto write_err_out;
1348 } else {
1349 struct stat st;
1350 char *contents;
1351 size_t contents_sz, copy_begin, copy_end;
1352 int i, new_line = 0;
1354 if (value_regex == NULL)
1355 store.value_regex = NULL;
1356 else {
1357 if (value_regex[0] == '!') {
1358 store.do_not_match = 1;
1359 value_regex++;
1360 } else
1361 store.do_not_match = 0;
1363 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1364 if (regcomp(store.value_regex, value_regex,
1365 REG_EXTENDED)) {
1366 error("invalid pattern: %s", value_regex);
1367 free(store.value_regex);
1368 ret = CONFIG_INVALID_PATTERN;
1369 goto out_free;
1373 store.offset[0] = 0;
1374 store.state = START;
1375 store.seen = 0;
1378 * After this, store.offset will contain the *end* offset
1379 * of the last match, or remain at 0 if no match was found.
1380 * As a side effect, we make sure to transform only a valid
1381 * existing config file.
1383 if (git_config_from_file(store_aux, config_filename, NULL)) {
1384 error("invalid config file %s", config_filename);
1385 free(store.key);
1386 if (store.value_regex != NULL) {
1387 regfree(store.value_regex);
1388 free(store.value_regex);
1390 ret = CONFIG_INVALID_FILE;
1391 goto out_free;
1394 free(store.key);
1395 if (store.value_regex != NULL) {
1396 regfree(store.value_regex);
1397 free(store.value_regex);
1400 /* if nothing to unset, or too many matches, error out */
1401 if ((store.seen == 0 && value == NULL) ||
1402 (store.seen > 1 && multi_replace == 0)) {
1403 ret = CONFIG_NOTHING_SET;
1404 goto out_free;
1407 fstat(in_fd, &st);
1408 contents_sz = xsize_t(st.st_size);
1409 contents = xmmap(NULL, contents_sz, PROT_READ,
1410 MAP_PRIVATE, in_fd, 0);
1411 close(in_fd);
1413 if (store.seen == 0)
1414 store.seen = 1;
1416 for (i = 0, copy_begin = 0; i < store.seen; i++) {
1417 if (store.offset[i] == 0) {
1418 store.offset[i] = copy_end = contents_sz;
1419 } else if (store.state != KEY_SEEN) {
1420 copy_end = store.offset[i];
1421 } else
1422 copy_end = find_beginning_of_line(
1423 contents, contents_sz,
1424 store.offset[i]-2, &new_line);
1426 if (copy_end > 0 && contents[copy_end-1] != '\n')
1427 new_line = 1;
1429 /* write the first part of the config */
1430 if (copy_end > copy_begin) {
1431 if (write_in_full(fd, contents + copy_begin,
1432 copy_end - copy_begin) <
1433 copy_end - copy_begin)
1434 goto write_err_out;
1435 if (new_line &&
1436 write_str_in_full(fd, "\n") != 1)
1437 goto write_err_out;
1439 copy_begin = store.offset[i];
1442 /* write the pair (value == NULL means unset) */
1443 if (value != NULL) {
1444 if (store.state == START) {
1445 if (!store_write_section(fd, key))
1446 goto write_err_out;
1448 if (!store_write_pair(fd, key, value))
1449 goto write_err_out;
1452 /* write the rest of the config */
1453 if (copy_begin < contents_sz)
1454 if (write_in_full(fd, contents + copy_begin,
1455 contents_sz - copy_begin) <
1456 contents_sz - copy_begin)
1457 goto write_err_out;
1459 munmap(contents, contents_sz);
1462 if (commit_lock_file(lock) < 0) {
1463 error("could not commit config file %s", config_filename);
1464 ret = CONFIG_NO_WRITE;
1465 goto out_free;
1469 * lock is committed, so don't try to roll it back below.
1470 * NOTE: Since lockfile.c keeps a linked list of all created
1471 * lock_file structures, it isn't safe to free(lock). It's
1472 * better to just leave it hanging around.
1474 lock = NULL;
1475 ret = 0;
1477 out_free:
1478 if (lock)
1479 rollback_lock_file(lock);
1480 return ret;
1482 write_err_out:
1483 ret = write_error(lock->filename);
1484 goto out_free;
1488 int git_config_set_multivar(const char *key, const char *value,
1489 const char *value_regex, int multi_replace)
1491 const char *config_filename;
1492 char *buf = NULL;
1493 int ret;
1495 if (config_exclusive_filename)
1496 config_filename = config_exclusive_filename;
1497 else
1498 config_filename = buf = git_pathdup("config");
1500 ret = git_config_set_multivar_in_file(config_filename, key, value,
1501 value_regex, multi_replace);
1502 free(buf);
1503 return ret;
1506 static int section_name_match (const char *buf, const char *name)
1508 int i = 0, j = 0, dot = 0;
1509 if (buf[i] != '[')
1510 return 0;
1511 for (i = 1; buf[i] && buf[i] != ']'; i++) {
1512 if (!dot && isspace(buf[i])) {
1513 dot = 1;
1514 if (name[j++] != '.')
1515 break;
1516 for (i++; isspace(buf[i]); i++)
1517 ; /* do nothing */
1518 if (buf[i] != '"')
1519 break;
1520 continue;
1522 if (buf[i] == '\\' && dot)
1523 i++;
1524 else if (buf[i] == '"' && dot) {
1525 for (i++; isspace(buf[i]); i++)
1526 ; /* do_nothing */
1527 break;
1529 if (buf[i] != name[j++])
1530 break;
1532 if (buf[i] == ']' && name[j] == 0) {
1534 * We match, now just find the right length offset by
1535 * gobbling up any whitespace after it, as well
1537 i++;
1538 for (; buf[i] && isspace(buf[i]); i++)
1539 ; /* do nothing */
1540 return i;
1542 return 0;
1545 /* if new_name == NULL, the section is removed instead */
1546 int git_config_rename_section(const char *old_name, const char *new_name)
1548 int ret = 0, remove = 0;
1549 char *config_filename;
1550 struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1551 int out_fd;
1552 char buf[1024];
1553 FILE *config_file;
1555 if (config_exclusive_filename)
1556 config_filename = xstrdup(config_exclusive_filename);
1557 else
1558 config_filename = git_pathdup("config");
1559 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1560 if (out_fd < 0) {
1561 ret = error("could not lock config file %s", config_filename);
1562 goto out;
1565 if (!(config_file = fopen(config_filename, "rb"))) {
1566 /* no config file means nothing to rename, no error */
1567 goto unlock_and_out;
1570 while (fgets(buf, sizeof(buf), config_file)) {
1571 int i;
1572 int length;
1573 char *output = buf;
1574 for (i = 0; buf[i] && isspace(buf[i]); i++)
1575 ; /* do nothing */
1576 if (buf[i] == '[') {
1577 /* it's a section */
1578 int offset = section_name_match(&buf[i], old_name);
1579 if (offset > 0) {
1580 ret++;
1581 if (new_name == NULL) {
1582 remove = 1;
1583 continue;
1585 store.baselen = strlen(new_name);
1586 if (!store_write_section(out_fd, new_name)) {
1587 ret = write_error(lock->filename);
1588 goto out;
1591 * We wrote out the new section, with
1592 * a newline, now skip the old
1593 * section's length
1595 output += offset + i;
1596 if (strlen(output) > 0) {
1598 * More content means there's
1599 * a declaration to put on the
1600 * next line; indent with a
1601 * tab
1603 output -= 1;
1604 output[0] = '\t';
1607 remove = 0;
1609 if (remove)
1610 continue;
1611 length = strlen(output);
1612 if (write_in_full(out_fd, output, length) != length) {
1613 ret = write_error(lock->filename);
1614 goto out;
1617 fclose(config_file);
1618 unlock_and_out:
1619 if (commit_lock_file(lock) < 0)
1620 ret = error("could not commit config file %s", config_filename);
1621 out:
1622 free(config_filename);
1623 return ret;
1627 * Call this to report error for your variable that should not
1628 * get a boolean value (i.e. "[my] var" means "true").
1630 int config_error_nonbool(const char *var)
1632 return error("Missing value for '%s'", var);