2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
5 * Copyright (C) Johannes Schindelin, 2005
12 #include "environment.h"
13 #include "repository.h"
19 #include "string-list.h"
20 #include "object-store.h"
27 struct config_source
{
28 struct config_source
*prev
;
37 enum config_origin_type origin_type
;
40 enum config_error_action default_error_action
;
46 unsigned subsection_case_sensitive
: 1;
48 int (*do_fgetc
)(struct config_source
*c
);
49 int (*do_ungetc
)(int c
, struct config_source
*conf
);
50 long (*do_ftell
)(struct config_source
*c
);
54 * These variables record the "current" config source, which
55 * can be accessed by parsing callbacks.
57 * The "cf" variable will be non-NULL only when we are actually parsing a real
58 * config source (file, blob, cmdline, etc).
60 * The "current_config_kvi" variable will be non-NULL only when we are feeding
61 * cached config from a configset into a callback.
63 * They should generally never be non-NULL at the same time. If they are both
64 * NULL, then we aren't parsing anything (and depending on the function looking
65 * at the variables, it's either a bug for it to be called in the first place,
66 * or it's a function which can be reused for non-config purposes, and should
67 * fall back to some sane behavior).
69 static struct config_source
*cf
;
70 static struct key_value_info
*current_config_kvi
;
73 * Similar to the variables above, this gives access to the "scope" of the
74 * current value (repo, global, etc). For cached values, it can be found via
75 * the current_config_kvi as above. During parsing, the current value can be
76 * found in this variable. It's not part of "cf" because it transcends a single
77 * file (i.e., a file included from .git/config is still in "repo" scope).
79 static enum config_scope current_parsing_scope
;
81 static int pack_compression_seen
;
82 static int zlib_compression_seen
;
84 static int config_file_fgetc(struct config_source
*conf
)
86 return getc_unlocked(conf
->u
.file
);
89 static int config_file_ungetc(int c
, struct config_source
*conf
)
91 return ungetc(c
, conf
->u
.file
);
94 static long config_file_ftell(struct config_source
*conf
)
96 return ftell(conf
->u
.file
);
100 static int config_buf_fgetc(struct config_source
*conf
)
102 if (conf
->u
.buf
.pos
< conf
->u
.buf
.len
)
103 return conf
->u
.buf
.buf
[conf
->u
.buf
.pos
++];
108 static int config_buf_ungetc(int c
, struct config_source
*conf
)
110 if (conf
->u
.buf
.pos
> 0) {
112 if (conf
->u
.buf
.buf
[conf
->u
.buf
.pos
] != c
)
113 BUG("config_buf can only ungetc the same character");
120 static long config_buf_ftell(struct config_source
*conf
)
122 return conf
->u
.buf
.pos
;
125 struct config_include_data
{
129 const struct config_options
*opts
;
130 struct git_config_source
*config_source
;
133 * All remote URLs discovered when reading all config files.
135 struct string_list
*remote_urls
;
137 #define CONFIG_INCLUDE_INIT { 0 }
139 static int git_config_include(const char *var
, const char *value
, void *data
);
141 #define MAX_INCLUDE_DEPTH 10
142 static const char include_depth_advice
[] = N_(
143 "exceeded maximum include depth (%d) while including\n"
147 "This might be due to circular includes.");
148 static int handle_path_include(const char *path
, struct config_include_data
*inc
)
151 struct strbuf buf
= STRBUF_INIT
;
155 return config_error_nonbool("include.path");
157 expanded
= interpolate_path(path
, 0);
159 return error(_("could not expand include path '%s'"), path
);
163 * Use an absolute path as-is, but interpret relative paths
164 * based on the including config file.
166 if (!is_absolute_path(path
)) {
169 if (!cf
|| !cf
->path
) {
170 ret
= error(_("relative config includes must come from files"));
174 slash
= find_last_dir_sep(cf
->path
);
176 strbuf_add(&buf
, cf
->path
, slash
- cf
->path
+ 1);
177 strbuf_addstr(&buf
, path
);
181 if (!access_or_die(path
, R_OK
, 0)) {
182 if (++inc
->depth
> MAX_INCLUDE_DEPTH
)
183 die(_(include_depth_advice
), MAX_INCLUDE_DEPTH
, path
,
185 cf
->name
? cf
->name
:
187 ret
= git_config_from_file(git_config_include
, path
, inc
);
191 strbuf_release(&buf
);
196 static void add_trailing_starstar_for_dir(struct strbuf
*pat
)
198 if (pat
->len
&& is_dir_sep(pat
->buf
[pat
->len
- 1]))
199 strbuf_addstr(pat
, "**");
202 static int prepare_include_condition_pattern(struct strbuf
*pat
)
204 struct strbuf path
= STRBUF_INIT
;
208 expanded
= interpolate_path(pat
->buf
, 1);
211 strbuf_addstr(pat
, expanded
);
215 if (pat
->buf
[0] == '.' && is_dir_sep(pat
->buf
[1])) {
218 if (!cf
|| !cf
->path
)
219 return error(_("relative config include "
220 "conditionals must come from files"));
222 strbuf_realpath(&path
, cf
->path
, 1);
223 slash
= find_last_dir_sep(path
.buf
);
225 BUG("how is this possible?");
226 strbuf_splice(pat
, 0, 1, path
.buf
, slash
- path
.buf
);
227 prefix
= slash
- path
.buf
+ 1 /* slash */;
228 } else if (!is_absolute_path(pat
->buf
))
229 strbuf_insertstr(pat
, 0, "**/");
231 add_trailing_starstar_for_dir(pat
);
233 strbuf_release(&path
);
237 static int include_by_gitdir(const struct config_options
*opts
,
238 const char *cond
, size_t cond_len
, int icase
)
240 struct strbuf text
= STRBUF_INIT
;
241 struct strbuf pattern
= STRBUF_INIT
;
244 int already_tried_absolute
= 0;
247 git_dir
= opts
->git_dir
;
251 strbuf_realpath(&text
, git_dir
, 1);
252 strbuf_add(&pattern
, cond
, cond_len
);
253 prefix
= prepare_include_condition_pattern(&pattern
);
261 * perform literal matching on the prefix part so that
262 * any wildcard character in it can't create side effects.
264 if (text
.len
< prefix
)
266 if (!icase
&& strncmp(pattern
.buf
, text
.buf
, prefix
))
268 if (icase
&& strncasecmp(pattern
.buf
, text
.buf
, prefix
))
272 ret
= !wildmatch(pattern
.buf
+ prefix
, text
.buf
+ prefix
,
273 WM_PATHNAME
| (icase
? WM_CASEFOLD
: 0));
275 if (!ret
&& !already_tried_absolute
) {
277 * We've tried e.g. matching gitdir:~/work, but if
278 * ~/work is a symlink to /mnt/storage/work
279 * strbuf_realpath() will expand it, so the rule won't
280 * match. Let's match against a
281 * strbuf_add_absolute_path() version of the path,
282 * which'll do the right thing
285 strbuf_add_absolute_path(&text
, git_dir
);
286 already_tried_absolute
= 1;
290 strbuf_release(&pattern
);
291 strbuf_release(&text
);
295 static int include_by_branch(const char *cond
, size_t cond_len
)
299 struct strbuf pattern
= STRBUF_INIT
;
300 const char *refname
= !the_repository
->gitdir
?
301 NULL
: resolve_ref_unsafe("HEAD", 0, NULL
, &flags
);
302 const char *shortname
;
304 if (!refname
|| !(flags
& REF_ISSYMREF
) ||
305 !skip_prefix(refname
, "refs/heads/", &shortname
))
308 strbuf_add(&pattern
, cond
, cond_len
);
309 add_trailing_starstar_for_dir(&pattern
);
310 ret
= !wildmatch(pattern
.buf
, shortname
, WM_PATHNAME
);
311 strbuf_release(&pattern
);
315 static int add_remote_url(const char *var
, const char *value
, void *data
)
317 struct string_list
*remote_urls
= data
;
318 const char *remote_name
;
319 size_t remote_name_len
;
322 if (!parse_config_key(var
, "remote", &remote_name
, &remote_name_len
,
326 string_list_append(remote_urls
, value
);
330 static void populate_remote_urls(struct config_include_data
*inc
)
332 struct config_options opts
;
334 struct config_source
*store_cf
= cf
;
335 struct key_value_info
*store_kvi
= current_config_kvi
;
336 enum config_scope store_scope
= current_parsing_scope
;
339 opts
.unconditional_remote_url
= 1;
342 current_config_kvi
= NULL
;
343 current_parsing_scope
= 0;
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
, inc
->config_source
, &opts
);
350 current_config_kvi
= store_kvi
;
351 current_parsing_scope
= store_scope
;
354 static int forbid_remote_url(const char *var
, const char *value
, void *data
)
356 const char *remote_name
;
357 size_t remote_name_len
;
360 if (!parse_config_key(var
, "remote", &remote_name
, &remote_name_len
,
364 die(_("remote URLs cannot be configured in file directly or indirectly included by includeIf.hasconfig:remote.*.url"));
368 static int at_least_one_url_matches_glob(const char *glob
, int glob_len
,
369 struct string_list
*remote_urls
)
371 struct strbuf pattern
= STRBUF_INIT
;
372 struct string_list_item
*url_item
;
375 strbuf_add(&pattern
, glob
, glob_len
);
376 for_each_string_list_item(url_item
, remote_urls
) {
377 if (!wildmatch(pattern
.buf
, url_item
->string
, WM_PATHNAME
)) {
382 strbuf_release(&pattern
);
386 static int include_by_remote_url(struct config_include_data
*inc
,
387 const char *cond
, size_t cond_len
)
389 if (inc
->opts
->unconditional_remote_url
)
391 if (!inc
->remote_urls
)
392 populate_remote_urls(inc
);
393 return at_least_one_url_matches_glob(cond
, cond_len
,
397 static int include_condition_is_true(struct config_include_data
*inc
,
398 const char *cond
, size_t cond_len
)
400 const struct config_options
*opts
= inc
->opts
;
402 if (skip_prefix_mem(cond
, cond_len
, "gitdir:", &cond
, &cond_len
))
403 return include_by_gitdir(opts
, cond
, cond_len
, 0);
404 else if (skip_prefix_mem(cond
, cond_len
, "gitdir/i:", &cond
, &cond_len
))
405 return include_by_gitdir(opts
, cond
, cond_len
, 1);
406 else if (skip_prefix_mem(cond
, cond_len
, "onbranch:", &cond
, &cond_len
))
407 return include_by_branch(cond
, cond_len
);
408 else if (skip_prefix_mem(cond
, cond_len
, "hasconfig:remote.*.url:", &cond
,
410 return include_by_remote_url(inc
, cond
, cond_len
);
412 /* unknown conditionals are always false */
416 static int git_config_include(const char *var
, const char *value
, void *data
)
418 struct config_include_data
*inc
= data
;
419 const char *cond
, *key
;
424 * Pass along all values, including "include" directives; this makes it
425 * possible to query information on the includes themselves.
427 ret
= inc
->fn(var
, value
, inc
->data
);
431 if (!strcmp(var
, "include.path"))
432 ret
= handle_path_include(value
, inc
);
434 if (!parse_config_key(var
, "includeif", &cond
, &cond_len
, &key
) &&
435 cond
&& include_condition_is_true(inc
, cond
, cond_len
) &&
436 !strcmp(key
, "path")) {
437 config_fn_t old_fn
= inc
->fn
;
439 if (inc
->opts
->unconditional_remote_url
)
440 inc
->fn
= forbid_remote_url
;
441 ret
= handle_path_include(value
, inc
);
448 static void git_config_push_split_parameter(const char *key
, const char *value
)
450 struct strbuf env
= STRBUF_INIT
;
451 const char *old
= getenv(CONFIG_DATA_ENVIRONMENT
);
453 strbuf_addstr(&env
, old
);
454 strbuf_addch(&env
, ' ');
456 sq_quote_buf(&env
, key
);
457 strbuf_addch(&env
, '=');
459 sq_quote_buf(&env
, value
);
460 setenv(CONFIG_DATA_ENVIRONMENT
, env
.buf
, 1);
461 strbuf_release(&env
);
464 void git_config_push_parameter(const char *text
)
471 * section.subsection=with=equals.key=value
473 * we cannot tell if it means:
475 * [section "subsection=with=equals"]
481 * subsection = with=equals.key=value
483 * We parse left-to-right for the first "=", meaning we'll prefer to
484 * keep the value intact over the subsection. This is historical, but
485 * also sensible since values are more likely to contain odd or
486 * untrusted input than a section name.
488 * A missing equals is explicitly allowed (as a bool-only entry).
490 value
= strchr(text
, '=');
492 char *key
= xmemdupz(text
, value
- text
);
493 git_config_push_split_parameter(key
, value
+ 1);
496 git_config_push_split_parameter(text
, NULL
);
500 void git_config_push_env(const char *spec
)
503 const char *env_name
;
504 const char *env_value
;
506 env_name
= strrchr(spec
, '=');
508 die(_("invalid config format: %s"), spec
);
509 key
= xmemdupz(spec
, env_name
- spec
);
512 die(_("missing environment variable name for configuration '%.*s'"),
513 (int)(env_name
- spec
- 1), spec
);
515 env_value
= getenv(env_name
);
517 die(_("missing environment variable '%s' for configuration '%.*s'"),
518 env_name
, (int)(env_name
- spec
- 1), spec
);
520 git_config_push_split_parameter(key
, env_value
);
524 static inline int iskeychar(int c
)
526 return isalnum(c
) || c
== '-';
530 * Auxiliary function to sanity-check and split the key into the section
531 * identifier and variable name.
533 * Returns 0 on success, -1 when there is an invalid character in the key and
534 * -2 if there is no section name in the key.
536 * store_key - pointer to char* which will hold a copy of the key with
537 * lowercase section and variable name
538 * baselen - pointer to size_t which will hold the length of the
539 * section + subsection part, can be NULL
541 int git_config_parse_key(const char *key
, char **store_key
, size_t *baselen_
)
545 const char *last_dot
= strrchr(key
, '.');
548 * Since "key" actually contains the section name and the real
549 * key name separated by a dot, we have to know where the dot is.
552 if (last_dot
== NULL
|| last_dot
== key
) {
553 error(_("key does not contain a section: %s"), key
);
554 return -CONFIG_NO_SECTION_OR_NAME
;
558 error(_("key does not contain variable name: %s"), key
);
559 return -CONFIG_NO_SECTION_OR_NAME
;
562 baselen
= last_dot
- key
;
567 * Validate the key and while at it, lower case it for matching.
569 *store_key
= xmallocz(strlen(key
));
572 for (i
= 0; key
[i
]; i
++) {
573 unsigned char c
= key
[i
];
576 /* Leave the extended basename untouched.. */
577 if (!dot
|| i
> baselen
) {
579 (i
== baselen
+ 1 && !isalpha(c
))) {
580 error(_("invalid key: %s"), key
);
584 } else if (c
== '\n') {
585 error(_("invalid key (newline): %s"), key
);
594 FREE_AND_NULL(*store_key
);
595 return -CONFIG_INVALID_KEY
;
598 static int config_parse_pair(const char *key
, const char *value
,
599 config_fn_t fn
, void *data
)
601 char *canonical_name
;
605 return error(_("empty config key"));
606 if (git_config_parse_key(key
, &canonical_name
, NULL
))
609 ret
= (fn(canonical_name
, value
, data
) < 0) ? -1 : 0;
610 free(canonical_name
);
614 int git_config_parse_parameter(const char *text
,
615 config_fn_t fn
, void *data
)
618 struct strbuf
**pair
;
621 pair
= strbuf_split_str(text
, '=', 2);
623 return error(_("bogus config parameter: %s"), text
);
625 if (pair
[0]->len
&& pair
[0]->buf
[pair
[0]->len
- 1] == '=') {
626 strbuf_setlen(pair
[0], pair
[0]->len
- 1);
627 value
= pair
[1] ? pair
[1]->buf
: "";
632 strbuf_trim(pair
[0]);
634 strbuf_list_free(pair
);
635 return error(_("bogus config parameter: %s"), text
);
638 ret
= config_parse_pair(pair
[0]->buf
, value
, fn
, data
);
639 strbuf_list_free(pair
);
643 static int parse_config_env_list(char *env
, config_fn_t fn
, void *data
)
646 while (cur
&& *cur
) {
647 const char *key
= sq_dequote_step(cur
, &cur
);
649 return error(_("bogus format in %s"),
650 CONFIG_DATA_ENVIRONMENT
);
652 if (!cur
|| isspace(*cur
)) {
653 /* old-style 'key=value' */
654 if (git_config_parse_parameter(key
, fn
, data
) < 0)
657 else if (*cur
== '=') {
658 /* new-style 'key'='value' */
664 value
= sq_dequote_step(cur
, &cur
);
665 if (!value
|| (cur
&& !isspace(*cur
))) {
666 return error(_("bogus format in %s"),
667 CONFIG_DATA_ENVIRONMENT
);
669 } else if (!*cur
|| isspace(*cur
)) {
670 /* implicit bool: 'key'= */
673 return error(_("bogus format in %s"),
674 CONFIG_DATA_ENVIRONMENT
);
677 if (config_parse_pair(key
, value
, fn
, data
) < 0)
682 return error(_("bogus format in %s"),
683 CONFIG_DATA_ENVIRONMENT
);
687 while (isspace(*cur
))
694 int git_config_from_parameters(config_fn_t fn
, void *data
)
697 struct strbuf envvar
= STRBUF_INIT
;
698 struct strvec to_free
= STRVEC_INIT
;
701 struct config_source source
;
703 memset(&source
, 0, sizeof(source
));
705 source
.origin_type
= CONFIG_ORIGIN_CMDLINE
;
708 env
= getenv(CONFIG_COUNT_ENVIRONMENT
);
714 count
= strtoul(env
, &endp
, 10);
716 ret
= error(_("bogus count in %s"), CONFIG_COUNT_ENVIRONMENT
);
719 if (count
> INT_MAX
) {
720 ret
= error(_("too many entries in %s"), CONFIG_COUNT_ENVIRONMENT
);
724 for (i
= 0; i
< count
; i
++) {
725 const char *key
, *value
;
727 strbuf_addf(&envvar
, "GIT_CONFIG_KEY_%d", i
);
728 key
= getenv_safe(&to_free
, envvar
.buf
);
730 ret
= error(_("missing config key %s"), envvar
.buf
);
733 strbuf_reset(&envvar
);
735 strbuf_addf(&envvar
, "GIT_CONFIG_VALUE_%d", i
);
736 value
= getenv_safe(&to_free
, envvar
.buf
);
738 ret
= error(_("missing config value %s"), envvar
.buf
);
741 strbuf_reset(&envvar
);
743 if (config_parse_pair(key
, value
, fn
, data
) < 0) {
750 env
= getenv(CONFIG_DATA_ENVIRONMENT
);
752 /* sq_dequote will write over it */
754 if (parse_config_env_list(envw
, fn
, data
) < 0) {
761 strbuf_release(&envvar
);
762 strvec_clear(&to_free
);
768 static int get_next_char(void)
770 int c
= cf
->do_fgetc(cf
);
773 /* DOS like systems */
774 c
= cf
->do_fgetc(cf
);
777 cf
->do_ungetc(c
, cf
);
782 if (c
!= EOF
&& ++cf
->total_len
> INT_MAX
) {
784 * This is an absurdly long config file; refuse to parse
785 * further in order to protect downstream code from integer
786 * overflows. Note that we can't return an error specifically,
787 * but we can mark EOF and put trash in the return value,
788 * which will trigger a parse error.
804 static char *parse_value(void)
806 int quote
= 0, comment
= 0, space
= 0;
808 strbuf_reset(&cf
->value
);
810 int c
= get_next_char();
816 return cf
->value
.buf
;
820 if (isspace(c
) && !quote
) {
826 if (c
== ';' || c
== '#') {
831 for (; space
; space
--)
832 strbuf_addch(&cf
->value
, ' ');
847 /* Some characters escape as themselves */
850 /* Reject unknown escape sequences */
854 strbuf_addch(&cf
->value
, c
);
861 strbuf_addch(&cf
->value
, c
);
865 static int get_value(config_fn_t fn
, void *data
, struct strbuf
*name
)
871 /* Get the full name */
878 strbuf_addch(name
, tolower(c
));
881 while (c
== ' ' || c
== '\t')
888 value
= parse_value();
893 * We already consumed the \n, but we need linenr to point to
894 * the line we just parsed during the call to fn to get
895 * accurate line number in error messages.
898 ret
= fn(name
->buf
, value
, data
);
904 static int get_extended_base_var(struct strbuf
*name
, int c
)
906 cf
->subsection_case_sensitive
= 0;
909 goto error_incomplete_line
;
911 } while (isspace(c
));
913 /* We require the format to be '[base "extension"]' */
916 strbuf_addch(name
, '.');
919 int c
= get_next_char();
921 goto error_incomplete_line
;
927 goto error_incomplete_line
;
929 strbuf_addch(name
, c
);
933 if (get_next_char() != ']')
936 error_incomplete_line
:
941 static int get_base_var(struct strbuf
*name
)
943 cf
->subsection_case_sensitive
= 1;
945 int c
= get_next_char();
951 return get_extended_base_var(name
, c
);
952 if (!iskeychar(c
) && c
!= '.')
954 strbuf_addch(name
, tolower(c
));
958 struct parse_event_data
{
959 enum config_event_t previous_type
;
960 size_t previous_offset
;
961 const struct config_options
*opts
;
964 static int do_event(enum config_event_t type
, struct parse_event_data
*data
)
968 if (!data
->opts
|| !data
->opts
->event_fn
)
971 if (type
== CONFIG_EVENT_WHITESPACE
&&
972 data
->previous_type
== type
)
975 offset
= cf
->do_ftell(cf
);
977 * At EOF, the parser always "inserts" an extra '\n', therefore
978 * the end offset of the event is the current file position, otherwise
979 * we will already have advanced to the next event.
981 if (type
!= CONFIG_EVENT_EOF
)
984 if (data
->previous_type
!= CONFIG_EVENT_EOF
&&
985 data
->opts
->event_fn(data
->previous_type
, data
->previous_offset
,
986 offset
, data
->opts
->event_fn_data
) < 0)
989 data
->previous_type
= type
;
990 data
->previous_offset
= offset
;
995 static int git_parse_source(config_fn_t fn
, void *data
,
996 const struct config_options
*opts
)
1000 struct strbuf
*var
= &cf
->var
;
1001 int error_return
= 0;
1002 char *error_msg
= NULL
;
1004 /* U+FEFF Byte Order Mark in UTF8 */
1005 const char *bomptr
= utf8_bom
;
1007 /* For the parser event callback */
1008 struct parse_event_data event_data
= {
1009 CONFIG_EVENT_EOF
, 0, opts
1015 c
= get_next_char();
1016 if (bomptr
&& *bomptr
) {
1017 /* We are at the file beginning; skip UTF8-encoded BOM
1018 * if present. Sane editors won't put this in on their
1019 * own, but e.g. Windows Notepad will do it happily. */
1020 if (c
== (*bomptr
& 0377)) {
1024 /* Do not tolerate partial BOM. */
1025 if (bomptr
!= utf8_bom
)
1027 /* No BOM at file beginning. Cool. */
1033 if (do_event(CONFIG_EVENT_EOF
, &event_data
) < 0)
1037 if (do_event(CONFIG_EVENT_WHITESPACE
, &event_data
) < 0)
1045 if (do_event(CONFIG_EVENT_WHITESPACE
, &event_data
) < 0)
1049 if (c
== '#' || c
== ';') {
1050 if (do_event(CONFIG_EVENT_COMMENT
, &event_data
) < 0)
1056 if (do_event(CONFIG_EVENT_SECTION
, &event_data
) < 0)
1059 /* Reset prior to determining a new stem */
1061 if (get_base_var(var
) < 0 || var
->len
< 1)
1063 strbuf_addch(var
, '.');
1070 if (do_event(CONFIG_EVENT_ENTRY
, &event_data
) < 0)
1074 * Truncate the var name back to the section header
1075 * stem prior to grabbing the suffix part of the name
1078 strbuf_setlen(var
, baselen
);
1079 strbuf_addch(var
, tolower(c
));
1080 if (get_value(fn
, data
, var
) < 0)
1084 if (do_event(CONFIG_EVENT_ERROR
, &event_data
) < 0)
1087 switch (cf
->origin_type
) {
1088 case CONFIG_ORIGIN_BLOB
:
1089 error_msg
= xstrfmt(_("bad config line %d in blob %s"),
1090 cf
->linenr
, cf
->name
);
1092 case CONFIG_ORIGIN_FILE
:
1093 error_msg
= xstrfmt(_("bad config line %d in file %s"),
1094 cf
->linenr
, cf
->name
);
1096 case CONFIG_ORIGIN_STDIN
:
1097 error_msg
= xstrfmt(_("bad config line %d in standard input"),
1100 case CONFIG_ORIGIN_SUBMODULE_BLOB
:
1101 error_msg
= xstrfmt(_("bad config line %d in submodule-blob %s"),
1102 cf
->linenr
, cf
->name
);
1104 case CONFIG_ORIGIN_CMDLINE
:
1105 error_msg
= xstrfmt(_("bad config line %d in command line %s"),
1106 cf
->linenr
, cf
->name
);
1109 error_msg
= xstrfmt(_("bad config line %d in %s"),
1110 cf
->linenr
, cf
->name
);
1113 switch (opts
&& opts
->error_action
?
1114 opts
->error_action
:
1115 cf
->default_error_action
) {
1116 case CONFIG_ERROR_DIE
:
1117 die("%s", error_msg
);
1119 case CONFIG_ERROR_ERROR
:
1120 error_return
= error("%s", error_msg
);
1122 case CONFIG_ERROR_SILENT
:
1125 case CONFIG_ERROR_UNSET
:
1126 BUG("config error action unset");
1130 return error_return
;
1133 static uintmax_t get_unit_factor(const char *end
)
1137 else if (!strcasecmp(end
, "k"))
1139 else if (!strcasecmp(end
, "m"))
1141 else if (!strcasecmp(end
, "g"))
1142 return 1024 * 1024 * 1024;
1146 static int git_parse_signed(const char *value
, intmax_t *ret
, intmax_t max
)
1148 if (value
&& *value
) {
1155 val
= strtoimax(value
, &end
, 0);
1156 if (errno
== ERANGE
)
1158 factor
= get_unit_factor(end
);
1163 uval
= val
< 0 ? -val
: val
;
1164 if (unsigned_mult_overflows(factor
, uval
) ||
1165 factor
* uval
> max
) {
1177 static int git_parse_unsigned(const char *value
, uintmax_t *ret
, uintmax_t max
)
1179 if (value
&& *value
) {
1185 val
= strtoumax(value
, &end
, 0);
1186 if (errno
== ERANGE
)
1188 factor
= get_unit_factor(end
);
1193 if (unsigned_mult_overflows(factor
, val
) ||
1194 factor
* val
> max
) {
1206 static int git_parse_int(const char *value
, int *ret
)
1209 if (!git_parse_signed(value
, &tmp
, maximum_signed_value_of_type(int)))
1215 static int git_parse_int64(const char *value
, int64_t *ret
)
1218 if (!git_parse_signed(value
, &tmp
, maximum_signed_value_of_type(int64_t)))
1224 int git_parse_ulong(const char *value
, unsigned long *ret
)
1227 if (!git_parse_unsigned(value
, &tmp
, maximum_unsigned_value_of_type(long)))
1233 int git_parse_ssize_t(const char *value
, ssize_t
*ret
)
1236 if (!git_parse_signed(value
, &tmp
, maximum_signed_value_of_type(ssize_t
)))
1243 static void die_bad_number(const char *name
, const char *value
)
1245 const char *error_type
= (errno
== ERANGE
) ?
1246 N_("out of range") : N_("invalid unit");
1247 const char *bad_numeric
= N_("bad numeric config value '%s' for '%s': %s");
1252 if (!(cf
&& cf
->name
))
1253 die(_(bad_numeric
), value
, name
, _(error_type
));
1255 switch (cf
->origin_type
) {
1256 case CONFIG_ORIGIN_BLOB
:
1257 die(_("bad numeric config value '%s' for '%s' in blob %s: %s"),
1258 value
, name
, cf
->name
, _(error_type
));
1259 case CONFIG_ORIGIN_FILE
:
1260 die(_("bad numeric config value '%s' for '%s' in file %s: %s"),
1261 value
, name
, cf
->name
, _(error_type
));
1262 case CONFIG_ORIGIN_STDIN
:
1263 die(_("bad numeric config value '%s' for '%s' in standard input: %s"),
1264 value
, name
, _(error_type
));
1265 case CONFIG_ORIGIN_SUBMODULE_BLOB
:
1266 die(_("bad numeric config value '%s' for '%s' in submodule-blob %s: %s"),
1267 value
, name
, cf
->name
, _(error_type
));
1268 case CONFIG_ORIGIN_CMDLINE
:
1269 die(_("bad numeric config value '%s' for '%s' in command line %s: %s"),
1270 value
, name
, cf
->name
, _(error_type
));
1272 die(_("bad numeric config value '%s' for '%s' in %s: %s"),
1273 value
, name
, cf
->name
, _(error_type
));
1277 int git_config_int(const char *name
, const char *value
)
1280 if (!git_parse_int(value
, &ret
))
1281 die_bad_number(name
, value
);
1285 int64_t git_config_int64(const char *name
, const char *value
)
1288 if (!git_parse_int64(value
, &ret
))
1289 die_bad_number(name
, value
);
1293 unsigned long git_config_ulong(const char *name
, const char *value
)
1296 if (!git_parse_ulong(value
, &ret
))
1297 die_bad_number(name
, value
);
1301 ssize_t
git_config_ssize_t(const char *name
, const char *value
)
1304 if (!git_parse_ssize_t(value
, &ret
))
1305 die_bad_number(name
, value
);
1309 static int git_parse_maybe_bool_text(const char *value
)
1315 if (!strcasecmp(value
, "true")
1316 || !strcasecmp(value
, "yes")
1317 || !strcasecmp(value
, "on"))
1319 if (!strcasecmp(value
, "false")
1320 || !strcasecmp(value
, "no")
1321 || !strcasecmp(value
, "off"))
1326 int git_parse_maybe_bool(const char *value
)
1328 int v
= git_parse_maybe_bool_text(value
);
1331 if (git_parse_int(value
, &v
))
1336 int git_config_bool_or_int(const char *name
, const char *value
, int *is_bool
)
1338 int v
= git_parse_maybe_bool_text(value
);
1344 return git_config_int(name
, value
);
1347 int git_config_bool(const char *name
, const char *value
)
1349 int v
= git_parse_maybe_bool(value
);
1351 die(_("bad boolean config value '%s' for '%s'"), value
, name
);
1355 int git_config_string(const char **dest
, const char *var
, const char *value
)
1358 return config_error_nonbool(var
);
1359 *dest
= xstrdup(value
);
1363 int git_config_pathname(const char **dest
, const char *var
, const char *value
)
1366 return config_error_nonbool(var
);
1367 *dest
= interpolate_path(value
, 0);
1369 die(_("failed to expand user dir in: '%s'"), value
);
1373 int git_config_expiry_date(timestamp_t
*timestamp
, const char *var
, const char *value
)
1376 return config_error_nonbool(var
);
1377 if (parse_expiry_date(value
, timestamp
))
1378 return error(_("'%s' for '%s' is not a valid timestamp"),
1383 int git_config_color(char *dest
, const char *var
, const char *value
)
1386 return config_error_nonbool(var
);
1387 if (color_parse(value
, dest
) < 0)
1392 static int git_default_core_config(const char *var
, const char *value
, void *cb
)
1394 /* This needs a better name */
1395 if (!strcmp(var
, "core.filemode")) {
1396 trust_executable_bit
= git_config_bool(var
, value
);
1399 if (!strcmp(var
, "core.trustctime")) {
1400 trust_ctime
= git_config_bool(var
, value
);
1403 if (!strcmp(var
, "core.checkstat")) {
1404 if (!strcasecmp(value
, "default"))
1406 else if (!strcasecmp(value
, "minimal"))
1410 if (!strcmp(var
, "core.quotepath")) {
1411 quote_path_fully
= git_config_bool(var
, value
);
1415 if (!strcmp(var
, "core.symlinks")) {
1416 has_symlinks
= git_config_bool(var
, value
);
1420 if (!strcmp(var
, "core.ignorecase")) {
1421 ignore_case
= git_config_bool(var
, value
);
1425 if (!strcmp(var
, "core.attributesfile"))
1426 return git_config_pathname(&git_attributes_file
, var
, value
);
1428 if (!strcmp(var
, "core.hookspath"))
1429 return git_config_pathname(&git_hooks_path
, var
, value
);
1431 if (!strcmp(var
, "core.bare")) {
1432 is_bare_repository_cfg
= git_config_bool(var
, value
);
1436 if (!strcmp(var
, "core.ignorestat")) {
1437 assume_unchanged
= git_config_bool(var
, value
);
1441 if (!strcmp(var
, "core.prefersymlinkrefs")) {
1442 prefer_symlink_refs
= git_config_bool(var
, value
);
1446 if (!strcmp(var
, "core.logallrefupdates")) {
1447 if (value
&& !strcasecmp(value
, "always"))
1448 log_all_ref_updates
= LOG_REFS_ALWAYS
;
1449 else if (git_config_bool(var
, value
))
1450 log_all_ref_updates
= LOG_REFS_NORMAL
;
1452 log_all_ref_updates
= LOG_REFS_NONE
;
1456 if (!strcmp(var
, "core.warnambiguousrefs")) {
1457 warn_ambiguous_refs
= git_config_bool(var
, value
);
1461 if (!strcmp(var
, "core.abbrev")) {
1463 return config_error_nonbool(var
);
1464 if (!strcasecmp(value
, "auto"))
1465 default_abbrev
= -1;
1466 else if (!git_parse_maybe_bool_text(value
))
1467 default_abbrev
= the_hash_algo
->hexsz
;
1469 int abbrev
= git_config_int(var
, value
);
1470 if (abbrev
< minimum_abbrev
|| abbrev
> the_hash_algo
->hexsz
)
1471 return error(_("abbrev length out of range: %d"), abbrev
);
1472 default_abbrev
= abbrev
;
1477 if (!strcmp(var
, "core.disambiguate"))
1478 return set_disambiguate_hint_config(var
, value
);
1480 if (!strcmp(var
, "core.loosecompression")) {
1481 int level
= git_config_int(var
, value
);
1483 level
= Z_DEFAULT_COMPRESSION
;
1484 else if (level
< 0 || level
> Z_BEST_COMPRESSION
)
1485 die(_("bad zlib compression level %d"), level
);
1486 zlib_compression_level
= level
;
1487 zlib_compression_seen
= 1;
1491 if (!strcmp(var
, "core.compression")) {
1492 int level
= git_config_int(var
, value
);
1494 level
= Z_DEFAULT_COMPRESSION
;
1495 else if (level
< 0 || level
> Z_BEST_COMPRESSION
)
1496 die(_("bad zlib compression level %d"), level
);
1497 if (!zlib_compression_seen
)
1498 zlib_compression_level
= level
;
1499 if (!pack_compression_seen
)
1500 pack_compression_level
= level
;
1504 if (!strcmp(var
, "core.packedgitwindowsize")) {
1505 int pgsz_x2
= getpagesize() * 2;
1506 packed_git_window_size
= git_config_ulong(var
, value
);
1508 /* This value must be multiple of (pagesize * 2) */
1509 packed_git_window_size
/= pgsz_x2
;
1510 if (packed_git_window_size
< 1)
1511 packed_git_window_size
= 1;
1512 packed_git_window_size
*= pgsz_x2
;
1516 if (!strcmp(var
, "core.bigfilethreshold")) {
1517 big_file_threshold
= git_config_ulong(var
, value
);
1521 if (!strcmp(var
, "core.packedgitlimit")) {
1522 packed_git_limit
= git_config_ulong(var
, value
);
1526 if (!strcmp(var
, "core.deltabasecachelimit")) {
1527 delta_base_cache_limit
= git_config_ulong(var
, value
);
1531 if (!strcmp(var
, "core.autocrlf")) {
1532 if (value
&& !strcasecmp(value
, "input")) {
1533 auto_crlf
= AUTO_CRLF_INPUT
;
1536 auto_crlf
= git_config_bool(var
, value
);
1540 if (!strcmp(var
, "core.safecrlf")) {
1542 if (value
&& !strcasecmp(value
, "warn")) {
1543 global_conv_flags_eol
= CONV_EOL_RNDTRP_WARN
;
1546 eol_rndtrp_die
= git_config_bool(var
, value
);
1547 global_conv_flags_eol
= eol_rndtrp_die
?
1548 CONV_EOL_RNDTRP_DIE
: 0;
1552 if (!strcmp(var
, "core.eol")) {
1553 if (value
&& !strcasecmp(value
, "lf"))
1555 else if (value
&& !strcasecmp(value
, "crlf"))
1556 core_eol
= EOL_CRLF
;
1557 else if (value
&& !strcasecmp(value
, "native"))
1558 core_eol
= EOL_NATIVE
;
1560 core_eol
= EOL_UNSET
;
1564 if (!strcmp(var
, "core.checkroundtripencoding")) {
1565 check_roundtrip_encoding
= xstrdup(value
);
1569 if (!strcmp(var
, "core.notesref")) {
1570 notes_ref_name
= xstrdup(value
);
1574 if (!strcmp(var
, "core.editor"))
1575 return git_config_string(&editor_program
, var
, value
);
1577 if (!strcmp(var
, "core.commentchar")) {
1579 return config_error_nonbool(var
);
1580 else if (!strcasecmp(value
, "auto"))
1581 auto_comment_line_char
= 1;
1582 else if (value
[0] && !value
[1]) {
1583 comment_line_char
= value
[0];
1584 auto_comment_line_char
= 0;
1586 return error(_("core.commentChar should only be one character"));
1590 if (!strcmp(var
, "core.askpass"))
1591 return git_config_string(&askpass_program
, var
, value
);
1593 if (!strcmp(var
, "core.excludesfile"))
1594 return git_config_pathname(&excludes_file
, var
, value
);
1596 if (!strcmp(var
, "core.whitespace")) {
1598 return config_error_nonbool(var
);
1599 whitespace_rule_cfg
= parse_whitespace_rule(value
);
1603 if (!strcmp(var
, "core.fsyncobjectfiles")) {
1604 fsync_object_files
= git_config_bool(var
, value
);
1608 if (!strcmp(var
, "core.preloadindex")) {
1609 core_preload_index
= git_config_bool(var
, value
);
1613 if (!strcmp(var
, "core.createobject")) {
1614 if (!strcmp(value
, "rename"))
1615 object_creation_mode
= OBJECT_CREATION_USES_RENAMES
;
1616 else if (!strcmp(value
, "link"))
1617 object_creation_mode
= OBJECT_CREATION_USES_HARDLINKS
;
1619 die(_("invalid mode for object creation: %s"), value
);
1623 if (!strcmp(var
, "core.sparsecheckout")) {
1624 core_apply_sparse_checkout
= git_config_bool(var
, value
);
1628 if (!strcmp(var
, "core.sparsecheckoutcone")) {
1629 core_sparse_checkout_cone
= git_config_bool(var
, value
);
1633 if (!strcmp(var
, "core.precomposeunicode")) {
1634 precomposed_unicode
= git_config_bool(var
, value
);
1638 if (!strcmp(var
, "core.protecthfs")) {
1639 protect_hfs
= git_config_bool(var
, value
);
1643 if (!strcmp(var
, "core.protectntfs")) {
1644 protect_ntfs
= git_config_bool(var
, value
);
1648 if (!strcmp(var
, "core.usereplacerefs")) {
1649 read_replace_refs
= git_config_bool(var
, value
);
1653 /* Add other config variables here and to Documentation/config.txt. */
1654 return platform_core_config(var
, value
, cb
);
1657 static int git_default_i18n_config(const char *var
, const char *value
)
1659 if (!strcmp(var
, "i18n.commitencoding"))
1660 return git_config_string(&git_commit_encoding
, var
, value
);
1662 if (!strcmp(var
, "i18n.logoutputencoding"))
1663 return git_config_string(&git_log_output_encoding
, var
, value
);
1665 /* Add other config variables here and to Documentation/config.txt. */
1669 static int git_default_branch_config(const char *var
, const char *value
)
1671 if (!strcmp(var
, "branch.autosetupmerge")) {
1672 if (value
&& !strcmp(value
, "always")) {
1673 git_branch_track
= BRANCH_TRACK_ALWAYS
;
1675 } else if (value
&& !strcmp(value
, "inherit")) {
1676 git_branch_track
= BRANCH_TRACK_INHERIT
;
1679 git_branch_track
= git_config_bool(var
, value
);
1682 if (!strcmp(var
, "branch.autosetuprebase")) {
1684 return config_error_nonbool(var
);
1685 else if (!strcmp(value
, "never"))
1686 autorebase
= AUTOREBASE_NEVER
;
1687 else if (!strcmp(value
, "local"))
1688 autorebase
= AUTOREBASE_LOCAL
;
1689 else if (!strcmp(value
, "remote"))
1690 autorebase
= AUTOREBASE_REMOTE
;
1691 else if (!strcmp(value
, "always"))
1692 autorebase
= AUTOREBASE_ALWAYS
;
1694 return error(_("malformed value for %s"), var
);
1698 /* Add other config variables here and to Documentation/config.txt. */
1702 static int git_default_push_config(const char *var
, const char *value
)
1704 if (!strcmp(var
, "push.default")) {
1706 return config_error_nonbool(var
);
1707 else if (!strcmp(value
, "nothing"))
1708 push_default
= PUSH_DEFAULT_NOTHING
;
1709 else if (!strcmp(value
, "matching"))
1710 push_default
= PUSH_DEFAULT_MATCHING
;
1711 else if (!strcmp(value
, "simple"))
1712 push_default
= PUSH_DEFAULT_SIMPLE
;
1713 else if (!strcmp(value
, "upstream"))
1714 push_default
= PUSH_DEFAULT_UPSTREAM
;
1715 else if (!strcmp(value
, "tracking")) /* deprecated */
1716 push_default
= PUSH_DEFAULT_UPSTREAM
;
1717 else if (!strcmp(value
, "current"))
1718 push_default
= PUSH_DEFAULT_CURRENT
;
1720 error(_("malformed value for %s: %s"), var
, value
);
1721 return error(_("must be one of nothing, matching, simple, "
1722 "upstream or current"));
1727 /* Add other config variables here and to Documentation/config.txt. */
1731 static int git_default_mailmap_config(const char *var
, const char *value
)
1733 if (!strcmp(var
, "mailmap.file"))
1734 return git_config_pathname(&git_mailmap_file
, var
, value
);
1735 if (!strcmp(var
, "mailmap.blob"))
1736 return git_config_string(&git_mailmap_blob
, var
, value
);
1738 /* Add other config variables here and to Documentation/config.txt. */
1742 int git_default_config(const char *var
, const char *value
, void *cb
)
1744 if (starts_with(var
, "core."))
1745 return git_default_core_config(var
, value
, cb
);
1747 if (starts_with(var
, "user.") ||
1748 starts_with(var
, "author.") ||
1749 starts_with(var
, "committer."))
1750 return git_ident_config(var
, value
, cb
);
1752 if (starts_with(var
, "i18n."))
1753 return git_default_i18n_config(var
, value
);
1755 if (starts_with(var
, "branch."))
1756 return git_default_branch_config(var
, value
);
1758 if (starts_with(var
, "push."))
1759 return git_default_push_config(var
, value
);
1761 if (starts_with(var
, "mailmap."))
1762 return git_default_mailmap_config(var
, value
);
1764 if (starts_with(var
, "advice.") || starts_with(var
, "color.advice"))
1765 return git_default_advice_config(var
, value
);
1767 if (!strcmp(var
, "pager.color") || !strcmp(var
, "color.pager")) {
1768 pager_use_color
= git_config_bool(var
,value
);
1772 if (!strcmp(var
, "pack.packsizelimit")) {
1773 pack_size_limit_cfg
= git_config_ulong(var
, value
);
1777 if (!strcmp(var
, "pack.compression")) {
1778 int level
= git_config_int(var
, value
);
1780 level
= Z_DEFAULT_COMPRESSION
;
1781 else if (level
< 0 || level
> Z_BEST_COMPRESSION
)
1782 die(_("bad pack compression level %d"), level
);
1783 pack_compression_level
= level
;
1784 pack_compression_seen
= 1;
1788 /* Add other config variables here and to Documentation/config.txt. */
1793 * All source specific fields in the union, die_on_error, name and the callbacks
1794 * fgetc, ungetc, ftell of top need to be initialized before calling
1797 static int do_config_from(struct config_source
*top
, config_fn_t fn
, void *data
,
1798 const struct config_options
*opts
)
1802 /* push config-file parsing state stack */
1807 strbuf_init(&top
->value
, 1024);
1808 strbuf_init(&top
->var
, 1024);
1811 ret
= git_parse_source(fn
, data
, opts
);
1813 /* pop config-file parsing state stack */
1814 strbuf_release(&top
->value
);
1815 strbuf_release(&top
->var
);
1821 static int do_config_from_file(config_fn_t fn
,
1822 const enum config_origin_type origin_type
,
1823 const char *name
, const char *path
, FILE *f
,
1824 void *data
, const struct config_options
*opts
)
1826 struct config_source top
;
1830 top
.origin_type
= origin_type
;
1833 top
.default_error_action
= CONFIG_ERROR_DIE
;
1834 top
.do_fgetc
= config_file_fgetc
;
1835 top
.do_ungetc
= config_file_ungetc
;
1836 top
.do_ftell
= config_file_ftell
;
1839 ret
= do_config_from(&top
, fn
, data
, opts
);
1844 static int git_config_from_stdin(config_fn_t fn
, void *data
)
1846 return do_config_from_file(fn
, CONFIG_ORIGIN_STDIN
, "", NULL
, stdin
,
1850 int git_config_from_file_with_options(config_fn_t fn
, const char *filename
,
1852 const struct config_options
*opts
)
1857 f
= fopen_or_warn(filename
, "r");
1859 ret
= do_config_from_file(fn
, CONFIG_ORIGIN_FILE
, filename
,
1860 filename
, f
, data
, opts
);
1866 int git_config_from_file(config_fn_t fn
, const char *filename
, void *data
)
1868 return git_config_from_file_with_options(fn
, filename
, data
, NULL
);
1871 int git_config_from_mem(config_fn_t fn
,
1872 const enum config_origin_type origin_type
,
1873 const char *name
, const char *buf
, size_t len
,
1874 void *data
, const struct config_options
*opts
)
1876 struct config_source top
;
1878 top
.u
.buf
.buf
= buf
;
1879 top
.u
.buf
.len
= len
;
1881 top
.origin_type
= origin_type
;
1884 top
.default_error_action
= CONFIG_ERROR_ERROR
;
1885 top
.do_fgetc
= config_buf_fgetc
;
1886 top
.do_ungetc
= config_buf_ungetc
;
1887 top
.do_ftell
= config_buf_ftell
;
1889 return do_config_from(&top
, fn
, data
, opts
);
1892 int git_config_from_blob_oid(config_fn_t fn
,
1894 struct repository
*repo
,
1895 const struct object_id
*oid
,
1898 enum object_type type
;
1903 buf
= repo_read_object_file(repo
, oid
, &type
, &size
);
1905 return error(_("unable to load config blob object '%s'"), name
);
1906 if (type
!= OBJ_BLOB
) {
1908 return error(_("reference '%s' does not point to a blob"), name
);
1911 ret
= git_config_from_mem(fn
, CONFIG_ORIGIN_BLOB
, name
, buf
, size
,
1918 static int git_config_from_blob_ref(config_fn_t fn
,
1919 struct repository
*repo
,
1923 struct object_id oid
;
1925 if (repo_get_oid(repo
, name
, &oid
) < 0)
1926 return error(_("unable to resolve config blob '%s'"), name
);
1927 return git_config_from_blob_oid(fn
, name
, repo
, &oid
, data
);
1930 char *git_system_config(void)
1932 char *system_config
= xstrdup_or_null(getenv("GIT_CONFIG_SYSTEM"));
1934 system_config
= system_path(ETC_GITCONFIG
);
1935 normalize_path_copy(system_config
, system_config
);
1936 return system_config
;
1939 void git_global_config(char **user_out
, char **xdg_out
)
1941 char *user_config
= xstrdup_or_null(getenv("GIT_CONFIG_GLOBAL"));
1942 char *xdg_config
= NULL
;
1945 user_config
= interpolate_path("~/.gitconfig", 0);
1946 xdg_config
= xdg_config_home("config");
1949 *user_out
= user_config
;
1950 *xdg_out
= xdg_config
;
1954 * Parse environment variable 'k' as a boolean (in various
1955 * possible spellings); if missing, use the default value 'def'.
1957 int git_env_bool(const char *k
, int def
)
1959 const char *v
= getenv(k
);
1960 return v
? git_config_bool(k
, v
) : def
;
1964 * Parse environment variable 'k' as ulong with possibly a unit
1965 * suffix; if missing, use the default value 'val'.
1967 unsigned long git_env_ulong(const char *k
, unsigned long val
)
1969 const char *v
= getenv(k
);
1970 if (v
&& !git_parse_ulong(v
, &val
))
1971 die(_("failed to parse %s"), k
);
1975 int git_config_system(void)
1977 return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
1980 static int do_git_config_sequence(const struct config_options
*opts
,
1981 config_fn_t fn
, void *data
)
1984 char *system_config
= git_system_config();
1985 char *xdg_config
= NULL
;
1986 char *user_config
= NULL
;
1988 enum config_scope prev_parsing_scope
= current_parsing_scope
;
1990 if (opts
->commondir
)
1991 repo_config
= mkpathdup("%s/config", opts
->commondir
);
1992 else if (opts
->git_dir
)
1993 BUG("git_dir without commondir");
1997 current_parsing_scope
= CONFIG_SCOPE_SYSTEM
;
1998 if (git_config_system() && system_config
&&
1999 !access_or_die(system_config
, R_OK
,
2000 opts
->system_gently
? ACCESS_EACCES_OK
: 0))
2001 ret
+= git_config_from_file(fn
, system_config
, data
);
2003 current_parsing_scope
= CONFIG_SCOPE_GLOBAL
;
2004 git_global_config(&user_config
, &xdg_config
);
2006 if (xdg_config
&& !access_or_die(xdg_config
, R_OK
, ACCESS_EACCES_OK
))
2007 ret
+= git_config_from_file(fn
, xdg_config
, data
);
2009 if (user_config
&& !access_or_die(user_config
, R_OK
, ACCESS_EACCES_OK
))
2010 ret
+= git_config_from_file(fn
, user_config
, data
);
2012 current_parsing_scope
= CONFIG_SCOPE_LOCAL
;
2013 if (!opts
->ignore_repo
&& repo_config
&&
2014 !access_or_die(repo_config
, R_OK
, 0))
2015 ret
+= git_config_from_file(fn
, repo_config
, data
);
2017 current_parsing_scope
= CONFIG_SCOPE_WORKTREE
;
2018 if (!opts
->ignore_worktree
&& repository_format_worktree_config
) {
2019 char *path
= git_pathdup("config.worktree");
2020 if (!access_or_die(path
, R_OK
, 0))
2021 ret
+= git_config_from_file(fn
, path
, data
);
2025 current_parsing_scope
= CONFIG_SCOPE_COMMAND
;
2026 if (!opts
->ignore_cmdline
&& git_config_from_parameters(fn
, data
) < 0)
2027 die(_("unable to parse command-line config"));
2029 current_parsing_scope
= prev_parsing_scope
;
2030 free(system_config
);
2037 int config_with_options(config_fn_t fn
, void *data
,
2038 struct git_config_source
*config_source
,
2039 const struct config_options
*opts
)
2041 struct config_include_data inc
= CONFIG_INCLUDE_INIT
;
2044 if (opts
->respect_includes
) {
2048 inc
.config_source
= config_source
;
2049 fn
= git_config_include
;
2054 current_parsing_scope
= config_source
->scope
;
2057 * If we have a specific filename, use it. Otherwise, follow the
2058 * regular lookup sequence.
2060 if (config_source
&& config_source
->use_stdin
) {
2061 ret
= git_config_from_stdin(fn
, data
);
2062 } else if (config_source
&& config_source
->file
) {
2063 ret
= git_config_from_file(fn
, config_source
->file
, data
);
2064 } else if (config_source
&& config_source
->blob
) {
2065 struct repository
*repo
= config_source
->repo
?
2066 config_source
->repo
: the_repository
;
2067 ret
= git_config_from_blob_ref(fn
, repo
, config_source
->blob
,
2070 ret
= do_git_config_sequence(opts
, fn
, data
);
2073 if (inc
.remote_urls
) {
2074 string_list_clear(inc
.remote_urls
, 0);
2075 FREE_AND_NULL(inc
.remote_urls
);
2080 static void configset_iter(struct config_set
*cs
, config_fn_t fn
, void *data
)
2083 struct string_list
*values
;
2084 struct config_set_element
*entry
;
2085 struct configset_list
*list
= &cs
->list
;
2087 for (i
= 0; i
< list
->nr
; i
++) {
2088 entry
= list
->items
[i
].e
;
2089 value_index
= list
->items
[i
].value_index
;
2090 values
= &entry
->value_list
;
2092 current_config_kvi
= values
->items
[value_index
].util
;
2094 if (fn(entry
->key
, values
->items
[value_index
].string
, data
) < 0)
2095 git_die_config_linenr(entry
->key
,
2096 current_config_kvi
->filename
,
2097 current_config_kvi
->linenr
);
2099 current_config_kvi
= NULL
;
2103 void read_early_config(config_fn_t cb
, void *data
)
2105 struct config_options opts
= {0};
2106 struct strbuf commondir
= STRBUF_INIT
;
2107 struct strbuf gitdir
= STRBUF_INIT
;
2109 opts
.respect_includes
= 1;
2111 if (have_git_dir()) {
2112 opts
.commondir
= get_git_common_dir();
2113 opts
.git_dir
= get_git_dir();
2115 * When setup_git_directory() was not yet asked to discover the
2116 * GIT_DIR, we ask discover_git_directory() to figure out whether there
2117 * is any repository config we should use (but unlike
2118 * setup_git_directory_gently(), no global state is changed, most
2119 * notably, the current working directory is still the same after the
2122 } else if (!discover_git_directory(&commondir
, &gitdir
)) {
2123 opts
.commondir
= commondir
.buf
;
2124 opts
.git_dir
= gitdir
.buf
;
2127 config_with_options(cb
, data
, NULL
, &opts
);
2129 strbuf_release(&commondir
);
2130 strbuf_release(&gitdir
);
2134 * Read config but only enumerate system and global settings.
2135 * Omit any repo-local, worktree-local, or command-line settings.
2137 void read_very_early_config(config_fn_t cb
, void *data
)
2139 struct config_options opts
= { 0 };
2141 opts
.respect_includes
= 1;
2142 opts
.ignore_repo
= 1;
2143 opts
.ignore_worktree
= 1;
2144 opts
.ignore_cmdline
= 1;
2145 opts
.system_gently
= 1;
2147 config_with_options(cb
, data
, NULL
, &opts
);
2150 static struct config_set_element
*configset_find_element(struct config_set
*cs
, const char *key
)
2152 struct config_set_element k
;
2153 struct config_set_element
*found_entry
;
2154 char *normalized_key
;
2156 * `key` may come from the user, so normalize it before using it
2157 * for querying entries from the hashmap.
2159 if (git_config_parse_key(key
, &normalized_key
, NULL
))
2162 hashmap_entry_init(&k
.ent
, strhash(normalized_key
));
2163 k
.key
= normalized_key
;
2164 found_entry
= hashmap_get_entry(&cs
->config_hash
, &k
, ent
, NULL
);
2165 free(normalized_key
);
2169 static int configset_add_value(struct config_set
*cs
, const char *key
, const char *value
)
2171 struct config_set_element
*e
;
2172 struct string_list_item
*si
;
2173 struct configset_list_item
*l_item
;
2174 struct key_value_info
*kv_info
= xmalloc(sizeof(*kv_info
));
2176 e
= configset_find_element(cs
, key
);
2178 * Since the keys are being fed by git_config*() callback mechanism, they
2179 * are already normalized. So simply add them without any further munging.
2182 e
= xmalloc(sizeof(*e
));
2183 hashmap_entry_init(&e
->ent
, strhash(key
));
2184 e
->key
= xstrdup(key
);
2185 string_list_init_dup(&e
->value_list
);
2186 hashmap_add(&cs
->config_hash
, &e
->ent
);
2188 si
= string_list_append_nodup(&e
->value_list
, xstrdup_or_null(value
));
2190 ALLOC_GROW(cs
->list
.items
, cs
->list
.nr
+ 1, cs
->list
.alloc
);
2191 l_item
= &cs
->list
.items
[cs
->list
.nr
++];
2193 l_item
->value_index
= e
->value_list
.nr
- 1;
2196 BUG("configset_add_value has no source");
2198 kv_info
->filename
= strintern(cf
->name
);
2199 kv_info
->linenr
= cf
->linenr
;
2200 kv_info
->origin_type
= cf
->origin_type
;
2202 /* for values read from `git_config_from_parameters()` */
2203 kv_info
->filename
= NULL
;
2204 kv_info
->linenr
= -1;
2205 kv_info
->origin_type
= CONFIG_ORIGIN_CMDLINE
;
2207 kv_info
->scope
= current_parsing_scope
;
2213 static int config_set_element_cmp(const void *unused_cmp_data
,
2214 const struct hashmap_entry
*eptr
,
2215 const struct hashmap_entry
*entry_or_key
,
2216 const void *unused_keydata
)
2218 const struct config_set_element
*e1
, *e2
;
2220 e1
= container_of(eptr
, const struct config_set_element
, ent
);
2221 e2
= container_of(entry_or_key
, const struct config_set_element
, ent
);
2223 return strcmp(e1
->key
, e2
->key
);
2226 void git_configset_init(struct config_set
*cs
)
2228 hashmap_init(&cs
->config_hash
, config_set_element_cmp
, NULL
, 0);
2229 cs
->hash_initialized
= 1;
2232 cs
->list
.items
= NULL
;
2235 void git_configset_clear(struct config_set
*cs
)
2237 struct config_set_element
*entry
;
2238 struct hashmap_iter iter
;
2239 if (!cs
->hash_initialized
)
2242 hashmap_for_each_entry(&cs
->config_hash
, &iter
, entry
,
2243 ent
/* member name */) {
2245 string_list_clear(&entry
->value_list
, 1);
2247 hashmap_clear_and_free(&cs
->config_hash
, struct config_set_element
, ent
);
2248 cs
->hash_initialized
= 0;
2249 free(cs
->list
.items
);
2252 cs
->list
.items
= NULL
;
2255 static int config_set_callback(const char *key
, const char *value
, void *cb
)
2257 struct config_set
*cs
= cb
;
2258 configset_add_value(cs
, key
, value
);
2262 int git_configset_add_file(struct config_set
*cs
, const char *filename
)
2264 return git_config_from_file(config_set_callback
, filename
, cs
);
2267 int git_configset_get_value(struct config_set
*cs
, const char *key
, const char **value
)
2269 const struct string_list
*values
= NULL
;
2271 * Follows "last one wins" semantic, i.e., if there are multiple matches for the
2272 * queried key in the files of the configset, the value returned will be the last
2273 * value in the value list for that key.
2275 values
= git_configset_get_value_multi(cs
, key
);
2279 assert(values
->nr
> 0);
2280 *value
= values
->items
[values
->nr
- 1].string
;
2284 const struct string_list
*git_configset_get_value_multi(struct config_set
*cs
, const char *key
)
2286 struct config_set_element
*e
= configset_find_element(cs
, key
);
2287 return e
? &e
->value_list
: NULL
;
2290 int git_configset_get_string(struct config_set
*cs
, const char *key
, char **dest
)
2293 if (!git_configset_get_value(cs
, key
, &value
))
2294 return git_config_string((const char **)dest
, key
, value
);
2299 static int git_configset_get_string_tmp(struct config_set
*cs
, const char *key
,
2303 if (!git_configset_get_value(cs
, key
, &value
)) {
2305 return config_error_nonbool(key
);
2313 int git_configset_get_int(struct config_set
*cs
, const char *key
, int *dest
)
2316 if (!git_configset_get_value(cs
, key
, &value
)) {
2317 *dest
= git_config_int(key
, value
);
2323 int git_configset_get_ulong(struct config_set
*cs
, const char *key
, unsigned long *dest
)
2326 if (!git_configset_get_value(cs
, key
, &value
)) {
2327 *dest
= git_config_ulong(key
, value
);
2333 int git_configset_get_bool(struct config_set
*cs
, const char *key
, int *dest
)
2336 if (!git_configset_get_value(cs
, key
, &value
)) {
2337 *dest
= git_config_bool(key
, value
);
2343 int git_configset_get_bool_or_int(struct config_set
*cs
, const char *key
,
2344 int *is_bool
, int *dest
)
2347 if (!git_configset_get_value(cs
, key
, &value
)) {
2348 *dest
= git_config_bool_or_int(key
, value
, is_bool
);
2354 int git_configset_get_maybe_bool(struct config_set
*cs
, const char *key
, int *dest
)
2357 if (!git_configset_get_value(cs
, key
, &value
)) {
2358 *dest
= git_parse_maybe_bool(value
);
2366 int git_configset_get_pathname(struct config_set
*cs
, const char *key
, const char **dest
)
2369 if (!git_configset_get_value(cs
, key
, &value
))
2370 return git_config_pathname(dest
, key
, value
);
2375 /* Functions use to read configuration from a repository */
2376 static void repo_read_config(struct repository
*repo
)
2378 struct config_options opts
= { 0 };
2380 opts
.respect_includes
= 1;
2381 opts
.commondir
= repo
->commondir
;
2382 opts
.git_dir
= repo
->gitdir
;
2385 CALLOC_ARRAY(repo
->config
, 1);
2387 git_configset_clear(repo
->config
);
2389 git_configset_init(repo
->config
);
2391 if (config_with_options(config_set_callback
, repo
->config
, NULL
, &opts
) < 0)
2393 * config_with_options() normally returns only
2394 * zero, as most errors are fatal, and
2395 * non-fatal potential errors are guarded by "if"
2396 * statements that are entered only when no error is
2399 * If we ever encounter a non-fatal error, it means
2400 * something went really wrong and we should stop
2403 die(_("unknown error occurred while reading the configuration files"));
2406 static void git_config_check_init(struct repository
*repo
)
2408 if (repo
->config
&& repo
->config
->hash_initialized
)
2410 repo_read_config(repo
);
2413 static void repo_config_clear(struct repository
*repo
)
2415 if (!repo
->config
|| !repo
->config
->hash_initialized
)
2417 git_configset_clear(repo
->config
);
2420 void repo_config(struct repository
*repo
, config_fn_t fn
, void *data
)
2422 git_config_check_init(repo
);
2423 configset_iter(repo
->config
, fn
, data
);
2426 int repo_config_get_value(struct repository
*repo
,
2427 const char *key
, const char **value
)
2429 git_config_check_init(repo
);
2430 return git_configset_get_value(repo
->config
, key
, value
);
2433 const struct string_list
*repo_config_get_value_multi(struct repository
*repo
,
2436 git_config_check_init(repo
);
2437 return git_configset_get_value_multi(repo
->config
, key
);
2440 int repo_config_get_string(struct repository
*repo
,
2441 const char *key
, char **dest
)
2444 git_config_check_init(repo
);
2445 ret
= git_configset_get_string(repo
->config
, key
, dest
);
2447 git_die_config(key
, NULL
);
2451 int repo_config_get_string_tmp(struct repository
*repo
,
2452 const char *key
, const char **dest
)
2455 git_config_check_init(repo
);
2456 ret
= git_configset_get_string_tmp(repo
->config
, key
, dest
);
2458 git_die_config(key
, NULL
);
2462 int repo_config_get_int(struct repository
*repo
,
2463 const char *key
, int *dest
)
2465 git_config_check_init(repo
);
2466 return git_configset_get_int(repo
->config
, key
, dest
);
2469 int repo_config_get_ulong(struct repository
*repo
,
2470 const char *key
, unsigned long *dest
)
2472 git_config_check_init(repo
);
2473 return git_configset_get_ulong(repo
->config
, key
, dest
);
2476 int repo_config_get_bool(struct repository
*repo
,
2477 const char *key
, int *dest
)
2479 git_config_check_init(repo
);
2480 return git_configset_get_bool(repo
->config
, key
, dest
);
2483 int repo_config_get_bool_or_int(struct repository
*repo
,
2484 const char *key
, int *is_bool
, int *dest
)
2486 git_config_check_init(repo
);
2487 return git_configset_get_bool_or_int(repo
->config
, key
, is_bool
, dest
);
2490 int repo_config_get_maybe_bool(struct repository
*repo
,
2491 const char *key
, int *dest
)
2493 git_config_check_init(repo
);
2494 return git_configset_get_maybe_bool(repo
->config
, key
, dest
);
2497 int repo_config_get_pathname(struct repository
*repo
,
2498 const char *key
, const char **dest
)
2501 git_config_check_init(repo
);
2502 ret
= git_configset_get_pathname(repo
->config
, key
, dest
);
2504 git_die_config(key
, NULL
);
2508 /* Functions used historically to read configuration from 'the_repository' */
2509 void git_config(config_fn_t fn
, void *data
)
2511 repo_config(the_repository
, fn
, data
);
2514 void git_config_clear(void)
2516 repo_config_clear(the_repository
);
2519 int git_config_get_value(const char *key
, const char **value
)
2521 return repo_config_get_value(the_repository
, key
, value
);
2524 const struct string_list
*git_config_get_value_multi(const char *key
)
2526 return repo_config_get_value_multi(the_repository
, key
);
2529 int git_config_get_string(const char *key
, char **dest
)
2531 return repo_config_get_string(the_repository
, key
, dest
);
2534 int git_config_get_string_tmp(const char *key
, const char **dest
)
2536 return repo_config_get_string_tmp(the_repository
, key
, dest
);
2539 int git_config_get_int(const char *key
, int *dest
)
2541 return repo_config_get_int(the_repository
, key
, dest
);
2544 int git_config_get_ulong(const char *key
, unsigned long *dest
)
2546 return repo_config_get_ulong(the_repository
, key
, dest
);
2549 int git_config_get_bool(const char *key
, int *dest
)
2551 return repo_config_get_bool(the_repository
, key
, dest
);
2554 int git_config_get_bool_or_int(const char *key
, int *is_bool
, int *dest
)
2556 return repo_config_get_bool_or_int(the_repository
, key
, is_bool
, dest
);
2559 int git_config_get_maybe_bool(const char *key
, int *dest
)
2561 return repo_config_get_maybe_bool(the_repository
, key
, dest
);
2564 int git_config_get_pathname(const char *key
, const char **dest
)
2566 return repo_config_get_pathname(the_repository
, key
, dest
);
2569 int git_config_get_expiry(const char *key
, const char **output
)
2571 int ret
= git_config_get_string(key
, (char **)output
);
2574 if (strcmp(*output
, "now")) {
2575 timestamp_t now
= approxidate("now");
2576 if (approxidate(*output
) >= now
)
2577 git_die_config(key
, _("Invalid %s: '%s'"), key
, *output
);
2582 int git_config_get_expiry_in_days(const char *key
, timestamp_t
*expiry
, timestamp_t now
)
2584 const char *expiry_string
;
2588 if (git_config_get_string_tmp(key
, &expiry_string
))
2589 return 1; /* no such thing */
2591 if (git_parse_signed(expiry_string
, &days
, maximum_signed_value_of_type(int))) {
2592 const int scale
= 86400;
2593 *expiry
= now
- days
* scale
;
2597 if (!parse_expiry_date(expiry_string
, &when
)) {
2601 return -1; /* thing exists but cannot be parsed */
2604 int git_config_get_split_index(void)
2608 if (!git_config_get_maybe_bool("core.splitindex", &val
))
2611 return -1; /* default value */
2614 int git_config_get_max_percent_split_change(void)
2618 if (!git_config_get_int("splitindex.maxpercentchange", &val
)) {
2619 if (0 <= val
&& val
<= 100)
2622 return error(_("splitIndex.maxPercentChange value '%d' "
2623 "should be between 0 and 100"), val
);
2626 return -1; /* default value */
2629 int git_config_get_index_threads(int *dest
)
2633 val
= git_env_ulong("GIT_TEST_INDEX_THREADS", 0);
2639 if (!git_config_get_bool_or_int("index.threads", &is_bool
, &val
)) {
2641 *dest
= val
? 0 : 1;
2651 void git_die_config_linenr(const char *key
, const char *filename
, int linenr
)
2654 die(_("unable to parse '%s' from command-line config"), key
);
2656 die(_("bad config variable '%s' in file '%s' at line %d"),
2657 key
, filename
, linenr
);
2660 NORETURN
__attribute__((format(printf
, 2, 3)))
2661 void git_die_config(const char *key
, const char *err
, ...)
2663 const struct string_list
*values
;
2664 struct key_value_info
*kv_info
;
2665 report_fn error_fn
= get_error_routine();
2669 va_start(params
, err
);
2670 error_fn(err
, params
);
2673 values
= git_config_get_value_multi(key
);
2674 kv_info
= values
->items
[values
->nr
- 1].util
;
2675 git_die_config_linenr(key
, kv_info
->filename
, kv_info
->linenr
);
2679 * Find all the stuff for git_config_set() below.
2682 struct config_store_data
{
2686 const char *fixed_value
;
2687 regex_t
*value_pattern
;
2691 enum config_event_t type
;
2692 int is_keys_section
;
2694 unsigned int parsed_nr
, parsed_alloc
, *seen
, seen_nr
, seen_alloc
;
2695 unsigned int key_seen
:1, section_seen
:1, is_keys_section
:1;
2698 static void config_store_data_clear(struct config_store_data
*store
)
2701 if (store
->value_pattern
!= NULL
&&
2702 store
->value_pattern
!= CONFIG_REGEX_NONE
) {
2703 regfree(store
->value_pattern
);
2704 free(store
->value_pattern
);
2706 free(store
->parsed
);
2708 memset(store
, 0, sizeof(*store
));
2711 static int matches(const char *key
, const char *value
,
2712 const struct config_store_data
*store
)
2714 if (strcmp(key
, store
->key
))
2715 return 0; /* not ours */
2716 if (store
->fixed_value
)
2717 return !strcmp(store
->fixed_value
, value
);
2718 if (!store
->value_pattern
)
2719 return 1; /* always matches */
2720 if (store
->value_pattern
== CONFIG_REGEX_NONE
)
2721 return 0; /* never matches */
2723 return store
->do_not_match
^
2724 (value
&& !regexec(store
->value_pattern
, value
, 0, NULL
, 0));
2727 static int store_aux_event(enum config_event_t type
,
2728 size_t begin
, size_t end
, void *data
)
2730 struct config_store_data
*store
= data
;
2732 ALLOC_GROW(store
->parsed
, store
->parsed_nr
+ 1, store
->parsed_alloc
);
2733 store
->parsed
[store
->parsed_nr
].begin
= begin
;
2734 store
->parsed
[store
->parsed_nr
].end
= end
;
2735 store
->parsed
[store
->parsed_nr
].type
= type
;
2737 if (type
== CONFIG_EVENT_SECTION
) {
2738 int (*cmpfn
)(const char *, const char *, size_t);
2740 if (cf
->var
.len
< 2 || cf
->var
.buf
[cf
->var
.len
- 1] != '.')
2741 return error(_("invalid section name '%s'"), cf
->var
.buf
);
2743 if (cf
->subsection_case_sensitive
)
2744 cmpfn
= strncasecmp
;
2748 /* Is this the section we were looking for? */
2749 store
->is_keys_section
=
2750 store
->parsed
[store
->parsed_nr
].is_keys_section
=
2751 cf
->var
.len
- 1 == store
->baselen
&&
2752 !cmpfn(cf
->var
.buf
, store
->key
, store
->baselen
);
2753 if (store
->is_keys_section
) {
2754 store
->section_seen
= 1;
2755 ALLOC_GROW(store
->seen
, store
->seen_nr
+ 1,
2757 store
->seen
[store
->seen_nr
] = store
->parsed_nr
;
2766 static int store_aux(const char *key
, const char *value
, void *cb
)
2768 struct config_store_data
*store
= cb
;
2770 if (store
->key_seen
) {
2771 if (matches(key
, value
, store
)) {
2772 if (store
->seen_nr
== 1 && store
->multi_replace
== 0) {
2773 warning(_("%s has multiple values"), key
);
2776 ALLOC_GROW(store
->seen
, store
->seen_nr
+ 1,
2779 store
->seen
[store
->seen_nr
] = store
->parsed_nr
;
2782 } else if (store
->is_keys_section
) {
2784 * Do not increment matches yet: this may not be a match, but we
2785 * are in the desired section.
2787 ALLOC_GROW(store
->seen
, store
->seen_nr
+ 1, store
->seen_alloc
);
2788 store
->seen
[store
->seen_nr
] = store
->parsed_nr
;
2789 store
->section_seen
= 1;
2791 if (matches(key
, value
, store
)) {
2793 store
->key_seen
= 1;
2800 static int write_error(const char *filename
)
2802 error(_("failed to write new configuration file %s"), filename
);
2804 /* Same error code as "failed to rename". */
2808 static struct strbuf
store_create_section(const char *key
,
2809 const struct config_store_data
*store
)
2813 struct strbuf sb
= STRBUF_INIT
;
2815 dot
= memchr(key
, '.', store
->baselen
);
2817 strbuf_addf(&sb
, "[%.*s \"", (int)(dot
- key
), key
);
2818 for (i
= dot
- key
+ 1; i
< store
->baselen
; i
++) {
2819 if (key
[i
] == '"' || key
[i
] == '\\')
2820 strbuf_addch(&sb
, '\\');
2821 strbuf_addch(&sb
, key
[i
]);
2823 strbuf_addstr(&sb
, "\"]\n");
2825 strbuf_addch(&sb
, '[');
2826 strbuf_add(&sb
, key
, store
->baselen
);
2827 strbuf_addstr(&sb
, "]\n");
2833 static ssize_t
write_section(int fd
, const char *key
,
2834 const struct config_store_data
*store
)
2836 struct strbuf sb
= store_create_section(key
, store
);
2839 ret
= write_in_full(fd
, sb
.buf
, sb
.len
);
2840 strbuf_release(&sb
);
2845 static ssize_t
write_pair(int fd
, const char *key
, const char *value
,
2846 const struct config_store_data
*store
)
2850 const char *quote
= "";
2851 struct strbuf sb
= STRBUF_INIT
;
2854 * Check to see if the value needs to be surrounded with a dq pair.
2855 * Note that problematic characters are always backslash-quoted; this
2856 * check is about not losing leading or trailing SP and strings that
2857 * follow beginning-of-comment characters (i.e. ';' and '#') by the
2858 * configuration parser.
2860 if (value
[0] == ' ')
2862 for (i
= 0; value
[i
]; i
++)
2863 if (value
[i
] == ';' || value
[i
] == '#')
2865 if (i
&& value
[i
- 1] == ' ')
2868 strbuf_addf(&sb
, "\t%s = %s", key
+ store
->baselen
+ 1, quote
);
2870 for (i
= 0; value
[i
]; i
++)
2873 strbuf_addstr(&sb
, "\\n");
2876 strbuf_addstr(&sb
, "\\t");
2880 strbuf_addch(&sb
, '\\');
2883 strbuf_addch(&sb
, value
[i
]);
2886 strbuf_addf(&sb
, "%s\n", quote
);
2888 ret
= write_in_full(fd
, sb
.buf
, sb
.len
);
2889 strbuf_release(&sb
);
2895 * If we are about to unset the last key(s) in a section, and if there are
2896 * no comments surrounding (or included in) the section, we will want to
2897 * extend begin/end to remove the entire section.
2899 * Note: the parameter `seen_ptr` points to the index into the store.seen
2900 * array. * This index may be incremented if a section has more than one
2901 * entry (which all are to be removed).
2903 static void maybe_remove_section(struct config_store_data
*store
,
2904 size_t *begin_offset
, size_t *end_offset
,
2908 int i
, seen
, section_seen
= 0;
2911 * First, ensure that this is the first key, and that there are no
2912 * comments before the entry nor before the section header.
2915 for (i
= store
->seen
[seen
]; i
> 0; i
--) {
2916 enum config_event_t type
= store
->parsed
[i
- 1].type
;
2918 if (type
== CONFIG_EVENT_COMMENT
)
2919 /* There is a comment before this entry or section */
2921 if (type
== CONFIG_EVENT_ENTRY
) {
2923 /* This is not the section's first entry. */
2925 /* We encountered no comment before the section. */
2928 if (type
== CONFIG_EVENT_SECTION
) {
2929 if (!store
->parsed
[i
- 1].is_keys_section
)
2934 begin
= store
->parsed
[i
].begin
;
2937 * Next, make sure that we are removing the last key(s) in the section,
2938 * and that there are no comments that are possibly about the current
2941 for (i
= store
->seen
[seen
] + 1; i
< store
->parsed_nr
; i
++) {
2942 enum config_event_t type
= store
->parsed
[i
].type
;
2944 if (type
== CONFIG_EVENT_COMMENT
)
2946 if (type
== CONFIG_EVENT_SECTION
) {
2947 if (store
->parsed
[i
].is_keys_section
)
2951 if (type
== CONFIG_EVENT_ENTRY
) {
2952 if (++seen
< store
->seen_nr
&&
2953 i
== store
->seen
[seen
])
2954 /* We want to remove this entry, too */
2956 /* There is another entry in this section. */
2962 * We are really removing the last entry/entries from this section, and
2963 * there are no enclosed or surrounding comments. Remove the entire,
2964 * now-empty section.
2967 *begin_offset
= begin
;
2968 if (i
< store
->parsed_nr
)
2969 *end_offset
= store
->parsed
[i
].begin
;
2971 *end_offset
= store
->parsed
[store
->parsed_nr
- 1].end
;
2974 int git_config_set_in_file_gently(const char *config_filename
,
2975 const char *key
, const char *value
)
2977 return git_config_set_multivar_in_file_gently(config_filename
, key
, value
, NULL
, 0);
2980 void git_config_set_in_file(const char *config_filename
,
2981 const char *key
, const char *value
)
2983 git_config_set_multivar_in_file(config_filename
, key
, value
, NULL
, 0);
2986 int git_config_set_gently(const char *key
, const char *value
)
2988 return git_config_set_multivar_gently(key
, value
, NULL
, 0);
2991 int repo_config_set_worktree_gently(struct repository
*r
,
2992 const char *key
, const char *value
)
2994 /* Only use worktree-specific config if it is is already enabled. */
2995 if (repository_format_worktree_config
) {
2996 char *file
= repo_git_path(r
, "config.worktree");
2997 int ret
= git_config_set_multivar_in_file_gently(
2998 file
, key
, value
, NULL
, 0);
3002 return repo_config_set_multivar_gently(r
, key
, value
, NULL
, 0);
3005 void git_config_set(const char *key
, const char *value
)
3007 git_config_set_multivar(key
, value
, NULL
, 0);
3009 trace2_cmd_set_config(key
, value
);
3013 * If value==NULL, unset in (remove from) config,
3014 * if value_pattern!=NULL, disregard key/value pairs where value does not match.
3015 * if value_pattern==CONFIG_REGEX_NONE, do not match any existing values
3016 * (only add a new one)
3017 * if flags contains the CONFIG_FLAGS_MULTI_REPLACE flag, all matching
3018 * key/values are removed before a single new pair is written. If the
3019 * flag is not present, then replace only the first match.
3021 * Returns 0 on success.
3023 * This function does this:
3025 * - it locks the config file by creating ".git/config.lock"
3027 * - it then parses the config using store_aux() as validator to find
3028 * the position on the key/value pair to replace. If it is to be unset,
3029 * it must be found exactly once.
3031 * - the config file is mmap()ed and the part before the match (if any) is
3032 * written to the lock file, then the changed part and the rest.
3034 * - the config file is removed and the lock file rename()d to it.
3037 int git_config_set_multivar_in_file_gently(const char *config_filename
,
3038 const char *key
, const char *value
,
3039 const char *value_pattern
,
3042 int fd
= -1, in_fd
= -1;
3044 struct lock_file lock
= LOCK_INIT
;
3045 char *filename_buf
= NULL
;
3046 char *contents
= NULL
;
3048 struct config_store_data store
;
3050 memset(&store
, 0, sizeof(store
));
3052 /* parse-key returns negative; flip the sign to feed exit(3) */
3053 ret
= 0 - git_config_parse_key(key
, &store
.key
, &store
.baselen
);
3057 store
.multi_replace
= (flags
& CONFIG_FLAGS_MULTI_REPLACE
) != 0;
3059 if (!config_filename
)
3060 config_filename
= filename_buf
= git_pathdup("config");
3063 * The lock serves a purpose in addition to locking: the new
3064 * contents of .git/config will be written into it.
3066 fd
= hold_lock_file_for_update(&lock
, config_filename
, 0);
3068 error_errno(_("could not lock config file %s"), config_filename
);
3069 ret
= CONFIG_NO_LOCK
;
3074 * If .git/config does not exist yet, write a minimal version.
3076 in_fd
= open(config_filename
, O_RDONLY
);
3078 if ( ENOENT
!= errno
) {
3079 error_errno(_("opening %s"), config_filename
);
3080 ret
= CONFIG_INVALID_FILE
; /* same as "invalid config file" */
3083 /* if nothing to unset, error out */
3084 if (value
== NULL
) {
3085 ret
= CONFIG_NOTHING_SET
;
3090 store
.key
= xstrdup(key
);
3091 if (write_section(fd
, key
, &store
) < 0 ||
3092 write_pair(fd
, key
, value
, &store
) < 0)
3096 size_t copy_begin
, copy_end
;
3097 int i
, new_line
= 0;
3098 struct config_options opts
;
3100 if (value_pattern
== NULL
)
3101 store
.value_pattern
= NULL
;
3102 else if (value_pattern
== CONFIG_REGEX_NONE
)
3103 store
.value_pattern
= CONFIG_REGEX_NONE
;
3104 else if (flags
& CONFIG_FLAGS_FIXED_VALUE
)
3105 store
.fixed_value
= value_pattern
;
3107 if (value_pattern
[0] == '!') {
3108 store
.do_not_match
= 1;
3111 store
.do_not_match
= 0;
3113 store
.value_pattern
= (regex_t
*)xmalloc(sizeof(regex_t
));
3114 if (regcomp(store
.value_pattern
, value_pattern
,
3116 error(_("invalid pattern: %s"), value_pattern
);
3117 FREE_AND_NULL(store
.value_pattern
);
3118 ret
= CONFIG_INVALID_PATTERN
;
3123 ALLOC_GROW(store
.parsed
, 1, store
.parsed_alloc
);
3124 store
.parsed
[0].end
= 0;
3126 memset(&opts
, 0, sizeof(opts
));
3127 opts
.event_fn
= store_aux_event
;
3128 opts
.event_fn_data
= &store
;
3131 * After this, store.parsed will contain offsets of all the
3132 * parsed elements, and store.seen will contain a list of
3133 * matches, as indices into store.parsed.
3135 * As a side effect, we make sure to transform only a valid
3136 * existing config file.
3138 if (git_config_from_file_with_options(store_aux
,
3141 error(_("invalid config file %s"), config_filename
);
3142 ret
= CONFIG_INVALID_FILE
;
3146 /* if nothing to unset, or too many matches, error out */
3147 if ((store
.seen_nr
== 0 && value
== NULL
) ||
3148 (store
.seen_nr
> 1 && !store
.multi_replace
)) {
3149 ret
= CONFIG_NOTHING_SET
;
3153 if (fstat(in_fd
, &st
) == -1) {
3154 error_errno(_("fstat on %s failed"), config_filename
);
3155 ret
= CONFIG_INVALID_FILE
;
3159 contents_sz
= xsize_t(st
.st_size
);
3160 contents
= xmmap_gently(NULL
, contents_sz
, PROT_READ
,
3161 MAP_PRIVATE
, in_fd
, 0);
3162 if (contents
== MAP_FAILED
) {
3163 if (errno
== ENODEV
&& S_ISDIR(st
.st_mode
))
3165 error_errno(_("unable to mmap '%s'%s"),
3166 config_filename
, mmap_os_err());
3167 ret
= CONFIG_INVALID_FILE
;
3174 if (chmod(get_lock_file_path(&lock
), st
.st_mode
& 07777) < 0) {
3175 error_errno(_("chmod on %s failed"), get_lock_file_path(&lock
));
3176 ret
= CONFIG_NO_WRITE
;
3180 if (store
.seen_nr
== 0) {
3181 if (!store
.seen_alloc
) {
3182 /* Did not see key nor section */
3183 ALLOC_GROW(store
.seen
, 1, store
.seen_alloc
);
3184 store
.seen
[0] = store
.parsed_nr
3185 - !!store
.parsed_nr
;
3190 for (i
= 0, copy_begin
= 0; i
< store
.seen_nr
; i
++) {
3192 int j
= store
.seen
[i
];
3195 if (!store
.key_seen
) {
3196 copy_end
= store
.parsed
[j
].end
;
3197 /* include '\n' when copying section header */
3198 if (copy_end
> 0 && copy_end
< contents_sz
&&
3199 contents
[copy_end
- 1] != '\n' &&
3200 contents
[copy_end
] == '\n')
3202 replace_end
= copy_end
;
3204 replace_end
= store
.parsed
[j
].end
;
3205 copy_end
= store
.parsed
[j
].begin
;
3207 maybe_remove_section(&store
,
3211 * Swallow preceding white-space on the same
3214 while (copy_end
> 0 ) {
3215 char c
= contents
[copy_end
- 1];
3217 if (isspace(c
) && c
!= '\n')
3224 if (copy_end
> 0 && contents
[copy_end
-1] != '\n')
3227 /* write the first part of the config */
3228 if (copy_end
> copy_begin
) {
3229 if (write_in_full(fd
, contents
+ copy_begin
,
3230 copy_end
- copy_begin
) < 0)
3233 write_str_in_full(fd
, "\n") < 0)
3236 copy_begin
= replace_end
;
3239 /* write the pair (value == NULL means unset) */
3240 if (value
!= NULL
) {
3241 if (!store
.section_seen
) {
3242 if (write_section(fd
, key
, &store
) < 0)
3245 if (write_pair(fd
, key
, value
, &store
) < 0)
3249 /* write the rest of the config */
3250 if (copy_begin
< contents_sz
)
3251 if (write_in_full(fd
, contents
+ copy_begin
,
3252 contents_sz
- copy_begin
) < 0)
3255 munmap(contents
, contents_sz
);
3259 if (commit_lock_file(&lock
) < 0) {
3260 error_errno(_("could not write config file %s"), config_filename
);
3261 ret
= CONFIG_NO_WRITE
;
3267 /* Invalidate the config cache */
3271 rollback_lock_file(&lock
);
3274 munmap(contents
, contents_sz
);
3277 config_store_data_clear(&store
);
3281 ret
= write_error(get_lock_file_path(&lock
));
3286 void git_config_set_multivar_in_file(const char *config_filename
,
3287 const char *key
, const char *value
,
3288 const char *value_pattern
, unsigned flags
)
3290 if (!git_config_set_multivar_in_file_gently(config_filename
, key
, value
,
3291 value_pattern
, flags
))
3294 die(_("could not set '%s' to '%s'"), key
, value
);
3296 die(_("could not unset '%s'"), key
);
3299 int git_config_set_multivar_gently(const char *key
, const char *value
,
3300 const char *value_pattern
, unsigned flags
)
3302 return repo_config_set_multivar_gently(the_repository
, key
, value
,
3303 value_pattern
, flags
);
3306 int repo_config_set_multivar_gently(struct repository
*r
, const char *key
,
3308 const char *value_pattern
, unsigned flags
)
3310 char *file
= repo_git_path(r
, "config");
3311 int res
= git_config_set_multivar_in_file_gently(file
,
3319 void git_config_set_multivar(const char *key
, const char *value
,
3320 const char *value_pattern
, unsigned flags
)
3322 git_config_set_multivar_in_file(git_path("config"),
3323 key
, value
, value_pattern
,
3327 static int section_name_match (const char *buf
, const char *name
)
3329 int i
= 0, j
= 0, dot
= 0;
3332 for (i
= 1; buf
[i
] && buf
[i
] != ']'; i
++) {
3333 if (!dot
&& isspace(buf
[i
])) {
3335 if (name
[j
++] != '.')
3337 for (i
++; isspace(buf
[i
]); i
++)
3343 if (buf
[i
] == '\\' && dot
)
3345 else if (buf
[i
] == '"' && dot
) {
3346 for (i
++; isspace(buf
[i
]); i
++)
3350 if (buf
[i
] != name
[j
++])
3353 if (buf
[i
] == ']' && name
[j
] == 0) {
3355 * We match, now just find the right length offset by
3356 * gobbling up any whitespace after it, as well
3359 for (; buf
[i
] && isspace(buf
[i
]); i
++)
3366 static int section_name_is_ok(const char *name
)
3368 /* Empty section names are bogus. */
3373 * Before a dot, we must be alphanumeric or dash. After the first dot,
3374 * anything goes, so we can stop checking.
3376 for (; *name
&& *name
!= '.'; name
++)
3377 if (*name
!= '-' && !isalnum(*name
))
3382 /* if new_name == NULL, the section is removed instead */
3383 static int git_config_copy_or_rename_section_in_file(const char *config_filename
,
3384 const char *old_name
,
3385 const char *new_name
, int copy
)
3387 int ret
= 0, remove
= 0;
3388 char *filename_buf
= NULL
;
3389 struct lock_file lock
= LOCK_INIT
;
3392 FILE *config_file
= NULL
;
3394 struct strbuf copystr
= STRBUF_INIT
;
3395 struct config_store_data store
;
3397 memset(&store
, 0, sizeof(store
));
3399 if (new_name
&& !section_name_is_ok(new_name
)) {
3400 ret
= error(_("invalid section name: %s"), new_name
);
3401 goto out_no_rollback
;
3404 if (!config_filename
)
3405 config_filename
= filename_buf
= git_pathdup("config");
3407 out_fd
= hold_lock_file_for_update(&lock
, config_filename
, 0);
3409 ret
= error(_("could not lock config file %s"), config_filename
);
3413 if (!(config_file
= fopen(config_filename
, "rb"))) {
3414 ret
= warn_on_fopen_errors(config_filename
);
3417 /* no config file means nothing to rename, no error */
3418 goto commit_and_out
;
3421 if (fstat(fileno(config_file
), &st
) == -1) {
3422 ret
= error_errno(_("fstat on %s failed"), config_filename
);
3426 if (chmod(get_lock_file_path(&lock
), st
.st_mode
& 07777) < 0) {
3427 ret
= error_errno(_("chmod on %s failed"),
3428 get_lock_file_path(&lock
));
3432 while (fgets(buf
, sizeof(buf
), config_file
)) {
3437 for (i
= 0; buf
[i
] && isspace(buf
[i
]); i
++)
3439 if (buf
[i
] == '[') {
3440 /* it's a section */
3445 * When encountering a new section under -c we
3446 * need to flush out any section we're already
3447 * coping and begin anew. There might be
3448 * multiple [branch "$name"] sections.
3450 if (copystr
.len
> 0) {
3451 if (write_in_full(out_fd
, copystr
.buf
, copystr
.len
) < 0) {
3452 ret
= write_error(get_lock_file_path(&lock
));
3455 strbuf_reset(©str
);
3458 offset
= section_name_match(&buf
[i
], old_name
);
3461 if (new_name
== NULL
) {
3465 store
.baselen
= strlen(new_name
);
3467 if (write_section(out_fd
, new_name
, &store
) < 0) {
3468 ret
= write_error(get_lock_file_path(&lock
));
3472 * We wrote out the new section, with
3473 * a newline, now skip the old
3476 output
+= offset
+ i
;
3477 if (strlen(output
) > 0) {
3479 * More content means there's
3480 * a declaration to put on the
3481 * next line; indent with a
3488 copystr
= store_create_section(new_name
, &store
);
3495 length
= strlen(output
);
3497 if (!is_section
&& copystr
.len
> 0) {
3498 strbuf_add(©str
, output
, length
);
3501 if (write_in_full(out_fd
, output
, length
) < 0) {
3502 ret
= write_error(get_lock_file_path(&lock
));
3508 * Copy a trailing section at the end of the config, won't be
3509 * flushed by the usual "flush because we have a new section
3510 * logic in the loop above.
3512 if (copystr
.len
> 0) {
3513 if (write_in_full(out_fd
, copystr
.buf
, copystr
.len
) < 0) {
3514 ret
= write_error(get_lock_file_path(&lock
));
3517 strbuf_reset(©str
);
3520 fclose(config_file
);
3523 if (commit_lock_file(&lock
) < 0)
3524 ret
= error_errno(_("could not write config file %s"),
3528 fclose(config_file
);
3529 rollback_lock_file(&lock
);
3532 config_store_data_clear(&store
);
3536 int git_config_rename_section_in_file(const char *config_filename
,
3537 const char *old_name
, const char *new_name
)
3539 return git_config_copy_or_rename_section_in_file(config_filename
,
3540 old_name
, new_name
, 0);
3543 int git_config_rename_section(const char *old_name
, const char *new_name
)
3545 return git_config_rename_section_in_file(NULL
, old_name
, new_name
);
3548 int git_config_copy_section_in_file(const char *config_filename
,
3549 const char *old_name
, const char *new_name
)
3551 return git_config_copy_or_rename_section_in_file(config_filename
,
3552 old_name
, new_name
, 1);
3555 int git_config_copy_section(const char *old_name
, const char *new_name
)
3557 return git_config_copy_section_in_file(NULL
, old_name
, new_name
);
3561 * Call this to report error for your variable that should not
3562 * get a boolean value (i.e. "[my] var" means "true").
3564 #undef config_error_nonbool
3565 int config_error_nonbool(const char *var
)
3567 return error(_("missing value for '%s'"), var
);
3570 int parse_config_key(const char *var
,
3571 const char *section
,
3572 const char **subsection
, size_t *subsection_len
,
3577 /* Does it start with "section." ? */
3578 if (!skip_prefix(var
, section
, &var
) || *var
!= '.')
3582 * Find the key; we don't know yet if we have a subsection, but we must
3583 * parse backwards from the end, since the subsection may have dots in
3586 dot
= strrchr(var
, '.');
3589 /* Did we have a subsection at all? */
3593 *subsection_len
= 0;
3599 *subsection
= var
+ 1;
3600 *subsection_len
= dot
- *subsection
;
3606 const char *current_config_origin_type(void)
3609 if (current_config_kvi
)
3610 type
= current_config_kvi
->origin_type
;
3612 type
= cf
->origin_type
;
3614 BUG("current_config_origin_type called outside config callback");
3617 case CONFIG_ORIGIN_BLOB
:
3619 case CONFIG_ORIGIN_FILE
:
3621 case CONFIG_ORIGIN_STDIN
:
3622 return "standard input";
3623 case CONFIG_ORIGIN_SUBMODULE_BLOB
:
3624 return "submodule-blob";
3625 case CONFIG_ORIGIN_CMDLINE
:
3626 return "command line";
3628 BUG("unknown config origin type");
3632 const char *config_scope_name(enum config_scope scope
)
3635 case CONFIG_SCOPE_SYSTEM
:
3637 case CONFIG_SCOPE_GLOBAL
:
3639 case CONFIG_SCOPE_LOCAL
:
3641 case CONFIG_SCOPE_WORKTREE
:
3643 case CONFIG_SCOPE_COMMAND
:
3645 case CONFIG_SCOPE_SUBMODULE
:
3652 const char *current_config_name(void)
3655 if (current_config_kvi
)
3656 name
= current_config_kvi
->filename
;
3660 BUG("current_config_name called outside config callback");
3661 return name
? name
: "";
3664 enum config_scope
current_config_scope(void)
3666 if (current_config_kvi
)
3667 return current_config_kvi
->scope
;
3669 return current_parsing_scope
;
3672 int current_config_line(void)
3674 if (current_config_kvi
)
3675 return current_config_kvi
->linenr
;
3680 int lookup_config(const char **mapping
, int nr_mapping
, const char *var
)
3684 for (i
= 0; i
< nr_mapping
; i
++) {
3685 const char *name
= mapping
[i
];
3687 if (name
&& !strcasecmp(var
, name
))