Code

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