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