submodule--helper: do not call utf8_fprintf() unnecessarily
[git/debian.git] / builtin / submodule--helper.c
blob704df874d168cf43aa465448af4b65cc193a3689
1 #include "builtin.h"
2 #include "cache.h"
3 #include "parse-options.h"
4 #include "quote.h"
5 #include "pathspec.h"
6 #include "dir.h"
7 #include "submodule.h"
8 #include "submodule-config.h"
9 #include "string-list.h"
10 #include "run-command.h"
11 #include "remote.h"
12 #include "refs.h"
13 #include "connect.h"
15 static char *get_default_remote(void)
17 char *dest = NULL, *ret;
18 unsigned char sha1[20];
19 struct strbuf sb = STRBUF_INIT;
20 const char *refname = resolve_ref_unsafe("HEAD", 0, sha1, NULL);
22 if (!refname)
23 die(_("No such ref: %s"), "HEAD");
25 /* detached HEAD */
26 if (!strcmp(refname, "HEAD"))
27 return xstrdup("origin");
29 if (!skip_prefix(refname, "refs/heads/", &refname))
30 die(_("Expecting a full ref name, got %s"), refname);
32 strbuf_addf(&sb, "branch.%s.remote", refname);
33 if (git_config_get_string(sb.buf, &dest))
34 ret = xstrdup("origin");
35 else
36 ret = dest;
38 strbuf_release(&sb);
39 return ret;
42 static int starts_with_dot_slash(const char *str)
44 return str[0] == '.' && is_dir_sep(str[1]);
47 static int starts_with_dot_dot_slash(const char *str)
49 return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
53 * Returns 1 if it was the last chop before ':'.
55 static int chop_last_dir(char **remoteurl, int is_relative)
57 char *rfind = find_last_dir_sep(*remoteurl);
58 if (rfind) {
59 *rfind = '\0';
60 return 0;
63 rfind = strrchr(*remoteurl, ':');
64 if (rfind) {
65 *rfind = '\0';
66 return 1;
69 if (is_relative || !strcmp(".", *remoteurl))
70 die(_("cannot strip one component off url '%s'"),
71 *remoteurl);
73 free(*remoteurl);
74 *remoteurl = xstrdup(".");
75 return 0;
79 * The `url` argument is the URL that navigates to the submodule origin
80 * repo. When relative, this URL is relative to the superproject origin
81 * URL repo. The `up_path` argument, if specified, is the relative
82 * path that navigates from the submodule working tree to the superproject
83 * working tree. Returns the origin URL of the submodule.
85 * Return either an absolute URL or filesystem path (if the superproject
86 * origin URL is an absolute URL or filesystem path, respectively) or a
87 * relative file system path (if the superproject origin URL is a relative
88 * file system path).
90 * When the output is a relative file system path, the path is either
91 * relative to the submodule working tree, if up_path is specified, or to
92 * the superproject working tree otherwise.
94 * NEEDSWORK: This works incorrectly on the domain and protocol part.
95 * remote_url url outcome expectation
96 * http://a.com/b ../c http://a.com/c as is
97 * http://a.com/b ../../c http://c error out
98 * http://a.com/b ../../../c http:/c error out
99 * http://a.com/b ../../../../c http:c error out
100 * http://a.com/b ../../../../../c .:c error out
101 * NEEDSWORK: Given how chop_last_dir() works, this function is broken
102 * when a local part has a colon in its path component, too.
104 static char *relative_url(const char *remote_url,
105 const char *url,
106 const char *up_path)
108 int is_relative = 0;
109 int colonsep = 0;
110 char *out;
111 char *remoteurl = xstrdup(remote_url);
112 struct strbuf sb = STRBUF_INIT;
113 size_t len = strlen(remoteurl);
115 if (is_dir_sep(remoteurl[len]))
116 remoteurl[len] = '\0';
118 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
119 is_relative = 0;
120 else {
121 is_relative = 1;
123 * Prepend a './' to ensure all relative
124 * remoteurls start with './' or '../'
126 if (!starts_with_dot_slash(remoteurl) &&
127 !starts_with_dot_dot_slash(remoteurl)) {
128 strbuf_reset(&sb);
129 strbuf_addf(&sb, "./%s", remoteurl);
130 free(remoteurl);
131 remoteurl = strbuf_detach(&sb, NULL);
135 * When the url starts with '../', remove that and the
136 * last directory in remoteurl.
138 while (url) {
139 if (starts_with_dot_dot_slash(url)) {
140 url += 3;
141 colonsep |= chop_last_dir(&remoteurl, is_relative);
142 } else if (starts_with_dot_slash(url))
143 url += 2;
144 else
145 break;
147 strbuf_reset(&sb);
148 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
149 free(remoteurl);
151 if (starts_with_dot_slash(sb.buf))
152 out = xstrdup(sb.buf + 2);
153 else
154 out = xstrdup(sb.buf);
155 strbuf_reset(&sb);
157 if (!up_path || !is_relative)
158 return out;
160 strbuf_addf(&sb, "%s%s", up_path, out);
161 free(out);
162 return strbuf_detach(&sb, NULL);
165 static int resolve_relative_url(int argc, const char **argv, const char *prefix)
167 char *remoteurl = NULL;
168 char *remote = get_default_remote();
169 const char *up_path = NULL;
170 char *res;
171 const char *url;
172 struct strbuf sb = STRBUF_INIT;
174 if (argc != 2 && argc != 3)
175 die("resolve-relative-url only accepts one or two arguments");
177 url = argv[1];
178 strbuf_addf(&sb, "remote.%s.url", remote);
179 free(remote);
181 if (git_config_get_string(sb.buf, &remoteurl))
182 /* the repository is its own authoritative upstream */
183 remoteurl = xgetcwd();
185 if (argc == 3)
186 up_path = argv[2];
188 res = relative_url(remoteurl, url, up_path);
189 puts(res);
190 free(res);
191 free(remoteurl);
192 return 0;
195 static int resolve_relative_url_test(int argc, const char **argv, const char *prefix)
197 char *remoteurl, *res;
198 const char *up_path, *url;
200 if (argc != 4)
201 die("resolve-relative-url-test only accepts three arguments: <up_path> <remoteurl> <url>");
203 up_path = argv[1];
204 remoteurl = xstrdup(argv[2]);
205 url = argv[3];
207 if (!strcmp(up_path, "(null)"))
208 up_path = NULL;
210 res = relative_url(remoteurl, url, up_path);
211 puts(res);
212 free(res);
213 free(remoteurl);
214 return 0;
217 struct module_list {
218 const struct cache_entry **entries;
219 int alloc, nr;
221 #define MODULE_LIST_INIT { NULL, 0, 0 }
223 static int module_list_compute(int argc, const char **argv,
224 const char *prefix,
225 struct pathspec *pathspec,
226 struct module_list *list)
228 int i, result = 0;
229 char *ps_matched = NULL;
230 parse_pathspec(pathspec, 0,
231 PATHSPEC_PREFER_FULL |
232 PATHSPEC_STRIP_SUBMODULE_SLASH_CHEAP,
233 prefix, argv);
235 if (pathspec->nr)
236 ps_matched = xcalloc(pathspec->nr, 1);
238 if (read_cache() < 0)
239 die(_("index file corrupt"));
241 for (i = 0; i < active_nr; i++) {
242 const struct cache_entry *ce = active_cache[i];
244 if (!match_pathspec(pathspec, ce->name, ce_namelen(ce),
245 0, ps_matched, 1) ||
246 !S_ISGITLINK(ce->ce_mode))
247 continue;
249 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
250 list->entries[list->nr++] = ce;
251 while (i + 1 < active_nr &&
252 !strcmp(ce->name, active_cache[i + 1]->name))
254 * Skip entries with the same name in different stages
255 * to make sure an entry is returned only once.
257 i++;
260 if (ps_matched && report_path_error(ps_matched, pathspec, prefix))
261 result = -1;
263 free(ps_matched);
265 return result;
268 static int module_list(int argc, const char **argv, const char *prefix)
270 int i;
271 struct pathspec pathspec;
272 struct module_list list = MODULE_LIST_INIT;
274 struct option module_list_options[] = {
275 OPT_STRING(0, "prefix", &prefix,
276 N_("path"),
277 N_("alternative anchor for relative paths")),
278 OPT_END()
281 const char *const git_submodule_helper_usage[] = {
282 N_("git submodule--helper list [--prefix=<path>] [<path>...]"),
283 NULL
286 argc = parse_options(argc, argv, prefix, module_list_options,
287 git_submodule_helper_usage, 0);
289 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
290 return 1;
292 for (i = 0; i < list.nr; i++) {
293 const struct cache_entry *ce = list.entries[i];
295 if (ce_stage(ce))
296 printf("%06o %s U\t", ce->ce_mode, sha1_to_hex(null_sha1));
297 else
298 printf("%06o %s %d\t", ce->ce_mode, sha1_to_hex(ce->sha1), ce_stage(ce));
300 fprintf(stdout, "%s\n", ce->name);
302 return 0;
305 static void init_submodule(const char *path, const char *prefix, int quiet)
307 const struct submodule *sub;
308 struct strbuf sb = STRBUF_INIT;
309 char *upd = NULL, *url = NULL, *displaypath;
311 /* Only loads from .gitmodules, no overlay with .git/config */
312 gitmodules_config();
314 if (prefix) {
315 strbuf_addf(&sb, "%s%s", prefix, path);
316 displaypath = strbuf_detach(&sb, NULL);
317 } else
318 displaypath = xstrdup(path);
320 sub = submodule_from_path(null_sha1, path);
322 if (!sub)
323 die(_("No url found for submodule path '%s' in .gitmodules"),
324 displaypath);
327 * Copy url setting when it is not set yet.
328 * To look up the url in .git/config, we must not fall back to
329 * .gitmodules, so look it up directly.
331 strbuf_reset(&sb);
332 strbuf_addf(&sb, "submodule.%s.url", sub->name);
333 if (git_config_get_string(sb.buf, &url)) {
334 url = xstrdup(sub->url);
336 if (!url)
337 die(_("No url found for submodule path '%s' in .gitmodules"),
338 displaypath);
340 /* Possibly a url relative to parent */
341 if (starts_with_dot_dot_slash(url) ||
342 starts_with_dot_slash(url)) {
343 char *remoteurl, *relurl;
344 char *remote = get_default_remote();
345 struct strbuf remotesb = STRBUF_INIT;
346 strbuf_addf(&remotesb, "remote.%s.url", remote);
347 free(remote);
349 if (git_config_get_string(remotesb.buf, &remoteurl))
351 * The repository is its own
352 * authoritative upstream
354 remoteurl = xgetcwd();
355 relurl = relative_url(remoteurl, url, NULL);
356 strbuf_release(&remotesb);
357 free(remoteurl);
358 free(url);
359 url = relurl;
362 if (git_config_set_gently(sb.buf, url))
363 die(_("Failed to register url for submodule path '%s'"),
364 displaypath);
365 if (!quiet)
366 fprintf(stderr,
367 _("Submodule '%s' (%s) registered for path '%s'\n"),
368 sub->name, url, displaypath);
371 /* Copy "update" setting when it is not set yet */
372 strbuf_reset(&sb);
373 strbuf_addf(&sb, "submodule.%s.update", sub->name);
374 if (git_config_get_string(sb.buf, &upd) &&
375 sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
376 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
377 fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
378 sub->name);
379 upd = xstrdup("none");
380 } else
381 upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
383 if (git_config_set_gently(sb.buf, upd))
384 die(_("Failed to register update mode for submodule path '%s'"), displaypath);
386 strbuf_release(&sb);
387 free(displaypath);
388 free(url);
389 free(upd);
392 static int module_init(int argc, const char **argv, const char *prefix)
394 struct pathspec pathspec;
395 struct module_list list = MODULE_LIST_INIT;
396 int quiet = 0;
397 int i;
399 struct option module_init_options[] = {
400 OPT_STRING(0, "prefix", &prefix,
401 N_("path"),
402 N_("alternative anchor for relative paths")),
403 OPT__QUIET(&quiet, N_("Suppress output for initializing a submodule")),
404 OPT_END()
407 const char *const git_submodule_helper_usage[] = {
408 N_("git submodule--helper init [<path>]"),
409 NULL
412 argc = parse_options(argc, argv, prefix, module_init_options,
413 git_submodule_helper_usage, 0);
415 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
416 return 1;
418 for (i = 0; i < list.nr; i++)
419 init_submodule(list.entries[i]->name, prefix, quiet);
421 return 0;
424 static int module_name(int argc, const char **argv, const char *prefix)
426 const struct submodule *sub;
428 if (argc != 2)
429 usage(_("git submodule--helper name <path>"));
431 gitmodules_config();
432 sub = submodule_from_path(null_sha1, argv[1]);
434 if (!sub)
435 die(_("no submodule mapping found in .gitmodules for path '%s'"),
436 argv[1]);
438 printf("%s\n", sub->name);
440 return 0;
443 static int clone_submodule(const char *path, const char *gitdir, const char *url,
444 const char *depth, const char *reference, int quiet)
446 struct child_process cp = CHILD_PROCESS_INIT;
448 argv_array_push(&cp.args, "clone");
449 argv_array_push(&cp.args, "--no-checkout");
450 if (quiet)
451 argv_array_push(&cp.args, "--quiet");
452 if (depth && *depth)
453 argv_array_pushl(&cp.args, "--depth", depth, NULL);
454 if (reference && *reference)
455 argv_array_pushl(&cp.args, "--reference", reference, NULL);
456 if (gitdir && *gitdir)
457 argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
459 argv_array_push(&cp.args, url);
460 argv_array_push(&cp.args, path);
462 cp.git_cmd = 1;
463 prepare_submodule_repo_env(&cp.env_array);
464 cp.no_stdin = 1;
466 return run_command(&cp);
469 static int module_clone(int argc, const char **argv, const char *prefix)
471 const char *name = NULL, *url = NULL;
472 const char *reference = NULL, *depth = NULL;
473 int quiet = 0;
474 FILE *submodule_dot_git;
475 char *p, *path = NULL, *sm_gitdir;
476 struct strbuf rel_path = STRBUF_INIT;
477 struct strbuf sb = STRBUF_INIT;
479 struct option module_clone_options[] = {
480 OPT_STRING(0, "prefix", &prefix,
481 N_("path"),
482 N_("alternative anchor for relative paths")),
483 OPT_STRING(0, "path", &path,
484 N_("path"),
485 N_("where the new submodule will be cloned to")),
486 OPT_STRING(0, "name", &name,
487 N_("string"),
488 N_("name of the new submodule")),
489 OPT_STRING(0, "url", &url,
490 N_("string"),
491 N_("url where to clone the submodule from")),
492 OPT_STRING(0, "reference", &reference,
493 N_("string"),
494 N_("reference repository")),
495 OPT_STRING(0, "depth", &depth,
496 N_("string"),
497 N_("depth for shallow clones")),
498 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
499 OPT_END()
502 const char *const git_submodule_helper_usage[] = {
503 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
504 "[--reference <repository>] [--name <name>] [--depth <depth>] "
505 "--url <url> --path <path>"),
506 NULL
509 argc = parse_options(argc, argv, prefix, module_clone_options,
510 git_submodule_helper_usage, 0);
512 if (argc || !url || !path || !*path)
513 usage_with_options(git_submodule_helper_usage,
514 module_clone_options);
516 strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
517 sm_gitdir = xstrdup(absolute_path(sb.buf));
518 strbuf_reset(&sb);
520 if (!is_absolute_path(path)) {
521 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
522 path = strbuf_detach(&sb, NULL);
523 } else
524 path = xstrdup(path);
526 if (!file_exists(sm_gitdir)) {
527 if (safe_create_leading_directories_const(sm_gitdir) < 0)
528 die(_("could not create directory '%s'"), sm_gitdir);
529 if (clone_submodule(path, sm_gitdir, url, depth, reference, quiet))
530 die(_("clone of '%s' into submodule path '%s' failed"),
531 url, path);
532 } else {
533 if (safe_create_leading_directories_const(path) < 0)
534 die(_("could not create directory '%s'"), path);
535 strbuf_addf(&sb, "%s/index", sm_gitdir);
536 unlink_or_warn(sb.buf);
537 strbuf_reset(&sb);
540 /* Write a .git file in the submodule to redirect to the superproject. */
541 strbuf_addf(&sb, "%s/.git", path);
542 if (safe_create_leading_directories_const(sb.buf) < 0)
543 die(_("could not create leading directories of '%s'"), sb.buf);
544 submodule_dot_git = fopen(sb.buf, "w");
545 if (!submodule_dot_git)
546 die_errno(_("cannot open file '%s'"), sb.buf);
548 fprintf_or_die(submodule_dot_git, "gitdir: %s\n",
549 relative_path(sm_gitdir, path, &rel_path));
550 if (fclose(submodule_dot_git))
551 die(_("could not close file %s"), sb.buf);
552 strbuf_reset(&sb);
553 strbuf_reset(&rel_path);
555 /* Redirect the worktree of the submodule in the superproject's config */
556 p = git_pathdup_submodule(path, "config");
557 if (!p)
558 die(_("could not get submodule directory for '%s'"), path);
559 git_config_set_in_file(p, "core.worktree",
560 relative_path(path, sm_gitdir, &rel_path));
561 strbuf_release(&sb);
562 strbuf_release(&rel_path);
563 free(sm_gitdir);
564 free(path);
565 free(p);
566 return 0;
569 struct submodule_update_clone {
570 /* index into 'list', the list of submodules to look into for cloning */
571 int current;
572 struct module_list list;
573 unsigned warn_if_uninitialized : 1;
575 /* update parameter passed via commandline */
576 struct submodule_update_strategy update;
578 /* configuration parameters which are passed on to the children */
579 int quiet;
580 int recommend_shallow;
581 const char *reference;
582 const char *depth;
583 const char *recursive_prefix;
584 const char *prefix;
586 /* Machine-readable status lines to be consumed by git-submodule.sh */
587 struct string_list projectlines;
589 /* If we want to stop as fast as possible and return an error */
590 unsigned quickstop : 1;
592 /* failed clones to be retried again */
593 const struct cache_entry **failed_clones;
594 int failed_clones_nr, failed_clones_alloc;
596 #define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
597 SUBMODULE_UPDATE_STRATEGY_INIT, 0, -1, NULL, NULL, NULL, NULL, \
598 STRING_LIST_INIT_DUP, 0, NULL, 0, 0}
601 static void next_submodule_warn_missing(struct submodule_update_clone *suc,
602 struct strbuf *out, const char *displaypath)
605 * Only mention uninitialized submodules when their
606 * paths have been specified.
608 if (suc->warn_if_uninitialized) {
609 strbuf_addf(out,
610 _("Submodule path '%s' not initialized"),
611 displaypath);
612 strbuf_addch(out, '\n');
613 strbuf_addstr(out,
614 _("Maybe you want to use 'update --init'?"));
615 strbuf_addch(out, '\n');
620 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
621 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
623 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
624 struct child_process *child,
625 struct submodule_update_clone *suc,
626 struct strbuf *out)
628 const struct submodule *sub = NULL;
629 struct strbuf displaypath_sb = STRBUF_INIT;
630 struct strbuf sb = STRBUF_INIT;
631 const char *displaypath = NULL;
632 char *url = NULL;
633 int needs_cloning = 0;
635 if (ce_stage(ce)) {
636 if (suc->recursive_prefix)
637 strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
638 else
639 strbuf_addstr(&sb, ce->name);
640 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
641 strbuf_addch(out, '\n');
642 goto cleanup;
645 sub = submodule_from_path(null_sha1, ce->name);
647 if (suc->recursive_prefix)
648 displaypath = relative_path(suc->recursive_prefix,
649 ce->name, &displaypath_sb);
650 else
651 displaypath = ce->name;
653 if (!sub) {
654 next_submodule_warn_missing(suc, out, displaypath);
655 goto cleanup;
658 if (suc->update.type == SM_UPDATE_NONE
659 || (suc->update.type == SM_UPDATE_UNSPECIFIED
660 && sub->update_strategy.type == SM_UPDATE_NONE)) {
661 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
662 strbuf_addch(out, '\n');
663 goto cleanup;
667 * Looking up the url in .git/config.
668 * We must not fall back to .gitmodules as we only want
669 * to process configured submodules.
671 strbuf_reset(&sb);
672 strbuf_addf(&sb, "submodule.%s.url", sub->name);
673 git_config_get_string(sb.buf, &url);
674 if (!url) {
675 next_submodule_warn_missing(suc, out, displaypath);
676 goto cleanup;
679 strbuf_reset(&sb);
680 strbuf_addf(&sb, "%s/.git", ce->name);
681 needs_cloning = !file_exists(sb.buf);
683 strbuf_reset(&sb);
684 strbuf_addf(&sb, "%06o %s %d %d\t%s\n", ce->ce_mode,
685 sha1_to_hex(ce->sha1), ce_stage(ce),
686 needs_cloning, ce->name);
687 string_list_append(&suc->projectlines, sb.buf);
689 if (!needs_cloning)
690 goto cleanup;
692 child->git_cmd = 1;
693 child->no_stdin = 1;
694 child->stdout_to_stderr = 1;
695 child->err = -1;
696 argv_array_push(&child->args, "submodule--helper");
697 argv_array_push(&child->args, "clone");
698 if (suc->quiet)
699 argv_array_push(&child->args, "--quiet");
700 if (suc->prefix)
701 argv_array_pushl(&child->args, "--prefix", suc->prefix, NULL);
702 if (suc->recommend_shallow && sub->recommend_shallow == 1)
703 argv_array_push(&child->args, "--depth=1");
704 argv_array_pushl(&child->args, "--path", sub->path, NULL);
705 argv_array_pushl(&child->args, "--name", sub->name, NULL);
706 argv_array_pushl(&child->args, "--url", url, NULL);
707 if (suc->reference)
708 argv_array_push(&child->args, suc->reference);
709 if (suc->depth)
710 argv_array_push(&child->args, suc->depth);
712 cleanup:
713 free(url);
714 strbuf_reset(&displaypath_sb);
715 strbuf_reset(&sb);
717 return needs_cloning;
720 static int update_clone_get_next_task(struct child_process *child,
721 struct strbuf *err,
722 void *suc_cb,
723 void **idx_task_cb)
725 struct submodule_update_clone *suc = suc_cb;
726 const struct cache_entry *ce;
727 int index;
729 for (; suc->current < suc->list.nr; suc->current++) {
730 ce = suc->list.entries[suc->current];
731 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
732 int *p = xmalloc(sizeof(*p));
733 *p = suc->current;
734 *idx_task_cb = p;
735 suc->current++;
736 return 1;
741 * The loop above tried cloning each submodule once, now try the
742 * stragglers again, which we can imagine as an extension of the
743 * entry list.
745 index = suc->current - suc->list.nr;
746 if (index < suc->failed_clones_nr) {
747 int *p;
748 ce = suc->failed_clones[index];
749 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
750 suc->current ++;
751 strbuf_addstr(err, "BUG: submodule considered for "
752 "cloning, doesn't need cloning "
753 "any more?\n");
754 return 0;
756 p = xmalloc(sizeof(*p));
757 *p = suc->current;
758 *idx_task_cb = p;
759 suc->current ++;
760 return 1;
763 return 0;
766 static int update_clone_start_failure(struct strbuf *err,
767 void *suc_cb,
768 void *idx_task_cb)
770 struct submodule_update_clone *suc = suc_cb;
771 suc->quickstop = 1;
772 return 1;
775 static int update_clone_task_finished(int result,
776 struct strbuf *err,
777 void *suc_cb,
778 void *idx_task_cb)
780 const struct cache_entry *ce;
781 struct submodule_update_clone *suc = suc_cb;
783 int *idxP = *(int**)idx_task_cb;
784 int idx = *idxP;
785 free(idxP);
787 if (!result)
788 return 0;
790 if (idx < suc->list.nr) {
791 ce = suc->list.entries[idx];
792 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
793 ce->name);
794 strbuf_addch(err, '\n');
795 ALLOC_GROW(suc->failed_clones,
796 suc->failed_clones_nr + 1,
797 suc->failed_clones_alloc);
798 suc->failed_clones[suc->failed_clones_nr++] = ce;
799 return 0;
800 } else {
801 idx -= suc->list.nr;
802 ce = suc->failed_clones[idx];
803 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
804 ce->name);
805 strbuf_addch(err, '\n');
806 suc->quickstop = 1;
807 return 1;
810 return 0;
813 static int update_clone(int argc, const char **argv, const char *prefix)
815 const char *update = NULL;
816 int max_jobs = -1;
817 struct string_list_item *item;
818 struct pathspec pathspec;
819 struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
821 struct option module_update_clone_options[] = {
822 OPT_STRING(0, "prefix", &prefix,
823 N_("path"),
824 N_("path into the working tree")),
825 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
826 N_("path"),
827 N_("path into the working tree, across nested "
828 "submodule boundaries")),
829 OPT_STRING(0, "update", &update,
830 N_("string"),
831 N_("rebase, merge, checkout or none")),
832 OPT_STRING(0, "reference", &suc.reference, N_("repo"),
833 N_("reference repository")),
834 OPT_STRING(0, "depth", &suc.depth, "<depth>",
835 N_("Create a shallow clone truncated to the "
836 "specified number of revisions")),
837 OPT_INTEGER('j', "jobs", &max_jobs,
838 N_("parallel jobs")),
839 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
840 N_("whether the initial clone should follow the shallow recommendation")),
841 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
842 OPT_END()
845 const char *const git_submodule_helper_usage[] = {
846 N_("git submodule--helper update_clone [--prefix=<path>] [<path>...]"),
847 NULL
849 suc.prefix = prefix;
851 argc = parse_options(argc, argv, prefix, module_update_clone_options,
852 git_submodule_helper_usage, 0);
854 if (update)
855 if (parse_submodule_update_strategy(update, &suc.update) < 0)
856 die(_("bad value for update parameter"));
858 if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
859 return 1;
861 if (pathspec.nr)
862 suc.warn_if_uninitialized = 1;
864 /* Overlay the parsed .gitmodules file with .git/config */
865 gitmodules_config();
866 git_config(submodule_config, NULL);
868 if (max_jobs < 0)
869 max_jobs = parallel_submodules();
871 run_processes_parallel(max_jobs,
872 update_clone_get_next_task,
873 update_clone_start_failure,
874 update_clone_task_finished,
875 &suc);
878 * We saved the output and put it out all at once now.
879 * That means:
880 * - the listener does not have to interleave their (checkout)
881 * work with our fetching. The writes involved in a
882 * checkout involve more straightforward sequential I/O.
883 * - the listener can avoid doing any work if fetching failed.
885 if (suc.quickstop)
886 return 1;
888 for_each_string_list_item(item, &suc.projectlines)
889 fprintf(stdout, "%s", item->string);
891 return 0;
894 static int resolve_relative_path(int argc, const char **argv, const char *prefix)
896 struct strbuf sb = STRBUF_INIT;
897 if (argc != 3)
898 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
900 printf("%s", relative_path(argv[1], argv[2], &sb));
901 strbuf_release(&sb);
902 return 0;
905 static const char *remote_submodule_branch(const char *path)
907 const struct submodule *sub;
908 gitmodules_config();
909 git_config(submodule_config, NULL);
911 sub = submodule_from_path(null_sha1, path);
912 if (!sub)
913 return NULL;
915 if (!sub->branch)
916 return "master";
918 if (!strcmp(sub->branch, ".")) {
919 unsigned char sha1[20];
920 const char *refname = resolve_ref_unsafe("HEAD", 0, sha1, NULL);
922 if (!refname)
923 die(_("No such ref: %s"), "HEAD");
925 /* detached HEAD */
926 if (!strcmp(refname, "HEAD"))
927 die(_("Submodule (%s) branch configured to inherit "
928 "branch from superproject, but the superproject "
929 "is not on any branch"), sub->name);
931 if (!skip_prefix(refname, "refs/heads/", &refname))
932 die(_("Expecting a full ref name, got %s"), refname);
933 return refname;
936 return sub->branch;
939 static int resolve_remote_submodule_branch(int argc, const char **argv,
940 const char *prefix)
942 const char *ret;
943 struct strbuf sb = STRBUF_INIT;
944 if (argc != 2)
945 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
947 ret = remote_submodule_branch(argv[1]);
948 if (!ret)
949 die("submodule %s doesn't exist", argv[1]);
951 printf("%s", ret);
952 strbuf_release(&sb);
953 return 0;
956 struct cmd_struct {
957 const char *cmd;
958 int (*fn)(int, const char **, const char *);
961 static struct cmd_struct commands[] = {
962 {"list", module_list},
963 {"name", module_name},
964 {"clone", module_clone},
965 {"update-clone", update_clone},
966 {"relative-path", resolve_relative_path},
967 {"resolve-relative-url", resolve_relative_url},
968 {"resolve-relative-url-test", resolve_relative_url_test},
969 {"init", module_init},
970 {"remote-branch", resolve_remote_submodule_branch}
973 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
975 int i;
976 if (argc < 2)
977 die(_("submodule--helper subcommand must be "
978 "called with a subcommand"));
980 for (i = 0; i < ARRAY_SIZE(commands); i++)
981 if (!strcmp(argv[1], commands[i].cmd))
982 return commands[i].fn(argc - 1, argv + 1, prefix);
984 die(_("'%s' is not a valid submodule--helper "
985 "subcommand"), argv[1]);