Coverage Report

Created: 2026-10-17 07:15

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