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