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