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