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