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