submodule: eliminate unused parameters from print_submodule_summary()
[git] / builtin / submodule--helper.c
1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
2 #include "builtin.h"
3 #include "repository.h"
4 #include "cache.h"
5 #include "config.h"
6 #include "parse-options.h"
7 #include "quote.h"
8 #include "pathspec.h"
9 #include "dir.h"
10 #include "submodule.h"
11 #include "submodule-config.h"
12 #include "string-list.h"
13 #include "run-command.h"
14 #include "remote.h"
15 #include "refs.h"
16 #include "refspec.h"
17 #include "connect.h"
18 #include "revision.h"
19 #include "diffcore.h"
20 #include "diff.h"
21 #include "object-store.h"
22 #include "dir.h"
23 #include "advice.h"
24
25 #define OPT_QUIET (1 << 0)
26 #define OPT_CACHED (1 << 1)
27 #define OPT_RECURSIVE (1 << 2)
28 #define OPT_FORCE (1 << 3)
29
30 typedef void (*each_submodule_fn)(const struct cache_entry *list_item,
31                                   void *cb_data);
32
33 static char *get_default_remote(void)
34 {
35         char *dest = NULL, *ret;
36         struct strbuf sb = STRBUF_INIT;
37         const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
38
39         if (!refname)
40                 die(_("No such ref: %s"), "HEAD");
41
42         /* detached HEAD */
43         if (!strcmp(refname, "HEAD"))
44                 return xstrdup("origin");
45
46         if (!skip_prefix(refname, "refs/heads/", &refname))
47                 die(_("Expecting a full ref name, got %s"), refname);
48
49         strbuf_addf(&sb, "branch.%s.remote", refname);
50         if (git_config_get_string(sb.buf, &dest))
51                 ret = xstrdup("origin");
52         else
53                 ret = dest;
54
55         strbuf_release(&sb);
56         return ret;
57 }
58
59 static int print_default_remote(int argc, const char **argv, const char *prefix)
60 {
61         char *remote;
62
63         if (argc != 1)
64                 die(_("submodule--helper print-default-remote takes no arguments"));
65
66         remote = get_default_remote();
67         if (remote)
68                 printf("%s\n", remote);
69
70         free(remote);
71         return 0;
72 }
73
74 static int starts_with_dot_slash(const char *str)
75 {
76         return str[0] == '.' && is_dir_sep(str[1]);
77 }
78
79 static int starts_with_dot_dot_slash(const char *str)
80 {
81         return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
82 }
83
84 /*
85  * Returns 1 if it was the last chop before ':'.
86  */
87 static int chop_last_dir(char **remoteurl, int is_relative)
88 {
89         char *rfind = find_last_dir_sep(*remoteurl);
90         if (rfind) {
91                 *rfind = '\0';
92                 return 0;
93         }
94
95         rfind = strrchr(*remoteurl, ':');
96         if (rfind) {
97                 *rfind = '\0';
98                 return 1;
99         }
100
101         if (is_relative || !strcmp(".", *remoteurl))
102                 die(_("cannot strip one component off url '%s'"),
103                         *remoteurl);
104
105         free(*remoteurl);
106         *remoteurl = xstrdup(".");
107         return 0;
108 }
109
110 /*
111  * The `url` argument is the URL that navigates to the submodule origin
112  * repo. When relative, this URL is relative to the superproject origin
113  * URL repo. The `up_path` argument, if specified, is the relative
114  * path that navigates from the submodule working tree to the superproject
115  * working tree. Returns the origin URL of the submodule.
116  *
117  * Return either an absolute URL or filesystem path (if the superproject
118  * origin URL is an absolute URL or filesystem path, respectively) or a
119  * relative file system path (if the superproject origin URL is a relative
120  * file system path).
121  *
122  * When the output is a relative file system path, the path is either
123  * relative to the submodule working tree, if up_path is specified, or to
124  * the superproject working tree otherwise.
125  *
126  * NEEDSWORK: This works incorrectly on the domain and protocol part.
127  * remote_url      url              outcome          expectation
128  * http://a.com/b  ../c             http://a.com/c   as is
129  * http://a.com/b/ ../c             http://a.com/c   same as previous line, but
130  *                                                   ignore trailing slash in url
131  * http://a.com/b  ../../c          http://c         error out
132  * http://a.com/b  ../../../c       http:/c          error out
133  * http://a.com/b  ../../../../c    http:c           error out
134  * http://a.com/b  ../../../../../c    .:c           error out
135  * NEEDSWORK: Given how chop_last_dir() works, this function is broken
136  * when a local part has a colon in its path component, too.
137  */
138 static char *relative_url(const char *remote_url,
139                                 const char *url,
140                                 const char *up_path)
141 {
142         int is_relative = 0;
143         int colonsep = 0;
144         char *out;
145         char *remoteurl = xstrdup(remote_url);
146         struct strbuf sb = STRBUF_INIT;
147         size_t len = strlen(remoteurl);
148
149         if (is_dir_sep(remoteurl[len-1]))
150                 remoteurl[len-1] = '\0';
151
152         if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
153                 is_relative = 0;
154         else {
155                 is_relative = 1;
156                 /*
157                  * Prepend a './' to ensure all relative
158                  * remoteurls start with './' or '../'
159                  */
160                 if (!starts_with_dot_slash(remoteurl) &&
161                     !starts_with_dot_dot_slash(remoteurl)) {
162                         strbuf_reset(&sb);
163                         strbuf_addf(&sb, "./%s", remoteurl);
164                         free(remoteurl);
165                         remoteurl = strbuf_detach(&sb, NULL);
166                 }
167         }
168         /*
169          * When the url starts with '../', remove that and the
170          * last directory in remoteurl.
171          */
172         while (url) {
173                 if (starts_with_dot_dot_slash(url)) {
174                         url += 3;
175                         colonsep |= chop_last_dir(&remoteurl, is_relative);
176                 } else if (starts_with_dot_slash(url))
177                         url += 2;
178                 else
179                         break;
180         }
181         strbuf_reset(&sb);
182         strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
183         if (ends_with(url, "/"))
184                 strbuf_setlen(&sb, sb.len - 1);
185         free(remoteurl);
186
187         if (starts_with_dot_slash(sb.buf))
188                 out = xstrdup(sb.buf + 2);
189         else
190                 out = xstrdup(sb.buf);
191         strbuf_reset(&sb);
192
193         if (!up_path || !is_relative)
194                 return out;
195
196         strbuf_addf(&sb, "%s%s", up_path, out);
197         free(out);
198         return strbuf_detach(&sb, NULL);
199 }
200
201 static int resolve_relative_url(int argc, const char **argv, const char *prefix)
202 {
203         char *remoteurl = NULL;
204         char *remote = get_default_remote();
205         const char *up_path = NULL;
206         char *res;
207         const char *url;
208         struct strbuf sb = STRBUF_INIT;
209
210         if (argc != 2 && argc != 3)
211                 die("resolve-relative-url only accepts one or two arguments");
212
213         url = argv[1];
214         strbuf_addf(&sb, "remote.%s.url", remote);
215         free(remote);
216
217         if (git_config_get_string(sb.buf, &remoteurl))
218                 /* the repository is its own authoritative upstream */
219                 remoteurl = xgetcwd();
220
221         if (argc == 3)
222                 up_path = argv[2];
223
224         res = relative_url(remoteurl, url, up_path);
225         puts(res);
226         free(res);
227         free(remoteurl);
228         return 0;
229 }
230
231 static int resolve_relative_url_test(int argc, const char **argv, const char *prefix)
232 {
233         char *remoteurl, *res;
234         const char *up_path, *url;
235
236         if (argc != 4)
237                 die("resolve-relative-url-test only accepts three arguments: <up_path> <remoteurl> <url>");
238
239         up_path = argv[1];
240         remoteurl = xstrdup(argv[2]);
241         url = argv[3];
242
243         if (!strcmp(up_path, "(null)"))
244                 up_path = NULL;
245
246         res = relative_url(remoteurl, url, up_path);
247         puts(res);
248         free(res);
249         free(remoteurl);
250         return 0;
251 }
252
253 /* the result should be freed by the caller. */
254 static char *get_submodule_displaypath(const char *path, const char *prefix)
255 {
256         const char *super_prefix = get_super_prefix();
257
258         if (prefix && super_prefix) {
259                 BUG("cannot have prefix '%s' and superprefix '%s'",
260                     prefix, super_prefix);
261         } else if (prefix) {
262                 struct strbuf sb = STRBUF_INIT;
263                 char *displaypath = xstrdup(relative_path(path, prefix, &sb));
264                 strbuf_release(&sb);
265                 return displaypath;
266         } else if (super_prefix) {
267                 return xstrfmt("%s%s", super_prefix, path);
268         } else {
269                 return xstrdup(path);
270         }
271 }
272
273 static char *compute_rev_name(const char *sub_path, const char* object_id)
274 {
275         struct strbuf sb = STRBUF_INIT;
276         const char ***d;
277
278         static const char *describe_bare[] = { NULL };
279
280         static const char *describe_tags[] = { "--tags", NULL };
281
282         static const char *describe_contains[] = { "--contains", NULL };
283
284         static const char *describe_all_always[] = { "--all", "--always", NULL };
285
286         static const char **describe_argv[] = { describe_bare, describe_tags,
287                                                 describe_contains,
288                                                 describe_all_always, NULL };
289
290         for (d = describe_argv; *d; d++) {
291                 struct child_process cp = CHILD_PROCESS_INIT;
292                 prepare_submodule_repo_env(&cp.env_array);
293                 cp.dir = sub_path;
294                 cp.git_cmd = 1;
295                 cp.no_stderr = 1;
296
297                 strvec_push(&cp.args, "describe");
298                 strvec_pushv(&cp.args, *d);
299                 strvec_push(&cp.args, object_id);
300
301                 if (!capture_command(&cp, &sb, 0)) {
302                         strbuf_strip_suffix(&sb, "\n");
303                         return strbuf_detach(&sb, NULL);
304                 }
305         }
306
307         strbuf_release(&sb);
308         return NULL;
309 }
310
311 struct module_list {
312         const struct cache_entry **entries;
313         int alloc, nr;
314 };
315 #define MODULE_LIST_INIT { NULL, 0, 0 }
316
317 static int module_list_compute(int argc, const char **argv,
318                                const char *prefix,
319                                struct pathspec *pathspec,
320                                struct module_list *list)
321 {
322         int i, result = 0;
323         char *ps_matched = NULL;
324         parse_pathspec(pathspec, 0,
325                        PATHSPEC_PREFER_FULL,
326                        prefix, argv);
327
328         if (pathspec->nr)
329                 ps_matched = xcalloc(pathspec->nr, 1);
330
331         if (read_cache() < 0)
332                 die(_("index file corrupt"));
333
334         for (i = 0; i < active_nr; i++) {
335                 const struct cache_entry *ce = active_cache[i];
336
337                 if (!match_pathspec(&the_index, pathspec, ce->name, ce_namelen(ce),
338                                     0, ps_matched, 1) ||
339                     !S_ISGITLINK(ce->ce_mode))
340                         continue;
341
342                 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
343                 list->entries[list->nr++] = ce;
344                 while (i + 1 < active_nr &&
345                        !strcmp(ce->name, active_cache[i + 1]->name))
346                         /*
347                          * Skip entries with the same name in different stages
348                          * to make sure an entry is returned only once.
349                          */
350                         i++;
351         }
352
353         if (ps_matched && report_path_error(ps_matched, pathspec))
354                 result = -1;
355
356         free(ps_matched);
357
358         return result;
359 }
360
361 static void module_list_active(struct module_list *list)
362 {
363         int i;
364         struct module_list active_modules = MODULE_LIST_INIT;
365
366         for (i = 0; i < list->nr; i++) {
367                 const struct cache_entry *ce = list->entries[i];
368
369                 if (!is_submodule_active(the_repository, ce->name))
370                         continue;
371
372                 ALLOC_GROW(active_modules.entries,
373                            active_modules.nr + 1,
374                            active_modules.alloc);
375                 active_modules.entries[active_modules.nr++] = ce;
376         }
377
378         free(list->entries);
379         *list = active_modules;
380 }
381
382 static char *get_up_path(const char *path)
383 {
384         int i;
385         struct strbuf sb = STRBUF_INIT;
386
387         for (i = count_slashes(path); i; i--)
388                 strbuf_addstr(&sb, "../");
389
390         /*
391          * Check if 'path' ends with slash or not
392          * for having the same output for dir/sub_dir
393          * and dir/sub_dir/
394          */
395         if (!is_dir_sep(path[strlen(path) - 1]))
396                 strbuf_addstr(&sb, "../");
397
398         return strbuf_detach(&sb, NULL);
399 }
400
401 static int module_list(int argc, const char **argv, const char *prefix)
402 {
403         int i;
404         struct pathspec pathspec;
405         struct module_list list = MODULE_LIST_INIT;
406
407         struct option module_list_options[] = {
408                 OPT_STRING(0, "prefix", &prefix,
409                            N_("path"),
410                            N_("alternative anchor for relative paths")),
411                 OPT_END()
412         };
413
414         const char *const git_submodule_helper_usage[] = {
415                 N_("git submodule--helper list [--prefix=<path>] [<path>...]"),
416                 NULL
417         };
418
419         argc = parse_options(argc, argv, prefix, module_list_options,
420                              git_submodule_helper_usage, 0);
421
422         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
423                 return 1;
424
425         for (i = 0; i < list.nr; i++) {
426                 const struct cache_entry *ce = list.entries[i];
427
428                 if (ce_stage(ce))
429                         printf("%06o %s U\t", ce->ce_mode, oid_to_hex(&null_oid));
430                 else
431                         printf("%06o %s %d\t", ce->ce_mode,
432                                oid_to_hex(&ce->oid), ce_stage(ce));
433
434                 fprintf(stdout, "%s\n", ce->name);
435         }
436         return 0;
437 }
438
439 static void for_each_listed_submodule(const struct module_list *list,
440                                       each_submodule_fn fn, void *cb_data)
441 {
442         int i;
443         for (i = 0; i < list->nr; i++)
444                 fn(list->entries[i], cb_data);
445 }
446
447 struct foreach_cb {
448         int argc;
449         const char **argv;
450         const char *prefix;
451         int quiet;
452         int recursive;
453 };
454 #define FOREACH_CB_INIT { 0 }
455
456 static void runcommand_in_submodule_cb(const struct cache_entry *list_item,
457                                        void *cb_data)
458 {
459         struct foreach_cb *info = cb_data;
460         const char *path = list_item->name;
461         const struct object_id *ce_oid = &list_item->oid;
462
463         const struct submodule *sub;
464         struct child_process cp = CHILD_PROCESS_INIT;
465         char *displaypath;
466
467         displaypath = get_submodule_displaypath(path, info->prefix);
468
469         sub = submodule_from_path(the_repository, &null_oid, path);
470
471         if (!sub)
472                 die(_("No url found for submodule path '%s' in .gitmodules"),
473                         displaypath);
474
475         if (!is_submodule_populated_gently(path, NULL))
476                 goto cleanup;
477
478         prepare_submodule_repo_env(&cp.env_array);
479
480         /*
481          * For the purpose of executing <command> in the submodule,
482          * separate shell is used for the purpose of running the
483          * child process.
484          */
485         cp.use_shell = 1;
486         cp.dir = path;
487
488         /*
489          * NEEDSWORK: the command currently has access to the variables $name,
490          * $sm_path, $displaypath, $sha1 and $toplevel only when the command
491          * contains a single argument. This is done for maintaining a faithful
492          * translation from shell script.
493          */
494         if (info->argc == 1) {
495                 char *toplevel = xgetcwd();
496                 struct strbuf sb = STRBUF_INIT;
497
498                 strvec_pushf(&cp.env_array, "name=%s", sub->name);
499                 strvec_pushf(&cp.env_array, "sm_path=%s", path);
500                 strvec_pushf(&cp.env_array, "displaypath=%s", displaypath);
501                 strvec_pushf(&cp.env_array, "sha1=%s",
502                              oid_to_hex(ce_oid));
503                 strvec_pushf(&cp.env_array, "toplevel=%s", toplevel);
504
505                 /*
506                  * Since the path variable was accessible from the script
507                  * before porting, it is also made available after porting.
508                  * The environment variable "PATH" has a very special purpose
509                  * on windows. And since environment variables are
510                  * case-insensitive in windows, it interferes with the
511                  * existing PATH variable. Hence, to avoid that, we expose
512                  * path via the args strvec and not via env_array.
513                  */
514                 sq_quote_buf(&sb, path);
515                 strvec_pushf(&cp.args, "path=%s; %s",
516                              sb.buf, info->argv[0]);
517                 strbuf_release(&sb);
518                 free(toplevel);
519         } else {
520                 strvec_pushv(&cp.args, info->argv);
521         }
522
523         if (!info->quiet)
524                 printf(_("Entering '%s'\n"), displaypath);
525
526         if (info->argv[0] && run_command(&cp))
527                 die(_("run_command returned non-zero status for %s\n."),
528                         displaypath);
529
530         if (info->recursive) {
531                 struct child_process cpr = CHILD_PROCESS_INIT;
532
533                 cpr.git_cmd = 1;
534                 cpr.dir = path;
535                 prepare_submodule_repo_env(&cpr.env_array);
536
537                 strvec_pushl(&cpr.args, "--super-prefix", NULL);
538                 strvec_pushf(&cpr.args, "%s/", displaypath);
539                 strvec_pushl(&cpr.args, "submodule--helper", "foreach", "--recursive",
540                              NULL);
541
542                 if (info->quiet)
543                         strvec_push(&cpr.args, "--quiet");
544
545                 strvec_push(&cpr.args, "--");
546                 strvec_pushv(&cpr.args, info->argv);
547
548                 if (run_command(&cpr))
549                         die(_("run_command returned non-zero status while "
550                                 "recursing in the nested submodules of %s\n."),
551                                 displaypath);
552         }
553
554 cleanup:
555         free(displaypath);
556 }
557
558 static int module_foreach(int argc, const char **argv, const char *prefix)
559 {
560         struct foreach_cb info = FOREACH_CB_INIT;
561         struct pathspec pathspec;
562         struct module_list list = MODULE_LIST_INIT;
563
564         struct option module_foreach_options[] = {
565                 OPT__QUIET(&info.quiet, N_("Suppress output of entering each submodule command")),
566                 OPT_BOOL(0, "recursive", &info.recursive,
567                          N_("Recurse into nested submodules")),
568                 OPT_END()
569         };
570
571         const char *const git_submodule_helper_usage[] = {
572                 N_("git submodule--helper foreach [--quiet] [--recursive] [--] <command>"),
573                 NULL
574         };
575
576         argc = parse_options(argc, argv, prefix, module_foreach_options,
577                              git_submodule_helper_usage, 0);
578
579         if (module_list_compute(0, NULL, prefix, &pathspec, &list) < 0)
580                 return 1;
581
582         info.argc = argc;
583         info.argv = argv;
584         info.prefix = prefix;
585
586         for_each_listed_submodule(&list, runcommand_in_submodule_cb, &info);
587
588         return 0;
589 }
590
591 static char *compute_submodule_clone_url(const char *rel_url)
592 {
593         char *remoteurl, *relurl;
594         char *remote = get_default_remote();
595         struct strbuf remotesb = STRBUF_INIT;
596
597         strbuf_addf(&remotesb, "remote.%s.url", remote);
598         if (git_config_get_string(remotesb.buf, &remoteurl)) {
599                 warning(_("could not look up configuration '%s'. Assuming this repository is its own authoritative upstream."), remotesb.buf);
600                 remoteurl = xgetcwd();
601         }
602         relurl = relative_url(remoteurl, rel_url, NULL);
603
604         free(remote);
605         free(remoteurl);
606         strbuf_release(&remotesb);
607
608         return relurl;
609 }
610
611 struct init_cb {
612         const char *prefix;
613         unsigned int flags;
614 };
615 #define INIT_CB_INIT { NULL, 0 }
616
617 static void init_submodule(const char *path, const char *prefix,
618                            unsigned int flags)
619 {
620         const struct submodule *sub;
621         struct strbuf sb = STRBUF_INIT;
622         char *upd = NULL, *url = NULL, *displaypath;
623
624         displaypath = get_submodule_displaypath(path, prefix);
625
626         sub = submodule_from_path(the_repository, &null_oid, path);
627
628         if (!sub)
629                 die(_("No url found for submodule path '%s' in .gitmodules"),
630                         displaypath);
631
632         /*
633          * NEEDSWORK: In a multi-working-tree world, this needs to be
634          * set in the per-worktree config.
635          *
636          * Set active flag for the submodule being initialized
637          */
638         if (!is_submodule_active(the_repository, path)) {
639                 strbuf_addf(&sb, "submodule.%s.active", sub->name);
640                 git_config_set_gently(sb.buf, "true");
641                 strbuf_reset(&sb);
642         }
643
644         /*
645          * Copy url setting when it is not set yet.
646          * To look up the url in .git/config, we must not fall back to
647          * .gitmodules, so look it up directly.
648          */
649         strbuf_addf(&sb, "submodule.%s.url", sub->name);
650         if (git_config_get_string(sb.buf, &url)) {
651                 if (!sub->url)
652                         die(_("No url found for submodule path '%s' in .gitmodules"),
653                                 displaypath);
654
655                 url = xstrdup(sub->url);
656
657                 /* Possibly a url relative to parent */
658                 if (starts_with_dot_dot_slash(url) ||
659                     starts_with_dot_slash(url)) {
660                         char *oldurl = url;
661                         url = compute_submodule_clone_url(oldurl);
662                         free(oldurl);
663                 }
664
665                 if (git_config_set_gently(sb.buf, url))
666                         die(_("Failed to register url for submodule path '%s'"),
667                             displaypath);
668                 if (!(flags & OPT_QUIET))
669                         fprintf(stderr,
670                                 _("Submodule '%s' (%s) registered for path '%s'\n"),
671                                 sub->name, url, displaypath);
672         }
673         strbuf_reset(&sb);
674
675         /* Copy "update" setting when it is not set yet */
676         strbuf_addf(&sb, "submodule.%s.update", sub->name);
677         if (git_config_get_string(sb.buf, &upd) &&
678             sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
679                 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
680                         fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
681                                 sub->name);
682                         upd = xstrdup("none");
683                 } else
684                         upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
685
686                 if (git_config_set_gently(sb.buf, upd))
687                         die(_("Failed to register update mode for submodule path '%s'"), displaypath);
688         }
689         strbuf_release(&sb);
690         free(displaypath);
691         free(url);
692         free(upd);
693 }
694
695 static void init_submodule_cb(const struct cache_entry *list_item, void *cb_data)
696 {
697         struct init_cb *info = cb_data;
698         init_submodule(list_item->name, info->prefix, info->flags);
699 }
700
701 static int module_init(int argc, const char **argv, const char *prefix)
702 {
703         struct init_cb info = INIT_CB_INIT;
704         struct pathspec pathspec;
705         struct module_list list = MODULE_LIST_INIT;
706         int quiet = 0;
707
708         struct option module_init_options[] = {
709                 OPT__QUIET(&quiet, N_("Suppress output for initializing a submodule")),
710                 OPT_END()
711         };
712
713         const char *const git_submodule_helper_usage[] = {
714                 N_("git submodule--helper init [<options>] [<path>]"),
715                 NULL
716         };
717
718         argc = parse_options(argc, argv, prefix, module_init_options,
719                              git_submodule_helper_usage, 0);
720
721         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
722                 return 1;
723
724         /*
725          * If there are no path args and submodule.active is set then,
726          * by default, only initialize 'active' modules.
727          */
728         if (!argc && git_config_get_value_multi("submodule.active"))
729                 module_list_active(&list);
730
731         info.prefix = prefix;
732         if (quiet)
733                 info.flags |= OPT_QUIET;
734
735         for_each_listed_submodule(&list, init_submodule_cb, &info);
736
737         return 0;
738 }
739
740 struct status_cb {
741         const char *prefix;
742         unsigned int flags;
743 };
744 #define STATUS_CB_INIT { NULL, 0 }
745
746 static void print_status(unsigned int flags, char state, const char *path,
747                          const struct object_id *oid, const char *displaypath)
748 {
749         if (flags & OPT_QUIET)
750                 return;
751
752         printf("%c%s %s", state, oid_to_hex(oid), displaypath);
753
754         if (state == ' ' || state == '+') {
755                 const char *name = compute_rev_name(path, oid_to_hex(oid));
756
757                 if (name)
758                         printf(" (%s)", name);
759         }
760
761         printf("\n");
762 }
763
764 static int handle_submodule_head_ref(const char *refname,
765                                      const struct object_id *oid, int flags,
766                                      void *cb_data)
767 {
768         struct object_id *output = cb_data;
769         if (oid)
770                 oidcpy(output, oid);
771
772         return 0;
773 }
774
775 static void status_submodule(const char *path, const struct object_id *ce_oid,
776                              unsigned int ce_flags, const char *prefix,
777                              unsigned int flags)
778 {
779         char *displaypath;
780         struct strvec diff_files_args = STRVEC_INIT;
781         struct rev_info rev;
782         int diff_files_result;
783         struct strbuf buf = STRBUF_INIT;
784         const char *git_dir;
785
786         if (!submodule_from_path(the_repository, &null_oid, path))
787                 die(_("no submodule mapping found in .gitmodules for path '%s'"),
788                       path);
789
790         displaypath = get_submodule_displaypath(path, prefix);
791
792         if ((CE_STAGEMASK & ce_flags) >> CE_STAGESHIFT) {
793                 print_status(flags, 'U', path, &null_oid, displaypath);
794                 goto cleanup;
795         }
796
797         strbuf_addf(&buf, "%s/.git", path);
798         git_dir = read_gitfile(buf.buf);
799         if (!git_dir)
800                 git_dir = buf.buf;
801
802         if (!is_submodule_active(the_repository, path) ||
803             !is_git_directory(git_dir)) {
804                 print_status(flags, '-', path, ce_oid, displaypath);
805                 strbuf_release(&buf);
806                 goto cleanup;
807         }
808         strbuf_release(&buf);
809
810         strvec_pushl(&diff_files_args, "diff-files",
811                      "--ignore-submodules=dirty", "--quiet", "--",
812                      path, NULL);
813
814         git_config(git_diff_basic_config, NULL);
815
816         repo_init_revisions(the_repository, &rev, NULL);
817         rev.abbrev = 0;
818         diff_files_args.nr = setup_revisions(diff_files_args.nr,
819                                              diff_files_args.v,
820                                              &rev, NULL);
821         diff_files_result = run_diff_files(&rev, 0);
822
823         if (!diff_result_code(&rev.diffopt, diff_files_result)) {
824                 print_status(flags, ' ', path, ce_oid,
825                              displaypath);
826         } else if (!(flags & OPT_CACHED)) {
827                 struct object_id oid;
828                 struct ref_store *refs = get_submodule_ref_store(path);
829
830                 if (!refs) {
831                         print_status(flags, '-', path, ce_oid, displaypath);
832                         goto cleanup;
833                 }
834                 if (refs_head_ref(refs, handle_submodule_head_ref, &oid))
835                         die(_("could not resolve HEAD ref inside the "
836                               "submodule '%s'"), path);
837
838                 print_status(flags, '+', path, &oid, displaypath);
839         } else {
840                 print_status(flags, '+', path, ce_oid, displaypath);
841         }
842
843         if (flags & OPT_RECURSIVE) {
844                 struct child_process cpr = CHILD_PROCESS_INIT;
845
846                 cpr.git_cmd = 1;
847                 cpr.dir = path;
848                 prepare_submodule_repo_env(&cpr.env_array);
849
850                 strvec_push(&cpr.args, "--super-prefix");
851                 strvec_pushf(&cpr.args, "%s/", displaypath);
852                 strvec_pushl(&cpr.args, "submodule--helper", "status",
853                              "--recursive", NULL);
854
855                 if (flags & OPT_CACHED)
856                         strvec_push(&cpr.args, "--cached");
857
858                 if (flags & OPT_QUIET)
859                         strvec_push(&cpr.args, "--quiet");
860
861                 if (run_command(&cpr))
862                         die(_("failed to recurse into submodule '%s'"), path);
863         }
864
865 cleanup:
866         strvec_clear(&diff_files_args);
867         free(displaypath);
868 }
869
870 static void status_submodule_cb(const struct cache_entry *list_item,
871                                 void *cb_data)
872 {
873         struct status_cb *info = cb_data;
874         status_submodule(list_item->name, &list_item->oid, list_item->ce_flags,
875                          info->prefix, info->flags);
876 }
877
878 static int module_status(int argc, const char **argv, const char *prefix)
879 {
880         struct status_cb info = STATUS_CB_INIT;
881         struct pathspec pathspec;
882         struct module_list list = MODULE_LIST_INIT;
883         int quiet = 0;
884
885         struct option module_status_options[] = {
886                 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
887                 OPT_BIT(0, "cached", &info.flags, N_("Use commit stored in the index instead of the one stored in the submodule HEAD"), OPT_CACHED),
888                 OPT_BIT(0, "recursive", &info.flags, N_("recurse into nested submodules"), OPT_RECURSIVE),
889                 OPT_END()
890         };
891
892         const char *const git_submodule_helper_usage[] = {
893                 N_("git submodule status [--quiet] [--cached] [--recursive] [<path>...]"),
894                 NULL
895         };
896
897         argc = parse_options(argc, argv, prefix, module_status_options,
898                              git_submodule_helper_usage, 0);
899
900         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
901                 return 1;
902
903         info.prefix = prefix;
904         if (quiet)
905                 info.flags |= OPT_QUIET;
906
907         for_each_listed_submodule(&list, status_submodule_cb, &info);
908
909         return 0;
910 }
911
912 static int module_name(int argc, const char **argv, const char *prefix)
913 {
914         const struct submodule *sub;
915
916         if (argc != 2)
917                 usage(_("git submodule--helper name <path>"));
918
919         sub = submodule_from_path(the_repository, &null_oid, argv[1]);
920
921         if (!sub)
922                 die(_("no submodule mapping found in .gitmodules for path '%s'"),
923                     argv[1]);
924
925         printf("%s\n", sub->name);
926
927         return 0;
928 }
929
930 struct module_cb {
931         unsigned int mod_src;
932         unsigned int mod_dst;
933         struct object_id oid_src;
934         struct object_id oid_dst;
935         char status;
936         const char *sm_path;
937 };
938 #define MODULE_CB_INIT { 0, 0, NULL, NULL, '\0', NULL }
939
940 struct module_cb_list {
941         struct module_cb **entries;
942         int alloc, nr;
943 };
944 #define MODULE_CB_LIST_INIT { NULL, 0, 0 }
945
946 struct summary_cb {
947         int argc;
948         const char **argv;
949         const char *prefix;
950         unsigned int cached: 1;
951         unsigned int for_status: 1;
952         unsigned int files: 1;
953         int summary_limit;
954 };
955 #define SUMMARY_CB_INIT { 0, NULL, NULL, 0, 0, 0, 0 }
956
957 enum diff_cmd {
958         DIFF_INDEX,
959         DIFF_FILES
960 };
961
962 static char* verify_submodule_committish(const char *sm_path,
963                                          const char *committish)
964 {
965         struct child_process cp_rev_parse = CHILD_PROCESS_INIT;
966         struct strbuf result = STRBUF_INIT;
967
968         cp_rev_parse.git_cmd = 1;
969         cp_rev_parse.dir = sm_path;
970         prepare_submodule_repo_env(&cp_rev_parse.env_array);
971         strvec_pushl(&cp_rev_parse.args, "rev-parse", "-q", "--short", NULL);
972         strvec_pushf(&cp_rev_parse.args, "%s^0", committish);
973         strvec_push(&cp_rev_parse.args, "--");
974
975         if (capture_command(&cp_rev_parse, &result, 0))
976                 return NULL;
977
978         strbuf_trim_trailing_newline(&result);
979         return strbuf_detach(&result, NULL);
980 }
981
982 static void print_submodule_summary(struct summary_cb *info, char* errmsg,
983                                     int total_commits, const char *displaypath,
984                                     const char *src_abbrev, const char *dst_abbrev,
985                                     struct module_cb *p)
986 {
987         if (p->status == 'T') {
988                 if (S_ISGITLINK(p->mod_dst))
989                         printf(_("* %s %s(blob)->%s(submodule)"),
990                                  displaypath, src_abbrev, dst_abbrev);
991                 else
992                         printf(_("* %s %s(submodule)->%s(blob)"),
993                                  displaypath, src_abbrev, dst_abbrev);
994         } else {
995                 printf("* %s %s...%s",
996                         displaypath, src_abbrev, dst_abbrev);
997         }
998
999         if (total_commits < 0)
1000                 printf(":\n");
1001         else
1002                 printf(" (%d):\n", total_commits);
1003
1004         if (errmsg) {
1005                 printf(_("%s"), errmsg);
1006         } else if (total_commits > 0) {
1007                 struct child_process cp_log = CHILD_PROCESS_INIT;
1008
1009                 cp_log.git_cmd = 1;
1010                 cp_log.dir = p->sm_path;
1011                 prepare_submodule_repo_env(&cp_log.env_array);
1012                 strvec_pushl(&cp_log.args, "log", NULL);
1013
1014                 if (S_ISGITLINK(p->mod_src) && S_ISGITLINK(p->mod_dst)) {
1015                         if (info->summary_limit > 0)
1016                                 strvec_pushf(&cp_log.args, "-%d",
1017                                              info->summary_limit);
1018
1019                         strvec_pushl(&cp_log.args, "--pretty=  %m %s",
1020                                      "--first-parent", NULL);
1021                         strvec_pushf(&cp_log.args, "%s...%s",
1022                                      src_abbrev, dst_abbrev);
1023                 } else if (S_ISGITLINK(p->mod_dst)) {
1024                         strvec_pushl(&cp_log.args, "--pretty=  > %s",
1025                                      "-1", dst_abbrev, NULL);
1026                 } else {
1027                         strvec_pushl(&cp_log.args, "--pretty=  < %s",
1028                                      "-1", src_abbrev, NULL);
1029                 }
1030                 run_command(&cp_log);
1031         }
1032         printf("\n");
1033 }
1034
1035 static void generate_submodule_summary(struct summary_cb *info,
1036                                        struct module_cb *p)
1037 {
1038         char *displaypath, *src_abbrev, *dst_abbrev;
1039         int missing_src = 0, missing_dst = 0;
1040         char *errmsg = NULL;
1041         int total_commits = -1;
1042
1043         if (!info->cached && oideq(&p->oid_dst, &null_oid)) {
1044                 if (S_ISGITLINK(p->mod_dst)) {
1045                         struct ref_store *refs = get_submodule_ref_store(p->sm_path);
1046                         if (refs)
1047                                 refs_head_ref(refs, handle_submodule_head_ref, &p->oid_dst);
1048                 } else if (S_ISLNK(p->mod_dst) || S_ISREG(p->mod_dst)) {
1049                         struct stat st;
1050                         int fd = open(p->sm_path, O_RDONLY);
1051
1052                         if (fd < 0 || fstat(fd, &st) < 0 ||
1053                             index_fd(&the_index, &p->oid_dst, fd, &st, OBJ_BLOB,
1054                                      p->sm_path, 0))
1055                                 error(_("couldn't hash object from '%s'"), p->sm_path);
1056                 } else {
1057                         /* for a submodule removal (mode:0000000), don't warn */
1058                         if (p->mod_dst)
1059                                 warning(_("unexpected mode %d\n"), p->mod_dst);
1060                 }
1061         }
1062
1063         if (S_ISGITLINK(p->mod_src)) {
1064                 src_abbrev = verify_submodule_committish(p->sm_path,
1065                                                          oid_to_hex(&p->oid_src));
1066                 if (!src_abbrev) {
1067                         missing_src = 1;
1068                         /*
1069                          * As `rev-parse` failed, we fallback to getting
1070                          * the abbreviated hash using oid_src. We do
1071                          * this as we might still need the abbreviated
1072                          * hash in cases like a submodule type change, etc.
1073                          */
1074                         src_abbrev = xstrndup(oid_to_hex(&p->oid_src), 7);
1075                 }
1076         } else {
1077                 /*
1078                  * The source does not point to a submodule.
1079                  * So, we fallback to getting the abbreviation using
1080                  * oid_src as we might still need the abbreviated
1081                  * hash in cases like submodule add, etc.
1082                  */
1083                 src_abbrev = xstrndup(oid_to_hex(&p->oid_src), 7);
1084         }
1085
1086         if (S_ISGITLINK(p->mod_dst)) {
1087                 dst_abbrev = verify_submodule_committish(p->sm_path,
1088                                                          oid_to_hex(&p->oid_dst));
1089                 if (!dst_abbrev) {
1090                         missing_dst = 1;
1091                         /*
1092                          * As `rev-parse` failed, we fallback to getting
1093                          * the abbreviated hash using oid_dst. We do
1094                          * this as we might still need the abbreviated
1095                          * hash in cases like a submodule type change, etc.
1096                          */
1097                         dst_abbrev = xstrndup(oid_to_hex(&p->oid_dst), 7);
1098                 }
1099         } else {
1100                 /*
1101                  * The destination does not point to a submodule.
1102                  * So, we fallback to getting the abbreviation using
1103                  * oid_dst as we might still need the abbreviated
1104                  * hash in cases like a submodule removal, etc.
1105                  */
1106                 dst_abbrev = xstrndup(oid_to_hex(&p->oid_dst), 7);
1107         }
1108
1109         displaypath = get_submodule_displaypath(p->sm_path, info->prefix);
1110
1111         if (!missing_src && !missing_dst) {
1112                 struct child_process cp_rev_list = CHILD_PROCESS_INIT;
1113                 struct strbuf sb_rev_list = STRBUF_INIT;
1114
1115                 strvec_pushl(&cp_rev_list.args, "rev-list",
1116                              "--first-parent", "--count", NULL);
1117                 if (S_ISGITLINK(p->mod_src) && S_ISGITLINK(p->mod_dst))
1118                         strvec_pushf(&cp_rev_list.args, "%s...%s",
1119                                      src_abbrev, dst_abbrev);
1120                 else
1121                         strvec_push(&cp_rev_list.args, S_ISGITLINK(p->mod_src) ?
1122                                     src_abbrev : dst_abbrev);
1123                 strvec_push(&cp_rev_list.args, "--");
1124
1125                 cp_rev_list.git_cmd = 1;
1126                 cp_rev_list.dir = p->sm_path;
1127                 prepare_submodule_repo_env(&cp_rev_list.env_array);
1128
1129                 if (!capture_command(&cp_rev_list, &sb_rev_list, 0))
1130                         total_commits = atoi(sb_rev_list.buf);
1131
1132                 strbuf_release(&sb_rev_list);
1133         } else {
1134                 /*
1135                  * Don't give error msg for modification whose dst is not
1136                  * submodule, i.e., deleted or changed to blob
1137                  */
1138                 if (S_ISGITLINK(p->mod_dst)) {
1139                         struct strbuf errmsg_str = STRBUF_INIT;
1140                         if (missing_src && missing_dst) {
1141                                 strbuf_addf(&errmsg_str, "  Warn: %s doesn't contain commits %s and %s\n",
1142                                             displaypath, oid_to_hex(&p->oid_src),
1143                                             oid_to_hex(&p->oid_dst));
1144                         } else {
1145                                 strbuf_addf(&errmsg_str, "  Warn: %s doesn't contain commit %s\n",
1146                                             displaypath, missing_src ?
1147                                             oid_to_hex(&p->oid_src) :
1148                                             oid_to_hex(&p->oid_dst));
1149                         }
1150                         errmsg = strbuf_detach(&errmsg_str, NULL);
1151                 }
1152         }
1153
1154         print_submodule_summary(info, errmsg, total_commits,
1155                                 displaypath, src_abbrev,
1156                                 dst_abbrev, p);
1157
1158         free(displaypath);
1159         free(src_abbrev);
1160         free(dst_abbrev);
1161 }
1162
1163 static void prepare_submodule_summary(struct summary_cb *info,
1164                                       struct module_cb_list *list)
1165 {
1166         int i;
1167         for (i = 0; i < list->nr; i++) {
1168                 const struct submodule *sub;
1169                 struct module_cb *p = list->entries[i];
1170                 struct strbuf sm_gitdir = STRBUF_INIT;
1171
1172                 if (p->status == 'D' || p->status == 'T') {
1173                         generate_submodule_summary(info, p);
1174                         continue;
1175                 }
1176
1177                 if (info->for_status && p->status != 'A' &&
1178                     (sub = submodule_from_path(the_repository,
1179                                                &null_oid, p->sm_path))) {
1180                         char *config_key = NULL;
1181                         const char *value;
1182                         int ignore_all = 0;
1183
1184                         config_key = xstrfmt("submodule.%s.ignore",
1185                                              sub->name);
1186                         if (!git_config_get_string_const(config_key, &value))
1187                                 ignore_all = !strcmp(value, "all");
1188                         else if (sub->ignore)
1189                                 ignore_all = !strcmp(sub->ignore, "all");
1190
1191                         free(config_key);
1192                         if (ignore_all)
1193                                 continue;
1194                 }
1195
1196                 /* Also show added or modified modules which are checked out */
1197                 strbuf_addstr(&sm_gitdir, p->sm_path);
1198                 if (is_nonbare_repository_dir(&sm_gitdir))
1199                         generate_submodule_summary(info, p);
1200                 strbuf_release(&sm_gitdir);
1201         }
1202 }
1203
1204 static void submodule_summary_callback(struct diff_queue_struct *q,
1205                                        struct diff_options *options,
1206                                        void *data)
1207 {
1208         int i;
1209         struct module_cb_list *list = data;
1210         for (i = 0; i < q->nr; i++) {
1211                 struct diff_filepair *p = q->queue[i];
1212                 struct module_cb *temp;
1213
1214                 if (!S_ISGITLINK(p->one->mode) && !S_ISGITLINK(p->two->mode))
1215                         continue;
1216                 temp = (struct module_cb*)malloc(sizeof(struct module_cb));
1217                 temp->mod_src = p->one->mode;
1218                 temp->mod_dst = p->two->mode;
1219                 temp->oid_src = p->one->oid;
1220                 temp->oid_dst = p->two->oid;
1221                 temp->status = p->status;
1222                 temp->sm_path = xstrdup(p->one->path);
1223
1224                 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
1225                 list->entries[list->nr++] = temp;
1226         }
1227 }
1228
1229 static const char *get_diff_cmd(enum diff_cmd diff_cmd)
1230 {
1231         switch (diff_cmd) {
1232         case DIFF_INDEX: return "diff-index";
1233         case DIFF_FILES: return "diff-files";
1234         default: BUG("bad diff_cmd value %d", diff_cmd);
1235         }
1236 }
1237
1238 static int compute_summary_module_list(struct object_id *head_oid,
1239                                        struct summary_cb *info,
1240                                        enum diff_cmd diff_cmd)
1241 {
1242         struct strvec diff_args = STRVEC_INIT;
1243         struct rev_info rev;
1244         struct module_cb_list list = MODULE_CB_LIST_INIT;
1245
1246         strvec_push(&diff_args, get_diff_cmd(diff_cmd));
1247         if (info->cached)
1248                 strvec_push(&diff_args, "--cached");
1249         strvec_pushl(&diff_args, "--ignore-submodules=dirty", "--raw", NULL);
1250         if (head_oid)
1251                 strvec_push(&diff_args, oid_to_hex(head_oid));
1252         strvec_push(&diff_args, "--");
1253         if (info->argc)
1254                 strvec_pushv(&diff_args, info->argv);
1255
1256         git_config(git_diff_basic_config, NULL);
1257         init_revisions(&rev, info->prefix);
1258         rev.abbrev = 0;
1259         precompose_argv(diff_args.nr, diff_args.v);
1260         setup_revisions(diff_args.nr, diff_args.v, &rev, NULL);
1261         rev.diffopt.output_format = DIFF_FORMAT_NO_OUTPUT | DIFF_FORMAT_CALLBACK;
1262         rev.diffopt.format_callback = submodule_summary_callback;
1263         rev.diffopt.format_callback_data = &list;
1264
1265         if (!info->cached) {
1266                 if (diff_cmd == DIFF_INDEX)
1267                         setup_work_tree();
1268                 if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
1269                         perror("read_cache_preload");
1270                         return -1;
1271                 }
1272         } else if (read_cache() < 0) {
1273                 perror("read_cache");
1274                 return -1;
1275         }
1276
1277         if (diff_cmd == DIFF_INDEX)
1278                 run_diff_index(&rev, info->cached);
1279         else
1280                 run_diff_files(&rev, 0);
1281         prepare_submodule_summary(info, &list);
1282         strvec_clear(&diff_args);
1283         return 0;
1284 }
1285
1286 static int module_summary(int argc, const char **argv, const char *prefix)
1287 {
1288         struct summary_cb info = SUMMARY_CB_INIT;
1289         int cached = 0;
1290         int for_status = 0;
1291         int files = 0;
1292         int summary_limit = -1;
1293         enum diff_cmd diff_cmd = DIFF_INDEX;
1294         struct object_id head_oid;
1295         int ret;
1296
1297         struct option module_summary_options[] = {
1298                 OPT_BOOL(0, "cached", &cached,
1299                          N_("use the commit stored in the index instead of the submodule HEAD")),
1300                 OPT_BOOL(0, "files", &files,
1301                          N_("to compare the commit in the index with that in the submodule HEAD")),
1302                 OPT_BOOL(0, "for-status", &for_status,
1303                          N_("skip submodules with 'ignore_config' value set to 'all'")),
1304                 OPT_INTEGER('n', "summary-limit", &summary_limit,
1305                              N_("limit the summary size")),
1306                 OPT_END()
1307         };
1308
1309         const char *const git_submodule_helper_usage[] = {
1310                 N_("git submodule--helper summary [<options>] [commit] [--] [<path>]"),
1311                 NULL
1312         };
1313
1314         argc = parse_options(argc, argv, prefix, module_summary_options,
1315                              git_submodule_helper_usage, 0);
1316
1317         if (!summary_limit)
1318                 return 0;
1319
1320         if (!get_oid(argc ? argv[0] : "HEAD", &head_oid)) {
1321                 if (argc) {
1322                         argv++;
1323                         argc--;
1324                 }
1325         } else if (!argc || !strcmp(argv[0], "HEAD")) {
1326                 /* before the first commit: compare with an empty tree */
1327                 oidcpy(&head_oid, the_hash_algo->empty_tree);
1328                 if (argc) {
1329                         argv++;
1330                         argc--;
1331                 }
1332         } else {
1333                 if (get_oid("HEAD", &head_oid))
1334                         die(_("could not fetch a revision for HEAD"));
1335         }
1336
1337         if (files) {
1338                 if (cached)
1339                         die(_("--cached and --files are mutually exclusive"));
1340                 diff_cmd = DIFF_FILES;
1341         }
1342
1343         info.argc = argc;
1344         info.argv = argv;
1345         info.prefix = prefix;
1346         info.cached = !!cached;
1347         info.files = !!files;
1348         info.for_status = !!for_status;
1349         info.summary_limit = summary_limit;
1350
1351         ret = compute_summary_module_list((diff_cmd == DIFF_INDEX) ? &head_oid : NULL,
1352                                           &info, diff_cmd);
1353         return ret;
1354 }
1355
1356 struct sync_cb {
1357         const char *prefix;
1358         unsigned int flags;
1359 };
1360 #define SYNC_CB_INIT { NULL, 0 }
1361
1362 static void sync_submodule(const char *path, const char *prefix,
1363                            unsigned int flags)
1364 {
1365         const struct submodule *sub;
1366         char *remote_key = NULL;
1367         char *sub_origin_url, *super_config_url, *displaypath;
1368         struct strbuf sb = STRBUF_INIT;
1369         struct child_process cp = CHILD_PROCESS_INIT;
1370         char *sub_config_path = NULL;
1371
1372         if (!is_submodule_active(the_repository, path))
1373                 return;
1374
1375         sub = submodule_from_path(the_repository, &null_oid, path);
1376
1377         if (sub && sub->url) {
1378                 if (starts_with_dot_dot_slash(sub->url) ||
1379                     starts_with_dot_slash(sub->url)) {
1380                         char *remote_url, *up_path;
1381                         char *remote = get_default_remote();
1382                         strbuf_addf(&sb, "remote.%s.url", remote);
1383
1384                         if (git_config_get_string(sb.buf, &remote_url))
1385                                 remote_url = xgetcwd();
1386
1387                         up_path = get_up_path(path);
1388                         sub_origin_url = relative_url(remote_url, sub->url, up_path);
1389                         super_config_url = relative_url(remote_url, sub->url, NULL);
1390
1391                         free(remote);
1392                         free(up_path);
1393                         free(remote_url);
1394                 } else {
1395                         sub_origin_url = xstrdup(sub->url);
1396                         super_config_url = xstrdup(sub->url);
1397                 }
1398         } else {
1399                 sub_origin_url = xstrdup("");
1400                 super_config_url = xstrdup("");
1401         }
1402
1403         displaypath = get_submodule_displaypath(path, prefix);
1404
1405         if (!(flags & OPT_QUIET))
1406                 printf(_("Synchronizing submodule url for '%s'\n"),
1407                          displaypath);
1408
1409         strbuf_reset(&sb);
1410         strbuf_addf(&sb, "submodule.%s.url", sub->name);
1411         if (git_config_set_gently(sb.buf, super_config_url))
1412                 die(_("failed to register url for submodule path '%s'"),
1413                       displaypath);
1414
1415         if (!is_submodule_populated_gently(path, NULL))
1416                 goto cleanup;
1417
1418         prepare_submodule_repo_env(&cp.env_array);
1419         cp.git_cmd = 1;
1420         cp.dir = path;
1421         strvec_pushl(&cp.args, "submodule--helper",
1422                      "print-default-remote", NULL);
1423
1424         strbuf_reset(&sb);
1425         if (capture_command(&cp, &sb, 0))
1426                 die(_("failed to get the default remote for submodule '%s'"),
1427                       path);
1428
1429         strbuf_strip_suffix(&sb, "\n");
1430         remote_key = xstrfmt("remote.%s.url", sb.buf);
1431
1432         strbuf_reset(&sb);
1433         submodule_to_gitdir(&sb, path);
1434         strbuf_addstr(&sb, "/config");
1435
1436         if (git_config_set_in_file_gently(sb.buf, remote_key, sub_origin_url))
1437                 die(_("failed to update remote for submodule '%s'"),
1438                       path);
1439
1440         if (flags & OPT_RECURSIVE) {
1441                 struct child_process cpr = CHILD_PROCESS_INIT;
1442
1443                 cpr.git_cmd = 1;
1444                 cpr.dir = path;
1445                 prepare_submodule_repo_env(&cpr.env_array);
1446
1447                 strvec_push(&cpr.args, "--super-prefix");
1448                 strvec_pushf(&cpr.args, "%s/", displaypath);
1449                 strvec_pushl(&cpr.args, "submodule--helper", "sync",
1450                              "--recursive", NULL);
1451
1452                 if (flags & OPT_QUIET)
1453                         strvec_push(&cpr.args, "--quiet");
1454
1455                 if (run_command(&cpr))
1456                         die(_("failed to recurse into submodule '%s'"),
1457                               path);
1458         }
1459
1460 cleanup:
1461         free(super_config_url);
1462         free(sub_origin_url);
1463         strbuf_release(&sb);
1464         free(remote_key);
1465         free(displaypath);
1466         free(sub_config_path);
1467 }
1468
1469 static void sync_submodule_cb(const struct cache_entry *list_item, void *cb_data)
1470 {
1471         struct sync_cb *info = cb_data;
1472         sync_submodule(list_item->name, info->prefix, info->flags);
1473 }
1474
1475 static int module_sync(int argc, const char **argv, const char *prefix)
1476 {
1477         struct sync_cb info = SYNC_CB_INIT;
1478         struct pathspec pathspec;
1479         struct module_list list = MODULE_LIST_INIT;
1480         int quiet = 0;
1481         int recursive = 0;
1482
1483         struct option module_sync_options[] = {
1484                 OPT__QUIET(&quiet, N_("Suppress output of synchronizing submodule url")),
1485                 OPT_BOOL(0, "recursive", &recursive,
1486                         N_("Recurse into nested submodules")),
1487                 OPT_END()
1488         };
1489
1490         const char *const git_submodule_helper_usage[] = {
1491                 N_("git submodule--helper sync [--quiet] [--recursive] [<path>]"),
1492                 NULL
1493         };
1494
1495         argc = parse_options(argc, argv, prefix, module_sync_options,
1496                              git_submodule_helper_usage, 0);
1497
1498         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1499                 return 1;
1500
1501         info.prefix = prefix;
1502         if (quiet)
1503                 info.flags |= OPT_QUIET;
1504         if (recursive)
1505                 info.flags |= OPT_RECURSIVE;
1506
1507         for_each_listed_submodule(&list, sync_submodule_cb, &info);
1508
1509         return 0;
1510 }
1511
1512 struct deinit_cb {
1513         const char *prefix;
1514         unsigned int flags;
1515 };
1516 #define DEINIT_CB_INIT { NULL, 0 }
1517
1518 static void deinit_submodule(const char *path, const char *prefix,
1519                              unsigned int flags)
1520 {
1521         const struct submodule *sub;
1522         char *displaypath = NULL;
1523         struct child_process cp_config = CHILD_PROCESS_INIT;
1524         struct strbuf sb_config = STRBUF_INIT;
1525         char *sub_git_dir = xstrfmt("%s/.git", path);
1526
1527         sub = submodule_from_path(the_repository, &null_oid, path);
1528
1529         if (!sub || !sub->name)
1530                 goto cleanup;
1531
1532         displaypath = get_submodule_displaypath(path, prefix);
1533
1534         /* remove the submodule work tree (unless the user already did it) */
1535         if (is_directory(path)) {
1536                 struct strbuf sb_rm = STRBUF_INIT;
1537                 const char *format;
1538
1539                 /*
1540                  * protect submodules containing a .git directory
1541                  * NEEDSWORK: instead of dying, automatically call
1542                  * absorbgitdirs and (possibly) warn.
1543                  */
1544                 if (is_directory(sub_git_dir))
1545                         die(_("Submodule work tree '%s' contains a .git "
1546                               "directory (use 'rm -rf' if you really want "
1547                               "to remove it including all of its history)"),
1548                             displaypath);
1549
1550                 if (!(flags & OPT_FORCE)) {
1551                         struct child_process cp_rm = CHILD_PROCESS_INIT;
1552                         cp_rm.git_cmd = 1;
1553                         strvec_pushl(&cp_rm.args, "rm", "-qn",
1554                                      path, NULL);
1555
1556                         if (run_command(&cp_rm))
1557                                 die(_("Submodule work tree '%s' contains local "
1558                                       "modifications; use '-f' to discard them"),
1559                                       displaypath);
1560                 }
1561
1562                 strbuf_addstr(&sb_rm, path);
1563
1564                 if (!remove_dir_recursively(&sb_rm, 0))
1565                         format = _("Cleared directory '%s'\n");
1566                 else
1567                         format = _("Could not remove submodule work tree '%s'\n");
1568
1569                 if (!(flags & OPT_QUIET))
1570                         printf(format, displaypath);
1571
1572                 submodule_unset_core_worktree(sub);
1573
1574                 strbuf_release(&sb_rm);
1575         }
1576
1577         if (mkdir(path, 0777))
1578                 printf(_("could not create empty submodule directory %s"),
1579                       displaypath);
1580
1581         cp_config.git_cmd = 1;
1582         strvec_pushl(&cp_config.args, "config", "--get-regexp", NULL);
1583         strvec_pushf(&cp_config.args, "submodule.%s\\.", sub->name);
1584
1585         /* remove the .git/config entries (unless the user already did it) */
1586         if (!capture_command(&cp_config, &sb_config, 0) && sb_config.len) {
1587                 char *sub_key = xstrfmt("submodule.%s", sub->name);
1588                 /*
1589                  * remove the whole section so we have a clean state when
1590                  * the user later decides to init this submodule again
1591                  */
1592                 git_config_rename_section_in_file(NULL, sub_key, NULL);
1593                 if (!(flags & OPT_QUIET))
1594                         printf(_("Submodule '%s' (%s) unregistered for path '%s'\n"),
1595                                  sub->name, sub->url, displaypath);
1596                 free(sub_key);
1597         }
1598
1599 cleanup:
1600         free(displaypath);
1601         free(sub_git_dir);
1602         strbuf_release(&sb_config);
1603 }
1604
1605 static void deinit_submodule_cb(const struct cache_entry *list_item,
1606                                 void *cb_data)
1607 {
1608         struct deinit_cb *info = cb_data;
1609         deinit_submodule(list_item->name, info->prefix, info->flags);
1610 }
1611
1612 static int module_deinit(int argc, const char **argv, const char *prefix)
1613 {
1614         struct deinit_cb info = DEINIT_CB_INIT;
1615         struct pathspec pathspec;
1616         struct module_list list = MODULE_LIST_INIT;
1617         int quiet = 0;
1618         int force = 0;
1619         int all = 0;
1620
1621         struct option module_deinit_options[] = {
1622                 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
1623                 OPT__FORCE(&force, N_("Remove submodule working trees even if they contain local changes"), 0),
1624                 OPT_BOOL(0, "all", &all, N_("Unregister all submodules")),
1625                 OPT_END()
1626         };
1627
1628         const char *const git_submodule_helper_usage[] = {
1629                 N_("git submodule deinit [--quiet] [-f | --force] [--all | [--] [<path>...]]"),
1630                 NULL
1631         };
1632
1633         argc = parse_options(argc, argv, prefix, module_deinit_options,
1634                              git_submodule_helper_usage, 0);
1635
1636         if (all && argc) {
1637                 error("pathspec and --all are incompatible");
1638                 usage_with_options(git_submodule_helper_usage,
1639                                    module_deinit_options);
1640         }
1641
1642         if (!argc && !all)
1643                 die(_("Use '--all' if you really want to deinitialize all submodules"));
1644
1645         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1646                 return 1;
1647
1648         info.prefix = prefix;
1649         if (quiet)
1650                 info.flags |= OPT_QUIET;
1651         if (force)
1652                 info.flags |= OPT_FORCE;
1653
1654         for_each_listed_submodule(&list, deinit_submodule_cb, &info);
1655
1656         return 0;
1657 }
1658
1659 static int clone_submodule(const char *path, const char *gitdir, const char *url,
1660                            const char *depth, struct string_list *reference, int dissociate,
1661                            int quiet, int progress, int single_branch)
1662 {
1663         struct child_process cp = CHILD_PROCESS_INIT;
1664
1665         strvec_push(&cp.args, "clone");
1666         strvec_push(&cp.args, "--no-checkout");
1667         if (quiet)
1668                 strvec_push(&cp.args, "--quiet");
1669         if (progress)
1670                 strvec_push(&cp.args, "--progress");
1671         if (depth && *depth)
1672                 strvec_pushl(&cp.args, "--depth", depth, NULL);
1673         if (reference->nr) {
1674                 struct string_list_item *item;
1675                 for_each_string_list_item(item, reference)
1676                         strvec_pushl(&cp.args, "--reference",
1677                                      item->string, NULL);
1678         }
1679         if (dissociate)
1680                 strvec_push(&cp.args, "--dissociate");
1681         if (gitdir && *gitdir)
1682                 strvec_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
1683         if (single_branch >= 0)
1684                 strvec_push(&cp.args, single_branch ?
1685                                           "--single-branch" :
1686                                           "--no-single-branch");
1687
1688         strvec_push(&cp.args, "--");
1689         strvec_push(&cp.args, url);
1690         strvec_push(&cp.args, path);
1691
1692         cp.git_cmd = 1;
1693         prepare_submodule_repo_env(&cp.env_array);
1694         cp.no_stdin = 1;
1695
1696         return run_command(&cp);
1697 }
1698
1699 struct submodule_alternate_setup {
1700         const char *submodule_name;
1701         enum SUBMODULE_ALTERNATE_ERROR_MODE {
1702                 SUBMODULE_ALTERNATE_ERROR_DIE,
1703                 SUBMODULE_ALTERNATE_ERROR_INFO,
1704                 SUBMODULE_ALTERNATE_ERROR_IGNORE
1705         } error_mode;
1706         struct string_list *reference;
1707 };
1708 #define SUBMODULE_ALTERNATE_SETUP_INIT { NULL, \
1709         SUBMODULE_ALTERNATE_ERROR_IGNORE, NULL }
1710
1711 static const char alternate_error_advice[] = N_(
1712 "An alternate computed from a superproject's alternate is invalid.\n"
1713 "To allow Git to clone without an alternate in such a case, set\n"
1714 "submodule.alternateErrorStrategy to 'info' or, equivalently, clone with\n"
1715 "'--reference-if-able' instead of '--reference'."
1716 );
1717
1718 static int add_possible_reference_from_superproject(
1719                 struct object_directory *odb, void *sas_cb)
1720 {
1721         struct submodule_alternate_setup *sas = sas_cb;
1722         size_t len;
1723
1724         /*
1725          * If the alternate object store is another repository, try the
1726          * standard layout with .git/(modules/<name>)+/objects
1727          */
1728         if (strip_suffix(odb->path, "/objects", &len)) {
1729                 char *sm_alternate;
1730                 struct strbuf sb = STRBUF_INIT;
1731                 struct strbuf err = STRBUF_INIT;
1732                 strbuf_add(&sb, odb->path, len);
1733
1734                 /*
1735                  * We need to end the new path with '/' to mark it as a dir,
1736                  * otherwise a submodule name containing '/' will be broken
1737                  * as the last part of a missing submodule reference would
1738                  * be taken as a file name.
1739                  */
1740                 strbuf_addf(&sb, "/modules/%s/", sas->submodule_name);
1741
1742                 sm_alternate = compute_alternate_path(sb.buf, &err);
1743                 if (sm_alternate) {
1744                         string_list_append(sas->reference, xstrdup(sb.buf));
1745                         free(sm_alternate);
1746                 } else {
1747                         switch (sas->error_mode) {
1748                         case SUBMODULE_ALTERNATE_ERROR_DIE:
1749                                 if (advice_submodule_alternate_error_strategy_die)
1750                                         advise(_(alternate_error_advice));
1751                                 die(_("submodule '%s' cannot add alternate: %s"),
1752                                     sas->submodule_name, err.buf);
1753                         case SUBMODULE_ALTERNATE_ERROR_INFO:
1754                                 fprintf_ln(stderr, _("submodule '%s' cannot add alternate: %s"),
1755                                         sas->submodule_name, err.buf);
1756                         case SUBMODULE_ALTERNATE_ERROR_IGNORE:
1757                                 ; /* nothing */
1758                         }
1759                 }
1760                 strbuf_release(&sb);
1761         }
1762
1763         return 0;
1764 }
1765
1766 static void prepare_possible_alternates(const char *sm_name,
1767                 struct string_list *reference)
1768 {
1769         char *sm_alternate = NULL, *error_strategy = NULL;
1770         struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
1771
1772         git_config_get_string("submodule.alternateLocation", &sm_alternate);
1773         if (!sm_alternate)
1774                 return;
1775
1776         git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1777
1778         if (!error_strategy)
1779                 error_strategy = xstrdup("die");
1780
1781         sas.submodule_name = sm_name;
1782         sas.reference = reference;
1783         if (!strcmp(error_strategy, "die"))
1784                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
1785         else if (!strcmp(error_strategy, "info"))
1786                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
1787         else if (!strcmp(error_strategy, "ignore"))
1788                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
1789         else
1790                 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
1791
1792         if (!strcmp(sm_alternate, "superproject"))
1793                 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
1794         else if (!strcmp(sm_alternate, "no"))
1795                 ; /* do nothing */
1796         else
1797                 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
1798
1799         free(sm_alternate);
1800         free(error_strategy);
1801 }
1802
1803 static int module_clone(int argc, const char **argv, const char *prefix)
1804 {
1805         const char *name = NULL, *url = NULL, *depth = NULL;
1806         int quiet = 0;
1807         int progress = 0;
1808         char *p, *path = NULL, *sm_gitdir;
1809         struct strbuf sb = STRBUF_INIT;
1810         struct string_list reference = STRING_LIST_INIT_NODUP;
1811         int dissociate = 0, require_init = 0;
1812         char *sm_alternate = NULL, *error_strategy = NULL;
1813         int single_branch = -1;
1814
1815         struct option module_clone_options[] = {
1816                 OPT_STRING(0, "prefix", &prefix,
1817                            N_("path"),
1818                            N_("alternative anchor for relative paths")),
1819                 OPT_STRING(0, "path", &path,
1820                            N_("path"),
1821                            N_("where the new submodule will be cloned to")),
1822                 OPT_STRING(0, "name", &name,
1823                            N_("string"),
1824                            N_("name of the new submodule")),
1825                 OPT_STRING(0, "url", &url,
1826                            N_("string"),
1827                            N_("url where to clone the submodule from")),
1828                 OPT_STRING_LIST(0, "reference", &reference,
1829                            N_("repo"),
1830                            N_("reference repository")),
1831                 OPT_BOOL(0, "dissociate", &dissociate,
1832                            N_("use --reference only while cloning")),
1833                 OPT_STRING(0, "depth", &depth,
1834                            N_("string"),
1835                            N_("depth for shallow clones")),
1836                 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
1837                 OPT_BOOL(0, "progress", &progress,
1838                            N_("force cloning progress")),
1839                 OPT_BOOL(0, "require-init", &require_init,
1840                            N_("disallow cloning into non-empty directory")),
1841                 OPT_BOOL(0, "single-branch", &single_branch,
1842                          N_("clone only one branch, HEAD or --branch")),
1843                 OPT_END()
1844         };
1845
1846         const char *const git_submodule_helper_usage[] = {
1847                 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
1848                    "[--reference <repository>] [--name <name>] [--depth <depth>] "
1849                    "[--single-branch] "
1850                    "--url <url> --path <path>"),
1851                 NULL
1852         };
1853
1854         argc = parse_options(argc, argv, prefix, module_clone_options,
1855                              git_submodule_helper_usage, 0);
1856
1857         if (argc || !url || !path || !*path)
1858                 usage_with_options(git_submodule_helper_usage,
1859                                    module_clone_options);
1860
1861         strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
1862         sm_gitdir = absolute_pathdup(sb.buf);
1863         strbuf_reset(&sb);
1864
1865         if (!is_absolute_path(path)) {
1866                 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
1867                 path = strbuf_detach(&sb, NULL);
1868         } else
1869                 path = xstrdup(path);
1870
1871         if (validate_submodule_git_dir(sm_gitdir, name) < 0)
1872                 die(_("refusing to create/use '%s' in another submodule's "
1873                         "git dir"), sm_gitdir);
1874
1875         if (!file_exists(sm_gitdir)) {
1876                 if (safe_create_leading_directories_const(sm_gitdir) < 0)
1877                         die(_("could not create directory '%s'"), sm_gitdir);
1878
1879                 prepare_possible_alternates(name, &reference);
1880
1881                 if (clone_submodule(path, sm_gitdir, url, depth, &reference, dissociate,
1882                                     quiet, progress, single_branch))
1883                         die(_("clone of '%s' into submodule path '%s' failed"),
1884                             url, path);
1885         } else {
1886                 if (require_init && !access(path, X_OK) && !is_empty_dir(path))
1887                         die(_("directory not empty: '%s'"), path);
1888                 if (safe_create_leading_directories_const(path) < 0)
1889                         die(_("could not create directory '%s'"), path);
1890                 strbuf_addf(&sb, "%s/index", sm_gitdir);
1891                 unlink_or_warn(sb.buf);
1892                 strbuf_reset(&sb);
1893         }
1894
1895         connect_work_tree_and_git_dir(path, sm_gitdir, 0);
1896
1897         p = git_pathdup_submodule(path, "config");
1898         if (!p)
1899                 die(_("could not get submodule directory for '%s'"), path);
1900
1901         /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
1902         git_config_get_string("submodule.alternateLocation", &sm_alternate);
1903         if (sm_alternate)
1904                 git_config_set_in_file(p, "submodule.alternateLocation",
1905                                            sm_alternate);
1906         git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1907         if (error_strategy)
1908                 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
1909                                            error_strategy);
1910
1911         free(sm_alternate);
1912         free(error_strategy);
1913
1914         strbuf_release(&sb);
1915         free(sm_gitdir);
1916         free(path);
1917         free(p);
1918         return 0;
1919 }
1920
1921 static void determine_submodule_update_strategy(struct repository *r,
1922                                                 int just_cloned,
1923                                                 const char *path,
1924                                                 const char *update,
1925                                                 struct submodule_update_strategy *out)
1926 {
1927         const struct submodule *sub = submodule_from_path(r, &null_oid, path);
1928         char *key;
1929         const char *val;
1930
1931         key = xstrfmt("submodule.%s.update", sub->name);
1932
1933         if (update) {
1934                 if (parse_submodule_update_strategy(update, out) < 0)
1935                         die(_("Invalid update mode '%s' for submodule path '%s'"),
1936                                 update, path);
1937         } else if (!repo_config_get_string_const(r, key, &val)) {
1938                 if (parse_submodule_update_strategy(val, out) < 0)
1939                         die(_("Invalid update mode '%s' configured for submodule path '%s'"),
1940                                 val, path);
1941         } else if (sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
1942                 if (sub->update_strategy.type == SM_UPDATE_COMMAND)
1943                         BUG("how did we read update = !command from .gitmodules?");
1944                 out->type = sub->update_strategy.type;
1945                 out->command = sub->update_strategy.command;
1946         } else
1947                 out->type = SM_UPDATE_CHECKOUT;
1948
1949         if (just_cloned &&
1950             (out->type == SM_UPDATE_MERGE ||
1951              out->type == SM_UPDATE_REBASE ||
1952              out->type == SM_UPDATE_NONE))
1953                 out->type = SM_UPDATE_CHECKOUT;
1954
1955         free(key);
1956 }
1957
1958 static int module_update_module_mode(int argc, const char **argv, const char *prefix)
1959 {
1960         const char *path, *update = NULL;
1961         int just_cloned;
1962         struct submodule_update_strategy update_strategy = { .type = SM_UPDATE_CHECKOUT };
1963
1964         if (argc < 3 || argc > 4)
1965                 die("submodule--helper update-module-clone expects <just-cloned> <path> [<update>]");
1966
1967         just_cloned = git_config_int("just_cloned", argv[1]);
1968         path = argv[2];
1969
1970         if (argc == 4)
1971                 update = argv[3];
1972
1973         determine_submodule_update_strategy(the_repository,
1974                                             just_cloned, path, update,
1975                                             &update_strategy);
1976         fputs(submodule_strategy_to_string(&update_strategy), stdout);
1977
1978         return 0;
1979 }
1980
1981 struct update_clone_data {
1982         const struct submodule *sub;
1983         struct object_id oid;
1984         unsigned just_cloned;
1985 };
1986
1987 struct submodule_update_clone {
1988         /* index into 'list', the list of submodules to look into for cloning */
1989         int current;
1990         struct module_list list;
1991         unsigned warn_if_uninitialized : 1;
1992
1993         /* update parameter passed via commandline */
1994         struct submodule_update_strategy update;
1995
1996         /* configuration parameters which are passed on to the children */
1997         int progress;
1998         int quiet;
1999         int recommend_shallow;
2000         struct string_list references;
2001         int dissociate;
2002         unsigned require_init;
2003         const char *depth;
2004         const char *recursive_prefix;
2005         const char *prefix;
2006         int single_branch;
2007
2008         /* to be consumed by git-submodule.sh */
2009         struct update_clone_data *update_clone;
2010         int update_clone_nr; int update_clone_alloc;
2011
2012         /* If we want to stop as fast as possible and return an error */
2013         unsigned quickstop : 1;
2014
2015         /* failed clones to be retried again */
2016         const struct cache_entry **failed_clones;
2017         int failed_clones_nr, failed_clones_alloc;
2018
2019         int max_jobs;
2020 };
2021 #define SUBMODULE_UPDATE_CLONE_INIT { \
2022         .list = MODULE_LIST_INIT, \
2023         .update = SUBMODULE_UPDATE_STRATEGY_INIT, \
2024         .recommend_shallow = -1, \
2025         .references = STRING_LIST_INIT_DUP, \
2026         .single_branch = -1, \
2027         .max_jobs = 1, \
2028 }
2029
2030
2031 static void next_submodule_warn_missing(struct submodule_update_clone *suc,
2032                 struct strbuf *out, const char *displaypath)
2033 {
2034         /*
2035          * Only mention uninitialized submodules when their
2036          * paths have been specified.
2037          */
2038         if (suc->warn_if_uninitialized) {
2039                 strbuf_addf(out,
2040                         _("Submodule path '%s' not initialized"),
2041                         displaypath);
2042                 strbuf_addch(out, '\n');
2043                 strbuf_addstr(out,
2044                         _("Maybe you want to use 'update --init'?"));
2045                 strbuf_addch(out, '\n');
2046         }
2047 }
2048
2049 /**
2050  * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
2051  * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
2052  */
2053 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
2054                                            struct child_process *child,
2055                                            struct submodule_update_clone *suc,
2056                                            struct strbuf *out)
2057 {
2058         const struct submodule *sub = NULL;
2059         const char *url = NULL;
2060         const char *update_string;
2061         enum submodule_update_type update_type;
2062         char *key;
2063         struct strbuf displaypath_sb = STRBUF_INIT;
2064         struct strbuf sb = STRBUF_INIT;
2065         const char *displaypath = NULL;
2066         int needs_cloning = 0;
2067         int need_free_url = 0;
2068
2069         if (ce_stage(ce)) {
2070                 if (suc->recursive_prefix)
2071                         strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
2072                 else
2073                         strbuf_addstr(&sb, ce->name);
2074                 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
2075                 strbuf_addch(out, '\n');
2076                 goto cleanup;
2077         }
2078
2079         sub = submodule_from_path(the_repository, &null_oid, ce->name);
2080
2081         if (suc->recursive_prefix)
2082                 displaypath = relative_path(suc->recursive_prefix,
2083                                             ce->name, &displaypath_sb);
2084         else
2085                 displaypath = ce->name;
2086
2087         if (!sub) {
2088                 next_submodule_warn_missing(suc, out, displaypath);
2089                 goto cleanup;
2090         }
2091
2092         key = xstrfmt("submodule.%s.update", sub->name);
2093         if (!repo_config_get_string_const(the_repository, key, &update_string)) {
2094                 update_type = parse_submodule_update_type(update_string);
2095         } else {
2096                 update_type = sub->update_strategy.type;
2097         }
2098         free(key);
2099
2100         if (suc->update.type == SM_UPDATE_NONE
2101             || (suc->update.type == SM_UPDATE_UNSPECIFIED
2102                 && update_type == SM_UPDATE_NONE)) {
2103                 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
2104                 strbuf_addch(out, '\n');
2105                 goto cleanup;
2106         }
2107
2108         /* Check if the submodule has been initialized. */
2109         if (!is_submodule_active(the_repository, ce->name)) {
2110                 next_submodule_warn_missing(suc, out, displaypath);
2111                 goto cleanup;
2112         }
2113
2114         strbuf_reset(&sb);
2115         strbuf_addf(&sb, "submodule.%s.url", sub->name);
2116         if (repo_config_get_string_const(the_repository, sb.buf, &url)) {
2117                 if (starts_with_dot_slash(sub->url) ||
2118                     starts_with_dot_dot_slash(sub->url)) {
2119                         url = compute_submodule_clone_url(sub->url);
2120                         need_free_url = 1;
2121                 } else
2122                         url = sub->url;
2123         }
2124
2125         strbuf_reset(&sb);
2126         strbuf_addf(&sb, "%s/.git", ce->name);
2127         needs_cloning = !file_exists(sb.buf);
2128
2129         ALLOC_GROW(suc->update_clone, suc->update_clone_nr + 1,
2130                    suc->update_clone_alloc);
2131         oidcpy(&suc->update_clone[suc->update_clone_nr].oid, &ce->oid);
2132         suc->update_clone[suc->update_clone_nr].just_cloned = needs_cloning;
2133         suc->update_clone[suc->update_clone_nr].sub = sub;
2134         suc->update_clone_nr++;
2135
2136         if (!needs_cloning)
2137                 goto cleanup;
2138
2139         child->git_cmd = 1;
2140         child->no_stdin = 1;
2141         child->stdout_to_stderr = 1;
2142         child->err = -1;
2143         strvec_push(&child->args, "submodule--helper");
2144         strvec_push(&child->args, "clone");
2145         if (suc->progress)
2146                 strvec_push(&child->args, "--progress");
2147         if (suc->quiet)
2148                 strvec_push(&child->args, "--quiet");
2149         if (suc->prefix)
2150                 strvec_pushl(&child->args, "--prefix", suc->prefix, NULL);
2151         if (suc->recommend_shallow && sub->recommend_shallow == 1)
2152                 strvec_push(&child->args, "--depth=1");
2153         if (suc->require_init)
2154                 strvec_push(&child->args, "--require-init");
2155         strvec_pushl(&child->args, "--path", sub->path, NULL);
2156         strvec_pushl(&child->args, "--name", sub->name, NULL);
2157         strvec_pushl(&child->args, "--url", url, NULL);
2158         if (suc->references.nr) {
2159                 struct string_list_item *item;
2160                 for_each_string_list_item(item, &suc->references)
2161                         strvec_pushl(&child->args, "--reference", item->string, NULL);
2162         }
2163         if (suc->dissociate)
2164                 strvec_push(&child->args, "--dissociate");
2165         if (suc->depth)
2166                 strvec_push(&child->args, suc->depth);
2167         if (suc->single_branch >= 0)
2168                 strvec_push(&child->args, suc->single_branch ?
2169                                               "--single-branch" :
2170                                               "--no-single-branch");
2171
2172 cleanup:
2173         strbuf_reset(&displaypath_sb);
2174         strbuf_reset(&sb);
2175         if (need_free_url)
2176                 free((void*)url);
2177
2178         return needs_cloning;
2179 }
2180
2181 static int update_clone_get_next_task(struct child_process *child,
2182                                       struct strbuf *err,
2183                                       void *suc_cb,
2184                                       void **idx_task_cb)
2185 {
2186         struct submodule_update_clone *suc = suc_cb;
2187         const struct cache_entry *ce;
2188         int index;
2189
2190         for (; suc->current < suc->list.nr; suc->current++) {
2191                 ce = suc->list.entries[suc->current];
2192                 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
2193                         int *p = xmalloc(sizeof(*p));
2194                         *p = suc->current;
2195                         *idx_task_cb = p;
2196                         suc->current++;
2197                         return 1;
2198                 }
2199         }
2200
2201         /*
2202          * The loop above tried cloning each submodule once, now try the
2203          * stragglers again, which we can imagine as an extension of the
2204          * entry list.
2205          */
2206         index = suc->current - suc->list.nr;
2207         if (index < suc->failed_clones_nr) {
2208                 int *p;
2209                 ce = suc->failed_clones[index];
2210                 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
2211                         suc->current ++;
2212                         strbuf_addstr(err, "BUG: submodule considered for "
2213                                            "cloning, doesn't need cloning "
2214                                            "any more?\n");
2215                         return 0;
2216                 }
2217                 p = xmalloc(sizeof(*p));
2218                 *p = suc->current;
2219                 *idx_task_cb = p;
2220                 suc->current ++;
2221                 return 1;
2222         }
2223
2224         return 0;
2225 }
2226
2227 static int update_clone_start_failure(struct strbuf *err,
2228                                       void *suc_cb,
2229                                       void *idx_task_cb)
2230 {
2231         struct submodule_update_clone *suc = suc_cb;
2232         suc->quickstop = 1;
2233         return 1;
2234 }
2235
2236 static int update_clone_task_finished(int result,
2237                                       struct strbuf *err,
2238                                       void *suc_cb,
2239                                       void *idx_task_cb)
2240 {
2241         const struct cache_entry *ce;
2242         struct submodule_update_clone *suc = suc_cb;
2243
2244         int *idxP = idx_task_cb;
2245         int idx = *idxP;
2246         free(idxP);
2247
2248         if (!result)
2249                 return 0;
2250
2251         if (idx < suc->list.nr) {
2252                 ce  = suc->list.entries[idx];
2253                 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
2254                             ce->name);
2255                 strbuf_addch(err, '\n');
2256                 ALLOC_GROW(suc->failed_clones,
2257                            suc->failed_clones_nr + 1,
2258                            suc->failed_clones_alloc);
2259                 suc->failed_clones[suc->failed_clones_nr++] = ce;
2260                 return 0;
2261         } else {
2262                 idx -= suc->list.nr;
2263                 ce  = suc->failed_clones[idx];
2264                 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
2265                             ce->name);
2266                 strbuf_addch(err, '\n');
2267                 suc->quickstop = 1;
2268                 return 1;
2269         }
2270
2271         return 0;
2272 }
2273
2274 static int git_update_clone_config(const char *var, const char *value,
2275                                    void *cb)
2276 {
2277         int *max_jobs = cb;
2278         if (!strcmp(var, "submodule.fetchjobs"))
2279                 *max_jobs = parse_submodule_fetchjobs(var, value);
2280         return 0;
2281 }
2282
2283 static void update_submodule(struct update_clone_data *ucd)
2284 {
2285         fprintf(stdout, "dummy %s %d\t%s\n",
2286                 oid_to_hex(&ucd->oid),
2287                 ucd->just_cloned,
2288                 ucd->sub->path);
2289 }
2290
2291 static int update_submodules(struct submodule_update_clone *suc)
2292 {
2293         int i;
2294
2295         run_processes_parallel_tr2(suc->max_jobs, update_clone_get_next_task,
2296                                    update_clone_start_failure,
2297                                    update_clone_task_finished, suc, "submodule",
2298                                    "parallel/update");
2299
2300         /*
2301          * We saved the output and put it out all at once now.
2302          * That means:
2303          * - the listener does not have to interleave their (checkout)
2304          *   work with our fetching.  The writes involved in a
2305          *   checkout involve more straightforward sequential I/O.
2306          * - the listener can avoid doing any work if fetching failed.
2307          */
2308         if (suc->quickstop)
2309                 return 1;
2310
2311         for (i = 0; i < suc->update_clone_nr; i++)
2312                 update_submodule(&suc->update_clone[i]);
2313
2314         return 0;
2315 }
2316
2317 static int update_clone(int argc, const char **argv, const char *prefix)
2318 {
2319         const char *update = NULL;
2320         struct pathspec pathspec;
2321         struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
2322
2323         struct option module_update_clone_options[] = {
2324                 OPT_STRING(0, "prefix", &prefix,
2325                            N_("path"),
2326                            N_("path into the working tree")),
2327                 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
2328                            N_("path"),
2329                            N_("path into the working tree, across nested "
2330                               "submodule boundaries")),
2331                 OPT_STRING(0, "update", &update,
2332                            N_("string"),
2333                            N_("rebase, merge, checkout or none")),
2334                 OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
2335                            N_("reference repository")),
2336                 OPT_BOOL(0, "dissociate", &suc.dissociate,
2337                            N_("use --reference only while cloning")),
2338                 OPT_STRING(0, "depth", &suc.depth, "<depth>",
2339                            N_("Create a shallow clone truncated to the "
2340                               "specified number of revisions")),
2341                 OPT_INTEGER('j', "jobs", &suc.max_jobs,
2342                             N_("parallel jobs")),
2343                 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
2344                             N_("whether the initial clone should follow the shallow recommendation")),
2345                 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
2346                 OPT_BOOL(0, "progress", &suc.progress,
2347                             N_("force cloning progress")),
2348                 OPT_BOOL(0, "require-init", &suc.require_init,
2349                            N_("disallow cloning into non-empty directory")),
2350                 OPT_BOOL(0, "single-branch", &suc.single_branch,
2351                          N_("clone only one branch, HEAD or --branch")),
2352                 OPT_END()
2353         };
2354
2355         const char *const git_submodule_helper_usage[] = {
2356                 N_("git submodule--helper update-clone [--prefix=<path>] [<path>...]"),
2357                 NULL
2358         };
2359         suc.prefix = prefix;
2360
2361         update_clone_config_from_gitmodules(&suc.max_jobs);
2362         git_config(git_update_clone_config, &suc.max_jobs);
2363
2364         argc = parse_options(argc, argv, prefix, module_update_clone_options,
2365                              git_submodule_helper_usage, 0);
2366
2367         if (update)
2368                 if (parse_submodule_update_strategy(update, &suc.update) < 0)
2369                         die(_("bad value for update parameter"));
2370
2371         if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
2372                 return 1;
2373
2374         if (pathspec.nr)
2375                 suc.warn_if_uninitialized = 1;
2376
2377         return update_submodules(&suc);
2378 }
2379
2380 static int resolve_relative_path(int argc, const char **argv, const char *prefix)
2381 {
2382         struct strbuf sb = STRBUF_INIT;
2383         if (argc != 3)
2384                 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
2385
2386         printf("%s", relative_path(argv[1], argv[2], &sb));
2387         strbuf_release(&sb);
2388         return 0;
2389 }
2390
2391 static const char *remote_submodule_branch(const char *path)
2392 {
2393         const struct submodule *sub;
2394         const char *branch = NULL;
2395         char *key;
2396
2397         sub = submodule_from_path(the_repository, &null_oid, path);
2398         if (!sub)
2399                 return NULL;
2400
2401         key = xstrfmt("submodule.%s.branch", sub->name);
2402         if (repo_config_get_string_const(the_repository, key, &branch))
2403                 branch = sub->branch;
2404         free(key);
2405
2406         if (!branch)
2407                 return "HEAD";
2408
2409         if (!strcmp(branch, ".")) {
2410                 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
2411
2412                 if (!refname)
2413                         die(_("No such ref: %s"), "HEAD");
2414
2415                 /* detached HEAD */
2416                 if (!strcmp(refname, "HEAD"))
2417                         die(_("Submodule (%s) branch configured to inherit "
2418                               "branch from superproject, but the superproject "
2419                               "is not on any branch"), sub->name);
2420
2421                 if (!skip_prefix(refname, "refs/heads/", &refname))
2422                         die(_("Expecting a full ref name, got %s"), refname);
2423                 return refname;
2424         }
2425
2426         return branch;
2427 }
2428
2429 static int resolve_remote_submodule_branch(int argc, const char **argv,
2430                 const char *prefix)
2431 {
2432         const char *ret;
2433         struct strbuf sb = STRBUF_INIT;
2434         if (argc != 2)
2435                 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
2436
2437         ret = remote_submodule_branch(argv[1]);
2438         if (!ret)
2439                 die("submodule %s doesn't exist", argv[1]);
2440
2441         printf("%s", ret);
2442         strbuf_release(&sb);
2443         return 0;
2444 }
2445
2446 static int push_check(int argc, const char **argv, const char *prefix)
2447 {
2448         struct remote *remote;
2449         const char *superproject_head;
2450         char *head;
2451         int detached_head = 0;
2452         struct object_id head_oid;
2453
2454         if (argc < 3)
2455                 die("submodule--helper push-check requires at least 2 arguments");
2456
2457         /*
2458          * superproject's resolved head ref.
2459          * if HEAD then the superproject is in a detached head state, otherwise
2460          * it will be the resolved head ref.
2461          */
2462         superproject_head = argv[1];
2463         argv++;
2464         argc--;
2465         /* Get the submodule's head ref and determine if it is detached */
2466         head = resolve_refdup("HEAD", 0, &head_oid, NULL);
2467         if (!head)
2468                 die(_("Failed to resolve HEAD as a valid ref."));
2469         if (!strcmp(head, "HEAD"))
2470                 detached_head = 1;
2471
2472         /*
2473          * The remote must be configured.
2474          * This is to avoid pushing to the exact same URL as the parent.
2475          */
2476         remote = pushremote_get(argv[1]);
2477         if (!remote || remote->origin == REMOTE_UNCONFIGURED)
2478                 die("remote '%s' not configured", argv[1]);
2479
2480         /* Check the refspec */
2481         if (argc > 2) {
2482                 int i;
2483                 struct ref *local_refs = get_local_heads();
2484                 struct refspec refspec = REFSPEC_INIT_PUSH;
2485
2486                 refspec_appendn(&refspec, argv + 2, argc - 2);
2487
2488                 for (i = 0; i < refspec.nr; i++) {
2489                         const struct refspec_item *rs = &refspec.items[i];
2490
2491                         if (rs->pattern || rs->matching)
2492                                 continue;
2493
2494                         /* LHS must match a single ref */
2495                         switch (count_refspec_match(rs->src, local_refs, NULL)) {
2496                         case 1:
2497                                 break;
2498                         case 0:
2499                                 /*
2500                                  * If LHS matches 'HEAD' then we need to ensure
2501                                  * that it matches the same named branch
2502                                  * checked out in the superproject.
2503                                  */
2504                                 if (!strcmp(rs->src, "HEAD")) {
2505                                         if (!detached_head &&
2506                                             !strcmp(head, superproject_head))
2507                                                 break;
2508                                         die("HEAD does not match the named branch in the superproject");
2509                                 }
2510                                 /* fallthrough */
2511                         default:
2512                                 die("src refspec '%s' must name a ref",
2513                                     rs->src);
2514                         }
2515                 }
2516                 refspec_clear(&refspec);
2517         }
2518         free(head);
2519
2520         return 0;
2521 }
2522
2523 static int ensure_core_worktree(int argc, const char **argv, const char *prefix)
2524 {
2525         const struct submodule *sub;
2526         const char *path;
2527         char *cw;
2528         struct repository subrepo;
2529
2530         if (argc != 2)
2531                 BUG("submodule--helper ensure-core-worktree <path>");
2532
2533         path = argv[1];
2534
2535         sub = submodule_from_path(the_repository, &null_oid, path);
2536         if (!sub)
2537                 BUG("We could get the submodule handle before?");
2538
2539         if (repo_submodule_init(&subrepo, the_repository, sub))
2540                 die(_("could not get a repository handle for submodule '%s'"), path);
2541
2542         if (!repo_config_get_string(&subrepo, "core.worktree", &cw)) {
2543                 char *cfg_file, *abs_path;
2544                 const char *rel_path;
2545                 struct strbuf sb = STRBUF_INIT;
2546
2547                 cfg_file = repo_git_path(&subrepo, "config");
2548
2549                 abs_path = absolute_pathdup(path);
2550                 rel_path = relative_path(abs_path, subrepo.gitdir, &sb);
2551
2552                 git_config_set_in_file(cfg_file, "core.worktree", rel_path);
2553
2554                 free(cfg_file);
2555                 free(abs_path);
2556                 strbuf_release(&sb);
2557         }
2558
2559         return 0;
2560 }
2561
2562 static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
2563 {
2564         int i;
2565         struct pathspec pathspec;
2566         struct module_list list = MODULE_LIST_INIT;
2567         unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
2568
2569         struct option embed_gitdir_options[] = {
2570                 OPT_STRING(0, "prefix", &prefix,
2571                            N_("path"),
2572                            N_("path into the working tree")),
2573                 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
2574                         ABSORB_GITDIR_RECURSE_SUBMODULES),
2575                 OPT_END()
2576         };
2577
2578         const char *const git_submodule_helper_usage[] = {
2579                 N_("git submodule--helper absorb-git-dirs [<options>] [<path>...]"),
2580                 NULL
2581         };
2582
2583         argc = parse_options(argc, argv, prefix, embed_gitdir_options,
2584                              git_submodule_helper_usage, 0);
2585
2586         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
2587                 return 1;
2588
2589         for (i = 0; i < list.nr; i++)
2590                 absorb_git_dir_into_superproject(list.entries[i]->name, flags);
2591
2592         return 0;
2593 }
2594
2595 static int is_active(int argc, const char **argv, const char *prefix)
2596 {
2597         if (argc != 2)
2598                 die("submodule--helper is-active takes exactly 1 argument");
2599
2600         return !is_submodule_active(the_repository, argv[1]);
2601 }
2602
2603 /*
2604  * Exit non-zero if any of the submodule names given on the command line is
2605  * invalid. If no names are given, filter stdin to print only valid names
2606  * (which is primarily intended for testing).
2607  */
2608 static int check_name(int argc, const char **argv, const char *prefix)
2609 {
2610         if (argc > 1) {
2611                 while (*++argv) {
2612                         if (check_submodule_name(*argv) < 0)
2613                                 return 1;
2614                 }
2615         } else {
2616                 struct strbuf buf = STRBUF_INIT;
2617                 while (strbuf_getline(&buf, stdin) != EOF) {
2618                         if (!check_submodule_name(buf.buf))
2619                                 printf("%s\n", buf.buf);
2620                 }
2621                 strbuf_release(&buf);
2622         }
2623         return 0;
2624 }
2625
2626 static int module_config(int argc, const char **argv, const char *prefix)
2627 {
2628         enum {
2629                 CHECK_WRITEABLE = 1,
2630                 DO_UNSET = 2
2631         } command = 0;
2632
2633         struct option module_config_options[] = {
2634                 OPT_CMDMODE(0, "check-writeable", &command,
2635                             N_("check if it is safe to write to the .gitmodules file"),
2636                             CHECK_WRITEABLE),
2637                 OPT_CMDMODE(0, "unset", &command,
2638                             N_("unset the config in the .gitmodules file"),
2639                             DO_UNSET),
2640                 OPT_END()
2641         };
2642         const char *const git_submodule_helper_usage[] = {
2643                 N_("git submodule--helper config <name> [<value>]"),
2644                 N_("git submodule--helper config --unset <name>"),
2645                 N_("git submodule--helper config --check-writeable"),
2646                 NULL
2647         };
2648
2649         argc = parse_options(argc, argv, prefix, module_config_options,
2650                              git_submodule_helper_usage, PARSE_OPT_KEEP_ARGV0);
2651
2652         if (argc == 1 && command == CHECK_WRITEABLE)
2653                 return is_writing_gitmodules_ok() ? 0 : -1;
2654
2655         /* Equivalent to ACTION_GET in builtin/config.c */
2656         if (argc == 2 && command != DO_UNSET)
2657                 return print_config_from_gitmodules(the_repository, argv[1]);
2658
2659         /* Equivalent to ACTION_SET in builtin/config.c */
2660         if (argc == 3 || (argc == 2 && command == DO_UNSET)) {
2661                 const char *value = (argc == 3) ? argv[2] : NULL;
2662
2663                 if (!is_writing_gitmodules_ok())
2664                         die(_("please make sure that the .gitmodules file is in the working tree"));
2665
2666                 return config_set_in_gitmodules_file_gently(argv[1], value);
2667         }
2668
2669         usage_with_options(git_submodule_helper_usage, module_config_options);
2670 }
2671
2672 static int module_set_url(int argc, const char **argv, const char *prefix)
2673 {
2674         int quiet = 0;
2675         const char *newurl;
2676         const char *path;
2677         char *config_name;
2678
2679         struct option options[] = {
2680                 OPT__QUIET(&quiet, N_("Suppress output for setting url of a submodule")),
2681                 OPT_END()
2682         };
2683         const char *const usage[] = {
2684                 N_("git submodule--helper set-url [--quiet] <path> <newurl>"),
2685                 NULL
2686         };
2687
2688         argc = parse_options(argc, argv, prefix, options, usage, 0);
2689
2690         if (argc != 2 || !(path = argv[0]) || !(newurl = argv[1]))
2691                 usage_with_options(usage, options);
2692
2693         config_name = xstrfmt("submodule.%s.url", path);
2694
2695         config_set_in_gitmodules_file_gently(config_name, newurl);
2696         sync_submodule(path, prefix, quiet ? OPT_QUIET : 0);
2697
2698         free(config_name);
2699
2700         return 0;
2701 }
2702
2703 static int module_set_branch(int argc, const char **argv, const char *prefix)
2704 {
2705         int opt_default = 0, ret;
2706         const char *opt_branch = NULL;
2707         const char *path;
2708         char *config_name;
2709
2710         /*
2711          * We accept the `quiet` option for uniformity across subcommands,
2712          * though there is nothing to make less verbose in this subcommand.
2713          */
2714         struct option options[] = {
2715                 OPT_NOOP_NOARG('q', "quiet"),
2716                 OPT_BOOL('d', "default", &opt_default,
2717                         N_("set the default tracking branch to master")),
2718                 OPT_STRING('b', "branch", &opt_branch, N_("branch"),
2719                         N_("set the default tracking branch")),
2720                 OPT_END()
2721         };
2722         const char *const usage[] = {
2723                 N_("git submodule--helper set-branch [-q|--quiet] (-d|--default) <path>"),
2724                 N_("git submodule--helper set-branch [-q|--quiet] (-b|--branch) <branch> <path>"),
2725                 NULL
2726         };
2727
2728         argc = parse_options(argc, argv, prefix, options, usage, 0);
2729
2730         if (!opt_branch && !opt_default)
2731                 die(_("--branch or --default required"));
2732
2733         if (opt_branch && opt_default)
2734                 die(_("--branch and --default are mutually exclusive"));
2735
2736         if (argc != 1 || !(path = argv[0]))
2737                 usage_with_options(usage, options);
2738
2739         config_name = xstrfmt("submodule.%s.branch", path);
2740         ret = config_set_in_gitmodules_file_gently(config_name, opt_branch);
2741
2742         free(config_name);
2743         return !!ret;
2744 }
2745
2746 #define SUPPORT_SUPER_PREFIX (1<<0)
2747
2748 struct cmd_struct {
2749         const char *cmd;
2750         int (*fn)(int, const char **, const char *);
2751         unsigned option;
2752 };
2753
2754 static struct cmd_struct commands[] = {
2755         {"list", module_list, 0},
2756         {"name", module_name, 0},
2757         {"clone", module_clone, 0},
2758         {"update-module-mode", module_update_module_mode, 0},
2759         {"update-clone", update_clone, 0},
2760         {"ensure-core-worktree", ensure_core_worktree, 0},
2761         {"relative-path", resolve_relative_path, 0},
2762         {"resolve-relative-url", resolve_relative_url, 0},
2763         {"resolve-relative-url-test", resolve_relative_url_test, 0},
2764         {"foreach", module_foreach, SUPPORT_SUPER_PREFIX},
2765         {"init", module_init, SUPPORT_SUPER_PREFIX},
2766         {"status", module_status, SUPPORT_SUPER_PREFIX},
2767         {"print-default-remote", print_default_remote, 0},
2768         {"sync", module_sync, SUPPORT_SUPER_PREFIX},
2769         {"deinit", module_deinit, 0},
2770         {"summary", module_summary, SUPPORT_SUPER_PREFIX},
2771         {"remote-branch", resolve_remote_submodule_branch, 0},
2772         {"push-check", push_check, 0},
2773         {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
2774         {"is-active", is_active, 0},
2775         {"check-name", check_name, 0},
2776         {"config", module_config, 0},
2777         {"set-url", module_set_url, 0},
2778         {"set-branch", module_set_branch, 0},
2779 };
2780
2781 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
2782 {
2783         int i;
2784         if (argc < 2 || !strcmp(argv[1], "-h"))
2785                 usage("git submodule--helper <command>");
2786
2787         for (i = 0; i < ARRAY_SIZE(commands); i++) {
2788                 if (!strcmp(argv[1], commands[i].cmd)) {
2789                         if (get_super_prefix() &&
2790                             !(commands[i].option & SUPPORT_SUPER_PREFIX))
2791                                 die(_("%s doesn't support --super-prefix"),
2792                                     commands[i].cmd);
2793                         return commands[i].fn(argc - 1, argv + 1, prefix);
2794                 }
2795         }
2796
2797         die(_("'%s' is not a valid submodule--helper "
2798               "subcommand"), argv[1]);
2799 }