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