Improve reporting of errors in config file routines
[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
11 #define MAXNAME (256)
12
13 static FILE *config_file;
14 static const char *config_file_name;
15 static int config_linenr;
16 static int config_file_eof;
17 static int zlib_compression_seen;
18
19 static int get_next_char(void)
20 {
21         int c;
22         FILE *f;
23
24         c = '\n';
25         if ((f = config_file) != NULL) {
26                 c = fgetc(f);
27                 if (c == '\r') {
28                         /* DOS like systems */
29                         c = fgetc(f);
30                         if (c != '\n') {
31                                 ungetc(c, f);
32                                 c = '\r';
33                         }
34                 }
35                 if (c == '\n')
36                         config_linenr++;
37                 if (c == EOF) {
38                         config_file_eof = 1;
39                         c = '\n';
40                 }
41         }
42         return c;
43 }
44
45 static char *parse_value(void)
46 {
47         static char value[1024];
48         int quote = 0, comment = 0, len = 0, space = 0;
49
50         for (;;) {
51                 int c = get_next_char();
52                 if (len >= sizeof(value))
53                         return NULL;
54                 if (c == '\n') {
55                         if (quote)
56                                 return NULL;
57                         value[len] = 0;
58                         return value;
59                 }
60                 if (comment)
61                         continue;
62                 if (isspace(c) && !quote) {
63                         space = 1;
64                         continue;
65                 }
66                 if (!quote) {
67                         if (c == ';' || c == '#') {
68                                 comment = 1;
69                                 continue;
70                         }
71                 }
72                 if (space) {
73                         if (len)
74                                 value[len++] = ' ';
75                         space = 0;
76                 }
77                 if (c == '\\') {
78                         c = get_next_char();
79                         switch (c) {
80                         case '\n':
81                                 continue;
82                         case 't':
83                                 c = '\t';
84                                 break;
85                         case 'b':
86                                 c = '\b';
87                                 break;
88                         case 'n':
89                                 c = '\n';
90                                 break;
91                         /* Some characters escape as themselves */
92                         case '\\': case '"':
93                                 break;
94                         /* Reject unknown escape sequences */
95                         default:
96                                 return NULL;
97                         }
98                         value[len++] = c;
99                         continue;
100                 }
101                 if (c == '"') {
102                         quote = 1-quote;
103                         continue;
104                 }
105                 value[len++] = c;
106         }
107 }
108
109 static inline int iskeychar(int c)
110 {
111         return isalnum(c) || c == '-';
112 }
113
114 static int get_value(config_fn_t fn, char *name, unsigned int len)
115 {
116         int c;
117         char *value;
118
119         /* Get the full name */
120         for (;;) {
121                 c = get_next_char();
122                 if (config_file_eof)
123                         break;
124                 if (!iskeychar(c))
125                         break;
126                 name[len++] = tolower(c);
127                 if (len >= MAXNAME)
128                         return -1;
129         }
130         name[len] = 0;
131         while (c == ' ' || c == '\t')
132                 c = get_next_char();
133
134         value = NULL;
135         if (c != '\n') {
136                 if (c != '=')
137                         return -1;
138                 value = parse_value();
139                 if (!value)
140                         return -1;
141         }
142         return fn(name, value);
143 }
144
145 static int get_extended_base_var(char *name, int baselen, int c)
146 {
147         do {
148                 if (c == '\n')
149                         return -1;
150                 c = get_next_char();
151         } while (isspace(c));
152
153         /* We require the format to be '[base "extension"]' */
154         if (c != '"')
155                 return -1;
156         name[baselen++] = '.';
157
158         for (;;) {
159                 int c = get_next_char();
160                 if (c == '\n')
161                         return -1;
162                 if (c == '"')
163                         break;
164                 if (c == '\\') {
165                         c = get_next_char();
166                         if (c == '\n')
167                                 return -1;
168                 }
169                 name[baselen++] = c;
170                 if (baselen > MAXNAME / 2)
171                         return -1;
172         }
173
174         /* Final ']' */
175         if (get_next_char() != ']')
176                 return -1;
177         return baselen;
178 }
179
180 static int get_base_var(char *name)
181 {
182         int baselen = 0;
183
184         for (;;) {
185                 int c = get_next_char();
186                 if (config_file_eof)
187                         return -1;
188                 if (c == ']')
189                         return baselen;
190                 if (isspace(c))
191                         return get_extended_base_var(name, baselen, c);
192                 if (!iskeychar(c) && c != '.')
193                         return -1;
194                 if (baselen > MAXNAME / 2)
195                         return -1;
196                 name[baselen++] = tolower(c);
197         }
198 }
199
200 static int git_parse_file(config_fn_t fn)
201 {
202         int comment = 0;
203         int baselen = 0;
204         static char var[MAXNAME];
205
206         for (;;) {
207                 int c = get_next_char();
208                 if (c == '\n') {
209                         if (config_file_eof)
210                                 return 0;
211                         comment = 0;
212                         continue;
213                 }
214                 if (comment || isspace(c))
215                         continue;
216                 if (c == '#' || c == ';') {
217                         comment = 1;
218                         continue;
219                 }
220                 if (c == '[') {
221                         baselen = get_base_var(var);
222                         if (baselen <= 0)
223                                 break;
224                         var[baselen++] = '.';
225                         var[baselen] = 0;
226                         continue;
227                 }
228                 if (!isalpha(c))
229                         break;
230                 var[baselen] = tolower(c);
231                 if (get_value(fn, var, baselen+1) < 0)
232                         break;
233         }
234         die("bad config file line %d in %s", config_linenr, config_file_name);
235 }
236
237 static int parse_unit_factor(const char *end, unsigned long *val)
238 {
239         if (!*end)
240                 return 1;
241         else if (!strcasecmp(end, "k")) {
242                 *val *= 1024;
243                 return 1;
244         }
245         else if (!strcasecmp(end, "m")) {
246                 *val *= 1024 * 1024;
247                 return 1;
248         }
249         else if (!strcasecmp(end, "g")) {
250                 *val *= 1024 * 1024 * 1024;
251                 return 1;
252         }
253         return 0;
254 }
255
256 int git_parse_long(const char *value, long *ret)
257 {
258         if (value && *value) {
259                 char *end;
260                 long val = strtol(value, &end, 0);
261                 unsigned long factor = 1;
262                 if (!parse_unit_factor(end, &factor))
263                         return 0;
264                 *ret = val * factor;
265                 return 1;
266         }
267         return 0;
268 }
269
270 int git_parse_ulong(const char *value, unsigned long *ret)
271 {
272         if (value && *value) {
273                 char *end;
274                 unsigned long val = strtoul(value, &end, 0);
275                 if (!parse_unit_factor(end, &val))
276                         return 0;
277                 *ret = val;
278                 return 1;
279         }
280         return 0;
281 }
282
283 static void die_bad_config(const char *name)
284 {
285         if (config_file_name)
286                 die("bad config value for '%s' in %s", name, config_file_name);
287         die("bad config value for '%s'", name);
288 }
289
290 int git_config_int(const char *name, const char *value)
291 {
292         long ret;
293         if (!git_parse_long(value, &ret))
294                 die_bad_config(name);
295         return ret;
296 }
297
298 unsigned long git_config_ulong(const char *name, const char *value)
299 {
300         unsigned long ret;
301         if (!git_parse_ulong(value, &ret))
302                 die_bad_config(name);
303         return ret;
304 }
305
306 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
307 {
308         *is_bool = 1;
309         if (!value)
310                 return 1;
311         if (!*value)
312                 return 0;
313         if (!strcasecmp(value, "true") || !strcasecmp(value, "yes"))
314                 return 1;
315         if (!strcasecmp(value, "false") || !strcasecmp(value, "no"))
316                 return 0;
317         *is_bool = 0;
318         return git_config_int(name, value);
319 }
320
321 int git_config_bool(const char *name, const char *value)
322 {
323         int discard;
324         return !!git_config_bool_or_int(name, value, &discard);
325 }
326
327 int git_config_string(const char **dest, const char *var, const char *value)
328 {
329         if (!value)
330                 return config_error_nonbool(var);
331         *dest = xstrdup(value);
332         return 0;
333 }
334
335 int git_default_config(const char *var, const char *value)
336 {
337         /* This needs a better name */
338         if (!strcmp(var, "core.filemode")) {
339                 trust_executable_bit = git_config_bool(var, value);
340                 return 0;
341         }
342
343         if (!strcmp(var, "core.quotepath")) {
344                 quote_path_fully = git_config_bool(var, value);
345                 return 0;
346         }
347
348         if (!strcmp(var, "core.symlinks")) {
349                 has_symlinks = git_config_bool(var, value);
350                 return 0;
351         }
352
353         if (!strcmp(var, "core.ignorecase")) {
354                 ignore_case = git_config_bool(var, value);
355                 return 0;
356         }
357
358         if (!strcmp(var, "core.bare")) {
359                 is_bare_repository_cfg = git_config_bool(var, value);
360                 return 0;
361         }
362
363         if (!strcmp(var, "core.ignorestat")) {
364                 assume_unchanged = git_config_bool(var, value);
365                 return 0;
366         }
367
368         if (!strcmp(var, "core.prefersymlinkrefs")) {
369                 prefer_symlink_refs = git_config_bool(var, value);
370                 return 0;
371         }
372
373         if (!strcmp(var, "core.logallrefupdates")) {
374                 log_all_ref_updates = git_config_bool(var, value);
375                 return 0;
376         }
377
378         if (!strcmp(var, "core.warnambiguousrefs")) {
379                 warn_ambiguous_refs = git_config_bool(var, value);
380                 return 0;
381         }
382
383         if (!strcmp(var, "core.loosecompression")) {
384                 int level = git_config_int(var, value);
385                 if (level == -1)
386                         level = Z_DEFAULT_COMPRESSION;
387                 else if (level < 0 || level > Z_BEST_COMPRESSION)
388                         die("bad zlib compression level %d", level);
389                 zlib_compression_level = level;
390                 zlib_compression_seen = 1;
391                 return 0;
392         }
393
394         if (!strcmp(var, "core.compression")) {
395                 int level = git_config_int(var, value);
396                 if (level == -1)
397                         level = Z_DEFAULT_COMPRESSION;
398                 else if (level < 0 || level > Z_BEST_COMPRESSION)
399                         die("bad zlib compression level %d", level);
400                 core_compression_level = level;
401                 core_compression_seen = 1;
402                 if (!zlib_compression_seen)
403                         zlib_compression_level = level;
404                 return 0;
405         }
406
407         if (!strcmp(var, "core.packedgitwindowsize")) {
408                 int pgsz_x2 = getpagesize() * 2;
409                 packed_git_window_size = git_config_int(var, value);
410
411                 /* This value must be multiple of (pagesize * 2) */
412                 packed_git_window_size /= pgsz_x2;
413                 if (packed_git_window_size < 1)
414                         packed_git_window_size = 1;
415                 packed_git_window_size *= pgsz_x2;
416                 return 0;
417         }
418
419         if (!strcmp(var, "core.packedgitlimit")) {
420                 packed_git_limit = git_config_int(var, value);
421                 return 0;
422         }
423
424         if (!strcmp(var, "core.deltabasecachelimit")) {
425                 delta_base_cache_limit = git_config_int(var, value);
426                 return 0;
427         }
428
429         if (!strcmp(var, "core.autocrlf")) {
430                 if (value && !strcasecmp(value, "input")) {
431                         auto_crlf = -1;
432                         return 0;
433                 }
434                 auto_crlf = git_config_bool(var, value);
435                 return 0;
436         }
437
438         if (!strcmp(var, "core.safecrlf")) {
439                 if (value && !strcasecmp(value, "warn")) {
440                         safe_crlf = SAFE_CRLF_WARN;
441                         return 0;
442                 }
443                 safe_crlf = git_config_bool(var, value);
444                 return 0;
445         }
446
447         if (!strcmp(var, "user.name")) {
448                 if (!value)
449                         return config_error_nonbool(var);
450                 strlcpy(git_default_name, value, sizeof(git_default_name));
451                 return 0;
452         }
453
454         if (!strcmp(var, "user.email")) {
455                 if (!value)
456                         return config_error_nonbool(var);
457                 strlcpy(git_default_email, value, sizeof(git_default_email));
458                 return 0;
459         }
460
461         if (!strcmp(var, "i18n.commitencoding"))
462                 return git_config_string(&git_commit_encoding, var, value);
463
464         if (!strcmp(var, "i18n.logoutputencoding"))
465                 return git_config_string(&git_log_output_encoding, var, value);
466
467         if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
468                 pager_use_color = git_config_bool(var,value);
469                 return 0;
470         }
471
472         if (!strcmp(var, "core.pager"))
473                 return git_config_string(&pager_program, var, value);
474
475         if (!strcmp(var, "core.editor"))
476                 return git_config_string(&editor_program, var, value);
477
478         if (!strcmp(var, "core.excludesfile"))
479                 return git_config_string(&excludes_file, var, value);
480
481         if (!strcmp(var, "core.whitespace")) {
482                 if (!value)
483                         return config_error_nonbool(var);
484                 whitespace_rule_cfg = parse_whitespace_rule(value);
485                 return 0;
486         }
487         if (!strcmp(var, "branch.autosetupmerge")) {
488                 if (value && !strcasecmp(value, "always")) {
489                         git_branch_track = BRANCH_TRACK_ALWAYS;
490                         return 0;
491                 }
492                 git_branch_track = git_config_bool(var, value);
493                 return 0;
494         }
495         if (!strcmp(var, "branch.autosetuprebase")) {
496                 if (!value)
497                         return config_error_nonbool(var);
498                 else if (!strcmp(value, "never"))
499                         autorebase = AUTOREBASE_NEVER;
500                 else if (!strcmp(value, "local"))
501                         autorebase = AUTOREBASE_LOCAL;
502                 else if (!strcmp(value, "remote"))
503                         autorebase = AUTOREBASE_REMOTE;
504                 else if (!strcmp(value, "always"))
505                         autorebase = AUTOREBASE_ALWAYS;
506                 else
507                         return error("Malformed value for %s", var);
508                 return 0;
509         }
510
511         /* Add other config variables here and to Documentation/config.txt. */
512         return 0;
513 }
514
515 int git_config_from_file(config_fn_t fn, const char *filename)
516 {
517         int ret;
518         FILE *f = fopen(filename, "r");
519
520         ret = -1;
521         if (f) {
522                 config_file = f;
523                 config_file_name = filename;
524                 config_linenr = 1;
525                 config_file_eof = 0;
526                 ret = git_parse_file(fn);
527                 fclose(f);
528                 config_file_name = NULL;
529         }
530         return ret;
531 }
532
533 const char *git_etc_gitconfig(void)
534 {
535         static const char *system_wide;
536         if (!system_wide) {
537                 system_wide = ETC_GITCONFIG;
538                 if (!is_absolute_path(system_wide)) {
539                         /* interpret path relative to exec-dir */
540                         struct strbuf d = STRBUF_INIT;
541                         strbuf_addf(&d, "%s/%s", git_exec_path(), system_wide);
542                         system_wide = strbuf_detach(&d, NULL);
543                 }
544         }
545         return system_wide;
546 }
547
548 int git_env_bool(const char *k, int def)
549 {
550         const char *v = getenv(k);
551         return v ? git_config_bool(k, v) : def;
552 }
553
554 int git_config_system(void)
555 {
556         return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
557 }
558
559 int git_config_global(void)
560 {
561         return !git_env_bool("GIT_CONFIG_NOGLOBAL", 0);
562 }
563
564 int git_config(config_fn_t fn)
565 {
566         int ret = 0;
567         char *repo_config = NULL;
568         const char *home = NULL, *filename;
569
570         /* $GIT_CONFIG makes git read _only_ the given config file,
571          * $GIT_CONFIG_LOCAL will make it process it in addition to the
572          * global config file, the same way it would the per-repository
573          * config file otherwise. */
574         filename = getenv(CONFIG_ENVIRONMENT);
575         if (!filename) {
576                 if (git_config_system() && !access(git_etc_gitconfig(), R_OK))
577                         ret += git_config_from_file(fn, git_etc_gitconfig());
578                 home = getenv("HOME");
579                 filename = getenv(CONFIG_LOCAL_ENVIRONMENT);
580                 if (!filename)
581                         filename = repo_config = xstrdup(git_path("config"));
582         }
583
584         if (git_config_global() && home) {
585                 char *user_config = xstrdup(mkpath("%s/.gitconfig", home));
586                 if (!access(user_config, R_OK))
587                         ret = git_config_from_file(fn, user_config);
588                 free(user_config);
589         }
590
591         ret += git_config_from_file(fn, filename);
592         free(repo_config);
593         return ret;
594 }
595
596 /*
597  * Find all the stuff for git_config_set() below.
598  */
599
600 #define MAX_MATCHES 512
601
602 static struct {
603         int baselen;
604         char* key;
605         int do_not_match;
606         regex_t* value_regex;
607         int multi_replace;
608         size_t offset[MAX_MATCHES];
609         enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
610         int seen;
611 } store;
612
613 static int matches(const char* key, const char* value)
614 {
615         return !strcmp(key, store.key) &&
616                 (store.value_regex == NULL ||
617                  (store.do_not_match ^
618                   !regexec(store.value_regex, value, 0, NULL, 0)));
619 }
620
621 static int store_aux(const char* key, const char* value)
622 {
623         const char *ep;
624         size_t section_len;
625
626         switch (store.state) {
627         case KEY_SEEN:
628                 if (matches(key, value)) {
629                         if (store.seen == 1 && store.multi_replace == 0) {
630                                 warning("%s has multiple values", key);
631                         } else if (store.seen >= MAX_MATCHES) {
632                                 error("too many matches for %s", key);
633                                 return 1;
634                         }
635
636                         store.offset[store.seen] = ftell(config_file);
637                         store.seen++;
638                 }
639                 break;
640         case SECTION_SEEN:
641                 /*
642                  * What we are looking for is in store.key (both
643                  * section and var), and its section part is baselen
644                  * long.  We found key (again, both section and var).
645                  * We would want to know if this key is in the same
646                  * section as what we are looking for.  We already
647                  * know we are in the same section as what should
648                  * hold store.key.
649                  */
650                 ep = strrchr(key, '.');
651                 section_len = ep - key;
652
653                 if ((section_len != store.baselen) ||
654                     memcmp(key, store.key, section_len+1)) {
655                         store.state = SECTION_END_SEEN;
656                         break;
657                 }
658
659                 /*
660                  * Do not increment matches: this is no match, but we
661                  * just made sure we are in the desired section.
662                  */
663                 store.offset[store.seen] = ftell(config_file);
664                 /* fallthru */
665         case SECTION_END_SEEN:
666         case START:
667                 if (matches(key, value)) {
668                         store.offset[store.seen] = ftell(config_file);
669                         store.state = KEY_SEEN;
670                         store.seen++;
671                 } else {
672                         if (strrchr(key, '.') - key == store.baselen &&
673                               !strncmp(key, store.key, store.baselen)) {
674                                         store.state = SECTION_SEEN;
675                                         store.offset[store.seen] = ftell(config_file);
676                         }
677                 }
678         }
679         return 0;
680 }
681
682 static int write_error(const char *filename)
683 {
684         error("failed to write new configuration file %s", filename);
685
686         /* Same error code as "failed to rename". */
687         return 4;
688 }
689
690 static int store_write_section(int fd, const char* key)
691 {
692         const char *dot;
693         int i, success;
694         struct strbuf sb;
695
696         strbuf_init(&sb, 0);
697         dot = memchr(key, '.', store.baselen);
698         if (dot) {
699                 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
700                 for (i = dot - key + 1; i < store.baselen; i++) {
701                         if (key[i] == '"')
702                                 strbuf_addch(&sb, '\\');
703                         strbuf_addch(&sb, key[i]);
704                 }
705                 strbuf_addstr(&sb, "\"]\n");
706         } else {
707                 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
708         }
709
710         success = write_in_full(fd, sb.buf, sb.len) == sb.len;
711         strbuf_release(&sb);
712
713         return success;
714 }
715
716 static int store_write_pair(int fd, const char* key, const char* value)
717 {
718         int i, success;
719         int length = strlen(key + store.baselen + 1);
720         const char *quote = "";
721         struct strbuf sb;
722
723         /*
724          * Check to see if the value needs to be surrounded with a dq pair.
725          * Note that problematic characters are always backslash-quoted; this
726          * check is about not losing leading or trailing SP and strings that
727          * follow beginning-of-comment characters (i.e. ';' and '#') by the
728          * configuration parser.
729          */
730         if (value[0] == ' ')
731                 quote = "\"";
732         for (i = 0; value[i]; i++)
733                 if (value[i] == ';' || value[i] == '#')
734                         quote = "\"";
735         if (i && value[i - 1] == ' ')
736                 quote = "\"";
737
738         strbuf_init(&sb, 0);
739         strbuf_addf(&sb, "\t%.*s = %s",
740                     length, key + store.baselen + 1, quote);
741
742         for (i = 0; value[i]; i++)
743                 switch (value[i]) {
744                 case '\n':
745                         strbuf_addstr(&sb, "\\n");
746                         break;
747                 case '\t':
748                         strbuf_addstr(&sb, "\\t");
749                         break;
750                 case '"':
751                 case '\\':
752                         strbuf_addch(&sb, '\\');
753                 default:
754                         strbuf_addch(&sb, value[i]);
755                         break;
756                 }
757         strbuf_addf(&sb, "%s\n", quote);
758
759         success = write_in_full(fd, sb.buf, sb.len) == sb.len;
760         strbuf_release(&sb);
761
762         return success;
763 }
764
765 static ssize_t find_beginning_of_line(const char* contents, size_t size,
766         size_t offset_, int* found_bracket)
767 {
768         size_t equal_offset = size, bracket_offset = size;
769         ssize_t offset;
770
771 contline:
772         for (offset = offset_-2; offset > 0
773                         && contents[offset] != '\n'; offset--)
774                 switch (contents[offset]) {
775                         case '=': equal_offset = offset; break;
776                         case ']': bracket_offset = offset; break;
777                 }
778         if (offset > 0 && contents[offset-1] == '\\') {
779                 offset_ = offset;
780                 goto contline;
781         }
782         if (bracket_offset < equal_offset) {
783                 *found_bracket = 1;
784                 offset = bracket_offset+1;
785         } else
786                 offset++;
787
788         return offset;
789 }
790
791 int git_config_set(const char* key, const char* value)
792 {
793         return git_config_set_multivar(key, value, NULL, 0);
794 }
795
796 /*
797  * If value==NULL, unset in (remove from) config,
798  * if value_regex!=NULL, disregard key/value pairs where value does not match.
799  * if multi_replace==0, nothing, or only one matching key/value is replaced,
800  *     else all matching key/values (regardless how many) are removed,
801  *     before the new pair is written.
802  *
803  * Returns 0 on success.
804  *
805  * This function does this:
806  *
807  * - it locks the config file by creating ".git/config.lock"
808  *
809  * - it then parses the config using store_aux() as validator to find
810  *   the position on the key/value pair to replace. If it is to be unset,
811  *   it must be found exactly once.
812  *
813  * - the config file is mmap()ed and the part before the match (if any) is
814  *   written to the lock file, then the changed part and the rest.
815  *
816  * - the config file is removed and the lock file rename()d to it.
817  *
818  */
819 int git_config_set_multivar(const char* key, const char* value,
820         const char* value_regex, int multi_replace)
821 {
822         int i, dot;
823         int fd = -1, in_fd;
824         int ret;
825         char* config_filename;
826         struct lock_file *lock = NULL;
827         const char* last_dot = strrchr(key, '.');
828
829         config_filename = getenv(CONFIG_ENVIRONMENT);
830         if (!config_filename) {
831                 config_filename = getenv(CONFIG_LOCAL_ENVIRONMENT);
832                 if (!config_filename)
833                         config_filename  = git_path("config");
834         }
835         config_filename = xstrdup(config_filename);
836
837         /*
838          * Since "key" actually contains the section name and the real
839          * key name separated by a dot, we have to know where the dot is.
840          */
841
842         if (last_dot == NULL) {
843                 error("key does not contain a section: %s", key);
844                 ret = 2;
845                 goto out_free;
846         }
847         store.baselen = last_dot - key;
848
849         store.multi_replace = multi_replace;
850
851         /*
852          * Validate the key and while at it, lower case it for matching.
853          */
854         store.key = xmalloc(strlen(key) + 1);
855         dot = 0;
856         for (i = 0; key[i]; i++) {
857                 unsigned char c = key[i];
858                 if (c == '.')
859                         dot = 1;
860                 /* Leave the extended basename untouched.. */
861                 if (!dot || i > store.baselen) {
862                         if (!iskeychar(c) || (i == store.baselen+1 && !isalpha(c))) {
863                                 error("invalid key: %s", key);
864                                 free(store.key);
865                                 ret = 1;
866                                 goto out_free;
867                         }
868                         c = tolower(c);
869                 } else if (c == '\n') {
870                         error("invalid key (newline): %s", key);
871                         free(store.key);
872                         ret = 1;
873                         goto out_free;
874                 }
875                 store.key[i] = c;
876         }
877         store.key[i] = 0;
878
879         /*
880          * The lock serves a purpose in addition to locking: the new
881          * contents of .git/config will be written into it.
882          */
883         lock = xcalloc(sizeof(struct lock_file), 1);
884         fd = hold_lock_file_for_update(lock, config_filename, 0);
885         if (fd < 0) {
886                 error("could not lock config file %s", config_filename);
887                 free(store.key);
888                 ret = -1;
889                 goto out_free;
890         }
891
892         /*
893          * If .git/config does not exist yet, write a minimal version.
894          */
895         in_fd = open(config_filename, O_RDONLY);
896         if ( in_fd < 0 ) {
897                 free(store.key);
898
899                 if ( ENOENT != errno ) {
900                         error("opening %s: %s", config_filename,
901                               strerror(errno));
902                         ret = 3; /* same as "invalid config file" */
903                         goto out_free;
904                 }
905                 /* if nothing to unset, error out */
906                 if (value == NULL) {
907                         ret = 5;
908                         goto out_free;
909                 }
910
911                 store.key = (char*)key;
912                 if (!store_write_section(fd, key) ||
913                     !store_write_pair(fd, key, value))
914                         goto write_err_out;
915         } else {
916                 struct stat st;
917                 char* contents;
918                 size_t contents_sz, copy_begin, copy_end;
919                 int i, new_line = 0;
920
921                 if (value_regex == NULL)
922                         store.value_regex = NULL;
923                 else {
924                         if (value_regex[0] == '!') {
925                                 store.do_not_match = 1;
926                                 value_regex++;
927                         } else
928                                 store.do_not_match = 0;
929
930                         store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
931                         if (regcomp(store.value_regex, value_regex,
932                                         REG_EXTENDED)) {
933                                 error("invalid pattern: %s", value_regex);
934                                 free(store.value_regex);
935                                 ret = 6;
936                                 goto out_free;
937                         }
938                 }
939
940                 store.offset[0] = 0;
941                 store.state = START;
942                 store.seen = 0;
943
944                 /*
945                  * After this, store.offset will contain the *end* offset
946                  * of the last match, or remain at 0 if no match was found.
947                  * As a side effect, we make sure to transform only a valid
948                  * existing config file.
949                  */
950                 if (git_config_from_file(store_aux, config_filename)) {
951                         error("invalid config file %s", config_filename);
952                         free(store.key);
953                         if (store.value_regex != NULL) {
954                                 regfree(store.value_regex);
955                                 free(store.value_regex);
956                         }
957                         ret = 3;
958                         goto out_free;
959                 }
960
961                 free(store.key);
962                 if (store.value_regex != NULL) {
963                         regfree(store.value_regex);
964                         free(store.value_regex);
965                 }
966
967                 /* if nothing to unset, or too many matches, error out */
968                 if ((store.seen == 0 && value == NULL) ||
969                                 (store.seen > 1 && multi_replace == 0)) {
970                         ret = 5;
971                         goto out_free;
972                 }
973
974                 fstat(in_fd, &st);
975                 contents_sz = xsize_t(st.st_size);
976                 contents = xmmap(NULL, contents_sz, PROT_READ,
977                         MAP_PRIVATE, in_fd, 0);
978                 close(in_fd);
979
980                 if (store.seen == 0)
981                         store.seen = 1;
982
983                 for (i = 0, copy_begin = 0; i < store.seen; i++) {
984                         if (store.offset[i] == 0) {
985                                 store.offset[i] = copy_end = contents_sz;
986                         } else if (store.state != KEY_SEEN) {
987                                 copy_end = store.offset[i];
988                         } else
989                                 copy_end = find_beginning_of_line(
990                                         contents, contents_sz,
991                                         store.offset[i]-2, &new_line);
992
993                         if (copy_end > 0 && contents[copy_end-1] != '\n')
994                                 new_line = 1;
995
996                         /* write the first part of the config */
997                         if (copy_end > copy_begin) {
998                                 if (write_in_full(fd, contents + copy_begin,
999                                                   copy_end - copy_begin) <
1000                                     copy_end - copy_begin)
1001                                         goto write_err_out;
1002                                 if (new_line &&
1003                                     write_in_full(fd, "\n", 1) != 1)
1004                                         goto write_err_out;
1005                         }
1006                         copy_begin = store.offset[i];
1007                 }
1008
1009                 /* write the pair (value == NULL means unset) */
1010                 if (value != NULL) {
1011                         if (store.state == START) {
1012                                 if (!store_write_section(fd, key))
1013                                         goto write_err_out;
1014                         }
1015                         if (!store_write_pair(fd, key, value))
1016                                 goto write_err_out;
1017                 }
1018
1019                 /* write the rest of the config */
1020                 if (copy_begin < contents_sz)
1021                         if (write_in_full(fd, contents + copy_begin,
1022                                           contents_sz - copy_begin) <
1023                             contents_sz - copy_begin)
1024                                 goto write_err_out;
1025
1026                 munmap(contents, contents_sz);
1027         }
1028
1029         if (commit_lock_file(lock) < 0) {
1030                 error("could not commit config file %s", config_filename);
1031                 ret = 4;
1032                 goto out_free;
1033         }
1034
1035         /*
1036          * lock is committed, so don't try to roll it back below.
1037          * NOTE: Since lockfile.c keeps a linked list of all created
1038          * lock_file structures, it isn't safe to free(lock).  It's
1039          * better to just leave it hanging around.
1040          */
1041         lock = NULL;
1042         ret = 0;
1043
1044 out_free:
1045         if (lock)
1046                 rollback_lock_file(lock);
1047         free(config_filename);
1048         return ret;
1049
1050 write_err_out:
1051         ret = write_error(lock->filename);
1052         goto out_free;
1053
1054 }
1055
1056 static int section_name_match (const char *buf, const char *name)
1057 {
1058         int i = 0, j = 0, dot = 0;
1059         for (; buf[i] && buf[i] != ']'; i++) {
1060                 if (!dot && isspace(buf[i])) {
1061                         dot = 1;
1062                         if (name[j++] != '.')
1063                                 break;
1064                         for (i++; isspace(buf[i]); i++)
1065                                 ; /* do nothing */
1066                         if (buf[i] != '"')
1067                                 break;
1068                         continue;
1069                 }
1070                 if (buf[i] == '\\' && dot)
1071                         i++;
1072                 else if (buf[i] == '"' && dot) {
1073                         for (i++; isspace(buf[i]); i++)
1074                                 ; /* do_nothing */
1075                         break;
1076                 }
1077                 if (buf[i] != name[j++])
1078                         break;
1079         }
1080         return (buf[i] == ']' && name[j] == 0);
1081 }
1082
1083 /* if new_name == NULL, the section is removed instead */
1084 int git_config_rename_section(const char *old_name, const char *new_name)
1085 {
1086         int ret = 0, remove = 0;
1087         char *config_filename;
1088         struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1089         int out_fd;
1090         char buf[1024];
1091
1092         config_filename = getenv(CONFIG_ENVIRONMENT);
1093         if (!config_filename) {
1094                 config_filename = getenv(CONFIG_LOCAL_ENVIRONMENT);
1095                 if (!config_filename)
1096                         config_filename  = git_path("config");
1097         }
1098         config_filename = xstrdup(config_filename);
1099         out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1100         if (out_fd < 0) {
1101                 ret = error("could not lock config file %s", config_filename);
1102                 goto out;
1103         }
1104
1105         if (!(config_file = fopen(config_filename, "rb"))) {
1106                 /* no config file means nothing to rename, no error */
1107                 goto unlock_and_out;
1108         }
1109
1110         while (fgets(buf, sizeof(buf), config_file)) {
1111                 int i;
1112                 int length;
1113                 for (i = 0; buf[i] && isspace(buf[i]); i++)
1114                         ; /* do nothing */
1115                 if (buf[i] == '[') {
1116                         /* it's a section */
1117                         if (section_name_match (&buf[i+1], old_name)) {
1118                                 ret++;
1119                                 if (new_name == NULL) {
1120                                         remove = 1;
1121                                         continue;
1122                                 }
1123                                 store.baselen = strlen(new_name);
1124                                 if (!store_write_section(out_fd, new_name)) {
1125                                         ret = write_error(lock->filename);
1126                                         goto out;
1127                                 }
1128                                 continue;
1129                         }
1130                         remove = 0;
1131                 }
1132                 if (remove)
1133                         continue;
1134                 length = strlen(buf);
1135                 if (write_in_full(out_fd, buf, length) != length) {
1136                         ret = write_error(lock->filename);
1137                         goto out;
1138                 }
1139         }
1140         fclose(config_file);
1141  unlock_and_out:
1142         if (commit_lock_file(lock) < 0)
1143                 ret = error("could not commit config file %s", config_filename);
1144  out:
1145         free(config_filename);
1146         return ret;
1147 }
1148
1149 /*
1150  * Call this to report error for your variable that should not
1151  * get a boolean value (i.e. "[my] var" means "true").
1152  */
1153 int config_error_nonbool(const char *var)
1154 {
1155         return error("Missing value for '%s'", var);
1156 }