packaging: Add contrib installation
[platform/upstream/git.git] / builtin / remote.c
1 #include "builtin.h"
2 #include "config.h"
3 #include "parse-options.h"
4 #include "transport.h"
5 #include "remote.h"
6 #include "string-list.h"
7 #include "strbuf.h"
8 #include "run-command.h"
9 #include "rebase.h"
10 #include "refs.h"
11 #include "refspec.h"
12 #include "object-store.h"
13 #include "strvec.h"
14 #include "commit-reach.h"
15
16 static const char * const builtin_remote_usage[] = {
17         N_("git remote [-v | --verbose]"),
18         N_("git remote add [-t <branch>] [-m <master>] [-f] [--tags | --no-tags] [--mirror=<fetch|push>] <name> <url>"),
19         N_("git remote rename <old> <new>"),
20         N_("git remote remove <name>"),
21         N_("git remote set-head <name> (-a | --auto | -d | --delete | <branch>)"),
22         N_("git remote [-v | --verbose] show [-n] <name>"),
23         N_("git remote prune [-n | --dry-run] <name>"),
24         N_("git remote [-v | --verbose] update [-p | --prune] [(<group> | <remote>)...]"),
25         N_("git remote set-branches [--add] <name> <branch>..."),
26         N_("git remote get-url [--push] [--all] <name>"),
27         N_("git remote set-url [--push] <name> <newurl> [<oldurl>]"),
28         N_("git remote set-url --add <name> <newurl>"),
29         N_("git remote set-url --delete <name> <url>"),
30         NULL
31 };
32
33 static const char * const builtin_remote_add_usage[] = {
34         N_("git remote add [<options>] <name> <url>"),
35         NULL
36 };
37
38 static const char * const builtin_remote_rename_usage[] = {
39         N_("git remote rename <old> <new>"),
40         NULL
41 };
42
43 static const char * const builtin_remote_rm_usage[] = {
44         N_("git remote remove <name>"),
45         NULL
46 };
47
48 static const char * const builtin_remote_sethead_usage[] = {
49         N_("git remote set-head <name> (-a | --auto | -d | --delete | <branch>)"),
50         NULL
51 };
52
53 static const char * const builtin_remote_setbranches_usage[] = {
54         N_("git remote set-branches <name> <branch>..."),
55         N_("git remote set-branches --add <name> <branch>..."),
56         NULL
57 };
58
59 static const char * const builtin_remote_show_usage[] = {
60         N_("git remote show [<options>] <name>"),
61         NULL
62 };
63
64 static const char * const builtin_remote_prune_usage[] = {
65         N_("git remote prune [<options>] <name>"),
66         NULL
67 };
68
69 static const char * const builtin_remote_update_usage[] = {
70         N_("git remote update [<options>] [<group> | <remote>]..."),
71         NULL
72 };
73
74 static const char * const builtin_remote_geturl_usage[] = {
75         N_("git remote get-url [--push] [--all] <name>"),
76         NULL
77 };
78
79 static const char * const builtin_remote_seturl_usage[] = {
80         N_("git remote set-url [--push] <name> <newurl> [<oldurl>]"),
81         N_("git remote set-url --add <name> <newurl>"),
82         N_("git remote set-url --delete <name> <url>"),
83         NULL
84 };
85
86 #define GET_REF_STATES (1<<0)
87 #define GET_HEAD_NAMES (1<<1)
88 #define GET_PUSH_REF_STATES (1<<2)
89
90 static int verbose;
91
92 static int fetch_remote(const char *name)
93 {
94         const char *argv[] = { "fetch", name, NULL, NULL };
95         if (verbose) {
96                 argv[1] = "-v";
97                 argv[2] = name;
98         }
99         printf_ln(_("Updating %s"), name);
100         if (run_command_v_opt(argv, RUN_GIT_CMD))
101                 return error(_("Could not fetch %s"), name);
102         return 0;
103 }
104
105 enum {
106         TAGS_UNSET = 0,
107         TAGS_DEFAULT = 1,
108         TAGS_SET = 2
109 };
110
111 #define MIRROR_NONE 0
112 #define MIRROR_FETCH 1
113 #define MIRROR_PUSH 2
114 #define MIRROR_BOTH (MIRROR_FETCH|MIRROR_PUSH)
115
116 static void add_branch(const char *key, const char *branchname,
117                        const char *remotename, int mirror, struct strbuf *tmp)
118 {
119         strbuf_reset(tmp);
120         strbuf_addch(tmp, '+');
121         if (mirror)
122                 strbuf_addf(tmp, "refs/%s:refs/%s",
123                                 branchname, branchname);
124         else
125                 strbuf_addf(tmp, "refs/heads/%s:refs/remotes/%s/%s",
126                                 branchname, remotename, branchname);
127         git_config_set_multivar(key, tmp->buf, "^$", 0);
128 }
129
130 static const char mirror_advice[] =
131 N_("--mirror is dangerous and deprecated; please\n"
132    "\t use --mirror=fetch or --mirror=push instead");
133
134 static int parse_mirror_opt(const struct option *opt, const char *arg, int not)
135 {
136         unsigned *mirror = opt->value;
137         if (not)
138                 *mirror = MIRROR_NONE;
139         else if (!arg) {
140                 warning("%s", _(mirror_advice));
141                 *mirror = MIRROR_BOTH;
142         }
143         else if (!strcmp(arg, "fetch"))
144                 *mirror = MIRROR_FETCH;
145         else if (!strcmp(arg, "push"))
146                 *mirror = MIRROR_PUSH;
147         else
148                 return error(_("unknown mirror argument: %s"), arg);
149         return 0;
150 }
151
152 static int add(int argc, const char **argv)
153 {
154         int fetch = 0, fetch_tags = TAGS_DEFAULT;
155         unsigned mirror = MIRROR_NONE;
156         struct string_list track = STRING_LIST_INIT_NODUP;
157         const char *master = NULL;
158         struct remote *remote;
159         struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
160         const char *name, *url;
161         int i;
162
163         struct option options[] = {
164                 OPT_BOOL('f', "fetch", &fetch, N_("fetch the remote branches")),
165                 OPT_SET_INT(0, "tags", &fetch_tags,
166                             N_("import all tags and associated objects when fetching"),
167                             TAGS_SET),
168                 OPT_SET_INT(0, NULL, &fetch_tags,
169                             N_("or do not fetch any tag at all (--no-tags)"), TAGS_UNSET),
170                 OPT_STRING_LIST('t', "track", &track, N_("branch"),
171                                 N_("branch(es) to track")),
172                 OPT_STRING('m', "master", &master, N_("branch"), N_("master branch")),
173                 OPT_CALLBACK_F(0, "mirror", &mirror, "(push|fetch)",
174                         N_("set up remote as a mirror to push to or fetch from"),
175                         PARSE_OPT_OPTARG | PARSE_OPT_COMP_ARG, parse_mirror_opt),
176                 OPT_END()
177         };
178
179         argc = parse_options(argc, argv, NULL, options, builtin_remote_add_usage,
180                              0);
181
182         if (argc != 2)
183                 usage_with_options(builtin_remote_add_usage, options);
184
185         if (mirror && master)
186                 die(_("specifying a master branch makes no sense with --mirror"));
187         if (mirror && !(mirror & MIRROR_FETCH) && track.nr)
188                 die(_("specifying branches to track makes sense only with fetch mirrors"));
189
190         name = argv[0];
191         url = argv[1];
192
193         remote = remote_get(name);
194         if (remote_is_configured(remote, 1)) {
195                 error(_("remote %s already exists."), name);
196                 exit(3);
197         }
198
199         if (!valid_remote_name(name))
200                 die(_("'%s' is not a valid remote name"), name);
201
202         strbuf_addf(&buf, "remote.%s.url", name);
203         git_config_set(buf.buf, url);
204
205         if (!mirror || mirror & MIRROR_FETCH) {
206                 strbuf_reset(&buf);
207                 strbuf_addf(&buf, "remote.%s.fetch", name);
208                 if (track.nr == 0)
209                         string_list_append(&track, "*");
210                 for (i = 0; i < track.nr; i++) {
211                         add_branch(buf.buf, track.items[i].string,
212                                    name, mirror, &buf2);
213                 }
214         }
215
216         if (mirror & MIRROR_PUSH) {
217                 strbuf_reset(&buf);
218                 strbuf_addf(&buf, "remote.%s.mirror", name);
219                 git_config_set(buf.buf, "true");
220         }
221
222         if (fetch_tags != TAGS_DEFAULT) {
223                 strbuf_reset(&buf);
224                 strbuf_addf(&buf, "remote.%s.tagopt", name);
225                 git_config_set(buf.buf,
226                                fetch_tags == TAGS_SET ? "--tags" : "--no-tags");
227         }
228
229         if (fetch && fetch_remote(name))
230                 return 1;
231
232         if (master) {
233                 strbuf_reset(&buf);
234                 strbuf_addf(&buf, "refs/remotes/%s/HEAD", name);
235
236                 strbuf_reset(&buf2);
237                 strbuf_addf(&buf2, "refs/remotes/%s/%s", name, master);
238
239                 if (create_symref(buf.buf, buf2.buf, "remote add"))
240                         return error(_("Could not setup master '%s'"), master);
241         }
242
243         strbuf_release(&buf);
244         strbuf_release(&buf2);
245         string_list_clear(&track, 0);
246
247         return 0;
248 }
249
250 struct branch_info {
251         char *remote_name;
252         struct string_list merge;
253         enum rebase_type rebase;
254         char *push_remote_name;
255 };
256
257 static struct string_list branch_list = STRING_LIST_INIT_NODUP;
258
259 static const char *abbrev_ref(const char *name, const char *prefix)
260 {
261         skip_prefix(name, prefix, &name);
262         return name;
263 }
264 #define abbrev_branch(name) abbrev_ref((name), "refs/heads/")
265
266 static int config_read_branches(const char *key, const char *value, void *cb)
267 {
268         const char *orig_key = key;
269         char *name;
270         struct string_list_item *item;
271         struct branch_info *info;
272         enum { REMOTE, MERGE, REBASE, PUSH_REMOTE } type;
273         size_t key_len;
274
275         if (!starts_with(key, "branch."))
276                 return 0;
277
278         key += strlen("branch.");
279         if (strip_suffix(key, ".remote", &key_len))
280                 type = REMOTE;
281         else if (strip_suffix(key, ".merge", &key_len))
282                 type = MERGE;
283         else if (strip_suffix(key, ".rebase", &key_len))
284                 type = REBASE;
285         else if (strip_suffix(key, ".pushremote", &key_len))
286                 type = PUSH_REMOTE;
287         else
288                 return 0;
289         name = xmemdupz(key, key_len);
290
291         item = string_list_insert(&branch_list, name);
292
293         if (!item->util)
294                 item->util = xcalloc(1, sizeof(struct branch_info));
295         info = item->util;
296         switch (type) {
297         case REMOTE:
298                 if (info->remote_name)
299                         warning(_("more than one %s"), orig_key);
300                 info->remote_name = xstrdup(value);
301                 break;
302         case MERGE: {
303                 char *space = strchr(value, ' ');
304                 value = abbrev_branch(value);
305                 while (space) {
306                         char *merge;
307                         merge = xstrndup(value, space - value);
308                         string_list_append(&info->merge, merge);
309                         value = abbrev_branch(space + 1);
310                         space = strchr(value, ' ');
311                 }
312                 string_list_append(&info->merge, xstrdup(value));
313                 break;
314         }
315         case REBASE:
316                 /*
317                  * Consider invalid values as false and check the
318                  * truth value with >= REBASE_TRUE.
319                  */
320                 info->rebase = rebase_parse_value(value);
321                 break;
322         case PUSH_REMOTE:
323                 if (info->push_remote_name)
324                         warning(_("more than one %s"), orig_key);
325                 info->push_remote_name = xstrdup(value);
326                 break;
327         default:
328                 BUG("unexpected type=%d", type);
329         }
330
331         return 0;
332 }
333
334 static void read_branches(void)
335 {
336         if (branch_list.nr)
337                 return;
338         git_config(config_read_branches, NULL);
339 }
340
341 struct ref_states {
342         struct remote *remote;
343         struct string_list new_refs, stale, tracked, heads, push;
344         int queried;
345 };
346
347 static int get_ref_states(const struct ref *remote_refs, struct ref_states *states)
348 {
349         struct ref *fetch_map = NULL, **tail = &fetch_map;
350         struct ref *ref, *stale_refs;
351         int i;
352
353         for (i = 0; i < states->remote->fetch.nr; i++)
354                 if (get_fetch_map(remote_refs, &states->remote->fetch.items[i], &tail, 1))
355                         die(_("Could not get fetch map for refspec %s"),
356                                 states->remote->fetch.raw[i]);
357
358         states->new_refs.strdup_strings = 1;
359         states->tracked.strdup_strings = 1;
360         states->stale.strdup_strings = 1;
361         for (ref = fetch_map; ref; ref = ref->next) {
362                 if (!ref->peer_ref || !ref_exists(ref->peer_ref->name))
363                         string_list_append(&states->new_refs, abbrev_branch(ref->name));
364                 else
365                         string_list_append(&states->tracked, abbrev_branch(ref->name));
366         }
367         stale_refs = get_stale_heads(&states->remote->fetch, fetch_map);
368         for (ref = stale_refs; ref; ref = ref->next) {
369                 struct string_list_item *item =
370                         string_list_append(&states->stale, abbrev_branch(ref->name));
371                 item->util = xstrdup(ref->name);
372         }
373         free_refs(stale_refs);
374         free_refs(fetch_map);
375
376         string_list_sort(&states->new_refs);
377         string_list_sort(&states->tracked);
378         string_list_sort(&states->stale);
379
380         return 0;
381 }
382
383 struct push_info {
384         char *dest;
385         int forced;
386         enum {
387                 PUSH_STATUS_CREATE = 0,
388                 PUSH_STATUS_DELETE,
389                 PUSH_STATUS_UPTODATE,
390                 PUSH_STATUS_FASTFORWARD,
391                 PUSH_STATUS_OUTOFDATE,
392                 PUSH_STATUS_NOTQUERIED
393         } status;
394 };
395
396 static int get_push_ref_states(const struct ref *remote_refs,
397         struct ref_states *states)
398 {
399         struct remote *remote = states->remote;
400         struct ref *ref, *local_refs, *push_map;
401         if (remote->mirror)
402                 return 0;
403
404         local_refs = get_local_heads();
405         push_map = copy_ref_list(remote_refs);
406
407         match_push_refs(local_refs, &push_map, &remote->push, MATCH_REFS_NONE);
408
409         states->push.strdup_strings = 1;
410         for (ref = push_map; ref; ref = ref->next) {
411                 struct string_list_item *item;
412                 struct push_info *info;
413
414                 if (!ref->peer_ref)
415                         continue;
416                 oidcpy(&ref->new_oid, &ref->peer_ref->new_oid);
417
418                 item = string_list_append(&states->push,
419                                           abbrev_branch(ref->peer_ref->name));
420                 item->util = xcalloc(1, sizeof(struct push_info));
421                 info = item->util;
422                 info->forced = ref->force;
423                 info->dest = xstrdup(abbrev_branch(ref->name));
424
425                 if (is_null_oid(&ref->new_oid)) {
426                         info->status = PUSH_STATUS_DELETE;
427                 } else if (oideq(&ref->old_oid, &ref->new_oid))
428                         info->status = PUSH_STATUS_UPTODATE;
429                 else if (is_null_oid(&ref->old_oid))
430                         info->status = PUSH_STATUS_CREATE;
431                 else if (has_object_file(&ref->old_oid) &&
432                          ref_newer(&ref->new_oid, &ref->old_oid))
433                         info->status = PUSH_STATUS_FASTFORWARD;
434                 else
435                         info->status = PUSH_STATUS_OUTOFDATE;
436         }
437         free_refs(local_refs);
438         free_refs(push_map);
439         return 0;
440 }
441
442 static int get_push_ref_states_noquery(struct ref_states *states)
443 {
444         int i;
445         struct remote *remote = states->remote;
446         struct string_list_item *item;
447         struct push_info *info;
448
449         if (remote->mirror)
450                 return 0;
451
452         states->push.strdup_strings = 1;
453         if (!remote->push.nr) {
454                 item = string_list_append(&states->push, _("(matching)"));
455                 info = item->util = xcalloc(1, sizeof(struct push_info));
456                 info->status = PUSH_STATUS_NOTQUERIED;
457                 info->dest = xstrdup(item->string);
458         }
459         for (i = 0; i < remote->push.nr; i++) {
460                 const struct refspec_item *spec = &remote->push.items[i];
461                 if (spec->matching)
462                         item = string_list_append(&states->push, _("(matching)"));
463                 else if (strlen(spec->src))
464                         item = string_list_append(&states->push, spec->src);
465                 else
466                         item = string_list_append(&states->push, _("(delete)"));
467
468                 info = item->util = xcalloc(1, sizeof(struct push_info));
469                 info->forced = spec->force;
470                 info->status = PUSH_STATUS_NOTQUERIED;
471                 info->dest = xstrdup(spec->dst ? spec->dst : item->string);
472         }
473         return 0;
474 }
475
476 static int get_head_names(const struct ref *remote_refs, struct ref_states *states)
477 {
478         struct ref *ref, *matches;
479         struct ref *fetch_map = NULL, **fetch_map_tail = &fetch_map;
480         struct refspec_item refspec;
481
482         memset(&refspec, 0, sizeof(refspec));
483         refspec.force = 0;
484         refspec.pattern = 1;
485         refspec.src = refspec.dst = "refs/heads/*";
486         states->heads.strdup_strings = 1;
487         get_fetch_map(remote_refs, &refspec, &fetch_map_tail, 0);
488         matches = guess_remote_head(find_ref_by_name(remote_refs, "HEAD"),
489                                     fetch_map, 1);
490         for (ref = matches; ref; ref = ref->next)
491                 string_list_append(&states->heads, abbrev_branch(ref->name));
492
493         free_refs(fetch_map);
494         free_refs(matches);
495
496         return 0;
497 }
498
499 struct known_remote {
500         struct known_remote *next;
501         struct remote *remote;
502 };
503
504 struct known_remotes {
505         struct remote *to_delete;
506         struct known_remote *list;
507 };
508
509 static int add_known_remote(struct remote *remote, void *cb_data)
510 {
511         struct known_remotes *all = cb_data;
512         struct known_remote *r;
513
514         if (!strcmp(all->to_delete->name, remote->name))
515                 return 0;
516
517         r = xmalloc(sizeof(*r));
518         r->remote = remote;
519         r->next = all->list;
520         all->list = r;
521         return 0;
522 }
523
524 struct branches_for_remote {
525         struct remote *remote;
526         struct string_list *branches, *skipped;
527         struct known_remotes *keep;
528 };
529
530 static int add_branch_for_removal(const char *refname,
531         const struct object_id *oid, int flags, void *cb_data)
532 {
533         struct branches_for_remote *branches = cb_data;
534         struct refspec_item refspec;
535         struct known_remote *kr;
536
537         memset(&refspec, 0, sizeof(refspec));
538         refspec.dst = (char *)refname;
539         if (remote_find_tracking(branches->remote, &refspec))
540                 return 0;
541
542         /* don't delete a branch if another remote also uses it */
543         for (kr = branches->keep->list; kr; kr = kr->next) {
544                 memset(&refspec, 0, sizeof(refspec));
545                 refspec.dst = (char *)refname;
546                 if (!remote_find_tracking(kr->remote, &refspec))
547                         return 0;
548         }
549
550         /* don't delete non-remote-tracking refs */
551         if (!starts_with(refname, "refs/remotes/")) {
552                 /* advise user how to delete local branches */
553                 if (starts_with(refname, "refs/heads/"))
554                         string_list_append(branches->skipped,
555                                            abbrev_branch(refname));
556                 /* silently skip over other non-remote refs */
557                 return 0;
558         }
559
560         string_list_append(branches->branches, refname);
561
562         return 0;
563 }
564
565 struct rename_info {
566         const char *old_name;
567         const char *new_name;
568         struct string_list *remote_branches;
569 };
570
571 static int read_remote_branches(const char *refname,
572         const struct object_id *oid, int flags, void *cb_data)
573 {
574         struct rename_info *rename = cb_data;
575         struct strbuf buf = STRBUF_INIT;
576         struct string_list_item *item;
577         int flag;
578         const char *symref;
579
580         strbuf_addf(&buf, "refs/remotes/%s/", rename->old_name);
581         if (starts_with(refname, buf.buf)) {
582                 item = string_list_append(rename->remote_branches, refname);
583                 symref = resolve_ref_unsafe(refname, RESOLVE_REF_READING,
584                                             NULL, &flag);
585                 if (symref && (flag & REF_ISSYMREF))
586                         item->util = xstrdup(symref);
587                 else
588                         item->util = NULL;
589         }
590         strbuf_release(&buf);
591
592         return 0;
593 }
594
595 static int migrate_file(struct remote *remote)
596 {
597         struct strbuf buf = STRBUF_INIT;
598         int i;
599
600         strbuf_addf(&buf, "remote.%s.url", remote->name);
601         for (i = 0; i < remote->url_nr; i++)
602                 git_config_set_multivar(buf.buf, remote->url[i], "^$", 0);
603         strbuf_reset(&buf);
604         strbuf_addf(&buf, "remote.%s.push", remote->name);
605         for (i = 0; i < remote->push.raw_nr; i++)
606                 git_config_set_multivar(buf.buf, remote->push.raw[i], "^$", 0);
607         strbuf_reset(&buf);
608         strbuf_addf(&buf, "remote.%s.fetch", remote->name);
609         for (i = 0; i < remote->fetch.raw_nr; i++)
610                 git_config_set_multivar(buf.buf, remote->fetch.raw[i], "^$", 0);
611         if (remote->origin == REMOTE_REMOTES)
612                 unlink_or_warn(git_path("remotes/%s", remote->name));
613         else if (remote->origin == REMOTE_BRANCHES)
614                 unlink_or_warn(git_path("branches/%s", remote->name));
615         strbuf_release(&buf);
616
617         return 0;
618 }
619
620 struct push_default_info
621 {
622         const char *old_name;
623         enum config_scope scope;
624         struct strbuf origin;
625         int linenr;
626 };
627
628 static int config_read_push_default(const char *key, const char *value,
629         void *cb)
630 {
631         struct push_default_info* info = cb;
632         if (strcmp(key, "remote.pushdefault") ||
633             !value || strcmp(value, info->old_name))
634                 return 0;
635
636         info->scope = current_config_scope();
637         strbuf_reset(&info->origin);
638         strbuf_addstr(&info->origin, current_config_name());
639         info->linenr = current_config_line();
640
641         return 0;
642 }
643
644 static void handle_push_default(const char* old_name, const char* new_name)
645 {
646         struct push_default_info push_default = {
647                 old_name, CONFIG_SCOPE_UNKNOWN, STRBUF_INIT, -1 };
648         git_config(config_read_push_default, &push_default);
649         if (push_default.scope >= CONFIG_SCOPE_COMMAND)
650                 ; /* pass */
651         else if (push_default.scope >= CONFIG_SCOPE_LOCAL) {
652                 int result = git_config_set_gently("remote.pushDefault",
653                                                    new_name);
654                 if (new_name && result && result != CONFIG_NOTHING_SET)
655                         die(_("could not set '%s'"), "remote.pushDefault");
656                 else if (!new_name && result && result != CONFIG_NOTHING_SET)
657                         die(_("could not unset '%s'"), "remote.pushDefault");
658         } else if (push_default.scope >= CONFIG_SCOPE_SYSTEM) {
659                 /* warn */
660                 warning(_("The %s configuration remote.pushDefault in:\n"
661                           "\t%s:%d\n"
662                           "now names the non-existent remote '%s'"),
663                         config_scope_name(push_default.scope),
664                         push_default.origin.buf, push_default.linenr,
665                         old_name);
666         }
667 }
668
669
670 static int mv(int argc, const char **argv)
671 {
672         struct option options[] = {
673                 OPT_END()
674         };
675         struct remote *oldremote, *newremote;
676         struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT, buf3 = STRBUF_INIT,
677                 old_remote_context = STRBUF_INIT;
678         struct string_list remote_branches = STRING_LIST_INIT_DUP;
679         struct rename_info rename;
680         int i, refspec_updated = 0;
681
682         if (argc != 3)
683                 usage_with_options(builtin_remote_rename_usage, options);
684
685         rename.old_name = argv[1];
686         rename.new_name = argv[2];
687         rename.remote_branches = &remote_branches;
688
689         oldremote = remote_get(rename.old_name);
690         if (!remote_is_configured(oldremote, 1)) {
691                 error(_("No such remote: '%s'"), rename.old_name);
692                 exit(2);
693         }
694
695         if (!strcmp(rename.old_name, rename.new_name) && oldremote->origin != REMOTE_CONFIG)
696                 return migrate_file(oldremote);
697
698         newremote = remote_get(rename.new_name);
699         if (remote_is_configured(newremote, 1)) {
700                 error(_("remote %s already exists."), rename.new_name);
701                 exit(3);
702         }
703
704         if (!valid_remote_name(rename.new_name))
705                 die(_("'%s' is not a valid remote name"), rename.new_name);
706
707         strbuf_addf(&buf, "remote.%s", rename.old_name);
708         strbuf_addf(&buf2, "remote.%s", rename.new_name);
709         if (git_config_rename_section(buf.buf, buf2.buf) < 1)
710                 return error(_("Could not rename config section '%s' to '%s'"),
711                                 buf.buf, buf2.buf);
712
713         strbuf_reset(&buf);
714         strbuf_addf(&buf, "remote.%s.fetch", rename.new_name);
715         git_config_set_multivar(buf.buf, NULL, NULL, CONFIG_FLAGS_MULTI_REPLACE);
716         strbuf_addf(&old_remote_context, ":refs/remotes/%s/", rename.old_name);
717         for (i = 0; i < oldremote->fetch.raw_nr; i++) {
718                 char *ptr;
719
720                 strbuf_reset(&buf2);
721                 strbuf_addstr(&buf2, oldremote->fetch.raw[i]);
722                 ptr = strstr(buf2.buf, old_remote_context.buf);
723                 if (ptr) {
724                         refspec_updated = 1;
725                         strbuf_splice(&buf2,
726                                       ptr-buf2.buf + strlen(":refs/remotes/"),
727                                       strlen(rename.old_name), rename.new_name,
728                                       strlen(rename.new_name));
729                 } else
730                         warning(_("Not updating non-default fetch refspec\n"
731                                   "\t%s\n"
732                                   "\tPlease update the configuration manually if necessary."),
733                                 buf2.buf);
734
735                 git_config_set_multivar(buf.buf, buf2.buf, "^$", 0);
736         }
737
738         read_branches();
739         for (i = 0; i < branch_list.nr; i++) {
740                 struct string_list_item *item = branch_list.items + i;
741                 struct branch_info *info = item->util;
742                 if (info->remote_name && !strcmp(info->remote_name, rename.old_name)) {
743                         strbuf_reset(&buf);
744                         strbuf_addf(&buf, "branch.%s.remote", item->string);
745                         git_config_set(buf.buf, rename.new_name);
746                 }
747                 if (info->push_remote_name && !strcmp(info->push_remote_name, rename.old_name)) {
748                         strbuf_reset(&buf);
749                         strbuf_addf(&buf, "branch.%s.pushremote", item->string);
750                         git_config_set(buf.buf, rename.new_name);
751                 }
752         }
753
754         if (!refspec_updated)
755                 return 0;
756
757         /*
758          * First remove symrefs, then rename the rest, finally create
759          * the new symrefs.
760          */
761         for_each_ref(read_remote_branches, &rename);
762         for (i = 0; i < remote_branches.nr; i++) {
763                 struct string_list_item *item = remote_branches.items + i;
764                 int flag = 0;
765
766                 read_ref_full(item->string, RESOLVE_REF_READING, NULL, &flag);
767                 if (!(flag & REF_ISSYMREF))
768                         continue;
769                 if (delete_ref(NULL, item->string, NULL, REF_NO_DEREF))
770                         die(_("deleting '%s' failed"), item->string);
771         }
772         for (i = 0; i < remote_branches.nr; i++) {
773                 struct string_list_item *item = remote_branches.items + i;
774
775                 if (item->util)
776                         continue;
777                 strbuf_reset(&buf);
778                 strbuf_addstr(&buf, item->string);
779                 strbuf_splice(&buf, strlen("refs/remotes/"), strlen(rename.old_name),
780                                 rename.new_name, strlen(rename.new_name));
781                 strbuf_reset(&buf2);
782                 strbuf_addf(&buf2, "remote: renamed %s to %s",
783                                 item->string, buf.buf);
784                 if (rename_ref(item->string, buf.buf, buf2.buf))
785                         die(_("renaming '%s' failed"), item->string);
786         }
787         for (i = 0; i < remote_branches.nr; i++) {
788                 struct string_list_item *item = remote_branches.items + i;
789
790                 if (!item->util)
791                         continue;
792                 strbuf_reset(&buf);
793                 strbuf_addstr(&buf, item->string);
794                 strbuf_splice(&buf, strlen("refs/remotes/"), strlen(rename.old_name),
795                                 rename.new_name, strlen(rename.new_name));
796                 strbuf_reset(&buf2);
797                 strbuf_addstr(&buf2, item->util);
798                 strbuf_splice(&buf2, strlen("refs/remotes/"), strlen(rename.old_name),
799                                 rename.new_name, strlen(rename.new_name));
800                 strbuf_reset(&buf3);
801                 strbuf_addf(&buf3, "remote: renamed %s to %s",
802                                 item->string, buf.buf);
803                 if (create_symref(buf.buf, buf2.buf, buf3.buf))
804                         die(_("creating '%s' failed"), buf.buf);
805         }
806         string_list_clear(&remote_branches, 1);
807
808         handle_push_default(rename.old_name, rename.new_name);
809
810         return 0;
811 }
812
813 static int rm(int argc, const char **argv)
814 {
815         struct option options[] = {
816                 OPT_END()
817         };
818         struct remote *remote;
819         struct strbuf buf = STRBUF_INIT;
820         struct known_remotes known_remotes = { NULL, NULL };
821         struct string_list branches = STRING_LIST_INIT_DUP;
822         struct string_list skipped = STRING_LIST_INIT_DUP;
823         struct branches_for_remote cb_data;
824         int i, result;
825
826         memset(&cb_data, 0, sizeof(cb_data));
827         cb_data.branches = &branches;
828         cb_data.skipped = &skipped;
829         cb_data.keep = &known_remotes;
830
831         if (argc != 2)
832                 usage_with_options(builtin_remote_rm_usage, options);
833
834         remote = remote_get(argv[1]);
835         if (!remote_is_configured(remote, 1)) {
836                 error(_("No such remote: '%s'"), argv[1]);
837                 exit(2);
838         }
839
840         known_remotes.to_delete = remote;
841         for_each_remote(add_known_remote, &known_remotes);
842
843         read_branches();
844         for (i = 0; i < branch_list.nr; i++) {
845                 struct string_list_item *item = branch_list.items + i;
846                 struct branch_info *info = item->util;
847                 if (info->remote_name && !strcmp(info->remote_name, remote->name)) {
848                         const char *keys[] = { "remote", "merge", NULL }, **k;
849                         for (k = keys; *k; k++) {
850                                 strbuf_reset(&buf);
851                                 strbuf_addf(&buf, "branch.%s.%s",
852                                                 item->string, *k);
853                                 result = git_config_set_gently(buf.buf, NULL);
854                                 if (result && result != CONFIG_NOTHING_SET)
855                                         die(_("could not unset '%s'"), buf.buf);
856                         }
857                 }
858                 if (info->push_remote_name && !strcmp(info->push_remote_name, remote->name)) {
859                         strbuf_reset(&buf);
860                         strbuf_addf(&buf, "branch.%s.pushremote", item->string);
861                         result = git_config_set_gently(buf.buf, NULL);
862                         if (result && result != CONFIG_NOTHING_SET)
863                                 die(_("could not unset '%s'"), buf.buf);
864                 }
865         }
866
867         /*
868          * We cannot just pass a function to for_each_ref() which deletes
869          * the branches one by one, since for_each_ref() relies on cached
870          * refs, which are invalidated when deleting a branch.
871          */
872         cb_data.remote = remote;
873         result = for_each_ref(add_branch_for_removal, &cb_data);
874         strbuf_release(&buf);
875
876         if (!result)
877                 result = delete_refs("remote: remove", &branches, REF_NO_DEREF);
878         string_list_clear(&branches, 0);
879
880         if (skipped.nr) {
881                 fprintf_ln(stderr,
882                            Q_("Note: A branch outside the refs/remotes/ hierarchy was not removed;\n"
883                               "to delete it, use:",
884                               "Note: Some branches outside the refs/remotes/ hierarchy were not removed;\n"
885                               "to delete them, use:",
886                               skipped.nr));
887                 for (i = 0; i < skipped.nr; i++)
888                         fprintf(stderr, "  git branch -d %s\n",
889                                 skipped.items[i].string);
890         }
891         string_list_clear(&skipped, 0);
892
893         if (!result) {
894                 strbuf_addf(&buf, "remote.%s", remote->name);
895                 if (git_config_rename_section(buf.buf, NULL) < 1)
896                         return error(_("Could not remove config section '%s'"), buf.buf);
897
898                 handle_push_default(remote->name, NULL);
899         }
900
901         return result;
902 }
903
904 static void clear_push_info(void *util, const char *string)
905 {
906         struct push_info *info = util;
907         free(info->dest);
908         free(info);
909 }
910
911 static void free_remote_ref_states(struct ref_states *states)
912 {
913         string_list_clear(&states->new_refs, 0);
914         string_list_clear(&states->stale, 1);
915         string_list_clear(&states->tracked, 0);
916         string_list_clear(&states->heads, 0);
917         string_list_clear_func(&states->push, clear_push_info);
918 }
919
920 static int append_ref_to_tracked_list(const char *refname,
921         const struct object_id *oid, int flags, void *cb_data)
922 {
923         struct ref_states *states = cb_data;
924         struct refspec_item refspec;
925
926         if (flags & REF_ISSYMREF)
927                 return 0;
928
929         memset(&refspec, 0, sizeof(refspec));
930         refspec.dst = (char *)refname;
931         if (!remote_find_tracking(states->remote, &refspec))
932                 string_list_append(&states->tracked, abbrev_branch(refspec.src));
933
934         return 0;
935 }
936
937 static int get_remote_ref_states(const char *name,
938                                  struct ref_states *states,
939                                  int query)
940 {
941         struct transport *transport;
942         const struct ref *remote_refs;
943
944         states->remote = remote_get(name);
945         if (!states->remote)
946                 return error(_("No such remote: '%s'"), name);
947
948         read_branches();
949
950         if (query) {
951                 transport = transport_get(states->remote, states->remote->url_nr > 0 ?
952                         states->remote->url[0] : NULL);
953                 remote_refs = transport_get_remote_refs(transport, NULL);
954                 transport_disconnect(transport);
955
956                 states->queried = 1;
957                 if (query & GET_REF_STATES)
958                         get_ref_states(remote_refs, states);
959                 if (query & GET_HEAD_NAMES)
960                         get_head_names(remote_refs, states);
961                 if (query & GET_PUSH_REF_STATES)
962                         get_push_ref_states(remote_refs, states);
963         } else {
964                 for_each_ref(append_ref_to_tracked_list, states);
965                 string_list_sort(&states->tracked);
966                 get_push_ref_states_noquery(states);
967         }
968
969         return 0;
970 }
971
972 struct show_info {
973         struct string_list *list;
974         struct ref_states *states;
975         int width, width2;
976         int any_rebase;
977 };
978
979 static int add_remote_to_show_info(struct string_list_item *item, void *cb_data)
980 {
981         struct show_info *info = cb_data;
982         int n = strlen(item->string);
983         if (n > info->width)
984                 info->width = n;
985         string_list_insert(info->list, item->string);
986         return 0;
987 }
988
989 static int show_remote_info_item(struct string_list_item *item, void *cb_data)
990 {
991         struct show_info *info = cb_data;
992         struct ref_states *states = info->states;
993         const char *name = item->string;
994
995         if (states->queried) {
996                 const char *fmt = "%s";
997                 const char *arg = "";
998                 if (string_list_has_string(&states->new_refs, name)) {
999                         fmt = _(" new (next fetch will store in remotes/%s)");
1000                         arg = states->remote->name;
1001                 } else if (string_list_has_string(&states->tracked, name))
1002                         arg = _(" tracked");
1003                 else if (string_list_has_string(&states->stale, name))
1004                         arg = _(" stale (use 'git remote prune' to remove)");
1005                 else
1006                         arg = _(" ???");
1007                 printf("    %-*s", info->width, name);
1008                 printf(fmt, arg);
1009                 printf("\n");
1010         } else
1011                 printf("    %s\n", name);
1012
1013         return 0;
1014 }
1015
1016 static int add_local_to_show_info(struct string_list_item *branch_item, void *cb_data)
1017 {
1018         struct show_info *show_info = cb_data;
1019         struct ref_states *states = show_info->states;
1020         struct branch_info *branch_info = branch_item->util;
1021         struct string_list_item *item;
1022         int n;
1023
1024         if (!branch_info->merge.nr || !branch_info->remote_name ||
1025             strcmp(states->remote->name, branch_info->remote_name))
1026                 return 0;
1027         if ((n = strlen(branch_item->string)) > show_info->width)
1028                 show_info->width = n;
1029         if (branch_info->rebase >= REBASE_TRUE)
1030                 show_info->any_rebase = 1;
1031
1032         item = string_list_insert(show_info->list, branch_item->string);
1033         item->util = branch_info;
1034
1035         return 0;
1036 }
1037
1038 static int show_local_info_item(struct string_list_item *item, void *cb_data)
1039 {
1040         struct show_info *show_info = cb_data;
1041         struct branch_info *branch_info = item->util;
1042         struct string_list *merge = &branch_info->merge;
1043         int width = show_info->width + 4;
1044         int i;
1045
1046         if (branch_info->rebase >= REBASE_TRUE && branch_info->merge.nr > 1) {
1047                 error(_("invalid branch.%s.merge; cannot rebase onto > 1 branch"),
1048                         item->string);
1049                 return 0;
1050         }
1051
1052         printf("    %-*s ", show_info->width, item->string);
1053         if (branch_info->rebase >= REBASE_TRUE) {
1054                 const char *msg;
1055                 if (branch_info->rebase == REBASE_INTERACTIVE)
1056                         msg = _("rebases interactively onto remote %s");
1057                 else if (branch_info->rebase == REBASE_MERGES)
1058                         msg = _("rebases interactively (with merges) onto "
1059                                 "remote %s");
1060                 else
1061                         msg = _("rebases onto remote %s");
1062                 printf_ln(msg, merge->items[0].string);
1063                 return 0;
1064         } else if (show_info->any_rebase) {
1065                 printf_ln(_(" merges with remote %s"), merge->items[0].string);
1066                 width++;
1067         } else {
1068                 printf_ln(_("merges with remote %s"), merge->items[0].string);
1069         }
1070         for (i = 1; i < merge->nr; i++)
1071                 printf(_("%-*s    and with remote %s\n"), width, "",
1072                        merge->items[i].string);
1073
1074         return 0;
1075 }
1076
1077 static int add_push_to_show_info(struct string_list_item *push_item, void *cb_data)
1078 {
1079         struct show_info *show_info = cb_data;
1080         struct push_info *push_info = push_item->util;
1081         struct string_list_item *item;
1082         int n;
1083         if ((n = strlen(push_item->string)) > show_info->width)
1084                 show_info->width = n;
1085         if ((n = strlen(push_info->dest)) > show_info->width2)
1086                 show_info->width2 = n;
1087         item = string_list_append(show_info->list, push_item->string);
1088         item->util = push_item->util;
1089         return 0;
1090 }
1091
1092 /*
1093  * Sorting comparison for a string list that has push_info
1094  * structs in its util field
1095  */
1096 static int cmp_string_with_push(const void *va, const void *vb)
1097 {
1098         const struct string_list_item *a = va;
1099         const struct string_list_item *b = vb;
1100         const struct push_info *a_push = a->util;
1101         const struct push_info *b_push = b->util;
1102         int cmp = strcmp(a->string, b->string);
1103         return cmp ? cmp : strcmp(a_push->dest, b_push->dest);
1104 }
1105
1106 static int show_push_info_item(struct string_list_item *item, void *cb_data)
1107 {
1108         struct show_info *show_info = cb_data;
1109         struct push_info *push_info = item->util;
1110         const char *src = item->string, *status = NULL;
1111
1112         switch (push_info->status) {
1113         case PUSH_STATUS_CREATE:
1114                 status = _("create");
1115                 break;
1116         case PUSH_STATUS_DELETE:
1117                 status = _("delete");
1118                 src = _("(none)");
1119                 break;
1120         case PUSH_STATUS_UPTODATE:
1121                 status = _("up to date");
1122                 break;
1123         case PUSH_STATUS_FASTFORWARD:
1124                 status = _("fast-forwardable");
1125                 break;
1126         case PUSH_STATUS_OUTOFDATE:
1127                 status = _("local out of date");
1128                 break;
1129         case PUSH_STATUS_NOTQUERIED:
1130                 break;
1131         }
1132         if (status) {
1133                 if (push_info->forced)
1134                         printf_ln(_("    %-*s forces to %-*s (%s)"), show_info->width, src,
1135                                show_info->width2, push_info->dest, status);
1136                 else
1137                         printf_ln(_("    %-*s pushes to %-*s (%s)"), show_info->width, src,
1138                                show_info->width2, push_info->dest, status);
1139         } else {
1140                 if (push_info->forced)
1141                         printf_ln(_("    %-*s forces to %s"), show_info->width, src,
1142                                push_info->dest);
1143                 else
1144                         printf_ln(_("    %-*s pushes to %s"), show_info->width, src,
1145                                push_info->dest);
1146         }
1147         return 0;
1148 }
1149
1150 static int get_one_entry(struct remote *remote, void *priv)
1151 {
1152         struct string_list *list = priv;
1153         struct strbuf url_buf = STRBUF_INIT;
1154         const char **url;
1155         int i, url_nr;
1156
1157         if (remote->url_nr > 0) {
1158                 strbuf_addf(&url_buf, "%s (fetch)", remote->url[0]);
1159                 string_list_append(list, remote->name)->util =
1160                                 strbuf_detach(&url_buf, NULL);
1161         } else
1162                 string_list_append(list, remote->name)->util = NULL;
1163         if (remote->pushurl_nr) {
1164                 url = remote->pushurl;
1165                 url_nr = remote->pushurl_nr;
1166         } else {
1167                 url = remote->url;
1168                 url_nr = remote->url_nr;
1169         }
1170         for (i = 0; i < url_nr; i++)
1171         {
1172                 strbuf_addf(&url_buf, "%s (push)", url[i]);
1173                 string_list_append(list, remote->name)->util =
1174                                 strbuf_detach(&url_buf, NULL);
1175         }
1176
1177         return 0;
1178 }
1179
1180 static int show_all(void)
1181 {
1182         struct string_list list = STRING_LIST_INIT_NODUP;
1183         int result;
1184
1185         list.strdup_strings = 1;
1186         result = for_each_remote(get_one_entry, &list);
1187
1188         if (!result) {
1189                 int i;
1190
1191                 string_list_sort(&list);
1192                 for (i = 0; i < list.nr; i++) {
1193                         struct string_list_item *item = list.items + i;
1194                         if (verbose)
1195                                 printf("%s\t%s\n", item->string,
1196                                         item->util ? (const char *)item->util : "");
1197                         else {
1198                                 if (i && !strcmp((item - 1)->string, item->string))
1199                                         continue;
1200                                 printf("%s\n", item->string);
1201                         }
1202                 }
1203         }
1204         string_list_clear(&list, 1);
1205         return result;
1206 }
1207
1208 static int show(int argc, const char **argv)
1209 {
1210         int no_query = 0, result = 0, query_flag = 0;
1211         struct option options[] = {
1212                 OPT_BOOL('n', NULL, &no_query, N_("do not query remotes")),
1213                 OPT_END()
1214         };
1215         struct ref_states states;
1216         struct string_list info_list = STRING_LIST_INIT_NODUP;
1217         struct show_info info;
1218
1219         argc = parse_options(argc, argv, NULL, options, builtin_remote_show_usage,
1220                              0);
1221
1222         if (argc < 1)
1223                 return show_all();
1224
1225         if (!no_query)
1226                 query_flag = (GET_REF_STATES | GET_HEAD_NAMES | GET_PUSH_REF_STATES);
1227
1228         memset(&states, 0, sizeof(states));
1229         memset(&info, 0, sizeof(info));
1230         info.states = &states;
1231         info.list = &info_list;
1232         for (; argc; argc--, argv++) {
1233                 int i;
1234                 const char **url;
1235                 int url_nr;
1236
1237                 get_remote_ref_states(*argv, &states, query_flag);
1238
1239                 printf_ln(_("* remote %s"), *argv);
1240                 printf_ln(_("  Fetch URL: %s"), states.remote->url_nr > 0 ?
1241                        states.remote->url[0] : _("(no URL)"));
1242                 if (states.remote->pushurl_nr) {
1243                         url = states.remote->pushurl;
1244                         url_nr = states.remote->pushurl_nr;
1245                 } else {
1246                         url = states.remote->url;
1247                         url_nr = states.remote->url_nr;
1248                 }
1249                 for (i = 0; i < url_nr; i++)
1250                         /*
1251                          * TRANSLATORS: the colon ':' should align
1252                          * with the one in " Fetch URL: %s"
1253                          * translation.
1254                          */
1255                         printf_ln(_("  Push  URL: %s"), url[i]);
1256                 if (!i)
1257                         printf_ln(_("  Push  URL: %s"), _("(no URL)"));
1258                 if (no_query)
1259                         printf_ln(_("  HEAD branch: %s"), _("(not queried)"));
1260                 else if (!states.heads.nr)
1261                         printf_ln(_("  HEAD branch: %s"), _("(unknown)"));
1262                 else if (states.heads.nr == 1)
1263                         printf_ln(_("  HEAD branch: %s"), states.heads.items[0].string);
1264                 else {
1265                         printf(_("  HEAD branch (remote HEAD is ambiguous,"
1266                                  " may be one of the following):\n"));
1267                         for (i = 0; i < states.heads.nr; i++)
1268                                 printf("    %s\n", states.heads.items[i].string);
1269                 }
1270
1271                 /* remote branch info */
1272                 info.width = 0;
1273                 for_each_string_list(&states.new_refs, add_remote_to_show_info, &info);
1274                 for_each_string_list(&states.tracked, add_remote_to_show_info, &info);
1275                 for_each_string_list(&states.stale, add_remote_to_show_info, &info);
1276                 if (info.list->nr)
1277                         printf_ln(Q_("  Remote branch:%s",
1278                                      "  Remote branches:%s",
1279                                      info.list->nr),
1280                                   no_query ? _(" (status not queried)") : "");
1281                 for_each_string_list(info.list, show_remote_info_item, &info);
1282                 string_list_clear(info.list, 0);
1283
1284                 /* git pull info */
1285                 info.width = 0;
1286                 info.any_rebase = 0;
1287                 for_each_string_list(&branch_list, add_local_to_show_info, &info);
1288                 if (info.list->nr)
1289                         printf_ln(Q_("  Local branch configured for 'git pull':",
1290                                      "  Local branches configured for 'git pull':",
1291                                      info.list->nr));
1292                 for_each_string_list(info.list, show_local_info_item, &info);
1293                 string_list_clear(info.list, 0);
1294
1295                 /* git push info */
1296                 if (states.remote->mirror)
1297                         printf_ln(_("  Local refs will be mirrored by 'git push'"));
1298
1299                 info.width = info.width2 = 0;
1300                 for_each_string_list(&states.push, add_push_to_show_info, &info);
1301                 QSORT(info.list->items, info.list->nr, cmp_string_with_push);
1302                 if (info.list->nr)
1303                         printf_ln(Q_("  Local ref configured for 'git push'%s:",
1304                                      "  Local refs configured for 'git push'%s:",
1305                                      info.list->nr),
1306                                   no_query ? _(" (status not queried)") : "");
1307                 for_each_string_list(info.list, show_push_info_item, &info);
1308                 string_list_clear(info.list, 0);
1309
1310                 free_remote_ref_states(&states);
1311         }
1312
1313         return result;
1314 }
1315
1316 static int set_head(int argc, const char **argv)
1317 {
1318         int i, opt_a = 0, opt_d = 0, result = 0;
1319         struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT;
1320         char *head_name = NULL;
1321
1322         struct option options[] = {
1323                 OPT_BOOL('a', "auto", &opt_a,
1324                          N_("set refs/remotes/<name>/HEAD according to remote")),
1325                 OPT_BOOL('d', "delete", &opt_d,
1326                          N_("delete refs/remotes/<name>/HEAD")),
1327                 OPT_END()
1328         };
1329         argc = parse_options(argc, argv, NULL, options, builtin_remote_sethead_usage,
1330                              0);
1331         if (argc)
1332                 strbuf_addf(&buf, "refs/remotes/%s/HEAD", argv[0]);
1333
1334         if (!opt_a && !opt_d && argc == 2) {
1335                 head_name = xstrdup(argv[1]);
1336         } else if (opt_a && !opt_d && argc == 1) {
1337                 struct ref_states states;
1338                 memset(&states, 0, sizeof(states));
1339                 get_remote_ref_states(argv[0], &states, GET_HEAD_NAMES);
1340                 if (!states.heads.nr)
1341                         result |= error(_("Cannot determine remote HEAD"));
1342                 else if (states.heads.nr > 1) {
1343                         result |= error(_("Multiple remote HEAD branches. "
1344                                           "Please choose one explicitly with:"));
1345                         for (i = 0; i < states.heads.nr; i++)
1346                                 fprintf(stderr, "  git remote set-head %s %s\n",
1347                                         argv[0], states.heads.items[i].string);
1348                 } else
1349                         head_name = xstrdup(states.heads.items[0].string);
1350                 free_remote_ref_states(&states);
1351         } else if (opt_d && !opt_a && argc == 1) {
1352                 if (delete_ref(NULL, buf.buf, NULL, REF_NO_DEREF))
1353                         result |= error(_("Could not delete %s"), buf.buf);
1354         } else
1355                 usage_with_options(builtin_remote_sethead_usage, options);
1356
1357         if (head_name) {
1358                 strbuf_addf(&buf2, "refs/remotes/%s/%s", argv[0], head_name);
1359                 /* make sure it's valid */
1360                 if (!ref_exists(buf2.buf))
1361                         result |= error(_("Not a valid ref: %s"), buf2.buf);
1362                 else if (create_symref(buf.buf, buf2.buf, "remote set-head"))
1363                         result |= error(_("Could not setup %s"), buf.buf);
1364                 else if (opt_a)
1365                         printf("%s/HEAD set to %s\n", argv[0], head_name);
1366                 free(head_name);
1367         }
1368
1369         strbuf_release(&buf);
1370         strbuf_release(&buf2);
1371         return result;
1372 }
1373
1374 static int prune_remote(const char *remote, int dry_run)
1375 {
1376         int result = 0;
1377         struct ref_states states;
1378         struct string_list refs_to_prune = STRING_LIST_INIT_NODUP;
1379         struct string_list_item *item;
1380         const char *dangling_msg = dry_run
1381                 ? _(" %s will become dangling!")
1382                 : _(" %s has become dangling!");
1383
1384         memset(&states, 0, sizeof(states));
1385         get_remote_ref_states(remote, &states, GET_REF_STATES);
1386
1387         if (!states.stale.nr) {
1388                 free_remote_ref_states(&states);
1389                 return 0;
1390         }
1391
1392         printf_ln(_("Pruning %s"), remote);
1393         printf_ln(_("URL: %s"),
1394                   states.remote->url_nr
1395                   ? states.remote->url[0]
1396                   : _("(no URL)"));
1397
1398         for_each_string_list_item(item, &states.stale)
1399                 string_list_append(&refs_to_prune, item->util);
1400         string_list_sort(&refs_to_prune);
1401
1402         if (!dry_run)
1403                 result |= delete_refs("remote: prune", &refs_to_prune, 0);
1404
1405         for_each_string_list_item(item, &states.stale) {
1406                 const char *refname = item->util;
1407
1408                 if (dry_run)
1409                         printf_ln(_(" * [would prune] %s"),
1410                                abbrev_ref(refname, "refs/remotes/"));
1411                 else
1412                         printf_ln(_(" * [pruned] %s"),
1413                                abbrev_ref(refname, "refs/remotes/"));
1414         }
1415
1416         warn_dangling_symrefs(stdout, dangling_msg, &refs_to_prune);
1417
1418         string_list_clear(&refs_to_prune, 0);
1419         free_remote_ref_states(&states);
1420         return result;
1421 }
1422
1423 static int prune(int argc, const char **argv)
1424 {
1425         int dry_run = 0, result = 0;
1426         struct option options[] = {
1427                 OPT__DRY_RUN(&dry_run, N_("dry run")),
1428                 OPT_END()
1429         };
1430
1431         argc = parse_options(argc, argv, NULL, options, builtin_remote_prune_usage,
1432                              0);
1433
1434         if (argc < 1)
1435                 usage_with_options(builtin_remote_prune_usage, options);
1436
1437         for (; argc; argc--, argv++)
1438                 result |= prune_remote(*argv, dry_run);
1439
1440         return result;
1441 }
1442
1443 static int get_remote_default(const char *key, const char *value, void *priv)
1444 {
1445         if (strcmp(key, "remotes.default") == 0) {
1446                 int *found = priv;
1447                 *found = 1;
1448         }
1449         return 0;
1450 }
1451
1452 static int update(int argc, const char **argv)
1453 {
1454         int i, prune = -1;
1455         struct option options[] = {
1456                 OPT_BOOL('p', "prune", &prune,
1457                          N_("prune remotes after fetching")),
1458                 OPT_END()
1459         };
1460         struct strvec fetch_argv = STRVEC_INIT;
1461         int default_defined = 0;
1462         int retval;
1463
1464         argc = parse_options(argc, argv, NULL, options, builtin_remote_update_usage,
1465                              PARSE_OPT_KEEP_ARGV0);
1466
1467         strvec_push(&fetch_argv, "fetch");
1468
1469         if (prune != -1)
1470                 strvec_push(&fetch_argv, prune ? "--prune" : "--no-prune");
1471         if (verbose)
1472                 strvec_push(&fetch_argv, "-v");
1473         strvec_push(&fetch_argv, "--multiple");
1474         if (argc < 2)
1475                 strvec_push(&fetch_argv, "default");
1476         for (i = 1; i < argc; i++)
1477                 strvec_push(&fetch_argv, argv[i]);
1478
1479         if (strcmp(fetch_argv.v[fetch_argv.nr-1], "default") == 0) {
1480                 git_config(get_remote_default, &default_defined);
1481                 if (!default_defined) {
1482                         strvec_pop(&fetch_argv);
1483                         strvec_push(&fetch_argv, "--all");
1484                 }
1485         }
1486
1487         retval = run_command_v_opt(fetch_argv.v, RUN_GIT_CMD);
1488         strvec_clear(&fetch_argv);
1489         return retval;
1490 }
1491
1492 static int remove_all_fetch_refspecs(const char *key)
1493 {
1494         return git_config_set_multivar_gently(key, NULL, NULL,
1495                                               CONFIG_FLAGS_MULTI_REPLACE);
1496 }
1497
1498 static void add_branches(struct remote *remote, const char **branches,
1499                          const char *key)
1500 {
1501         const char *remotename = remote->name;
1502         int mirror = remote->mirror;
1503         struct strbuf refspec = STRBUF_INIT;
1504
1505         for (; *branches; branches++)
1506                 add_branch(key, *branches, remotename, mirror, &refspec);
1507
1508         strbuf_release(&refspec);
1509 }
1510
1511 static int set_remote_branches(const char *remotename, const char **branches,
1512                                 int add_mode)
1513 {
1514         struct strbuf key = STRBUF_INIT;
1515         struct remote *remote;
1516
1517         strbuf_addf(&key, "remote.%s.fetch", remotename);
1518
1519         remote = remote_get(remotename);
1520         if (!remote_is_configured(remote, 1)) {
1521                 error(_("No such remote '%s'"), remotename);
1522                 exit(2);
1523         }
1524
1525         if (!add_mode && remove_all_fetch_refspecs(key.buf)) {
1526                 strbuf_release(&key);
1527                 return 1;
1528         }
1529         add_branches(remote, branches, key.buf);
1530
1531         strbuf_release(&key);
1532         return 0;
1533 }
1534
1535 static int set_branches(int argc, const char **argv)
1536 {
1537         int add_mode = 0;
1538         struct option options[] = {
1539                 OPT_BOOL('\0', "add", &add_mode, N_("add branch")),
1540                 OPT_END()
1541         };
1542
1543         argc = parse_options(argc, argv, NULL, options,
1544                              builtin_remote_setbranches_usage, 0);
1545         if (argc == 0) {
1546                 error(_("no remote specified"));
1547                 usage_with_options(builtin_remote_setbranches_usage, options);
1548         }
1549         argv[argc] = NULL;
1550
1551         return set_remote_branches(argv[0], argv + 1, add_mode);
1552 }
1553
1554 static int get_url(int argc, const char **argv)
1555 {
1556         int i, push_mode = 0, all_mode = 0;
1557         const char *remotename = NULL;
1558         struct remote *remote;
1559         const char **url;
1560         int url_nr;
1561         struct option options[] = {
1562                 OPT_BOOL('\0', "push", &push_mode,
1563                          N_("query push URLs rather than fetch URLs")),
1564                 OPT_BOOL('\0', "all", &all_mode,
1565                          N_("return all URLs")),
1566                 OPT_END()
1567         };
1568         argc = parse_options(argc, argv, NULL, options, builtin_remote_geturl_usage, 0);
1569
1570         if (argc != 1)
1571                 usage_with_options(builtin_remote_geturl_usage, options);
1572
1573         remotename = argv[0];
1574
1575         remote = remote_get(remotename);
1576         if (!remote_is_configured(remote, 1)) {
1577                 error(_("No such remote '%s'"), remotename);
1578                 exit(2);
1579         }
1580
1581         url_nr = 0;
1582         if (push_mode) {
1583                 url = remote->pushurl;
1584                 url_nr = remote->pushurl_nr;
1585         }
1586         /* else fetch mode */
1587
1588         /* Use the fetch URL when no push URLs were found or requested. */
1589         if (!url_nr) {
1590                 url = remote->url;
1591                 url_nr = remote->url_nr;
1592         }
1593
1594         if (!url_nr)
1595                 die(_("no URLs configured for remote '%s'"), remotename);
1596
1597         if (all_mode) {
1598                 for (i = 0; i < url_nr; i++)
1599                         printf_ln("%s", url[i]);
1600         } else {
1601                 printf_ln("%s", *url);
1602         }
1603
1604         return 0;
1605 }
1606
1607 static int set_url(int argc, const char **argv)
1608 {
1609         int i, push_mode = 0, add_mode = 0, delete_mode = 0;
1610         int matches = 0, negative_matches = 0;
1611         const char *remotename = NULL;
1612         const char *newurl = NULL;
1613         const char *oldurl = NULL;
1614         struct remote *remote;
1615         regex_t old_regex;
1616         const char **urlset;
1617         int urlset_nr;
1618         struct strbuf name_buf = STRBUF_INIT;
1619         struct option options[] = {
1620                 OPT_BOOL('\0', "push", &push_mode,
1621                          N_("manipulate push URLs")),
1622                 OPT_BOOL('\0', "add", &add_mode,
1623                          N_("add URL")),
1624                 OPT_BOOL('\0', "delete", &delete_mode,
1625                             N_("delete URLs")),
1626                 OPT_END()
1627         };
1628         argc = parse_options(argc, argv, NULL, options, builtin_remote_seturl_usage,
1629                              PARSE_OPT_KEEP_ARGV0);
1630
1631         if (add_mode && delete_mode)
1632                 die(_("--add --delete doesn't make sense"));
1633
1634         if (argc < 3 || argc > 4 || ((add_mode || delete_mode) && argc != 3))
1635                 usage_with_options(builtin_remote_seturl_usage, options);
1636
1637         remotename = argv[1];
1638         newurl = argv[2];
1639         if (argc > 3)
1640                 oldurl = argv[3];
1641
1642         if (delete_mode)
1643                 oldurl = newurl;
1644
1645         remote = remote_get(remotename);
1646         if (!remote_is_configured(remote, 1)) {
1647                 error(_("No such remote '%s'"), remotename);
1648                 exit(2);
1649         }
1650
1651         if (push_mode) {
1652                 strbuf_addf(&name_buf, "remote.%s.pushurl", remotename);
1653                 urlset = remote->pushurl;
1654                 urlset_nr = remote->pushurl_nr;
1655         } else {
1656                 strbuf_addf(&name_buf, "remote.%s.url", remotename);
1657                 urlset = remote->url;
1658                 urlset_nr = remote->url_nr;
1659         }
1660
1661         /* Special cases that add new entry. */
1662         if ((!oldurl && !delete_mode) || add_mode) {
1663                 if (add_mode)
1664                         git_config_set_multivar(name_buf.buf, newurl,
1665                                                        "^$", 0);
1666                 else
1667                         git_config_set(name_buf.buf, newurl);
1668                 goto out;
1669         }
1670
1671         /* Old URL specified. Demand that one matches. */
1672         if (regcomp(&old_regex, oldurl, REG_EXTENDED))
1673                 die(_("Invalid old URL pattern: %s"), oldurl);
1674
1675         for (i = 0; i < urlset_nr; i++)
1676                 if (!regexec(&old_regex, urlset[i], 0, NULL, 0))
1677                         matches++;
1678                 else
1679                         negative_matches++;
1680         if (!delete_mode && !matches)
1681                 die(_("No such URL found: %s"), oldurl);
1682         if (delete_mode && !negative_matches && !push_mode)
1683                 die(_("Will not delete all non-push URLs"));
1684
1685         regfree(&old_regex);
1686
1687         if (!delete_mode)
1688                 git_config_set_multivar(name_buf.buf, newurl, oldurl, 0);
1689         else
1690                 git_config_set_multivar(name_buf.buf, NULL, oldurl,
1691                                         CONFIG_FLAGS_MULTI_REPLACE);
1692 out:
1693         strbuf_release(&name_buf);
1694         return 0;
1695 }
1696
1697 int cmd_remote(int argc, const char **argv, const char *prefix)
1698 {
1699         struct option options[] = {
1700                 OPT__VERBOSE(&verbose, N_("be verbose; must be placed before a subcommand")),
1701                 OPT_END()
1702         };
1703         int result;
1704
1705         argc = parse_options(argc, argv, prefix, options, builtin_remote_usage,
1706                 PARSE_OPT_STOP_AT_NON_OPTION);
1707
1708         if (argc < 1)
1709                 result = show_all();
1710         else if (!strcmp(argv[0], "add"))
1711                 result = add(argc, argv);
1712         else if (!strcmp(argv[0], "rename"))
1713                 result = mv(argc, argv);
1714         else if (!strcmp(argv[0], "rm") || !strcmp(argv[0], "remove"))
1715                 result = rm(argc, argv);
1716         else if (!strcmp(argv[0], "set-head"))
1717                 result = set_head(argc, argv);
1718         else if (!strcmp(argv[0], "set-branches"))
1719                 result = set_branches(argc, argv);
1720         else if (!strcmp(argv[0], "get-url"))
1721                 result = get_url(argc, argv);
1722         else if (!strcmp(argv[0], "set-url"))
1723                 result = set_url(argc, argv);
1724         else if (!strcmp(argv[0], "show"))
1725                 result = show(argc, argv);
1726         else if (!strcmp(argv[0], "prune"))
1727                 result = prune(argc, argv);
1728         else if (!strcmp(argv[0], "update"))
1729                 result = update(argc, argv);
1730         else {
1731                 error(_("Unknown subcommand: %s"), argv[0]);
1732                 usage_with_options(builtin_remote_usage, options);
1733         }
1734
1735         return result ? 1 : 0;
1736 }