t7421: introduce a test script for verifying 'summary' output
[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 sync_cb {
931         const char *prefix;
932         unsigned int flags;
933 };
934 #define SYNC_CB_INIT { NULL, 0 }
935
936 static void sync_submodule(const char *path, const char *prefix,
937                            unsigned int flags)
938 {
939         const struct submodule *sub;
940         char *remote_key = NULL;
941         char *sub_origin_url, *super_config_url, *displaypath;
942         struct strbuf sb = STRBUF_INIT;
943         struct child_process cp = CHILD_PROCESS_INIT;
944         char *sub_config_path = NULL;
945
946         if (!is_submodule_active(the_repository, path))
947                 return;
948
949         sub = submodule_from_path(the_repository, &null_oid, path);
950
951         if (sub && sub->url) {
952                 if (starts_with_dot_dot_slash(sub->url) ||
953                     starts_with_dot_slash(sub->url)) {
954                         char *remote_url, *up_path;
955                         char *remote = get_default_remote();
956                         strbuf_addf(&sb, "remote.%s.url", remote);
957
958                         if (git_config_get_string(sb.buf, &remote_url))
959                                 remote_url = xgetcwd();
960
961                         up_path = get_up_path(path);
962                         sub_origin_url = relative_url(remote_url, sub->url, up_path);
963                         super_config_url = relative_url(remote_url, sub->url, NULL);
964
965                         free(remote);
966                         free(up_path);
967                         free(remote_url);
968                 } else {
969                         sub_origin_url = xstrdup(sub->url);
970                         super_config_url = xstrdup(sub->url);
971                 }
972         } else {
973                 sub_origin_url = xstrdup("");
974                 super_config_url = xstrdup("");
975         }
976
977         displaypath = get_submodule_displaypath(path, prefix);
978
979         if (!(flags & OPT_QUIET))
980                 printf(_("Synchronizing submodule url for '%s'\n"),
981                          displaypath);
982
983         strbuf_reset(&sb);
984         strbuf_addf(&sb, "submodule.%s.url", sub->name);
985         if (git_config_set_gently(sb.buf, super_config_url))
986                 die(_("failed to register url for submodule path '%s'"),
987                       displaypath);
988
989         if (!is_submodule_populated_gently(path, NULL))
990                 goto cleanup;
991
992         prepare_submodule_repo_env(&cp.env_array);
993         cp.git_cmd = 1;
994         cp.dir = path;
995         strvec_pushl(&cp.args, "submodule--helper",
996                      "print-default-remote", NULL);
997
998         strbuf_reset(&sb);
999         if (capture_command(&cp, &sb, 0))
1000                 die(_("failed to get the default remote for submodule '%s'"),
1001                       path);
1002
1003         strbuf_strip_suffix(&sb, "\n");
1004         remote_key = xstrfmt("remote.%s.url", sb.buf);
1005
1006         strbuf_reset(&sb);
1007         submodule_to_gitdir(&sb, path);
1008         strbuf_addstr(&sb, "/config");
1009
1010         if (git_config_set_in_file_gently(sb.buf, remote_key, sub_origin_url))
1011                 die(_("failed to update remote for submodule '%s'"),
1012                       path);
1013
1014         if (flags & OPT_RECURSIVE) {
1015                 struct child_process cpr = CHILD_PROCESS_INIT;
1016
1017                 cpr.git_cmd = 1;
1018                 cpr.dir = path;
1019                 prepare_submodule_repo_env(&cpr.env_array);
1020
1021                 strvec_push(&cpr.args, "--super-prefix");
1022                 strvec_pushf(&cpr.args, "%s/", displaypath);
1023                 strvec_pushl(&cpr.args, "submodule--helper", "sync",
1024                              "--recursive", NULL);
1025
1026                 if (flags & OPT_QUIET)
1027                         strvec_push(&cpr.args, "--quiet");
1028
1029                 if (run_command(&cpr))
1030                         die(_("failed to recurse into submodule '%s'"),
1031                               path);
1032         }
1033
1034 cleanup:
1035         free(super_config_url);
1036         free(sub_origin_url);
1037         strbuf_release(&sb);
1038         free(remote_key);
1039         free(displaypath);
1040         free(sub_config_path);
1041 }
1042
1043 static void sync_submodule_cb(const struct cache_entry *list_item, void *cb_data)
1044 {
1045         struct sync_cb *info = cb_data;
1046         sync_submodule(list_item->name, info->prefix, info->flags);
1047 }
1048
1049 static int module_sync(int argc, const char **argv, const char *prefix)
1050 {
1051         struct sync_cb info = SYNC_CB_INIT;
1052         struct pathspec pathspec;
1053         struct module_list list = MODULE_LIST_INIT;
1054         int quiet = 0;
1055         int recursive = 0;
1056
1057         struct option module_sync_options[] = {
1058                 OPT__QUIET(&quiet, N_("Suppress output of synchronizing submodule url")),
1059                 OPT_BOOL(0, "recursive", &recursive,
1060                         N_("Recurse into nested submodules")),
1061                 OPT_END()
1062         };
1063
1064         const char *const git_submodule_helper_usage[] = {
1065                 N_("git submodule--helper sync [--quiet] [--recursive] [<path>]"),
1066                 NULL
1067         };
1068
1069         argc = parse_options(argc, argv, prefix, module_sync_options,
1070                              git_submodule_helper_usage, 0);
1071
1072         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1073                 return 1;
1074
1075         info.prefix = prefix;
1076         if (quiet)
1077                 info.flags |= OPT_QUIET;
1078         if (recursive)
1079                 info.flags |= OPT_RECURSIVE;
1080
1081         for_each_listed_submodule(&list, sync_submodule_cb, &info);
1082
1083         return 0;
1084 }
1085
1086 struct deinit_cb {
1087         const char *prefix;
1088         unsigned int flags;
1089 };
1090 #define DEINIT_CB_INIT { NULL, 0 }
1091
1092 static void deinit_submodule(const char *path, const char *prefix,
1093                              unsigned int flags)
1094 {
1095         const struct submodule *sub;
1096         char *displaypath = NULL;
1097         struct child_process cp_config = CHILD_PROCESS_INIT;
1098         struct strbuf sb_config = STRBUF_INIT;
1099         char *sub_git_dir = xstrfmt("%s/.git", path);
1100
1101         sub = submodule_from_path(the_repository, &null_oid, path);
1102
1103         if (!sub || !sub->name)
1104                 goto cleanup;
1105
1106         displaypath = get_submodule_displaypath(path, prefix);
1107
1108         /* remove the submodule work tree (unless the user already did it) */
1109         if (is_directory(path)) {
1110                 struct strbuf sb_rm = STRBUF_INIT;
1111                 const char *format;
1112
1113                 /*
1114                  * protect submodules containing a .git directory
1115                  * NEEDSWORK: instead of dying, automatically call
1116                  * absorbgitdirs and (possibly) warn.
1117                  */
1118                 if (is_directory(sub_git_dir))
1119                         die(_("Submodule work tree '%s' contains a .git "
1120                               "directory (use 'rm -rf' if you really want "
1121                               "to remove it including all of its history)"),
1122                             displaypath);
1123
1124                 if (!(flags & OPT_FORCE)) {
1125                         struct child_process cp_rm = CHILD_PROCESS_INIT;
1126                         cp_rm.git_cmd = 1;
1127                         strvec_pushl(&cp_rm.args, "rm", "-qn",
1128                                      path, NULL);
1129
1130                         if (run_command(&cp_rm))
1131                                 die(_("Submodule work tree '%s' contains local "
1132                                       "modifications; use '-f' to discard them"),
1133                                       displaypath);
1134                 }
1135
1136                 strbuf_addstr(&sb_rm, path);
1137
1138                 if (!remove_dir_recursively(&sb_rm, 0))
1139                         format = _("Cleared directory '%s'\n");
1140                 else
1141                         format = _("Could not remove submodule work tree '%s'\n");
1142
1143                 if (!(flags & OPT_QUIET))
1144                         printf(format, displaypath);
1145
1146                 submodule_unset_core_worktree(sub);
1147
1148                 strbuf_release(&sb_rm);
1149         }
1150
1151         if (mkdir(path, 0777))
1152                 printf(_("could not create empty submodule directory %s"),
1153                       displaypath);
1154
1155         cp_config.git_cmd = 1;
1156         strvec_pushl(&cp_config.args, "config", "--get-regexp", NULL);
1157         strvec_pushf(&cp_config.args, "submodule.%s\\.", sub->name);
1158
1159         /* remove the .git/config entries (unless the user already did it) */
1160         if (!capture_command(&cp_config, &sb_config, 0) && sb_config.len) {
1161                 char *sub_key = xstrfmt("submodule.%s", sub->name);
1162                 /*
1163                  * remove the whole section so we have a clean state when
1164                  * the user later decides to init this submodule again
1165                  */
1166                 git_config_rename_section_in_file(NULL, sub_key, NULL);
1167                 if (!(flags & OPT_QUIET))
1168                         printf(_("Submodule '%s' (%s) unregistered for path '%s'\n"),
1169                                  sub->name, sub->url, displaypath);
1170                 free(sub_key);
1171         }
1172
1173 cleanup:
1174         free(displaypath);
1175         free(sub_git_dir);
1176         strbuf_release(&sb_config);
1177 }
1178
1179 static void deinit_submodule_cb(const struct cache_entry *list_item,
1180                                 void *cb_data)
1181 {
1182         struct deinit_cb *info = cb_data;
1183         deinit_submodule(list_item->name, info->prefix, info->flags);
1184 }
1185
1186 static int module_deinit(int argc, const char **argv, const char *prefix)
1187 {
1188         struct deinit_cb info = DEINIT_CB_INIT;
1189         struct pathspec pathspec;
1190         struct module_list list = MODULE_LIST_INIT;
1191         int quiet = 0;
1192         int force = 0;
1193         int all = 0;
1194
1195         struct option module_deinit_options[] = {
1196                 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
1197                 OPT__FORCE(&force, N_("Remove submodule working trees even if they contain local changes"), 0),
1198                 OPT_BOOL(0, "all", &all, N_("Unregister all submodules")),
1199                 OPT_END()
1200         };
1201
1202         const char *const git_submodule_helper_usage[] = {
1203                 N_("git submodule deinit [--quiet] [-f | --force] [--all | [--] [<path>...]]"),
1204                 NULL
1205         };
1206
1207         argc = parse_options(argc, argv, prefix, module_deinit_options,
1208                              git_submodule_helper_usage, 0);
1209
1210         if (all && argc) {
1211                 error("pathspec and --all are incompatible");
1212                 usage_with_options(git_submodule_helper_usage,
1213                                    module_deinit_options);
1214         }
1215
1216         if (!argc && !all)
1217                 die(_("Use '--all' if you really want to deinitialize all submodules"));
1218
1219         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1220                 return 1;
1221
1222         info.prefix = prefix;
1223         if (quiet)
1224                 info.flags |= OPT_QUIET;
1225         if (force)
1226                 info.flags |= OPT_FORCE;
1227
1228         for_each_listed_submodule(&list, deinit_submodule_cb, &info);
1229
1230         return 0;
1231 }
1232
1233 static int clone_submodule(const char *path, const char *gitdir, const char *url,
1234                            const char *depth, struct string_list *reference, int dissociate,
1235                            int quiet, int progress, int single_branch)
1236 {
1237         struct child_process cp = CHILD_PROCESS_INIT;
1238
1239         strvec_push(&cp.args, "clone");
1240         strvec_push(&cp.args, "--no-checkout");
1241         if (quiet)
1242                 strvec_push(&cp.args, "--quiet");
1243         if (progress)
1244                 strvec_push(&cp.args, "--progress");
1245         if (depth && *depth)
1246                 strvec_pushl(&cp.args, "--depth", depth, NULL);
1247         if (reference->nr) {
1248                 struct string_list_item *item;
1249                 for_each_string_list_item(item, reference)
1250                         strvec_pushl(&cp.args, "--reference",
1251                                      item->string, NULL);
1252         }
1253         if (dissociate)
1254                 strvec_push(&cp.args, "--dissociate");
1255         if (gitdir && *gitdir)
1256                 strvec_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
1257         if (single_branch >= 0)
1258                 strvec_push(&cp.args, single_branch ?
1259                                           "--single-branch" :
1260                                           "--no-single-branch");
1261
1262         strvec_push(&cp.args, "--");
1263         strvec_push(&cp.args, url);
1264         strvec_push(&cp.args, path);
1265
1266         cp.git_cmd = 1;
1267         prepare_submodule_repo_env(&cp.env_array);
1268         cp.no_stdin = 1;
1269
1270         return run_command(&cp);
1271 }
1272
1273 struct submodule_alternate_setup {
1274         const char *submodule_name;
1275         enum SUBMODULE_ALTERNATE_ERROR_MODE {
1276                 SUBMODULE_ALTERNATE_ERROR_DIE,
1277                 SUBMODULE_ALTERNATE_ERROR_INFO,
1278                 SUBMODULE_ALTERNATE_ERROR_IGNORE
1279         } error_mode;
1280         struct string_list *reference;
1281 };
1282 #define SUBMODULE_ALTERNATE_SETUP_INIT { NULL, \
1283         SUBMODULE_ALTERNATE_ERROR_IGNORE, NULL }
1284
1285 static const char alternate_error_advice[] = N_(
1286 "An alternate computed from a superproject's alternate is invalid.\n"
1287 "To allow Git to clone without an alternate in such a case, set\n"
1288 "submodule.alternateErrorStrategy to 'info' or, equivalently, clone with\n"
1289 "'--reference-if-able' instead of '--reference'."
1290 );
1291
1292 static int add_possible_reference_from_superproject(
1293                 struct object_directory *odb, void *sas_cb)
1294 {
1295         struct submodule_alternate_setup *sas = sas_cb;
1296         size_t len;
1297
1298         /*
1299          * If the alternate object store is another repository, try the
1300          * standard layout with .git/(modules/<name>)+/objects
1301          */
1302         if (strip_suffix(odb->path, "/objects", &len)) {
1303                 char *sm_alternate;
1304                 struct strbuf sb = STRBUF_INIT;
1305                 struct strbuf err = STRBUF_INIT;
1306                 strbuf_add(&sb, odb->path, len);
1307
1308                 /*
1309                  * We need to end the new path with '/' to mark it as a dir,
1310                  * otherwise a submodule name containing '/' will be broken
1311                  * as the last part of a missing submodule reference would
1312                  * be taken as a file name.
1313                  */
1314                 strbuf_addf(&sb, "/modules/%s/", sas->submodule_name);
1315
1316                 sm_alternate = compute_alternate_path(sb.buf, &err);
1317                 if (sm_alternate) {
1318                         string_list_append(sas->reference, xstrdup(sb.buf));
1319                         free(sm_alternate);
1320                 } else {
1321                         switch (sas->error_mode) {
1322                         case SUBMODULE_ALTERNATE_ERROR_DIE:
1323                                 if (advice_submodule_alternate_error_strategy_die)
1324                                         advise(_(alternate_error_advice));
1325                                 die(_("submodule '%s' cannot add alternate: %s"),
1326                                     sas->submodule_name, err.buf);
1327                         case SUBMODULE_ALTERNATE_ERROR_INFO:
1328                                 fprintf_ln(stderr, _("submodule '%s' cannot add alternate: %s"),
1329                                         sas->submodule_name, err.buf);
1330                         case SUBMODULE_ALTERNATE_ERROR_IGNORE:
1331                                 ; /* nothing */
1332                         }
1333                 }
1334                 strbuf_release(&sb);
1335         }
1336
1337         return 0;
1338 }
1339
1340 static void prepare_possible_alternates(const char *sm_name,
1341                 struct string_list *reference)
1342 {
1343         char *sm_alternate = NULL, *error_strategy = NULL;
1344         struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
1345
1346         git_config_get_string("submodule.alternateLocation", &sm_alternate);
1347         if (!sm_alternate)
1348                 return;
1349
1350         git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1351
1352         if (!error_strategy)
1353                 error_strategy = xstrdup("die");
1354
1355         sas.submodule_name = sm_name;
1356         sas.reference = reference;
1357         if (!strcmp(error_strategy, "die"))
1358                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
1359         else if (!strcmp(error_strategy, "info"))
1360                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
1361         else if (!strcmp(error_strategy, "ignore"))
1362                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
1363         else
1364                 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
1365
1366         if (!strcmp(sm_alternate, "superproject"))
1367                 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
1368         else if (!strcmp(sm_alternate, "no"))
1369                 ; /* do nothing */
1370         else
1371                 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
1372
1373         free(sm_alternate);
1374         free(error_strategy);
1375 }
1376
1377 static int module_clone(int argc, const char **argv, const char *prefix)
1378 {
1379         const char *name = NULL, *url = NULL, *depth = NULL;
1380         int quiet = 0;
1381         int progress = 0;
1382         char *p, *path = NULL, *sm_gitdir;
1383         struct strbuf sb = STRBUF_INIT;
1384         struct string_list reference = STRING_LIST_INIT_NODUP;
1385         int dissociate = 0, require_init = 0;
1386         char *sm_alternate = NULL, *error_strategy = NULL;
1387         int single_branch = -1;
1388
1389         struct option module_clone_options[] = {
1390                 OPT_STRING(0, "prefix", &prefix,
1391                            N_("path"),
1392                            N_("alternative anchor for relative paths")),
1393                 OPT_STRING(0, "path", &path,
1394                            N_("path"),
1395                            N_("where the new submodule will be cloned to")),
1396                 OPT_STRING(0, "name", &name,
1397                            N_("string"),
1398                            N_("name of the new submodule")),
1399                 OPT_STRING(0, "url", &url,
1400                            N_("string"),
1401                            N_("url where to clone the submodule from")),
1402                 OPT_STRING_LIST(0, "reference", &reference,
1403                            N_("repo"),
1404                            N_("reference repository")),
1405                 OPT_BOOL(0, "dissociate", &dissociate,
1406                            N_("use --reference only while cloning")),
1407                 OPT_STRING(0, "depth", &depth,
1408                            N_("string"),
1409                            N_("depth for shallow clones")),
1410                 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
1411                 OPT_BOOL(0, "progress", &progress,
1412                            N_("force cloning progress")),
1413                 OPT_BOOL(0, "require-init", &require_init,
1414                            N_("disallow cloning into non-empty directory")),
1415                 OPT_BOOL(0, "single-branch", &single_branch,
1416                          N_("clone only one branch, HEAD or --branch")),
1417                 OPT_END()
1418         };
1419
1420         const char *const git_submodule_helper_usage[] = {
1421                 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
1422                    "[--reference <repository>] [--name <name>] [--depth <depth>] "
1423                    "[--single-branch] "
1424                    "--url <url> --path <path>"),
1425                 NULL
1426         };
1427
1428         argc = parse_options(argc, argv, prefix, module_clone_options,
1429                              git_submodule_helper_usage, 0);
1430
1431         if (argc || !url || !path || !*path)
1432                 usage_with_options(git_submodule_helper_usage,
1433                                    module_clone_options);
1434
1435         strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
1436         sm_gitdir = absolute_pathdup(sb.buf);
1437         strbuf_reset(&sb);
1438
1439         if (!is_absolute_path(path)) {
1440                 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
1441                 path = strbuf_detach(&sb, NULL);
1442         } else
1443                 path = xstrdup(path);
1444
1445         if (validate_submodule_git_dir(sm_gitdir, name) < 0)
1446                 die(_("refusing to create/use '%s' in another submodule's "
1447                         "git dir"), sm_gitdir);
1448
1449         if (!file_exists(sm_gitdir)) {
1450                 if (safe_create_leading_directories_const(sm_gitdir) < 0)
1451                         die(_("could not create directory '%s'"), sm_gitdir);
1452
1453                 prepare_possible_alternates(name, &reference);
1454
1455                 if (clone_submodule(path, sm_gitdir, url, depth, &reference, dissociate,
1456                                     quiet, progress, single_branch))
1457                         die(_("clone of '%s' into submodule path '%s' failed"),
1458                             url, path);
1459         } else {
1460                 if (require_init && !access(path, X_OK) && !is_empty_dir(path))
1461                         die(_("directory not empty: '%s'"), path);
1462                 if (safe_create_leading_directories_const(path) < 0)
1463                         die(_("could not create directory '%s'"), path);
1464                 strbuf_addf(&sb, "%s/index", sm_gitdir);
1465                 unlink_or_warn(sb.buf);
1466                 strbuf_reset(&sb);
1467         }
1468
1469         connect_work_tree_and_git_dir(path, sm_gitdir, 0);
1470
1471         p = git_pathdup_submodule(path, "config");
1472         if (!p)
1473                 die(_("could not get submodule directory for '%s'"), path);
1474
1475         /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
1476         git_config_get_string("submodule.alternateLocation", &sm_alternate);
1477         if (sm_alternate)
1478                 git_config_set_in_file(p, "submodule.alternateLocation",
1479                                            sm_alternate);
1480         git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1481         if (error_strategy)
1482                 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
1483                                            error_strategy);
1484
1485         free(sm_alternate);
1486         free(error_strategy);
1487
1488         strbuf_release(&sb);
1489         free(sm_gitdir);
1490         free(path);
1491         free(p);
1492         return 0;
1493 }
1494
1495 static void determine_submodule_update_strategy(struct repository *r,
1496                                                 int just_cloned,
1497                                                 const char *path,
1498                                                 const char *update,
1499                                                 struct submodule_update_strategy *out)
1500 {
1501         const struct submodule *sub = submodule_from_path(r, &null_oid, path);
1502         char *key;
1503         const char *val;
1504
1505         key = xstrfmt("submodule.%s.update", sub->name);
1506
1507         if (update) {
1508                 if (parse_submodule_update_strategy(update, out) < 0)
1509                         die(_("Invalid update mode '%s' for submodule path '%s'"),
1510                                 update, path);
1511         } else if (!repo_config_get_string_const(r, key, &val)) {
1512                 if (parse_submodule_update_strategy(val, out) < 0)
1513                         die(_("Invalid update mode '%s' configured for submodule path '%s'"),
1514                                 val, path);
1515         } else if (sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
1516                 if (sub->update_strategy.type == SM_UPDATE_COMMAND)
1517                         BUG("how did we read update = !command from .gitmodules?");
1518                 out->type = sub->update_strategy.type;
1519                 out->command = sub->update_strategy.command;
1520         } else
1521                 out->type = SM_UPDATE_CHECKOUT;
1522
1523         if (just_cloned &&
1524             (out->type == SM_UPDATE_MERGE ||
1525              out->type == SM_UPDATE_REBASE ||
1526              out->type == SM_UPDATE_NONE))
1527                 out->type = SM_UPDATE_CHECKOUT;
1528
1529         free(key);
1530 }
1531
1532 static int module_update_module_mode(int argc, const char **argv, const char *prefix)
1533 {
1534         const char *path, *update = NULL;
1535         int just_cloned;
1536         struct submodule_update_strategy update_strategy = { .type = SM_UPDATE_CHECKOUT };
1537
1538         if (argc < 3 || argc > 4)
1539                 die("submodule--helper update-module-clone expects <just-cloned> <path> [<update>]");
1540
1541         just_cloned = git_config_int("just_cloned", argv[1]);
1542         path = argv[2];
1543
1544         if (argc == 4)
1545                 update = argv[3];
1546
1547         determine_submodule_update_strategy(the_repository,
1548                                             just_cloned, path, update,
1549                                             &update_strategy);
1550         fputs(submodule_strategy_to_string(&update_strategy), stdout);
1551
1552         return 0;
1553 }
1554
1555 struct update_clone_data {
1556         const struct submodule *sub;
1557         struct object_id oid;
1558         unsigned just_cloned;
1559 };
1560
1561 struct submodule_update_clone {
1562         /* index into 'list', the list of submodules to look into for cloning */
1563         int current;
1564         struct module_list list;
1565         unsigned warn_if_uninitialized : 1;
1566
1567         /* update parameter passed via commandline */
1568         struct submodule_update_strategy update;
1569
1570         /* configuration parameters which are passed on to the children */
1571         int progress;
1572         int quiet;
1573         int recommend_shallow;
1574         struct string_list references;
1575         int dissociate;
1576         unsigned require_init;
1577         const char *depth;
1578         const char *recursive_prefix;
1579         const char *prefix;
1580         int single_branch;
1581
1582         /* to be consumed by git-submodule.sh */
1583         struct update_clone_data *update_clone;
1584         int update_clone_nr; int update_clone_alloc;
1585
1586         /* If we want to stop as fast as possible and return an error */
1587         unsigned quickstop : 1;
1588
1589         /* failed clones to be retried again */
1590         const struct cache_entry **failed_clones;
1591         int failed_clones_nr, failed_clones_alloc;
1592
1593         int max_jobs;
1594 };
1595 #define SUBMODULE_UPDATE_CLONE_INIT { \
1596         .list = MODULE_LIST_INIT, \
1597         .update = SUBMODULE_UPDATE_STRATEGY_INIT, \
1598         .recommend_shallow = -1, \
1599         .references = STRING_LIST_INIT_DUP, \
1600         .single_branch = -1, \
1601         .max_jobs = 1, \
1602 }
1603
1604
1605 static void next_submodule_warn_missing(struct submodule_update_clone *suc,
1606                 struct strbuf *out, const char *displaypath)
1607 {
1608         /*
1609          * Only mention uninitialized submodules when their
1610          * paths have been specified.
1611          */
1612         if (suc->warn_if_uninitialized) {
1613                 strbuf_addf(out,
1614                         _("Submodule path '%s' not initialized"),
1615                         displaypath);
1616                 strbuf_addch(out, '\n');
1617                 strbuf_addstr(out,
1618                         _("Maybe you want to use 'update --init'?"));
1619                 strbuf_addch(out, '\n');
1620         }
1621 }
1622
1623 /**
1624  * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
1625  * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
1626  */
1627 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
1628                                            struct child_process *child,
1629                                            struct submodule_update_clone *suc,
1630                                            struct strbuf *out)
1631 {
1632         const struct submodule *sub = NULL;
1633         const char *url = NULL;
1634         const char *update_string;
1635         enum submodule_update_type update_type;
1636         char *key;
1637         struct strbuf displaypath_sb = STRBUF_INIT;
1638         struct strbuf sb = STRBUF_INIT;
1639         const char *displaypath = NULL;
1640         int needs_cloning = 0;
1641         int need_free_url = 0;
1642
1643         if (ce_stage(ce)) {
1644                 if (suc->recursive_prefix)
1645                         strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
1646                 else
1647                         strbuf_addstr(&sb, ce->name);
1648                 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
1649                 strbuf_addch(out, '\n');
1650                 goto cleanup;
1651         }
1652
1653         sub = submodule_from_path(the_repository, &null_oid, ce->name);
1654
1655         if (suc->recursive_prefix)
1656                 displaypath = relative_path(suc->recursive_prefix,
1657                                             ce->name, &displaypath_sb);
1658         else
1659                 displaypath = ce->name;
1660
1661         if (!sub) {
1662                 next_submodule_warn_missing(suc, out, displaypath);
1663                 goto cleanup;
1664         }
1665
1666         key = xstrfmt("submodule.%s.update", sub->name);
1667         if (!repo_config_get_string_const(the_repository, key, &update_string)) {
1668                 update_type = parse_submodule_update_type(update_string);
1669         } else {
1670                 update_type = sub->update_strategy.type;
1671         }
1672         free(key);
1673
1674         if (suc->update.type == SM_UPDATE_NONE
1675             || (suc->update.type == SM_UPDATE_UNSPECIFIED
1676                 && update_type == SM_UPDATE_NONE)) {
1677                 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
1678                 strbuf_addch(out, '\n');
1679                 goto cleanup;
1680         }
1681
1682         /* Check if the submodule has been initialized. */
1683         if (!is_submodule_active(the_repository, ce->name)) {
1684                 next_submodule_warn_missing(suc, out, displaypath);
1685                 goto cleanup;
1686         }
1687
1688         strbuf_reset(&sb);
1689         strbuf_addf(&sb, "submodule.%s.url", sub->name);
1690         if (repo_config_get_string_const(the_repository, sb.buf, &url)) {
1691                 if (starts_with_dot_slash(sub->url) ||
1692                     starts_with_dot_dot_slash(sub->url)) {
1693                         url = compute_submodule_clone_url(sub->url);
1694                         need_free_url = 1;
1695                 } else
1696                         url = sub->url;
1697         }
1698
1699         strbuf_reset(&sb);
1700         strbuf_addf(&sb, "%s/.git", ce->name);
1701         needs_cloning = !file_exists(sb.buf);
1702
1703         ALLOC_GROW(suc->update_clone, suc->update_clone_nr + 1,
1704                    suc->update_clone_alloc);
1705         oidcpy(&suc->update_clone[suc->update_clone_nr].oid, &ce->oid);
1706         suc->update_clone[suc->update_clone_nr].just_cloned = needs_cloning;
1707         suc->update_clone[suc->update_clone_nr].sub = sub;
1708         suc->update_clone_nr++;
1709
1710         if (!needs_cloning)
1711                 goto cleanup;
1712
1713         child->git_cmd = 1;
1714         child->no_stdin = 1;
1715         child->stdout_to_stderr = 1;
1716         child->err = -1;
1717         strvec_push(&child->args, "submodule--helper");
1718         strvec_push(&child->args, "clone");
1719         if (suc->progress)
1720                 strvec_push(&child->args, "--progress");
1721         if (suc->quiet)
1722                 strvec_push(&child->args, "--quiet");
1723         if (suc->prefix)
1724                 strvec_pushl(&child->args, "--prefix", suc->prefix, NULL);
1725         if (suc->recommend_shallow && sub->recommend_shallow == 1)
1726                 strvec_push(&child->args, "--depth=1");
1727         if (suc->require_init)
1728                 strvec_push(&child->args, "--require-init");
1729         strvec_pushl(&child->args, "--path", sub->path, NULL);
1730         strvec_pushl(&child->args, "--name", sub->name, NULL);
1731         strvec_pushl(&child->args, "--url", url, NULL);
1732         if (suc->references.nr) {
1733                 struct string_list_item *item;
1734                 for_each_string_list_item(item, &suc->references)
1735                         strvec_pushl(&child->args, "--reference", item->string, NULL);
1736         }
1737         if (suc->dissociate)
1738                 strvec_push(&child->args, "--dissociate");
1739         if (suc->depth)
1740                 strvec_push(&child->args, suc->depth);
1741         if (suc->single_branch >= 0)
1742                 strvec_push(&child->args, suc->single_branch ?
1743                                               "--single-branch" :
1744                                               "--no-single-branch");
1745
1746 cleanup:
1747         strbuf_reset(&displaypath_sb);
1748         strbuf_reset(&sb);
1749         if (need_free_url)
1750                 free((void*)url);
1751
1752         return needs_cloning;
1753 }
1754
1755 static int update_clone_get_next_task(struct child_process *child,
1756                                       struct strbuf *err,
1757                                       void *suc_cb,
1758                                       void **idx_task_cb)
1759 {
1760         struct submodule_update_clone *suc = suc_cb;
1761         const struct cache_entry *ce;
1762         int index;
1763
1764         for (; suc->current < suc->list.nr; suc->current++) {
1765                 ce = suc->list.entries[suc->current];
1766                 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
1767                         int *p = xmalloc(sizeof(*p));
1768                         *p = suc->current;
1769                         *idx_task_cb = p;
1770                         suc->current++;
1771                         return 1;
1772                 }
1773         }
1774
1775         /*
1776          * The loop above tried cloning each submodule once, now try the
1777          * stragglers again, which we can imagine as an extension of the
1778          * entry list.
1779          */
1780         index = suc->current - suc->list.nr;
1781         if (index < suc->failed_clones_nr) {
1782                 int *p;
1783                 ce = suc->failed_clones[index];
1784                 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
1785                         suc->current ++;
1786                         strbuf_addstr(err, "BUG: submodule considered for "
1787                                            "cloning, doesn't need cloning "
1788                                            "any more?\n");
1789                         return 0;
1790                 }
1791                 p = xmalloc(sizeof(*p));
1792                 *p = suc->current;
1793                 *idx_task_cb = p;
1794                 suc->current ++;
1795                 return 1;
1796         }
1797
1798         return 0;
1799 }
1800
1801 static int update_clone_start_failure(struct strbuf *err,
1802                                       void *suc_cb,
1803                                       void *idx_task_cb)
1804 {
1805         struct submodule_update_clone *suc = suc_cb;
1806         suc->quickstop = 1;
1807         return 1;
1808 }
1809
1810 static int update_clone_task_finished(int result,
1811                                       struct strbuf *err,
1812                                       void *suc_cb,
1813                                       void *idx_task_cb)
1814 {
1815         const struct cache_entry *ce;
1816         struct submodule_update_clone *suc = suc_cb;
1817
1818         int *idxP = idx_task_cb;
1819         int idx = *idxP;
1820         free(idxP);
1821
1822         if (!result)
1823                 return 0;
1824
1825         if (idx < suc->list.nr) {
1826                 ce  = suc->list.entries[idx];
1827                 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
1828                             ce->name);
1829                 strbuf_addch(err, '\n');
1830                 ALLOC_GROW(suc->failed_clones,
1831                            suc->failed_clones_nr + 1,
1832                            suc->failed_clones_alloc);
1833                 suc->failed_clones[suc->failed_clones_nr++] = ce;
1834                 return 0;
1835         } else {
1836                 idx -= suc->list.nr;
1837                 ce  = suc->failed_clones[idx];
1838                 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
1839                             ce->name);
1840                 strbuf_addch(err, '\n');
1841                 suc->quickstop = 1;
1842                 return 1;
1843         }
1844
1845         return 0;
1846 }
1847
1848 static int git_update_clone_config(const char *var, const char *value,
1849                                    void *cb)
1850 {
1851         int *max_jobs = cb;
1852         if (!strcmp(var, "submodule.fetchjobs"))
1853                 *max_jobs = parse_submodule_fetchjobs(var, value);
1854         return 0;
1855 }
1856
1857 static void update_submodule(struct update_clone_data *ucd)
1858 {
1859         fprintf(stdout, "dummy %s %d\t%s\n",
1860                 oid_to_hex(&ucd->oid),
1861                 ucd->just_cloned,
1862                 ucd->sub->path);
1863 }
1864
1865 static int update_submodules(struct submodule_update_clone *suc)
1866 {
1867         int i;
1868
1869         run_processes_parallel_tr2(suc->max_jobs, update_clone_get_next_task,
1870                                    update_clone_start_failure,
1871                                    update_clone_task_finished, suc, "submodule",
1872                                    "parallel/update");
1873
1874         /*
1875          * We saved the output and put it out all at once now.
1876          * That means:
1877          * - the listener does not have to interleave their (checkout)
1878          *   work with our fetching.  The writes involved in a
1879          *   checkout involve more straightforward sequential I/O.
1880          * - the listener can avoid doing any work if fetching failed.
1881          */
1882         if (suc->quickstop)
1883                 return 1;
1884
1885         for (i = 0; i < suc->update_clone_nr; i++)
1886                 update_submodule(&suc->update_clone[i]);
1887
1888         return 0;
1889 }
1890
1891 static int update_clone(int argc, const char **argv, const char *prefix)
1892 {
1893         const char *update = NULL;
1894         struct pathspec pathspec;
1895         struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
1896
1897         struct option module_update_clone_options[] = {
1898                 OPT_STRING(0, "prefix", &prefix,
1899                            N_("path"),
1900                            N_("path into the working tree")),
1901                 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
1902                            N_("path"),
1903                            N_("path into the working tree, across nested "
1904                               "submodule boundaries")),
1905                 OPT_STRING(0, "update", &update,
1906                            N_("string"),
1907                            N_("rebase, merge, checkout or none")),
1908                 OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
1909                            N_("reference repository")),
1910                 OPT_BOOL(0, "dissociate", &suc.dissociate,
1911                            N_("use --reference only while cloning")),
1912                 OPT_STRING(0, "depth", &suc.depth, "<depth>",
1913                            N_("Create a shallow clone truncated to the "
1914                               "specified number of revisions")),
1915                 OPT_INTEGER('j', "jobs", &suc.max_jobs,
1916                             N_("parallel jobs")),
1917                 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
1918                             N_("whether the initial clone should follow the shallow recommendation")),
1919                 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
1920                 OPT_BOOL(0, "progress", &suc.progress,
1921                             N_("force cloning progress")),
1922                 OPT_BOOL(0, "require-init", &suc.require_init,
1923                            N_("disallow cloning into non-empty directory")),
1924                 OPT_BOOL(0, "single-branch", &suc.single_branch,
1925                          N_("clone only one branch, HEAD or --branch")),
1926                 OPT_END()
1927         };
1928
1929         const char *const git_submodule_helper_usage[] = {
1930                 N_("git submodule--helper update-clone [--prefix=<path>] [<path>...]"),
1931                 NULL
1932         };
1933         suc.prefix = prefix;
1934
1935         update_clone_config_from_gitmodules(&suc.max_jobs);
1936         git_config(git_update_clone_config, &suc.max_jobs);
1937
1938         argc = parse_options(argc, argv, prefix, module_update_clone_options,
1939                              git_submodule_helper_usage, 0);
1940
1941         if (update)
1942                 if (parse_submodule_update_strategy(update, &suc.update) < 0)
1943                         die(_("bad value for update parameter"));
1944
1945         if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
1946                 return 1;
1947
1948         if (pathspec.nr)
1949                 suc.warn_if_uninitialized = 1;
1950
1951         return update_submodules(&suc);
1952 }
1953
1954 static int resolve_relative_path(int argc, const char **argv, const char *prefix)
1955 {
1956         struct strbuf sb = STRBUF_INIT;
1957         if (argc != 3)
1958                 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
1959
1960         printf("%s", relative_path(argv[1], argv[2], &sb));
1961         strbuf_release(&sb);
1962         return 0;
1963 }
1964
1965 static const char *remote_submodule_branch(const char *path)
1966 {
1967         const struct submodule *sub;
1968         const char *branch = NULL;
1969         char *key;
1970
1971         sub = submodule_from_path(the_repository, &null_oid, path);
1972         if (!sub)
1973                 return NULL;
1974
1975         key = xstrfmt("submodule.%s.branch", sub->name);
1976         if (repo_config_get_string_const(the_repository, key, &branch))
1977                 branch = sub->branch;
1978         free(key);
1979
1980         if (!branch)
1981                 return "HEAD";
1982
1983         if (!strcmp(branch, ".")) {
1984                 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1985
1986                 if (!refname)
1987                         die(_("No such ref: %s"), "HEAD");
1988
1989                 /* detached HEAD */
1990                 if (!strcmp(refname, "HEAD"))
1991                         die(_("Submodule (%s) branch configured to inherit "
1992                               "branch from superproject, but the superproject "
1993                               "is not on any branch"), sub->name);
1994
1995                 if (!skip_prefix(refname, "refs/heads/", &refname))
1996                         die(_("Expecting a full ref name, got %s"), refname);
1997                 return refname;
1998         }
1999
2000         return branch;
2001 }
2002
2003 static int resolve_remote_submodule_branch(int argc, const char **argv,
2004                 const char *prefix)
2005 {
2006         const char *ret;
2007         struct strbuf sb = STRBUF_INIT;
2008         if (argc != 2)
2009                 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
2010
2011         ret = remote_submodule_branch(argv[1]);
2012         if (!ret)
2013                 die("submodule %s doesn't exist", argv[1]);
2014
2015         printf("%s", ret);
2016         strbuf_release(&sb);
2017         return 0;
2018 }
2019
2020 static int push_check(int argc, const char **argv, const char *prefix)
2021 {
2022         struct remote *remote;
2023         const char *superproject_head;
2024         char *head;
2025         int detached_head = 0;
2026         struct object_id head_oid;
2027
2028         if (argc < 3)
2029                 die("submodule--helper push-check requires at least 2 arguments");
2030
2031         /*
2032          * superproject's resolved head ref.
2033          * if HEAD then the superproject is in a detached head state, otherwise
2034          * it will be the resolved head ref.
2035          */
2036         superproject_head = argv[1];
2037         argv++;
2038         argc--;
2039         /* Get the submodule's head ref and determine if it is detached */
2040         head = resolve_refdup("HEAD", 0, &head_oid, NULL);
2041         if (!head)
2042                 die(_("Failed to resolve HEAD as a valid ref."));
2043         if (!strcmp(head, "HEAD"))
2044                 detached_head = 1;
2045
2046         /*
2047          * The remote must be configured.
2048          * This is to avoid pushing to the exact same URL as the parent.
2049          */
2050         remote = pushremote_get(argv[1]);
2051         if (!remote || remote->origin == REMOTE_UNCONFIGURED)
2052                 die("remote '%s' not configured", argv[1]);
2053
2054         /* Check the refspec */
2055         if (argc > 2) {
2056                 int i;
2057                 struct ref *local_refs = get_local_heads();
2058                 struct refspec refspec = REFSPEC_INIT_PUSH;
2059
2060                 refspec_appendn(&refspec, argv + 2, argc - 2);
2061
2062                 for (i = 0; i < refspec.nr; i++) {
2063                         const struct refspec_item *rs = &refspec.items[i];
2064
2065                         if (rs->pattern || rs->matching)
2066                                 continue;
2067
2068                         /* LHS must match a single ref */
2069                         switch (count_refspec_match(rs->src, local_refs, NULL)) {
2070                         case 1:
2071                                 break;
2072                         case 0:
2073                                 /*
2074                                  * If LHS matches 'HEAD' then we need to ensure
2075                                  * that it matches the same named branch
2076                                  * checked out in the superproject.
2077                                  */
2078                                 if (!strcmp(rs->src, "HEAD")) {
2079                                         if (!detached_head &&
2080                                             !strcmp(head, superproject_head))
2081                                                 break;
2082                                         die("HEAD does not match the named branch in the superproject");
2083                                 }
2084                                 /* fallthrough */
2085                         default:
2086                                 die("src refspec '%s' must name a ref",
2087                                     rs->src);
2088                         }
2089                 }
2090                 refspec_clear(&refspec);
2091         }
2092         free(head);
2093
2094         return 0;
2095 }
2096
2097 static int ensure_core_worktree(int argc, const char **argv, const char *prefix)
2098 {
2099         const struct submodule *sub;
2100         const char *path;
2101         char *cw;
2102         struct repository subrepo;
2103
2104         if (argc != 2)
2105                 BUG("submodule--helper ensure-core-worktree <path>");
2106
2107         path = argv[1];
2108
2109         sub = submodule_from_path(the_repository, &null_oid, path);
2110         if (!sub)
2111                 BUG("We could get the submodule handle before?");
2112
2113         if (repo_submodule_init(&subrepo, the_repository, sub))
2114                 die(_("could not get a repository handle for submodule '%s'"), path);
2115
2116         if (!repo_config_get_string(&subrepo, "core.worktree", &cw)) {
2117                 char *cfg_file, *abs_path;
2118                 const char *rel_path;
2119                 struct strbuf sb = STRBUF_INIT;
2120
2121                 cfg_file = repo_git_path(&subrepo, "config");
2122
2123                 abs_path = absolute_pathdup(path);
2124                 rel_path = relative_path(abs_path, subrepo.gitdir, &sb);
2125
2126                 git_config_set_in_file(cfg_file, "core.worktree", rel_path);
2127
2128                 free(cfg_file);
2129                 free(abs_path);
2130                 strbuf_release(&sb);
2131         }
2132
2133         return 0;
2134 }
2135
2136 static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
2137 {
2138         int i;
2139         struct pathspec pathspec;
2140         struct module_list list = MODULE_LIST_INIT;
2141         unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
2142
2143         struct option embed_gitdir_options[] = {
2144                 OPT_STRING(0, "prefix", &prefix,
2145                            N_("path"),
2146                            N_("path into the working tree")),
2147                 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
2148                         ABSORB_GITDIR_RECURSE_SUBMODULES),
2149                 OPT_END()
2150         };
2151
2152         const char *const git_submodule_helper_usage[] = {
2153                 N_("git submodule--helper absorb-git-dirs [<options>] [<path>...]"),
2154                 NULL
2155         };
2156
2157         argc = parse_options(argc, argv, prefix, embed_gitdir_options,
2158                              git_submodule_helper_usage, 0);
2159
2160         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
2161                 return 1;
2162
2163         for (i = 0; i < list.nr; i++)
2164                 absorb_git_dir_into_superproject(list.entries[i]->name, flags);
2165
2166         return 0;
2167 }
2168
2169 static int is_active(int argc, const char **argv, const char *prefix)
2170 {
2171         if (argc != 2)
2172                 die("submodule--helper is-active takes exactly 1 argument");
2173
2174         return !is_submodule_active(the_repository, argv[1]);
2175 }
2176
2177 /*
2178  * Exit non-zero if any of the submodule names given on the command line is
2179  * invalid. If no names are given, filter stdin to print only valid names
2180  * (which is primarily intended for testing).
2181  */
2182 static int check_name(int argc, const char **argv, const char *prefix)
2183 {
2184         if (argc > 1) {
2185                 while (*++argv) {
2186                         if (check_submodule_name(*argv) < 0)
2187                                 return 1;
2188                 }
2189         } else {
2190                 struct strbuf buf = STRBUF_INIT;
2191                 while (strbuf_getline(&buf, stdin) != EOF) {
2192                         if (!check_submodule_name(buf.buf))
2193                                 printf("%s\n", buf.buf);
2194                 }
2195                 strbuf_release(&buf);
2196         }
2197         return 0;
2198 }
2199
2200 static int module_config(int argc, const char **argv, const char *prefix)
2201 {
2202         enum {
2203                 CHECK_WRITEABLE = 1,
2204                 DO_UNSET = 2
2205         } command = 0;
2206
2207         struct option module_config_options[] = {
2208                 OPT_CMDMODE(0, "check-writeable", &command,
2209                             N_("check if it is safe to write to the .gitmodules file"),
2210                             CHECK_WRITEABLE),
2211                 OPT_CMDMODE(0, "unset", &command,
2212                             N_("unset the config in the .gitmodules file"),
2213                             DO_UNSET),
2214                 OPT_END()
2215         };
2216         const char *const git_submodule_helper_usage[] = {
2217                 N_("git submodule--helper config <name> [<value>]"),
2218                 N_("git submodule--helper config --unset <name>"),
2219                 N_("git submodule--helper config --check-writeable"),
2220                 NULL
2221         };
2222
2223         argc = parse_options(argc, argv, prefix, module_config_options,
2224                              git_submodule_helper_usage, PARSE_OPT_KEEP_ARGV0);
2225
2226         if (argc == 1 && command == CHECK_WRITEABLE)
2227                 return is_writing_gitmodules_ok() ? 0 : -1;
2228
2229         /* Equivalent to ACTION_GET in builtin/config.c */
2230         if (argc == 2 && command != DO_UNSET)
2231                 return print_config_from_gitmodules(the_repository, argv[1]);
2232
2233         /* Equivalent to ACTION_SET in builtin/config.c */
2234         if (argc == 3 || (argc == 2 && command == DO_UNSET)) {
2235                 const char *value = (argc == 3) ? argv[2] : NULL;
2236
2237                 if (!is_writing_gitmodules_ok())
2238                         die(_("please make sure that the .gitmodules file is in the working tree"));
2239
2240                 return config_set_in_gitmodules_file_gently(argv[1], value);
2241         }
2242
2243         usage_with_options(git_submodule_helper_usage, module_config_options);
2244 }
2245
2246 static int module_set_url(int argc, const char **argv, const char *prefix)
2247 {
2248         int quiet = 0;
2249         const char *newurl;
2250         const char *path;
2251         char *config_name;
2252
2253         struct option options[] = {
2254                 OPT__QUIET(&quiet, N_("Suppress output for setting url of a submodule")),
2255                 OPT_END()
2256         };
2257         const char *const usage[] = {
2258                 N_("git submodule--helper set-url [--quiet] <path> <newurl>"),
2259                 NULL
2260         };
2261
2262         argc = parse_options(argc, argv, prefix, options, usage, 0);
2263
2264         if (argc != 2 || !(path = argv[0]) || !(newurl = argv[1]))
2265                 usage_with_options(usage, options);
2266
2267         config_name = xstrfmt("submodule.%s.url", path);
2268
2269         config_set_in_gitmodules_file_gently(config_name, newurl);
2270         sync_submodule(path, prefix, quiet ? OPT_QUIET : 0);
2271
2272         free(config_name);
2273
2274         return 0;
2275 }
2276
2277 static int module_set_branch(int argc, const char **argv, const char *prefix)
2278 {
2279         int opt_default = 0, ret;
2280         const char *opt_branch = NULL;
2281         const char *path;
2282         char *config_name;
2283
2284         /*
2285          * We accept the `quiet` option for uniformity across subcommands,
2286          * though there is nothing to make less verbose in this subcommand.
2287          */
2288         struct option options[] = {
2289                 OPT_NOOP_NOARG('q', "quiet"),
2290                 OPT_BOOL('d', "default", &opt_default,
2291                         N_("set the default tracking branch to master")),
2292                 OPT_STRING('b', "branch", &opt_branch, N_("branch"),
2293                         N_("set the default tracking branch")),
2294                 OPT_END()
2295         };
2296         const char *const usage[] = {
2297                 N_("git submodule--helper set-branch [-q|--quiet] (-d|--default) <path>"),
2298                 N_("git submodule--helper set-branch [-q|--quiet] (-b|--branch) <branch> <path>"),
2299                 NULL
2300         };
2301
2302         argc = parse_options(argc, argv, prefix, options, usage, 0);
2303
2304         if (!opt_branch && !opt_default)
2305                 die(_("--branch or --default required"));
2306
2307         if (opt_branch && opt_default)
2308                 die(_("--branch and --default are mutually exclusive"));
2309
2310         if (argc != 1 || !(path = argv[0]))
2311                 usage_with_options(usage, options);
2312
2313         config_name = xstrfmt("submodule.%s.branch", path);
2314         ret = config_set_in_gitmodules_file_gently(config_name, opt_branch);
2315
2316         free(config_name);
2317         return !!ret;
2318 }
2319
2320 #define SUPPORT_SUPER_PREFIX (1<<0)
2321
2322 struct cmd_struct {
2323         const char *cmd;
2324         int (*fn)(int, const char **, const char *);
2325         unsigned option;
2326 };
2327
2328 static struct cmd_struct commands[] = {
2329         {"list", module_list, 0},
2330         {"name", module_name, 0},
2331         {"clone", module_clone, 0},
2332         {"update-module-mode", module_update_module_mode, 0},
2333         {"update-clone", update_clone, 0},
2334         {"ensure-core-worktree", ensure_core_worktree, 0},
2335         {"relative-path", resolve_relative_path, 0},
2336         {"resolve-relative-url", resolve_relative_url, 0},
2337         {"resolve-relative-url-test", resolve_relative_url_test, 0},
2338         {"foreach", module_foreach, SUPPORT_SUPER_PREFIX},
2339         {"init", module_init, SUPPORT_SUPER_PREFIX},
2340         {"status", module_status, SUPPORT_SUPER_PREFIX},
2341         {"print-default-remote", print_default_remote, 0},
2342         {"sync", module_sync, SUPPORT_SUPER_PREFIX},
2343         {"deinit", module_deinit, 0},
2344         {"remote-branch", resolve_remote_submodule_branch, 0},
2345         {"push-check", push_check, 0},
2346         {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
2347         {"is-active", is_active, 0},
2348         {"check-name", check_name, 0},
2349         {"config", module_config, 0},
2350         {"set-url", module_set_url, 0},
2351         {"set-branch", module_set_branch, 0},
2352 };
2353
2354 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
2355 {
2356         int i;
2357         if (argc < 2 || !strcmp(argv[1], "-h"))
2358                 usage("git submodule--helper <command>");
2359
2360         for (i = 0; i < ARRAY_SIZE(commands); i++) {
2361                 if (!strcmp(argv[1], commands[i].cmd)) {
2362                         if (get_super_prefix() &&
2363                             !(commands[i].option & SUPPORT_SUPER_PREFIX))
2364                                 die(_("%s doesn't support --super-prefix"),
2365                                     commands[i].cmd);
2366                         return commands[i].fn(argc - 1, argv + 1, prefix);
2367                 }
2368         }
2369
2370         die(_("'%s' is not a valid submodule--helper "
2371               "subcommand"), argv[1]);
2372 }