Coverage Report

Created: 2025-12-31 07:01

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