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