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