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