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