Coverage Report

Created: 2026-03-31 06:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/git/remote.c
Line
Count
Source
1
#define USE_THE_REPOSITORY_VARIABLE
2
#define DISABLE_SIGN_COMPARE_WARNINGS
3
4
#include "git-compat-util.h"
5
#include "abspath.h"
6
#include "config.h"
7
#include "environment.h"
8
#include "gettext.h"
9
#include "hex.h"
10
#include "remote.h"
11
#include "urlmatch.h"
12
#include "refs.h"
13
#include "refspec.h"
14
#include "object-name.h"
15
#include "odb.h"
16
#include "path.h"
17
#include "commit.h"
18
#include "diff.h"
19
#include "revision.h"
20
#include "dir.h"
21
#include "setup.h"
22
#include "string-list.h"
23
#include "strvec.h"
24
#include "commit-reach.h"
25
#include "advice.h"
26
#include "connect.h"
27
#include "parse-options.h"
28
#include "transport.h"
29
30
enum map_direction { FROM_SRC, FROM_DST };
31
32
enum {
33
  ENABLE_ADVICE_PULL       = (1 << 0),
34
  ENABLE_ADVICE_PUSH       = (1 << 1),
35
  ENABLE_ADVICE_DIVERGENCE = (1 << 2),
36
};
37
38
struct counted_string {
39
  size_t len;
40
  const char *s;
41
};
42
43
static int valid_remote(const struct remote *remote)
44
0
{
45
0
  return !!remote->url.nr;
46
0
}
47
48
static char *alias_url(const char *url, struct rewrites *r)
49
0
{
50
0
  int i, j;
51
0
  struct counted_string *longest;
52
0
  int longest_i;
53
54
0
  longest = NULL;
55
0
  longest_i = -1;
56
0
  for (i = 0; i < r->rewrite_nr; i++) {
57
0
    if (!r->rewrite[i])
58
0
      continue;
59
0
    for (j = 0; j < r->rewrite[i]->instead_of_nr; j++) {
60
0
      if (starts_with(url, r->rewrite[i]->instead_of[j].s) &&
61
0
          (!longest ||
62
0
           longest->len < r->rewrite[i]->instead_of[j].len)) {
63
0
        longest = &(r->rewrite[i]->instead_of[j]);
64
0
        longest_i = i;
65
0
      }
66
0
    }
67
0
  }
68
0
  if (!longest)
69
0
    return NULL;
70
71
0
  return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
72
0
}
73
74
static void add_url(struct remote *remote, const char *url)
75
0
{
76
0
  if (*url)
77
0
    strvec_push(&remote->url, url);
78
0
  else
79
0
    strvec_clear(&remote->url);
80
0
}
81
82
static void add_pushurl(struct remote *remote, const char *pushurl)
83
0
{
84
0
  if (*pushurl)
85
0
    strvec_push(&remote->pushurl, pushurl);
86
0
  else
87
0
    strvec_clear(&remote->pushurl);
88
0
}
89
90
static void add_pushurl_alias(struct remote_state *remote_state,
91
            struct remote *remote, const char *url)
92
0
{
93
0
  char *alias = alias_url(url, &remote_state->rewrites_push);
94
0
  if (alias)
95
0
    add_pushurl(remote, alias);
96
0
  free(alias);
97
0
}
98
99
static void add_url_alias(struct remote_state *remote_state,
100
        struct remote *remote, const char *url)
101
0
{
102
0
  char *alias = alias_url(url, &remote_state->rewrites);
103
0
  add_url(remote, alias ? alias : url);
104
0
  add_pushurl_alias(remote_state, remote, url);
105
0
  free(alias);
106
0
}
107
108
struct remotes_hash_key {
109
  const char *str;
110
  int len;
111
};
112
113
static int remotes_hash_cmp(const void *cmp_data UNUSED,
114
          const struct hashmap_entry *eptr,
115
          const struct hashmap_entry *entry_or_key,
116
          const void *keydata)
117
0
{
118
0
  const struct remote *a, *b;
119
0
  const struct remotes_hash_key *key = keydata;
120
121
0
  a = container_of(eptr, const struct remote, ent);
122
0
  b = container_of(entry_or_key, const struct remote, ent);
123
124
0
  if (key)
125
0
    return !!xstrncmpz(a->name, key->str, key->len);
126
0
  else
127
0
    return strcmp(a->name, b->name);
128
0
}
129
130
static struct remote *make_remote(struct remote_state *remote_state,
131
          const char *name, int len)
132
0
{
133
0
  struct remote *ret;
134
0
  struct remotes_hash_key lookup;
135
0
  struct hashmap_entry lookup_entry, *e;
136
137
0
  if (!len)
138
0
    len = strlen(name);
139
140
0
  lookup.str = name;
141
0
  lookup.len = len;
142
0
  hashmap_entry_init(&lookup_entry, memhash(name, len));
143
144
0
  e = hashmap_get(&remote_state->remotes_hash, &lookup_entry, &lookup);
145
0
  if (e)
146
0
    return container_of(e, struct remote, ent);
147
148
0
  CALLOC_ARRAY(ret, 1);
149
0
  ret->prune = -1;  /* unspecified */
150
0
  ret->prune_tags = -1;  /* unspecified */
151
0
  ret->name = xstrndup(name, len);
152
0
  refspec_init_push(&ret->push);
153
0
  refspec_init_fetch(&ret->fetch);
154
0
  string_list_init_dup(&ret->server_options);
155
156
0
  ALLOC_GROW(remote_state->remotes, remote_state->remotes_nr + 1,
157
0
       remote_state->remotes_alloc);
158
0
  remote_state->remotes[remote_state->remotes_nr++] = ret;
159
160
0
  hashmap_entry_init(&ret->ent, lookup_entry.hash);
161
0
  if (hashmap_put_entry(&remote_state->remotes_hash, ret, ent))
162
0
    BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
163
0
  return ret;
164
0
}
165
166
static void remote_clear(struct remote *remote)
167
0
{
168
0
  free((char *)remote->name);
169
0
  free((char *)remote->foreign_vcs);
170
171
0
  strvec_clear(&remote->url);
172
0
  strvec_clear(&remote->pushurl);
173
174
0
  refspec_clear(&remote->push);
175
0
  refspec_clear(&remote->fetch);
176
177
0
  free((char *)remote->receivepack);
178
0
  free((char *)remote->uploadpack);
179
0
  FREE_AND_NULL(remote->http_proxy);
180
0
  FREE_AND_NULL(remote->http_proxy_authmethod);
181
0
  string_list_clear(&remote->server_options, 0);
182
0
}
183
184
static void add_merge(struct branch *branch, const char *name)
185
0
{
186
0
  struct refspec_item *merge;
187
188
0
  ALLOC_GROW(branch->merge, branch->merge_nr + 1,
189
0
       branch->merge_alloc);
190
191
0
  merge = xcalloc(1, sizeof(*merge));
192
0
  merge->src = xstrdup(name);
193
194
0
  branch->merge[branch->merge_nr++] = merge;
195
0
}
196
197
struct branches_hash_key {
198
  const char *str;
199
  int len;
200
};
201
202
static int branches_hash_cmp(const void *cmp_data UNUSED,
203
           const struct hashmap_entry *eptr,
204
           const struct hashmap_entry *entry_or_key,
205
           const void *keydata)
206
0
{
207
0
  const struct branch *a, *b;
208
0
  const struct branches_hash_key *key = keydata;
209
210
0
  a = container_of(eptr, const struct branch, ent);
211
0
  b = container_of(entry_or_key, const struct branch, ent);
212
213
0
  if (key)
214
0
    return !!xstrncmpz(a->name, key->str, key->len);
215
0
  else
216
0
    return strcmp(a->name, b->name);
217
0
}
218
219
static struct branch *find_branch(struct remote_state *remote_state,
220
          const char *name, size_t len)
221
0
{
222
0
  struct branches_hash_key lookup;
223
0
  struct hashmap_entry lookup_entry, *e;
224
225
0
  lookup.str = name;
226
0
  lookup.len = len;
227
0
  hashmap_entry_init(&lookup_entry, memhash(name, len));
228
229
0
  e = hashmap_get(&remote_state->branches_hash, &lookup_entry, &lookup);
230
0
  if (e)
231
0
    return container_of(e, struct branch, ent);
232
233
0
  return NULL;
234
0
}
235
236
static void die_on_missing_branch(struct repository *repo,
237
          struct branch *branch)
238
0
{
239
  /* branch == NULL is always valid because it represents detached HEAD. */
240
0
  if (branch &&
241
0
      branch != find_branch(repo->remote_state, branch->name,
242
0
          strlen(branch->name)))
243
0
    die("branch %s was not found in the repository", branch->name);
244
0
}
245
246
static struct branch *make_branch(struct remote_state *remote_state,
247
          const char *name, size_t len)
248
0
{
249
0
  struct branch *ret;
250
251
0
  ret = find_branch(remote_state, name, len);
252
0
  if (ret)
253
0
    return ret;
254
255
0
  CALLOC_ARRAY(ret, 1);
256
0
  ret->name = xstrndup(name, len);
257
0
  ret->refname = xstrfmt("refs/heads/%s", ret->name);
258
259
0
  hashmap_entry_init(&ret->ent, memhash(name, len));
260
0
  if (hashmap_put_entry(&remote_state->branches_hash, ret, ent))
261
0
    BUG("hashmap_put overwrote entry after hashmap_get returned NULL");
262
0
  return ret;
263
0
}
264
265
static void merge_clear(struct branch *branch)
266
0
{
267
0
  for (int i = 0; i < branch->merge_nr; i++) {
268
0
    refspec_item_clear(branch->merge[i]);
269
0
    free(branch->merge[i]);
270
0
  }
271
0
  FREE_AND_NULL(branch->merge);
272
0
  branch->merge_nr = 0;
273
0
}
274
275
static void branch_release(struct branch *branch)
276
0
{
277
0
  free((char *)branch->name);
278
0
  free((char *)branch->refname);
279
0
  free(branch->remote_name);
280
0
  free(branch->pushremote_name);
281
0
  free(branch->push_tracking_ref);
282
0
  merge_clear(branch);
283
0
}
284
285
static struct rewrite *make_rewrite(struct rewrites *r,
286
            const char *base, size_t len)
287
0
{
288
0
  struct rewrite *ret;
289
0
  int i;
290
291
0
  for (i = 0; i < r->rewrite_nr; i++) {
292
0
    if (len == r->rewrite[i]->baselen &&
293
0
        !strncmp(base, r->rewrite[i]->base, len))
294
0
      return r->rewrite[i];
295
0
  }
296
297
0
  ALLOC_GROW(r->rewrite, r->rewrite_nr + 1, r->rewrite_alloc);
298
0
  CALLOC_ARRAY(ret, 1);
299
0
  r->rewrite[r->rewrite_nr++] = ret;
300
0
  ret->base = xstrndup(base, len);
301
0
  ret->baselen = len;
302
0
  return ret;
303
0
}
304
305
static void rewrites_release(struct rewrites *r)
306
114
{
307
114
  for (int i = 0; i < r->rewrite_nr; i++)
308
0
    free((char *)r->rewrite[i]->base);
309
114
  free(r->rewrite);
310
114
  memset(r, 0, sizeof(*r));
311
114
}
312
313
static void add_instead_of(struct rewrite *rewrite, const char *instead_of)
314
0
{
315
0
  ALLOC_GROW(rewrite->instead_of, rewrite->instead_of_nr + 1, rewrite->instead_of_alloc);
316
0
  rewrite->instead_of[rewrite->instead_of_nr].s = instead_of;
317
0
  rewrite->instead_of[rewrite->instead_of_nr].len = strlen(instead_of);
318
0
  rewrite->instead_of_nr++;
319
0
}
320
321
#ifndef WITH_BREAKING_CHANGES
322
static const char *skip_spaces(const char *s)
323
0
{
324
0
  while (isspace(*s))
325
0
    s++;
326
0
  return s;
327
0
}
328
329
static void warn_about_deprecated_remote_type(const char *type,
330
                const struct remote *remote)
331
0
{
332
0
  warning(_("reading remote from \"%s/%s\", which is nominated for removal.\n"
333
0
      "\n"
334
0
      "If you still use the \"remotes/\" directory it is recommended to\n"
335
0
      "migrate to config-based remotes:\n"
336
0
      "\n"
337
0
      "\tgit remote rename %s %s\n"
338
0
      "\n"
339
0
      "If you cannot, please let us know why you still need to use it by\n"
340
0
      "sending an e-mail to <git@vger.kernel.org>."),
341
0
    type, remote->name, remote->name, remote->name);
342
0
}
343
344
static void read_remotes_file(struct repository *repo, struct remote *remote)
345
0
{
346
0
  struct strbuf buf = STRBUF_INIT;
347
0
  FILE *f = fopen_or_warn(repo_git_path_append(repo, &buf,
348
0
                 "remotes/%s", remote->name), "r");
349
350
0
  if (!f)
351
0
    goto out;
352
353
0
  warn_about_deprecated_remote_type("remotes", remote);
354
355
0
  remote->configured_in_repo = 1;
356
0
  remote->origin = REMOTE_REMOTES;
357
0
  while (strbuf_getline(&buf, f) != EOF) {
358
0
    const char *v;
359
360
0
    strbuf_rtrim(&buf);
361
362
0
    if (skip_prefix(buf.buf, "URL:", &v))
363
0
      add_url_alias(repo->remote_state, remote,
364
0
              skip_spaces(v));
365
0
    else if (skip_prefix(buf.buf, "Push:", &v))
366
0
      refspec_append(&remote->push, skip_spaces(v));
367
0
    else if (skip_prefix(buf.buf, "Pull:", &v))
368
0
      refspec_append(&remote->fetch, skip_spaces(v));
369
0
  }
370
0
  fclose(f);
371
372
0
out:
373
0
  strbuf_release(&buf);
374
0
}
375
376
static void read_branches_file(struct repository *repo, struct remote *remote)
377
0
{
378
0
  char *frag, *to_free = NULL;
379
0
  struct strbuf buf = STRBUF_INIT;
380
0
  FILE *f = fopen_or_warn(repo_git_path_append(repo, &buf,
381
0
                 "branches/%s", remote->name), "r");
382
383
0
  if (!f)
384
0
    goto out;
385
386
0
  warn_about_deprecated_remote_type("branches", remote);
387
388
0
  strbuf_getline_lf(&buf, f);
389
0
  fclose(f);
390
0
  strbuf_trim(&buf);
391
0
  if (!buf.len)
392
0
    goto out;
393
394
0
  remote->configured_in_repo = 1;
395
0
  remote->origin = REMOTE_BRANCHES;
396
397
  /*
398
   * The branches file would have URL and optionally
399
   * #branch specified.  The default (or specified) branch is
400
   * fetched and stored in the local branch matching the
401
   * remote name.
402
   */
403
0
  frag = strchr(buf.buf, '#');
404
0
  if (frag)
405
0
    *(frag++) = '\0';
406
0
  else
407
0
    frag = to_free = repo_default_branch_name(repo, 0);
408
409
0
  add_url_alias(repo->remote_state, remote, buf.buf);
410
0
  refspec_appendf(&remote->fetch, "refs/heads/%s:refs/heads/%s",
411
0
      frag, remote->name);
412
413
  /*
414
   * Cogito compatible push: push current HEAD to remote #branch
415
   * (master if missing)
416
   */
417
0
  refspec_appendf(&remote->push, "HEAD:refs/heads/%s", frag);
418
0
  remote->fetch_tags = 1; /* always auto-follow */
419
420
0
out:
421
0
  strbuf_release(&buf);
422
0
  free(to_free);
423
0
}
424
#endif /* WITH_BREAKING_CHANGES */
425
426
static int handle_config(const char *key, const char *value,
427
       const struct config_context *ctx, void *cb)
428
0
{
429
0
  const char *name;
430
0
  size_t namelen;
431
0
  const char *subkey;
432
0
  struct remote *remote;
433
0
  struct branch *branch;
434
0
  struct remote_state *remote_state = cb;
435
0
  const struct key_value_info *kvi = ctx->kvi;
436
437
0
  if (parse_config_key(key, "branch", &name, &namelen, &subkey) >= 0) {
438
    /* There is no subsection. */
439
0
    if (!name)
440
0
      return 0;
441
    /* There is a subsection, but it is empty. */
442
0
    if (!namelen)
443
0
      return -1;
444
0
    branch = make_branch(remote_state, name, namelen);
445
0
    if (!strcmp(subkey, "remote")) {
446
0
      FREE_AND_NULL(branch->remote_name);
447
0
      return git_config_string(&branch->remote_name, key, value);
448
0
    } else if (!strcmp(subkey, "pushremote")) {
449
0
      FREE_AND_NULL(branch->pushremote_name);
450
0
      return git_config_string(&branch->pushremote_name, key, value);
451
0
    } else if (!strcmp(subkey, "merge")) {
452
0
      if (!value)
453
0
        return config_error_nonbool(key);
454
0
      add_merge(branch, value);
455
0
    }
456
0
    return 0;
457
0
  }
458
0
  if (parse_config_key(key, "url", &name, &namelen, &subkey) >= 0) {
459
0
    struct rewrite *rewrite;
460
0
    if (!name)
461
0
      return 0;
462
0
    if (!strcmp(subkey, "insteadof")) {
463
0
      if (!value)
464
0
        return config_error_nonbool(key);
465
0
      rewrite = make_rewrite(&remote_state->rewrites, name,
466
0
                 namelen);
467
0
      add_instead_of(rewrite, xstrdup(value));
468
0
    } else if (!strcmp(subkey, "pushinsteadof")) {
469
0
      if (!value)
470
0
        return config_error_nonbool(key);
471
0
      rewrite = make_rewrite(&remote_state->rewrites_push,
472
0
                 name, namelen);
473
0
      add_instead_of(rewrite, xstrdup(value));
474
0
    }
475
0
  }
476
477
0
  if (parse_config_key(key, "remote", &name, &namelen, &subkey) < 0)
478
0
    return 0;
479
480
  /* Handle remote.* variables */
481
0
  if (!name && !strcmp(subkey, "pushdefault")) {
482
0
    FREE_AND_NULL(remote_state->pushremote_name);
483
0
    return git_config_string(&remote_state->pushremote_name, key,
484
0
           value);
485
0
  }
486
487
0
  if (!name)
488
0
    return 0;
489
  /* Handle remote.<name>.* variables */
490
0
  if (*name == '/') {
491
0
    warning(_("config remote shorthand cannot begin with '/': %s"),
492
0
      name);
493
0
    return 0;
494
0
  }
495
0
  remote = make_remote(remote_state, name, namelen);
496
0
  remote->origin = REMOTE_CONFIG;
497
0
  if (kvi->scope == CONFIG_SCOPE_LOCAL ||
498
0
      kvi->scope == CONFIG_SCOPE_WORKTREE)
499
0
    remote->configured_in_repo = 1;
500
0
  if (!strcmp(subkey, "mirror"))
501
0
    remote->mirror = git_config_bool(key, value);
502
0
  else if (!strcmp(subkey, "skipdefaultupdate"))
503
0
    remote->skip_default_update = git_config_bool(key, value);
504
0
  else if (!strcmp(subkey, "skipfetchall"))
505
0
    remote->skip_default_update = git_config_bool(key, value);
506
0
  else if (!strcmp(subkey, "prune"))
507
0
    remote->prune = git_config_bool(key, value);
508
0
  else if (!strcmp(subkey, "prunetags"))
509
0
    remote->prune_tags = git_config_bool(key, value);
510
0
  else if (!strcmp(subkey, "url")) {
511
0
    if (!value)
512
0
      return config_error_nonbool(key);
513
0
    add_url(remote, value);
514
0
  } else if (!strcmp(subkey, "pushurl")) {
515
0
    if (!value)
516
0
      return config_error_nonbool(key);
517
0
    add_pushurl(remote, value);
518
0
  } else if (!strcmp(subkey, "push")) {
519
0
    char *v;
520
0
    if (git_config_string(&v, key, value))
521
0
      return -1;
522
0
    refspec_append(&remote->push, v);
523
0
    free(v);
524
0
  } else if (!strcmp(subkey, "fetch")) {
525
0
    char *v;
526
0
    if (git_config_string(&v, key, value))
527
0
      return -1;
528
0
    refspec_append(&remote->fetch, v);
529
0
    free(v);
530
0
  } else if (!strcmp(subkey, "receivepack")) {
531
0
    char *v;
532
0
    if (git_config_string(&v, key, value))
533
0
      return -1;
534
0
    if (!remote->receivepack)
535
0
      remote->receivepack = v;
536
0
    else
537
0
      error(_("more than one receivepack given, using the first"));
538
0
  } else if (!strcmp(subkey, "uploadpack")) {
539
0
    char *v;
540
0
    if (git_config_string(&v, key, value))
541
0
      return -1;
542
0
    if (!remote->uploadpack)
543
0
      remote->uploadpack = v;
544
0
    else
545
0
      error(_("more than one uploadpack given, using the first"));
546
0
  } else if (!strcmp(subkey, "tagopt")) {
547
0
    if (!strcmp(value, "--no-tags"))
548
0
      remote->fetch_tags = -1;
549
0
    else if (!strcmp(value, "--tags"))
550
0
      remote->fetch_tags = 2;
551
0
  } else if (!strcmp(subkey, "proxy")) {
552
0
    FREE_AND_NULL(remote->http_proxy);
553
0
    return git_config_string(&remote->http_proxy,
554
0
           key, value);
555
0
  } else if (!strcmp(subkey, "proxyauthmethod")) {
556
0
    FREE_AND_NULL(remote->http_proxy_authmethod);
557
0
    return git_config_string(&remote->http_proxy_authmethod,
558
0
           key, value);
559
0
  } else if (!strcmp(subkey, "vcs")) {
560
0
    FREE_AND_NULL(remote->foreign_vcs);
561
0
    return git_config_string(&remote->foreign_vcs, key, value);
562
0
  } else if (!strcmp(subkey, "serveroption")) {
563
0
    return parse_transport_option(key, value,
564
0
                &remote->server_options);
565
0
  } else if (!strcmp(subkey, "followremotehead")) {
566
0
    const char *no_warn_branch;
567
0
    if (!strcmp(value, "never"))
568
0
      remote->follow_remote_head = FOLLOW_REMOTE_NEVER;
569
0
    else if (!strcmp(value, "create"))
570
0
      remote->follow_remote_head = FOLLOW_REMOTE_CREATE;
571
0
    else if (!strcmp(value, "warn")) {
572
0
      remote->follow_remote_head = FOLLOW_REMOTE_WARN;
573
0
      remote->no_warn_branch = NULL;
574
0
    } else if (skip_prefix(value, "warn-if-not-", &no_warn_branch)) {
575
0
      remote->follow_remote_head = FOLLOW_REMOTE_WARN;
576
0
      remote->no_warn_branch = no_warn_branch;
577
0
    } else if (!strcmp(value, "always")) {
578
0
      remote->follow_remote_head = FOLLOW_REMOTE_ALWAYS;
579
0
    } else {
580
0
      warning(_("unrecognized followRemoteHEAD value '%s' ignored"),
581
0
        value);
582
0
    }
583
0
  }
584
0
  return 0;
585
0
}
586
587
static void alias_all_urls(struct remote_state *remote_state)
588
0
{
589
0
  int i, j;
590
0
  for (i = 0; i < remote_state->remotes_nr; i++) {
591
0
    int add_pushurl_aliases;
592
0
    if (!remote_state->remotes[i])
593
0
      continue;
594
0
    for (j = 0; j < remote_state->remotes[i]->pushurl.nr; j++) {
595
0
      char *alias = alias_url(remote_state->remotes[i]->pushurl.v[j],
596
0
            &remote_state->rewrites);
597
0
      if (alias)
598
0
        strvec_replace(&remote_state->remotes[i]->pushurl,
599
0
                 j, alias);
600
0
      free(alias);
601
0
    }
602
0
    add_pushurl_aliases = remote_state->remotes[i]->pushurl.nr == 0;
603
0
    for (j = 0; j < remote_state->remotes[i]->url.nr; j++) {
604
0
      char *alias;
605
0
      if (add_pushurl_aliases)
606
0
        add_pushurl_alias(
607
0
          remote_state, remote_state->remotes[i],
608
0
          remote_state->remotes[i]->url.v[j]);
609
0
      alias = alias_url(remote_state->remotes[i]->url.v[j],
610
0
            &remote_state->rewrites);
611
0
      if (alias)
612
0
        strvec_replace(&remote_state->remotes[i]->url,
613
0
                 j, alias);
614
0
      free(alias);
615
0
    }
616
0
  }
617
0
}
618
619
static void read_config(struct repository *repo, int early)
620
0
{
621
0
  int flag;
622
623
0
  if (repo->remote_state->initialized)
624
0
    return;
625
0
  repo->remote_state->initialized = 1;
626
627
0
  repo->remote_state->current_branch = NULL;
628
0
  if (startup_info->have_repository && !early) {
629
0
    const char *head_ref = refs_resolve_ref_unsafe(
630
0
      get_main_ref_store(repo), "HEAD", 0, NULL, &flag);
631
0
    if (head_ref && (flag & REF_ISSYMREF) &&
632
0
        skip_prefix(head_ref, "refs/heads/", &head_ref)) {
633
0
      repo->remote_state->current_branch = make_branch(
634
0
        repo->remote_state, head_ref, strlen(head_ref));
635
0
    }
636
0
  }
637
0
  repo_config(repo, handle_config, repo->remote_state);
638
0
  alias_all_urls(repo->remote_state);
639
0
}
640
641
#ifndef WITH_BREAKING_CHANGES
642
static int valid_remote_nick(const char *name)
643
0
{
644
0
  if (!name[0] || is_dot_or_dotdot(name))
645
0
    return 0;
646
647
  /* remote nicknames cannot contain slashes */
648
0
  while (*name)
649
0
    if (is_dir_sep(*name++))
650
0
      return 0;
651
0
  return 1;
652
0
}
653
#endif /* WITH_BREAKING_CHANGES */
654
655
static const char *remotes_remote_for_branch(struct remote_state *remote_state,
656
               struct branch *branch,
657
               int *explicit)
658
0
{
659
0
  if (branch && branch->remote_name) {
660
0
    if (explicit)
661
0
      *explicit = 1;
662
0
    return branch->remote_name;
663
0
  }
664
0
  if (explicit)
665
0
    *explicit = 0;
666
0
  if (remote_state->remotes_nr == 1)
667
0
    return remote_state->remotes[0]->name;
668
0
  return "origin";
669
0
}
670
671
const char *remote_for_branch(struct branch *branch, int *explicit)
672
0
{
673
0
  read_config(the_repository, 0);
674
0
  die_on_missing_branch(the_repository, branch);
675
676
0
  return remotes_remote_for_branch(the_repository->remote_state, branch,
677
0
           explicit);
678
0
}
679
680
static const char *
681
remotes_pushremote_for_branch(struct remote_state *remote_state,
682
            struct branch *branch, int *explicit)
683
0
{
684
0
  if (branch && branch->pushremote_name) {
685
0
    if (explicit)
686
0
      *explicit = 1;
687
0
    return branch->pushremote_name;
688
0
  }
689
0
  if (remote_state->pushremote_name) {
690
0
    if (explicit)
691
0
      *explicit = 1;
692
0
    return remote_state->pushremote_name;
693
0
  }
694
0
  return remotes_remote_for_branch(remote_state, branch, explicit);
695
0
}
696
697
const char *pushremote_for_branch(struct branch *branch, int *explicit)
698
0
{
699
0
  read_config(the_repository, 0);
700
0
  die_on_missing_branch(the_repository, branch);
701
702
0
  return remotes_pushremote_for_branch(the_repository->remote_state,
703
0
               branch, explicit);
704
0
}
705
706
static struct remote *remotes_remote_get(struct repository *repo,
707
           const char *name);
708
709
char *remote_ref_for_branch(struct branch *branch, int for_push)
710
0
{
711
0
  read_config(the_repository, 0);
712
0
  die_on_missing_branch(the_repository, branch);
713
714
0
  if (branch) {
715
0
    if (!for_push) {
716
0
      if (branch->merge_nr) {
717
0
        return xstrdup(branch->merge[0]->src);
718
0
      }
719
0
    } else {
720
0
      char *dst;
721
0
      const char *remote_name = remotes_pushremote_for_branch(
722
0
          the_repository->remote_state, branch,
723
0
          NULL);
724
0
      struct remote *remote = remotes_remote_get(
725
0
        the_repository, remote_name);
726
727
0
      if (remote && remote->push.nr &&
728
0
          (dst = apply_refspecs(&remote->push,
729
0
              branch->refname))) {
730
0
        return dst;
731
0
      }
732
0
    }
733
0
  }
734
0
  return NULL;
735
0
}
736
737
static void validate_remote_url(struct remote *remote)
738
0
{
739
0
  int i;
740
0
  const char *value;
741
0
  struct strbuf redacted = STRBUF_INIT;
742
0
  int warn_not_die;
743
744
0
  if (repo_config_get_string_tmp(the_repository, "transfer.credentialsinurl", &value))
745
0
    return;
746
747
0
  if (!strcmp("warn", value))
748
0
    warn_not_die = 1;
749
0
  else if (!strcmp("die", value))
750
0
    warn_not_die = 0;
751
0
  else if (!strcmp("allow", value))
752
0
    return;
753
0
  else
754
0
    die(_("unrecognized value transfer.credentialsInUrl: '%s'"), value);
755
756
0
  for (i = 0; i < remote->url.nr; i++) {
757
0
    struct url_info url_info = { 0 };
758
759
0
    if (!url_normalize(remote->url.v[i], &url_info) ||
760
0
        !url_info.passwd_off)
761
0
      goto loop_cleanup;
762
763
0
    strbuf_reset(&redacted);
764
0
    strbuf_add(&redacted, url_info.url, url_info.passwd_off);
765
0
    strbuf_addstr(&redacted, "<redacted>");
766
0
    strbuf_addstr(&redacted,
767
0
            url_info.url + url_info.passwd_off + url_info.passwd_len);
768
769
0
    if (warn_not_die)
770
0
      warning(_("URL '%s' uses plaintext credentials"), redacted.buf);
771
0
    else
772
0
      die(_("URL '%s' uses plaintext credentials"), redacted.buf);
773
774
0
loop_cleanup:
775
0
    free(url_info.url);
776
0
  }
777
778
0
  strbuf_release(&redacted);
779
0
}
780
781
static struct remote *
782
remotes_remote_get_1(struct repository *repo, const char *name,
783
         const char *(*get_default)(struct remote_state *,
784
            struct branch *, int *))
785
0
{
786
0
  struct remote_state *remote_state = repo->remote_state;
787
0
  struct remote *ret;
788
0
  int name_given = 0;
789
790
0
  if (name)
791
0
    name_given = 1;
792
0
  else
793
0
    name = get_default(remote_state, remote_state->current_branch,
794
0
           &name_given);
795
796
0
  ret = make_remote(remote_state, name, 0);
797
0
#ifndef WITH_BREAKING_CHANGES
798
0
  if (valid_remote_nick(name) && have_git_dir()) {
799
0
    if (!valid_remote(ret))
800
0
      read_remotes_file(repo, ret);
801
0
    if (!valid_remote(ret))
802
0
      read_branches_file(repo, ret);
803
0
  }
804
0
#endif /* WITH_BREAKING_CHANGES */
805
0
  if (name_given && !valid_remote(ret))
806
0
    add_url_alias(remote_state, ret, name);
807
0
  if (!valid_remote(ret))
808
0
    return NULL;
809
810
0
  validate_remote_url(ret);
811
812
0
  return ret;
813
0
}
814
815
static inline struct remote *
816
remotes_remote_get(struct repository *repo, const char *name)
817
0
{
818
0
  return remotes_remote_get_1(repo, name, remotes_remote_for_branch);
819
0
}
820
821
struct remote *remote_get(const char *name)
822
0
{
823
0
  read_config(the_repository, 0);
824
0
  return remotes_remote_get(the_repository, name);
825
0
}
826
827
struct remote *remote_get_early(const char *name)
828
0
{
829
0
  read_config(the_repository, 1);
830
0
  return remotes_remote_get(the_repository, name);
831
0
}
832
833
static inline struct remote *
834
remotes_pushremote_get(struct repository *repo, const char *name)
835
0
{
836
0
  return remotes_remote_get_1(repo, name, remotes_pushremote_for_branch);
837
0
}
838
839
struct remote *pushremote_get(const char *name)
840
0
{
841
0
  read_config(the_repository, 0);
842
0
  return remotes_pushremote_get(the_repository, name);
843
0
}
844
845
int remote_is_configured(struct remote *remote, int in_repo)
846
0
{
847
0
  if (!remote)
848
0
    return 0;
849
0
  if (in_repo)
850
0
    return remote->configured_in_repo;
851
0
  return !!remote->origin;
852
0
}
853
854
int for_each_remote(each_remote_fn fn, void *priv)
855
0
{
856
0
  int i, result = 0;
857
0
  read_config(the_repository, 0);
858
0
  for (i = 0; i < the_repository->remote_state->remotes_nr && !result;
859
0
       i++) {
860
0
    struct remote *remote =
861
0
      the_repository->remote_state->remotes[i];
862
0
    if (!remote)
863
0
      continue;
864
0
    result = fn(remote, priv);
865
0
  }
866
0
  return result;
867
0
}
868
869
static void handle_duplicate(struct ref *ref1, struct ref *ref2)
870
0
{
871
0
  if (strcmp(ref1->name, ref2->name)) {
872
0
    if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
873
0
        ref2->fetch_head_status != FETCH_HEAD_IGNORE) {
874
0
      die(_("Cannot fetch both %s and %s to %s"),
875
0
          ref1->name, ref2->name, ref2->peer_ref->name);
876
0
    } else if (ref1->fetch_head_status != FETCH_HEAD_IGNORE &&
877
0
         ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
878
0
      warning(_("%s usually tracks %s, not %s"),
879
0
        ref2->peer_ref->name, ref2->name, ref1->name);
880
0
    } else if (ref1->fetch_head_status == FETCH_HEAD_IGNORE &&
881
0
         ref2->fetch_head_status == FETCH_HEAD_IGNORE) {
882
0
      die(_("%s tracks both %s and %s"),
883
0
          ref2->peer_ref->name, ref1->name, ref2->name);
884
0
    } else {
885
      /*
886
       * This last possibility doesn't occur because
887
       * FETCH_HEAD_IGNORE entries always appear at
888
       * the end of the list.
889
       */
890
0
      BUG("Internal error");
891
0
    }
892
0
  }
893
0
  free(ref2->peer_ref);
894
0
  free(ref2);
895
0
}
896
897
struct ref *ref_remove_duplicates(struct ref *ref_map)
898
0
{
899
0
  struct string_list refs = STRING_LIST_INIT_NODUP;
900
0
  struct ref *retval = NULL;
901
0
  struct ref **p = &retval;
902
903
0
  while (ref_map) {
904
0
    struct ref *ref = ref_map;
905
906
0
    ref_map = ref_map->next;
907
0
    ref->next = NULL;
908
909
0
    if (!ref->peer_ref) {
910
0
      *p = ref;
911
0
      p = &ref->next;
912
0
    } else {
913
0
      struct string_list_item *item =
914
0
        string_list_insert(&refs, ref->peer_ref->name);
915
916
0
      if (item->util) {
917
        /* Entry already existed */
918
0
        handle_duplicate((struct ref *)item->util, ref);
919
0
      } else {
920
0
        *p = ref;
921
0
        p = &ref->next;
922
0
        item->util = ref;
923
0
      }
924
0
    }
925
0
  }
926
927
0
  string_list_clear(&refs, 0);
928
0
  return retval;
929
0
}
930
931
int remote_has_url(struct remote *remote, const char *url)
932
0
{
933
0
  int i;
934
0
  for (i = 0; i < remote->url.nr; i++) {
935
0
    if (!strcmp(remote->url.v[i], url))
936
0
      return 1;
937
0
  }
938
0
  return 0;
939
0
}
940
941
struct strvec *push_url_of_remote(struct remote *remote)
942
0
{
943
0
  return remote->pushurl.nr ? &remote->pushurl : &remote->url;
944
0
}
945
946
void ref_push_report_free(struct ref_push_report *report)
947
0
{
948
0
  while (report) {
949
0
    struct ref_push_report *next = report->next;
950
951
0
    free(report->ref_name);
952
0
    free(report->old_oid);
953
0
    free(report->new_oid);
954
0
    free(report);
955
956
0
    report = next;
957
0
  }
958
0
}
959
960
int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
961
0
{
962
0
  return refspec_find_match(&remote->fetch, refspec);
963
0
}
964
965
static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
966
    const char *name)
967
0
{
968
0
  size_t len = strlen(name);
969
0
  struct ref *ref = xcalloc(1, st_add4(sizeof(*ref), prefixlen, len, 1));
970
0
  memcpy(ref->name, prefix, prefixlen);
971
0
  memcpy(ref->name + prefixlen, name, len);
972
0
  return ref;
973
0
}
974
975
struct ref *alloc_ref(const char *name)
976
0
{
977
0
  return alloc_ref_with_prefix("", 0, name);
978
0
}
979
980
struct ref *copy_ref(const struct ref *ref)
981
0
{
982
0
  struct ref *cpy;
983
0
  size_t len;
984
0
  if (!ref)
985
0
    return NULL;
986
0
  len = st_add3(sizeof(struct ref), strlen(ref->name), 1);
987
0
  cpy = xmalloc(len);
988
0
  memcpy(cpy, ref, len);
989
0
  cpy->next = NULL;
990
0
  cpy->symref = xstrdup_or_null(ref->symref);
991
0
  cpy->remote_status = xstrdup_or_null(ref->remote_status);
992
0
  cpy->peer_ref = copy_ref(ref->peer_ref);
993
0
  return cpy;
994
0
}
995
996
struct ref *copy_ref_list(const struct ref *ref)
997
0
{
998
0
  struct ref *ret = NULL;
999
0
  struct ref **tail = &ret;
1000
0
  while (ref) {
1001
0
    *tail = copy_ref(ref);
1002
0
    ref = ref->next;
1003
0
    tail = &((*tail)->next);
1004
0
  }
1005
0
  return ret;
1006
0
}
1007
1008
void free_one_ref(struct ref *ref)
1009
0
{
1010
0
  if (!ref)
1011
0
    return;
1012
0
  free_one_ref(ref->peer_ref);
1013
0
  ref_push_report_free(ref->report);
1014
0
  free(ref->remote_status);
1015
0
  free(ref->tracking_ref);
1016
0
  free(ref->symref);
1017
0
  free(ref);
1018
0
}
1019
1020
void free_refs(struct ref *ref)
1021
0
{
1022
0
  struct ref *next;
1023
0
  while (ref) {
1024
0
    next = ref->next;
1025
0
    free_one_ref(ref);
1026
0
    ref = next;
1027
0
  }
1028
0
}
1029
1030
int count_refspec_match(const char *pattern,
1031
      struct ref *refs,
1032
      struct ref **matched_ref)
1033
0
{
1034
0
  int patlen = strlen(pattern);
1035
0
  struct ref *matched_weak = NULL;
1036
0
  struct ref *matched = NULL;
1037
0
  int weak_match = 0;
1038
0
  int match = 0;
1039
1040
0
  for (weak_match = match = 0; refs; refs = refs->next) {
1041
0
    char *name = refs->name;
1042
0
    int namelen = strlen(name);
1043
1044
0
    if (!refname_match(pattern, name))
1045
0
      continue;
1046
1047
    /* A match is "weak" if it is with refs outside
1048
     * heads or tags, and did not specify the pattern
1049
     * in full (e.g. "refs/remotes/origin/master") or at
1050
     * least from the toplevel (e.g. "remotes/origin/master");
1051
     * otherwise "git push $URL master" would result in
1052
     * ambiguity between remotes/origin/master and heads/master
1053
     * at the remote site.
1054
     */
1055
0
    if (namelen != patlen &&
1056
0
        patlen != namelen - 5 &&
1057
0
        !starts_with(name, "refs/heads/") &&
1058
0
        !starts_with(name, "refs/tags/")) {
1059
      /* We want to catch the case where only weak
1060
       * matches are found and there are multiple
1061
       * matches, and where more than one strong
1062
       * matches are found, as ambiguous.  One
1063
       * strong match with zero or more weak matches
1064
       * are acceptable as a unique match.
1065
       */
1066
0
      matched_weak = refs;
1067
0
      weak_match++;
1068
0
    }
1069
0
    else {
1070
0
      matched = refs;
1071
0
      match++;
1072
0
    }
1073
0
  }
1074
0
  if (!matched) {
1075
0
    if (matched_ref)
1076
0
      *matched_ref = matched_weak;
1077
0
    return weak_match;
1078
0
  }
1079
0
  else {
1080
0
    if (matched_ref)
1081
0
      *matched_ref = matched;
1082
0
    return match;
1083
0
  }
1084
0
}
1085
1086
void tail_link_ref(struct ref *ref, struct ref ***tail)
1087
0
{
1088
0
  **tail = ref;
1089
0
  while (ref->next)
1090
0
    ref = ref->next;
1091
0
  *tail = &ref->next;
1092
0
}
1093
1094
static struct ref *alloc_delete_ref(void)
1095
0
{
1096
0
  struct ref *ref = alloc_ref("(delete)");
1097
0
  oidclr(&ref->new_oid, the_repository->hash_algo);
1098
0
  return ref;
1099
0
}
1100
1101
static int try_explicit_object_name(const char *name,
1102
            struct ref **match)
1103
0
{
1104
0
  struct object_id oid;
1105
1106
0
  if (!*name) {
1107
0
    if (match)
1108
0
      *match = alloc_delete_ref();
1109
0
    return 0;
1110
0
  }
1111
1112
0
  if (repo_get_oid(the_repository, name, &oid))
1113
0
    return -1;
1114
1115
0
  if (match) {
1116
0
    *match = alloc_ref(name);
1117
0
    oidcpy(&(*match)->new_oid, &oid);
1118
0
  }
1119
0
  return 0;
1120
0
}
1121
1122
static struct ref *make_linked_ref(const char *name, struct ref ***tail)
1123
0
{
1124
0
  struct ref *ret = alloc_ref(name);
1125
0
  tail_link_ref(ret, tail);
1126
0
  return ret;
1127
0
}
1128
1129
static char *guess_ref(const char *name, struct ref *peer)
1130
0
{
1131
0
  struct strbuf buf = STRBUF_INIT;
1132
1133
0
  const char *r = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1134
0
            peer->name,
1135
0
            RESOLVE_REF_READING,
1136
0
            NULL, NULL);
1137
0
  if (!r)
1138
0
    return NULL;
1139
1140
0
  if (starts_with(r, "refs/heads/")) {
1141
0
    strbuf_addstr(&buf, "refs/heads/");
1142
0
  } else if (starts_with(r, "refs/tags/")) {
1143
0
    strbuf_addstr(&buf, "refs/tags/");
1144
0
  } else {
1145
0
    return NULL;
1146
0
  }
1147
1148
0
  strbuf_addstr(&buf, name);
1149
0
  return strbuf_detach(&buf, NULL);
1150
0
}
1151
1152
static int match_explicit_lhs(struct ref *src,
1153
            struct refspec_item *rs,
1154
            struct ref **match,
1155
            int *allocated_match)
1156
0
{
1157
0
  switch (count_refspec_match(rs->src, src, match)) {
1158
0
  case 1:
1159
0
    if (allocated_match)
1160
0
      *allocated_match = 0;
1161
0
    return 0;
1162
0
  case 0:
1163
    /* The source could be in the get_sha1() format
1164
     * not a reference name.  :refs/other is a
1165
     * way to delete 'other' ref at the remote end.
1166
     */
1167
0
    if (try_explicit_object_name(rs->src, match) < 0)
1168
0
      return error(_("src refspec %s does not match any"), rs->src);
1169
0
    if (allocated_match)
1170
0
      *allocated_match = 1;
1171
0
    return 0;
1172
0
  default:
1173
0
    return error(_("src refspec %s matches more than one"), rs->src);
1174
0
  }
1175
0
}
1176
1177
static void show_push_unqualified_ref_name_error(const char *dst_value,
1178
             const char *matched_src_name)
1179
0
{
1180
0
  struct object_id oid;
1181
1182
  /*
1183
   * TRANSLATORS: "matches '%s'%" is the <dst> part of "git push
1184
   * <remote> <src>:<dst>" push, and "being pushed ('%s')" is
1185
   * the <src>.
1186
   */
1187
0
  error(_("The destination you provided is not a full refname (i.e.,\n"
1188
0
    "starting with \"refs/\"). We tried to guess what you meant by:\n"
1189
0
    "\n"
1190
0
    "- Looking for a ref that matches '%s' on the remote side.\n"
1191
0
    "- Checking if the <src> being pushed ('%s')\n"
1192
0
    "  is a ref in \"refs/{heads,tags}/\". If so we add a corresponding\n"
1193
0
    "  refs/{heads,tags}/ prefix on the remote side.\n"
1194
0
    "\n"
1195
0
    "Neither worked, so we gave up. You must fully qualify the ref."),
1196
0
        dst_value, matched_src_name);
1197
1198
0
  if (!advice_enabled(ADVICE_PUSH_UNQUALIFIED_REF_NAME))
1199
0
    return;
1200
1201
0
  if (repo_get_oid(the_repository, matched_src_name, &oid))
1202
0
    BUG("'%s' is not a valid object, "
1203
0
        "match_explicit_lhs() should catch this!",
1204
0
        matched_src_name);
1205
1206
0
  switch (odb_read_object_info(the_repository->objects, &oid, NULL)) {
1207
0
  case OBJ_COMMIT:
1208
0
    advise(_("The <src> part of the refspec is a commit object.\n"
1209
0
       "Did you mean to create a new branch by pushing to\n"
1210
0
       "'%s:refs/heads/%s'?"),
1211
0
           matched_src_name, dst_value);
1212
0
    break;
1213
0
  case OBJ_TAG:
1214
0
    advise(_("The <src> part of the refspec is a tag object.\n"
1215
0
       "Did you mean to create a new tag by pushing to\n"
1216
0
       "'%s:refs/tags/%s'?"),
1217
0
           matched_src_name, dst_value);
1218
0
    break;
1219
0
  case OBJ_TREE:
1220
0
    advise(_("The <src> part of the refspec is a tree object.\n"
1221
0
       "Did you mean to tag a new tree by pushing to\n"
1222
0
       "'%s:refs/tags/%s'?"),
1223
0
           matched_src_name, dst_value);
1224
0
    break;
1225
0
  case OBJ_BLOB:
1226
0
    advise(_("The <src> part of the refspec is a blob object.\n"
1227
0
       "Did you mean to tag a new blob by pushing to\n"
1228
0
       "'%s:refs/tags/%s'?"),
1229
0
           matched_src_name, dst_value);
1230
0
    break;
1231
0
  default:
1232
0
    advise(_("The <src> part of the refspec ('%s') "
1233
0
       "is an object ID that doesn't exist.\n"),
1234
0
           matched_src_name);
1235
0
    break;
1236
0
  }
1237
0
}
1238
1239
static int match_explicit(struct ref *src, struct ref *dst,
1240
        struct ref ***dst_tail,
1241
        struct refspec_item *rs)
1242
0
{
1243
0
  struct ref *matched_src = NULL, *matched_dst = NULL;
1244
0
  int allocated_src = 0, ret;
1245
1246
0
  const char *dst_value = rs->dst;
1247
0
  char *dst_guess;
1248
1249
0
  if (rs->pattern || rs->matching || rs->negative) {
1250
0
    ret = 0;
1251
0
    goto out;
1252
0
  }
1253
1254
0
  if (match_explicit_lhs(src, rs, &matched_src, &allocated_src) < 0) {
1255
0
    ret = -1;
1256
0
    goto out;
1257
0
  }
1258
1259
0
  if (!dst_value) {
1260
0
    int flag;
1261
1262
0
    dst_value = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1263
0
                matched_src->name,
1264
0
                RESOLVE_REF_READING,
1265
0
                NULL, &flag);
1266
0
    if (!dst_value ||
1267
0
        ((flag & REF_ISSYMREF) &&
1268
0
         !starts_with(dst_value, "refs/heads/")))
1269
0
      die(_("%s cannot be resolved to branch"),
1270
0
          matched_src->name);
1271
0
  }
1272
1273
0
  switch (count_refspec_match(dst_value, dst, &matched_dst)) {
1274
0
  case 1:
1275
0
    break;
1276
0
  case 0:
1277
0
    if (starts_with(dst_value, "refs/")) {
1278
0
      matched_dst = make_linked_ref(dst_value, dst_tail);
1279
0
    } else if (is_null_oid(&matched_src->new_oid)) {
1280
0
      error(_("unable to delete '%s': remote ref does not exist"),
1281
0
            dst_value);
1282
0
    } else if ((dst_guess = guess_ref(dst_value, matched_src))) {
1283
0
      matched_dst = make_linked_ref(dst_guess, dst_tail);
1284
0
      free(dst_guess);
1285
0
    } else {
1286
0
      show_push_unqualified_ref_name_error(dst_value,
1287
0
                   matched_src->name);
1288
0
    }
1289
0
    break;
1290
0
  default:
1291
0
    matched_dst = NULL;
1292
0
    error(_("dst refspec %s matches more than one"),
1293
0
          dst_value);
1294
0
    break;
1295
0
  }
1296
1297
0
  if (!matched_dst) {
1298
0
    ret = -1;
1299
0
    goto out;
1300
0
  }
1301
1302
0
  if (matched_dst->peer_ref) {
1303
0
    ret = error(_("dst ref %s receives from more than one src"),
1304
0
          matched_dst->name);
1305
0
    goto out;
1306
0
  } else {
1307
0
    matched_dst->peer_ref = allocated_src ?
1308
0
          matched_src :
1309
0
          copy_ref(matched_src);
1310
0
    matched_dst->force = rs->force;
1311
0
    matched_src = NULL;
1312
0
  }
1313
1314
0
  ret = 0;
1315
1316
0
out:
1317
0
  if (allocated_src)
1318
0
    free_one_ref(matched_src);
1319
0
  return ret;
1320
0
}
1321
1322
static int match_explicit_refs(struct ref *src, struct ref *dst,
1323
             struct ref ***dst_tail, struct refspec *rs)
1324
0
{
1325
0
  int i, errs;
1326
0
  for (i = errs = 0; i < rs->nr; i++)
1327
0
    errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
1328
0
  return errs;
1329
0
}
1330
1331
static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
1332
         int send_mirror, int direction,
1333
         const struct refspec_item **ret_pat)
1334
0
{
1335
0
  const struct refspec_item *pat;
1336
0
  char *name;
1337
0
  int i;
1338
0
  int matching_refs = -1;
1339
0
  for (i = 0; i < rs->nr; i++) {
1340
0
    const struct refspec_item *item = &rs->items[i];
1341
1342
0
    if (item->negative)
1343
0
      continue;
1344
1345
0
    if (item->matching &&
1346
0
        (matching_refs == -1 || item->force)) {
1347
0
      matching_refs = i;
1348
0
      continue;
1349
0
    }
1350
1351
0
    if (item->pattern) {
1352
0
      const char *dst_side = item->dst ? item->dst : item->src;
1353
0
      int match;
1354
0
      if (direction == FROM_SRC)
1355
0
        match = match_refname_with_pattern(item->src, ref->name, dst_side, &name);
1356
0
      else
1357
0
        match = match_refname_with_pattern(dst_side, ref->name, item->src, &name);
1358
0
      if (match) {
1359
0
        matching_refs = i;
1360
0
        break;
1361
0
      }
1362
0
    }
1363
0
  }
1364
0
  if (matching_refs == -1)
1365
0
    return NULL;
1366
1367
0
  pat = &rs->items[matching_refs];
1368
0
  if (pat->matching) {
1369
    /*
1370
     * "matching refs"; traditionally we pushed everything
1371
     * including refs outside refs/heads/ hierarchy, but
1372
     * that does not make much sense these days.
1373
     */
1374
0
    if (!send_mirror && !starts_with(ref->name, "refs/heads/"))
1375
0
      return NULL;
1376
0
    name = xstrdup(ref->name);
1377
0
  }
1378
0
  if (ret_pat)
1379
0
    *ret_pat = pat;
1380
0
  return name;
1381
0
}
1382
1383
static struct ref **tail_ref(struct ref **head)
1384
0
{
1385
0
  struct ref **tail = head;
1386
0
  while (*tail)
1387
0
    tail = &((*tail)->next);
1388
0
  return tail;
1389
0
}
1390
1391
static void add_to_tips(struct commit_stack *tips, const struct object_id *oid)
1392
0
{
1393
0
  struct commit *commit;
1394
1395
0
  if (is_null_oid(oid))
1396
0
    return;
1397
0
  commit = lookup_commit_reference_gently(the_repository, oid, 1);
1398
0
  if (!commit || (commit->object.flags & TMP_MARK))
1399
0
    return;
1400
0
  commit->object.flags |= TMP_MARK;
1401
0
  commit_stack_push(tips, commit);
1402
0
}
1403
1404
static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***dst_tail)
1405
0
{
1406
0
  struct string_list dst_tag = STRING_LIST_INIT_NODUP;
1407
0
  struct string_list src_tag = STRING_LIST_INIT_NODUP;
1408
0
  struct string_list_item *item;
1409
0
  struct ref *ref;
1410
0
  struct commit_stack sent_tips = COMMIT_STACK_INIT;
1411
1412
  /*
1413
   * Collect everything we know they would have at the end of
1414
   * this push, and collect all tags they have.
1415
   */
1416
0
  for (ref = *dst; ref; ref = ref->next) {
1417
0
    if (ref->peer_ref &&
1418
0
        !is_null_oid(&ref->peer_ref->new_oid))
1419
0
      add_to_tips(&sent_tips, &ref->peer_ref->new_oid);
1420
0
    else
1421
0
      add_to_tips(&sent_tips, &ref->old_oid);
1422
0
    if (starts_with(ref->name, "refs/tags/"))
1423
0
      string_list_append(&dst_tag, ref->name);
1424
0
  }
1425
0
  clear_commit_marks_many(sent_tips.nr, sent_tips.items, TMP_MARK);
1426
1427
0
  string_list_sort(&dst_tag);
1428
1429
  /* Collect tags they do not have. */
1430
0
  for (ref = src; ref; ref = ref->next) {
1431
0
    if (!starts_with(ref->name, "refs/tags/"))
1432
0
      continue; /* not a tag */
1433
0
    if (string_list_has_string(&dst_tag, ref->name))
1434
0
      continue; /* they already have it */
1435
0
    if (odb_read_object_info(the_repository->objects,
1436
0
           &ref->new_oid, NULL) != OBJ_TAG)
1437
0
      continue; /* be conservative */
1438
0
    item = string_list_append(&src_tag, ref->name);
1439
0
    item->util = ref;
1440
0
  }
1441
0
  string_list_clear(&dst_tag, 0);
1442
1443
  /*
1444
   * At this point, src_tag lists tags that are missing from
1445
   * dst, and sent_tips lists the tips we are pushing or those
1446
   * that we know they already have. An element in the src_tag
1447
   * that is an ancestor of any of the sent_tips needs to be
1448
   * sent to the other side.
1449
   */
1450
0
  if (sent_tips.nr) {
1451
0
    const int reachable_flag = 1;
1452
0
    struct commit_list *found_commits;
1453
0
    struct commit_stack src_commits = COMMIT_STACK_INIT;
1454
1455
0
    for_each_string_list_item(item, &src_tag) {
1456
0
      struct ref *ref = item->util;
1457
0
      struct commit *commit;
1458
1459
0
      if (is_null_oid(&ref->new_oid))
1460
0
        continue;
1461
0
      commit = lookup_commit_reference_gently(the_repository,
1462
0
                &ref->new_oid,
1463
0
                1);
1464
0
      if (!commit)
1465
        /* not pushing a commit, which is not an error */
1466
0
        continue;
1467
1468
0
      commit_stack_push(&src_commits, commit);
1469
0
    }
1470
1471
0
    found_commits = get_reachable_subset(sent_tips.items,
1472
0
                 sent_tips.nr,
1473
0
                 src_commits.items,
1474
0
                 src_commits.nr,
1475
0
                 reachable_flag);
1476
1477
0
    for_each_string_list_item(item, &src_tag) {
1478
0
      struct ref *dst_ref;
1479
0
      struct ref *ref = item->util;
1480
0
      struct commit *commit;
1481
1482
0
      if (is_null_oid(&ref->new_oid))
1483
0
        continue;
1484
0
      commit = lookup_commit_reference_gently(the_repository,
1485
0
                &ref->new_oid,
1486
0
                1);
1487
0
      if (!commit)
1488
        /* not pushing a commit, which is not an error */
1489
0
        continue;
1490
1491
      /*
1492
       * Is this tag, which they do not have, reachable from
1493
       * any of the commits we are sending?
1494
       */
1495
0
      if (!(commit->object.flags & reachable_flag))
1496
0
        continue;
1497
1498
      /* Add it in */
1499
0
      dst_ref = make_linked_ref(ref->name, dst_tail);
1500
0
      oidcpy(&dst_ref->new_oid, &ref->new_oid);
1501
0
      dst_ref->peer_ref = copy_ref(ref);
1502
0
    }
1503
1504
0
    clear_commit_marks_many(src_commits.nr, src_commits.items,
1505
0
          reachable_flag);
1506
0
    commit_stack_clear(&src_commits);
1507
0
    commit_list_free(found_commits);
1508
0
  }
1509
1510
0
  string_list_clear(&src_tag, 0);
1511
0
  commit_stack_clear(&sent_tips);
1512
0
}
1513
1514
struct ref *find_ref_by_name(const struct ref *list, const char *name)
1515
0
{
1516
0
  for ( ; list; list = list->next)
1517
0
    if (!strcmp(list->name, name))
1518
0
      return (struct ref *)list;
1519
0
  return NULL;
1520
0
}
1521
1522
static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
1523
0
{
1524
0
  for ( ; ref; ref = ref->next)
1525
0
    string_list_append_nodup(ref_index, ref->name)->util = ref;
1526
1527
0
  string_list_sort(ref_index);
1528
0
}
1529
1530
/*
1531
 * Given only the set of local refs, sanity-check the set of push
1532
 * refspecs. We can't catch all errors that match_push_refs would,
1533
 * but we can catch some errors early before even talking to the
1534
 * remote side.
1535
 */
1536
int check_push_refs(struct ref *src, struct refspec *rs)
1537
0
{
1538
0
  int ret = 0;
1539
0
  int i;
1540
1541
0
  for (i = 0; i < rs->nr; i++) {
1542
0
    struct refspec_item *item = &rs->items[i];
1543
1544
0
    if (item->pattern || item->matching || item->negative)
1545
0
      continue;
1546
1547
0
    ret |= match_explicit_lhs(src, item, NULL, NULL);
1548
0
  }
1549
1550
0
  return ret;
1551
0
}
1552
1553
/*
1554
 * Given the set of refs the local repository has, the set of refs the
1555
 * remote repository has, and the refspec used for push, determine
1556
 * what remote refs we will update and with what value by setting
1557
 * peer_ref (which object is being pushed) and force (if the push is
1558
 * forced) in elements of "dst". The function may add new elements to
1559
 * dst (e.g. pushing to a new branch, done in match_explicit_refs).
1560
 */
1561
int match_push_refs(struct ref *src, struct ref **dst,
1562
        struct refspec *rs, int flags)
1563
0
{
1564
0
  int send_all = flags & MATCH_REFS_ALL;
1565
0
  int send_mirror = flags & MATCH_REFS_MIRROR;
1566
0
  int send_prune = flags & MATCH_REFS_PRUNE;
1567
0
  int errs;
1568
0
  struct ref *ref, **dst_tail = tail_ref(dst);
1569
0
  struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
1570
1571
  /* If no refspec is provided, use the default ":" */
1572
0
  if (!rs->nr)
1573
0
    refspec_append(rs, ":");
1574
1575
0
  errs = match_explicit_refs(src, *dst, &dst_tail, rs);
1576
1577
  /* pick the remainder */
1578
0
  for (ref = src; ref; ref = ref->next) {
1579
0
    struct string_list_item *dst_item;
1580
0
    struct ref *dst_peer;
1581
0
    const struct refspec_item *pat = NULL;
1582
0
    char *dst_name;
1583
1584
0
    dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
1585
0
    if (!dst_name)
1586
0
      continue;
1587
1588
0
    if (!dst_ref_index.nr)
1589
0
      prepare_ref_index(&dst_ref_index, *dst);
1590
1591
0
    dst_item = string_list_lookup(&dst_ref_index, dst_name);
1592
0
    dst_peer = dst_item ? dst_item->util : NULL;
1593
0
    if (dst_peer) {
1594
0
      if (dst_peer->peer_ref)
1595
        /* We're already sending something to this ref. */
1596
0
        goto free_name;
1597
0
    } else {
1598
0
      if (pat->matching && !(send_all || send_mirror))
1599
        /*
1600
         * Remote doesn't have it, and we have no
1601
         * explicit pattern, and we don't have
1602
         * --all or --mirror.
1603
         */
1604
0
        goto free_name;
1605
1606
      /* Create a new one and link it */
1607
0
      dst_peer = make_linked_ref(dst_name, &dst_tail);
1608
0
      oidcpy(&dst_peer->new_oid, &ref->new_oid);
1609
0
      string_list_insert(&dst_ref_index,
1610
0
        dst_peer->name)->util = dst_peer;
1611
0
    }
1612
0
    dst_peer->peer_ref = copy_ref(ref);
1613
0
    dst_peer->force = pat->force;
1614
0
  free_name:
1615
0
    free(dst_name);
1616
0
  }
1617
1618
0
  string_list_clear(&dst_ref_index, 0);
1619
1620
0
  if (flags & MATCH_REFS_FOLLOW_TAGS)
1621
0
    add_missing_tags(src, dst, &dst_tail);
1622
1623
0
  if (send_prune) {
1624
0
    struct string_list src_ref_index = STRING_LIST_INIT_NODUP;
1625
    /* check for missing refs on the remote */
1626
0
    for (ref = *dst; ref; ref = ref->next) {
1627
0
      char *src_name;
1628
1629
0
      if (ref->peer_ref)
1630
        /* We're already sending something to this ref. */
1631
0
        continue;
1632
1633
0
      src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
1634
0
      if (src_name) {
1635
0
        if (!src_ref_index.nr)
1636
0
          prepare_ref_index(&src_ref_index, src);
1637
0
        if (!string_list_has_string(&src_ref_index,
1638
0
              src_name))
1639
0
          ref->peer_ref = alloc_delete_ref();
1640
0
        free(src_name);
1641
0
      }
1642
0
    }
1643
0
    string_list_clear(&src_ref_index, 0);
1644
0
  }
1645
1646
0
  *dst = apply_negative_refspecs(*dst, rs);
1647
1648
0
  if (errs)
1649
0
    return -1;
1650
0
  return 0;
1651
0
}
1652
1653
void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
1654
           int force_update)
1655
0
{
1656
0
  struct ref *ref;
1657
1658
0
  for (ref = remote_refs; ref; ref = ref->next) {
1659
0
    int force_ref_update = ref->force || force_update;
1660
0
    int reject_reason = 0;
1661
1662
0
    if (ref->peer_ref)
1663
0
      oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
1664
0
    else if (!send_mirror)
1665
0
      continue;
1666
1667
0
    ref->deletion = is_null_oid(&ref->new_oid);
1668
0
    if (!ref->deletion &&
1669
0
      oideq(&ref->old_oid, &ref->new_oid)) {
1670
0
      ref->status = REF_STATUS_UPTODATE;
1671
0
      continue;
1672
0
    }
1673
1674
    /*
1675
     * If the remote ref has moved and is now different
1676
     * from what we expect, reject any push.
1677
     *
1678
     * It also is an error if the user told us to check
1679
     * with the remote-tracking branch to find the value
1680
     * to expect, but we did not have such a tracking
1681
     * branch.
1682
     *
1683
     * If the tip of the remote-tracking ref is unreachable
1684
     * from any reflog entry of its local ref indicating a
1685
     * possible update since checkout; reject the push.
1686
     */
1687
0
    if (ref->expect_old_sha1) {
1688
0
      if (!oideq(&ref->old_oid, &ref->old_oid_expect))
1689
0
        reject_reason = REF_STATUS_REJECT_STALE;
1690
0
      else if (ref->check_reachable && ref->unreachable)
1691
0
        reject_reason =
1692
0
          REF_STATUS_REJECT_REMOTE_UPDATED;
1693
0
      else
1694
        /*
1695
         * If the ref isn't stale, and is reachable
1696
         * from one of the reflog entries of
1697
         * the local branch, force the update.
1698
         */
1699
0
        force_ref_update = 1;
1700
0
    }
1701
1702
    /*
1703
     * If the update isn't already rejected then check
1704
     * the usual "must fast-forward" rules.
1705
     *
1706
     * Decide whether an individual refspec A:B can be
1707
     * pushed.  The push will succeed if any of the
1708
     * following are true:
1709
     *
1710
     * (1) the remote reference B does not exist
1711
     *
1712
     * (2) the remote reference B is being removed (i.e.,
1713
     *     pushing :B where no source is specified)
1714
     *
1715
     * (3) the destination is not under refs/tags/, and
1716
     *     if the old and new value is a commit, the new
1717
     *     is a descendant of the old.
1718
     *
1719
     * (4) it is forced using the +A:B notation, or by
1720
     *     passing the --force argument
1721
     */
1722
1723
0
    if (!reject_reason && !ref->deletion && !is_null_oid(&ref->old_oid)) {
1724
0
      if (starts_with(ref->name, "refs/tags/"))
1725
0
        reject_reason = REF_STATUS_REJECT_ALREADY_EXISTS;
1726
0
      else if (!odb_has_object(the_repository->objects, &ref->old_oid, HAS_OBJECT_RECHECK_PACKED))
1727
0
        reject_reason = REF_STATUS_REJECT_FETCH_FIRST;
1728
0
      else if (!lookup_commit_reference_gently(the_repository, &ref->old_oid, 1) ||
1729
0
         !lookup_commit_reference_gently(the_repository, &ref->new_oid, 1))
1730
0
        reject_reason = REF_STATUS_REJECT_NEEDS_FORCE;
1731
0
      else if (!ref_newer(&ref->new_oid, &ref->old_oid))
1732
0
        reject_reason = REF_STATUS_REJECT_NONFASTFORWARD;
1733
0
    }
1734
1735
    /*
1736
     * "--force" will defeat any rejection implemented
1737
     * by the rules above.
1738
     */
1739
0
    if (!force_ref_update)
1740
0
      ref->status = reject_reason;
1741
0
    else if (reject_reason)
1742
0
      ref->forced_update = 1;
1743
0
  }
1744
0
}
1745
1746
static void set_merge(struct repository *repo, struct branch *ret)
1747
0
{
1748
0
  struct remote *remote;
1749
0
  char *ref;
1750
0
  struct object_id oid;
1751
0
  int i;
1752
1753
0
  if (!ret)
1754
0
    return; /* no branch */
1755
0
  if (ret->set_merge)
1756
0
    return; /* already run */
1757
0
  if (!ret->remote_name || !ret->merge_nr) {
1758
    /*
1759
     * no merge config; let's make sure we don't confuse callers
1760
     * with a non-zero merge_nr but a NULL merge
1761
     */
1762
0
    merge_clear(ret);
1763
0
    return;
1764
0
  }
1765
0
  ret->set_merge = 1;
1766
1767
0
  remote = remotes_remote_get(repo, ret->remote_name);
1768
1769
0
  for (i = 0; i < ret->merge_nr; i++) {
1770
0
    if (!remote_find_tracking(remote, ret->merge[i]) ||
1771
0
        strcmp(ret->remote_name, "."))
1772
0
      continue;
1773
0
    if (repo_dwim_ref(repo, ret->merge[i]->src,
1774
0
          strlen(ret->merge[i]->src), &oid, &ref,
1775
0
          0) == 1)
1776
0
      ret->merge[i]->dst = ref;
1777
0
    else
1778
0
      ret->merge[i]->dst = xstrdup(ret->merge[i]->src);
1779
0
  }
1780
0
}
1781
1782
static struct branch *repo_branch_get(struct repository *repo, const char *name)
1783
0
{
1784
0
  struct branch *ret;
1785
1786
0
  read_config(repo, 0);
1787
0
  if (!name || !*name || !strcmp(name, "HEAD"))
1788
0
    ret = repo->remote_state->current_branch;
1789
0
  else
1790
0
    ret = make_branch(repo->remote_state, name,
1791
0
          strlen(name));
1792
0
  set_merge(repo, ret);
1793
0
  return ret;
1794
0
}
1795
1796
struct branch *branch_get(const char *name)
1797
0
{
1798
0
  return repo_branch_get(the_repository, name);
1799
0
}
1800
1801
const char *repo_default_remote(struct repository *repo)
1802
0
{
1803
0
  struct branch *branch;
1804
1805
0
  read_config(repo, 0);
1806
0
  branch = repo_branch_get(repo, "HEAD");
1807
1808
0
  return remotes_remote_for_branch(repo->remote_state, branch, NULL);
1809
0
}
1810
1811
const char *repo_remote_from_url(struct repository *repo, const char *url)
1812
0
{
1813
0
  read_config(repo, 0);
1814
1815
0
  for (int i = 0; i < repo->remote_state->remotes_nr; i++) {
1816
0
    struct remote *remote = repo->remote_state->remotes[i];
1817
0
    if (!remote)
1818
0
      continue;
1819
1820
0
    if (remote_has_url(remote, url))
1821
0
      return remote->name;
1822
0
  }
1823
0
  return NULL;
1824
0
}
1825
1826
int branch_has_merge_config(struct branch *branch)
1827
0
{
1828
0
  return branch && branch->set_merge;
1829
0
}
1830
1831
int branch_merge_matches(struct branch *branch,
1832
                     int i,
1833
                     const char *refname)
1834
0
{
1835
0
  if (!branch || i < 0 || i >= branch->merge_nr)
1836
0
    return 0;
1837
0
  return refname_match(branch->merge[i]->src, refname);
1838
0
}
1839
1840
__attribute__((format (printf,2,3)))
1841
static char *error_buf(struct strbuf *err, const char *fmt, ...)
1842
0
{
1843
0
  if (err) {
1844
0
    va_list ap;
1845
0
    va_start(ap, fmt);
1846
0
    strbuf_vaddf(err, fmt, ap);
1847
0
    va_end(ap);
1848
0
  }
1849
0
  return NULL;
1850
0
}
1851
1852
const char *branch_get_upstream(struct branch *branch, struct strbuf *err)
1853
0
{
1854
0
  if (!branch)
1855
0
    return error_buf(err, _("HEAD does not point to a branch"));
1856
1857
0
  if (!branch->merge || !branch->merge[0]) {
1858
    /*
1859
     * no merge config; is it because the user didn't define any,
1860
     * or because it is not a real branch, and get_branch
1861
     * auto-vivified it?
1862
     */
1863
0
    if (!refs_ref_exists(get_main_ref_store(the_repository), branch->refname))
1864
0
      return error_buf(err, _("no such branch: '%s'"),
1865
0
           branch->name);
1866
0
    return error_buf(err,
1867
0
         _("no upstream configured for branch '%s'"),
1868
0
         branch->name);
1869
0
  }
1870
1871
0
  if (!branch->merge[0]->dst)
1872
0
    return error_buf(err,
1873
0
         _("upstream branch '%s' not stored as a remote-tracking branch"),
1874
0
         branch->merge[0]->src);
1875
1876
0
  return branch->merge[0]->dst;
1877
0
}
1878
1879
static char *tracking_for_push_dest(struct remote *remote,
1880
            const char *refname,
1881
            struct strbuf *err)
1882
0
{
1883
0
  char *ret;
1884
1885
0
  ret = apply_refspecs(&remote->fetch, refname);
1886
0
  if (!ret)
1887
0
    return error_buf(err,
1888
0
         _("push destination '%s' on remote '%s' has no local tracking branch"),
1889
0
         refname, remote->name);
1890
0
  return ret;
1891
0
}
1892
1893
static char *branch_get_push_1(struct repository *repo,
1894
             struct branch *branch, struct strbuf *err)
1895
0
{
1896
0
  struct remote_state *remote_state = repo->remote_state;
1897
0
  struct remote *remote;
1898
1899
0
  remote = remotes_remote_get(
1900
0
    repo,
1901
0
    remotes_pushremote_for_branch(remote_state, branch, NULL));
1902
0
  if (!remote)
1903
0
    return error_buf(err,
1904
0
         _("branch '%s' has no remote for pushing"),
1905
0
         branch->name);
1906
1907
0
  if (remote->push.nr) {
1908
0
    char *dst;
1909
0
    char *ret;
1910
1911
0
    dst = apply_refspecs(&remote->push, branch->refname);
1912
0
    if (!dst)
1913
0
      return error_buf(err,
1914
0
           _("push refspecs for '%s' do not include '%s'"),
1915
0
           remote->name, branch->name);
1916
1917
0
    ret = tracking_for_push_dest(remote, dst, err);
1918
0
    free(dst);
1919
0
    return ret;
1920
0
  }
1921
1922
0
  if (remote->mirror)
1923
0
    return tracking_for_push_dest(remote, branch->refname, err);
1924
1925
0
  switch (push_default) {
1926
0
  case PUSH_DEFAULT_NOTHING:
1927
0
    return error_buf(err, _("push has no destination (push.default is 'nothing')"));
1928
1929
0
  case PUSH_DEFAULT_MATCHING:
1930
0
  case PUSH_DEFAULT_CURRENT:
1931
0
    return tracking_for_push_dest(remote, branch->refname, err);
1932
1933
0
  case PUSH_DEFAULT_UPSTREAM:
1934
0
    return xstrdup_or_null(branch_get_upstream(branch, err));
1935
1936
0
  case PUSH_DEFAULT_UNSPECIFIED:
1937
0
  case PUSH_DEFAULT_SIMPLE:
1938
0
    {
1939
0
      const char *up;
1940
0
      char *cur;
1941
1942
0
      up = branch_get_upstream(branch, err);
1943
0
      if (!up)
1944
0
        return NULL;
1945
0
      cur = tracking_for_push_dest(remote, branch->refname, err);
1946
0
      if (!cur)
1947
0
        return NULL;
1948
0
      if (strcmp(cur, up)) {
1949
0
        free(cur);
1950
0
        return error_buf(err,
1951
0
             _("cannot resolve 'simple' push to a single destination"));
1952
0
      }
1953
0
      return cur;
1954
0
    }
1955
0
  }
1956
1957
0
  BUG("unhandled push situation");
1958
0
}
1959
1960
const char *branch_get_push(struct branch *branch, struct strbuf *err)
1961
0
{
1962
0
  read_config(the_repository, 0);
1963
0
  die_on_missing_branch(the_repository, branch);
1964
1965
0
  if (!branch)
1966
0
    return error_buf(err, _("HEAD does not point to a branch"));
1967
1968
0
  if (!branch->push_tracking_ref)
1969
0
    branch->push_tracking_ref = branch_get_push_1(
1970
0
      the_repository, branch, err);
1971
0
  return branch->push_tracking_ref;
1972
0
}
1973
1974
static int ignore_symref_update(const char *refname, struct strbuf *scratch)
1975
0
{
1976
0
  return !refs_read_symbolic_ref(get_main_ref_store(the_repository), refname, scratch);
1977
0
}
1978
1979
/*
1980
 * Create and return a list of (struct ref) consisting of copies of
1981
 * each remote_ref that matches refspec.  refspec must be a pattern.
1982
 * Fill in the copies' peer_ref to describe the local tracking refs to
1983
 * which they map.  Omit any references that would map to an existing
1984
 * local symbolic ref.
1985
 */
1986
static struct ref *get_expanded_map(const struct ref *remote_refs,
1987
            const struct refspec_item *refspec)
1988
0
{
1989
0
  struct strbuf scratch = STRBUF_INIT;
1990
0
  const struct ref *ref;
1991
0
  struct ref *ret = NULL;
1992
0
  struct ref **tail = &ret;
1993
1994
0
  for (ref = remote_refs; ref; ref = ref->next) {
1995
0
    char *expn_name = NULL;
1996
1997
0
    strbuf_reset(&scratch);
1998
1999
0
    if (strchr(ref->name, '^'))
2000
0
      continue; /* a dereference item */
2001
0
    if (match_refname_with_pattern(refspec->src, ref->name,
2002
0
              refspec->dst, &expn_name) &&
2003
0
        !ignore_symref_update(expn_name, &scratch)) {
2004
0
      struct ref *cpy = copy_ref(ref);
2005
2006
0
      if (cpy->peer_ref)
2007
0
        free_one_ref(cpy->peer_ref);
2008
0
      cpy->peer_ref = alloc_ref(expn_name);
2009
0
      if (refspec->force)
2010
0
        cpy->peer_ref->force = 1;
2011
0
      *tail = cpy;
2012
0
      tail = &cpy->next;
2013
0
    }
2014
0
    free(expn_name);
2015
0
  }
2016
2017
0
  strbuf_release(&scratch);
2018
0
  return ret;
2019
0
}
2020
2021
static const struct ref *find_ref_by_name_abbrev(const struct ref *refs, const char *name)
2022
0
{
2023
0
  const struct ref *ref;
2024
0
  const struct ref *best_match = NULL;
2025
0
  int best_score = 0;
2026
2027
0
  for (ref = refs; ref; ref = ref->next) {
2028
0
    int score = refname_match(name, ref->name);
2029
2030
0
    if (best_score < score) {
2031
0
      best_match = ref;
2032
0
      best_score = score;
2033
0
    }
2034
0
  }
2035
0
  return best_match;
2036
0
}
2037
2038
struct ref *get_remote_ref(const struct ref *remote_refs, const char *name)
2039
0
{
2040
0
  const struct ref *ref = find_ref_by_name_abbrev(remote_refs, name);
2041
2042
0
  if (!ref)
2043
0
    return NULL;
2044
2045
0
  return copy_ref(ref);
2046
0
}
2047
2048
static struct ref *get_local_ref(const char *name)
2049
0
{
2050
0
  if (!name || name[0] == '\0')
2051
0
    return NULL;
2052
2053
0
  if (starts_with(name, "refs/"))
2054
0
    return alloc_ref(name);
2055
2056
0
  if (starts_with(name, "heads/") ||
2057
0
      starts_with(name, "tags/") ||
2058
0
      starts_with(name, "remotes/"))
2059
0
    return alloc_ref_with_prefix("refs/", 5, name);
2060
2061
0
  return alloc_ref_with_prefix("refs/heads/", 11, name);
2062
0
}
2063
2064
int get_fetch_map(const struct ref *remote_refs,
2065
      const struct refspec_item *refspec,
2066
      struct ref ***tail,
2067
      int missing_ok)
2068
0
{
2069
0
  struct ref *ref_map, **rmp;
2070
2071
0
  if (refspec->negative)
2072
0
    return 0;
2073
2074
0
  if (refspec->pattern) {
2075
0
    ref_map = get_expanded_map(remote_refs, refspec);
2076
0
  } else {
2077
0
    const char *name = refspec->src[0] ? refspec->src : "HEAD";
2078
2079
0
    if (refspec->exact_sha1) {
2080
0
      ref_map = alloc_ref(name);
2081
0
      get_oid_hex(name, &ref_map->old_oid);
2082
0
      ref_map->exact_oid = 1;
2083
0
    } else {
2084
0
      ref_map = get_remote_ref(remote_refs, name);
2085
0
    }
2086
0
    if (!missing_ok && !ref_map)
2087
0
      die(_("couldn't find remote ref %s"), name);
2088
0
    if (ref_map) {
2089
0
      ref_map->peer_ref = get_local_ref(refspec->dst);
2090
0
      if (ref_map->peer_ref && refspec->force)
2091
0
        ref_map->peer_ref->force = 1;
2092
0
    }
2093
0
  }
2094
2095
0
  for (rmp = &ref_map; *rmp; ) {
2096
0
    if ((*rmp)->peer_ref) {
2097
0
      if (!starts_with((*rmp)->peer_ref->name, "refs/") ||
2098
0
          check_refname_format((*rmp)->peer_ref->name, 0)) {
2099
0
        struct ref *ignore = *rmp;
2100
0
        error(_("* Ignoring funny ref '%s' locally"),
2101
0
              (*rmp)->peer_ref->name);
2102
0
        *rmp = (*rmp)->next;
2103
0
        free(ignore->peer_ref);
2104
0
        free(ignore);
2105
0
        continue;
2106
0
      }
2107
0
    }
2108
0
    rmp = &((*rmp)->next);
2109
0
  }
2110
2111
0
  if (ref_map)
2112
0
    tail_link_ref(ref_map, tail);
2113
2114
0
  return 0;
2115
0
}
2116
2117
int resolve_remote_symref(struct ref *ref, struct ref *list)
2118
0
{
2119
0
  if (!ref->symref)
2120
0
    return 0;
2121
0
  for (; list; list = list->next)
2122
0
    if (!strcmp(ref->symref, list->name)) {
2123
0
      oidcpy(&ref->old_oid, &list->old_oid);
2124
0
      return 0;
2125
0
    }
2126
0
  return 1;
2127
0
}
2128
2129
/*
2130
 * Compute the commit ahead/behind values for the pair branch_name, base.
2131
 *
2132
 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2133
 * counts in *num_ours and *num_theirs.  If abf is AHEAD_BEHIND_QUICK, skip
2134
 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2135
 * set to zero).
2136
 *
2137
 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., ref
2138
 * does not exist).  Returns 0 if the commits are identical.  Returns 1 if
2139
 * commits are different.
2140
 */
2141
2142
static int stat_branch_pair(const char *branch_name, const char *base,
2143
           int *num_ours, int *num_theirs,
2144
           enum ahead_behind_flags abf)
2145
0
{
2146
0
  struct object_id oid;
2147
0
  struct commit *ours, *theirs;
2148
0
  struct rev_info revs;
2149
0
  struct strvec argv = STRVEC_INIT;
2150
2151
  /* Cannot stat if what we used to build on no longer exists */
2152
0
  if (refs_read_ref(get_main_ref_store(the_repository), base, &oid))
2153
0
    return -1;
2154
0
  theirs = lookup_commit_reference(the_repository, &oid);
2155
0
  if (!theirs)
2156
0
    return -1;
2157
2158
0
  if (refs_read_ref(get_main_ref_store(the_repository), branch_name, &oid))
2159
0
    return -1;
2160
0
  ours = lookup_commit_reference(the_repository, &oid);
2161
0
  if (!ours)
2162
0
    return -1;
2163
2164
0
  *num_theirs = *num_ours = 0;
2165
2166
  /* are we the same? */
2167
0
  if (theirs == ours)
2168
0
    return 0;
2169
0
  if (abf == AHEAD_BEHIND_QUICK)
2170
0
    return 1;
2171
0
  if (abf != AHEAD_BEHIND_FULL)
2172
0
    BUG("stat_branch_pair: invalid abf '%d'", abf);
2173
2174
  /* Run "rev-list --left-right ours...theirs" internally... */
2175
0
  strvec_push(&argv, ""); /* ignored */
2176
0
  strvec_push(&argv, "--left-right");
2177
0
  strvec_pushf(&argv, "%s...%s",
2178
0
         oid_to_hex(&ours->object.oid),
2179
0
         oid_to_hex(&theirs->object.oid));
2180
0
  strvec_push(&argv, "--");
2181
2182
0
  repo_init_revisions(the_repository, &revs, NULL);
2183
0
  setup_revisions_from_strvec(&argv, &revs, NULL);
2184
0
  if (prepare_revision_walk(&revs))
2185
0
    die(_("revision walk setup failed"));
2186
2187
  /* ... and count the commits on each side. */
2188
0
  while (1) {
2189
0
    struct commit *c = get_revision(&revs);
2190
0
    if (!c)
2191
0
      break;
2192
0
    if (c->object.flags & SYMMETRIC_LEFT)
2193
0
      (*num_ours)++;
2194
0
    else
2195
0
      (*num_theirs)++;
2196
0
  }
2197
2198
  /* clear object flags smudged by the above traversal */
2199
0
  clear_commit_marks(ours, ALL_REV_FLAGS);
2200
0
  clear_commit_marks(theirs, ALL_REV_FLAGS);
2201
2202
0
  strvec_clear(&argv);
2203
0
  release_revisions(&revs);
2204
0
  return 1;
2205
0
}
2206
2207
/*
2208
 * Lookup the tracking branch for the given branch and if present, optionally
2209
 * compute the commit ahead/behind values for the pair.
2210
 *
2211
 * If for_push is true, the tracking branch refers to the push branch,
2212
 * otherwise it refers to the upstream branch.
2213
 *
2214
 * The name of the tracking branch (or NULL if it is not defined) is
2215
 * returned via *tracking_name, if it is not itself NULL.
2216
 *
2217
 * If abf is AHEAD_BEHIND_FULL, compute the full ahead/behind and return the
2218
 * counts in *num_ours and *num_theirs.  If abf is AHEAD_BEHIND_QUICK, skip
2219
 * the (potentially expensive) a/b computation (*num_ours and *num_theirs are
2220
 * set to zero).
2221
 *
2222
 * Returns -1 if num_ours and num_theirs could not be filled in (e.g., no
2223
 * upstream defined, or ref does not exist).  Returns 0 if the commits are
2224
 * identical.  Returns 1 if commits are different.
2225
 */
2226
int stat_tracking_info(struct branch *branch, int *num_ours, int *num_theirs,
2227
           const char **tracking_name, int for_push,
2228
           enum ahead_behind_flags abf)
2229
0
{
2230
0
  const char *base;
2231
2232
  /* Cannot stat unless we are marked to build on top of somebody else. */
2233
0
  base = for_push ? branch_get_push(branch, NULL) :
2234
0
    branch_get_upstream(branch, NULL);
2235
0
  if (tracking_name)
2236
0
    *tracking_name = base;
2237
0
  if (!base)
2238
0
    return -1;
2239
2240
0
  return stat_branch_pair(branch->refname, base, num_ours, num_theirs, abf);
2241
0
}
2242
2243
static char *resolve_compare_branch(struct branch *branch, const char *name)
2244
0
{
2245
0
  const char *resolved = NULL;
2246
2247
0
  if (!branch || !name)
2248
0
    return NULL;
2249
2250
0
  if (!strcasecmp(name, "@{upstream}")) {
2251
0
    resolved = branch_get_upstream(branch, NULL);
2252
0
  } else if (!strcasecmp(name, "@{push}")) {
2253
0
    resolved = branch_get_push(branch, NULL);
2254
0
  } else {
2255
0
    warning(_("ignoring value '%s' for status.compareBranches, "
2256
0
        "only @{upstream} and @{push} are supported"),
2257
0
      name);
2258
0
    return NULL;
2259
0
  }
2260
2261
0
  if (resolved)
2262
0
    return xstrdup(resolved);
2263
0
  return NULL;
2264
0
}
2265
2266
static void format_branch_comparison(struct strbuf *sb,
2267
             bool up_to_date,
2268
             int ours, int theirs,
2269
             const char *branch_name,
2270
             enum ahead_behind_flags abf,
2271
             unsigned flags)
2272
0
{
2273
0
  bool use_push_advice = (flags & ENABLE_ADVICE_PUSH);
2274
0
  bool use_pull_advice = (flags & ENABLE_ADVICE_PULL);
2275
0
  bool use_divergence_advice = (flags & ENABLE_ADVICE_DIVERGENCE);
2276
2277
0
  if (up_to_date) {
2278
0
    strbuf_addf(sb,
2279
0
      _("Your branch is up to date with '%s'.\n"),
2280
0
      branch_name);
2281
0
  } else if (abf == AHEAD_BEHIND_QUICK) {
2282
0
    strbuf_addf(sb,
2283
0
          _("Your branch and '%s' refer to different commits.\n"),
2284
0
          branch_name);
2285
0
    if (use_push_advice && advice_enabled(ADVICE_STATUS_HINTS))
2286
0
      strbuf_addf(sb, _("  (use \"%s\" for details)\n"),
2287
0
            "git status --ahead-behind");
2288
0
  } else if (!theirs) {
2289
0
    strbuf_addf(sb,
2290
0
      Q_("Your branch is ahead of '%s' by %d commit.\n",
2291
0
         "Your branch is ahead of '%s' by %d commits.\n",
2292
0
         ours),
2293
0
      branch_name, ours);
2294
0
    if (use_push_advice && advice_enabled(ADVICE_STATUS_HINTS))
2295
0
      strbuf_addstr(sb,
2296
0
        _("  (use \"git push\" to publish your local commits)\n"));
2297
0
  } else if (!ours) {
2298
0
    strbuf_addf(sb,
2299
0
      Q_("Your branch is behind '%s' by %d commit, "
2300
0
             "and can be fast-forwarded.\n",
2301
0
         "Your branch is behind '%s' by %d commits, "
2302
0
             "and can be fast-forwarded.\n",
2303
0
         theirs),
2304
0
      branch_name, theirs);
2305
0
    if (use_pull_advice && advice_enabled(ADVICE_STATUS_HINTS))
2306
0
      strbuf_addstr(sb,
2307
0
        _("  (use \"git pull\" to update your local branch)\n"));
2308
0
  } else {
2309
0
    strbuf_addf(sb,
2310
0
      Q_("Your branch and '%s' have diverged,\n"
2311
0
             "and have %d and %d different commit each, "
2312
0
             "respectively.\n",
2313
0
         "Your branch and '%s' have diverged,\n"
2314
0
             "and have %d and %d different commits each, "
2315
0
             "respectively.\n",
2316
0
         ours + theirs),
2317
0
      branch_name, ours, theirs);
2318
0
    if (use_divergence_advice && advice_enabled(ADVICE_STATUS_HINTS))
2319
0
      strbuf_addstr(sb,
2320
0
        _("  (use \"git pull\" if you want to integrate the remote branch with yours)\n"));
2321
0
  }
2322
0
}
2323
2324
/*
2325
 * Return true when there is anything to report, otherwise false.
2326
 */
2327
int format_tracking_info(struct branch *branch, struct strbuf *sb,
2328
       enum ahead_behind_flags abf,
2329
       int show_divergence_advice)
2330
0
{
2331
0
  char *compare_branches = NULL;
2332
0
  struct string_list branches = STRING_LIST_INIT_DUP;
2333
0
  struct strset processed_refs = STRSET_INIT;
2334
0
  int reported = 0;
2335
0
  size_t i;
2336
0
  const char *upstream_ref;
2337
0
  const char *push_ref;
2338
2339
0
  repo_config_get_string(the_repository, "status.comparebranches",
2340
0
             &compare_branches);
2341
2342
0
  if (compare_branches) {
2343
0
    string_list_split(&branches, compare_branches, " ", -1);
2344
0
    string_list_remove_empty_items(&branches, 0);
2345
0
  } else {
2346
0
    string_list_append(&branches, "@{upstream}");
2347
0
  }
2348
2349
0
  upstream_ref = branch_get_upstream(branch, NULL);
2350
0
  push_ref = branch_get_push(branch, NULL);
2351
2352
0
  for (i = 0; i < branches.nr; i++) {
2353
0
    char *full_ref;
2354
0
    char *short_ref;
2355
0
    int ours, theirs, cmp;
2356
0
    int is_upstream, is_push;
2357
0
    unsigned flags = 0;
2358
2359
0
    full_ref = resolve_compare_branch(branch,
2360
0
              branches.items[i].string);
2361
0
    if (!full_ref)
2362
0
      continue;
2363
2364
0
    if (!strset_add(&processed_refs, full_ref)) {
2365
0
      free(full_ref);
2366
0
      continue;
2367
0
    }
2368
2369
0
    short_ref = refs_shorten_unambiguous_ref(
2370
0
      get_main_ref_store(the_repository), full_ref, 0);
2371
2372
0
    is_upstream = upstream_ref && !strcmp(full_ref, upstream_ref);
2373
0
    is_push = push_ref && !strcmp(full_ref, push_ref);
2374
2375
0
    if (is_upstream && (!push_ref || !strcmp(upstream_ref, push_ref)))
2376
0
      is_push = 1;
2377
2378
0
    cmp = stat_branch_pair(branch->refname, full_ref,
2379
0
               &ours, &theirs, abf);
2380
2381
0
    if (cmp < 0) {
2382
0
      if (is_upstream) {
2383
0
        strbuf_addf(sb,
2384
0
          _("Your branch is based on '%s', but the upstream is gone.\n"),
2385
0
          short_ref);
2386
0
        if (advice_enabled(ADVICE_STATUS_HINTS))
2387
0
          strbuf_addstr(sb,
2388
0
            _("  (use \"git branch --unset-upstream\" to fixup)\n"));
2389
0
        reported = 1;
2390
0
      }
2391
0
      free(full_ref);
2392
0
      free(short_ref);
2393
0
      continue;
2394
0
    }
2395
2396
0
    if (reported)
2397
0
      strbuf_addstr(sb, "\n");
2398
2399
0
    if (is_upstream)
2400
0
      flags |= ENABLE_ADVICE_PULL;
2401
0
    if (is_push)
2402
0
      flags |= ENABLE_ADVICE_PUSH;
2403
0
    if (show_divergence_advice && is_upstream)
2404
0
      flags |= ENABLE_ADVICE_DIVERGENCE;
2405
0
    format_branch_comparison(sb, !cmp, ours, theirs, short_ref,
2406
0
           abf, flags);
2407
0
    reported = 1;
2408
2409
0
    free(full_ref);
2410
0
    free(short_ref);
2411
0
  }
2412
2413
0
  string_list_clear(&branches, 0);
2414
0
  strset_clear(&processed_refs);
2415
0
  free(compare_branches);
2416
0
  return reported;
2417
0
}
2418
2419
static int one_local_ref(const struct reference *ref, void *cb_data)
2420
0
{
2421
0
  struct ref ***local_tail = cb_data;
2422
0
  struct ref *local_ref;
2423
2424
  /* we already know it starts with refs/ to get here */
2425
0
  if (check_refname_format(ref->name + 5, 0))
2426
0
    return 0;
2427
2428
0
  local_ref = alloc_ref(ref->name);
2429
0
  oidcpy(&local_ref->new_oid, ref->oid);
2430
0
  **local_tail = local_ref;
2431
0
  *local_tail = &local_ref->next;
2432
0
  return 0;
2433
0
}
2434
2435
struct ref *get_local_heads(void)
2436
0
{
2437
0
  struct ref *local_refs = NULL, **local_tail = &local_refs;
2438
2439
0
  refs_for_each_ref(get_main_ref_store(the_repository), one_local_ref,
2440
0
        &local_tail);
2441
0
  return local_refs;
2442
0
}
2443
2444
struct ref *guess_remote_head(const struct ref *head,
2445
            const struct ref *refs,
2446
            unsigned flags)
2447
0
{
2448
0
  const struct ref *r;
2449
0
  struct ref *list = NULL;
2450
0
  struct ref **tail = &list;
2451
2452
0
  if (!head)
2453
0
    return NULL;
2454
2455
  /*
2456
   * Some transports support directly peeking at
2457
   * where HEAD points; if that is the case, then
2458
   * we don't have to guess.
2459
   */
2460
0
  if (head->symref)
2461
0
    return copy_ref(find_ref_by_name(refs, head->symref));
2462
2463
  /* If a remote branch exists with the default branch name, let's use it. */
2464
0
  if (!(flags & REMOTE_GUESS_HEAD_ALL)) {
2465
0
    char *default_branch =
2466
0
      repo_default_branch_name(the_repository,
2467
0
             flags & REMOTE_GUESS_HEAD_QUIET);
2468
0
    char *ref = xstrfmt("refs/heads/%s", default_branch);
2469
2470
0
    r = find_ref_by_name(refs, ref);
2471
0
    free(ref);
2472
0
    free(default_branch);
2473
2474
0
    if (r && oideq(&r->old_oid, &head->old_oid))
2475
0
      return copy_ref(r);
2476
2477
    /* Fall back to the hard-coded historical default */
2478
0
    r = find_ref_by_name(refs, "refs/heads/master");
2479
0
    if (r && oideq(&r->old_oid, &head->old_oid))
2480
0
      return copy_ref(r);
2481
0
  }
2482
2483
  /* Look for another ref that points there */
2484
0
  for (r = refs; r; r = r->next) {
2485
0
    if (r != head &&
2486
0
        starts_with(r->name, "refs/heads/") &&
2487
0
        oideq(&r->old_oid, &head->old_oid)) {
2488
0
      *tail = copy_ref(r);
2489
0
      tail = &((*tail)->next);
2490
0
      if (!(flags & REMOTE_GUESS_HEAD_ALL))
2491
0
        break;
2492
0
    }
2493
0
  }
2494
2495
0
  return list;
2496
0
}
2497
2498
struct stale_heads_info {
2499
  struct string_list *ref_names;
2500
  struct ref **stale_refs_tail;
2501
  struct refspec *rs;
2502
};
2503
2504
static int get_stale_heads_cb(const struct reference *ref, void *cb_data)
2505
0
{
2506
0
  struct stale_heads_info *info = cb_data;
2507
0
  struct string_list matches = STRING_LIST_INIT_DUP;
2508
0
  struct refspec_item query;
2509
0
  int i, stale = 1;
2510
0
  memset(&query, 0, sizeof(struct refspec_item));
2511
0
  query.dst = (char *)ref->name;
2512
2513
0
  refspec_find_all_matches(info->rs, &query, &matches);
2514
0
  if (matches.nr == 0)
2515
0
    goto clean_exit; /* No matches */
2516
2517
  /*
2518
   * If we did find a suitable refspec and it's not a symref and
2519
   * it's not in the list of refs that currently exist in that
2520
   * remote, we consider it to be stale. In order to deal with
2521
   * overlapping refspecs, we need to go over all of the
2522
   * matching refs.
2523
   */
2524
0
  if (ref->flags & REF_ISSYMREF)
2525
0
    goto clean_exit;
2526
2527
0
  for (i = 0; stale && i < matches.nr; i++)
2528
0
    if (string_list_has_string(info->ref_names, matches.items[i].string))
2529
0
      stale = 0;
2530
2531
0
  if (stale) {
2532
0
    struct ref *linked_ref = make_linked_ref(ref->name, &info->stale_refs_tail);
2533
0
    oidcpy(&linked_ref->new_oid, ref->oid);
2534
0
  }
2535
2536
0
clean_exit:
2537
0
  string_list_clear(&matches, 0);
2538
0
  return 0;
2539
0
}
2540
2541
struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
2542
0
{
2543
0
  struct ref *ref, *stale_refs = NULL;
2544
0
  struct string_list ref_names = STRING_LIST_INIT_NODUP;
2545
0
  struct stale_heads_info info;
2546
2547
0
  info.ref_names = &ref_names;
2548
0
  info.stale_refs_tail = &stale_refs;
2549
0
  info.rs = rs;
2550
0
  for (ref = fetch_map; ref; ref = ref->next)
2551
0
    string_list_append(&ref_names, ref->name);
2552
0
  string_list_sort(&ref_names);
2553
0
  refs_for_each_ref(get_main_ref_store(the_repository),
2554
0
        get_stale_heads_cb, &info);
2555
0
  string_list_clear(&ref_names, 0);
2556
0
  return stale_refs;
2557
0
}
2558
2559
/*
2560
 * Compare-and-swap
2561
 */
2562
void clear_cas_option(struct push_cas_option *cas)
2563
0
{
2564
0
  int i;
2565
2566
0
  for (i = 0; i < cas->nr; i++)
2567
0
    free(cas->entry[i].refname);
2568
0
  free(cas->entry);
2569
0
  memset(cas, 0, sizeof(*cas));
2570
0
}
2571
2572
static struct push_cas *add_cas_entry(struct push_cas_option *cas,
2573
              const char *refname,
2574
              size_t refnamelen)
2575
0
{
2576
0
  struct push_cas *entry;
2577
0
  ALLOC_GROW(cas->entry, cas->nr + 1, cas->alloc);
2578
0
  entry = &cas->entry[cas->nr++];
2579
0
  memset(entry, 0, sizeof(*entry));
2580
0
  entry->refname = xmemdupz(refname, refnamelen);
2581
0
  return entry;
2582
0
}
2583
2584
static int parse_push_cas_option(struct push_cas_option *cas, const char *arg, int unset)
2585
0
{
2586
0
  const char *colon;
2587
0
  struct push_cas *entry;
2588
2589
0
  if (unset) {
2590
    /* "--no-<option>" */
2591
0
    clear_cas_option(cas);
2592
0
    return 0;
2593
0
  }
2594
2595
0
  if (!arg) {
2596
    /* just "--<option>" */
2597
0
    cas->use_tracking_for_rest = 1;
2598
0
    return 0;
2599
0
  }
2600
2601
  /* "--<option>=refname" or "--<option>=refname:value" */
2602
0
  colon = strchrnul(arg, ':');
2603
0
  entry = add_cas_entry(cas, arg, colon - arg);
2604
0
  if (!*colon)
2605
0
    entry->use_tracking = 1;
2606
0
  else if (!colon[1])
2607
0
    oidclr(&entry->expect, the_repository->hash_algo);
2608
0
  else if (repo_get_oid(the_repository, colon + 1, &entry->expect))
2609
0
    return error(_("cannot parse expected object name '%s'"),
2610
0
           colon + 1);
2611
0
  return 0;
2612
0
}
2613
2614
int parseopt_push_cas_option(const struct option *opt, const char *arg, int unset)
2615
0
{
2616
0
  return parse_push_cas_option(opt->value, arg, unset);
2617
0
}
2618
2619
int is_empty_cas(const struct push_cas_option *cas)
2620
0
{
2621
0
  return !cas->use_tracking_for_rest && !cas->nr;
2622
0
}
2623
2624
/*
2625
 * Look at remote.fetch refspec and see if we have a remote
2626
 * tracking branch for the refname there. Fill the name of
2627
 * the remote-tracking branch in *dst_refname, and the name
2628
 * of the commit object at its tip in oid[].
2629
 * If we cannot do so, return negative to signal an error.
2630
 */
2631
static int remote_tracking(struct remote *remote, const char *refname,
2632
         struct object_id *oid, char **dst_refname)
2633
0
{
2634
0
  char *dst;
2635
2636
0
  dst = apply_refspecs(&remote->fetch, refname);
2637
0
  if (!dst)
2638
0
    return -1; /* no tracking ref for refname at remote */
2639
0
  if (refs_read_ref(get_main_ref_store(the_repository), dst, oid)) {
2640
0
    free(dst);
2641
0
    return -1; /* we know what the tracking ref is but we cannot read it */
2642
0
  }
2643
2644
0
  *dst_refname = dst;
2645
0
  return 0;
2646
0
}
2647
2648
struct check_and_collect_until_cb_data {
2649
  struct commit *remote_commit;
2650
  struct commit_stack *local_commits;
2651
  timestamp_t remote_reflog_timestamp;
2652
};
2653
2654
/* Get the timestamp of the latest entry. */
2655
static int peek_reflog(const char *refname UNUSED,
2656
           struct object_id *o_oid UNUSED,
2657
           struct object_id *n_oid UNUSED,
2658
           const char *ident UNUSED,
2659
           timestamp_t timestamp, int tz UNUSED,
2660
           const char *message UNUSED, void *cb_data)
2661
0
{
2662
0
  timestamp_t *ts = cb_data;
2663
0
  *ts = timestamp;
2664
0
  return 1;
2665
0
}
2666
2667
static int check_and_collect_until(const char *refname UNUSED,
2668
           struct object_id *o_oid UNUSED,
2669
           struct object_id *n_oid,
2670
           const char *ident UNUSED,
2671
           timestamp_t timestamp, int tz UNUSED,
2672
           const char *message UNUSED, void *cb_data)
2673
0
{
2674
0
  struct commit *commit;
2675
0
  struct check_and_collect_until_cb_data *cb = cb_data;
2676
2677
  /* An entry was found. */
2678
0
  if (oideq(n_oid, &cb->remote_commit->object.oid))
2679
0
    return 1;
2680
2681
0
  if ((commit = lookup_commit_reference(the_repository, n_oid)))
2682
0
    commit_stack_push(cb->local_commits, commit);
2683
2684
  /*
2685
   * If the reflog entry timestamp is older than the remote ref's
2686
   * latest reflog entry, there is no need to check or collect
2687
   * entries older than this one.
2688
   */
2689
0
  if (timestamp < cb->remote_reflog_timestamp)
2690
0
    return -1;
2691
2692
0
  return 0;
2693
0
}
2694
2695
0
#define MERGE_BASES_BATCH_SIZE 8
2696
2697
/*
2698
 * Iterate through the reflog of the local ref to check if there is an entry
2699
 * for the given remote-tracking ref; runs until the timestamp of an entry is
2700
 * older than latest timestamp of remote-tracking ref's reflog. Any commits
2701
 * are that seen along the way are collected into an array to check if the
2702
 * remote-tracking ref is reachable from any of them.
2703
 */
2704
static int is_reachable_in_reflog(const char *local, const struct ref *remote)
2705
0
{
2706
0
  timestamp_t date;
2707
0
  struct commit *commit;
2708
0
  struct commit **chunk;
2709
0
  struct check_and_collect_until_cb_data cb;
2710
0
  struct commit_stack arr = COMMIT_STACK_INIT;
2711
0
  size_t size = 0;
2712
0
  int ret = 0;
2713
2714
0
  commit = lookup_commit_reference(the_repository, &remote->old_oid);
2715
0
  if (!commit)
2716
0
    goto cleanup_return;
2717
2718
  /*
2719
   * Get the timestamp from the latest entry
2720
   * of the remote-tracking ref's reflog.
2721
   */
2722
0
  refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2723
0
           remote->tracking_ref, peek_reflog,
2724
0
           &date);
2725
2726
0
  cb.remote_commit = commit;
2727
0
  cb.local_commits = &arr;
2728
0
  cb.remote_reflog_timestamp = date;
2729
0
  ret = refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2730
0
                 local, check_and_collect_until,
2731
0
                 &cb);
2732
2733
  /* We found an entry in the reflog. */
2734
0
  if (ret > 0)
2735
0
    goto cleanup_return;
2736
2737
  /*
2738
   * Check if the remote commit is reachable from any
2739
   * of the commits in the collected array, in batches.
2740
   */
2741
0
  for (chunk = arr.items; chunk < arr.items + arr.nr; chunk += size) {
2742
0
    size = arr.items + arr.nr - chunk;
2743
0
    if (MERGE_BASES_BATCH_SIZE < size)
2744
0
      size = MERGE_BASES_BATCH_SIZE;
2745
2746
0
    if ((ret = repo_in_merge_bases_many(the_repository, commit, size, chunk, 0)))
2747
0
      break;
2748
0
  }
2749
2750
0
cleanup_return:
2751
0
  commit_stack_clear(&arr);
2752
0
  return ret;
2753
0
}
2754
2755
/*
2756
 * Check for reachability of a remote-tracking
2757
 * ref in the reflog entries of its local ref.
2758
 */
2759
static void check_if_includes_upstream(struct ref *remote)
2760
0
{
2761
0
  struct ref *local = get_local_ref(remote->name);
2762
0
  if (!local)
2763
0
    return;
2764
2765
0
  if (is_reachable_in_reflog(local->name, remote) <= 0)
2766
0
    remote->unreachable = 1;
2767
0
  free_one_ref(local);
2768
0
}
2769
2770
static void apply_cas(struct push_cas_option *cas,
2771
          struct remote *remote,
2772
          struct ref *ref)
2773
0
{
2774
0
  int i;
2775
2776
  /* Find an explicit --<option>=<name>[:<value>] entry */
2777
0
  for (i = 0; i < cas->nr; i++) {
2778
0
    struct push_cas *entry = &cas->entry[i];
2779
0
    if (!refname_match(entry->refname, ref->name))
2780
0
      continue;
2781
0
    ref->expect_old_sha1 = 1;
2782
0
    if (!entry->use_tracking)
2783
0
      oidcpy(&ref->old_oid_expect, &entry->expect);
2784
0
    else if (remote_tracking(remote, ref->name,
2785
0
           &ref->old_oid_expect,
2786
0
           &ref->tracking_ref))
2787
0
      oidclr(&ref->old_oid_expect, the_repository->hash_algo);
2788
0
    else
2789
0
      ref->check_reachable = cas->use_force_if_includes;
2790
0
    return;
2791
0
  }
2792
2793
  /* Are we using "--<option>" to cover all? */
2794
0
  if (!cas->use_tracking_for_rest)
2795
0
    return;
2796
2797
0
  ref->expect_old_sha1 = 1;
2798
0
  if (remote_tracking(remote, ref->name,
2799
0
          &ref->old_oid_expect,
2800
0
          &ref->tracking_ref))
2801
0
    oidclr(&ref->old_oid_expect, the_repository->hash_algo);
2802
0
  else
2803
0
    ref->check_reachable = cas->use_force_if_includes;
2804
0
}
2805
2806
void apply_push_cas(struct push_cas_option *cas,
2807
        struct remote *remote,
2808
        struct ref *remote_refs)
2809
0
{
2810
0
  struct ref *ref;
2811
0
  for (ref = remote_refs; ref; ref = ref->next) {
2812
0
    apply_cas(cas, remote, ref);
2813
2814
    /*
2815
     * If "compare-and-swap" is in "use_tracking[_for_rest]"
2816
     * mode, and if "--force-if-includes" was specified, run
2817
     * the check.
2818
     */
2819
0
    if (ref->check_reachable)
2820
0
      check_if_includes_upstream(ref);
2821
0
  }
2822
0
}
2823
2824
struct remote_state *remote_state_new(void)
2825
57
{
2826
57
  struct remote_state *r;
2827
2828
57
  CALLOC_ARRAY(r, 1);
2829
2830
57
  hashmap_init(&r->remotes_hash, remotes_hash_cmp, NULL, 0);
2831
57
  hashmap_init(&r->branches_hash, branches_hash_cmp, NULL, 0);
2832
57
  return r;
2833
57
}
2834
2835
void remote_state_clear(struct remote_state *remote_state)
2836
57
{
2837
57
  struct hashmap_iter iter;
2838
57
  struct branch *b;
2839
57
  int i;
2840
2841
57
  for (i = 0; i < remote_state->remotes_nr; i++)
2842
0
    remote_clear(remote_state->remotes[i]);
2843
57
  FREE_AND_NULL(remote_state->remotes);
2844
57
  FREE_AND_NULL(remote_state->pushremote_name);
2845
57
  remote_state->remotes_alloc = 0;
2846
57
  remote_state->remotes_nr = 0;
2847
2848
57
  rewrites_release(&remote_state->rewrites);
2849
57
  rewrites_release(&remote_state->rewrites_push);
2850
2851
57
  hashmap_clear_and_free(&remote_state->remotes_hash, struct remote, ent);
2852
57
  hashmap_for_each_entry(&remote_state->branches_hash, &iter, b, ent) {
2853
0
    branch_release(b);
2854
0
    free(b);
2855
0
  }
2856
57
  hashmap_clear(&remote_state->branches_hash);
2857
57
}
2858
2859
/*
2860
 * Returns 1 if it was the last chop before ':'.
2861
 */
2862
static int chop_last_dir(char **remoteurl, int is_relative)
2863
0
{
2864
0
  char *rfind = find_last_dir_sep(*remoteurl);
2865
0
  if (rfind) {
2866
0
    *rfind = '\0';
2867
0
    return 0;
2868
0
  }
2869
2870
0
  rfind = strrchr(*remoteurl, ':');
2871
0
  if (rfind) {
2872
0
    *rfind = '\0';
2873
0
    return 1;
2874
0
  }
2875
2876
0
  if (is_relative || !strcmp(".", *remoteurl))
2877
0
    die(_("cannot strip one component off url '%s'"),
2878
0
      *remoteurl);
2879
2880
0
  free(*remoteurl);
2881
0
  *remoteurl = xstrdup(".");
2882
0
  return 0;
2883
0
}
2884
2885
char *relative_url(const char *remote_url, const char *url,
2886
       const char *up_path)
2887
0
{
2888
0
  int is_relative = 0;
2889
0
  int colonsep = 0;
2890
0
  char *out;
2891
0
  char *remoteurl;
2892
0
  struct strbuf sb = STRBUF_INIT;
2893
0
  size_t len;
2894
2895
0
  if (!url_is_local_not_ssh(url) || is_absolute_path(url))
2896
0
    return xstrdup(url);
2897
2898
0
  len = strlen(remote_url);
2899
0
  if (!len)
2900
0
    BUG("invalid empty remote_url");
2901
2902
0
  remoteurl = xstrdup(remote_url);
2903
0
  if (is_dir_sep(remoteurl[len-1]))
2904
0
    remoteurl[len-1] = '\0';
2905
2906
0
  if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
2907
0
    is_relative = 0;
2908
0
  else {
2909
0
    is_relative = 1;
2910
    /*
2911
     * Prepend a './' to ensure all relative
2912
     * remoteurls start with './' or '../'
2913
     */
2914
0
    if (!starts_with_dot_slash_native(remoteurl) &&
2915
0
        !starts_with_dot_dot_slash_native(remoteurl)) {
2916
0
      strbuf_reset(&sb);
2917
0
      strbuf_addf(&sb, "./%s", remoteurl);
2918
0
      free(remoteurl);
2919
0
      remoteurl = strbuf_detach(&sb, NULL);
2920
0
    }
2921
0
  }
2922
  /*
2923
   * When the url starts with '../', remove that and the
2924
   * last directory in remoteurl.
2925
   */
2926
0
  while (*url) {
2927
0
    if (starts_with_dot_dot_slash_native(url)) {
2928
0
      url += 3;
2929
0
      colonsep |= chop_last_dir(&remoteurl, is_relative);
2930
0
    } else if (starts_with_dot_slash_native(url))
2931
0
      url += 2;
2932
0
    else
2933
0
      break;
2934
0
  }
2935
0
  strbuf_reset(&sb);
2936
0
  strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
2937
0
  if (ends_with(url, "/"))
2938
0
    strbuf_setlen(&sb, sb.len - 1);
2939
0
  free(remoteurl);
2940
2941
0
  if (starts_with_dot_slash_native(sb.buf))
2942
0
    out = xstrdup(sb.buf + 2);
2943
0
  else
2944
0
    out = xstrdup(sb.buf);
2945
2946
0
  if (!up_path || !is_relative) {
2947
0
    strbuf_release(&sb);
2948
0
    return out;
2949
0
  }
2950
2951
0
  strbuf_reset(&sb);
2952
0
  strbuf_addf(&sb, "%s%s", up_path, out);
2953
0
  free(out);
2954
0
  return strbuf_detach(&sb, NULL);
2955
0
}
2956
2957
int valid_remote_name(const char *name)
2958
0
{
2959
0
  int result;
2960
0
  struct strbuf refspec = STRBUF_INIT;
2961
0
  strbuf_addf(&refspec, "refs/heads/test:refs/remotes/%s/test", name);
2962
0
  result = valid_fetch_refspec(refspec.buf);
2963
0
  strbuf_release(&refspec);
2964
0
  return result;
2965
0
}