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