Coverage Report

Created: 2026-12-01 06:58

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