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