Imported Upstream version 2.19.3
[platform/upstream/git.git] / builtin / submodule--helper.c
1 #include "builtin.h"
2 #include "repository.h"
3 #include "cache.h"
4 #include "config.h"
5 #include "parse-options.h"
6 #include "quote.h"
7 #include "pathspec.h"
8 #include "dir.h"
9 #include "submodule.h"
10 #include "submodule-config.h"
11 #include "string-list.h"
12 #include "run-command.h"
13 #include "remote.h"
14 #include "refs.h"
15 #include "refspec.h"
16 #include "connect.h"
17 #include "revision.h"
18 #include "diffcore.h"
19 #include "diff.h"
20 #include "object-store.h"
21 #include "dir.h"
22
23 #define OPT_QUIET (1 << 0)
24 #define OPT_CACHED (1 << 1)
25 #define OPT_RECURSIVE (1 << 2)
26 #define OPT_FORCE (1 << 3)
27
28 typedef void (*each_submodule_fn)(const struct cache_entry *list_item,
29                                   void *cb_data);
30
31 static char *get_default_remote(void)
32 {
33         char *dest = NULL, *ret;
34         struct strbuf sb = STRBUF_INIT;
35         const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
36
37         if (!refname)
38                 die(_("No such ref: %s"), "HEAD");
39
40         /* detached HEAD */
41         if (!strcmp(refname, "HEAD"))
42                 return xstrdup("origin");
43
44         if (!skip_prefix(refname, "refs/heads/", &refname))
45                 die(_("Expecting a full ref name, got %s"), refname);
46
47         strbuf_addf(&sb, "branch.%s.remote", refname);
48         if (git_config_get_string(sb.buf, &dest))
49                 ret = xstrdup("origin");
50         else
51                 ret = dest;
52
53         strbuf_release(&sb);
54         return ret;
55 }
56
57 static int print_default_remote(int argc, const char **argv, const char *prefix)
58 {
59         char *remote;
60
61         if (argc != 1)
62                 die(_("submodule--helper print-default-remote takes no arguments"));
63
64         remote = get_default_remote();
65         if (remote)
66                 printf("%s\n", remote);
67
68         free(remote);
69         return 0;
70 }
71
72 static int starts_with_dot_slash(const char *str)
73 {
74         return str[0] == '.' && is_dir_sep(str[1]);
75 }
76
77 static int starts_with_dot_dot_slash(const char *str)
78 {
79         return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
80 }
81
82 /*
83  * Returns 1 if it was the last chop before ':'.
84  */
85 static int chop_last_dir(char **remoteurl, int is_relative)
86 {
87         char *rfind = find_last_dir_sep(*remoteurl);
88         if (rfind) {
89                 *rfind = '\0';
90                 return 0;
91         }
92
93         rfind = strrchr(*remoteurl, ':');
94         if (rfind) {
95                 *rfind = '\0';
96                 return 1;
97         }
98
99         if (is_relative || !strcmp(".", *remoteurl))
100                 die(_("cannot strip one component off url '%s'"),
101                         *remoteurl);
102
103         free(*remoteurl);
104         *remoteurl = xstrdup(".");
105         return 0;
106 }
107
108 /*
109  * The `url` argument is the URL that navigates to the submodule origin
110  * repo. When relative, this URL is relative to the superproject origin
111  * URL repo. The `up_path` argument, if specified, is the relative
112  * path that navigates from the submodule working tree to the superproject
113  * working tree. Returns the origin URL of the submodule.
114  *
115  * Return either an absolute URL or filesystem path (if the superproject
116  * origin URL is an absolute URL or filesystem path, respectively) or a
117  * relative file system path (if the superproject origin URL is a relative
118  * file system path).
119  *
120  * When the output is a relative file system path, the path is either
121  * relative to the submodule working tree, if up_path is specified, or to
122  * the superproject working tree otherwise.
123  *
124  * NEEDSWORK: This works incorrectly on the domain and protocol part.
125  * remote_url      url              outcome          expectation
126  * http://a.com/b  ../c             http://a.com/c   as is
127  * http://a.com/b/ ../c             http://a.com/c   same as previous line, but
128  *                                                   ignore trailing slash in url
129  * http://a.com/b  ../../c          http://c         error out
130  * http://a.com/b  ../../../c       http:/c          error out
131  * http://a.com/b  ../../../../c    http:c           error out
132  * http://a.com/b  ../../../../../c    .:c           error out
133  * NEEDSWORK: Given how chop_last_dir() works, this function is broken
134  * when a local part has a colon in its path component, too.
135  */
136 static char *relative_url(const char *remote_url,
137                                 const char *url,
138                                 const char *up_path)
139 {
140         int is_relative = 0;
141         int colonsep = 0;
142         char *out;
143         char *remoteurl = xstrdup(remote_url);
144         struct strbuf sb = STRBUF_INIT;
145         size_t len = strlen(remoteurl);
146
147         if (is_dir_sep(remoteurl[len-1]))
148                 remoteurl[len-1] = '\0';
149
150         if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
151                 is_relative = 0;
152         else {
153                 is_relative = 1;
154                 /*
155                  * Prepend a './' to ensure all relative
156                  * remoteurls start with './' or '../'
157                  */
158                 if (!starts_with_dot_slash(remoteurl) &&
159                     !starts_with_dot_dot_slash(remoteurl)) {
160                         strbuf_reset(&sb);
161                         strbuf_addf(&sb, "./%s", remoteurl);
162                         free(remoteurl);
163                         remoteurl = strbuf_detach(&sb, NULL);
164                 }
165         }
166         /*
167          * When the url starts with '../', remove that and the
168          * last directory in remoteurl.
169          */
170         while (url) {
171                 if (starts_with_dot_dot_slash(url)) {
172                         url += 3;
173                         colonsep |= chop_last_dir(&remoteurl, is_relative);
174                 } else if (starts_with_dot_slash(url))
175                         url += 2;
176                 else
177                         break;
178         }
179         strbuf_reset(&sb);
180         strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
181         if (ends_with(url, "/"))
182                 strbuf_setlen(&sb, sb.len - 1);
183         free(remoteurl);
184
185         if (starts_with_dot_slash(sb.buf))
186                 out = xstrdup(sb.buf + 2);
187         else
188                 out = xstrdup(sb.buf);
189         strbuf_reset(&sb);
190
191         if (!up_path || !is_relative)
192                 return out;
193
194         strbuf_addf(&sb, "%s%s", up_path, out);
195         free(out);
196         return strbuf_detach(&sb, NULL);
197 }
198
199 static int resolve_relative_url(int argc, const char **argv, const char *prefix)
200 {
201         char *remoteurl = NULL;
202         char *remote = get_default_remote();
203         const char *up_path = NULL;
204         char *res;
205         const char *url;
206         struct strbuf sb = STRBUF_INIT;
207
208         if (argc != 2 && argc != 3)
209                 die("resolve-relative-url only accepts one or two arguments");
210
211         url = argv[1];
212         strbuf_addf(&sb, "remote.%s.url", remote);
213         free(remote);
214
215         if (git_config_get_string(sb.buf, &remoteurl))
216                 /* the repository is its own authoritative upstream */
217                 remoteurl = xgetcwd();
218
219         if (argc == 3)
220                 up_path = argv[2];
221
222         res = relative_url(remoteurl, url, up_path);
223         puts(res);
224         free(res);
225         free(remoteurl);
226         return 0;
227 }
228
229 static int resolve_relative_url_test(int argc, const char **argv, const char *prefix)
230 {
231         char *remoteurl, *res;
232         const char *up_path, *url;
233
234         if (argc != 4)
235                 die("resolve-relative-url-test only accepts three arguments: <up_path> <remoteurl> <url>");
236
237         up_path = argv[1];
238         remoteurl = xstrdup(argv[2]);
239         url = argv[3];
240
241         if (!strcmp(up_path, "(null)"))
242                 up_path = NULL;
243
244         res = relative_url(remoteurl, url, up_path);
245         puts(res);
246         free(res);
247         free(remoteurl);
248         return 0;
249 }
250
251 /* the result should be freed by the caller. */
252 static char *get_submodule_displaypath(const char *path, const char *prefix)
253 {
254         const char *super_prefix = get_super_prefix();
255
256         if (prefix && super_prefix) {
257                 BUG("cannot have prefix '%s' and superprefix '%s'",
258                     prefix, super_prefix);
259         } else if (prefix) {
260                 struct strbuf sb = STRBUF_INIT;
261                 char *displaypath = xstrdup(relative_path(path, prefix, &sb));
262                 strbuf_release(&sb);
263                 return displaypath;
264         } else if (super_prefix) {
265                 return xstrfmt("%s%s", super_prefix, path);
266         } else {
267                 return xstrdup(path);
268         }
269 }
270
271 static char *compute_rev_name(const char *sub_path, const char* object_id)
272 {
273         struct strbuf sb = STRBUF_INIT;
274         const char ***d;
275
276         static const char *describe_bare[] = { NULL };
277
278         static const char *describe_tags[] = { "--tags", NULL };
279
280         static const char *describe_contains[] = { "--contains", NULL };
281
282         static const char *describe_all_always[] = { "--all", "--always", NULL };
283
284         static const char **describe_argv[] = { describe_bare, describe_tags,
285                                                 describe_contains,
286                                                 describe_all_always, NULL };
287
288         for (d = describe_argv; *d; d++) {
289                 struct child_process cp = CHILD_PROCESS_INIT;
290                 prepare_submodule_repo_env(&cp.env_array);
291                 cp.dir = sub_path;
292                 cp.git_cmd = 1;
293                 cp.no_stderr = 1;
294
295                 argv_array_push(&cp.args, "describe");
296                 argv_array_pushv(&cp.args, *d);
297                 argv_array_push(&cp.args, object_id);
298
299                 if (!capture_command(&cp, &sb, 0)) {
300                         strbuf_strip_suffix(&sb, "\n");
301                         return strbuf_detach(&sb, NULL);
302                 }
303         }
304
305         strbuf_release(&sb);
306         return NULL;
307 }
308
309 struct module_list {
310         const struct cache_entry **entries;
311         int alloc, nr;
312 };
313 #define MODULE_LIST_INIT { NULL, 0, 0 }
314
315 static int module_list_compute(int argc, const char **argv,
316                                const char *prefix,
317                                struct pathspec *pathspec,
318                                struct module_list *list)
319 {
320         int i, result = 0;
321         char *ps_matched = NULL;
322         parse_pathspec(pathspec, 0,
323                        PATHSPEC_PREFER_FULL,
324                        prefix, argv);
325
326         if (pathspec->nr)
327                 ps_matched = xcalloc(pathspec->nr, 1);
328
329         if (read_cache() < 0)
330                 die(_("index file corrupt"));
331
332         for (i = 0; i < active_nr; i++) {
333                 const struct cache_entry *ce = active_cache[i];
334
335                 if (!match_pathspec(&the_index, pathspec, ce->name, ce_namelen(ce),
336                                     0, ps_matched, 1) ||
337                     !S_ISGITLINK(ce->ce_mode))
338                         continue;
339
340                 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
341                 list->entries[list->nr++] = ce;
342                 while (i + 1 < active_nr &&
343                        !strcmp(ce->name, active_cache[i + 1]->name))
344                         /*
345                          * Skip entries with the same name in different stages
346                          * to make sure an entry is returned only once.
347                          */
348                         i++;
349         }
350
351         if (ps_matched && report_path_error(ps_matched, pathspec, prefix))
352                 result = -1;
353
354         free(ps_matched);
355
356         return result;
357 }
358
359 static void module_list_active(struct module_list *list)
360 {
361         int i;
362         struct module_list active_modules = MODULE_LIST_INIT;
363
364         for (i = 0; i < list->nr; i++) {
365                 const struct cache_entry *ce = list->entries[i];
366
367                 if (!is_submodule_active(the_repository, ce->name))
368                         continue;
369
370                 ALLOC_GROW(active_modules.entries,
371                            active_modules.nr + 1,
372                            active_modules.alloc);
373                 active_modules.entries[active_modules.nr++] = ce;
374         }
375
376         free(list->entries);
377         *list = active_modules;
378 }
379
380 static char *get_up_path(const char *path)
381 {
382         int i;
383         struct strbuf sb = STRBUF_INIT;
384
385         for (i = count_slashes(path); i; i--)
386                 strbuf_addstr(&sb, "../");
387
388         /*
389          * Check if 'path' ends with slash or not
390          * for having the same output for dir/sub_dir
391          * and dir/sub_dir/
392          */
393         if (!is_dir_sep(path[strlen(path) - 1]))
394                 strbuf_addstr(&sb, "../");
395
396         return strbuf_detach(&sb, NULL);
397 }
398
399 static int module_list(int argc, const char **argv, const char *prefix)
400 {
401         int i;
402         struct pathspec pathspec;
403         struct module_list list = MODULE_LIST_INIT;
404
405         struct option module_list_options[] = {
406                 OPT_STRING(0, "prefix", &prefix,
407                            N_("path"),
408                            N_("alternative anchor for relative paths")),
409                 OPT_END()
410         };
411
412         const char *const git_submodule_helper_usage[] = {
413                 N_("git submodule--helper list [--prefix=<path>] [<path>...]"),
414                 NULL
415         };
416
417         argc = parse_options(argc, argv, prefix, module_list_options,
418                              git_submodule_helper_usage, 0);
419
420         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
421                 return 1;
422
423         for (i = 0; i < list.nr; i++) {
424                 const struct cache_entry *ce = list.entries[i];
425
426                 if (ce_stage(ce))
427                         printf("%06o %s U\t", ce->ce_mode, sha1_to_hex(null_sha1));
428                 else
429                         printf("%06o %s %d\t", ce->ce_mode,
430                                oid_to_hex(&ce->oid), ce_stage(ce));
431
432                 fprintf(stdout, "%s\n", ce->name);
433         }
434         return 0;
435 }
436
437 static void for_each_listed_submodule(const struct module_list *list,
438                                       each_submodule_fn fn, void *cb_data)
439 {
440         int i;
441         for (i = 0; i < list->nr; i++)
442                 fn(list->entries[i], cb_data);
443 }
444
445 struct cb_foreach {
446         int argc;
447         const char **argv;
448         const char *prefix;
449         int quiet;
450         int recursive;
451 };
452 #define CB_FOREACH_INIT { 0 }
453
454 static void runcommand_in_submodule_cb(const struct cache_entry *list_item,
455                                        void *cb_data)
456 {
457         struct cb_foreach *info = cb_data;
458         const char *path = list_item->name;
459         const struct object_id *ce_oid = &list_item->oid;
460
461         const struct submodule *sub;
462         struct child_process cp = CHILD_PROCESS_INIT;
463         char *displaypath;
464
465         displaypath = get_submodule_displaypath(path, info->prefix);
466
467         sub = submodule_from_path(the_repository, &null_oid, path);
468
469         if (!sub)
470                 die(_("No url found for submodule path '%s' in .gitmodules"),
471                         displaypath);
472
473         if (!is_submodule_populated_gently(path, NULL))
474                 goto cleanup;
475
476         prepare_submodule_repo_env(&cp.env_array);
477
478         /*
479          * For the purpose of executing <command> in the submodule,
480          * separate shell is used for the purpose of running the
481          * child process.
482          */
483         cp.use_shell = 1;
484         cp.dir = path;
485
486         /*
487          * NEEDSWORK: the command currently has access to the variables $name,
488          * $sm_path, $displaypath, $sha1 and $toplevel only when the command
489          * contains a single argument. This is done for maintaining a faithful
490          * translation from shell script.
491          */
492         if (info->argc == 1) {
493                 char *toplevel = xgetcwd();
494                 struct strbuf sb = STRBUF_INIT;
495
496                 argv_array_pushf(&cp.env_array, "name=%s", sub->name);
497                 argv_array_pushf(&cp.env_array, "sm_path=%s", path);
498                 argv_array_pushf(&cp.env_array, "displaypath=%s", displaypath);
499                 argv_array_pushf(&cp.env_array, "sha1=%s",
500                                 oid_to_hex(ce_oid));
501                 argv_array_pushf(&cp.env_array, "toplevel=%s", toplevel);
502
503                 /*
504                  * Since the path variable was accessible from the script
505                  * before porting, it is also made available after porting.
506                  * The environment variable "PATH" has a very special purpose
507                  * on windows. And since environment variables are
508                  * case-insensitive in windows, it interferes with the
509                  * existing PATH variable. Hence, to avoid that, we expose
510                  * path via the args argv_array and not via env_array.
511                  */
512                 sq_quote_buf(&sb, path);
513                 argv_array_pushf(&cp.args, "path=%s; %s",
514                                  sb.buf, info->argv[0]);
515                 strbuf_release(&sb);
516                 free(toplevel);
517         } else {
518                 argv_array_pushv(&cp.args, info->argv);
519         }
520
521         if (!info->quiet)
522                 printf(_("Entering '%s'\n"), displaypath);
523
524         if (info->argv[0] && run_command(&cp))
525                 die(_("run_command returned non-zero status for %s\n."),
526                         displaypath);
527
528         if (info->recursive) {
529                 struct child_process cpr = CHILD_PROCESS_INIT;
530
531                 cpr.git_cmd = 1;
532                 cpr.dir = path;
533                 prepare_submodule_repo_env(&cpr.env_array);
534
535                 argv_array_pushl(&cpr.args, "--super-prefix", NULL);
536                 argv_array_pushf(&cpr.args, "%s/", displaypath);
537                 argv_array_pushl(&cpr.args, "submodule--helper", "foreach", "--recursive",
538                                 NULL);
539
540                 if (info->quiet)
541                         argv_array_push(&cpr.args, "--quiet");
542
543                 argv_array_pushv(&cpr.args, info->argv);
544
545                 if (run_command(&cpr))
546                         die(_("run_command returned non-zero status while "
547                                 "recursing in the nested submodules of %s\n."),
548                                 displaypath);
549         }
550
551 cleanup:
552         free(displaypath);
553 }
554
555 static int module_foreach(int argc, const char **argv, const char *prefix)
556 {
557         struct cb_foreach info = CB_FOREACH_INIT;
558         struct pathspec pathspec;
559         struct module_list list = MODULE_LIST_INIT;
560
561         struct option module_foreach_options[] = {
562                 OPT__QUIET(&info.quiet, N_("Suppress output of entering each submodule command")),
563                 OPT_BOOL(0, "recursive", &info.recursive,
564                          N_("Recurse into nested submodules")),
565                 OPT_END()
566         };
567
568         const char *const git_submodule_helper_usage[] = {
569                 N_("git submodule--helper foreach [--quiet] [--recursive] <command>"),
570                 NULL
571         };
572
573         argc = parse_options(argc, argv, prefix, module_foreach_options,
574                              git_submodule_helper_usage, PARSE_OPT_KEEP_UNKNOWN);
575
576         if (module_list_compute(0, NULL, prefix, &pathspec, &list) < 0)
577                 return 1;
578
579         info.argc = argc;
580         info.argv = argv;
581         info.prefix = prefix;
582
583         for_each_listed_submodule(&list, runcommand_in_submodule_cb, &info);
584
585         return 0;
586 }
587
588 struct init_cb {
589         const char *prefix;
590         unsigned int flags;
591 };
592
593 #define INIT_CB_INIT { NULL, 0 }
594
595 static void init_submodule(const char *path, const char *prefix,
596                            unsigned int flags)
597 {
598         const struct submodule *sub;
599         struct strbuf sb = STRBUF_INIT;
600         char *upd = NULL, *url = NULL, *displaypath;
601
602         displaypath = get_submodule_displaypath(path, prefix);
603
604         sub = submodule_from_path(the_repository, &null_oid, path);
605
606         if (!sub)
607                 die(_("No url found for submodule path '%s' in .gitmodules"),
608                         displaypath);
609
610         /*
611          * NEEDSWORK: In a multi-working-tree world, this needs to be
612          * set in the per-worktree config.
613          *
614          * Set active flag for the submodule being initialized
615          */
616         if (!is_submodule_active(the_repository, path)) {
617                 strbuf_addf(&sb, "submodule.%s.active", sub->name);
618                 git_config_set_gently(sb.buf, "true");
619                 strbuf_reset(&sb);
620         }
621
622         /*
623          * Copy url setting when it is not set yet.
624          * To look up the url in .git/config, we must not fall back to
625          * .gitmodules, so look it up directly.
626          */
627         strbuf_addf(&sb, "submodule.%s.url", sub->name);
628         if (git_config_get_string(sb.buf, &url)) {
629                 if (!sub->url)
630                         die(_("No url found for submodule path '%s' in .gitmodules"),
631                                 displaypath);
632
633                 url = xstrdup(sub->url);
634
635                 /* Possibly a url relative to parent */
636                 if (starts_with_dot_dot_slash(url) ||
637                     starts_with_dot_slash(url)) {
638                         char *remoteurl, *relurl;
639                         char *remote = get_default_remote();
640                         struct strbuf remotesb = STRBUF_INIT;
641                         strbuf_addf(&remotesb, "remote.%s.url", remote);
642                         free(remote);
643
644                         if (git_config_get_string(remotesb.buf, &remoteurl)) {
645                                 warning(_("could not lookup configuration '%s'. Assuming this repository is its own authoritative upstream."), remotesb.buf);
646                                 remoteurl = xgetcwd();
647                         }
648                         relurl = relative_url(remoteurl, url, NULL);
649                         strbuf_release(&remotesb);
650                         free(remoteurl);
651                         free(url);
652                         url = relurl;
653                 }
654
655                 if (git_config_set_gently(sb.buf, url))
656                         die(_("Failed to register url for submodule path '%s'"),
657                             displaypath);
658                 if (!(flags & OPT_QUIET))
659                         fprintf(stderr,
660                                 _("Submodule '%s' (%s) registered for path '%s'\n"),
661                                 sub->name, url, displaypath);
662         }
663         strbuf_reset(&sb);
664
665         /* Copy "update" setting when it is not set yet */
666         strbuf_addf(&sb, "submodule.%s.update", sub->name);
667         if (git_config_get_string(sb.buf, &upd) &&
668             sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
669                 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
670                         fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
671                                 sub->name);
672                         upd = xstrdup("none");
673                 } else
674                         upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
675
676                 if (git_config_set_gently(sb.buf, upd))
677                         die(_("Failed to register update mode for submodule path '%s'"), displaypath);
678         }
679         strbuf_release(&sb);
680         free(displaypath);
681         free(url);
682         free(upd);
683 }
684
685 static void init_submodule_cb(const struct cache_entry *list_item, void *cb_data)
686 {
687         struct init_cb *info = cb_data;
688         init_submodule(list_item->name, info->prefix, info->flags);
689 }
690
691 static int module_init(int argc, const char **argv, const char *prefix)
692 {
693         struct init_cb info = INIT_CB_INIT;
694         struct pathspec pathspec;
695         struct module_list list = MODULE_LIST_INIT;
696         int quiet = 0;
697
698         struct option module_init_options[] = {
699                 OPT__QUIET(&quiet, N_("Suppress output for initializing a submodule")),
700                 OPT_END()
701         };
702
703         const char *const git_submodule_helper_usage[] = {
704                 N_("git submodule--helper init [<path>]"),
705                 NULL
706         };
707
708         argc = parse_options(argc, argv, prefix, module_init_options,
709                              git_submodule_helper_usage, 0);
710
711         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
712                 return 1;
713
714         /*
715          * If there are no path args and submodule.active is set then,
716          * by default, only initialize 'active' modules.
717          */
718         if (!argc && git_config_get_value_multi("submodule.active"))
719                 module_list_active(&list);
720
721         info.prefix = prefix;
722         if (quiet)
723                 info.flags |= OPT_QUIET;
724
725         for_each_listed_submodule(&list, init_submodule_cb, &info);
726
727         return 0;
728 }
729
730 struct status_cb {
731         const char *prefix;
732         unsigned int flags;
733 };
734
735 #define STATUS_CB_INIT { NULL, 0 }
736
737 static void print_status(unsigned int flags, char state, const char *path,
738                          const struct object_id *oid, const char *displaypath)
739 {
740         if (flags & OPT_QUIET)
741                 return;
742
743         printf("%c%s %s", state, oid_to_hex(oid), displaypath);
744
745         if (state == ' ' || state == '+') {
746                 const char *name = compute_rev_name(path, oid_to_hex(oid));
747
748                 if (name)
749                         printf(" (%s)", name);
750         }
751
752         printf("\n");
753 }
754
755 static int handle_submodule_head_ref(const char *refname,
756                                      const struct object_id *oid, int flags,
757                                      void *cb_data)
758 {
759         struct object_id *output = cb_data;
760         if (oid)
761                 oidcpy(output, oid);
762
763         return 0;
764 }
765
766 static void status_submodule(const char *path, const struct object_id *ce_oid,
767                              unsigned int ce_flags, const char *prefix,
768                              unsigned int flags)
769 {
770         char *displaypath;
771         struct argv_array diff_files_args = ARGV_ARRAY_INIT;
772         struct rev_info rev;
773         int diff_files_result;
774
775         if (!submodule_from_path(the_repository, &null_oid, path))
776                 die(_("no submodule mapping found in .gitmodules for path '%s'"),
777                       path);
778
779         displaypath = get_submodule_displaypath(path, prefix);
780
781         if ((CE_STAGEMASK & ce_flags) >> CE_STAGESHIFT) {
782                 print_status(flags, 'U', path, &null_oid, displaypath);
783                 goto cleanup;
784         }
785
786         if (!is_submodule_active(the_repository, path)) {
787                 print_status(flags, '-', path, ce_oid, displaypath);
788                 goto cleanup;
789         }
790
791         argv_array_pushl(&diff_files_args, "diff-files",
792                          "--ignore-submodules=dirty", "--quiet", "--",
793                          path, NULL);
794
795         git_config(git_diff_basic_config, NULL);
796         init_revisions(&rev, prefix);
797         rev.abbrev = 0;
798         diff_files_args.argc = setup_revisions(diff_files_args.argc,
799                                                diff_files_args.argv,
800                                                &rev, NULL);
801         diff_files_result = run_diff_files(&rev, 0);
802
803         if (!diff_result_code(&rev.diffopt, diff_files_result)) {
804                 print_status(flags, ' ', path, ce_oid,
805                              displaypath);
806         } else if (!(flags & OPT_CACHED)) {
807                 struct object_id oid;
808                 struct ref_store *refs = get_submodule_ref_store(path);
809
810                 if (!refs) {
811                         print_status(flags, '-', path, ce_oid, displaypath);
812                         goto cleanup;
813                 }
814                 if (refs_head_ref(refs, handle_submodule_head_ref, &oid))
815                         die(_("could not resolve HEAD ref inside the "
816                               "submodule '%s'"), path);
817
818                 print_status(flags, '+', path, &oid, displaypath);
819         } else {
820                 print_status(flags, '+', path, ce_oid, displaypath);
821         }
822
823         if (flags & OPT_RECURSIVE) {
824                 struct child_process cpr = CHILD_PROCESS_INIT;
825
826                 cpr.git_cmd = 1;
827                 cpr.dir = path;
828                 prepare_submodule_repo_env(&cpr.env_array);
829
830                 argv_array_push(&cpr.args, "--super-prefix");
831                 argv_array_pushf(&cpr.args, "%s/", displaypath);
832                 argv_array_pushl(&cpr.args, "submodule--helper", "status",
833                                  "--recursive", NULL);
834
835                 if (flags & OPT_CACHED)
836                         argv_array_push(&cpr.args, "--cached");
837
838                 if (flags & OPT_QUIET)
839                         argv_array_push(&cpr.args, "--quiet");
840
841                 if (run_command(&cpr))
842                         die(_("failed to recurse into submodule '%s'"), path);
843         }
844
845 cleanup:
846         argv_array_clear(&diff_files_args);
847         free(displaypath);
848 }
849
850 static void status_submodule_cb(const struct cache_entry *list_item,
851                                 void *cb_data)
852 {
853         struct status_cb *info = cb_data;
854         status_submodule(list_item->name, &list_item->oid, list_item->ce_flags,
855                          info->prefix, info->flags);
856 }
857
858 static int module_status(int argc, const char **argv, const char *prefix)
859 {
860         struct status_cb info = STATUS_CB_INIT;
861         struct pathspec pathspec;
862         struct module_list list = MODULE_LIST_INIT;
863         int quiet = 0;
864
865         struct option module_status_options[] = {
866                 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
867                 OPT_BIT(0, "cached", &info.flags, N_("Use commit stored in the index instead of the one stored in the submodule HEAD"), OPT_CACHED),
868                 OPT_BIT(0, "recursive", &info.flags, N_("recurse into nested submodules"), OPT_RECURSIVE),
869                 OPT_END()
870         };
871
872         const char *const git_submodule_helper_usage[] = {
873                 N_("git submodule status [--quiet] [--cached] [--recursive] [<path>...]"),
874                 NULL
875         };
876
877         argc = parse_options(argc, argv, prefix, module_status_options,
878                              git_submodule_helper_usage, 0);
879
880         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
881                 return 1;
882
883         info.prefix = prefix;
884         if (quiet)
885                 info.flags |= OPT_QUIET;
886
887         for_each_listed_submodule(&list, status_submodule_cb, &info);
888
889         return 0;
890 }
891
892 static int module_name(int argc, const char **argv, const char *prefix)
893 {
894         const struct submodule *sub;
895
896         if (argc != 2)
897                 usage(_("git submodule--helper name <path>"));
898
899         sub = submodule_from_path(the_repository, &null_oid, argv[1]);
900
901         if (!sub)
902                 die(_("no submodule mapping found in .gitmodules for path '%s'"),
903                     argv[1]);
904
905         printf("%s\n", sub->name);
906
907         return 0;
908 }
909
910 struct sync_cb {
911         const char *prefix;
912         unsigned int flags;
913 };
914
915 #define SYNC_CB_INIT { NULL, 0 }
916
917 static void sync_submodule(const char *path, const char *prefix,
918                            unsigned int flags)
919 {
920         const struct submodule *sub;
921         char *remote_key = NULL;
922         char *sub_origin_url, *super_config_url, *displaypath;
923         struct strbuf sb = STRBUF_INIT;
924         struct child_process cp = CHILD_PROCESS_INIT;
925         char *sub_config_path = NULL;
926
927         if (!is_submodule_active(the_repository, path))
928                 return;
929
930         sub = submodule_from_path(the_repository, &null_oid, path);
931
932         if (sub && sub->url) {
933                 if (starts_with_dot_dot_slash(sub->url) ||
934                     starts_with_dot_slash(sub->url)) {
935                         char *remote_url, *up_path;
936                         char *remote = get_default_remote();
937                         strbuf_addf(&sb, "remote.%s.url", remote);
938
939                         if (git_config_get_string(sb.buf, &remote_url))
940                                 remote_url = xgetcwd();
941
942                         up_path = get_up_path(path);
943                         sub_origin_url = relative_url(remote_url, sub->url, up_path);
944                         super_config_url = relative_url(remote_url, sub->url, NULL);
945
946                         free(remote);
947                         free(up_path);
948                         free(remote_url);
949                 } else {
950                         sub_origin_url = xstrdup(sub->url);
951                         super_config_url = xstrdup(sub->url);
952                 }
953         } else {
954                 sub_origin_url = xstrdup("");
955                 super_config_url = xstrdup("");
956         }
957
958         displaypath = get_submodule_displaypath(path, prefix);
959
960         if (!(flags & OPT_QUIET))
961                 printf(_("Synchronizing submodule url for '%s'\n"),
962                          displaypath);
963
964         strbuf_reset(&sb);
965         strbuf_addf(&sb, "submodule.%s.url", sub->name);
966         if (git_config_set_gently(sb.buf, super_config_url))
967                 die(_("failed to register url for submodule path '%s'"),
968                       displaypath);
969
970         if (!is_submodule_populated_gently(path, NULL))
971                 goto cleanup;
972
973         prepare_submodule_repo_env(&cp.env_array);
974         cp.git_cmd = 1;
975         cp.dir = path;
976         argv_array_pushl(&cp.args, "submodule--helper",
977                          "print-default-remote", NULL);
978
979         strbuf_reset(&sb);
980         if (capture_command(&cp, &sb, 0))
981                 die(_("failed to get the default remote for submodule '%s'"),
982                       path);
983
984         strbuf_strip_suffix(&sb, "\n");
985         remote_key = xstrfmt("remote.%s.url", sb.buf);
986
987         strbuf_reset(&sb);
988         submodule_to_gitdir(&sb, path);
989         strbuf_addstr(&sb, "/config");
990
991         if (git_config_set_in_file_gently(sb.buf, remote_key, sub_origin_url))
992                 die(_("failed to update remote for submodule '%s'"),
993                       path);
994
995         if (flags & OPT_RECURSIVE) {
996                 struct child_process cpr = CHILD_PROCESS_INIT;
997
998                 cpr.git_cmd = 1;
999                 cpr.dir = path;
1000                 prepare_submodule_repo_env(&cpr.env_array);
1001
1002                 argv_array_push(&cpr.args, "--super-prefix");
1003                 argv_array_pushf(&cpr.args, "%s/", displaypath);
1004                 argv_array_pushl(&cpr.args, "submodule--helper", "sync",
1005                                  "--recursive", NULL);
1006
1007                 if (flags & OPT_QUIET)
1008                         argv_array_push(&cpr.args, "--quiet");
1009
1010                 if (run_command(&cpr))
1011                         die(_("failed to recurse into submodule '%s'"),
1012                               path);
1013         }
1014
1015 cleanup:
1016         free(super_config_url);
1017         free(sub_origin_url);
1018         strbuf_release(&sb);
1019         free(remote_key);
1020         free(displaypath);
1021         free(sub_config_path);
1022 }
1023
1024 static void sync_submodule_cb(const struct cache_entry *list_item, void *cb_data)
1025 {
1026         struct sync_cb *info = cb_data;
1027         sync_submodule(list_item->name, info->prefix, info->flags);
1028 }
1029
1030 static int module_sync(int argc, const char **argv, const char *prefix)
1031 {
1032         struct sync_cb info = SYNC_CB_INIT;
1033         struct pathspec pathspec;
1034         struct module_list list = MODULE_LIST_INIT;
1035         int quiet = 0;
1036         int recursive = 0;
1037
1038         struct option module_sync_options[] = {
1039                 OPT__QUIET(&quiet, N_("Suppress output of synchronizing submodule url")),
1040                 OPT_BOOL(0, "recursive", &recursive,
1041                         N_("Recurse into nested submodules")),
1042                 OPT_END()
1043         };
1044
1045         const char *const git_submodule_helper_usage[] = {
1046                 N_("git submodule--helper sync [--quiet] [--recursive] [<path>]"),
1047                 NULL
1048         };
1049
1050         argc = parse_options(argc, argv, prefix, module_sync_options,
1051                              git_submodule_helper_usage, 0);
1052
1053         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1054                 return 1;
1055
1056         info.prefix = prefix;
1057         if (quiet)
1058                 info.flags |= OPT_QUIET;
1059         if (recursive)
1060                 info.flags |= OPT_RECURSIVE;
1061
1062         for_each_listed_submodule(&list, sync_submodule_cb, &info);
1063
1064         return 0;
1065 }
1066
1067 struct deinit_cb {
1068         const char *prefix;
1069         unsigned int flags;
1070 };
1071 #define DEINIT_CB_INIT { NULL, 0 }
1072
1073 static void deinit_submodule(const char *path, const char *prefix,
1074                              unsigned int flags)
1075 {
1076         const struct submodule *sub;
1077         char *displaypath = NULL;
1078         struct child_process cp_config = CHILD_PROCESS_INIT;
1079         struct strbuf sb_config = STRBUF_INIT;
1080         char *sub_git_dir = xstrfmt("%s/.git", path);
1081
1082         sub = submodule_from_path(the_repository, &null_oid, path);
1083
1084         if (!sub || !sub->name)
1085                 goto cleanup;
1086
1087         displaypath = get_submodule_displaypath(path, prefix);
1088
1089         /* remove the submodule work tree (unless the user already did it) */
1090         if (is_directory(path)) {
1091                 struct strbuf sb_rm = STRBUF_INIT;
1092                 const char *format;
1093
1094                 /*
1095                  * protect submodules containing a .git directory
1096                  * NEEDSWORK: instead of dying, automatically call
1097                  * absorbgitdirs and (possibly) warn.
1098                  */
1099                 if (is_directory(sub_git_dir))
1100                         die(_("Submodule work tree '%s' contains a .git "
1101                               "directory (use 'rm -rf' if you really want "
1102                               "to remove it including all of its history)"),
1103                             displaypath);
1104
1105                 if (!(flags & OPT_FORCE)) {
1106                         struct child_process cp_rm = CHILD_PROCESS_INIT;
1107                         cp_rm.git_cmd = 1;
1108                         argv_array_pushl(&cp_rm.args, "rm", "-qn",
1109                                          path, NULL);
1110
1111                         if (run_command(&cp_rm))
1112                                 die(_("Submodule work tree '%s' contains local "
1113                                       "modifications; use '-f' to discard them"),
1114                                       displaypath);
1115                 }
1116
1117                 strbuf_addstr(&sb_rm, path);
1118
1119                 if (!remove_dir_recursively(&sb_rm, 0))
1120                         format = _("Cleared directory '%s'\n");
1121                 else
1122                         format = _("Could not remove submodule work tree '%s'\n");
1123
1124                 if (!(flags & OPT_QUIET))
1125                         printf(format, displaypath);
1126
1127                 strbuf_release(&sb_rm);
1128         }
1129
1130         if (mkdir(path, 0777))
1131                 printf(_("could not create empty submodule directory %s"),
1132                       displaypath);
1133
1134         cp_config.git_cmd = 1;
1135         argv_array_pushl(&cp_config.args, "config", "--get-regexp", NULL);
1136         argv_array_pushf(&cp_config.args, "submodule.%s\\.", sub->name);
1137
1138         /* remove the .git/config entries (unless the user already did it) */
1139         if (!capture_command(&cp_config, &sb_config, 0) && sb_config.len) {
1140                 char *sub_key = xstrfmt("submodule.%s", sub->name);
1141                 /*
1142                  * remove the whole section so we have a clean state when
1143                  * the user later decides to init this submodule again
1144                  */
1145                 git_config_rename_section_in_file(NULL, sub_key, NULL);
1146                 if (!(flags & OPT_QUIET))
1147                         printf(_("Submodule '%s' (%s) unregistered for path '%s'\n"),
1148                                  sub->name, sub->url, displaypath);
1149                 free(sub_key);
1150         }
1151
1152 cleanup:
1153         free(displaypath);
1154         free(sub_git_dir);
1155         strbuf_release(&sb_config);
1156 }
1157
1158 static void deinit_submodule_cb(const struct cache_entry *list_item,
1159                                 void *cb_data)
1160 {
1161         struct deinit_cb *info = cb_data;
1162         deinit_submodule(list_item->name, info->prefix, info->flags);
1163 }
1164
1165 static int module_deinit(int argc, const char **argv, const char *prefix)
1166 {
1167         struct deinit_cb info = DEINIT_CB_INIT;
1168         struct pathspec pathspec;
1169         struct module_list list = MODULE_LIST_INIT;
1170         int quiet = 0;
1171         int force = 0;
1172         int all = 0;
1173
1174         struct option module_deinit_options[] = {
1175                 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
1176                 OPT__FORCE(&force, N_("Remove submodule working trees even if they contain local changes"), 0),
1177                 OPT_BOOL(0, "all", &all, N_("Unregister all submodules")),
1178                 OPT_END()
1179         };
1180
1181         const char *const git_submodule_helper_usage[] = {
1182                 N_("git submodule deinit [--quiet] [-f | --force] [--all | [--] [<path>...]]"),
1183                 NULL
1184         };
1185
1186         argc = parse_options(argc, argv, prefix, module_deinit_options,
1187                              git_submodule_helper_usage, 0);
1188
1189         if (all && argc) {
1190                 error("pathspec and --all are incompatible");
1191                 usage_with_options(git_submodule_helper_usage,
1192                                    module_deinit_options);
1193         }
1194
1195         if (!argc && !all)
1196                 die(_("Use '--all' if you really want to deinitialize all submodules"));
1197
1198         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1199                 return 1;
1200
1201         info.prefix = prefix;
1202         if (quiet)
1203                 info.flags |= OPT_QUIET;
1204         if (force)
1205                 info.flags |= OPT_FORCE;
1206
1207         for_each_listed_submodule(&list, deinit_submodule_cb, &info);
1208
1209         return 0;
1210 }
1211
1212 static int clone_submodule(const char *path, const char *gitdir, const char *url,
1213                            const char *depth, struct string_list *reference, int dissociate,
1214                            int quiet, int progress)
1215 {
1216         struct child_process cp = CHILD_PROCESS_INIT;
1217
1218         argv_array_push(&cp.args, "clone");
1219         argv_array_push(&cp.args, "--no-checkout");
1220         if (quiet)
1221                 argv_array_push(&cp.args, "--quiet");
1222         if (progress)
1223                 argv_array_push(&cp.args, "--progress");
1224         if (depth && *depth)
1225                 argv_array_pushl(&cp.args, "--depth", depth, NULL);
1226         if (reference->nr) {
1227                 struct string_list_item *item;
1228                 for_each_string_list_item(item, reference)
1229                         argv_array_pushl(&cp.args, "--reference",
1230                                          item->string, NULL);
1231         }
1232         if (dissociate)
1233                 argv_array_push(&cp.args, "--dissociate");
1234         if (gitdir && *gitdir)
1235                 argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
1236
1237         argv_array_push(&cp.args, "--");
1238         argv_array_push(&cp.args, url);
1239         argv_array_push(&cp.args, path);
1240
1241         cp.git_cmd = 1;
1242         prepare_submodule_repo_env(&cp.env_array);
1243         cp.no_stdin = 1;
1244
1245         return run_command(&cp);
1246 }
1247
1248 struct submodule_alternate_setup {
1249         const char *submodule_name;
1250         enum SUBMODULE_ALTERNATE_ERROR_MODE {
1251                 SUBMODULE_ALTERNATE_ERROR_DIE,
1252                 SUBMODULE_ALTERNATE_ERROR_INFO,
1253                 SUBMODULE_ALTERNATE_ERROR_IGNORE
1254         } error_mode;
1255         struct string_list *reference;
1256 };
1257 #define SUBMODULE_ALTERNATE_SETUP_INIT { NULL, \
1258         SUBMODULE_ALTERNATE_ERROR_IGNORE, NULL }
1259
1260 static int add_possible_reference_from_superproject(
1261                 struct alternate_object_database *alt, void *sas_cb)
1262 {
1263         struct submodule_alternate_setup *sas = sas_cb;
1264
1265         /*
1266          * If the alternate object store is another repository, try the
1267          * standard layout with .git/(modules/<name>)+/objects
1268          */
1269         if (ends_with(alt->path, "/objects")) {
1270                 char *sm_alternate;
1271                 struct strbuf sb = STRBUF_INIT;
1272                 struct strbuf err = STRBUF_INIT;
1273                 strbuf_add(&sb, alt->path, strlen(alt->path) - strlen("objects"));
1274
1275                 /*
1276                  * We need to end the new path with '/' to mark it as a dir,
1277                  * otherwise a submodule name containing '/' will be broken
1278                  * as the last part of a missing submodule reference would
1279                  * be taken as a file name.
1280                  */
1281                 strbuf_addf(&sb, "modules/%s/", sas->submodule_name);
1282
1283                 sm_alternate = compute_alternate_path(sb.buf, &err);
1284                 if (sm_alternate) {
1285                         string_list_append(sas->reference, xstrdup(sb.buf));
1286                         free(sm_alternate);
1287                 } else {
1288                         switch (sas->error_mode) {
1289                         case SUBMODULE_ALTERNATE_ERROR_DIE:
1290                                 die(_("submodule '%s' cannot add alternate: %s"),
1291                                     sas->submodule_name, err.buf);
1292                         case SUBMODULE_ALTERNATE_ERROR_INFO:
1293                                 fprintf(stderr, _("submodule '%s' cannot add alternate: %s"),
1294                                         sas->submodule_name, err.buf);
1295                         case SUBMODULE_ALTERNATE_ERROR_IGNORE:
1296                                 ; /* nothing */
1297                         }
1298                 }
1299                 strbuf_release(&sb);
1300         }
1301
1302         return 0;
1303 }
1304
1305 static void prepare_possible_alternates(const char *sm_name,
1306                 struct string_list *reference)
1307 {
1308         char *sm_alternate = NULL, *error_strategy = NULL;
1309         struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
1310
1311         git_config_get_string("submodule.alternateLocation", &sm_alternate);
1312         if (!sm_alternate)
1313                 return;
1314
1315         git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1316
1317         if (!error_strategy)
1318                 error_strategy = xstrdup("die");
1319
1320         sas.submodule_name = sm_name;
1321         sas.reference = reference;
1322         if (!strcmp(error_strategy, "die"))
1323                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
1324         else if (!strcmp(error_strategy, "info"))
1325                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
1326         else if (!strcmp(error_strategy, "ignore"))
1327                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
1328         else
1329                 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
1330
1331         if (!strcmp(sm_alternate, "superproject"))
1332                 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
1333         else if (!strcmp(sm_alternate, "no"))
1334                 ; /* do nothing */
1335         else
1336                 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
1337
1338         free(sm_alternate);
1339         free(error_strategy);
1340 }
1341
1342 static int module_clone(int argc, const char **argv, const char *prefix)
1343 {
1344         const char *name = NULL, *url = NULL, *depth = NULL;
1345         int quiet = 0;
1346         int progress = 0;
1347         char *p, *path = NULL, *sm_gitdir;
1348         struct strbuf sb = STRBUF_INIT;
1349         struct string_list reference = STRING_LIST_INIT_NODUP;
1350         int dissociate = 0, require_init = 0;
1351         char *sm_alternate = NULL, *error_strategy = NULL;
1352
1353         struct option module_clone_options[] = {
1354                 OPT_STRING(0, "prefix", &prefix,
1355                            N_("path"),
1356                            N_("alternative anchor for relative paths")),
1357                 OPT_STRING(0, "path", &path,
1358                            N_("path"),
1359                            N_("where the new submodule will be cloned to")),
1360                 OPT_STRING(0, "name", &name,
1361                            N_("string"),
1362                            N_("name of the new submodule")),
1363                 OPT_STRING(0, "url", &url,
1364                            N_("string"),
1365                            N_("url where to clone the submodule from")),
1366                 OPT_STRING_LIST(0, "reference", &reference,
1367                            N_("repo"),
1368                            N_("reference repository")),
1369                 OPT_BOOL(0, "dissociate", &dissociate,
1370                            N_("use --reference only while cloning")),
1371                 OPT_STRING(0, "depth", &depth,
1372                            N_("string"),
1373                            N_("depth for shallow clones")),
1374                 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
1375                 OPT_BOOL(0, "progress", &progress,
1376                            N_("force cloning progress")),
1377                 OPT_BOOL(0, "require-init", &require_init,
1378                            N_("disallow cloning into non-empty directory")),
1379                 OPT_END()
1380         };
1381
1382         const char *const git_submodule_helper_usage[] = {
1383                 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
1384                    "[--reference <repository>] [--name <name>] [--depth <depth>] "
1385                    "--url <url> --path <path>"),
1386                 NULL
1387         };
1388
1389         argc = parse_options(argc, argv, prefix, module_clone_options,
1390                              git_submodule_helper_usage, 0);
1391
1392         if (argc || !url || !path || !*path)
1393                 usage_with_options(git_submodule_helper_usage,
1394                                    module_clone_options);
1395
1396         strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
1397         sm_gitdir = absolute_pathdup(sb.buf);
1398         strbuf_reset(&sb);
1399
1400         if (!is_absolute_path(path)) {
1401                 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
1402                 path = strbuf_detach(&sb, NULL);
1403         } else
1404                 path = xstrdup(path);
1405
1406         if (validate_submodule_git_dir(sm_gitdir, name) < 0)
1407                 die(_("refusing to create/use '%s' in another submodule's "
1408                         "git dir"), sm_gitdir);
1409
1410         if (!file_exists(sm_gitdir)) {
1411                 if (safe_create_leading_directories_const(sm_gitdir) < 0)
1412                         die(_("could not create directory '%s'"), sm_gitdir);
1413
1414                 prepare_possible_alternates(name, &reference);
1415
1416                 if (clone_submodule(path, sm_gitdir, url, depth, &reference, dissociate,
1417                                     quiet, progress))
1418                         die(_("clone of '%s' into submodule path '%s' failed"),
1419                             url, path);
1420         } else {
1421                 if (require_init && !access(path, X_OK) && !is_empty_dir(path))
1422                         die(_("directory not empty: '%s'"), path);
1423                 if (safe_create_leading_directories_const(path) < 0)
1424                         die(_("could not create directory '%s'"), path);
1425                 strbuf_addf(&sb, "%s/index", sm_gitdir);
1426                 unlink_or_warn(sb.buf);
1427                 strbuf_reset(&sb);
1428         }
1429
1430         connect_work_tree_and_git_dir(path, sm_gitdir, 0);
1431
1432         p = git_pathdup_submodule(path, "config");
1433         if (!p)
1434                 die(_("could not get submodule directory for '%s'"), path);
1435
1436         /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
1437         git_config_get_string("submodule.alternateLocation", &sm_alternate);
1438         if (sm_alternate)
1439                 git_config_set_in_file(p, "submodule.alternateLocation",
1440                                            sm_alternate);
1441         git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1442         if (error_strategy)
1443                 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
1444                                            error_strategy);
1445
1446         free(sm_alternate);
1447         free(error_strategy);
1448
1449         strbuf_release(&sb);
1450         free(sm_gitdir);
1451         free(path);
1452         free(p);
1453         return 0;
1454 }
1455
1456 struct submodule_update_clone {
1457         /* index into 'list', the list of submodules to look into for cloning */
1458         int current;
1459         struct module_list list;
1460         unsigned warn_if_uninitialized : 1;
1461
1462         /* update parameter passed via commandline */
1463         struct submodule_update_strategy update;
1464
1465         /* configuration parameters which are passed on to the children */
1466         int progress;
1467         int quiet;
1468         int recommend_shallow;
1469         struct string_list references;
1470         int dissociate;
1471         unsigned require_init;
1472         const char *depth;
1473         const char *recursive_prefix;
1474         const char *prefix;
1475
1476         /* Machine-readable status lines to be consumed by git-submodule.sh */
1477         struct string_list projectlines;
1478
1479         /* If we want to stop as fast as possible and return an error */
1480         unsigned quickstop : 1;
1481
1482         /* failed clones to be retried again */
1483         const struct cache_entry **failed_clones;
1484         int failed_clones_nr, failed_clones_alloc;
1485 };
1486 #define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
1487         SUBMODULE_UPDATE_STRATEGY_INIT, 0, 0, -1, STRING_LIST_INIT_DUP, 0, 0, \
1488         NULL, NULL, NULL, \
1489         STRING_LIST_INIT_DUP, 0, NULL, 0, 0}
1490
1491
1492 static void next_submodule_warn_missing(struct submodule_update_clone *suc,
1493                 struct strbuf *out, const char *displaypath)
1494 {
1495         /*
1496          * Only mention uninitialized submodules when their
1497          * paths have been specified.
1498          */
1499         if (suc->warn_if_uninitialized) {
1500                 strbuf_addf(out,
1501                         _("Submodule path '%s' not initialized"),
1502                         displaypath);
1503                 strbuf_addch(out, '\n');
1504                 strbuf_addstr(out,
1505                         _("Maybe you want to use 'update --init'?"));
1506                 strbuf_addch(out, '\n');
1507         }
1508 }
1509
1510 /**
1511  * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
1512  * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
1513  */
1514 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
1515                                            struct child_process *child,
1516                                            struct submodule_update_clone *suc,
1517                                            struct strbuf *out)
1518 {
1519         const struct submodule *sub = NULL;
1520         const char *url = NULL;
1521         const char *update_string;
1522         enum submodule_update_type update_type;
1523         char *key;
1524         struct strbuf displaypath_sb = STRBUF_INIT;
1525         struct strbuf sb = STRBUF_INIT;
1526         const char *displaypath = NULL;
1527         int needs_cloning = 0;
1528
1529         if (ce_stage(ce)) {
1530                 if (suc->recursive_prefix)
1531                         strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
1532                 else
1533                         strbuf_addstr(&sb, ce->name);
1534                 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
1535                 strbuf_addch(out, '\n');
1536                 goto cleanup;
1537         }
1538
1539         sub = submodule_from_path(the_repository, &null_oid, ce->name);
1540
1541         if (suc->recursive_prefix)
1542                 displaypath = relative_path(suc->recursive_prefix,
1543                                             ce->name, &displaypath_sb);
1544         else
1545                 displaypath = ce->name;
1546
1547         if (!sub) {
1548                 next_submodule_warn_missing(suc, out, displaypath);
1549                 goto cleanup;
1550         }
1551
1552         key = xstrfmt("submodule.%s.update", sub->name);
1553         if (!repo_config_get_string_const(the_repository, key, &update_string)) {
1554                 update_type = parse_submodule_update_type(update_string);
1555         } else {
1556                 update_type = sub->update_strategy.type;
1557         }
1558         free(key);
1559
1560         if (suc->update.type == SM_UPDATE_NONE
1561             || (suc->update.type == SM_UPDATE_UNSPECIFIED
1562                 && update_type == SM_UPDATE_NONE)) {
1563                 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
1564                 strbuf_addch(out, '\n');
1565                 goto cleanup;
1566         }
1567
1568         /* Check if the submodule has been initialized. */
1569         if (!is_submodule_active(the_repository, ce->name)) {
1570                 next_submodule_warn_missing(suc, out, displaypath);
1571                 goto cleanup;
1572         }
1573
1574         strbuf_reset(&sb);
1575         strbuf_addf(&sb, "submodule.%s.url", sub->name);
1576         if (repo_config_get_string_const(the_repository, sb.buf, &url))
1577                 url = sub->url;
1578
1579         strbuf_reset(&sb);
1580         strbuf_addf(&sb, "%s/.git", ce->name);
1581         needs_cloning = !file_exists(sb.buf);
1582
1583         strbuf_reset(&sb);
1584         strbuf_addf(&sb, "%06o %s %d %d\t%s\n", ce->ce_mode,
1585                         oid_to_hex(&ce->oid), ce_stage(ce),
1586                         needs_cloning, ce->name);
1587         string_list_append(&suc->projectlines, sb.buf);
1588
1589         if (!needs_cloning)
1590                 goto cleanup;
1591
1592         child->git_cmd = 1;
1593         child->no_stdin = 1;
1594         child->stdout_to_stderr = 1;
1595         child->err = -1;
1596         argv_array_push(&child->args, "submodule--helper");
1597         argv_array_push(&child->args, "clone");
1598         if (suc->progress)
1599                 argv_array_push(&child->args, "--progress");
1600         if (suc->quiet)
1601                 argv_array_push(&child->args, "--quiet");
1602         if (suc->prefix)
1603                 argv_array_pushl(&child->args, "--prefix", suc->prefix, NULL);
1604         if (suc->recommend_shallow && sub->recommend_shallow == 1)
1605                 argv_array_push(&child->args, "--depth=1");
1606         if (suc->require_init)
1607                 argv_array_push(&child->args, "--require-init");
1608         argv_array_pushl(&child->args, "--path", sub->path, NULL);
1609         argv_array_pushl(&child->args, "--name", sub->name, NULL);
1610         argv_array_pushl(&child->args, "--url", url, NULL);
1611         if (suc->references.nr) {
1612                 struct string_list_item *item;
1613                 for_each_string_list_item(item, &suc->references)
1614                         argv_array_pushl(&child->args, "--reference", item->string, NULL);
1615         }
1616         if (suc->dissociate)
1617                 argv_array_push(&child->args, "--dissociate");
1618         if (suc->depth)
1619                 argv_array_push(&child->args, suc->depth);
1620
1621 cleanup:
1622         strbuf_reset(&displaypath_sb);
1623         strbuf_reset(&sb);
1624
1625         return needs_cloning;
1626 }
1627
1628 static int update_clone_get_next_task(struct child_process *child,
1629                                       struct strbuf *err,
1630                                       void *suc_cb,
1631                                       void **idx_task_cb)
1632 {
1633         struct submodule_update_clone *suc = suc_cb;
1634         const struct cache_entry *ce;
1635         int index;
1636
1637         for (; suc->current < suc->list.nr; suc->current++) {
1638                 ce = suc->list.entries[suc->current];
1639                 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
1640                         int *p = xmalloc(sizeof(*p));
1641                         *p = suc->current;
1642                         *idx_task_cb = p;
1643                         suc->current++;
1644                         return 1;
1645                 }
1646         }
1647
1648         /*
1649          * The loop above tried cloning each submodule once, now try the
1650          * stragglers again, which we can imagine as an extension of the
1651          * entry list.
1652          */
1653         index = suc->current - suc->list.nr;
1654         if (index < suc->failed_clones_nr) {
1655                 int *p;
1656                 ce = suc->failed_clones[index];
1657                 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
1658                         suc->current ++;
1659                         strbuf_addstr(err, "BUG: submodule considered for "
1660                                            "cloning, doesn't need cloning "
1661                                            "any more?\n");
1662                         return 0;
1663                 }
1664                 p = xmalloc(sizeof(*p));
1665                 *p = suc->current;
1666                 *idx_task_cb = p;
1667                 suc->current ++;
1668                 return 1;
1669         }
1670
1671         return 0;
1672 }
1673
1674 static int update_clone_start_failure(struct strbuf *err,
1675                                       void *suc_cb,
1676                                       void *idx_task_cb)
1677 {
1678         struct submodule_update_clone *suc = suc_cb;
1679         suc->quickstop = 1;
1680         return 1;
1681 }
1682
1683 static int update_clone_task_finished(int result,
1684                                       struct strbuf *err,
1685                                       void *suc_cb,
1686                                       void *idx_task_cb)
1687 {
1688         const struct cache_entry *ce;
1689         struct submodule_update_clone *suc = suc_cb;
1690
1691         int *idxP = idx_task_cb;
1692         int idx = *idxP;
1693         free(idxP);
1694
1695         if (!result)
1696                 return 0;
1697
1698         if (idx < suc->list.nr) {
1699                 ce  = suc->list.entries[idx];
1700                 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
1701                             ce->name);
1702                 strbuf_addch(err, '\n');
1703                 ALLOC_GROW(suc->failed_clones,
1704                            suc->failed_clones_nr + 1,
1705                            suc->failed_clones_alloc);
1706                 suc->failed_clones[suc->failed_clones_nr++] = ce;
1707                 return 0;
1708         } else {
1709                 idx -= suc->list.nr;
1710                 ce  = suc->failed_clones[idx];
1711                 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
1712                             ce->name);
1713                 strbuf_addch(err, '\n');
1714                 suc->quickstop = 1;
1715                 return 1;
1716         }
1717
1718         return 0;
1719 }
1720
1721 static int git_update_clone_config(const char *var, const char *value,
1722                                    void *cb)
1723 {
1724         int *max_jobs = cb;
1725         if (!strcmp(var, "submodule.fetchjobs"))
1726                 *max_jobs = parse_submodule_fetchjobs(var, value);
1727         return 0;
1728 }
1729
1730 static int update_clone(int argc, const char **argv, const char *prefix)
1731 {
1732         const char *update = NULL;
1733         int max_jobs = 1;
1734         struct string_list_item *item;
1735         struct pathspec pathspec;
1736         struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
1737
1738         struct option module_update_clone_options[] = {
1739                 OPT_STRING(0, "prefix", &prefix,
1740                            N_("path"),
1741                            N_("path into the working tree")),
1742                 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
1743                            N_("path"),
1744                            N_("path into the working tree, across nested "
1745                               "submodule boundaries")),
1746                 OPT_STRING(0, "update", &update,
1747                            N_("string"),
1748                            N_("rebase, merge, checkout or none")),
1749                 OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
1750                            N_("reference repository")),
1751                 OPT_BOOL(0, "dissociate", &suc.dissociate,
1752                            N_("use --reference only while cloning")),
1753                 OPT_STRING(0, "depth", &suc.depth, "<depth>",
1754                            N_("Create a shallow clone truncated to the "
1755                               "specified number of revisions")),
1756                 OPT_INTEGER('j', "jobs", &max_jobs,
1757                             N_("parallel jobs")),
1758                 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
1759                             N_("whether the initial clone should follow the shallow recommendation")),
1760                 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
1761                 OPT_BOOL(0, "progress", &suc.progress,
1762                             N_("force cloning progress")),
1763                 OPT_BOOL(0, "require-init", &suc.require_init,
1764                            N_("disallow cloning into non-empty directory")),
1765                 OPT_END()
1766         };
1767
1768         const char *const git_submodule_helper_usage[] = {
1769                 N_("git submodule--helper update_clone [--prefix=<path>] [<path>...]"),
1770                 NULL
1771         };
1772         suc.prefix = prefix;
1773
1774         update_clone_config_from_gitmodules(&max_jobs);
1775         git_config(git_update_clone_config, &max_jobs);
1776
1777         argc = parse_options(argc, argv, prefix, module_update_clone_options,
1778                              git_submodule_helper_usage, 0);
1779
1780         if (update)
1781                 if (parse_submodule_update_strategy(update, &suc.update) < 0)
1782                         die(_("bad value for update parameter"));
1783
1784         if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
1785                 return 1;
1786
1787         if (pathspec.nr)
1788                 suc.warn_if_uninitialized = 1;
1789
1790         run_processes_parallel(max_jobs,
1791                                update_clone_get_next_task,
1792                                update_clone_start_failure,
1793                                update_clone_task_finished,
1794                                &suc);
1795
1796         /*
1797          * We saved the output and put it out all at once now.
1798          * That means:
1799          * - the listener does not have to interleave their (checkout)
1800          *   work with our fetching.  The writes involved in a
1801          *   checkout involve more straightforward sequential I/O.
1802          * - the listener can avoid doing any work if fetching failed.
1803          */
1804         if (suc.quickstop)
1805                 return 1;
1806
1807         for_each_string_list_item(item, &suc.projectlines)
1808                 fprintf(stdout, "%s", item->string);
1809
1810         return 0;
1811 }
1812
1813 static int resolve_relative_path(int argc, const char **argv, const char *prefix)
1814 {
1815         struct strbuf sb = STRBUF_INIT;
1816         if (argc != 3)
1817                 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
1818
1819         printf("%s", relative_path(argv[1], argv[2], &sb));
1820         strbuf_release(&sb);
1821         return 0;
1822 }
1823
1824 static const char *remote_submodule_branch(const char *path)
1825 {
1826         const struct submodule *sub;
1827         const char *branch = NULL;
1828         char *key;
1829
1830         sub = submodule_from_path(the_repository, &null_oid, path);
1831         if (!sub)
1832                 return NULL;
1833
1834         key = xstrfmt("submodule.%s.branch", sub->name);
1835         if (repo_config_get_string_const(the_repository, key, &branch))
1836                 branch = sub->branch;
1837         free(key);
1838
1839         if (!branch)
1840                 return "master";
1841
1842         if (!strcmp(branch, ".")) {
1843                 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1844
1845                 if (!refname)
1846                         die(_("No such ref: %s"), "HEAD");
1847
1848                 /* detached HEAD */
1849                 if (!strcmp(refname, "HEAD"))
1850                         die(_("Submodule (%s) branch configured to inherit "
1851                               "branch from superproject, but the superproject "
1852                               "is not on any branch"), sub->name);
1853
1854                 if (!skip_prefix(refname, "refs/heads/", &refname))
1855                         die(_("Expecting a full ref name, got %s"), refname);
1856                 return refname;
1857         }
1858
1859         return branch;
1860 }
1861
1862 static int resolve_remote_submodule_branch(int argc, const char **argv,
1863                 const char *prefix)
1864 {
1865         const char *ret;
1866         struct strbuf sb = STRBUF_INIT;
1867         if (argc != 2)
1868                 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
1869
1870         ret = remote_submodule_branch(argv[1]);
1871         if (!ret)
1872                 die("submodule %s doesn't exist", argv[1]);
1873
1874         printf("%s", ret);
1875         strbuf_release(&sb);
1876         return 0;
1877 }
1878
1879 static int push_check(int argc, const char **argv, const char *prefix)
1880 {
1881         struct remote *remote;
1882         const char *superproject_head;
1883         char *head;
1884         int detached_head = 0;
1885         struct object_id head_oid;
1886
1887         if (argc < 3)
1888                 die("submodule--helper push-check requires at least 2 arguments");
1889
1890         /*
1891          * superproject's resolved head ref.
1892          * if HEAD then the superproject is in a detached head state, otherwise
1893          * it will be the resolved head ref.
1894          */
1895         superproject_head = argv[1];
1896         argv++;
1897         argc--;
1898         /* Get the submodule's head ref and determine if it is detached */
1899         head = resolve_refdup("HEAD", 0, &head_oid, NULL);
1900         if (!head)
1901                 die(_("Failed to resolve HEAD as a valid ref."));
1902         if (!strcmp(head, "HEAD"))
1903                 detached_head = 1;
1904
1905         /*
1906          * The remote must be configured.
1907          * This is to avoid pushing to the exact same URL as the parent.
1908          */
1909         remote = pushremote_get(argv[1]);
1910         if (!remote || remote->origin == REMOTE_UNCONFIGURED)
1911                 die("remote '%s' not configured", argv[1]);
1912
1913         /* Check the refspec */
1914         if (argc > 2) {
1915                 int i;
1916                 struct ref *local_refs = get_local_heads();
1917                 struct refspec refspec = REFSPEC_INIT_PUSH;
1918
1919                 refspec_appendn(&refspec, argv + 2, argc - 2);
1920
1921                 for (i = 0; i < refspec.nr; i++) {
1922                         const struct refspec_item *rs = &refspec.items[i];
1923
1924                         if (rs->pattern || rs->matching)
1925                                 continue;
1926
1927                         /* LHS must match a single ref */
1928                         switch (count_refspec_match(rs->src, local_refs, NULL)) {
1929                         case 1:
1930                                 break;
1931                         case 0:
1932                                 /*
1933                                  * If LHS matches 'HEAD' then we need to ensure
1934                                  * that it matches the same named branch
1935                                  * checked out in the superproject.
1936                                  */
1937                                 if (!strcmp(rs->src, "HEAD")) {
1938                                         if (!detached_head &&
1939                                             !strcmp(head, superproject_head))
1940                                                 break;
1941                                         die("HEAD does not match the named branch in the superproject");
1942                                 }
1943                                 /* fallthrough */
1944                         default:
1945                                 die("src refspec '%s' must name a ref",
1946                                     rs->src);
1947                         }
1948                 }
1949                 refspec_clear(&refspec);
1950         }
1951         free(head);
1952
1953         return 0;
1954 }
1955
1956 static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
1957 {
1958         int i;
1959         struct pathspec pathspec;
1960         struct module_list list = MODULE_LIST_INIT;
1961         unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
1962
1963         struct option embed_gitdir_options[] = {
1964                 OPT_STRING(0, "prefix", &prefix,
1965                            N_("path"),
1966                            N_("path into the working tree")),
1967                 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
1968                         ABSORB_GITDIR_RECURSE_SUBMODULES),
1969                 OPT_END()
1970         };
1971
1972         const char *const git_submodule_helper_usage[] = {
1973                 N_("git submodule--helper embed-git-dir [<path>...]"),
1974                 NULL
1975         };
1976
1977         argc = parse_options(argc, argv, prefix, embed_gitdir_options,
1978                              git_submodule_helper_usage, 0);
1979
1980         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1981                 return 1;
1982
1983         for (i = 0; i < list.nr; i++)
1984                 absorb_git_dir_into_superproject(prefix,
1985                                 list.entries[i]->name, flags);
1986
1987         return 0;
1988 }
1989
1990 static int is_active(int argc, const char **argv, const char *prefix)
1991 {
1992         if (argc != 2)
1993                 die("submodule--helper is-active takes exactly 1 argument");
1994
1995         return !is_submodule_active(the_repository, argv[1]);
1996 }
1997
1998 /*
1999  * Exit non-zero if any of the submodule names given on the command line is
2000  * invalid. If no names are given, filter stdin to print only valid names
2001  * (which is primarily intended for testing).
2002  */
2003 static int check_name(int argc, const char **argv, const char *prefix)
2004 {
2005         if (argc > 1) {
2006                 while (*++argv) {
2007                         if (check_submodule_name(*argv) < 0)
2008                                 return 1;
2009                 }
2010         } else {
2011                 struct strbuf buf = STRBUF_INIT;
2012                 while (strbuf_getline(&buf, stdin) != EOF) {
2013                         if (!check_submodule_name(buf.buf))
2014                                 printf("%s\n", buf.buf);
2015                 }
2016                 strbuf_release(&buf);
2017         }
2018         return 0;
2019 }
2020
2021 #define SUPPORT_SUPER_PREFIX (1<<0)
2022
2023 struct cmd_struct {
2024         const char *cmd;
2025         int (*fn)(int, const char **, const char *);
2026         unsigned option;
2027 };
2028
2029 static struct cmd_struct commands[] = {
2030         {"list", module_list, 0},
2031         {"name", module_name, 0},
2032         {"clone", module_clone, 0},
2033         {"update-clone", update_clone, 0},
2034         {"relative-path", resolve_relative_path, 0},
2035         {"resolve-relative-url", resolve_relative_url, 0},
2036         {"resolve-relative-url-test", resolve_relative_url_test, 0},
2037         {"foreach", module_foreach, SUPPORT_SUPER_PREFIX},
2038         {"init", module_init, SUPPORT_SUPER_PREFIX},
2039         {"status", module_status, SUPPORT_SUPER_PREFIX},
2040         {"print-default-remote", print_default_remote, 0},
2041         {"sync", module_sync, SUPPORT_SUPER_PREFIX},
2042         {"deinit", module_deinit, 0},
2043         {"remote-branch", resolve_remote_submodule_branch, 0},
2044         {"push-check", push_check, 0},
2045         {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
2046         {"is-active", is_active, 0},
2047         {"check-name", check_name, 0},
2048 };
2049
2050 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
2051 {
2052         int i;
2053         if (argc < 2 || !strcmp(argv[1], "-h"))
2054                 usage("git submodule--helper <command>");
2055
2056         for (i = 0; i < ARRAY_SIZE(commands); i++) {
2057                 if (!strcmp(argv[1], commands[i].cmd)) {
2058                         if (get_super_prefix() &&
2059                             !(commands[i].option & SUPPORT_SUPER_PREFIX))
2060                                 die(_("%s doesn't support --super-prefix"),
2061                                     commands[i].cmd);
2062                         return commands[i].fn(argc - 1, argv + 1, prefix);
2063                 }
2064         }
2065
2066         die(_("'%s' is not a valid submodule--helper "
2067               "subcommand"), argv[1]);
2068 }