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