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