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