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