Merge branch 'en/merge-ort-api-null-impl'
[git] / builtin / config.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "config.h"
4 #include "color.h"
5 #include "parse-options.h"
6 #include "urlmatch.h"
7 #include "quote.h"
8 #include "worktree.h"
9
10 static const char *const builtin_config_usage[] = {
11         N_("git config [<options>]"),
12         NULL
13 };
14
15 static char *key;
16 static regex_t *key_regexp;
17 static regex_t *regexp;
18 static int show_keys;
19 static int omit_values;
20 static int use_key_regexp;
21 static int do_all;
22 static int do_not_match;
23 static char delim = '=';
24 static char key_delim = ' ';
25 static char term = '\n';
26
27 static int use_global_config, use_system_config, use_local_config;
28 static int use_worktree_config;
29 static struct git_config_source given_config_source;
30 static int actions, type;
31 static char *default_value;
32 static int end_nul;
33 static int respect_includes_opt = -1;
34 static struct config_options config_options;
35 static int show_origin;
36 static int show_scope;
37
38 #define ACTION_GET (1<<0)
39 #define ACTION_GET_ALL (1<<1)
40 #define ACTION_GET_REGEXP (1<<2)
41 #define ACTION_REPLACE_ALL (1<<3)
42 #define ACTION_ADD (1<<4)
43 #define ACTION_UNSET (1<<5)
44 #define ACTION_UNSET_ALL (1<<6)
45 #define ACTION_RENAME_SECTION (1<<7)
46 #define ACTION_REMOVE_SECTION (1<<8)
47 #define ACTION_LIST (1<<9)
48 #define ACTION_EDIT (1<<10)
49 #define ACTION_SET (1<<11)
50 #define ACTION_SET_ALL (1<<12)
51 #define ACTION_GET_COLOR (1<<13)
52 #define ACTION_GET_COLORBOOL (1<<14)
53 #define ACTION_GET_URLMATCH (1<<15)
54
55 /*
56  * The actions "ACTION_LIST | ACTION_GET_*" which may produce more than
57  * one line of output and which should therefore be paged.
58  */
59 #define PAGING_ACTIONS (ACTION_LIST | ACTION_GET_ALL | \
60                         ACTION_GET_REGEXP | ACTION_GET_URLMATCH)
61
62 #define TYPE_BOOL               1
63 #define TYPE_INT                2
64 #define TYPE_BOOL_OR_INT        3
65 #define TYPE_PATH               4
66 #define TYPE_EXPIRY_DATE        5
67 #define TYPE_COLOR              6
68 #define TYPE_BOOL_OR_STR        7
69
70 #define OPT_CALLBACK_VALUE(s, l, v, h, i) \
71         { OPTION_CALLBACK, (s), (l), (v), NULL, (h), PARSE_OPT_NOARG | \
72         PARSE_OPT_NONEG, option_parse_type, (i) }
73
74 static NORETURN void usage_builtin_config(void);
75
76 static int option_parse_type(const struct option *opt, const char *arg,
77                              int unset)
78 {
79         int new_type, *to_type;
80
81         if (unset) {
82                 *((int *) opt->value) = 0;
83                 return 0;
84         }
85
86         /*
87          * To support '--<type>' style flags, begin with new_type equal to
88          * opt->defval.
89          */
90         new_type = opt->defval;
91         if (!new_type) {
92                 if (!strcmp(arg, "bool"))
93                         new_type = TYPE_BOOL;
94                 else if (!strcmp(arg, "int"))
95                         new_type = TYPE_INT;
96                 else if (!strcmp(arg, "bool-or-int"))
97                         new_type = TYPE_BOOL_OR_INT;
98                 else if (!strcmp(arg, "bool-or-str"))
99                         new_type = TYPE_BOOL_OR_STR;
100                 else if (!strcmp(arg, "path"))
101                         new_type = TYPE_PATH;
102                 else if (!strcmp(arg, "expiry-date"))
103                         new_type = TYPE_EXPIRY_DATE;
104                 else if (!strcmp(arg, "color"))
105                         new_type = TYPE_COLOR;
106                 else
107                         die(_("unrecognized --type argument, %s"), arg);
108         }
109
110         to_type = opt->value;
111         if (*to_type && *to_type != new_type) {
112                 /*
113                  * Complain when there is a new type not equal to the old type.
114                  * This allows for combinations like '--int --type=int' and
115                  * '--type=int --type=int', but disallows ones like '--type=bool
116                  * --int' and '--type=bool
117                  * --type=int'.
118                  */
119                 error(_("only one type at a time"));
120                 usage_builtin_config();
121         }
122         *to_type = new_type;
123
124         return 0;
125 }
126
127 static struct option builtin_config_options[] = {
128         OPT_GROUP(N_("Config file location")),
129         OPT_BOOL(0, "global", &use_global_config, N_("use global config file")),
130         OPT_BOOL(0, "system", &use_system_config, N_("use system config file")),
131         OPT_BOOL(0, "local", &use_local_config, N_("use repository config file")),
132         OPT_BOOL(0, "worktree", &use_worktree_config, N_("use per-worktree config file")),
133         OPT_STRING('f', "file", &given_config_source.file, N_("file"), N_("use given config file")),
134         OPT_STRING(0, "blob", &given_config_source.blob, N_("blob-id"), N_("read config from given blob object")),
135         OPT_GROUP(N_("Action")),
136         OPT_BIT(0, "get", &actions, N_("get value: name [value-regex]"), ACTION_GET),
137         OPT_BIT(0, "get-all", &actions, N_("get all values: key [value-regex]"), ACTION_GET_ALL),
138         OPT_BIT(0, "get-regexp", &actions, N_("get values for regexp: name-regex [value-regex]"), ACTION_GET_REGEXP),
139         OPT_BIT(0, "get-urlmatch", &actions, N_("get value specific for the URL: section[.var] URL"), ACTION_GET_URLMATCH),
140         OPT_BIT(0, "replace-all", &actions, N_("replace all matching variables: name value [value_regex]"), ACTION_REPLACE_ALL),
141         OPT_BIT(0, "add", &actions, N_("add a new variable: name value"), ACTION_ADD),
142         OPT_BIT(0, "unset", &actions, N_("remove a variable: name [value-regex]"), ACTION_UNSET),
143         OPT_BIT(0, "unset-all", &actions, N_("remove all matches: name [value-regex]"), ACTION_UNSET_ALL),
144         OPT_BIT(0, "rename-section", &actions, N_("rename section: old-name new-name"), ACTION_RENAME_SECTION),
145         OPT_BIT(0, "remove-section", &actions, N_("remove a section: name"), ACTION_REMOVE_SECTION),
146         OPT_BIT('l', "list", &actions, N_("list all"), ACTION_LIST),
147         OPT_BIT('e', "edit", &actions, N_("open an editor"), ACTION_EDIT),
148         OPT_BIT(0, "get-color", &actions, N_("find the color configured: slot [default]"), ACTION_GET_COLOR),
149         OPT_BIT(0, "get-colorbool", &actions, N_("find the color setting: slot [stdout-is-tty]"), ACTION_GET_COLORBOOL),
150         OPT_GROUP(N_("Type")),
151         OPT_CALLBACK('t', "type", &type, "", N_("value is given this type"), option_parse_type),
152         OPT_CALLBACK_VALUE(0, "bool", &type, N_("value is \"true\" or \"false\""), TYPE_BOOL),
153         OPT_CALLBACK_VALUE(0, "int", &type, N_("value is decimal number"), TYPE_INT),
154         OPT_CALLBACK_VALUE(0, "bool-or-int", &type, N_("value is --bool or --int"), TYPE_BOOL_OR_INT),
155         OPT_CALLBACK_VALUE(0, "bool-or-str", &type, N_("value is --bool or string"), TYPE_BOOL_OR_STR),
156         OPT_CALLBACK_VALUE(0, "path", &type, N_("value is a path (file or directory name)"), TYPE_PATH),
157         OPT_CALLBACK_VALUE(0, "expiry-date", &type, N_("value is an expiry date"), TYPE_EXPIRY_DATE),
158         OPT_GROUP(N_("Other")),
159         OPT_BOOL('z', "null", &end_nul, N_("terminate values with NUL byte")),
160         OPT_BOOL(0, "name-only", &omit_values, N_("show variable names only")),
161         OPT_BOOL(0, "includes", &respect_includes_opt, N_("respect include directives on lookup")),
162         OPT_BOOL(0, "show-origin", &show_origin, N_("show origin of config (file, standard input, blob, command line)")),
163         OPT_BOOL(0, "show-scope", &show_scope, N_("show scope of config (worktree, local, global, system, command)")),
164         OPT_STRING(0, "default", &default_value, N_("value"), N_("with --get, use default value when missing entry")),
165         OPT_END(),
166 };
167
168 static NORETURN void usage_builtin_config(void)
169 {
170         usage_with_options(builtin_config_usage, builtin_config_options);
171 }
172
173 static void check_argc(int argc, int min, int max)
174 {
175         if (argc >= min && argc <= max)
176                 return;
177         if (min == max)
178                 error(_("wrong number of arguments, should be %d"), min);
179         else
180                 error(_("wrong number of arguments, should be from %d to %d"),
181                       min, max);
182         usage_builtin_config();
183 }
184
185 static void show_config_origin(struct strbuf *buf)
186 {
187         const char term = end_nul ? '\0' : '\t';
188
189         strbuf_addstr(buf, current_config_origin_type());
190         strbuf_addch(buf, ':');
191         if (end_nul)
192                 strbuf_addstr(buf, current_config_name());
193         else
194                 quote_c_style(current_config_name(), buf, NULL, 0);
195         strbuf_addch(buf, term);
196 }
197
198 static void show_config_scope(struct strbuf *buf)
199 {
200         const char term = end_nul ? '\0' : '\t';
201         const char *scope = config_scope_name(current_config_scope());
202
203         strbuf_addstr(buf, N_(scope));
204         strbuf_addch(buf, term);
205 }
206
207 static int show_all_config(const char *key_, const char *value_, void *cb)
208 {
209         if (show_origin || show_scope) {
210                 struct strbuf buf = STRBUF_INIT;
211                 if (show_scope)
212                         show_config_scope(&buf);
213                 if (show_origin)
214                         show_config_origin(&buf);
215                 /* Use fwrite as "buf" can contain \0's if "end_null" is set. */
216                 fwrite(buf.buf, 1, buf.len, stdout);
217                 strbuf_release(&buf);
218         }
219         if (!omit_values && value_)
220                 printf("%s%c%s%c", key_, delim, value_, term);
221         else
222                 printf("%s%c", key_, term);
223         return 0;
224 }
225
226 struct strbuf_list {
227         struct strbuf *items;
228         int nr;
229         int alloc;
230 };
231
232 static int format_config(struct strbuf *buf, const char *key_, const char *value_)
233 {
234         if (show_scope)
235                 show_config_scope(buf);
236         if (show_origin)
237                 show_config_origin(buf);
238         if (show_keys)
239                 strbuf_addstr(buf, key_);
240         if (!omit_values) {
241                 if (show_keys)
242                         strbuf_addch(buf, key_delim);
243
244                 if (type == TYPE_INT)
245                         strbuf_addf(buf, "%"PRId64,
246                                     git_config_int64(key_, value_ ? value_ : ""));
247                 else if (type == TYPE_BOOL)
248                         strbuf_addstr(buf, git_config_bool(key_, value_) ?
249                                       "true" : "false");
250                 else if (type == TYPE_BOOL_OR_INT) {
251                         int is_bool, v;
252                         v = git_config_bool_or_int(key_, value_, &is_bool);
253                         if (is_bool)
254                                 strbuf_addstr(buf, v ? "true" : "false");
255                         else
256                                 strbuf_addf(buf, "%d", v);
257                 } else if (type == TYPE_BOOL_OR_STR) {
258                         int v = git_parse_maybe_bool(value_);
259                         if (v < 0)
260                                 strbuf_addstr(buf, value_);
261                         else
262                                 strbuf_addstr(buf, v ? "true" : "false");
263                 } else if (type == TYPE_PATH) {
264                         const char *v;
265                         if (git_config_pathname(&v, key_, value_) < 0)
266                                 return -1;
267                         strbuf_addstr(buf, v);
268                         free((char *)v);
269                 } else if (type == TYPE_EXPIRY_DATE) {
270                         timestamp_t t;
271                         if (git_config_expiry_date(&t, key_, value_) < 0)
272                                 return -1;
273                         strbuf_addf(buf, "%"PRItime, t);
274                 } else if (type == TYPE_COLOR) {
275                         char v[COLOR_MAXLEN];
276                         if (git_config_color(v, key_, value_) < 0)
277                                 return -1;
278                         strbuf_addstr(buf, v);
279                 } else if (value_) {
280                         strbuf_addstr(buf, value_);
281                 } else {
282                         /* Just show the key name; back out delimiter */
283                         if (show_keys)
284                                 strbuf_setlen(buf, buf->len - 1);
285                 }
286         }
287         strbuf_addch(buf, term);
288         return 0;
289 }
290
291 static int collect_config(const char *key_, const char *value_, void *cb)
292 {
293         struct strbuf_list *values = cb;
294
295         if (!use_key_regexp && strcmp(key_, key))
296                 return 0;
297         if (use_key_regexp && regexec(key_regexp, key_, 0, NULL, 0))
298                 return 0;
299         if (regexp != NULL &&
300             (do_not_match ^ !!regexec(regexp, (value_?value_:""), 0, NULL, 0)))
301                 return 0;
302
303         ALLOC_GROW(values->items, values->nr + 1, values->alloc);
304         strbuf_init(&values->items[values->nr], 0);
305
306         return format_config(&values->items[values->nr++], key_, value_);
307 }
308
309 static int get_value(const char *key_, const char *regex_)
310 {
311         int ret = CONFIG_GENERIC_ERROR;
312         struct strbuf_list values = {NULL};
313         int i;
314
315         if (use_key_regexp) {
316                 char *tl;
317
318                 /*
319                  * NEEDSWORK: this naive pattern lowercasing obviously does not
320                  * work for more complex patterns like "^[^.]*Foo.*bar".
321                  * Perhaps we should deprecate this altogether someday.
322                  */
323
324                 key = xstrdup(key_);
325                 for (tl = key + strlen(key) - 1;
326                      tl >= key && *tl != '.';
327                      tl--)
328                         *tl = tolower(*tl);
329                 for (tl = key; *tl && *tl != '.'; tl++)
330                         *tl = tolower(*tl);
331
332                 key_regexp = (regex_t*)xmalloc(sizeof(regex_t));
333                 if (regcomp(key_regexp, key, REG_EXTENDED)) {
334                         error(_("invalid key pattern: %s"), key_);
335                         FREE_AND_NULL(key_regexp);
336                         ret = CONFIG_INVALID_PATTERN;
337                         goto free_strings;
338                 }
339         } else {
340                 if (git_config_parse_key(key_, &key, NULL)) {
341                         ret = CONFIG_INVALID_KEY;
342                         goto free_strings;
343                 }
344         }
345
346         if (regex_) {
347                 if (regex_[0] == '!') {
348                         do_not_match = 1;
349                         regex_++;
350                 }
351
352                 regexp = (regex_t*)xmalloc(sizeof(regex_t));
353                 if (regcomp(regexp, regex_, REG_EXTENDED)) {
354                         error(_("invalid pattern: %s"), regex_);
355                         FREE_AND_NULL(regexp);
356                         ret = CONFIG_INVALID_PATTERN;
357                         goto free_strings;
358                 }
359         }
360
361         config_with_options(collect_config, &values,
362                             &given_config_source, &config_options);
363
364         if (!values.nr && default_value) {
365                 struct strbuf *item;
366                 ALLOC_GROW(values.items, values.nr + 1, values.alloc);
367                 item = &values.items[values.nr++];
368                 strbuf_init(item, 0);
369                 if (format_config(item, key_, default_value) < 0)
370                         die(_("failed to format default config value: %s"),
371                                 default_value);
372         }
373
374         ret = !values.nr;
375
376         for (i = 0; i < values.nr; i++) {
377                 struct strbuf *buf = values.items + i;
378                 if (do_all || i == values.nr - 1)
379                         fwrite(buf->buf, 1, buf->len, stdout);
380                 strbuf_release(buf);
381         }
382         free(values.items);
383
384 free_strings:
385         free(key);
386         if (key_regexp) {
387                 regfree(key_regexp);
388                 free(key_regexp);
389         }
390         if (regexp) {
391                 regfree(regexp);
392                 free(regexp);
393         }
394
395         return ret;
396 }
397
398 static char *normalize_value(const char *key, const char *value)
399 {
400         if (!value)
401                 return NULL;
402
403         if (type == 0 || type == TYPE_PATH || type == TYPE_EXPIRY_DATE)
404                 /*
405                  * We don't do normalization for TYPE_PATH here: If
406                  * the path is like ~/foobar/, we prefer to store
407                  * "~/foobar/" in the config file, and to expand the ~
408                  * when retrieving the value.
409                  * Also don't do normalization for expiry dates.
410                  */
411                 return xstrdup(value);
412         if (type == TYPE_INT)
413                 return xstrfmt("%"PRId64, git_config_int64(key, value));
414         if (type == TYPE_BOOL)
415                 return xstrdup(git_config_bool(key, value) ?  "true" : "false");
416         if (type == TYPE_BOOL_OR_INT) {
417                 int is_bool, v;
418                 v = git_config_bool_or_int(key, value, &is_bool);
419                 if (!is_bool)
420                         return xstrfmt("%d", v);
421                 else
422                         return xstrdup(v ? "true" : "false");
423         }
424         if (type == TYPE_BOOL_OR_STR) {
425                 int v = git_parse_maybe_bool(value);
426                 if (v < 0)
427                         return xstrdup(value);
428                 else
429                         return xstrdup(v ? "true" : "false");
430         }
431         if (type == TYPE_COLOR) {
432                 char v[COLOR_MAXLEN];
433                 if (git_config_color(v, key, value))
434                         die(_("cannot parse color '%s'"), value);
435
436                 /*
437                  * The contents of `v` now contain an ANSI escape
438                  * sequence, not suitable for including within a
439                  * configuration file. Treat the above as a
440                  * "sanity-check", and return the given value, which we
441                  * know is representable as valid color code.
442                  */
443                 return xstrdup(value);
444         }
445
446         BUG("cannot normalize type %d", type);
447 }
448
449 static int get_color_found;
450 static const char *get_color_slot;
451 static const char *get_colorbool_slot;
452 static char parsed_color[COLOR_MAXLEN];
453
454 static int git_get_color_config(const char *var, const char *value, void *cb)
455 {
456         if (!strcmp(var, get_color_slot)) {
457                 if (!value)
458                         config_error_nonbool(var);
459                 if (color_parse(value, parsed_color) < 0)
460                         return -1;
461                 get_color_found = 1;
462         }
463         return 0;
464 }
465
466 static void get_color(const char *var, const char *def_color)
467 {
468         get_color_slot = var;
469         get_color_found = 0;
470         parsed_color[0] = '\0';
471         config_with_options(git_get_color_config, NULL,
472                             &given_config_source, &config_options);
473
474         if (!get_color_found && def_color) {
475                 if (color_parse(def_color, parsed_color) < 0)
476                         die(_("unable to parse default color value"));
477         }
478
479         fputs(parsed_color, stdout);
480 }
481
482 static int get_colorbool_found;
483 static int get_diff_color_found;
484 static int get_color_ui_found;
485 static int git_get_colorbool_config(const char *var, const char *value,
486                 void *cb)
487 {
488         if (!strcmp(var, get_colorbool_slot))
489                 get_colorbool_found = git_config_colorbool(var, value);
490         else if (!strcmp(var, "diff.color"))
491                 get_diff_color_found = git_config_colorbool(var, value);
492         else if (!strcmp(var, "color.ui"))
493                 get_color_ui_found = git_config_colorbool(var, value);
494         return 0;
495 }
496
497 static int get_colorbool(const char *var, int print)
498 {
499         get_colorbool_slot = var;
500         get_colorbool_found = -1;
501         get_diff_color_found = -1;
502         get_color_ui_found = -1;
503         config_with_options(git_get_colorbool_config, NULL,
504                             &given_config_source, &config_options);
505
506         if (get_colorbool_found < 0) {
507                 if (!strcmp(get_colorbool_slot, "color.diff"))
508                         get_colorbool_found = get_diff_color_found;
509                 if (get_colorbool_found < 0)
510                         get_colorbool_found = get_color_ui_found;
511         }
512
513         if (get_colorbool_found < 0)
514                 /* default value if none found in config */
515                 get_colorbool_found = GIT_COLOR_AUTO;
516
517         get_colorbool_found = want_color(get_colorbool_found);
518
519         if (print) {
520                 printf("%s\n", get_colorbool_found ? "true" : "false");
521                 return 0;
522         } else
523                 return get_colorbool_found ? 0 : 1;
524 }
525
526 static void check_write(void)
527 {
528         if (!given_config_source.file && !startup_info->have_repository)
529                 die(_("not in a git directory"));
530
531         if (given_config_source.use_stdin)
532                 die(_("writing to stdin is not supported"));
533
534         if (given_config_source.blob)
535                 die(_("writing config blobs is not supported"));
536 }
537
538 struct urlmatch_current_candidate_value {
539         char value_is_null;
540         struct strbuf value;
541 };
542
543 static int urlmatch_collect_fn(const char *var, const char *value, void *cb)
544 {
545         struct string_list *values = cb;
546         struct string_list_item *item = string_list_insert(values, var);
547         struct urlmatch_current_candidate_value *matched = item->util;
548
549         if (!matched) {
550                 matched = xmalloc(sizeof(*matched));
551                 strbuf_init(&matched->value, 0);
552                 item->util = matched;
553         } else {
554                 strbuf_reset(&matched->value);
555         }
556
557         if (value) {
558                 strbuf_addstr(&matched->value, value);
559                 matched->value_is_null = 0;
560         } else {
561                 matched->value_is_null = 1;
562         }
563         return 0;
564 }
565
566 static int get_urlmatch(const char *var, const char *url)
567 {
568         int ret;
569         char *section_tail;
570         struct string_list_item *item;
571         struct urlmatch_config config = { STRING_LIST_INIT_DUP };
572         struct string_list values = STRING_LIST_INIT_DUP;
573
574         config.collect_fn = urlmatch_collect_fn;
575         config.cascade_fn = NULL;
576         config.cb = &values;
577
578         if (!url_normalize(url, &config.url))
579                 die("%s", config.url.err);
580
581         config.section = xstrdup_tolower(var);
582         section_tail = strchr(config.section, '.');
583         if (section_tail) {
584                 *section_tail = '\0';
585                 config.key = section_tail + 1;
586                 show_keys = 0;
587         } else {
588                 config.key = NULL;
589                 show_keys = 1;
590         }
591
592         config_with_options(urlmatch_config_entry, &config,
593                             &given_config_source, &config_options);
594
595         ret = !values.nr;
596
597         for_each_string_list_item(item, &values) {
598                 struct urlmatch_current_candidate_value *matched = item->util;
599                 struct strbuf buf = STRBUF_INIT;
600
601                 format_config(&buf, item->string,
602                               matched->value_is_null ? NULL : matched->value.buf);
603                 fwrite(buf.buf, 1, buf.len, stdout);
604                 strbuf_release(&buf);
605
606                 strbuf_release(&matched->value);
607         }
608         string_list_clear(&config.vars, 1);
609         string_list_clear(&values, 1);
610         free(config.url.url);
611
612         free((void *)config.section);
613         return ret;
614 }
615
616 static char *default_user_config(void)
617 {
618         struct strbuf buf = STRBUF_INIT;
619         strbuf_addf(&buf,
620                     _("# This is Git's per-user configuration file.\n"
621                       "[user]\n"
622                       "# Please adapt and uncomment the following lines:\n"
623                       "#        name = %s\n"
624                       "#        email = %s\n"),
625                     ident_default_name(),
626                     ident_default_email());
627         return strbuf_detach(&buf, NULL);
628 }
629
630 int cmd_config(int argc, const char **argv, const char *prefix)
631 {
632         int nongit = !startup_info->have_repository;
633         char *value;
634
635         given_config_source.file = xstrdup_or_null(getenv(CONFIG_ENVIRONMENT));
636
637         argc = parse_options(argc, argv, prefix, builtin_config_options,
638                              builtin_config_usage,
639                              PARSE_OPT_STOP_AT_NON_OPTION);
640
641         if (use_global_config + use_system_config + use_local_config +
642             use_worktree_config +
643             !!given_config_source.file + !!given_config_source.blob > 1) {
644                 error(_("only one config file at a time"));
645                 usage_builtin_config();
646         }
647
648         if (nongit) {
649                 if (use_local_config)
650                         die(_("--local can only be used inside a git repository"));
651                 if (given_config_source.blob)
652                         die(_("--blob can only be used inside a git repository"));
653                 if (use_worktree_config)
654                         die(_("--worktree can only be used inside a git repository"));
655
656         }
657
658         if (given_config_source.file &&
659                         !strcmp(given_config_source.file, "-")) {
660                 given_config_source.file = NULL;
661                 given_config_source.use_stdin = 1;
662                 given_config_source.scope = CONFIG_SCOPE_COMMAND;
663         }
664
665         if (use_global_config) {
666                 char *user_config = expand_user_path("~/.gitconfig", 0);
667                 char *xdg_config = xdg_config_home("config");
668
669                 if (!user_config)
670                         /*
671                          * It is unknown if HOME/.gitconfig exists, so
672                          * we do not know if we should write to XDG
673                          * location; error out even if XDG_CONFIG_HOME
674                          * is set and points at a sane location.
675                          */
676                         die(_("$HOME not set"));
677
678                 given_config_source.scope = CONFIG_SCOPE_GLOBAL;
679
680                 if (access_or_warn(user_config, R_OK, 0) &&
681                     xdg_config && !access_or_warn(xdg_config, R_OK, 0)) {
682                         given_config_source.file = xdg_config;
683                         free(user_config);
684                 } else {
685                         given_config_source.file = user_config;
686                         free(xdg_config);
687                 }
688         }
689         else if (use_system_config) {
690                 given_config_source.file = git_etc_gitconfig();
691                 given_config_source.scope = CONFIG_SCOPE_SYSTEM;
692         } else if (use_local_config) {
693                 given_config_source.file = git_pathdup("config");
694                 given_config_source.scope = CONFIG_SCOPE_LOCAL;
695         } else if (use_worktree_config) {
696                 struct worktree **worktrees = get_worktrees();
697                 if (repository_format_worktree_config)
698                         given_config_source.file = git_pathdup("config.worktree");
699                 else if (worktrees[0] && worktrees[1])
700                         die(_("--worktree cannot be used with multiple "
701                               "working trees unless the config\n"
702                               "extension worktreeConfig is enabled. "
703                               "Please read \"CONFIGURATION FILE\"\n"
704                               "section in \"git help worktree\" for details"));
705                 else
706                         given_config_source.file = git_pathdup("config");
707                 given_config_source.scope = CONFIG_SCOPE_LOCAL;
708                 free_worktrees(worktrees);
709         } else if (given_config_source.file) {
710                 if (!is_absolute_path(given_config_source.file) && prefix)
711                         given_config_source.file =
712                                 prefix_filename(prefix, given_config_source.file);
713                 given_config_source.scope = CONFIG_SCOPE_COMMAND;
714         } else if (given_config_source.blob) {
715                 given_config_source.scope = CONFIG_SCOPE_COMMAND;
716         }
717
718
719         if (respect_includes_opt == -1)
720                 config_options.respect_includes = !given_config_source.file;
721         else
722                 config_options.respect_includes = respect_includes_opt;
723         if (!nongit) {
724                 config_options.commondir = get_git_common_dir();
725                 config_options.git_dir = get_git_dir();
726         }
727
728         if (end_nul) {
729                 term = '\0';
730                 delim = '\n';
731                 key_delim = '\n';
732         }
733
734         if ((actions & (ACTION_GET_COLOR|ACTION_GET_COLORBOOL)) && type) {
735                 error(_("--get-color and variable type are incoherent"));
736                 usage_builtin_config();
737         }
738
739         if (HAS_MULTI_BITS(actions)) {
740                 error(_("only one action at a time"));
741                 usage_builtin_config();
742         }
743         if (actions == 0)
744                 switch (argc) {
745                 case 1: actions = ACTION_GET; break;
746                 case 2: actions = ACTION_SET; break;
747                 case 3: actions = ACTION_SET_ALL; break;
748                 default:
749                         usage_builtin_config();
750                 }
751         if (omit_values &&
752             !(actions == ACTION_LIST || actions == ACTION_GET_REGEXP)) {
753                 error(_("--name-only is only applicable to --list or --get-regexp"));
754                 usage_builtin_config();
755         }
756
757         if (show_origin && !(actions &
758                 (ACTION_GET|ACTION_GET_ALL|ACTION_GET_REGEXP|ACTION_LIST))) {
759                 error(_("--show-origin is only applicable to --get, --get-all, "
760                         "--get-regexp, and --list"));
761                 usage_builtin_config();
762         }
763
764         if (default_value && !(actions & ACTION_GET)) {
765                 error(_("--default is only applicable to --get"));
766                 usage_builtin_config();
767         }
768
769         if (actions & PAGING_ACTIONS)
770                 setup_auto_pager("config", 1);
771
772         if (actions == ACTION_LIST) {
773                 check_argc(argc, 0, 0);
774                 if (config_with_options(show_all_config, NULL,
775                                         &given_config_source,
776                                         &config_options) < 0) {
777                         if (given_config_source.file)
778                                 die_errno(_("unable to read config file '%s'"),
779                                           given_config_source.file);
780                         else
781                                 die(_("error processing config file(s)"));
782                 }
783         }
784         else if (actions == ACTION_EDIT) {
785                 char *config_file;
786
787                 check_argc(argc, 0, 0);
788                 if (!given_config_source.file && nongit)
789                         die(_("not in a git directory"));
790                 if (given_config_source.use_stdin)
791                         die(_("editing stdin is not supported"));
792                 if (given_config_source.blob)
793                         die(_("editing blobs is not supported"));
794                 git_config(git_default_config, NULL);
795                 config_file = given_config_source.file ?
796                                 xstrdup(given_config_source.file) :
797                                 git_pathdup("config");
798                 if (use_global_config) {
799                         int fd = open(config_file, O_CREAT | O_EXCL | O_WRONLY, 0666);
800                         if (fd >= 0) {
801                                 char *content = default_user_config();
802                                 write_str_in_full(fd, content);
803                                 free(content);
804                                 close(fd);
805                         }
806                         else if (errno != EEXIST)
807                                 die_errno(_("cannot create configuration file %s"), config_file);
808                 }
809                 launch_editor(config_file, NULL, NULL);
810                 free(config_file);
811         }
812         else if (actions == ACTION_SET) {
813                 int ret;
814                 check_write();
815                 check_argc(argc, 2, 2);
816                 value = normalize_value(argv[0], argv[1]);
817                 UNLEAK(value);
818                 ret = git_config_set_in_file_gently(given_config_source.file, argv[0], value);
819                 if (ret == CONFIG_NOTHING_SET)
820                         error(_("cannot overwrite multiple values with a single value\n"
821                         "       Use a regexp, --add or --replace-all to change %s."), argv[0]);
822                 return ret;
823         }
824         else if (actions == ACTION_SET_ALL) {
825                 check_write();
826                 check_argc(argc, 2, 3);
827                 value = normalize_value(argv[0], argv[1]);
828                 UNLEAK(value);
829                 return git_config_set_multivar_in_file_gently(given_config_source.file,
830                                                               argv[0], value, argv[2], 0);
831         }
832         else if (actions == ACTION_ADD) {
833                 check_write();
834                 check_argc(argc, 2, 2);
835                 value = normalize_value(argv[0], argv[1]);
836                 UNLEAK(value);
837                 return git_config_set_multivar_in_file_gently(given_config_source.file,
838                                                               argv[0], value,
839                                                               CONFIG_REGEX_NONE, 0);
840         }
841         else if (actions == ACTION_REPLACE_ALL) {
842                 check_write();
843                 check_argc(argc, 2, 3);
844                 value = normalize_value(argv[0], argv[1]);
845                 UNLEAK(value);
846                 return git_config_set_multivar_in_file_gently(given_config_source.file,
847                                                               argv[0], value, argv[2], 1);
848         }
849         else if (actions == ACTION_GET) {
850                 check_argc(argc, 1, 2);
851                 return get_value(argv[0], argv[1]);
852         }
853         else if (actions == ACTION_GET_ALL) {
854                 do_all = 1;
855                 check_argc(argc, 1, 2);
856                 return get_value(argv[0], argv[1]);
857         }
858         else if (actions == ACTION_GET_REGEXP) {
859                 show_keys = 1;
860                 use_key_regexp = 1;
861                 do_all = 1;
862                 check_argc(argc, 1, 2);
863                 return get_value(argv[0], argv[1]);
864         }
865         else if (actions == ACTION_GET_URLMATCH) {
866                 check_argc(argc, 2, 2);
867                 return get_urlmatch(argv[0], argv[1]);
868         }
869         else if (actions == ACTION_UNSET) {
870                 check_write();
871                 check_argc(argc, 1, 2);
872                 if (argc == 2)
873                         return git_config_set_multivar_in_file_gently(given_config_source.file,
874                                                                       argv[0], NULL, argv[1], 0);
875                 else
876                         return git_config_set_in_file_gently(given_config_source.file,
877                                                              argv[0], NULL);
878         }
879         else if (actions == ACTION_UNSET_ALL) {
880                 check_write();
881                 check_argc(argc, 1, 2);
882                 return git_config_set_multivar_in_file_gently(given_config_source.file,
883                                                               argv[0], NULL, argv[1], 1);
884         }
885         else if (actions == ACTION_RENAME_SECTION) {
886                 int ret;
887                 check_write();
888                 check_argc(argc, 2, 2);
889                 ret = git_config_rename_section_in_file(given_config_source.file,
890                                                         argv[0], argv[1]);
891                 if (ret < 0)
892                         return ret;
893                 if (ret == 0)
894                         die(_("no such section: %s"), argv[0]);
895         }
896         else if (actions == ACTION_REMOVE_SECTION) {
897                 int ret;
898                 check_write();
899                 check_argc(argc, 1, 1);
900                 ret = git_config_rename_section_in_file(given_config_source.file,
901                                                         argv[0], NULL);
902                 if (ret < 0)
903                         return ret;
904                 if (ret == 0)
905                         die(_("no such section: %s"), argv[0]);
906         }
907         else if (actions == ACTION_GET_COLOR) {
908                 check_argc(argc, 1, 2);
909                 get_color(argv[0], argv[1]);
910         }
911         else if (actions == ACTION_GET_COLORBOOL) {
912                 check_argc(argc, 1, 2);
913                 if (argc == 2)
914                         color_stdout_is_tty = git_config_bool("command line", argv[1]);
915                 return get_colorbool(argv[0], argc == 2);
916         }
917
918         return 0;
919 }