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