i18n: notes: mark comment for translation
[git/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"
697cc8ef 9#include "lockfile.h"
7f0e39fa 10#include "exec_cmd.h"
572e4f6a 11#include "strbuf.h"
2b64fc89 12#include "quote.h"
3c8687a7
TA
13#include "hashmap.h"
14#include "string-list.h"
599446dc 15#include "utf8.h"
17712991 16
4d8dd149
HV
17struct config_source {
18 struct config_source *prev;
19 union {
20 FILE *file;
1bc88819
HV
21 struct config_buf {
22 const char *buf;
23 size_t len;
24 size_t pos;
25 } buf;
4d8dd149 26 } u;
473166b9 27 const char *origin_type;
924aaf3e 28 const char *name;
d14d4244 29 const char *path;
b2dc0945 30 int die_on_error;
924aaf3e
RJ
31 int linenr;
32 int eof;
33 struct strbuf value;
0971e992 34 struct strbuf var;
924aaf3e 35
49d6cfa5
JK
36 int (*do_fgetc)(struct config_source *c);
37 int (*do_ungetc)(int c, struct config_source *conf);
38 long (*do_ftell)(struct config_source *c);
4d8dd149
HV
39};
40
0d44a2da
JK
41/*
42 * These variables record the "current" config source, which
43 * can be accessed by parsing callbacks.
44 *
45 * The "cf" variable will be non-NULL only when we are actually parsing a real
46 * config source (file, blob, cmdline, etc).
47 *
48 * The "current_config_kvi" variable will be non-NULL only when we are feeding
49 * cached config from a configset into a callback.
50 *
51 * They should generally never be non-NULL at the same time. If they are both
52 * NULL, then we aren't parsing anything (and depending on the function looking
53 * at the variables, it's either a bug for it to be called in the first place,
54 * or it's a function which can be reused for non-config purposes, and should
55 * fall back to some sane behavior).
56 */
4d8dd149 57static struct config_source *cf;
0d44a2da 58static struct key_value_info *current_config_kvi;
924aaf3e 59
9acc5911
JK
60/*
61 * Similar to the variables above, this gives access to the "scope" of the
62 * current value (repo, global, etc). For cached values, it can be found via
63 * the current_config_kvi as above. During parsing, the current value can be
64 * found in this variable. It's not part of "cf" because it transcends a single
65 * file (i.e., a file included from .git/config is still in "repo" scope).
66 */
67static enum config_scope current_parsing_scope;
924aaf3e 68
960ccca6
DH
69static int zlib_compression_seen;
70
3c8687a7
TA
71/*
72 * Default config_set that contains key-value pairs from the usual set of config
73 * config files (i.e repo specific .git/config, user wide ~/.gitconfig, XDG
74 * config file and the global /etc/gitconfig)
75 */
76static struct config_set the_config_set;
77
4d8dd149
HV
78static int config_file_fgetc(struct config_source *conf)
79{
260d408e 80 return getc_unlocked(conf->u.file);
4d8dd149
HV
81}
82
83static int config_file_ungetc(int c, struct config_source *conf)
84{
85 return ungetc(c, conf->u.file);
86}
87
88static long config_file_ftell(struct config_source *conf)
89{
90 return ftell(conf->u.file);
91}
92
1bc88819
HV
93
94static int config_buf_fgetc(struct config_source *conf)
95{
96 if (conf->u.buf.pos < conf->u.buf.len)
97 return conf->u.buf.buf[conf->u.buf.pos++];
98
99 return EOF;
100}
101
102static int config_buf_ungetc(int c, struct config_source *conf)
103{
1d0655c1
JK
104 if (conf->u.buf.pos > 0) {
105 conf->u.buf.pos--;
106 if (conf->u.buf.buf[conf->u.buf.pos] != c)
107 die("BUG: config_buf can only ungetc the same character");
108 return c;
109 }
1bc88819
HV
110
111 return EOF;
112}
113
114static long config_buf_ftell(struct config_source *conf)
115{
116 return conf->u.buf.pos;
117}
118
9b25a0b5
JK
119#define MAX_INCLUDE_DEPTH 10
120static const char include_depth_advice[] =
121"exceeded maximum include depth (%d) while including\n"
122" %s\n"
123"from\n"
124" %s\n"
125"Do you have circular includes?";
126static int handle_path_include(const char *path, struct config_include_data *inc)
127{
128 int ret = 0;
129 struct strbuf buf = STRBUF_INIT;
67beb600 130 char *expanded;
4c0a89fc 131
67beb600
JK
132 if (!path)
133 return config_error_nonbool("include.path");
134
135 expanded = expand_user_path(path);
4c0a89fc 136 if (!expanded)
8c3ca351 137 return error("could not expand include path '%s'", path);
4c0a89fc 138 path = expanded;
9b25a0b5
JK
139
140 /*
141 * Use an absolute path as-is, but interpret relative paths
142 * based on the including config file.
143 */
144 if (!is_absolute_path(path)) {
145 char *slash;
146
d14d4244 147 if (!cf || !cf->path)
9b25a0b5
JK
148 return error("relative config includes must come from files");
149
d14d4244 150 slash = find_last_dir_sep(cf->path);
9b25a0b5 151 if (slash)
d14d4244 152 strbuf_add(&buf, cf->path, slash - cf->path + 1);
9b25a0b5
JK
153 strbuf_addstr(&buf, path);
154 path = buf.buf;
155 }
156
4698c8fe 157 if (!access_or_die(path, R_OK, 0)) {
9b25a0b5
JK
158 if (++inc->depth > MAX_INCLUDE_DEPTH)
159 die(include_depth_advice, MAX_INCLUDE_DEPTH, path,
3258258f
JK
160 !cf ? "<unknown>" :
161 cf->name ? cf->name :
162 "the command line");
9b25a0b5
JK
163 ret = git_config_from_file(git_config_include, path, inc);
164 inc->depth--;
165 }
166 strbuf_release(&buf);
4c0a89fc 167 free(expanded);
9b25a0b5
JK
168 return ret;
169}
170
171int git_config_include(const char *var, const char *value, void *data)
172{
173 struct config_include_data *inc = data;
9b25a0b5
JK
174 int ret;
175
176 /*
177 * Pass along all values, including "include" directives; this makes it
178 * possible to query information on the includes themselves.
179 */
180 ret = inc->fn(var, value, inc->data);
181 if (ret < 0)
182 return ret;
183
37007c3a 184 if (!strcmp(var, "include.path"))
9b25a0b5
JK
185 ret = handle_path_include(value, inc);
186 return ret;
187}
188
2b64fc89
JK
189void git_config_push_parameter(const char *text)
190{
191 struct strbuf env = STRBUF_INIT;
192 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
d1f88498 193 if (old && *old) {
2b64fc89
JK
194 strbuf_addstr(&env, old);
195 strbuf_addch(&env, ' ');
196 }
197 sq_quote_buf(&env, text);
198 setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
199 strbuf_release(&env);
200}
201
2496844b
JK
202int git_config_parse_parameter(const char *text,
203 config_fn_t fn, void *data)
8b1fa778 204{
a789ca70 205 const char *value;
572e4f6a 206 struct strbuf **pair;
a789ca70 207
f77bccae 208 pair = strbuf_split_str(text, '=', 2);
c5d6350b
JK
209 if (!pair[0])
210 return error("bogus config parameter: %s", text);
a789ca70
JH
211
212 if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
572e4f6a 213 strbuf_setlen(pair[0], pair[0]->len - 1);
a789ca70
JH
214 value = pair[1] ? pair[1]->buf : "";
215 } else {
216 value = NULL;
217 }
218
572e4f6a
AR
219 strbuf_trim(pair[0]);
220 if (!pair[0]->len) {
221 strbuf_list_free(pair);
06eb708f 222 return error("bogus config parameter: %s", text);
8b1fa778 223 }
ffb20ce1 224 strbuf_tolower(pair[0]);
a789ca70 225 if (fn(pair[0]->buf, value, data) < 0) {
06eb708f
JK
226 strbuf_list_free(pair);
227 return -1;
572e4f6a
AR
228 }
229 strbuf_list_free(pair);
8b1fa778
AR
230 return 0;
231}
232
06eb708f
JK
233int git_config_from_parameters(config_fn_t fn, void *data)
234{
2b64fc89 235 const char *env = getenv(CONFIG_DATA_ENVIRONMENT);
a77d6db6 236 int ret = 0;
2b64fc89
JK
237 char *envw;
238 const char **argv = NULL;
239 int nr = 0, alloc = 0;
240 int i;
3258258f 241 struct config_source source;
2b64fc89
JK
242
243 if (!env)
244 return 0;
3258258f
JK
245
246 memset(&source, 0, sizeof(source));
247 source.prev = cf;
248 cf = &source;
249
2b64fc89
JK
250 /* sq_dequote will write over it */
251 envw = xstrdup(env);
252
253 if (sq_dequote_to_argv(envw, &argv, &nr, &alloc) < 0) {
a77d6db6
JK
254 ret = error("bogus format in " CONFIG_DATA_ENVIRONMENT);
255 goto out;
2b64fc89
JK
256 }
257
258 for (i = 0; i < nr; i++) {
06eb708f 259 if (git_config_parse_parameter(argv[i], fn, data) < 0) {
a77d6db6
JK
260 ret = -1;
261 goto out;
2b64fc89
JK
262 }
263 }
264
a77d6db6 265out:
2b64fc89
JK
266 free(argv);
267 free(envw);
3258258f 268 cf = source.prev;
a77d6db6 269 return ret;
2b64fc89
JK
270}
271
17712991
LT
272static int get_next_char(void)
273{
49d6cfa5 274 int c = cf->do_fgetc(cf);
17712991 275
dbb9a812
HV
276 if (c == '\r') {
277 /* DOS like systems */
49d6cfa5 278 c = cf->do_fgetc(cf);
dbb9a812 279 if (c != '\n') {
5e0be134
JK
280 if (c != EOF)
281 cf->do_ungetc(c, cf);
dbb9a812 282 c = '\r';
17712991
LT
283 }
284 }
dbb9a812
HV
285 if (c == '\n')
286 cf->linenr++;
287 if (c == EOF) {
288 cf->eof = 1;
b3b3f60b 289 cf->linenr++;
dbb9a812
HV
290 c = '\n';
291 }
17712991
LT
292 return c;
293}
294
295static char *parse_value(void)
296{
e96c19c5 297 int quote = 0, comment = 0, space = 0;
17712991 298
924aaf3e 299 strbuf_reset(&cf->value);
17712991
LT
300 for (;;) {
301 int c = get_next_char();
17712991 302 if (c == '\n') {
4b340593
MS
303 if (quote) {
304 cf->linenr--;
17712991 305 return NULL;
4b340593 306 }
924aaf3e 307 return cf->value.buf;
17712991
LT
308 }
309 if (comment)
310 continue;
311 if (isspace(c) && !quote) {
924aaf3e 312 if (cf->value.len)
ebdaae37 313 space++;
17712991
LT
314 continue;
315 }
7ebdba61
JS
316 if (!quote) {
317 if (c == ';' || c == '#') {
318 comment = 1;
319 continue;
320 }
321 }
ebdaae37 322 for (; space; space--)
924aaf3e 323 strbuf_addch(&cf->value, ' ');
17712991
LT
324 if (c == '\\') {
325 c = get_next_char();
326 switch (c) {
327 case '\n':
328 continue;
329 case 't':
330 c = '\t';
331 break;
332 case 'b':
333 c = '\b';
334 break;
335 case 'n':
336 c = '\n';
337 break;
5cbb401d
LT
338 /* Some characters escape as themselves */
339 case '\\': case '"':
340 break;
341 /* Reject unknown escape sequences */
342 default:
343 return NULL;
17712991 344 }
924aaf3e 345 strbuf_addch(&cf->value, c);
17712991
LT
346 continue;
347 }
348 if (c == '"') {
349 quote = 1-quote;
350 continue;
351 }
924aaf3e 352 strbuf_addch(&cf->value, c);
17712991
LT
353 }
354}
355
38c5afa8
LT
356static inline int iskeychar(int c)
357{
358 return isalnum(c) || c == '-';
359}
360
0971e992 361static int get_value(config_fn_t fn, void *data, struct strbuf *name)
17712991
LT
362{
363 int c;
364 char *value;
b3b3f60b 365 int ret;
17712991
LT
366
367 /* Get the full name */
368 for (;;) {
369 c = get_next_char();
924aaf3e 370 if (cf->eof)
17712991 371 break;
38c5afa8 372 if (!iskeychar(c))
17712991 373 break;
0971e992 374 strbuf_addch(name, tolower(c));
17712991 375 }
0971e992 376
17712991
LT
377 while (c == ' ' || c == '\t')
378 c = get_next_char();
379
380 value = NULL;
381 if (c != '\n') {
382 if (c != '=')
383 return -1;
384 value = parse_value();
385 if (!value)
386 return -1;
387 }
b3b3f60b
MM
388 /*
389 * We already consumed the \n, but we need linenr to point to
390 * the line we just parsed during the call to fn to get
391 * accurate line number in error messages.
392 */
393 cf->linenr--;
394 ret = fn(name->buf, value, data);
395 cf->linenr++;
396 return ret;
17712991
LT
397}
398
0971e992 399static int get_extended_base_var(struct strbuf *name, int c)
d14f7764
LT
400{
401 do {
402 if (c == '\n')
4b340593 403 goto error_incomplete_line;
d14f7764
LT
404 c = get_next_char();
405 } while (isspace(c));
406
407 /* We require the format to be '[base "extension"]' */
408 if (c != '"')
409 return -1;
0971e992 410 strbuf_addch(name, '.');
d14f7764
LT
411
412 for (;;) {
413 int c = get_next_char();
414 if (c == '\n')
4b340593 415 goto error_incomplete_line;
d14f7764
LT
416 if (c == '"')
417 break;
418 if (c == '\\') {
419 c = get_next_char();
420 if (c == '\n')
4b340593 421 goto error_incomplete_line;
d14f7764 422 }
0971e992 423 strbuf_addch(name, c);
d14f7764
LT
424 }
425
426 /* Final ']' */
427 if (get_next_char() != ']')
428 return -1;
0971e992 429 return 0;
4b340593
MS
430error_incomplete_line:
431 cf->linenr--;
432 return -1;
d14f7764
LT
433}
434
0971e992 435static int get_base_var(struct strbuf *name)
17712991 436{
17712991
LT
437 for (;;) {
438 int c = get_next_char();
924aaf3e 439 if (cf->eof)
17712991
LT
440 return -1;
441 if (c == ']')
0971e992 442 return 0;
d14f7764 443 if (isspace(c))
0971e992 444 return get_extended_base_var(name, c);
38c5afa8 445 if (!iskeychar(c) && c != '.')
17712991 446 return -1;
0971e992 447 strbuf_addch(name, tolower(c));
17712991
LT
448 }
449}
450
4d8dd149 451static int git_parse_source(config_fn_t fn, void *data)
17712991
LT
452{
453 int comment = 0;
454 int baselen = 0;
0971e992 455 struct strbuf *var = &cf->var;
17712991 456
de056402 457 /* U+FEFF Byte Order Mark in UTF8 */
599446dc 458 const char *bomptr = utf8_bom;
de056402 459
17712991
LT
460 for (;;) {
461 int c = get_next_char();
de056402
PB
462 if (bomptr && *bomptr) {
463 /* We are at the file beginning; skip UTF8-encoded BOM
464 * if present. Sane editors won't put this in on their
465 * own, but e.g. Windows Notepad will do it happily. */
599446dc 466 if (c == (*bomptr & 0377)) {
de056402
PB
467 bomptr++;
468 continue;
469 } else {
470 /* Do not tolerate partial BOM. */
471 if (bomptr != utf8_bom)
472 break;
473 /* No BOM at file beginning. Cool. */
474 bomptr = NULL;
475 }
476 }
17712991 477 if (c == '\n') {
924aaf3e 478 if (cf->eof)
17712991
LT
479 return 0;
480 comment = 0;
481 continue;
482 }
483 if (comment || isspace(c))
484 continue;
485 if (c == '#' || c == ';') {
486 comment = 1;
487 continue;
488 }
489 if (c == '[') {
0971e992
BW
490 /* Reset prior to determining a new stem */
491 strbuf_reset(var);
492 if (get_base_var(var) < 0 || var->len < 1)
17712991 493 break;
0971e992
BW
494 strbuf_addch(var, '.');
495 baselen = var->len;
17712991
LT
496 continue;
497 }
498 if (!isalpha(c))
499 break;
0971e992
BW
500 /*
501 * Truncate the var name back to the section header
502 * stem prior to grabbing the suffix part of the name
503 * and the value.
504 */
505 strbuf_setlen(var, baselen);
506 strbuf_addch(var, tolower(c));
507 if (get_value(fn, data, var) < 0)
17712991
LT
508 break;
509 }
b2dc0945 510 if (cf->die_on_error)
473166b9 511 die(_("bad config line %d in %s %s"), cf->linenr, cf->origin_type, cf->name);
b2dc0945 512 else
473166b9 513 return error(_("bad config line %d in %s %s"), cf->linenr, cf->origin_type, cf->name);
17712991
LT
514}
515
ebaa1bd4 516static int parse_unit_factor(const char *end, uintmax_t *val)
0b87b6e0
BD
517{
518 if (!*end)
519 return 1;
c8deb5a1
SP
520 else if (!strcasecmp(end, "k")) {
521 *val *= 1024;
522 return 1;
523 }
524 else if (!strcasecmp(end, "m")) {
525 *val *= 1024 * 1024;
526 return 1;
527 }
528 else if (!strcasecmp(end, "g")) {
529 *val *= 1024 * 1024 * 1024;
530 return 1;
531 }
532 return 0;
0b87b6e0
BD
533}
534
7192777d 535static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
0b87b6e0
BD
536{
537 if (value && *value) {
538 char *end;
ebaa1bd4
NA
539 intmax_t val;
540 uintmax_t uval;
541 uintmax_t factor = 1;
542
543 errno = 0;
544 val = strtoimax(value, &end, 0);
545 if (errno == ERANGE)
546 return 0;
33fdd77e
JK
547 if (!parse_unit_factor(end, &factor)) {
548 errno = EINVAL;
c8deb5a1 549 return 0;
33fdd77e 550 }
83915ba5 551 uval = labs(val);
ebaa1bd4 552 uval *= factor;
83915ba5 553 if (uval > max || labs(val) > uval) {
33fdd77e 554 errno = ERANGE;
ebaa1bd4 555 return 0;
33fdd77e 556 }
ebaa1bd4
NA
557 val *= factor;
558 *ret = val;
0b87b6e0
BD
559 return 1;
560 }
33fdd77e 561 errno = EINVAL;
0b87b6e0
BD
562 return 0;
563}
564
0b4dc661 565static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
17712991
LT
566{
567 if (value && *value) {
568 char *end;
ebaa1bd4
NA
569 uintmax_t val;
570 uintmax_t oldval;
571
572 errno = 0;
573 val = strtoumax(value, &end, 0);
574 if (errno == ERANGE)
575 return 0;
576 oldval = val;
33fdd77e
JK
577 if (!parse_unit_factor(end, &val)) {
578 errno = EINVAL;
c8deb5a1 579 return 0;
33fdd77e
JK
580 }
581 if (val > max || oldval > val) {
582 errno = ERANGE;
ebaa1bd4 583 return 0;
33fdd77e 584 }
c8deb5a1 585 *ret = val;
0b87b6e0 586 return 1;
17712991 587 }
33fdd77e 588 errno = EINVAL;
0b87b6e0
BD
589 return 0;
590}
591
42d194e9 592static int git_parse_int(const char *value, int *ret)
c1867cea 593{
7192777d 594 intmax_t tmp;
42d194e9 595 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
7192777d
JK
596 return 0;
597 *ret = tmp;
598 return 1;
599}
600
00160242
JK
601static int git_parse_int64(const char *value, int64_t *ret)
602{
603 intmax_t tmp;
604 if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
605 return 0;
606 *ret = tmp;
607 return 1;
608}
609
7192777d
JK
610int git_parse_ulong(const char *value, unsigned long *ret)
611{
612 uintmax_t tmp;
613 if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
614 return 0;
615 *ret = tmp;
616 return 1;
617}
618
06bdc23b 619NORETURN
2f666581 620static void die_bad_number(const char *name, const char *value)
c1867cea 621{
2f666581
JK
622 const char *reason = errno == ERANGE ?
623 "out of range" :
624 "invalid unit";
625 if (!value)
626 value = "";
627
473166b9
LS
628 if (cf && cf->origin_type && cf->name)
629 die(_("bad numeric config value '%s' for '%s' in %s %s: %s"),
630 value, name, cf->origin_type, cf->name, reason);
8262aaa2 631 die(_("bad numeric config value '%s' for '%s': %s"), value, name, reason);
c1867cea
JK
632}
633
0b87b6e0
BD
634int git_config_int(const char *name, const char *value)
635{
42d194e9
JK
636 int ret;
637 if (!git_parse_int(value, &ret))
2f666581 638 die_bad_number(name, value);
0b87b6e0
BD
639 return ret;
640}
641
00160242
JK
642int64_t git_config_int64(const char *name, const char *value)
643{
644 int64_t ret;
645 if (!git_parse_int64(value, &ret))
646 die_bad_number(name, value);
0b87b6e0
BD
647 return ret;
648}
649
650unsigned long git_config_ulong(const char *name, const char *value)
651{
652 unsigned long ret;
653 if (!git_parse_ulong(value, &ret))
2f666581 654 die_bad_number(name, value);
0b87b6e0 655 return ret;
17712991
LT
656}
657
9a549d43 658int git_parse_maybe_bool(const char *value)
17712991
LT
659{
660 if (!value)
661 return 1;
662 if (!*value)
663 return 0;
8420ccd8
JH
664 if (!strcasecmp(value, "true")
665 || !strcasecmp(value, "yes")
666 || !strcasecmp(value, "on"))
17712991 667 return 1;
8420ccd8
JH
668 if (!strcasecmp(value, "false")
669 || !strcasecmp(value, "no")
670 || !strcasecmp(value, "off"))
17712991 671 return 0;
8420ccd8
JH
672 return -1;
673}
674
b2be2f6a
JK
675int git_config_maybe_bool(const char *name, const char *value)
676{
9a549d43 677 int v = git_parse_maybe_bool(value);
b2be2f6a
JK
678 if (0 <= v)
679 return v;
42d194e9 680 if (git_parse_int(value, &v))
db6195ef 681 return !!v;
b2be2f6a
JK
682 return -1;
683}
684
8420ccd8
JH
685int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
686{
9a549d43 687 int v = git_parse_maybe_bool(value);
8420ccd8
JH
688 if (0 <= v) {
689 *is_bool = 1;
690 return v;
691 }
a53f2ec6 692 *is_bool = 0;
c35b0b58 693 return git_config_int(name, value);
17712991
LT
694}
695
a53f2ec6
JH
696int git_config_bool(const char *name, const char *value)
697{
698 int discard;
c35b0b58 699 return !!git_config_bool_or_int(name, value, &discard);
a53f2ec6
JH
700}
701
ea5105a5
CC
702int git_config_string(const char **dest, const char *var, const char *value)
703{
704 if (!value)
705 return config_error_nonbool(var);
706 *dest = xstrdup(value);
707 return 0;
708}
709
395de250
MM
710int git_config_pathname(const char **dest, const char *var, const char *value)
711{
712 if (!value)
713 return config_error_nonbool(var);
714 *dest = expand_user_path(value);
715 if (!*dest)
8262aaa2 716 die(_("failed to expand user dir in: '%s'"), value);
395de250
MM
717 return 0;
718}
719
806e2ad7 720static int git_default_core_config(const char *var, const char *value)
17712991
LT
721{
722 /* This needs a better name */
723 if (!strcmp(var, "core.filemode")) {
724 trust_executable_bit = git_config_bool(var, value);
725 return 0;
726 }
1ce4790b
AR
727 if (!strcmp(var, "core.trustctime")) {
728 trust_ctime = git_config_bool(var, value);
729 return 0;
730 }
c1b5d738 731 if (!strcmp(var, "core.checkstat")) {
c08e4d5b
RR
732 if (!strcasecmp(value, "default"))
733 check_stat = 1;
734 else if (!strcasecmp(value, "minimal"))
735 check_stat = 0;
736 }
17712991 737
9378c161
JH
738 if (!strcmp(var, "core.quotepath")) {
739 quote_path_fully = git_config_bool(var, value);
740 return 0;
741 }
742
78a8d641
JS
743 if (!strcmp(var, "core.symlinks")) {
744 has_symlinks = git_config_bool(var, value);
745 return 0;
746 }
747
0a9b88b7
LT
748 if (!strcmp(var, "core.ignorecase")) {
749 ignore_case = git_config_bool(var, value);
750 return 0;
751 }
752
64589a03
JH
753 if (!strcmp(var, "core.attributesfile"))
754 return git_config_pathname(&git_attributes_file, var, value);
755
867ad08a
ÆAB
756 if (!strcmp(var, "core.hookspath"))
757 return git_config_pathname(&git_hooks_path, var, value);
758
7d1864ce
JH
759 if (!strcmp(var, "core.bare")) {
760 is_bare_repository_cfg = git_config_bool(var, value);
761 return 0;
762 }
763
5f73076c
JH
764 if (!strcmp(var, "core.ignorestat")) {
765 assume_unchanged = git_config_bool(var, value);
766 return 0;
767 }
768
e388c738
JH
769 if (!strcmp(var, "core.prefersymlinkrefs")) {
770 prefer_symlink_refs = git_config_bool(var, value);
f8348be3
JS
771 return 0;
772 }
773
6de08ae6
SP
774 if (!strcmp(var, "core.logallrefupdates")) {
775 log_all_ref_updates = git_config_bool(var, value);
776 return 0;
777 }
778
2f8acdb3
JH
779 if (!strcmp(var, "core.warnambiguousrefs")) {
780 warn_ambiguous_refs = git_config_bool(var, value);
781 return 0;
782 }
783
a71f09fe 784 if (!strcmp(var, "core.abbrev")) {
dce96489
LT
785 int abbrev = git_config_int(var, value);
786 if (abbrev < minimum_abbrev || abbrev > 40)
787 return -1;
788 default_abbrev = abbrev;
789 return 0;
790 }
791
960ccca6 792 if (!strcmp(var, "core.loosecompression")) {
12f6c308
JBH
793 int level = git_config_int(var, value);
794 if (level == -1)
795 level = Z_DEFAULT_COMPRESSION;
796 else if (level < 0 || level > Z_BEST_COMPRESSION)
8262aaa2 797 die(_("bad zlib compression level %d"), level);
12f6c308 798 zlib_compression_level = level;
960ccca6
DH
799 zlib_compression_seen = 1;
800 return 0;
801 }
802
803 if (!strcmp(var, "core.compression")) {
804 int level = git_config_int(var, value);
805 if (level == -1)
806 level = Z_DEFAULT_COMPRESSION;
807 else if (level < 0 || level > Z_BEST_COMPRESSION)
8262aaa2 808 die(_("bad zlib compression level %d"), level);
960ccca6
DH
809 core_compression_level = level;
810 core_compression_seen = 1;
811 if (!zlib_compression_seen)
812 zlib_compression_level = level;
12f6c308
JBH
813 return 0;
814 }
815
60bb8b14 816 if (!strcmp(var, "core.packedgitwindowsize")) {
5faaf246 817 int pgsz_x2 = getpagesize() * 2;
ebaa1bd4 818 packed_git_window_size = git_config_ulong(var, value);
5faaf246
JH
819
820 /* This value must be multiple of (pagesize * 2) */
821 packed_git_window_size /= pgsz_x2;
822 if (packed_git_window_size < 1)
823 packed_git_window_size = 1;
824 packed_git_window_size *= pgsz_x2;
60bb8b14
SP
825 return 0;
826 }
827
15366280 828 if (!strcmp(var, "core.bigfilethreshold")) {
ebaa1bd4 829 big_file_threshold = git_config_ulong(var, value);
15366280
JH
830 return 0;
831 }
832
77ccc5bb 833 if (!strcmp(var, "core.packedgitlimit")) {
ebaa1bd4 834 packed_git_limit = git_config_ulong(var, value);
77ccc5bb
SP
835 return 0;
836 }
837
18bdec11 838 if (!strcmp(var, "core.deltabasecachelimit")) {
ebaa1bd4 839 delta_base_cache_limit = git_config_ulong(var, value);
18bdec11
SP
840 return 0;
841 }
842
6c510bee 843 if (!strcmp(var, "core.autocrlf")) {
d7f46334 844 if (value && !strcasecmp(value, "input")) {
fd6cce9e 845 auto_crlf = AUTO_CRLF_INPUT;
d7f46334
LT
846 return 0;
847 }
6c510bee
LT
848 auto_crlf = git_config_bool(var, value);
849 return 0;
850 }
851
21e5ad50
SP
852 if (!strcmp(var, "core.safecrlf")) {
853 if (value && !strcasecmp(value, "warn")) {
854 safe_crlf = SAFE_CRLF_WARN;
855 return 0;
856 }
857 safe_crlf = git_config_bool(var, value);
858 return 0;
859 }
860
942e7747
EB
861 if (!strcmp(var, "core.eol")) {
862 if (value && !strcasecmp(value, "lf"))
ec70f52f 863 core_eol = EOL_LF;
942e7747 864 else if (value && !strcasecmp(value, "crlf"))
ec70f52f 865 core_eol = EOL_CRLF;
942e7747 866 else if (value && !strcasecmp(value, "native"))
ec70f52f 867 core_eol = EOL_NATIVE;
942e7747 868 else
ec70f52f 869 core_eol = EOL_UNSET;
942e7747
EB
870 return 0;
871 }
872
a97a7468
JS
873 if (!strcmp(var, "core.notesref")) {
874 notes_ref_name = xstrdup(value);
875 return 0;
876 }
877
806e2ad7
LT
878 if (!strcmp(var, "core.pager"))
879 return git_config_string(&pager_program, var, value);
880
881 if (!strcmp(var, "core.editor"))
882 return git_config_string(&editor_program, var, value);
883
eff80a9f 884 if (!strcmp(var, "core.commentchar")) {
649409b7
JK
885 if (!value)
886 return config_error_nonbool(var);
ad524f83 887 else if (!strcasecmp(value, "auto"))
84c9dc2c 888 auto_comment_line_char = 1;
ad524f83 889 else if (value[0] && !value[1]) {
649409b7 890 comment_line_char = value[0];
84c9dc2c 891 auto_comment_line_char = 0;
50b54fd7
NTND
892 } else
893 return error("core.commentChar should only be one character");
894 return 0;
eff80a9f
JH
895 }
896
d3e7da89
AK
897 if (!strcmp(var, "core.askpass"))
898 return git_config_string(&askpass_program, var, value);
899
806e2ad7 900 if (!strcmp(var, "core.excludesfile"))
395de250 901 return git_config_pathname(&excludes_file, var, value);
806e2ad7
LT
902
903 if (!strcmp(var, "core.whitespace")) {
904 if (!value)
905 return config_error_nonbool(var);
906 whitespace_rule_cfg = parse_whitespace_rule(value);
907 return 0;
908 }
909
aafe9fba
LT
910 if (!strcmp(var, "core.fsyncobjectfiles")) {
911 fsync_object_files = git_config_bool(var, value);
912 return 0;
913 }
914
671c9b7e
LT
915 if (!strcmp(var, "core.preloadindex")) {
916 core_preload_index = git_config_bool(var, value);
917 return 0;
918 }
919
348df166
JS
920 if (!strcmp(var, "core.createobject")) {
921 if (!strcmp(value, "rename"))
922 object_creation_mode = OBJECT_CREATION_USES_RENAMES;
923 else if (!strcmp(value, "link"))
924 object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
925 else
8262aaa2 926 die(_("invalid mode for object creation: %s"), value);
be66a6c4
JS
927 return 0;
928 }
929
08aefc9e
NTND
930 if (!strcmp(var, "core.sparsecheckout")) {
931 core_apply_sparse_checkout = git_config_bool(var, value);
932 return 0;
933 }
934
76759c7d
TB
935 if (!strcmp(var, "core.precomposeunicode")) {
936 precomposed_unicode = git_config_bool(var, value);
937 return 0;
938 }
939
a42643aa
JK
940 if (!strcmp(var, "core.protecthfs")) {
941 protect_hfs = git_config_bool(var, value);
942 return 0;
943 }
944
2b4c6efc
JS
945 if (!strcmp(var, "core.protectntfs")) {
946 protect_ntfs = git_config_bool(var, value);
947 return 0;
76759c7d
TB
948 }
949
f30afdab
JS
950 if (!strcmp(var, "core.hidedotfiles")) {
951 if (value && !strcasecmp(value, "dotgitonly"))
952 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
953 else
954 hide_dotfiles = git_config_bool(var, value);
955 return 0;
956 }
957
806e2ad7
LT
958 /* Add other config variables here and to Documentation/config.txt. */
959 return 0;
960}
961
1141f492 962static int git_default_i18n_config(const char *var, const char *value)
d1364529 963{
ea5105a5
CC
964 if (!strcmp(var, "i18n.commitencoding"))
965 return git_config_string(&git_commit_encoding, var, value);
d2c11a38 966
ea5105a5
CC
967 if (!strcmp(var, "i18n.logoutputencoding"))
968 return git_config_string(&git_log_output_encoding, var, value);
d2c11a38 969
1141f492
LT
970 /* Add other config variables here and to Documentation/config.txt. */
971 return 0;
972}
039bc64e 973
1141f492
LT
974static int git_default_branch_config(const char *var, const char *value)
975{
9ed36cfa
JS
976 if (!strcmp(var, "branch.autosetupmerge")) {
977 if (value && !strcasecmp(value, "always")) {
978 git_branch_track = BRANCH_TRACK_ALWAYS;
979 return 0;
980 }
981 git_branch_track = git_config_bool(var, value);
982 return 0;
983 }
c998ae9b
DS
984 if (!strcmp(var, "branch.autosetuprebase")) {
985 if (!value)
986 return config_error_nonbool(var);
987 else if (!strcmp(value, "never"))
988 autorebase = AUTOREBASE_NEVER;
989 else if (!strcmp(value, "local"))
990 autorebase = AUTOREBASE_LOCAL;
991 else if (!strcmp(value, "remote"))
992 autorebase = AUTOREBASE_REMOTE;
993 else if (!strcmp(value, "always"))
994 autorebase = AUTOREBASE_ALWAYS;
995 else
8c3ca351 996 return error("malformed value for %s", var);
c998ae9b
DS
997 return 0;
998 }
a9cc857a 999
1ab661dd 1000 /* Add other config variables here and to Documentation/config.txt. */
17712991
LT
1001 return 0;
1002}
1003
52153747
FAG
1004static int git_default_push_config(const char *var, const char *value)
1005{
1006 if (!strcmp(var, "push.default")) {
1007 if (!value)
1008 return config_error_nonbool(var);
1009 else if (!strcmp(value, "nothing"))
1010 push_default = PUSH_DEFAULT_NOTHING;
1011 else if (!strcmp(value, "matching"))
1012 push_default = PUSH_DEFAULT_MATCHING;
b55e6775
MM
1013 else if (!strcmp(value, "simple"))
1014 push_default = PUSH_DEFAULT_SIMPLE;
53c40311
JH
1015 else if (!strcmp(value, "upstream"))
1016 push_default = PUSH_DEFAULT_UPSTREAM;
1017 else if (!strcmp(value, "tracking")) /* deprecated */
1018 push_default = PUSH_DEFAULT_UPSTREAM;
52153747
FAG
1019 else if (!strcmp(value, "current"))
1020 push_default = PUSH_DEFAULT_CURRENT;
1021 else {
8c3ca351 1022 error("malformed value for %s: %s", var, value);
b55e6775
MM
1023 return error("Must be one of nothing, matching, simple, "
1024 "upstream or current.");
52153747
FAG
1025 }
1026 return 0;
1027 }
1028
1029 /* Add other config variables here and to Documentation/config.txt. */
1030 return 0;
1031}
1032
d551a488
MSO
1033static int git_default_mailmap_config(const char *var, const char *value)
1034{
1035 if (!strcmp(var, "mailmap.file"))
9352fd57 1036 return git_config_pathname(&git_mailmap_file, var, value);
08610900
JK
1037 if (!strcmp(var, "mailmap.blob"))
1038 return git_config_string(&git_mailmap_blob, var, value);
d551a488
MSO
1039
1040 /* Add other config variables here and to Documentation/config.txt. */
1041 return 0;
1042}
1043
1141f492
LT
1044int git_default_config(const char *var, const char *value, void *dummy)
1045{
59556548 1046 if (starts_with(var, "core."))
1141f492
LT
1047 return git_default_core_config(var, value);
1048
59556548 1049 if (starts_with(var, "user."))
9597921b 1050 return git_ident_config(var, value, dummy);
1141f492 1051
59556548 1052 if (starts_with(var, "i18n."))
1141f492
LT
1053 return git_default_i18n_config(var, value);
1054
59556548 1055 if (starts_with(var, "branch."))
1141f492
LT
1056 return git_default_branch_config(var, value);
1057
59556548 1058 if (starts_with(var, "push."))
52153747
FAG
1059 return git_default_push_config(var, value);
1060
59556548 1061 if (starts_with(var, "mailmap."))
d551a488
MSO
1062 return git_default_mailmap_config(var, value);
1063
59556548 1064 if (starts_with(var, "advice."))
75194438
JK
1065 return git_default_advice_config(var, value);
1066
1141f492
LT
1067 if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1068 pager_use_color = git_config_bool(var,value);
1069 return 0;
1070 }
1071
568508e7
JH
1072 if (!strcmp(var, "pack.packsizelimit")) {
1073 pack_size_limit_cfg = git_config_ulong(var, value);
1074 return 0;
1075 }
1141f492
LT
1076 /* Add other config variables here and to Documentation/config.txt. */
1077 return 0;
1078}
1079
ca4b5de2 1080/*
b2dc0945 1081 * All source specific fields in the union, die_on_error, name and the callbacks
4d8dd149 1082 * fgetc, ungetc, ftell of top need to be initialized before calling
ca4b5de2
HV
1083 * this function.
1084 */
4d8dd149 1085static int do_config_from(struct config_source *top, config_fn_t fn, void *data)
ca4b5de2
HV
1086{
1087 int ret;
1088
1089 /* push config-file parsing state stack */
1090 top->prev = cf;
1091 top->linenr = 1;
1092 top->eof = 0;
1093 strbuf_init(&top->value, 1024);
1094 strbuf_init(&top->var, 1024);
1095 cf = top;
1096
4d8dd149 1097 ret = git_parse_source(fn, data);
ca4b5de2
HV
1098
1099 /* pop config-file parsing state stack */
1100 strbuf_release(&top->value);
1101 strbuf_release(&top->var);
1102 cf = top->prev;
1103
1104 return ret;
1105}
1106
3caec73b 1107static int do_config_from_file(config_fn_t fn,
473166b9
LS
1108 const char *origin_type, const char *name, const char *path, FILE *f,
1109 void *data)
17712991 1110{
3caec73b 1111 struct config_source top;
17712991 1112
3caec73b 1113 top.u.file = f;
473166b9 1114 top.origin_type = origin_type;
3caec73b
KS
1115 top.name = name;
1116 top.path = path;
1117 top.die_on_error = 1;
1118 top.do_fgetc = config_file_fgetc;
1119 top.do_ungetc = config_file_ungetc;
1120 top.do_ftell = config_file_ftell;
924aaf3e 1121
3caec73b
KS
1122 return do_config_from(&top, fn, data);
1123}
924aaf3e 1124
3caec73b
KS
1125static int git_config_from_stdin(config_fn_t fn, void *data)
1126{
473166b9 1127 return do_config_from_file(fn, "standard input", "", NULL, stdin, data);
3caec73b
KS
1128}
1129
1130int git_config_from_file(config_fn_t fn, const char *filename, void *data)
1131{
1132 int ret = -1;
1133 FILE *f;
924aaf3e 1134
3caec73b
KS
1135 f = fopen(filename, "r");
1136 if (f) {
260d408e 1137 flockfile(f);
473166b9 1138 ret = do_config_from_file(fn, "file", filename, filename, f, data);
260d408e 1139 funlockfile(f);
17712991
LT
1140 fclose(f);
1141 }
1142 return ret;
1143}
10bea152 1144
473166b9
LS
1145int git_config_from_mem(config_fn_t fn, const char *origin_type,
1146 const char *name, const char *buf, size_t len, void *data)
1bc88819
HV
1147{
1148 struct config_source top;
1149
1150 top.u.buf.buf = buf;
1151 top.u.buf.len = len;
1152 top.u.buf.pos = 0;
473166b9 1153 top.origin_type = origin_type;
1bc88819 1154 top.name = name;
d14d4244 1155 top.path = NULL;
b2dc0945 1156 top.die_on_error = 0;
49d6cfa5
JK
1157 top.do_fgetc = config_buf_fgetc;
1158 top.do_ungetc = config_buf_ungetc;
1159 top.do_ftell = config_buf_ftell;
1bc88819
HV
1160
1161 return do_config_from(&top, fn, data);
1162}
1163
1164static int git_config_from_blob_sha1(config_fn_t fn,
1165 const char *name,
1166 const unsigned char *sha1,
1167 void *data)
1168{
1169 enum object_type type;
1170 char *buf;
1171 unsigned long size;
1172 int ret;
1173
1174 buf = read_sha1_file(sha1, &type, &size);
1175 if (!buf)
1176 return error("unable to load config blob object '%s'", name);
1177 if (type != OBJ_BLOB) {
1178 free(buf);
1179 return error("reference '%s' does not point to a blob", name);
1180 }
1181
473166b9 1182 ret = git_config_from_mem(fn, "blob", name, buf, size, data);
1bc88819
HV
1183 free(buf);
1184
1185 return ret;
1186}
1187
1188static int git_config_from_blob_ref(config_fn_t fn,
1189 const char *name,
1190 void *data)
1191{
1192 unsigned char sha1[20];
1193
1194 if (get_sha1(name, sha1) < 0)
1195 return error("unable to resolve config blob '%s'", name);
1196 return git_config_from_blob_sha1(fn, name, sha1, data);
1197}
1198
506b17b1
JS
1199const char *git_etc_gitconfig(void)
1200{
7f0e39fa 1201 static const char *system_wide;
2de9de5e
SP
1202 if (!system_wide)
1203 system_wide = system_path(ETC_GITCONFIG);
7f0e39fa 1204 return system_wide;
506b17b1
JS
1205}
1206
23b0c478
SP
1207/*
1208 * Parse environment variable 'k' as a boolean (in various
1209 * possible spellings); if missing, use the default value 'def'.
1210 */
0ef37164 1211int git_env_bool(const char *k, int def)
ab88c363
JK
1212{
1213 const char *v = getenv(k);
1214 return v ? git_config_bool(k, v) : def;
1215}
1216
23b0c478
SP
1217/*
1218 * Parse environment variable 'k' as ulong with possibly a unit
1219 * suffix; if missing, use the default value 'val'.
1220 */
1221unsigned long git_env_ulong(const char *k, unsigned long val)
1222{
1223 const char *v = getenv(k);
1224 if (v && !git_parse_ulong(v, &val))
1225 die("failed to parse %s", k);
1226 return val;
1227}
1228
ab88c363
JK
1229int git_config_system(void)
1230{
1231 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
1232}
1233
80181868 1234static int do_git_config_sequence(config_fn_t fn, void *data)
4f629539 1235{
c72ee44b 1236 int ret = 0;
509adc33
PT
1237 char *xdg_config = xdg_config_home("config");
1238 char *user_config = expand_user_path("~/.gitconfig");
80181868 1239 char *repo_config = git_pathdup("config");
5f1a63e0 1240
9acc5911 1241 current_parsing_scope = CONFIG_SCOPE_SYSTEM;
c72ee44b 1242 if (git_config_system() && !access_or_die(git_etc_gitconfig(), R_OK, 0))
dc871831
DB
1243 ret += git_config_from_file(fn, git_etc_gitconfig(),
1244 data);
5f1a63e0 1245
9acc5911 1246 current_parsing_scope = CONFIG_SCOPE_GLOBAL;
c72ee44b 1247 if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
21cf3227 1248 ret += git_config_from_file(fn, xdg_config, data);
21cf3227 1249
c72ee44b 1250 if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
21cf3227 1251 ret += git_config_from_file(fn, user_config, data);
5f1a63e0 1252
9acc5911 1253 current_parsing_scope = CONFIG_SCOPE_REPO;
c72ee44b 1254 if (repo_config && !access_or_die(repo_config, R_OK, 0))
aa387407 1255 ret += git_config_from_file(fn, repo_config, data);
8b1fa778 1256
9acc5911 1257 current_parsing_scope = CONFIG_SCOPE_CMDLINE;
c72ee44b 1258 if (git_config_from_parameters(fn, data) < 0)
8262aaa2 1259 die(_("unable to parse command-line config"));
8b1fa778 1260
9acc5911 1261 current_parsing_scope = CONFIG_SCOPE_UNKNOWN;
21cf3227
HKNN
1262 free(xdg_config);
1263 free(user_config);
80181868 1264 free(repo_config);
c72ee44b 1265 return ret;
4f629539
JH
1266}
1267
c9b5e2a5 1268int git_config_with_options(config_fn_t fn, void *data,
c8985ce0 1269 struct git_config_source *config_source,
1bc88819 1270 int respect_includes)
dbdf5854 1271{
9b25a0b5
JK
1272 struct config_include_data inc = CONFIG_INCLUDE_INIT;
1273
1274 if (respect_includes) {
1275 inc.fn = fn;
1276 inc.data = data;
1277 fn = git_config_include;
1278 data = &inc;
1279 }
dbdf5854 1280
c9b5e2a5
JK
1281 /*
1282 * If we have a specific filename, use it. Otherwise, follow the
1283 * regular lookup sequence.
1284 */
3caec73b
KS
1285 if (config_source && config_source->use_stdin)
1286 return git_config_from_stdin(fn, data);
1287 else if (config_source && config_source->file)
c8985ce0
KS
1288 return git_config_from_file(fn, config_source->file, data);
1289 else if (config_source && config_source->blob)
1290 return git_config_from_blob_ref(fn, config_source->blob, data);
c9b5e2a5 1291
80181868 1292 return do_git_config_sequence(fn, data);
dbdf5854
NTND
1293}
1294
155ef25f 1295static void git_config_raw(config_fn_t fn, void *data)
c9b5e2a5 1296{
aace4385
TA
1297 if (git_config_with_options(fn, data, NULL, 1) < 0)
1298 /*
1299 * git_config_with_options() normally returns only
c72ee44b 1300 * zero, as most errors are fatal, and
aace4385
TA
1301 * non-fatal potential errors are guarded by "if"
1302 * statements that are entered only when no error is
1303 * possible.
1304 *
1305 * If we ever encounter a non-fatal error, it means
1306 * something went really wrong and we should stop
1307 * immediately.
1308 */
3a39f61e 1309 die(_("unknown error occurred while reading the configuration files"));
c9b5e2a5
JK
1310}
1311
155ef25f 1312static void configset_iter(struct config_set *cs, config_fn_t fn, void *data)
c9b5e2a5 1313{
155ef25f
TA
1314 int i, value_index;
1315 struct string_list *values;
1316 struct config_set_element *entry;
1317 struct configset_list *list = &cs->list;
155ef25f
TA
1318
1319 for (i = 0; i < list->nr; i++) {
1320 entry = list->items[i].e;
1321 value_index = list->items[i].value_index;
1322 values = &entry->value_list;
0d44a2da
JK
1323
1324 current_config_kvi = values->items[value_index].util;
1325
1326 if (fn(entry->key, values->items[value_index].string, data) < 0)
1327 git_die_config_linenr(entry->key,
1328 current_config_kvi->filename,
1329 current_config_kvi->linenr);
1330
1331 current_config_kvi = NULL;
155ef25f
TA
1332 }
1333}
1334
1335static void git_config_check_init(void);
1336
1337void git_config(config_fn_t fn, void *data)
1338{
1339 git_config_check_init();
1340 configset_iter(&the_config_set, fn, data);
c9b5e2a5
JK
1341}
1342
3c8687a7
TA
1343static struct config_set_element *configset_find_element(struct config_set *cs, const char *key)
1344{
1345 struct config_set_element k;
1346 struct config_set_element *found_entry;
1347 char *normalized_key;
3c8687a7
TA
1348 /*
1349 * `key` may come from the user, so normalize it before using it
1350 * for querying entries from the hashmap.
1351 */
270cd9ea 1352 if (git_config_parse_key(key, &normalized_key, NULL))
3c8687a7
TA
1353 return NULL;
1354
1355 hashmap_entry_init(&k, strhash(normalized_key));
1356 k.key = normalized_key;
1357 found_entry = hashmap_get(&cs->config_hash, &k, NULL);
1358 free(normalized_key);
1359 return found_entry;
1360}
1361
1362static int configset_add_value(struct config_set *cs, const char *key, const char *value)
1363{
1364 struct config_set_element *e;
3df8fd62 1365 struct string_list_item *si;
155ef25f 1366 struct configset_list_item *l_item;
3df8fd62
TA
1367 struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
1368
3c8687a7
TA
1369 e = configset_find_element(cs, key);
1370 /*
1371 * Since the keys are being fed by git_config*() callback mechanism, they
1372 * are already normalized. So simply add them without any further munging.
1373 */
1374 if (!e) {
1375 e = xmalloc(sizeof(*e));
1376 hashmap_entry_init(e, strhash(key));
1377 e->key = xstrdup(key);
1378 string_list_init(&e->value_list, 1);
1379 hashmap_add(&cs->config_hash, e);
1380 }
8c53f071 1381 si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
155ef25f
TA
1382
1383 ALLOC_GROW(cs->list.items, cs->list.nr + 1, cs->list.alloc);
1384 l_item = &cs->list.items[cs->list.nr++];
1385 l_item->e = e;
1386 l_item->value_index = e->value_list.nr - 1;
1387
3258258f
JK
1388 if (!cf)
1389 die("BUG: configset_add_value has no source");
1390 if (cf->name) {
3df8fd62
TA
1391 kv_info->filename = strintern(cf->name);
1392 kv_info->linenr = cf->linenr;
0d44a2da 1393 kv_info->origin_type = strintern(cf->origin_type);
3df8fd62
TA
1394 } else {
1395 /* for values read from `git_config_from_parameters()` */
1396 kv_info->filename = NULL;
1397 kv_info->linenr = -1;
0d44a2da 1398 kv_info->origin_type = NULL;
3df8fd62 1399 }
9acc5911 1400 kv_info->scope = current_parsing_scope;
3df8fd62 1401 si->util = kv_info;
3c8687a7
TA
1402
1403 return 0;
1404}
1405
1406static int config_set_element_cmp(const struct config_set_element *e1,
1407 const struct config_set_element *e2, const void *unused)
1408{
1409 return strcmp(e1->key, e2->key);
1410}
1411
1412void git_configset_init(struct config_set *cs)
1413{
1414 hashmap_init(&cs->config_hash, (hashmap_cmp_fn)config_set_element_cmp, 0);
1415 cs->hash_initialized = 1;
155ef25f
TA
1416 cs->list.nr = 0;
1417 cs->list.alloc = 0;
1418 cs->list.items = NULL;
3c8687a7
TA
1419}
1420
1421void git_configset_clear(struct config_set *cs)
1422{
1423 struct config_set_element *entry;
1424 struct hashmap_iter iter;
1425 if (!cs->hash_initialized)
1426 return;
1427
1428 hashmap_iter_init(&cs->config_hash, &iter);
1429 while ((entry = hashmap_iter_next(&iter))) {
1430 free(entry->key);
3df8fd62 1431 string_list_clear(&entry->value_list, 1);
3c8687a7
TA
1432 }
1433 hashmap_free(&cs->config_hash, 1);
1434 cs->hash_initialized = 0;
155ef25f
TA
1435 free(cs->list.items);
1436 cs->list.nr = 0;
1437 cs->list.alloc = 0;
1438 cs->list.items = NULL;
3c8687a7
TA
1439}
1440
1441static int config_set_callback(const char *key, const char *value, void *cb)
1442{
1443 struct config_set *cs = cb;
1444 configset_add_value(cs, key, value);
1445 return 0;
1446}
1447
1448int git_configset_add_file(struct config_set *cs, const char *filename)
1449{
1450 return git_config_from_file(config_set_callback, filename, cs);
1451}
1452
1453int git_configset_get_value(struct config_set *cs, const char *key, const char **value)
1454{
1455 const struct string_list *values = NULL;
1456 /*
1457 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
1458 * queried key in the files of the configset, the value returned will be the last
1459 * value in the value list for that key.
1460 */
1461 values = git_configset_get_value_multi(cs, key);
1462
1463 if (!values)
1464 return 1;
1465 assert(values->nr > 0);
1466 *value = values->items[values->nr - 1].string;
1467 return 0;
1468}
1469
1470const struct string_list *git_configset_get_value_multi(struct config_set *cs, const char *key)
1471{
1472 struct config_set_element *e = configset_find_element(cs, key);
1473 return e ? &e->value_list : NULL;
1474}
1475
1476int git_configset_get_string_const(struct config_set *cs, const char *key, const char **dest)
1477{
1478 const char *value;
1479 if (!git_configset_get_value(cs, key, &value))
1480 return git_config_string(dest, key, value);
1481 else
1482 return 1;
1483}
1484
1485int git_configset_get_string(struct config_set *cs, const char *key, char **dest)
1486{
1487 return git_configset_get_string_const(cs, key, (const char **)dest);
1488}
1489
1490int git_configset_get_int(struct config_set *cs, const char *key, int *dest)
1491{
1492 const char *value;
1493 if (!git_configset_get_value(cs, key, &value)) {
1494 *dest = git_config_int(key, value);
1495 return 0;
1496 } else
1497 return 1;
1498}
1499
1500int git_configset_get_ulong(struct config_set *cs, const char *key, unsigned long *dest)
1501{
1502 const char *value;
1503 if (!git_configset_get_value(cs, key, &value)) {
1504 *dest = git_config_ulong(key, value);
1505 return 0;
1506 } else
1507 return 1;
1508}
1509
1510int git_configset_get_bool(struct config_set *cs, const char *key, int *dest)
1511{
1512 const char *value;
1513 if (!git_configset_get_value(cs, key, &value)) {
1514 *dest = git_config_bool(key, value);
1515 return 0;
1516 } else
1517 return 1;
1518}
1519
1520int git_configset_get_bool_or_int(struct config_set *cs, const char *key,
1521 int *is_bool, int *dest)
1522{
1523 const char *value;
1524 if (!git_configset_get_value(cs, key, &value)) {
1525 *dest = git_config_bool_or_int(key, value, is_bool);
1526 return 0;
1527 } else
1528 return 1;
1529}
1530
1531int git_configset_get_maybe_bool(struct config_set *cs, const char *key, int *dest)
1532{
1533 const char *value;
1534 if (!git_configset_get_value(cs, key, &value)) {
1535 *dest = git_config_maybe_bool(key, value);
1536 if (*dest == -1)
1537 return -1;
1538 return 0;
1539 } else
1540 return 1;
1541}
1542
1543int git_configset_get_pathname(struct config_set *cs, const char *key, const char **dest)
1544{
1545 const char *value;
1546 if (!git_configset_get_value(cs, key, &value))
1547 return git_config_pathname(dest, key, value);
1548 else
1549 return 1;
1550}
1551
1552static void git_config_check_init(void)
1553{
1554 if (the_config_set.hash_initialized)
1555 return;
1556 git_configset_init(&the_config_set);
155ef25f 1557 git_config_raw(config_set_callback, &the_config_set);
3c8687a7
TA
1558}
1559
1560void git_config_clear(void)
1561{
1562 if (!the_config_set.hash_initialized)
1563 return;
1564 git_configset_clear(&the_config_set);
1565}
1566
1567int git_config_get_value(const char *key, const char **value)
1568{
1569 git_config_check_init();
1570 return git_configset_get_value(&the_config_set, key, value);
1571}
1572
1573const struct string_list *git_config_get_value_multi(const char *key)
1574{
1575 git_config_check_init();
1576 return git_configset_get_value_multi(&the_config_set, key);
1577}
1578
1579int git_config_get_string_const(const char *key, const char **dest)
1580{
5a80e97c 1581 int ret;
3c8687a7 1582 git_config_check_init();
5a80e97c
TA
1583 ret = git_configset_get_string_const(&the_config_set, key, dest);
1584 if (ret < 0)
1585 git_die_config(key, NULL);
1586 return ret;
3c8687a7
TA
1587}
1588
1589int git_config_get_string(const char *key, char **dest)
1590{
1591 git_config_check_init();
1592 return git_config_get_string_const(key, (const char **)dest);
1593}
1594
1595int git_config_get_int(const char *key, int *dest)
1596{
1597 git_config_check_init();
1598 return git_configset_get_int(&the_config_set, key, dest);
1599}
1600
1601int git_config_get_ulong(const char *key, unsigned long *dest)
1602{
1603 git_config_check_init();
1604 return git_configset_get_ulong(&the_config_set, key, dest);
1605}
1606
1607int git_config_get_bool(const char *key, int *dest)
1608{
1609 git_config_check_init();
1610 return git_configset_get_bool(&the_config_set, key, dest);
1611}
1612
1613int git_config_get_bool_or_int(const char *key, int *is_bool, int *dest)
1614{
1615 git_config_check_init();
1616 return git_configset_get_bool_or_int(&the_config_set, key, is_bool, dest);
1617}
1618
1619int git_config_get_maybe_bool(const char *key, int *dest)
1620{
1621 git_config_check_init();
1622 return git_configset_get_maybe_bool(&the_config_set, key, dest);
1623}
1624
1625int git_config_get_pathname(const char *key, const char **dest)
1626{
5a80e97c 1627 int ret;
3c8687a7 1628 git_config_check_init();
5a80e97c
TA
1629 ret = git_configset_get_pathname(&the_config_set, key, dest);
1630 if (ret < 0)
1631 git_die_config(key, NULL);
1632 return ret;
1633}
1634
435ec090
CC
1635int git_config_get_untracked_cache(void)
1636{
1637 int val = -1;
1638 const char *v;
1639
dae6c322
CC
1640 /* Hack for test programs like test-dump-untracked-cache */
1641 if (ignore_untracked_cache_config)
1642 return -1;
1643
435ec090
CC
1644 if (!git_config_get_maybe_bool("core.untrackedcache", &val))
1645 return val;
1646
1647 if (!git_config_get_value("core.untrackedcache", &v)) {
1648 if (!strcasecmp(v, "keep"))
1649 return -1;
1650
1651 error("unknown core.untrackedCache value '%s'; "
1652 "using 'keep' default value", v);
1653 return -1;
1654 }
1655
1656 return -1; /* default value */
1657}
1658
5a80e97c
TA
1659NORETURN
1660void git_die_config_linenr(const char *key, const char *filename, int linenr)
1661{
1662 if (!filename)
1663 die(_("unable to parse '%s' from command-line config"), key);
1664 else
1665 die(_("bad config variable '%s' in file '%s' at line %d"),
1666 key, filename, linenr);
1667}
1668
1669NORETURN __attribute__((format(printf, 2, 3)))
1670void git_die_config(const char *key, const char *err, ...)
1671{
1672 const struct string_list *values;
1673 struct key_value_info *kv_info;
1674
1675 if (err) {
1676 va_list params;
1677 va_start(params, err);
1678 vreportf("error: ", err, params);
1679 va_end(params);
1680 }
1681 values = git_config_get_value_multi(key);
1682 kv_info = values->items[values->nr - 1].util;
1683 git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
3c8687a7
TA
1684}
1685
10bea152
JS
1686/*
1687 * Find all the stuff for git_config_set() below.
1688 */
4ddba79d 1689
10bea152
JS
1690static struct {
1691 int baselen;
4b25d091 1692 char *key;
f98d863d 1693 int do_not_match;
4b25d091 1694 regex_t *value_regex;
4ddba79d 1695 int multi_replace;
83786fa4
TR
1696 size_t *offset;
1697 unsigned int offset_alloc;
10bea152
JS
1698 enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
1699 int seen;
1700} store;
1701
4b25d091 1702static int matches(const char *key, const char *value)
f98d863d 1703{
c1063be2
JK
1704 if (strcmp(key, store.key))
1705 return 0; /* not ours */
1706 if (!store.value_regex)
1707 return 1; /* always matches */
1708 if (store.value_regex == CONFIG_REGEX_NONE)
1709 return 0; /* never matches */
1710
1711 return store.do_not_match ^
1712 (value && !regexec(store.value_regex, value, 0, NULL, 0));
f98d863d
JS
1713}
1714
4b25d091 1715static int store_aux(const char *key, const char *value, void *cb)
10bea152 1716{
ae9ee41d
JH
1717 const char *ep;
1718 size_t section_len;
1719
10bea152
JS
1720 switch (store.state) {
1721 case KEY_SEEN:
f98d863d 1722 if (matches(key, value)) {
4ddba79d 1723 if (store.seen == 1 && store.multi_replace == 0) {
8262aaa2 1724 warning(_("%s has multiple values"), key);
10bea152 1725 }
4ddba79d 1726
83786fa4
TR
1727 ALLOC_GROW(store.offset, store.seen + 1,
1728 store.offset_alloc);
1729
49d6cfa5 1730 store.offset[store.seen] = cf->do_ftell(cf);
10bea152
JS
1731 store.seen++;
1732 }
1733 break;
1734 case SECTION_SEEN:
ae9ee41d
JH
1735 /*
1736 * What we are looking for is in store.key (both
1737 * section and var), and its section part is baselen
1738 * long. We found key (again, both section and var).
1739 * We would want to know if this key is in the same
1740 * section as what we are looking for. We already
1741 * know we are in the same section as what should
1742 * hold store.key.
1743 */
1744 ep = strrchr(key, '.');
1745 section_len = ep - key;
1746
1747 if ((section_len != store.baselen) ||
1748 memcmp(key, store.key, section_len+1)) {
10bea152
JS
1749 store.state = SECTION_END_SEEN;
1750 break;
ae9ee41d
JH
1751 }
1752
1753 /*
1754 * Do not increment matches: this is no match, but we
1755 * just made sure we are in the desired section.
1756 */
83786fa4
TR
1757 ALLOC_GROW(store.offset, store.seen + 1,
1758 store.offset_alloc);
49d6cfa5 1759 store.offset[store.seen] = cf->do_ftell(cf);
10bea152
JS
1760 /* fallthru */
1761 case SECTION_END_SEEN:
1762 case START:
f98d863d 1763 if (matches(key, value)) {
83786fa4
TR
1764 ALLOC_GROW(store.offset, store.seen + 1,
1765 store.offset_alloc);
49d6cfa5 1766 store.offset[store.seen] = cf->do_ftell(cf);
10bea152
JS
1767 store.state = KEY_SEEN;
1768 store.seen++;
d14f7764
LT
1769 } else {
1770 if (strrchr(key, '.') - key == store.baselen &&
bdf0ef08 1771 !strncmp(key, store.key, store.baselen)) {
93ddef3e 1772 store.state = SECTION_SEEN;
83786fa4
TR
1773 ALLOC_GROW(store.offset,
1774 store.seen + 1,
1775 store.offset_alloc);
49d6cfa5 1776 store.offset[store.seen] = cf->do_ftell(cf);
d14f7764 1777 }
bdf0ef08 1778 }
10bea152
JS
1779 }
1780 return 0;
1781}
1782
64c0d71c 1783static int write_error(const char *filename)
480c9e52 1784{
64c0d71c 1785 error("failed to write new configuration file %s", filename);
480c9e52
AW
1786
1787 /* Same error code as "failed to rename". */
1788 return 4;
1789}
1790
4b25d091 1791static int store_write_section(int fd, const char *key)
10bea152 1792{
cb891a59
KH
1793 const char *dot;
1794 int i, success;
f285a2d7 1795 struct strbuf sb = STRBUF_INIT;
d14f7764 1796
cb891a59 1797 dot = memchr(key, '.', store.baselen);
d14f7764 1798 if (dot) {
cb891a59
KH
1799 strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
1800 for (i = dot - key + 1; i < store.baselen; i++) {
e5c349ba 1801 if (key[i] == '"' || key[i] == '\\')
cb891a59
KH
1802 strbuf_addch(&sb, '\\');
1803 strbuf_addch(&sb, key[i]);
d14f7764 1804 }
cb891a59
KH
1805 strbuf_addstr(&sb, "\"]\n");
1806 } else {
1807 strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
d14f7764
LT
1808 }
1809
cb891a59
KH
1810 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1811 strbuf_release(&sb);
480c9e52 1812
cb891a59 1813 return success;
10bea152
JS
1814}
1815
4b25d091 1816static int store_write_pair(int fd, const char *key, const char *value)
10bea152 1817{
cb891a59
KH
1818 int i, success;
1819 int length = strlen(key + store.baselen + 1);
1820 const char *quote = "";
f285a2d7 1821 struct strbuf sb = STRBUF_INIT;
cdd4fb15 1822
6281f394
JM
1823 /*
1824 * Check to see if the value needs to be surrounded with a dq pair.
1825 * Note that problematic characters are always backslash-quoted; this
1826 * check is about not losing leading or trailing SP and strings that
1827 * follow beginning-of-comment characters (i.e. ';' and '#') by the
1828 * configuration parser.
1829 */
cdd4fb15 1830 if (value[0] == ' ')
cb891a59 1831 quote = "\"";
cdd4fb15
BG
1832 for (i = 0; value[i]; i++)
1833 if (value[i] == ';' || value[i] == '#')
cb891a59
KH
1834 quote = "\"";
1835 if (i && value[i - 1] == ' ')
1836 quote = "\"";
1837
cb891a59
KH
1838 strbuf_addf(&sb, "\t%.*s = %s",
1839 length, key + store.baselen + 1, quote);
10bea152 1840
10bea152
JS
1841 for (i = 0; value[i]; i++)
1842 switch (value[i]) {
480c9e52 1843 case '\n':
cb891a59 1844 strbuf_addstr(&sb, "\\n");
480c9e52
AW
1845 break;
1846 case '\t':
cb891a59 1847 strbuf_addstr(&sb, "\\t");
480c9e52
AW
1848 break;
1849 case '"':
1850 case '\\':
cb891a59 1851 strbuf_addch(&sb, '\\');
480c9e52 1852 default:
cb891a59 1853 strbuf_addch(&sb, value[i]);
480c9e52
AW
1854 break;
1855 }
cb891a59
KH
1856 strbuf_addf(&sb, "%s\n", quote);
1857
1858 success = write_in_full(fd, sb.buf, sb.len) == sb.len;
1859 strbuf_release(&sb);
1860
1861 return success;
10bea152
JS
1862}
1863
4b25d091
FC
1864static ssize_t find_beginning_of_line(const char *contents, size_t size,
1865 size_t offset_, int *found_bracket)
4ddba79d 1866{
dc49cd76
SP
1867 size_t equal_offset = size, bracket_offset = size;
1868 ssize_t offset;
4ddba79d 1869
7a31cc0f 1870contline:
a6080a0a 1871 for (offset = offset_-2; offset > 0
4ddba79d
JS
1872 && contents[offset] != '\n'; offset--)
1873 switch (contents[offset]) {
1874 case '=': equal_offset = offset; break;
1875 case ']': bracket_offset = offset; break;
1876 }
7a31cc0f
FL
1877 if (offset > 0 && contents[offset-1] == '\\') {
1878 offset_ = offset;
1879 goto contline;
1880 }
4ddba79d
JS
1881 if (bracket_offset < equal_offset) {
1882 *found_bracket = 1;
1883 offset = bracket_offset+1;
1884 } else
1885 offset++;
1886
1887 return offset;
1888}
1889
30598ad0
PS
1890int git_config_set_in_file_gently(const char *config_filename,
1891 const char *key, const char *value)
5ec31182 1892{
30598ad0 1893 return git_config_set_multivar_in_file_gently(config_filename, key, value, NULL, 0);
5ec31182
RR
1894}
1895
3d180648
PS
1896void git_config_set_in_file(const char *config_filename,
1897 const char *key, const char *value)
10bea152 1898{
3d180648 1899 git_config_set_multivar_in_file(config_filename, key, value, NULL, 0);
b4c8aba6
PS
1900}
1901
30598ad0 1902int git_config_set_gently(const char *key, const char *value)
10bea152 1903{
30598ad0 1904 return git_config_set_multivar_gently(key, value, NULL, 0);
10bea152
JS
1905}
1906
3d180648 1907void git_config_set(const char *key, const char *value)
b4c8aba6 1908{
3d180648 1909 git_config_set_multivar(key, value, NULL, 0);
10bea152
JS
1910}
1911
b09c53a3
LP
1912/*
1913 * Auxiliary function to sanity-check and split the key into the section
1914 * identifier and variable name.
1915 *
1916 * Returns 0 on success, -1 when there is an invalid character in the key and
1917 * -2 if there is no section name in the key.
1918 *
1919 * store_key - pointer to char* which will hold a copy of the key with
1920 * lowercase section and variable name
1921 * baselen - pointer to int which will hold the length of the
1922 * section + subsection part, can be NULL
1923 */
9e9de18f 1924static int git_config_parse_key_1(const char *key, char **store_key, int *baselen_, int quiet)
b09c53a3
LP
1925{
1926 int i, dot, baselen;
1927 const char *last_dot = strrchr(key, '.');
1928
1929 /*
1930 * Since "key" actually contains the section name and the real
1931 * key name separated by a dot, we have to know where the dot is.
1932 */
1933
2169ddc0 1934 if (last_dot == NULL || last_dot == key) {
9e9de18f
JK
1935 if (!quiet)
1936 error("key does not contain a section: %s", key);
7a397419 1937 return -CONFIG_NO_SECTION_OR_NAME;
b09c53a3
LP
1938 }
1939
2169ddc0 1940 if (!last_dot[1]) {
9e9de18f
JK
1941 if (!quiet)
1942 error("key does not contain variable name: %s", key);
7a397419 1943 return -CONFIG_NO_SECTION_OR_NAME;
2169ddc0
LP
1944 }
1945
b09c53a3
LP
1946 baselen = last_dot - key;
1947 if (baselen_)
1948 *baselen_ = baselen;
1949
1950 /*
1951 * Validate the key and while at it, lower case it for matching.
1952 */
9e9de18f 1953 if (store_key)
3733e694 1954 *store_key = xmallocz(strlen(key));
b09c53a3
LP
1955
1956 dot = 0;
1957 for (i = 0; key[i]; i++) {
1958 unsigned char c = key[i];
1959 if (c == '.')
1960 dot = 1;
1961 /* Leave the extended basename untouched.. */
1962 if (!dot || i > baselen) {
1963 if (!iskeychar(c) ||
1964 (i == baselen + 1 && !isalpha(c))) {
9e9de18f
JK
1965 if (!quiet)
1966 error("invalid key: %s", key);
b09c53a3
LP
1967 goto out_free_ret_1;
1968 }
1969 c = tolower(c);
1970 } else if (c == '\n') {
9e9de18f
JK
1971 if (!quiet)
1972 error("invalid key (newline): %s", key);
b09c53a3
LP
1973 goto out_free_ret_1;
1974 }
9e9de18f
JK
1975 if (store_key)
1976 (*store_key)[i] = c;
b09c53a3 1977 }
b09c53a3
LP
1978
1979 return 0;
1980
1981out_free_ret_1:
9e9de18f
JK
1982 if (store_key) {
1983 free(*store_key);
1984 *store_key = NULL;
1985 }
7a397419 1986 return -CONFIG_INVALID_KEY;
b09c53a3
LP
1987}
1988
9e9de18f
JK
1989int git_config_parse_key(const char *key, char **store_key, int *baselen)
1990{
1991 return git_config_parse_key_1(key, store_key, baselen, 0);
1992}
1993
1994int git_config_key_is_valid(const char *key)
1995{
1996 return !git_config_parse_key_1(key, NULL, NULL, 1);
1997}
1998
10bea152
JS
1999/*
2000 * If value==NULL, unset in (remove from) config,
2001 * if value_regex!=NULL, disregard key/value pairs where value does not match.
c1063be2
JK
2002 * if value_regex==CONFIG_REGEX_NONE, do not match any existing values
2003 * (only add a new one)
4ddba79d
JS
2004 * if multi_replace==0, nothing, or only one matching key/value is replaced,
2005 * else all matching key/values (regardless how many) are removed,
2006 * before the new pair is written.
10bea152
JS
2007 *
2008 * Returns 0 on success.
2009 *
2010 * This function does this:
2011 *
2012 * - it locks the config file by creating ".git/config.lock"
2013 *
2014 * - it then parses the config using store_aux() as validator to find
2015 * the position on the key/value pair to replace. If it is to be unset,
2016 * it must be found exactly once.
2017 *
2018 * - the config file is mmap()ed and the part before the match (if any) is
2019 * written to the lock file, then the changed part and the rest.
2020 *
2021 * - the config file is removed and the lock file rename()d to it.
2022 *
2023 */
30598ad0
PS
2024int git_config_set_multivar_in_file_gently(const char *config_filename,
2025 const char *key, const char *value,
2026 const char *value_regex,
2027 int multi_replace)
10bea152 2028{
54d160ec 2029 int fd = -1, in_fd = -1;
dafc88b1 2030 int ret;
6cbf973c 2031 struct lock_file *lock = NULL;
0a5f5759 2032 char *filename_buf = NULL;
3a1b3126
JK
2033 char *contents = NULL;
2034 size_t contents_sz;
4ddba79d 2035
b09c53a3
LP
2036 /* parse-key returns negative; flip the sign to feed exit(3) */
2037 ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
2038 if (ret)
dafc88b1 2039 goto out_free;
b17e659d
JS
2040
2041 store.multi_replace = multi_replace;
10bea152 2042
0a5f5759
JK
2043 if (!config_filename)
2044 config_filename = filename_buf = git_pathdup("config");
10bea152
JS
2045
2046 /*
6cbf973c 2047 * The lock serves a purpose in addition to locking: the new
10bea152
JS
2048 * contents of .git/config will be written into it.
2049 */
f1064f6b 2050 lock = xcalloc(1, sizeof(struct lock_file));
6cbf973c
BS
2051 fd = hold_lock_file_for_update(lock, config_filename, 0);
2052 if (fd < 0) {
f0658ec9 2053 error_errno("could not lock config file %s", config_filename);
10bea152 2054 free(store.key);
7a397419 2055 ret = CONFIG_NO_LOCK;
dafc88b1 2056 goto out_free;
10bea152
JS
2057 }
2058
2059 /*
2060 * If .git/config does not exist yet, write a minimal version.
2061 */
88fb958b
AR
2062 in_fd = open(config_filename, O_RDONLY);
2063 if ( in_fd < 0 ) {
10bea152
JS
2064 free(store.key);
2065
88fb958b 2066 if ( ENOENT != errno ) {
f0658ec9 2067 error_errno("opening %s", config_filename);
7a397419 2068 ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
dafc88b1 2069 goto out_free;
88fb958b 2070 }
10bea152
JS
2071 /* if nothing to unset, error out */
2072 if (value == NULL) {
7a397419 2073 ret = CONFIG_NOTHING_SET;
dafc88b1 2074 goto out_free;
10bea152
JS
2075 }
2076
4b25d091 2077 store.key = (char *)key;
480c9e52 2078 if (!store_write_section(fd, key) ||
93c1e079
JH
2079 !store_write_pair(fd, key, value))
2080 goto write_err_out;
2081 } else {
88fb958b 2082 struct stat st;
3a1b3126 2083 size_t copy_begin, copy_end;
dc49cd76 2084 int i, new_line = 0;
10bea152
JS
2085
2086 if (value_regex == NULL)
2087 store.value_regex = NULL;
c1063be2
JK
2088 else if (value_regex == CONFIG_REGEX_NONE)
2089 store.value_regex = CONFIG_REGEX_NONE;
10bea152 2090 else {
f98d863d
JS
2091 if (value_regex[0] == '!') {
2092 store.do_not_match = 1;
2093 value_regex++;
2094 } else
2095 store.do_not_match = 0;
2096
2d7320d0 2097 store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
10bea152
JS
2098 if (regcomp(store.value_regex, value_regex,
2099 REG_EXTENDED)) {
64c0d71c 2100 error("invalid pattern: %s", value_regex);
10bea152 2101 free(store.value_regex);
7a397419 2102 ret = CONFIG_INVALID_PATTERN;
dafc88b1 2103 goto out_free;
10bea152
JS
2104 }
2105 }
2106
83786fa4 2107 ALLOC_GROW(store.offset, 1, store.offset_alloc);
4ddba79d 2108 store.offset[0] = 0;
10bea152
JS
2109 store.state = START;
2110 store.seen = 0;
2111
2112 /*
2113 * After this, store.offset will contain the *end* offset
2114 * of the last match, or remain at 0 if no match was found.
2115 * As a side effect, we make sure to transform only a valid
2116 * existing config file.
2117 */
ef90d6d4 2118 if (git_config_from_file(store_aux, config_filename, NULL)) {
64c0d71c 2119 error("invalid config file %s", config_filename);
10bea152 2120 free(store.key);
c1063be2
JK
2121 if (store.value_regex != NULL &&
2122 store.value_regex != CONFIG_REGEX_NONE) {
10bea152
JS
2123 regfree(store.value_regex);
2124 free(store.value_regex);
2125 }
7a397419 2126 ret = CONFIG_INVALID_FILE;
dafc88b1 2127 goto out_free;
10bea152
JS
2128 }
2129
2130 free(store.key);
c1063be2
JK
2131 if (store.value_regex != NULL &&
2132 store.value_regex != CONFIG_REGEX_NONE) {
10bea152
JS
2133 regfree(store.value_regex);
2134 free(store.value_regex);
2135 }
2136
4ddba79d
JS
2137 /* if nothing to unset, or too many matches, error out */
2138 if ((store.seen == 0 && value == NULL) ||
2139 (store.seen > 1 && multi_replace == 0)) {
7a397419 2140 ret = CONFIG_NOTHING_SET;
dafc88b1 2141 goto out_free;
10bea152
JS
2142 }
2143
88fb958b 2144 fstat(in_fd, &st);
dc49cd76 2145 contents_sz = xsize_t(st.st_size);
1570856b
JK
2146 contents = xmmap_gently(NULL, contents_sz, PROT_READ,
2147 MAP_PRIVATE, in_fd, 0);
2148 if (contents == MAP_FAILED) {
0e8771f1
JK
2149 if (errno == ENODEV && S_ISDIR(st.st_mode))
2150 errno = EISDIR;
f0658ec9 2151 error_errno("unable to mmap '%s'", config_filename);
1570856b
JK
2152 ret = CONFIG_INVALID_FILE;
2153 contents = NULL;
2154 goto out_free;
2155 }
10bea152 2156 close(in_fd);
54d160ec 2157 in_fd = -1;
10bea152 2158
b4fb09e4 2159 if (chmod(get_lock_file_path(lock), st.st_mode & 07777) < 0) {
f0658ec9 2160 error_errno("chmod on %s failed", get_lock_file_path(lock));
daa22c6f
EW
2161 ret = CONFIG_NO_WRITE;
2162 goto out_free;
2163 }
2164
4ddba79d
JS
2165 if (store.seen == 0)
2166 store.seen = 1;
2167
2168 for (i = 0, copy_begin = 0; i < store.seen; i++) {
2169 if (store.offset[i] == 0) {
dc49cd76 2170 store.offset[i] = copy_end = contents_sz;
4ddba79d
JS
2171 } else if (store.state != KEY_SEEN) {
2172 copy_end = store.offset[i];
10bea152 2173 } else
4ddba79d 2174 copy_end = find_beginning_of_line(
dc49cd76 2175 contents, contents_sz,
4ddba79d
JS
2176 store.offset[i]-2, &new_line);
2177
02e5ba4a
JK
2178 if (copy_end > 0 && contents[copy_end-1] != '\n')
2179 new_line = 1;
2180
4ddba79d
JS
2181 /* write the first part of the config */
2182 if (copy_end > copy_begin) {
93c1e079
JH
2183 if (write_in_full(fd, contents + copy_begin,
2184 copy_end - copy_begin) <
2185 copy_end - copy_begin)
2186 goto write_err_out;
2187 if (new_line &&
2b7ca830 2188 write_str_in_full(fd, "\n") != 1)
93c1e079 2189 goto write_err_out;
4ddba79d
JS
2190 }
2191 copy_begin = store.offset[i];
10bea152
JS
2192 }
2193
10bea152
JS
2194 /* write the pair (value == NULL means unset) */
2195 if (value != NULL) {
93c1e079
JH
2196 if (store.state == START) {
2197 if (!store_write_section(fd, key))
2198 goto write_err_out;
480c9e52 2199 }
93c1e079
JH
2200 if (!store_write_pair(fd, key, value))
2201 goto write_err_out;
10bea152
JS
2202 }
2203
2204 /* write the rest of the config */
dc49cd76 2205 if (copy_begin < contents_sz)
93c1e079 2206 if (write_in_full(fd, contents + copy_begin,
dc49cd76
SP
2207 contents_sz - copy_begin) <
2208 contents_sz - copy_begin)
93c1e079 2209 goto write_err_out;
7a64592c
KB
2210
2211 munmap(contents, contents_sz);
2212 contents = NULL;
10bea152
JS
2213 }
2214
4ed7cd3a 2215 if (commit_lock_file(lock) < 0) {
f0658ec9 2216 error_errno("could not write config file %s", config_filename);
7a397419 2217 ret = CONFIG_NO_WRITE;
e831855e 2218 lock = NULL;
dafc88b1 2219 goto out_free;
10bea152
JS
2220 }
2221
6cbf973c
BS
2222 /*
2223 * lock is committed, so don't try to roll it back below.
2224 * NOTE: Since lockfile.c keeps a linked list of all created
2225 * lock_file structures, it isn't safe to free(lock). It's
2226 * better to just leave it hanging around.
2227 */
2228 lock = NULL;
dafc88b1
SH
2229 ret = 0;
2230
3c8687a7
TA
2231 /* Invalidate the config cache */
2232 git_config_clear();
2233
dafc88b1 2234out_free:
6cbf973c
BS
2235 if (lock)
2236 rollback_lock_file(lock);
0a5f5759 2237 free(filename_buf);
3a1b3126
JK
2238 if (contents)
2239 munmap(contents, contents_sz);
54d160ec
SS
2240 if (in_fd >= 0)
2241 close(in_fd);
dafc88b1 2242 return ret;
93c1e079
JH
2243
2244write_err_out:
b4fb09e4 2245 ret = write_error(get_lock_file_path(lock));
93c1e079
JH
2246 goto out_free;
2247
10bea152
JS
2248}
2249
3d180648
PS
2250void git_config_set_multivar_in_file(const char *config_filename,
2251 const char *key, const char *value,
2252 const char *value_regex, int multi_replace)
b4c8aba6 2253{
1cae428e
JK
2254 if (!git_config_set_multivar_in_file_gently(config_filename, key, value,
2255 value_regex, multi_replace))
2256 return;
2257 if (value)
8c3ca351 2258 die(_("could not set '%s' to '%s'"), key, value);
1cae428e
JK
2259 else
2260 die(_("could not unset '%s'"), key);
b4c8aba6
PS
2261}
2262
30598ad0
PS
2263int git_config_set_multivar_gently(const char *key, const char *value,
2264 const char *value_regex, int multi_replace)
5ec31182 2265{
30598ad0
PS
2266 return git_config_set_multivar_in_file_gently(NULL, key, value, value_regex,
2267 multi_replace);
5ec31182
RR
2268}
2269
3d180648
PS
2270void git_config_set_multivar(const char *key, const char *value,
2271 const char *value_regex, int multi_replace)
5ec31182 2272{
3d180648
PS
2273 git_config_set_multivar_in_file(NULL, key, value, value_regex,
2274 multi_replace);
5ec31182
RR
2275}
2276
118f8b24
PB
2277static int section_name_match (const char *buf, const char *name)
2278{
2279 int i = 0, j = 0, dot = 0;
a4c0d463
AV
2280 if (buf[i] != '[')
2281 return 0;
2282 for (i = 1; buf[i] && buf[i] != ']'; i++) {
118f8b24
PB
2283 if (!dot && isspace(buf[i])) {
2284 dot = 1;
2285 if (name[j++] != '.')
2286 break;
2287 for (i++; isspace(buf[i]); i++)
2288 ; /* do nothing */
2289 if (buf[i] != '"')
2290 break;
2291 continue;
2292 }
2293 if (buf[i] == '\\' && dot)
2294 i++;
2295 else if (buf[i] == '"' && dot) {
2296 for (i++; isspace(buf[i]); i++)
2297 ; /* do_nothing */
2298 break;
2299 }
2300 if (buf[i] != name[j++])
2301 break;
2302 }
a4c0d463
AV
2303 if (buf[i] == ']' && name[j] == 0) {
2304 /*
2305 * We match, now just find the right length offset by
2306 * gobbling up any whitespace after it, as well
2307 */
2308 i++;
2309 for (; buf[i] && isspace(buf[i]); i++)
2310 ; /* do nothing */
2311 return i;
2312 }
2313 return 0;
118f8b24
PB
2314}
2315
94a35b1a
JK
2316static int section_name_is_ok(const char *name)
2317{
2318 /* Empty section names are bogus. */
2319 if (!*name)
2320 return 0;
2321
2322 /*
2323 * Before a dot, we must be alphanumeric or dash. After the first dot,
2324 * anything goes, so we can stop checking.
2325 */
2326 for (; *name && *name != '.'; name++)
2327 if (*name != '-' && !isalnum(*name))
2328 return 0;
2329 return 1;
2330}
2331
118f8b24 2332/* if new_name == NULL, the section is removed instead */
42bd39b5
JK
2333int git_config_rename_section_in_file(const char *config_filename,
2334 const char *old_name, const char *new_name)
0667fcfb 2335{
118f8b24 2336 int ret = 0, remove = 0;
42bd39b5 2337 char *filename_buf = NULL;
94a35b1a 2338 struct lock_file *lock;
0667fcfb
JS
2339 int out_fd;
2340 char buf[1024];
924aaf3e 2341 FILE *config_file;
daa22c6f 2342 struct stat st;
0667fcfb 2343
94a35b1a
JK
2344 if (new_name && !section_name_is_ok(new_name)) {
2345 ret = error("invalid section name: %s", new_name);
2346 goto out;
2347 }
2348
42bd39b5
JK
2349 if (!config_filename)
2350 config_filename = filename_buf = git_pathdup("config");
2351
f1064f6b 2352 lock = xcalloc(1, sizeof(struct lock_file));
0667fcfb 2353 out_fd = hold_lock_file_for_update(lock, config_filename, 0);
fc1905bb 2354 if (out_fd < 0) {
64c0d71c 2355 ret = error("could not lock config file %s", config_filename);
fc1905bb
JH
2356 goto out;
2357 }
0667fcfb 2358
fc1905bb 2359 if (!(config_file = fopen(config_filename, "rb"))) {
01ebb9dc
GB
2360 /* no config file means nothing to rename, no error */
2361 goto unlock_and_out;
fc1905bb 2362 }
0667fcfb 2363
daa22c6f
EW
2364 fstat(fileno(config_file), &st);
2365
b4fb09e4 2366 if (chmod(get_lock_file_path(lock), st.st_mode & 07777) < 0) {
f0658ec9
NTND
2367 ret = error_errno("chmod on %s failed",
2368 get_lock_file_path(lock));
daa22c6f
EW
2369 goto out;
2370 }
2371
0667fcfb
JS
2372 while (fgets(buf, sizeof(buf), config_file)) {
2373 int i;
480c9e52 2374 int length;
9a5abfc7 2375 char *output = buf;
0667fcfb
JS
2376 for (i = 0; buf[i] && isspace(buf[i]); i++)
2377 ; /* do nothing */
2378 if (buf[i] == '[') {
2379 /* it's a section */
a4c0d463
AV
2380 int offset = section_name_match(&buf[i], old_name);
2381 if (offset > 0) {
118f8b24
PB
2382 ret++;
2383 if (new_name == NULL) {
2384 remove = 1;
0667fcfb
JS
2385 continue;
2386 }
0667fcfb 2387 store.baselen = strlen(new_name);
480c9e52 2388 if (!store_write_section(out_fd, new_name)) {
b4fb09e4 2389 ret = write_error(get_lock_file_path(lock));
480c9e52
AW
2390 goto out;
2391 }
9a5abfc7
AV
2392 /*
2393 * We wrote out the new section, with
2394 * a newline, now skip the old
2395 * section's length
2396 */
2397 output += offset + i;
2398 if (strlen(output) > 0) {
2399 /*
2400 * More content means there's
2401 * a declaration to put on the
2402 * next line; indent with a
2403 * tab
2404 */
2405 output -= 1;
2406 output[0] = '\t';
2407 }
0667fcfb 2408 }
118f8b24 2409 remove = 0;
0667fcfb 2410 }
118f8b24
PB
2411 if (remove)
2412 continue;
9a5abfc7
AV
2413 length = strlen(output);
2414 if (write_in_full(out_fd, output, length) != length) {
b4fb09e4 2415 ret = write_error(get_lock_file_path(lock));
480c9e52
AW
2416 goto out;
2417 }
0667fcfb 2418 }
fc1905bb 2419 fclose(config_file);
8b590075 2420unlock_and_out:
4ed7cd3a 2421 if (commit_lock_file(lock) < 0)
f0658ec9
NTND
2422 ret = error_errno("could not write config file %s",
2423 config_filename);
8b590075 2424out:
42bd39b5 2425 free(filename_buf);
0667fcfb
JS
2426 return ret;
2427}
40ea4ed9 2428
42bd39b5
JK
2429int git_config_rename_section(const char *old_name, const char *new_name)
2430{
4a7bb5ba 2431 return git_config_rename_section_in_file(NULL, old_name, new_name);
42bd39b5
JK
2432}
2433
40ea4ed9
JH
2434/*
2435 * Call this to report error for your variable that should not
2436 * get a boolean value (i.e. "[my] var" means "true").
2437 */
a469a101 2438#undef config_error_nonbool
40ea4ed9
JH
2439int config_error_nonbool(const char *var)
2440{
8c3ca351 2441 return error("missing value for '%s'", var);
40ea4ed9 2442}
1b86bbb0
JK
2443
2444int parse_config_key(const char *var,
2445 const char *section,
2446 const char **subsection, int *subsection_len,
2447 const char **key)
2448{
2449 int section_len = strlen(section);
2450 const char *dot;
2451
2452 /* Does it start with "section." ? */
59556548 2453 if (!starts_with(var, section) || var[section_len] != '.')
1b86bbb0
JK
2454 return -1;
2455
2456 /*
2457 * Find the key; we don't know yet if we have a subsection, but we must
2458 * parse backwards from the end, since the subsection may have dots in
2459 * it, too.
2460 */
2461 dot = strrchr(var, '.');
2462 *key = dot + 1;
2463
2464 /* Did we have a subsection at all? */
2465 if (dot == var + section_len) {
2466 *subsection = NULL;
2467 *subsection_len = 0;
2468 }
2469 else {
2470 *subsection = var + section_len + 1;
2471 *subsection_len = dot - *subsection;
2472 }
2473
2474 return 0;
2475}
473166b9
LS
2476
2477const char *current_config_origin_type(void)
2478{
0d44a2da
JK
2479 const char *type;
2480 if (current_config_kvi)
2481 type = current_config_kvi->origin_type;
2482 else if(cf)
2483 type = cf->origin_type;
2484 else
3258258f 2485 die("BUG: current_config_origin_type called outside config callback");
0d44a2da 2486 return type ? type : "command line";
473166b9
LS
2487}
2488
2489const char *current_config_name(void)
2490{
0d44a2da
JK
2491 const char *name;
2492 if (current_config_kvi)
2493 name = current_config_kvi->filename;
2494 else if (cf)
2495 name = cf->name;
2496 else
3258258f 2497 die("BUG: current_config_name called outside config callback");
0d44a2da 2498 return name ? name : "";
473166b9 2499}
9acc5911
JK
2500
2501enum config_scope current_config_scope(void)
2502{
2503 if (current_config_kvi)
2504 return current_config_kvi->scope;
2505 else
2506 return current_parsing_scope;
473166b9 2507}