Merge branch 'jk/gc-pre-detach-under-hook' into maint
[git] / config.c
1 /*
2  * GIT - The information manager from hell
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  * Copyright (C) Johannes Schindelin, 2005
6  *
7  */
8 #include "cache.h"
9 #include "lockfile.h"
10 #include "exec_cmd.h"
11 #include "strbuf.h"
12 #include "quote.h"
13 #include "hashmap.h"
14 #include "string-list.h"
15 #include "utf8.h"
16 #include "dir.h"
17
18 struct config_source {
19         struct config_source *prev;
20         union {
21                 FILE *file;
22                 struct config_buf {
23                         const char *buf;
24                         size_t len;
25                         size_t pos;
26                 } buf;
27         } u;
28         enum config_origin_type origin_type;
29         const char *name;
30         const char *path;
31         int die_on_error;
32         int linenr;
33         int eof;
34         struct strbuf value;
35         struct strbuf var;
36
37         int (*do_fgetc)(struct config_source *c);
38         int (*do_ungetc)(int c, struct config_source *conf);
39         long (*do_ftell)(struct config_source *c);
40 };
41
42 /*
43  * These variables record the "current" config source, which
44  * can be accessed by parsing callbacks.
45  *
46  * The "cf" variable will be non-NULL only when we are actually parsing a real
47  * config source (file, blob, cmdline, etc).
48  *
49  * The "current_config_kvi" variable will be non-NULL only when we are feeding
50  * cached config from a configset into a callback.
51  *
52  * They should generally never be non-NULL at the same time. If they are both
53  * NULL, then we aren't parsing anything (and depending on the function looking
54  * at the variables, it's either a bug for it to be called in the first place,
55  * or it's a function which can be reused for non-config purposes, and should
56  * fall back to some sane behavior).
57  */
58 static struct config_source *cf;
59 static struct key_value_info *current_config_kvi;
60
61 /*
62  * Similar to the variables above, this gives access to the "scope" of the
63  * current value (repo, global, etc). For cached values, it can be found via
64  * the current_config_kvi as above. During parsing, the current value can be
65  * found in this variable. It's not part of "cf" because it transcends a single
66  * file (i.e., a file included from .git/config is still in "repo" scope).
67  */
68 static enum config_scope current_parsing_scope;
69
70 static int core_compression_seen;
71 static int pack_compression_seen;
72 static int zlib_compression_seen;
73
74 /*
75  * Default config_set that contains key-value pairs from the usual set of config
76  * config files (i.e repo specific .git/config, user wide ~/.gitconfig, XDG
77  * config file and the global /etc/gitconfig)
78  */
79 static struct config_set the_config_set;
80
81 static int config_file_fgetc(struct config_source *conf)
82 {
83         return getc_unlocked(conf->u.file);
84 }
85
86 static int config_file_ungetc(int c, struct config_source *conf)
87 {
88         return ungetc(c, conf->u.file);
89 }
90
91 static long config_file_ftell(struct config_source *conf)
92 {
93         return ftell(conf->u.file);
94 }
95
96
97 static int config_buf_fgetc(struct config_source *conf)
98 {
99         if (conf->u.buf.pos < conf->u.buf.len)
100                 return conf->u.buf.buf[conf->u.buf.pos++];
101
102         return EOF;
103 }
104
105 static int config_buf_ungetc(int c, struct config_source *conf)
106 {
107         if (conf->u.buf.pos > 0) {
108                 conf->u.buf.pos--;
109                 if (conf->u.buf.buf[conf->u.buf.pos] != c)
110                         die("BUG: config_buf can only ungetc the same character");
111                 return c;
112         }
113
114         return EOF;
115 }
116
117 static long config_buf_ftell(struct config_source *conf)
118 {
119         return conf->u.buf.pos;
120 }
121
122 #define MAX_INCLUDE_DEPTH 10
123 static const char include_depth_advice[] =
124 "exceeded maximum include depth (%d) while including\n"
125 "       %s\n"
126 "from\n"
127 "       %s\n"
128 "Do you have circular includes?";
129 static int handle_path_include(const char *path, struct config_include_data *inc)
130 {
131         int ret = 0;
132         struct strbuf buf = STRBUF_INIT;
133         char *expanded;
134
135         if (!path)
136                 return config_error_nonbool("include.path");
137
138         expanded = expand_user_path(path, 0);
139         if (!expanded)
140                 return error("could not expand include path '%s'", path);
141         path = expanded;
142
143         /*
144          * Use an absolute path as-is, but interpret relative paths
145          * based on the including config file.
146          */
147         if (!is_absolute_path(path)) {
148                 char *slash;
149
150                 if (!cf || !cf->path)
151                         return error("relative config includes must come from files");
152
153                 slash = find_last_dir_sep(cf->path);
154                 if (slash)
155                         strbuf_add(&buf, cf->path, slash - cf->path + 1);
156                 strbuf_addstr(&buf, path);
157                 path = buf.buf;
158         }
159
160         if (!access_or_die(path, R_OK, 0)) {
161                 if (++inc->depth > MAX_INCLUDE_DEPTH)
162                         die(include_depth_advice, MAX_INCLUDE_DEPTH, path,
163                             !cf ? "<unknown>" :
164                             cf->name ? cf->name :
165                             "the command line");
166                 ret = git_config_from_file(git_config_include, path, inc);
167                 inc->depth--;
168         }
169         strbuf_release(&buf);
170         free(expanded);
171         return ret;
172 }
173
174 static int prepare_include_condition_pattern(struct strbuf *pat)
175 {
176         struct strbuf path = STRBUF_INIT;
177         char *expanded;
178         int prefix = 0;
179
180         expanded = expand_user_path(pat->buf, 1);
181         if (expanded) {
182                 strbuf_reset(pat);
183                 strbuf_addstr(pat, expanded);
184                 free(expanded);
185         }
186
187         if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
188                 const char *slash;
189
190                 if (!cf || !cf->path)
191                         return error(_("relative config include "
192                                        "conditionals must come from files"));
193
194                 strbuf_realpath(&path, cf->path, 1);
195                 slash = find_last_dir_sep(path.buf);
196                 if (!slash)
197                         die("BUG: how is this possible?");
198                 strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
199                 prefix = slash - path.buf + 1 /* slash */;
200         } else if (!is_absolute_path(pat->buf))
201                 strbuf_insert(pat, 0, "**/", 3);
202
203         if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
204                 strbuf_addstr(pat, "**");
205
206         strbuf_release(&path);
207         return prefix;
208 }
209
210 static int include_by_gitdir(const struct config_options *opts,
211                              const char *cond, size_t cond_len, int icase)
212 {
213         struct strbuf text = STRBUF_INIT;
214         struct strbuf pattern = STRBUF_INIT;
215         int ret = 0, prefix;
216         const char *git_dir;
217
218         if (opts->git_dir)
219                 git_dir = opts->git_dir;
220         else if (have_git_dir())
221                 git_dir = get_git_dir();
222         else
223                 goto done;
224
225         strbuf_realpath(&text, git_dir, 1);
226         strbuf_add(&pattern, cond, cond_len);
227         prefix = prepare_include_condition_pattern(&pattern);
228
229         if (prefix < 0)
230                 goto done;
231
232         if (prefix > 0) {
233                 /*
234                  * perform literal matching on the prefix part so that
235                  * any wildcard character in it can't create side effects.
236                  */
237                 if (text.len < prefix)
238                         goto done;
239                 if (!icase && strncmp(pattern.buf, text.buf, prefix))
240                         goto done;
241                 if (icase && strncasecmp(pattern.buf, text.buf, prefix))
242                         goto done;
243         }
244
245         ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
246                          icase ? WM_CASEFOLD : 0, NULL);
247
248 done:
249         strbuf_release(&pattern);
250         strbuf_release(&text);
251         return ret;
252 }
253
254 static int include_condition_is_true(const struct config_options *opts,
255                                      const char *cond, size_t cond_len)
256 {
257
258         if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
259                 return include_by_gitdir(opts, cond, cond_len, 0);
260         else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
261                 return include_by_gitdir(opts, cond, cond_len, 1);
262
263         /* unknown conditionals are always false */
264         return 0;
265 }
266
267 int git_config_include(const char *var, const char *value, void *data)
268 {
269         struct config_include_data *inc = data;
270         const char *cond, *key;
271         int cond_len;
272         int ret;
273
274         /*
275          * Pass along all values, including "include" directives; this makes it
276          * possible to query information on the includes themselves.
277          */
278         ret = inc->fn(var, value, inc->data);
279         if (ret < 0)
280                 return ret;
281
282         if (!strcmp(var, "include.path"))
283                 ret = handle_path_include(value, inc);
284
285         if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
286             (cond && include_condition_is_true(inc->opts, cond, cond_len)) &&
287             !strcmp(key, "path"))
288                 ret = handle_path_include(value, inc);
289
290         return ret;
291 }
292
293 void git_config_push_parameter(const char *text)
294 {
295         struct strbuf env = STRBUF_INIT;
296         const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
297         if (old && *old) {
298                 strbuf_addstr(&env, old);
299                 strbuf_addch(&env, ' ');
300         }
301         sq_quote_buf(&env, text);
302         setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
303         strbuf_release(&env);
304 }
305
306 static inline int iskeychar(int c)
307 {
308         return isalnum(c) || c == '-';
309 }
310
311 /*
312  * Auxiliary function to sanity-check and split the key into the section
313  * identifier and variable name.
314  *
315  * Returns 0 on success, -1 when there is an invalid character in the key and
316  * -2 if there is no section name in the key.
317  *
318  * store_key - pointer to char* which will hold a copy of the key with
319  *             lowercase section and variable name
320  * baselen - pointer to int which will hold the length of the
321  *           section + subsection part, can be NULL
322  */
323 static int git_config_parse_key_1(const char *key, char **store_key, int *baselen_, int quiet)
324 {
325         int i, dot, baselen;
326         const char *last_dot = strrchr(key, '.');
327
328         /*
329          * Since "key" actually contains the section name and the real
330          * key name separated by a dot, we have to know where the dot is.
331          */
332
333         if (last_dot == NULL || last_dot == key) {
334                 if (!quiet)
335                         error("key does not contain a section: %s", key);
336                 return -CONFIG_NO_SECTION_OR_NAME;
337         }
338
339         if (!last_dot[1]) {
340                 if (!quiet)
341                         error("key does not contain variable name: %s", key);
342                 return -CONFIG_NO_SECTION_OR_NAME;
343         }
344
345         baselen = last_dot - key;
346         if (baselen_)
347                 *baselen_ = baselen;
348
349         /*
350          * Validate the key and while at it, lower case it for matching.
351          */
352         if (store_key)
353                 *store_key = xmallocz(strlen(key));
354
355         dot = 0;
356         for (i = 0; key[i]; i++) {
357                 unsigned char c = key[i];
358                 if (c == '.')
359                         dot = 1;
360                 /* Leave the extended basename untouched.. */
361                 if (!dot || i > baselen) {
362                         if (!iskeychar(c) ||
363                             (i == baselen + 1 && !isalpha(c))) {
364                                 if (!quiet)
365                                         error("invalid key: %s", key);
366                                 goto out_free_ret_1;
367                         }
368                         c = tolower(c);
369                 } else if (c == '\n') {
370                         if (!quiet)
371                                 error("invalid key (newline): %s", key);
372                         goto out_free_ret_1;
373                 }
374                 if (store_key)
375                         (*store_key)[i] = c;
376         }
377
378         return 0;
379
380 out_free_ret_1:
381         if (store_key) {
382                 free(*store_key);
383                 *store_key = NULL;
384         }
385         return -CONFIG_INVALID_KEY;
386 }
387
388 int git_config_parse_key(const char *key, char **store_key, int *baselen)
389 {
390         return git_config_parse_key_1(key, store_key, baselen, 0);
391 }
392
393 int git_config_key_is_valid(const char *key)
394 {
395         return !git_config_parse_key_1(key, NULL, NULL, 1);
396 }
397
398 int git_config_parse_parameter(const char *text,
399                                config_fn_t fn, void *data)
400 {
401         const char *value;
402         char *canonical_name;
403         struct strbuf **pair;
404         int ret;
405
406         pair = strbuf_split_str(text, '=', 2);
407         if (!pair[0])
408                 return error("bogus config parameter: %s", text);
409
410         if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
411                 strbuf_setlen(pair[0], pair[0]->len - 1);
412                 value = pair[1] ? pair[1]->buf : "";
413         } else {
414                 value = NULL;
415         }
416
417         strbuf_trim(pair[0]);
418         if (!pair[0]->len) {
419                 strbuf_list_free(pair);
420                 return error("bogus config parameter: %s", text);
421         }
422
423         if (git_config_parse_key(pair[0]->buf, &canonical_name, NULL)) {
424                 ret = -1;
425         } else {
426                 ret = (fn(canonical_name, value, data) < 0) ? -1 : 0;
427                 free(canonical_name);
428         }
429         strbuf_list_free(pair);
430         return ret;
431 }
432
433 int git_config_from_parameters(config_fn_t fn, void *data)
434 {
435         const char *env = getenv(CONFIG_DATA_ENVIRONMENT);
436         int ret = 0;
437         char *envw;
438         const char **argv = NULL;
439         int nr = 0, alloc = 0;
440         int i;
441         struct config_source source;
442
443         if (!env)
444                 return 0;
445
446         memset(&source, 0, sizeof(source));
447         source.prev = cf;
448         source.origin_type = CONFIG_ORIGIN_CMDLINE;
449         cf = &source;
450
451         /* sq_dequote will write over it */
452         envw = xstrdup(env);
453
454         if (sq_dequote_to_argv(envw, &argv, &nr, &alloc) < 0) {
455                 ret = error("bogus format in " CONFIG_DATA_ENVIRONMENT);
456                 goto out;
457         }
458
459         for (i = 0; i < nr; i++) {
460                 if (git_config_parse_parameter(argv[i], fn, data) < 0) {
461                         ret = -1;
462                         goto out;
463                 }
464         }
465
466 out:
467         free(argv);
468         free(envw);
469         cf = source.prev;
470         return ret;
471 }
472
473 static int get_next_char(void)
474 {
475         int c = cf->do_fgetc(cf);
476
477         if (c == '\r') {
478                 /* DOS like systems */
479                 c = cf->do_fgetc(cf);
480                 if (c != '\n') {
481                         if (c != EOF)
482                                 cf->do_ungetc(c, cf);
483                         c = '\r';
484                 }
485         }
486         if (c == '\n')
487                 cf->linenr++;
488         if (c == EOF) {
489                 cf->eof = 1;
490                 cf->linenr++;
491                 c = '\n';
492         }
493         return c;
494 }
495
496 static char *parse_value(void)
497 {
498         int quote = 0, comment = 0, space = 0;
499
500         strbuf_reset(&cf->value);
501         for (;;) {
502                 int c = get_next_char();
503                 if (c == '\n') {
504                         if (quote) {
505                                 cf->linenr--;
506                                 return NULL;
507                         }
508                         return cf->value.buf;
509                 }
510                 if (comment)
511                         continue;
512                 if (isspace(c) && !quote) {
513                         if (cf->value.len)
514                                 space++;
515                         continue;
516                 }
517                 if (!quote) {
518                         if (c == ';' || c == '#') {
519                                 comment = 1;
520                                 continue;
521                         }
522                 }
523                 for (; space; space--)
524                         strbuf_addch(&cf->value, ' ');
525                 if (c == '\\') {
526                         c = get_next_char();
527                         switch (c) {
528                         case '\n':
529                                 continue;
530                         case 't':
531                                 c = '\t';
532                                 break;
533                         case 'b':
534                                 c = '\b';
535                                 break;
536                         case 'n':
537                                 c = '\n';
538                                 break;
539                         /* Some characters escape as themselves */
540                         case '\\': case '"':
541                                 break;
542                         /* Reject unknown escape sequences */
543                         default:
544                                 return NULL;
545                         }
546                         strbuf_addch(&cf->value, c);
547                         continue;
548                 }
549                 if (c == '"') {
550                         quote = 1-quote;
551                         continue;
552                 }
553                 strbuf_addch(&cf->value, c);
554         }
555 }
556
557 static int get_value(config_fn_t fn, void *data, struct strbuf *name)
558 {
559         int c;
560         char *value;
561         int ret;
562
563         /* Get the full name */
564         for (;;) {
565                 c = get_next_char();
566                 if (cf->eof)
567                         break;
568                 if (!iskeychar(c))
569                         break;
570                 strbuf_addch(name, tolower(c));
571         }
572
573         while (c == ' ' || c == '\t')
574                 c = get_next_char();
575
576         value = NULL;
577         if (c != '\n') {
578                 if (c != '=')
579                         return -1;
580                 value = parse_value();
581                 if (!value)
582                         return -1;
583         }
584         /*
585          * We already consumed the \n, but we need linenr to point to
586          * the line we just parsed during the call to fn to get
587          * accurate line number in error messages.
588          */
589         cf->linenr--;
590         ret = fn(name->buf, value, data);
591         if (ret >= 0)
592                 cf->linenr++;
593         return ret;
594 }
595
596 static int get_extended_base_var(struct strbuf *name, int c)
597 {
598         do {
599                 if (c == '\n')
600                         goto error_incomplete_line;
601                 c = get_next_char();
602         } while (isspace(c));
603
604         /* We require the format to be '[base "extension"]' */
605         if (c != '"')
606                 return -1;
607         strbuf_addch(name, '.');
608
609         for (;;) {
610                 int c = get_next_char();
611                 if (c == '\n')
612                         goto error_incomplete_line;
613                 if (c == '"')
614                         break;
615                 if (c == '\\') {
616                         c = get_next_char();
617                         if (c == '\n')
618                                 goto error_incomplete_line;
619                 }
620                 strbuf_addch(name, c);
621         }
622
623         /* Final ']' */
624         if (get_next_char() != ']')
625                 return -1;
626         return 0;
627 error_incomplete_line:
628         cf->linenr--;
629         return -1;
630 }
631
632 static int get_base_var(struct strbuf *name)
633 {
634         for (;;) {
635                 int c = get_next_char();
636                 if (cf->eof)
637                         return -1;
638                 if (c == ']')
639                         return 0;
640                 if (isspace(c))
641                         return get_extended_base_var(name, c);
642                 if (!iskeychar(c) && c != '.')
643                         return -1;
644                 strbuf_addch(name, tolower(c));
645         }
646 }
647
648 static int git_parse_source(config_fn_t fn, void *data)
649 {
650         int comment = 0;
651         int baselen = 0;
652         struct strbuf *var = &cf->var;
653         int error_return = 0;
654         char *error_msg = NULL;
655
656         /* U+FEFF Byte Order Mark in UTF8 */
657         const char *bomptr = utf8_bom;
658
659         for (;;) {
660                 int c = get_next_char();
661                 if (bomptr && *bomptr) {
662                         /* We are at the file beginning; skip UTF8-encoded BOM
663                          * if present. Sane editors won't put this in on their
664                          * own, but e.g. Windows Notepad will do it happily. */
665                         if (c == (*bomptr & 0377)) {
666                                 bomptr++;
667                                 continue;
668                         } else {
669                                 /* Do not tolerate partial BOM. */
670                                 if (bomptr != utf8_bom)
671                                         break;
672                                 /* No BOM at file beginning. Cool. */
673                                 bomptr = NULL;
674                         }
675                 }
676                 if (c == '\n') {
677                         if (cf->eof)
678                                 return 0;
679                         comment = 0;
680                         continue;
681                 }
682                 if (comment || isspace(c))
683                         continue;
684                 if (c == '#' || c == ';') {
685                         comment = 1;
686                         continue;
687                 }
688                 if (c == '[') {
689                         /* Reset prior to determining a new stem */
690                         strbuf_reset(var);
691                         if (get_base_var(var) < 0 || var->len < 1)
692                                 break;
693                         strbuf_addch(var, '.');
694                         baselen = var->len;
695                         continue;
696                 }
697                 if (!isalpha(c))
698                         break;
699                 /*
700                  * Truncate the var name back to the section header
701                  * stem prior to grabbing the suffix part of the name
702                  * and the value.
703                  */
704                 strbuf_setlen(var, baselen);
705                 strbuf_addch(var, tolower(c));
706                 if (get_value(fn, data, var) < 0)
707                         break;
708         }
709
710         switch (cf->origin_type) {
711         case CONFIG_ORIGIN_BLOB:
712                 error_msg = xstrfmt(_("bad config line %d in blob %s"),
713                                       cf->linenr, cf->name);
714                 break;
715         case CONFIG_ORIGIN_FILE:
716                 error_msg = xstrfmt(_("bad config line %d in file %s"),
717                                       cf->linenr, cf->name);
718                 break;
719         case CONFIG_ORIGIN_STDIN:
720                 error_msg = xstrfmt(_("bad config line %d in standard input"),
721                                       cf->linenr);
722                 break;
723         case CONFIG_ORIGIN_SUBMODULE_BLOB:
724                 error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
725                                        cf->linenr, cf->name);
726                 break;
727         case CONFIG_ORIGIN_CMDLINE:
728                 error_msg = xstrfmt(_("bad config line %d in command line %s"),
729                                        cf->linenr, cf->name);
730                 break;
731         default:
732                 error_msg = xstrfmt(_("bad config line %d in %s"),
733                                       cf->linenr, cf->name);
734         }
735
736         if (cf->die_on_error)
737                 die("%s", error_msg);
738         else
739                 error_return = error("%s", error_msg);
740
741         free(error_msg);
742         return error_return;
743 }
744
745 static int parse_unit_factor(const char *end, uintmax_t *val)
746 {
747         if (!*end)
748                 return 1;
749         else if (!strcasecmp(end, "k")) {
750                 *val *= 1024;
751                 return 1;
752         }
753         else if (!strcasecmp(end, "m")) {
754                 *val *= 1024 * 1024;
755                 return 1;
756         }
757         else if (!strcasecmp(end, "g")) {
758                 *val *= 1024 * 1024 * 1024;
759                 return 1;
760         }
761         return 0;
762 }
763
764 static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
765 {
766         if (value && *value) {
767                 char *end;
768                 intmax_t val;
769                 uintmax_t uval;
770                 uintmax_t factor = 1;
771
772                 errno = 0;
773                 val = strtoimax(value, &end, 0);
774                 if (errno == ERANGE)
775                         return 0;
776                 if (!parse_unit_factor(end, &factor)) {
777                         errno = EINVAL;
778                         return 0;
779                 }
780                 uval = labs(val);
781                 uval *= factor;
782                 if (uval > max || labs(val) > uval) {
783                         errno = ERANGE;
784                         return 0;
785                 }
786                 val *= factor;
787                 *ret = val;
788                 return 1;
789         }
790         errno = EINVAL;
791         return 0;
792 }
793
794 static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
795 {
796         if (value && *value) {
797                 char *end;
798                 uintmax_t val;
799                 uintmax_t oldval;
800
801                 errno = 0;
802                 val = strtoumax(value, &end, 0);
803                 if (errno == ERANGE)
804                         return 0;
805                 oldval = val;
806                 if (!parse_unit_factor(end, &val)) {
807                         errno = EINVAL;
808                         return 0;
809                 }
810                 if (val > max || oldval > val) {
811                         errno = ERANGE;
812                         return 0;
813                 }
814                 *ret = val;
815                 return 1;
816         }
817         errno = EINVAL;
818         return 0;
819 }
820
821 static int git_parse_int(const char *value, int *ret)
822 {
823         intmax_t tmp;
824         if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
825                 return 0;
826         *ret = tmp;
827         return 1;
828 }
829
830 static int git_parse_int64(const char *value, int64_t *ret)
831 {
832         intmax_t tmp;
833         if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
834                 return 0;
835         *ret = tmp;
836         return 1;
837 }
838
839 int git_parse_ulong(const char *value, unsigned long *ret)
840 {
841         uintmax_t tmp;
842         if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
843                 return 0;
844         *ret = tmp;
845         return 1;
846 }
847
848 static int git_parse_ssize_t(const char *value, ssize_t *ret)
849 {
850         intmax_t tmp;
851         if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(ssize_t)))
852                 return 0;
853         *ret = tmp;
854         return 1;
855 }
856
857 NORETURN
858 static void die_bad_number(const char *name, const char *value)
859 {
860         const char * error_type = (errno == ERANGE)? _("out of range"):_("invalid unit");
861
862         if (!value)
863                 value = "";
864
865         if (!(cf && cf->name))
866                 die(_("bad numeric config value '%s' for '%s': %s"),
867                     value, name, error_type);
868
869         switch (cf->origin_type) {
870         case CONFIG_ORIGIN_BLOB:
871                 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
872                     value, name, cf->name, error_type);
873         case CONFIG_ORIGIN_FILE:
874                 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
875                     value, name, cf->name, error_type);
876         case CONFIG_ORIGIN_STDIN:
877                 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
878                     value, name, error_type);
879         case CONFIG_ORIGIN_SUBMODULE_BLOB:
880                 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
881                     value, name, cf->name, error_type);
882         case CONFIG_ORIGIN_CMDLINE:
883                 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
884                     value, name, cf->name, error_type);
885         default:
886                 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
887                     value, name, cf->name, error_type);
888         }
889 }
890
891 int git_config_int(const char *name, const char *value)
892 {
893         int ret;
894         if (!git_parse_int(value, &ret))
895                 die_bad_number(name, value);
896         return ret;
897 }
898
899 int64_t git_config_int64(const char *name, const char *value)
900 {
901         int64_t ret;
902         if (!git_parse_int64(value, &ret))
903                 die_bad_number(name, value);
904         return ret;
905 }
906
907 unsigned long git_config_ulong(const char *name, const char *value)
908 {
909         unsigned long ret;
910         if (!git_parse_ulong(value, &ret))
911                 die_bad_number(name, value);
912         return ret;
913 }
914
915 ssize_t git_config_ssize_t(const char *name, const char *value)
916 {
917         ssize_t ret;
918         if (!git_parse_ssize_t(value, &ret))
919                 die_bad_number(name, value);
920         return ret;
921 }
922
923 int git_parse_maybe_bool(const char *value)
924 {
925         if (!value)
926                 return 1;
927         if (!*value)
928                 return 0;
929         if (!strcasecmp(value, "true")
930             || !strcasecmp(value, "yes")
931             || !strcasecmp(value, "on"))
932                 return 1;
933         if (!strcasecmp(value, "false")
934             || !strcasecmp(value, "no")
935             || !strcasecmp(value, "off"))
936                 return 0;
937         return -1;
938 }
939
940 int git_config_maybe_bool(const char *name, const char *value)
941 {
942         int v = git_parse_maybe_bool(value);
943         if (0 <= v)
944                 return v;
945         if (git_parse_int(value, &v))
946                 return !!v;
947         return -1;
948 }
949
950 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
951 {
952         int v = git_parse_maybe_bool(value);
953         if (0 <= v) {
954                 *is_bool = 1;
955                 return v;
956         }
957         *is_bool = 0;
958         return git_config_int(name, value);
959 }
960
961 int git_config_bool(const char *name, const char *value)
962 {
963         int discard;
964         return !!git_config_bool_or_int(name, value, &discard);
965 }
966
967 int git_config_string(const char **dest, const char *var, const char *value)
968 {
969         if (!value)
970                 return config_error_nonbool(var);
971         *dest = xstrdup(value);
972         return 0;
973 }
974
975 int git_config_pathname(const char **dest, const char *var, const char *value)
976 {
977         if (!value)
978                 return config_error_nonbool(var);
979         *dest = expand_user_path(value, 0);
980         if (!*dest)
981                 die(_("failed to expand user dir in: '%s'"), value);
982         return 0;
983 }
984
985 static int git_default_core_config(const char *var, const char *value)
986 {
987         /* This needs a better name */
988         if (!strcmp(var, "core.filemode")) {
989                 trust_executable_bit = git_config_bool(var, value);
990                 return 0;
991         }
992         if (!strcmp(var, "core.trustctime")) {
993                 trust_ctime = git_config_bool(var, value);
994                 return 0;
995         }
996         if (!strcmp(var, "core.checkstat")) {
997                 if (!strcasecmp(value, "default"))
998                         check_stat = 1;
999                 else if (!strcasecmp(value, "minimal"))
1000                         check_stat = 0;
1001         }
1002
1003         if (!strcmp(var, "core.quotepath")) {
1004                 quote_path_fully = git_config_bool(var, value);
1005                 return 0;
1006         }
1007
1008         if (!strcmp(var, "core.symlinks")) {
1009                 has_symlinks = git_config_bool(var, value);
1010                 return 0;
1011         }
1012
1013         if (!strcmp(var, "core.ignorecase")) {
1014                 ignore_case = git_config_bool(var, value);
1015                 return 0;
1016         }
1017
1018         if (!strcmp(var, "core.attributesfile"))
1019                 return git_config_pathname(&git_attributes_file, var, value);
1020
1021         if (!strcmp(var, "core.hookspath"))
1022                 return git_config_pathname(&git_hooks_path, var, value);
1023
1024         if (!strcmp(var, "core.bare")) {
1025                 is_bare_repository_cfg = git_config_bool(var, value);
1026                 return 0;
1027         }
1028
1029         if (!strcmp(var, "core.ignorestat")) {
1030                 assume_unchanged = git_config_bool(var, value);
1031                 return 0;
1032         }
1033
1034         if (!strcmp(var, "core.prefersymlinkrefs")) {
1035                 prefer_symlink_refs = git_config_bool(var, value);
1036                 return 0;
1037         }
1038
1039         if (!strcmp(var, "core.logallrefupdates")) {
1040                 if (value && !strcasecmp(value, "always"))
1041                         log_all_ref_updates = LOG_REFS_ALWAYS;
1042                 else if (git_config_bool(var, value))
1043                         log_all_ref_updates = LOG_REFS_NORMAL;
1044                 else
1045                         log_all_ref_updates = LOG_REFS_NONE;
1046                 return 0;
1047         }
1048
1049         if (!strcmp(var, "core.warnambiguousrefs")) {
1050                 warn_ambiguous_refs = git_config_bool(var, value);
1051                 return 0;
1052         }
1053
1054         if (!strcmp(var, "core.abbrev")) {
1055                 if (!value)
1056                         return config_error_nonbool(var);
1057                 if (!strcasecmp(value, "auto"))
1058                         default_abbrev = -1;
1059                 else {
1060                         int abbrev = git_config_int(var, value);
1061                         if (abbrev < minimum_abbrev || abbrev > 40)
1062                                 return error("abbrev length out of range: %d", abbrev);
1063                         default_abbrev = abbrev;
1064                 }
1065                 return 0;
1066         }
1067
1068         if (!strcmp(var, "core.disambiguate"))
1069                 return set_disambiguate_hint_config(var, value);
1070
1071         if (!strcmp(var, "core.loosecompression")) {
1072                 int level = git_config_int(var, value);
1073                 if (level == -1)
1074                         level = Z_DEFAULT_COMPRESSION;
1075                 else if (level < 0 || level > Z_BEST_COMPRESSION)
1076                         die(_("bad zlib compression level %d"), level);
1077                 zlib_compression_level = level;
1078                 zlib_compression_seen = 1;
1079                 return 0;
1080         }
1081
1082         if (!strcmp(var, "core.compression")) {
1083                 int level = git_config_int(var, value);
1084                 if (level == -1)
1085                         level = Z_DEFAULT_COMPRESSION;
1086                 else if (level < 0 || level > Z_BEST_COMPRESSION)
1087                         die(_("bad zlib compression level %d"), level);
1088                 core_compression_level = level;
1089                 core_compression_seen = 1;
1090                 if (!zlib_compression_seen)
1091                         zlib_compression_level = level;
1092                 if (!pack_compression_seen)
1093                         pack_compression_level = level;
1094                 return 0;
1095         }
1096
1097         if (!strcmp(var, "core.packedgitwindowsize")) {
1098                 int pgsz_x2 = getpagesize() * 2;
1099                 packed_git_window_size = git_config_ulong(var, value);
1100
1101                 /* This value must be multiple of (pagesize * 2) */
1102                 packed_git_window_size /= pgsz_x2;
1103                 if (packed_git_window_size < 1)
1104                         packed_git_window_size = 1;
1105                 packed_git_window_size *= pgsz_x2;
1106                 return 0;
1107         }
1108
1109         if (!strcmp(var, "core.bigfilethreshold")) {
1110                 big_file_threshold = git_config_ulong(var, value);
1111                 return 0;
1112         }
1113
1114         if (!strcmp(var, "core.packedgitlimit")) {
1115                 packed_git_limit = git_config_ulong(var, value);
1116                 return 0;
1117         }
1118
1119         if (!strcmp(var, "core.deltabasecachelimit")) {
1120                 delta_base_cache_limit = git_config_ulong(var, value);
1121                 return 0;
1122         }
1123
1124         if (!strcmp(var, "core.autocrlf")) {
1125                 if (value && !strcasecmp(value, "input")) {
1126                         auto_crlf = AUTO_CRLF_INPUT;
1127                         return 0;
1128                 }
1129                 auto_crlf = git_config_bool(var, value);
1130                 return 0;
1131         }
1132
1133         if (!strcmp(var, "core.safecrlf")) {
1134                 if (value && !strcasecmp(value, "warn")) {
1135                         safe_crlf = SAFE_CRLF_WARN;
1136                         return 0;
1137                 }
1138                 safe_crlf = git_config_bool(var, value);
1139                 return 0;
1140         }
1141
1142         if (!strcmp(var, "core.eol")) {
1143                 if (value && !strcasecmp(value, "lf"))
1144                         core_eol = EOL_LF;
1145                 else if (value && !strcasecmp(value, "crlf"))
1146                         core_eol = EOL_CRLF;
1147                 else if (value && !strcasecmp(value, "native"))
1148                         core_eol = EOL_NATIVE;
1149                 else
1150                         core_eol = EOL_UNSET;
1151                 return 0;
1152         }
1153
1154         if (!strcmp(var, "core.notesref")) {
1155                 notes_ref_name = xstrdup(value);
1156                 return 0;
1157         }
1158
1159         if (!strcmp(var, "core.editor"))
1160                 return git_config_string(&editor_program, var, value);
1161
1162         if (!strcmp(var, "core.commentchar")) {
1163                 if (!value)
1164                         return config_error_nonbool(var);
1165                 else if (!strcasecmp(value, "auto"))
1166                         auto_comment_line_char = 1;
1167                 else if (value[0] && !value[1]) {
1168                         comment_line_char = value[0];
1169                         auto_comment_line_char = 0;
1170                 } else
1171                         return error("core.commentChar should only be one character");
1172                 return 0;
1173         }
1174
1175         if (!strcmp(var, "core.askpass"))
1176                 return git_config_string(&askpass_program, var, value);
1177
1178         if (!strcmp(var, "core.excludesfile"))
1179                 return git_config_pathname(&excludes_file, var, value);
1180
1181         if (!strcmp(var, "core.whitespace")) {
1182                 if (!value)
1183                         return config_error_nonbool(var);
1184                 whitespace_rule_cfg = parse_whitespace_rule(value);
1185                 return 0;
1186         }
1187
1188         if (!strcmp(var, "core.fsyncobjectfiles")) {
1189                 fsync_object_files = git_config_bool(var, value);
1190                 return 0;
1191         }
1192
1193         if (!strcmp(var, "core.preloadindex")) {
1194                 core_preload_index = git_config_bool(var, value);
1195                 return 0;
1196         }
1197
1198         if (!strcmp(var, "core.createobject")) {
1199                 if (!strcmp(value, "rename"))
1200                         object_creation_mode = OBJECT_CREATION_USES_RENAMES;
1201                 else if (!strcmp(value, "link"))
1202                         object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
1203                 else
1204                         die(_("invalid mode for object creation: %s"), value);
1205                 return 0;
1206         }
1207
1208         if (!strcmp(var, "core.sparsecheckout")) {
1209                 core_apply_sparse_checkout = git_config_bool(var, value);
1210                 return 0;
1211         }
1212
1213         if (!strcmp(var, "core.precomposeunicode")) {
1214                 precomposed_unicode = git_config_bool(var, value);
1215                 return 0;
1216         }
1217
1218         if (!strcmp(var, "core.protecthfs")) {
1219                 protect_hfs = git_config_bool(var, value);
1220                 return 0;
1221         }
1222
1223         if (!strcmp(var, "core.protectntfs")) {
1224                 protect_ntfs = git_config_bool(var, value);
1225                 return 0;
1226         }
1227
1228         if (!strcmp(var, "core.hidedotfiles")) {
1229                 if (value && !strcasecmp(value, "dotgitonly"))
1230                         hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
1231                 else
1232                         hide_dotfiles = git_config_bool(var, value);
1233                 return 0;
1234         }
1235
1236         /* Add other config variables here and to Documentation/config.txt. */
1237         return 0;
1238 }
1239
1240 static int git_default_i18n_config(const char *var, const char *value)
1241 {
1242         if (!strcmp(var, "i18n.commitencoding"))
1243                 return git_config_string(&git_commit_encoding, var, value);
1244
1245         if (!strcmp(var, "i18n.logoutputencoding"))
1246                 return git_config_string(&git_log_output_encoding, var, value);
1247
1248         /* Add other config variables here and to Documentation/config.txt. */
1249         return 0;
1250 }
1251
1252 static int git_default_branch_config(const char *var, const char *value)
1253 {
1254         if (!strcmp(var, "branch.autosetupmerge")) {
1255                 if (value && !strcasecmp(value, "always")) {
1256                         git_branch_track = BRANCH_TRACK_ALWAYS;
1257                         return 0;
1258                 }
1259                 git_branch_track = git_config_bool(var, value);
1260                 return 0;
1261         }
1262         if (!strcmp(var, "branch.autosetuprebase")) {
1263                 if (!value)
1264                         return config_error_nonbool(var);
1265                 else if (!strcmp(value, "never"))
1266                         autorebase = AUTOREBASE_NEVER;
1267                 else if (!strcmp(value, "local"))
1268                         autorebase = AUTOREBASE_LOCAL;
1269                 else if (!strcmp(value, "remote"))
1270                         autorebase = AUTOREBASE_REMOTE;
1271                 else if (!strcmp(value, "always"))
1272                         autorebase = AUTOREBASE_ALWAYS;
1273                 else
1274                         return error("malformed value for %s", var);
1275                 return 0;
1276         }
1277
1278         /* Add other config variables here and to Documentation/config.txt. */
1279         return 0;
1280 }
1281
1282 static int git_default_push_config(const char *var, const char *value)
1283 {
1284         if (!strcmp(var, "push.default")) {
1285                 if (!value)
1286                         return config_error_nonbool(var);
1287                 else if (!strcmp(value, "nothing"))
1288                         push_default = PUSH_DEFAULT_NOTHING;
1289                 else if (!strcmp(value, "matching"))
1290                         push_default = PUSH_DEFAULT_MATCHING;
1291                 else if (!strcmp(value, "simple"))
1292                         push_default = PUSH_DEFAULT_SIMPLE;
1293                 else if (!strcmp(value, "upstream"))
1294                         push_default = PUSH_DEFAULT_UPSTREAM;
1295                 else if (!strcmp(value, "tracking")) /* deprecated */
1296                         push_default = PUSH_DEFAULT_UPSTREAM;
1297                 else if (!strcmp(value, "current"))
1298                         push_default = PUSH_DEFAULT_CURRENT;
1299                 else {
1300                         error("malformed value for %s: %s", var, value);
1301                         return error("Must be one of nothing, matching, simple, "
1302                                      "upstream or current.");
1303                 }
1304                 return 0;
1305         }
1306
1307         /* Add other config variables here and to Documentation/config.txt. */
1308         return 0;
1309 }
1310
1311 static int git_default_mailmap_config(const char *var, const char *value)
1312 {
1313         if (!strcmp(var, "mailmap.file"))
1314                 return git_config_pathname(&git_mailmap_file, var, value);
1315         if (!strcmp(var, "mailmap.blob"))
1316                 return git_config_string(&git_mailmap_blob, var, value);
1317
1318         /* Add other config variables here and to Documentation/config.txt. */
1319         return 0;
1320 }
1321
1322 int git_default_config(const char *var, const char *value, void *dummy)
1323 {
1324         if (starts_with(var, "core."))
1325                 return git_default_core_config(var, value);
1326
1327         if (starts_with(var, "user."))
1328                 return git_ident_config(var, value, dummy);
1329
1330         if (starts_with(var, "i18n."))
1331                 return git_default_i18n_config(var, value);
1332
1333         if (starts_with(var, "branch."))
1334                 return git_default_branch_config(var, value);
1335
1336         if (starts_with(var, "push."))
1337                 return git_default_push_config(var, value);
1338
1339         if (starts_with(var, "mailmap."))
1340                 return git_default_mailmap_config(var, value);
1341
1342         if (starts_with(var, "advice."))
1343                 return git_default_advice_config(var, value);
1344
1345         if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1346                 pager_use_color = git_config_bool(var,value);
1347                 return 0;
1348         }
1349
1350         if (!strcmp(var, "pack.packsizelimit")) {
1351                 pack_size_limit_cfg = git_config_ulong(var, value);
1352                 return 0;
1353         }
1354
1355         if (!strcmp(var, "pack.compression")) {
1356                 int level = git_config_int(var, value);
1357                 if (level == -1)
1358                         level = Z_DEFAULT_COMPRESSION;
1359                 else if (level < 0 || level > Z_BEST_COMPRESSION)
1360                         die(_("bad pack compression level %d"), level);
1361                 pack_compression_level = level;
1362                 pack_compression_seen = 1;
1363                 return 0;
1364         }
1365
1366         /* Add other config variables here and to Documentation/config.txt. */
1367         return 0;
1368 }
1369
1370 /*
1371  * All source specific fields in the union, die_on_error, name and the callbacks
1372  * fgetc, ungetc, ftell of top need to be initialized before calling
1373  * this function.
1374  */
1375 static int do_config_from(struct config_source *top, config_fn_t fn, void *data)
1376 {
1377         int ret;
1378
1379         /* push config-file parsing state stack */
1380         top->prev = cf;
1381         top->linenr = 1;
1382         top->eof = 0;
1383         strbuf_init(&top->value, 1024);
1384         strbuf_init(&top->var, 1024);
1385         cf = top;
1386
1387         ret = git_parse_source(fn, data);
1388
1389         /* pop config-file parsing state stack */
1390         strbuf_release(&top->value);
1391         strbuf_release(&top->var);
1392         cf = top->prev;
1393
1394         return ret;
1395 }
1396
1397 static int do_config_from_file(config_fn_t fn,
1398                 const enum config_origin_type origin_type,
1399                 const char *name, const char *path, FILE *f,
1400                 void *data)
1401 {
1402         struct config_source top;
1403
1404         top.u.file = f;
1405         top.origin_type = origin_type;
1406         top.name = name;
1407         top.path = path;
1408         top.die_on_error = 1;
1409         top.do_fgetc = config_file_fgetc;
1410         top.do_ungetc = config_file_ungetc;
1411         top.do_ftell = config_file_ftell;
1412
1413         return do_config_from(&top, fn, data);
1414 }
1415
1416 static int git_config_from_stdin(config_fn_t fn, void *data)
1417 {
1418         return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", NULL, stdin, data);
1419 }
1420
1421 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
1422 {
1423         int ret = -1;
1424         FILE *f;
1425
1426         f = fopen(filename, "r");
1427         if (f) {
1428                 flockfile(f);
1429                 ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename, filename, f, data);
1430                 funlockfile(f);
1431                 fclose(f);
1432         }
1433         return ret;
1434 }
1435
1436 int git_config_from_mem(config_fn_t fn, const enum config_origin_type origin_type,
1437                         const char *name, const char *buf, size_t len, void *data)
1438 {
1439         struct config_source top;
1440
1441         top.u.buf.buf = buf;
1442         top.u.buf.len = len;
1443         top.u.buf.pos = 0;
1444         top.origin_type = origin_type;
1445         top.name = name;
1446         top.path = NULL;
1447         top.die_on_error = 0;
1448         top.do_fgetc = config_buf_fgetc;
1449         top.do_ungetc = config_buf_ungetc;
1450         top.do_ftell = config_buf_ftell;
1451
1452         return do_config_from(&top, fn, data);
1453 }
1454
1455 int git_config_from_blob_sha1(config_fn_t fn,
1456                               const char *name,
1457                               const unsigned char *sha1,
1458                               void *data)
1459 {
1460         enum object_type type;
1461         char *buf;
1462         unsigned long size;
1463         int ret;
1464
1465         buf = read_sha1_file(sha1, &type, &size);
1466         if (!buf)
1467                 return error("unable to load config blob object '%s'", name);
1468         if (type != OBJ_BLOB) {
1469                 free(buf);
1470                 return error("reference '%s' does not point to a blob", name);
1471         }
1472
1473         ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size, data);
1474         free(buf);
1475
1476         return ret;
1477 }
1478
1479 static int git_config_from_blob_ref(config_fn_t fn,
1480                                     const char *name,
1481                                     void *data)
1482 {
1483         unsigned char sha1[20];
1484
1485         if (get_sha1(name, sha1) < 0)
1486                 return error("unable to resolve config blob '%s'", name);
1487         return git_config_from_blob_sha1(fn, name, sha1, data);
1488 }
1489
1490 const char *git_etc_gitconfig(void)
1491 {
1492         static const char *system_wide;
1493         if (!system_wide)
1494                 system_wide = system_path(ETC_GITCONFIG);
1495         return system_wide;
1496 }
1497
1498 /*
1499  * Parse environment variable 'k' as a boolean (in various
1500  * possible spellings); if missing, use the default value 'def'.
1501  */
1502 int git_env_bool(const char *k, int def)
1503 {
1504         const char *v = getenv(k);
1505         return v ? git_config_bool(k, v) : def;
1506 }
1507
1508 /*
1509  * Parse environment variable 'k' as ulong with possibly a unit
1510  * suffix; if missing, use the default value 'val'.
1511  */
1512 unsigned long git_env_ulong(const char *k, unsigned long val)
1513 {
1514         const char *v = getenv(k);
1515         if (v && !git_parse_ulong(v, &val))
1516                 die("failed to parse %s", k);
1517         return val;
1518 }
1519
1520 int git_config_system(void)
1521 {
1522         return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
1523 }
1524
1525 static int do_git_config_sequence(const struct config_options *opts,
1526                                   config_fn_t fn, void *data)
1527 {
1528         int ret = 0;
1529         char *xdg_config = xdg_config_home("config");
1530         char *user_config = expand_user_path("~/.gitconfig", 0);
1531         char *repo_config;
1532
1533         if (opts->git_dir)
1534                 repo_config = mkpathdup("%s/config", opts->git_dir);
1535         else if (have_git_dir())
1536                 repo_config = git_pathdup("config");
1537         else
1538                 repo_config = NULL;
1539
1540         current_parsing_scope = CONFIG_SCOPE_SYSTEM;
1541         if (git_config_system() && !access_or_die(git_etc_gitconfig(), R_OK, 0))
1542                 ret += git_config_from_file(fn, git_etc_gitconfig(),
1543                                             data);
1544
1545         current_parsing_scope = CONFIG_SCOPE_GLOBAL;
1546         if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
1547                 ret += git_config_from_file(fn, xdg_config, data);
1548
1549         if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
1550                 ret += git_config_from_file(fn, user_config, data);
1551
1552         current_parsing_scope = CONFIG_SCOPE_REPO;
1553         if (repo_config && !access_or_die(repo_config, R_OK, 0))
1554                 ret += git_config_from_file(fn, repo_config, data);
1555
1556         current_parsing_scope = CONFIG_SCOPE_CMDLINE;
1557         if (git_config_from_parameters(fn, data) < 0)
1558                 die(_("unable to parse command-line config"));
1559
1560         current_parsing_scope = CONFIG_SCOPE_UNKNOWN;
1561         free(xdg_config);
1562         free(user_config);
1563         free(repo_config);
1564         return ret;
1565 }
1566
1567 int git_config_with_options(config_fn_t fn, void *data,
1568                             struct git_config_source *config_source,
1569                             const struct config_options *opts)
1570 {
1571         struct config_include_data inc = CONFIG_INCLUDE_INIT;
1572
1573         if (opts->respect_includes) {
1574                 inc.fn = fn;
1575                 inc.data = data;
1576                 inc.opts = opts;
1577                 fn = git_config_include;
1578                 data = &inc;
1579         }
1580
1581         /*
1582          * If we have a specific filename, use it. Otherwise, follow the
1583          * regular lookup sequence.
1584          */
1585         if (config_source && config_source->use_stdin)
1586                 return git_config_from_stdin(fn, data);
1587         else if (config_source && config_source->file)
1588                 return git_config_from_file(fn, config_source->file, data);
1589         else if (config_source && config_source->blob)
1590                 return git_config_from_blob_ref(fn, config_source->blob, data);
1591
1592         return do_git_config_sequence(opts, fn, data);
1593 }
1594
1595 static void git_config_raw(config_fn_t fn, void *data)
1596 {
1597         struct config_options opts = {0};
1598
1599         opts.respect_includes = 1;
1600         if (git_config_with_options(fn, data, NULL, &opts) < 0)
1601                 /*
1602                  * git_config_with_options() normally returns only
1603                  * zero, as most errors are fatal, and
1604                  * non-fatal potential errors are guarded by "if"
1605                  * statements that are entered only when no error is
1606                  * possible.
1607                  *
1608                  * If we ever encounter a non-fatal error, it means
1609                  * something went really wrong and we should stop
1610                  * immediately.
1611                  */
1612                 die(_("unknown error occurred while reading the configuration files"));
1613 }
1614
1615 static void configset_iter(struct config_set *cs, config_fn_t fn, void *data)
1616 {
1617         int i, value_index;
1618         struct string_list *values;
1619         struct config_set_element *entry;
1620         struct configset_list *list = &cs->list;
1621
1622         for (i = 0; i < list->nr; i++) {
1623                 entry = list->items[i].e;
1624                 value_index = list->items[i].value_index;
1625                 values = &entry->value_list;
1626
1627                 current_config_kvi = values->items[value_index].util;
1628
1629                 if (fn(entry->key, values->items[value_index].string, data) < 0)
1630                         git_die_config_linenr(entry->key,
1631                                               current_config_kvi->filename,
1632                                               current_config_kvi->linenr);
1633
1634                 current_config_kvi = NULL;
1635         }
1636 }
1637
1638 void read_early_config(config_fn_t cb, void *data)
1639 {
1640         struct config_options opts = {0};
1641         struct strbuf buf = STRBUF_INIT;
1642
1643         opts.respect_includes = 1;
1644
1645         if (have_git_dir())
1646                 opts.git_dir = get_git_dir();
1647         /*
1648          * When setup_git_directory() was not yet asked to discover the
1649          * GIT_DIR, we ask discover_git_directory() to figure out whether there
1650          * is any repository config we should use (but unlike
1651          * setup_git_directory_gently(), no global state is changed, most
1652          * notably, the current working directory is still the same after the
1653          * call).
1654          */
1655         else if (discover_git_directory(&buf))
1656                 opts.git_dir = buf.buf;
1657
1658         git_config_with_options(cb, data, NULL, &opts);
1659
1660         strbuf_release(&buf);
1661 }
1662
1663 static void git_config_check_init(void);
1664
1665 void git_config(config_fn_t fn, void *data)
1666 {
1667         git_config_check_init();
1668         configset_iter(&the_config_set, fn, data);
1669 }
1670
1671 static struct config_set_element *configset_find_element(struct config_set *cs, const char *key)
1672 {
1673         struct config_set_element k;
1674         struct config_set_element *found_entry;
1675         char *normalized_key;
1676         /*
1677          * `key` may come from the user, so normalize it before using it
1678          * for querying entries from the hashmap.
1679          */
1680         if (git_config_parse_key(key, &normalized_key, NULL))
1681                 return NULL;
1682
1683         hashmap_entry_init(&k, strhash(normalized_key));
1684         k.key = normalized_key;
1685         found_entry = hashmap_get(&cs->config_hash, &k, NULL);
1686         free(normalized_key);
1687         return found_entry;
1688 }
1689
1690 static int configset_add_value(struct config_set *cs, const char *key, const char *value)
1691 {
1692         struct config_set_element *e;
1693         struct string_list_item *si;
1694         struct configset_list_item *l_item;
1695         struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
1696
1697         e = configset_find_element(cs, key);
1698         /*
1699          * Since the keys are being fed by git_config*() callback mechanism, they
1700          * are already normalized. So simply add them without any further munging.
1701          */
1702         if (!e) {
1703                 e = xmalloc(sizeof(*e));
1704                 hashmap_entry_init(e, strhash(key));
1705                 e->key = xstrdup(key);
1706                 string_list_init(&e->value_list, 1);
1707                 hashmap_add(&cs->config_hash, e);
1708         }
1709         si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
1710
1711         ALLOC_GROW(cs->list.items, cs->list.nr + 1, cs->list.alloc);
1712         l_item = &cs->list.items[cs->list.nr++];
1713         l_item->e = e;
1714         l_item->value_index = e->value_list.nr - 1;
1715
1716         if (!cf)
1717                 die("BUG: configset_add_value has no source");
1718         if (cf->name) {
1719                 kv_info->filename = strintern(cf->name);
1720                 kv_info->linenr = cf->linenr;
1721                 kv_info->origin_type = cf->origin_type;
1722         } else {
1723                 /* for values read from `git_config_from_parameters()` */
1724                 kv_info->filename = NULL;
1725                 kv_info->linenr = -1;
1726                 kv_info->origin_type = CONFIG_ORIGIN_CMDLINE;
1727         }
1728         kv_info->scope = current_parsing_scope;
1729         si->util = kv_info;
1730
1731         return 0;
1732 }
1733
1734 static int config_set_element_cmp(const struct config_set_element *e1,
1735                                  const struct config_set_element *e2, const void *unused)
1736 {
1737         return strcmp(e1->key, e2->key);
1738 }
1739
1740 void git_configset_init(struct config_set *cs)
1741 {
1742         hashmap_init(&cs->config_hash, (hashmap_cmp_fn)config_set_element_cmp, 0);
1743         cs->hash_initialized = 1;
1744         cs->list.nr = 0;
1745         cs->list.alloc = 0;
1746         cs->list.items = NULL;
1747 }
1748
1749 void git_configset_clear(struct config_set *cs)
1750 {
1751         struct config_set_element *entry;
1752         struct hashmap_iter iter;
1753         if (!cs->hash_initialized)
1754                 return;
1755
1756         hashmap_iter_init(&cs->config_hash, &iter);
1757         while ((entry = hashmap_iter_next(&iter))) {
1758                 free(entry->key);
1759                 string_list_clear(&entry->value_list, 1);
1760         }
1761         hashmap_free(&cs->config_hash, 1);
1762         cs->hash_initialized = 0;
1763         free(cs->list.items);
1764         cs->list.nr = 0;
1765         cs->list.alloc = 0;
1766         cs->list.items = NULL;
1767 }
1768
1769 static int config_set_callback(const char *key, const char *value, void *cb)
1770 {
1771         struct config_set *cs = cb;
1772         configset_add_value(cs, key, value);
1773         return 0;
1774 }
1775
1776 int git_configset_add_file(struct config_set *cs, const char *filename)
1777 {
1778         return git_config_from_file(config_set_callback, filename, cs);
1779 }
1780
1781 int git_configset_get_value(struct config_set *cs, const char *key, const char **value)
1782 {
1783         const struct string_list *values = NULL;
1784         /*
1785          * Follows "last one wins" semantic, i.e., if there are multiple matches for the
1786          * queried key in the files of the configset, the value returned will be the last
1787          * value in the value list for that key.
1788          */
1789         values = git_configset_get_value_multi(cs, key);
1790
1791         if (!values)
1792                 return 1;
1793         assert(values->nr > 0);
1794         *value = values->items[values->nr - 1].string;
1795         return 0;
1796 }
1797
1798 const struct string_list *git_configset_get_value_multi(struct config_set *cs, const char *key)
1799 {
1800         struct config_set_element *e = configset_find_element(cs, key);
1801         return e ? &e->value_list : NULL;
1802 }
1803
1804 int git_configset_get_string_const(struct config_set *cs, const char *key, const char **dest)
1805 {
1806         const char *value;
1807         if (!git_configset_get_value(cs, key, &value))
1808                 return git_config_string(dest, key, value);
1809         else
1810                 return 1;
1811 }
1812
1813 int git_configset_get_string(struct config_set *cs, const char *key, char **dest)
1814 {
1815         return git_configset_get_string_const(cs, key, (const char **)dest);
1816 }
1817
1818 int git_configset_get_int(struct config_set *cs, const char *key, int *dest)
1819 {
1820         const char *value;
1821         if (!git_configset_get_value(cs, key, &value)) {
1822                 *dest = git_config_int(key, value);
1823                 return 0;
1824         } else
1825                 return 1;
1826 }
1827
1828 int git_configset_get_ulong(struct config_set *cs, const char *key, unsigned long *dest)
1829 {
1830         const char *value;
1831         if (!git_configset_get_value(cs, key, &value)) {
1832                 *dest = git_config_ulong(key, value);
1833                 return 0;
1834         } else
1835                 return 1;
1836 }
1837
1838 int git_configset_get_bool(struct config_set *cs, const char *key, int *dest)
1839 {
1840         const char *value;
1841         if (!git_configset_get_value(cs, key, &value)) {
1842                 *dest = git_config_bool(key, value);
1843                 return 0;
1844         } else
1845                 return 1;
1846 }
1847
1848 int git_configset_get_bool_or_int(struct config_set *cs, const char *key,
1849                                 int *is_bool, int *dest)
1850 {
1851         const char *value;
1852         if (!git_configset_get_value(cs, key, &value)) {
1853                 *dest = git_config_bool_or_int(key, value, is_bool);
1854                 return 0;
1855         } else
1856                 return 1;
1857 }
1858
1859 int git_configset_get_maybe_bool(struct config_set *cs, const char *key, int *dest)
1860 {
1861         const char *value;
1862         if (!git_configset_get_value(cs, key, &value)) {
1863                 *dest = git_config_maybe_bool(key, value);
1864                 if (*dest == -1)
1865                         return -1;
1866                 return 0;
1867         } else
1868                 return 1;
1869 }
1870
1871 int git_configset_get_pathname(struct config_set *cs, const char *key, const char **dest)
1872 {
1873         const char *value;
1874         if (!git_configset_get_value(cs, key, &value))
1875                 return git_config_pathname(dest, key, value);
1876         else
1877                 return 1;
1878 }
1879
1880 static void git_config_check_init(void)
1881 {
1882         if (the_config_set.hash_initialized)
1883                 return;
1884         git_configset_init(&the_config_set);
1885         git_config_raw(config_set_callback, &the_config_set);
1886 }
1887
1888 void git_config_clear(void)
1889 {
1890         if (!the_config_set.hash_initialized)
1891                 return;
1892         git_configset_clear(&the_config_set);
1893 }
1894
1895 int git_config_get_value(const char *key, const char **value)
1896 {
1897         git_config_check_init();
1898         return git_configset_get_value(&the_config_set, key, value);
1899 }
1900
1901 const struct string_list *git_config_get_value_multi(const char *key)
1902 {
1903         git_config_check_init();
1904         return git_configset_get_value_multi(&the_config_set, key);
1905 }
1906
1907 int git_config_get_string_const(const char *key, const char **dest)
1908 {
1909         int ret;
1910         git_config_check_init();
1911         ret = git_configset_get_string_const(&the_config_set, key, dest);
1912         if (ret < 0)
1913                 git_die_config(key, NULL);
1914         return ret;
1915 }
1916
1917 int git_config_get_string(const char *key, char **dest)
1918 {
1919         git_config_check_init();
1920         return git_config_get_string_const(key, (const char **)dest);
1921 }
1922
1923 int git_config_get_int(const char *key, int *dest)
1924 {
1925         git_config_check_init();
1926         return git_configset_get_int(&the_config_set, key, dest);
1927 }
1928
1929 int git_config_get_ulong(const char *key, unsigned long *dest)
1930 {
1931         git_config_check_init();
1932         return git_configset_get_ulong(&the_config_set, key, dest);
1933 }
1934
1935 int git_config_get_bool(const char *key, int *dest)
1936 {
1937         git_config_check_init();
1938         return git_configset_get_bool(&the_config_set, key, dest);
1939 }
1940
1941 int git_config_get_bool_or_int(const char *key, int *is_bool, int *dest)
1942 {
1943         git_config_check_init();
1944         return git_configset_get_bool_or_int(&the_config_set, key, is_bool, dest);
1945 }
1946
1947 int git_config_get_maybe_bool(const char *key, int *dest)
1948 {
1949         git_config_check_init();
1950         return git_configset_get_maybe_bool(&the_config_set, key, dest);
1951 }
1952
1953 int git_config_get_pathname(const char *key, const char **dest)
1954 {
1955         int ret;
1956         git_config_check_init();
1957         ret = git_configset_get_pathname(&the_config_set, key, dest);
1958         if (ret < 0)
1959                 git_die_config(key, NULL);
1960         return ret;
1961 }
1962
1963 int git_config_get_expiry(const char *key, const char **output)
1964 {
1965         int ret = git_config_get_string_const(key, output);
1966         if (ret)
1967                 return ret;
1968         if (strcmp(*output, "now")) {
1969                 unsigned long now = approxidate("now");
1970                 if (approxidate(*output) >= now)
1971                         git_die_config(key, _("Invalid %s: '%s'"), key, *output);
1972         }
1973         return ret;
1974 }
1975
1976 int git_config_get_untracked_cache(void)
1977 {
1978         int val = -1;
1979         const char *v;
1980
1981         /* Hack for test programs like test-dump-untracked-cache */
1982         if (ignore_untracked_cache_config)
1983                 return -1;
1984
1985         if (!git_config_get_maybe_bool("core.untrackedcache", &val))
1986                 return val;
1987
1988         if (!git_config_get_value("core.untrackedcache", &v)) {
1989                 if (!strcasecmp(v, "keep"))
1990                         return -1;
1991
1992                 error(_("unknown core.untrackedCache value '%s'; "
1993                         "using 'keep' default value"), v);
1994                 return -1;
1995         }
1996
1997         return -1; /* default value */
1998 }
1999
2000 int git_config_get_split_index(void)
2001 {
2002         int val;
2003
2004         if (!git_config_get_maybe_bool("core.splitindex", &val))
2005                 return val;
2006
2007         return -1; /* default value */
2008 }
2009
2010 int git_config_get_max_percent_split_change(void)
2011 {
2012         int val = -1;
2013
2014         if (!git_config_get_int("splitindex.maxpercentchange", &val)) {
2015                 if (0 <= val && val <= 100)
2016                         return val;
2017
2018                 return error(_("splitIndex.maxPercentChange value '%d' "
2019                                "should be between 0 and 100"), val);
2020         }
2021
2022         return -1; /* default value */
2023 }
2024
2025 NORETURN
2026 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2027 {
2028         if (!filename)
2029                 die(_("unable to parse '%s' from command-line config"), key);
2030         else
2031                 die(_("bad config variable '%s' in file '%s' at line %d"),
2032                     key, filename, linenr);
2033 }
2034
2035 NORETURN __attribute__((format(printf, 2, 3)))
2036 void git_die_config(const char *key, const char *err, ...)
2037 {
2038         const struct string_list *values;
2039         struct key_value_info *kv_info;
2040
2041         if (err) {
2042                 va_list params;
2043                 va_start(params, err);
2044                 vreportf("error: ", err, params);
2045                 va_end(params);
2046         }
2047         values = git_config_get_value_multi(key);
2048         kv_info = values->items[values->nr - 1].util;
2049         git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
2050 }
2051
2052 /*
2053  * Find all the stuff for git_config_set() below.
2054  */
2055
2056 static struct {
2057         int baselen;
2058         char *key;
2059         int do_not_match;
2060         regex_t *value_regex;
2061         int multi_replace;
2062         size_t *offset;
2063         unsigned int offset_alloc;
2064         enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
2065         int seen;
2066 } store;
2067
2068 static int matches(const char *key, const char *value)
2069 {
2070         if (strcmp(key, store.key))
2071                 return 0; /* not ours */
2072         if (!store.value_regex)
2073                 return 1; /* always matches */
2074         if (store.value_regex == CONFIG_REGEX_NONE)
2075                 return 0; /* never matches */
2076
2077         return store.do_not_match ^
2078                 (value && !regexec(store.value_regex, value, 0, NULL, 0));
2079 }
2080
2081 static int store_aux(const char *key, const char *value, void *cb)
2082 {
2083         const char *ep;
2084         size_t section_len;
2085
2086         switch (store.state) {
2087         case KEY_SEEN:
2088                 if (matches(key, value)) {
2089                         if (store.seen == 1 && store.multi_replace == 0) {
2090                                 warning(_("%s has multiple values"), key);
2091                         }
2092
2093                         ALLOC_GROW(store.offset, store.seen + 1,
2094                                    store.offset_alloc);
2095
2096                         store.offset[store.seen] = cf->do_ftell(cf);
2097                         store.seen++;
2098                 }
2099                 break;
2100         case SECTION_SEEN:
2101                 /*
2102                  * What we are looking for is in store.key (both
2103                  * section and var), and its section part is baselen
2104                  * long.  We found key (again, both section and var).
2105                  * We would want to know if this key is in the same
2106                  * section as what we are looking for.  We already
2107                  * know we are in the same section as what should
2108                  * hold store.key.
2109                  */
2110                 ep = strrchr(key, '.');
2111                 section_len = ep - key;
2112
2113                 if ((section_len != store.baselen) ||
2114                     memcmp(key, store.key, section_len+1)) {
2115                         store.state = SECTION_END_SEEN;
2116                         break;
2117                 }
2118
2119                 /*
2120                  * Do not increment matches: this is no match, but we
2121                  * just made sure we are in the desired section.
2122                  */
2123                 ALLOC_GROW(store.offset, store.seen + 1,
2124                            store.offset_alloc);
2125                 store.offset[store.seen] = cf->do_ftell(cf);
2126                 /* fallthru */
2127         case SECTION_END_SEEN:
2128         case START:
2129                 if (matches(key, value)) {
2130                         ALLOC_GROW(store.offset, store.seen + 1,
2131                                    store.offset_alloc);
2132                         store.offset[store.seen] = cf->do_ftell(cf);
2133                         store.state = KEY_SEEN;
2134                         store.seen++;
2135                 } else {
2136                         if (strrchr(key, '.') - key == store.baselen &&
2137                               !strncmp(key, store.key, store.baselen)) {
2138                                         store.state = SECTION_SEEN;
2139                                         ALLOC_GROW(store.offset,
2140                                                    store.seen + 1,
2141                                                    store.offset_alloc);
2142                                         store.offset[store.seen] = cf->do_ftell(cf);
2143                         }
2144                 }
2145         }
2146         return 0;
2147 }
2148
2149 static int write_error(const char *filename)
2150 {
2151         error("failed to write new configuration file %s", filename);
2152
2153         /* Same error code as "failed to rename". */
2154         return 4;
2155 }
2156
2157 static int store_write_section(int fd, const char *key)
2158 {
2159         const char *dot;
2160         int i, success;
2161         struct strbuf sb = STRBUF_INIT;
2162
2163         dot = memchr(key, '.', store.baselen);
2164         if (dot) {
2165                 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
2166                 for (i = dot - key + 1; i < store.baselen; i++) {
2167                         if (key[i] == '"' || key[i] == '\\')
2168                                 strbuf_addch(&sb, '\\');
2169                         strbuf_addch(&sb, key[i]);
2170                 }
2171                 strbuf_addstr(&sb, "\"]\n");
2172         } else {
2173                 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
2174         }
2175
2176         success = write_in_full(fd, sb.buf, sb.len) == sb.len;
2177         strbuf_release(&sb);
2178
2179         return success;
2180 }
2181
2182 static int store_write_pair(int fd, const char *key, const char *value)
2183 {
2184         int i, success;
2185         int length = strlen(key + store.baselen + 1);
2186         const char *quote = "";
2187         struct strbuf sb = STRBUF_INIT;
2188
2189         /*
2190          * Check to see if the value needs to be surrounded with a dq pair.
2191          * Note that problematic characters are always backslash-quoted; this
2192          * check is about not losing leading or trailing SP and strings that
2193          * follow beginning-of-comment characters (i.e. ';' and '#') by the
2194          * configuration parser.
2195          */
2196         if (value[0] == ' ')
2197                 quote = "\"";
2198         for (i = 0; value[i]; i++)
2199                 if (value[i] == ';' || value[i] == '#')
2200                         quote = "\"";
2201         if (i && value[i - 1] == ' ')
2202                 quote = "\"";
2203
2204         strbuf_addf(&sb, "\t%.*s = %s",
2205                     length, key + store.baselen + 1, quote);
2206
2207         for (i = 0; value[i]; i++)
2208                 switch (value[i]) {
2209                 case '\n':
2210                         strbuf_addstr(&sb, "\\n");
2211                         break;
2212                 case '\t':
2213                         strbuf_addstr(&sb, "\\t");
2214                         break;
2215                 case '"':
2216                 case '\\':
2217                         strbuf_addch(&sb, '\\');
2218                 default:
2219                         strbuf_addch(&sb, value[i]);
2220                         break;
2221                 }
2222         strbuf_addf(&sb, "%s\n", quote);
2223
2224         success = write_in_full(fd, sb.buf, sb.len) == sb.len;
2225         strbuf_release(&sb);
2226
2227         return success;
2228 }
2229
2230 static ssize_t find_beginning_of_line(const char *contents, size_t size,
2231         size_t offset_, int *found_bracket)
2232 {
2233         size_t equal_offset = size, bracket_offset = size;
2234         ssize_t offset;
2235
2236 contline:
2237         for (offset = offset_-2; offset > 0
2238                         && contents[offset] != '\n'; offset--)
2239                 switch (contents[offset]) {
2240                         case '=': equal_offset = offset; break;
2241                         case ']': bracket_offset = offset; break;
2242                 }
2243         if (offset > 0 && contents[offset-1] == '\\') {
2244                 offset_ = offset;
2245                 goto contline;
2246         }
2247         if (bracket_offset < equal_offset) {
2248                 *found_bracket = 1;
2249                 offset = bracket_offset+1;
2250         } else
2251                 offset++;
2252
2253         return offset;
2254 }
2255
2256 int git_config_set_in_file_gently(const char *config_filename,
2257                                   const char *key, const char *value)
2258 {
2259         return git_config_set_multivar_in_file_gently(config_filename, key, value, NULL, 0);
2260 }
2261
2262 void git_config_set_in_file(const char *config_filename,
2263                             const char *key, const char *value)
2264 {
2265         git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
2266 }
2267
2268 int git_config_set_gently(const char *key, const char *value)
2269 {
2270         return git_config_set_multivar_gently(key, value, NULL, 0);
2271 }
2272
2273 void git_config_set(const char *key, const char *value)
2274 {
2275         git_config_set_multivar(key, value, NULL, 0);
2276 }
2277
2278 /*
2279  * If value==NULL, unset in (remove from) config,
2280  * if value_regex!=NULL, disregard key/value pairs where value does not match.
2281  * if value_regex==CONFIG_REGEX_NONE, do not match any existing values
2282  *     (only add a new one)
2283  * if multi_replace==0, nothing, or only one matching key/value is replaced,
2284  *     else all matching key/values (regardless how many) are removed,
2285  *     before the new pair is written.
2286  *
2287  * Returns 0 on success.
2288  *
2289  * This function does this:
2290  *
2291  * - it locks the config file by creating ".git/config.lock"
2292  *
2293  * - it then parses the config using store_aux() as validator to find
2294  *   the position on the key/value pair to replace. If it is to be unset,
2295  *   it must be found exactly once.
2296  *
2297  * - the config file is mmap()ed and the part before the match (if any) is
2298  *   written to the lock file, then the changed part and the rest.
2299  *
2300  * - the config file is removed and the lock file rename()d to it.
2301  *
2302  */
2303 int git_config_set_multivar_in_file_gently(const char *config_filename,
2304                                            const char *key, const char *value,
2305                                            const char *value_regex,
2306                                            int multi_replace)
2307 {
2308         int fd = -1, in_fd = -1;
2309         int ret;
2310         struct lock_file *lock = NULL;
2311         char *filename_buf = NULL;
2312         char *contents = NULL;
2313         size_t contents_sz;
2314
2315         /* parse-key returns negative; flip the sign to feed exit(3) */
2316         ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
2317         if (ret)
2318                 goto out_free;
2319
2320         store.multi_replace = multi_replace;
2321
2322         if (!config_filename)
2323                 config_filename = filename_buf = git_pathdup("config");
2324
2325         /*
2326          * The lock serves a purpose in addition to locking: the new
2327          * contents of .git/config will be written into it.
2328          */
2329         lock = xcalloc(1, sizeof(struct lock_file));
2330         fd = hold_lock_file_for_update(lock, config_filename, 0);
2331         if (fd < 0) {
2332                 error_errno("could not lock config file %s", config_filename);
2333                 free(store.key);
2334                 ret = CONFIG_NO_LOCK;
2335                 goto out_free;
2336         }
2337
2338         /*
2339          * If .git/config does not exist yet, write a minimal version.
2340          */
2341         in_fd = open(config_filename, O_RDONLY);
2342         if ( in_fd < 0 ) {
2343                 free(store.key);
2344
2345                 if ( ENOENT != errno ) {
2346                         error_errno("opening %s", config_filename);
2347                         ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
2348                         goto out_free;
2349                 }
2350                 /* if nothing to unset, error out */
2351                 if (value == NULL) {
2352                         ret = CONFIG_NOTHING_SET;
2353                         goto out_free;
2354                 }
2355
2356                 store.key = (char *)key;
2357                 if (!store_write_section(fd, key) ||
2358                     !store_write_pair(fd, key, value))
2359                         goto write_err_out;
2360         } else {
2361                 struct stat st;
2362                 size_t copy_begin, copy_end;
2363                 int i, new_line = 0;
2364
2365                 if (value_regex == NULL)
2366                         store.value_regex = NULL;
2367                 else if (value_regex == CONFIG_REGEX_NONE)
2368                         store.value_regex = CONFIG_REGEX_NONE;
2369                 else {
2370                         if (value_regex[0] == '!') {
2371                                 store.do_not_match = 1;
2372                                 value_regex++;
2373                         } else
2374                                 store.do_not_match = 0;
2375
2376                         store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
2377                         if (regcomp(store.value_regex, value_regex,
2378                                         REG_EXTENDED)) {
2379                                 error("invalid pattern: %s", value_regex);
2380                                 free(store.value_regex);
2381                                 ret = CONFIG_INVALID_PATTERN;
2382                                 goto out_free;
2383                         }
2384                 }
2385
2386                 ALLOC_GROW(store.offset, 1, store.offset_alloc);
2387                 store.offset[0] = 0;
2388                 store.state = START;
2389                 store.seen = 0;
2390
2391                 /*
2392                  * After this, store.offset will contain the *end* offset
2393                  * of the last match, or remain at 0 if no match was found.
2394                  * As a side effect, we make sure to transform only a valid
2395                  * existing config file.
2396                  */
2397                 if (git_config_from_file(store_aux, config_filename, NULL)) {
2398                         error("invalid config file %s", config_filename);
2399                         free(store.key);
2400                         if (store.value_regex != NULL &&
2401                             store.value_regex != CONFIG_REGEX_NONE) {
2402                                 regfree(store.value_regex);
2403                                 free(store.value_regex);
2404                         }
2405                         ret = CONFIG_INVALID_FILE;
2406                         goto out_free;
2407                 }
2408
2409                 free(store.key);
2410                 if (store.value_regex != NULL &&
2411                     store.value_regex != CONFIG_REGEX_NONE) {
2412                         regfree(store.value_regex);
2413                         free(store.value_regex);
2414                 }
2415
2416                 /* if nothing to unset, or too many matches, error out */
2417                 if ((store.seen == 0 && value == NULL) ||
2418                                 (store.seen > 1 && multi_replace == 0)) {
2419                         ret = CONFIG_NOTHING_SET;
2420                         goto out_free;
2421                 }
2422
2423                 if (fstat(in_fd, &st) == -1) {
2424                         error_errno(_("fstat on %s failed"), config_filename);
2425                         ret = CONFIG_INVALID_FILE;
2426                         goto out_free;
2427                 }
2428
2429                 contents_sz = xsize_t(st.st_size);
2430                 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
2431                                         MAP_PRIVATE, in_fd, 0);
2432                 if (contents == MAP_FAILED) {
2433                         if (errno == ENODEV && S_ISDIR(st.st_mode))
2434                                 errno = EISDIR;
2435                         error_errno("unable to mmap '%s'", config_filename);
2436                         ret = CONFIG_INVALID_FILE;
2437                         contents = NULL;
2438                         goto out_free;
2439                 }
2440                 close(in_fd);
2441                 in_fd = -1;
2442
2443                 if (chmod(get_lock_file_path(lock), st.st_mode & 07777) < 0) {
2444                         error_errno("chmod on %s failed", get_lock_file_path(lock));
2445                         ret = CONFIG_NO_WRITE;
2446                         goto out_free;
2447                 }
2448
2449                 if (store.seen == 0)
2450                         store.seen = 1;
2451
2452                 for (i = 0, copy_begin = 0; i < store.seen; i++) {
2453                         if (store.offset[i] == 0) {
2454                                 store.offset[i] = copy_end = contents_sz;
2455                         } else if (store.state != KEY_SEEN) {
2456                                 copy_end = store.offset[i];
2457                         } else
2458                                 copy_end = find_beginning_of_line(
2459                                         contents, contents_sz,
2460                                         store.offset[i]-2, &new_line);
2461
2462                         if (copy_end > 0 && contents[copy_end-1] != '\n')
2463                                 new_line = 1;
2464
2465                         /* write the first part of the config */
2466                         if (copy_end > copy_begin) {
2467                                 if (write_in_full(fd, contents + copy_begin,
2468                                                   copy_end - copy_begin) <
2469                                     copy_end - copy_begin)
2470                                         goto write_err_out;
2471                                 if (new_line &&
2472                                     write_str_in_full(fd, "\n") != 1)
2473                                         goto write_err_out;
2474                         }
2475                         copy_begin = store.offset[i];
2476                 }
2477
2478                 /* write the pair (value == NULL means unset) */
2479                 if (value != NULL) {
2480                         if (store.state == START) {
2481                                 if (!store_write_section(fd, key))
2482                                         goto write_err_out;
2483                         }
2484                         if (!store_write_pair(fd, key, value))
2485                                 goto write_err_out;
2486                 }
2487
2488                 /* write the rest of the config */
2489                 if (copy_begin < contents_sz)
2490                         if (write_in_full(fd, contents + copy_begin,
2491                                           contents_sz - copy_begin) <
2492                             contents_sz - copy_begin)
2493                                 goto write_err_out;
2494
2495                 munmap(contents, contents_sz);
2496                 contents = NULL;
2497         }
2498
2499         if (commit_lock_file(lock) < 0) {
2500                 error_errno("could not write config file %s", config_filename);
2501                 ret = CONFIG_NO_WRITE;
2502                 lock = NULL;
2503                 goto out_free;
2504         }
2505
2506         /*
2507          * lock is committed, so don't try to roll it back below.
2508          * NOTE: Since lockfile.c keeps a linked list of all created
2509          * lock_file structures, it isn't safe to free(lock).  It's
2510          * better to just leave it hanging around.
2511          */
2512         lock = NULL;
2513         ret = 0;
2514
2515         /* Invalidate the config cache */
2516         git_config_clear();
2517
2518 out_free:
2519         if (lock)
2520                 rollback_lock_file(lock);
2521         free(filename_buf);
2522         if (contents)
2523                 munmap(contents, contents_sz);
2524         if (in_fd >= 0)
2525                 close(in_fd);
2526         return ret;
2527
2528 write_err_out:
2529         ret = write_error(get_lock_file_path(lock));
2530         goto out_free;
2531
2532 }
2533
2534 void git_config_set_multivar_in_file(const char *config_filename,
2535                                      const char *key, const char *value,
2536                                      const char *value_regex, int multi_replace)
2537 {
2538         if (!git_config_set_multivar_in_file_gently(config_filename, key, value,
2539                                                     value_regex, multi_replace))
2540                 return;
2541         if (value)
2542                 die(_("could not set '%s' to '%s'"), key, value);
2543         else
2544                 die(_("could not unset '%s'"), key);
2545 }
2546
2547 int git_config_set_multivar_gently(const char *key, const char *value,
2548                                    const char *value_regex, int multi_replace)
2549 {
2550         return git_config_set_multivar_in_file_gently(NULL, key, value, value_regex,
2551                                                       multi_replace);
2552 }
2553
2554 void git_config_set_multivar(const char *key, const char *value,
2555                              const char *value_regex, int multi_replace)
2556 {
2557         git_config_set_multivar_in_file(NULL, key, value, value_regex,
2558                                         multi_replace);
2559 }
2560
2561 static int section_name_match (const char *buf, const char *name)
2562 {
2563         int i = 0, j = 0, dot = 0;
2564         if (buf[i] != '[')
2565                 return 0;
2566         for (i = 1; buf[i] && buf[i] != ']'; i++) {
2567                 if (!dot && isspace(buf[i])) {
2568                         dot = 1;
2569                         if (name[j++] != '.')
2570                                 break;
2571                         for (i++; isspace(buf[i]); i++)
2572                                 ; /* do nothing */
2573                         if (buf[i] != '"')
2574                                 break;
2575                         continue;
2576                 }
2577                 if (buf[i] == '\\' && dot)
2578                         i++;
2579                 else if (buf[i] == '"' && dot) {
2580                         for (i++; isspace(buf[i]); i++)
2581                                 ; /* do_nothing */
2582                         break;
2583                 }
2584                 if (buf[i] != name[j++])
2585                         break;
2586         }
2587         if (buf[i] == ']' && name[j] == 0) {
2588                 /*
2589                  * We match, now just find the right length offset by
2590                  * gobbling up any whitespace after it, as well
2591                  */
2592                 i++;
2593                 for (; buf[i] && isspace(buf[i]); i++)
2594                         ; /* do nothing */
2595                 return i;
2596         }
2597         return 0;
2598 }
2599
2600 static int section_name_is_ok(const char *name)
2601 {
2602         /* Empty section names are bogus. */
2603         if (!*name)
2604                 return 0;
2605
2606         /*
2607          * Before a dot, we must be alphanumeric or dash. After the first dot,
2608          * anything goes, so we can stop checking.
2609          */
2610         for (; *name && *name != '.'; name++)
2611                 if (*name != '-' && !isalnum(*name))
2612                         return 0;
2613         return 1;
2614 }
2615
2616 /* if new_name == NULL, the section is removed instead */
2617 int git_config_rename_section_in_file(const char *config_filename,
2618                                       const char *old_name, const char *new_name)
2619 {
2620         int ret = 0, remove = 0;
2621         char *filename_buf = NULL;
2622         struct lock_file *lock;
2623         int out_fd;
2624         char buf[1024];
2625         FILE *config_file = NULL;
2626         struct stat st;
2627
2628         if (new_name && !section_name_is_ok(new_name)) {
2629                 ret = error("invalid section name: %s", new_name);
2630                 goto out_no_rollback;
2631         }
2632
2633         if (!config_filename)
2634                 config_filename = filename_buf = git_pathdup("config");
2635
2636         lock = xcalloc(1, sizeof(struct lock_file));
2637         out_fd = hold_lock_file_for_update(lock, config_filename, 0);
2638         if (out_fd < 0) {
2639                 ret = error("could not lock config file %s", config_filename);
2640                 goto out;
2641         }
2642
2643         if (!(config_file = fopen(config_filename, "rb"))) {
2644                 /* no config file means nothing to rename, no error */
2645                 goto commit_and_out;
2646         }
2647
2648         if (fstat(fileno(config_file), &st) == -1) {
2649                 ret = error_errno(_("fstat on %s failed"), config_filename);
2650                 goto out;
2651         }
2652
2653         if (chmod(get_lock_file_path(lock), st.st_mode & 07777) < 0) {
2654                 ret = error_errno("chmod on %s failed",
2655                                   get_lock_file_path(lock));
2656                 goto out;
2657         }
2658
2659         while (fgets(buf, sizeof(buf), config_file)) {
2660                 int i;
2661                 int length;
2662                 char *output = buf;
2663                 for (i = 0; buf[i] && isspace(buf[i]); i++)
2664                         ; /* do nothing */
2665                 if (buf[i] == '[') {
2666                         /* it's a section */
2667                         int offset = section_name_match(&buf[i], old_name);
2668                         if (offset > 0) {
2669                                 ret++;
2670                                 if (new_name == NULL) {
2671                                         remove = 1;
2672                                         continue;
2673                                 }
2674                                 store.baselen = strlen(new_name);
2675                                 if (!store_write_section(out_fd, new_name)) {
2676                                         ret = write_error(get_lock_file_path(lock));
2677                                         goto out;
2678                                 }
2679                                 /*
2680                                  * We wrote out the new section, with
2681                                  * a newline, now skip the old
2682                                  * section's length
2683                                  */
2684                                 output += offset + i;
2685                                 if (strlen(output) > 0) {
2686                                         /*
2687                                          * More content means there's
2688                                          * a declaration to put on the
2689                                          * next line; indent with a
2690                                          * tab
2691                                          */
2692                                         output -= 1;
2693                                         output[0] = '\t';
2694                                 }
2695                         }
2696                         remove = 0;
2697                 }
2698                 if (remove)
2699                         continue;
2700                 length = strlen(output);
2701                 if (write_in_full(out_fd, output, length) != length) {
2702                         ret = write_error(get_lock_file_path(lock));
2703                         goto out;
2704                 }
2705         }
2706         fclose(config_file);
2707         config_file = NULL;
2708 commit_and_out:
2709         if (commit_lock_file(lock) < 0)
2710                 ret = error_errno("could not write config file %s",
2711                                   config_filename);
2712 out:
2713         if (config_file)
2714                 fclose(config_file);
2715         rollback_lock_file(lock);
2716 out_no_rollback:
2717         free(filename_buf);
2718         return ret;
2719 }
2720
2721 int git_config_rename_section(const char *old_name, const char *new_name)
2722 {
2723         return git_config_rename_section_in_file(NULL, old_name, new_name);
2724 }
2725
2726 /*
2727  * Call this to report error for your variable that should not
2728  * get a boolean value (i.e. "[my] var" means "true").
2729  */
2730 #undef config_error_nonbool
2731 int config_error_nonbool(const char *var)
2732 {
2733         return error("missing value for '%s'", var);
2734 }
2735
2736 int parse_config_key(const char *var,
2737                      const char *section,
2738                      const char **subsection, int *subsection_len,
2739                      const char **key)
2740 {
2741         const char *dot;
2742
2743         /* Does it start with "section." ? */
2744         if (!skip_prefix(var, section, &var) || *var != '.')
2745                 return -1;
2746
2747         /*
2748          * Find the key; we don't know yet if we have a subsection, but we must
2749          * parse backwards from the end, since the subsection may have dots in
2750          * it, too.
2751          */
2752         dot = strrchr(var, '.');
2753         *key = dot + 1;
2754
2755         /* Did we have a subsection at all? */
2756         if (dot == var) {
2757                 if (subsection) {
2758                         *subsection = NULL;
2759                         *subsection_len = 0;
2760                 }
2761         }
2762         else {
2763                 if (!subsection)
2764                         return -1;
2765                 *subsection = var + 1;
2766                 *subsection_len = dot - *subsection;
2767         }
2768
2769         return 0;
2770 }
2771
2772 const char *current_config_origin_type(void)
2773 {
2774         int type;
2775         if (current_config_kvi)
2776                 type = current_config_kvi->origin_type;
2777         else if(cf)
2778                 type = cf->origin_type;
2779         else
2780                 die("BUG: current_config_origin_type called outside config callback");
2781
2782         switch (type) {
2783         case CONFIG_ORIGIN_BLOB:
2784                 return "blob";
2785         case CONFIG_ORIGIN_FILE:
2786                 return "file";
2787         case CONFIG_ORIGIN_STDIN:
2788                 return "standard input";
2789         case CONFIG_ORIGIN_SUBMODULE_BLOB:
2790                 return "submodule-blob";
2791         case CONFIG_ORIGIN_CMDLINE:
2792                 return "command line";
2793         default:
2794                 die("BUG: unknown config origin type");
2795         }
2796 }
2797
2798 const char *current_config_name(void)
2799 {
2800         const char *name;
2801         if (current_config_kvi)
2802                 name = current_config_kvi->filename;
2803         else if (cf)
2804                 name = cf->name;
2805         else
2806                 die("BUG: current_config_name called outside config callback");
2807         return name ? name : "";
2808 }
2809
2810 enum config_scope current_config_scope(void)
2811 {
2812         if (current_config_kvi)
2813                 return current_config_kvi->scope;
2814         else
2815                 return current_parsing_scope;
2816 }