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