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