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