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