]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/submodule--helper.c
Merge branch 'gc/branch-recurse-submodules'
[thirdparty/git.git] / builtin / submodule--helper.c
1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
2 #include "builtin.h"
3 #include "repository.h"
4 #include "cache.h"
5 #include "config.h"
6 #include "parse-options.h"
7 #include "quote.h"
8 #include "pathspec.h"
9 #include "dir.h"
10 #include "submodule.h"
11 #include "submodule-config.h"
12 #include "string-list.h"
13 #include "run-command.h"
14 #include "remote.h"
15 #include "refs.h"
16 #include "refspec.h"
17 #include "connect.h"
18 #include "revision.h"
19 #include "diffcore.h"
20 #include "diff.h"
21 #include "object-store.h"
22 #include "advice.h"
23 #include "branch.h"
24
25 #define OPT_QUIET (1 << 0)
26 #define OPT_CACHED (1 << 1)
27 #define OPT_RECURSIVE (1 << 2)
28 #define OPT_FORCE (1 << 3)
29
30 typedef void (*each_submodule_fn)(const struct cache_entry *list_item,
31 void *cb_data);
32
33 static char *get_default_remote(void)
34 {
35 char *dest = NULL, *ret;
36 struct strbuf sb = STRBUF_INIT;
37 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
38
39 if (!refname)
40 die(_("No such ref: %s"), "HEAD");
41
42 /* detached HEAD */
43 if (!strcmp(refname, "HEAD"))
44 return xstrdup("origin");
45
46 if (!skip_prefix(refname, "refs/heads/", &refname))
47 die(_("Expecting a full ref name, got %s"), refname);
48
49 strbuf_addf(&sb, "branch.%s.remote", refname);
50 if (git_config_get_string(sb.buf, &dest))
51 ret = xstrdup("origin");
52 else
53 ret = dest;
54
55 strbuf_release(&sb);
56 return ret;
57 }
58
59 static int print_default_remote(int argc, const char **argv, const char *prefix)
60 {
61 char *remote;
62
63 if (argc != 1)
64 die(_("submodule--helper print-default-remote takes no arguments"));
65
66 remote = get_default_remote();
67 if (remote)
68 printf("%s\n", remote);
69
70 free(remote);
71 return 0;
72 }
73
74 static int starts_with_dot_slash(const char *str)
75 {
76 return str[0] == '.' && is_dir_sep(str[1]);
77 }
78
79 static int starts_with_dot_dot_slash(const char *str)
80 {
81 return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
82 }
83
84 /*
85 * Returns 1 if it was the last chop before ':'.
86 */
87 static int chop_last_dir(char **remoteurl, int is_relative)
88 {
89 char *rfind = find_last_dir_sep(*remoteurl);
90 if (rfind) {
91 *rfind = '\0';
92 return 0;
93 }
94
95 rfind = strrchr(*remoteurl, ':');
96 if (rfind) {
97 *rfind = '\0';
98 return 1;
99 }
100
101 if (is_relative || !strcmp(".", *remoteurl))
102 die(_("cannot strip one component off url '%s'"),
103 *remoteurl);
104
105 free(*remoteurl);
106 *remoteurl = xstrdup(".");
107 return 0;
108 }
109
110 /*
111 * The `url` argument is the URL that navigates to the submodule origin
112 * repo. When relative, this URL is relative to the superproject origin
113 * URL repo. The `up_path` argument, if specified, is the relative
114 * path that navigates from the submodule working tree to the superproject
115 * working tree. Returns the origin URL of the submodule.
116 *
117 * Return either an absolute URL or filesystem path (if the superproject
118 * origin URL is an absolute URL or filesystem path, respectively) or a
119 * relative file system path (if the superproject origin URL is a relative
120 * file system path).
121 *
122 * When the output is a relative file system path, the path is either
123 * relative to the submodule working tree, if up_path is specified, or to
124 * the superproject working tree otherwise.
125 *
126 * NEEDSWORK: This works incorrectly on the domain and protocol part.
127 * remote_url url outcome expectation
128 * http://a.com/b ../c http://a.com/c as is
129 * http://a.com/b/ ../c http://a.com/c same as previous line, but
130 * ignore trailing slash in url
131 * http://a.com/b ../../c http://c error out
132 * http://a.com/b ../../../c http:/c error out
133 * http://a.com/b ../../../../c http:c error out
134 * http://a.com/b ../../../../../c .:c error out
135 * NEEDSWORK: Given how chop_last_dir() works, this function is broken
136 * when a local part has a colon in its path component, too.
137 */
138 static char *relative_url(const char *remote_url,
139 const char *url,
140 const char *up_path)
141 {
142 int is_relative = 0;
143 int colonsep = 0;
144 char *out;
145 char *remoteurl = xstrdup(remote_url);
146 struct strbuf sb = STRBUF_INIT;
147 size_t len = strlen(remoteurl);
148
149 if (is_dir_sep(remoteurl[len-1]))
150 remoteurl[len-1] = '\0';
151
152 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
153 is_relative = 0;
154 else {
155 is_relative = 1;
156 /*
157 * Prepend a './' to ensure all relative
158 * remoteurls start with './' or '../'
159 */
160 if (!starts_with_dot_slash(remoteurl) &&
161 !starts_with_dot_dot_slash(remoteurl)) {
162 strbuf_reset(&sb);
163 strbuf_addf(&sb, "./%s", remoteurl);
164 free(remoteurl);
165 remoteurl = strbuf_detach(&sb, NULL);
166 }
167 }
168 /*
169 * When the url starts with '../', remove that and the
170 * last directory in remoteurl.
171 */
172 while (url) {
173 if (starts_with_dot_dot_slash(url)) {
174 url += 3;
175 colonsep |= chop_last_dir(&remoteurl, is_relative);
176 } else if (starts_with_dot_slash(url))
177 url += 2;
178 else
179 break;
180 }
181 strbuf_reset(&sb);
182 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
183 if (ends_with(url, "/"))
184 strbuf_setlen(&sb, sb.len - 1);
185 free(remoteurl);
186
187 if (starts_with_dot_slash(sb.buf))
188 out = xstrdup(sb.buf + 2);
189 else
190 out = xstrdup(sb.buf);
191
192 if (!up_path || !is_relative) {
193 strbuf_release(&sb);
194 return out;
195 }
196
197 strbuf_reset(&sb);
198 strbuf_addf(&sb, "%s%s", up_path, out);
199 free(out);
200 return strbuf_detach(&sb, NULL);
201 }
202
203 static char *resolve_relative_url(const char *rel_url, const char *up_path, int quiet)
204 {
205 char *remoteurl, *resolved_url;
206 char *remote = get_default_remote();
207 struct strbuf remotesb = STRBUF_INIT;
208
209 strbuf_addf(&remotesb, "remote.%s.url", remote);
210 if (git_config_get_string(remotesb.buf, &remoteurl)) {
211 if (!quiet)
212 warning(_("could not look up configuration '%s'. "
213 "Assuming this repository is its own "
214 "authoritative upstream."),
215 remotesb.buf);
216 remoteurl = xgetcwd();
217 }
218 resolved_url = relative_url(remoteurl, rel_url, up_path);
219
220 free(remote);
221 free(remoteurl);
222 strbuf_release(&remotesb);
223
224 return resolved_url;
225 }
226
227 static int resolve_relative_url_test(int argc, const char **argv, const char *prefix)
228 {
229 char *remoteurl, *res;
230 const char *up_path, *url;
231
232 if (argc != 4)
233 die("resolve-relative-url-test only accepts three arguments: <up_path> <remoteurl> <url>");
234
235 up_path = argv[1];
236 remoteurl = xstrdup(argv[2]);
237 url = argv[3];
238
239 if (!strcmp(up_path, "(null)"))
240 up_path = NULL;
241
242 res = relative_url(remoteurl, url, up_path);
243 puts(res);
244 free(res);
245 free(remoteurl);
246 return 0;
247 }
248
249 /* the result should be freed by the caller. */
250 static char *get_submodule_displaypath(const char *path, const char *prefix)
251 {
252 const char *super_prefix = get_super_prefix();
253
254 if (prefix && super_prefix) {
255 BUG("cannot have prefix '%s' and superprefix '%s'",
256 prefix, super_prefix);
257 } else if (prefix) {
258 struct strbuf sb = STRBUF_INIT;
259 char *displaypath = xstrdup(relative_path(path, prefix, &sb));
260 strbuf_release(&sb);
261 return displaypath;
262 } else if (super_prefix) {
263 return xstrfmt("%s%s", super_prefix, path);
264 } else {
265 return xstrdup(path);
266 }
267 }
268
269 static char *compute_rev_name(const char *sub_path, const char* object_id)
270 {
271 struct strbuf sb = STRBUF_INIT;
272 const char ***d;
273
274 static const char *describe_bare[] = { NULL };
275
276 static const char *describe_tags[] = { "--tags", NULL };
277
278 static const char *describe_contains[] = { "--contains", NULL };
279
280 static const char *describe_all_always[] = { "--all", "--always", NULL };
281
282 static const char **describe_argv[] = { describe_bare, describe_tags,
283 describe_contains,
284 describe_all_always, NULL };
285
286 for (d = describe_argv; *d; d++) {
287 struct child_process cp = CHILD_PROCESS_INIT;
288 prepare_submodule_repo_env(&cp.env_array);
289 cp.dir = sub_path;
290 cp.git_cmd = 1;
291 cp.no_stderr = 1;
292
293 strvec_push(&cp.args, "describe");
294 strvec_pushv(&cp.args, *d);
295 strvec_push(&cp.args, object_id);
296
297 if (!capture_command(&cp, &sb, 0)) {
298 strbuf_strip_suffix(&sb, "\n");
299 return strbuf_detach(&sb, NULL);
300 }
301 }
302
303 strbuf_release(&sb);
304 return NULL;
305 }
306
307 struct module_list {
308 const struct cache_entry **entries;
309 int alloc, nr;
310 };
311 #define MODULE_LIST_INIT { 0 }
312
313 static int module_list_compute(int argc, const char **argv,
314 const char *prefix,
315 struct pathspec *pathspec,
316 struct module_list *list)
317 {
318 int i, result = 0;
319 char *ps_matched = NULL;
320 parse_pathspec(pathspec, 0,
321 PATHSPEC_PREFER_FULL,
322 prefix, argv);
323
324 if (pathspec->nr)
325 ps_matched = xcalloc(pathspec->nr, 1);
326
327 if (read_cache() < 0)
328 die(_("index file corrupt"));
329
330 for (i = 0; i < active_nr; i++) {
331 const struct cache_entry *ce = active_cache[i];
332
333 if (!match_pathspec(&the_index, pathspec, ce->name, ce_namelen(ce),
334 0, ps_matched, 1) ||
335 !S_ISGITLINK(ce->ce_mode))
336 continue;
337
338 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
339 list->entries[list->nr++] = ce;
340 while (i + 1 < active_nr &&
341 !strcmp(ce->name, active_cache[i + 1]->name))
342 /*
343 * Skip entries with the same name in different stages
344 * to make sure an entry is returned only once.
345 */
346 i++;
347 }
348
349 if (ps_matched && report_path_error(ps_matched, pathspec))
350 result = -1;
351
352 free(ps_matched);
353
354 return result;
355 }
356
357 static void module_list_active(struct module_list *list)
358 {
359 int i;
360 struct module_list active_modules = MODULE_LIST_INIT;
361
362 for (i = 0; i < list->nr; i++) {
363 const struct cache_entry *ce = list->entries[i];
364
365 if (!is_submodule_active(the_repository, ce->name))
366 continue;
367
368 ALLOC_GROW(active_modules.entries,
369 active_modules.nr + 1,
370 active_modules.alloc);
371 active_modules.entries[active_modules.nr++] = ce;
372 }
373
374 free(list->entries);
375 *list = active_modules;
376 }
377
378 static char *get_up_path(const char *path)
379 {
380 int i;
381 struct strbuf sb = STRBUF_INIT;
382
383 for (i = count_slashes(path); i; i--)
384 strbuf_addstr(&sb, "../");
385
386 /*
387 * Check if 'path' ends with slash or not
388 * for having the same output for dir/sub_dir
389 * and dir/sub_dir/
390 */
391 if (!is_dir_sep(path[strlen(path) - 1]))
392 strbuf_addstr(&sb, "../");
393
394 return strbuf_detach(&sb, NULL);
395 }
396
397 static int module_list(int argc, const char **argv, const char *prefix)
398 {
399 int i;
400 struct pathspec pathspec;
401 struct module_list list = MODULE_LIST_INIT;
402
403 struct option module_list_options[] = {
404 OPT_STRING(0, "prefix", &prefix,
405 N_("path"),
406 N_("alternative anchor for relative paths")),
407 OPT_END()
408 };
409
410 const char *const git_submodule_helper_usage[] = {
411 N_("git submodule--helper list [--prefix=<path>] [<path>...]"),
412 NULL
413 };
414
415 argc = parse_options(argc, argv, prefix, module_list_options,
416 git_submodule_helper_usage, 0);
417
418 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
419 return 1;
420
421 for (i = 0; i < list.nr; i++) {
422 const struct cache_entry *ce = list.entries[i];
423
424 if (ce_stage(ce))
425 printf("%06o %s U\t", ce->ce_mode,
426 oid_to_hex(null_oid()));
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 foreach_cb {
445 int argc;
446 const char **argv;
447 const char *prefix;
448 int quiet;
449 int recursive;
450 };
451 #define FOREACH_CB_INIT { 0 }
452
453 static void runcommand_in_submodule_cb(const struct cache_entry *list_item,
454 void *cb_data)
455 {
456 struct foreach_cb *info = cb_data;
457 const char *path = list_item->name;
458 const struct object_id *ce_oid = &list_item->oid;
459
460 const struct submodule *sub;
461 struct child_process cp = CHILD_PROCESS_INIT;
462 char *displaypath;
463
464 displaypath = get_submodule_displaypath(path, info->prefix);
465
466 sub = submodule_from_path(the_repository, null_oid(), path);
467
468 if (!sub)
469 die(_("No url found for submodule path '%s' in .gitmodules"),
470 displaypath);
471
472 if (!is_submodule_populated_gently(path, NULL))
473 goto cleanup;
474
475 prepare_submodule_repo_env(&cp.env_array);
476
477 /*
478 * For the purpose of executing <command> in the submodule,
479 * separate shell is used for the purpose of running the
480 * child process.
481 */
482 cp.use_shell = 1;
483 cp.dir = path;
484
485 /*
486 * NEEDSWORK: the command currently has access to the variables $name,
487 * $sm_path, $displaypath, $sha1 and $toplevel only when the command
488 * contains a single argument. This is done for maintaining a faithful
489 * translation from shell script.
490 */
491 if (info->argc == 1) {
492 char *toplevel = xgetcwd();
493 struct strbuf sb = STRBUF_INIT;
494
495 strvec_pushf(&cp.env_array, "name=%s", sub->name);
496 strvec_pushf(&cp.env_array, "sm_path=%s", path);
497 strvec_pushf(&cp.env_array, "displaypath=%s", displaypath);
498 strvec_pushf(&cp.env_array, "sha1=%s",
499 oid_to_hex(ce_oid));
500 strvec_pushf(&cp.env_array, "toplevel=%s", toplevel);
501
502 /*
503 * Since the path variable was accessible from the script
504 * before porting, it is also made available after porting.
505 * The environment variable "PATH" has a very special purpose
506 * on windows. And since environment variables are
507 * case-insensitive in windows, it interferes with the
508 * existing PATH variable. Hence, to avoid that, we expose
509 * path via the args strvec and not via env_array.
510 */
511 sq_quote_buf(&sb, path);
512 strvec_pushf(&cp.args, "path=%s; %s",
513 sb.buf, info->argv[0]);
514 strbuf_release(&sb);
515 free(toplevel);
516 } else {
517 strvec_pushv(&cp.args, info->argv);
518 }
519
520 if (!info->quiet)
521 printf(_("Entering '%s'\n"), displaypath);
522
523 if (info->argv[0] && run_command(&cp))
524 die(_("run_command returned non-zero status for %s\n."),
525 displaypath);
526
527 if (info->recursive) {
528 struct child_process cpr = CHILD_PROCESS_INIT;
529
530 cpr.git_cmd = 1;
531 cpr.dir = path;
532 prepare_submodule_repo_env(&cpr.env_array);
533
534 strvec_pushl(&cpr.args, "--super-prefix", NULL);
535 strvec_pushf(&cpr.args, "%s/", displaypath);
536 strvec_pushl(&cpr.args, "submodule--helper", "foreach", "--recursive",
537 NULL);
538
539 if (info->quiet)
540 strvec_push(&cpr.args, "--quiet");
541
542 strvec_push(&cpr.args, "--");
543 strvec_pushv(&cpr.args, info->argv);
544
545 if (run_command(&cpr))
546 die(_("run_command returned non-zero status while "
547 "recursing in the nested submodules of %s\n."),
548 displaypath);
549 }
550
551 cleanup:
552 free(displaypath);
553 }
554
555 static int module_foreach(int argc, const char **argv, const char *prefix)
556 {
557 struct foreach_cb info = FOREACH_CB_INIT;
558 struct pathspec pathspec;
559 struct module_list list = MODULE_LIST_INIT;
560
561 struct option module_foreach_options[] = {
562 OPT__QUIET(&info.quiet, N_("suppress output of entering each submodule command")),
563 OPT_BOOL(0, "recursive", &info.recursive,
564 N_("recurse into nested submodules")),
565 OPT_END()
566 };
567
568 const char *const git_submodule_helper_usage[] = {
569 N_("git submodule--helper foreach [--quiet] [--recursive] [--] <command>"),
570 NULL
571 };
572
573 argc = parse_options(argc, argv, prefix, module_foreach_options,
574 git_submodule_helper_usage, 0);
575
576 if (module_list_compute(0, NULL, prefix, &pathspec, &list) < 0)
577 return 1;
578
579 info.argc = argc;
580 info.argv = argv;
581 info.prefix = prefix;
582
583 for_each_listed_submodule(&list, runcommand_in_submodule_cb, &info);
584
585 return 0;
586 }
587
588 struct init_cb {
589 const char *prefix;
590 unsigned int flags;
591 };
592 #define INIT_CB_INIT { 0 }
593
594 static void init_submodule(const char *path, const char *prefix,
595 unsigned int flags)
596 {
597 const struct submodule *sub;
598 struct strbuf sb = STRBUF_INIT;
599 char *upd = NULL, *url = NULL, *displaypath;
600
601 displaypath = get_submodule_displaypath(path, prefix);
602
603 sub = submodule_from_path(the_repository, null_oid(), path);
604
605 if (!sub)
606 die(_("No url found for submodule path '%s' in .gitmodules"),
607 displaypath);
608
609 /*
610 * NEEDSWORK: In a multi-working-tree world, this needs to be
611 * set in the per-worktree config.
612 *
613 * Set active flag for the submodule being initialized
614 */
615 if (!is_submodule_active(the_repository, path)) {
616 strbuf_addf(&sb, "submodule.%s.active", sub->name);
617 git_config_set_gently(sb.buf, "true");
618 strbuf_reset(&sb);
619 }
620
621 /*
622 * Copy url setting when it is not set yet.
623 * To look up the url in .git/config, we must not fall back to
624 * .gitmodules, so look it up directly.
625 */
626 strbuf_addf(&sb, "submodule.%s.url", sub->name);
627 if (git_config_get_string(sb.buf, &url)) {
628 if (!sub->url)
629 die(_("No url found for submodule path '%s' in .gitmodules"),
630 displaypath);
631
632 url = xstrdup(sub->url);
633
634 /* Possibly a url relative to parent */
635 if (starts_with_dot_dot_slash(url) ||
636 starts_with_dot_slash(url)) {
637 char *oldurl = url;
638 url = resolve_relative_url(oldurl, NULL, 0);
639 free(oldurl);
640 }
641
642 if (git_config_set_gently(sb.buf, url))
643 die(_("Failed to register url for submodule path '%s'"),
644 displaypath);
645 if (!(flags & OPT_QUIET))
646 fprintf(stderr,
647 _("Submodule '%s' (%s) registered for path '%s'\n"),
648 sub->name, url, displaypath);
649 }
650 strbuf_reset(&sb);
651
652 /* Copy "update" setting when it is not set yet */
653 strbuf_addf(&sb, "submodule.%s.update", sub->name);
654 if (git_config_get_string(sb.buf, &upd) &&
655 sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
656 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
657 fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
658 sub->name);
659 upd = xstrdup("none");
660 } else
661 upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
662
663 if (git_config_set_gently(sb.buf, upd))
664 die(_("Failed to register update mode for submodule path '%s'"), displaypath);
665 }
666 strbuf_release(&sb);
667 free(displaypath);
668 free(url);
669 free(upd);
670 }
671
672 static void init_submodule_cb(const struct cache_entry *list_item, void *cb_data)
673 {
674 struct init_cb *info = cb_data;
675 init_submodule(list_item->name, info->prefix, info->flags);
676 }
677
678 static int module_init(int argc, const char **argv, const char *prefix)
679 {
680 struct init_cb info = INIT_CB_INIT;
681 struct pathspec pathspec;
682 struct module_list list = MODULE_LIST_INIT;
683 int quiet = 0;
684
685 struct option module_init_options[] = {
686 OPT__QUIET(&quiet, N_("suppress output for initializing a submodule")),
687 OPT_END()
688 };
689
690 const char *const git_submodule_helper_usage[] = {
691 N_("git submodule--helper init [<options>] [<path>]"),
692 NULL
693 };
694
695 argc = parse_options(argc, argv, prefix, module_init_options,
696 git_submodule_helper_usage, 0);
697
698 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
699 return 1;
700
701 /*
702 * If there are no path args and submodule.active is set then,
703 * by default, only initialize 'active' modules.
704 */
705 if (!argc && git_config_get_value_multi("submodule.active"))
706 module_list_active(&list);
707
708 info.prefix = prefix;
709 if (quiet)
710 info.flags |= OPT_QUIET;
711
712 for_each_listed_submodule(&list, init_submodule_cb, &info);
713
714 return 0;
715 }
716
717 struct status_cb {
718 const char *prefix;
719 unsigned int flags;
720 };
721 #define STATUS_CB_INIT { 0 }
722
723 static void print_status(unsigned int flags, char state, const char *path,
724 const struct object_id *oid, const char *displaypath)
725 {
726 if (flags & OPT_QUIET)
727 return;
728
729 printf("%c%s %s", state, oid_to_hex(oid), displaypath);
730
731 if (state == ' ' || state == '+') {
732 const char *name = compute_rev_name(path, oid_to_hex(oid));
733
734 if (name)
735 printf(" (%s)", name);
736 }
737
738 printf("\n");
739 }
740
741 static int handle_submodule_head_ref(const char *refname,
742 const struct object_id *oid, int flags,
743 void *cb_data)
744 {
745 struct object_id *output = cb_data;
746 if (oid)
747 oidcpy(output, oid);
748
749 return 0;
750 }
751
752 static void status_submodule(const char *path, const struct object_id *ce_oid,
753 unsigned int ce_flags, const char *prefix,
754 unsigned int flags)
755 {
756 char *displaypath;
757 struct strvec diff_files_args = STRVEC_INIT;
758 struct rev_info rev;
759 int diff_files_result;
760 struct strbuf buf = STRBUF_INIT;
761 const char *git_dir;
762
763 if (!submodule_from_path(the_repository, null_oid(), path))
764 die(_("no submodule mapping found in .gitmodules for path '%s'"),
765 path);
766
767 displaypath = get_submodule_displaypath(path, prefix);
768
769 if ((CE_STAGEMASK & ce_flags) >> CE_STAGESHIFT) {
770 print_status(flags, 'U', path, null_oid(), displaypath);
771 goto cleanup;
772 }
773
774 strbuf_addf(&buf, "%s/.git", path);
775 git_dir = read_gitfile(buf.buf);
776 if (!git_dir)
777 git_dir = buf.buf;
778
779 if (!is_submodule_active(the_repository, path) ||
780 !is_git_directory(git_dir)) {
781 print_status(flags, '-', path, ce_oid, displaypath);
782 strbuf_release(&buf);
783 goto cleanup;
784 }
785 strbuf_release(&buf);
786
787 strvec_pushl(&diff_files_args, "diff-files",
788 "--ignore-submodules=dirty", "--quiet", "--",
789 path, NULL);
790
791 git_config(git_diff_basic_config, NULL);
792
793 repo_init_revisions(the_repository, &rev, NULL);
794 rev.abbrev = 0;
795 diff_files_args.nr = setup_revisions(diff_files_args.nr,
796 diff_files_args.v,
797 &rev, NULL);
798 diff_files_result = run_diff_files(&rev, 0);
799
800 if (!diff_result_code(&rev.diffopt, diff_files_result)) {
801 print_status(flags, ' ', path, ce_oid,
802 displaypath);
803 } else if (!(flags & OPT_CACHED)) {
804 struct object_id oid;
805 struct ref_store *refs = get_submodule_ref_store(path);
806
807 if (!refs) {
808 print_status(flags, '-', path, ce_oid, displaypath);
809 goto cleanup;
810 }
811 if (refs_head_ref(refs, handle_submodule_head_ref, &oid))
812 die(_("could not resolve HEAD ref inside the "
813 "submodule '%s'"), path);
814
815 print_status(flags, '+', path, &oid, displaypath);
816 } else {
817 print_status(flags, '+', path, ce_oid, displaypath);
818 }
819
820 if (flags & OPT_RECURSIVE) {
821 struct child_process cpr = CHILD_PROCESS_INIT;
822
823 cpr.git_cmd = 1;
824 cpr.dir = path;
825 prepare_submodule_repo_env(&cpr.env_array);
826
827 strvec_push(&cpr.args, "--super-prefix");
828 strvec_pushf(&cpr.args, "%s/", displaypath);
829 strvec_pushl(&cpr.args, "submodule--helper", "status",
830 "--recursive", NULL);
831
832 if (flags & OPT_CACHED)
833 strvec_push(&cpr.args, "--cached");
834
835 if (flags & OPT_QUIET)
836 strvec_push(&cpr.args, "--quiet");
837
838 if (run_command(&cpr))
839 die(_("failed to recurse into submodule '%s'"), path);
840 }
841
842 cleanup:
843 strvec_clear(&diff_files_args);
844 free(displaypath);
845 }
846
847 static void status_submodule_cb(const struct cache_entry *list_item,
848 void *cb_data)
849 {
850 struct status_cb *info = cb_data;
851 status_submodule(list_item->name, &list_item->oid, list_item->ce_flags,
852 info->prefix, info->flags);
853 }
854
855 static int module_status(int argc, const char **argv, const char *prefix)
856 {
857 struct status_cb info = STATUS_CB_INIT;
858 struct pathspec pathspec;
859 struct module_list list = MODULE_LIST_INIT;
860 int quiet = 0;
861
862 struct option module_status_options[] = {
863 OPT__QUIET(&quiet, N_("suppress submodule status output")),
864 OPT_BIT(0, "cached", &info.flags, N_("use commit stored in the index instead of the one stored in the submodule HEAD"), OPT_CACHED),
865 OPT_BIT(0, "recursive", &info.flags, N_("recurse into nested submodules"), OPT_RECURSIVE),
866 OPT_END()
867 };
868
869 const char *const git_submodule_helper_usage[] = {
870 N_("git submodule status [--quiet] [--cached] [--recursive] [<path>...]"),
871 NULL
872 };
873
874 argc = parse_options(argc, argv, prefix, module_status_options,
875 git_submodule_helper_usage, 0);
876
877 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
878 return 1;
879
880 info.prefix = prefix;
881 if (quiet)
882 info.flags |= OPT_QUIET;
883
884 for_each_listed_submodule(&list, status_submodule_cb, &info);
885
886 return 0;
887 }
888
889 static int module_name(int argc, const char **argv, const char *prefix)
890 {
891 const struct submodule *sub;
892
893 if (argc != 2)
894 usage(_("git submodule--helper name <path>"));
895
896 sub = submodule_from_path(the_repository, null_oid(), argv[1]);
897
898 if (!sub)
899 die(_("no submodule mapping found in .gitmodules for path '%s'"),
900 argv[1]);
901
902 printf("%s\n", sub->name);
903
904 return 0;
905 }
906
907 struct module_cb {
908 unsigned int mod_src;
909 unsigned int mod_dst;
910 struct object_id oid_src;
911 struct object_id oid_dst;
912 char status;
913 const char *sm_path;
914 };
915 #define MODULE_CB_INIT { 0 }
916
917 struct module_cb_list {
918 struct module_cb **entries;
919 int alloc, nr;
920 };
921 #define MODULE_CB_LIST_INIT { 0 }
922
923 struct summary_cb {
924 int argc;
925 const char **argv;
926 const char *prefix;
927 unsigned int cached: 1;
928 unsigned int for_status: 1;
929 unsigned int files: 1;
930 int summary_limit;
931 };
932 #define SUMMARY_CB_INIT { 0 }
933
934 enum diff_cmd {
935 DIFF_INDEX,
936 DIFF_FILES
937 };
938
939 static char *verify_submodule_committish(const char *sm_path,
940 const char *committish)
941 {
942 struct child_process cp_rev_parse = CHILD_PROCESS_INIT;
943 struct strbuf result = STRBUF_INIT;
944
945 cp_rev_parse.git_cmd = 1;
946 cp_rev_parse.dir = sm_path;
947 prepare_submodule_repo_env(&cp_rev_parse.env_array);
948 strvec_pushl(&cp_rev_parse.args, "rev-parse", "-q", "--short", NULL);
949 strvec_pushf(&cp_rev_parse.args, "%s^0", committish);
950 strvec_push(&cp_rev_parse.args, "--");
951
952 if (capture_command(&cp_rev_parse, &result, 0))
953 return NULL;
954
955 strbuf_trim_trailing_newline(&result);
956 return strbuf_detach(&result, NULL);
957 }
958
959 static void print_submodule_summary(struct summary_cb *info, char *errmsg,
960 int total_commits, const char *displaypath,
961 const char *src_abbrev, const char *dst_abbrev,
962 struct module_cb *p)
963 {
964 if (p->status == 'T') {
965 if (S_ISGITLINK(p->mod_dst))
966 printf(_("* %s %s(blob)->%s(submodule)"),
967 displaypath, src_abbrev, dst_abbrev);
968 else
969 printf(_("* %s %s(submodule)->%s(blob)"),
970 displaypath, src_abbrev, dst_abbrev);
971 } else {
972 printf("* %s %s...%s",
973 displaypath, src_abbrev, dst_abbrev);
974 }
975
976 if (total_commits < 0)
977 printf(":\n");
978 else
979 printf(" (%d):\n", total_commits);
980
981 if (errmsg) {
982 printf(_("%s"), errmsg);
983 } else if (total_commits > 0) {
984 struct child_process cp_log = CHILD_PROCESS_INIT;
985
986 cp_log.git_cmd = 1;
987 cp_log.dir = p->sm_path;
988 prepare_submodule_repo_env(&cp_log.env_array);
989 strvec_pushl(&cp_log.args, "log", NULL);
990
991 if (S_ISGITLINK(p->mod_src) && S_ISGITLINK(p->mod_dst)) {
992 if (info->summary_limit > 0)
993 strvec_pushf(&cp_log.args, "-%d",
994 info->summary_limit);
995
996 strvec_pushl(&cp_log.args, "--pretty= %m %s",
997 "--first-parent", NULL);
998 strvec_pushf(&cp_log.args, "%s...%s",
999 src_abbrev, dst_abbrev);
1000 } else if (S_ISGITLINK(p->mod_dst)) {
1001 strvec_pushl(&cp_log.args, "--pretty= > %s",
1002 "-1", dst_abbrev, NULL);
1003 } else {
1004 strvec_pushl(&cp_log.args, "--pretty= < %s",
1005 "-1", src_abbrev, NULL);
1006 }
1007 run_command(&cp_log);
1008 }
1009 printf("\n");
1010 }
1011
1012 static void generate_submodule_summary(struct summary_cb *info,
1013 struct module_cb *p)
1014 {
1015 char *displaypath, *src_abbrev = NULL, *dst_abbrev;
1016 int missing_src = 0, missing_dst = 0;
1017 char *errmsg = NULL;
1018 int total_commits = -1;
1019
1020 if (!info->cached && oideq(&p->oid_dst, null_oid())) {
1021 if (S_ISGITLINK(p->mod_dst)) {
1022 struct ref_store *refs = get_submodule_ref_store(p->sm_path);
1023 if (refs)
1024 refs_head_ref(refs, handle_submodule_head_ref, &p->oid_dst);
1025 } else if (S_ISLNK(p->mod_dst) || S_ISREG(p->mod_dst)) {
1026 struct stat st;
1027 int fd = open(p->sm_path, O_RDONLY);
1028
1029 if (fd < 0 || fstat(fd, &st) < 0 ||
1030 index_fd(&the_index, &p->oid_dst, fd, &st, OBJ_BLOB,
1031 p->sm_path, 0))
1032 error(_("couldn't hash object from '%s'"), p->sm_path);
1033 } else {
1034 /* for a submodule removal (mode:0000000), don't warn */
1035 if (p->mod_dst)
1036 warning(_("unexpected mode %o\n"), p->mod_dst);
1037 }
1038 }
1039
1040 if (S_ISGITLINK(p->mod_src)) {
1041 if (p->status != 'D')
1042 src_abbrev = verify_submodule_committish(p->sm_path,
1043 oid_to_hex(&p->oid_src));
1044 if (!src_abbrev) {
1045 missing_src = 1;
1046 /*
1047 * As `rev-parse` failed, we fallback to getting
1048 * the abbreviated hash using oid_src. We do
1049 * this as we might still need the abbreviated
1050 * hash in cases like a submodule type change, etc.
1051 */
1052 src_abbrev = xstrndup(oid_to_hex(&p->oid_src), 7);
1053 }
1054 } else {
1055 /*
1056 * The source does not point to a submodule.
1057 * So, we fallback to getting the abbreviation using
1058 * oid_src as we might still need the abbreviated
1059 * hash in cases like submodule add, etc.
1060 */
1061 src_abbrev = xstrndup(oid_to_hex(&p->oid_src), 7);
1062 }
1063
1064 if (S_ISGITLINK(p->mod_dst)) {
1065 dst_abbrev = verify_submodule_committish(p->sm_path,
1066 oid_to_hex(&p->oid_dst));
1067 if (!dst_abbrev) {
1068 missing_dst = 1;
1069 /*
1070 * As `rev-parse` failed, we fallback to getting
1071 * the abbreviated hash using oid_dst. We do
1072 * this as we might still need the abbreviated
1073 * hash in cases like a submodule type change, etc.
1074 */
1075 dst_abbrev = xstrndup(oid_to_hex(&p->oid_dst), 7);
1076 }
1077 } else {
1078 /*
1079 * The destination does not point to a submodule.
1080 * So, we fallback to getting the abbreviation using
1081 * oid_dst as we might still need the abbreviated
1082 * hash in cases like a submodule removal, etc.
1083 */
1084 dst_abbrev = xstrndup(oid_to_hex(&p->oid_dst), 7);
1085 }
1086
1087 displaypath = get_submodule_displaypath(p->sm_path, info->prefix);
1088
1089 if (!missing_src && !missing_dst) {
1090 struct child_process cp_rev_list = CHILD_PROCESS_INIT;
1091 struct strbuf sb_rev_list = STRBUF_INIT;
1092
1093 strvec_pushl(&cp_rev_list.args, "rev-list",
1094 "--first-parent", "--count", NULL);
1095 if (S_ISGITLINK(p->mod_src) && S_ISGITLINK(p->mod_dst))
1096 strvec_pushf(&cp_rev_list.args, "%s...%s",
1097 src_abbrev, dst_abbrev);
1098 else
1099 strvec_push(&cp_rev_list.args, S_ISGITLINK(p->mod_src) ?
1100 src_abbrev : dst_abbrev);
1101 strvec_push(&cp_rev_list.args, "--");
1102
1103 cp_rev_list.git_cmd = 1;
1104 cp_rev_list.dir = p->sm_path;
1105 prepare_submodule_repo_env(&cp_rev_list.env_array);
1106
1107 if (!capture_command(&cp_rev_list, &sb_rev_list, 0))
1108 total_commits = atoi(sb_rev_list.buf);
1109
1110 strbuf_release(&sb_rev_list);
1111 } else {
1112 /*
1113 * Don't give error msg for modification whose dst is not
1114 * submodule, i.e., deleted or changed to blob
1115 */
1116 if (S_ISGITLINK(p->mod_dst)) {
1117 struct strbuf errmsg_str = STRBUF_INIT;
1118 if (missing_src && missing_dst) {
1119 strbuf_addf(&errmsg_str, " Warn: %s doesn't contain commits %s and %s\n",
1120 displaypath, oid_to_hex(&p->oid_src),
1121 oid_to_hex(&p->oid_dst));
1122 } else {
1123 strbuf_addf(&errmsg_str, " Warn: %s doesn't contain commit %s\n",
1124 displaypath, missing_src ?
1125 oid_to_hex(&p->oid_src) :
1126 oid_to_hex(&p->oid_dst));
1127 }
1128 errmsg = strbuf_detach(&errmsg_str, NULL);
1129 }
1130 }
1131
1132 print_submodule_summary(info, errmsg, total_commits,
1133 displaypath, src_abbrev,
1134 dst_abbrev, p);
1135
1136 free(displaypath);
1137 free(src_abbrev);
1138 free(dst_abbrev);
1139 }
1140
1141 static void prepare_submodule_summary(struct summary_cb *info,
1142 struct module_cb_list *list)
1143 {
1144 int i;
1145 for (i = 0; i < list->nr; i++) {
1146 const struct submodule *sub;
1147 struct module_cb *p = list->entries[i];
1148 struct strbuf sm_gitdir = STRBUF_INIT;
1149
1150 if (p->status == 'D' || p->status == 'T') {
1151 generate_submodule_summary(info, p);
1152 continue;
1153 }
1154
1155 if (info->for_status && p->status != 'A' &&
1156 (sub = submodule_from_path(the_repository,
1157 null_oid(), p->sm_path))) {
1158 char *config_key = NULL;
1159 const char *value;
1160 int ignore_all = 0;
1161
1162 config_key = xstrfmt("submodule.%s.ignore",
1163 sub->name);
1164 if (!git_config_get_string_tmp(config_key, &value))
1165 ignore_all = !strcmp(value, "all");
1166 else if (sub->ignore)
1167 ignore_all = !strcmp(sub->ignore, "all");
1168
1169 free(config_key);
1170 if (ignore_all)
1171 continue;
1172 }
1173
1174 /* Also show added or modified modules which are checked out */
1175 strbuf_addstr(&sm_gitdir, p->sm_path);
1176 if (is_nonbare_repository_dir(&sm_gitdir))
1177 generate_submodule_summary(info, p);
1178 strbuf_release(&sm_gitdir);
1179 }
1180 }
1181
1182 static void submodule_summary_callback(struct diff_queue_struct *q,
1183 struct diff_options *options,
1184 void *data)
1185 {
1186 int i;
1187 struct module_cb_list *list = data;
1188 for (i = 0; i < q->nr; i++) {
1189 struct diff_filepair *p = q->queue[i];
1190 struct module_cb *temp;
1191
1192 if (!S_ISGITLINK(p->one->mode) && !S_ISGITLINK(p->two->mode))
1193 continue;
1194 temp = (struct module_cb*)malloc(sizeof(struct module_cb));
1195 temp->mod_src = p->one->mode;
1196 temp->mod_dst = p->two->mode;
1197 temp->oid_src = p->one->oid;
1198 temp->oid_dst = p->two->oid;
1199 temp->status = p->status;
1200 temp->sm_path = xstrdup(p->one->path);
1201
1202 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
1203 list->entries[list->nr++] = temp;
1204 }
1205 }
1206
1207 static const char *get_diff_cmd(enum diff_cmd diff_cmd)
1208 {
1209 switch (diff_cmd) {
1210 case DIFF_INDEX: return "diff-index";
1211 case DIFF_FILES: return "diff-files";
1212 default: BUG("bad diff_cmd value %d", diff_cmd);
1213 }
1214 }
1215
1216 static int compute_summary_module_list(struct object_id *head_oid,
1217 struct summary_cb *info,
1218 enum diff_cmd diff_cmd)
1219 {
1220 struct strvec diff_args = STRVEC_INIT;
1221 struct rev_info rev;
1222 struct module_cb_list list = MODULE_CB_LIST_INIT;
1223
1224 strvec_push(&diff_args, get_diff_cmd(diff_cmd));
1225 if (info->cached)
1226 strvec_push(&diff_args, "--cached");
1227 strvec_pushl(&diff_args, "--ignore-submodules=dirty", "--raw", NULL);
1228 if (head_oid)
1229 strvec_push(&diff_args, oid_to_hex(head_oid));
1230 strvec_push(&diff_args, "--");
1231 if (info->argc)
1232 strvec_pushv(&diff_args, info->argv);
1233
1234 git_config(git_diff_basic_config, NULL);
1235 init_revisions(&rev, info->prefix);
1236 rev.abbrev = 0;
1237 precompose_argv_prefix(diff_args.nr, diff_args.v, NULL);
1238 setup_revisions(diff_args.nr, diff_args.v, &rev, NULL);
1239 rev.diffopt.output_format = DIFF_FORMAT_NO_OUTPUT | DIFF_FORMAT_CALLBACK;
1240 rev.diffopt.format_callback = submodule_summary_callback;
1241 rev.diffopt.format_callback_data = &list;
1242
1243 if (!info->cached) {
1244 if (diff_cmd == DIFF_INDEX)
1245 setup_work_tree();
1246 if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
1247 perror("read_cache_preload");
1248 return -1;
1249 }
1250 } else if (read_cache() < 0) {
1251 perror("read_cache");
1252 return -1;
1253 }
1254
1255 if (diff_cmd == DIFF_INDEX)
1256 run_diff_index(&rev, info->cached);
1257 else
1258 run_diff_files(&rev, 0);
1259 prepare_submodule_summary(info, &list);
1260 strvec_clear(&diff_args);
1261 return 0;
1262 }
1263
1264 static int module_summary(int argc, const char **argv, const char *prefix)
1265 {
1266 struct summary_cb info = SUMMARY_CB_INIT;
1267 int cached = 0;
1268 int for_status = 0;
1269 int files = 0;
1270 int summary_limit = -1;
1271 enum diff_cmd diff_cmd = DIFF_INDEX;
1272 struct object_id head_oid;
1273 int ret;
1274
1275 struct option module_summary_options[] = {
1276 OPT_BOOL(0, "cached", &cached,
1277 N_("use the commit stored in the index instead of the submodule HEAD")),
1278 OPT_BOOL(0, "files", &files,
1279 N_("compare the commit in the index with that in the submodule HEAD")),
1280 OPT_BOOL(0, "for-status", &for_status,
1281 N_("skip submodules with 'ignore_config' value set to 'all'")),
1282 OPT_INTEGER('n', "summary-limit", &summary_limit,
1283 N_("limit the summary size")),
1284 OPT_END()
1285 };
1286
1287 const char *const git_submodule_helper_usage[] = {
1288 N_("git submodule--helper summary [<options>] [<commit>] [--] [<path>]"),
1289 NULL
1290 };
1291
1292 argc = parse_options(argc, argv, prefix, module_summary_options,
1293 git_submodule_helper_usage, 0);
1294
1295 if (!summary_limit)
1296 return 0;
1297
1298 if (!get_oid(argc ? argv[0] : "HEAD", &head_oid)) {
1299 if (argc) {
1300 argv++;
1301 argc--;
1302 }
1303 } else if (!argc || !strcmp(argv[0], "HEAD")) {
1304 /* before the first commit: compare with an empty tree */
1305 oidcpy(&head_oid, the_hash_algo->empty_tree);
1306 if (argc) {
1307 argv++;
1308 argc--;
1309 }
1310 } else {
1311 if (get_oid("HEAD", &head_oid))
1312 die(_("could not fetch a revision for HEAD"));
1313 }
1314
1315 if (files) {
1316 if (cached)
1317 die(_("options '%s' and '%s' cannot be used together"), "--cached", "--files");
1318 diff_cmd = DIFF_FILES;
1319 }
1320
1321 info.argc = argc;
1322 info.argv = argv;
1323 info.prefix = prefix;
1324 info.cached = !!cached;
1325 info.files = !!files;
1326 info.for_status = !!for_status;
1327 info.summary_limit = summary_limit;
1328
1329 ret = compute_summary_module_list((diff_cmd == DIFF_INDEX) ? &head_oid : NULL,
1330 &info, diff_cmd);
1331 return ret;
1332 }
1333
1334 struct sync_cb {
1335 const char *prefix;
1336 unsigned int flags;
1337 };
1338 #define SYNC_CB_INIT { 0 }
1339
1340 static void sync_submodule(const char *path, const char *prefix,
1341 unsigned int flags)
1342 {
1343 const struct submodule *sub;
1344 char *remote_key = NULL;
1345 char *sub_origin_url, *super_config_url, *displaypath;
1346 struct strbuf sb = STRBUF_INIT;
1347 struct child_process cp = CHILD_PROCESS_INIT;
1348 char *sub_config_path = NULL;
1349
1350 if (!is_submodule_active(the_repository, path))
1351 return;
1352
1353 sub = submodule_from_path(the_repository, null_oid(), path);
1354
1355 if (sub && sub->url) {
1356 if (starts_with_dot_dot_slash(sub->url) ||
1357 starts_with_dot_slash(sub->url)) {
1358 char *up_path = get_up_path(path);
1359 sub_origin_url = resolve_relative_url(sub->url, up_path, 1);
1360 super_config_url = resolve_relative_url(sub->url, NULL, 1);
1361 free(up_path);
1362 } else {
1363 sub_origin_url = xstrdup(sub->url);
1364 super_config_url = xstrdup(sub->url);
1365 }
1366 } else {
1367 sub_origin_url = xstrdup("");
1368 super_config_url = xstrdup("");
1369 }
1370
1371 displaypath = get_submodule_displaypath(path, prefix);
1372
1373 if (!(flags & OPT_QUIET))
1374 printf(_("Synchronizing submodule url for '%s'\n"),
1375 displaypath);
1376
1377 strbuf_reset(&sb);
1378 strbuf_addf(&sb, "submodule.%s.url", sub->name);
1379 if (git_config_set_gently(sb.buf, super_config_url))
1380 die(_("failed to register url for submodule path '%s'"),
1381 displaypath);
1382
1383 if (!is_submodule_populated_gently(path, NULL))
1384 goto cleanup;
1385
1386 prepare_submodule_repo_env(&cp.env_array);
1387 cp.git_cmd = 1;
1388 cp.dir = path;
1389 strvec_pushl(&cp.args, "submodule--helper",
1390 "print-default-remote", NULL);
1391
1392 strbuf_reset(&sb);
1393 if (capture_command(&cp, &sb, 0))
1394 die(_("failed to get the default remote for submodule '%s'"),
1395 path);
1396
1397 strbuf_strip_suffix(&sb, "\n");
1398 remote_key = xstrfmt("remote.%s.url", sb.buf);
1399
1400 strbuf_reset(&sb);
1401 submodule_to_gitdir(&sb, path);
1402 strbuf_addstr(&sb, "/config");
1403
1404 if (git_config_set_in_file_gently(sb.buf, remote_key, sub_origin_url))
1405 die(_("failed to update remote for submodule '%s'"),
1406 path);
1407
1408 if (flags & OPT_RECURSIVE) {
1409 struct child_process cpr = CHILD_PROCESS_INIT;
1410
1411 cpr.git_cmd = 1;
1412 cpr.dir = path;
1413 prepare_submodule_repo_env(&cpr.env_array);
1414
1415 strvec_push(&cpr.args, "--super-prefix");
1416 strvec_pushf(&cpr.args, "%s/", displaypath);
1417 strvec_pushl(&cpr.args, "submodule--helper", "sync",
1418 "--recursive", NULL);
1419
1420 if (flags & OPT_QUIET)
1421 strvec_push(&cpr.args, "--quiet");
1422
1423 if (run_command(&cpr))
1424 die(_("failed to recurse into submodule '%s'"),
1425 path);
1426 }
1427
1428 cleanup:
1429 free(super_config_url);
1430 free(sub_origin_url);
1431 strbuf_release(&sb);
1432 free(remote_key);
1433 free(displaypath);
1434 free(sub_config_path);
1435 }
1436
1437 static void sync_submodule_cb(const struct cache_entry *list_item, void *cb_data)
1438 {
1439 struct sync_cb *info = cb_data;
1440 sync_submodule(list_item->name, info->prefix, info->flags);
1441 }
1442
1443 static int module_sync(int argc, const char **argv, const char *prefix)
1444 {
1445 struct sync_cb info = SYNC_CB_INIT;
1446 struct pathspec pathspec;
1447 struct module_list list = MODULE_LIST_INIT;
1448 int quiet = 0;
1449 int recursive = 0;
1450
1451 struct option module_sync_options[] = {
1452 OPT__QUIET(&quiet, N_("suppress output of synchronizing submodule url")),
1453 OPT_BOOL(0, "recursive", &recursive,
1454 N_("recurse into nested submodules")),
1455 OPT_END()
1456 };
1457
1458 const char *const git_submodule_helper_usage[] = {
1459 N_("git submodule--helper sync [--quiet] [--recursive] [<path>]"),
1460 NULL
1461 };
1462
1463 argc = parse_options(argc, argv, prefix, module_sync_options,
1464 git_submodule_helper_usage, 0);
1465
1466 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1467 return 1;
1468
1469 info.prefix = prefix;
1470 if (quiet)
1471 info.flags |= OPT_QUIET;
1472 if (recursive)
1473 info.flags |= OPT_RECURSIVE;
1474
1475 for_each_listed_submodule(&list, sync_submodule_cb, &info);
1476
1477 return 0;
1478 }
1479
1480 struct deinit_cb {
1481 const char *prefix;
1482 unsigned int flags;
1483 };
1484 #define DEINIT_CB_INIT { 0 }
1485
1486 static void deinit_submodule(const char *path, const char *prefix,
1487 unsigned int flags)
1488 {
1489 const struct submodule *sub;
1490 char *displaypath = NULL;
1491 struct child_process cp_config = CHILD_PROCESS_INIT;
1492 struct strbuf sb_config = STRBUF_INIT;
1493 char *sub_git_dir = xstrfmt("%s/.git", path);
1494
1495 sub = submodule_from_path(the_repository, null_oid(), path);
1496
1497 if (!sub || !sub->name)
1498 goto cleanup;
1499
1500 displaypath = get_submodule_displaypath(path, prefix);
1501
1502 /* remove the submodule work tree (unless the user already did it) */
1503 if (is_directory(path)) {
1504 struct strbuf sb_rm = STRBUF_INIT;
1505 const char *format;
1506
1507 if (is_directory(sub_git_dir)) {
1508 if (!(flags & OPT_QUIET))
1509 warning(_("Submodule work tree '%s' contains a .git "
1510 "directory. This will be replaced with a "
1511 ".git file by using absorbgitdirs."),
1512 displaypath);
1513
1514 absorb_git_dir_into_superproject(path,
1515 ABSORB_GITDIR_RECURSE_SUBMODULES);
1516
1517 }
1518
1519 if (!(flags & OPT_FORCE)) {
1520 struct child_process cp_rm = CHILD_PROCESS_INIT;
1521 cp_rm.git_cmd = 1;
1522 strvec_pushl(&cp_rm.args, "rm", "-qn",
1523 path, NULL);
1524
1525 if (run_command(&cp_rm))
1526 die(_("Submodule work tree '%s' contains local "
1527 "modifications; use '-f' to discard them"),
1528 displaypath);
1529 }
1530
1531 strbuf_addstr(&sb_rm, path);
1532
1533 if (!remove_dir_recursively(&sb_rm, 0))
1534 format = _("Cleared directory '%s'\n");
1535 else
1536 format = _("Could not remove submodule work tree '%s'\n");
1537
1538 if (!(flags & OPT_QUIET))
1539 printf(format, displaypath);
1540
1541 submodule_unset_core_worktree(sub);
1542
1543 strbuf_release(&sb_rm);
1544 }
1545
1546 if (mkdir(path, 0777))
1547 printf(_("could not create empty submodule directory %s"),
1548 displaypath);
1549
1550 cp_config.git_cmd = 1;
1551 strvec_pushl(&cp_config.args, "config", "--get-regexp", NULL);
1552 strvec_pushf(&cp_config.args, "submodule.%s\\.", sub->name);
1553
1554 /* remove the .git/config entries (unless the user already did it) */
1555 if (!capture_command(&cp_config, &sb_config, 0) && sb_config.len) {
1556 char *sub_key = xstrfmt("submodule.%s", sub->name);
1557 /*
1558 * remove the whole section so we have a clean state when
1559 * the user later decides to init this submodule again
1560 */
1561 git_config_rename_section_in_file(NULL, sub_key, NULL);
1562 if (!(flags & OPT_QUIET))
1563 printf(_("Submodule '%s' (%s) unregistered for path '%s'\n"),
1564 sub->name, sub->url, displaypath);
1565 free(sub_key);
1566 }
1567
1568 cleanup:
1569 free(displaypath);
1570 free(sub_git_dir);
1571 strbuf_release(&sb_config);
1572 }
1573
1574 static void deinit_submodule_cb(const struct cache_entry *list_item,
1575 void *cb_data)
1576 {
1577 struct deinit_cb *info = cb_data;
1578 deinit_submodule(list_item->name, info->prefix, info->flags);
1579 }
1580
1581 static int module_deinit(int argc, const char **argv, const char *prefix)
1582 {
1583 struct deinit_cb info = DEINIT_CB_INIT;
1584 struct pathspec pathspec;
1585 struct module_list list = MODULE_LIST_INIT;
1586 int quiet = 0;
1587 int force = 0;
1588 int all = 0;
1589
1590 struct option module_deinit_options[] = {
1591 OPT__QUIET(&quiet, N_("suppress submodule status output")),
1592 OPT__FORCE(&force, N_("remove submodule working trees even if they contain local changes"), 0),
1593 OPT_BOOL(0, "all", &all, N_("unregister all submodules")),
1594 OPT_END()
1595 };
1596
1597 const char *const git_submodule_helper_usage[] = {
1598 N_("git submodule deinit [--quiet] [-f | --force] [--all | [--] [<path>...]]"),
1599 NULL
1600 };
1601
1602 argc = parse_options(argc, argv, prefix, module_deinit_options,
1603 git_submodule_helper_usage, 0);
1604
1605 if (all && argc) {
1606 error("pathspec and --all are incompatible");
1607 usage_with_options(git_submodule_helper_usage,
1608 module_deinit_options);
1609 }
1610
1611 if (!argc && !all)
1612 die(_("Use '--all' if you really want to deinitialize all submodules"));
1613
1614 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1615 return 1;
1616
1617 info.prefix = prefix;
1618 if (quiet)
1619 info.flags |= OPT_QUIET;
1620 if (force)
1621 info.flags |= OPT_FORCE;
1622
1623 for_each_listed_submodule(&list, deinit_submodule_cb, &info);
1624
1625 return 0;
1626 }
1627
1628 struct module_clone_data {
1629 const char *prefix;
1630 const char *path;
1631 const char *name;
1632 const char *url;
1633 const char *depth;
1634 struct string_list reference;
1635 unsigned int quiet: 1;
1636 unsigned int progress: 1;
1637 unsigned int dissociate: 1;
1638 unsigned int require_init: 1;
1639 int single_branch;
1640 };
1641 #define MODULE_CLONE_DATA_INIT { .reference = STRING_LIST_INIT_NODUP, .single_branch = -1 }
1642
1643 struct submodule_alternate_setup {
1644 const char *submodule_name;
1645 enum SUBMODULE_ALTERNATE_ERROR_MODE {
1646 SUBMODULE_ALTERNATE_ERROR_DIE,
1647 SUBMODULE_ALTERNATE_ERROR_INFO,
1648 SUBMODULE_ALTERNATE_ERROR_IGNORE
1649 } error_mode;
1650 struct string_list *reference;
1651 };
1652 #define SUBMODULE_ALTERNATE_SETUP_INIT { \
1653 .error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE, \
1654 }
1655
1656 static const char alternate_error_advice[] = N_(
1657 "An alternate computed from a superproject's alternate is invalid.\n"
1658 "To allow Git to clone without an alternate in such a case, set\n"
1659 "submodule.alternateErrorStrategy to 'info' or, equivalently, clone with\n"
1660 "'--reference-if-able' instead of '--reference'."
1661 );
1662
1663 static int add_possible_reference_from_superproject(
1664 struct object_directory *odb, void *sas_cb)
1665 {
1666 struct submodule_alternate_setup *sas = sas_cb;
1667 size_t len;
1668
1669 /*
1670 * If the alternate object store is another repository, try the
1671 * standard layout with .git/(modules/<name>)+/objects
1672 */
1673 if (strip_suffix(odb->path, "/objects", &len)) {
1674 struct repository alternate;
1675 char *sm_alternate;
1676 struct strbuf sb = STRBUF_INIT;
1677 struct strbuf err = STRBUF_INIT;
1678 strbuf_add(&sb, odb->path, len);
1679
1680 repo_init(&alternate, sb.buf, NULL);
1681
1682 /*
1683 * We need to end the new path with '/' to mark it as a dir,
1684 * otherwise a submodule name containing '/' will be broken
1685 * as the last part of a missing submodule reference would
1686 * be taken as a file name.
1687 */
1688 strbuf_reset(&sb);
1689 submodule_name_to_gitdir(&sb, &alternate, sas->submodule_name);
1690 strbuf_addch(&sb, '/');
1691 repo_clear(&alternate);
1692
1693 sm_alternate = compute_alternate_path(sb.buf, &err);
1694 if (sm_alternate) {
1695 string_list_append(sas->reference, xstrdup(sb.buf));
1696 free(sm_alternate);
1697 } else {
1698 switch (sas->error_mode) {
1699 case SUBMODULE_ALTERNATE_ERROR_DIE:
1700 if (advice_enabled(ADVICE_SUBMODULE_ALTERNATE_ERROR_STRATEGY_DIE))
1701 advise(_(alternate_error_advice));
1702 die(_("submodule '%s' cannot add alternate: %s"),
1703 sas->submodule_name, err.buf);
1704 case SUBMODULE_ALTERNATE_ERROR_INFO:
1705 fprintf_ln(stderr, _("submodule '%s' cannot add alternate: %s"),
1706 sas->submodule_name, err.buf);
1707 case SUBMODULE_ALTERNATE_ERROR_IGNORE:
1708 ; /* nothing */
1709 }
1710 }
1711 strbuf_release(&sb);
1712 }
1713
1714 return 0;
1715 }
1716
1717 static void prepare_possible_alternates(const char *sm_name,
1718 struct string_list *reference)
1719 {
1720 char *sm_alternate = NULL, *error_strategy = NULL;
1721 struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
1722
1723 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1724 if (!sm_alternate)
1725 return;
1726
1727 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1728
1729 if (!error_strategy)
1730 error_strategy = xstrdup("die");
1731
1732 sas.submodule_name = sm_name;
1733 sas.reference = reference;
1734 if (!strcmp(error_strategy, "die"))
1735 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
1736 else if (!strcmp(error_strategy, "info"))
1737 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
1738 else if (!strcmp(error_strategy, "ignore"))
1739 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
1740 else
1741 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
1742
1743 if (!strcmp(sm_alternate, "superproject"))
1744 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
1745 else if (!strcmp(sm_alternate, "no"))
1746 ; /* do nothing */
1747 else
1748 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
1749
1750 free(sm_alternate);
1751 free(error_strategy);
1752 }
1753
1754 static int clone_submodule(struct module_clone_data *clone_data)
1755 {
1756 char *p, *sm_gitdir;
1757 char *sm_alternate = NULL, *error_strategy = NULL;
1758 struct strbuf sb = STRBUF_INIT;
1759 struct child_process cp = CHILD_PROCESS_INIT;
1760
1761 submodule_name_to_gitdir(&sb, the_repository, clone_data->name);
1762 sm_gitdir = absolute_pathdup(sb.buf);
1763 strbuf_reset(&sb);
1764
1765 if (!is_absolute_path(clone_data->path)) {
1766 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), clone_data->path);
1767 clone_data->path = strbuf_detach(&sb, NULL);
1768 } else {
1769 clone_data->path = xstrdup(clone_data->path);
1770 }
1771
1772 if (validate_submodule_git_dir(sm_gitdir, clone_data->name) < 0)
1773 die(_("refusing to create/use '%s' in another submodule's "
1774 "git dir"), sm_gitdir);
1775
1776 if (!file_exists(sm_gitdir)) {
1777 if (safe_create_leading_directories_const(sm_gitdir) < 0)
1778 die(_("could not create directory '%s'"), sm_gitdir);
1779
1780 prepare_possible_alternates(clone_data->name, &clone_data->reference);
1781
1782 strvec_push(&cp.args, "clone");
1783 strvec_push(&cp.args, "--no-checkout");
1784 if (clone_data->quiet)
1785 strvec_push(&cp.args, "--quiet");
1786 if (clone_data->progress)
1787 strvec_push(&cp.args, "--progress");
1788 if (clone_data->depth && *(clone_data->depth))
1789 strvec_pushl(&cp.args, "--depth", clone_data->depth, NULL);
1790 if (clone_data->reference.nr) {
1791 struct string_list_item *item;
1792 for_each_string_list_item(item, &clone_data->reference)
1793 strvec_pushl(&cp.args, "--reference",
1794 item->string, NULL);
1795 }
1796 if (clone_data->dissociate)
1797 strvec_push(&cp.args, "--dissociate");
1798 if (sm_gitdir && *sm_gitdir)
1799 strvec_pushl(&cp.args, "--separate-git-dir", sm_gitdir, NULL);
1800 if (clone_data->single_branch >= 0)
1801 strvec_push(&cp.args, clone_data->single_branch ?
1802 "--single-branch" :
1803 "--no-single-branch");
1804
1805 strvec_push(&cp.args, "--");
1806 strvec_push(&cp.args, clone_data->url);
1807 strvec_push(&cp.args, clone_data->path);
1808
1809 cp.git_cmd = 1;
1810 prepare_submodule_repo_env(&cp.env_array);
1811 cp.no_stdin = 1;
1812
1813 if(run_command(&cp))
1814 die(_("clone of '%s' into submodule path '%s' failed"),
1815 clone_data->url, clone_data->path);
1816 } else {
1817 if (clone_data->require_init && !access(clone_data->path, X_OK) &&
1818 !is_empty_dir(clone_data->path))
1819 die(_("directory not empty: '%s'"), clone_data->path);
1820 if (safe_create_leading_directories_const(clone_data->path) < 0)
1821 die(_("could not create directory '%s'"), clone_data->path);
1822 strbuf_addf(&sb, "%s/index", sm_gitdir);
1823 unlink_or_warn(sb.buf);
1824 strbuf_reset(&sb);
1825 }
1826
1827 connect_work_tree_and_git_dir(clone_data->path, sm_gitdir, 0);
1828
1829 p = git_pathdup_submodule(clone_data->path, "config");
1830 if (!p)
1831 die(_("could not get submodule directory for '%s'"), clone_data->path);
1832
1833 /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
1834 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1835 if (sm_alternate)
1836 git_config_set_in_file(p, "submodule.alternateLocation",
1837 sm_alternate);
1838 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1839 if (error_strategy)
1840 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
1841 error_strategy);
1842
1843 free(sm_alternate);
1844 free(error_strategy);
1845
1846 strbuf_release(&sb);
1847 free(sm_gitdir);
1848 free(p);
1849 return 0;
1850 }
1851
1852 static int module_clone(int argc, const char **argv, const char *prefix)
1853 {
1854 int dissociate = 0, quiet = 0, progress = 0, require_init = 0;
1855 struct module_clone_data clone_data = MODULE_CLONE_DATA_INIT;
1856
1857 struct option module_clone_options[] = {
1858 OPT_STRING(0, "prefix", &clone_data.prefix,
1859 N_("path"),
1860 N_("alternative anchor for relative paths")),
1861 OPT_STRING(0, "path", &clone_data.path,
1862 N_("path"),
1863 N_("where the new submodule will be cloned to")),
1864 OPT_STRING(0, "name", &clone_data.name,
1865 N_("string"),
1866 N_("name of the new submodule")),
1867 OPT_STRING(0, "url", &clone_data.url,
1868 N_("string"),
1869 N_("url where to clone the submodule from")),
1870 OPT_STRING_LIST(0, "reference", &clone_data.reference,
1871 N_("repo"),
1872 N_("reference repository")),
1873 OPT_BOOL(0, "dissociate", &dissociate,
1874 N_("use --reference only while cloning")),
1875 OPT_STRING(0, "depth", &clone_data.depth,
1876 N_("string"),
1877 N_("depth for shallow clones")),
1878 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
1879 OPT_BOOL(0, "progress", &progress,
1880 N_("force cloning progress")),
1881 OPT_BOOL(0, "require-init", &require_init,
1882 N_("disallow cloning into non-empty directory")),
1883 OPT_BOOL(0, "single-branch", &clone_data.single_branch,
1884 N_("clone only one branch, HEAD or --branch")),
1885 OPT_END()
1886 };
1887
1888 const char *const git_submodule_helper_usage[] = {
1889 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
1890 "[--reference <repository>] [--name <name>] [--depth <depth>] "
1891 "[--single-branch] "
1892 "--url <url> --path <path>"),
1893 NULL
1894 };
1895
1896 argc = parse_options(argc, argv, prefix, module_clone_options,
1897 git_submodule_helper_usage, 0);
1898
1899 clone_data.dissociate = !!dissociate;
1900 clone_data.quiet = !!quiet;
1901 clone_data.progress = !!progress;
1902 clone_data.require_init = !!require_init;
1903
1904 if (argc || !clone_data.url || !clone_data.path || !*(clone_data.path))
1905 usage_with_options(git_submodule_helper_usage,
1906 module_clone_options);
1907
1908 clone_submodule(&clone_data);
1909 return 0;
1910 }
1911
1912 static void determine_submodule_update_strategy(struct repository *r,
1913 int just_cloned,
1914 const char *path,
1915 const char *update,
1916 struct submodule_update_strategy *out)
1917 {
1918 const struct submodule *sub = submodule_from_path(r, null_oid(), path);
1919 char *key;
1920 const char *val;
1921
1922 key = xstrfmt("submodule.%s.update", sub->name);
1923
1924 if (update) {
1925 if (parse_submodule_update_strategy(update, out) < 0)
1926 die(_("Invalid update mode '%s' for submodule path '%s'"),
1927 update, path);
1928 } else if (!repo_config_get_string_tmp(r, key, &val)) {
1929 if (parse_submodule_update_strategy(val, out) < 0)
1930 die(_("Invalid update mode '%s' configured for submodule path '%s'"),
1931 val, path);
1932 } else if (sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
1933 if (sub->update_strategy.type == SM_UPDATE_COMMAND)
1934 BUG("how did we read update = !command from .gitmodules?");
1935 out->type = sub->update_strategy.type;
1936 out->command = sub->update_strategy.command;
1937 } else
1938 out->type = SM_UPDATE_CHECKOUT;
1939
1940 if (just_cloned &&
1941 (out->type == SM_UPDATE_MERGE ||
1942 out->type == SM_UPDATE_REBASE ||
1943 out->type == SM_UPDATE_NONE))
1944 out->type = SM_UPDATE_CHECKOUT;
1945
1946 free(key);
1947 }
1948
1949 static int module_update_module_mode(int argc, const char **argv, const char *prefix)
1950 {
1951 const char *path, *update = NULL;
1952 int just_cloned;
1953 struct submodule_update_strategy update_strategy = { .type = SM_UPDATE_CHECKOUT };
1954
1955 if (argc < 3 || argc > 4)
1956 die("submodule--helper update-module-clone expects <just-cloned> <path> [<update>]");
1957
1958 just_cloned = git_config_int("just_cloned", argv[1]);
1959 path = argv[2];
1960
1961 if (argc == 4)
1962 update = argv[3];
1963
1964 determine_submodule_update_strategy(the_repository,
1965 just_cloned, path, update,
1966 &update_strategy);
1967 fputs(submodule_strategy_to_string(&update_strategy), stdout);
1968
1969 return 0;
1970 }
1971
1972 struct update_clone_data {
1973 const struct submodule *sub;
1974 struct object_id oid;
1975 unsigned just_cloned;
1976 };
1977
1978 struct submodule_update_clone {
1979 /* index into 'list', the list of submodules to look into for cloning */
1980 int current;
1981 struct module_list list;
1982 unsigned warn_if_uninitialized : 1;
1983
1984 /* update parameter passed via commandline */
1985 struct submodule_update_strategy update;
1986
1987 /* configuration parameters which are passed on to the children */
1988 int progress;
1989 int quiet;
1990 int recommend_shallow;
1991 struct string_list references;
1992 int dissociate;
1993 unsigned require_init;
1994 const char *depth;
1995 const char *recursive_prefix;
1996 const char *prefix;
1997 int single_branch;
1998
1999 /* to be consumed by git-submodule.sh */
2000 struct update_clone_data *update_clone;
2001 int update_clone_nr; int update_clone_alloc;
2002
2003 /* If we want to stop as fast as possible and return an error */
2004 unsigned quickstop : 1;
2005
2006 /* failed clones to be retried again */
2007 const struct cache_entry **failed_clones;
2008 int failed_clones_nr, failed_clones_alloc;
2009
2010 int max_jobs;
2011 };
2012 #define SUBMODULE_UPDATE_CLONE_INIT { \
2013 .list = MODULE_LIST_INIT, \
2014 .update = SUBMODULE_UPDATE_STRATEGY_INIT, \
2015 .recommend_shallow = -1, \
2016 .references = STRING_LIST_INIT_DUP, \
2017 .single_branch = -1, \
2018 .max_jobs = 1, \
2019 }
2020
2021 struct update_data {
2022 const char *recursive_prefix;
2023 const char *sm_path;
2024 const char *displaypath;
2025 struct object_id oid;
2026 struct object_id suboid;
2027 struct submodule_update_strategy update_strategy;
2028 int depth;
2029 unsigned int force: 1;
2030 unsigned int quiet: 1;
2031 unsigned int nofetch: 1;
2032 unsigned int just_cloned: 1;
2033 };
2034 #define UPDATE_DATA_INIT { .update_strategy = SUBMODULE_UPDATE_STRATEGY_INIT }
2035
2036 static void next_submodule_warn_missing(struct submodule_update_clone *suc,
2037 struct strbuf *out, const char *displaypath)
2038 {
2039 /*
2040 * Only mention uninitialized submodules when their
2041 * paths have been specified.
2042 */
2043 if (suc->warn_if_uninitialized) {
2044 strbuf_addf(out,
2045 _("Submodule path '%s' not initialized"),
2046 displaypath);
2047 strbuf_addch(out, '\n');
2048 strbuf_addstr(out,
2049 _("Maybe you want to use 'update --init'?"));
2050 strbuf_addch(out, '\n');
2051 }
2052 }
2053
2054 /**
2055 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
2056 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
2057 */
2058 static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
2059 struct child_process *child,
2060 struct submodule_update_clone *suc,
2061 struct strbuf *out)
2062 {
2063 const struct submodule *sub = NULL;
2064 const char *url = NULL;
2065 const char *update_string;
2066 enum submodule_update_type update_type;
2067 char *key;
2068 struct strbuf displaypath_sb = STRBUF_INIT;
2069 struct strbuf sb = STRBUF_INIT;
2070 const char *displaypath = NULL;
2071 int needs_cloning = 0;
2072 int need_free_url = 0;
2073
2074 if (ce_stage(ce)) {
2075 if (suc->recursive_prefix)
2076 strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
2077 else
2078 strbuf_addstr(&sb, ce->name);
2079 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
2080 strbuf_addch(out, '\n');
2081 goto cleanup;
2082 }
2083
2084 sub = submodule_from_path(the_repository, null_oid(), ce->name);
2085
2086 if (suc->recursive_prefix)
2087 displaypath = relative_path(suc->recursive_prefix,
2088 ce->name, &displaypath_sb);
2089 else
2090 displaypath = ce->name;
2091
2092 if (!sub) {
2093 next_submodule_warn_missing(suc, out, displaypath);
2094 goto cleanup;
2095 }
2096
2097 key = xstrfmt("submodule.%s.update", sub->name);
2098 if (!repo_config_get_string_tmp(the_repository, key, &update_string)) {
2099 update_type = parse_submodule_update_type(update_string);
2100 } else {
2101 update_type = sub->update_strategy.type;
2102 }
2103 free(key);
2104
2105 if (suc->update.type == SM_UPDATE_NONE
2106 || (suc->update.type == SM_UPDATE_UNSPECIFIED
2107 && update_type == SM_UPDATE_NONE)) {
2108 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
2109 strbuf_addch(out, '\n');
2110 goto cleanup;
2111 }
2112
2113 /* Check if the submodule has been initialized. */
2114 if (!is_submodule_active(the_repository, ce->name)) {
2115 next_submodule_warn_missing(suc, out, displaypath);
2116 goto cleanup;
2117 }
2118
2119 strbuf_reset(&sb);
2120 strbuf_addf(&sb, "submodule.%s.url", sub->name);
2121 if (repo_config_get_string_tmp(the_repository, sb.buf, &url)) {
2122 if (starts_with_dot_slash(sub->url) ||
2123 starts_with_dot_dot_slash(sub->url)) {
2124 url = resolve_relative_url(sub->url, NULL, 0);
2125 need_free_url = 1;
2126 } else
2127 url = sub->url;
2128 }
2129
2130 strbuf_reset(&sb);
2131 strbuf_addf(&sb, "%s/.git", ce->name);
2132 needs_cloning = !file_exists(sb.buf);
2133
2134 ALLOC_GROW(suc->update_clone, suc->update_clone_nr + 1,
2135 suc->update_clone_alloc);
2136 oidcpy(&suc->update_clone[suc->update_clone_nr].oid, &ce->oid);
2137 suc->update_clone[suc->update_clone_nr].just_cloned = needs_cloning;
2138 suc->update_clone[suc->update_clone_nr].sub = sub;
2139 suc->update_clone_nr++;
2140
2141 if (!needs_cloning)
2142 goto cleanup;
2143
2144 child->git_cmd = 1;
2145 child->no_stdin = 1;
2146 child->stdout_to_stderr = 1;
2147 child->err = -1;
2148 strvec_push(&child->args, "submodule--helper");
2149 strvec_push(&child->args, "clone");
2150 if (suc->progress)
2151 strvec_push(&child->args, "--progress");
2152 if (suc->quiet)
2153 strvec_push(&child->args, "--quiet");
2154 if (suc->prefix)
2155 strvec_pushl(&child->args, "--prefix", suc->prefix, NULL);
2156 if (suc->recommend_shallow && sub->recommend_shallow == 1)
2157 strvec_push(&child->args, "--depth=1");
2158 if (suc->require_init)
2159 strvec_push(&child->args, "--require-init");
2160 strvec_pushl(&child->args, "--path", sub->path, NULL);
2161 strvec_pushl(&child->args, "--name", sub->name, NULL);
2162 strvec_pushl(&child->args, "--url", url, NULL);
2163 if (suc->references.nr) {
2164 struct string_list_item *item;
2165 for_each_string_list_item(item, &suc->references)
2166 strvec_pushl(&child->args, "--reference", item->string, NULL);
2167 }
2168 if (suc->dissociate)
2169 strvec_push(&child->args, "--dissociate");
2170 if (suc->depth)
2171 strvec_push(&child->args, suc->depth);
2172 if (suc->single_branch >= 0)
2173 strvec_push(&child->args, suc->single_branch ?
2174 "--single-branch" :
2175 "--no-single-branch");
2176
2177 cleanup:
2178 strbuf_release(&displaypath_sb);
2179 strbuf_release(&sb);
2180 if (need_free_url)
2181 free((void*)url);
2182
2183 return needs_cloning;
2184 }
2185
2186 static int update_clone_get_next_task(struct child_process *child,
2187 struct strbuf *err,
2188 void *suc_cb,
2189 void **idx_task_cb)
2190 {
2191 struct submodule_update_clone *suc = suc_cb;
2192 const struct cache_entry *ce;
2193 int index;
2194
2195 for (; suc->current < suc->list.nr; suc->current++) {
2196 ce = suc->list.entries[suc->current];
2197 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
2198 int *p = xmalloc(sizeof(*p));
2199 *p = suc->current;
2200 *idx_task_cb = p;
2201 suc->current++;
2202 return 1;
2203 }
2204 }
2205
2206 /*
2207 * The loop above tried cloning each submodule once, now try the
2208 * stragglers again, which we can imagine as an extension of the
2209 * entry list.
2210 */
2211 index = suc->current - suc->list.nr;
2212 if (index < suc->failed_clones_nr) {
2213 int *p;
2214 ce = suc->failed_clones[index];
2215 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
2216 suc->current ++;
2217 strbuf_addstr(err, "BUG: submodule considered for "
2218 "cloning, doesn't need cloning "
2219 "any more?\n");
2220 return 0;
2221 }
2222 p = xmalloc(sizeof(*p));
2223 *p = suc->current;
2224 *idx_task_cb = p;
2225 suc->current ++;
2226 return 1;
2227 }
2228
2229 return 0;
2230 }
2231
2232 static int update_clone_start_failure(struct strbuf *err,
2233 void *suc_cb,
2234 void *idx_task_cb)
2235 {
2236 struct submodule_update_clone *suc = suc_cb;
2237 suc->quickstop = 1;
2238 return 1;
2239 }
2240
2241 static int update_clone_task_finished(int result,
2242 struct strbuf *err,
2243 void *suc_cb,
2244 void *idx_task_cb)
2245 {
2246 const struct cache_entry *ce;
2247 struct submodule_update_clone *suc = suc_cb;
2248
2249 int *idxP = idx_task_cb;
2250 int idx = *idxP;
2251 free(idxP);
2252
2253 if (!result)
2254 return 0;
2255
2256 if (idx < suc->list.nr) {
2257 ce = suc->list.entries[idx];
2258 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
2259 ce->name);
2260 strbuf_addch(err, '\n');
2261 ALLOC_GROW(suc->failed_clones,
2262 suc->failed_clones_nr + 1,
2263 suc->failed_clones_alloc);
2264 suc->failed_clones[suc->failed_clones_nr++] = ce;
2265 return 0;
2266 } else {
2267 idx -= suc->list.nr;
2268 ce = suc->failed_clones[idx];
2269 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
2270 ce->name);
2271 strbuf_addch(err, '\n');
2272 suc->quickstop = 1;
2273 return 1;
2274 }
2275
2276 return 0;
2277 }
2278
2279 static int git_update_clone_config(const char *var, const char *value,
2280 void *cb)
2281 {
2282 int *max_jobs = cb;
2283 if (!strcmp(var, "submodule.fetchjobs"))
2284 *max_jobs = parse_submodule_fetchjobs(var, value);
2285 return 0;
2286 }
2287
2288 static int is_tip_reachable(const char *path, struct object_id *oid)
2289 {
2290 struct child_process cp = CHILD_PROCESS_INIT;
2291 struct strbuf rev = STRBUF_INIT;
2292 char *hex = oid_to_hex(oid);
2293
2294 cp.git_cmd = 1;
2295 cp.dir = xstrdup(path);
2296 cp.no_stderr = 1;
2297 strvec_pushl(&cp.args, "rev-list", "-n", "1", hex, "--not", "--all", NULL);
2298
2299 prepare_submodule_repo_env(&cp.env_array);
2300
2301 if (capture_command(&cp, &rev, GIT_MAX_HEXSZ + 1) || rev.len)
2302 return 0;
2303
2304 return 1;
2305 }
2306
2307 static int fetch_in_submodule(const char *module_path, int depth, int quiet, struct object_id *oid)
2308 {
2309 struct child_process cp = CHILD_PROCESS_INIT;
2310
2311 prepare_submodule_repo_env(&cp.env_array);
2312 cp.git_cmd = 1;
2313 cp.dir = xstrdup(module_path);
2314
2315 strvec_push(&cp.args, "fetch");
2316 if (quiet)
2317 strvec_push(&cp.args, "--quiet");
2318 if (depth)
2319 strvec_pushf(&cp.args, "--depth=%d", depth);
2320 if (oid) {
2321 char *hex = oid_to_hex(oid);
2322 char *remote = get_default_remote();
2323 strvec_pushl(&cp.args, remote, hex, NULL);
2324 }
2325
2326 return run_command(&cp);
2327 }
2328
2329 static int run_update_command(struct update_data *ud, int subforce)
2330 {
2331 struct strvec args = STRVEC_INIT;
2332 struct strvec child_env = STRVEC_INIT;
2333 char *oid = oid_to_hex(&ud->oid);
2334 int must_die_on_failure = 0;
2335 int git_cmd;
2336
2337 switch (ud->update_strategy.type) {
2338 case SM_UPDATE_CHECKOUT:
2339 git_cmd = 1;
2340 strvec_pushl(&args, "checkout", "-q", NULL);
2341 if (subforce)
2342 strvec_push(&args, "-f");
2343 break;
2344 case SM_UPDATE_REBASE:
2345 git_cmd = 1;
2346 strvec_push(&args, "rebase");
2347 if (ud->quiet)
2348 strvec_push(&args, "--quiet");
2349 must_die_on_failure = 1;
2350 break;
2351 case SM_UPDATE_MERGE:
2352 git_cmd = 1;
2353 strvec_push(&args, "merge");
2354 if (ud->quiet)
2355 strvec_push(&args, "--quiet");
2356 must_die_on_failure = 1;
2357 break;
2358 case SM_UPDATE_COMMAND:
2359 git_cmd = 0;
2360 strvec_push(&args, ud->update_strategy.command);
2361 must_die_on_failure = 1;
2362 break;
2363 default:
2364 BUG("unexpected update strategy type: %s",
2365 submodule_strategy_to_string(&ud->update_strategy));
2366 }
2367 strvec_push(&args, oid);
2368
2369 prepare_submodule_repo_env(&child_env);
2370 if (run_command_v_opt_cd_env(args.v, git_cmd ? RUN_GIT_CMD : RUN_USING_SHELL,
2371 ud->sm_path, child_env.v)) {
2372 switch (ud->update_strategy.type) {
2373 case SM_UPDATE_CHECKOUT:
2374 printf(_("Unable to checkout '%s' in submodule path '%s'"),
2375 oid, ud->displaypath);
2376 break;
2377 case SM_UPDATE_REBASE:
2378 printf(_("Unable to rebase '%s' in submodule path '%s'"),
2379 oid, ud->displaypath);
2380 break;
2381 case SM_UPDATE_MERGE:
2382 printf(_("Unable to merge '%s' in submodule path '%s'"),
2383 oid, ud->displaypath);
2384 break;
2385 case SM_UPDATE_COMMAND:
2386 printf(_("Execution of '%s %s' failed in submodule path '%s'"),
2387 ud->update_strategy.command, oid, ud->displaypath);
2388 break;
2389 default:
2390 BUG("unexpected update strategy type: %s",
2391 submodule_strategy_to_string(&ud->update_strategy));
2392 }
2393 /*
2394 * NEEDSWORK: We are currently printing to stdout with error
2395 * return so that the shell caller handles the error output
2396 * properly. Once we start handling the error messages within
2397 * C, we should use die() instead.
2398 */
2399 if (must_die_on_failure)
2400 return 2;
2401 /*
2402 * This signifies to the caller in shell that the command
2403 * failed without dying
2404 */
2405 return 1;
2406 }
2407
2408 switch (ud->update_strategy.type) {
2409 case SM_UPDATE_CHECKOUT:
2410 printf(_("Submodule path '%s': checked out '%s'\n"),
2411 ud->displaypath, oid);
2412 break;
2413 case SM_UPDATE_REBASE:
2414 printf(_("Submodule path '%s': rebased into '%s'\n"),
2415 ud->displaypath, oid);
2416 break;
2417 case SM_UPDATE_MERGE:
2418 printf(_("Submodule path '%s': merged in '%s'\n"),
2419 ud->displaypath, oid);
2420 break;
2421 case SM_UPDATE_COMMAND:
2422 printf(_("Submodule path '%s': '%s %s'\n"),
2423 ud->displaypath, ud->update_strategy.command, oid);
2424 break;
2425 default:
2426 BUG("unexpected update strategy type: %s",
2427 submodule_strategy_to_string(&ud->update_strategy));
2428 }
2429
2430 return 0;
2431 }
2432
2433 static int do_run_update_procedure(struct update_data *ud)
2434 {
2435 int subforce = is_null_oid(&ud->suboid) || ud->force;
2436
2437 if (!ud->nofetch) {
2438 /*
2439 * Run fetch only if `oid` isn't present or it
2440 * is not reachable from a ref.
2441 */
2442 if (!is_tip_reachable(ud->sm_path, &ud->oid) &&
2443 fetch_in_submodule(ud->sm_path, ud->depth, ud->quiet, NULL) &&
2444 !ud->quiet)
2445 fprintf_ln(stderr,
2446 _("Unable to fetch in submodule path '%s'; "
2447 "trying to directly fetch %s:"),
2448 ud->displaypath, oid_to_hex(&ud->oid));
2449 /*
2450 * Now we tried the usual fetch, but `oid` may
2451 * not be reachable from any of the refs.
2452 */
2453 if (!is_tip_reachable(ud->sm_path, &ud->oid) &&
2454 fetch_in_submodule(ud->sm_path, ud->depth, ud->quiet, &ud->oid))
2455 die(_("Fetched in submodule path '%s', but it did not "
2456 "contain %s. Direct fetching of that commit failed."),
2457 ud->displaypath, oid_to_hex(&ud->oid));
2458 }
2459
2460 return run_update_command(ud, subforce);
2461 }
2462
2463 static void update_submodule(struct update_clone_data *ucd)
2464 {
2465 fprintf(stdout, "dummy %s %d\t%s\n",
2466 oid_to_hex(&ucd->oid),
2467 ucd->just_cloned,
2468 ucd->sub->path);
2469 }
2470
2471 static int update_submodules(struct submodule_update_clone *suc)
2472 {
2473 int i;
2474
2475 run_processes_parallel_tr2(suc->max_jobs, update_clone_get_next_task,
2476 update_clone_start_failure,
2477 update_clone_task_finished, suc, "submodule",
2478 "parallel/update");
2479
2480 /*
2481 * We saved the output and put it out all at once now.
2482 * That means:
2483 * - the listener does not have to interleave their (checkout)
2484 * work with our fetching. The writes involved in a
2485 * checkout involve more straightforward sequential I/O.
2486 * - the listener can avoid doing any work if fetching failed.
2487 */
2488 if (suc->quickstop)
2489 return 1;
2490
2491 for (i = 0; i < suc->update_clone_nr; i++)
2492 update_submodule(&suc->update_clone[i]);
2493
2494 return 0;
2495 }
2496
2497 static int update_clone(int argc, const char **argv, const char *prefix)
2498 {
2499 const char *update = NULL;
2500 struct pathspec pathspec;
2501 struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
2502
2503 struct option module_update_clone_options[] = {
2504 OPT_STRING(0, "prefix", &prefix,
2505 N_("path"),
2506 N_("path into the working tree")),
2507 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
2508 N_("path"),
2509 N_("path into the working tree, across nested "
2510 "submodule boundaries")),
2511 OPT_STRING(0, "update", &update,
2512 N_("string"),
2513 N_("rebase, merge, checkout or none")),
2514 OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
2515 N_("reference repository")),
2516 OPT_BOOL(0, "dissociate", &suc.dissociate,
2517 N_("use --reference only while cloning")),
2518 OPT_STRING(0, "depth", &suc.depth, "<depth>",
2519 N_("create a shallow clone truncated to the "
2520 "specified number of revisions")),
2521 OPT_INTEGER('j', "jobs", &suc.max_jobs,
2522 N_("parallel jobs")),
2523 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
2524 N_("whether the initial clone should follow the shallow recommendation")),
2525 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
2526 OPT_BOOL(0, "progress", &suc.progress,
2527 N_("force cloning progress")),
2528 OPT_BOOL(0, "require-init", &suc.require_init,
2529 N_("disallow cloning into non-empty directory")),
2530 OPT_BOOL(0, "single-branch", &suc.single_branch,
2531 N_("clone only one branch, HEAD or --branch")),
2532 OPT_END()
2533 };
2534
2535 const char *const git_submodule_helper_usage[] = {
2536 N_("git submodule--helper update-clone [--prefix=<path>] [<path>...]"),
2537 NULL
2538 };
2539 suc.prefix = prefix;
2540
2541 update_clone_config_from_gitmodules(&suc.max_jobs);
2542 git_config(git_update_clone_config, &suc.max_jobs);
2543
2544 argc = parse_options(argc, argv, prefix, module_update_clone_options,
2545 git_submodule_helper_usage, 0);
2546
2547 if (update)
2548 if (parse_submodule_update_strategy(update, &suc.update) < 0)
2549 die(_("bad value for update parameter"));
2550
2551 if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
2552 return 1;
2553
2554 if (pathspec.nr)
2555 suc.warn_if_uninitialized = 1;
2556
2557 return update_submodules(&suc);
2558 }
2559
2560 static int run_update_procedure(int argc, const char **argv, const char *prefix)
2561 {
2562 int force = 0, quiet = 0, nofetch = 0, just_cloned = 0;
2563 char *prefixed_path, *update = NULL;
2564 struct update_data update_data = UPDATE_DATA_INIT;
2565
2566 struct option options[] = {
2567 OPT__QUIET(&quiet, N_("suppress output for update by rebase or merge")),
2568 OPT__FORCE(&force, N_("force checkout updates"), 0),
2569 OPT_BOOL('N', "no-fetch", &nofetch,
2570 N_("don't fetch new objects from the remote site")),
2571 OPT_BOOL(0, "just-cloned", &just_cloned,
2572 N_("overrides update mode in case the repository is a fresh clone")),
2573 OPT_INTEGER(0, "depth", &update_data.depth, N_("depth for shallow fetch")),
2574 OPT_STRING(0, "prefix", &prefix,
2575 N_("path"),
2576 N_("path into the working tree")),
2577 OPT_STRING(0, "update", &update,
2578 N_("string"),
2579 N_("rebase, merge, checkout or none")),
2580 OPT_STRING(0, "recursive-prefix", &update_data.recursive_prefix, N_("path"),
2581 N_("path into the working tree, across nested "
2582 "submodule boundaries")),
2583 OPT_CALLBACK_F(0, "oid", &update_data.oid, N_("sha1"),
2584 N_("SHA1 expected by superproject"), PARSE_OPT_NONEG,
2585 parse_opt_object_id),
2586 OPT_CALLBACK_F(0, "suboid", &update_data.suboid, N_("subsha1"),
2587 N_("SHA1 of submodule's HEAD"), PARSE_OPT_NONEG,
2588 parse_opt_object_id),
2589 OPT_END()
2590 };
2591
2592 const char *const usage[] = {
2593 N_("git submodule--helper run-update-procedure [<options>] <path>"),
2594 NULL
2595 };
2596
2597 argc = parse_options(argc, argv, prefix, options, usage, 0);
2598
2599 if (argc != 1)
2600 usage_with_options(usage, options);
2601
2602 update_data.force = !!force;
2603 update_data.quiet = !!quiet;
2604 update_data.nofetch = !!nofetch;
2605 update_data.just_cloned = !!just_cloned;
2606 update_data.sm_path = argv[0];
2607
2608 if (update_data.recursive_prefix)
2609 prefixed_path = xstrfmt("%s%s", update_data.recursive_prefix, update_data.sm_path);
2610 else
2611 prefixed_path = xstrdup(update_data.sm_path);
2612
2613 update_data.displaypath = get_submodule_displaypath(prefixed_path, prefix);
2614
2615 determine_submodule_update_strategy(the_repository, update_data.just_cloned,
2616 update_data.sm_path, update,
2617 &update_data.update_strategy);
2618
2619 free(prefixed_path);
2620
2621 if (!oideq(&update_data.oid, &update_data.suboid) || update_data.force)
2622 return do_run_update_procedure(&update_data);
2623
2624 return 3;
2625 }
2626
2627 static int resolve_relative_path(int argc, const char **argv, const char *prefix)
2628 {
2629 struct strbuf sb = STRBUF_INIT;
2630 if (argc != 3)
2631 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
2632
2633 printf("%s", relative_path(argv[1], argv[2], &sb));
2634 strbuf_release(&sb);
2635 return 0;
2636 }
2637
2638 static const char *remote_submodule_branch(const char *path)
2639 {
2640 const struct submodule *sub;
2641 const char *branch = NULL;
2642 char *key;
2643
2644 sub = submodule_from_path(the_repository, null_oid(), path);
2645 if (!sub)
2646 return NULL;
2647
2648 key = xstrfmt("submodule.%s.branch", sub->name);
2649 if (repo_config_get_string_tmp(the_repository, key, &branch))
2650 branch = sub->branch;
2651 free(key);
2652
2653 if (!branch)
2654 return "HEAD";
2655
2656 if (!strcmp(branch, ".")) {
2657 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
2658
2659 if (!refname)
2660 die(_("No such ref: %s"), "HEAD");
2661
2662 /* detached HEAD */
2663 if (!strcmp(refname, "HEAD"))
2664 die(_("Submodule (%s) branch configured to inherit "
2665 "branch from superproject, but the superproject "
2666 "is not on any branch"), sub->name);
2667
2668 if (!skip_prefix(refname, "refs/heads/", &refname))
2669 die(_("Expecting a full ref name, got %s"), refname);
2670 return refname;
2671 }
2672
2673 return branch;
2674 }
2675
2676 static int resolve_remote_submodule_branch(int argc, const char **argv,
2677 const char *prefix)
2678 {
2679 const char *ret;
2680 struct strbuf sb = STRBUF_INIT;
2681 if (argc != 2)
2682 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
2683
2684 ret = remote_submodule_branch(argv[1]);
2685 if (!ret)
2686 die("submodule %s doesn't exist", argv[1]);
2687
2688 printf("%s", ret);
2689 strbuf_release(&sb);
2690 return 0;
2691 }
2692
2693 static int push_check(int argc, const char **argv, const char *prefix)
2694 {
2695 struct remote *remote;
2696 const char *superproject_head;
2697 char *head;
2698 int detached_head = 0;
2699 struct object_id head_oid;
2700
2701 if (argc < 3)
2702 die("submodule--helper push-check requires at least 2 arguments");
2703
2704 /*
2705 * superproject's resolved head ref.
2706 * if HEAD then the superproject is in a detached head state, otherwise
2707 * it will be the resolved head ref.
2708 */
2709 superproject_head = argv[1];
2710 argv++;
2711 argc--;
2712 /* Get the submodule's head ref and determine if it is detached */
2713 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
2714 if (!head)
2715 die(_("Failed to resolve HEAD as a valid ref."));
2716 if (!strcmp(head, "HEAD"))
2717 detached_head = 1;
2718
2719 /*
2720 * The remote must be configured.
2721 * This is to avoid pushing to the exact same URL as the parent.
2722 */
2723 remote = pushremote_get(argv[1]);
2724 if (!remote || remote->origin == REMOTE_UNCONFIGURED)
2725 die("remote '%s' not configured", argv[1]);
2726
2727 /* Check the refspec */
2728 if (argc > 2) {
2729 int i;
2730 struct ref *local_refs = get_local_heads();
2731 struct refspec refspec = REFSPEC_INIT_PUSH;
2732
2733 refspec_appendn(&refspec, argv + 2, argc - 2);
2734
2735 for (i = 0; i < refspec.nr; i++) {
2736 const struct refspec_item *rs = &refspec.items[i];
2737
2738 if (rs->pattern || rs->matching)
2739 continue;
2740
2741 /* LHS must match a single ref */
2742 switch (count_refspec_match(rs->src, local_refs, NULL)) {
2743 case 1:
2744 break;
2745 case 0:
2746 /*
2747 * If LHS matches 'HEAD' then we need to ensure
2748 * that it matches the same named branch
2749 * checked out in the superproject.
2750 */
2751 if (!strcmp(rs->src, "HEAD")) {
2752 if (!detached_head &&
2753 !strcmp(head, superproject_head))
2754 break;
2755 die("HEAD does not match the named branch in the superproject");
2756 }
2757 /* fallthrough */
2758 default:
2759 die("src refspec '%s' must name a ref",
2760 rs->src);
2761 }
2762 }
2763 refspec_clear(&refspec);
2764 }
2765 free(head);
2766
2767 return 0;
2768 }
2769
2770 static int ensure_core_worktree(int argc, const char **argv, const char *prefix)
2771 {
2772 const char *path;
2773 const char *cw;
2774 struct repository subrepo;
2775
2776 if (argc != 2)
2777 BUG("submodule--helper ensure-core-worktree <path>");
2778
2779 path = argv[1];
2780
2781 if (repo_submodule_init(&subrepo, the_repository, path, null_oid()))
2782 die(_("could not get a repository handle for submodule '%s'"), path);
2783
2784 if (!repo_config_get_string_tmp(&subrepo, "core.worktree", &cw)) {
2785 char *cfg_file, *abs_path;
2786 const char *rel_path;
2787 struct strbuf sb = STRBUF_INIT;
2788
2789 cfg_file = repo_git_path(&subrepo, "config");
2790
2791 abs_path = absolute_pathdup(path);
2792 rel_path = relative_path(abs_path, subrepo.gitdir, &sb);
2793
2794 git_config_set_in_file(cfg_file, "core.worktree", rel_path);
2795
2796 free(cfg_file);
2797 free(abs_path);
2798 strbuf_release(&sb);
2799 }
2800
2801 return 0;
2802 }
2803
2804 static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
2805 {
2806 int i;
2807 struct pathspec pathspec;
2808 struct module_list list = MODULE_LIST_INIT;
2809 unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
2810
2811 struct option embed_gitdir_options[] = {
2812 OPT_STRING(0, "prefix", &prefix,
2813 N_("path"),
2814 N_("path into the working tree")),
2815 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
2816 ABSORB_GITDIR_RECURSE_SUBMODULES),
2817 OPT_END()
2818 };
2819
2820 const char *const git_submodule_helper_usage[] = {
2821 N_("git submodule--helper absorb-git-dirs [<options>] [<path>...]"),
2822 NULL
2823 };
2824
2825 argc = parse_options(argc, argv, prefix, embed_gitdir_options,
2826 git_submodule_helper_usage, 0);
2827
2828 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
2829 return 1;
2830
2831 for (i = 0; i < list.nr; i++)
2832 absorb_git_dir_into_superproject(list.entries[i]->name, flags);
2833
2834 return 0;
2835 }
2836
2837 static int is_active(int argc, const char **argv, const char *prefix)
2838 {
2839 if (argc != 2)
2840 die("submodule--helper is-active takes exactly 1 argument");
2841
2842 return !is_submodule_active(the_repository, argv[1]);
2843 }
2844
2845 /*
2846 * Exit non-zero if any of the submodule names given on the command line is
2847 * invalid. If no names are given, filter stdin to print only valid names
2848 * (which is primarily intended for testing).
2849 */
2850 static int check_name(int argc, const char **argv, const char *prefix)
2851 {
2852 if (argc > 1) {
2853 while (*++argv) {
2854 if (check_submodule_name(*argv) < 0)
2855 return 1;
2856 }
2857 } else {
2858 struct strbuf buf = STRBUF_INIT;
2859 while (strbuf_getline(&buf, stdin) != EOF) {
2860 if (!check_submodule_name(buf.buf))
2861 printf("%s\n", buf.buf);
2862 }
2863 strbuf_release(&buf);
2864 }
2865 return 0;
2866 }
2867
2868 static int module_config(int argc, const char **argv, const char *prefix)
2869 {
2870 enum {
2871 CHECK_WRITEABLE = 1,
2872 DO_UNSET = 2
2873 } command = 0;
2874
2875 struct option module_config_options[] = {
2876 OPT_CMDMODE(0, "check-writeable", &command,
2877 N_("check if it is safe to write to the .gitmodules file"),
2878 CHECK_WRITEABLE),
2879 OPT_CMDMODE(0, "unset", &command,
2880 N_("unset the config in the .gitmodules file"),
2881 DO_UNSET),
2882 OPT_END()
2883 };
2884 const char *const git_submodule_helper_usage[] = {
2885 N_("git submodule--helper config <name> [<value>]"),
2886 N_("git submodule--helper config --unset <name>"),
2887 N_("git submodule--helper config --check-writeable"),
2888 NULL
2889 };
2890
2891 argc = parse_options(argc, argv, prefix, module_config_options,
2892 git_submodule_helper_usage, PARSE_OPT_KEEP_ARGV0);
2893
2894 if (argc == 1 && command == CHECK_WRITEABLE)
2895 return is_writing_gitmodules_ok() ? 0 : -1;
2896
2897 /* Equivalent to ACTION_GET in builtin/config.c */
2898 if (argc == 2 && command != DO_UNSET)
2899 return print_config_from_gitmodules(the_repository, argv[1]);
2900
2901 /* Equivalent to ACTION_SET in builtin/config.c */
2902 if (argc == 3 || (argc == 2 && command == DO_UNSET)) {
2903 const char *value = (argc == 3) ? argv[2] : NULL;
2904
2905 if (!is_writing_gitmodules_ok())
2906 die(_("please make sure that the .gitmodules file is in the working tree"));
2907
2908 return config_set_in_gitmodules_file_gently(argv[1], value);
2909 }
2910
2911 usage_with_options(git_submodule_helper_usage, module_config_options);
2912 }
2913
2914 static int module_set_url(int argc, const char **argv, const char *prefix)
2915 {
2916 int quiet = 0;
2917 const char *newurl;
2918 const char *path;
2919 char *config_name;
2920
2921 struct option options[] = {
2922 OPT__QUIET(&quiet, N_("suppress output for setting url of a submodule")),
2923 OPT_END()
2924 };
2925 const char *const usage[] = {
2926 N_("git submodule--helper set-url [--quiet] <path> <newurl>"),
2927 NULL
2928 };
2929
2930 argc = parse_options(argc, argv, prefix, options, usage, 0);
2931
2932 if (argc != 2 || !(path = argv[0]) || !(newurl = argv[1]))
2933 usage_with_options(usage, options);
2934
2935 config_name = xstrfmt("submodule.%s.url", path);
2936
2937 config_set_in_gitmodules_file_gently(config_name, newurl);
2938 sync_submodule(path, prefix, quiet ? OPT_QUIET : 0);
2939
2940 free(config_name);
2941
2942 return 0;
2943 }
2944
2945 static int module_set_branch(int argc, const char **argv, const char *prefix)
2946 {
2947 int opt_default = 0, ret;
2948 const char *opt_branch = NULL;
2949 const char *path;
2950 char *config_name;
2951
2952 /*
2953 * We accept the `quiet` option for uniformity across subcommands,
2954 * though there is nothing to make less verbose in this subcommand.
2955 */
2956 struct option options[] = {
2957 OPT_NOOP_NOARG('q', "quiet"),
2958 OPT_BOOL('d', "default", &opt_default,
2959 N_("set the default tracking branch to master")),
2960 OPT_STRING('b', "branch", &opt_branch, N_("branch"),
2961 N_("set the default tracking branch")),
2962 OPT_END()
2963 };
2964 const char *const usage[] = {
2965 N_("git submodule--helper set-branch [-q|--quiet] (-d|--default) <path>"),
2966 N_("git submodule--helper set-branch [-q|--quiet] (-b|--branch) <branch> <path>"),
2967 NULL
2968 };
2969
2970 argc = parse_options(argc, argv, prefix, options, usage, 0);
2971
2972 if (!opt_branch && !opt_default)
2973 die(_("--branch or --default required"));
2974
2975 if (opt_branch && opt_default)
2976 die(_("options '%s' and '%s' cannot be used together"), "--branch", "--default");
2977
2978 if (argc != 1 || !(path = argv[0]))
2979 usage_with_options(usage, options);
2980
2981 config_name = xstrfmt("submodule.%s.branch", path);
2982 ret = config_set_in_gitmodules_file_gently(config_name, opt_branch);
2983
2984 free(config_name);
2985 return !!ret;
2986 }
2987
2988 static int module_create_branch(int argc, const char **argv, const char *prefix)
2989 {
2990 enum branch_track track;
2991 int quiet = 0, force = 0, reflog = 0, dry_run = 0;
2992
2993 struct option options[] = {
2994 OPT__QUIET(&quiet, N_("print only error messages")),
2995 OPT__FORCE(&force, N_("force creation"), 0),
2996 OPT_BOOL(0, "create-reflog", &reflog,
2997 N_("create the branch's reflog")),
2998 OPT_SET_INT('t', "track", &track,
2999 N_("set up tracking mode (see git-pull(1))"),
3000 BRANCH_TRACK_EXPLICIT),
3001 OPT__DRY_RUN(&dry_run,
3002 N_("show whether the branch would be created")),
3003 OPT_END()
3004 };
3005 const char *const usage[] = {
3006 N_("git submodule--helper create-branch [-f|--force] [--create-reflog] [-q|--quiet] [-t|--track] [-n|--dry-run] <name> <start_oid> <start_name>"),
3007 NULL
3008 };
3009
3010 git_config(git_default_config, NULL);
3011 track = git_branch_track;
3012 argc = parse_options(argc, argv, prefix, options, usage, 0);
3013
3014 if (argc != 3)
3015 usage_with_options(usage, options);
3016
3017 if (!quiet && !dry_run)
3018 printf_ln(_("creating branch '%s'"), argv[0]);
3019
3020 create_branches_recursively(the_repository, argv[0], argv[1], argv[2],
3021 force, reflog, quiet, track, dry_run);
3022 return 0;
3023 }
3024 struct add_data {
3025 const char *prefix;
3026 const char *branch;
3027 const char *reference_path;
3028 char *sm_path;
3029 const char *sm_name;
3030 const char *repo;
3031 const char *realrepo;
3032 int depth;
3033 unsigned int force: 1;
3034 unsigned int quiet: 1;
3035 unsigned int progress: 1;
3036 unsigned int dissociate: 1;
3037 };
3038 #define ADD_DATA_INIT { .depth = -1 }
3039
3040 static void append_fetch_remotes(struct strbuf *msg, const char *git_dir_path)
3041 {
3042 struct child_process cp_remote = CHILD_PROCESS_INIT;
3043 struct strbuf sb_remote_out = STRBUF_INIT;
3044
3045 cp_remote.git_cmd = 1;
3046 strvec_pushf(&cp_remote.env_array,
3047 "GIT_DIR=%s", git_dir_path);
3048 strvec_push(&cp_remote.env_array, "GIT_WORK_TREE=.");
3049 strvec_pushl(&cp_remote.args, "remote", "-v", NULL);
3050 if (!capture_command(&cp_remote, &sb_remote_out, 0)) {
3051 char *next_line;
3052 char *line = sb_remote_out.buf;
3053 while ((next_line = strchr(line, '\n')) != NULL) {
3054 size_t len = next_line - line;
3055 if (strip_suffix_mem(line, &len, " (fetch)"))
3056 strbuf_addf(msg, " %.*s\n", (int)len, line);
3057 line = next_line + 1;
3058 }
3059 }
3060
3061 strbuf_release(&sb_remote_out);
3062 }
3063
3064 static int add_submodule(const struct add_data *add_data)
3065 {
3066 char *submod_gitdir_path;
3067 struct module_clone_data clone_data = MODULE_CLONE_DATA_INIT;
3068
3069 /* perhaps the path already exists and is already a git repo, else clone it */
3070 if (is_directory(add_data->sm_path)) {
3071 struct strbuf sm_path = STRBUF_INIT;
3072 strbuf_addstr(&sm_path, add_data->sm_path);
3073 submod_gitdir_path = xstrfmt("%s/.git", add_data->sm_path);
3074 if (is_nonbare_repository_dir(&sm_path))
3075 printf(_("Adding existing repo at '%s' to the index\n"),
3076 add_data->sm_path);
3077 else
3078 die(_("'%s' already exists and is not a valid git repo"),
3079 add_data->sm_path);
3080 strbuf_release(&sm_path);
3081 free(submod_gitdir_path);
3082 } else {
3083 struct child_process cp = CHILD_PROCESS_INIT;
3084 submod_gitdir_path = xstrfmt(".git/modules/%s", add_data->sm_name);
3085
3086 if (is_directory(submod_gitdir_path)) {
3087 if (!add_data->force) {
3088 struct strbuf msg = STRBUF_INIT;
3089 char *die_msg;
3090
3091 strbuf_addf(&msg, _("A git directory for '%s' is found "
3092 "locally with remote(s):\n"),
3093 add_data->sm_name);
3094
3095 append_fetch_remotes(&msg, submod_gitdir_path);
3096 free(submod_gitdir_path);
3097
3098 strbuf_addf(&msg, _("If you want to reuse this local git "
3099 "directory instead of cloning again from\n"
3100 " %s\n"
3101 "use the '--force' option. If the local git "
3102 "directory is not the correct repo\n"
3103 "or you are unsure what this means choose "
3104 "another name with the '--name' option."),
3105 add_data->realrepo);
3106
3107 die_msg = strbuf_detach(&msg, NULL);
3108 die("%s", die_msg);
3109 } else {
3110 printf(_("Reactivating local git directory for "
3111 "submodule '%s'\n"), add_data->sm_name);
3112 }
3113 }
3114 free(submod_gitdir_path);
3115
3116 clone_data.prefix = add_data->prefix;
3117 clone_data.path = add_data->sm_path;
3118 clone_data.name = add_data->sm_name;
3119 clone_data.url = add_data->realrepo;
3120 clone_data.quiet = add_data->quiet;
3121 clone_data.progress = add_data->progress;
3122 if (add_data->reference_path)
3123 string_list_append(&clone_data.reference,
3124 xstrdup(add_data->reference_path));
3125 clone_data.dissociate = add_data->dissociate;
3126 if (add_data->depth >= 0)
3127 clone_data.depth = xstrfmt("%d", add_data->depth);
3128
3129 if (clone_submodule(&clone_data))
3130 return -1;
3131
3132 prepare_submodule_repo_env(&cp.env_array);
3133 cp.git_cmd = 1;
3134 cp.dir = add_data->sm_path;
3135 /*
3136 * NOTE: we only get here if add_data->force is true, so
3137 * passing --force to checkout is reasonable.
3138 */
3139 strvec_pushl(&cp.args, "checkout", "-f", "-q", NULL);
3140
3141 if (add_data->branch) {
3142 strvec_pushl(&cp.args, "-B", add_data->branch, NULL);
3143 strvec_pushf(&cp.args, "origin/%s", add_data->branch);
3144 }
3145
3146 if (run_command(&cp))
3147 die(_("unable to checkout submodule '%s'"), add_data->sm_path);
3148 }
3149 return 0;
3150 }
3151
3152 static int config_submodule_in_gitmodules(const char *name, const char *var, const char *value)
3153 {
3154 char *key;
3155 int ret;
3156
3157 if (!is_writing_gitmodules_ok())
3158 die(_("please make sure that the .gitmodules file is in the working tree"));
3159
3160 key = xstrfmt("submodule.%s.%s", name, var);
3161 ret = config_set_in_gitmodules_file_gently(key, value);
3162 free(key);
3163
3164 return ret;
3165 }
3166
3167 static void configure_added_submodule(struct add_data *add_data)
3168 {
3169 char *key;
3170 char *val = NULL;
3171 struct child_process add_submod = CHILD_PROCESS_INIT;
3172 struct child_process add_gitmodules = CHILD_PROCESS_INIT;
3173
3174 key = xstrfmt("submodule.%s.url", add_data->sm_name);
3175 git_config_set_gently(key, add_data->realrepo);
3176 free(key);
3177
3178 add_submod.git_cmd = 1;
3179 strvec_pushl(&add_submod.args, "add",
3180 "--no-warn-embedded-repo", NULL);
3181 if (add_data->force)
3182 strvec_push(&add_submod.args, "--force");
3183 strvec_pushl(&add_submod.args, "--", add_data->sm_path, NULL);
3184
3185 if (run_command(&add_submod))
3186 die(_("Failed to add submodule '%s'"), add_data->sm_path);
3187
3188 if (config_submodule_in_gitmodules(add_data->sm_name, "path", add_data->sm_path) ||
3189 config_submodule_in_gitmodules(add_data->sm_name, "url", add_data->repo))
3190 die(_("Failed to register submodule '%s'"), add_data->sm_path);
3191
3192 if (add_data->branch) {
3193 if (config_submodule_in_gitmodules(add_data->sm_name,
3194 "branch", add_data->branch))
3195 die(_("Failed to register submodule '%s'"), add_data->sm_path);
3196 }
3197
3198 add_gitmodules.git_cmd = 1;
3199 strvec_pushl(&add_gitmodules.args,
3200 "add", "--force", "--", ".gitmodules", NULL);
3201
3202 if (run_command(&add_gitmodules))
3203 die(_("Failed to register submodule '%s'"), add_data->sm_path);
3204
3205 /*
3206 * NEEDSWORK: In a multi-working-tree world this needs to be
3207 * set in the per-worktree config.
3208 */
3209 /*
3210 * NEEDSWORK: In the longer run, we need to get rid of this
3211 * pattern of querying "submodule.active" before calling
3212 * is_submodule_active(), since that function needs to find
3213 * out the value of "submodule.active" again anyway.
3214 */
3215 if (!git_config_get_string("submodule.active", &val) && val) {
3216 /*
3217 * If the submodule being added isn't already covered by the
3218 * current configured pathspec, set the submodule's active flag
3219 */
3220 if (!is_submodule_active(the_repository, add_data->sm_path)) {
3221 key = xstrfmt("submodule.%s.active", add_data->sm_name);
3222 git_config_set_gently(key, "true");
3223 free(key);
3224 }
3225 } else {
3226 key = xstrfmt("submodule.%s.active", add_data->sm_name);
3227 git_config_set_gently(key, "true");
3228 free(key);
3229 }
3230 }
3231
3232 static void die_on_index_match(const char *path, int force)
3233 {
3234 struct pathspec ps;
3235 const char *args[] = { path, NULL };
3236 parse_pathspec(&ps, 0, PATHSPEC_PREFER_CWD, NULL, args);
3237
3238 if (read_cache_preload(NULL) < 0)
3239 die(_("index file corrupt"));
3240
3241 if (ps.nr) {
3242 int i;
3243 char *ps_matched = xcalloc(ps.nr, 1);
3244
3245 /* TODO: audit for interaction with sparse-index. */
3246 ensure_full_index(&the_index);
3247
3248 /*
3249 * Since there is only one pathspec, we just need
3250 * need to check ps_matched[0] to know if a cache
3251 * entry matched.
3252 */
3253 for (i = 0; i < active_nr; i++) {
3254 ce_path_match(&the_index, active_cache[i], &ps,
3255 ps_matched);
3256
3257 if (ps_matched[0]) {
3258 if (!force)
3259 die(_("'%s' already exists in the index"),
3260 path);
3261 if (!S_ISGITLINK(active_cache[i]->ce_mode))
3262 die(_("'%s' already exists in the index "
3263 "and is not a submodule"), path);
3264 break;
3265 }
3266 }
3267 free(ps_matched);
3268 }
3269 clear_pathspec(&ps);
3270 }
3271
3272 static void die_on_repo_without_commits(const char *path)
3273 {
3274 struct strbuf sb = STRBUF_INIT;
3275 strbuf_addstr(&sb, path);
3276 if (is_nonbare_repository_dir(&sb)) {
3277 struct object_id oid;
3278 if (resolve_gitlink_ref(path, "HEAD", &oid) < 0)
3279 die(_("'%s' does not have a commit checked out"), path);
3280 }
3281 strbuf_release(&sb);
3282 }
3283
3284 static int module_add(int argc, const char **argv, const char *prefix)
3285 {
3286 int force = 0, quiet = 0, progress = 0, dissociate = 0;
3287 struct add_data add_data = ADD_DATA_INIT;
3288
3289 struct option options[] = {
3290 OPT_STRING('b', "branch", &add_data.branch, N_("branch"),
3291 N_("branch of repository to add as submodule")),
3292 OPT__FORCE(&force, N_("allow adding an otherwise ignored submodule path"),
3293 PARSE_OPT_NOCOMPLETE),
3294 OPT__QUIET(&quiet, N_("print only error messages")),
3295 OPT_BOOL(0, "progress", &progress, N_("force cloning progress")),
3296 OPT_STRING(0, "reference", &add_data.reference_path, N_("repository"),
3297 N_("reference repository")),
3298 OPT_BOOL(0, "dissociate", &dissociate, N_("borrow the objects from reference repositories")),
3299 OPT_STRING(0, "name", &add_data.sm_name, N_("name"),
3300 N_("sets the submodule’s name to the given string "
3301 "instead of defaulting to its path")),
3302 OPT_INTEGER(0, "depth", &add_data.depth, N_("depth for shallow clones")),
3303 OPT_END()
3304 };
3305
3306 const char *const usage[] = {
3307 N_("git submodule--helper add [<options>] [--] <repository> [<path>]"),
3308 NULL
3309 };
3310
3311 argc = parse_options(argc, argv, prefix, options, usage, 0);
3312
3313 if (!is_writing_gitmodules_ok())
3314 die(_("please make sure that the .gitmodules file is in the working tree"));
3315
3316 if (prefix && *prefix &&
3317 add_data.reference_path && !is_absolute_path(add_data.reference_path))
3318 add_data.reference_path = xstrfmt("%s%s", prefix, add_data.reference_path);
3319
3320 if (argc == 0 || argc > 2)
3321 usage_with_options(usage, options);
3322
3323 add_data.repo = argv[0];
3324 if (argc == 1)
3325 add_data.sm_path = git_url_basename(add_data.repo, 0, 0);
3326 else
3327 add_data.sm_path = xstrdup(argv[1]);
3328
3329 if (prefix && *prefix && !is_absolute_path(add_data.sm_path))
3330 add_data.sm_path = xstrfmt("%s%s", prefix, add_data.sm_path);
3331
3332 if (starts_with_dot_dot_slash(add_data.repo) ||
3333 starts_with_dot_slash(add_data.repo)) {
3334 if (prefix)
3335 die(_("Relative path can only be used from the toplevel "
3336 "of the working tree"));
3337
3338 /* dereference source url relative to parent's url */
3339 add_data.realrepo = resolve_relative_url(add_data.repo, NULL, 1);
3340 } else if (is_dir_sep(add_data.repo[0]) || strchr(add_data.repo, ':')) {
3341 add_data.realrepo = add_data.repo;
3342 } else {
3343 die(_("repo URL: '%s' must be absolute or begin with ./|../"),
3344 add_data.repo);
3345 }
3346
3347 /*
3348 * normalize path:
3349 * multiple //; leading ./; /./; /../;
3350 */
3351 normalize_path_copy(add_data.sm_path, add_data.sm_path);
3352 strip_dir_trailing_slashes(add_data.sm_path);
3353
3354 die_on_index_match(add_data.sm_path, force);
3355 die_on_repo_without_commits(add_data.sm_path);
3356
3357 if (!force) {
3358 int exit_code = -1;
3359 struct strbuf sb = STRBUF_INIT;
3360 struct child_process cp = CHILD_PROCESS_INIT;
3361 cp.git_cmd = 1;
3362 cp.no_stdout = 1;
3363 strvec_pushl(&cp.args, "add", "--dry-run", "--ignore-missing",
3364 "--no-warn-embedded-repo", add_data.sm_path, NULL);
3365 if ((exit_code = pipe_command(&cp, NULL, 0, NULL, 0, &sb, 0))) {
3366 strbuf_complete_line(&sb);
3367 fputs(sb.buf, stderr);
3368 free(add_data.sm_path);
3369 return exit_code;
3370 }
3371 strbuf_release(&sb);
3372 }
3373
3374 if(!add_data.sm_name)
3375 add_data.sm_name = add_data.sm_path;
3376
3377 if (check_submodule_name(add_data.sm_name))
3378 die(_("'%s' is not a valid submodule name"), add_data.sm_name);
3379
3380 add_data.prefix = prefix;
3381 add_data.force = !!force;
3382 add_data.quiet = !!quiet;
3383 add_data.progress = !!progress;
3384 add_data.dissociate = !!dissociate;
3385
3386 if (add_submodule(&add_data)) {
3387 free(add_data.sm_path);
3388 return 1;
3389 }
3390 configure_added_submodule(&add_data);
3391 free(add_data.sm_path);
3392
3393 return 0;
3394 }
3395
3396 #define SUPPORT_SUPER_PREFIX (1<<0)
3397
3398 struct cmd_struct {
3399 const char *cmd;
3400 int (*fn)(int, const char **, const char *);
3401 unsigned option;
3402 };
3403
3404 static struct cmd_struct commands[] = {
3405 {"list", module_list, 0},
3406 {"name", module_name, 0},
3407 {"clone", module_clone, 0},
3408 {"add", module_add, SUPPORT_SUPER_PREFIX},
3409 {"update-module-mode", module_update_module_mode, 0},
3410 {"update-clone", update_clone, 0},
3411 {"run-update-procedure", run_update_procedure, 0},
3412 {"ensure-core-worktree", ensure_core_worktree, 0},
3413 {"relative-path", resolve_relative_path, 0},
3414 {"resolve-relative-url-test", resolve_relative_url_test, 0},
3415 {"foreach", module_foreach, SUPPORT_SUPER_PREFIX},
3416 {"init", module_init, SUPPORT_SUPER_PREFIX},
3417 {"status", module_status, SUPPORT_SUPER_PREFIX},
3418 {"print-default-remote", print_default_remote, 0},
3419 {"sync", module_sync, SUPPORT_SUPER_PREFIX},
3420 {"deinit", module_deinit, 0},
3421 {"summary", module_summary, SUPPORT_SUPER_PREFIX},
3422 {"remote-branch", resolve_remote_submodule_branch, 0},
3423 {"push-check", push_check, 0},
3424 {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
3425 {"is-active", is_active, 0},
3426 {"check-name", check_name, 0},
3427 {"config", module_config, 0},
3428 {"set-url", module_set_url, 0},
3429 {"set-branch", module_set_branch, 0},
3430 {"create-branch", module_create_branch, 0},
3431 };
3432
3433 int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
3434 {
3435 int i;
3436 if (argc < 2 || !strcmp(argv[1], "-h"))
3437 usage("git submodule--helper <command>");
3438
3439 for (i = 0; i < ARRAY_SIZE(commands); i++) {
3440 if (!strcmp(argv[1], commands[i].cmd)) {
3441 if (get_super_prefix() &&
3442 !(commands[i].option & SUPPORT_SUPER_PREFIX))
3443 die(_("%s doesn't support --super-prefix"),
3444 commands[i].cmd);
3445 return commands[i].fn(argc - 1, argv + 1, prefix);
3446 }
3447 }
3448
3449 die(_("'%s' is not a valid submodule--helper "
3450 "subcommand"), argv[1]);
3451 }