config.c 79.3 KB
Newer Older
1 2 3 4 5 6 7
/*
 * GIT - The information manager from hell
 *
 * Copyright (C) Linus Torvalds, 2005
 * Copyright (C) Johannes Schindelin, 2005
 *
 */
8
#include "cache.h"
9
#include "branch.h"
10
#include "config.h"
11
#include "repository.h"
12
#include "lockfile.h"
13
#include "exec-cmd.h"
14
#include "strbuf.h"
15
#include "quote.h"
16 17
#include "hashmap.h"
#include "string-list.h"
18
#include "object-store.h"
19
#include "utf8.h"
20
#include "dir.h"
21
#include "color.h"
22

23 24 25 26
struct config_source {
	struct config_source *prev;
	union {
		FILE *file;
27 28 29 30 31
		struct config_buf {
			const char *buf;
			size_t len;
			size_t pos;
		} buf;
32
	} u;
33
	enum config_origin_type origin_type;
34
	const char *name;
35
	const char *path;
36
	enum config_error_action default_error_action;
37 38 39
	int linenr;
	int eof;
	struct strbuf value;
40
	struct strbuf var;
41
	unsigned subsection_case_sensitive : 1;
42

43 44 45
	int (*do_fgetc)(struct config_source *c);
	int (*do_ungetc)(int c, struct config_source *conf);
	long (*do_ftell)(struct config_source *c);
46 47
};

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
/*
 * These variables record the "current" config source, which
 * can be accessed by parsing callbacks.
 *
 * The "cf" variable will be non-NULL only when we are actually parsing a real
 * config source (file, blob, cmdline, etc).
 *
 * The "current_config_kvi" variable will be non-NULL only when we are feeding
 * cached config from a configset into a callback.
 *
 * They should generally never be non-NULL at the same time. If they are both
 * NULL, then we aren't parsing anything (and depending on the function looking
 * at the variables, it's either a bug for it to be called in the first place,
 * or it's a function which can be reused for non-config purposes, and should
 * fall back to some sane behavior).
 */
64
static struct config_source *cf;
65
static struct key_value_info *current_config_kvi;
66

67 68 69 70 71 72 73 74
/*
 * Similar to the variables above, this gives access to the "scope" of the
 * current value (repo, global, etc). For cached values, it can be found via
 * the current_config_kvi as above. During parsing, the current value can be
 * found in this variable. It's not part of "cf" because it transcends a single
 * file (i.e., a file included from .git/config is still in "repo" scope).
 */
static enum config_scope current_parsing_scope;
75

76 77
static int core_compression_seen;
static int pack_compression_seen;
78 79
static int zlib_compression_seen;

80 81
static int config_file_fgetc(struct config_source *conf)
{
82
	return getc_unlocked(conf->u.file);
83 84 85 86 87 88 89 90 91 92 93 94
}

static int config_file_ungetc(int c, struct config_source *conf)
{
	return ungetc(c, conf->u.file);
}

static long config_file_ftell(struct config_source *conf)
{
	return ftell(conf->u.file);
}

95 96 97 98 99 100 101 102 103 104 105

static int config_buf_fgetc(struct config_source *conf)
{
	if (conf->u.buf.pos < conf->u.buf.len)
		return conf->u.buf.buf[conf->u.buf.pos++];

	return EOF;
}

static int config_buf_ungetc(int c, struct config_source *conf)
{
106 107 108
	if (conf->u.buf.pos > 0) {
		conf->u.buf.pos--;
		if (conf->u.buf.buf[conf->u.buf.pos] != c)
109
			BUG("config_buf can only ungetc the same character");
110 111
		return c;
	}
112 113 114 115 116 117 118 119 120

	return EOF;
}

static long config_buf_ftell(struct config_source *conf)
{
	return conf->u.buf.pos;
}

121
#define MAX_INCLUDE_DEPTH 10
122
static const char include_depth_advice[] = N_(
123 124 125 126
"exceeded maximum include depth (%d) while including\n"
"	%s\n"
"from\n"
"	%s\n"
127
"This might be due to circular includes.");
128 129 130 131
static int handle_path_include(const char *path, struct config_include_data *inc)
{
	int ret = 0;
	struct strbuf buf = STRBUF_INIT;
132
	char *expanded;
133

134 135 136
	if (!path)
		return config_error_nonbool("include.path");

137
	expanded = expand_user_path(path, 0);
138
	if (!expanded)
139
		return error(_("could not expand include path '%s'"), path);
140
	path = expanded;
141 142 143 144 145 146 147 148

	/*
	 * Use an absolute path as-is, but interpret relative paths
	 * based on the including config file.
	 */
	if (!is_absolute_path(path)) {
		char *slash;

149
		if (!cf || !cf->path)
150
			return error(_("relative config includes must come from files"));
151

152
		slash = find_last_dir_sep(cf->path);
153
		if (slash)
154
			strbuf_add(&buf, cf->path, slash - cf->path + 1);
155 156 157 158
		strbuf_addstr(&buf, path);
		path = buf.buf;
	}

159
	if (!access_or_die(path, R_OK, 0)) {
160
		if (++inc->depth > MAX_INCLUDE_DEPTH)
161
			die(_(include_depth_advice), MAX_INCLUDE_DEPTH, path,
162 163 164
			    !cf ? "<unknown>" :
			    cf->name ? cf->name :
			    "the command line");
165 166 167 168
		ret = git_config_from_file(git_config_include, path, inc);
		inc->depth--;
	}
	strbuf_release(&buf);
169
	free(expanded);
170 171 172
	return ret;
}

173 174 175 176 177 178
static int prepare_include_condition_pattern(struct strbuf *pat)
{
	struct strbuf path = STRBUF_INIT;
	char *expanded;
	int prefix = 0;

179
	expanded = expand_user_path(pat->buf, 1);
180 181 182 183 184 185 186 187 188 189 190 191 192
	if (expanded) {
		strbuf_reset(pat);
		strbuf_addstr(pat, expanded);
		free(expanded);
	}

	if (pat->buf[0] == '.' && is_dir_sep(pat->buf[1])) {
		const char *slash;

		if (!cf || !cf->path)
			return error(_("relative config include "
				       "conditionals must come from files"));

193
		strbuf_realpath(&path, cf->path, 1);
194 195
		slash = find_last_dir_sep(path.buf);
		if (!slash)
196
			BUG("how is this possible?");
197 198 199 200 201 202 203 204 205 206 207 208
		strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
		prefix = slash - path.buf + 1 /* slash */;
	} else if (!is_absolute_path(pat->buf))
		strbuf_insert(pat, 0, "**/", 3);

	if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
		strbuf_addstr(pat, "**");

	strbuf_release(&path);
	return prefix;
}

209 210
static int include_by_gitdir(const struct config_options *opts,
			     const char *cond, size_t cond_len, int icase)
211 212 213 214
{
	struct strbuf text = STRBUF_INIT;
	struct strbuf pattern = STRBUF_INIT;
	int ret = 0, prefix;
215
	const char *git_dir;
216
	int already_tried_absolute = 0;
217

218 219 220 221 222
	if (opts->git_dir)
		git_dir = opts->git_dir;
	else
		goto done;

223
	strbuf_realpath(&text, git_dir, 1);
224 225 226
	strbuf_add(&pattern, cond, cond_len);
	prefix = prepare_include_condition_pattern(&pattern);

227
again:
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
	if (prefix < 0)
		goto done;

	if (prefix > 0) {
		/*
		 * perform literal matching on the prefix part so that
		 * any wildcard character in it can't create side effects.
		 */
		if (text.len < prefix)
			goto done;
		if (!icase && strncmp(pattern.buf, text.buf, prefix))
			goto done;
		if (icase && strncasecmp(pattern.buf, text.buf, prefix))
			goto done;
	}

	ret = !wildmatch(pattern.buf + prefix, text.buf + prefix,
245
			 WM_PATHNAME | (icase ? WM_CASEFOLD : 0));
246

247 248 249 250 251 252 253 254 255 256 257 258 259 260
	if (!ret && !already_tried_absolute) {
		/*
		 * We've tried e.g. matching gitdir:~/work, but if
		 * ~/work is a symlink to /mnt/storage/work
		 * strbuf_realpath() will expand it, so the rule won't
		 * match. Let's match against a
		 * strbuf_add_absolute_path() version of the path,
		 * which'll do the right thing
		 */
		strbuf_reset(&text);
		strbuf_add_absolute_path(&text, git_dir);
		already_tried_absolute = 1;
		goto again;
	}
261 262 263 264 265 266
done:
	strbuf_release(&pattern);
	strbuf_release(&text);
	return ret;
}

267 268
static int include_condition_is_true(const struct config_options *opts,
				     const char *cond, size_t cond_len)
269 270 271
{

	if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
272
		return include_by_gitdir(opts, cond, cond_len, 0);
273
	else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
274
		return include_by_gitdir(opts, cond, cond_len, 1);
275 276 277 278 279

	/* unknown conditionals are always false */
	return 0;
}

280 281 282
int git_config_include(const char *var, const char *value, void *data)
{
	struct config_include_data *inc = data;
283 284
	const char *cond, *key;
	int cond_len;
285 286 287 288 289 290 291 292 293 294
	int ret;

	/*
	 * Pass along all values, including "include" directives; this makes it
	 * possible to query information on the includes themselves.
	 */
	ret = inc->fn(var, value, inc->data);
	if (ret < 0)
		return ret;

295
	if (!strcmp(var, "include.path"))
296
		ret = handle_path_include(value, inc);
297 298

	if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
299
	    (cond && include_condition_is_true(inc->opts, cond, cond_len)) &&
300 301 302
	    !strcmp(key, "path"))
		ret = handle_path_include(value, inc);

303 304 305
	return ret;
}

306 307 308 309
void git_config_push_parameter(const char *text)
{
	struct strbuf env = STRBUF_INIT;
	const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
310
	if (old && *old) {
311 312 313 314 315 316 317 318
		strbuf_addstr(&env, old);
		strbuf_addch(&env, ' ');
	}
	sq_quote_buf(&env, text);
	setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
	strbuf_release(&env);
}

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
static inline int iskeychar(int c)
{
	return isalnum(c) || c == '-';
}

/*
 * Auxiliary function to sanity-check and split the key into the section
 * identifier and variable name.
 *
 * Returns 0 on success, -1 when there is an invalid character in the key and
 * -2 if there is no section name in the key.
 *
 * store_key - pointer to char* which will hold a copy of the key with
 *             lowercase section and variable name
 * baselen - pointer to int which will hold the length of the
 *           section + subsection part, can be NULL
 */
static int git_config_parse_key_1(const char *key, char **store_key, int *baselen_, int quiet)
{
	int i, dot, baselen;
	const char *last_dot = strrchr(key, '.');

	/*
	 * Since "key" actually contains the section name and the real
	 * key name separated by a dot, we have to know where the dot is.
	 */

	if (last_dot == NULL || last_dot == key) {
		if (!quiet)
348
			error(_("key does not contain a section: %s"), key);
349 350 351 352 353
		return -CONFIG_NO_SECTION_OR_NAME;
	}

	if (!last_dot[1]) {
		if (!quiet)
354
			error(_("key does not contain variable name: %s"), key);
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
		return -CONFIG_NO_SECTION_OR_NAME;
	}

	baselen = last_dot - key;
	if (baselen_)
		*baselen_ = baselen;

	/*
	 * Validate the key and while at it, lower case it for matching.
	 */
	if (store_key)
		*store_key = xmallocz(strlen(key));

	dot = 0;
	for (i = 0; key[i]; i++) {
		unsigned char c = key[i];
		if (c == '.')
			dot = 1;
		/* Leave the extended basename untouched.. */
		if (!dot || i > baselen) {
			if (!iskeychar(c) ||
			    (i == baselen + 1 && !isalpha(c))) {
				if (!quiet)
378
					error(_("invalid key: %s"), key);
379 380 381 382 383
				goto out_free_ret_1;
			}
			c = tolower(c);
		} else if (c == '\n') {
			if (!quiet)
384
				error(_("invalid key (newline): %s"), key);
385 386 387 388 389 390 391 392 393 394
			goto out_free_ret_1;
		}
		if (store_key)
			(*store_key)[i] = c;
	}

	return 0;

out_free_ret_1:
	if (store_key) {
395
		FREE_AND_NULL(*store_key);
396 397 398 399 400 401 402 403 404 405 406 407 408 409
	}
	return -CONFIG_INVALID_KEY;
}

int git_config_parse_key(const char *key, char **store_key, int *baselen)
{
	return git_config_parse_key_1(key, store_key, baselen, 0);
}

int git_config_key_is_valid(const char *key)
{
	return !git_config_parse_key_1(key, NULL, NULL, 1);
}

410 411
int git_config_parse_parameter(const char *text,
			       config_fn_t fn, void *data)
412
{
413
	const char *value;
414
	char *canonical_name;
415
	struct strbuf **pair;
416
	int ret;
417

418
	pair = strbuf_split_str(text, '=', 2);
419
	if (!pair[0])
420
		return error(_("bogus config parameter: %s"), text);
421 422

	if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
423
		strbuf_setlen(pair[0], pair[0]->len - 1);
424 425 426 427 428
		value = pair[1] ? pair[1]->buf : "";
	} else {
		value = NULL;
	}

429 430 431
	strbuf_trim(pair[0]);
	if (!pair[0]->len) {
		strbuf_list_free(pair);
432
		return error(_("bogus config parameter: %s"), text);
433
	}
434 435 436 437 438 439

	if (git_config_parse_key(pair[0]->buf, &canonical_name, NULL)) {
		ret = -1;
	} else {
		ret = (fn(canonical_name, value, data) < 0) ? -1 : 0;
		free(canonical_name);
440 441
	}
	strbuf_list_free(pair);
442
	return ret;
443 444
}

445 446
int git_config_from_parameters(config_fn_t fn, void *data)
{
447
	const char *env = getenv(CONFIG_DATA_ENVIRONMENT);
448
	int ret = 0;
449 450 451 452
	char *envw;
	const char **argv = NULL;
	int nr = 0, alloc = 0;
	int i;
453
	struct config_source source;
454 455 456

	if (!env)
		return 0;
457 458 459

	memset(&source, 0, sizeof(source));
	source.prev = cf;
460
	source.origin_type = CONFIG_ORIGIN_CMDLINE;
461 462
	cf = &source;

463 464 465 466
	/* sq_dequote will write over it */
	envw = xstrdup(env);

	if (sq_dequote_to_argv(envw, &argv, &nr, &alloc) < 0) {
467
		ret = error(_("bogus format in %s"), CONFIG_DATA_ENVIRONMENT);
468
		goto out;
469 470 471
	}

	for (i = 0; i < nr; i++) {
472
		if (git_config_parse_parameter(argv[i], fn, data) < 0) {
473 474
			ret = -1;
			goto out;
475 476 477
		}
	}

478
out:
479 480
	free(argv);
	free(envw);
481
	cf = source.prev;
482
	return ret;
483 484
}

485 486
static int get_next_char(void)
{
487
	int c = cf->do_fgetc(cf);
488

489 490
	if (c == '\r') {
		/* DOS like systems */
491
		c = cf->do_fgetc(cf);
492
		if (c != '\n') {
Jeff King's avatar
Jeff King committed
493 494
			if (c != EOF)
				cf->do_ungetc(c, cf);
495
			c = '\r';
496 497
		}
	}
498 499 500 501
	if (c == '\n')
		cf->linenr++;
	if (c == EOF) {
		cf->eof = 1;
502
		cf->linenr++;
503 504
		c = '\n';
	}
505 506 507 508 509
	return c;
}

static char *parse_value(void)
{
510
	int quote = 0, comment = 0, space = 0;
511

512
	strbuf_reset(&cf->value);
513 514 515
	for (;;) {
		int c = get_next_char();
		if (c == '\n') {
516 517
			if (quote) {
				cf->linenr--;
518
				return NULL;
519
			}
520
			return cf->value.buf;
521 522 523 524
		}
		if (comment)
			continue;
		if (isspace(c) && !quote) {
525
			if (cf->value.len)
526
				space++;
527 528
			continue;
		}
529 530 531 532 533 534
		if (!quote) {
			if (c == ';' || c == '#') {
				comment = 1;
				continue;
			}
		}
535
		for (; space; space--)
536
			strbuf_addch(&cf->value, ' ');
537 538 539 540 541 542 543 544 545 546 547 548 549 550
		if (c == '\\') {
			c = get_next_char();
			switch (c) {
			case '\n':
				continue;
			case 't':
				c = '\t';
				break;
			case 'b':
				c = '\b';
				break;
			case 'n':
				c = '\n';
				break;
551 552 553 554 555 556
			/* Some characters escape as themselves */
			case '\\': case '"':
				break;
			/* Reject unknown escape sequences */
			default:
				return NULL;
557
			}
558
			strbuf_addch(&cf->value, c);
559 560 561 562 563 564
			continue;
		}
		if (c == '"') {
			quote = 1-quote;
			continue;
		}
565
		strbuf_addch(&cf->value, c);
566 567 568
	}
}

569
static int get_value(config_fn_t fn, void *data, struct strbuf *name)
570 571 572
{
	int c;
	char *value;
573
	int ret;
574 575 576 577

	/* Get the full name */
	for (;;) {
		c = get_next_char();
578
		if (cf->eof)
579
			break;
580
		if (!iskeychar(c))
581
			break;
582
		strbuf_addch(name, tolower(c));
583
	}
584

585 586 587 588 589 590 591 592 593 594 595
	while (c == ' ' || c == '\t')
		c = get_next_char();

	value = NULL;
	if (c != '\n') {
		if (c != '=')
			return -1;
		value = parse_value();
		if (!value)
			return -1;
	}
596 597 598 599 600 601 602
	/*
	 * We already consumed the \n, but we need linenr to point to
	 * the line we just parsed during the call to fn to get
	 * accurate line number in error messages.
	 */
	cf->linenr--;
	ret = fn(name->buf, value, data);
603 604
	if (ret >= 0)
		cf->linenr++;
605
	return ret;
606 607
}

608
static int get_extended_base_var(struct strbuf *name, int c)
609
{
610
	cf->subsection_case_sensitive = 0;
611 612
	do {
		if (c == '\n')
613
			goto error_incomplete_line;
614 615 616 617 618 619
		c = get_next_char();
	} while (isspace(c));

	/* We require the format to be '[base "extension"]' */
	if (c != '"')
		return -1;
620
	strbuf_addch(name, '.');
621 622 623 624

	for (;;) {
		int c = get_next_char();
		if (c == '\n')
625
			goto error_incomplete_line;
626 627 628 629 630
		if (c == '"')
			break;
		if (c == '\\') {
			c = get_next_char();
			if (c == '\n')
631
				goto error_incomplete_line;
632
		}
633
		strbuf_addch(name, c);
634 635 636 637 638
	}

	/* Final ']' */
	if (get_next_char() != ']')
		return -1;
639
	return 0;
640 641 642
error_incomplete_line:
	cf->linenr--;
	return -1;
643 644
}

645
static int get_base_var(struct strbuf *name)
646
{
647
	cf->subsection_case_sensitive = 1;
648 649
	for (;;) {
		int c = get_next_char();
650
		if (cf->eof)
651 652
			return -1;
		if (c == ']')
653
			return 0;
654
		if (isspace(c))
655
			return get_extended_base_var(name, c);
656
		if (!iskeychar(c) && c != '.')
657
			return -1;
658
		strbuf_addch(name, tolower(c));
659 660 661
	}
}

662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
struct parse_event_data {
	enum config_event_t previous_type;
	size_t previous_offset;
	const struct config_options *opts;
};

static int do_event(enum config_event_t type, struct parse_event_data *data)
{
	size_t offset;

	if (!data->opts || !data->opts->event_fn)
		return 0;

	if (type == CONFIG_EVENT_WHITESPACE &&
	    data->previous_type == type)
		return 0;

	offset = cf->do_ftell(cf);
	/*
	 * At EOF, the parser always "inserts" an extra '\n', therefore
	 * the end offset of the event is the current file position, otherwise
	 * we will already have advanced to the next event.
	 */
	if (type != CONFIG_EVENT_EOF)
		offset--;

	if (data->previous_type != CONFIG_EVENT_EOF &&
	    data->opts->event_fn(data->previous_type, data->previous_offset,
				 offset, data->opts->event_fn_data) < 0)
		return -1;

	data->previous_type = type;
	data->previous_offset = offset;

	return 0;
}

static int git_parse_source(config_fn_t fn, void *data,
			    const struct config_options *opts)
701 702 703
{
	int comment = 0;
	int baselen = 0;
704
	struct strbuf *var = &cf->var;
705 706
	int error_return = 0;
	char *error_msg = NULL;
707

708
	/* U+FEFF Byte Order Mark in UTF8 */
709
	const char *bomptr = utf8_bom;
710

711 712 713 714 715
	/* For the parser event callback */
	struct parse_event_data event_data = {
		CONFIG_EVENT_EOF, 0, opts
	};

716
	for (;;) {
717 718 719
		int c;

		c = get_next_char();
720 721 722 723
		if (bomptr && *bomptr) {
			/* We are at the file beginning; skip UTF8-encoded BOM
			 * if present. Sane editors won't put this in on their
			 * own, but e.g. Windows Notepad will do it happily. */
724
			if (c == (*bomptr & 0377)) {
725 726 727 728 729 730 731 732 733 734
				bomptr++;
				continue;
			} else {
				/* Do not tolerate partial BOM. */
				if (bomptr != utf8_bom)
					break;
				/* No BOM at file beginning. Cool. */
				bomptr = NULL;
			}
		}
735
		if (c == '\n') {
736 737 738
			if (cf->eof) {
				if (do_event(CONFIG_EVENT_EOF, &event_data) < 0)
					return -1;
739
				return 0;
740 741 742
			}
			if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
				return -1;
743 744 745
			comment = 0;
			continue;
		}
746
		if (comment)
747
			continue;
748 749 750
		if (isspace(c)) {
			if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
					return -1;
751
			continue;
752
		}
753
		if (c == '#' || c == ';') {
754 755
			if (do_event(CONFIG_EVENT_COMMENT, &event_data) < 0)
					return -1;
756 757 758 759
			comment = 1;
			continue;
		}
		if (c == '[') {
760 761 762
			if (do_event(CONFIG_EVENT_SECTION, &event_data) < 0)
					return -1;

763 764 765
			/* Reset prior to determining a new stem */
			strbuf_reset(var);
			if (get_base_var(var) < 0 || var->len < 1)
766
				break;
767 768
			strbuf_addch(var, '.');
			baselen = var->len;
769 770 771 772
			continue;
		}
		if (!isalpha(c))
			break;
773 774 775 776

		if (do_event(CONFIG_EVENT_ENTRY, &event_data) < 0)
			return -1;

777 778 779 780 781 782 783 784
		/*
		 * Truncate the var name back to the section header
		 * stem prior to grabbing the suffix part of the name
		 * and the value.
		 */
		strbuf_setlen(var, baselen);
		strbuf_addch(var, tolower(c));
		if (get_value(fn, data, var) < 0)
785 786
			break;
	}
787

788 789 790
	if (do_event(CONFIG_EVENT_ERROR, &event_data) < 0)
		return -1;

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
	switch (cf->origin_type) {
	case CONFIG_ORIGIN_BLOB:
		error_msg = xstrfmt(_("bad config line %d in blob %s"),
				      cf->linenr, cf->name);
		break;
	case CONFIG_ORIGIN_FILE:
		error_msg = xstrfmt(_("bad config line %d in file %s"),
				      cf->linenr, cf->name);
		break;
	case CONFIG_ORIGIN_STDIN:
		error_msg = xstrfmt(_("bad config line %d in standard input"),
				      cf->linenr);
		break;
	case CONFIG_ORIGIN_SUBMODULE_BLOB:
		error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
				       cf->linenr, cf->name);
		break;
	case CONFIG_ORIGIN_CMDLINE:
		error_msg = xstrfmt(_("bad config line %d in command line %s"),
				       cf->linenr, cf->name);
		break;
	default:
		error_msg = xstrfmt(_("bad config line %d in %s"),
				      cf->linenr, cf->name);
	}

817 818 819 820
	switch (opts && opts->error_action ?
		opts->error_action :
		cf->default_error_action) {
	case CONFIG_ERROR_DIE:
821
		die("%s", error_msg);
822 823
		break;
	case CONFIG_ERROR_ERROR:
824
		error_return = error("%s", error_msg);
825
		break;
826 827 828
	case CONFIG_ERROR_SILENT:
		error_return = -1;
		break;
829 830 831
	case CONFIG_ERROR_UNSET:
		BUG("config error action unset");
	}
832 833 834

	free(error_msg);
	return error_return;
835 836
}

837
static int parse_unit_factor(const char *end, uintmax_t *val)
838 839 840
{
	if (!*end)
		return 1;
841 842 843 844 845 846 847 848 849 850 851 852 853
	else if (!strcasecmp(end, "k")) {
		*val *= 1024;
		return 1;
	}
	else if (!strcasecmp(end, "m")) {
		*val *= 1024 * 1024;
		return 1;
	}
	else if (!strcasecmp(end, "g")) {
		*val *= 1024 * 1024 * 1024;
		return 1;
	}
	return 0;
854 855
}

856
static int git_parse_signed(const char *value, intmax_t *ret, intmax_t max)
857 858 859
{
	if (value && *value) {
		char *end;
860 861 862 863 864 865 866 867
		intmax_t val;
		uintmax_t uval;
		uintmax_t factor = 1;

		errno = 0;
		val = strtoimax(value, &end, 0);
		if (errno == ERANGE)
			return 0;
868 869
		if (!parse_unit_factor(end, &factor)) {
			errno = EINVAL;
870
			return 0;
871
		}
872
		uval = labs(val);
873
		uval *= factor;
874
		if (uval > max || labs(val) > uval) {
875
			errno = ERANGE;
876
			return 0;
877
		}
878 879
		val *= factor;
		*ret = val;
880 881
		return 1;
	}
882
	errno = EINVAL;
883 884 885
	return 0;
}

886
static int git_parse_unsigned(const char *value, uintmax_t *ret, uintmax_t max)
887 888 889
{
	if (value && *value) {
		char *end;
890 891 892 893 894 895 896 897
		uintmax_t val;
		uintmax_t oldval;

		errno = 0;
		val = strtoumax(value, &end, 0);
		if (errno == ERANGE)
			return 0;
		oldval = val;
898 899
		if (!parse_unit_factor(end, &val)) {
			errno = EINVAL;
900
			return 0;
901 902 903
		}
		if (val > max || oldval > val) {
			errno = ERANGE;
904
			return 0;
905
		}
906
		*ret = val;
907
		return 1;
908
	}
909
	errno = EINVAL;
910 911 912
	return 0;
}

913
static int git_parse_int(const char *value, int *ret)
914
{
915
	intmax_t tmp;
916
	if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int)))
917 918 919 920 921
		return 0;
	*ret = tmp;
	return 1;
}

922 923 924 925 926 927 928 929 930
static int git_parse_int64(const char *value, int64_t *ret)
{
	intmax_t tmp;
	if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(int64_t)))
		return 0;
	*ret = tmp;
	return 1;
}

931 932 933 934 935 936 937 938 939
int git_parse_ulong(const char *value, unsigned long *ret)
{
	uintmax_t tmp;
	if (!git_parse_unsigned(value, &tmp, maximum_unsigned_value_of_type(long)))
		return 0;
	*ret = tmp;
	return 1;
}

940
int git_parse_ssize_t(const char *value, ssize_t *ret)
941 942 943 944 945 946 947 948
{
	intmax_t tmp;
	if (!git_parse_signed(value, &tmp, maximum_signed_value_of_type(ssize_t)))
		return 0;
	*ret = tmp;
	return 1;
}

949
NORETURN
950
static void die_bad_number(const char *name, const char *value)
951
{
952 953
	const char * error_type = (errno == ERANGE)? _("out of range"):_("invalid unit");

954 955 956
	if (!value)
		value = "";

957
	if (!(cf && cf->name))
958 959
		die(_("bad numeric config value '%s' for '%s': %s"),
		    value, name, error_type);
960 961 962

	switch (cf->origin_type) {
	case CONFIG_ORIGIN_BLOB:
963 964
		die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
		    value, name, cf->name, error_type);
965
	case CONFIG_ORIGIN_FILE:
966 967
		die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
		    value, name, cf->name, error_type);
968
	case CONFIG_ORIGIN_STDIN:
969 970
		die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
		    value, name, error_type);
971
	case CONFIG_ORIGIN_SUBMODULE_BLOB:
972 973
		die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
		    value, name, cf->name, error_type);
974
	case CONFIG_ORIGIN_CMDLINE:
975 976
		die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
		    value, name, cf->name, error_type);
977
	default:
978 979
		die(_("bad numeric config value '%s' for '%s' in %s: %s"),
		    value, name, cf->name, error_type);
980
	}
981 982
}

983 984
int git_config_int(const char *name, const char *value)
{
985 986
	int ret;
	if (!git_parse_int(value, &ret))
987
		die_bad_number(name, value);
988 989 990
	return ret;
}

991 992 993 994 995
int64_t git_config_int64(const char *name, const char *value)
{
	int64_t ret;
	if (!git_parse_int64(value, &ret))
		die_bad_number(name, value);
996 997 998 999 1000 1001 1002
	return ret;
}

unsigned long git_config_ulong(const char *name, const char *value)
{
	unsigned long ret;
	if (!git_parse_ulong(value, &ret))
1003
		die_bad_number(name, value);
1004
	return ret;
1005 1006
}

1007 1008 1009 1010 1011 1012 1013 1014
ssize_t git_config_ssize_t(const char *name, const char *value)
{
	ssize_t ret;
	if (!git_parse_ssize_t(value, &ret))
		die_bad_number(name, value);
	return ret;
}

1015
static int git_parse_maybe_bool_text(const char *value)
1016 1017 1018 1019 1020
{
	if (!value)
		return 1;
	if (!*value)
		return 0;
Junio C Hamano's avatar
Junio C Hamano committed
1021 1022 1023
	if (!strcasecmp(value, "true")
	    || !strcasecmp(value, "yes")
	    || !strcasecmp(value, "on"))
1024
		return 1;
Junio C Hamano's avatar
Junio C Hamano committed
1025 1026 1027
	if (!strcasecmp(value, "false")
	    || !strcasecmp(value, "no")
	    || !strcasecmp(value, "off"))
1028
		return 0;
Junio C Hamano's avatar
Junio C Hamano committed
1029 1030 1031
	return -1;
}

1032
int git_parse_maybe_bool(const char *value)
1033
{
1034
	int v = git_parse_maybe_bool_text(value);
1035 1036
	if (0 <= v)
		return v;
1037
	if (git_parse_int(value, &v))
1038
		return !!v;
1039 1040 1041
	return -1;
}

Junio C Hamano's avatar
Junio C Hamano committed
1042 1043
int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
{
1044
	int v = git_parse_maybe_bool_text(value);
Junio C Hamano's avatar
Junio C Hamano committed
1045 1046 1047 1048
	if (0 <= v) {
		*is_bool = 1;
		return v;
	}
1049
	*is_bool = 0;
1050
	return git_config_int(name, value);
1051 1052
}

1053 1054 1055
int git_config_bool(const char *name, const char *value)
{
	int discard;
1056
	return !!git_config_bool_or_int(name, value, &discard);
1057 1058
}

1059 1060 1061 1062 1063 1064 1065 1066
int git_config_string(const char **dest, const char *var, const char *value)
{
	if (!value)
		return config_error_nonbool(var);
	*dest = xstrdup(value);
	return 0;
}

1067 1068 1069 1070
int git_config_pathname(const char **dest, const char *var, const char *value)
{
	if (!value)
		return config_error_nonbool(var);
1071
	*dest = expand_user_path(value, 0);
1072
	if (!*dest)
1073
		die(_("failed to expand user dir in: '%s'"), value);
1074 1075 1076
	return 0;
}

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
{
	if (!value)
		return config_error_nonbool(var);
	if (parse_expiry_date(value, timestamp))
		return error(_("'%s' for '%s' is not a valid timestamp"),
			     value, var);
	return 0;
}

1087 1088 1089 1090 1091 1092 1093 1094 1095
int git_config_color(char *dest, const char *var, const char *value)
{
	if (!value)
		return config_error_nonbool(var);
	if (color_parse(value, dest) < 0)
		return -1;
	return 0;
}

1096
static int git_default_core_config(const char *var, const char *value, void *cb)
1097 1098 1099 1100 1101 1102
{
	/* This needs a better name */
	if (!strcmp(var, "core.filemode")) {
		trust_executable_bit = git_config_bool(var, value);
		return 0;
	}
1103 1104 1105 1106
	if (!strcmp(var, "core.trustctime")) {
		trust_ctime = git_config_bool(var, value);
		return 0;
	}
1107
	if (!strcmp(var, "core.checkstat")) {
1108 1109 1110 1111 1112
		if (!strcasecmp(value, "default"))
			check_stat = 1;
		else if (!strcasecmp(value, "minimal"))
			check_stat = 0;
	}
1113

1114 1115 1116 1117 1118
	if (!strcmp(var, "core.quotepath")) {
		quote_path_fully = git_config_bool(var, value);
		return 0;
	}

1119 1120 1121 1122 1123
	if (!strcmp(var, "core.symlinks")) {
		has_symlinks = git_config_bool(var, value);
		return 0;
	}

1124 1125 1126 1127 1128
	if (!strcmp(var, "core.ignorecase")) {
		ignore_case = git_config_bool(var, value);
		return 0;
	}

1129 1130 1131
	if (!strcmp(var, "core.attributesfile"))
		return git_config_pathname(&git_attributes_file, var, value);

1132 1133 1134
	if (!strcmp(var, "core.hookspath"))
		return git_config_pathname(&git_hooks_path, var, value);

1135 1136 1137 1138 1139
	if (!strcmp(var, "core.bare")) {
		is_bare_repository_cfg = git_config_bool(var, value);
		return 0;
	}

Junio C Hamano's avatar
Junio C Hamano committed
1140 1141 1142 1143 1144
	if (!strcmp(var, "core.ignorestat")) {
		assume_unchanged = git_config_bool(var, value);
		return 0;
	}

1145 1146
	if (!strcmp(var, "core.prefersymlinkrefs")) {
		prefer_symlink_refs = git_config_bool(var, value);
1147 1148 1149
		return 0;
	}

1150
	if (!strcmp(var, "core.logallrefupdates")) {
1151 1152 1153 1154 1155 1156
		if (value && !strcasecmp(value, "always"))
			log_all_ref_updates = LOG_REFS_ALWAYS;
		else if (git_config_bool(var, value))
			log_all_ref_updates = LOG_REFS_NORMAL;
		else
			log_all_ref_updates = LOG_REFS_NONE;
1157 1158 1159
		return 0;
	}

1160 1161 1162 1163 1164
	if (!strcmp(var, "core.warnambiguousrefs")) {
		warn_ambiguous_refs = git_config_bool(var, value);
		return 0;
	}

1165
	if (!strcmp(var, "core.abbrev")) {
1166 1167 1168 1169 1170 1171 1172
		if (!value)
			return config_error_nonbool(var);
		if (!strcasecmp(value, "auto"))
			default_abbrev = -1;
		else {
			int abbrev = git_config_int(var, value);
			if (abbrev < minimum_abbrev || abbrev > 40)
1173
				return error(_("abbrev length out of range: %d"), abbrev);
1174 1175
			default_abbrev = abbrev;
		}
1176 1177 1178
		return 0;
	}

1179 1180 1181
	if (!strcmp(var, "core.disambiguate"))
		return set_disambiguate_hint_config(var, value);

1182
	if (!strcmp(var, "core.loosecompression")) {
1183 1184 1185 1186
		int level = git_config_int(var, value);
		if (level == -1)
			level = Z_DEFAULT_COMPRESSION;
		else if (level < 0 || level > Z_BEST_COMPRESSION)
1187
			die(_("bad zlib compression level %d"), level);
1188
		zlib_compression_level = level;
1189 1190 1191 1192 1193 1194 1195 1196 1197
		zlib_compression_seen = 1;
		return 0;
	}

	if (!strcmp(var, "core.compression")) {
		int level = git_config_int(var, value);
		if (level == -1)
			level = Z_DEFAULT_COMPRESSION;
		else if (level < 0 || level > Z_BEST_COMPRESSION)
1198
			die(_("bad zlib compression level %d"), level);
1199 1200 1201 1202
		core_compression_level = level;
		core_compression_seen = 1;
		if (!zlib_compression_seen)
			zlib_compression_level = level;
1203 1204
		if (!pack_compression_seen)
			pack_compression_level = level;
1205 1206 1207
		return 0;
	}

1208
	if (!strcmp(var, "core.packedgitwindowsize")) {
1209
		int pgsz_x2 = getpagesize() * 2;
1210
		packed_git_window_size = git_config_ulong(var, value);
1211 1212 1213 1214 1215 1216

		/* This value must be multiple of (pagesize * 2) */
		packed_git_window_size /= pgsz_x2;
		if (packed_git_window_size < 1)
			packed_git_window_size = 1;
		packed_git_window_size *= pgsz_x2;
1217 1218 1219
		return 0;
	}

1220
	if (!strcmp(var, "core.bigfilethreshold")) {
1221
		big_file_threshold = git_config_ulong(var, value);
1222 1223 1224
		return 0;
	}

1225
	if (!strcmp(var, "core.packedgitlimit")) {
1226
		packed_git_limit = git_config_ulong(var, value);
1227 1228 1229
		return 0;
	}

1230
	if (!strcmp(var, "core.deltabasecachelimit")) {
1231
		delta_base_cache_limit = git_config_ulong(var, value);
1232 1233 1234
		return 0;
	}

Linus Torvalds's avatar
Linus Torvalds committed
1235
	if (!strcmp(var, "core.autocrlf")) {
1236
		if (value && !strcasecmp(value, "input")) {
1237
			auto_crlf = AUTO_CRLF_INPUT;
1238 1239
			return 0;
		}
Linus Torvalds's avatar
Linus Torvalds committed
1240 1241 1242 1243
		auto_crlf = git_config_bool(var, value);
		return 0;
	}

1244
	if (!strcmp(var, "core.safecrlf")) {
1245
		int eol_rndtrp_die;
1246
		if (value && !strcasecmp(value, "warn")) {
1247
			global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
1248 1249
			return 0;
		}
1250 1251
		eol_rndtrp_die = git_config_bool(var, value);
		global_conv_flags_eol = eol_rndtrp_die ?
1252
			CONV_EOL_RNDTRP_DIE : 0;
1253 1254 1255
		return 0;
	}

1256 1257
	if (!strcmp(var, "core.eol")) {
		if (value && !strcasecmp(value, "lf"))
1258
			core_eol = EOL_LF;
1259
		else if (value && !strcasecmp(value, "crlf"))
1260
			core_eol = EOL_CRLF;
1261
		else if (value && !strcasecmp(value, "native"))
1262
			core_eol = EOL_NATIVE;
1263
		else
1264
			core_eol = EOL_UNSET;
1265 1266 1267
		return 0;
	}

1268 1269 1270 1271 1272
	if (!strcmp(var, "core.checkroundtripencoding")) {
		check_roundtrip_encoding = xstrdup(value);
		return 0;
	}

1273 1274 1275 1276 1277
	if (!strcmp(var, "core.notesref")) {
		notes_ref_name = xstrdup(value);
		return 0;
	}

1278 1279 1280
	if (!strcmp(var, "core.editor"))
		return git_config_string(&editor_program, var, value);

1281
	if (!strcmp(var, "core.commentchar")) {
1282 1283
		if (!value)
			return config_error_nonbool(var);
1284
		else if (!strcasecmp(value, "auto"))
1285
			auto_comment_line_char = 1;
1286
		else if (value[0] && !value[1]) {
1287
			comment_line_char = value[0];
1288
			auto_comment_line_char = 0;
1289
		} else
1290
			return error(_("core.commentChar should only be one character"));
1291
		return 0;
1292 1293
	}

1294 1295 1296
	if (!strcmp(var, "core.askpass"))
		return git_config_string(&askpass_program, var, value);

1297
	if (!strcmp(var, "core.excludesfile"))
1298
		return git_config_pathname(&excludes_file, var, value);
1299 1300 1301 1302 1303 1304 1305 1306

	if (!strcmp(var, "core.whitespace")) {
		if (!value)
			return config_error_nonbool(var);
		whitespace_rule_cfg = parse_whitespace_rule(value);
		return 0;
	}

1307 1308 1309 1310 1311
	if (!strcmp(var, "core.fsyncobjectfiles")) {
		fsync_object_files = git_config_bool(var, value);
		return 0;
	}

1312 1313 1314 1315 1316
	if (!strcmp(var, "core.preloadindex")) {
		core_preload_index = git_config_bool(var, value);
		return 0;
	}

1317 1318 1319 1320 1321 1322
	if (!strcmp(var, "core.createobject")) {
		if (!strcmp(value, "rename"))
			object_creation_mode = OBJECT_CREATION_USES_RENAMES;
		else if (!strcmp(value, "link"))
			object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
		else
1323
			die(_("invalid mode for object creation: %s"), value);
1324 1325 1326
		return 0;
	}

1327 1328 1329 1330 1331
	if (!strcmp(var, "core.sparsecheckout")) {
		core_apply_sparse_checkout = git_config_bool(var, value);
		return 0;
	}

1332 1333 1334 1335 1336
	if (!strcmp(var, "core.precomposeunicode")) {
		precomposed_unicode = git_config_bool(var, value);
		return 0;
	}

1337 1338 1339 1340 1341
	if (!strcmp(var, "core.protecthfs")) {
		protect_hfs = git_config_bool(var, value);
		return 0;
	}

1342 1343 1344
	if (!strcmp(var, "core.protectntfs")) {
		protect_ntfs = git_config_bool(var, value);
		return 0;
1345 1346
	}

1347 1348 1349 1350 1351
	if (!strcmp(var, "core.partialclonefilter")) {
		return git_config_string(&core_partial_clone_filter_default,
					 var, value);
	}

1352 1353 1354 1355 1356
	if (!strcmp(var, "core.usereplacerefs")) {
		read_replace_refs = git_config_bool(var, value);
		return 0;
	}

1357
	/* Add other config variables here and to Documentation/config.txt. */
1358
	return platform_core_config(var, value, cb);
1359 1360
}

1361
static int git_default_i18n_config(const char *var, const char *value)
1362
{
1363 1364
	if (!strcmp(var, "i18n.commitencoding"))
		return git_config_string(&git_commit_encoding, var, value);
1365

1366 1367
	if (!strcmp(var, "i18n.logoutputencoding"))
		return git_config_string(&git_log_output_encoding, var, value);