git

Форк
0
/
config.c 
3860 строк · 95.2 Кб
1
/*
2
 * GIT - The information manager from hell
3
 *
4
 * Copyright (C) Linus Torvalds, 2005
5
 * Copyright (C) Johannes Schindelin, 2005
6
 *
7
 */
8

9
#include "git-compat-util.h"
10
#include "abspath.h"
11
#include "advice.h"
12
#include "date.h"
13
#include "branch.h"
14
#include "config.h"
15
#include "parse.h"
16
#include "convert.h"
17
#include "environment.h"
18
#include "gettext.h"
19
#include "ident.h"
20
#include "repository.h"
21
#include "lockfile.h"
22
#include "mailmap.h"
23
#include "attr.h"
24
#include "exec-cmd.h"
25
#include "strbuf.h"
26
#include "quote.h"
27
#include "hashmap.h"
28
#include "string-list.h"
29
#include "object-name.h"
30
#include "object-store-ll.h"
31
#include "pager.h"
32
#include "path.h"
33
#include "utf8.h"
34
#include "color.h"
35
#include "refs.h"
36
#include "setup.h"
37
#include "strvec.h"
38
#include "trace2.h"
39
#include "wildmatch.h"
40
#include "ws.h"
41
#include "write-or-die.h"
42

43
struct config_source {
44
	struct config_source *prev;
45
	union {
46
		FILE *file;
47
		struct config_buf {
48
			const char *buf;
49
			size_t len;
50
			size_t pos;
51
		} buf;
52
	} u;
53
	enum config_origin_type origin_type;
54
	const char *name;
55
	const char *path;
56
	enum config_error_action default_error_action;
57
	int linenr;
58
	int eof;
59
	size_t total_len;
60
	struct strbuf value;
61
	struct strbuf var;
62
	unsigned subsection_case_sensitive : 1;
63

64
	int (*do_fgetc)(struct config_source *c);
65
	int (*do_ungetc)(int c, struct config_source *conf);
66
	long (*do_ftell)(struct config_source *c);
67
};
68
#define CONFIG_SOURCE_INIT { 0 }
69

70
static int pack_compression_seen;
71
static int zlib_compression_seen;
72

73
/*
74
 * Config that comes from trusted scopes, namely:
75
 * - CONFIG_SCOPE_SYSTEM (e.g. /etc/gitconfig)
76
 * - CONFIG_SCOPE_GLOBAL (e.g. $HOME/.gitconfig, $XDG_CONFIG_HOME/git)
77
 * - CONFIG_SCOPE_COMMAND (e.g. "-c" option, environment variables)
78
 *
79
 * This is declared here for code cleanliness, but unlike the other
80
 * static variables, this does not hold config parser state.
81
 */
82
static struct config_set protected_config;
83

84
static int config_file_fgetc(struct config_source *conf)
85
{
86
	return getc_unlocked(conf->u.file);
87
}
88

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

94
static long config_file_ftell(struct config_source *conf)
95
{
96
	return ftell(conf->u.file);
97
}
98

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

104
	return EOF;
105
}
106

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

116
	return EOF;
117
}
118

119
static long config_buf_ftell(struct config_source *conf)
120
{
121
	return conf->u.buf.pos;
122
}
123

124
struct config_include_data {
125
	int depth;
126
	config_fn_t fn;
127
	void *data;
128
	const struct config_options *opts;
129
	const struct git_config_source *config_source;
130
	struct repository *repo;
131

132
	/*
133
	 * All remote URLs discovered when reading all config files.
134
	 */
135
	struct string_list *remote_urls;
136
};
137
#define CONFIG_INCLUDE_INIT { 0 }
138

139
static int git_config_include(const char *var, const char *value,
140
			      const struct config_context *ctx, void *data);
141

142
#define MAX_INCLUDE_DEPTH 10
143
static const char include_depth_advice[] = N_(
144
"exceeded maximum include depth (%d) while including\n"
145
"	%s\n"
146
"from\n"
147
"	%s\n"
148
"This might be due to circular includes.");
149
static int handle_path_include(const struct key_value_info *kvi,
150
			       const char *path,
151
			       struct config_include_data *inc)
152
{
153
	int ret = 0;
154
	struct strbuf buf = STRBUF_INIT;
155
	char *expanded;
156

157
	if (!path)
158
		return config_error_nonbool("include.path");
159

160
	expanded = interpolate_path(path, 0);
161
	if (!expanded)
162
		return error(_("could not expand include path '%s'"), path);
163
	path = expanded;
164

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

172
		if (!kvi || !kvi->path) {
173
			ret = error(_("relative config includes must come from files"));
174
			goto cleanup;
175
		}
176

177
		slash = find_last_dir_sep(kvi->path);
178
		if (slash)
179
			strbuf_add(&buf, kvi->path, slash - kvi->path + 1);
180
		strbuf_addstr(&buf, path);
181
		path = buf.buf;
182
	}
183

184
	if (!access_or_die(path, R_OK, 0)) {
185
		if (++inc->depth > MAX_INCLUDE_DEPTH)
186
			die(_(include_depth_advice), MAX_INCLUDE_DEPTH, path,
187
			    !kvi ? "<unknown>" :
188
			    kvi->filename ? kvi->filename :
189
			    "the command line");
190
		ret = git_config_from_file_with_options(git_config_include, path, inc,
191
							kvi->scope, NULL);
192
		inc->depth--;
193
	}
194
cleanup:
195
	strbuf_release(&buf);
196
	free(expanded);
197
	return ret;
198
}
199

200
static void add_trailing_starstar_for_dir(struct strbuf *pat)
201
{
202
	if (pat->len && is_dir_sep(pat->buf[pat->len - 1]))
203
		strbuf_addstr(pat, "**");
204
}
205

206
static int prepare_include_condition_pattern(const struct key_value_info *kvi,
207
					     struct strbuf *pat)
208
{
209
	struct strbuf path = STRBUF_INIT;
210
	char *expanded;
211
	int prefix = 0;
212

213
	expanded = interpolate_path(pat->buf, 1);
214
	if (expanded) {
215
		strbuf_reset(pat);
216
		strbuf_addstr(pat, expanded);
217
		free(expanded);
218
	}
219

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

223
		if (!kvi || !kvi->path)
224
			return error(_("relative config include "
225
				       "conditionals must come from files"));
226

227
		strbuf_realpath(&path, kvi->path, 1);
228
		slash = find_last_dir_sep(path.buf);
229
		if (!slash)
230
			BUG("how is this possible?");
231
		strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
232
		prefix = slash - path.buf + 1 /* slash */;
233
	} else if (!is_absolute_path(pat->buf))
234
		strbuf_insertstr(pat, 0, "**/");
235

236
	add_trailing_starstar_for_dir(pat);
237

238
	strbuf_release(&path);
239
	return prefix;
240
}
241

242
static int include_by_gitdir(const struct key_value_info *kvi,
243
			     const struct config_options *opts,
244
			     const char *cond, size_t cond_len, int icase)
245
{
246
	struct strbuf text = STRBUF_INIT;
247
	struct strbuf pattern = STRBUF_INIT;
248
	int ret = 0, prefix;
249
	const char *git_dir;
250
	int already_tried_absolute = 0;
251

252
	if (opts->git_dir)
253
		git_dir = opts->git_dir;
254
	else
255
		goto done;
256

257
	strbuf_realpath(&text, git_dir, 1);
258
	strbuf_add(&pattern, cond, cond_len);
259
	prefix = prepare_include_condition_pattern(kvi, &pattern);
260

261
again:
262
	if (prefix < 0)
263
		goto done;
264

265
	if (prefix > 0) {
266
		/*
267
		 * perform literal matching on the prefix part so that
268
		 * any wildcard character in it can't create side effects.
269
		 */
270
		if (text.len < prefix)
271
			goto done;
272
		if (!icase && strncmp(pattern.buf, text.buf, prefix))
273
			goto done;
274
		if (icase && strncasecmp(pattern.buf, text.buf, prefix))
275
			goto done;
276
	}
277

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

281
	if (!ret && !already_tried_absolute) {
282
		/*
283
		 * We've tried e.g. matching gitdir:~/work, but if
284
		 * ~/work is a symlink to /mnt/storage/work
285
		 * strbuf_realpath() will expand it, so the rule won't
286
		 * match. Let's match against a
287
		 * strbuf_add_absolute_path() version of the path,
288
		 * which'll do the right thing
289
		 */
290
		strbuf_reset(&text);
291
		strbuf_add_absolute_path(&text, git_dir);
292
		already_tried_absolute = 1;
293
		goto again;
294
	}
295
done:
296
	strbuf_release(&pattern);
297
	strbuf_release(&text);
298
	return ret;
299
}
300

301
static int include_by_branch(struct config_include_data *data,
302
			     const char *cond, size_t cond_len)
303
{
304
	int flags;
305
	int ret;
306
	struct strbuf pattern = STRBUF_INIT;
307
	const char *refname = (!data->repo || !data->repo->gitdir) ?
308
		NULL : refs_resolve_ref_unsafe(get_main_ref_store(data->repo),
309
					       "HEAD", 0, NULL, &flags);
310
	const char *shortname;
311

312
	if (!refname || !(flags & REF_ISSYMREF)	||
313
			!skip_prefix(refname, "refs/heads/", &shortname))
314
		return 0;
315

316
	strbuf_add(&pattern, cond, cond_len);
317
	add_trailing_starstar_for_dir(&pattern);
318
	ret = !wildmatch(pattern.buf, shortname, WM_PATHNAME);
319
	strbuf_release(&pattern);
320
	return ret;
321
}
322

323
static int add_remote_url(const char *var, const char *value,
324
			  const struct config_context *ctx UNUSED, void *data)
325
{
326
	struct string_list *remote_urls = data;
327
	const char *remote_name;
328
	size_t remote_name_len;
329
	const char *key;
330

331
	if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
332
			      &key) &&
333
	    remote_name &&
334
	    !strcmp(key, "url"))
335
		string_list_append(remote_urls, value);
336
	return 0;
337
}
338

339
static void populate_remote_urls(struct config_include_data *inc)
340
{
341
	struct config_options opts;
342

343
	opts = *inc->opts;
344
	opts.unconditional_remote_url = 1;
345

346
	inc->remote_urls = xmalloc(sizeof(*inc->remote_urls));
347
	string_list_init_dup(inc->remote_urls);
348
	config_with_options(add_remote_url, inc->remote_urls,
349
			    inc->config_source, inc->repo, &opts);
350
}
351

352
static int forbid_remote_url(const char *var, const char *value UNUSED,
353
			     const struct config_context *ctx UNUSED,
354
			     void *data UNUSED)
355
{
356
	const char *remote_name;
357
	size_t remote_name_len;
358
	const char *key;
359

360
	if (!parse_config_key(var, "remote", &remote_name, &remote_name_len,
361
			      &key) &&
362
	    remote_name &&
363
	    !strcmp(key, "url"))
364
		die(_("remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"));
365
	return 0;
366
}
367

368
static int at_least_one_url_matches_glob(const char *glob, int glob_len,
369
					 struct string_list *remote_urls)
370
{
371
	struct strbuf pattern = STRBUF_INIT;
372
	struct string_list_item *url_item;
373
	int found = 0;
374

375
	strbuf_add(&pattern, glob, glob_len);
376
	for_each_string_list_item(url_item, remote_urls) {
377
		if (!wildmatch(pattern.buf, url_item->string, WM_PATHNAME)) {
378
			found = 1;
379
			break;
380
		}
381
	}
382
	strbuf_release(&pattern);
383
	return found;
384
}
385

386
static int include_by_remote_url(struct config_include_data *inc,
387
		const char *cond, size_t cond_len)
388
{
389
	if (inc->opts->unconditional_remote_url)
390
		return 1;
391
	if (!inc->remote_urls)
392
		populate_remote_urls(inc);
393
	return at_least_one_url_matches_glob(cond, cond_len,
394
					     inc->remote_urls);
395
}
396

397
static int include_condition_is_true(const struct key_value_info *kvi,
398
				     struct config_include_data *inc,
399
				     const char *cond, size_t cond_len)
400
{
401
	const struct config_options *opts = inc->opts;
402

403
	if (skip_prefix_mem(cond, cond_len, "gitdir:", &cond, &cond_len))
404
		return include_by_gitdir(kvi, opts, cond, cond_len, 0);
405
	else if (skip_prefix_mem(cond, cond_len, "gitdir/i:", &cond, &cond_len))
406
		return include_by_gitdir(kvi, opts, cond, cond_len, 1);
407
	else if (skip_prefix_mem(cond, cond_len, "onbranch:", &cond, &cond_len))
408
		return include_by_branch(inc, cond, cond_len);
409
	else if (skip_prefix_mem(cond, cond_len, "hasconfig:remote.*.url:", &cond,
410
				   &cond_len))
411
		return include_by_remote_url(inc, cond, cond_len);
412

413
	/* unknown conditionals are always false */
414
	return 0;
415
}
416

417
static int git_config_include(const char *var, const char *value,
418
			      const struct config_context *ctx,
419
			      void *data)
420
{
421
	struct config_include_data *inc = data;
422
	const char *cond, *key;
423
	size_t cond_len;
424
	int ret;
425

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

434
	if (!strcmp(var, "include.path"))
435
		ret = handle_path_include(ctx->kvi, value, inc);
436

437
	if (!parse_config_key(var, "includeif", &cond, &cond_len, &key) &&
438
	    cond && include_condition_is_true(ctx->kvi, inc, cond, cond_len) &&
439
	    !strcmp(key, "path")) {
440
		config_fn_t old_fn = inc->fn;
441

442
		if (inc->opts->unconditional_remote_url)
443
			inc->fn = forbid_remote_url;
444
		ret = handle_path_include(ctx->kvi, value, inc);
445
		inc->fn = old_fn;
446
	}
447

448
	return ret;
449
}
450

451
static void git_config_push_split_parameter(const char *key, const char *value)
452
{
453
	struct strbuf env = STRBUF_INIT;
454
	const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
455
	if (old && *old) {
456
		strbuf_addstr(&env, old);
457
		strbuf_addch(&env, ' ');
458
	}
459
	sq_quote_buf(&env, key);
460
	strbuf_addch(&env, '=');
461
	if (value)
462
		sq_quote_buf(&env, value);
463
	setenv(CONFIG_DATA_ENVIRONMENT, env.buf, 1);
464
	strbuf_release(&env);
465
}
466

467
void git_config_push_parameter(const char *text)
468
{
469
	const char *value;
470

471
	/*
472
	 * When we see:
473
	 *
474
	 *   section.subsection=with=equals.key=value
475
	 *
476
	 * we cannot tell if it means:
477
	 *
478
	 *   [section "subsection=with=equals"]
479
	 *   key = value
480
	 *
481
	 * or:
482
	 *
483
	 *   [section]
484
	 *   subsection = with=equals.key=value
485
	 *
486
	 * We parse left-to-right for the first "=", meaning we'll prefer to
487
	 * keep the value intact over the subsection. This is historical, but
488
	 * also sensible since values are more likely to contain odd or
489
	 * untrusted input than a section name.
490
	 *
491
	 * A missing equals is explicitly allowed (as a bool-only entry).
492
	 */
493
	value = strchr(text, '=');
494
	if (value) {
495
		char *key = xmemdupz(text, value - text);
496
		git_config_push_split_parameter(key, value + 1);
497
		free(key);
498
	} else {
499
		git_config_push_split_parameter(text, NULL);
500
	}
501
}
502

503
void git_config_push_env(const char *spec)
504
{
505
	char *key;
506
	const char *env_name;
507
	const char *env_value;
508

509
	env_name = strrchr(spec, '=');
510
	if (!env_name)
511
		die(_("invalid config format: %s"), spec);
512
	key = xmemdupz(spec, env_name - spec);
513
	env_name++;
514
	if (!*env_name)
515
		die(_("missing environment variable name for configuration '%.*s'"),
516
		    (int)(env_name - spec - 1), spec);
517

518
	env_value = getenv(env_name);
519
	if (!env_value)
520
		die(_("missing environment variable '%s' for configuration '%.*s'"),
521
		    env_name, (int)(env_name - spec - 1), spec);
522

523
	git_config_push_split_parameter(key, env_value);
524
	free(key);
525
}
526

527
static inline int iskeychar(int c)
528
{
529
	return isalnum(c) || c == '-';
530
}
531

532
/*
533
 * Auxiliary function to sanity-check and split the key into the section
534
 * identifier and variable name.
535
 *
536
 * Returns 0 on success, -1 when there is an invalid character in the key and
537
 * -2 if there is no section name in the key.
538
 *
539
 * store_key - pointer to char* which will hold a copy of the key with
540
 *             lowercase section and variable name
541
 * baselen - pointer to size_t which will hold the length of the
542
 *           section + subsection part, can be NULL
543
 */
544
int git_config_parse_key(const char *key, char **store_key, size_t *baselen_)
545
{
546
	size_t i, baselen;
547
	int dot;
548
	const char *last_dot = strrchr(key, '.');
549

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

555
	if (last_dot == NULL || last_dot == key) {
556
		error(_("key does not contain a section: %s"), key);
557
		return -CONFIG_NO_SECTION_OR_NAME;
558
	}
559

560
	if (!last_dot[1]) {
561
		error(_("key does not contain variable name: %s"), key);
562
		return -CONFIG_NO_SECTION_OR_NAME;
563
	}
564

565
	baselen = last_dot - key;
566
	if (baselen_)
567
		*baselen_ = baselen;
568

569
	/*
570
	 * Validate the key and while at it, lower case it for matching.
571
	 */
572
	*store_key = xmallocz(strlen(key));
573

574
	dot = 0;
575
	for (i = 0; key[i]; i++) {
576
		unsigned char c = key[i];
577
		if (c == '.')
578
			dot = 1;
579
		/* Leave the extended basename untouched.. */
580
		if (!dot || i > baselen) {
581
			if (!iskeychar(c) ||
582
			    (i == baselen + 1 && !isalpha(c))) {
583
				error(_("invalid key: %s"), key);
584
				goto out_free_ret_1;
585
			}
586
			c = tolower(c);
587
		} else if (c == '\n') {
588
			error(_("invalid key (newline): %s"), key);
589
			goto out_free_ret_1;
590
		}
591
		(*store_key)[i] = c;
592
	}
593

594
	return 0;
595

596
out_free_ret_1:
597
	FREE_AND_NULL(*store_key);
598
	return -CONFIG_INVALID_KEY;
599
}
600

601
static int config_parse_pair(const char *key, const char *value,
602
			     struct key_value_info *kvi,
603
			     config_fn_t fn, void *data)
604
{
605
	char *canonical_name;
606
	int ret;
607
	struct config_context ctx = {
608
		.kvi = kvi,
609
	};
610

611
	if (!strlen(key))
612
		return error(_("empty config key"));
613
	if (git_config_parse_key(key, &canonical_name, NULL))
614
		return -1;
615

616
	ret = (fn(canonical_name, value, &ctx, data) < 0) ? -1 : 0;
617
	free(canonical_name);
618
	return ret;
619
}
620

621

622
/* for values read from `git_config_from_parameters()` */
623
void kvi_from_param(struct key_value_info *out)
624
{
625
	out->filename = NULL;
626
	out->linenr = -1;
627
	out->origin_type = CONFIG_ORIGIN_CMDLINE;
628
	out->scope = CONFIG_SCOPE_COMMAND;
629
	out->path = NULL;
630
}
631

632
int git_config_parse_parameter(const char *text,
633
			       config_fn_t fn, void *data)
634
{
635
	const char *value;
636
	struct strbuf **pair;
637
	int ret;
638
	struct key_value_info kvi = KVI_INIT;
639

640
	kvi_from_param(&kvi);
641

642
	pair = strbuf_split_str(text, '=', 2);
643
	if (!pair[0])
644
		return error(_("bogus config parameter: %s"), text);
645

646
	if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=') {
647
		strbuf_setlen(pair[0], pair[0]->len - 1);
648
		value = pair[1] ? pair[1]->buf : "";
649
	} else {
650
		value = NULL;
651
	}
652

653
	strbuf_trim(pair[0]);
654
	if (!pair[0]->len) {
655
		strbuf_list_free(pair);
656
		return error(_("bogus config parameter: %s"), text);
657
	}
658

659
	ret = config_parse_pair(pair[0]->buf, value, &kvi, fn, data);
660
	strbuf_list_free(pair);
661
	return ret;
662
}
663

664
static int parse_config_env_list(char *env, struct key_value_info *kvi,
665
				 config_fn_t fn, void *data)
666
{
667
	char *cur = env;
668
	while (cur && *cur) {
669
		const char *key = sq_dequote_step(cur, &cur);
670
		if (!key)
671
			return error(_("bogus format in %s"),
672
				     CONFIG_DATA_ENVIRONMENT);
673

674
		if (!cur || isspace(*cur)) {
675
			/* old-style 'key=value' */
676
			if (git_config_parse_parameter(key, fn, data) < 0)
677
				return -1;
678
		}
679
		else if (*cur == '=') {
680
			/* new-style 'key'='value' */
681
			const char *value;
682

683
			cur++;
684
			if (*cur == '\'') {
685
				/* quoted value */
686
				value = sq_dequote_step(cur, &cur);
687
				if (!value || (cur && !isspace(*cur))) {
688
					return error(_("bogus format in %s"),
689
						     CONFIG_DATA_ENVIRONMENT);
690
				}
691
			} else if (!*cur || isspace(*cur)) {
692
				/* implicit bool: 'key'= */
693
				value = NULL;
694
			} else {
695
				return error(_("bogus format in %s"),
696
					     CONFIG_DATA_ENVIRONMENT);
697
			}
698

699
			if (config_parse_pair(key, value, kvi, fn, data) < 0)
700
				return -1;
701
		}
702
		else {
703
			/* unknown format */
704
			return error(_("bogus format in %s"),
705
				     CONFIG_DATA_ENVIRONMENT);
706
		}
707

708
		if (cur) {
709
			while (isspace(*cur))
710
				cur++;
711
		}
712
	}
713
	return 0;
714
}
715

716
int git_config_from_parameters(config_fn_t fn, void *data)
717
{
718
	const char *env;
719
	struct strbuf envvar = STRBUF_INIT;
720
	struct strvec to_free = STRVEC_INIT;
721
	int ret = 0;
722
	char *envw = NULL;
723
	struct key_value_info kvi = KVI_INIT;
724

725
	kvi_from_param(&kvi);
726
	env = getenv(CONFIG_COUNT_ENVIRONMENT);
727
	if (env) {
728
		unsigned long count;
729
		char *endp;
730
		int i;
731

732
		count = strtoul(env, &endp, 10);
733
		if (*endp) {
734
			ret = error(_("bogus count in %s"), CONFIG_COUNT_ENVIRONMENT);
735
			goto out;
736
		}
737
		if (count > INT_MAX) {
738
			ret = error(_("too many entries in %s"), CONFIG_COUNT_ENVIRONMENT);
739
			goto out;
740
		}
741

742
		for (i = 0; i < count; i++) {
743
			const char *key, *value;
744

745
			strbuf_addf(&envvar, "GIT_CONFIG_KEY_%d", i);
746
			key = getenv_safe(&to_free, envvar.buf);
747
			if (!key) {
748
				ret = error(_("missing config key %s"), envvar.buf);
749
				goto out;
750
			}
751
			strbuf_reset(&envvar);
752

753
			strbuf_addf(&envvar, "GIT_CONFIG_VALUE_%d", i);
754
			value = getenv_safe(&to_free, envvar.buf);
755
			if (!value) {
756
				ret = error(_("missing config value %s"), envvar.buf);
757
				goto out;
758
			}
759
			strbuf_reset(&envvar);
760

761
			if (config_parse_pair(key, value, &kvi, fn, data) < 0) {
762
				ret = -1;
763
				goto out;
764
			}
765
		}
766
	}
767

768
	env = getenv(CONFIG_DATA_ENVIRONMENT);
769
	if (env) {
770
		/* sq_dequote will write over it */
771
		envw = xstrdup(env);
772
		if (parse_config_env_list(envw, &kvi, fn, data) < 0) {
773
			ret = -1;
774
			goto out;
775
		}
776
	}
777

778
out:
779
	strbuf_release(&envvar);
780
	strvec_clear(&to_free);
781
	free(envw);
782
	return ret;
783
}
784

785
static int get_next_char(struct config_source *cs)
786
{
787
	int c = cs->do_fgetc(cs);
788

789
	if (c == '\r') {
790
		/* DOS like systems */
791
		c = cs->do_fgetc(cs);
792
		if (c != '\n') {
793
			if (c != EOF)
794
				cs->do_ungetc(c, cs);
795
			c = '\r';
796
		}
797
	}
798

799
	if (c != EOF && ++cs->total_len > INT_MAX) {
800
		/*
801
		 * This is an absurdly long config file; refuse to parse
802
		 * further in order to protect downstream code from integer
803
		 * overflows. Note that we can't return an error specifically,
804
		 * but we can mark EOF and put trash in the return value,
805
		 * which will trigger a parse error.
806
		 */
807
		cs->eof = 1;
808
		return 0;
809
	}
810

811
	if (c == '\n')
812
		cs->linenr++;
813
	if (c == EOF) {
814
		cs->eof = 1;
815
		cs->linenr++;
816
		c = '\n';
817
	}
818
	return c;
819
}
820

821
static char *parse_value(struct config_source *cs)
822
{
823
	int quote = 0, comment = 0;
824
	size_t trim_len = 0;
825

826
	strbuf_reset(&cs->value);
827
	for (;;) {
828
		int c = get_next_char(cs);
829
		if (c == '\n') {
830
			if (quote) {
831
				cs->linenr--;
832
				return NULL;
833
			}
834
			if (trim_len)
835
				strbuf_setlen(&cs->value, trim_len);
836
			return cs->value.buf;
837
		}
838
		if (comment)
839
			continue;
840
		if (isspace(c) && !quote) {
841
			if (!trim_len)
842
				trim_len = cs->value.len;
843
			if (cs->value.len)
844
				strbuf_addch(&cs->value, c);
845
			continue;
846
		}
847
		if (!quote) {
848
			if (c == ';' || c == '#') {
849
				comment = 1;
850
				continue;
851
			}
852
		}
853
		if (trim_len)
854
			trim_len = 0;
855
		if (c == '\\') {
856
			c = get_next_char(cs);
857
			switch (c) {
858
			case '\n':
859
				continue;
860
			case 't':
861
				c = '\t';
862
				break;
863
			case 'b':
864
				c = '\b';
865
				break;
866
			case 'n':
867
				c = '\n';
868
				break;
869
			/* Some characters escape as themselves */
870
			case '\\': case '"':
871
				break;
872
			/* Reject unknown escape sequences */
873
			default:
874
				return NULL;
875
			}
876
			strbuf_addch(&cs->value, c);
877
			continue;
878
		}
879
		if (c == '"') {
880
			quote = 1 - quote;
881
			continue;
882
		}
883
		strbuf_addch(&cs->value, c);
884
	}
885
}
886

887
static int get_value(struct config_source *cs, struct key_value_info *kvi,
888
		     config_fn_t fn, void *data, struct strbuf *name)
889
{
890
	int c;
891
	char *value;
892
	int ret;
893
	struct config_context ctx = {
894
		.kvi = kvi,
895
	};
896

897
	/* Get the full name */
898
	for (;;) {
899
		c = get_next_char(cs);
900
		if (cs->eof)
901
			break;
902
		if (!iskeychar(c))
903
			break;
904
		strbuf_addch(name, tolower(c));
905
	}
906

907
	while (c == ' ' || c == '\t')
908
		c = get_next_char(cs);
909

910
	value = NULL;
911
	if (c != '\n') {
912
		if (c != '=')
913
			return -1;
914
		value = parse_value(cs);
915
		if (!value)
916
			return -1;
917
	}
918
	/*
919
	 * We already consumed the \n, but we need linenr to point to
920
	 * the line we just parsed during the call to fn to get
921
	 * accurate line number in error messages.
922
	 */
923
	cs->linenr--;
924
	kvi->linenr = cs->linenr;
925
	ret = fn(name->buf, value, &ctx, data);
926
	if (ret >= 0)
927
		cs->linenr++;
928
	return ret;
929
}
930

931
static int get_extended_base_var(struct config_source *cs, struct strbuf *name,
932
				 int c)
933
{
934
	cs->subsection_case_sensitive = 0;
935
	do {
936
		if (c == '\n')
937
			goto error_incomplete_line;
938
		c = get_next_char(cs);
939
	} while (isspace(c));
940

941
	/* We require the format to be '[base "extension"]' */
942
	if (c != '"')
943
		return -1;
944
	strbuf_addch(name, '.');
945

946
	for (;;) {
947
		int c = get_next_char(cs);
948
		if (c == '\n')
949
			goto error_incomplete_line;
950
		if (c == '"')
951
			break;
952
		if (c == '\\') {
953
			c = get_next_char(cs);
954
			if (c == '\n')
955
				goto error_incomplete_line;
956
		}
957
		strbuf_addch(name, c);
958
	}
959

960
	/* Final ']' */
961
	if (get_next_char(cs) != ']')
962
		return -1;
963
	return 0;
964
error_incomplete_line:
965
	cs->linenr--;
966
	return -1;
967
}
968

969
static int get_base_var(struct config_source *cs, struct strbuf *name)
970
{
971
	cs->subsection_case_sensitive = 1;
972
	for (;;) {
973
		int c = get_next_char(cs);
974
		if (cs->eof)
975
			return -1;
976
		if (c == ']')
977
			return 0;
978
		if (isspace(c))
979
			return get_extended_base_var(cs, name, c);
980
		if (!iskeychar(c) && c != '.')
981
			return -1;
982
		strbuf_addch(name, tolower(c));
983
	}
984
}
985

986
struct parse_event_data {
987
	enum config_event_t previous_type;
988
	size_t previous_offset;
989
	const struct config_options *opts;
990
};
991

992
static int do_event(struct config_source *cs, enum config_event_t type,
993
		    struct parse_event_data *data)
994
{
995
	size_t offset;
996

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

1000
	if (type == CONFIG_EVENT_WHITESPACE &&
1001
	    data->previous_type == type)
1002
		return 0;
1003

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

1013
	if (data->previous_type != CONFIG_EVENT_EOF &&
1014
	    data->opts->event_fn(data->previous_type, data->previous_offset,
1015
				 offset, cs, data->opts->event_fn_data) < 0)
1016
		return -1;
1017

1018
	data->previous_type = type;
1019
	data->previous_offset = offset;
1020

1021
	return 0;
1022
}
1023

1024
static void kvi_from_source(struct config_source *cs,
1025
			    enum config_scope scope,
1026
			    struct key_value_info *out)
1027
{
1028
	out->filename = strintern(cs->name);
1029
	out->origin_type = cs->origin_type;
1030
	out->linenr = cs->linenr;
1031
	out->scope = scope;
1032
	out->path = cs->path;
1033
}
1034

1035
static int git_parse_source(struct config_source *cs, config_fn_t fn,
1036
			    struct key_value_info *kvi, void *data,
1037
			    const struct config_options *opts)
1038
{
1039
	int comment = 0;
1040
	size_t baselen = 0;
1041
	struct strbuf *var = &cs->var;
1042
	int error_return = 0;
1043
	char *error_msg = NULL;
1044

1045
	/* U+FEFF Byte Order Mark in UTF8 */
1046
	const char *bomptr = utf8_bom;
1047

1048
	/* For the parser event callback */
1049
	struct parse_event_data event_data = {
1050
		CONFIG_EVENT_EOF, 0, opts
1051
	};
1052

1053
	for (;;) {
1054
		int c;
1055

1056
		c = get_next_char(cs);
1057
		if (bomptr && *bomptr) {
1058
			/* We are at the file beginning; skip UTF8-encoded BOM
1059
			 * if present. Sane editors won't put this in on their
1060
			 * own, but e.g. Windows Notepad will do it happily. */
1061
			if (c == (*bomptr & 0377)) {
1062
				bomptr++;
1063
				continue;
1064
			} else {
1065
				/* Do not tolerate partial BOM. */
1066
				if (bomptr != utf8_bom)
1067
					break;
1068
				/* No BOM at file beginning. Cool. */
1069
				bomptr = NULL;
1070
			}
1071
		}
1072
		if (c == '\n') {
1073
			if (cs->eof) {
1074
				if (do_event(cs, CONFIG_EVENT_EOF, &event_data) < 0)
1075
					return -1;
1076
				return 0;
1077
			}
1078
			if (do_event(cs, CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1079
				return -1;
1080
			comment = 0;
1081
			continue;
1082
		}
1083
		if (comment)
1084
			continue;
1085
		if (isspace(c)) {
1086
			if (do_event(cs, CONFIG_EVENT_WHITESPACE, &event_data) < 0)
1087
					return -1;
1088
			continue;
1089
		}
1090
		if (c == '#' || c == ';') {
1091
			if (do_event(cs, CONFIG_EVENT_COMMENT, &event_data) < 0)
1092
					return -1;
1093
			comment = 1;
1094
			continue;
1095
		}
1096
		if (c == '[') {
1097
			if (do_event(cs, CONFIG_EVENT_SECTION, &event_data) < 0)
1098
					return -1;
1099

1100
			/* Reset prior to determining a new stem */
1101
			strbuf_reset(var);
1102
			if (get_base_var(cs, var) < 0 || var->len < 1)
1103
				break;
1104
			strbuf_addch(var, '.');
1105
			baselen = var->len;
1106
			continue;
1107
		}
1108
		if (!isalpha(c))
1109
			break;
1110

1111
		if (do_event(cs, CONFIG_EVENT_ENTRY, &event_data) < 0)
1112
			return -1;
1113

1114
		/*
1115
		 * Truncate the var name back to the section header
1116
		 * stem prior to grabbing the suffix part of the name
1117
		 * and the value.
1118
		 */
1119
		strbuf_setlen(var, baselen);
1120
		strbuf_addch(var, tolower(c));
1121
		if (get_value(cs, kvi, fn, data, var) < 0)
1122
			break;
1123
	}
1124

1125
	if (do_event(cs, CONFIG_EVENT_ERROR, &event_data) < 0)
1126
		return -1;
1127

1128
	switch (cs->origin_type) {
1129
	case CONFIG_ORIGIN_BLOB:
1130
		error_msg = xstrfmt(_("bad config line %d in blob %s"),
1131
				      cs->linenr, cs->name);
1132
		break;
1133
	case CONFIG_ORIGIN_FILE:
1134
		error_msg = xstrfmt(_("bad config line %d in file %s"),
1135
				      cs->linenr, cs->name);
1136
		break;
1137
	case CONFIG_ORIGIN_STDIN:
1138
		error_msg = xstrfmt(_("bad config line %d in standard input"),
1139
				      cs->linenr);
1140
		break;
1141
	case CONFIG_ORIGIN_SUBMODULE_BLOB:
1142
		error_msg = xstrfmt(_("bad config line %d in submodule-blob %s"),
1143
				       cs->linenr, cs->name);
1144
		break;
1145
	case CONFIG_ORIGIN_CMDLINE:
1146
		error_msg = xstrfmt(_("bad config line %d in command line %s"),
1147
				       cs->linenr, cs->name);
1148
		break;
1149
	default:
1150
		error_msg = xstrfmt(_("bad config line %d in %s"),
1151
				      cs->linenr, cs->name);
1152
	}
1153

1154
	switch (opts && opts->error_action ?
1155
		opts->error_action :
1156
		cs->default_error_action) {
1157
	case CONFIG_ERROR_DIE:
1158
		die("%s", error_msg);
1159
		break;
1160
	case CONFIG_ERROR_ERROR:
1161
		error_return = error("%s", error_msg);
1162
		break;
1163
	case CONFIG_ERROR_SILENT:
1164
		error_return = -1;
1165
		break;
1166
	case CONFIG_ERROR_UNSET:
1167
		BUG("config error action unset");
1168
	}
1169

1170
	free(error_msg);
1171
	return error_return;
1172
}
1173

1174
NORETURN
1175
static void die_bad_number(const char *name, const char *value,
1176
			   const struct key_value_info *kvi)
1177
{
1178
	const char *error_type = (errno == ERANGE) ?
1179
		N_("out of range") : N_("invalid unit");
1180
	const char *bad_numeric = N_("bad numeric config value '%s' for '%s': %s");
1181

1182
	if (!kvi)
1183
		BUG("kvi should not be NULL");
1184

1185
	if (!value)
1186
		value = "";
1187

1188
	if (!kvi->filename)
1189
		die(_(bad_numeric), value, name, _(error_type));
1190

1191
	switch (kvi->origin_type) {
1192
	case CONFIG_ORIGIN_BLOB:
1193
		die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
1194
		    value, name, kvi->filename, _(error_type));
1195
	case CONFIG_ORIGIN_FILE:
1196
		die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
1197
		    value, name, kvi->filename, _(error_type));
1198
	case CONFIG_ORIGIN_STDIN:
1199
		die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
1200
		    value, name, _(error_type));
1201
	case CONFIG_ORIGIN_SUBMODULE_BLOB:
1202
		die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
1203
		    value, name, kvi->filename, _(error_type));
1204
	case CONFIG_ORIGIN_CMDLINE:
1205
		die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
1206
		    value, name, kvi->filename, _(error_type));
1207
	default:
1208
		die(_("bad numeric config value '%s' for '%s' in %s: %s"),
1209
		    value, name, kvi->filename, _(error_type));
1210
	}
1211
}
1212

1213
int git_config_int(const char *name, const char *value,
1214
		   const struct key_value_info *kvi)
1215
{
1216
	int ret;
1217
	if (!git_parse_int(value, &ret))
1218
		die_bad_number(name, value, kvi);
1219
	return ret;
1220
}
1221

1222
int64_t git_config_int64(const char *name, const char *value,
1223
			 const struct key_value_info *kvi)
1224
{
1225
	int64_t ret;
1226
	if (!git_parse_int64(value, &ret))
1227
		die_bad_number(name, value, kvi);
1228
	return ret;
1229
}
1230

1231
unsigned long git_config_ulong(const char *name, const char *value,
1232
			       const struct key_value_info *kvi)
1233
{
1234
	unsigned long ret;
1235
	if (!git_parse_ulong(value, &ret))
1236
		die_bad_number(name, value, kvi);
1237
	return ret;
1238
}
1239

1240
ssize_t git_config_ssize_t(const char *name, const char *value,
1241
			   const struct key_value_info *kvi)
1242
{
1243
	ssize_t ret;
1244
	if (!git_parse_ssize_t(value, &ret))
1245
		die_bad_number(name, value, kvi);
1246
	return ret;
1247
}
1248

1249
double git_config_double(const char *name, const char *value,
1250
			 const struct key_value_info *kvi)
1251
{
1252
	double ret;
1253
	if (!git_parse_double(value, &ret))
1254
		die_bad_number(name, value, kvi);
1255
	return ret;
1256
}
1257

1258
static const struct fsync_component_name {
1259
	const char *name;
1260
	enum fsync_component component_bits;
1261
} fsync_component_names[] = {
1262
	{ "loose-object", FSYNC_COMPONENT_LOOSE_OBJECT },
1263
	{ "pack", FSYNC_COMPONENT_PACK },
1264
	{ "pack-metadata", FSYNC_COMPONENT_PACK_METADATA },
1265
	{ "commit-graph", FSYNC_COMPONENT_COMMIT_GRAPH },
1266
	{ "index", FSYNC_COMPONENT_INDEX },
1267
	{ "objects", FSYNC_COMPONENTS_OBJECTS },
1268
	{ "reference", FSYNC_COMPONENT_REFERENCE },
1269
	{ "derived-metadata", FSYNC_COMPONENTS_DERIVED_METADATA },
1270
	{ "committed", FSYNC_COMPONENTS_COMMITTED },
1271
	{ "added", FSYNC_COMPONENTS_ADDED },
1272
	{ "all", FSYNC_COMPONENTS_ALL },
1273
};
1274

1275
static enum fsync_component parse_fsync_components(const char *var, const char *string)
1276
{
1277
	enum fsync_component current = FSYNC_COMPONENTS_PLATFORM_DEFAULT;
1278
	enum fsync_component positive = 0, negative = 0;
1279

1280
	while (string) {
1281
		int i;
1282
		size_t len;
1283
		const char *ep;
1284
		int negated = 0;
1285
		int found = 0;
1286

1287
		string = string + strspn(string, ", \t\n\r");
1288
		ep = strchrnul(string, ',');
1289
		len = ep - string;
1290
		if (!strcmp(string, "none")) {
1291
			current = FSYNC_COMPONENT_NONE;
1292
			goto next_name;
1293
		}
1294

1295
		if (*string == '-') {
1296
			negated = 1;
1297
			string++;
1298
			len--;
1299
			if (!len)
1300
				warning(_("invalid value for variable %s"), var);
1301
		}
1302

1303
		if (!len)
1304
			break;
1305

1306
		for (i = 0; i < ARRAY_SIZE(fsync_component_names); ++i) {
1307
			const struct fsync_component_name *n = &fsync_component_names[i];
1308

1309
			if (strncmp(n->name, string, len))
1310
				continue;
1311

1312
			found = 1;
1313
			if (negated)
1314
				negative |= n->component_bits;
1315
			else
1316
				positive |= n->component_bits;
1317
		}
1318

1319
		if (!found) {
1320
			char *component = xstrndup(string, len);
1321
			warning(_("ignoring unknown core.fsync component '%s'"), component);
1322
			free(component);
1323
		}
1324

1325
next_name:
1326
		string = ep;
1327
	}
1328

1329
	return (current & ~negative) | positive;
1330
}
1331

1332
int git_config_bool_or_int(const char *name, const char *value,
1333
			   const struct key_value_info *kvi, int *is_bool)
1334
{
1335
	int v = git_parse_maybe_bool_text(value);
1336
	if (0 <= v) {
1337
		*is_bool = 1;
1338
		return v;
1339
	}
1340
	*is_bool = 0;
1341
	return git_config_int(name, value, kvi);
1342
}
1343

1344
int git_config_bool(const char *name, const char *value)
1345
{
1346
	int v = git_parse_maybe_bool(value);
1347
	if (v < 0)
1348
		die(_("bad boolean config value '%s' for '%s'"), value, name);
1349
	return v;
1350
}
1351

1352
int git_config_string(char **dest, const char *var, const char *value)
1353
{
1354
	if (!value)
1355
		return config_error_nonbool(var);
1356
	*dest = xstrdup(value);
1357
	return 0;
1358
}
1359

1360
int git_config_pathname(char **dest, const char *var, const char *value)
1361
{
1362
	if (!value)
1363
		return config_error_nonbool(var);
1364
	*dest = interpolate_path(value, 0);
1365
	if (!*dest)
1366
		die(_("failed to expand user dir in: '%s'"), value);
1367
	return 0;
1368
}
1369

1370
int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *value)
1371
{
1372
	if (!value)
1373
		return config_error_nonbool(var);
1374
	if (parse_expiry_date(value, timestamp))
1375
		return error(_("'%s' for '%s' is not a valid timestamp"),
1376
			     value, var);
1377
	return 0;
1378
}
1379

1380
int git_config_color(char *dest, const char *var, const char *value)
1381
{
1382
	if (!value)
1383
		return config_error_nonbool(var);
1384
	if (color_parse(value, dest) < 0)
1385
		return -1;
1386
	return 0;
1387
}
1388

1389
static int git_default_core_config(const char *var, const char *value,
1390
				   const struct config_context *ctx, void *cb)
1391
{
1392
	/* This needs a better name */
1393
	if (!strcmp(var, "core.filemode")) {
1394
		trust_executable_bit = git_config_bool(var, value);
1395
		return 0;
1396
	}
1397
	if (!strcmp(var, "core.trustctime")) {
1398
		trust_ctime = git_config_bool(var, value);
1399
		return 0;
1400
	}
1401
	if (!strcmp(var, "core.checkstat")) {
1402
		if (!value)
1403
			return config_error_nonbool(var);
1404
		if (!strcasecmp(value, "default"))
1405
			check_stat = 1;
1406
		else if (!strcasecmp(value, "minimal"))
1407
			check_stat = 0;
1408
		else
1409
			return error(_("invalid value for '%s': '%s'"),
1410
				     var, value);
1411
	}
1412

1413
	if (!strcmp(var, "core.quotepath")) {
1414
		quote_path_fully = git_config_bool(var, value);
1415
		return 0;
1416
	}
1417

1418
	if (!strcmp(var, "core.symlinks")) {
1419
		has_symlinks = git_config_bool(var, value);
1420
		return 0;
1421
	}
1422

1423
	if (!strcmp(var, "core.ignorecase")) {
1424
		ignore_case = git_config_bool(var, value);
1425
		return 0;
1426
	}
1427

1428
	if (!strcmp(var, "core.attributesfile")) {
1429
		FREE_AND_NULL(git_attributes_file);
1430
		return git_config_pathname(&git_attributes_file, var, value);
1431
	}
1432

1433
	if (!strcmp(var, "core.hookspath")) {
1434
		FREE_AND_NULL(git_hooks_path);
1435
		return git_config_pathname(&git_hooks_path, var, value);
1436
	}
1437

1438
	if (!strcmp(var, "core.bare")) {
1439
		is_bare_repository_cfg = git_config_bool(var, value);
1440
		return 0;
1441
	}
1442

1443
	if (!strcmp(var, "core.ignorestat")) {
1444
		assume_unchanged = git_config_bool(var, value);
1445
		return 0;
1446
	}
1447

1448
	if (!strcmp(var, "core.prefersymlinkrefs")) {
1449
		prefer_symlink_refs = git_config_bool(var, value);
1450
		return 0;
1451
	}
1452

1453
	if (!strcmp(var, "core.logallrefupdates")) {
1454
		if (value && !strcasecmp(value, "always"))
1455
			log_all_ref_updates = LOG_REFS_ALWAYS;
1456
		else if (git_config_bool(var, value))
1457
			log_all_ref_updates = LOG_REFS_NORMAL;
1458
		else
1459
			log_all_ref_updates = LOG_REFS_NONE;
1460
		return 0;
1461
	}
1462

1463
	if (!strcmp(var, "core.warnambiguousrefs")) {
1464
		warn_ambiguous_refs = git_config_bool(var, value);
1465
		return 0;
1466
	}
1467

1468
	if (!strcmp(var, "core.abbrev")) {
1469
		if (!value)
1470
			return config_error_nonbool(var);
1471
		if (!strcasecmp(value, "auto"))
1472
			default_abbrev = -1;
1473
		else if (!git_parse_maybe_bool_text(value))
1474
			default_abbrev = GIT_MAX_HEXSZ;
1475
		else {
1476
			int abbrev = git_config_int(var, value, ctx->kvi);
1477
			if (abbrev < minimum_abbrev)
1478
				return error(_("abbrev length out of range: %d"), abbrev);
1479
			default_abbrev = abbrev;
1480
		}
1481
		return 0;
1482
	}
1483

1484
	if (!strcmp(var, "core.disambiguate"))
1485
		return set_disambiguate_hint_config(var, value);
1486

1487
	if (!strcmp(var, "core.loosecompression")) {
1488
		int level = git_config_int(var, value, ctx->kvi);
1489
		if (level == -1)
1490
			level = Z_DEFAULT_COMPRESSION;
1491
		else if (level < 0 || level > Z_BEST_COMPRESSION)
1492
			die(_("bad zlib compression level %d"), level);
1493
		zlib_compression_level = level;
1494
		zlib_compression_seen = 1;
1495
		return 0;
1496
	}
1497

1498
	if (!strcmp(var, "core.compression")) {
1499
		int level = git_config_int(var, value, ctx->kvi);
1500
		if (level == -1)
1501
			level = Z_DEFAULT_COMPRESSION;
1502
		else if (level < 0 || level > Z_BEST_COMPRESSION)
1503
			die(_("bad zlib compression level %d"), level);
1504
		if (!zlib_compression_seen)
1505
			zlib_compression_level = level;
1506
		if (!pack_compression_seen)
1507
			pack_compression_level = level;
1508
		return 0;
1509
	}
1510

1511
	if (!strcmp(var, "core.packedgitwindowsize")) {
1512
		int pgsz_x2 = getpagesize() * 2;
1513
		packed_git_window_size = git_config_ulong(var, value, ctx->kvi);
1514

1515
		/* This value must be multiple of (pagesize * 2) */
1516
		packed_git_window_size /= pgsz_x2;
1517
		if (packed_git_window_size < 1)
1518
			packed_git_window_size = 1;
1519
		packed_git_window_size *= pgsz_x2;
1520
		return 0;
1521
	}
1522

1523
	if (!strcmp(var, "core.bigfilethreshold")) {
1524
		big_file_threshold = git_config_ulong(var, value, ctx->kvi);
1525
		return 0;
1526
	}
1527

1528
	if (!strcmp(var, "core.packedgitlimit")) {
1529
		packed_git_limit = git_config_ulong(var, value, ctx->kvi);
1530
		return 0;
1531
	}
1532

1533
	if (!strcmp(var, "core.deltabasecachelimit")) {
1534
		delta_base_cache_limit = git_config_ulong(var, value, ctx->kvi);
1535
		return 0;
1536
	}
1537

1538
	if (!strcmp(var, "core.autocrlf")) {
1539
		if (value && !strcasecmp(value, "input")) {
1540
			auto_crlf = AUTO_CRLF_INPUT;
1541
			return 0;
1542
		}
1543
		auto_crlf = git_config_bool(var, value);
1544
		return 0;
1545
	}
1546

1547
	if (!strcmp(var, "core.safecrlf")) {
1548
		int eol_rndtrp_die;
1549
		if (value && !strcasecmp(value, "warn")) {
1550
			global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
1551
			return 0;
1552
		}
1553
		eol_rndtrp_die = git_config_bool(var, value);
1554
		global_conv_flags_eol = eol_rndtrp_die ?
1555
			CONV_EOL_RNDTRP_DIE : 0;
1556
		return 0;
1557
	}
1558

1559
	if (!strcmp(var, "core.eol")) {
1560
		if (value && !strcasecmp(value, "lf"))
1561
			core_eol = EOL_LF;
1562
		else if (value && !strcasecmp(value, "crlf"))
1563
			core_eol = EOL_CRLF;
1564
		else if (value && !strcasecmp(value, "native"))
1565
			core_eol = EOL_NATIVE;
1566
		else
1567
			core_eol = EOL_UNSET;
1568
		return 0;
1569
	}
1570

1571
	if (!strcmp(var, "core.checkroundtripencoding")) {
1572
		FREE_AND_NULL(check_roundtrip_encoding);
1573
		return git_config_string(&check_roundtrip_encoding, var, value);
1574
	}
1575

1576
	if (!strcmp(var, "core.notesref")) {
1577
		if (!value)
1578
			return config_error_nonbool(var);
1579
		free(notes_ref_name);
1580
		notes_ref_name = xstrdup(value);
1581
		return 0;
1582
	}
1583

1584
	if (!strcmp(var, "core.editor")) {
1585
		FREE_AND_NULL(editor_program);
1586
		return git_config_string(&editor_program, var, value);
1587
	}
1588

1589
	if (!strcmp(var, "core.commentchar") ||
1590
	    !strcmp(var, "core.commentstring")) {
1591
		if (!value)
1592
			return config_error_nonbool(var);
1593
		else if (!strcasecmp(value, "auto"))
1594
			auto_comment_line_char = 1;
1595
		else if (value[0]) {
1596
			if (strchr(value, '\n'))
1597
				return error(_("%s cannot contain newline"), var);
1598
			comment_line_str = value;
1599
			FREE_AND_NULL(comment_line_str_to_free);
1600
			auto_comment_line_char = 0;
1601
		} else
1602
			return error(_("%s must have at least one character"), var);
1603
		return 0;
1604
	}
1605

1606
	if (!strcmp(var, "core.askpass")) {
1607
		FREE_AND_NULL(askpass_program);
1608
		return git_config_string(&askpass_program, var, value);
1609
	}
1610

1611
	if (!strcmp(var, "core.excludesfile")) {
1612
		FREE_AND_NULL(excludes_file);
1613
		return git_config_pathname(&excludes_file, var, value);
1614
	}
1615

1616
	if (!strcmp(var, "core.whitespace")) {
1617
		if (!value)
1618
			return config_error_nonbool(var);
1619
		whitespace_rule_cfg = parse_whitespace_rule(value);
1620
		return 0;
1621
	}
1622

1623
	if (!strcmp(var, "core.fsync")) {
1624
		if (!value)
1625
			return config_error_nonbool(var);
1626
		fsync_components = parse_fsync_components(var, value);
1627
		return 0;
1628
	}
1629

1630
	if (!strcmp(var, "core.fsyncmethod")) {
1631
		if (!value)
1632
			return config_error_nonbool(var);
1633
		if (!strcmp(value, "fsync"))
1634
			fsync_method = FSYNC_METHOD_FSYNC;
1635
		else if (!strcmp(value, "writeout-only"))
1636
			fsync_method = FSYNC_METHOD_WRITEOUT_ONLY;
1637
		else if (!strcmp(value, "batch"))
1638
			fsync_method = FSYNC_METHOD_BATCH;
1639
		else
1640
			warning(_("ignoring unknown core.fsyncMethod value '%s'"), value);
1641

1642
	}
1643

1644
	if (!strcmp(var, "core.fsyncobjectfiles")) {
1645
		if (fsync_object_files < 0)
1646
			warning(_("core.fsyncObjectFiles is deprecated; use core.fsync instead"));
1647
		fsync_object_files = git_config_bool(var, value);
1648
		return 0;
1649
	}
1650

1651
	if (!strcmp(var, "core.preloadindex")) {
1652
		core_preload_index = git_config_bool(var, value);
1653
		return 0;
1654
	}
1655

1656
	if (!strcmp(var, "core.createobject")) {
1657
		if (!value)
1658
			return config_error_nonbool(var);
1659
		if (!strcmp(value, "rename"))
1660
			object_creation_mode = OBJECT_CREATION_USES_RENAMES;
1661
		else if (!strcmp(value, "link"))
1662
			object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
1663
		else
1664
			die(_("invalid mode for object creation: %s"), value);
1665
		return 0;
1666
	}
1667

1668
	if (!strcmp(var, "core.sparsecheckout")) {
1669
		core_apply_sparse_checkout = git_config_bool(var, value);
1670
		return 0;
1671
	}
1672

1673
	if (!strcmp(var, "core.sparsecheckoutcone")) {
1674
		core_sparse_checkout_cone = git_config_bool(var, value);
1675
		return 0;
1676
	}
1677

1678
	if (!strcmp(var, "core.precomposeunicode")) {
1679
		precomposed_unicode = git_config_bool(var, value);
1680
		return 0;
1681
	}
1682

1683
	if (!strcmp(var, "core.protecthfs")) {
1684
		protect_hfs = git_config_bool(var, value);
1685
		return 0;
1686
	}
1687

1688
	if (!strcmp(var, "core.protectntfs")) {
1689
		protect_ntfs = git_config_bool(var, value);
1690
		return 0;
1691
	}
1692

1693
	if (!strcmp(var, "core.maxtreedepth")) {
1694
		max_allowed_tree_depth = git_config_int(var, value, ctx->kvi);
1695
		return 0;
1696
	}
1697

1698
	/* Add other config variables here and to Documentation/config.txt. */
1699
	return platform_core_config(var, value, ctx, cb);
1700
}
1701

1702
static int git_default_sparse_config(const char *var, const char *value)
1703
{
1704
	if (!strcmp(var, "sparse.expectfilesoutsideofpatterns")) {
1705
		sparse_expect_files_outside_of_patterns = git_config_bool(var, value);
1706
		return 0;
1707
	}
1708

1709
	/* Add other config variables here and to Documentation/config/sparse.txt. */
1710
	return 0;
1711
}
1712

1713
static int git_default_i18n_config(const char *var, const char *value)
1714
{
1715
	if (!strcmp(var, "i18n.commitencoding")) {
1716
		FREE_AND_NULL(git_commit_encoding);
1717
		return git_config_string(&git_commit_encoding, var, value);
1718
	}
1719

1720
	if (!strcmp(var, "i18n.logoutputencoding")) {
1721
		FREE_AND_NULL(git_log_output_encoding);
1722
		return git_config_string(&git_log_output_encoding, var, value);
1723
	}
1724

1725
	/* Add other config variables here and to Documentation/config.txt. */
1726
	return 0;
1727
}
1728

1729
static int git_default_branch_config(const char *var, const char *value)
1730
{
1731
	if (!strcmp(var, "branch.autosetupmerge")) {
1732
		if (value && !strcmp(value, "always")) {
1733
			git_branch_track = BRANCH_TRACK_ALWAYS;
1734
			return 0;
1735
		} else if (value && !strcmp(value, "inherit")) {
1736
			git_branch_track = BRANCH_TRACK_INHERIT;
1737
			return 0;
1738
		} else if (value && !strcmp(value, "simple")) {
1739
			git_branch_track = BRANCH_TRACK_SIMPLE;
1740
			return 0;
1741
		}
1742
		git_branch_track = git_config_bool(var, value);
1743
		return 0;
1744
	}
1745
	if (!strcmp(var, "branch.autosetuprebase")) {
1746
		if (!value)
1747
			return config_error_nonbool(var);
1748
		else if (!strcmp(value, "never"))
1749
			autorebase = AUTOREBASE_NEVER;
1750
		else if (!strcmp(value, "local"))
1751
			autorebase = AUTOREBASE_LOCAL;
1752
		else if (!strcmp(value, "remote"))
1753
			autorebase = AUTOREBASE_REMOTE;
1754
		else if (!strcmp(value, "always"))
1755
			autorebase = AUTOREBASE_ALWAYS;
1756
		else
1757
			return error(_("malformed value for %s"), var);
1758
		return 0;
1759
	}
1760

1761
	/* Add other config variables here and to Documentation/config.txt. */
1762
	return 0;
1763
}
1764

1765
static int git_default_push_config(const char *var, const char *value)
1766
{
1767
	if (!strcmp(var, "push.default")) {
1768
		if (!value)
1769
			return config_error_nonbool(var);
1770
		else if (!strcmp(value, "nothing"))
1771
			push_default = PUSH_DEFAULT_NOTHING;
1772
		else if (!strcmp(value, "matching"))
1773
			push_default = PUSH_DEFAULT_MATCHING;
1774
		else if (!strcmp(value, "simple"))
1775
			push_default = PUSH_DEFAULT_SIMPLE;
1776
		else if (!strcmp(value, "upstream"))
1777
			push_default = PUSH_DEFAULT_UPSTREAM;
1778
		else if (!strcmp(value, "tracking")) /* deprecated */
1779
			push_default = PUSH_DEFAULT_UPSTREAM;
1780
		else if (!strcmp(value, "current"))
1781
			push_default = PUSH_DEFAULT_CURRENT;
1782
		else {
1783
			error(_("malformed value for %s: %s"), var, value);
1784
			return error(_("must be one of nothing, matching, simple, "
1785
				       "upstream or current"));
1786
		}
1787
		return 0;
1788
	}
1789

1790
	/* Add other config variables here and to Documentation/config.txt. */
1791
	return 0;
1792
}
1793

1794
static int git_default_mailmap_config(const char *var, const char *value)
1795
{
1796
	if (!strcmp(var, "mailmap.file")) {
1797
		FREE_AND_NULL(git_mailmap_file);
1798
		return git_config_pathname(&git_mailmap_file, var, value);
1799
	}
1800

1801
	if (!strcmp(var, "mailmap.blob")) {
1802
		FREE_AND_NULL(git_mailmap_blob);
1803
		return git_config_string(&git_mailmap_blob, var, value);
1804
	}
1805

1806
	/* Add other config variables here and to Documentation/config.txt. */
1807
	return 0;
1808
}
1809

1810
static int git_default_attr_config(const char *var, const char *value)
1811
{
1812
	if (!strcmp(var, "attr.tree")) {
1813
		FREE_AND_NULL(git_attr_tree);
1814
		return git_config_string(&git_attr_tree, var, value);
1815
	}
1816

1817
	/*
1818
	 * Add other attribute related config variables here and to
1819
	 * Documentation/config/attr.txt.
1820
	 */
1821
	return 0;
1822
}
1823

1824
int git_default_config(const char *var, const char *value,
1825
		       const struct config_context *ctx, void *cb)
1826
{
1827
	if (starts_with(var, "core."))
1828
		return git_default_core_config(var, value, ctx, cb);
1829

1830
	if (starts_with(var, "user.") ||
1831
	    starts_with(var, "author.") ||
1832
	    starts_with(var, "committer."))
1833
		return git_ident_config(var, value, ctx, cb);
1834

1835
	if (starts_with(var, "i18n."))
1836
		return git_default_i18n_config(var, value);
1837

1838
	if (starts_with(var, "branch."))
1839
		return git_default_branch_config(var, value);
1840

1841
	if (starts_with(var, "push."))
1842
		return git_default_push_config(var, value);
1843

1844
	if (starts_with(var, "mailmap."))
1845
		return git_default_mailmap_config(var, value);
1846

1847
	if (starts_with(var, "attr."))
1848
		return git_default_attr_config(var, value);
1849

1850
	if (starts_with(var, "advice.") || starts_with(var, "color.advice"))
1851
		return git_default_advice_config(var, value);
1852

1853
	if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
1854
		pager_use_color = git_config_bool(var,value);
1855
		return 0;
1856
	}
1857

1858
	if (!strcmp(var, "pack.packsizelimit")) {
1859
		pack_size_limit_cfg = git_config_ulong(var, value, ctx->kvi);
1860
		return 0;
1861
	}
1862

1863
	if (!strcmp(var, "pack.compression")) {
1864
		int level = git_config_int(var, value, ctx->kvi);
1865
		if (level == -1)
1866
			level = Z_DEFAULT_COMPRESSION;
1867
		else if (level < 0 || level > Z_BEST_COMPRESSION)
1868
			die(_("bad pack compression level %d"), level);
1869
		pack_compression_level = level;
1870
		pack_compression_seen = 1;
1871
		return 0;
1872
	}
1873

1874
	if (starts_with(var, "sparse."))
1875
		return git_default_sparse_config(var, value);
1876

1877
	/* Add other config variables here and to Documentation/config.txt. */
1878
	return 0;
1879
}
1880

1881
/*
1882
 * All source specific fields in the union, die_on_error, name and the callbacks
1883
 * fgetc, ungetc, ftell of top need to be initialized before calling
1884
 * this function.
1885
 */
1886
static int do_config_from(struct config_source *top, config_fn_t fn,
1887
			  void *data, enum config_scope scope,
1888
			  const struct config_options *opts)
1889
{
1890
	struct key_value_info kvi = KVI_INIT;
1891
	int ret;
1892

1893
	/* push config-file parsing state stack */
1894
	top->linenr = 1;
1895
	top->eof = 0;
1896
	top->total_len = 0;
1897
	strbuf_init(&top->value, 1024);
1898
	strbuf_init(&top->var, 1024);
1899
	kvi_from_source(top, scope, &kvi);
1900

1901
	ret = git_parse_source(top, fn, &kvi, data, opts);
1902

1903
	strbuf_release(&top->value);
1904
	strbuf_release(&top->var);
1905

1906
	return ret;
1907
}
1908

1909
static int do_config_from_file(config_fn_t fn,
1910
			       const enum config_origin_type origin_type,
1911
			       const char *name, const char *path, FILE *f,
1912
			       void *data, enum config_scope scope,
1913
			       const struct config_options *opts)
1914
{
1915
	struct config_source top = CONFIG_SOURCE_INIT;
1916
	int ret;
1917

1918
	top.u.file = f;
1919
	top.origin_type = origin_type;
1920
	top.name = name;
1921
	top.path = path;
1922
	top.default_error_action = CONFIG_ERROR_DIE;
1923
	top.do_fgetc = config_file_fgetc;
1924
	top.do_ungetc = config_file_ungetc;
1925
	top.do_ftell = config_file_ftell;
1926

1927
	flockfile(f);
1928
	ret = do_config_from(&top, fn, data, scope, opts);
1929
	funlockfile(f);
1930
	return ret;
1931
}
1932

1933
static int git_config_from_stdin(config_fn_t fn, void *data,
1934
				 enum config_scope scope)
1935
{
1936
	return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", NULL, stdin,
1937
				   data, scope, NULL);
1938
}
1939

1940
int git_config_from_file_with_options(config_fn_t fn, const char *filename,
1941
				      void *data, enum config_scope scope,
1942
				      const struct config_options *opts)
1943
{
1944
	int ret = -1;
1945
	FILE *f;
1946

1947
	if (!filename)
1948
		BUG("filename cannot be NULL");
1949
	f = fopen_or_warn(filename, "r");
1950
	if (f) {
1951
		ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename,
1952
					  filename, f, data, scope, opts);
1953
		fclose(f);
1954
	}
1955
	return ret;
1956
}
1957

1958
int git_config_from_file(config_fn_t fn, const char *filename, void *data)
1959
{
1960
	return git_config_from_file_with_options(fn, filename, data,
1961
						 CONFIG_SCOPE_UNKNOWN, NULL);
1962
}
1963

1964
int git_config_from_mem(config_fn_t fn,
1965
			const enum config_origin_type origin_type,
1966
			const char *name, const char *buf, size_t len,
1967
			void *data, enum config_scope scope,
1968
			const struct config_options *opts)
1969
{
1970
	struct config_source top = CONFIG_SOURCE_INIT;
1971

1972
	top.u.buf.buf = buf;
1973
	top.u.buf.len = len;
1974
	top.u.buf.pos = 0;
1975
	top.origin_type = origin_type;
1976
	top.name = name;
1977
	top.path = NULL;
1978
	top.default_error_action = CONFIG_ERROR_ERROR;
1979
	top.do_fgetc = config_buf_fgetc;
1980
	top.do_ungetc = config_buf_ungetc;
1981
	top.do_ftell = config_buf_ftell;
1982

1983
	return do_config_from(&top, fn, data, scope, opts);
1984
}
1985

1986
int git_config_from_blob_oid(config_fn_t fn,
1987
			      const char *name,
1988
			      struct repository *repo,
1989
			      const struct object_id *oid,
1990
			      void *data,
1991
			      enum config_scope scope)
1992
{
1993
	enum object_type type;
1994
	char *buf;
1995
	unsigned long size;
1996
	int ret;
1997

1998
	buf = repo_read_object_file(repo, oid, &type, &size);
1999
	if (!buf)
2000
		return error(_("unable to load config blob object '%s'"), name);
2001
	if (type != OBJ_BLOB) {
2002
		free(buf);
2003
		return error(_("reference '%s' does not point to a blob"), name);
2004
	}
2005

2006
	ret = git_config_from_mem(fn, CONFIG_ORIGIN_BLOB, name, buf, size,
2007
				  data, scope, NULL);
2008
	free(buf);
2009

2010
	return ret;
2011
}
2012

2013
static int git_config_from_blob_ref(config_fn_t fn,
2014
				    struct repository *repo,
2015
				    const char *name,
2016
				    void *data,
2017
				    enum config_scope scope)
2018
{
2019
	struct object_id oid;
2020

2021
	if (repo_get_oid(repo, name, &oid) < 0)
2022
		return error(_("unable to resolve config blob '%s'"), name);
2023
	return git_config_from_blob_oid(fn, name, repo, &oid, data, scope);
2024
}
2025

2026
char *git_system_config(void)
2027
{
2028
	char *system_config = xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
2029
	if (!system_config)
2030
		system_config = system_path(ETC_GITCONFIG);
2031
	normalize_path_copy(system_config, system_config);
2032
	return system_config;
2033
}
2034

2035
char *git_global_config(void)
2036
{
2037
	char *user_config, *xdg_config;
2038

2039
	git_global_config_paths(&user_config, &xdg_config);
2040
	if (!user_config) {
2041
		free(xdg_config);
2042
		return NULL;
2043
	}
2044

2045
	if (access_or_warn(user_config, R_OK, 0) && xdg_config &&
2046
	    !access_or_warn(xdg_config, R_OK, 0)) {
2047
		free(user_config);
2048
		return xdg_config;
2049
	} else {
2050
		free(xdg_config);
2051
		return user_config;
2052
	}
2053
}
2054

2055
void git_global_config_paths(char **user_out, char **xdg_out)
2056
{
2057
	char *user_config = xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
2058
	char *xdg_config = NULL;
2059

2060
	if (!user_config) {
2061
		user_config = interpolate_path("~/.gitconfig", 0);
2062
		xdg_config = xdg_config_home("config");
2063
	}
2064

2065
	*user_out = user_config;
2066
	*xdg_out = xdg_config;
2067
}
2068

2069
int git_config_system(void)
2070
{
2071
	return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
2072
}
2073

2074
static int do_git_config_sequence(const struct config_options *opts,
2075
				  const struct repository *repo,
2076
				  config_fn_t fn, void *data)
2077
{
2078
	int ret = 0;
2079
	char *system_config = git_system_config();
2080
	char *xdg_config = NULL;
2081
	char *user_config = NULL;
2082
	char *repo_config;
2083
	char *worktree_config;
2084

2085
	/*
2086
	 * Ensure that either:
2087
	 * - the git_dir and commondir are both set, or
2088
	 * - the git_dir and commondir are both NULL
2089
	 */
2090
	if (!opts->git_dir != !opts->commondir)
2091
		BUG("only one of commondir and git_dir is non-NULL");
2092

2093
	if (opts->commondir) {
2094
		repo_config = mkpathdup("%s/config", opts->commondir);
2095
		worktree_config = mkpathdup("%s/config.worktree", opts->git_dir);
2096
	} else {
2097
		repo_config = NULL;
2098
		worktree_config = NULL;
2099
	}
2100

2101
	if (git_config_system() && system_config &&
2102
	    !access_or_die(system_config, R_OK,
2103
			   opts->system_gently ? ACCESS_EACCES_OK : 0))
2104
		ret += git_config_from_file_with_options(fn, system_config,
2105
							 data, CONFIG_SCOPE_SYSTEM,
2106
							 NULL);
2107

2108
	git_global_config_paths(&user_config, &xdg_config);
2109

2110
	if (xdg_config && !access_or_die(xdg_config, R_OK, ACCESS_EACCES_OK))
2111
		ret += git_config_from_file_with_options(fn, xdg_config, data,
2112
							 CONFIG_SCOPE_GLOBAL, NULL);
2113

2114
	if (user_config && !access_or_die(user_config, R_OK, ACCESS_EACCES_OK))
2115
		ret += git_config_from_file_with_options(fn, user_config, data,
2116
							 CONFIG_SCOPE_GLOBAL, NULL);
2117

2118
	if (!opts->ignore_repo && repo_config &&
2119
	    !access_or_die(repo_config, R_OK, 0))
2120
		ret += git_config_from_file_with_options(fn, repo_config, data,
2121
							 CONFIG_SCOPE_LOCAL, NULL);
2122

2123
	if (!opts->ignore_worktree && worktree_config &&
2124
	    repo && repo->repository_format_worktree_config &&
2125
	    !access_or_die(worktree_config, R_OK, 0)) {
2126
			ret += git_config_from_file_with_options(fn, worktree_config, data,
2127
								 CONFIG_SCOPE_WORKTREE,
2128
								 NULL);
2129
	}
2130

2131
	if (!opts->ignore_cmdline && git_config_from_parameters(fn, data) < 0)
2132
		die(_("unable to parse command-line config"));
2133

2134
	free(system_config);
2135
	free(xdg_config);
2136
	free(user_config);
2137
	free(repo_config);
2138
	free(worktree_config);
2139
	return ret;
2140
}
2141

2142
int config_with_options(config_fn_t fn, void *data,
2143
			const struct git_config_source *config_source,
2144
			struct repository *repo,
2145
			const struct config_options *opts)
2146
{
2147
	struct config_include_data inc = CONFIG_INCLUDE_INIT;
2148
	int ret;
2149

2150
	if (opts->respect_includes) {
2151
		inc.fn = fn;
2152
		inc.data = data;
2153
		inc.opts = opts;
2154
		inc.repo = repo;
2155
		inc.config_source = config_source;
2156
		fn = git_config_include;
2157
		data = &inc;
2158
	}
2159

2160
	/*
2161
	 * If we have a specific filename, use it. Otherwise, follow the
2162
	 * regular lookup sequence.
2163
	 */
2164
	if (config_source && config_source->use_stdin) {
2165
		ret = git_config_from_stdin(fn, data, config_source->scope);
2166
	} else if (config_source && config_source->file) {
2167
		ret = git_config_from_file_with_options(fn, config_source->file,
2168
							data, config_source->scope,
2169
							NULL);
2170
	} else if (config_source && config_source->blob) {
2171
		ret = git_config_from_blob_ref(fn, repo, config_source->blob,
2172
					       data, config_source->scope);
2173
	} else {
2174
		ret = do_git_config_sequence(opts, repo, fn, data);
2175
	}
2176

2177
	if (inc.remote_urls) {
2178
		string_list_clear(inc.remote_urls, 0);
2179
		FREE_AND_NULL(inc.remote_urls);
2180
	}
2181
	return ret;
2182
}
2183

2184
static void configset_iter(struct config_set *set, config_fn_t fn, void *data)
2185
{
2186
	int i, value_index;
2187
	struct string_list *values;
2188
	struct config_set_element *entry;
2189
	struct configset_list *list = &set->list;
2190
	struct config_context ctx = CONFIG_CONTEXT_INIT;
2191

2192
	for (i = 0; i < list->nr; i++) {
2193
		entry = list->items[i].e;
2194
		value_index = list->items[i].value_index;
2195
		values = &entry->value_list;
2196

2197
		ctx.kvi = values->items[value_index].util;
2198
		if (fn(entry->key, values->items[value_index].string, &ctx, data) < 0)
2199
			git_die_config_linenr(entry->key,
2200
					      ctx.kvi->filename,
2201
					      ctx.kvi->linenr);
2202
	}
2203
}
2204

2205
void read_early_config(config_fn_t cb, void *data)
2206
{
2207
	struct config_options opts = {0};
2208
	struct strbuf commondir = STRBUF_INIT;
2209
	struct strbuf gitdir = STRBUF_INIT;
2210

2211
	opts.respect_includes = 1;
2212

2213
	if (have_git_dir()) {
2214
		opts.commondir = get_git_common_dir();
2215
		opts.git_dir = get_git_dir();
2216
	/*
2217
	 * When setup_git_directory() was not yet asked to discover the
2218
	 * GIT_DIR, we ask discover_git_directory() to figure out whether there
2219
	 * is any repository config we should use (but unlike
2220
	 * setup_git_directory_gently(), no global state is changed, most
2221
	 * notably, the current working directory is still the same after the
2222
	 * call).
2223
	 */
2224
	} else if (!discover_git_directory(&commondir, &gitdir)) {
2225
		opts.commondir = commondir.buf;
2226
		opts.git_dir = gitdir.buf;
2227
	}
2228

2229
	config_with_options(cb, data, NULL, NULL, &opts);
2230

2231
	strbuf_release(&commondir);
2232
	strbuf_release(&gitdir);
2233
}
2234

2235
/*
2236
 * Read config but only enumerate system and global settings.
2237
 * Omit any repo-local, worktree-local, or command-line settings.
2238
 */
2239
void read_very_early_config(config_fn_t cb, void *data)
2240
{
2241
	struct config_options opts = { 0 };
2242

2243
	opts.respect_includes = 1;
2244
	opts.ignore_repo = 1;
2245
	opts.ignore_worktree = 1;
2246
	opts.ignore_cmdline = 1;
2247
	opts.system_gently = 1;
2248

2249
	config_with_options(cb, data, NULL, NULL, &opts);
2250
}
2251

2252
RESULT_MUST_BE_USED
2253
static int configset_find_element(struct config_set *set, const char *key,
2254
				  struct config_set_element **dest)
2255
{
2256
	struct config_set_element k;
2257
	struct config_set_element *found_entry;
2258
	char *normalized_key;
2259
	int ret;
2260

2261
	/*
2262
	 * `key` may come from the user, so normalize it before using it
2263
	 * for querying entries from the hashmap.
2264
	 */
2265
	ret = git_config_parse_key(key, &normalized_key, NULL);
2266
	if (ret)
2267
		return ret;
2268

2269
	hashmap_entry_init(&k.ent, strhash(normalized_key));
2270
	k.key = normalized_key;
2271
	found_entry = hashmap_get_entry(&set->config_hash, &k, ent, NULL);
2272
	free(normalized_key);
2273
	*dest = found_entry;
2274
	return 0;
2275
}
2276

2277
static int configset_add_value(const struct key_value_info *kvi_p,
2278
			       struct config_set *set, const char *key,
2279
			       const char *value)
2280
{
2281
	struct config_set_element *e;
2282
	struct string_list_item *si;
2283
	struct configset_list_item *l_item;
2284
	struct key_value_info *kv_info = xmalloc(sizeof(*kv_info));
2285
	int ret;
2286

2287
	ret = configset_find_element(set, key, &e);
2288
	if (ret)
2289
		return ret;
2290
	/*
2291
	 * Since the keys are being fed by git_config*() callback mechanism, they
2292
	 * are already normalized. So simply add them without any further munging.
2293
	 */
2294
	if (!e) {
2295
		e = xmalloc(sizeof(*e));
2296
		hashmap_entry_init(&e->ent, strhash(key));
2297
		e->key = xstrdup(key);
2298
		string_list_init_dup(&e->value_list);
2299
		hashmap_add(&set->config_hash, &e->ent);
2300
	}
2301
	si = string_list_append_nodup(&e->value_list, xstrdup_or_null(value));
2302

2303
	ALLOC_GROW(set->list.items, set->list.nr + 1, set->list.alloc);
2304
	l_item = &set->list.items[set->list.nr++];
2305
	l_item->e = e;
2306
	l_item->value_index = e->value_list.nr - 1;
2307

2308
	*kv_info = *kvi_p;
2309
	si->util = kv_info;
2310

2311
	return 0;
2312
}
2313

2314
static int config_set_element_cmp(const void *cmp_data UNUSED,
2315
				  const struct hashmap_entry *eptr,
2316
				  const struct hashmap_entry *entry_or_key,
2317
				  const void *keydata UNUSED)
2318
{
2319
	const struct config_set_element *e1, *e2;
2320

2321
	e1 = container_of(eptr, const struct config_set_element, ent);
2322
	e2 = container_of(entry_or_key, const struct config_set_element, ent);
2323

2324
	return strcmp(e1->key, e2->key);
2325
}
2326

2327
void git_configset_init(struct config_set *set)
2328
{
2329
	hashmap_init(&set->config_hash, config_set_element_cmp, NULL, 0);
2330
	set->hash_initialized = 1;
2331
	set->list.nr = 0;
2332
	set->list.alloc = 0;
2333
	set->list.items = NULL;
2334
}
2335

2336
void git_configset_clear(struct config_set *set)
2337
{
2338
	struct config_set_element *entry;
2339
	struct hashmap_iter iter;
2340
	if (!set->hash_initialized)
2341
		return;
2342

2343
	hashmap_for_each_entry(&set->config_hash, &iter, entry,
2344
				ent /* member name */) {
2345
		free(entry->key);
2346
		string_list_clear(&entry->value_list, 1);
2347
	}
2348
	hashmap_clear_and_free(&set->config_hash, struct config_set_element, ent);
2349
	set->hash_initialized = 0;
2350
	free(set->list.items);
2351
	set->list.nr = 0;
2352
	set->list.alloc = 0;
2353
	set->list.items = NULL;
2354
}
2355

2356
static int config_set_callback(const char *key, const char *value,
2357
			       const struct config_context *ctx,
2358
			       void *cb)
2359
{
2360
	struct config_set *set = cb;
2361
	configset_add_value(ctx->kvi, set, key, value);
2362
	return 0;
2363
}
2364

2365
int git_configset_add_file(struct config_set *set, const char *filename)
2366
{
2367
	return git_config_from_file(config_set_callback, filename, set);
2368
}
2369

2370
int git_configset_get_value(struct config_set *set, const char *key,
2371
			    const char **value, struct key_value_info *kvi)
2372
{
2373
	const struct string_list *values = NULL;
2374
	int ret;
2375
	struct string_list_item item;
2376
	/*
2377
	 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
2378
	 * queried key in the files of the configset, the value returned will be the last
2379
	 * value in the value list for that key.
2380
	 */
2381
	if ((ret = git_configset_get_value_multi(set, key, &values)))
2382
		return ret;
2383

2384
	assert(values->nr > 0);
2385
	item = values->items[values->nr - 1];
2386
	*value = item.string;
2387
	if (kvi)
2388
		*kvi = *((struct key_value_info *)item.util);
2389
	return 0;
2390
}
2391

2392
int git_configset_get_value_multi(struct config_set *set, const char *key,
2393
				  const struct string_list **dest)
2394
{
2395
	struct config_set_element *e;
2396
	int ret;
2397

2398
	if ((ret = configset_find_element(set, key, &e)))
2399
		return ret;
2400
	else if (!e)
2401
		return 1;
2402
	*dest = &e->value_list;
2403

2404
	return 0;
2405
}
2406

2407
static int check_multi_string(struct string_list_item *item, void *util)
2408
{
2409
	return item->string ? 0 : config_error_nonbool(util);
2410
}
2411

2412
int git_configset_get_string_multi(struct config_set *cs, const char *key,
2413
				   const struct string_list **dest)
2414
{
2415
	int ret;
2416

2417
	if ((ret = git_configset_get_value_multi(cs, key, dest)))
2418
		return ret;
2419
	if ((ret = for_each_string_list((struct string_list *)*dest,
2420
					check_multi_string, (void *)key)))
2421
		return ret;
2422

2423
	return 0;
2424
}
2425

2426
int git_configset_get(struct config_set *set, const char *key)
2427
{
2428
	struct config_set_element *e;
2429
	int ret;
2430

2431
	if ((ret = configset_find_element(set, key, &e)))
2432
		return ret;
2433
	else if (!e)
2434
		return 1;
2435
	return 0;
2436
}
2437

2438
int git_configset_get_string(struct config_set *set, const char *key, char **dest)
2439
{
2440
	const char *value;
2441
	if (!git_configset_get_value(set, key, &value, NULL))
2442
		return git_config_string(dest, key, value);
2443
	else
2444
		return 1;
2445
}
2446

2447
static int git_configset_get_string_tmp(struct config_set *set, const char *key,
2448
					const char **dest)
2449
{
2450
	const char *value;
2451
	if (!git_configset_get_value(set, key, &value, NULL)) {
2452
		if (!value)
2453
			return config_error_nonbool(key);
2454
		*dest = value;
2455
		return 0;
2456
	} else {
2457
		return 1;
2458
	}
2459
}
2460

2461
int git_configset_get_int(struct config_set *set, const char *key, int *dest)
2462
{
2463
	const char *value;
2464
	struct key_value_info kvi;
2465

2466
	if (!git_configset_get_value(set, key, &value, &kvi)) {
2467
		*dest = git_config_int(key, value, &kvi);
2468
		return 0;
2469
	} else
2470
		return 1;
2471
}
2472

2473
int git_configset_get_ulong(struct config_set *set, const char *key, unsigned long *dest)
2474
{
2475
	const char *value;
2476
	struct key_value_info kvi;
2477

2478
	if (!git_configset_get_value(set, key, &value, &kvi)) {
2479
		*dest = git_config_ulong(key, value, &kvi);
2480
		return 0;
2481
	} else
2482
		return 1;
2483
}
2484

2485
int git_configset_get_bool(struct config_set *set, const char *key, int *dest)
2486
{
2487
	const char *value;
2488
	if (!git_configset_get_value(set, key, &value, NULL)) {
2489
		*dest = git_config_bool(key, value);
2490
		return 0;
2491
	} else
2492
		return 1;
2493
}
2494

2495
int git_configset_get_bool_or_int(struct config_set *set, const char *key,
2496
				int *is_bool, int *dest)
2497
{
2498
	const char *value;
2499
	struct key_value_info kvi;
2500

2501
	if (!git_configset_get_value(set, key, &value, &kvi)) {
2502
		*dest = git_config_bool_or_int(key, value, &kvi, is_bool);
2503
		return 0;
2504
	} else
2505
		return 1;
2506
}
2507

2508
int git_configset_get_maybe_bool(struct config_set *set, const char *key, int *dest)
2509
{
2510
	const char *value;
2511
	if (!git_configset_get_value(set, key, &value, NULL)) {
2512
		*dest = git_parse_maybe_bool(value);
2513
		if (*dest == -1)
2514
			return -1;
2515
		return 0;
2516
	} else
2517
		return 1;
2518
}
2519

2520
int git_configset_get_pathname(struct config_set *set, const char *key, char **dest)
2521
{
2522
	const char *value;
2523
	if (!git_configset_get_value(set, key, &value, NULL))
2524
		return git_config_pathname(dest, key, value);
2525
	else
2526
		return 1;
2527
}
2528

2529
/* Functions use to read configuration from a repository */
2530
static void repo_read_config(struct repository *repo)
2531
{
2532
	struct config_options opts = { 0 };
2533

2534
	opts.respect_includes = 1;
2535
	opts.commondir = repo->commondir;
2536
	opts.git_dir = repo->gitdir;
2537

2538
	if (!repo->config)
2539
		CALLOC_ARRAY(repo->config, 1);
2540
	else
2541
		git_configset_clear(repo->config);
2542

2543
	git_configset_init(repo->config);
2544
	if (config_with_options(config_set_callback, repo->config, NULL,
2545
				repo, &opts) < 0)
2546
		/*
2547
		 * config_with_options() normally returns only
2548
		 * zero, as most errors are fatal, and
2549
		 * non-fatal potential errors are guarded by "if"
2550
		 * statements that are entered only when no error is
2551
		 * possible.
2552
		 *
2553
		 * If we ever encounter a non-fatal error, it means
2554
		 * something went really wrong and we should stop
2555
		 * immediately.
2556
		 */
2557
		die(_("unknown error occurred while reading the configuration files"));
2558
}
2559

2560
static void git_config_check_init(struct repository *repo)
2561
{
2562
	if (repo->config && repo->config->hash_initialized)
2563
		return;
2564
	repo_read_config(repo);
2565
}
2566

2567
void repo_config_clear(struct repository *repo)
2568
{
2569
	if (!repo->config || !repo->config->hash_initialized)
2570
		return;
2571
	git_configset_clear(repo->config);
2572
}
2573

2574
void repo_config(struct repository *repo, config_fn_t fn, void *data)
2575
{
2576
	git_config_check_init(repo);
2577
	configset_iter(repo->config, fn, data);
2578
}
2579

2580
int repo_config_get(struct repository *repo, const char *key)
2581
{
2582
	git_config_check_init(repo);
2583
	return git_configset_get(repo->config, key);
2584
}
2585

2586
int repo_config_get_value(struct repository *repo,
2587
			  const char *key, const char **value)
2588
{
2589
	git_config_check_init(repo);
2590
	return git_configset_get_value(repo->config, key, value, NULL);
2591
}
2592

2593
int repo_config_get_value_multi(struct repository *repo, const char *key,
2594
				const struct string_list **dest)
2595
{
2596
	git_config_check_init(repo);
2597
	return git_configset_get_value_multi(repo->config, key, dest);
2598
}
2599

2600
int repo_config_get_string_multi(struct repository *repo, const char *key,
2601
				 const struct string_list **dest)
2602
{
2603
	git_config_check_init(repo);
2604
	return git_configset_get_string_multi(repo->config, key, dest);
2605
}
2606

2607
int repo_config_get_string(struct repository *repo,
2608
			   const char *key, char **dest)
2609
{
2610
	int ret;
2611
	git_config_check_init(repo);
2612
	ret = git_configset_get_string(repo->config, key, dest);
2613
	if (ret < 0)
2614
		git_die_config(repo, key, NULL);
2615
	return ret;
2616
}
2617

2618
int repo_config_get_string_tmp(struct repository *repo,
2619
			       const char *key, const char **dest)
2620
{
2621
	int ret;
2622
	git_config_check_init(repo);
2623
	ret = git_configset_get_string_tmp(repo->config, key, dest);
2624
	if (ret < 0)
2625
		git_die_config(repo, key, NULL);
2626
	return ret;
2627
}
2628

2629
int repo_config_get_int(struct repository *repo,
2630
			const char *key, int *dest)
2631
{
2632
	git_config_check_init(repo);
2633
	return git_configset_get_int(repo->config, key, dest);
2634
}
2635

2636
int repo_config_get_ulong(struct repository *repo,
2637
			  const char *key, unsigned long *dest)
2638
{
2639
	git_config_check_init(repo);
2640
	return git_configset_get_ulong(repo->config, key, dest);
2641
}
2642

2643
int repo_config_get_bool(struct repository *repo,
2644
			 const char *key, int *dest)
2645
{
2646
	git_config_check_init(repo);
2647
	return git_configset_get_bool(repo->config, key, dest);
2648
}
2649

2650
int repo_config_get_bool_or_int(struct repository *repo,
2651
				const char *key, int *is_bool, int *dest)
2652
{
2653
	git_config_check_init(repo);
2654
	return git_configset_get_bool_or_int(repo->config, key, is_bool, dest);
2655
}
2656

2657
int repo_config_get_maybe_bool(struct repository *repo,
2658
			       const char *key, int *dest)
2659
{
2660
	git_config_check_init(repo);
2661
	return git_configset_get_maybe_bool(repo->config, key, dest);
2662
}
2663

2664
int repo_config_get_pathname(struct repository *repo,
2665
			     const char *key, char **dest)
2666
{
2667
	int ret;
2668
	git_config_check_init(repo);
2669
	ret = git_configset_get_pathname(repo->config, key, dest);
2670
	if (ret < 0)
2671
		git_die_config(repo, key, NULL);
2672
	return ret;
2673
}
2674

2675
/* Read values into protected_config. */
2676
static void read_protected_config(void)
2677
{
2678
	struct config_options opts = {
2679
		.respect_includes = 1,
2680
		.ignore_repo = 1,
2681
		.ignore_worktree = 1,
2682
		.system_gently = 1,
2683
	};
2684

2685
	git_configset_init(&protected_config);
2686
	config_with_options(config_set_callback, &protected_config, NULL,
2687
			    NULL, &opts);
2688
}
2689

2690
void git_protected_config(config_fn_t fn, void *data)
2691
{
2692
	if (!protected_config.hash_initialized)
2693
		read_protected_config();
2694
	configset_iter(&protected_config, fn, data);
2695
}
2696

2697
int repo_config_get_expiry(struct repository *r, const char *key, char **output)
2698
{
2699
	int ret = repo_config_get_string(r, key, output);
2700

2701
	if (ret)
2702
		return ret;
2703
	if (strcmp(*output, "now")) {
2704
		timestamp_t now = approxidate("now");
2705
		if (approxidate(*output) >= now)
2706
			git_die_config(r, key, _("Invalid %s: '%s'"), key, *output);
2707
	}
2708
	return ret;
2709
}
2710

2711
int repo_config_get_expiry_in_days(struct repository *r, const char *key,
2712
				   timestamp_t *expiry, timestamp_t now)
2713
{
2714
	const char *expiry_string;
2715
	intmax_t days;
2716
	timestamp_t when;
2717

2718
	if (repo_config_get_string_tmp(r, key, &expiry_string))
2719
		return 1; /* no such thing */
2720

2721
	if (git_parse_signed(expiry_string, &days, maximum_signed_value_of_type(int))) {
2722
		const int scale = 86400;
2723
		*expiry = now - days * scale;
2724
		return 0;
2725
	}
2726

2727
	if (!parse_expiry_date(expiry_string, &when)) {
2728
		*expiry = when;
2729
		return 0;
2730
	}
2731
	return -1; /* thing exists but cannot be parsed */
2732
}
2733

2734
int repo_config_get_split_index(struct repository *r)
2735
{
2736
	int val;
2737

2738
	if (!repo_config_get_maybe_bool(r, "core.splitindex", &val))
2739
		return val;
2740

2741
	return -1; /* default value */
2742
}
2743

2744
int repo_config_get_max_percent_split_change(struct repository *r)
2745
{
2746
	int val = -1;
2747

2748
	if (!repo_config_get_int(r, "splitindex.maxpercentchange", &val)) {
2749
		if (0 <= val && val <= 100)
2750
			return val;
2751

2752
		return error(_("splitIndex.maxPercentChange value '%d' "
2753
			       "should be between 0 and 100"), val);
2754
	}
2755

2756
	return -1; /* default value */
2757
}
2758

2759
int repo_config_get_index_threads(struct repository *r, int *dest)
2760
{
2761
	int is_bool, val;
2762

2763
	val = git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2764
	if (val) {
2765
		*dest = val;
2766
		return 0;
2767
	}
2768

2769
	if (!repo_config_get_bool_or_int(r, "index.threads", &is_bool, &val)) {
2770
		if (is_bool)
2771
			*dest = val ? 0 : 1;
2772
		else
2773
			*dest = val;
2774
		return 0;
2775
	}
2776

2777
	return 1;
2778
}
2779

2780
NORETURN
2781
void git_die_config_linenr(const char *key, const char *filename, int linenr)
2782
{
2783
	if (!filename)
2784
		die(_("unable to parse '%s' from command-line config"), key);
2785
	else
2786
		die(_("bad config variable '%s' in file '%s' at line %d"),
2787
		    key, filename, linenr);
2788
}
2789

2790
void git_die_config(struct repository *r, const char *key, const char *err, ...)
2791
{
2792
	const struct string_list *values;
2793
	struct key_value_info *kv_info;
2794
	report_fn error_fn = get_error_routine();
2795

2796
	if (err) {
2797
		va_list params;
2798
		va_start(params, err);
2799
		error_fn(err, params);
2800
		va_end(params);
2801
	}
2802
	if (repo_config_get_value_multi(r, key, &values))
2803
		BUG("for key '%s' we must have a value to report on", key);
2804
	kv_info = values->items[values->nr - 1].util;
2805
	git_die_config_linenr(key, kv_info->filename, kv_info->linenr);
2806
}
2807

2808
/*
2809
 * Find all the stuff for git_config_set() below.
2810
 */
2811

2812
struct config_store_data {
2813
	size_t baselen;
2814
	char *key;
2815
	int do_not_match;
2816
	const char *fixed_value;
2817
	regex_t *value_pattern;
2818
	int multi_replace;
2819
	struct {
2820
		size_t begin, end;
2821
		enum config_event_t type;
2822
		int is_keys_section;
2823
	} *parsed;
2824
	unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
2825
	unsigned int key_seen:1, section_seen:1, is_keys_section:1;
2826
};
2827
#define CONFIG_STORE_INIT { 0 }
2828

2829
static void config_store_data_clear(struct config_store_data *store)
2830
{
2831
	free(store->key);
2832
	if (store->value_pattern != NULL &&
2833
	    store->value_pattern != CONFIG_REGEX_NONE) {
2834
		regfree(store->value_pattern);
2835
		free(store->value_pattern);
2836
	}
2837
	free(store->parsed);
2838
	free(store->seen);
2839
	memset(store, 0, sizeof(*store));
2840
}
2841

2842
static int matches(const char *key, const char *value,
2843
		   const struct config_store_data *store)
2844
{
2845
	if (strcmp(key, store->key))
2846
		return 0; /* not ours */
2847
	if (store->fixed_value && value)
2848
		return !strcmp(store->fixed_value, value);
2849
	if (!store->value_pattern)
2850
		return 1; /* always matches */
2851
	if (store->value_pattern == CONFIG_REGEX_NONE)
2852
		return 0; /* never matches */
2853

2854
	return store->do_not_match ^
2855
		(value && !regexec(store->value_pattern, value, 0, NULL, 0));
2856
}
2857

2858
static int store_aux_event(enum config_event_t type, size_t begin, size_t end,
2859
			   struct config_source *cs, void *data)
2860
{
2861
	struct config_store_data *store = data;
2862

2863
	ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
2864
	store->parsed[store->parsed_nr].begin = begin;
2865
	store->parsed[store->parsed_nr].end = end;
2866
	store->parsed[store->parsed_nr].type = type;
2867

2868
	if (type == CONFIG_EVENT_SECTION) {
2869
		int (*cmpfn)(const char *, const char *, size_t);
2870

2871
		if (cs->var.len < 2 || cs->var.buf[cs->var.len - 1] != '.')
2872
			return error(_("invalid section name '%s'"), cs->var.buf);
2873

2874
		if (cs->subsection_case_sensitive)
2875
			cmpfn = strncasecmp;
2876
		else
2877
			cmpfn = strncmp;
2878

2879
		/* Is this the section we were looking for? */
2880
		store->is_keys_section =
2881
			store->parsed[store->parsed_nr].is_keys_section =
2882
			cs->var.len - 1 == store->baselen &&
2883
			!cmpfn(cs->var.buf, store->key, store->baselen);
2884
		if (store->is_keys_section) {
2885
			store->section_seen = 1;
2886
			ALLOC_GROW(store->seen, store->seen_nr + 1,
2887
				   store->seen_alloc);
2888
			store->seen[store->seen_nr] = store->parsed_nr;
2889
		}
2890
	}
2891

2892
	store->parsed_nr++;
2893

2894
	return 0;
2895
}
2896

2897
static int store_aux(const char *key, const char *value,
2898
		     const struct config_context *ctx UNUSED, void *cb)
2899
{
2900
	struct config_store_data *store = cb;
2901

2902
	if (store->key_seen) {
2903
		if (matches(key, value, store)) {
2904
			if (store->seen_nr == 1 && store->multi_replace == 0) {
2905
				warning(_("%s has multiple values"), key);
2906
			}
2907

2908
			ALLOC_GROW(store->seen, store->seen_nr + 1,
2909
				   store->seen_alloc);
2910

2911
			store->seen[store->seen_nr] = store->parsed_nr;
2912
			store->seen_nr++;
2913
		}
2914
	} else if (store->is_keys_section) {
2915
		/*
2916
		 * Do not increment matches yet: this may not be a match, but we
2917
		 * are in the desired section.
2918
		 */
2919
		ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
2920
		store->seen[store->seen_nr] = store->parsed_nr;
2921
		store->section_seen = 1;
2922

2923
		if (matches(key, value, store)) {
2924
			store->seen_nr++;
2925
			store->key_seen = 1;
2926
		}
2927
	}
2928

2929
	return 0;
2930
}
2931

2932
static int write_error(const char *filename)
2933
{
2934
	error(_("failed to write new configuration file %s"), filename);
2935

2936
	/* Same error code as "failed to rename". */
2937
	return 4;
2938
}
2939

2940
static struct strbuf store_create_section(const char *key,
2941
					  const struct config_store_data *store)
2942
{
2943
	const char *dot;
2944
	size_t i;
2945
	struct strbuf sb = STRBUF_INIT;
2946

2947
	dot = memchr(key, '.', store->baselen);
2948
	if (dot) {
2949
		strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
2950
		for (i = dot - key + 1; i < store->baselen; i++) {
2951
			if (key[i] == '"' || key[i] == '\\')
2952
				strbuf_addch(&sb, '\\');
2953
			strbuf_addch(&sb, key[i]);
2954
		}
2955
		strbuf_addstr(&sb, "\"]\n");
2956
	} else {
2957
		strbuf_addch(&sb, '[');
2958
		strbuf_add(&sb, key, store->baselen);
2959
		strbuf_addstr(&sb, "]\n");
2960
	}
2961

2962
	return sb;
2963
}
2964

2965
static ssize_t write_section(int fd, const char *key,
2966
			     const struct config_store_data *store)
2967
{
2968
	struct strbuf sb = store_create_section(key, store);
2969
	ssize_t ret;
2970

2971
	ret = write_in_full(fd, sb.buf, sb.len);
2972
	strbuf_release(&sb);
2973

2974
	return ret;
2975
}
2976

2977
static ssize_t write_pair(int fd, const char *key, const char *value,
2978
			  const char *comment,
2979
			  const struct config_store_data *store)
2980
{
2981
	int i;
2982
	ssize_t ret;
2983
	const char *quote = "";
2984
	struct strbuf sb = STRBUF_INIT;
2985

2986
	/*
2987
	 * Check to see if the value needs to be surrounded with a dq pair.
2988
	 * Note that problematic characters are always backslash-quoted; this
2989
	 * check is about not losing leading or trailing SP and strings that
2990
	 * follow beginning-of-comment characters (i.e. ';' and '#') by the
2991
	 * configuration parser.
2992
	 */
2993
	if (value[0] == ' ')
2994
		quote = "\"";
2995
	for (i = 0; value[i]; i++)
2996
		if (value[i] == ';' || value[i] == '#')
2997
			quote = "\"";
2998
	if (i && value[i - 1] == ' ')
2999
		quote = "\"";
3000

3001
	strbuf_addf(&sb, "\t%s = %s", key + store->baselen + 1, quote);
3002

3003
	for (i = 0; value[i]; i++)
3004
		switch (value[i]) {
3005
		case '\n':
3006
			strbuf_addstr(&sb, "\\n");
3007
			break;
3008
		case '\t':
3009
			strbuf_addstr(&sb, "\\t");
3010
			break;
3011
		case '"':
3012
		case '\\':
3013
			strbuf_addch(&sb, '\\');
3014
			/* fallthrough */
3015
		default:
3016
			strbuf_addch(&sb, value[i]);
3017
			break;
3018
		}
3019

3020
	if (comment)
3021
		strbuf_addf(&sb, "%s%s\n", quote, comment);
3022
	else
3023
		strbuf_addf(&sb, "%s\n", quote);
3024

3025
	ret = write_in_full(fd, sb.buf, sb.len);
3026
	strbuf_release(&sb);
3027

3028
	return ret;
3029
}
3030

3031
/*
3032
 * If we are about to unset the last key(s) in a section, and if there are
3033
 * no comments surrounding (or included in) the section, we will want to
3034
 * extend begin/end to remove the entire section.
3035
 *
3036
 * Note: the parameter `seen_ptr` points to the index into the store.seen
3037
 * array.  * This index may be incremented if a section has more than one
3038
 * entry (which all are to be removed).
3039
 */
3040
static void maybe_remove_section(struct config_store_data *store,
3041
				 size_t *begin_offset, size_t *end_offset,
3042
				 int *seen_ptr)
3043
{
3044
	size_t begin;
3045
	int i, seen, section_seen = 0;
3046

3047
	/*
3048
	 * First, ensure that this is the first key, and that there are no
3049
	 * comments before the entry nor before the section header.
3050
	 */
3051
	seen = *seen_ptr;
3052
	for (i = store->seen[seen]; i > 0; i--) {
3053
		enum config_event_t type = store->parsed[i - 1].type;
3054

3055
		if (type == CONFIG_EVENT_COMMENT)
3056
			/* There is a comment before this entry or section */
3057
			return;
3058
		if (type == CONFIG_EVENT_ENTRY) {
3059
			if (!section_seen)
3060
				/* This is not the section's first entry. */
3061
				return;
3062
			/* We encountered no comment before the section. */
3063
			break;
3064
		}
3065
		if (type == CONFIG_EVENT_SECTION) {
3066
			if (!store->parsed[i - 1].is_keys_section)
3067
				break;
3068
			section_seen = 1;
3069
		}
3070
	}
3071
	begin = store->parsed[i].begin;
3072

3073
	/*
3074
	 * Next, make sure that we are removing the last key(s) in the section,
3075
	 * and that there are no comments that are possibly about the current
3076
	 * section.
3077
	 */
3078
	for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
3079
		enum config_event_t type = store->parsed[i].type;
3080

3081
		if (type == CONFIG_EVENT_COMMENT)
3082
			return;
3083
		if (type == CONFIG_EVENT_SECTION) {
3084
			if (store->parsed[i].is_keys_section)
3085
				continue;
3086
			break;
3087
		}
3088
		if (type == CONFIG_EVENT_ENTRY) {
3089
			if (++seen < store->seen_nr &&
3090
			    i == store->seen[seen])
3091
				/* We want to remove this entry, too */
3092
				continue;
3093
			/* There is another entry in this section. */
3094
			return;
3095
		}
3096
	}
3097

3098
	/*
3099
	 * We are really removing the last entry/entries from this section, and
3100
	 * there are no enclosed or surrounding comments. Remove the entire,
3101
	 * now-empty section.
3102
	 */
3103
	*seen_ptr = seen;
3104
	*begin_offset = begin;
3105
	if (i < store->parsed_nr)
3106
		*end_offset = store->parsed[i].begin;
3107
	else
3108
		*end_offset = store->parsed[store->parsed_nr - 1].end;
3109
}
3110

3111
int repo_config_set_in_file_gently(struct repository *r, const char *config_filename,
3112
				   const char *key, const char *comment, const char *value)
3113
{
3114
	return repo_config_set_multivar_in_file_gently(r, config_filename, key, value, NULL, comment, 0);
3115
}
3116

3117
void repo_config_set_in_file(struct repository *r, const char *config_filename,
3118
			     const char *key, const char *value)
3119
{
3120
	repo_config_set_multivar_in_file(r, config_filename, key, value, NULL, 0);
3121
}
3122

3123
int repo_config_set_gently(struct repository *r, const char *key, const char *value)
3124
{
3125
	return repo_config_set_multivar_gently(r, key, value, NULL, 0);
3126
}
3127

3128
int repo_config_set_worktree_gently(struct repository *r,
3129
				    const char *key, const char *value)
3130
{
3131
	/* Only use worktree-specific config if it is already enabled. */
3132
	if (r->repository_format_worktree_config) {
3133
		char *file = repo_git_path(r, "config.worktree");
3134
		int ret = repo_config_set_multivar_in_file_gently(
3135
					r, file, key, value, NULL, NULL, 0);
3136
		free(file);
3137
		return ret;
3138
	}
3139
	return repo_config_set_multivar_gently(r, key, value, NULL, 0);
3140
}
3141

3142
void repo_config_set(struct repository *r, const char *key, const char *value)
3143
{
3144
	repo_config_set_multivar(r, key, value, NULL, 0);
3145

3146
	trace2_cmd_set_config(key, value);
3147
}
3148

3149
char *git_config_prepare_comment_string(const char *comment)
3150
{
3151
	size_t leading_blanks;
3152
	char *prepared;
3153

3154
	if (!comment)
3155
		return NULL;
3156

3157
	if (strchr(comment, '\n'))
3158
		die(_("no multi-line comment allowed: '%s'"), comment);
3159

3160
	/*
3161
	 * If it begins with one or more leading whitespace characters
3162
	 * followed by '#", the comment string is used as-is.
3163
	 *
3164
	 * If it begins with '#', a SP is inserted between the comment
3165
	 * and the value the comment is about.
3166
	 *
3167
	 * Otherwise, the value is followed by a SP followed by '#'
3168
	 * followed by SP and then the comment string comes.
3169
	 */
3170

3171
	leading_blanks = strspn(comment, " \t");
3172
	if (leading_blanks && comment[leading_blanks] == '#')
3173
		prepared = xstrdup(comment); /* use it as-is */
3174
	else if (comment[0] == '#')
3175
		prepared = xstrfmt(" %s", comment);
3176
	else
3177
		prepared = xstrfmt(" # %s", comment);
3178

3179
	return prepared;
3180
}
3181

3182
static void validate_comment_string(const char *comment)
3183
{
3184
	size_t leading_blanks;
3185

3186
	if (!comment)
3187
		return;
3188
	/*
3189
	 * The front-end must have massaged the comment string
3190
	 * properly before calling us.
3191
	 */
3192
	if (strchr(comment, '\n'))
3193
		BUG("multi-line comments are not permitted: '%s'", comment);
3194

3195
	leading_blanks = strspn(comment, " \t");
3196
	if (!leading_blanks || comment[leading_blanks] != '#')
3197
		BUG("comment must begin with one or more SP followed by '#': '%s'",
3198
		    comment);
3199
}
3200

3201
/*
3202
 * If value==NULL, unset in (remove from) config,
3203
 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
3204
 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
3205
 *     (only add a new one)
3206
 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3207
 *     key/values are removed before a single new pair is written. If the
3208
 *     flag is not present, then replace only the first match.
3209
 *
3210
 * Returns 0 on success.
3211
 *
3212
 * This function does this:
3213
 *
3214
 * - it locks the config file by creating ".git/config.lock"
3215
 *
3216
 * - it then parses the config using store_aux() as validator to find
3217
 *   the position on the key/value pair to replace. If it is to be unset,
3218
 *   it must be found exactly once.
3219
 *
3220
 * - the config file is mmap()ed and the part before the match (if any) is
3221
 *   written to the lock file, then the changed part and the rest.
3222
 *
3223
 * - the config file is removed and the lock file rename()d to it.
3224
 *
3225
 */
3226
int repo_config_set_multivar_in_file_gently(struct repository *r,
3227
					    const char *config_filename,
3228
					    const char *key, const char *value,
3229
					    const char *value_pattern,
3230
					    const char *comment,
3231
					    unsigned flags)
3232
{
3233
	int fd = -1, in_fd = -1;
3234
	int ret;
3235
	struct lock_file lock = LOCK_INIT;
3236
	char *filename_buf = NULL;
3237
	char *contents = NULL;
3238
	size_t contents_sz;
3239
	struct config_store_data store = CONFIG_STORE_INIT;
3240

3241
	validate_comment_string(comment);
3242

3243
	/* parse-key returns negative; flip the sign to feed exit(3) */
3244
	ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
3245
	if (ret)
3246
		goto out_free;
3247

3248
	store.multi_replace = (flags & CONFIG_FLAGS_MULTI_REPLACE) != 0;
3249

3250
	if (!config_filename)
3251
		config_filename = filename_buf = repo_git_path(r, "config");
3252

3253
	/*
3254
	 * The lock serves a purpose in addition to locking: the new
3255
	 * contents of .git/config will be written into it.
3256
	 */
3257
	fd = hold_lock_file_for_update(&lock, config_filename, 0);
3258
	if (fd < 0) {
3259
		error_errno(_("could not lock config file %s"), config_filename);
3260
		ret = CONFIG_NO_LOCK;
3261
		goto out_free;
3262
	}
3263

3264
	/*
3265
	 * If .git/config does not exist yet, write a minimal version.
3266
	 */
3267
	in_fd = open(config_filename, O_RDONLY);
3268
	if ( in_fd < 0 ) {
3269
		if ( ENOENT != errno ) {
3270
			error_errno(_("opening %s"), config_filename);
3271
			ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
3272
			goto out_free;
3273
		}
3274
		/* if nothing to unset, error out */
3275
		if (!value) {
3276
			ret = CONFIG_NOTHING_SET;
3277
			goto out_free;
3278
		}
3279

3280
		free(store.key);
3281
		store.key = xstrdup(key);
3282
		if (write_section(fd, key, &store) < 0 ||
3283
		    write_pair(fd, key, value, comment, &store) < 0)
3284
			goto write_err_out;
3285
	} else {
3286
		struct stat st;
3287
		size_t copy_begin, copy_end;
3288
		int i, new_line = 0;
3289
		struct config_options opts;
3290

3291
		if (!value_pattern)
3292
			store.value_pattern = NULL;
3293
		else if (value_pattern == CONFIG_REGEX_NONE)
3294
			store.value_pattern = CONFIG_REGEX_NONE;
3295
		else if (flags & CONFIG_FLAGS_FIXED_VALUE)
3296
			store.fixed_value = value_pattern;
3297
		else {
3298
			if (value_pattern[0] == '!') {
3299
				store.do_not_match = 1;
3300
				value_pattern++;
3301
			} else
3302
				store.do_not_match = 0;
3303

3304
			store.value_pattern = (regex_t*)xmalloc(sizeof(regex_t));
3305
			if (regcomp(store.value_pattern, value_pattern,
3306
					REG_EXTENDED)) {
3307
				error(_("invalid pattern: %s"), value_pattern);
3308
				FREE_AND_NULL(store.value_pattern);
3309
				ret = CONFIG_INVALID_PATTERN;
3310
				goto out_free;
3311
			}
3312
		}
3313

3314
		ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
3315
		store.parsed[0].end = 0;
3316

3317
		memset(&opts, 0, sizeof(opts));
3318
		opts.event_fn = store_aux_event;
3319
		opts.event_fn_data = &store;
3320

3321
		/*
3322
		 * After this, store.parsed will contain offsets of all the
3323
		 * parsed elements, and store.seen will contain a list of
3324
		 * matches, as indices into store.parsed.
3325
		 *
3326
		 * As a side effect, we make sure to transform only a valid
3327
		 * existing config file.
3328
		 */
3329
		if (git_config_from_file_with_options(store_aux,
3330
						      config_filename,
3331
						      &store, CONFIG_SCOPE_UNKNOWN,
3332
						      &opts)) {
3333
			error(_("invalid config file %s"), config_filename);
3334
			ret = CONFIG_INVALID_FILE;
3335
			goto out_free;
3336
		}
3337

3338
		/* if nothing to unset, or too many matches, error out */
3339
		if ((store.seen_nr == 0 && value == NULL) ||
3340
		    (store.seen_nr > 1 && !store.multi_replace)) {
3341
			ret = CONFIG_NOTHING_SET;
3342
			goto out_free;
3343
		}
3344

3345
		if (fstat(in_fd, &st) == -1) {
3346
			error_errno(_("fstat on %s failed"), config_filename);
3347
			ret = CONFIG_INVALID_FILE;
3348
			goto out_free;
3349
		}
3350

3351
		contents_sz = xsize_t(st.st_size);
3352
		contents = xmmap_gently(NULL, contents_sz, PROT_READ,
3353
					MAP_PRIVATE, in_fd, 0);
3354
		if (contents == MAP_FAILED) {
3355
			if (errno == ENODEV && S_ISDIR(st.st_mode))
3356
				errno = EISDIR;
3357
			error_errno(_("unable to mmap '%s'%s"),
3358
					config_filename, mmap_os_err());
3359
			ret = CONFIG_INVALID_FILE;
3360
			contents = NULL;
3361
			goto out_free;
3362
		}
3363
		close(in_fd);
3364
		in_fd = -1;
3365

3366
		if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3367
			error_errno(_("chmod on %s failed"), get_lock_file_path(&lock));
3368
			ret = CONFIG_NO_WRITE;
3369
			goto out_free;
3370
		}
3371

3372
		if (store.seen_nr == 0) {
3373
			if (!store.seen_alloc) {
3374
				/* Did not see key nor section */
3375
				ALLOC_GROW(store.seen, 1, store.seen_alloc);
3376
				store.seen[0] = store.parsed_nr
3377
					- !!store.parsed_nr;
3378
			}
3379
			store.seen_nr = 1;
3380
		}
3381

3382
		for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
3383
			size_t replace_end;
3384
			int j = store.seen[i];
3385

3386
			new_line = 0;
3387
			if (!store.key_seen) {
3388
				copy_end = store.parsed[j].end;
3389
				/* include '\n' when copying section header */
3390
				if (copy_end > 0 && copy_end < contents_sz &&
3391
				    contents[copy_end - 1] != '\n' &&
3392
				    contents[copy_end] == '\n')
3393
					copy_end++;
3394
				replace_end = copy_end;
3395
			} else {
3396
				replace_end = store.parsed[j].end;
3397
				copy_end = store.parsed[j].begin;
3398
				if (!value)
3399
					maybe_remove_section(&store,
3400
							     &copy_end,
3401
							     &replace_end, &i);
3402
				/*
3403
				 * Swallow preceding white-space on the same
3404
				 * line.
3405
				 */
3406
				while (copy_end > 0 ) {
3407
					char c = contents[copy_end - 1];
3408

3409
					if (isspace(c) && c != '\n')
3410
						copy_end--;
3411
					else
3412
						break;
3413
				}
3414
			}
3415

3416
			if (copy_end > 0 && contents[copy_end-1] != '\n')
3417
				new_line = 1;
3418

3419
			/* write the first part of the config */
3420
			if (copy_end > copy_begin) {
3421
				if (write_in_full(fd, contents + copy_begin,
3422
						  copy_end - copy_begin) < 0)
3423
					goto write_err_out;
3424
				if (new_line &&
3425
				    write_str_in_full(fd, "\n") < 0)
3426
					goto write_err_out;
3427
			}
3428
			copy_begin = replace_end;
3429
		}
3430

3431
		/* write the pair (value == NULL means unset) */
3432
		if (value) {
3433
			if (!store.section_seen) {
3434
				if (write_section(fd, key, &store) < 0)
3435
					goto write_err_out;
3436
			}
3437
			if (write_pair(fd, key, value, comment, &store) < 0)
3438
				goto write_err_out;
3439
		}
3440

3441
		/* write the rest of the config */
3442
		if (copy_begin < contents_sz)
3443
			if (write_in_full(fd, contents + copy_begin,
3444
					  contents_sz - copy_begin) < 0)
3445
				goto write_err_out;
3446

3447
		munmap(contents, contents_sz);
3448
		contents = NULL;
3449
	}
3450

3451
	if (commit_lock_file(&lock) < 0) {
3452
		error_errno(_("could not write config file %s"), config_filename);
3453
		ret = CONFIG_NO_WRITE;
3454
		goto out_free;
3455
	}
3456

3457
	ret = 0;
3458

3459
	/* Invalidate the config cache */
3460
	repo_config_clear(r);
3461

3462
out_free:
3463
	rollback_lock_file(&lock);
3464
	free(filename_buf);
3465
	if (contents)
3466
		munmap(contents, contents_sz);
3467
	if (in_fd >= 0)
3468
		close(in_fd);
3469
	config_store_data_clear(&store);
3470
	return ret;
3471

3472
write_err_out:
3473
	ret = write_error(get_lock_file_path(&lock));
3474
	goto out_free;
3475
}
3476

3477
void repo_config_set_multivar_in_file(struct repository *r,
3478
				      const char *config_filename,
3479
				      const char *key, const char *value,
3480
				      const char *value_pattern, unsigned flags)
3481
{
3482
	if (!repo_config_set_multivar_in_file_gently(r, config_filename, key, value,
3483
						     value_pattern, NULL, flags))
3484
		return;
3485
	if (value)
3486
		die(_("could not set '%s' to '%s'"), key, value);
3487
	else
3488
		die(_("could not unset '%s'"), key);
3489
}
3490

3491
int repo_config_set_multivar_gently(struct repository *r, const char *key,
3492
				    const char *value,
3493
				    const char *value_pattern, unsigned flags)
3494
{
3495
	char *file = repo_git_path(r, "config");
3496
	int res = repo_config_set_multivar_in_file_gently(r, file,
3497
							  key, value,
3498
							  value_pattern,
3499
							  NULL, flags);
3500
	free(file);
3501
	return res;
3502
}
3503

3504
void repo_config_set_multivar(struct repository *r,
3505
			      const char *key, const char *value,
3506
			      const char *value_pattern, unsigned flags)
3507
{
3508
	char *file = repo_git_path(r, "config");
3509
	repo_config_set_multivar_in_file(r, file, key, value,
3510
					 value_pattern, flags);
3511
	free(file);
3512
}
3513

3514
static size_t section_name_match (const char *buf, const char *name)
3515
{
3516
	size_t i = 0, j = 0;
3517
	int dot = 0;
3518
	if (buf[i] != '[')
3519
		return 0;
3520
	for (i = 1; buf[i] && buf[i] != ']'; i++) {
3521
		if (!dot && isspace(buf[i])) {
3522
			dot = 1;
3523
			if (name[j++] != '.')
3524
				break;
3525
			for (i++; isspace(buf[i]); i++)
3526
				; /* do nothing */
3527
			if (buf[i] != '"')
3528
				break;
3529
			continue;
3530
		}
3531
		if (buf[i] == '\\' && dot)
3532
			i++;
3533
		else if (buf[i] == '"' && dot) {
3534
			for (i++; isspace(buf[i]); i++)
3535
				; /* do_nothing */
3536
			break;
3537
		}
3538
		if (buf[i] != name[j++])
3539
			break;
3540
	}
3541
	if (buf[i] == ']' && name[j] == 0) {
3542
		/*
3543
		 * We match, now just find the right length offset by
3544
		 * gobbling up any whitespace after it, as well
3545
		 */
3546
		i++;
3547
		for (; buf[i] && isspace(buf[i]); i++)
3548
			; /* do nothing */
3549
		return i;
3550
	}
3551
	return 0;
3552
}
3553

3554
static int section_name_is_ok(const char *name)
3555
{
3556
	/* Empty section names are bogus. */
3557
	if (!*name)
3558
		return 0;
3559

3560
	/*
3561
	 * Before a dot, we must be alphanumeric or dash. After the first dot,
3562
	 * anything goes, so we can stop checking.
3563
	 */
3564
	for (; *name && *name != '.'; name++)
3565
		if (*name != '-' && !isalnum(*name))
3566
			return 0;
3567
	return 1;
3568
}
3569

3570
#define GIT_CONFIG_MAX_LINE_LEN (512 * 1024)
3571

3572
/* if new_name == NULL, the section is removed instead */
3573
static int repo_config_copy_or_rename_section_in_file(
3574
	struct repository *r,
3575
	const char *config_filename,
3576
	const char *old_name,
3577
	const char *new_name, int copy)
3578
{
3579
	int ret = 0, remove = 0;
3580
	char *filename_buf = NULL;
3581
	struct lock_file lock = LOCK_INIT;
3582
	int out_fd;
3583
	struct strbuf buf = STRBUF_INIT;
3584
	FILE *config_file = NULL;
3585
	struct stat st;
3586
	struct strbuf copystr = STRBUF_INIT;
3587
	struct config_store_data store;
3588
	uint32_t line_nr = 0;
3589

3590
	memset(&store, 0, sizeof(store));
3591

3592
	if (new_name && !section_name_is_ok(new_name)) {
3593
		ret = error(_("invalid section name: %s"), new_name);
3594
		goto out_no_rollback;
3595
	}
3596

3597
	if (!config_filename)
3598
		config_filename = filename_buf = repo_git_path(r, "config");
3599

3600
	out_fd = hold_lock_file_for_update(&lock, config_filename, 0);
3601
	if (out_fd < 0) {
3602
		ret = error(_("could not lock config file %s"), config_filename);
3603
		goto out;
3604
	}
3605

3606
	if (!(config_file = fopen(config_filename, "rb"))) {
3607
		ret = warn_on_fopen_errors(config_filename);
3608
		if (ret)
3609
			goto out;
3610
		/* no config file means nothing to rename, no error */
3611
		goto commit_and_out;
3612
	}
3613

3614
	if (fstat(fileno(config_file), &st) == -1) {
3615
		ret = error_errno(_("fstat on %s failed"), config_filename);
3616
		goto out;
3617
	}
3618

3619
	if (chmod(get_lock_file_path(&lock), st.st_mode & 07777) < 0) {
3620
		ret = error_errno(_("chmod on %s failed"),
3621
				  get_lock_file_path(&lock));
3622
		goto out;
3623
	}
3624

3625
	while (!strbuf_getwholeline(&buf, config_file, '\n')) {
3626
		size_t i, length;
3627
		int is_section = 0;
3628
		char *output = buf.buf;
3629

3630
		line_nr++;
3631

3632
		if (buf.len >= GIT_CONFIG_MAX_LINE_LEN) {
3633
			ret = error(_("refusing to work with overly long line "
3634
				      "in '%s' on line %"PRIuMAX),
3635
				    config_filename, (uintmax_t)line_nr);
3636
			goto out;
3637
		}
3638

3639
		for (i = 0; buf.buf[i] && isspace(buf.buf[i]); i++)
3640
			; /* do nothing */
3641
		if (buf.buf[i] == '[') {
3642
			/* it's a section */
3643
			size_t offset;
3644
			is_section = 1;
3645

3646
			/*
3647
			 * When encountering a new section under -c we
3648
			 * need to flush out any section we're already
3649
			 * coping and begin anew. There might be
3650
			 * multiple [branch "$name"] sections.
3651
			 */
3652
			if (copystr.len > 0) {
3653
				if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3654
					ret = write_error(get_lock_file_path(&lock));
3655
					goto out;
3656
				}
3657
				strbuf_reset(&copystr);
3658
			}
3659

3660
			offset = section_name_match(&buf.buf[i], old_name);
3661
			if (offset > 0) {
3662
				ret++;
3663
				if (!new_name) {
3664
					remove = 1;
3665
					continue;
3666
				}
3667
				store.baselen = strlen(new_name);
3668
				if (!copy) {
3669
					if (write_section(out_fd, new_name, &store) < 0) {
3670
						ret = write_error(get_lock_file_path(&lock));
3671
						goto out;
3672
					}
3673
					/*
3674
					 * We wrote out the new section, with
3675
					 * a newline, now skip the old
3676
					 * section's length
3677
					 */
3678
					output += offset + i;
3679
					if (strlen(output) > 0) {
3680
						/*
3681
						 * More content means there's
3682
						 * a declaration to put on the
3683
						 * next line; indent with a
3684
						 * tab
3685
						 */
3686
						output -= 1;
3687
						output[0] = '\t';
3688
					}
3689
				} else {
3690
					strbuf_release(&copystr);
3691
					copystr = store_create_section(new_name, &store);
3692
				}
3693
			}
3694
			remove = 0;
3695
		}
3696
		if (remove)
3697
			continue;
3698
		length = strlen(output);
3699

3700
		if (!is_section && copystr.len > 0) {
3701
			strbuf_add(&copystr, output, length);
3702
		}
3703

3704
		if (write_in_full(out_fd, output, length) < 0) {
3705
			ret = write_error(get_lock_file_path(&lock));
3706
			goto out;
3707
		}
3708
	}
3709

3710
	/*
3711
	 * Copy a trailing section at the end of the config, won't be
3712
	 * flushed by the usual "flush because we have a new section
3713
	 * logic in the loop above.
3714
	 */
3715
	if (copystr.len > 0) {
3716
		if (write_in_full(out_fd, copystr.buf, copystr.len) < 0) {
3717
			ret = write_error(get_lock_file_path(&lock));
3718
			goto out;
3719
		}
3720
		strbuf_reset(&copystr);
3721
	}
3722

3723
	fclose(config_file);
3724
	config_file = NULL;
3725
commit_and_out:
3726
	if (commit_lock_file(&lock) < 0)
3727
		ret = error_errno(_("could not write config file %s"),
3728
				  config_filename);
3729
out:
3730
	if (config_file)
3731
		fclose(config_file);
3732
	rollback_lock_file(&lock);
3733
out_no_rollback:
3734
	free(filename_buf);
3735
	config_store_data_clear(&store);
3736
	strbuf_release(&buf);
3737
	strbuf_release(&copystr);
3738
	return ret;
3739
}
3740

3741
int repo_config_rename_section_in_file(struct repository *r, const char *config_filename,
3742
				       const char *old_name, const char *new_name)
3743
{
3744
	return repo_config_copy_or_rename_section_in_file(r, config_filename,
3745
					 old_name, new_name, 0);
3746
}
3747

3748
int repo_config_rename_section(struct repository *r, const char *old_name, const char *new_name)
3749
{
3750
	return repo_config_rename_section_in_file(r, NULL, old_name, new_name);
3751
}
3752

3753
int repo_config_copy_section_in_file(struct repository *r, const char *config_filename,
3754
				     const char *old_name, const char *new_name)
3755
{
3756
	return repo_config_copy_or_rename_section_in_file(r, config_filename,
3757
					 old_name, new_name, 1);
3758
}
3759

3760
int repo_config_copy_section(struct repository *r, const char *old_name, const char *new_name)
3761
{
3762
	return repo_config_copy_section_in_file(r, NULL, old_name, new_name);
3763
}
3764

3765
/*
3766
 * Call this to report error for your variable that should not
3767
 * get a boolean value (i.e. "[my] var" means "true").
3768
 */
3769
#undef config_error_nonbool
3770
int config_error_nonbool(const char *var)
3771
{
3772
	return error(_("missing value for '%s'"), var);
3773
}
3774

3775
int parse_config_key(const char *var,
3776
		     const char *section,
3777
		     const char **subsection, size_t *subsection_len,
3778
		     const char **key)
3779
{
3780
	const char *dot;
3781

3782
	/* Does it start with "section." ? */
3783
	if (!skip_prefix(var, section, &var) || *var != '.')
3784
		return -1;
3785

3786
	/*
3787
	 * Find the key; we don't know yet if we have a subsection, but we must
3788
	 * parse backwards from the end, since the subsection may have dots in
3789
	 * it, too.
3790
	 */
3791
	dot = strrchr(var, '.');
3792
	*key = dot + 1;
3793

3794
	/* Did we have a subsection at all? */
3795
	if (dot == var) {
3796
		if (subsection) {
3797
			*subsection = NULL;
3798
			*subsection_len = 0;
3799
		}
3800
	}
3801
	else {
3802
		if (!subsection)
3803
			return -1;
3804
		*subsection = var + 1;
3805
		*subsection_len = dot - *subsection;
3806
	}
3807

3808
	return 0;
3809
}
3810

3811
const char *config_origin_type_name(enum config_origin_type type)
3812
{
3813
	switch (type) {
3814
	case CONFIG_ORIGIN_BLOB:
3815
		return "blob";
3816
	case CONFIG_ORIGIN_FILE:
3817
		return "file";
3818
	case CONFIG_ORIGIN_STDIN:
3819
		return "standard input";
3820
	case CONFIG_ORIGIN_SUBMODULE_BLOB:
3821
		return "submodule-blob";
3822
	case CONFIG_ORIGIN_CMDLINE:
3823
		return "command line";
3824
	default:
3825
		BUG("unknown config origin type");
3826
	}
3827
}
3828

3829
const char *config_scope_name(enum config_scope scope)
3830
{
3831
	switch (scope) {
3832
	case CONFIG_SCOPE_SYSTEM:
3833
		return "system";
3834
	case CONFIG_SCOPE_GLOBAL:
3835
		return "global";
3836
	case CONFIG_SCOPE_LOCAL:
3837
		return "local";
3838
	case CONFIG_SCOPE_WORKTREE:
3839
		return "worktree";
3840
	case CONFIG_SCOPE_COMMAND:
3841
		return "command";
3842
	case CONFIG_SCOPE_SUBMODULE:
3843
		return "submodule";
3844
	default:
3845
		return "unknown";
3846
	}
3847
}
3848

3849
int lookup_config(const char **mapping, int nr_mapping, const char *var)
3850
{
3851
	int i;
3852

3853
	for (i = 0; i < nr_mapping; i++) {
3854
		const char *name = mapping[i];
3855

3856
		if (name && !strcasecmp(var, name))
3857
			return i;
3858
	}
3859
	return -1;
3860
}
3861

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.