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