config_buf_ungetc: warn when pushing back a random character
[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 "exec_cmd.h"
10 #include "strbuf.h"
11 #include "quote.h"
12
13 struct config_source {
14         struct config_source *prev;
15         union {
16                 FILE *file;
17                 struct config_buf {
18                         const char *buf;
19                         size_t len;
20                         size_t pos;
21                 } buf;
22         } u;
23         const char *name;
24         const char *path;
25         int die_on_error;
26         int linenr;
27         int eof;
28         struct strbuf value;
29         struct strbuf var;
30
31         int (*do_fgetc)(struct config_source *c);
32         int (*do_ungetc)(int c, struct config_source *conf);
33         long (*do_ftell)(struct config_source *c);
34 };
35
36 static struct config_source *cf;
37
38 static int zlib_compression_seen;
39
40 static int config_file_fgetc(struct config_source *conf)
41 {
42         return fgetc(conf->u.file);
43 }
44
45 static int config_file_ungetc(int c, struct config_source *conf)
46 {
47         return ungetc(c, conf->u.file);
48 }
49
50 static long config_file_ftell(struct config_source *conf)
51 {
52         return ftell(conf->u.file);
53 }
54
55
56 static int config_buf_fgetc(struct config_source *conf)
57 {
58         if (conf->u.buf.pos < conf->u.buf.len)
59                 return conf->u.buf.buf[conf->u.buf.pos++];
60
61         return EOF;
62 }
63
64 static int config_buf_ungetc(int c, struct config_source *conf)
65 {
66         if (conf->u.buf.pos > 0) {
67                 conf->u.buf.pos--;
68                 if (conf->u.buf.buf[conf->u.buf.pos] != c)
69                         die("BUG: config_buf can only ungetc the same character");
70                 return c;
71         }
72
73         return EOF;
74 }
75
76 static long config_buf_ftell(struct config_source *conf)
77 {
78         return conf->u.buf.pos;
79 }
80
81 #define MAX_INCLUDE_DEPTH 10
82 static const char include_depth_advice[] =
83 "exceeded maximum include depth (%d) while including\n"
84 "       %s\n"
85 "from\n"
86 "       %s\n"
87 "Do you have circular includes?";
88 static int handle_path_include(const char *path, struct config_include_data *inc)
89 {
90         int ret = 0;
91         struct strbuf buf = STRBUF_INIT;
92         char *expanded;
93
94         if (!path)
95                 return config_error_nonbool("include.path");
96
97         expanded = expand_user_path(path);
98         if (!expanded)
99                 return error("Could not expand include path '%s'", path);
100         path = expanded;
101
102         /*
103          * Use an absolute path as-is, but interpret relative paths
104          * based on the including config file.
105          */
106         if (!is_absolute_path(path)) {
107                 char *slash;
108
109                 if (!cf || !cf->path)
110                         return error("relative config includes must come from files");
111
112                 slash = find_last_dir_sep(cf->path);
113                 if (slash)
114                         strbuf_add(&buf, cf->path, slash - cf->path + 1);
115                 strbuf_addstr(&buf, path);
116                 path = buf.buf;
117         }
118
119         if (!access_or_die(path, R_OK, 0)) {
120                 if (++inc->depth > MAX_INCLUDE_DEPTH)
121                         die(include_depth_advice, MAX_INCLUDE_DEPTH, path,
122                             cf && cf->name ? cf->name : "the command line");
123                 ret = git_config_from_file(git_config_include, path, inc);
124                 inc->depth--;
125         }
126         strbuf_release(&buf);
127         free(expanded);
128         return ret;
129 }
130
131 int git_config_include(const char *var, const char *value, void *data)
132 {
133         struct config_include_data *inc = data;
134         const char *type;
135         int ret;
136
137         /*
138          * Pass along all values, including "include" directives; this makes it
139          * possible to query information on the includes themselves.
140          */
141         ret = inc->fn(var, value, inc->data);
142         if (ret < 0)
143                 return ret;
144
145         type = skip_prefix(var, "include.");
146         if (!type)
147                 return ret;
148
149         if (!strcmp(type, "path"))
150                 ret = handle_path_include(value, inc);
151         return ret;
152 }
153
154 static void lowercase(char *p)
155 {
156         for (; *p; p++)
157                 *p = tolower(*p);
158 }
159
160 void git_config_push_parameter(const char *text)
161 {
162         struct strbuf env = STRBUF_INIT;
163         const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
164         if (old) {
165                 strbuf_addstr(&env, old);
166                 strbuf_addch(&env, ' ');
167         }
168         sq_quote_buf(&env, text);
169         setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
170         strbuf_release(&env);
171 }
172
173 int git_config_parse_parameter(const char *text,
174                                config_fn_t fn, void *data)
175 {
176         struct strbuf **pair;
177         pair = strbuf_split_str(text, '=', 2);
178         if (!pair[0])
179                 return error("bogus config parameter: %s", text);
180         if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=')
181                 strbuf_setlen(pair[0], pair[0]->len - 1);
182         strbuf_trim(pair[0]);
183         if (!pair[0]->len) {
184                 strbuf_list_free(pair);
185                 return error("bogus config parameter: %s", text);
186         }
187         lowercase(pair[0]->buf);
188         if (fn(pair[0]->buf, pair[1] ? pair[1]->buf : NULL, data) < 0) {
189                 strbuf_list_free(pair);
190                 return -1;
191         }
192         strbuf_list_free(pair);
193         return 0;
194 }
195
196 int git_config_from_parameters(config_fn_t fn, void *data)
197 {
198         const char *env = getenv(CONFIG_DATA_ENVIRONMENT);
199         char *envw;
200         const char **argv = NULL;
201         int nr = 0, alloc = 0;
202         int i;
203
204         if (!env)
205                 return 0;
206         /* sq_dequote will write over it */
207         envw = xstrdup(env);
208
209         if (sq_dequote_to_argv(envw, &argv, &nr, &alloc) < 0) {
210                 free(envw);
211                 return error("bogus format in " CONFIG_DATA_ENVIRONMENT);
212         }
213
214         for (i = 0; i < nr; i++) {
215                 if (git_config_parse_parameter(argv[i], fn, data) < 0) {
216                         free(argv);
217                         free(envw);
218                         return -1;
219                 }
220         }
221
222         free(argv);
223         free(envw);
224         return nr > 0;
225 }
226
227 static int get_next_char(void)
228 {
229         int c = cf->do_fgetc(cf);
230
231         if (c == '\r') {
232                 /* DOS like systems */
233                 c = cf->do_fgetc(cf);
234                 if (c != '\n') {
235                         if (c != EOF)
236                                 cf->do_ungetc(c, cf);
237                         c = '\r';
238                 }
239         }
240         if (c == '\n')
241                 cf->linenr++;
242         if (c == EOF) {
243                 cf->eof = 1;
244                 c = '\n';
245         }
246         return c;
247 }
248
249 static char *parse_value(void)
250 {
251         int quote = 0, comment = 0, space = 0;
252
253         strbuf_reset(&cf->value);
254         for (;;) {
255                 int c = get_next_char();
256                 if (c == '\n') {
257                         if (quote) {
258                                 cf->linenr--;
259                                 return NULL;
260                         }
261                         return cf->value.buf;
262                 }
263                 if (comment)
264                         continue;
265                 if (isspace(c) && !quote) {
266                         if (cf->value.len)
267                                 space++;
268                         continue;
269                 }
270                 if (!quote) {
271                         if (c == ';' || c == '#') {
272                                 comment = 1;
273                                 continue;
274                         }
275                 }
276                 for (; space; space--)
277                         strbuf_addch(&cf->value, ' ');
278                 if (c == '\\') {
279                         c = get_next_char();
280                         switch (c) {
281                         case '\n':
282                                 continue;
283                         case 't':
284                                 c = '\t';
285                                 break;
286                         case 'b':
287                                 c = '\b';
288                                 break;
289                         case 'n':
290                                 c = '\n';
291                                 break;
292                         /* Some characters escape as themselves */
293                         case '\\': case '"':
294                                 break;
295                         /* Reject unknown escape sequences */
296                         default:
297                                 return NULL;
298                         }
299                         strbuf_addch(&cf->value, c);
300                         continue;
301                 }
302                 if (c == '"') {
303                         quote = 1-quote;
304                         continue;
305                 }
306                 strbuf_addch(&cf->value, c);
307         }
308 }
309
310 static inline int iskeychar(int c)
311 {
312         return isalnum(c) || c == '-';
313 }
314
315 static int get_value(config_fn_t fn, void *data, struct strbuf *name)
316 {
317         int c;
318         char *value;
319
320         /* Get the full name */
321         for (;;) {
322                 c = get_next_char();
323                 if (cf->eof)
324                         break;
325                 if (!iskeychar(c))
326                         break;
327                 strbuf_addch(name, tolower(c));
328         }
329
330         while (c == ' ' || c == '\t')
331                 c = get_next_char();
332
333         value = NULL;
334         if (c != '\n') {
335                 if (c != '=')
336                         return -1;
337                 value = parse_value();
338                 if (!value)
339                         return -1;
340         }
341         return fn(name->buf, value, data);
342 }
343
344 static int get_extended_base_var(struct strbuf *name, int c)
345 {
346         do {
347                 if (c == '\n')
348                         goto error_incomplete_line;
349                 c = get_next_char();
350         } while (isspace(c));
351
352         /* We require the format to be '[base "extension"]' */
353         if (c != '"')
354                 return -1;
355         strbuf_addch(name, '.');
356
357         for (;;) {
358                 int c = get_next_char();
359                 if (c == '\n')
360                         goto error_incomplete_line;
361                 if (c == '"')
362                         break;
363                 if (c == '\\') {
364                         c = get_next_char();
365                         if (c == '\n')
366                                 goto error_incomplete_line;
367                 }
368                 strbuf_addch(name, c);
369         }
370
371         /* Final ']' */
372         if (get_next_char() != ']')
373                 return -1;
374         return 0;
375 error_incomplete_line:
376         cf->linenr--;
377         return -1;
378 }
379
380 static int get_base_var(struct strbuf *name)
381 {
382         for (;;) {
383                 int c = get_next_char();
384                 if (cf->eof)
385                         return -1;
386                 if (c == ']')
387                         return 0;
388                 if (isspace(c))
389                         return get_extended_base_var(name, c);
390                 if (!iskeychar(c) && c != '.')
391                         return -1;
392                 strbuf_addch(name, tolower(c));
393         }
394 }
395
396 static int git_parse_source(config_fn_t fn, void *data)
397 {
398         int comment = 0;
399         int baselen = 0;
400         struct strbuf *var = &cf->var;
401
402         /* U+FEFF Byte Order Mark in UTF8 */
403         static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
404         const unsigned char *bomptr = utf8_bom;
405
406         for (;;) {
407                 int c = get_next_char();
408                 if (bomptr && *bomptr) {
409                         /* We are at the file beginning; skip UTF8-encoded BOM
410                          * if present. Sane editors won't put this in on their
411                          * own, but e.g. Windows Notepad will do it happily. */
412                         if ((unsigned char) c == *bomptr) {
413                                 bomptr++;
414                                 continue;
415                         } else {
416                                 /* Do not tolerate partial BOM. */
417                                 if (bomptr != utf8_bom)
418                                         break;
419                                 /* No BOM at file beginning. Cool. */
420                                 bomptr = NULL;
421                         }
422                 }
423                 if (c == '\n') {
424                         if (cf->eof)
425                                 return 0;
426                         comment = 0;
427                         continue;
428                 }
429                 if (comment || isspace(c))
430                         continue;
431                 if (c == '#' || c == ';') {
432                         comment = 1;
433                         continue;
434                 }
435                 if (c == '[') {
436                         /* Reset prior to determining a new stem */
437                         strbuf_reset(var);
438                         if (get_base_var(var) < 0 || var->len < 1)
439                                 break;
440                         strbuf_addch(var, '.');
441                         baselen = var->len;
442                         continue;
443                 }
444                 if (!isalpha(c))
445                         break;
446                 /*
447                  * Truncate the var name back to the section header
448                  * stem prior to grabbing the suffix part of the name
449                  * and the value.
450                  */
451                 strbuf_setlen(var, baselen);
452                 strbuf_addch(var, tolower(c));
453                 if (get_value(fn, data, var) < 0)
454                         break;
455         }
456         if (cf->die_on_error)
457                 die("bad config file line %d in %s", cf->linenr, cf->name);
458         else
459                 return error("bad config file line %d in %s", cf->linenr, cf->name);
460 }
461
462 static int parse_unit_factor(const char *end, uintmax_t *val)
463 {
464         if (!*end)
465                 return 1;
466         else if (!strcasecmp(end, "k")) {
467                 *val *= 1024;
468                 return 1;
469         }
470         else if (!strcasecmp(end, "m")) {
471                 *val *= 1024 * 1024;
472                 return 1;
473         }
474         else if (!strcasecmp(end, "g")) {
475                 *val *= 1024 * 1024 * 1024;
476                 return 1;
477         }
478         return 0;
479 }
480
481 static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
482 {
483         if (value && *value) {
484                 char *end;
485                 intmax_t val;
486                 uintmax_t uval;
487                 uintmax_t factor = 1;
488
489                 errno = 0;
490                 val = strtoimax(value, &end, 0);
491                 if (errno == ERANGE)
492                         return 0;
493                 if (!parse_unit_factor(end, &factor)) {
494                         errno = EINVAL;
495                         return 0;
496                 }
497                 uval = abs(val);
498                 uval *= factor;
499                 if (uval > max || abs(val) > uval) {
500                         errno = ERANGE;
501                         return 0;
502                 }
503                 val *= factor;
504                 *ret = val;
505                 return 1;
506         }
507         errno = EINVAL;
508         return 0;
509 }
510
511 static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
512 {
513         if (value && *value) {
514                 char *end;
515                 uintmax_t val;
516                 uintmax_t oldval;
517
518                 errno = 0;
519                 val = strtoumax(value, &end, 0);
520                 if (errno == ERANGE)
521                         return 0;
522                 oldval = val;
523                 if (!parse_unit_factor(end, &val)) {
524                         errno = EINVAL;
525                         return 0;
526                 }
527                 if (val > max || oldval > val) {
528                         errno = ERANGE;
529                         return 0;
530                 }
531                 *ret = val;
532                 return 1;
533         }
534         errno = EINVAL;
535         return 0;
536 }
537
538 static int git_parse_int(const char *value, int *ret)
539 {
540         intmax_t tmp;
541         if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
542                 return 0;
543         *ret = tmp;
544         return 1;
545 }
546
547 static int git_parse_int64(const char *value, int64_t *ret)
548 {
549         intmax_t tmp;
550         if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
551                 return 0;
552         *ret = tmp;
553         return 1;
554 }
555
556 int git_parse_ulong(const char *value, unsigned long *ret)
557 {
558         uintmax_t tmp;
559         if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
560                 return 0;
561         *ret = tmp;
562         return 1;
563 }
564
565 NORETURN
566 static void die_bad_number(const char *name, const char *value)
567 {
568         const char *reason = errno == ERANGE ?
569                              "out of range" :
570                              "invalid unit";
571         if (!value)
572                 value = "";
573
574         if (cf && cf->name)
575                 die("bad numeric config value '%s' for '%s' in %s: %s",
576                     value, name, cf->name, reason);
577         die("bad numeric config value '%s' for '%s': %s", value, name, reason);
578 }
579
580 int git_config_int(const char *name, const char *value)
581 {
582         int ret;
583         if (!git_parse_int(value, &ret))
584                 die_bad_number(name, value);
585         return ret;
586 }
587
588 int64_t git_config_int64(const char *name, const char *value)
589 {
590         int64_t ret;
591         if (!git_parse_int64(value, &ret))
592                 die_bad_number(name, value);
593         return ret;
594 }
595
596 unsigned long git_config_ulong(const char *name, const char *value)
597 {
598         unsigned long ret;
599         if (!git_parse_ulong(value, &ret))
600                 die_bad_number(name, value);
601         return ret;
602 }
603
604 static int git_config_maybe_bool_text(const char *name, const char *value)
605 {
606         if (!value)
607                 return 1;
608         if (!*value)
609                 return 0;
610         if (!strcasecmp(value, "true")
611             || !strcasecmp(value, "yes")
612             || !strcasecmp(value, "on"))
613                 return 1;
614         if (!strcasecmp(value, "false")
615             || !strcasecmp(value, "no")
616             || !strcasecmp(value, "off"))
617                 return 0;
618         return -1;
619 }
620
621 int git_config_maybe_bool(const char *name, const char *value)
622 {
623         int v = git_config_maybe_bool_text(name, value);
624         if (0 <= v)
625                 return v;
626         if (git_parse_int(value, &v))
627                 return !!v;
628         return -1;
629 }
630
631 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
632 {
633         int v = git_config_maybe_bool_text(name, value);
634         if (0 <= v) {
635                 *is_bool = 1;
636                 return v;
637         }
638         *is_bool = 0;
639         return git_config_int(name, value);
640 }
641
642 int git_config_bool(const char *name, const char *value)
643 {
644         int discard;
645         return !!git_config_bool_or_int(name, value, &discard);
646 }
647
648 int git_config_string(const char **dest, const char *var, const char *value)
649 {
650         if (!value)
651                 return config_error_nonbool(var);
652         *dest = xstrdup(value);
653         return 0;
654 }
655
656 int git_config_pathname(const char **dest, const char *var, const char *value)
657 {
658         if (!value)
659                 return config_error_nonbool(var);
660         *dest = expand_user_path(value);
661         if (!*dest)
662                 die("Failed to expand user dir in: '%s'", value);
663         return 0;
664 }
665
666 static int git_default_core_config(const char *var, const char *value)
667 {
668         /* This needs a better name */
669         if (!strcmp(var, "core.filemode")) {
670                 trust_executable_bit = git_config_bool(var, value);
671                 return 0;
672         }
673         if (!strcmp(var, "core.trustctime")) {
674                 trust_ctime = git_config_bool(var, value);
675                 return 0;
676         }
677         if (!strcmp(var, "core.checkstat")) {
678                 if (!strcasecmp(value, "default"))
679                         check_stat = 1;
680                 else if (!strcasecmp(value, "minimal"))
681                         check_stat = 0;
682         }
683
684         if (!strcmp(var, "core.quotepath")) {
685                 quote_path_fully = git_config_bool(var, value);
686                 return 0;
687         }
688
689         if (!strcmp(var, "core.symlinks")) {
690                 has_symlinks = git_config_bool(var, value);
691                 return 0;
692         }
693
694         if (!strcmp(var, "core.ignorecase")) {
695                 ignore_case = git_config_bool(var, value);
696                 return 0;
697         }
698
699         if (!strcmp(var, "core.attributesfile"))
700                 return git_config_pathname(&git_attributes_file, var, value);
701
702         if (!strcmp(var, "core.bare")) {
703                 is_bare_repository_cfg = git_config_bool(var, value);
704                 return 0;
705         }
706
707         if (!strcmp(var, "core.ignorestat")) {
708                 assume_unchanged = git_config_bool(var, value);
709                 return 0;
710         }
711
712         if (!strcmp(var, "core.prefersymlinkrefs")) {
713                 prefer_symlink_refs = git_config_bool(var, value);
714                 return 0;
715         }
716
717         if (!strcmp(var, "core.logallrefupdates")) {
718                 log_all_ref_updates = git_config_bool(var, value);
719                 return 0;
720         }
721
722         if (!strcmp(var, "core.warnambiguousrefs")) {
723                 warn_ambiguous_refs = git_config_bool(var, value);
724                 return 0;
725         }
726
727         if (!strcmp(var, "core.abbrev")) {
728                 int abbrev = git_config_int(var, value);
729                 if (abbrev < minimum_abbrev || abbrev > 40)
730                         return -1;
731                 default_abbrev = abbrev;
732                 return 0;
733         }
734
735         if (!strcmp(var, "core.loosecompression")) {
736                 int level = git_config_int(var, value);
737                 if (level == -1)
738                         level = Z_DEFAULT_COMPRESSION;
739                 else if (level < 0 || level > Z_BEST_COMPRESSION)
740                         die("bad zlib compression level %d", level);
741                 zlib_compression_level = level;
742                 zlib_compression_seen = 1;
743                 return 0;
744         }
745
746         if (!strcmp(var, "core.compression")) {
747                 int level = git_config_int(var, value);
748                 if (level == -1)
749                         level = Z_DEFAULT_COMPRESSION;
750                 else if (level < 0 || level > Z_BEST_COMPRESSION)
751                         die("bad zlib compression level %d", level);
752                 core_compression_level = level;
753                 core_compression_seen = 1;
754                 if (!zlib_compression_seen)
755                         zlib_compression_level = level;
756                 return 0;
757         }
758
759         if (!strcmp(var, "core.packedgitwindowsize")) {
760                 int pgsz_x2 = getpagesize() * 2;
761                 packed_git_window_size = git_config_ulong(var, value);
762
763                 /* This value must be multiple of (pagesize * 2) */
764                 packed_git_window_size /= pgsz_x2;
765                 if (packed_git_window_size < 1)
766                         packed_git_window_size = 1;
767                 packed_git_window_size *= pgsz_x2;
768                 return 0;
769         }
770
771         if (!strcmp(var, "core.bigfilethreshold")) {
772                 big_file_threshold = git_config_ulong(var, value);
773                 return 0;
774         }
775
776         if (!strcmp(var, "core.packedgitlimit")) {
777                 packed_git_limit = git_config_ulong(var, value);
778                 return 0;
779         }
780
781         if (!strcmp(var, "core.deltabasecachelimit")) {
782                 delta_base_cache_limit = git_config_ulong(var, value);
783                 return 0;
784         }
785
786         if (!strcmp(var, "core.autocrlf")) {
787                 if (value && !strcasecmp(value, "input")) {
788                         if (core_eol == EOL_CRLF)
789                                 return error("core.autocrlf=input conflicts with core.eol=crlf");
790                         auto_crlf = AUTO_CRLF_INPUT;
791                         return 0;
792                 }
793                 auto_crlf = git_config_bool(var, value);
794                 return 0;
795         }
796
797         if (!strcmp(var, "core.safecrlf")) {
798                 if (value && !strcasecmp(value, "warn")) {
799                         safe_crlf = SAFE_CRLF_WARN;
800                         return 0;
801                 }
802                 safe_crlf = git_config_bool(var, value);
803                 return 0;
804         }
805
806         if (!strcmp(var, "core.eol")) {
807                 if (value && !strcasecmp(value, "lf"))
808                         core_eol = EOL_LF;
809                 else if (value && !strcasecmp(value, "crlf"))
810                         core_eol = EOL_CRLF;
811                 else if (value && !strcasecmp(value, "native"))
812                         core_eol = EOL_NATIVE;
813                 else
814                         core_eol = EOL_UNSET;
815                 if (core_eol == EOL_CRLF && auto_crlf == AUTO_CRLF_INPUT)
816                         return error("core.autocrlf=input conflicts with core.eol=crlf");
817                 return 0;
818         }
819
820         if (!strcmp(var, "core.notesref")) {
821                 notes_ref_name = xstrdup(value);
822                 return 0;
823         }
824
825         if (!strcmp(var, "core.pager"))
826                 return git_config_string(&pager_program, var, value);
827
828         if (!strcmp(var, "core.editor"))
829                 return git_config_string(&editor_program, var, value);
830
831         if (!strcmp(var, "core.commentchar")) {
832                 const char *comment;
833                 int ret = git_config_string(&comment, var, value);
834                 if (!ret)
835                         comment_line_char = comment[0];
836                 return ret;
837         }
838
839         if (!strcmp(var, "core.askpass"))
840                 return git_config_string(&askpass_program, var, value);
841
842         if (!strcmp(var, "core.excludesfile"))
843                 return git_config_pathname(&excludes_file, var, value);
844
845         if (!strcmp(var, "core.whitespace")) {
846                 if (!value)
847                         return config_error_nonbool(var);
848                 whitespace_rule_cfg = parse_whitespace_rule(value);
849                 return 0;
850         }
851
852         if (!strcmp(var, "core.fsyncobjectfiles")) {
853                 fsync_object_files = git_config_bool(var, value);
854                 return 0;
855         }
856
857         if (!strcmp(var, "core.preloadindex")) {
858                 core_preload_index = git_config_bool(var, value);
859                 return 0;
860         }
861
862         if (!strcmp(var, "core.createobject")) {
863                 if (!strcmp(value, "rename"))
864                         object_creation_mode = OBJECT_CREATION_USES_RENAMES;
865                 else if (!strcmp(value, "link"))
866                         object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
867                 else
868                         die("Invalid mode for object creation: %s", value);
869                 return 0;
870         }
871
872         if (!strcmp(var, "core.sparsecheckout")) {
873                 core_apply_sparse_checkout = git_config_bool(var, value);
874                 return 0;
875         }
876
877         if (!strcmp(var, "core.precomposeunicode")) {
878                 precomposed_unicode = git_config_bool(var, value);
879                 return 0;
880         }
881
882         if (!strcmp(var, "core.protecthfs")) {
883                 protect_hfs = git_config_bool(var, value);
884                 return 0;
885         }
886
887         if (!strcmp(var, "core.protectntfs")) {
888                 protect_ntfs = git_config_bool(var, value);
889                 return 0;
890         }
891
892         /* Add other config variables here and to Documentation/config.txt. */
893         return 0;
894 }
895
896 static int git_default_i18n_config(const char *var, const char *value)
897 {
898         if (!strcmp(var, "i18n.commitencoding"))
899                 return git_config_string(&git_commit_encoding, var, value);
900
901         if (!strcmp(var, "i18n.logoutputencoding"))
902                 return git_config_string(&git_log_output_encoding, var, value);
903
904         /* Add other config variables here and to Documentation/config.txt. */
905         return 0;
906 }
907
908 static int git_default_branch_config(const char *var, const char *value)
909 {
910         if (!strcmp(var, "branch.autosetupmerge")) {
911                 if (value && !strcasecmp(value, "always")) {
912                         git_branch_track = BRANCH_TRACK_ALWAYS;
913                         return 0;
914                 }
915                 git_branch_track = git_config_bool(var, value);
916                 return 0;
917         }
918         if (!strcmp(var, "branch.autosetuprebase")) {
919                 if (!value)
920                         return config_error_nonbool(var);
921                 else if (!strcmp(value, "never"))
922                         autorebase = AUTOREBASE_NEVER;
923                 else if (!strcmp(value, "local"))
924                         autorebase = AUTOREBASE_LOCAL;
925                 else if (!strcmp(value, "remote"))
926                         autorebase = AUTOREBASE_REMOTE;
927                 else if (!strcmp(value, "always"))
928                         autorebase = AUTOREBASE_ALWAYS;
929                 else
930                         return error("Malformed value for %s", var);
931                 return 0;
932         }
933
934         /* Add other config variables here and to Documentation/config.txt. */
935         return 0;
936 }
937
938 static int git_default_push_config(const char *var, const char *value)
939 {
940         if (!strcmp(var, "push.default")) {
941                 if (!value)
942                         return config_error_nonbool(var);
943                 else if (!strcmp(value, "nothing"))
944                         push_default = PUSH_DEFAULT_NOTHING;
945                 else if (!strcmp(value, "matching"))
946                         push_default = PUSH_DEFAULT_MATCHING;
947                 else if (!strcmp(value, "simple"))
948                         push_default = PUSH_DEFAULT_SIMPLE;
949                 else if (!strcmp(value, "upstream"))
950                         push_default = PUSH_DEFAULT_UPSTREAM;
951                 else if (!strcmp(value, "tracking")) /* deprecated */
952                         push_default = PUSH_DEFAULT_UPSTREAM;
953                 else if (!strcmp(value, "current"))
954                         push_default = PUSH_DEFAULT_CURRENT;
955                 else {
956                         error("Malformed value for %s: %s", var, value);
957                         return error("Must be one of nothing, matching, simple, "
958                                      "upstream or current.");
959                 }
960                 return 0;
961         }
962
963         /* Add other config variables here and to Documentation/config.txt. */
964         return 0;
965 }
966
967 static int git_default_mailmap_config(const char *var, const char *value)
968 {
969         if (!strcmp(var, "mailmap.file"))
970                 return git_config_pathname(&git_mailmap_file, var, value);
971         if (!strcmp(var, "mailmap.blob"))
972                 return git_config_string(&git_mailmap_blob, var, value);
973
974         /* Add other config variables here and to Documentation/config.txt. */
975         return 0;
976 }
977
978 int git_default_config(const char *var, const char *value, void *dummy)
979 {
980         if (starts_with(var, "core."))
981                 return git_default_core_config(var, value);
982
983         if (starts_with(var, "user."))
984                 return git_ident_config(var, value, dummy);
985
986         if (starts_with(var, "i18n."))
987                 return git_default_i18n_config(var, value);
988
989         if (starts_with(var, "branch."))
990                 return git_default_branch_config(var, value);
991
992         if (starts_with(var, "push."))
993                 return git_default_push_config(var, value);
994
995         if (starts_with(var, "mailmap."))
996                 return git_default_mailmap_config(var, value);
997
998         if (starts_with(var, "advice."))
999                 return git_default_advice_config(var, value);
1000
1001         if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1002                 pager_use_color = git_config_bool(var,value);
1003                 return 0;
1004         }
1005
1006         if (!strcmp(var, "pack.packsizelimit")) {
1007                 pack_size_limit_cfg = git_config_ulong(var, value);
1008                 return 0;
1009         }
1010         /* Add other config variables here and to Documentation/config.txt. */
1011         return 0;
1012 }
1013
1014 /*
1015  * All source specific fields in the union, die_on_error, name and the callbacks
1016  * fgetc, ungetc, ftell of top need to be initialized before calling
1017  * this function.
1018  */
1019 static int do_config_from(struct config_source *top, config_fn_t fn, void *data)
1020 {
1021         int ret;
1022
1023         /* push config-file parsing state stack */
1024         top->prev = cf;
1025         top->linenr = 1;
1026         top->eof = 0;
1027         strbuf_init(&top->value, 1024);
1028         strbuf_init(&top->var, 1024);
1029         cf = top;
1030
1031         ret = git_parse_source(fn, data);
1032
1033         /* pop config-file parsing state stack */
1034         strbuf_release(&top->value);
1035         strbuf_release(&top->var);
1036         cf = top->prev;
1037
1038         return ret;
1039 }
1040
1041 static int do_config_from_file(config_fn_t fn,
1042                 const char *name, const char *path, FILE *f, void *data)
1043 {
1044         struct config_source top;
1045
1046         top.u.file = f;
1047         top.name = name;
1048         top.path = path;
1049         top.die_on_error = 1;
1050         top.do_fgetc = config_file_fgetc;
1051         top.do_ungetc = config_file_ungetc;
1052         top.do_ftell = config_file_ftell;
1053
1054         return do_config_from(&top, fn, data);
1055 }
1056
1057 static int git_config_from_stdin(config_fn_t fn, void *data)
1058 {
1059         return do_config_from_file(fn, "<stdin>", NULL, stdin, data);
1060 }
1061
1062 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
1063 {
1064         int ret = -1;
1065         FILE *f;
1066
1067         f = fopen(filename, "r");
1068         if (f) {
1069                 ret = do_config_from_file(fn, filename, filename, f, data);
1070                 fclose(f);
1071         }
1072         return ret;
1073 }
1074
1075 int git_config_from_buf(config_fn_t fn, const char *name, const char *buf,
1076                         size_t len, void *data)
1077 {
1078         struct config_source top;
1079
1080         top.u.buf.buf = buf;
1081         top.u.buf.len = len;
1082         top.u.buf.pos = 0;
1083         top.name = name;
1084         top.path = NULL;
1085         top.die_on_error = 0;
1086         top.do_fgetc = config_buf_fgetc;
1087         top.do_ungetc = config_buf_ungetc;
1088         top.do_ftell = config_buf_ftell;
1089
1090         return do_config_from(&top, fn, data);
1091 }
1092
1093 static int git_config_from_blob_sha1(config_fn_t fn,
1094                                      const char *name,
1095                                      const unsigned char *sha1,
1096                                      void *data)
1097 {
1098         enum object_type type;
1099         char *buf;
1100         unsigned long size;
1101         int ret;
1102
1103         buf = read_sha1_file(sha1, &type, &size);
1104         if (!buf)
1105                 return error("unable to load config blob object '%s'", name);
1106         if (type != OBJ_BLOB) {
1107                 free(buf);
1108                 return error("reference '%s' does not point to a blob", name);
1109         }
1110
1111         ret = git_config_from_buf(fn, name, buf, size, data);
1112         free(buf);
1113
1114         return ret;
1115 }
1116
1117 static int git_config_from_blob_ref(config_fn_t fn,
1118                                     const char *name,
1119                                     void *data)
1120 {
1121         unsigned char sha1[20];
1122
1123         if (get_sha1(name, sha1) < 0)
1124                 return error("unable to resolve config blob '%s'", name);
1125         return git_config_from_blob_sha1(fn, name, sha1, data);
1126 }
1127
1128 const char *git_etc_gitconfig(void)
1129 {
1130         static const char *system_wide;
1131         if (!system_wide)
1132                 system_wide = system_path(ETC_GITCONFIG);
1133         return system_wide;
1134 }
1135
1136 int git_env_bool(const char *k, int def)
1137 {
1138         const char *v = getenv(k);
1139         return v ? git_config_bool(k, v) : def;
1140 }
1141
1142 int git_config_system(void)
1143 {
1144         return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
1145 }
1146
1147 int git_config_early(config_fn_t fn, void *data, const char *repo_config)
1148 {
1149         int ret = 0, found = 0;
1150         char *xdg_config = NULL;
1151         char *user_config = NULL;
1152
1153         home_config_paths(&user_config, &xdg_config, "config");
1154
1155         if (git_config_system() && !access_or_die(git_etc_gitconfig(), R_OK, 0)) {
1156                 ret += git_config_from_file(fn, git_etc_gitconfig(),
1157                                             data);
1158                 found += 1;
1159         }
1160
1161         if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK)) {
1162                 ret += git_config_from_file(fn, xdg_config, data);
1163                 found += 1;
1164         }
1165
1166         if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK)) {
1167                 ret += git_config_from_file(fn, user_config, data);
1168                 found += 1;
1169         }
1170
1171         if (repo_config && !access_or_die(repo_config, R_OK, 0)) {
1172                 ret += git_config_from_file(fn, repo_config, data);
1173                 found += 1;
1174         }
1175
1176         switch (git_config_from_parameters(fn, data)) {
1177         case -1: /* error */
1178                 die("unable to parse command-line config");
1179                 break;
1180         case 0: /* found nothing */
1181                 break;
1182         default: /* found at least one item */
1183                 found++;
1184                 break;
1185         }
1186
1187         free(xdg_config);
1188         free(user_config);
1189         return ret == 0 ? found : ret;
1190 }
1191
1192 int git_config_with_options(config_fn_t fn, void *data,
1193                             struct git_config_source *config_source,
1194                             int respect_includes)
1195 {
1196         char *repo_config = NULL;
1197         int ret;
1198         struct config_include_data inc = CONFIG_INCLUDE_INIT;
1199
1200         if (respect_includes) {
1201                 inc.fn = fn;
1202                 inc.data = data;
1203                 fn = git_config_include;
1204                 data = &inc;
1205         }
1206
1207         /*
1208          * If we have a specific filename, use it. Otherwise, follow the
1209          * regular lookup sequence.
1210          */
1211         if (config_source && config_source->use_stdin)
1212                 return git_config_from_stdin(fn, data);
1213         else if (config_source && config_source->file)
1214                 return git_config_from_file(fn, config_source->file, data);
1215         else if (config_source && config_source->blob)
1216                 return git_config_from_blob_ref(fn, config_source->blob, data);
1217
1218         repo_config = git_pathdup("config");
1219         ret = git_config_early(fn, data, repo_config);
1220         if (repo_config)
1221                 free(repo_config);
1222         return ret;
1223 }
1224
1225 int git_config(config_fn_t fn, void *data)
1226 {
1227         return git_config_with_options(fn, data, NULL, 1);
1228 }
1229
1230 /*
1231  * Find all the stuff for git_config_set() below.
1232  */
1233
1234 static struct {
1235         int baselen;
1236         char *key;
1237         int do_not_match;
1238         regex_t *value_regex;
1239         int multi_replace;
1240         size_t *offset;
1241         unsigned int offset_alloc;
1242         enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
1243         int seen;
1244 } store;
1245
1246 static int matches(const char *key, const char *value)
1247 {
1248         return !strcmp(key, store.key) &&
1249                 (store.value_regex == NULL ||
1250                  (store.do_not_match ^
1251                   !regexec(store.value_regex, value, 0, NULL, 0)));
1252 }
1253
1254 static int store_aux(const char *key, const char *value, void *cb)
1255 {
1256         const char *ep;
1257         size_t section_len;
1258
1259         switch (store.state) {
1260         case KEY_SEEN:
1261                 if (matches(key, value)) {
1262                         if (store.seen == 1 && store.multi_replace == 0) {
1263                                 warning("%s has multiple values", key);
1264                         }
1265
1266                         ALLOC_GROW(store.offset, store.seen + 1,
1267                                    store.offset_alloc);
1268
1269                         store.offset[store.seen] = cf->do_ftell(cf);
1270                         store.seen++;
1271                 }
1272                 break;
1273         case SECTION_SEEN:
1274                 /*
1275                  * What we are looking for is in store.key (both
1276                  * section and var), and its section part is baselen
1277                  * long.  We found key (again, both section and var).
1278                  * We would want to know if this key is in the same
1279                  * section as what we are looking for.  We already
1280                  * know we are in the same section as what should
1281                  * hold store.key.
1282                  */
1283                 ep = strrchr(key, '.');
1284                 section_len = ep - key;
1285
1286                 if ((section_len != store.baselen) ||
1287                     memcmp(key, store.key, section_len+1)) {
1288                         store.state = SECTION_END_SEEN;
1289                         break;
1290                 }
1291
1292                 /*
1293                  * Do not increment matches: this is no match, but we
1294                  * just made sure we are in the desired section.
1295                  */
1296                 ALLOC_GROW(store.offset, store.seen + 1,
1297                            store.offset_alloc);
1298                 store.offset[store.seen] = cf->do_ftell(cf);
1299                 /* fallthru */
1300         case SECTION_END_SEEN:
1301         case START:
1302                 if (matches(key, value)) {
1303                         ALLOC_GROW(store.offset, store.seen + 1,
1304                                    store.offset_alloc);
1305                         store.offset[store.seen] = cf->do_ftell(cf);
1306                         store.state = KEY_SEEN;
1307                         store.seen++;
1308                 } else {
1309                         if (strrchr(key, '.') - key == store.baselen &&
1310                               !strncmp(key, store.key, store.baselen)) {
1311                                         store.state = SECTION_SEEN;
1312                                         ALLOC_GROW(store.offset,
1313                                                    store.seen + 1,
1314                                                    store.offset_alloc);
1315                                         store.offset[store.seen] = cf->do_ftell(cf);
1316                         }
1317                 }
1318         }
1319         return 0;
1320 }
1321
1322 static int write_error(const char *filename)
1323 {
1324         error("failed to write new configuration file %s", filename);
1325
1326         /* Same error code as "failed to rename". */
1327         return 4;
1328 }
1329
1330 static int store_write_section(int fd, const char *key)
1331 {
1332         const char *dot;
1333         int i, success;
1334         struct strbuf sb = STRBUF_INIT;
1335
1336         dot = memchr(key, '.', store.baselen);
1337         if (dot) {
1338                 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
1339                 for (i = dot - key + 1; i < store.baselen; i++) {
1340                         if (key[i] == '"' || key[i] == '\\')
1341                                 strbuf_addch(&sb, '\\');
1342                         strbuf_addch(&sb, key[i]);
1343                 }
1344                 strbuf_addstr(&sb, "\"]\n");
1345         } else {
1346                 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
1347         }
1348
1349         success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1350         strbuf_release(&sb);
1351
1352         return success;
1353 }
1354
1355 static int store_write_pair(int fd, const char *key, const char *value)
1356 {
1357         int i, success;
1358         int length = strlen(key + store.baselen + 1);
1359         const char *quote = "";
1360         struct strbuf sb = STRBUF_INIT;
1361
1362         /*
1363          * Check to see if the value needs to be surrounded with a dq pair.
1364          * Note that problematic characters are always backslash-quoted; this
1365          * check is about not losing leading or trailing SP and strings that
1366          * follow beginning-of-comment characters (i.e. ';' and '#') by the
1367          * configuration parser.
1368          */
1369         if (value[0] == ' ')
1370                 quote = "\"";
1371         for (i = 0; value[i]; i++)
1372                 if (value[i] == ';' || value[i] == '#')
1373                         quote = "\"";
1374         if (i && value[i - 1] == ' ')
1375                 quote = "\"";
1376
1377         strbuf_addf(&sb, "\t%.*s = %s",
1378                     length, key + store.baselen + 1, quote);
1379
1380         for (i = 0; value[i]; i++)
1381                 switch (value[i]) {
1382                 case '\n':
1383                         strbuf_addstr(&sb, "\\n");
1384                         break;
1385                 case '\t':
1386                         strbuf_addstr(&sb, "\\t");
1387                         break;
1388                 case '"':
1389                 case '\\':
1390                         strbuf_addch(&sb, '\\');
1391                 default:
1392                         strbuf_addch(&sb, value[i]);
1393                         break;
1394                 }
1395         strbuf_addf(&sb, "%s\n", quote);
1396
1397         success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1398         strbuf_release(&sb);
1399
1400         return success;
1401 }
1402
1403 static ssize_t find_beginning_of_line(const char *contents, size_t size,
1404         size_t offset_, int *found_bracket)
1405 {
1406         size_t equal_offset = size, bracket_offset = size;
1407         ssize_t offset;
1408
1409 contline:
1410         for (offset = offset_-2; offset > 0
1411                         && contents[offset] != '\n'; offset--)
1412                 switch (contents[offset]) {
1413                         case '=': equal_offset = offset; break;
1414                         case ']': bracket_offset = offset; break;
1415                 }
1416         if (offset > 0 && contents[offset-1] == '\\') {
1417                 offset_ = offset;
1418                 goto contline;
1419         }
1420         if (bracket_offset < equal_offset) {
1421                 *found_bracket = 1;
1422                 offset = bracket_offset+1;
1423         } else
1424                 offset++;
1425
1426         return offset;
1427 }
1428
1429 int git_config_set_in_file(const char *config_filename,
1430                         const char *key, const char *value)
1431 {
1432         return git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
1433 }
1434
1435 int git_config_set(const char *key, const char *value)
1436 {
1437         return git_config_set_multivar(key, value, NULL, 0);
1438 }
1439
1440 /*
1441  * Auxiliary function to sanity-check and split the key into the section
1442  * identifier and variable name.
1443  *
1444  * Returns 0 on success, -1 when there is an invalid character in the key and
1445  * -2 if there is no section name in the key.
1446  *
1447  * store_key - pointer to char* which will hold a copy of the key with
1448  *             lowercase section and variable name
1449  * baselen - pointer to int which will hold the length of the
1450  *           section + subsection part, can be NULL
1451  */
1452 int git_config_parse_key(const char *key, char **store_key, int *baselen_)
1453 {
1454         int i, dot, baselen;
1455         const char *last_dot = strrchr(key, '.');
1456
1457         /*
1458          * Since "key" actually contains the section name and the real
1459          * key name separated by a dot, we have to know where the dot is.
1460          */
1461
1462         if (last_dot == NULL || last_dot == key) {
1463                 error("key does not contain a section: %s", key);
1464                 return -CONFIG_NO_SECTION_OR_NAME;
1465         }
1466
1467         if (!last_dot[1]) {
1468                 error("key does not contain variable name: %s", key);
1469                 return -CONFIG_NO_SECTION_OR_NAME;
1470         }
1471
1472         baselen = last_dot - key;
1473         if (baselen_)
1474                 *baselen_ = baselen;
1475
1476         /*
1477          * Validate the key and while at it, lower case it for matching.
1478          */
1479         *store_key = xmalloc(strlen(key) + 1);
1480
1481         dot = 0;
1482         for (i = 0; key[i]; i++) {
1483                 unsigned char c = key[i];
1484                 if (c == '.')
1485                         dot = 1;
1486                 /* Leave the extended basename untouched.. */
1487                 if (!dot || i > baselen) {
1488                         if (!iskeychar(c) ||
1489                             (i == baselen + 1 && !isalpha(c))) {
1490                                 error("invalid key: %s", key);
1491                                 goto out_free_ret_1;
1492                         }
1493                         c = tolower(c);
1494                 } else if (c == '\n') {
1495                         error("invalid key (newline): %s", key);
1496                         goto out_free_ret_1;
1497                 }
1498                 (*store_key)[i] = c;
1499         }
1500         (*store_key)[i] = 0;
1501
1502         return 0;
1503
1504 out_free_ret_1:
1505         free(*store_key);
1506         *store_key = NULL;
1507         return -CONFIG_INVALID_KEY;
1508 }
1509
1510 /*
1511  * If value==NULL, unset in (remove from) config,
1512  * if value_regex!=NULL, disregard key/value pairs where value does not match.
1513  * if multi_replace==0, nothing, or only one matching key/value is replaced,
1514  *     else all matching key/values (regardless how many) are removed,
1515  *     before the new pair is written.
1516  *
1517  * Returns 0 on success.
1518  *
1519  * This function does this:
1520  *
1521  * - it locks the config file by creating ".git/config.lock"
1522  *
1523  * - it then parses the config using store_aux() as validator to find
1524  *   the position on the key/value pair to replace. If it is to be unset,
1525  *   it must be found exactly once.
1526  *
1527  * - the config file is mmap()ed and the part before the match (if any) is
1528  *   written to the lock file, then the changed part and the rest.
1529  *
1530  * - the config file is removed and the lock file rename()d to it.
1531  *
1532  */
1533 int git_config_set_multivar_in_file(const char *config_filename,
1534                                 const char *key, const char *value,
1535                                 const char *value_regex, int multi_replace)
1536 {
1537         int fd = -1, in_fd;
1538         int ret;
1539         struct lock_file *lock = NULL;
1540         char *filename_buf = NULL;
1541
1542         /* parse-key returns negative; flip the sign to feed exit(3) */
1543         ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
1544         if (ret)
1545                 goto out_free;
1546
1547         store.multi_replace = multi_replace;
1548
1549         if (!config_filename)
1550                 config_filename = filename_buf = git_pathdup("config");
1551
1552         /*
1553          * The lock serves a purpose in addition to locking: the new
1554          * contents of .git/config will be written into it.
1555          */
1556         lock = xcalloc(1, sizeof(struct lock_file));
1557         fd = hold_lock_file_for_update(lock, config_filename, 0);
1558         if (fd < 0) {
1559                 error("could not lock config file %s: %s", config_filename, strerror(errno));
1560                 free(store.key);
1561                 ret = CONFIG_NO_LOCK;
1562                 goto out_free;
1563         }
1564
1565         /*
1566          * If .git/config does not exist yet, write a minimal version.
1567          */
1568         in_fd = open(config_filename, O_RDONLY);
1569         if ( in_fd < 0 ) {
1570                 free(store.key);
1571
1572                 if ( ENOENT != errno ) {
1573                         error("opening %s: %s", config_filename,
1574                               strerror(errno));
1575                         ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
1576                         goto out_free;
1577                 }
1578                 /* if nothing to unset, error out */
1579                 if (value == NULL) {
1580                         ret = CONFIG_NOTHING_SET;
1581                         goto out_free;
1582                 }
1583
1584                 store.key = (char *)key;
1585                 if (!store_write_section(fd, key) ||
1586                     !store_write_pair(fd, key, value))
1587                         goto write_err_out;
1588         } else {
1589                 struct stat st;
1590                 char *contents;
1591                 size_t contents_sz, copy_begin, copy_end;
1592                 int i, new_line = 0;
1593
1594                 if (value_regex == NULL)
1595                         store.value_regex = NULL;
1596                 else {
1597                         if (value_regex[0] == '!') {
1598                                 store.do_not_match = 1;
1599                                 value_regex++;
1600                         } else
1601                                 store.do_not_match = 0;
1602
1603                         store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1604                         if (regcomp(store.value_regex, value_regex,
1605                                         REG_EXTENDED)) {
1606                                 error("invalid pattern: %s", value_regex);
1607                                 free(store.value_regex);
1608                                 ret = CONFIG_INVALID_PATTERN;
1609                                 goto out_free;
1610                         }
1611                 }
1612
1613                 ALLOC_GROW(store.offset, 1, store.offset_alloc);
1614                 store.offset[0] = 0;
1615                 store.state = START;
1616                 store.seen = 0;
1617
1618                 /*
1619                  * After this, store.offset will contain the *end* offset
1620                  * of the last match, or remain at 0 if no match was found.
1621                  * As a side effect, we make sure to transform only a valid
1622                  * existing config file.
1623                  */
1624                 if (git_config_from_file(store_aux, config_filename, NULL)) {
1625                         error("invalid config file %s", config_filename);
1626                         free(store.key);
1627                         if (store.value_regex != NULL) {
1628                                 regfree(store.value_regex);
1629                                 free(store.value_regex);
1630                         }
1631                         ret = CONFIG_INVALID_FILE;
1632                         goto out_free;
1633                 }
1634
1635                 free(store.key);
1636                 if (store.value_regex != NULL) {
1637                         regfree(store.value_regex);
1638                         free(store.value_regex);
1639                 }
1640
1641                 /* if nothing to unset, or too many matches, error out */
1642                 if ((store.seen == 0 && value == NULL) ||
1643                                 (store.seen > 1 && multi_replace == 0)) {
1644                         ret = CONFIG_NOTHING_SET;
1645                         goto out_free;
1646                 }
1647
1648                 fstat(in_fd, &st);
1649                 contents_sz = xsize_t(st.st_size);
1650                 contents = xmmap(NULL, contents_sz, PROT_READ,
1651                         MAP_PRIVATE, in_fd, 0);
1652                 close(in_fd);
1653
1654                 if (store.seen == 0)
1655                         store.seen = 1;
1656
1657                 for (i = 0, copy_begin = 0; i < store.seen; i++) {
1658                         if (store.offset[i] == 0) {
1659                                 store.offset[i] = copy_end = contents_sz;
1660                         } else if (store.state != KEY_SEEN) {
1661                                 copy_end = store.offset[i];
1662                         } else
1663                                 copy_end = find_beginning_of_line(
1664                                         contents, contents_sz,
1665                                         store.offset[i]-2, &new_line);
1666
1667                         if (copy_end > 0 && contents[copy_end-1] != '\n')
1668                                 new_line = 1;
1669
1670                         /* write the first part of the config */
1671                         if (copy_end > copy_begin) {
1672                                 if (write_in_full(fd, contents + copy_begin,
1673                                                   copy_end - copy_begin) <
1674                                     copy_end - copy_begin)
1675                                         goto write_err_out;
1676                                 if (new_line &&
1677                                     write_str_in_full(fd, "\n") != 1)
1678                                         goto write_err_out;
1679                         }
1680                         copy_begin = store.offset[i];
1681                 }
1682
1683                 /* write the pair (value == NULL means unset) */
1684                 if (value != NULL) {
1685                         if (store.state == START) {
1686                                 if (!store_write_section(fd, key))
1687                                         goto write_err_out;
1688                         }
1689                         if (!store_write_pair(fd, key, value))
1690                                 goto write_err_out;
1691                 }
1692
1693                 /* write the rest of the config */
1694                 if (copy_begin < contents_sz)
1695                         if (write_in_full(fd, contents + copy_begin,
1696                                           contents_sz - copy_begin) <
1697                             contents_sz - copy_begin)
1698                                 goto write_err_out;
1699
1700                 munmap(contents, contents_sz);
1701         }
1702
1703         if (commit_lock_file(lock) < 0) {
1704                 error("could not commit config file %s", config_filename);
1705                 ret = CONFIG_NO_WRITE;
1706                 goto out_free;
1707         }
1708
1709         /*
1710          * lock is committed, so don't try to roll it back below.
1711          * NOTE: Since lockfile.c keeps a linked list of all created
1712          * lock_file structures, it isn't safe to free(lock).  It's
1713          * better to just leave it hanging around.
1714          */
1715         lock = NULL;
1716         ret = 0;
1717
1718 out_free:
1719         if (lock)
1720                 rollback_lock_file(lock);
1721         free(filename_buf);
1722         return ret;
1723
1724 write_err_out:
1725         ret = write_error(lock->filename);
1726         goto out_free;
1727
1728 }
1729
1730 int git_config_set_multivar(const char *key, const char *value,
1731                         const char *value_regex, int multi_replace)
1732 {
1733         return git_config_set_multivar_in_file(NULL, key, value, value_regex,
1734                                                multi_replace);
1735 }
1736
1737 static int section_name_match (const char *buf, const char *name)
1738 {
1739         int i = 0, j = 0, dot = 0;
1740         if (buf[i] != '[')
1741                 return 0;
1742         for (i = 1; buf[i] && buf[i] != ']'; i++) {
1743                 if (!dot && isspace(buf[i])) {
1744                         dot = 1;
1745                         if (name[j++] != '.')
1746                                 break;
1747                         for (i++; isspace(buf[i]); i++)
1748                                 ; /* do nothing */
1749                         if (buf[i] != '"')
1750                                 break;
1751                         continue;
1752                 }
1753                 if (buf[i] == '\\' && dot)
1754                         i++;
1755                 else if (buf[i] == '"' && dot) {
1756                         for (i++; isspace(buf[i]); i++)
1757                                 ; /* do_nothing */
1758                         break;
1759                 }
1760                 if (buf[i] != name[j++])
1761                         break;
1762         }
1763         if (buf[i] == ']' && name[j] == 0) {
1764                 /*
1765                  * We match, now just find the right length offset by
1766                  * gobbling up any whitespace after it, as well
1767                  */
1768                 i++;
1769                 for (; buf[i] && isspace(buf[i]); i++)
1770                         ; /* do nothing */
1771                 return i;
1772         }
1773         return 0;
1774 }
1775
1776 static int section_name_is_ok(const char *name)
1777 {
1778         /* Empty section names are bogus. */
1779         if (!*name)
1780                 return 0;
1781
1782         /*
1783          * Before a dot, we must be alphanumeric or dash. After the first dot,
1784          * anything goes, so we can stop checking.
1785          */
1786         for (; *name && *name != '.'; name++)
1787                 if (*name != '-' && !isalnum(*name))
1788                         return 0;
1789         return 1;
1790 }
1791
1792 /* if new_name == NULL, the section is removed instead */
1793 int git_config_rename_section_in_file(const char *config_filename,
1794                                       const char *old_name, const char *new_name)
1795 {
1796         int ret = 0, remove = 0;
1797         char *filename_buf = NULL;
1798         struct lock_file *lock;
1799         int out_fd;
1800         char buf[1024];
1801         FILE *config_file;
1802
1803         if (new_name && !section_name_is_ok(new_name)) {
1804                 ret = error("invalid section name: %s", new_name);
1805                 goto out;
1806         }
1807
1808         if (!config_filename)
1809                 config_filename = filename_buf = git_pathdup("config");
1810
1811         lock = xcalloc(1, sizeof(struct lock_file));
1812         out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1813         if (out_fd < 0) {
1814                 ret = error("could not lock config file %s", config_filename);
1815                 goto out;
1816         }
1817
1818         if (!(config_file = fopen(config_filename, "rb"))) {
1819                 /* no config file means nothing to rename, no error */
1820                 goto unlock_and_out;
1821         }
1822
1823         while (fgets(buf, sizeof(buf), config_file)) {
1824                 int i;
1825                 int length;
1826                 char *output = buf;
1827                 for (i = 0; buf[i] && isspace(buf[i]); i++)
1828                         ; /* do nothing */
1829                 if (buf[i] == '[') {
1830                         /* it's a section */
1831                         int offset = section_name_match(&buf[i], old_name);
1832                         if (offset > 0) {
1833                                 ret++;
1834                                 if (new_name == NULL) {
1835                                         remove = 1;
1836                                         continue;
1837                                 }
1838                                 store.baselen = strlen(new_name);
1839                                 if (!store_write_section(out_fd, new_name)) {
1840                                         ret = write_error(lock->filename);
1841                                         goto out;
1842                                 }
1843                                 /*
1844                                  * We wrote out the new section, with
1845                                  * a newline, now skip the old
1846                                  * section's length
1847                                  */
1848                                 output += offset + i;
1849                                 if (strlen(output) > 0) {
1850                                         /*
1851                                          * More content means there's
1852                                          * a declaration to put on the
1853                                          * next line; indent with a
1854                                          * tab
1855                                          */
1856                                         output -= 1;
1857                                         output[0] = '\t';
1858                                 }
1859                         }
1860                         remove = 0;
1861                 }
1862                 if (remove)
1863                         continue;
1864                 length = strlen(output);
1865                 if (write_in_full(out_fd, output, length) != length) {
1866                         ret = write_error(lock->filename);
1867                         goto out;
1868                 }
1869         }
1870         fclose(config_file);
1871 unlock_and_out:
1872         if (commit_lock_file(lock) < 0)
1873                 ret = error("could not commit config file %s", config_filename);
1874 out:
1875         free(filename_buf);
1876         return ret;
1877 }
1878
1879 int git_config_rename_section(const char *old_name, const char *new_name)
1880 {
1881         return git_config_rename_section_in_file(NULL, old_name, new_name);
1882 }
1883
1884 /*
1885  * Call this to report error for your variable that should not
1886  * get a boolean value (i.e. "[my] var" means "true").
1887  */
1888 #undef config_error_nonbool
1889 int config_error_nonbool(const char *var)
1890 {
1891         return error("Missing value for '%s'", var);
1892 }
1893
1894 int parse_config_key(const char *var,
1895                      const char *section,
1896                      const char **subsection, int *subsection_len,
1897                      const char **key)
1898 {
1899         int section_len = strlen(section);
1900         const char *dot;
1901
1902         /* Does it start with "section." ? */
1903         if (!starts_with(var, section) || var[section_len] != '.')
1904                 return -1;
1905
1906         /*
1907          * Find the key; we don't know yet if we have a subsection, but we must
1908          * parse backwards from the end, since the subsection may have dots in
1909          * it, too.
1910          */
1911         dot = strrchr(var, '.');
1912         *key = dot + 1;
1913
1914         /* Did we have a subsection at all? */
1915         if (dot == var + section_len) {
1916                 *subsection = NULL;
1917                 *subsection_len = 0;
1918         }
1919         else {
1920                 *subsection = var + section_len + 1;
1921                 *subsection_len = dot - *subsection;
1922         }
1923
1924         return 0;
1925 }