Coverage Report

Created: 2024-09-08 06:23

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