]> git.ipfire.org Git - thirdparty/git.git/blob - config.c
Merge branch 'pw/add-p-single-key'
[thirdparty/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 "date.h"
10 #include "branch.h"
11 #include "config.h"
12 #include "environment.h"
13 #include "repository.h"
14 #include "lockfile.h"
15 #include "exec-cmd.h"
16 #include "strbuf.h"
17 #include "quote.h"
18 #include "hashmap.h"
19 #include "string-list.h"
20 #include "object-store.h"
21 #include "utf8.h"
22 #include "dir.h"
23 #include "color.h"
24 #include "refs.h"
25 #include "worktree.h"
26
27 struct config_source {
28 struct config_source *prev;
29 union {
30 FILE *file;
31 struct config_buf {
32 const char *buf;
33 size_t len;
34 size_t pos;
35 } buf;
36 } u;
37 enum config_origin_type origin_type;
38 const char *name;
39 const char *path;
40 enum config_error_action default_error_action;
41 int linenr;
42 int eof;
43 size_t total_len;
44 struct strbuf value;
45 struct strbuf var;
46 unsigned subsection_case_sensitive : 1;
47
48 int (*do_fgetc)(struct config_source *c);
49 int (*do_ungetc)(int c, struct config_source *conf);
50 long (*do_ftell)(struct config_source *c);
51 };
52
53 /*
54 * These variables record the "current" config source, which
55 * can be accessed by parsing callbacks.
56 *
57 * The "cf" variable will be non-NULL only when we are actually parsing a real
58 * config source (file, blob, cmdline, etc).
59 *
60 * The "current_config_kvi" variable will be non-NULL only when we are feeding
61 * cached config from a configset into a callback.
62 *
63 * They should generally never be non-NULL at the same time. If they are both
64 * NULL, then we aren't parsing anything (and depending on the function looking
65 * at the variables, it's either a bug for it to be called in the first place,
66 * or it's a function which can be reused for non-config purposes, and should
67 * fall back to some sane behavior).
68 */
69 static struct config_source *cf;
70 static struct key_value_info *current_config_kvi;
71
72 /*
73 * Similar to the variables above, this gives access to the "scope" of the
74 * current value (repo, global, etc). For cached values, it can be found via
75 * the current_config_kvi as above. During parsing, the current value can be
76 * found in this variable. It's not part of "cf" because it transcends a single
77 * file (i.e., a file included from .git/config is still in "repo" scope).
78 */
79 static enum config_scope current_parsing_scope;
80
81 static int pack_compression_seen;
82 static int zlib_compression_seen;
83
84 static int config_file_fgetc(struct config_source *conf)
85 {
86 return getc_unlocked(conf->u.file);
87 }
88
89 static int config_file_ungetc(int c, struct config_source *conf)
90 {
91 return ungetc(c, conf->u.file);
92 }
93
94 static long config_file_ftell(struct config_source *conf)
95 {
96 return ftell(conf->u.file);
97 }
98
99
100 static int config_buf_fgetc(struct config_source *conf)
101 {
102 if (conf->u.buf.pos < conf->u.buf.len)
103 return conf->u.buf.buf[conf->u.buf.pos++];
104
105 return EOF;
106 }
107
108 static int config_buf_ungetc(int c, struct config_source *conf)
109 {
110 if (conf->u.buf.pos > 0) {
111 conf->u.buf.pos--;
112 if (conf->u.buf.buf[conf->u.buf.pos] != c)
113 BUG("config_buf can only ungetc the same character");
114 return c;
115 }
116
117 return EOF;
118 }
119
120 static long config_buf_ftell(struct config_source *conf)
121 {
122 return conf->u.buf.pos;
123 }
124
125 struct config_include_data {
126 int depth;
127 config_fn_t fn;
128 void *data;
129 const struct config_options *opts;
130 struct git_config_source *config_source;
131
132 /*
133 * All remote URLs discovered when reading all config files.
134 */
135 struct string_list *remote_urls;
136 };
137 #define CONFIG_INCLUDE_INIT { 0 }
138
139 static int git_config_include(const char *var, const char *value, void *data);
140
141 #define MAX_INCLUDE_DEPTH 10
142 static const char include_depth_advice[] = N_(
143 "exceeded maximum include depth (%d) while including\n"
144 " %s\n"
145 "from\n"
146 " %s\n"
147 "This might be due to circular includes.");
148 static int handle_path_include(const char *path, struct config_include_data *inc)
149 {
150 int ret = 0;
151 struct strbuf buf = STRBUF_INIT;
152 char *expanded;
153
154 if (!path)
155 return config_error_nonbool("include.path");
156
157 expanded = interpolate_path(path, 0);
158 if (!expanded)
159 return error(_("could not expand include path '%s'"), path);
160 path = expanded;
161
162 /*
163 * Use an absolute path as-is, but interpret relative paths
164 * based on the including config file.
165 */
166 if (!is_absolute_path(path)) {
167 char *slash;
168
169 if (!cf || !cf->path) {
170 ret = error(_("relative config includes must come from files"));
171 goto cleanup;
172 }
173
174 slash = find_last_dir_sep(cf->path);
175 if (slash)
176 strbuf_add(&buf, cf->path, slash - cf->path + 1);
177 strbuf_addstr(&buf, path);
178 path = buf.buf;
179 }
180
181 if (!access_or_die(path, R_OK, 0)) {
182 if (++inc->depth > MAX_INCLUDE_DEPTH)
183 die(_(include_depth_advice), MAX_INCLUDE_DEPTH, path,
184 !cf ? "<unknown>" :
185 cf->name ? cf->name :
186 "the command line");
187 ret = git_config_from_file(git_config_include, path, inc);
188 inc->depth--;
189 }
190 cleanup:
191 strbuf_release(&buf);
192 free(expanded);
193 return ret;
194 }
195
196 static void add_trailing_starstar_for_dir(struct strbuf *pat)
197 {
198 if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
199 strbuf_addstr(pat, "**");
200 }
201
202 static int prepare_include_condition_pattern(struct strbuf *pat)
203 {
204 struct strbuf path = STRBUF_INIT;
205 char *expanded;
206 int prefix = 0;
207
208 expanded = interpolate_path(pat->buf, 1);
209 if (expanded) {
210 strbuf_reset(pat);
211 strbuf_addstr(pat, expanded);
212 free(expanded);
213 }
214
215 if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
216 const char *slash;
217
218 if (!cf || !cf->path)
219 return error(_("relative config include "
220 "conditionals must come from files"));
221
222 strbuf_realpath(&path, cf->path, 1);
223 slash = find_last_dir_sep(path.buf);
224 if (!slash)
225 BUG("how is this possible?");
226 strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
227 prefix = slash - path.buf + 1 /* slash */;
228 } else if (!is_absolute_path(pat->buf))
229 strbuf_insertstr(pat, 0, "**/");
230
231 add_trailing_starstar_for_dir(pat);
232
233 strbuf_release(&path);
234 return prefix;
235 }
236
237 static int include_by_gitdir(const struct config_options *opts,
238 const char *cond, size_t cond_len, int icase)
239 {
240 struct strbuf text = STRBUF_INIT;
241 struct strbuf pattern = STRBUF_INIT;
242 int ret = 0, prefix;
243 const char *git_dir;
244 int already_tried_absolute = 0;
245
246 if (opts->git_dir)
247 git_dir = opts->git_dir;
248 else
249 goto done;
250
251 strbuf_realpath(&text, git_dir, 1);
252 strbuf_add(&pattern, cond, cond_len);
253 prefix = prepare_include_condition_pattern(&pattern);
254
255 again:
256 if (prefix < 0)
257 goto done;
258
259 if (prefix > 0) {
260 /*
261 * perform literal matching on the prefix part so that
262 * any wildcard character in it can't create side effects.
263 */
264 if (text.len < prefix)
265 goto done;
266 if (!icase && strncmp(pattern.buf, text.buf, prefix))
267 goto done;
268 if (icase && strncasecmp(pattern.buf, text.buf, prefix))
269 goto done;
270 }
271
272 ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
273 WM_PATHNAME | (icase ? WM_CASEFOLD : 0));
274
275 if (!ret && !already_tried_absolute) {
276 /*
277 * We've tried e.g. matching gitdir:~/work, but if
278 * ~/work is a symlink to /mnt/storage/work
279 * strbuf_realpath() will expand it, so the rule won't
280 * match. Let's match against a
281 * strbuf_add_absolute_path() version of the path,
282 * which'll do the right thing
283 */
284 strbuf_reset(&text);
285 strbuf_add_absolute_path(&text, git_dir);
286 already_tried_absolute = 1;
287 goto again;
288 }
289 done:
290 strbuf_release(&pattern);
291 strbuf_release(&text);
292 return ret;
293 }
294
295 static int include_by_branch(const char *cond, size_t cond_len)
296 {
297 int flags;
298 int ret;
299 struct strbuf pattern = STRBUF_INIT;
300 const char *refname = !the_repository->gitdir ?
301 NULL : resolve_ref_unsafe("HEAD", 0, NULL, &flags);
302 const char *shortname;
303
304 if (!refname || !(flags & REF_ISSYMREF) ||
305 !skip_prefix(refname, "refs/heads/", &shortname))
306 return 0;
307
308 strbuf_add(&pattern, cond, cond_len);
309 add_trailing_starstar_for_dir(&pattern);
310 ret = !wildmatch(pattern.buf, shortname, WM_PATHNAME);
311 strbuf_release(&pattern);
312 return ret;
313 }
314
315 static int add_remote_url(const char *var, const char *value, void *data)
316 {
317 struct string_list *remote_urls = data;
318 const char *remote_name;
319 size_t remote_name_len;
320 const char *key;
321
322 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
323 &key) &&
324 remote_name &&
325 !strcmp(key, "url"))
326 string_list_append(remote_urls, value);
327 return 0;
328 }
329
330 static void populate_remote_urls(struct config_include_data *inc)
331 {
332 struct config_options opts;
333
334 struct config_source *store_cf = cf;
335 struct key_value_info *store_kvi = current_config_kvi;
336 enum config_scope store_scope = current_parsing_scope;
337
338 opts = *inc->opts;
339 opts.unconditional_remote_url = 1;
340
341 cf = NULL;
342 current_config_kvi = NULL;
343 current_parsing_scope = 0;
344
345 inc->remote_urls = xmalloc(sizeof(*inc->remote_urls));
346 string_list_init_dup(inc->remote_urls);
347 config_with_options(add_remote_url, inc->remote_urls, inc->config_source, &opts);
348
349 cf = store_cf;
350 current_config_kvi = store_kvi;
351 current_parsing_scope = store_scope;
352 }
353
354 static int forbid_remote_url(const char *var, const char *value, void *data)
355 {
356 const char *remote_name;
357 size_t remote_name_len;
358 const char *key;
359
360 if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
361 &key) &&
362 remote_name &&
363 !strcmp(key, "url"))
364 die(_("remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"));
365 return 0;
366 }
367
368 static int at_least_one_url_matches_glob(const char *glob, int glob_len,
369 struct string_list *remote_urls)
370 {
371 struct strbuf pattern = STRBUF_INIT;
372 struct string_list_item *url_item;
373 int found = 0;
374
375 strbuf_add(&pattern, glob, glob_len);
376 for_each_string_list_item(url_item, remote_urls) {
377 if (!wildmatch(pattern.buf, url_item->string, WM_PATHNAME)) {
378 found = 1;
379 break;
380 }
381 }
382 strbuf_release(&pattern);
383 return found;
384 }
385
386 static int include_by_remote_url(struct config_include_data *inc,
387 const char *cond, size_t cond_len)
388 {
389 if (inc->opts->unconditional_remote_url)
390 return 1;
391 if (!inc->remote_urls)
392 populate_remote_urls(inc);
393 return at_least_one_url_matches_glob(cond, cond_len,
394 inc->remote_urls);
395 }
396
397 static int include_condition_is_true(struct config_include_data *inc,
398 const char *cond, size_t cond_len)
399 {
400 const struct config_options *opts = inc->opts;
401
402 if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
403 return include_by_gitdir(opts, cond, cond_len, 0);
404 else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
405 return include_by_gitdir(opts, cond, cond_len, 1);
406 else if (skip_prefix_mem(cond, cond_len, "onbranch:", &cond, &cond_len))
407 return include_by_branch(cond, cond_len);
408 else if (skip_prefix_mem(cond, cond_len, "hasconfig:remote.*.url:", &cond,
409 &cond_len))
410 return include_by_remote_url(inc, cond, cond_len);
411
412 /* unknown conditionals are always false */
413 return 0;
414 }
415
416 static int git_config_include(const char *var, const char *value, void *data)
417 {
418 struct config_include_data *inc = data;
419 const char *cond, *key;
420 size_t cond_len;
421 int ret;
422
423 /*
424 * Pass along all values, including "include" directives; this makes it
425 * possible to query information on the includes themselves.
426 */
427 ret = inc->fn(var, value, inc->data);
428 if (ret < 0)
429 return ret;
430
431 if (!strcmp(var, "include.path"))
432 ret = handle_path_include(value, inc);
433
434 if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
435 cond && include_condition_is_true(inc, cond, cond_len) &&
436 !strcmp(key, "path")) {
437 config_fn_t old_fn = inc->fn;
438
439 if (inc->opts->unconditional_remote_url)
440 inc->fn = forbid_remote_url;
441 ret = handle_path_include(value, inc);
442 inc->fn = old_fn;
443 }
444
445 return ret;
446 }
447
448 static void git_config_push_split_parameter(const char *key, const char *value)
449 {
450 struct strbuf env = STRBUF_INIT;
451 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
452 if (old && *old) {
453 strbuf_addstr(&env, old);
454 strbuf_addch(&env, ' ');
455 }
456 sq_quote_buf(&env, key);
457 strbuf_addch(&env, '=');
458 if (value)
459 sq_quote_buf(&env, value);
460 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
461 strbuf_release(&env);
462 }
463
464 void git_config_push_parameter(const char *text)
465 {
466 const char *value;
467
468 /*
469 * When we see:
470 *
471 * section.subsection=with=equals.key=value
472 *
473 * we cannot tell if it means:
474 *
475 * [section "subsection=with=equals"]
476 * key = value
477 *
478 * or:
479 *
480 * [section]
481 * subsection = with=equals.key=value
482 *
483 * We parse left-to-right for the first "=", meaning we'll prefer to
484 * keep the value intact over the subsection. This is historical, but
485 * also sensible since values are more likely to contain odd or
486 * untrusted input than a section name.
487 *
488 * A missing equals is explicitly allowed (as a bool-only entry).
489 */
490 value = strchr(text, '=');
491 if (value) {
492 char *key = xmemdupz(text, value - text);
493 git_config_push_split_parameter(key, value + 1);
494 free(key);
495 } else {
496 git_config_push_split_parameter(text, NULL);
497 }
498 }
499
500 void git_config_push_env(const char *spec)
501 {
502 char *key;
503 const char *env_name;
504 const char *env_value;
505
506 env_name = strrchr(spec, '=');
507 if (!env_name)
508 die(_("invalid config format: %s"), spec);
509 key = xmemdupz(spec, env_name - spec);
510 env_name++;
511 if (!*env_name)
512 die(_("missing environment variable name for configuration '%.*s'"),
513 (int)(env_name - spec - 1), spec);
514
515 env_value = getenv(env_name);
516 if (!env_value)
517 die(_("missing environment variable '%s' for configuration '%.*s'"),
518 env_name, (int)(env_name - spec - 1), spec);
519
520 git_config_push_split_parameter(key, env_value);
521 free(key);
522 }
523
524 static inline int iskeychar(int c)
525 {
526 return isalnum(c) || c == '-';
527 }
528
529 /*
530 * Auxiliary function to sanity-check and split the key into the section
531 * identifier and variable name.
532 *
533 * Returns 0 on success, -1 when there is an invalid character in the key and
534 * -2 if there is no section name in the key.
535 *
536 * store_key - pointer to char* which will hold a copy of the key with
537 * lowercase section and variable name
538 * baselen - pointer to size_t which will hold the length of the
539 * section + subsection part, can be NULL
540 */
541 int git_config_parse_key(const char *key, char **store_key, size_t *baselen_)
542 {
543 size_t i, baselen;
544 int dot;
545 const char *last_dot = strrchr(key, '.');
546
547 /*
548 * Since "key" actually contains the section name and the real
549 * key name separated by a dot, we have to know where the dot is.
550 */
551
552 if (last_dot == NULL || last_dot == key) {
553 error(_("key does not contain a section: %s"), key);
554 return -CONFIG_NO_SECTION_OR_NAME;
555 }
556
557 if (!last_dot[1]) {
558 error(_("key does not contain variable name: %s"), key);
559 return -CONFIG_NO_SECTION_OR_NAME;
560 }
561
562 baselen = last_dot - key;
563 if (baselen_)
564 *baselen_ = baselen;
565
566 /*
567 * Validate the key and while at it, lower case it for matching.
568 */
569 *store_key = xmallocz(strlen(key));
570
571 dot = 0;
572 for (i = 0; key[i]; i++) {
573 unsigned char c = key[i];
574 if (c == '.')
575 dot = 1;
576 /* Leave the extended basename untouched.. */
577 if (!dot || i > baselen) {
578 if (!iskeychar(c) ||
579 (i == baselen + 1 && !isalpha(c))) {
580 error(_("invalid key: %s"), key);
581 goto out_free_ret_1;
582 }
583 c = tolower(c);
584 } else if (c == '\n') {
585 error(_("invalid key (newline): %s"), key);
586 goto out_free_ret_1;
587 }
588 (*store_key)[i] = c;
589 }
590
591 return 0;
592
593 out_free_ret_1:
594 FREE_AND_NULL(*store_key);
595 return -CONFIG_INVALID_KEY;
596 }
597
598 static int config_parse_pair(const char *key, const char *value,
599 config_fn_t fn, void *data)
600 {
601 char *canonical_name;
602 int ret;
603
604 if (!strlen(key))
605 return error(_("empty config key"));
606 if (git_config_parse_key(key, &canonical_name, NULL))
607 return -1;
608
609 ret = (fn(canonical_name, value, data) < 0) ? -1 : 0;
610 free(canonical_name);
611 return ret;
612 }
613
614 int git_config_parse_parameter(const char *text,
615 config_fn_t fn, void *data)
616 {
617 const char *value;
618 struct strbuf **pair;
619 int ret;
620
621 pair = strbuf_split_str(text, '=', 2);
622 if (!pair[0])
623 return error(_("bogus config parameter: %s"), text);
624
625 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
626 strbuf_setlen(pair[0], pair[0]->len - 1);
627 value = pair[1] ? pair[1]->buf : "";
628 } else {
629 value = NULL;
630 }
631
632 strbuf_trim(pair[0]);
633 if (!pair[0]->len) {
634 strbuf_list_free(pair);
635 return error(_("bogus config parameter: %s"), text);
636 }
637
638 ret = config_parse_pair(pair[0]->buf, value, fn, data);
639 strbuf_list_free(pair);
640 return ret;
641 }
642
643 static int parse_config_env_list(char *env, config_fn_t fn, void *data)
644 {
645 char *cur = env;
646 while (cur && *cur) {
647 const char *key = sq_dequote_step(cur, &cur);
648 if (!key)
649 return error(_("bogus format in %s"),
650 CONFIG_DATA_ENVIRONMENT);
651
652 if (!cur || isspace(*cur)) {
653 /* old-style 'key=value' */
654 if (git_config_parse_parameter(key, fn, data) < 0)
655 return -1;
656 }
657 else if (*cur == '=') {
658 /* new-style 'key'='value' */
659 const char *value;
660
661 cur++;
662 if (*cur == '\'') {
663 /* quoted value */
664 value = sq_dequote_step(cur, &cur);
665 if (!value || (cur && !isspace(*cur))) {
666 return error(_("bogus format in %s"),
667 CONFIG_DATA_ENVIRONMENT);
668 }
669 } else if (!*cur || isspace(*cur)) {
670 /* implicit bool: 'key'= */
671 value = NULL;
672 } else {
673 return error(_("bogus format in %s"),
674 CONFIG_DATA_ENVIRONMENT);
675 }
676
677 if (config_parse_pair(key, value, fn, data) < 0)
678 return -1;
679 }
680 else {
681 /* unknown format */
682 return error(_("bogus format in %s"),
683 CONFIG_DATA_ENVIRONMENT);
684 }
685
686 if (cur) {
687 while (isspace(*cur))
688 cur++;
689 }
690 }
691 return 0;
692 }
693
694 int git_config_from_parameters(config_fn_t fn, void *data)
695 {
696 const char *env;
697 struct strbuf envvar = STRBUF_INIT;
698 struct strvec to_free = STRVEC_INIT;
699 int ret = 0;
700 char *envw = NULL;
701 struct config_source source;
702
703 memset(&source, 0, sizeof(source));
704 source.prev = cf;
705 source.origin_type = CONFIG_ORIGIN_CMDLINE;
706 cf = &source;
707
708 env = getenv(CONFIG_COUNT_ENVIRONMENT);
709 if (env) {
710 unsigned long count;
711 char *endp;
712 int i;
713
714 count = strtoul(env, &endp, 10);
715 if (*endp) {
716 ret = error(_("bogus count in %s"), CONFIG_COUNT_ENVIRONMENT);
717 goto out;
718 }
719 if (count > INT_MAX) {
720 ret = error(_("too many entries in %s"), CONFIG_COUNT_ENVIRONMENT);
721 goto out;
722 }
723
724 for (i = 0; i < count; i++) {
725 const char *key, *value;
726
727 strbuf_addf(&envvar, "GIT_CONFIG_KEY_%d", i);
728 key = getenv_safe(&to_free, envvar.buf);
729 if (!key) {
730 ret = error(_("missing config key %s"), envvar.buf);
731 goto out;
732 }
733 strbuf_reset(&envvar);
734
735 strbuf_addf(&envvar, "GIT_CONFIG_VALUE_%d", i);
736 value = getenv_safe(&to_free, envvar.buf);
737 if (!value) {
738 ret = error(_("missing config value %s"), envvar.buf);
739 goto out;
740 }
741 strbuf_reset(&envvar);
742
743 if (config_parse_pair(key, value, fn, data) < 0) {
744 ret = -1;
745 goto out;
746 }
747 }
748 }
749
750 env = getenv(CONFIG_DATA_ENVIRONMENT);
751 if (env) {
752 /* sq_dequote will write over it */
753 envw = xstrdup(env);
754 if (parse_config_env_list(envw, fn, data) < 0) {
755 ret = -1;
756 goto out;
757 }
758 }
759
760 out:
761 strbuf_release(&envvar);
762 strvec_clear(&to_free);
763 free(envw);
764 cf = source.prev;
765 return ret;
766 }
767
768 static int get_next_char(void)
769 {
770 int c = cf->do_fgetc(cf);
771
772 if (c == '\r') {
773 /* DOS like systems */
774 c = cf->do_fgetc(cf);
775 if (c != '\n') {
776 if (c != EOF)
777 cf->do_ungetc(c, cf);
778 c = '\r';
779 }
780 }
781
782 if (c != EOF && ++cf->total_len > INT_MAX) {
783 /*
784 * This is an absurdly long config file; refuse to parse
785 * further in order to protect downstream code from integer
786 * overflows. Note that we can't return an error specifically,
787 * but we can mark EOF and put trash in the return value,
788 * which will trigger a parse error.
789 */
790 cf->eof = 1;
791 return 0;
792 }
793
794 if (c == '\n')
795 cf->linenr++;
796 if (c == EOF) {
797 cf->eof = 1;
798 cf->linenr++;
799 c = '\n';
800 }
801 return c;
802 }
803
804 static char *parse_value(void)
805 {
806 int quote = 0, comment = 0, space = 0;
807
808 strbuf_reset(&cf->value);
809 for (;;) {
810 int c = get_next_char();
811 if (c == '\n') {
812 if (quote) {
813 cf->linenr--;
814 return NULL;
815 }
816 return cf->value.buf;
817 }
818 if (comment)
819 continue;
820 if (isspace(c) && !quote) {
821 if (cf->value.len)
822 space++;
823 continue;
824 }
825 if (!quote) {
826 if (c == ';' || c == '#') {
827 comment = 1;
828 continue;
829 }
830 }
831 for (; space; space--)
832 strbuf_addch(&cf->value, ' ');
833 if (c == '\\') {
834 c = get_next_char();
835 switch (c) {
836 case '\n':
837 continue;
838 case 't':
839 c = '\t';
840 break;
841 case 'b':
842 c = '\b';
843 break;
844 case 'n':
845 c = '\n';
846 break;
847 /* Some characters escape as themselves */
848 case '\\': case '"':
849 break;
850 /* Reject unknown escape sequences */
851 default:
852 return NULL;
853 }
854 strbuf_addch(&cf->value, c);
855 continue;
856 }
857 if (c == '"') {
858 quote = 1-quote;
859 continue;
860 }
861 strbuf_addch(&cf->value, c);
862 }
863 }
864
865 static int get_value(config_fn_t fn, void *data, struct strbuf *name)
866 {
867 int c;
868 char *value;
869 int ret;
870
871 /* Get the full name */
872 for (;;) {
873 c = get_next_char();
874 if (cf->eof)
875 break;
876 if (!iskeychar(c))
877 break;
878 strbuf_addch(name, tolower(c));
879 }
880
881 while (c == ' ' || c == '\t')
882 c = get_next_char();
883
884 value = NULL;
885 if (c != '\n') {
886 if (c != '=')
887 return -1;
888 value = parse_value();
889 if (!value)
890 return -1;
891 }
892 /*
893 * We already consumed the \n, but we need linenr to point to
894 * the line we just parsed during the call to fn to get
895 * accurate line number in error messages.
896 */
897 cf->linenr--;
898 ret = fn(name->buf, value, data);
899 if (ret >= 0)
900 cf->linenr++;
901 return ret;
902 }
903
904 static int get_extended_base_var(struct strbuf *name, int c)
905 {
906 cf->subsection_case_sensitive = 0;
907 do {
908 if (c == '\n')
909 goto error_incomplete_line;
910 c = get_next_char();
911 } while (isspace(c));
912
913 /* We require the format to be '[base "extension"]' */
914 if (c != '"')
915 return -1;
916 strbuf_addch(name, '.');
917
918 for (;;) {
919 int c = get_next_char();
920 if (c == '\n')
921 goto error_incomplete_line;
922 if (c == '"')
923 break;
924 if (c == '\\') {
925 c = get_next_char();
926 if (c == '\n')
927 goto error_incomplete_line;
928 }
929 strbuf_addch(name, c);
930 }
931
932 /* Final ']' */
933 if (get_next_char() != ']')
934 return -1;
935 return 0;
936 error_incomplete_line:
937 cf->linenr--;
938 return -1;
939 }
940
941 static int get_base_var(struct strbuf *name)
942 {
943 cf->subsection_case_sensitive = 1;
944 for (;;) {
945 int c = get_next_char();
946 if (cf->eof)
947 return -1;
948 if (c == ']')
949 return 0;
950 if (isspace(c))
951 return get_extended_base_var(name, c);
952 if (!iskeychar(c) && c != '.')
953 return -1;
954 strbuf_addch(name, tolower(c));
955 }
956 }
957
958 struct parse_event_data {
959 enum config_event_t previous_type;
960 size_t previous_offset;
961 const struct config_options *opts;
962 };
963
964 static int do_event(enum config_event_t type, struct parse_event_data *data)
965 {
966 size_t offset;
967
968 if (!data->opts || !data->opts->event_fn)
969 return 0;
970
971 if (type == CONFIG_EVENT_WHITESPACE &&
972 data->previous_type == type)
973 return 0;
974
975 offset = cf->do_ftell(cf);
976 /*
977 * At EOF, the parser always "inserts" an extra '\n', therefore
978 * the end offset of the event is the current file position, otherwise
979 * we will already have advanced to the next event.
980 */
981 if (type != CONFIG_EVENT_EOF)
982 offset--;
983
984 if (data->previous_type != CONFIG_EVENT_EOF &&
985 data->opts->event_fn(data->previous_type, data->previous_offset,
986 offset, data->opts->event_fn_data) < 0)
987 return -1;
988
989 data->previous_type = type;
990 data->previous_offset = offset;
991
992 return 0;
993 }
994
995 static int git_parse_source(config_fn_t fn, void *data,
996 const struct config_options *opts)
997 {
998 int comment = 0;
999 size_t baselen = 0;
1000 struct strbuf *var = &cf->var;
1001 int error_return = 0;
1002 char *error_msg = NULL;
1003
1004 /* U+FEFF Byte Order Mark in UTF8 */
1005 const char *bomptr = utf8_bom;
1006
1007 /* For the parser event callback */
1008 struct parse_event_data event_data = {
1009 CONFIG_EVENT_EOF, 0, opts
1010 };
1011
1012 for (;;) {
1013 int c;
1014
1015 c = get_next_char();
1016 if (bomptr && *bomptr) {
1017 /* We are at the file beginning; skip UTF8-encoded BOM
1018 * if present. Sane editors won't put this in on their
1019 * own, but e.g. Windows Notepad will do it happily. */
1020 if (c == (*bomptr & 0377)) {
1021 bomptr++;
1022 continue;
1023 } else {
1024 /* Do not tolerate partial BOM. */
1025 if (bomptr != utf8_bom)
1026 break;
1027 /* No BOM at file beginning. Cool. */
1028 bomptr = NULL;
1029 }
1030 }
1031 if (c == '\n') {
1032 if (cf->eof) {
1033 if (do_event(CONFIG_EVENT_EOF, &event_data) < 0)
1034 return -1;
1035 return 0;
1036 }
1037 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1038 return -1;
1039 comment = 0;
1040 continue;
1041 }
1042 if (comment)
1043 continue;
1044 if (isspace(c)) {
1045 if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1046 return -1;
1047 continue;
1048 }
1049 if (c == '#' || c == ';') {
1050 if (do_event(CONFIG_EVENT_COMMENT, &event_data) < 0)
1051 return -1;
1052 comment = 1;
1053 continue;
1054 }
1055 if (c == '[') {
1056 if (do_event(CONFIG_EVENT_SECTION, &event_data) < 0)
1057 return -1;
1058
1059 /* Reset prior to determining a new stem */
1060 strbuf_reset(var);
1061 if (get_base_var(var) < 0 || var->len < 1)
1062 break;
1063 strbuf_addch(var, '.');
1064 baselen = var->len;
1065 continue;
1066 }
1067 if (!isalpha(c))
1068 break;
1069
1070 if (do_event(CONFIG_EVENT_ENTRY, &event_data) < 0)
1071 return -1;
1072
1073 /*
1074 * Truncate the var name back to the section header
1075 * stem prior to grabbing the suffix part of the name
1076 * and the value.
1077 */
1078 strbuf_setlen(var, baselen);
1079 strbuf_addch(var, tolower(c));
1080 if (get_value(fn, data, var) < 0)
1081 break;
1082 }
1083
1084 if (do_event(CONFIG_EVENT_ERROR, &event_data) < 0)
1085 return -1;
1086
1087 switch (cf->origin_type) {
1088 case CONFIG_ORIGIN_BLOB:
1089 error_msg = xstrfmt(_("bad config line %d in blob %s"),
1090 cf->linenr, cf->name);
1091 break;
1092 case CONFIG_ORIGIN_FILE:
1093 error_msg = xstrfmt(_("bad config line %d in file %s"),
1094 cf->linenr, cf->name);
1095 break;
1096 case CONFIG_ORIGIN_STDIN:
1097 error_msg = xstrfmt(_("bad config line %d in standard input"),
1098 cf->linenr);
1099 break;
1100 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1101 error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
1102 cf->linenr, cf->name);
1103 break;
1104 case CONFIG_ORIGIN_CMDLINE:
1105 error_msg = xstrfmt(_("bad config line %d in command line %s"),
1106 cf->linenr, cf->name);
1107 break;
1108 default:
1109 error_msg = xstrfmt(_("bad config line %d in %s"),
1110 cf->linenr, cf->name);
1111 }
1112
1113 switch (opts && opts->error_action ?
1114 opts->error_action :
1115 cf->default_error_action) {
1116 case CONFIG_ERROR_DIE:
1117 die("%s", error_msg);
1118 break;
1119 case CONFIG_ERROR_ERROR:
1120 error_return = error("%s", error_msg);
1121 break;
1122 case CONFIG_ERROR_SILENT:
1123 error_return = -1;
1124 break;
1125 case CONFIG_ERROR_UNSET:
1126 BUG("config error action unset");
1127 }
1128
1129 free(error_msg);
1130 return error_return;
1131 }
1132
1133 static uintmax_t get_unit_factor(const char *end)
1134 {
1135 if (!*end)
1136 return 1;
1137 else if (!strcasecmp(end, "k"))
1138 return 1024;
1139 else if (!strcasecmp(end, "m"))
1140 return 1024 * 1024;
1141 else if (!strcasecmp(end, "g"))
1142 return 1024 * 1024 * 1024;
1143 return 0;
1144 }
1145
1146 static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
1147 {
1148 if (value && *value) {
1149 char *end;
1150 intmax_t val;
1151 uintmax_t uval;
1152 uintmax_t factor;
1153
1154 errno = 0;
1155 val = strtoimax(value, &end, 0);
1156 if (errno == ERANGE)
1157 return 0;
1158 factor = get_unit_factor(end);
1159 if (!factor) {
1160 errno = EINVAL;
1161 return 0;
1162 }
1163 uval = val < 0 ? -val : val;
1164 if (unsigned_mult_overflows(factor, uval) ||
1165 factor * uval > max) {
1166 errno = ERANGE;
1167 return 0;
1168 }
1169 val *= factor;
1170 *ret = val;
1171 return 1;
1172 }
1173 errno = EINVAL;
1174 return 0;
1175 }
1176
1177 static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
1178 {
1179 if (value && *value) {
1180 char *end;
1181 uintmax_t val;
1182 uintmax_t factor;
1183
1184 errno = 0;
1185 val = strtoumax(value, &end, 0);
1186 if (errno == ERANGE)
1187 return 0;
1188 factor = get_unit_factor(end);
1189 if (!factor) {
1190 errno = EINVAL;
1191 return 0;
1192 }
1193 if (unsigned_mult_overflows(factor, val) ||
1194 factor * val > max) {
1195 errno = ERANGE;
1196 return 0;
1197 }
1198 val *= factor;
1199 *ret = val;
1200 return 1;
1201 }
1202 errno = EINVAL;
1203 return 0;
1204 }
1205
1206 static int git_parse_int(const char *value, int *ret)
1207 {
1208 intmax_t tmp;
1209 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
1210 return 0;
1211 *ret = tmp;
1212 return 1;
1213 }
1214
1215 static int git_parse_int64(const char *value, int64_t *ret)
1216 {
1217 intmax_t tmp;
1218 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
1219 return 0;
1220 *ret = tmp;
1221 return 1;
1222 }
1223
1224 int git_parse_ulong(const char *value, unsigned long *ret)
1225 {
1226 uintmax_t tmp;
1227 if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
1228 return 0;
1229 *ret = tmp;
1230 return 1;
1231 }
1232
1233 int git_parse_ssize_t(const char *value, ssize_t *ret)
1234 {
1235 intmax_t tmp;
1236 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(ssize_t)))
1237 return 0;
1238 *ret = tmp;
1239 return 1;
1240 }
1241
1242 NORETURN
1243 static void die_bad_number(const char *name, const char *value)
1244 {
1245 const char *error_type = (errno == ERANGE) ?
1246 N_("out of range") : N_("invalid unit");
1247 const char *bad_numeric = N_("bad numeric config value '%s' for '%s': %s");
1248
1249 if (!value)
1250 value = "";
1251
1252 if (!(cf && cf->name))
1253 die(_(bad_numeric), value, name, _(error_type));
1254
1255 switch (cf->origin_type) {
1256 case CONFIG_ORIGIN_BLOB:
1257 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
1258 value, name, cf->name, _(error_type));
1259 case CONFIG_ORIGIN_FILE:
1260 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
1261 value, name, cf->name, _(error_type));
1262 case CONFIG_ORIGIN_STDIN:
1263 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
1264 value, name, _(error_type));
1265 case CONFIG_ORIGIN_SUBMODULE_BLOB:
1266 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
1267 value, name, cf->name, _(error_type));
1268 case CONFIG_ORIGIN_CMDLINE:
1269 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
1270 value, name, cf->name, _(error_type));
1271 default:
1272 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
1273 value, name, cf->name, _(error_type));
1274 }
1275 }
1276
1277 int git_config_int(const char *name, const char *value)
1278 {
1279 int ret;
1280 if (!git_parse_int(value, &ret))
1281 die_bad_number(name, value);
1282 return ret;
1283 }
1284
1285 int64_t git_config_int64(const char *name, const char *value)
1286 {
1287 int64_t ret;
1288 if (!git_parse_int64(value, &ret))
1289 die_bad_number(name, value);
1290 return ret;
1291 }
1292
1293 unsigned long git_config_ulong(const char *name, const char *value)
1294 {
1295 unsigned long ret;
1296 if (!git_parse_ulong(value, &ret))
1297 die_bad_number(name, value);
1298 return ret;
1299 }
1300
1301 ssize_t git_config_ssize_t(const char *name, const char *value)
1302 {
1303 ssize_t ret;
1304 if (!git_parse_ssize_t(value, &ret))
1305 die_bad_number(name, value);
1306 return ret;
1307 }
1308
1309 static int git_parse_maybe_bool_text(const char *value)
1310 {
1311 if (!value)
1312 return 1;
1313 if (!*value)
1314 return 0;
1315 if (!strcasecmp(value, "true")
1316 || !strcasecmp(value, "yes")
1317 || !strcasecmp(value, "on"))
1318 return 1;
1319 if (!strcasecmp(value, "false")
1320 || !strcasecmp(value, "no")
1321 || !strcasecmp(value, "off"))
1322 return 0;
1323 return -1;
1324 }
1325
1326 static const struct fsync_component_name {
1327 const char *name;
1328 enum fsync_component component_bits;
1329 } fsync_component_names[] = {
1330 { "loose-object", FSYNC_COMPONENT_LOOSE_OBJECT },
1331 { "pack", FSYNC_COMPONENT_PACK },
1332 { "pack-metadata", FSYNC_COMPONENT_PACK_METADATA },
1333 { "commit-graph", FSYNC_COMPONENT_COMMIT_GRAPH },
1334 { "index", FSYNC_COMPONENT_INDEX },
1335 { "objects", FSYNC_COMPONENTS_OBJECTS },
1336 { "reference", FSYNC_COMPONENT_REFERENCE },
1337 { "derived-metadata", FSYNC_COMPONENTS_DERIVED_METADATA },
1338 { "committed", FSYNC_COMPONENTS_COMMITTED },
1339 { "added", FSYNC_COMPONENTS_ADDED },
1340 { "all", FSYNC_COMPONENTS_ALL },
1341 };
1342
1343 static enum fsync_component parse_fsync_components(const char *var, const char *string)
1344 {
1345 enum fsync_component current = FSYNC_COMPONENTS_DEFAULT;
1346 enum fsync_component positive = 0, negative = 0;
1347
1348 while (string) {
1349 int i;
1350 size_t len;
1351 const char *ep;
1352 int negated = 0;
1353 int found = 0;
1354
1355 string = string + strspn(string, ", \t\n\r");
1356 ep = strchrnul(string, ',');
1357 len = ep - string;
1358 if (!strcmp(string, "none")) {
1359 current = FSYNC_COMPONENT_NONE;
1360 goto next_name;
1361 }
1362
1363 if (*string == '-') {
1364 negated = 1;
1365 string++;
1366 len--;
1367 if (!len)
1368 warning(_("invalid value for variable %s"), var);
1369 }
1370
1371 if (!len)
1372 break;
1373
1374 for (i = 0; i < ARRAY_SIZE(fsync_component_names); ++i) {
1375 const struct fsync_component_name *n = &fsync_component_names[i];
1376
1377 if (strncmp(n->name, string, len))
1378 continue;
1379
1380 found = 1;
1381 if (negated)
1382 negative |= n->component_bits;
1383 else
1384 positive |= n->component_bits;
1385 }
1386
1387 if (!found) {
1388 char *component = xstrndup(string, len);
1389 warning(_("ignoring unknown core.fsync component '%s'"), component);
1390 free(component);
1391 }
1392
1393 next_name:
1394 string = ep;
1395 }
1396
1397 return (current & ~negative) | positive;
1398 }
1399
1400 int git_parse_maybe_bool(const char *value)
1401 {
1402 int v = git_parse_maybe_bool_text(value);
1403 if (0 <= v)
1404 return v;
1405 if (git_parse_int(value, &v))
1406 return !!v;
1407 return -1;
1408 }
1409
1410 int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
1411 {
1412 int v = git_parse_maybe_bool_text(value);
1413 if (0 <= v) {
1414 *is_bool = 1;
1415 return v;
1416 }
1417 *is_bool = 0;
1418 return git_config_int(name, value);
1419 }
1420
1421 int git_config_bool(const char *name, const char *value)
1422 {
1423 int v = git_parse_maybe_bool(value);
1424 if (v < 0)
1425 die(_("bad boolean config value '%s' for '%s'"), value, name);
1426 return v;
1427 }
1428
1429 int git_config_string(const char **dest, const char *var, const char *value)
1430 {
1431 if (!value)
1432 return config_error_nonbool(var);
1433 *dest = xstrdup(value);
1434 return 0;
1435 }
1436
1437 int git_config_pathname(const char **dest, const char *var, const char *value)
1438 {
1439 if (!value)
1440 return config_error_nonbool(var);
1441 *dest = interpolate_path(value, 0);
1442 if (!*dest)
1443 die(_("failed to expand user dir in: '%s'"), value);
1444 return 0;
1445 }
1446
1447 int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1448 {
1449 if (!value)
1450 return config_error_nonbool(var);
1451 if (parse_expiry_date(value, timestamp))
1452 return error(_("'%s' for '%s' is not a valid timestamp"),
1453 value, var);
1454 return 0;
1455 }
1456
1457 int git_config_color(char *dest, const char *var, const char *value)
1458 {
1459 if (!value)
1460 return config_error_nonbool(var);
1461 if (color_parse(value, dest) < 0)
1462 return -1;
1463 return 0;
1464 }
1465
1466 static int git_default_core_config(const char *var, const char *value, void *cb)
1467 {
1468 /* This needs a better name */
1469 if (!strcmp(var, "core.filemode")) {
1470 trust_executable_bit = git_config_bool(var, value);
1471 return 0;
1472 }
1473 if (!strcmp(var, "core.trustctime")) {
1474 trust_ctime = git_config_bool(var, value);
1475 return 0;
1476 }
1477 if (!strcmp(var, "core.checkstat")) {
1478 if (!strcasecmp(value, "default"))
1479 check_stat = 1;
1480 else if (!strcasecmp(value, "minimal"))
1481 check_stat = 0;
1482 }
1483
1484 if (!strcmp(var, "core.quotepath")) {
1485 quote_path_fully = git_config_bool(var, value);
1486 return 0;
1487 }
1488
1489 if (!strcmp(var, "core.symlinks")) {
1490 has_symlinks = git_config_bool(var, value);
1491 return 0;
1492 }
1493
1494 if (!strcmp(var, "core.ignorecase")) {
1495 ignore_case = git_config_bool(var, value);
1496 return 0;
1497 }
1498
1499 if (!strcmp(var, "core.attributesfile"))
1500 return git_config_pathname(&git_attributes_file, var, value);
1501
1502 if (!strcmp(var, "core.hookspath"))
1503 return git_config_pathname(&git_hooks_path, var, value);
1504
1505 if (!strcmp(var, "core.bare")) {
1506 is_bare_repository_cfg = git_config_bool(var, value);
1507 return 0;
1508 }
1509
1510 if (!strcmp(var, "core.ignorestat")) {
1511 assume_unchanged = git_config_bool(var, value);
1512 return 0;
1513 }
1514
1515 if (!strcmp(var, "core.prefersymlinkrefs")) {
1516 prefer_symlink_refs = git_config_bool(var, value);
1517 return 0;
1518 }
1519
1520 if (!strcmp(var, "core.logallrefupdates")) {
1521 if (value && !strcasecmp(value, "always"))
1522 log_all_ref_updates = LOG_REFS_ALWAYS;
1523 else if (git_config_bool(var, value))
1524 log_all_ref_updates = LOG_REFS_NORMAL;
1525 else
1526 log_all_ref_updates = LOG_REFS_NONE;
1527 return 0;
1528 }
1529
1530 if (!strcmp(var, "core.warnambiguousrefs")) {
1531 warn_ambiguous_refs = git_config_bool(var, value);
1532 return 0;
1533 }
1534
1535 if (!strcmp(var, "core.abbrev")) {
1536 if (!value)
1537 return config_error_nonbool(var);
1538 if (!strcasecmp(value, "auto"))
1539 default_abbrev = -1;
1540 else if (!git_parse_maybe_bool_text(value))
1541 default_abbrev = the_hash_algo->hexsz;
1542 else {
1543 int abbrev = git_config_int(var, value);
1544 if (abbrev < minimum_abbrev || abbrev > the_hash_algo->hexsz)
1545 return error(_("abbrev length out of range: %d"), abbrev);
1546 default_abbrev = abbrev;
1547 }
1548 return 0;
1549 }
1550
1551 if (!strcmp(var, "core.disambiguate"))
1552 return set_disambiguate_hint_config(var, value);
1553
1554 if (!strcmp(var, "core.loosecompression")) {
1555 int level = git_config_int(var, value);
1556 if (level == -1)
1557 level = Z_DEFAULT_COMPRESSION;
1558 else if (level < 0 || level > Z_BEST_COMPRESSION)
1559 die(_("bad zlib compression level %d"), level);
1560 zlib_compression_level = level;
1561 zlib_compression_seen = 1;
1562 return 0;
1563 }
1564
1565 if (!strcmp(var, "core.compression")) {
1566 int level = git_config_int(var, value);
1567 if (level == -1)
1568 level = Z_DEFAULT_COMPRESSION;
1569 else if (level < 0 || level > Z_BEST_COMPRESSION)
1570 die(_("bad zlib compression level %d"), level);
1571 if (!zlib_compression_seen)
1572 zlib_compression_level = level;
1573 if (!pack_compression_seen)
1574 pack_compression_level = level;
1575 return 0;
1576 }
1577
1578 if (!strcmp(var, "core.packedgitwindowsize")) {
1579 int pgsz_x2 = getpagesize() * 2;
1580 packed_git_window_size = git_config_ulong(var, value);
1581
1582 /* This value must be multiple of (pagesize * 2) */
1583 packed_git_window_size /= pgsz_x2;
1584 if (packed_git_window_size < 1)
1585 packed_git_window_size = 1;
1586 packed_git_window_size *= pgsz_x2;
1587 return 0;
1588 }
1589
1590 if (!strcmp(var, "core.bigfilethreshold")) {
1591 big_file_threshold = git_config_ulong(var, value);
1592 return 0;
1593 }
1594
1595 if (!strcmp(var, "core.packedgitlimit")) {
1596 packed_git_limit = git_config_ulong(var, value);
1597 return 0;
1598 }
1599
1600 if (!strcmp(var, "core.deltabasecachelimit")) {
1601 delta_base_cache_limit = git_config_ulong(var, value);
1602 return 0;
1603 }
1604
1605 if (!strcmp(var, "core.autocrlf")) {
1606 if (value && !strcasecmp(value, "input")) {
1607 auto_crlf = AUTO_CRLF_INPUT;
1608 return 0;
1609 }
1610 auto_crlf = git_config_bool(var, value);
1611 return 0;
1612 }
1613
1614 if (!strcmp(var, "core.safecrlf")) {
1615 int eol_rndtrp_die;
1616 if (value && !strcasecmp(value, "warn")) {
1617 global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
1618 return 0;
1619 }
1620 eol_rndtrp_die = git_config_bool(var, value);
1621 global_conv_flags_eol = eol_rndtrp_die ?
1622 CONV_EOL_RNDTRP_DIE : 0;
1623 return 0;
1624 }
1625
1626 if (!strcmp(var, "core.eol")) {
1627 if (value && !strcasecmp(value, "lf"))
1628 core_eol = EOL_LF;
1629 else if (value && !strcasecmp(value, "crlf"))
1630 core_eol = EOL_CRLF;
1631 else if (value && !strcasecmp(value, "native"))
1632 core_eol = EOL_NATIVE;
1633 else
1634 core_eol = EOL_UNSET;
1635 return 0;
1636 }
1637
1638 if (!strcmp(var, "core.checkroundtripencoding")) {
1639 check_roundtrip_encoding = xstrdup(value);
1640 return 0;
1641 }
1642
1643 if (!strcmp(var, "core.notesref")) {
1644 notes_ref_name = xstrdup(value);
1645 return 0;
1646 }
1647
1648 if (!strcmp(var, "core.editor"))
1649 return git_config_string(&editor_program, var, value);
1650
1651 if (!strcmp(var, "core.commentchar")) {
1652 if (!value)
1653 return config_error_nonbool(var);
1654 else if (!strcasecmp(value, "auto"))
1655 auto_comment_line_char = 1;
1656 else if (value[0] && !value[1]) {
1657 comment_line_char = value[0];
1658 auto_comment_line_char = 0;
1659 } else
1660 return error(_("core.commentChar should only be one character"));
1661 return 0;
1662 }
1663
1664 if (!strcmp(var, "core.askpass"))
1665 return git_config_string(&askpass_program, var, value);
1666
1667 if (!strcmp(var, "core.excludesfile"))
1668 return git_config_pathname(&excludes_file, var, value);
1669
1670 if (!strcmp(var, "core.whitespace")) {
1671 if (!value)
1672 return config_error_nonbool(var);
1673 whitespace_rule_cfg = parse_whitespace_rule(value);
1674 return 0;
1675 }
1676
1677 if (!strcmp(var, "core.fsync")) {
1678 if (!value)
1679 return config_error_nonbool(var);
1680 fsync_components = parse_fsync_components(var, value);
1681 return 0;
1682 }
1683
1684 if (!strcmp(var, "core.fsyncmethod")) {
1685 if (!value)
1686 return config_error_nonbool(var);
1687 if (!strcmp(value, "fsync"))
1688 fsync_method = FSYNC_METHOD_FSYNC;
1689 else if (!strcmp(value, "writeout-only"))
1690 fsync_method = FSYNC_METHOD_WRITEOUT_ONLY;
1691 else
1692 warning(_("ignoring unknown core.fsyncMethod value '%s'"), value);
1693
1694 }
1695
1696 if (!strcmp(var, "core.fsyncobjectfiles")) {
1697 if (fsync_object_files < 0)
1698 warning(_("core.fsyncobjectfiles is deprecated; use core.fsync instead"));
1699 fsync_object_files = git_config_bool(var, value);
1700 return 0;
1701 }
1702
1703 if (!strcmp(var, "core.preloadindex")) {
1704 core_preload_index = git_config_bool(var, value);
1705 return 0;
1706 }
1707
1708 if (!strcmp(var, "core.createobject")) {
1709 if (!strcmp(value, "rename"))
1710 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
1711 else if (!strcmp(value, "link"))
1712 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
1713 else
1714 die(_("invalid mode for object creation: %s"), value);
1715 return 0;
1716 }
1717
1718 if (!strcmp(var, "core.sparsecheckout")) {
1719 core_apply_sparse_checkout = git_config_bool(var, value);
1720 return 0;
1721 }
1722
1723 if (!strcmp(var, "core.sparsecheckoutcone")) {
1724 core_sparse_checkout_cone = git_config_bool(var, value);
1725 return 0;
1726 }
1727
1728 if (!strcmp(var, "core.precomposeunicode")) {
1729 precomposed_unicode = git_config_bool(var, value);
1730 return 0;
1731 }
1732
1733 if (!strcmp(var, "core.protecthfs")) {
1734 protect_hfs = git_config_bool(var, value);
1735 return 0;
1736 }
1737
1738 if (!strcmp(var, "core.protectntfs")) {
1739 protect_ntfs = git_config_bool(var, value);
1740 return 0;
1741 }
1742
1743 if (!strcmp(var, "core.usereplacerefs")) {
1744 read_replace_refs = git_config_bool(var, value);
1745 return 0;
1746 }
1747
1748 /* Add other config variables here and to Documentation/config.txt. */
1749 return platform_core_config(var, value, cb);
1750 }
1751
1752 static int git_default_sparse_config(const char *var, const char *value)
1753 {
1754 if (!strcmp(var, "sparse.expectfilesoutsideofpatterns")) {
1755 sparse_expect_files_outside_of_patterns = git_config_bool(var, value);
1756 return 0;
1757 }
1758
1759 /* Add other config variables here and to Documentation/config/sparse.txt. */
1760 return 0;
1761 }
1762
1763 static int git_default_i18n_config(const char *var, const char *value)
1764 {
1765 if (!strcmp(var, "i18n.commitencoding"))
1766 return git_config_string(&git_commit_encoding, var, value);
1767
1768 if (!strcmp(var, "i18n.logoutputencoding"))
1769 return git_config_string(&git_log_output_encoding, var, value);
1770
1771 /* Add other config variables here and to Documentation/config.txt. */
1772 return 0;
1773 }
1774
1775 static int git_default_branch_config(const char *var, const char *value)
1776 {
1777 if (!strcmp(var, "branch.autosetupmerge")) {
1778 if (value && !strcmp(value, "always")) {
1779 git_branch_track = BRANCH_TRACK_ALWAYS;
1780 return 0;
1781 } else if (value && !strcmp(value, "inherit")) {
1782 git_branch_track = BRANCH_TRACK_INHERIT;
1783 return 0;
1784 }
1785 git_branch_track = git_config_bool(var, value);
1786 return 0;
1787 }
1788 if (!strcmp(var, "branch.autosetuprebase")) {
1789 if (!value)
1790 return config_error_nonbool(var);
1791 else if (!strcmp(value, "never"))
1792 autorebase = AUTOREBASE_NEVER;
1793 else if (!strcmp(value, "local"))
1794 autorebase = AUTOREBASE_LOCAL;
1795 else if (!strcmp(value, "remote"))
1796 autorebase = AUTOREBASE_REMOTE;
1797 else if (!strcmp(value, "always"))
1798 autorebase = AUTOREBASE_ALWAYS;
1799 else
1800 return error(_("malformed value for %s"), var);
1801 return 0;
1802 }
1803
1804 /* Add other config variables here and to Documentation/config.txt. */
1805 return 0;
1806 }
1807
1808 static int git_default_push_config(const char *var, const char *value)
1809 {
1810 if (!strcmp(var, "push.default")) {
1811 if (!value)
1812 return config_error_nonbool(var);
1813 else if (!strcmp(value, "nothing"))
1814 push_default = PUSH_DEFAULT_NOTHING;
1815 else if (!strcmp(value, "matching"))
1816 push_default = PUSH_DEFAULT_MATCHING;
1817 else if (!strcmp(value, "simple"))
1818 push_default = PUSH_DEFAULT_SIMPLE;
1819 else if (!strcmp(value, "upstream"))
1820 push_default = PUSH_DEFAULT_UPSTREAM;
1821 else if (!strcmp(value, "tracking")) /* deprecated */
1822 push_default = PUSH_DEFAULT_UPSTREAM;
1823 else if (!strcmp(value, "current"))
1824 push_default = PUSH_DEFAULT_CURRENT;
1825 else {
1826 error(_("malformed value for %s: %s"), var, value);
1827 return error(_("must be one of nothing, matching, simple, "
1828 "upstream or current"));
1829 }
1830 return 0;
1831 }
1832
1833 /* Add other config variables here and to Documentation/config.txt. */
1834 return 0;
1835 }
1836
1837 static int git_default_mailmap_config(const char *var, const char *value)
1838 {
1839 if (!strcmp(var, "mailmap.file"))
1840 return git_config_pathname(&git_mailmap_file, var, value);
1841 if (!strcmp(var, "mailmap.blob"))
1842 return git_config_string(&git_mailmap_blob, var, value);
1843
1844 /* Add other config variables here and to Documentation/config.txt. */
1845 return 0;
1846 }
1847
1848 int git_default_config(const char *var, const char *value, void *cb)
1849 {
1850 if (starts_with(var, "core."))
1851 return git_default_core_config(var, value, cb);
1852
1853 if (starts_with(var, "user.") ||
1854 starts_with(var, "author.") ||
1855 starts_with(var, "committer."))
1856 return git_ident_config(var, value, cb);
1857
1858 if (starts_with(var, "i18n."))
1859 return git_default_i18n_config(var, value);
1860
1861 if (starts_with(var, "branch."))
1862 return git_default_branch_config(var, value);
1863
1864 if (starts_with(var, "push."))
1865 return git_default_push_config(var, value);
1866
1867 if (starts_with(var, "mailmap."))
1868 return git_default_mailmap_config(var, value);
1869
1870 if (starts_with(var, "advice.") || starts_with(var, "color.advice"))
1871 return git_default_advice_config(var, value);
1872
1873 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1874 pager_use_color = git_config_bool(var,value);
1875 return 0;
1876 }
1877
1878 if (!strcmp(var, "pack.packsizelimit")) {
1879 pack_size_limit_cfg = git_config_ulong(var, value);
1880 return 0;
1881 }
1882
1883 if (!strcmp(var, "pack.compression")) {
1884 int level = git_config_int(var, value);
1885 if (level == -1)
1886 level = Z_DEFAULT_COMPRESSION;
1887 else if (level < 0 || level > Z_BEST_COMPRESSION)
1888 die(_("bad pack compression level %d"), level);
1889 pack_compression_level = level;
1890 pack_compression_seen = 1;
1891 return 0;
1892 }
1893
1894 if (starts_with(var, "sparse."))
1895 return git_default_sparse_config(var, value);
1896
1897 /* Add other config variables here and to Documentation/config.txt. */
1898 return 0;
1899 }
1900
1901 /*
1902 * All source specific fields in the union, die_on_error, name and the callbacks
1903 * fgetc, ungetc, ftell of top need to be initialized before calling
1904 * this function.
1905 */
1906 static int do_config_from(struct config_source *top, config_fn_t fn, void *data,
1907 const struct config_options *opts)
1908 {
1909 int ret;
1910
1911 /* push config-file parsing state stack */
1912 top->prev = cf;
1913 top->linenr = 1;
1914 top->eof = 0;
1915 top->total_len = 0;
1916 strbuf_init(&top->value, 1024);
1917 strbuf_init(&top->var, 1024);
1918 cf = top;
1919
1920 ret = git_parse_source(fn, data, opts);
1921
1922 /* pop config-file parsing state stack */
1923 strbuf_release(&top->value);
1924 strbuf_release(&top->var);
1925 cf = top->prev;
1926
1927 return ret;
1928 }
1929
1930 static int do_config_from_file(config_fn_t fn,
1931 const enum config_origin_type origin_type,
1932 const char *name, const char *path, FILE *f,
1933 void *data, const struct config_options *opts)
1934 {
1935 struct config_source top;
1936 int ret;
1937
1938 top.u.file = f;
1939 top.origin_type = origin_type;
1940 top.name = name;
1941 top.path = path;
1942 top.default_error_action = CONFIG_ERROR_DIE;
1943 top.do_fgetc = config_file_fgetc;
1944 top.do_ungetc = config_file_ungetc;
1945 top.do_ftell = config_file_ftell;
1946
1947 flockfile(f);
1948 ret = do_config_from(&top, fn, data, opts);
1949 funlockfile(f);
1950 return ret;
1951 }
1952
1953 static int git_config_from_stdin(config_fn_t fn, void *data)
1954 {
1955 return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", NULL, stdin,
1956 data, NULL);
1957 }
1958
1959 int git_config_from_file_with_options(config_fn_t fn, const char *filename,
1960 void *data,
1961 const struct config_options *opts)
1962 {
1963 int ret = -1;
1964 FILE *f;
1965
1966 f = fopen_or_warn(filename, "r");
1967 if (f) {
1968 ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename,
1969 filename, f, data, opts);
1970 fclose(f);
1971 }
1972 return ret;
1973 }
1974
1975 int git_config_from_file(config_fn_t fn, const char *filename, void *data)
1976 {
1977 return git_config_from_file_with_options(fn, filename, data, NULL);
1978 }
1979
1980 int git_config_from_mem(config_fn_t fn,
1981 const enum config_origin_type origin_type,
1982 const char *name, const char *buf, size_t len,
1983 void *data, const struct config_options *opts)
1984 {
1985 struct config_source top;
1986
1987 top.u.buf.buf = buf;
1988 top.u.buf.len = len;
1989 top.u.buf.pos = 0;
1990 top.origin_type = origin_type;
1991 top.name = name;
1992 top.path = NULL;
1993 top.default_error_action = CONFIG_ERROR_ERROR;
1994 top.do_fgetc = config_buf_fgetc;
1995 top.do_ungetc = config_buf_ungetc;
1996 top.do_ftell = config_buf_ftell;
1997
1998 return do_config_from(&top, fn, data, opts);
1999 }
2000
2001 int git_config_from_blob_oid(config_fn_t fn,
2002 const char *name,
2003 struct repository *repo,
2004 const struct object_id *oid,
2005 void *data)
2006 {
2007 enum object_type type;
2008 char *buf;
2009 unsigned long size;
2010 int ret;
2011
2012 buf = repo_read_object_file(repo, oid, &type, &size);
2013 if (!buf)
2014 return error(_("unable to load config blob object '%s'"), name);
2015 if (type != OBJ_BLOB) {
2016 free(buf);
2017 return error(_("reference '%s' does not point to a blob"), name);
2018 }
2019
2020 ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size,
2021 data, NULL);
2022 free(buf);
2023
2024 return ret;
2025 }
2026
2027 static int git_config_from_blob_ref(config_fn_t fn,
2028 struct repository *repo,
2029 const char *name,
2030 void *data)
2031 {
2032 struct object_id oid;
2033
2034 if (repo_get_oid(repo, name, &oid) < 0)
2035 return error(_("unable to resolve config blob '%s'"), name);
2036 return git_config_from_blob_oid(fn, name, repo, &oid, data);
2037 }
2038
2039 char *git_system_config(void)
2040 {
2041 char *system_config = xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
2042 if (!system_config)
2043 system_config = system_path(ETC_GITCONFIG);
2044 normalize_path_copy(system_config, system_config);
2045 return system_config;
2046 }
2047
2048 void git_global_config(char **user_out, char **xdg_out)
2049 {
2050 char *user_config = xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
2051 char *xdg_config = NULL;
2052
2053 if (!user_config) {
2054 user_config = interpolate_path("~/.gitconfig", 0);
2055 xdg_config = xdg_config_home("config");
2056 }
2057
2058 *user_out = user_config;
2059 *xdg_out = xdg_config;
2060 }
2061
2062 /*
2063 * Parse environment variable 'k' as a boolean (in various
2064 * possible spellings); if missing, use the default value 'def'.
2065 */
2066 int git_env_bool(const char *k, int def)
2067 {
2068 const char *v = getenv(k);
2069 return v ? git_config_bool(k, v) : def;
2070 }
2071
2072 /*
2073 * Parse environment variable 'k' as ulong with possibly a unit
2074 * suffix; if missing, use the default value 'val'.
2075 */
2076 unsigned long git_env_ulong(const char *k, unsigned long val)
2077 {
2078 const char *v = getenv(k);
2079 if (v && !git_parse_ulong(v, &val))
2080 die(_("failed to parse %s"), k);
2081 return val;
2082 }
2083
2084 int git_config_system(void)
2085 {
2086 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
2087 }
2088
2089 static int do_git_config_sequence(const struct config_options *opts,
2090 config_fn_t fn, void *data)
2091 {
2092 int ret = 0;
2093 char *system_config = git_system_config();
2094 char *xdg_config = NULL;
2095 char *user_config = NULL;
2096 char *repo_config;
2097 enum config_scope prev_parsing_scope = current_parsing_scope;
2098
2099 if (opts->commondir)
2100 repo_config = mkpathdup("%s/config", opts->commondir);
2101 else if (opts->git_dir)
2102 BUG("git_dir without commondir");
2103 else
2104 repo_config = NULL;
2105
2106 current_parsing_scope = CONFIG_SCOPE_SYSTEM;
2107 if (git_config_system() && system_config &&
2108 !access_or_die(system_config, R_OK,
2109 opts->system_gently ? ACCESS_EACCES_OK : 0))
2110 ret += git_config_from_file(fn, system_config, data);
2111
2112 current_parsing_scope = CONFIG_SCOPE_GLOBAL;
2113 git_global_config(&user_config, &xdg_config);
2114
2115 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
2116 ret += git_config_from_file(fn, xdg_config, data);
2117
2118 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
2119 ret += git_config_from_file(fn, user_config, data);
2120
2121 current_parsing_scope = CONFIG_SCOPE_LOCAL;
2122 if (!opts->ignore_repo && repo_config &&
2123 !access_or_die(repo_config, R_OK, 0))
2124 ret += git_config_from_file(fn, repo_config, data);
2125
2126 current_parsing_scope = CONFIG_SCOPE_WORKTREE;
2127 if (!opts->ignore_worktree && repository_format_worktree_config) {
2128 char *path = git_pathdup("config.worktree");
2129 if (!access_or_die(path, R_OK, 0))
2130 ret += git_config_from_file(fn, path, data);
2131 free(path);
2132 }
2133
2134 current_parsing_scope = CONFIG_SCOPE_COMMAND;
2135 if (!opts->ignore_cmdline && git_config_from_parameters(fn, data) < 0)
2136 die(_("unable to parse command-line config"));
2137
2138 current_parsing_scope = prev_parsing_scope;
2139 free(system_config);
2140 free(xdg_config);
2141 free(user_config);
2142 free(repo_config);
2143 return ret;
2144 }
2145
2146 int config_with_options(config_fn_t fn, void *data,
2147 struct git_config_source *config_source,
2148 const struct config_options *opts)
2149 {
2150 struct config_include_data inc = CONFIG_INCLUDE_INIT;
2151 int ret;
2152
2153 if (opts->respect_includes) {
2154 inc.fn = fn;
2155 inc.data = data;
2156 inc.opts = opts;
2157 inc.config_source = config_source;
2158 fn = git_config_include;
2159 data = &inc;
2160 }
2161
2162 if (config_source)
2163 current_parsing_scope = config_source->scope;
2164
2165 /*
2166 * If we have a specific filename, use it. Otherwise, follow the
2167 * regular lookup sequence.
2168 */
2169 if (config_source && config_source->use_stdin) {
2170 ret = git_config_from_stdin(fn, data);
2171 } else if (config_source && config_source->file) {
2172 ret = git_config_from_file(fn, config_source->file, data);
2173 } else if (config_source && config_source->blob) {
2174 struct repository *repo = config_source->repo ?
2175 config_source->repo : the_repository;
2176 ret = git_config_from_blob_ref(fn, repo, config_source->blob,
2177 data);
2178 } else {
2179 ret = do_git_config_sequence(opts, fn, data);
2180 }
2181
2182 if (inc.remote_urls) {
2183 string_list_clear(inc.remote_urls, 0);
2184 FREE_AND_NULL(inc.remote_urls);
2185 }
2186 return ret;
2187 }
2188
2189 static void configset_iter(struct config_set *cs, config_fn_t fn, void *data)
2190 {
2191 int i, value_index;
2192 struct string_list *values;
2193 struct config_set_element *entry;
2194 struct configset_list *list = &cs->list;
2195
2196 for (i = 0; i < list->nr; i++) {
2197 entry = list->items[i].e;
2198 value_index = list->items[i].value_index;
2199 values = &entry->value_list;
2200
2201 current_config_kvi = values->items[value_index].util;
2202
2203 if (fn(entry->key, values->items[value_index].string, data) < 0)
2204 git_die_config_linenr(entry->key,
2205 current_config_kvi->filename,
2206 current_config_kvi->linenr);
2207
2208 current_config_kvi = NULL;
2209 }
2210 }
2211
2212 void read_early_config(config_fn_t cb, void *data)
2213 {
2214 struct config_options opts = {0};
2215 struct strbuf commondir = STRBUF_INIT;
2216 struct strbuf gitdir = STRBUF_INIT;
2217
2218 opts.respect_includes = 1;
2219
2220 if (have_git_dir()) {
2221 opts.commondir = get_git_common_dir();
2222 opts.git_dir = get_git_dir();
2223 /*
2224 * When setup_git_directory() was not yet asked to discover the
2225 * GIT_DIR, we ask discover_git_directory() to figure out whether there
2226 * is any repository config we should use (but unlike
2227 * setup_git_directory_gently(), no global state is changed, most
2228 * notably, the current working directory is still the same after the
2229 * call).
2230 */
2231 } else if (!discover_git_directory(&commondir, &gitdir)) {
2232 opts.commondir = commondir.buf;
2233 opts.git_dir = gitdir.buf;
2234 }
2235
2236 config_with_options(cb, data, NULL, &opts);
2237
2238 strbuf_release(&commondir);
2239 strbuf_release(&gitdir);
2240 }
2241
2242 /*
2243 * Read config but only enumerate system and global settings.
2244 * Omit any repo-local, worktree-local, or command-line settings.
2245 */
2246 void read_very_early_config(config_fn_t cb, void *data)
2247 {
2248 struct config_options opts = { 0 };
2249
2250 opts.respect_includes = 1;
2251 opts.ignore_repo = 1;
2252 opts.ignore_worktree = 1;
2253 opts.ignore_cmdline = 1;
2254 opts.system_gently = 1;
2255
2256 config_with_options(cb, data, NULL, &opts);
2257 }
2258
2259 static struct config_set_element *configset_find_element(struct config_set *cs, const char *key)
2260 {
2261 struct config_set_element k;
2262 struct config_set_element *found_entry;
2263 char *normalized_key;
2264 /*
2265 * `key` may come from the user, so normalize it before using it
2266 * for querying entries from the hashmap.
2267 */
2268 if (git_config_parse_key(key, &normalized_key, NULL))
2269 return NULL;
2270
2271 hashmap_entry_init(&k.ent, strhash(normalized_key));
2272 k.key = normalized_key;
2273 found_entry = hashmap_get_entry(&cs->config_hash, &k, ent, NULL);
2274 free(normalized_key);
2275 return found_entry;
2276 }
2277
2278 static int configset_add_value(struct config_set *cs, const char *key, const char *value)
2279 {
2280 struct config_set_element *e;
2281 struct string_list_item *si;
2282 struct configset_list_item *l_item;
2283 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
2284
2285 e = configset_find_element(cs, key);
2286 /*
2287 * Since the keys are being fed by git_config*() callback mechanism, they
2288 * are already normalized. So simply add them without any further munging.
2289 */
2290 if (!e) {
2291 e = xmalloc(sizeof(*e));
2292 hashmap_entry_init(&e->ent, strhash(key));
2293 e->key = xstrdup(key);
2294 string_list_init_dup(&e->value_list);
2295 hashmap_add(&cs->config_hash, &e->ent);
2296 }
2297 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
2298
2299 ALLOC_GROW(cs->list.items, cs->list.nr + 1, cs->list.alloc);
2300 l_item = &cs->list.items[cs->list.nr++];
2301 l_item->e = e;
2302 l_item->value_index = e->value_list.nr - 1;
2303
2304 if (!cf)
2305 BUG("configset_add_value has no source");
2306 if (cf->name) {
2307 kv_info->filename = strintern(cf->name);
2308 kv_info->linenr = cf->linenr;
2309 kv_info->origin_type = cf->origin_type;
2310 } else {
2311 /* for values read from `git_config_from_parameters()` */
2312 kv_info->filename = NULL;
2313 kv_info->linenr = -1;
2314 kv_info->origin_type = CONFIG_ORIGIN_CMDLINE;
2315 }
2316 kv_info->scope = current_parsing_scope;
2317 si->util = kv_info;
2318
2319 return 0;
2320 }
2321
2322 static int config_set_element_cmp(const void *unused_cmp_data,
2323 const struct hashmap_entry *eptr,
2324 const struct hashmap_entry *entry_or_key,
2325 const void *unused_keydata)
2326 {
2327 const struct config_set_element *e1, *e2;
2328
2329 e1 = container_of(eptr, const struct config_set_element, ent);
2330 e2 = container_of(entry_or_key, const struct config_set_element, ent);
2331
2332 return strcmp(e1->key, e2->key);
2333 }
2334
2335 void git_configset_init(struct config_set *cs)
2336 {
2337 hashmap_init(&cs->config_hash, config_set_element_cmp, NULL, 0);
2338 cs->hash_initialized = 1;
2339 cs->list.nr = 0;
2340 cs->list.alloc = 0;
2341 cs->list.items = NULL;
2342 }
2343
2344 void git_configset_clear(struct config_set *cs)
2345 {
2346 struct config_set_element *entry;
2347 struct hashmap_iter iter;
2348 if (!cs->hash_initialized)
2349 return;
2350
2351 hashmap_for_each_entry(&cs->config_hash, &iter, entry,
2352 ent /* member name */) {
2353 free(entry->key);
2354 string_list_clear(&entry->value_list, 1);
2355 }
2356 hashmap_clear_and_free(&cs->config_hash, struct config_set_element, ent);
2357 cs->hash_initialized = 0;
2358 free(cs->list.items);
2359 cs->list.nr = 0;
2360 cs->list.alloc = 0;
2361 cs->list.items = NULL;
2362 }
2363
2364 static int config_set_callback(const char *key, const char *value, void *cb)
2365 {
2366 struct config_set *cs = cb;
2367 configset_add_value(cs, key, value);
2368 return 0;
2369 }
2370
2371 int git_configset_add_file(struct config_set *cs, const char *filename)
2372 {
2373 return git_config_from_file(config_set_callback, filename, cs);
2374 }
2375
2376 int git_configset_get_value(struct config_set *cs, const char *key, const char **value)
2377 {
2378 const struct string_list *values = NULL;
2379 /*
2380 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
2381 * queried key in the files of the configset, the value returned will be the last
2382 * value in the value list for that key.
2383 */
2384 values = git_configset_get_value_multi(cs, key);
2385
2386 if (!values)
2387 return 1;
2388 assert(values->nr > 0);
2389 *value = values->items[values->nr - 1].string;
2390 return 0;
2391 }
2392
2393 const struct string_list *git_configset_get_value_multi(struct config_set *cs, const char *key)
2394 {
2395 struct config_set_element *e = configset_find_element(cs, key);
2396 return e ? &e->value_list : NULL;
2397 }
2398
2399 int git_configset_get_string(struct config_set *cs, const char *key, char **dest)
2400 {
2401 const char *value;
2402 if (!git_configset_get_value(cs, key, &value))
2403 return git_config_string((const char **)dest, key, value);
2404 else
2405 return 1;
2406 }
2407
2408 static int git_configset_get_string_tmp(struct config_set *cs, const char *key,
2409 const char **dest)
2410 {
2411 const char *value;
2412 if (!git_configset_get_value(cs, key, &value)) {
2413 if (!value)
2414 return config_error_nonbool(key);
2415 *dest = value;
2416 return 0;
2417 } else {
2418 return 1;
2419 }
2420 }
2421
2422 int git_configset_get_int(struct config_set *cs, const char *key, int *dest)
2423 {
2424 const char *value;
2425 if (!git_configset_get_value(cs, key, &value)) {
2426 *dest = git_config_int(key, value);
2427 return 0;
2428 } else
2429 return 1;
2430 }
2431
2432 int git_configset_get_ulong(struct config_set *cs, const char *key, unsigned long *dest)
2433 {
2434 const char *value;
2435 if (!git_configset_get_value(cs, key, &value)) {
2436 *dest = git_config_ulong(key, value);
2437 return 0;
2438 } else
2439 return 1;
2440 }
2441
2442 int git_configset_get_bool(struct config_set *cs, const char *key, int *dest)
2443 {
2444 const char *value;
2445 if (!git_configset_get_value(cs, key, &value)) {
2446 *dest = git_config_bool(key, value);
2447 return 0;
2448 } else
2449 return 1;
2450 }
2451
2452 int git_configset_get_bool_or_int(struct config_set *cs, const char *key,
2453 int *is_bool, int *dest)
2454 {
2455 const char *value;
2456 if (!git_configset_get_value(cs, key, &value)) {
2457 *dest = git_config_bool_or_int(key, value, is_bool);
2458 return 0;
2459 } else
2460 return 1;
2461 }
2462
2463 int git_configset_get_maybe_bool(struct config_set *cs, const char *key, int *dest)
2464 {
2465 const char *value;
2466 if (!git_configset_get_value(cs, key, &value)) {
2467 *dest = git_parse_maybe_bool(value);
2468 if (*dest == -1)
2469 return -1;
2470 return 0;
2471 } else
2472 return 1;
2473 }
2474
2475 int git_configset_get_pathname(struct config_set *cs, const char *key, const char **dest)
2476 {
2477 const char *value;
2478 if (!git_configset_get_value(cs, key, &value))
2479 return git_config_pathname(dest, key, value);
2480 else
2481 return 1;
2482 }
2483
2484 /* Functions use to read configuration from a repository */
2485 static void repo_read_config(struct repository *repo)
2486 {
2487 struct config_options opts = { 0 };
2488
2489 opts.respect_includes = 1;
2490 opts.commondir = repo->commondir;
2491 opts.git_dir = repo->gitdir;
2492
2493 if (!repo->config)
2494 CALLOC_ARRAY(repo->config, 1);
2495 else
2496 git_configset_clear(repo->config);
2497
2498 git_configset_init(repo->config);
2499
2500 if (config_with_options(config_set_callback, repo->config, NULL, &opts) < 0)
2501 /*
2502 * config_with_options() normally returns only
2503 * zero, as most errors are fatal, and
2504 * non-fatal potential errors are guarded by "if"
2505 * statements that are entered only when no error is
2506 * possible.
2507 *
2508 * If we ever encounter a non-fatal error, it means
2509 * something went really wrong and we should stop
2510 * immediately.
2511 */
2512 die(_("unknown error occurred while reading the configuration files"));
2513 }
2514
2515 static void git_config_check_init(struct repository *repo)
2516 {
2517 if (repo->config && repo->config->hash_initialized)
2518 return;
2519 repo_read_config(repo);
2520 }
2521
2522 static void repo_config_clear(struct repository *repo)
2523 {
2524 if (!repo->config || !repo->config->hash_initialized)
2525 return;
2526 git_configset_clear(repo->config);
2527 }
2528
2529 void repo_config(struct repository *repo, config_fn_t fn, void *data)
2530 {
2531 git_config_check_init(repo);
2532 configset_iter(repo->config, fn, data);
2533 }
2534
2535 int repo_config_get_value(struct repository *repo,
2536 const char *key, const char **value)
2537 {
2538 git_config_check_init(repo);
2539 return git_configset_get_value(repo->config, key, value);
2540 }
2541
2542 const struct string_list *repo_config_get_value_multi(struct repository *repo,
2543 const char *key)
2544 {
2545 git_config_check_init(repo);
2546 return git_configset_get_value_multi(repo->config, key);
2547 }
2548
2549 int repo_config_get_string(struct repository *repo,
2550 const char *key, char **dest)
2551 {
2552 int ret;
2553 git_config_check_init(repo);
2554 ret = git_configset_get_string(repo->config, key, dest);
2555 if (ret < 0)
2556 git_die_config(key, NULL);
2557 return ret;
2558 }
2559
2560 int repo_config_get_string_tmp(struct repository *repo,
2561 const char *key, const char **dest)
2562 {
2563 int ret;
2564 git_config_check_init(repo);
2565 ret = git_configset_get_string_tmp(repo->config, key, dest);
2566 if (ret < 0)
2567 git_die_config(key, NULL);
2568 return ret;
2569 }
2570
2571 int repo_config_get_int(struct repository *repo,
2572 const char *key, int *dest)
2573 {
2574 git_config_check_init(repo);
2575 return git_configset_get_int(repo->config, key, dest);
2576 }
2577
2578 int repo_config_get_ulong(struct repository *repo,
2579 const char *key, unsigned long *dest)
2580 {
2581 git_config_check_init(repo);
2582 return git_configset_get_ulong(repo->config, key, dest);
2583 }
2584
2585 int repo_config_get_bool(struct repository *repo,
2586 const char *key, int *dest)
2587 {
2588 git_config_check_init(repo);
2589 return git_configset_get_bool(repo->config, key, dest);
2590 }
2591
2592 int repo_config_get_bool_or_int(struct repository *repo,
2593 const char *key, int *is_bool, int *dest)
2594 {
2595 git_config_check_init(repo);
2596 return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2597 }
2598
2599 int repo_config_get_maybe_bool(struct repository *repo,
2600 const char *key, int *dest)
2601 {
2602 git_config_check_init(repo);
2603 return git_configset_get_maybe_bool(repo->config, key, dest);
2604 }
2605
2606 int repo_config_get_pathname(struct repository *repo,
2607 const char *key, const char **dest)
2608 {
2609 int ret;
2610 git_config_check_init(repo);
2611 ret = git_configset_get_pathname(repo->config, key, dest);
2612 if (ret < 0)
2613 git_die_config(key, NULL);
2614 return ret;
2615 }
2616
2617 /* Functions used historically to read configuration from 'the_repository' */
2618 void git_config(config_fn_t fn, void *data)
2619 {
2620 repo_config(the_repository, fn, data);
2621 }
2622
2623 void git_config_clear(void)
2624 {
2625 repo_config_clear(the_repository);
2626 }
2627
2628 int git_config_get_value(const char *key, const char **value)
2629 {
2630 return repo_config_get_value(the_repository, key, value);
2631 }
2632
2633 const struct string_list *git_config_get_value_multi(const char *key)
2634 {
2635 return repo_config_get_value_multi(the_repository, key);
2636 }
2637
2638 int git_config_get_string(const char *key, char **dest)
2639 {
2640 return repo_config_get_string(the_repository, key, dest);
2641 }
2642
2643 int git_config_get_string_tmp(const char *key, const char **dest)
2644 {
2645 return repo_config_get_string_tmp(the_repository, key, dest);
2646 }
2647
2648 int git_config_get_int(const char *key, int *dest)
2649 {
2650 return repo_config_get_int(the_repository, key, dest);
2651 }
2652
2653 int git_config_get_ulong(const char *key, unsigned long *dest)
2654 {
2655 return repo_config_get_ulong(the_repository, key, dest);
2656 }
2657
2658 int git_config_get_bool(const char *key, int *dest)
2659 {
2660 return repo_config_get_bool(the_repository, key, dest);
2661 }
2662
2663 int git_config_get_bool_or_int(const char *key, int *is_bool, int *dest)
2664 {
2665 return repo_config_get_bool_or_int(the_repository, key, is_bool, dest);
2666 }
2667
2668 int git_config_get_maybe_bool(const char *key, int *dest)
2669 {
2670 return repo_config_get_maybe_bool(the_repository, key, dest);
2671 }
2672
2673 int git_config_get_pathname(const char *key, const char **dest)
2674 {
2675 return repo_config_get_pathname(the_repository, key, dest);
2676 }
2677
2678 int git_config_get_expiry(const char *key, const char **output)
2679 {
2680 int ret = git_config_get_string(key, (char **)output);
2681 if (ret)
2682 return ret;
2683 if (strcmp(*output, "now")) {
2684 timestamp_t now = approxidate("now");
2685 if (approxidate(*output) >= now)
2686 git_die_config(key, _("Invalid %s: '%s'"), key, *output);
2687 }
2688 return ret;
2689 }
2690
2691 int git_config_get_expiry_in_days(const char *key, timestamp_t *expiry, timestamp_t now)
2692 {
2693 const char *expiry_string;
2694 intmax_t days;
2695 timestamp_t when;
2696
2697 if (git_config_get_string_tmp(key, &expiry_string))
2698 return 1; /* no such thing */
2699
2700 if (git_parse_signed(expiry_string, &days, maximum_signed_value_of_type(int))) {
2701 const int scale = 86400;
2702 *expiry = now - days * scale;
2703 return 0;
2704 }
2705
2706 if (!parse_expiry_date(expiry_string, &when)) {
2707 *expiry = when;
2708 return 0;
2709 }
2710 return -1; /* thing exists but cannot be parsed */
2711 }
2712
2713 int git_config_get_split_index(void)
2714 {
2715 int val;
2716
2717 if (!git_config_get_maybe_bool("core.splitindex", &val))
2718 return val;
2719
2720 return -1; /* default value */
2721 }
2722
2723 int git_config_get_max_percent_split_change(void)
2724 {
2725 int val = -1;
2726
2727 if (!git_config_get_int("splitindex.maxpercentchange", &val)) {
2728 if (0 <= val && val <= 100)
2729 return val;
2730
2731 return error(_("splitIndex.maxPercentChange value '%d' "
2732 "should be between 0 and 100"), val);
2733 }
2734
2735 return -1; /* default value */
2736 }
2737
2738 int git_config_get_fsmonitor(void)
2739 {
2740 if (git_config_get_pathname("core.fsmonitor", &core_fsmonitor))
2741 core_fsmonitor = getenv("GIT_TEST_FSMONITOR");
2742
2743 if (core_fsmonitor && !*core_fsmonitor)
2744 core_fsmonitor = NULL;
2745
2746 if (core_fsmonitor)
2747 return 1;
2748
2749 return 0;
2750 }
2751
2752 int git_config_get_index_threads(int *dest)
2753 {
2754 int is_bool, val;
2755
2756 val = git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2757 if (val) {
2758 *dest = val;
2759 return 0;
2760 }
2761
2762 if (!git_config_get_bool_or_int("index.threads", &is_bool, &val)) {
2763 if (is_bool)
2764 *dest = val ? 0 : 1;
2765 else
2766 *dest = val;
2767 return 0;
2768 }
2769
2770 return 1;
2771 }
2772
2773 NORETURN
2774 void git_die_config_linenr(const char *key, const char *filename, int linenr)
2775 {
2776 if (!filename)
2777 die(_("unable to parse '%s' from command-line config"), key);
2778 else
2779 die(_("bad config variable '%s' in file '%s' at line %d"),
2780 key, filename, linenr);
2781 }
2782
2783 NORETURN __attribute__((format(printf, 2, 3)))
2784 void git_die_config(const char *key, const char *err, ...)
2785 {
2786 const struct string_list *values;
2787 struct key_value_info *kv_info;
2788 report_fn error_fn = get_error_routine();
2789
2790 if (err) {
2791 va_list params;
2792 va_start(params, err);
2793 error_fn(err, params);
2794 va_end(params);
2795 }
2796 values = git_config_get_value_multi(key);
2797 kv_info = values->items[values->nr - 1].util;
2798 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
2799 }
2800
2801 /*
2802 * Find all the stuff for git_config_set() below.
2803 */
2804
2805 struct config_store_data {
2806 size_t baselen;
2807 char *key;
2808 int do_not_match;
2809 const char *fixed_value;
2810 regex_t *value_pattern;
2811 int multi_replace;
2812 struct {
2813 size_t begin, end;
2814 enum config_event_t type;
2815 int is_keys_section;
2816 } *parsed;
2817 unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
2818 unsigned int key_seen:1, section_seen:1, is_keys_section:1;
2819 };
2820
2821 static void config_store_data_clear(struct config_store_data *store)
2822 {
2823 free(store->key);
2824 if (store->value_pattern != NULL &&
2825 store->value_pattern != CONFIG_REGEX_NONE) {
2826 regfree(store->value_pattern);
2827 free(store->value_pattern);
2828 }
2829 free(store->parsed);
2830 free(store->seen);
2831 memset(store, 0, sizeof(*store));
2832 }
2833
2834 static int matches(const char *key, const char *value,
2835 const struct config_store_data *store)
2836 {
2837 if (strcmp(key, store->key))
2838 return 0; /* not ours */
2839 if (store->fixed_value)
2840 return !strcmp(store->fixed_value, value);
2841 if (!store->value_pattern)
2842 return 1; /* always matches */
2843 if (store->value_pattern == CONFIG_REGEX_NONE)
2844 return 0; /* never matches */
2845
2846 return store->do_not_match ^
2847 (value && !regexec(store->value_pattern, value, 0, NULL, 0));
2848 }
2849
2850 static int store_aux_event(enum config_event_t type,
2851 size_t begin, size_t end, void *data)
2852 {
2853 struct config_store_data *store = data;
2854
2855 ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
2856 store->parsed[store->parsed_nr].begin = begin;
2857 store->parsed[store->parsed_nr].end = end;
2858 store->parsed[store->parsed_nr].type = type;
2859
2860 if (type == CONFIG_EVENT_SECTION) {
2861 int (*cmpfn)(const char *, const char *, size_t);
2862
2863 if (cf->var.len < 2 || cf->var.buf[cf->var.len - 1] != '.')
2864 return error(_("invalid section name '%s'"), cf->var.buf);
2865
2866 if (cf->subsection_case_sensitive)
2867 cmpfn = strncasecmp;
2868 else
2869 cmpfn = strncmp;
2870
2871 /* Is this the section we were looking for? */
2872 store->is_keys_section =
2873 store->parsed[store->parsed_nr].is_keys_section =
2874 cf->var.len - 1 == store->baselen &&
2875 !cmpfn(cf->var.buf, store->key, store->baselen);
2876 if (store->is_keys_section) {
2877 store->section_seen = 1;
2878 ALLOC_GROW(store->seen, store->seen_nr + 1,
2879 store->seen_alloc);
2880 store->seen[store->seen_nr] = store->parsed_nr;
2881 }
2882 }
2883
2884 store->parsed_nr++;
2885
2886 return 0;
2887 }
2888
2889 static int store_aux(const char *key, const char *value, void *cb)
2890 {
2891 struct config_store_data *store = cb;
2892
2893 if (store->key_seen) {
2894 if (matches(key, value, store)) {
2895 if (store->seen_nr == 1 && store->multi_replace == 0) {
2896 warning(_("%s has multiple values"), key);
2897 }
2898
2899 ALLOC_GROW(store->seen, store->seen_nr + 1,
2900 store->seen_alloc);
2901
2902 store->seen[store->seen_nr] = store->parsed_nr;
2903 store->seen_nr++;
2904 }
2905 } else if (store->is_keys_section) {
2906 /*
2907 * Do not increment matches yet: this may not be a match, but we
2908 * are in the desired section.
2909 */
2910 ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
2911 store->seen[store->seen_nr] = store->parsed_nr;
2912 store->section_seen = 1;
2913
2914 if (matches(key, value, store)) {
2915 store->seen_nr++;
2916 store->key_seen = 1;
2917 }
2918 }
2919
2920 return 0;
2921 }
2922
2923 static int write_error(const char *filename)
2924 {
2925 error(_("failed to write new configuration file %s"), filename);
2926
2927 /* Same error code as "failed to rename". */
2928 return 4;
2929 }
2930
2931 static struct strbuf store_create_section(const char *key,
2932 const struct config_store_data *store)
2933 {
2934 const char *dot;
2935 size_t i;
2936 struct strbuf sb = STRBUF_INIT;
2937
2938 dot = memchr(key, '.', store->baselen);
2939 if (dot) {
2940 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
2941 for (i = dot - key + 1; i < store->baselen; i++) {
2942 if (key[i] == '"' || key[i] == '\\')
2943 strbuf_addch(&sb, '\\');
2944 strbuf_addch(&sb, key[i]);
2945 }
2946 strbuf_addstr(&sb, "\"]\n");
2947 } else {
2948 strbuf_addch(&sb, '[');
2949 strbuf_add(&sb, key, store->baselen);
2950 strbuf_addstr(&sb, "]\n");
2951 }
2952
2953 return sb;
2954 }
2955
2956 static ssize_t write_section(int fd, const char *key,
2957 const struct config_store_data *store)
2958 {
2959 struct strbuf sb = store_create_section(key, store);
2960 ssize_t ret;
2961
2962 ret = write_in_full(fd, sb.buf, sb.len);
2963 strbuf_release(&sb);
2964
2965 return ret;
2966 }
2967
2968 static ssize_t write_pair(int fd, const char *key, const char *value,
2969 const struct config_store_data *store)
2970 {
2971 int i;
2972 ssize_t ret;
2973 const char *quote = "";
2974 struct strbuf sb = STRBUF_INIT;
2975
2976 /*
2977 * Check to see if the value needs to be surrounded with a dq pair.
2978 * Note that problematic characters are always backslash-quoted; this
2979 * check is about not losing leading or trailing SP and strings that
2980 * follow beginning-of-comment characters (i.e. ';' and '#') by the
2981 * configuration parser.
2982 */
2983 if (value[0] == ' ')
2984 quote = "\"";
2985 for (i = 0; value[i]; i++)
2986 if (value[i] == ';' || value[i] == '#')
2987 quote = "\"";
2988 if (i && value[i - 1] == ' ')
2989 quote = "\"";
2990
2991 strbuf_addf(&sb, "\t%s = %s", key + store->baselen + 1, quote);
2992
2993 for (i = 0; value[i]; i++)
2994 switch (value[i]) {
2995 case '\n':
2996 strbuf_addstr(&sb, "\\n");
2997 break;
2998 case '\t':
2999 strbuf_addstr(&sb, "\\t");
3000 break;
3001 case '"':
3002 case '\\':
3003 strbuf_addch(&sb, '\\');
3004 /* fallthrough */
3005 default:
3006 strbuf_addch(&sb, value[i]);
3007 break;
3008 }
3009 strbuf_addf(&sb, "%s\n", quote);
3010
3011 ret = write_in_full(fd, sb.buf, sb.len);
3012 strbuf_release(&sb);
3013
3014 return ret;
3015 }
3016
3017 /*
3018 * If we are about to unset the last key(s) in a section, and if there are
3019 * no comments surrounding (or included in) the section, we will want to
3020 * extend begin/end to remove the entire section.
3021 *
3022 * Note: the parameter `seen_ptr` points to the index into the store.seen
3023 * array. * This index may be incremented if a section has more than one
3024 * entry (which all are to be removed).
3025 */
3026 static void maybe_remove_section(struct config_store_data *store,
3027 size_t *begin_offset, size_t *end_offset,
3028 int *seen_ptr)
3029 {
3030 size_t begin;
3031 int i, seen, section_seen = 0;
3032
3033 /*
3034 * First, ensure that this is the first key, and that there are no
3035 * comments before the entry nor before the section header.
3036 */
3037 seen = *seen_ptr;
3038 for (i = store->seen[seen]; i > 0; i--) {
3039 enum config_event_t type = store->parsed[i - 1].type;
3040
3041 if (type == CONFIG_EVENT_COMMENT)
3042 /* There is a comment before this entry or section */
3043 return;
3044 if (type == CONFIG_EVENT_ENTRY) {
3045 if (!section_seen)
3046 /* This is not the section's first entry. */
3047 return;
3048 /* We encountered no comment before the section. */
3049 break;
3050 }
3051 if (type == CONFIG_EVENT_SECTION) {
3052 if (!store->parsed[i - 1].is_keys_section)
3053 break;
3054 section_seen = 1;
3055 }
3056 }
3057 begin = store->parsed[i].begin;
3058
3059 /*
3060 * Next, make sure that we are removing the last key(s) in the section,
3061 * and that there are no comments that are possibly about the current
3062 * section.
3063 */
3064 for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
3065 enum config_event_t type = store->parsed[i].type;
3066
3067 if (type == CONFIG_EVENT_COMMENT)
3068 return;
3069 if (type == CONFIG_EVENT_SECTION) {
3070 if (store->parsed[i].is_keys_section)
3071 continue;
3072 break;
3073 }
3074 if (type == CONFIG_EVENT_ENTRY) {
3075 if (++seen < store->seen_nr &&
3076 i == store->seen[seen])
3077 /* We want to remove this entry, too */
3078 continue;
3079 /* There is another entry in this section. */
3080 return;
3081 }
3082 }
3083
3084 /*
3085 * We are really removing the last entry/entries from this section, and
3086 * there are no enclosed or surrounding comments. Remove the entire,
3087 * now-empty section.
3088 */
3089 *seen_ptr = seen;
3090 *begin_offset = begin;
3091 if (i < store->parsed_nr)
3092 *end_offset = store->parsed[i].begin;
3093 else
3094 *end_offset = store->parsed[store->parsed_nr - 1].end;
3095 }
3096
3097 int git_config_set_in_file_gently(const char *config_filename,
3098 const char *key, const char *value)
3099 {
3100 return git_config_set_multivar_in_file_gently(config_filename, key, value, NULL, 0);
3101 }
3102
3103 void git_config_set_in_file(const char *config_filename,
3104 const char *key, const char *value)
3105 {
3106 git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
3107 }
3108
3109 int git_config_set_gently(const char *key, const char *value)
3110 {
3111 return git_config_set_multivar_gently(key, value, NULL, 0);
3112 }
3113
3114 int repo_config_set_worktree_gently(struct repository *r,
3115 const char *key, const char *value)
3116 {
3117 /* Only use worktree-specific config if it is is already enabled. */
3118 if (repository_format_worktree_config) {
3119 char *file = repo_git_path(r, "config.worktree");
3120 int ret = git_config_set_multivar_in_file_gently(
3121 file, key, value, NULL, 0);
3122 free(file);
3123 return ret;
3124 }
3125 return repo_config_set_multivar_gently(r, key, value, NULL, 0);
3126 }
3127
3128 void git_config_set(const char *key, const char *value)
3129 {
3130 git_config_set_multivar(key, value, NULL, 0);
3131
3132 trace2_cmd_set_config(key, value);
3133 }
3134
3135 /*
3136 * If value==NULL, unset in (remove from) config,
3137 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
3138 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
3139 * (only add a new one)
3140 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3141 * key/values are removed before a single new pair is written. If the
3142 * flag is not present, then replace only the first match.
3143 *
3144 * Returns 0 on success.
3145 *
3146 * This function does this:
3147 *
3148 * - it locks the config file by creating ".git/config.lock"
3149 *
3150 * - it then parses the config using store_aux() as validator to find
3151 * the position on the key/value pair to replace. If it is to be unset,
3152 * it must be found exactly once.
3153 *
3154 * - the config file is mmap()ed and the part before the match (if any) is
3155 * written to the lock file, then the changed part and the rest.
3156 *
3157 * - the config file is removed and the lock file rename()d to it.
3158 *
3159 */
3160 int git_config_set_multivar_in_file_gently(const char *config_filename,
3161 const char *key, const char *value,
3162 const char *value_pattern,
3163 unsigned flags)
3164 {
3165 int fd = -1, in_fd = -1;
3166 int ret;
3167 struct lock_file lock = LOCK_INIT;
3168 char *filename_buf = NULL;
3169 char *contents = NULL;
3170 size_t contents_sz;
3171 struct config_store_data store;
3172
3173 memset(&store, 0, sizeof(store));
3174
3175 /* parse-key returns negative; flip the sign to feed exit(3) */
3176 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
3177 if (ret)
3178 goto out_free;
3179
3180 store.multi_replace = (flags & CONFIG_FLAGS_MULTI_REPLACE) != 0;
3181
3182 if (!config_filename)
3183 config_filename = filename_buf = git_pathdup("config");
3184
3185 /*
3186 * The lock serves a purpose in addition to locking: the new
3187 * contents of .git/config will be written into it.
3188 */
3189 fd = hold_lock_file_for_update(&lock, config_filename, 0);
3190 if (fd < 0) {
3191 error_errno(_("could not lock config file %s"), config_filename);
3192 ret = CONFIG_NO_LOCK;
3193 goto out_free;
3194 }
3195
3196 /*
3197 * If .git/config does not exist yet, write a minimal version.
3198 */
3199 in_fd = open(config_filename, O_RDONLY);
3200 if ( in_fd < 0 ) {
3201 if ( ENOENT != errno ) {
3202 error_errno(_("opening %s"), config_filename);
3203 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
3204 goto out_free;
3205 }
3206 /* if nothing to unset, error out */
3207 if (value == NULL) {
3208 ret = CONFIG_NOTHING_SET;
3209 goto out_free;
3210 }
3211
3212 free(store.key);
3213 store.key = xstrdup(key);
3214 if (write_section(fd, key, &store) < 0 ||
3215 write_pair(fd, key, value, &store) < 0)
3216 goto write_err_out;
3217 } else {
3218 struct stat st;
3219 size_t copy_begin, copy_end;
3220 int i, new_line = 0;
3221 struct config_options opts;
3222
3223 if (value_pattern == NULL)
3224 store.value_pattern = NULL;
3225 else if (value_pattern == CONFIG_REGEX_NONE)
3226 store.value_pattern = CONFIG_REGEX_NONE;
3227 else if (flags & CONFIG_FLAGS_FIXED_VALUE)
3228 store.fixed_value = value_pattern;
3229 else {
3230 if (value_pattern[0] == '!') {
3231 store.do_not_match = 1;
3232 value_pattern++;
3233 } else
3234 store.do_not_match = 0;
3235
3236 store.value_pattern = (regex_t*)xmalloc(sizeof(regex_t));
3237 if (regcomp(store.value_pattern, value_pattern,
3238 REG_EXTENDED)) {
3239 error(_("invalid pattern: %s"), value_pattern);
3240 FREE_AND_NULL(store.value_pattern);
3241 ret = CONFIG_INVALID_PATTERN;
3242 goto out_free;
3243 }
3244 }
3245
3246 ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
3247 store.parsed[0].end = 0;
3248
3249 memset(&opts, 0, sizeof(opts));
3250 opts.event_fn = store_aux_event;
3251 opts.event_fn_data = &store;
3252
3253 /*
3254 * After this, store.parsed will contain offsets of all the
3255 * parsed elements, and store.seen will contain a list of
3256 * matches, as indices into store.parsed.
3257 *
3258 * As a side effect, we make sure to transform only a valid
3259 * existing config file.
3260 */
3261 if (git_config_from_file_with_options(store_aux,
3262 config_filename,
3263 &store, &opts)) {
3264 error(_("invalid config file %s"), config_filename);
3265 ret = CONFIG_INVALID_FILE;
3266 goto out_free;
3267 }
3268
3269 /* if nothing to unset, or too many matches, error out */
3270 if ((store.seen_nr == 0 && value == NULL) ||
3271 (store.seen_nr > 1 && !store.multi_replace)) {
3272 ret = CONFIG_NOTHING_SET;
3273 goto out_free;
3274 }
3275
3276 if (fstat(in_fd, &st) == -1) {
3277 error_errno(_("fstat on %s failed"), config_filename);
3278 ret = CONFIG_INVALID_FILE;
3279 goto out_free;
3280 }
3281
3282 contents_sz = xsize_t(st.st_size);
3283 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
3284 MAP_PRIVATE, in_fd, 0);
3285 if (contents == MAP_FAILED) {
3286 if (errno == ENODEV && S_ISDIR(st.st_mode))
3287 errno = EISDIR;
3288 error_errno(_("unable to mmap '%s'%s"),
3289 config_filename, mmap_os_err());
3290 ret = CONFIG_INVALID_FILE;
3291 contents = NULL;
3292 goto out_free;
3293 }
3294 close(in_fd);
3295 in_fd = -1;
3296
3297 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3298 error_errno(_("chmod on %s failed"), get_lock_file_path(&lock));
3299 ret = CONFIG_NO_WRITE;
3300 goto out_free;
3301 }
3302
3303 if (store.seen_nr == 0) {
3304 if (!store.seen_alloc) {
3305 /* Did not see key nor section */
3306 ALLOC_GROW(store.seen, 1, store.seen_alloc);
3307 store.seen[0] = store.parsed_nr
3308 - !!store.parsed_nr;
3309 }
3310 store.seen_nr = 1;
3311 }
3312
3313 for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
3314 size_t replace_end;
3315 int j = store.seen[i];
3316
3317 new_line = 0;
3318 if (!store.key_seen) {
3319 copy_end = store.parsed[j].end;
3320 /* include '\n' when copying section header */
3321 if (copy_end > 0 && copy_end < contents_sz &&
3322 contents[copy_end - 1] != '\n' &&
3323 contents[copy_end] == '\n')
3324 copy_end++;
3325 replace_end = copy_end;
3326 } else {
3327 replace_end = store.parsed[j].end;
3328 copy_end = store.parsed[j].begin;
3329 if (!value)
3330 maybe_remove_section(&store,
3331 &copy_end,
3332 &replace_end, &i);
3333 /*
3334 * Swallow preceding white-space on the same
3335 * line.
3336 */
3337 while (copy_end > 0 ) {
3338 char c = contents[copy_end - 1];
3339
3340 if (isspace(c) && c != '\n')
3341 copy_end--;
3342 else
3343 break;
3344 }
3345 }
3346
3347 if (copy_end > 0 && contents[copy_end-1] != '\n')
3348 new_line = 1;
3349
3350 /* write the first part of the config */
3351 if (copy_end > copy_begin) {
3352 if (write_in_full(fd, contents + copy_begin,
3353 copy_end - copy_begin) < 0)
3354 goto write_err_out;
3355 if (new_line &&
3356 write_str_in_full(fd, "\n") < 0)
3357 goto write_err_out;
3358 }
3359 copy_begin = replace_end;
3360 }
3361
3362 /* write the pair (value == NULL means unset) */
3363 if (value != NULL) {
3364 if (!store.section_seen) {
3365 if (write_section(fd, key, &store) < 0)
3366 goto write_err_out;
3367 }
3368 if (write_pair(fd, key, value, &store) < 0)
3369 goto write_err_out;
3370 }
3371
3372 /* write the rest of the config */
3373 if (copy_begin < contents_sz)
3374 if (write_in_full(fd, contents + copy_begin,
3375 contents_sz - copy_begin) < 0)
3376 goto write_err_out;
3377
3378 munmap(contents, contents_sz);
3379 contents = NULL;
3380 }
3381
3382 if (commit_lock_file(&lock) < 0) {
3383 error_errno(_("could not write config file %s"), config_filename);
3384 ret = CONFIG_NO_WRITE;
3385 goto out_free;
3386 }
3387
3388 ret = 0;
3389
3390 /* Invalidate the config cache */
3391 git_config_clear();
3392
3393 out_free:
3394 rollback_lock_file(&lock);
3395 free(filename_buf);
3396 if (contents)
3397 munmap(contents, contents_sz);
3398 if (in_fd >= 0)
3399 close(in_fd);
3400 config_store_data_clear(&store);
3401 return ret;
3402
3403 write_err_out:
3404 ret = write_error(get_lock_file_path(&lock));
3405 goto out_free;
3406
3407 }
3408
3409 void git_config_set_multivar_in_file(const char *config_filename,
3410 const char *key, const char *value,
3411 const char *value_pattern, unsigned flags)
3412 {
3413 if (!git_config_set_multivar_in_file_gently(config_filename, key, value,
3414 value_pattern, flags))
3415 return;
3416 if (value)
3417 die(_("could not set '%s' to '%s'"), key, value);
3418 else
3419 die(_("could not unset '%s'"), key);
3420 }
3421
3422 int git_config_set_multivar_gently(const char *key, const char *value,
3423 const char *value_pattern, unsigned flags)
3424 {
3425 return repo_config_set_multivar_gently(the_repository, key, value,
3426 value_pattern, flags);
3427 }
3428
3429 int repo_config_set_multivar_gently(struct repository *r, const char *key,
3430 const char *value,
3431 const char *value_pattern, unsigned flags)
3432 {
3433 char *file = repo_git_path(r, "config");
3434 int res = git_config_set_multivar_in_file_gently(file,
3435 key, value,
3436 value_pattern,
3437 flags);
3438 free(file);
3439 return res;
3440 }
3441
3442 void git_config_set_multivar(const char *key, const char *value,
3443 const char *value_pattern, unsigned flags)
3444 {
3445 git_config_set_multivar_in_file(git_path("config"),
3446 key, value, value_pattern,
3447 flags);
3448 }
3449
3450 static int section_name_match (const char *buf, const char *name)
3451 {
3452 int i = 0, j = 0, dot = 0;
3453 if (buf[i] != '[')
3454 return 0;
3455 for (i = 1; buf[i] && buf[i] != ']'; i++) {
3456 if (!dot && isspace(buf[i])) {
3457 dot = 1;
3458 if (name[j++] != '.')
3459 break;
3460 for (i++; isspace(buf[i]); i++)
3461 ; /* do nothing */
3462 if (buf[i] != '"')
3463 break;
3464 continue;
3465 }
3466 if (buf[i] == '\\' && dot)
3467 i++;
3468 else if (buf[i] == '"' && dot) {
3469 for (i++; isspace(buf[i]); i++)
3470 ; /* do_nothing */
3471 break;
3472 }
3473 if (buf[i] != name[j++])
3474 break;
3475 }
3476 if (buf[i] == ']' && name[j] == 0) {
3477 /*
3478 * We match, now just find the right length offset by
3479 * gobbling up any whitespace after it, as well
3480 */
3481 i++;
3482 for (; buf[i] && isspace(buf[i]); i++)
3483 ; /* do nothing */
3484 return i;
3485 }
3486 return 0;
3487 }
3488
3489 static int section_name_is_ok(const char *name)
3490 {
3491 /* Empty section names are bogus. */
3492 if (!*name)
3493 return 0;
3494
3495 /*
3496 * Before a dot, we must be alphanumeric or dash. After the first dot,
3497 * anything goes, so we can stop checking.
3498 */
3499 for (; *name && *name != '.'; name++)
3500 if (*name != '-' && !isalnum(*name))
3501 return 0;
3502 return 1;
3503 }
3504
3505 /* if new_name == NULL, the section is removed instead */
3506 static int git_config_copy_or_rename_section_in_file(const char *config_filename,
3507 const char *old_name,
3508 const char *new_name, int copy)
3509 {
3510 int ret = 0, remove = 0;
3511 char *filename_buf = NULL;
3512 struct lock_file lock = LOCK_INIT;
3513 int out_fd;
3514 char buf[1024];
3515 FILE *config_file = NULL;
3516 struct stat st;
3517 struct strbuf copystr = STRBUF_INIT;
3518 struct config_store_data store;
3519
3520 memset(&store, 0, sizeof(store));
3521
3522 if (new_name && !section_name_is_ok(new_name)) {
3523 ret = error(_("invalid section name: %s"), new_name);
3524 goto out_no_rollback;
3525 }
3526
3527 if (!config_filename)
3528 config_filename = filename_buf = git_pathdup("config");
3529
3530 out_fd = hold_lock_file_for_update(&lock, config_filename, 0);
3531 if (out_fd < 0) {
3532 ret = error(_("could not lock config file %s"), config_filename);
3533 goto out;
3534 }
3535
3536 if (!(config_file = fopen(config_filename, "rb"))) {
3537 ret = warn_on_fopen_errors(config_filename);
3538 if (ret)
3539 goto out;
3540 /* no config file means nothing to rename, no error */
3541 goto commit_and_out;
3542 }
3543
3544 if (fstat(fileno(config_file), &st) == -1) {
3545 ret = error_errno(_("fstat on %s failed"), config_filename);
3546 goto out;
3547 }
3548
3549 if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3550 ret = error_errno(_("chmod on %s failed"),
3551 get_lock_file_path(&lock));
3552 goto out;
3553 }
3554
3555 while (fgets(buf, sizeof(buf), config_file)) {
3556 unsigned i;
3557 int length;
3558 int is_section = 0;
3559 char *output = buf;
3560 for (i = 0; buf[i] && isspace(buf[i]); i++)
3561 ; /* do nothing */
3562 if (buf[i] == '[') {
3563 /* it's a section */
3564 int offset;
3565 is_section = 1;
3566
3567 /*
3568 * When encountering a new section under -c we
3569 * need to flush out any section we're already
3570 * coping and begin anew. There might be
3571 * multiple [branch "$name"] sections.
3572 */
3573 if (copystr.len > 0) {
3574 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3575 ret = write_error(get_lock_file_path(&lock));
3576 goto out;
3577 }
3578 strbuf_reset(&copystr);
3579 }
3580
3581 offset = section_name_match(&buf[i], old_name);
3582 if (offset > 0) {
3583 ret++;
3584 if (new_name == NULL) {
3585 remove = 1;
3586 continue;
3587 }
3588 store.baselen = strlen(new_name);
3589 if (!copy) {
3590 if (write_section(out_fd, new_name, &store) < 0) {
3591 ret = write_error(get_lock_file_path(&lock));
3592 goto out;
3593 }
3594 /*
3595 * We wrote out the new section, with
3596 * a newline, now skip the old
3597 * section's length
3598 */
3599 output += offset + i;
3600 if (strlen(output) > 0) {
3601 /*
3602 * More content means there's
3603 * a declaration to put on the
3604 * next line; indent with a
3605 * tab
3606 */
3607 output -= 1;
3608 output[0] = '\t';
3609 }
3610 } else {
3611 copystr = store_create_section(new_name, &store);
3612 }
3613 }
3614 remove = 0;
3615 }
3616 if (remove)
3617 continue;
3618 length = strlen(output);
3619
3620 if (!is_section && copystr.len > 0) {
3621 strbuf_add(&copystr, output, length);
3622 }
3623
3624 if (write_in_full(out_fd, output, length) < 0) {
3625 ret = write_error(get_lock_file_path(&lock));
3626 goto out;
3627 }
3628 }
3629
3630 /*
3631 * Copy a trailing section at the end of the config, won't be
3632 * flushed by the usual "flush because we have a new section
3633 * logic in the loop above.
3634 */
3635 if (copystr.len > 0) {
3636 if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3637 ret = write_error(get_lock_file_path(&lock));
3638 goto out;
3639 }
3640 strbuf_reset(&copystr);
3641 }
3642
3643 fclose(config_file);
3644 config_file = NULL;
3645 commit_and_out:
3646 if (commit_lock_file(&lock) < 0)
3647 ret = error_errno(_("could not write config file %s"),
3648 config_filename);
3649 out:
3650 if (config_file)
3651 fclose(config_file);
3652 rollback_lock_file(&lock);
3653 out_no_rollback:
3654 free(filename_buf);
3655 config_store_data_clear(&store);
3656 return ret;
3657 }
3658
3659 int git_config_rename_section_in_file(const char *config_filename,
3660 const char *old_name, const char *new_name)
3661 {
3662 return git_config_copy_or_rename_section_in_file(config_filename,
3663 old_name, new_name, 0);
3664 }
3665
3666 int git_config_rename_section(const char *old_name, const char *new_name)
3667 {
3668 return git_config_rename_section_in_file(NULL, old_name, new_name);
3669 }
3670
3671 int git_config_copy_section_in_file(const char *config_filename,
3672 const char *old_name, const char *new_name)
3673 {
3674 return git_config_copy_or_rename_section_in_file(config_filename,
3675 old_name, new_name, 1);
3676 }
3677
3678 int git_config_copy_section(const char *old_name, const char *new_name)
3679 {
3680 return git_config_copy_section_in_file(NULL, old_name, new_name);
3681 }
3682
3683 /*
3684 * Call this to report error for your variable that should not
3685 * get a boolean value (i.e. "[my] var" means "true").
3686 */
3687 #undef config_error_nonbool
3688 int config_error_nonbool(const char *var)
3689 {
3690 return error(_("missing value for '%s'"), var);
3691 }
3692
3693 int parse_config_key(const char *var,
3694 const char *section,
3695 const char **subsection, size_t *subsection_len,
3696 const char **key)
3697 {
3698 const char *dot;
3699
3700 /* Does it start with "section." ? */
3701 if (!skip_prefix(var, section, &var) || *var != '.')
3702 return -1;
3703
3704 /*
3705 * Find the key; we don't know yet if we have a subsection, but we must
3706 * parse backwards from the end, since the subsection may have dots in
3707 * it, too.
3708 */
3709 dot = strrchr(var, '.');
3710 *key = dot + 1;
3711
3712 /* Did we have a subsection at all? */
3713 if (dot == var) {
3714 if (subsection) {
3715 *subsection = NULL;
3716 *subsection_len = 0;
3717 }
3718 }
3719 else {
3720 if (!subsection)
3721 return -1;
3722 *subsection = var + 1;
3723 *subsection_len = dot - *subsection;
3724 }
3725
3726 return 0;
3727 }
3728
3729 const char *current_config_origin_type(void)
3730 {
3731 int type;
3732 if (current_config_kvi)
3733 type = current_config_kvi->origin_type;
3734 else if(cf)
3735 type = cf->origin_type;
3736 else
3737 BUG("current_config_origin_type called outside config callback");
3738
3739 switch (type) {
3740 case CONFIG_ORIGIN_BLOB:
3741 return "blob";
3742 case CONFIG_ORIGIN_FILE:
3743 return "file";
3744 case CONFIG_ORIGIN_STDIN:
3745 return "standard input";
3746 case CONFIG_ORIGIN_SUBMODULE_BLOB:
3747 return "submodule-blob";
3748 case CONFIG_ORIGIN_CMDLINE:
3749 return "command line";
3750 default:
3751 BUG("unknown config origin type");
3752 }
3753 }
3754
3755 const char *config_scope_name(enum config_scope scope)
3756 {
3757 switch (scope) {
3758 case CONFIG_SCOPE_SYSTEM:
3759 return "system";
3760 case CONFIG_SCOPE_GLOBAL:
3761 return "global";
3762 case CONFIG_SCOPE_LOCAL:
3763 return "local";
3764 case CONFIG_SCOPE_WORKTREE:
3765 return "worktree";
3766 case CONFIG_SCOPE_COMMAND:
3767 return "command";
3768 case CONFIG_SCOPE_SUBMODULE:
3769 return "submodule";
3770 default:
3771 return "unknown";
3772 }
3773 }
3774
3775 const char *current_config_name(void)
3776 {
3777 const char *name;
3778 if (current_config_kvi)
3779 name = current_config_kvi->filename;
3780 else if (cf)
3781 name = cf->name;
3782 else
3783 BUG("current_config_name called outside config callback");
3784 return name ? name : "";
3785 }
3786
3787 enum config_scope current_config_scope(void)
3788 {
3789 if (current_config_kvi)
3790 return current_config_kvi->scope;
3791 else
3792 return current_parsing_scope;
3793 }
3794
3795 int current_config_line(void)
3796 {
3797 if (current_config_kvi)
3798 return current_config_kvi->linenr;
3799 else
3800 return cf->linenr;
3801 }
3802
3803 int lookup_config(const char **mapping, int nr_mapping, const char *var)
3804 {
3805 int i;
3806
3807 for (i = 0; i < nr_mapping; i++) {
3808 const char *name = mapping[i];
3809
3810 if (name && !strcasecmp(var, name))
3811 return i;
3812 }
3813 return -1;
3814 }