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