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