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