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