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