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