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