Coverage Report

Created: 2026-02-26 06:44

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