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