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