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