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