clone --recurse-submodules: prevent name squatting on Windows
[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 "dir.h"
17
18 static char *get_default_remote(void)
19 {
20         char *dest = NULL, *ret;
21         unsigned char sha1[20];
22         struct strbuf sb = STRBUF_INIT;
23         const char *refname = resolve_ref_unsafe("HEAD", 0, sha1, NULL);
24
25         if (!refname)
26                 die(_("No such ref: %s"), "HEAD");
27
28         /* detached HEAD */
29         if (!strcmp(refname, "HEAD"))
30                 return xstrdup("origin");
31
32         if (!skip_prefix(refname, "refs/heads/", &refname))
33                 die(_("Expecting a full ref name, got %s"), refname);
34
35         strbuf_addf(&sb, "branch.%s.remote", refname);
36         if (git_config_get_string(sb.buf, &dest))
37                 ret = xstrdup("origin");
38         else
39                 ret = dest;
40
41         strbuf_release(&sb);
42         return ret;
43 }
44
45 static int starts_with_dot_slash(const char *str)
46 {
47         return str[0] == '.' && is_dir_sep(str[1]);
48 }
49
50 static int starts_with_dot_dot_slash(const char *str)
51 {
52         return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
53 }
54
55 /*
56  * Returns 1 if it was the last chop before ':'.
57  */
58 static int chop_last_dir(char **remoteurl, int is_relative)
59 {
60         char *rfind = find_last_dir_sep(*remoteurl);
61         if (rfind) {
62                 *rfind = '\0';
63                 return 0;
64         }
65
66         rfind = strrchr(*remoteurl, ':');
67         if (rfind) {
68                 *rfind = '\0';
69                 return 1;
70         }
71
72         if (is_relative || !strcmp(".", *remoteurl))
73                 die(_("cannot strip one component off url '%s'"),
74                         *remoteurl);
75
76         free(*remoteurl);
77         *remoteurl = xstrdup(".");
78         return 0;
79 }
80
81 /*
82  * The `url` argument is the URL that navigates to the submodule origin
83  * repo. When relative, this URL is relative to the superproject origin
84  * URL repo. The `up_path` argument, if specified, is the relative
85  * path that navigates from the submodule working tree to the superproject
86  * working tree. Returns the origin URL of the submodule.
87  *
88  * Return either an absolute URL or filesystem path (if the superproject
89  * origin URL is an absolute URL or filesystem path, respectively) or a
90  * relative file system path (if the superproject origin URL is a relative
91  * file system path).
92  *
93  * When the output is a relative file system path, the path is either
94  * relative to the submodule working tree, if up_path is specified, or to
95  * the superproject working tree otherwise.
96  *
97  * NEEDSWORK: This works incorrectly on the domain and protocol part.
98  * remote_url      url              outcome          expectation
99  * http://a.com/b  ../c             http://a.com/c   as is
100  * http://a.com/b/ ../c             http://a.com/c   same as previous line, but
101  *                                                   ignore trailing slash in url
102  * http://a.com/b  ../../c          http://c         error out
103  * http://a.com/b  ../../../c       http:/c          error out
104  * http://a.com/b  ../../../../c    http:c           error out
105  * http://a.com/b  ../../../../../c    .:c           error out
106  * NEEDSWORK: Given how chop_last_dir() works, this function is broken
107  * when a local part has a colon in its path component, too.
108  */
109 static char *relative_url(const char *remote_url,
110                                 const char *url,
111                                 const char *up_path)
112 {
113         int is_relative = 0;
114         int colonsep = 0;
115         char *out;
116         char *remoteurl = xstrdup(remote_url);
117         struct strbuf sb = STRBUF_INIT;
118         size_t len = strlen(remoteurl);
119
120         if (is_dir_sep(remoteurl[len-1]))
121                 remoteurl[len-1] = '\0';
122
123         if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
124                 is_relative = 0;
125         else {
126                 is_relative = 1;
127                 /*
128                  * Prepend a './' to ensure all relative
129                  * remoteurls start with './' or '../'
130                  */
131                 if (!starts_with_dot_slash(remoteurl) &&
132                     !starts_with_dot_dot_slash(remoteurl)) {
133                         strbuf_reset(&sb);
134                         strbuf_addf(&sb, "./%s", remoteurl);
135                         free(remoteurl);
136                         remoteurl = strbuf_detach(&sb, NULL);
137                 }
138         }
139         /*
140          * When the url starts with '../', remove that and the
141          * last directory in remoteurl.
142          */
143         while (url) {
144                 if (starts_with_dot_dot_slash(url)) {
145                         url += 3;
146                         colonsep |= chop_last_dir(&remoteurl, is_relative);
147                 } else if (starts_with_dot_slash(url))
148                         url += 2;
149                 else
150                         break;
151         }
152         strbuf_reset(&sb);
153         strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
154         if (ends_with(url, "/"))
155                 strbuf_setlen(&sb, sb.len - 1);
156         free(remoteurl);
157
158         if (starts_with_dot_slash(sb.buf))
159                 out = xstrdup(sb.buf + 2);
160         else
161                 out = xstrdup(sb.buf);
162         strbuf_reset(&sb);
163
164         if (!up_path || !is_relative)
165                 return out;
166
167         strbuf_addf(&sb, "%s%s", up_path, out);
168         free(out);
169         return strbuf_detach(&sb, NULL);
170 }
171
172 static int resolve_relative_url(int argc, const char **argv, const char *prefix)
173 {
174         char *remoteurl = NULL;
175         char *remote = get_default_remote();
176         const char *up_path = NULL;
177         char *res;
178         const char *url;
179         struct strbuf sb = STRBUF_INIT;
180
181         if (argc != 2 && argc != 3)
182                 die("resolve-relative-url only accepts one or two arguments");
183
184         url = argv[1];
185         strbuf_addf(&sb, "remote.%s.url", remote);
186         free(remote);
187
188         if (git_config_get_string(sb.buf, &remoteurl))
189                 /* the repository is its own authoritative upstream */
190                 remoteurl = xgetcwd();
191
192         if (argc == 3)
193                 up_path = argv[2];
194
195         res = relative_url(remoteurl, url, up_path);
196         puts(res);
197         free(res);
198         free(remoteurl);
199         return 0;
200 }
201
202 static int resolve_relative_url_test(int argc, const char **argv, const char *prefix)
203 {
204         char *remoteurl, *res;
205         const char *up_path, *url;
206
207         if (argc != 4)
208                 die("resolve-relative-url-test only accepts three arguments: <up_path> <remoteurl> <url>");
209
210         up_path = argv[1];
211         remoteurl = xstrdup(argv[2]);
212         url = argv[3];
213
214         if (!strcmp(up_path, "(null)"))
215                 up_path = NULL;
216
217         res = relative_url(remoteurl, url, up_path);
218         puts(res);
219         free(res);
220         free(remoteurl);
221         return 0;
222 }
223
224 struct module_list {
225         const struct cache_entry **entries;
226         int alloc, nr;
227 };
228 #define MODULE_LIST_INIT { NULL, 0, 0 }
229
230 static int module_list_compute(int argc, const char **argv,
231                                const char *prefix,
232                                struct pathspec *pathspec,
233                                struct module_list *list)
234 {
235         int i, result = 0;
236         char *ps_matched = NULL;
237         parse_pathspec(pathspec, 0,
238                        PATHSPEC_PREFER_FULL,
239                        prefix, argv);
240
241         if (pathspec->nr)
242                 ps_matched = xcalloc(pathspec->nr, 1);
243
244         if (read_cache() < 0)
245                 die(_("index file corrupt"));
246
247         for (i = 0; i < active_nr; i++) {
248                 const struct cache_entry *ce = active_cache[i];
249
250                 if (!match_pathspec(pathspec, ce->name, ce_namelen(ce),
251                                     0, ps_matched, 1) ||
252                     !S_ISGITLINK(ce->ce_mode))
253                         continue;
254
255                 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
256                 list->entries[list->nr++] = ce;
257                 while (i + 1 < active_nr &&
258                        !strcmp(ce->name, active_cache[i + 1]->name))
259                         /*
260                          * Skip entries with the same name in different stages
261                          * to make sure an entry is returned only once.
262                          */
263                         i++;
264         }
265
266         if (ps_matched && report_path_error(ps_matched, pathspec, prefix))
267                 result = -1;
268
269         free(ps_matched);
270
271         return result;
272 }
273
274 static void module_list_active(struct module_list *list)
275 {
276         int i;
277         struct module_list active_modules = MODULE_LIST_INIT;
278
279         gitmodules_config();
280
281         for (i = 0; i < list->nr; i++) {
282                 const struct cache_entry *ce = list->entries[i];
283
284                 if (!is_submodule_active(the_repository, ce->name))
285                         continue;
286
287                 ALLOC_GROW(active_modules.entries,
288                            active_modules.nr + 1,
289                            active_modules.alloc);
290                 active_modules.entries[active_modules.nr++] = ce;
291         }
292
293         free(list->entries);
294         *list = active_modules;
295 }
296
297 static int module_list(int argc, const char **argv, const char *prefix)
298 {
299         int i;
300         struct pathspec pathspec;
301         struct module_list list = MODULE_LIST_INIT;
302
303         struct option module_list_options[] = {
304                 OPT_STRING(0, "prefix", &prefix,
305                            N_("path"),
306                            N_("alternative anchor for relative paths")),
307                 OPT_END()
308         };
309
310         const char *const git_submodule_helper_usage[] = {
311                 N_("git submodule--helper list [--prefix=<path>] [<path>...]"),
312                 NULL
313         };
314
315         argc = parse_options(argc, argv, prefix, module_list_options,
316                              git_submodule_helper_usage, 0);
317
318         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
319                 return 1;
320
321         for (i = 0; i < list.nr; i++) {
322                 const struct cache_entry *ce = list.entries[i];
323
324                 if (ce_stage(ce))
325                         printf("%06o %s U\t", ce->ce_mode, sha1_to_hex(null_sha1));
326                 else
327                         printf("%06o %s %d\t", ce->ce_mode,
328                                oid_to_hex(&ce->oid), ce_stage(ce));
329
330                 fprintf(stdout, "%s\n", ce->name);
331         }
332         return 0;
333 }
334
335 static void init_submodule(const char *path, const char *prefix, int quiet)
336 {
337         const struct submodule *sub;
338         struct strbuf sb = STRBUF_INIT;
339         char *upd = NULL, *url = NULL, *displaypath;
340
341         /* Only loads from .gitmodules, no overlay with .git/config */
342         gitmodules_config();
343
344         if (prefix && get_super_prefix())
345                 die("BUG: cannot have prefix and superprefix");
346         else if (prefix)
347                 displaypath = xstrdup(relative_path(path, prefix, &sb));
348         else if (get_super_prefix()) {
349                 strbuf_addf(&sb, "%s%s", get_super_prefix(), path);
350                 displaypath = strbuf_detach(&sb, NULL);
351         } else
352                 displaypath = xstrdup(path);
353
354         sub = submodule_from_path(null_sha1, path);
355
356         if (!sub)
357                 die(_("No url found for submodule path '%s' in .gitmodules"),
358                         displaypath);
359
360         /*
361          * NEEDSWORK: In a multi-working-tree world, this needs to be
362          * set in the per-worktree config.
363          *
364          * Set active flag for the submodule being initialized
365          */
366         if (!is_submodule_active(the_repository, path)) {
367                 strbuf_reset(&sb);
368                 strbuf_addf(&sb, "submodule.%s.active", sub->name);
369                 git_config_set_gently(sb.buf, "true");
370         }
371
372         /*
373          * Copy url setting when it is not set yet.
374          * To look up the url in .git/config, we must not fall back to
375          * .gitmodules, so look it up directly.
376          */
377         strbuf_reset(&sb);
378         strbuf_addf(&sb, "submodule.%s.url", sub->name);
379         if (git_config_get_string(sb.buf, &url)) {
380                 if (!sub->url)
381                         die(_("No url found for submodule path '%s' in .gitmodules"),
382                                 displaypath);
383
384                 url = xstrdup(sub->url);
385
386                 /* Possibly a url relative to parent */
387                 if (starts_with_dot_dot_slash(url) ||
388                     starts_with_dot_slash(url)) {
389                         char *remoteurl, *relurl;
390                         char *remote = get_default_remote();
391                         struct strbuf remotesb = STRBUF_INIT;
392                         strbuf_addf(&remotesb, "remote.%s.url", remote);
393                         free(remote);
394
395                         if (git_config_get_string(remotesb.buf, &remoteurl)) {
396                                 warning(_("could not lookup configuration '%s'. Assuming this repository is its own authoritative upstream."), remotesb.buf);
397                                 remoteurl = xgetcwd();
398                         }
399                         relurl = relative_url(remoteurl, url, NULL);
400                         strbuf_release(&remotesb);
401                         free(remoteurl);
402                         free(url);
403                         url = relurl;
404                 }
405
406                 if (git_config_set_gently(sb.buf, url))
407                         die(_("Failed to register url for submodule path '%s'"),
408                             displaypath);
409                 if (!quiet)
410                         fprintf(stderr,
411                                 _("Submodule '%s' (%s) registered for path '%s'\n"),
412                                 sub->name, url, displaypath);
413         }
414
415         /* Copy "update" setting when it is not set yet */
416         strbuf_reset(&sb);
417         strbuf_addf(&sb, "submodule.%s.update", sub->name);
418         if (git_config_get_string(sb.buf, &upd) &&
419             sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
420                 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
421                         fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
422                                 sub->name);
423                         upd = xstrdup("none");
424                 } else
425                         upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
426
427                 if (git_config_set_gently(sb.buf, upd))
428                         die(_("Failed to register update mode for submodule path '%s'"), displaypath);
429         }
430         strbuf_release(&sb);
431         free(displaypath);
432         free(url);
433         free(upd);
434 }
435
436 static int module_init(int argc, const char **argv, const char *prefix)
437 {
438         struct pathspec pathspec;
439         struct module_list list = MODULE_LIST_INIT;
440         int quiet = 0;
441         int i;
442
443         struct option module_init_options[] = {
444                 OPT__QUIET(&quiet, N_("Suppress output for initializing a submodule")),
445                 OPT_END()
446         };
447
448         const char *const git_submodule_helper_usage[] = {
449                 N_("git submodule--helper init [<path>]"),
450                 NULL
451         };
452
453         argc = parse_options(argc, argv, prefix, module_init_options,
454                              git_submodule_helper_usage, 0);
455
456         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
457                 return 1;
458
459         /*
460          * If there are no path args and submodule.active is set then,
461          * by default, only initialize 'active' modules.
462          */
463         if (!argc && git_config_get_value_multi("submodule.active"))
464                 module_list_active(&list);
465
466         for (i = 0; i < list.nr; i++)
467                 init_submodule(list.entries[i]->name, prefix, quiet);
468
469         return 0;
470 }
471
472 static int module_name(int argc, const char **argv, const char *prefix)
473 {
474         const struct submodule *sub;
475
476         if (argc != 2)
477                 usage(_("git submodule--helper name <path>"));
478
479         gitmodules_config();
480         sub = submodule_from_path(null_sha1, argv[1]);
481
482         if (!sub)
483                 die(_("no submodule mapping found in .gitmodules for path '%s'"),
484                     argv[1]);
485
486         printf("%s\n", sub->name);
487
488         return 0;
489 }
490
491 static int clone_submodule(const char *path, const char *gitdir, const char *url,
492                            const char *depth, struct string_list *reference,
493                            int quiet, int progress)
494 {
495         struct child_process cp = CHILD_PROCESS_INIT;
496
497         argv_array_push(&cp.args, "clone");
498         argv_array_push(&cp.args, "--no-checkout");
499         if (quiet)
500                 argv_array_push(&cp.args, "--quiet");
501         if (progress)
502                 argv_array_push(&cp.args, "--progress");
503         if (depth && *depth)
504                 argv_array_pushl(&cp.args, "--depth", depth, NULL);
505         if (reference->nr) {
506                 struct string_list_item *item;
507                 for_each_string_list_item(item, reference)
508                         argv_array_pushl(&cp.args, "--reference",
509                                          item->string, NULL);
510         }
511         if (gitdir && *gitdir)
512                 argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
513
514         argv_array_push(&cp.args, "--");
515         argv_array_push(&cp.args, url);
516         argv_array_push(&cp.args, path);
517
518         cp.git_cmd = 1;
519         prepare_submodule_repo_env(&cp.env_array);
520         cp.no_stdin = 1;
521
522         return run_command(&cp);
523 }
524
525 struct submodule_alternate_setup {
526         const char *submodule_name;
527         enum SUBMODULE_ALTERNATE_ERROR_MODE {
528                 SUBMODULE_ALTERNATE_ERROR_DIE,
529                 SUBMODULE_ALTERNATE_ERROR_INFO,
530                 SUBMODULE_ALTERNATE_ERROR_IGNORE
531         } error_mode;
532         struct string_list *reference;
533 };
534 #define SUBMODULE_ALTERNATE_SETUP_INIT { NULL, \
535         SUBMODULE_ALTERNATE_ERROR_IGNORE, NULL }
536
537 static int add_possible_reference_from_superproject(
538                 struct alternate_object_database *alt, void *sas_cb)
539 {
540         struct submodule_alternate_setup *sas = sas_cb;
541
542         /*
543          * If the alternate object store is another repository, try the
544          * standard layout with .git/(modules/<name>)+/objects
545          */
546         if (ends_with(alt->path, "/objects")) {
547                 char *sm_alternate;
548                 struct strbuf sb = STRBUF_INIT;
549                 struct strbuf err = STRBUF_INIT;
550                 strbuf_add(&sb, alt->path, strlen(alt->path) - strlen("objects"));
551
552                 /*
553                  * We need to end the new path with '/' to mark it as a dir,
554                  * otherwise a submodule name containing '/' will be broken
555                  * as the last part of a missing submodule reference would
556                  * be taken as a file name.
557                  */
558                 strbuf_addf(&sb, "modules/%s/", sas->submodule_name);
559
560                 sm_alternate = compute_alternate_path(sb.buf, &err);
561                 if (sm_alternate) {
562                         string_list_append(sas->reference, xstrdup(sb.buf));
563                         free(sm_alternate);
564                 } else {
565                         switch (sas->error_mode) {
566                         case SUBMODULE_ALTERNATE_ERROR_DIE:
567                                 die(_("submodule '%s' cannot add alternate: %s"),
568                                     sas->submodule_name, err.buf);
569                         case SUBMODULE_ALTERNATE_ERROR_INFO:
570                                 fprintf(stderr, _("submodule '%s' cannot add alternate: %s"),
571                                         sas->submodule_name, err.buf);
572                         case SUBMODULE_ALTERNATE_ERROR_IGNORE:
573                                 ; /* nothing */
574                         }
575                 }
576                 strbuf_release(&sb);
577         }
578
579         return 0;
580 }
581
582 static void prepare_possible_alternates(const char *sm_name,
583                 struct string_list *reference)
584 {
585         char *sm_alternate = NULL, *error_strategy = NULL;
586         struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
587
588         git_config_get_string("submodule.alternateLocation", &sm_alternate);
589         if (!sm_alternate)
590                 return;
591
592         git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
593
594         if (!error_strategy)
595                 error_strategy = xstrdup("die");
596
597         sas.submodule_name = sm_name;
598         sas.reference = reference;
599         if (!strcmp(error_strategy, "die"))
600                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
601         else if (!strcmp(error_strategy, "info"))
602                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
603         else if (!strcmp(error_strategy, "ignore"))
604                 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
605         else
606                 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
607
608         if (!strcmp(sm_alternate, "superproject"))
609                 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
610         else if (!strcmp(sm_alternate, "no"))
611                 ; /* do nothing */
612         else
613                 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
614
615         free(sm_alternate);
616         free(error_strategy);
617 }
618
619 static int module_clone(int argc, const char **argv, const char *prefix)
620 {
621         const char *name = NULL, *url = NULL, *depth = NULL;
622         int quiet = 0;
623         int progress = 0;
624         char *p, *path = NULL, *sm_gitdir;
625         struct strbuf sb = STRBUF_INIT;
626         struct string_list reference = STRING_LIST_INIT_NODUP;
627         int require_init = 0;
628         char *sm_alternate = NULL, *error_strategy = NULL;
629
630         struct option module_clone_options[] = {
631                 OPT_STRING(0, "prefix", &prefix,
632                            N_("path"),
633                            N_("alternative anchor for relative paths")),
634                 OPT_STRING(0, "path", &path,
635                            N_("path"),
636                            N_("where the new submodule will be cloned to")),
637                 OPT_STRING(0, "name", &name,
638                            N_("string"),
639                            N_("name of the new submodule")),
640                 OPT_STRING(0, "url", &url,
641                            N_("string"),
642                            N_("url where to clone the submodule from")),
643                 OPT_STRING_LIST(0, "reference", &reference,
644                            N_("repo"),
645                            N_("reference repository")),
646                 OPT_STRING(0, "depth", &depth,
647                            N_("string"),
648                            N_("depth for shallow clones")),
649                 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
650                 OPT_BOOL(0, "progress", &progress,
651                            N_("force cloning progress")),
652                 OPT_BOOL(0, "require-init", &require_init,
653                            N_("disallow cloning into non-empty directory")),
654                 OPT_END()
655         };
656
657         const char *const git_submodule_helper_usage[] = {
658                 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
659                    "[--reference <repository>] [--name <name>] [--depth <depth>] "
660                    "--url <url> --path <path>"),
661                 NULL
662         };
663
664         argc = parse_options(argc, argv, prefix, module_clone_options,
665                              git_submodule_helper_usage, 0);
666
667         if (argc || !url || !path || !*path)
668                 usage_with_options(git_submodule_helper_usage,
669                                    module_clone_options);
670
671         strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
672         sm_gitdir = absolute_pathdup(sb.buf);
673         strbuf_reset(&sb);
674
675         if (!is_absolute_path(path)) {
676                 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
677                 path = strbuf_detach(&sb, NULL);
678         } else
679                 path = xstrdup(path);
680
681         if (!file_exists(sm_gitdir)) {
682                 if (safe_create_leading_directories_const(sm_gitdir) < 0)
683                         die(_("could not create directory '%s'"), sm_gitdir);
684
685                 prepare_possible_alternates(name, &reference);
686
687                 if (clone_submodule(path, sm_gitdir, url, depth, &reference,
688                                     quiet, progress))
689                         die(_("clone of '%s' into submodule path '%s' failed"),
690                             url, path);
691         } else {
692                 if (require_init && !access(path, X_OK) && !is_empty_dir(path))
693                         die(_("directory not empty: '%s'"), path);
694                 if (safe_create_leading_directories_const(path) < 0)
695                         die(_("could not create directory '%s'"), path);
696                 strbuf_addf(&sb, "%s/index", sm_gitdir);
697                 unlink_or_warn(sb.buf);
698                 strbuf_reset(&sb);
699         }
700
701         /* Connect module worktree and git dir */
702         connect_work_tree_and_git_dir(path, sm_gitdir);
703
704         p = git_pathdup_submodule(path, "config");
705         if (!p)
706                 die(_("could not get submodule directory for '%s'"), path);
707
708         /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
709         git_config_get_string("submodule.alternateLocation", &sm_alternate);
710         if (sm_alternate)
711                 git_config_set_in_file(p, "submodule.alternateLocation",
712                                            sm_alternate);
713         git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
714         if (error_strategy)
715                 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
716                                            error_strategy);
717
718         free(sm_alternate);
719         free(error_strategy);
720
721         strbuf_release(&sb);
722         free(sm_gitdir);
723         free(path);
724         free(p);
725         return 0;
726 }
727
728 struct submodule_update_clone {
729         /* index into 'list', the list of submodules to look into for cloning */
730         int current;
731         struct module_list list;
732         unsigned warn_if_uninitialized : 1;
733
734         /* update parameter passed via commandline */
735         struct submodule_update_strategy update;
736
737         /* configuration parameters which are passed on to the children */
738         int progress;
739         int quiet;
740         int recommend_shallow;
741         struct string_list references;
742         unsigned require_init;
743         const char *depth;
744         const char *recursive_prefix;
745         const char *prefix;
746
747         /* Machine-readable status lines to be consumed by git-submodule.sh */
748         struct string_list projectlines;
749
750         /* If we want to stop as fast as possible and return an error */
751         unsigned quickstop : 1;
752
753         /* failed clones to be retried again */
754         const struct cache_entry **failed_clones;
755         int failed_clones_nr, failed_clones_alloc;
756 };
757 #define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
758         SUBMODULE_UPDATE_STRATEGY_INIT, 0, 0, -1, STRING_LIST_INIT_DUP, 0, \
759         NULL, NULL, NULL, \
760         STRING_LIST_INIT_DUP, 0, NULL, 0, 0}
761
762
763 static void next_submodule_warn_missing(struct submodule_update_clone *suc,
764                 struct strbuf *out, const char *displaypath)
765 {
766         /*
767          * Only mention uninitialized submodules when their
768          * paths have been specified.
769          */
770         if (suc->warn_if_uninitialized) {
771                 strbuf_addf(out,
772                         _("Submodule path '%s' not initialized"),
773                         displaypath);
774                 strbuf_addch(out, '\n');
775                 strbuf_addstr(out,
776                         _("Maybe you want to use 'update --init'?"));
777                 strbuf_addch(out, '\n');
778         }
779 }
780
781 /**
782  * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
783  * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
784  */
785 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
786                                            struct child_process *child,
787                                            struct submodule_update_clone *suc,
788                                            struct strbuf *out)
789 {
790         const struct submodule *sub = NULL;
791         struct strbuf displaypath_sb = STRBUF_INIT;
792         struct strbuf sb = STRBUF_INIT;
793         const char *displaypath = NULL;
794         int needs_cloning = 0;
795
796         if (ce_stage(ce)) {
797                 if (suc->recursive_prefix)
798                         strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
799                 else
800                         strbuf_addstr(&sb, ce->name);
801                 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
802                 strbuf_addch(out, '\n');
803                 goto cleanup;
804         }
805
806         sub = submodule_from_path(null_sha1, ce->name);
807
808         if (suc->recursive_prefix)
809                 displaypath = relative_path(suc->recursive_prefix,
810                                             ce->name, &displaypath_sb);
811         else
812                 displaypath = ce->name;
813
814         if (!sub) {
815                 next_submodule_warn_missing(suc, out, displaypath);
816                 goto cleanup;
817         }
818
819         if (suc->update.type == SM_UPDATE_NONE
820             || (suc->update.type == SM_UPDATE_UNSPECIFIED
821                 && sub->update_strategy.type == SM_UPDATE_NONE)) {
822                 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
823                 strbuf_addch(out, '\n');
824                 goto cleanup;
825         }
826
827         /* Check if the submodule has been initialized. */
828         if (!is_submodule_active(the_repository, ce->name)) {
829                 next_submodule_warn_missing(suc, out, displaypath);
830                 goto cleanup;
831         }
832
833         strbuf_reset(&sb);
834         strbuf_addf(&sb, "%s/.git", ce->name);
835         needs_cloning = !file_exists(sb.buf);
836
837         strbuf_reset(&sb);
838         strbuf_addf(&sb, "%06o %s %d %d\t%s\n", ce->ce_mode,
839                         oid_to_hex(&ce->oid), ce_stage(ce),
840                         needs_cloning, ce->name);
841         string_list_append(&suc->projectlines, sb.buf);
842
843         if (!needs_cloning)
844                 goto cleanup;
845
846         child->git_cmd = 1;
847         child->no_stdin = 1;
848         child->stdout_to_stderr = 1;
849         child->err = -1;
850         argv_array_push(&child->args, "submodule--helper");
851         argv_array_push(&child->args, "clone");
852         if (suc->progress)
853                 argv_array_push(&child->args, "--progress");
854         if (suc->quiet)
855                 argv_array_push(&child->args, "--quiet");
856         if (suc->prefix)
857                 argv_array_pushl(&child->args, "--prefix", suc->prefix, NULL);
858         if (suc->recommend_shallow && sub->recommend_shallow == 1)
859                 argv_array_push(&child->args, "--depth=1");
860         if (suc->require_init)
861                 argv_array_push(&child->args, "--require-init");
862         argv_array_pushl(&child->args, "--path", sub->path, NULL);
863         argv_array_pushl(&child->args, "--name", sub->name, NULL);
864         argv_array_pushl(&child->args, "--url", sub->url, NULL);
865         if (suc->references.nr) {
866                 struct string_list_item *item;
867                 for_each_string_list_item(item, &suc->references)
868                         argv_array_pushl(&child->args, "--reference", item->string, NULL);
869         }
870         if (suc->depth)
871                 argv_array_push(&child->args, suc->depth);
872
873 cleanup:
874         strbuf_reset(&displaypath_sb);
875         strbuf_reset(&sb);
876
877         return needs_cloning;
878 }
879
880 static int update_clone_get_next_task(struct child_process *child,
881                                       struct strbuf *err,
882                                       void *suc_cb,
883                                       void **idx_task_cb)
884 {
885         struct submodule_update_clone *suc = suc_cb;
886         const struct cache_entry *ce;
887         int index;
888
889         for (; suc->current < suc->list.nr; suc->current++) {
890                 ce = suc->list.entries[suc->current];
891                 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
892                         int *p = xmalloc(sizeof(*p));
893                         *p = suc->current;
894                         *idx_task_cb = p;
895                         suc->current++;
896                         return 1;
897                 }
898         }
899
900         /*
901          * The loop above tried cloning each submodule once, now try the
902          * stragglers again, which we can imagine as an extension of the
903          * entry list.
904          */
905         index = suc->current - suc->list.nr;
906         if (index < suc->failed_clones_nr) {
907                 int *p;
908                 ce = suc->failed_clones[index];
909                 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
910                         suc->current ++;
911                         strbuf_addstr(err, "BUG: submodule considered for "
912                                            "cloning, doesn't need cloning "
913                                            "any more?\n");
914                         return 0;
915                 }
916                 p = xmalloc(sizeof(*p));
917                 *p = suc->current;
918                 *idx_task_cb = p;
919                 suc->current ++;
920                 return 1;
921         }
922
923         return 0;
924 }
925
926 static int update_clone_start_failure(struct strbuf *err,
927                                       void *suc_cb,
928                                       void *idx_task_cb)
929 {
930         struct submodule_update_clone *suc = suc_cb;
931         suc->quickstop = 1;
932         return 1;
933 }
934
935 static int update_clone_task_finished(int result,
936                                       struct strbuf *err,
937                                       void *suc_cb,
938                                       void *idx_task_cb)
939 {
940         const struct cache_entry *ce;
941         struct submodule_update_clone *suc = suc_cb;
942
943         int *idxP = idx_task_cb;
944         int idx = *idxP;
945         free(idxP);
946
947         if (!result)
948                 return 0;
949
950         if (idx < suc->list.nr) {
951                 ce  = suc->list.entries[idx];
952                 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
953                             ce->name);
954                 strbuf_addch(err, '\n');
955                 ALLOC_GROW(suc->failed_clones,
956                            suc->failed_clones_nr + 1,
957                            suc->failed_clones_alloc);
958                 suc->failed_clones[suc->failed_clones_nr++] = ce;
959                 return 0;
960         } else {
961                 idx -= suc->list.nr;
962                 ce  = suc->failed_clones[idx];
963                 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
964                             ce->name);
965                 strbuf_addch(err, '\n');
966                 suc->quickstop = 1;
967                 return 1;
968         }
969
970         return 0;
971 }
972
973 static int update_clone(int argc, const char **argv, const char *prefix)
974 {
975         const char *update = NULL;
976         int max_jobs = -1;
977         struct string_list_item *item;
978         struct pathspec pathspec;
979         struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
980
981         struct option module_update_clone_options[] = {
982                 OPT_STRING(0, "prefix", &prefix,
983                            N_("path"),
984                            N_("path into the working tree")),
985                 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
986                            N_("path"),
987                            N_("path into the working tree, across nested "
988                               "submodule boundaries")),
989                 OPT_STRING(0, "update", &update,
990                            N_("string"),
991                            N_("rebase, merge, checkout or none")),
992                 OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
993                            N_("reference repository")),
994                 OPT_STRING(0, "depth", &suc.depth, "<depth>",
995                            N_("Create a shallow clone truncated to the "
996                               "specified number of revisions")),
997                 OPT_INTEGER('j', "jobs", &max_jobs,
998                             N_("parallel jobs")),
999                 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
1000                             N_("whether the initial clone should follow the shallow recommendation")),
1001                 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
1002                 OPT_BOOL(0, "progress", &suc.progress,
1003                             N_("force cloning progress")),
1004                 OPT_BOOL(0, "require-init", &suc.require_init,
1005                            N_("disallow cloning into non-empty directory")),
1006                 OPT_END()
1007         };
1008
1009         const char *const git_submodule_helper_usage[] = {
1010                 N_("git submodule--helper update_clone [--prefix=<path>] [<path>...]"),
1011                 NULL
1012         };
1013         suc.prefix = prefix;
1014
1015         argc = parse_options(argc, argv, prefix, module_update_clone_options,
1016                              git_submodule_helper_usage, 0);
1017
1018         if (update)
1019                 if (parse_submodule_update_strategy(update, &suc.update) < 0)
1020                         die(_("bad value for update parameter"));
1021
1022         if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
1023                 return 1;
1024
1025         if (pathspec.nr)
1026                 suc.warn_if_uninitialized = 1;
1027
1028         /* Overlay the parsed .gitmodules file with .git/config */
1029         gitmodules_config();
1030         git_config(submodule_config, NULL);
1031
1032         if (max_jobs < 0)
1033                 max_jobs = parallel_submodules();
1034
1035         run_processes_parallel(max_jobs,
1036                                update_clone_get_next_task,
1037                                update_clone_start_failure,
1038                                update_clone_task_finished,
1039                                &suc);
1040
1041         /*
1042          * We saved the output and put it out all at once now.
1043          * That means:
1044          * - the listener does not have to interleave their (checkout)
1045          *   work with our fetching.  The writes involved in a
1046          *   checkout involve more straightforward sequential I/O.
1047          * - the listener can avoid doing any work if fetching failed.
1048          */
1049         if (suc.quickstop)
1050                 return 1;
1051
1052         for_each_string_list_item(item, &suc.projectlines)
1053                 fprintf(stdout, "%s", item->string);
1054
1055         return 0;
1056 }
1057
1058 static int resolve_relative_path(int argc, const char **argv, const char *prefix)
1059 {
1060         struct strbuf sb = STRBUF_INIT;
1061         if (argc != 3)
1062                 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
1063
1064         printf("%s", relative_path(argv[1], argv[2], &sb));
1065         strbuf_release(&sb);
1066         return 0;
1067 }
1068
1069 static const char *remote_submodule_branch(const char *path)
1070 {
1071         const struct submodule *sub;
1072         gitmodules_config();
1073         git_config(submodule_config, NULL);
1074
1075         sub = submodule_from_path(null_sha1, path);
1076         if (!sub)
1077                 return NULL;
1078
1079         if (!sub->branch)
1080                 return "master";
1081
1082         if (!strcmp(sub->branch, ".")) {
1083                 unsigned char sha1[20];
1084                 const char *refname = resolve_ref_unsafe("HEAD", 0, sha1, NULL);
1085
1086                 if (!refname)
1087                         die(_("No such ref: %s"), "HEAD");
1088
1089                 /* detached HEAD */
1090                 if (!strcmp(refname, "HEAD"))
1091                         die(_("Submodule (%s) branch configured to inherit "
1092                               "branch from superproject, but the superproject "
1093                               "is not on any branch"), sub->name);
1094
1095                 if (!skip_prefix(refname, "refs/heads/", &refname))
1096                         die(_("Expecting a full ref name, got %s"), refname);
1097                 return refname;
1098         }
1099
1100         return sub->branch;
1101 }
1102
1103 static int resolve_remote_submodule_branch(int argc, const char **argv,
1104                 const char *prefix)
1105 {
1106         const char *ret;
1107         struct strbuf sb = STRBUF_INIT;
1108         if (argc != 2)
1109                 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
1110
1111         ret = remote_submodule_branch(argv[1]);
1112         if (!ret)
1113                 die("submodule %s doesn't exist", argv[1]);
1114
1115         printf("%s", ret);
1116         strbuf_release(&sb);
1117         return 0;
1118 }
1119
1120 static int push_check(int argc, const char **argv, const char *prefix)
1121 {
1122         struct remote *remote;
1123         const char *superproject_head;
1124         char *head;
1125         int detached_head = 0;
1126         struct object_id head_oid;
1127
1128         if (argc < 3)
1129                 die("submodule--helper push-check requires at least 2 arguments");
1130
1131         /*
1132          * superproject's resolved head ref.
1133          * if HEAD then the superproject is in a detached head state, otherwise
1134          * it will be the resolved head ref.
1135          */
1136         superproject_head = argv[1];
1137         argv++;
1138         argc--;
1139         /* Get the submodule's head ref and determine if it is detached */
1140         head = resolve_refdup("HEAD", 0, head_oid.hash, NULL);
1141         if (!head)
1142                 die(_("Failed to resolve HEAD as a valid ref."));
1143         if (!strcmp(head, "HEAD"))
1144                 detached_head = 1;
1145
1146         /*
1147          * The remote must be configured.
1148          * This is to avoid pushing to the exact same URL as the parent.
1149          */
1150         remote = pushremote_get(argv[1]);
1151         if (!remote || remote->origin == REMOTE_UNCONFIGURED)
1152                 die("remote '%s' not configured", argv[1]);
1153
1154         /* Check the refspec */
1155         if (argc > 2) {
1156                 int i, refspec_nr = argc - 2;
1157                 struct ref *local_refs = get_local_heads();
1158                 struct refspec *refspec = parse_push_refspec(refspec_nr,
1159                                                              argv + 2);
1160
1161                 for (i = 0; i < refspec_nr; i++) {
1162                         struct refspec *rs = refspec + i;
1163
1164                         if (rs->pattern || rs->matching)
1165                                 continue;
1166
1167                         /* LHS must match a single ref */
1168                         switch (count_refspec_match(rs->src, local_refs, NULL)) {
1169                         case 1:
1170                                 break;
1171                         case 0:
1172                                 /*
1173                                  * If LHS matches 'HEAD' then we need to ensure
1174                                  * that it matches the same named branch
1175                                  * checked out in the superproject.
1176                                  */
1177                                 if (!strcmp(rs->src, "HEAD")) {
1178                                         if (!detached_head &&
1179                                             !strcmp(head, superproject_head))
1180                                                 break;
1181                                         die("HEAD does not match the named branch in the superproject");
1182                                 }
1183                         default:
1184                                 die("src refspec '%s' must name a ref",
1185                                     rs->src);
1186                         }
1187                 }
1188                 free_refspec(refspec_nr, refspec);
1189         }
1190         free(head);
1191
1192         return 0;
1193 }
1194
1195 static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
1196 {
1197         int i;
1198         struct pathspec pathspec;
1199         struct module_list list = MODULE_LIST_INIT;
1200         unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
1201
1202         struct option embed_gitdir_options[] = {
1203                 OPT_STRING(0, "prefix", &prefix,
1204                            N_("path"),
1205                            N_("path into the working tree")),
1206                 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
1207                         ABSORB_GITDIR_RECURSE_SUBMODULES),
1208                 OPT_END()
1209         };
1210
1211         const char *const git_submodule_helper_usage[] = {
1212                 N_("git submodule--helper embed-git-dir [<path>...]"),
1213                 NULL
1214         };
1215
1216         argc = parse_options(argc, argv, prefix, embed_gitdir_options,
1217                              git_submodule_helper_usage, 0);
1218
1219         gitmodules_config();
1220         git_config(submodule_config, NULL);
1221
1222         if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1223                 return 1;
1224
1225         for (i = 0; i < list.nr; i++)
1226                 absorb_git_dir_into_superproject(prefix,
1227                                 list.entries[i]->name, flags);
1228
1229         return 0;
1230 }
1231
1232 static int is_active(int argc, const char **argv, const char *prefix)
1233 {
1234         if (argc != 2)
1235                 die("submodule--helper is-active takes exactly 1 argument");
1236
1237         gitmodules_config();
1238
1239         return !is_submodule_active(the_repository, argv[1]);
1240 }
1241
1242 /*
1243  * Exit non-zero if any of the submodule names given on the command line is
1244  * invalid. If no names are given, filter stdin to print only valid names
1245  * (which is primarily intended for testing).
1246  */
1247 static int check_name(int argc, const char **argv, const char *prefix)
1248 {
1249         if (argc > 1) {
1250                 while (*++argv) {
1251                         if (check_submodule_name(*argv) < 0)
1252                                 return 1;
1253                 }
1254         } else {
1255                 struct strbuf buf = STRBUF_INIT;
1256                 while (strbuf_getline(&buf, stdin) != EOF) {
1257                         if (!check_submodule_name(buf.buf))
1258                                 printf("%s\n", buf.buf);
1259                 }
1260                 strbuf_release(&buf);
1261         }
1262         return 0;
1263 }
1264
1265 #define SUPPORT_SUPER_PREFIX (1<<0)
1266
1267 struct cmd_struct {
1268         const char *cmd;
1269         int (*fn)(int, const char **, const char *);
1270         unsigned option;
1271 };
1272
1273 static struct cmd_struct commands[] = {
1274         {"list", module_list, 0},
1275         {"name", module_name, 0},
1276         {"clone", module_clone, 0},
1277         {"update-clone", update_clone, 0},
1278         {"relative-path", resolve_relative_path, 0},
1279         {"resolve-relative-url", resolve_relative_url, 0},
1280         {"resolve-relative-url-test", resolve_relative_url_test, 0},
1281         {"init", module_init, SUPPORT_SUPER_PREFIX},
1282         {"remote-branch", resolve_remote_submodule_branch, 0},
1283         {"push-check", push_check, 0},
1284         {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
1285         {"is-active", is_active, 0},
1286         {"check-name", check_name, 0},
1287 };
1288
1289 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
1290 {
1291         int i;
1292         if (argc < 2 || !strcmp(argv[1], "-h"))
1293                 usage("git submodule--helper <command>");
1294
1295         for (i = 0; i < ARRAY_SIZE(commands); i++) {
1296                 if (!strcmp(argv[1], commands[i].cmd)) {
1297                         if (get_super_prefix() &&
1298                             !(commands[i].option & SUPPORT_SUPER_PREFIX))
1299                                 die(_("%s doesn't support --super-prefix"),
1300                                     commands[i].cmd);
1301                         return commands[i].fn(argc - 1, argv + 1, prefix);
1302                 }
1303         }
1304
1305         die(_("'%s' is not a valid submodule--helper "
1306               "subcommand"), argv[1]);
1307 }