Allow passing of configuration parameters in the command line
[git/mjg.git] / config.c
blobb6a4257627373b2ce83321a7f21b0c86e50b9641
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 * Copyright (C) Johannes Schindelin, 2005
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 struct config_item
23 struct config_item *next;
24 char *value;
25 char name[1 /* NUL */];
27 static struct config_item *config_parameters;
28 static struct config_item **config_parameters_tail = &config_parameters;
30 static void lowercase(char *p)
32 for (; *p; p++)
33 *p = tolower(*p);
35 static char *skip_space(const char *p)
37 for (; *p; p++)
38 if (!isspace(*p))
39 break;
40 return (char *)p;
42 static char *trailing_space(const char *begin, const char *p)
44 while (p-- > begin)
45 if (!isspace(*p))
46 break;
47 return (char *)p + 1;
50 int git_config_parse_parameter(const char *text)
52 struct config_item *ct;
53 const char *name;
54 const char *val;
55 name = skip_space(text);
56 text = val = strchr(name, '=');
57 if (!text)
58 text = name + strlen(name);
59 text = trailing_space(name, text);
60 if (text <= name)
61 return -1;
62 ct = xcalloc(1, sizeof(struct config_item) + (text - name));
63 memcpy(ct->name, name, text - name);
64 lowercase(ct->name);
65 if (!val)
66 ct->value = NULL;
67 else {
68 val = skip_space(++val /* skip "=" */);
69 text = trailing_space(val, val + strlen(val));
70 ct->value = xstrndup(val, text - val);
72 *config_parameters_tail = ct;
73 config_parameters_tail = &ct->next;
74 return 0;
77 static int get_next_char(void)
79 int c;
80 FILE *f;
82 c = '\n';
83 if ((f = config_file) != NULL) {
84 c = fgetc(f);
85 if (c == '\r') {
86 /* DOS like systems */
87 c = fgetc(f);
88 if (c != '\n') {
89 ungetc(c, f);
90 c = '\r';
93 if (c == '\n')
94 config_linenr++;
95 if (c == EOF) {
96 config_file_eof = 1;
97 c = '\n';
100 return c;
103 static char *parse_value(void)
105 static char value[1024];
106 int quote = 0, comment = 0, len = 0, space = 0;
108 for (;;) {
109 int c = get_next_char();
110 if (len >= sizeof(value) - 1)
111 return NULL;
112 if (c == '\n') {
113 if (quote)
114 return NULL;
115 value[len] = 0;
116 return value;
118 if (comment)
119 continue;
120 if (isspace(c) && !quote) {
121 if (len)
122 space++;
123 continue;
125 if (!quote) {
126 if (c == ';' || c == '#') {
127 comment = 1;
128 continue;
131 for (; space; space--)
132 value[len++] = ' ';
133 if (c == '\\') {
134 c = get_next_char();
135 switch (c) {
136 case '\n':
137 continue;
138 case 't':
139 c = '\t';
140 break;
141 case 'b':
142 c = '\b';
143 break;
144 case 'n':
145 c = '\n';
146 break;
147 /* Some characters escape as themselves */
148 case '\\': case '"':
149 break;
150 /* Reject unknown escape sequences */
151 default:
152 return NULL;
154 value[len++] = c;
155 continue;
157 if (c == '"') {
158 quote = 1-quote;
159 continue;
161 value[len++] = c;
165 static inline int iskeychar(int c)
167 return isalnum(c) || c == '-';
170 static int get_value(config_fn_t fn, void *data, char *name, unsigned int len)
172 int c;
173 char *value;
175 /* Get the full name */
176 for (;;) {
177 c = get_next_char();
178 if (config_file_eof)
179 break;
180 if (!iskeychar(c))
181 break;
182 name[len++] = tolower(c);
183 if (len >= MAXNAME)
184 return -1;
186 name[len] = 0;
187 while (c == ' ' || c == '\t')
188 c = get_next_char();
190 value = NULL;
191 if (c != '\n') {
192 if (c != '=')
193 return -1;
194 value = parse_value();
195 if (!value)
196 return -1;
198 return fn(name, value, data);
201 static int get_extended_base_var(char *name, int baselen, int c)
203 do {
204 if (c == '\n')
205 return -1;
206 c = get_next_char();
207 } while (isspace(c));
209 /* We require the format to be '[base "extension"]' */
210 if (c != '"')
211 return -1;
212 name[baselen++] = '.';
214 for (;;) {
215 int c = get_next_char();
216 if (c == '\n')
217 return -1;
218 if (c == '"')
219 break;
220 if (c == '\\') {
221 c = get_next_char();
222 if (c == '\n')
223 return -1;
225 name[baselen++] = c;
226 if (baselen > MAXNAME / 2)
227 return -1;
230 /* Final ']' */
231 if (get_next_char() != ']')
232 return -1;
233 return baselen;
236 static int get_base_var(char *name)
238 int baselen = 0;
240 for (;;) {
241 int c = get_next_char();
242 if (config_file_eof)
243 return -1;
244 if (c == ']')
245 return baselen;
246 if (isspace(c))
247 return get_extended_base_var(name, baselen, c);
248 if (!iskeychar(c) && c != '.')
249 return -1;
250 if (baselen > MAXNAME / 2)
251 return -1;
252 name[baselen++] = tolower(c);
256 static int git_parse_file(config_fn_t fn, void *data)
258 int comment = 0;
259 int baselen = 0;
260 static char var[MAXNAME];
262 /* U+FEFF Byte Order Mark in UTF8 */
263 static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
264 const unsigned char *bomptr = utf8_bom;
266 for (;;) {
267 int c = get_next_char();
268 if (bomptr && *bomptr) {
269 /* We are at the file beginning; skip UTF8-encoded BOM
270 * if present. Sane editors won't put this in on their
271 * own, but e.g. Windows Notepad will do it happily. */
272 if ((unsigned char) c == *bomptr) {
273 bomptr++;
274 continue;
275 } else {
276 /* Do not tolerate partial BOM. */
277 if (bomptr != utf8_bom)
278 break;
279 /* No BOM at file beginning. Cool. */
280 bomptr = NULL;
283 if (c == '\n') {
284 if (config_file_eof)
285 return 0;
286 comment = 0;
287 continue;
289 if (comment || isspace(c))
290 continue;
291 if (c == '#' || c == ';') {
292 comment = 1;
293 continue;
295 if (c == '[') {
296 baselen = get_base_var(var);
297 if (baselen <= 0)
298 break;
299 var[baselen++] = '.';
300 var[baselen] = 0;
301 continue;
303 if (!isalpha(c))
304 break;
305 var[baselen] = tolower(c);
306 if (get_value(fn, data, var, baselen+1) < 0)
307 break;
309 die("bad config file line %d in %s", config_linenr, config_file_name);
312 static int parse_unit_factor(const char *end, unsigned long *val)
314 if (!*end)
315 return 1;
316 else if (!strcasecmp(end, "k")) {
317 *val *= 1024;
318 return 1;
320 else if (!strcasecmp(end, "m")) {
321 *val *= 1024 * 1024;
322 return 1;
324 else if (!strcasecmp(end, "g")) {
325 *val *= 1024 * 1024 * 1024;
326 return 1;
328 return 0;
331 static int git_parse_long(const char *value, long *ret)
333 if (value && *value) {
334 char *end;
335 long val = strtol(value, &end, 0);
336 unsigned long factor = 1;
337 if (!parse_unit_factor(end, &factor))
338 return 0;
339 *ret = val * factor;
340 return 1;
342 return 0;
345 int git_parse_ulong(const char *value, unsigned long *ret)
347 if (value && *value) {
348 char *end;
349 unsigned long val = strtoul(value, &end, 0);
350 if (!parse_unit_factor(end, &val))
351 return 0;
352 *ret = val;
353 return 1;
355 return 0;
358 static void die_bad_config(const char *name)
360 if (config_file_name)
361 die("bad config value for '%s' in %s", name, config_file_name);
362 die("bad config value for '%s'", name);
365 int git_config_int(const char *name, const char *value)
367 long ret = 0;
368 if (!git_parse_long(value, &ret))
369 die_bad_config(name);
370 return ret;
373 unsigned long git_config_ulong(const char *name, const char *value)
375 unsigned long ret;
376 if (!git_parse_ulong(value, &ret))
377 die_bad_config(name);
378 return ret;
381 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
383 *is_bool = 1;
384 if (!value)
385 return 1;
386 if (!*value)
387 return 0;
388 if (!strcasecmp(value, "true") || !strcasecmp(value, "yes") || !strcasecmp(value, "on"))
389 return 1;
390 if (!strcasecmp(value, "false") || !strcasecmp(value, "no") || !strcasecmp(value, "off"))
391 return 0;
392 *is_bool = 0;
393 return git_config_int(name, value);
396 int git_config_bool(const char *name, const char *value)
398 int discard;
399 return !!git_config_bool_or_int(name, value, &discard);
402 int git_config_string(const char **dest, const char *var, const char *value)
404 if (!value)
405 return config_error_nonbool(var);
406 *dest = xstrdup(value);
407 return 0;
410 int git_config_pathname(const char **dest, const char *var, const char *value)
412 if (!value)
413 return config_error_nonbool(var);
414 *dest = expand_user_path(value);
415 if (!*dest)
416 die("Failed to expand user dir in: '%s'", value);
417 return 0;
420 static int git_default_core_config(const char *var, const char *value)
422 /* This needs a better name */
423 if (!strcmp(var, "core.filemode")) {
424 trust_executable_bit = git_config_bool(var, value);
425 return 0;
427 if (!strcmp(var, "core.trustctime")) {
428 trust_ctime = git_config_bool(var, value);
429 return 0;
432 if (!strcmp(var, "core.quotepath")) {
433 quote_path_fully = git_config_bool(var, value);
434 return 0;
437 if (!strcmp(var, "core.symlinks")) {
438 has_symlinks = git_config_bool(var, value);
439 return 0;
442 if (!strcmp(var, "core.ignorecase")) {
443 ignore_case = git_config_bool(var, value);
444 return 0;
447 if (!strcmp(var, "core.bare")) {
448 is_bare_repository_cfg = git_config_bool(var, value);
449 return 0;
452 if (!strcmp(var, "core.ignorestat")) {
453 assume_unchanged = git_config_bool(var, value);
454 return 0;
457 if (!strcmp(var, "core.prefersymlinkrefs")) {
458 prefer_symlink_refs = git_config_bool(var, value);
459 return 0;
462 if (!strcmp(var, "core.logallrefupdates")) {
463 log_all_ref_updates = git_config_bool(var, value);
464 return 0;
467 if (!strcmp(var, "core.warnambiguousrefs")) {
468 warn_ambiguous_refs = git_config_bool(var, value);
469 return 0;
472 if (!strcmp(var, "core.loosecompression")) {
473 int level = git_config_int(var, value);
474 if (level == -1)
475 level = Z_DEFAULT_COMPRESSION;
476 else if (level < 0 || level > Z_BEST_COMPRESSION)
477 die("bad zlib compression level %d", level);
478 zlib_compression_level = level;
479 zlib_compression_seen = 1;
480 return 0;
483 if (!strcmp(var, "core.compression")) {
484 int level = git_config_int(var, value);
485 if (level == -1)
486 level = Z_DEFAULT_COMPRESSION;
487 else if (level < 0 || level > Z_BEST_COMPRESSION)
488 die("bad zlib compression level %d", level);
489 core_compression_level = level;
490 core_compression_seen = 1;
491 if (!zlib_compression_seen)
492 zlib_compression_level = level;
493 return 0;
496 if (!strcmp(var, "core.packedgitwindowsize")) {
497 int pgsz_x2 = getpagesize() * 2;
498 packed_git_window_size = git_config_int(var, value);
500 /* This value must be multiple of (pagesize * 2) */
501 packed_git_window_size /= pgsz_x2;
502 if (packed_git_window_size < 1)
503 packed_git_window_size = 1;
504 packed_git_window_size *= pgsz_x2;
505 return 0;
508 if (!strcmp(var, "core.packedgitlimit")) {
509 packed_git_limit = git_config_int(var, value);
510 return 0;
513 if (!strcmp(var, "core.deltabasecachelimit")) {
514 delta_base_cache_limit = git_config_int(var, value);
515 return 0;
518 if (!strcmp(var, "core.autocrlf")) {
519 if (value && !strcasecmp(value, "input")) {
520 auto_crlf = -1;
521 return 0;
523 auto_crlf = git_config_bool(var, value);
524 return 0;
527 if (!strcmp(var, "core.safecrlf")) {
528 if (value && !strcasecmp(value, "warn")) {
529 safe_crlf = SAFE_CRLF_WARN;
530 return 0;
532 safe_crlf = git_config_bool(var, value);
533 return 0;
536 if (!strcmp(var, "core.notesref")) {
537 notes_ref_name = xstrdup(value);
538 return 0;
541 if (!strcmp(var, "core.pager"))
542 return git_config_string(&pager_program, var, value);
544 if (!strcmp(var, "core.editor"))
545 return git_config_string(&editor_program, var, value);
547 if (!strcmp(var, "core.excludesfile"))
548 return git_config_pathname(&excludes_file, var, value);
550 if (!strcmp(var, "core.whitespace")) {
551 if (!value)
552 return config_error_nonbool(var);
553 whitespace_rule_cfg = parse_whitespace_rule(value);
554 return 0;
557 if (!strcmp(var, "core.fsyncobjectfiles")) {
558 fsync_object_files = git_config_bool(var, value);
559 return 0;
562 if (!strcmp(var, "core.preloadindex")) {
563 core_preload_index = git_config_bool(var, value);
564 return 0;
567 if (!strcmp(var, "core.createobject")) {
568 if (!strcmp(value, "rename"))
569 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
570 else if (!strcmp(value, "link"))
571 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
572 else
573 die("Invalid mode for object creation: %s", value);
574 return 0;
577 if (!strcmp(var, "core.sparsecheckout")) {
578 core_apply_sparse_checkout = git_config_bool(var, value);
579 return 0;
582 /* Add other config variables here and to Documentation/config.txt. */
583 return 0;
586 static int git_default_user_config(const char *var, const char *value)
588 if (!strcmp(var, "user.name")) {
589 if (!value)
590 return config_error_nonbool(var);
591 strlcpy(git_default_name, value, sizeof(git_default_name));
592 user_ident_explicitly_given |= IDENT_NAME_GIVEN;
593 return 0;
596 if (!strcmp(var, "user.email")) {
597 if (!value)
598 return config_error_nonbool(var);
599 strlcpy(git_default_email, value, sizeof(git_default_email));
600 user_ident_explicitly_given |= IDENT_MAIL_GIVEN;
601 return 0;
604 /* Add other config variables here and to Documentation/config.txt. */
605 return 0;
608 static int git_default_i18n_config(const char *var, const char *value)
610 if (!strcmp(var, "i18n.commitencoding"))
611 return git_config_string(&git_commit_encoding, var, value);
613 if (!strcmp(var, "i18n.logoutputencoding"))
614 return git_config_string(&git_log_output_encoding, var, value);
616 /* Add other config variables here and to Documentation/config.txt. */
617 return 0;
620 static int git_default_branch_config(const char *var, const char *value)
622 if (!strcmp(var, "branch.autosetupmerge")) {
623 if (value && !strcasecmp(value, "always")) {
624 git_branch_track = BRANCH_TRACK_ALWAYS;
625 return 0;
627 git_branch_track = git_config_bool(var, value);
628 return 0;
630 if (!strcmp(var, "branch.autosetuprebase")) {
631 if (!value)
632 return config_error_nonbool(var);
633 else if (!strcmp(value, "never"))
634 autorebase = AUTOREBASE_NEVER;
635 else if (!strcmp(value, "local"))
636 autorebase = AUTOREBASE_LOCAL;
637 else if (!strcmp(value, "remote"))
638 autorebase = AUTOREBASE_REMOTE;
639 else if (!strcmp(value, "always"))
640 autorebase = AUTOREBASE_ALWAYS;
641 else
642 return error("Malformed value for %s", var);
643 return 0;
646 /* Add other config variables here and to Documentation/config.txt. */
647 return 0;
650 static int git_default_push_config(const char *var, const char *value)
652 if (!strcmp(var, "push.default")) {
653 if (!value)
654 return config_error_nonbool(var);
655 else if (!strcmp(value, "nothing"))
656 push_default = PUSH_DEFAULT_NOTHING;
657 else if (!strcmp(value, "matching"))
658 push_default = PUSH_DEFAULT_MATCHING;
659 else if (!strcmp(value, "tracking"))
660 push_default = PUSH_DEFAULT_TRACKING;
661 else if (!strcmp(value, "current"))
662 push_default = PUSH_DEFAULT_CURRENT;
663 else {
664 error("Malformed value for %s: %s", var, value);
665 return error("Must be one of nothing, matching, "
666 "tracking or current.");
668 return 0;
671 /* Add other config variables here and to Documentation/config.txt. */
672 return 0;
675 static int git_default_mailmap_config(const char *var, const char *value)
677 if (!strcmp(var, "mailmap.file"))
678 return git_config_string(&git_mailmap_file, var, value);
680 /* Add other config variables here and to Documentation/config.txt. */
681 return 0;
684 int git_default_config(const char *var, const char *value, void *dummy)
686 if (!prefixcmp(var, "core."))
687 return git_default_core_config(var, value);
689 if (!prefixcmp(var, "user."))
690 return git_default_user_config(var, value);
692 if (!prefixcmp(var, "i18n."))
693 return git_default_i18n_config(var, value);
695 if (!prefixcmp(var, "branch."))
696 return git_default_branch_config(var, value);
698 if (!prefixcmp(var, "push."))
699 return git_default_push_config(var, value);
701 if (!prefixcmp(var, "mailmap."))
702 return git_default_mailmap_config(var, value);
704 if (!prefixcmp(var, "advice."))
705 return git_default_advice_config(var, value);
707 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
708 pager_use_color = git_config_bool(var,value);
709 return 0;
712 /* Add other config variables here and to Documentation/config.txt. */
713 return 0;
716 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
718 int ret;
719 FILE *f = fopen(filename, "r");
721 ret = -1;
722 if (f) {
723 config_file = f;
724 config_file_name = filename;
725 config_linenr = 1;
726 config_file_eof = 0;
727 ret = git_parse_file(fn, data);
728 fclose(f);
729 config_file_name = NULL;
731 return ret;
734 const char *git_etc_gitconfig(void)
736 static const char *system_wide;
737 if (!system_wide)
738 system_wide = system_path(ETC_GITCONFIG);
739 return system_wide;
742 static int git_env_bool(const char *k, int def)
744 const char *v = getenv(k);
745 return v ? git_config_bool(k, v) : def;
748 int git_config_system(void)
750 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
753 int git_config_global(void)
755 return !git_env_bool("GIT_CONFIG_NOGLOBAL", 0);
758 int git_config_from_parameters(config_fn_t fn, void *data)
760 const struct config_item *ct;
761 for (ct = config_parameters; ct; ct = ct->next)
762 if (fn(ct->name, ct->value, data) < 0)
763 return -1;
764 return 0;
767 int git_config(config_fn_t fn, void *data)
769 int ret = 0, found = 0;
770 char *repo_config = NULL;
771 const char *home = NULL;
773 /* Setting $GIT_CONFIG makes git read _only_ the given config file. */
774 if (config_exclusive_filename)
775 return git_config_from_file(fn, config_exclusive_filename, data);
776 if (git_config_system() && !access(git_etc_gitconfig(), R_OK)) {
777 ret += git_config_from_file(fn, git_etc_gitconfig(),
778 data);
779 found += 1;
782 home = getenv("HOME");
783 if (git_config_global() && home) {
784 char *user_config = xstrdup(mkpath("%s/.gitconfig", home));
785 if (!access(user_config, R_OK)) {
786 ret += git_config_from_file(fn, user_config, data);
787 found += 1;
789 free(user_config);
792 repo_config = git_pathdup("config");
793 if (!access(repo_config, R_OK)) {
794 ret += git_config_from_file(fn, repo_config, data);
795 found += 1;
797 free(repo_config);
799 if (config_parameters) {
800 ret += git_config_from_parameters(fn, data);
801 found += 1;
804 if (found == 0)
805 return -1;
806 return ret;
810 * Find all the stuff for git_config_set() below.
813 #define MAX_MATCHES 512
815 static struct {
816 int baselen;
817 char *key;
818 int do_not_match;
819 regex_t *value_regex;
820 int multi_replace;
821 size_t offset[MAX_MATCHES];
822 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
823 int seen;
824 } store;
826 static int matches(const char *key, const char *value)
828 return !strcmp(key, store.key) &&
829 (store.value_regex == NULL ||
830 (store.do_not_match ^
831 !regexec(store.value_regex, value, 0, NULL, 0)));
834 static int store_aux(const char *key, const char *value, void *cb)
836 const char *ep;
837 size_t section_len;
839 switch (store.state) {
840 case KEY_SEEN:
841 if (matches(key, value)) {
842 if (store.seen == 1 && store.multi_replace == 0) {
843 warning("%s has multiple values", key);
844 } else if (store.seen >= MAX_MATCHES) {
845 error("too many matches for %s", key);
846 return 1;
849 store.offset[store.seen] = ftell(config_file);
850 store.seen++;
852 break;
853 case SECTION_SEEN:
855 * What we are looking for is in store.key (both
856 * section and var), and its section part is baselen
857 * long. We found key (again, both section and var).
858 * We would want to know if this key is in the same
859 * section as what we are looking for. We already
860 * know we are in the same section as what should
861 * hold store.key.
863 ep = strrchr(key, '.');
864 section_len = ep - key;
866 if ((section_len != store.baselen) ||
867 memcmp(key, store.key, section_len+1)) {
868 store.state = SECTION_END_SEEN;
869 break;
873 * Do not increment matches: this is no match, but we
874 * just made sure we are in the desired section.
876 store.offset[store.seen] = ftell(config_file);
877 /* fallthru */
878 case SECTION_END_SEEN:
879 case START:
880 if (matches(key, value)) {
881 store.offset[store.seen] = ftell(config_file);
882 store.state = KEY_SEEN;
883 store.seen++;
884 } else {
885 if (strrchr(key, '.') - key == store.baselen &&
886 !strncmp(key, store.key, store.baselen)) {
887 store.state = SECTION_SEEN;
888 store.offset[store.seen] = ftell(config_file);
892 return 0;
895 static int write_error(const char *filename)
897 error("failed to write new configuration file %s", filename);
899 /* Same error code as "failed to rename". */
900 return 4;
903 static int store_write_section(int fd, const char *key)
905 const char *dot;
906 int i, success;
907 struct strbuf sb = STRBUF_INIT;
909 dot = memchr(key, '.', store.baselen);
910 if (dot) {
911 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
912 for (i = dot - key + 1; i < store.baselen; i++) {
913 if (key[i] == '"' || key[i] == '\\')
914 strbuf_addch(&sb, '\\');
915 strbuf_addch(&sb, key[i]);
917 strbuf_addstr(&sb, "\"]\n");
918 } else {
919 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
922 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
923 strbuf_release(&sb);
925 return success;
928 static int store_write_pair(int fd, const char *key, const char *value)
930 int i, success;
931 int length = strlen(key + store.baselen + 1);
932 const char *quote = "";
933 struct strbuf sb = STRBUF_INIT;
936 * Check to see if the value needs to be surrounded with a dq pair.
937 * Note that problematic characters are always backslash-quoted; this
938 * check is about not losing leading or trailing SP and strings that
939 * follow beginning-of-comment characters (i.e. ';' and '#') by the
940 * configuration parser.
942 if (value[0] == ' ')
943 quote = "\"";
944 for (i = 0; value[i]; i++)
945 if (value[i] == ';' || value[i] == '#')
946 quote = "\"";
947 if (i && value[i - 1] == ' ')
948 quote = "\"";
950 strbuf_addf(&sb, "\t%.*s = %s",
951 length, key + store.baselen + 1, quote);
953 for (i = 0; value[i]; i++)
954 switch (value[i]) {
955 case '\n':
956 strbuf_addstr(&sb, "\\n");
957 break;
958 case '\t':
959 strbuf_addstr(&sb, "\\t");
960 break;
961 case '"':
962 case '\\':
963 strbuf_addch(&sb, '\\');
964 default:
965 strbuf_addch(&sb, value[i]);
966 break;
968 strbuf_addf(&sb, "%s\n", quote);
970 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
971 strbuf_release(&sb);
973 return success;
976 static ssize_t find_beginning_of_line(const char *contents, size_t size,
977 size_t offset_, int *found_bracket)
979 size_t equal_offset = size, bracket_offset = size;
980 ssize_t offset;
982 contline:
983 for (offset = offset_-2; offset > 0
984 && contents[offset] != '\n'; offset--)
985 switch (contents[offset]) {
986 case '=': equal_offset = offset; break;
987 case ']': bracket_offset = offset; break;
989 if (offset > 0 && contents[offset-1] == '\\') {
990 offset_ = offset;
991 goto contline;
993 if (bracket_offset < equal_offset) {
994 *found_bracket = 1;
995 offset = bracket_offset+1;
996 } else
997 offset++;
999 return offset;
1002 int git_config_set(const char *key, const char *value)
1004 return git_config_set_multivar(key, value, NULL, 0);
1008 * If value==NULL, unset in (remove from) config,
1009 * if value_regex!=NULL, disregard key/value pairs where value does not match.
1010 * if multi_replace==0, nothing, or only one matching key/value is replaced,
1011 * else all matching key/values (regardless how many) are removed,
1012 * before the new pair is written.
1014 * Returns 0 on success.
1016 * This function does this:
1018 * - it locks the config file by creating ".git/config.lock"
1020 * - it then parses the config using store_aux() as validator to find
1021 * the position on the key/value pair to replace. If it is to be unset,
1022 * it must be found exactly once.
1024 * - the config file is mmap()ed and the part before the match (if any) is
1025 * written to the lock file, then the changed part and the rest.
1027 * - the config file is removed and the lock file rename()d to it.
1030 int git_config_set_multivar(const char *key, const char *value,
1031 const char *value_regex, int multi_replace)
1033 int i, dot;
1034 int fd = -1, in_fd;
1035 int ret;
1036 char *config_filename;
1037 struct lock_file *lock = NULL;
1038 const char *last_dot = strrchr(key, '.');
1040 if (config_exclusive_filename)
1041 config_filename = xstrdup(config_exclusive_filename);
1042 else
1043 config_filename = git_pathdup("config");
1046 * Since "key" actually contains the section name and the real
1047 * key name separated by a dot, we have to know where the dot is.
1050 if (last_dot == NULL) {
1051 error("key does not contain a section: %s", key);
1052 ret = 2;
1053 goto out_free;
1055 store.baselen = last_dot - key;
1057 store.multi_replace = multi_replace;
1060 * Validate the key and while at it, lower case it for matching.
1062 store.key = xmalloc(strlen(key) + 1);
1063 dot = 0;
1064 for (i = 0; key[i]; i++) {
1065 unsigned char c = key[i];
1066 if (c == '.')
1067 dot = 1;
1068 /* Leave the extended basename untouched.. */
1069 if (!dot || i > store.baselen) {
1070 if (!iskeychar(c) || (i == store.baselen+1 && !isalpha(c))) {
1071 error("invalid key: %s", key);
1072 free(store.key);
1073 ret = 1;
1074 goto out_free;
1076 c = tolower(c);
1077 } else if (c == '\n') {
1078 error("invalid key (newline): %s", key);
1079 free(store.key);
1080 ret = 1;
1081 goto out_free;
1083 store.key[i] = c;
1085 store.key[i] = 0;
1088 * The lock serves a purpose in addition to locking: the new
1089 * contents of .git/config will be written into it.
1091 lock = xcalloc(sizeof(struct lock_file), 1);
1092 fd = hold_lock_file_for_update(lock, config_filename, 0);
1093 if (fd < 0) {
1094 error("could not lock config file %s: %s", config_filename, strerror(errno));
1095 free(store.key);
1096 ret = -1;
1097 goto out_free;
1101 * If .git/config does not exist yet, write a minimal version.
1103 in_fd = open(config_filename, O_RDONLY);
1104 if ( in_fd < 0 ) {
1105 free(store.key);
1107 if ( ENOENT != errno ) {
1108 error("opening %s: %s", config_filename,
1109 strerror(errno));
1110 ret = 3; /* same as "invalid config file" */
1111 goto out_free;
1113 /* if nothing to unset, error out */
1114 if (value == NULL) {
1115 ret = 5;
1116 goto out_free;
1119 store.key = (char *)key;
1120 if (!store_write_section(fd, key) ||
1121 !store_write_pair(fd, key, value))
1122 goto write_err_out;
1123 } else {
1124 struct stat st;
1125 char *contents;
1126 size_t contents_sz, copy_begin, copy_end;
1127 int i, new_line = 0;
1129 if (value_regex == NULL)
1130 store.value_regex = NULL;
1131 else {
1132 if (value_regex[0] == '!') {
1133 store.do_not_match = 1;
1134 value_regex++;
1135 } else
1136 store.do_not_match = 0;
1138 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1139 if (regcomp(store.value_regex, value_regex,
1140 REG_EXTENDED)) {
1141 error("invalid pattern: %s", value_regex);
1142 free(store.value_regex);
1143 ret = 6;
1144 goto out_free;
1148 store.offset[0] = 0;
1149 store.state = START;
1150 store.seen = 0;
1153 * After this, store.offset will contain the *end* offset
1154 * of the last match, or remain at 0 if no match was found.
1155 * As a side effect, we make sure to transform only a valid
1156 * existing config file.
1158 if (git_config_from_file(store_aux, config_filename, NULL)) {
1159 error("invalid config file %s", config_filename);
1160 free(store.key);
1161 if (store.value_regex != NULL) {
1162 regfree(store.value_regex);
1163 free(store.value_regex);
1165 ret = 3;
1166 goto out_free;
1169 free(store.key);
1170 if (store.value_regex != NULL) {
1171 regfree(store.value_regex);
1172 free(store.value_regex);
1175 /* if nothing to unset, or too many matches, error out */
1176 if ((store.seen == 0 && value == NULL) ||
1177 (store.seen > 1 && multi_replace == 0)) {
1178 ret = 5;
1179 goto out_free;
1182 fstat(in_fd, &st);
1183 contents_sz = xsize_t(st.st_size);
1184 contents = xmmap(NULL, contents_sz, PROT_READ,
1185 MAP_PRIVATE, in_fd, 0);
1186 close(in_fd);
1188 if (store.seen == 0)
1189 store.seen = 1;
1191 for (i = 0, copy_begin = 0; i < store.seen; i++) {
1192 if (store.offset[i] == 0) {
1193 store.offset[i] = copy_end = contents_sz;
1194 } else if (store.state != KEY_SEEN) {
1195 copy_end = store.offset[i];
1196 } else
1197 copy_end = find_beginning_of_line(
1198 contents, contents_sz,
1199 store.offset[i]-2, &new_line);
1201 if (copy_end > 0 && contents[copy_end-1] != '\n')
1202 new_line = 1;
1204 /* write the first part of the config */
1205 if (copy_end > copy_begin) {
1206 if (write_in_full(fd, contents + copy_begin,
1207 copy_end - copy_begin) <
1208 copy_end - copy_begin)
1209 goto write_err_out;
1210 if (new_line &&
1211 write_str_in_full(fd, "\n") != 1)
1212 goto write_err_out;
1214 copy_begin = store.offset[i];
1217 /* write the pair (value == NULL means unset) */
1218 if (value != NULL) {
1219 if (store.state == START) {
1220 if (!store_write_section(fd, key))
1221 goto write_err_out;
1223 if (!store_write_pair(fd, key, value))
1224 goto write_err_out;
1227 /* write the rest of the config */
1228 if (copy_begin < contents_sz)
1229 if (write_in_full(fd, contents + copy_begin,
1230 contents_sz - copy_begin) <
1231 contents_sz - copy_begin)
1232 goto write_err_out;
1234 munmap(contents, contents_sz);
1237 if (commit_lock_file(lock) < 0) {
1238 error("could not commit config file %s", config_filename);
1239 ret = 4;
1240 goto out_free;
1244 * lock is committed, so don't try to roll it back below.
1245 * NOTE: Since lockfile.c keeps a linked list of all created
1246 * lock_file structures, it isn't safe to free(lock). It's
1247 * better to just leave it hanging around.
1249 lock = NULL;
1250 ret = 0;
1252 out_free:
1253 if (lock)
1254 rollback_lock_file(lock);
1255 free(config_filename);
1256 return ret;
1258 write_err_out:
1259 ret = write_error(lock->filename);
1260 goto out_free;
1264 static int section_name_match (const char *buf, const char *name)
1266 int i = 0, j = 0, dot = 0;
1267 if (buf[i] != '[')
1268 return 0;
1269 for (i = 1; buf[i] && buf[i] != ']'; i++) {
1270 if (!dot && isspace(buf[i])) {
1271 dot = 1;
1272 if (name[j++] != '.')
1273 break;
1274 for (i++; isspace(buf[i]); i++)
1275 ; /* do nothing */
1276 if (buf[i] != '"')
1277 break;
1278 continue;
1280 if (buf[i] == '\\' && dot)
1281 i++;
1282 else if (buf[i] == '"' && dot) {
1283 for (i++; isspace(buf[i]); i++)
1284 ; /* do_nothing */
1285 break;
1287 if (buf[i] != name[j++])
1288 break;
1290 if (buf[i] == ']' && name[j] == 0) {
1292 * We match, now just find the right length offset by
1293 * gobbling up any whitespace after it, as well
1295 i++;
1296 for (; buf[i] && isspace(buf[i]); i++)
1297 ; /* do nothing */
1298 return i;
1300 return 0;
1303 /* if new_name == NULL, the section is removed instead */
1304 int git_config_rename_section(const char *old_name, const char *new_name)
1306 int ret = 0, remove = 0;
1307 char *config_filename;
1308 struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1309 int out_fd;
1310 char buf[1024];
1312 if (config_exclusive_filename)
1313 config_filename = xstrdup(config_exclusive_filename);
1314 else
1315 config_filename = git_pathdup("config");
1316 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1317 if (out_fd < 0) {
1318 ret = error("could not lock config file %s", config_filename);
1319 goto out;
1322 if (!(config_file = fopen(config_filename, "rb"))) {
1323 /* no config file means nothing to rename, no error */
1324 goto unlock_and_out;
1327 while (fgets(buf, sizeof(buf), config_file)) {
1328 int i;
1329 int length;
1330 char *output = buf;
1331 for (i = 0; buf[i] && isspace(buf[i]); i++)
1332 ; /* do nothing */
1333 if (buf[i] == '[') {
1334 /* it's a section */
1335 int offset = section_name_match(&buf[i], old_name);
1336 if (offset > 0) {
1337 ret++;
1338 if (new_name == NULL) {
1339 remove = 1;
1340 continue;
1342 store.baselen = strlen(new_name);
1343 if (!store_write_section(out_fd, new_name)) {
1344 ret = write_error(lock->filename);
1345 goto out;
1348 * We wrote out the new section, with
1349 * a newline, now skip the old
1350 * section's length
1352 output += offset + i;
1353 if (strlen(output) > 0) {
1355 * More content means there's
1356 * a declaration to put on the
1357 * next line; indent with a
1358 * tab
1360 output -= 1;
1361 output[0] = '\t';
1364 remove = 0;
1366 if (remove)
1367 continue;
1368 length = strlen(output);
1369 if (write_in_full(out_fd, output, length) != length) {
1370 ret = write_error(lock->filename);
1371 goto out;
1374 fclose(config_file);
1375 unlock_and_out:
1376 if (commit_lock_file(lock) < 0)
1377 ret = error("could not commit config file %s", config_filename);
1378 out:
1379 free(config_filename);
1380 return ret;
1384 * Call this to report error for your variable that should not
1385 * get a boolean value (i.e. "[my] var" means "true").
1387 int config_error_nonbool(const char *var)
1389 return error("Missing value for '%s'", var);