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