Sync with 2.20.5
[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, prefix))
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_pushv(&cpr.args, info->argv);
545
546                 if (run_command(&cpr))
547                         die(_("run_command returned non-zero status while "
548                                 "recursing in the nested submodules of %s\n."),
549                                 displaypath);
550         }
551
552 cleanup:
553         free(displaypath);
554 }
555
556 static int module_foreach(int argc, const char **argv, const char *prefix)
557 {
558         struct cb_foreach info = CB_FOREACH_INIT;
559         struct pathspec pathspec;
560         struct module_list list = MODULE_LIST_INIT;
561
562         struct option module_foreach_options[] = {
563                 OPT__QUIET(&info.quiet, N_("Suppress output of entering each submodule command")),
564                 OPT_BOOL(0, "recursive", &info.recursive,
565                          N_("Recurse into nested submodules")),
566                 OPT_END()
567         };
568
569         const char *const git_submodule_helper_usage[] = {
570                 N_("git submodule--helper foreach [--quiet] [--recursive] <command>"),
571                 NULL
572         };
573
574         argc = parse_options(argc, argv, prefix, module_foreach_options,
575                              git_submodule_helper_usage, PARSE_OPT_KEEP_UNKNOWN);
576
577         if (module_list_compute(0, NULL, prefix, &pathspec, &list) < 0)
578                 return 1;
579
580         info.argc = argc;
581         info.argv = argv;
582         info.prefix = prefix;
583
584         for_each_listed_submodule(&list, runcommand_in_submodule_cb, &info);
585
586         return 0;
587 }
588
589 static char *compute_submodule_clone_url(const char *rel_url)
590 {
591         char *remoteurl, *relurl;
592         char *remote = get_default_remote();
593         struct strbuf remotesb = STRBUF_INIT;
594
595         strbuf_addf(&remotesb, "remote.%s.url", remote);
596         if (git_config_get_string(remotesb.buf, &remoteurl)) {
597                 warning(_("could not look up configuration '%s'. Assuming this repository is its own authoritative upstream."), remotesb.buf);
598                 remoteurl = xgetcwd();
599         }
600         relurl = relative_url(remoteurl, rel_url, NULL);
601
602         free(remote);
603         free(remoteurl);
604         strbuf_release(&remotesb);
605
606         return relurl;
607 }
608
609 struct init_cb {
610         const char *prefix;
611         unsigned int flags;
612 };
613
614 #define INIT_CB_INIT { NULL, 0 }
615
616 static void init_submodule(const char *path, const char *prefix,
617                            unsigned int flags)
618 {
619         const struct submodule *sub;
620         struct strbuf sb = STRBUF_INIT;
621         char *upd = NULL, *url = NULL, *displaypath;
622
623         displaypath = get_submodule_displaypath(path, prefix);
624
625         sub = submodule_from_path(the_repository, &null_oid, path);
626
627         if (!sub)
628                 die(_("No url found for submodule path '%s' in .gitmodules"),
629                         displaypath);
630
631         /*
632          * NEEDSWORK: In a multi-working-tree world, this needs to be
633          * set in the per-worktree config.
634          *
635          * Set active flag for the submodule being initialized
636          */
637         if (!is_submodule_active(the_repository, path)) {
638                 strbuf_addf(&sb, "submodule.%s.active", sub->name);
639                 git_config_set_gently(sb.buf, "true");
640                 strbuf_reset(&sb);
641         }
642
643         /*
644          * Copy url setting when it is not set yet.
645          * To look up the url in .git/config, we must not fall back to
646          * .gitmodules, so look it up directly.
647          */
648         strbuf_addf(&sb, "submodule.%s.url", sub->name);
649         if (git_config_get_string(sb.buf, &url)) {
650                 if (!sub->url)
651                         die(_("No url found for submodule path '%s' in .gitmodules"),
652                                 displaypath);
653
654                 url = xstrdup(sub->url);
655
656                 /* Possibly a url relative to parent */
657                 if (starts_with_dot_dot_slash(url) ||
658                     starts_with_dot_slash(url)) {
659                         char *oldurl = url;
660                         url = compute_submodule_clone_url(oldurl);
661                         free(oldurl);
662                 }
663
664                 if (git_config_set_gently(sb.buf, url))
665                         die(_("Failed to register url for submodule path '%s'"),
666                             displaypath);
667                 if (!(flags & OPT_QUIET))
668                         fprintf(stderr,
669                                 _("Submodule '%s' (%s) registered for path '%s'\n"),
670                                 sub->name, url, displaypath);
671         }
672         strbuf_reset(&sb);
673
674         /* Copy "update" setting when it is not set yet */
675         strbuf_addf(&sb, "submodule.%s.update", sub->name);
676         if (git_config_get_string(sb.buf, &upd) &&
677             sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
678                 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
679                         fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
680                                 sub->name);
681                         upd = xstrdup("none");
682                 } else
683                         upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
684
685                 if (git_config_set_gently(sb.buf, upd))
686                         die(_("Failed to register update mode for submodule path '%s'"), displaypath);
687         }
688         strbuf_release(&sb);
689         free(displaypath);
690         free(url);
691         free(upd);
692 }
693
694 static void init_submodule_cb(const struct cache_entry *list_item, void *cb_data)
695 {
696         struct init_cb *info = cb_data;
697         init_submodule(list_item->name, info->prefix, info->flags);
698 }
699
700 static int module_init(int argc, const char **argv, const char *prefix)
701 {
702         struct init_cb info = INIT_CB_INIT;
703         struct pathspec pathspec;
704         struct module_list list = MODULE_LIST_INIT;
705         int quiet = 0;
706
707         struct option module_init_options[] = {
708                 OPT__QUIET(&quiet, N_("Suppress output for initializing a submodule")),
709                 OPT_END()
710         };
711
712         const char *const git_submodule_helper_usage[] = {
713                 N_("git submodule--helper init [<path>]"),
714                 NULL
715         };
716
717         argc = parse_options(argc, argv, prefix, module_init_options,
718                              git_submodule_helper_usage, 0);
719
720         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
721                 return 1;
722
723         /*
724          * If there are no path args and submodule.active is set then,
725          * by default, only initialize 'active' modules.
726          */
727         if (!argc && git_config_get_value_multi("submodule.active"))
728                 module_list_active(&list);
729
730         info.prefix = prefix;
731         if (quiet)
732                 info.flags |= OPT_QUIET;
733
734         for_each_listed_submodule(&list, init_submodule_cb, &info);
735
736         return 0;
737 }
738
739 struct status_cb {
740         const char *prefix;
741         unsigned int flags;
742 };
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 argv_array diff_files_args = ARGV_ARRAY_INIT;
781         struct rev_info rev;
782         int diff_files_result;
783
784         if (!submodule_from_path(the_repository, &null_oid, path))
785                 die(_("no submodule mapping found in .gitmodules for path '%s'"),
786                       path);
787
788         displaypath = get_submodule_displaypath(path, prefix);
789
790         if ((CE_STAGEMASK & ce_flags) >> CE_STAGESHIFT) {
791                 print_status(flags, 'U', path, &null_oid, displaypath);
792                 goto cleanup;
793         }
794
795         if (!is_submodule_active(the_repository, path)) {
796                 print_status(flags, '-', path, ce_oid, displaypath);
797                 goto cleanup;
798         }
799
800         argv_array_pushl(&diff_files_args, "diff-files",
801                          "--ignore-submodules=dirty", "--quiet", "--",
802                          path, NULL);
803
804         git_config(git_diff_basic_config, NULL);
805         repo_init_revisions(the_repository, &rev, prefix);
806         rev.abbrev = 0;
807         diff_files_args.argc = setup_revisions(diff_files_args.argc,
808                                                diff_files_args.argv,
809                                                &rev, NULL);
810         diff_files_result = run_diff_files(&rev, 0);
811
812         if (!diff_result_code(&rev.diffopt, diff_files_result)) {
813                 print_status(flags, ' ', path, ce_oid,
814                              displaypath);
815         } else if (!(flags & OPT_CACHED)) {
816                 struct object_id oid;
817                 struct ref_store *refs = get_submodule_ref_store(path);
818
819                 if (!refs) {
820                         print_status(flags, '-', path, ce_oid, displaypath);
821                         goto cleanup;
822                 }
823                 if (refs_head_ref(refs, handle_submodule_head_ref, &oid))
824                         die(_("could not resolve HEAD ref inside the "
825                               "submodule '%s'"), path);
826
827                 print_status(flags, '+', path, &oid, displaypath);
828         } else {
829                 print_status(flags, '+', path, ce_oid, displaypath);
830         }
831
832         if (flags & OPT_RECURSIVE) {
833                 struct child_process cpr = CHILD_PROCESS_INIT;
834
835                 cpr.git_cmd = 1;
836                 cpr.dir = path;
837                 prepare_submodule_repo_env(&cpr.env_array);
838
839                 argv_array_push(&cpr.args, "--super-prefix");
840                 argv_array_pushf(&cpr.args, "%s/", displaypath);
841                 argv_array_pushl(&cpr.args, "submodule--helper", "status",
842                                  "--recursive", NULL);
843
844                 if (flags & OPT_CACHED)
845                         argv_array_push(&cpr.args, "--cached");
846
847                 if (flags & OPT_QUIET)
848                         argv_array_push(&cpr.args, "--quiet");
849
850                 if (run_command(&cpr))
851                         die(_("failed to recurse into submodule '%s'"), path);
852         }
853
854 cleanup:
855         argv_array_clear(&diff_files_args);
856         free(displaypath);
857 }
858
859 static void status_submodule_cb(const struct cache_entry *list_item,
860                                 void *cb_data)
861 {
862         struct status_cb *info = cb_data;
863         status_submodule(list_item->name, &list_item->oid, list_item->ce_flags,
864                          info->prefix, info->flags);
865 }
866
867 static int module_status(int argc, const char **argv, const char *prefix)
868 {
869         struct status_cb info = STATUS_CB_INIT;
870         struct pathspec pathspec;
871         struct module_list list = MODULE_LIST_INIT;
872         int quiet = 0;
873
874         struct option module_status_options[] = {
875                 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
876                 OPT_BIT(0, "cached", &info.flags, N_("Use commit stored in the index instead of the one stored in the submodule HEAD"), OPT_CACHED),
877                 OPT_BIT(0, "recursive", &info.flags, N_("recurse into nested submodules"), OPT_RECURSIVE),
878                 OPT_END()
879         };
880
881         const char *const git_submodule_helper_usage[] = {
882                 N_("git submodule status [--quiet] [--cached] [--recursive] [<path>...]"),
883                 NULL
884         };
885
886         argc = parse_options(argc, argv, prefix, module_status_options,
887                              git_submodule_helper_usage, 0);
888
889         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
890                 return 1;
891
892         info.prefix = prefix;
893         if (quiet)
894                 info.flags |= OPT_QUIET;
895
896         for_each_listed_submodule(&list, status_submodule_cb, &info);
897
898         return 0;
899 }
900
901 static int module_name(int argc, const char **argv, const char *prefix)
902 {
903         const struct submodule *sub;
904
905         if (argc != 2)
906                 usage(_("git submodule--helper name <path>"));
907
908         sub = submodule_from_path(the_repository, &null_oid, argv[1]);
909
910         if (!sub)
911                 die(_("no submodule mapping found in .gitmodules for path '%s'"),
912                     argv[1]);
913
914         printf("%s\n", sub->name);
915
916         return 0;
917 }
918
919 struct sync_cb {
920         const char *prefix;
921         unsigned int flags;
922 };
923
924 #define SYNC_CB_INIT { NULL, 0 }
925
926 static void sync_submodule(const char *path, const char *prefix,
927                            unsigned int flags)
928 {
929         const struct submodule *sub;
930         char *remote_key = NULL;
931         char *sub_origin_url, *super_config_url, *displaypath;
932         struct strbuf sb = STRBUF_INIT;
933         struct child_process cp = CHILD_PROCESS_INIT;
934         char *sub_config_path = NULL;
935
936         if (!is_submodule_active(the_repository, path))
937                 return;
938
939         sub = submodule_from_path(the_repository, &null_oid, path);
940
941         if (sub && sub->url) {
942                 if (starts_with_dot_dot_slash(sub->url) ||
943                     starts_with_dot_slash(sub->url)) {
944                         char *remote_url, *up_path;
945                         char *remote = get_default_remote();
946                         strbuf_addf(&sb, "remote.%s.url", remote);
947
948                         if (git_config_get_string(sb.buf, &remote_url))
949                                 remote_url = xgetcwd();
950
951                         up_path = get_up_path(path);
952                         sub_origin_url = relative_url(remote_url, sub->url, up_path);
953                         super_config_url = relative_url(remote_url, sub->url, NULL);
954
955                         free(remote);
956                         free(up_path);
957                         free(remote_url);
958                 } else {
959                         sub_origin_url = xstrdup(sub->url);
960                         super_config_url = xstrdup(sub->url);
961                 }
962         } else {
963                 sub_origin_url = xstrdup("");
964                 super_config_url = xstrdup("");
965         }
966
967         displaypath = get_submodule_displaypath(path, prefix);
968
969         if (!(flags & OPT_QUIET))
970                 printf(_("Synchronizing submodule url for '%s'\n"),
971                          displaypath);
972
973         strbuf_reset(&sb);
974         strbuf_addf(&sb, "submodule.%s.url", sub->name);
975         if (git_config_set_gently(sb.buf, super_config_url))
976                 die(_("failed to register url for submodule path '%s'"),
977                       displaypath);
978
979         if (!is_submodule_populated_gently(path, NULL))
980                 goto cleanup;
981
982         prepare_submodule_repo_env(&cp.env_array);
983         cp.git_cmd = 1;
984         cp.dir = path;
985         argv_array_pushl(&cp.args, "submodule--helper",
986                          "print-default-remote", NULL);
987
988         strbuf_reset(&sb);
989         if (capture_command(&cp, &sb, 0))
990                 die(_("failed to get the default remote for submodule '%s'"),
991                       path);
992
993         strbuf_strip_suffix(&sb, "\n");
994         remote_key = xstrfmt("remote.%s.url", sb.buf);
995
996         strbuf_reset(&sb);
997         submodule_to_gitdir(&sb, path);
998         strbuf_addstr(&sb, "/config");
999
1000         if (git_config_set_in_file_gently(sb.buf, remote_key, sub_origin_url))
1001                 die(_("failed to update remote for submodule '%s'"),
1002                       path);
1003
1004         if (flags & OPT_RECURSIVE) {
1005                 struct child_process cpr = CHILD_PROCESS_INIT;
1006
1007                 cpr.git_cmd = 1;
1008                 cpr.dir = path;
1009                 prepare_submodule_repo_env(&cpr.env_array);
1010
1011                 argv_array_push(&cpr.args, "--super-prefix");
1012                 argv_array_pushf(&cpr.args, "%s/", displaypath);
1013                 argv_array_pushl(&cpr.args, "submodule--helper", "sync",
1014                                  "--recursive", NULL);
1015
1016                 if (flags & OPT_QUIET)
1017                         argv_array_push(&cpr.args, "--quiet");
1018
1019                 if (run_command(&cpr))
1020                         die(_("failed to recurse into submodule '%s'"),
1021                               path);
1022         }
1023
1024 cleanup:
1025         free(super_config_url);
1026         free(sub_origin_url);
1027         strbuf_release(&sb);
1028         free(remote_key);
1029         free(displaypath);
1030         free(sub_config_path);
1031 }
1032
1033 static void sync_submodule_cb(const struct cache_entry *list_item, void *cb_data)
1034 {
1035         struct sync_cb *info = cb_data;
1036         sync_submodule(list_item->name, info->prefix, info->flags);
1037 }
1038
1039 static int module_sync(int argc, const char **argv, const char *prefix)
1040 {
1041         struct sync_cb info = SYNC_CB_INIT;
1042         struct pathspec pathspec;
1043         struct module_list list = MODULE_LIST_INIT;
1044         int quiet = 0;
1045         int recursive = 0;
1046
1047         struct option module_sync_options[] = {
1048                 OPT__QUIET(&quiet, N_("Suppress output of synchronizing submodule url")),
1049                 OPT_BOOL(0, "recursive", &recursive,
1050                         N_("Recurse into nested submodules")),
1051                 OPT_END()
1052         };
1053
1054         const char *const git_submodule_helper_usage[] = {
1055                 N_("git submodule--helper sync [--quiet] [--recursive] [<path>]"),
1056                 NULL
1057         };
1058
1059         argc = parse_options(argc, argv, prefix, module_sync_options,
1060                              git_submodule_helper_usage, 0);
1061
1062         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1063                 return 1;
1064
1065         info.prefix = prefix;
1066         if (quiet)
1067                 info.flags |= OPT_QUIET;
1068         if (recursive)
1069                 info.flags |= OPT_RECURSIVE;
1070
1071         for_each_listed_submodule(&list, sync_submodule_cb, &info);
1072
1073         return 0;
1074 }
1075
1076 struct deinit_cb {
1077         const char *prefix;
1078         unsigned int flags;
1079 };
1080 #define DEINIT_CB_INIT { NULL, 0 }
1081
1082 static void deinit_submodule(const char *path, const char *prefix,
1083                              unsigned int flags)
1084 {
1085         const struct submodule *sub;
1086         char *displaypath = NULL;
1087         struct child_process cp_config = CHILD_PROCESS_INIT;
1088         struct strbuf sb_config = STRBUF_INIT;
1089         char *sub_git_dir = xstrfmt("%s/.git", path);
1090
1091         sub = submodule_from_path(the_repository, &null_oid, path);
1092
1093         if (!sub || !sub->name)
1094                 goto cleanup;
1095
1096         displaypath = get_submodule_displaypath(path, prefix);
1097
1098         /* remove the submodule work tree (unless the user already did it) */
1099         if (is_directory(path)) {
1100                 struct strbuf sb_rm = STRBUF_INIT;
1101                 const char *format;
1102
1103                 /*
1104                  * protect submodules containing a .git directory
1105                  * NEEDSWORK: instead of dying, automatically call
1106                  * absorbgitdirs and (possibly) warn.
1107                  */
1108                 if (is_directory(sub_git_dir))
1109                         die(_("Submodule work tree '%s' contains a .git "
1110                               "directory (use 'rm -rf' if you really want "
1111                               "to remove it including all of its history)"),
1112                             displaypath);
1113
1114                 if (!(flags & OPT_FORCE)) {
1115                         struct child_process cp_rm = CHILD_PROCESS_INIT;
1116                         cp_rm.git_cmd = 1;
1117                         argv_array_pushl(&cp_rm.args, "rm", "-qn",
1118                                          path, NULL);
1119
1120                         if (run_command(&cp_rm))
1121                                 die(_("Submodule work tree '%s' contains local "
1122                                       "modifications; use '-f' to discard them"),
1123                                       displaypath);
1124                 }
1125
1126                 strbuf_addstr(&sb_rm, path);
1127
1128                 if (!remove_dir_recursively(&sb_rm, 0))
1129                         format = _("Cleared directory '%s'\n");
1130                 else
1131                         format = _("Could not remove submodule work tree '%s'\n");
1132
1133                 if (!(flags & OPT_QUIET))
1134                         printf(format, displaypath);
1135
1136                 submodule_unset_core_worktree(sub);
1137
1138                 strbuf_release(&sb_rm);
1139         }
1140
1141         if (mkdir(path, 0777))
1142                 printf(_("could not create empty submodule directory %s"),
1143                       displaypath);
1144
1145         cp_config.git_cmd = 1;
1146         argv_array_pushl(&cp_config.args, "config", "--get-regexp", NULL);
1147         argv_array_pushf(&cp_config.args, "submodule.%s\\.", sub->name);
1148
1149         /* remove the .git/config entries (unless the user already did it) */
1150         if (!capture_command(&cp_config, &sb_config, 0) && sb_config.len) {
1151                 char *sub_key = xstrfmt("submodule.%s", sub->name);
1152                 /*
1153                  * remove the whole section so we have a clean state when
1154                  * the user later decides to init this submodule again
1155                  */
1156                 git_config_rename_section_in_file(NULL, sub_key, NULL);
1157                 if (!(flags & OPT_QUIET))
1158                         printf(_("Submodule '%s' (%s) unregistered for path '%s'\n"),
1159                                  sub->name, sub->url, displaypath);
1160                 free(sub_key);
1161         }
1162
1163 cleanup:
1164         free(displaypath);
1165         free(sub_git_dir);
1166         strbuf_release(&sb_config);
1167 }
1168
1169 static void deinit_submodule_cb(const struct cache_entry *list_item,
1170                                 void *cb_data)
1171 {
1172         struct deinit_cb *info = cb_data;
1173         deinit_submodule(list_item->name, info->prefix, info->flags);
1174 }
1175
1176 static int module_deinit(int argc, const char **argv, const char *prefix)
1177 {
1178         struct deinit_cb info = DEINIT_CB_INIT;
1179         struct pathspec pathspec;
1180         struct module_list list = MODULE_LIST_INIT;
1181         int quiet = 0;
1182         int force = 0;
1183         int all = 0;
1184
1185         struct option module_deinit_options[] = {
1186                 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
1187                 OPT__FORCE(&force, N_("Remove submodule working trees even if they contain local changes"), 0),
1188                 OPT_BOOL(0, "all", &all, N_("Unregister all submodules")),
1189                 OPT_END()
1190         };
1191
1192         const char *const git_submodule_helper_usage[] = {
1193                 N_("git submodule deinit [--quiet] [-f | --force] [--all | [--] [<path>...]]"),
1194                 NULL
1195         };
1196
1197         argc = parse_options(argc, argv, prefix, module_deinit_options,
1198                              git_submodule_helper_usage, 0);
1199
1200         if (all && argc) {
1201                 error("pathspec and --all are incompatible");
1202                 usage_with_options(git_submodule_helper_usage,
1203                                    module_deinit_options);
1204         }
1205
1206         if (!argc && !all)
1207                 die(_("Use '--all' if you really want to deinitialize all submodules"));
1208
1209         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1210                 return 1;
1211
1212         info.prefix = prefix;
1213         if (quiet)
1214                 info.flags |= OPT_QUIET;
1215         if (force)
1216                 info.flags |= OPT_FORCE;
1217
1218         for_each_listed_submodule(&list, deinit_submodule_cb, &info);
1219
1220         return 0;
1221 }
1222
1223 static int clone_submodule(const char *path, const char *gitdir, const char *url,
1224                            const char *depth, struct string_list *reference, int dissociate,
1225                            int quiet, int progress)
1226 {
1227         struct child_process cp = CHILD_PROCESS_INIT;
1228
1229         argv_array_push(&cp.args, "clone");
1230         argv_array_push(&cp.args, "--no-checkout");
1231         if (quiet)
1232                 argv_array_push(&cp.args, "--quiet");
1233         if (progress)
1234                 argv_array_push(&cp.args, "--progress");
1235         if (depth && *depth)
1236                 argv_array_pushl(&cp.args, "--depth", depth, NULL);
1237         if (reference->nr) {
1238                 struct string_list_item *item;
1239                 for_each_string_list_item(item, reference)
1240                         argv_array_pushl(&cp.args, "--reference",
1241                                          item->string, NULL);
1242         }
1243         if (dissociate)
1244                 argv_array_push(&cp.args, "--dissociate");
1245         if (gitdir && *gitdir)
1246                 argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
1247
1248         argv_array_push(&cp.args, "--");
1249         argv_array_push(&cp.args, url);
1250         argv_array_push(&cp.args, path);
1251
1252         cp.git_cmd = 1;
1253         prepare_submodule_repo_env(&cp.env_array);
1254         cp.no_stdin = 1;
1255
1256         return run_command(&cp);
1257 }
1258
1259 struct submodule_alternate_setup {
1260         const char *submodule_name;
1261         enum SUBMODULE_ALTERNATE_ERROR_MODE {
1262                 SUBMODULE_ALTERNATE_ERROR_DIE,
1263                 SUBMODULE_ALTERNATE_ERROR_INFO,
1264                 SUBMODULE_ALTERNATE_ERROR_IGNORE
1265         } error_mode;
1266         struct string_list *reference;
1267 };
1268 #define SUBMODULE_ALTERNATE_SETUP_INIT { NULL, \
1269         SUBMODULE_ALTERNATE_ERROR_IGNORE, NULL }
1270
1271 static int add_possible_reference_from_superproject(
1272                 struct object_directory *odb, void *sas_cb)
1273 {
1274         struct submodule_alternate_setup *sas = sas_cb;
1275         size_t len;
1276
1277         /*
1278          * If the alternate object store is another repository, try the
1279          * standard layout with .git/(modules/<name>)+/objects
1280          */
1281         if (strip_suffix(odb->path, "/objects", &len)) {
1282                 char *sm_alternate;
1283                 struct strbuf sb = STRBUF_INIT;
1284                 struct strbuf err = STRBUF_INIT;
1285                 strbuf_add(&sb, odb->path, len);
1286
1287                 /*
1288                  * We need to end the new path with '/' to mark it as a dir,
1289                  * otherwise a submodule name containing '/' will be broken
1290                  * as the last part of a missing submodule reference would
1291                  * be taken as a file name.
1292                  */
1293                 strbuf_addf(&sb, "/modules/%s/", sas->submodule_name);
1294
1295                 sm_alternate = compute_alternate_path(sb.buf, &err);
1296                 if (sm_alternate) {
1297                         string_list_append(sas->reference, xstrdup(sb.buf));
1298                         free(sm_alternate);
1299                 } else {
1300                         switch (sas->error_mode) {
1301                         case SUBMODULE_ALTERNATE_ERROR_DIE:
1302                                 die(_("submodule '%s' cannot add alternate: %s"),
1303                                     sas->submodule_name, err.buf);
1304                         case SUBMODULE_ALTERNATE_ERROR_INFO:
1305                                 fprintf(stderr, _("submodule '%s' cannot add alternate: %s"),
1306                                         sas->submodule_name, err.buf);
1307                         case SUBMODULE_ALTERNATE_ERROR_IGNORE:
1308                                 ; /* nothing */
1309                         }
1310                 }
1311                 strbuf_release(&sb);
1312         }
1313
1314         return 0;
1315 }
1316
1317 static void prepare_possible_alternates(const char *sm_name,
1318                 struct string_list *reference)
1319 {
1320         char *sm_alternate = NULL, *error_strategy = NULL;
1321         struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
1322
1323         git_config_get_string("submodule.alternateLocation", &sm_alternate);
1324         if (!sm_alternate)
1325                 return;
1326
1327         git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1328
1329         if (!error_strategy)
1330                 error_strategy = xstrdup("die");
1331
1332         sas.submodule_name = sm_name;
1333         sas.reference = reference;
1334         if (!strcmp(error_strategy, "die"))
1335                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
1336         else if (!strcmp(error_strategy, "info"))
1337                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
1338         else if (!strcmp(error_strategy, "ignore"))
1339                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
1340         else
1341                 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
1342
1343         if (!strcmp(sm_alternate, "superproject"))
1344                 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
1345         else if (!strcmp(sm_alternate, "no"))
1346                 ; /* do nothing */
1347         else
1348                 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
1349
1350         free(sm_alternate);
1351         free(error_strategy);
1352 }
1353
1354 static int module_clone(int argc, const char **argv, const char *prefix)
1355 {
1356         const char *name = NULL, *url = NULL, *depth = NULL;
1357         int quiet = 0;
1358         int progress = 0;
1359         char *p, *path = NULL, *sm_gitdir;
1360         struct strbuf sb = STRBUF_INIT;
1361         struct string_list reference = STRING_LIST_INIT_NODUP;
1362         int dissociate = 0, require_init = 0;
1363         char *sm_alternate = NULL, *error_strategy = NULL;
1364
1365         struct option module_clone_options[] = {
1366                 OPT_STRING(0, "prefix", &prefix,
1367                            N_("path"),
1368                            N_("alternative anchor for relative paths")),
1369                 OPT_STRING(0, "path", &path,
1370                            N_("path"),
1371                            N_("where the new submodule will be cloned to")),
1372                 OPT_STRING(0, "name", &name,
1373                            N_("string"),
1374                            N_("name of the new submodule")),
1375                 OPT_STRING(0, "url", &url,
1376                            N_("string"),
1377                            N_("url where to clone the submodule from")),
1378                 OPT_STRING_LIST(0, "reference", &reference,
1379                            N_("repo"),
1380                            N_("reference repository")),
1381                 OPT_BOOL(0, "dissociate", &dissociate,
1382                            N_("use --reference only while cloning")),
1383                 OPT_STRING(0, "depth", &depth,
1384                            N_("string"),
1385                            N_("depth for shallow clones")),
1386                 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
1387                 OPT_BOOL(0, "progress", &progress,
1388                            N_("force cloning progress")),
1389                 OPT_BOOL(0, "require-init", &require_init,
1390                            N_("disallow cloning into non-empty directory")),
1391                 OPT_END()
1392         };
1393
1394         const char *const git_submodule_helper_usage[] = {
1395                 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
1396                    "[--reference <repository>] [--name <name>] [--depth <depth>] "
1397                    "--url <url> --path <path>"),
1398                 NULL
1399         };
1400
1401         argc = parse_options(argc, argv, prefix, module_clone_options,
1402                              git_submodule_helper_usage, 0);
1403
1404         if (argc || !url || !path || !*path)
1405                 usage_with_options(git_submodule_helper_usage,
1406                                    module_clone_options);
1407
1408         strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
1409         sm_gitdir = absolute_pathdup(sb.buf);
1410         strbuf_reset(&sb);
1411
1412         if (!is_absolute_path(path)) {
1413                 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
1414                 path = strbuf_detach(&sb, NULL);
1415         } else
1416                 path = xstrdup(path);
1417
1418         if (validate_submodule_git_dir(sm_gitdir, name) < 0)
1419                 die(_("refusing to create/use '%s' in another submodule's "
1420                         "git dir"), sm_gitdir);
1421
1422         if (!file_exists(sm_gitdir)) {
1423                 if (safe_create_leading_directories_const(sm_gitdir) < 0)
1424                         die(_("could not create directory '%s'"), sm_gitdir);
1425
1426                 prepare_possible_alternates(name, &reference);
1427
1428                 if (clone_submodule(path, sm_gitdir, url, depth, &reference, dissociate,
1429                                     quiet, progress))
1430                         die(_("clone of '%s' into submodule path '%s' failed"),
1431                             url, path);
1432         } else {
1433                 if (require_init && !access(path, X_OK) && !is_empty_dir(path))
1434                         die(_("directory not empty: '%s'"), path);
1435                 if (safe_create_leading_directories_const(path) < 0)
1436                         die(_("could not create directory '%s'"), path);
1437                 strbuf_addf(&sb, "%s/index", sm_gitdir);
1438                 unlink_or_warn(sb.buf);
1439                 strbuf_reset(&sb);
1440         }
1441
1442         connect_work_tree_and_git_dir(path, sm_gitdir, 0);
1443
1444         p = git_pathdup_submodule(path, "config");
1445         if (!p)
1446                 die(_("could not get submodule directory for '%s'"), path);
1447
1448         /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
1449         git_config_get_string("submodule.alternateLocation", &sm_alternate);
1450         if (sm_alternate)
1451                 git_config_set_in_file(p, "submodule.alternateLocation",
1452                                            sm_alternate);
1453         git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1454         if (error_strategy)
1455                 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
1456                                            error_strategy);
1457
1458         free(sm_alternate);
1459         free(error_strategy);
1460
1461         strbuf_release(&sb);
1462         free(sm_gitdir);
1463         free(path);
1464         free(p);
1465         return 0;
1466 }
1467
1468 static void determine_submodule_update_strategy(struct repository *r,
1469                                                 int just_cloned,
1470                                                 const char *path,
1471                                                 const char *update,
1472                                                 struct submodule_update_strategy *out)
1473 {
1474         const struct submodule *sub = submodule_from_path(r, &null_oid, path);
1475         char *key;
1476         const char *val;
1477
1478         key = xstrfmt("submodule.%s.update", sub->name);
1479
1480         if (update) {
1481                 if (parse_submodule_update_strategy(update, out) < 0)
1482                         die(_("Invalid update mode '%s' for submodule path '%s'"),
1483                                 update, path);
1484         } else if (!repo_config_get_string_const(r, key, &val)) {
1485                 if (parse_submodule_update_strategy(val, out) < 0)
1486                         die(_("Invalid update mode '%s' configured for submodule path '%s'"),
1487                                 val, path);
1488         } else if (sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
1489                 if (sub->update_strategy.type == SM_UPDATE_COMMAND)
1490                         BUG("how did we read update = !command from .gitmodules?");
1491                 out->type = sub->update_strategy.type;
1492                 out->command = sub->update_strategy.command;
1493         } else
1494                 out->type = SM_UPDATE_CHECKOUT;
1495
1496         if (just_cloned &&
1497             (out->type == SM_UPDATE_MERGE ||
1498              out->type == SM_UPDATE_REBASE ||
1499              out->type == SM_UPDATE_NONE))
1500                 out->type = SM_UPDATE_CHECKOUT;
1501
1502         free(key);
1503 }
1504
1505 static int module_update_module_mode(int argc, const char **argv, const char *prefix)
1506 {
1507         const char *path, *update = NULL;
1508         int just_cloned;
1509         struct submodule_update_strategy update_strategy = { .type = SM_UPDATE_CHECKOUT };
1510
1511         if (argc < 3 || argc > 4)
1512                 die("submodule--helper update-module-clone expects <just-cloned> <path> [<update>]");
1513
1514         just_cloned = git_config_int("just_cloned", argv[1]);
1515         path = argv[2];
1516
1517         if (argc == 4)
1518                 update = argv[3];
1519
1520         determine_submodule_update_strategy(the_repository,
1521                                             just_cloned, path, update,
1522                                             &update_strategy);
1523         fputs(submodule_strategy_to_string(&update_strategy), stdout);
1524
1525         return 0;
1526 }
1527
1528 struct update_clone_data {
1529         const struct submodule *sub;
1530         struct object_id oid;
1531         unsigned just_cloned;
1532 };
1533
1534 struct submodule_update_clone {
1535         /* index into 'list', the list of submodules to look into for cloning */
1536         int current;
1537         struct module_list list;
1538         unsigned warn_if_uninitialized : 1;
1539
1540         /* update parameter passed via commandline */
1541         struct submodule_update_strategy update;
1542
1543         /* configuration parameters which are passed on to the children */
1544         int progress;
1545         int quiet;
1546         int recommend_shallow;
1547         struct string_list references;
1548         int dissociate;
1549         unsigned require_init;
1550         const char *depth;
1551         const char *recursive_prefix;
1552         const char *prefix;
1553
1554         /* to be consumed by git-submodule.sh */
1555         struct update_clone_data *update_clone;
1556         int update_clone_nr; int update_clone_alloc;
1557
1558         /* If we want to stop as fast as possible and return an error */
1559         unsigned quickstop : 1;
1560
1561         /* failed clones to be retried again */
1562         const struct cache_entry **failed_clones;
1563         int failed_clones_nr, failed_clones_alloc;
1564
1565         int max_jobs;
1566 };
1567 #define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
1568         SUBMODULE_UPDATE_STRATEGY_INIT, 0, 0, -1, STRING_LIST_INIT_DUP, 0, 0, \
1569         NULL, NULL, NULL, \
1570         NULL, 0, 0, 0, NULL, 0, 0, 1}
1571
1572
1573 static void next_submodule_warn_missing(struct submodule_update_clone *suc,
1574                 struct strbuf *out, const char *displaypath)
1575 {
1576         /*
1577          * Only mention uninitialized submodules when their
1578          * paths have been specified.
1579          */
1580         if (suc->warn_if_uninitialized) {
1581                 strbuf_addf(out,
1582                         _("Submodule path '%s' not initialized"),
1583                         displaypath);
1584                 strbuf_addch(out, '\n');
1585                 strbuf_addstr(out,
1586                         _("Maybe you want to use 'update --init'?"));
1587                 strbuf_addch(out, '\n');
1588         }
1589 }
1590
1591 /**
1592  * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
1593  * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
1594  */
1595 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
1596                                            struct child_process *child,
1597                                            struct submodule_update_clone *suc,
1598                                            struct strbuf *out)
1599 {
1600         const struct submodule *sub = NULL;
1601         const char *url = NULL;
1602         const char *update_string;
1603         enum submodule_update_type update_type;
1604         char *key;
1605         struct strbuf displaypath_sb = STRBUF_INIT;
1606         struct strbuf sb = STRBUF_INIT;
1607         const char *displaypath = NULL;
1608         int needs_cloning = 0;
1609         int need_free_url = 0;
1610
1611         if (ce_stage(ce)) {
1612                 if (suc->recursive_prefix)
1613                         strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
1614                 else
1615                         strbuf_addstr(&sb, ce->name);
1616                 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
1617                 strbuf_addch(out, '\n');
1618                 goto cleanup;
1619         }
1620
1621         sub = submodule_from_path(the_repository, &null_oid, ce->name);
1622
1623         if (suc->recursive_prefix)
1624                 displaypath = relative_path(suc->recursive_prefix,
1625                                             ce->name, &displaypath_sb);
1626         else
1627                 displaypath = ce->name;
1628
1629         if (!sub) {
1630                 next_submodule_warn_missing(suc, out, displaypath);
1631                 goto cleanup;
1632         }
1633
1634         key = xstrfmt("submodule.%s.update", sub->name);
1635         if (!repo_config_get_string_const(the_repository, key, &update_string)) {
1636                 update_type = parse_submodule_update_type(update_string);
1637         } else {
1638                 update_type = sub->update_strategy.type;
1639         }
1640         free(key);
1641
1642         if (suc->update.type == SM_UPDATE_NONE
1643             || (suc->update.type == SM_UPDATE_UNSPECIFIED
1644                 && update_type == SM_UPDATE_NONE)) {
1645                 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
1646                 strbuf_addch(out, '\n');
1647                 goto cleanup;
1648         }
1649
1650         /* Check if the submodule has been initialized. */
1651         if (!is_submodule_active(the_repository, ce->name)) {
1652                 next_submodule_warn_missing(suc, out, displaypath);
1653                 goto cleanup;
1654         }
1655
1656         strbuf_reset(&sb);
1657         strbuf_addf(&sb, "submodule.%s.url", sub->name);
1658         if (repo_config_get_string_const(the_repository, sb.buf, &url)) {
1659                 if (starts_with_dot_slash(sub->url) ||
1660                     starts_with_dot_dot_slash(sub->url)) {
1661                         url = compute_submodule_clone_url(sub->url);
1662                         need_free_url = 1;
1663                 } else
1664                         url = sub->url;
1665         }
1666
1667         strbuf_reset(&sb);
1668         strbuf_addf(&sb, "%s/.git", ce->name);
1669         needs_cloning = !file_exists(sb.buf);
1670
1671         ALLOC_GROW(suc->update_clone, suc->update_clone_nr + 1,
1672                    suc->update_clone_alloc);
1673         oidcpy(&suc->update_clone[suc->update_clone_nr].oid, &ce->oid);
1674         suc->update_clone[suc->update_clone_nr].just_cloned = needs_cloning;
1675         suc->update_clone[suc->update_clone_nr].sub = sub;
1676         suc->update_clone_nr++;
1677
1678         if (!needs_cloning)
1679                 goto cleanup;
1680
1681         child->git_cmd = 1;
1682         child->no_stdin = 1;
1683         child->stdout_to_stderr = 1;
1684         child->err = -1;
1685         argv_array_push(&child->args, "submodule--helper");
1686         argv_array_push(&child->args, "clone");
1687         if (suc->progress)
1688                 argv_array_push(&child->args, "--progress");
1689         if (suc->quiet)
1690                 argv_array_push(&child->args, "--quiet");
1691         if (suc->prefix)
1692                 argv_array_pushl(&child->args, "--prefix", suc->prefix, NULL);
1693         if (suc->recommend_shallow && sub->recommend_shallow == 1)
1694                 argv_array_push(&child->args, "--depth=1");
1695         if (suc->require_init)
1696                 argv_array_push(&child->args, "--require-init");
1697         argv_array_pushl(&child->args, "--path", sub->path, NULL);
1698         argv_array_pushl(&child->args, "--name", sub->name, NULL);
1699         argv_array_pushl(&child->args, "--url", url, NULL);
1700         if (suc->references.nr) {
1701                 struct string_list_item *item;
1702                 for_each_string_list_item(item, &suc->references)
1703                         argv_array_pushl(&child->args, "--reference", item->string, NULL);
1704         }
1705         if (suc->dissociate)
1706                 argv_array_push(&child->args, "--dissociate");
1707         if (suc->depth)
1708                 argv_array_push(&child->args, suc->depth);
1709
1710 cleanup:
1711         strbuf_reset(&displaypath_sb);
1712         strbuf_reset(&sb);
1713         if (need_free_url)
1714                 free((void*)url);
1715
1716         return needs_cloning;
1717 }
1718
1719 static int update_clone_get_next_task(struct child_process *child,
1720                                       struct strbuf *err,
1721                                       void *suc_cb,
1722                                       void **idx_task_cb)
1723 {
1724         struct submodule_update_clone *suc = suc_cb;
1725         const struct cache_entry *ce;
1726         int index;
1727
1728         for (; suc->current < suc->list.nr; suc->current++) {
1729                 ce = suc->list.entries[suc->current];
1730                 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
1731                         int *p = xmalloc(sizeof(*p));
1732                         *p = suc->current;
1733                         *idx_task_cb = p;
1734                         suc->current++;
1735                         return 1;
1736                 }
1737         }
1738
1739         /*
1740          * The loop above tried cloning each submodule once, now try the
1741          * stragglers again, which we can imagine as an extension of the
1742          * entry list.
1743          */
1744         index = suc->current - suc->list.nr;
1745         if (index < suc->failed_clones_nr) {
1746                 int *p;
1747                 ce = suc->failed_clones[index];
1748                 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
1749                         suc->current ++;
1750                         strbuf_addstr(err, "BUG: submodule considered for "
1751                                            "cloning, doesn't need cloning "
1752                                            "any more?\n");
1753                         return 0;
1754                 }
1755                 p = xmalloc(sizeof(*p));
1756                 *p = suc->current;
1757                 *idx_task_cb = p;
1758                 suc->current ++;
1759                 return 1;
1760         }
1761
1762         return 0;
1763 }
1764
1765 static int update_clone_start_failure(struct strbuf *err,
1766                                       void *suc_cb,
1767                                       void *idx_task_cb)
1768 {
1769         struct submodule_update_clone *suc = suc_cb;
1770         suc->quickstop = 1;
1771         return 1;
1772 }
1773
1774 static int update_clone_task_finished(int result,
1775                                       struct strbuf *err,
1776                                       void *suc_cb,
1777                                       void *idx_task_cb)
1778 {
1779         const struct cache_entry *ce;
1780         struct submodule_update_clone *suc = suc_cb;
1781
1782         int *idxP = idx_task_cb;
1783         int idx = *idxP;
1784         free(idxP);
1785
1786         if (!result)
1787                 return 0;
1788
1789         if (idx < suc->list.nr) {
1790                 ce  = suc->list.entries[idx];
1791                 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
1792                             ce->name);
1793                 strbuf_addch(err, '\n');
1794                 ALLOC_GROW(suc->failed_clones,
1795                            suc->failed_clones_nr + 1,
1796                            suc->failed_clones_alloc);
1797                 suc->failed_clones[suc->failed_clones_nr++] = ce;
1798                 return 0;
1799         } else {
1800                 idx -= suc->list.nr;
1801                 ce  = suc->failed_clones[idx];
1802                 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
1803                             ce->name);
1804                 strbuf_addch(err, '\n');
1805                 suc->quickstop = 1;
1806                 return 1;
1807         }
1808
1809         return 0;
1810 }
1811
1812 static int git_update_clone_config(const char *var, const char *value,
1813                                    void *cb)
1814 {
1815         int *max_jobs = cb;
1816         if (!strcmp(var, "submodule.fetchjobs"))
1817                 *max_jobs = parse_submodule_fetchjobs(var, value);
1818         return 0;
1819 }
1820
1821 static void update_submodule(struct update_clone_data *ucd)
1822 {
1823         fprintf(stdout, "dummy %s %d\t%s\n",
1824                 oid_to_hex(&ucd->oid),
1825                 ucd->just_cloned,
1826                 ucd->sub->path);
1827 }
1828
1829 static int update_submodules(struct submodule_update_clone *suc)
1830 {
1831         int i;
1832
1833         run_processes_parallel(suc->max_jobs,
1834                                update_clone_get_next_task,
1835                                update_clone_start_failure,
1836                                update_clone_task_finished,
1837                                suc);
1838
1839         /*
1840          * We saved the output and put it out all at once now.
1841          * That means:
1842          * - the listener does not have to interleave their (checkout)
1843          *   work with our fetching.  The writes involved in a
1844          *   checkout involve more straightforward sequential I/O.
1845          * - the listener can avoid doing any work if fetching failed.
1846          */
1847         if (suc->quickstop)
1848                 return 1;
1849
1850         for (i = 0; i < suc->update_clone_nr; i++)
1851                 update_submodule(&suc->update_clone[i]);
1852
1853         return 0;
1854 }
1855
1856 static int update_clone(int argc, const char **argv, const char *prefix)
1857 {
1858         const char *update = NULL;
1859         struct pathspec pathspec;
1860         struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
1861
1862         struct option module_update_clone_options[] = {
1863                 OPT_STRING(0, "prefix", &prefix,
1864                            N_("path"),
1865                            N_("path into the working tree")),
1866                 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
1867                            N_("path"),
1868                            N_("path into the working tree, across nested "
1869                               "submodule boundaries")),
1870                 OPT_STRING(0, "update", &update,
1871                            N_("string"),
1872                            N_("rebase, merge, checkout or none")),
1873                 OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
1874                            N_("reference repository")),
1875                 OPT_BOOL(0, "dissociate", &suc.dissociate,
1876                            N_("use --reference only while cloning")),
1877                 OPT_STRING(0, "depth", &suc.depth, "<depth>",
1878                            N_("Create a shallow clone truncated to the "
1879                               "specified number of revisions")),
1880                 OPT_INTEGER('j', "jobs", &suc.max_jobs,
1881                             N_("parallel jobs")),
1882                 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
1883                             N_("whether the initial clone should follow the shallow recommendation")),
1884                 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
1885                 OPT_BOOL(0, "progress", &suc.progress,
1886                             N_("force cloning progress")),
1887                 OPT_BOOL(0, "require-init", &suc.require_init,
1888                            N_("disallow cloning into non-empty directory")),
1889                 OPT_END()
1890         };
1891
1892         const char *const git_submodule_helper_usage[] = {
1893                 N_("git submodule--helper update_clone [--prefix=<path>] [<path>...]"),
1894                 NULL
1895         };
1896         suc.prefix = prefix;
1897
1898         update_clone_config_from_gitmodules(&suc.max_jobs);
1899         git_config(git_update_clone_config, &suc.max_jobs);
1900
1901         argc = parse_options(argc, argv, prefix, module_update_clone_options,
1902                              git_submodule_helper_usage, 0);
1903
1904         if (update)
1905                 if (parse_submodule_update_strategy(update, &suc.update) < 0)
1906                         die(_("bad value for update parameter"));
1907
1908         if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
1909                 return 1;
1910
1911         if (pathspec.nr)
1912                 suc.warn_if_uninitialized = 1;
1913
1914         return update_submodules(&suc);
1915 }
1916
1917 static int resolve_relative_path(int argc, const char **argv, const char *prefix)
1918 {
1919         struct strbuf sb = STRBUF_INIT;
1920         if (argc != 3)
1921                 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
1922
1923         printf("%s", relative_path(argv[1], argv[2], &sb));
1924         strbuf_release(&sb);
1925         return 0;
1926 }
1927
1928 static const char *remote_submodule_branch(const char *path)
1929 {
1930         const struct submodule *sub;
1931         const char *branch = NULL;
1932         char *key;
1933
1934         sub = submodule_from_path(the_repository, &null_oid, path);
1935         if (!sub)
1936                 return NULL;
1937
1938         key = xstrfmt("submodule.%s.branch", sub->name);
1939         if (repo_config_get_string_const(the_repository, key, &branch))
1940                 branch = sub->branch;
1941         free(key);
1942
1943         if (!branch)
1944                 return "master";
1945
1946         if (!strcmp(branch, ".")) {
1947                 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1948
1949                 if (!refname)
1950                         die(_("No such ref: %s"), "HEAD");
1951
1952                 /* detached HEAD */
1953                 if (!strcmp(refname, "HEAD"))
1954                         die(_("Submodule (%s) branch configured to inherit "
1955                               "branch from superproject, but the superproject "
1956                               "is not on any branch"), sub->name);
1957
1958                 if (!skip_prefix(refname, "refs/heads/", &refname))
1959                         die(_("Expecting a full ref name, got %s"), refname);
1960                 return refname;
1961         }
1962
1963         return branch;
1964 }
1965
1966 static int resolve_remote_submodule_branch(int argc, const char **argv,
1967                 const char *prefix)
1968 {
1969         const char *ret;
1970         struct strbuf sb = STRBUF_INIT;
1971         if (argc != 2)
1972                 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
1973
1974         ret = remote_submodule_branch(argv[1]);
1975         if (!ret)
1976                 die("submodule %s doesn't exist", argv[1]);
1977
1978         printf("%s", ret);
1979         strbuf_release(&sb);
1980         return 0;
1981 }
1982
1983 static int push_check(int argc, const char **argv, const char *prefix)
1984 {
1985         struct remote *remote;
1986         const char *superproject_head;
1987         char *head;
1988         int detached_head = 0;
1989         struct object_id head_oid;
1990
1991         if (argc < 3)
1992                 die("submodule--helper push-check requires at least 2 arguments");
1993
1994         /*
1995          * superproject's resolved head ref.
1996          * if HEAD then the superproject is in a detached head state, otherwise
1997          * it will be the resolved head ref.
1998          */
1999         superproject_head = argv[1];
2000         argv++;
2001         argc--;
2002         /* Get the submodule's head ref and determine if it is detached */
2003         head = resolve_refdup("HEAD", 0, &head_oid, NULL);
2004         if (!head)
2005                 die(_("Failed to resolve HEAD as a valid ref."));
2006         if (!strcmp(head, "HEAD"))
2007                 detached_head = 1;
2008
2009         /*
2010          * The remote must be configured.
2011          * This is to avoid pushing to the exact same URL as the parent.
2012          */
2013         remote = pushremote_get(argv[1]);
2014         if (!remote || remote->origin == REMOTE_UNCONFIGURED)
2015                 die("remote '%s' not configured", argv[1]);
2016
2017         /* Check the refspec */
2018         if (argc > 2) {
2019                 int i;
2020                 struct ref *local_refs = get_local_heads();
2021                 struct refspec refspec = REFSPEC_INIT_PUSH;
2022
2023                 refspec_appendn(&refspec, argv + 2, argc - 2);
2024
2025                 for (i = 0; i < refspec.nr; i++) {
2026                         const struct refspec_item *rs = &refspec.items[i];
2027
2028                         if (rs->pattern || rs->matching)
2029                                 continue;
2030
2031                         /* LHS must match a single ref */
2032                         switch (count_refspec_match(rs->src, local_refs, NULL)) {
2033                         case 1:
2034                                 break;
2035                         case 0:
2036                                 /*
2037                                  * If LHS matches 'HEAD' then we need to ensure
2038                                  * that it matches the same named branch
2039                                  * checked out in the superproject.
2040                                  */
2041                                 if (!strcmp(rs->src, "HEAD")) {
2042                                         if (!detached_head &&
2043                                             !strcmp(head, superproject_head))
2044                                                 break;
2045                                         die("HEAD does not match the named branch in the superproject");
2046                                 }
2047                                 /* fallthrough */
2048                         default:
2049                                 die("src refspec '%s' must name a ref",
2050                                     rs->src);
2051                         }
2052                 }
2053                 refspec_clear(&refspec);
2054         }
2055         free(head);
2056
2057         return 0;
2058 }
2059
2060 static int ensure_core_worktree(int argc, const char **argv, const char *prefix)
2061 {
2062         const struct submodule *sub;
2063         const char *path;
2064         char *cw;
2065         struct repository subrepo;
2066
2067         if (argc != 2)
2068                 BUG("submodule--helper ensure-core-worktree <path>");
2069
2070         path = argv[1];
2071
2072         sub = submodule_from_path(the_repository, &null_oid, path);
2073         if (!sub)
2074                 BUG("We could get the submodule handle before?");
2075
2076         if (repo_submodule_init(&subrepo, the_repository, sub))
2077                 die(_("could not get a repository handle for submodule '%s'"), path);
2078
2079         if (!repo_config_get_string(&subrepo, "core.worktree", &cw)) {
2080                 char *cfg_file, *abs_path;
2081                 const char *rel_path;
2082                 struct strbuf sb = STRBUF_INIT;
2083
2084                 cfg_file = repo_git_path(&subrepo, "config");
2085
2086                 abs_path = absolute_pathdup(path);
2087                 rel_path = relative_path(abs_path, subrepo.gitdir, &sb);
2088
2089                 git_config_set_in_file(cfg_file, "core.worktree", rel_path);
2090
2091                 free(cfg_file);
2092                 free(abs_path);
2093                 strbuf_release(&sb);
2094         }
2095
2096         return 0;
2097 }
2098
2099 static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
2100 {
2101         int i;
2102         struct pathspec pathspec;
2103         struct module_list list = MODULE_LIST_INIT;
2104         unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
2105
2106         struct option embed_gitdir_options[] = {
2107                 OPT_STRING(0, "prefix", &prefix,
2108                            N_("path"),
2109                            N_("path into the working tree")),
2110                 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
2111                         ABSORB_GITDIR_RECURSE_SUBMODULES),
2112                 OPT_END()
2113         };
2114
2115         const char *const git_submodule_helper_usage[] = {
2116                 N_("git submodule--helper embed-git-dir [<path>...]"),
2117                 NULL
2118         };
2119
2120         argc = parse_options(argc, argv, prefix, embed_gitdir_options,
2121                              git_submodule_helper_usage, 0);
2122
2123         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
2124                 return 1;
2125
2126         for (i = 0; i < list.nr; i++)
2127                 absorb_git_dir_into_superproject(prefix,
2128                                 list.entries[i]->name, flags);
2129
2130         return 0;
2131 }
2132
2133 static int is_active(int argc, const char **argv, const char *prefix)
2134 {
2135         if (argc != 2)
2136                 die("submodule--helper is-active takes exactly 1 argument");
2137
2138         return !is_submodule_active(the_repository, argv[1]);
2139 }
2140
2141 /*
2142  * Exit non-zero if any of the submodule names given on the command line is
2143  * invalid. If no names are given, filter stdin to print only valid names
2144  * (which is primarily intended for testing).
2145  */
2146 static int check_name(int argc, const char **argv, const char *prefix)
2147 {
2148         if (argc > 1) {
2149                 while (*++argv) {
2150                         if (check_submodule_name(*argv) < 0)
2151                                 return 1;
2152                 }
2153         } else {
2154                 struct strbuf buf = STRBUF_INIT;
2155                 while (strbuf_getline(&buf, stdin) != EOF) {
2156                         if (!check_submodule_name(buf.buf))
2157                                 printf("%s\n", buf.buf);
2158                 }
2159                 strbuf_release(&buf);
2160         }
2161         return 0;
2162 }
2163
2164 static int module_config(int argc, const char **argv, const char *prefix)
2165 {
2166         enum {
2167                 CHECK_WRITEABLE = 1
2168         } command = 0;
2169
2170         struct option module_config_options[] = {
2171                 OPT_CMDMODE(0, "check-writeable", &command,
2172                             N_("check if it is safe to write to the .gitmodules file"),
2173                             CHECK_WRITEABLE),
2174                 OPT_END()
2175         };
2176         const char *const git_submodule_helper_usage[] = {
2177                 N_("git submodule--helper config name [value]"),
2178                 N_("git submodule--helper config --check-writeable"),
2179                 NULL
2180         };
2181
2182         argc = parse_options(argc, argv, prefix, module_config_options,
2183                              git_submodule_helper_usage, PARSE_OPT_KEEP_ARGV0);
2184
2185         if (argc == 1 && command == CHECK_WRITEABLE)
2186                 return is_writing_gitmodules_ok() ? 0 : -1;
2187
2188         /* Equivalent to ACTION_GET in builtin/config.c */
2189         if (argc == 2)
2190                 return print_config_from_gitmodules(the_repository, argv[1]);
2191
2192         /* Equivalent to ACTION_SET in builtin/config.c */
2193         if (argc == 3) {
2194                 if (!is_writing_gitmodules_ok())
2195                         die(_("please make sure that the .gitmodules file is in the working tree"));
2196
2197                 return config_set_in_gitmodules_file_gently(argv[1], argv[2]);
2198         }
2199
2200         usage_with_options(git_submodule_helper_usage, module_config_options);
2201 }
2202
2203 #define SUPPORT_SUPER_PREFIX (1<<0)
2204
2205 struct cmd_struct {
2206         const char *cmd;
2207         int (*fn)(int, const char **, const char *);
2208         unsigned option;
2209 };
2210
2211 static struct cmd_struct commands[] = {
2212         {"list", module_list, 0},
2213         {"name", module_name, 0},
2214         {"clone", module_clone, 0},
2215         {"update-module-mode", module_update_module_mode, 0},
2216         {"update-clone", update_clone, 0},
2217         {"ensure-core-worktree", ensure_core_worktree, 0},
2218         {"relative-path", resolve_relative_path, 0},
2219         {"resolve-relative-url", resolve_relative_url, 0},
2220         {"resolve-relative-url-test", resolve_relative_url_test, 0},
2221         {"foreach", module_foreach, SUPPORT_SUPER_PREFIX},
2222         {"init", module_init, SUPPORT_SUPER_PREFIX},
2223         {"status", module_status, SUPPORT_SUPER_PREFIX},
2224         {"print-default-remote", print_default_remote, 0},
2225         {"sync", module_sync, SUPPORT_SUPER_PREFIX},
2226         {"deinit", module_deinit, 0},
2227         {"remote-branch", resolve_remote_submodule_branch, 0},
2228         {"push-check", push_check, 0},
2229         {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
2230         {"is-active", is_active, 0},
2231         {"check-name", check_name, 0},
2232         {"config", module_config, 0},
2233 };
2234
2235 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
2236 {
2237         int i;
2238         if (argc < 2 || !strcmp(argv[1], "-h"))
2239                 usage("git submodule--helper <command>");
2240
2241         for (i = 0; i < ARRAY_SIZE(commands); i++) {
2242                 if (!strcmp(argv[1], commands[i].cmd)) {
2243                         if (get_super_prefix() &&
2244                             !(commands[i].option & SUPPORT_SUPER_PREFIX))
2245                                 die(_("%s doesn't support --super-prefix"),
2246                                     commands[i].cmd);
2247                         return commands[i].fn(argc - 1, argv + 1, prefix);
2248                 }
2249         }
2250
2251         die(_("'%s' is not a valid submodule--helper "
2252               "subcommand"), argv[1]);
2253 }