Code

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