]> git.ipfire.org Git - thirdparty/git.git/blame_incremental - builtin/submodule--helper.c
The third 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 key = xstrfmt("submodule.%s.update", sub->name);
1907
1908 if (update) {
1909 out->type = update;
1910 } else if (!repo_config_get_string_tmp(r, key, &val)) {
1911 if (parse_submodule_update_strategy(val, out) < 0) {
1912 ret = die_message(_("Invalid update mode '%s' configured for submodule path '%s'"),
1913 val, path);
1914 goto cleanup;
1915 }
1916 } else if (sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
1917 if (sub->update_strategy.type == SM_UPDATE_COMMAND)
1918 BUG("how did we read update = !command from .gitmodules?");
1919 out->type = sub->update_strategy.type;
1920 out->command = sub->update_strategy.command;
1921 } else
1922 out->type = SM_UPDATE_CHECKOUT;
1923
1924 if (just_cloned &&
1925 (out->type == SM_UPDATE_MERGE ||
1926 out->type == SM_UPDATE_REBASE ||
1927 out->type == SM_UPDATE_NONE))
1928 out->type = SM_UPDATE_CHECKOUT;
1929
1930 ret = 0;
1931cleanup:
1932 free(key);
1933 return ret;
1934}
1935
1936struct update_clone_data {
1937 const struct submodule *sub;
1938 struct object_id oid;
1939 unsigned just_cloned;
1940};
1941
1942struct submodule_update_clone {
1943 /* index into 'update_data.list', the list of submodules to look into for cloning */
1944 int current;
1945
1946 /* configuration parameters which are passed on to the children */
1947 const struct update_data *update_data;
1948
1949 /* to be consumed by update_submodule() */
1950 struct update_clone_data *update_clone;
1951 int update_clone_nr; int update_clone_alloc;
1952
1953 /* If we want to stop as fast as possible and return an error */
1954 unsigned quickstop : 1;
1955
1956 /* failed clones to be retried again */
1957 const struct cache_entry **failed_clones;
1958 int failed_clones_nr, failed_clones_alloc;
1959};
1960#define SUBMODULE_UPDATE_CLONE_INIT { 0 }
1961
1962static void submodule_update_clone_release(struct submodule_update_clone *suc)
1963{
1964 free(suc->update_clone);
1965 free(suc->failed_clones);
1966}
1967
1968struct update_data {
1969 const char *prefix;
1970 const char *super_prefix;
1971 char *displaypath;
1972 enum submodule_update_type update_default;
1973 struct object_id suboid;
1974 struct string_list references;
1975 struct submodule_update_strategy update_strategy;
1976 struct list_objects_filter_options *filter_options;
1977 struct module_list list;
1978 enum ref_storage_format ref_storage_format;
1979 int depth;
1980 int max_jobs;
1981 int single_branch;
1982 int recommend_shallow;
1983 unsigned int require_init;
1984 unsigned int force;
1985 unsigned int quiet;
1986 unsigned int nofetch;
1987 unsigned int remote;
1988 unsigned int progress;
1989 unsigned int dissociate;
1990 unsigned int init;
1991 unsigned int warn_if_uninitialized;
1992 unsigned int recursive;
1993
1994 /* copied over from update_clone_data */
1995 struct object_id oid;
1996 unsigned int just_cloned;
1997 const char *sm_path;
1998};
1999#define UPDATE_DATA_INIT { \
2000 .update_strategy = SUBMODULE_UPDATE_STRATEGY_INIT, \
2001 .list = MODULE_LIST_INIT, \
2002 .ref_storage_format = REF_STORAGE_FORMAT_UNKNOWN, \
2003 .recommend_shallow = -1, \
2004 .references = STRING_LIST_INIT_DUP, \
2005 .single_branch = -1, \
2006 .max_jobs = 1, \
2007}
2008
2009static void update_data_release(struct update_data *ud)
2010{
2011 free(ud->displaypath);
2012 submodule_update_strategy_release(&ud->update_strategy);
2013 module_list_release(&ud->list);
2014}
2015
2016static void next_submodule_warn_missing(struct submodule_update_clone *suc,
2017 struct strbuf *out, const char *displaypath)
2018{
2019 /*
2020 * Only mention uninitialized submodules when their
2021 * paths have been specified.
2022 */
2023 if (suc->update_data->warn_if_uninitialized) {
2024 strbuf_addf(out,
2025 _("Submodule path '%s' not initialized"),
2026 displaypath);
2027 strbuf_addch(out, '\n');
2028 strbuf_addstr(out,
2029 _("Maybe you want to use 'update --init'?"));
2030 strbuf_addch(out, '\n');
2031 }
2032}
2033
2034/**
2035 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
2036 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
2037 */
2038static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
2039 struct child_process *child,
2040 struct submodule_update_clone *suc,
2041 struct strbuf *out)
2042{
2043 const struct submodule *sub = NULL;
2044 const char *url = NULL;
2045 const char *update_string;
2046 enum submodule_update_type update_type;
2047 char *key;
2048 const struct update_data *ud = suc->update_data;
2049 char *displaypath = get_submodule_displaypath(ce->name, ud->prefix,
2050 ud->super_prefix);
2051 struct strbuf sb = STRBUF_INIT;
2052 int needs_cloning = 0;
2053 int need_free_url = 0;
2054
2055 if (ce_stage(ce)) {
2056 strbuf_addf(out, _("Skipping unmerged submodule %s"), displaypath);
2057 strbuf_addch(out, '\n');
2058 goto cleanup;
2059 }
2060
2061 sub = submodule_from_path(the_repository, null_oid(the_hash_algo), ce->name);
2062
2063 if (!sub) {
2064 next_submodule_warn_missing(suc, out, displaypath);
2065 goto cleanup;
2066 }
2067
2068 key = xstrfmt("submodule.%s.update", sub->name);
2069 if (!repo_config_get_string_tmp(the_repository, key, &update_string)) {
2070 update_type = parse_submodule_update_type(update_string);
2071 } else {
2072 update_type = sub->update_strategy.type;
2073 }
2074 free(key);
2075
2076 if (suc->update_data->update_strategy.type == SM_UPDATE_NONE
2077 || (suc->update_data->update_strategy.type == SM_UPDATE_UNSPECIFIED
2078 && update_type == SM_UPDATE_NONE)) {
2079 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
2080 strbuf_addch(out, '\n');
2081 goto cleanup;
2082 }
2083
2084 /* Check if the submodule has been initialized. */
2085 if (!is_submodule_active(the_repository, ce->name)) {
2086 next_submodule_warn_missing(suc, out, displaypath);
2087 goto cleanup;
2088 }
2089
2090 strbuf_reset(&sb);
2091 strbuf_addf(&sb, "submodule.%s.url", sub->name);
2092 if (repo_config_get_string_tmp(the_repository, sb.buf, &url)) {
2093 if (sub->url && (starts_with_dot_slash(sub->url) ||
2094 starts_with_dot_dot_slash(sub->url))) {
2095 url = resolve_relative_url(sub->url, NULL, 0);
2096 need_free_url = 1;
2097 } else
2098 url = sub->url;
2099 }
2100
2101 if (!url)
2102 die(_("cannot clone submodule '%s' without a URL"), sub->name);
2103
2104 strbuf_reset(&sb);
2105 strbuf_addf(&sb, "%s/.git", ce->name);
2106 needs_cloning = !file_exists(sb.buf);
2107
2108 ALLOC_GROW(suc->update_clone, suc->update_clone_nr + 1,
2109 suc->update_clone_alloc);
2110 oidcpy(&suc->update_clone[suc->update_clone_nr].oid, &ce->oid);
2111 suc->update_clone[suc->update_clone_nr].just_cloned = needs_cloning;
2112 suc->update_clone[suc->update_clone_nr].sub = sub;
2113 suc->update_clone_nr++;
2114
2115 if (!needs_cloning)
2116 goto cleanup;
2117
2118 child->git_cmd = 1;
2119 child->no_stdin = 1;
2120 child->stdout_to_stderr = 1;
2121 child->err = -1;
2122 strvec_push(&child->args, "submodule--helper");
2123 strvec_push(&child->args, "clone");
2124 if (suc->update_data->progress)
2125 strvec_push(&child->args, "--progress");
2126 if (suc->update_data->quiet)
2127 strvec_push(&child->args, "--quiet");
2128 if (suc->update_data->prefix)
2129 strvec_pushl(&child->args, "--prefix", suc->update_data->prefix, NULL);
2130 if (suc->update_data->recommend_shallow && sub->recommend_shallow == 1)
2131 strvec_push(&child->args, "--depth=1");
2132 else if (suc->update_data->depth)
2133 strvec_pushf(&child->args, "--depth=%d", suc->update_data->depth);
2134 if (suc->update_data->filter_options && suc->update_data->filter_options->choice)
2135 strvec_pushf(&child->args, "--filter=%s",
2136 expand_list_objects_filter_spec(suc->update_data->filter_options));
2137 if (suc->update_data->require_init)
2138 strvec_push(&child->args, "--require-init");
2139 if (suc->update_data->ref_storage_format != REF_STORAGE_FORMAT_UNKNOWN)
2140 strvec_pushf(&child->args, "--ref-format=%s",
2141 ref_storage_format_to_name(suc->update_data->ref_storage_format));
2142 strvec_pushl(&child->args, "--path", sub->path, NULL);
2143 strvec_pushl(&child->args, "--name", sub->name, NULL);
2144 strvec_pushl(&child->args, "--url", url, NULL);
2145 if (suc->update_data->references.nr) {
2146 struct string_list_item *item;
2147
2148 for_each_string_list_item(item, &suc->update_data->references)
2149 strvec_pushl(&child->args, "--reference", item->string, NULL);
2150 }
2151 if (suc->update_data->dissociate)
2152 strvec_push(&child->args, "--dissociate");
2153 if (suc->update_data->single_branch >= 0)
2154 strvec_push(&child->args, suc->update_data->single_branch ?
2155 "--single-branch" :
2156 "--no-single-branch");
2157
2158cleanup:
2159 free(displaypath);
2160 strbuf_release(&sb);
2161 if (need_free_url)
2162 free((void*)url);
2163
2164 return needs_cloning;
2165}
2166
2167static int update_clone_get_next_task(struct child_process *child,
2168 struct strbuf *err,
2169 void *suc_cb,
2170 void **idx_task_cb)
2171{
2172 struct submodule_update_clone *suc = suc_cb;
2173 const struct cache_entry *ce;
2174 int index;
2175
2176 for (; suc->current < suc->update_data->list.nr; suc->current++) {
2177 ce = suc->update_data->list.entries[suc->current];
2178 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
2179 int *p = xmalloc(sizeof(*p));
2180
2181 *p = suc->current;
2182 *idx_task_cb = p;
2183 suc->current++;
2184 return 1;
2185 }
2186 }
2187
2188 /*
2189 * The loop above tried cloning each submodule once, now try the
2190 * stragglers again, which we can imagine as an extension of the
2191 * entry list.
2192 */
2193 index = suc->current - suc->update_data->list.nr;
2194 if (index < suc->failed_clones_nr) {
2195 int *p;
2196
2197 ce = suc->failed_clones[index];
2198 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
2199 suc->current ++;
2200 strbuf_addstr(err, "BUG: submodule considered for "
2201 "cloning, doesn't need cloning "
2202 "any more?\n");
2203 return 0;
2204 }
2205 p = xmalloc(sizeof(*p));
2206 *p = suc->current;
2207 *idx_task_cb = p;
2208 suc->current ++;
2209 return 1;
2210 }
2211
2212 return 0;
2213}
2214
2215static int update_clone_start_failure(struct strbuf *err UNUSED,
2216 void *suc_cb,
2217 void *idx_task_cb UNUSED)
2218{
2219 struct submodule_update_clone *suc = suc_cb;
2220
2221 suc->quickstop = 1;
2222 return 1;
2223}
2224
2225static int update_clone_task_finished(int result,
2226 struct strbuf *err,
2227 void *suc_cb,
2228 void *idx_task_cb)
2229{
2230 const struct cache_entry *ce;
2231 struct submodule_update_clone *suc = suc_cb;
2232 int *idxP = idx_task_cb;
2233 int idx = *idxP;
2234
2235 free(idxP);
2236
2237 if (!result)
2238 return 0;
2239
2240 if (idx < suc->update_data->list.nr) {
2241 ce = suc->update_data->list.entries[idx];
2242 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
2243 ce->name);
2244 strbuf_addch(err, '\n');
2245 ALLOC_GROW(suc->failed_clones,
2246 suc->failed_clones_nr + 1,
2247 suc->failed_clones_alloc);
2248 suc->failed_clones[suc->failed_clones_nr++] = ce;
2249 return 0;
2250 } else {
2251 idx -= suc->update_data->list.nr;
2252 ce = suc->failed_clones[idx];
2253 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
2254 ce->name);
2255 strbuf_addch(err, '\n');
2256 suc->quickstop = 1;
2257 return 1;
2258 }
2259
2260 return 0;
2261}
2262
2263static int git_update_clone_config(const char *var, const char *value,
2264 const struct config_context *ctx,
2265 void *cb)
2266{
2267 int *max_jobs = cb;
2268
2269 if (!strcmp(var, "submodule.fetchjobs"))
2270 *max_jobs = parse_submodule_fetchjobs(var, value, ctx->kvi);
2271 return 0;
2272}
2273
2274static int is_tip_reachable(const char *path, const struct object_id *oid)
2275{
2276 struct child_process cp = CHILD_PROCESS_INIT;
2277 struct strbuf rev = STRBUF_INIT;
2278 char *hex = oid_to_hex(oid);
2279 int reachable;
2280
2281 cp.git_cmd = 1;
2282 cp.dir = path;
2283 cp.no_stderr = 1;
2284 strvec_pushl(&cp.args, "rev-list", "-n", "1", hex, "--not", "--all", NULL);
2285
2286 prepare_submodule_repo_env(&cp.env);
2287
2288 if (capture_command(&cp, &rev, GIT_MAX_HEXSZ + 1) || rev.len)
2289 reachable = 0;
2290 else
2291 reachable = 1;
2292
2293 strbuf_release(&rev);
2294 return reachable;
2295}
2296
2297static int fetch_in_submodule(const char *module_path, int depth, int quiet,
2298 const struct object_id *oid)
2299{
2300 struct child_process cp = CHILD_PROCESS_INIT;
2301
2302 prepare_submodule_repo_env(&cp.env);
2303 cp.git_cmd = 1;
2304 cp.dir = module_path;
2305
2306 strvec_push(&cp.args, "fetch");
2307 if (quiet)
2308 strvec_push(&cp.args, "--quiet");
2309 if (depth)
2310 strvec_pushf(&cp.args, "--depth=%d", depth);
2311 if (oid) {
2312 char *hex = oid_to_hex(oid);
2313 char *remote;
2314 int code;
2315
2316 code = get_default_remote_submodule(module_path, &remote);
2317 if (code) {
2318 child_process_clear(&cp);
2319 return code;
2320 }
2321
2322 strvec_pushl(&cp.args, remote, hex, NULL);
2323 free(remote);
2324 }
2325
2326 return run_command(&cp);
2327}
2328
2329static int run_update_command(const struct update_data *ud, int subforce)
2330{
2331 struct child_process cp = CHILD_PROCESS_INIT;
2332 char *oid = oid_to_hex(&ud->oid);
2333 int ret;
2334
2335 switch (ud->update_strategy.type) {
2336 case SM_UPDATE_CHECKOUT:
2337 cp.git_cmd = 1;
2338 strvec_pushl(&cp.args, "checkout", "-q", NULL);
2339 if (subforce)
2340 strvec_push(&cp.args, "-f");
2341 break;
2342 case SM_UPDATE_REBASE:
2343 cp.git_cmd = 1;
2344 strvec_push(&cp.args, "rebase");
2345 if (ud->quiet)
2346 strvec_push(&cp.args, "--quiet");
2347 break;
2348 case SM_UPDATE_MERGE:
2349 cp.git_cmd = 1;
2350 strvec_push(&cp.args, "merge");
2351 if (ud->quiet)
2352 strvec_push(&cp.args, "--quiet");
2353 break;
2354 case SM_UPDATE_COMMAND:
2355 cp.use_shell = 1;
2356 strvec_push(&cp.args, ud->update_strategy.command);
2357 break;
2358 default:
2359 BUG("unexpected update strategy type: %d",
2360 ud->update_strategy.type);
2361 }
2362 strvec_push(&cp.args, oid);
2363
2364 cp.dir = ud->sm_path;
2365 prepare_submodule_repo_env(&cp.env);
2366 if ((ret = run_command(&cp))) {
2367 switch (ud->update_strategy.type) {
2368 case SM_UPDATE_CHECKOUT:
2369 die_message(_("Unable to checkout '%s' in submodule path '%s'"),
2370 oid, ud->displaypath);
2371 /* No "ret" assignment, use "git checkout"'s */
2372 break;
2373 case SM_UPDATE_REBASE:
2374 ret = die_message(_("Unable to rebase '%s' in submodule path '%s'"),
2375 oid, ud->displaypath);
2376 break;
2377 case SM_UPDATE_MERGE:
2378 ret = die_message(_("Unable to merge '%s' in submodule path '%s'"),
2379 oid, ud->displaypath);
2380 break;
2381 case SM_UPDATE_COMMAND:
2382 ret = die_message(_("Execution of '%s %s' failed in submodule path '%s'"),
2383 ud->update_strategy.command, oid, ud->displaypath);
2384 break;
2385 default:
2386 BUG("unexpected update strategy type: %d",
2387 ud->update_strategy.type);
2388 }
2389
2390 return ret;
2391 }
2392
2393 if (ud->quiet)
2394 return 0;
2395
2396 switch (ud->update_strategy.type) {
2397 case SM_UPDATE_CHECKOUT:
2398 printf(_("Submodule path '%s': checked out '%s'\n"),
2399 ud->displaypath, oid);
2400 break;
2401 case SM_UPDATE_REBASE:
2402 printf(_("Submodule path '%s': rebased into '%s'\n"),
2403 ud->displaypath, oid);
2404 break;
2405 case SM_UPDATE_MERGE:
2406 printf(_("Submodule path '%s': merged in '%s'\n"),
2407 ud->displaypath, oid);
2408 break;
2409 case SM_UPDATE_COMMAND:
2410 printf(_("Submodule path '%s': '%s %s'\n"),
2411 ud->displaypath, ud->update_strategy.command, oid);
2412 break;
2413 default:
2414 BUG("unexpected update strategy type: %d",
2415 ud->update_strategy.type);
2416 }
2417
2418 return 0;
2419}
2420
2421static int run_update_procedure(const struct update_data *ud)
2422{
2423 int subforce = is_null_oid(&ud->suboid) || ud->force;
2424
2425 if (!ud->nofetch) {
2426 /*
2427 * Run fetch only if `oid` isn't present or it
2428 * is not reachable from a ref.
2429 */
2430 if (!is_tip_reachable(ud->sm_path, &ud->oid) &&
2431 fetch_in_submodule(ud->sm_path, ud->depth, ud->quiet, NULL) &&
2432 !ud->quiet)
2433 fprintf_ln(stderr,
2434 _("Unable to fetch in submodule path '%s'; "
2435 "trying to directly fetch %s:"),
2436 ud->displaypath, oid_to_hex(&ud->oid));
2437 /*
2438 * Now we tried the usual fetch, but `oid` may
2439 * not be reachable from any of the refs.
2440 */
2441 if (!is_tip_reachable(ud->sm_path, &ud->oid) &&
2442 fetch_in_submodule(ud->sm_path, ud->depth, ud->quiet, &ud->oid))
2443 return die_message(_("Fetched in submodule path '%s', but it did not "
2444 "contain %s. Direct fetching of that commit failed."),
2445 ud->displaypath, oid_to_hex(&ud->oid));
2446 }
2447
2448 return run_update_command(ud, subforce);
2449}
2450
2451static int remote_submodule_branch(const char *path, const char **branch)
2452{
2453 const struct submodule *sub;
2454 char *key;
2455 *branch = NULL;
2456
2457 sub = submodule_from_path(the_repository, null_oid(the_hash_algo), path);
2458 if (!sub)
2459 return die_message(_("could not initialize submodule at path '%s'"),
2460 path);
2461
2462 key = xstrfmt("submodule.%s.branch", sub->name);
2463 if (repo_config_get_string_tmp(the_repository, key, branch))
2464 *branch = sub->branch;
2465 free(key);
2466
2467 if (!*branch) {
2468 *branch = "HEAD";
2469 return 0;
2470 }
2471
2472 if (!strcmp(*branch, ".")) {
2473 const char *refname = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
2474 "HEAD", 0, NULL,
2475 NULL);
2476
2477 if (!refname)
2478 return die_message(_("No such ref: %s"), "HEAD");
2479
2480 /* detached HEAD */
2481 if (!strcmp(refname, "HEAD"))
2482 return die_message(_("Submodule (%s) branch configured to inherit "
2483 "branch from superproject, but the superproject "
2484 "is not on any branch"), sub->name);
2485
2486 if (!skip_prefix(refname, "refs/heads/", &refname))
2487 return die_message(_("Expecting a full ref name, got %s"),
2488 refname);
2489
2490 *branch = refname;
2491 return 0;
2492 }
2493
2494 /* Our "branch" is coming from repo_config_get_string_tmp() */
2495 return 0;
2496}
2497
2498static int ensure_core_worktree(const char *path)
2499{
2500 const char *cw;
2501 struct repository subrepo;
2502
2503 if (repo_submodule_init(&subrepo, the_repository, path, null_oid(the_hash_algo)))
2504 return die_message(_("could not get a repository handle for submodule '%s'"),
2505 path);
2506
2507 if (!repo_config_get_string_tmp(&subrepo, "core.worktree", &cw)) {
2508 char *cfg_file, *abs_path;
2509 const char *rel_path;
2510 struct strbuf sb = STRBUF_INIT;
2511
2512 cfg_file = repo_git_path(&subrepo, "config");
2513
2514 abs_path = absolute_pathdup(path);
2515 rel_path = relative_path(abs_path, subrepo.gitdir, &sb);
2516
2517 repo_config_set_in_file(the_repository, cfg_file, "core.worktree", rel_path);
2518
2519 free(cfg_file);
2520 free(abs_path);
2521 strbuf_release(&sb);
2522 }
2523
2524 repo_clear(&subrepo);
2525 return 0;
2526}
2527
2528static const char *submodule_update_type_to_label(enum submodule_update_type type)
2529{
2530 switch (type) {
2531 case SM_UPDATE_CHECKOUT:
2532 return "checkout";
2533 case SM_UPDATE_MERGE:
2534 return "merge";
2535 case SM_UPDATE_REBASE:
2536 return "rebase";
2537 case SM_UPDATE_UNSPECIFIED:
2538 case SM_UPDATE_NONE:
2539 case SM_UPDATE_COMMAND:
2540 break;
2541 }
2542 BUG("unreachable with type %d", type);
2543}
2544
2545static void update_data_to_args(const struct update_data *update_data,
2546 struct strvec *args)
2547{
2548 enum submodule_update_type update_type = update_data->update_default;
2549
2550 strvec_pushl(args, "submodule--helper", "update", "--recursive", NULL);
2551 if (update_data->displaypath)
2552 strvec_pushf(args, "--super-prefix=%s/",
2553 update_data->displaypath);
2554 strvec_pushf(args, "--jobs=%d", update_data->max_jobs);
2555 if (update_data->quiet)
2556 strvec_push(args, "--quiet");
2557 if (update_data->force)
2558 strvec_push(args, "--force");
2559 if (update_data->init)
2560 strvec_push(args, "--init");
2561 if (update_data->remote)
2562 strvec_push(args, "--remote");
2563 if (update_data->nofetch)
2564 strvec_push(args, "--no-fetch");
2565 if (update_data->dissociate)
2566 strvec_push(args, "--dissociate");
2567 if (update_data->progress)
2568 strvec_push(args, "--progress");
2569 if (update_data->require_init)
2570 strvec_push(args, "--require-init");
2571 if (update_data->depth)
2572 strvec_pushf(args, "--depth=%d", update_data->depth);
2573 if (update_type != SM_UPDATE_UNSPECIFIED)
2574 strvec_pushf(args, "--%s",
2575 submodule_update_type_to_label(update_type));
2576
2577 if (update_data->references.nr) {
2578 struct string_list_item *item;
2579
2580 for_each_string_list_item(item, &update_data->references)
2581 strvec_pushl(args, "--reference", item->string, NULL);
2582 }
2583 if (update_data->ref_storage_format != REF_STORAGE_FORMAT_UNKNOWN)
2584 strvec_pushf(args, "--ref-format=%s",
2585 ref_storage_format_to_name(update_data->ref_storage_format));
2586 if (update_data->filter_options && update_data->filter_options->choice)
2587 strvec_pushf(args, "--filter=%s",
2588 expand_list_objects_filter_spec(
2589 update_data->filter_options));
2590 if (update_data->recommend_shallow == 0)
2591 strvec_push(args, "--no-recommend-shallow");
2592 else if (update_data->recommend_shallow == 1)
2593 strvec_push(args, "--recommend-shallow");
2594 if (update_data->single_branch >= 0)
2595 strvec_push(args, update_data->single_branch ?
2596 "--single-branch" :
2597 "--no-single-branch");
2598}
2599
2600static int update_submodule(struct update_data *update_data)
2601{
2602 int ret;
2603
2604 if (validate_submodule_path(update_data->sm_path) < 0)
2605 return -1;
2606
2607 ret = determine_submodule_update_strategy(the_repository,
2608 update_data->just_cloned,
2609 update_data->sm_path,
2610 update_data->update_default,
2611 &update_data->update_strategy);
2612 if (ret)
2613 return ret;
2614
2615 if (update_data->just_cloned)
2616 oidcpy(&update_data->suboid, null_oid(the_hash_algo));
2617 else if (repo_resolve_gitlink_ref(the_repository, update_data->sm_path,
2618 "HEAD", &update_data->suboid))
2619 return die_message(_("Unable to find current revision in submodule path '%s'"),
2620 update_data->displaypath);
2621
2622 if (update_data->remote) {
2623 char *remote_name;
2624 const char *branch;
2625 char *remote_ref;
2626 int code;
2627
2628 code = get_default_remote_submodule(update_data->sm_path, &remote_name);
2629 if (code)
2630 return code;
2631 code = remote_submodule_branch(update_data->sm_path, &branch);
2632 if (code) {
2633 free(remote_name);
2634 return code;
2635 }
2636 remote_ref = xstrfmt("refs/remotes/%s/%s", remote_name, branch);
2637
2638 free(remote_name);
2639
2640 if (!update_data->nofetch) {
2641 if (fetch_in_submodule(update_data->sm_path, update_data->depth,
2642 0, NULL)) {
2643 free(remote_ref);
2644 return die_message(_("Unable to fetch in submodule path '%s'"),
2645 update_data->sm_path);
2646 }
2647 }
2648
2649 if (repo_resolve_gitlink_ref(the_repository, update_data->sm_path,
2650 remote_ref, &update_data->oid)) {
2651 ret = die_message(_("Unable to find %s revision in submodule path '%s'"),
2652 remote_ref, update_data->sm_path);
2653 free(remote_ref);
2654 return ret;
2655 }
2656
2657 free(remote_ref);
2658 }
2659
2660 if (!oideq(&update_data->oid, &update_data->suboid) || update_data->force) {
2661 ret = run_update_procedure(update_data);
2662 if (ret)
2663 return ret;
2664 }
2665
2666 if (update_data->recursive) {
2667 struct child_process cp = CHILD_PROCESS_INIT;
2668 struct update_data next = *update_data;
2669
2670 next.prefix = NULL;
2671 oidcpy(&next.oid, null_oid(the_hash_algo));
2672 oidcpy(&next.suboid, null_oid(the_hash_algo));
2673
2674 cp.dir = update_data->sm_path;
2675 cp.git_cmd = 1;
2676 prepare_submodule_repo_env(&cp.env);
2677 update_data_to_args(&next, &cp.args);
2678
2679 ret = run_command(&cp);
2680 if (ret)
2681 die_message(_("Failed to recurse into submodule path '%s'"),
2682 update_data->displaypath);
2683 return ret;
2684 }
2685
2686 return 0;
2687}
2688
2689static int update_submodules(struct update_data *update_data)
2690{
2691 int i, ret = 0;
2692 struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
2693 const struct run_process_parallel_opts opts = {
2694 .tr2_category = "submodule",
2695 .tr2_label = "parallel/update",
2696
2697 .processes = update_data->max_jobs,
2698
2699 .get_next_task = update_clone_get_next_task,
2700 .start_failure = update_clone_start_failure,
2701 .task_finished = update_clone_task_finished,
2702 .data = &suc,
2703 };
2704
2705 suc.update_data = update_data;
2706 run_processes_parallel(&opts);
2707
2708 /*
2709 * We saved the output and put it out all at once now.
2710 * That means:
2711 * - the listener does not have to interleave their (checkout)
2712 * work with our fetching. The writes involved in a
2713 * checkout involve more straightforward sequential I/O.
2714 * - the listener can avoid doing any work if fetching failed.
2715 */
2716 if (suc.quickstop) {
2717 ret = 1;
2718 goto cleanup;
2719 }
2720
2721 for (i = 0; i < suc.update_clone_nr; i++) {
2722 struct update_clone_data ucd = suc.update_clone[i];
2723 int code = 128;
2724
2725 oidcpy(&update_data->oid, &ucd.oid);
2726 update_data->just_cloned = ucd.just_cloned;
2727 update_data->sm_path = ucd.sub->path;
2728
2729 /*
2730 * Verify that the submodule path does not contain any
2731 * symlinks; if it does, it might have been tampered with.
2732 * TODO: allow exempting it via
2733 * `safe.submodule.path` or something
2734 */
2735 if (validate_submodule_path(update_data->sm_path) < 0)
2736 goto fail;
2737
2738 code = ensure_core_worktree(update_data->sm_path);
2739 if (code)
2740 goto fail;
2741
2742 update_data->displaypath = get_submodule_displaypath(
2743 update_data->sm_path, update_data->prefix,
2744 update_data->super_prefix);
2745 code = update_submodule(update_data);
2746 FREE_AND_NULL(update_data->displaypath);
2747fail:
2748 if (!code)
2749 continue;
2750 ret = code;
2751 if (ret == 128)
2752 goto cleanup;
2753 }
2754
2755cleanup:
2756 submodule_update_clone_release(&suc);
2757 string_list_clear(&update_data->references, 0);
2758 return ret;
2759}
2760
2761static int module_update(int argc, const char **argv, const char *prefix,
2762 struct repository *repo UNUSED)
2763{
2764 struct pathspec pathspec = { 0 };
2765 struct pathspec pathspec2 = { 0 };
2766 struct update_data opt = UPDATE_DATA_INIT;
2767 struct list_objects_filter_options filter_options =
2768 LIST_OBJECTS_FILTER_INIT;
2769 const char *ref_storage_format = NULL;
2770 int ret;
2771 struct option module_update_options[] = {
2772 OPT__SUPER_PREFIX(&opt.super_prefix),
2773 OPT__FORCE(&opt.force, N_("force checkout updates"), 0),
2774 OPT_BOOL(0, "init", &opt.init,
2775 N_("initialize uninitialized submodules before update")),
2776 OPT_BOOL(0, "remote", &opt.remote,
2777 N_("use SHA-1 of submodule's remote tracking branch")),
2778 OPT_BOOL(0, "recursive", &opt.recursive,
2779 N_("traverse submodules recursively")),
2780 OPT_BOOL('N', "no-fetch", &opt.nofetch,
2781 N_("don't fetch new objects from the remote site")),
2782 OPT_SET_INT(0, "checkout", &opt.update_default,
2783 N_("use the 'checkout' update strategy (default)"),
2784 SM_UPDATE_CHECKOUT),
2785 OPT_SET_INT('m', "merge", &opt.update_default,
2786 N_("use the 'merge' update strategy"),
2787 SM_UPDATE_MERGE),
2788 OPT_SET_INT('r', "rebase", &opt.update_default,
2789 N_("use the 'rebase' update strategy"),
2790 SM_UPDATE_REBASE),
2791 OPT_STRING_LIST(0, "reference", &opt.references, N_("repo"),
2792 N_("reference repository")),
2793 OPT_STRING(0, "ref-format", &ref_storage_format, N_("format"),
2794 N_("specify the reference format to use")),
2795 OPT_BOOL(0, "dissociate", &opt.dissociate,
2796 N_("use --reference only while cloning")),
2797 OPT_INTEGER(0, "depth", &opt.depth,
2798 N_("create a shallow clone truncated to the "
2799 "specified number of revisions")),
2800 OPT_INTEGER('j', "jobs", &opt.max_jobs,
2801 N_("parallel jobs")),
2802 OPT_BOOL(0, "recommend-shallow", &opt.recommend_shallow,
2803 N_("whether the initial clone should follow the shallow recommendation")),
2804 OPT__QUIET(&opt.quiet, N_("don't print cloning progress")),
2805 OPT_BOOL(0, "progress", &opt.progress,
2806 N_("force cloning progress")),
2807 OPT_BOOL(0, "require-init", &opt.require_init,
2808 N_("disallow cloning into non-empty directory, implies --init")),
2809 OPT_BOOL(0, "single-branch", &opt.single_branch,
2810 N_("clone only one branch, HEAD or --branch")),
2811 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
2812 OPT_END()
2813 };
2814 const char *const git_submodule_helper_usage[] = {
2815 N_("git submodule [--quiet] update"
2816 " [--init [--filter=<filter-spec>]] [--remote]"
2817 " [-N|--no-fetch] [-f|--force]"
2818 " [--checkout|--merge|--rebase]"
2819 " [--[no-]recommend-shallow] [--reference <repository>]"
2820 " [--recursive] [--[no-]single-branch] [--] [<path>...]"),
2821 NULL
2822 };
2823
2824 update_clone_config_from_gitmodules(&opt.max_jobs);
2825 repo_config(the_repository, git_update_clone_config, &opt.max_jobs);
2826
2827 argc = parse_options(argc, argv, prefix, module_update_options,
2828 git_submodule_helper_usage, 0);
2829
2830 if (opt.require_init)
2831 opt.init = 1;
2832
2833 if (filter_options.choice && !opt.init) {
2834 usage_with_options(git_submodule_helper_usage,
2835 module_update_options);
2836 }
2837
2838 if (ref_storage_format) {
2839 opt.ref_storage_format = ref_storage_format_by_name(ref_storage_format);
2840 if (opt.ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
2841 die(_("unknown ref storage format '%s'"), ref_storage_format);
2842 }
2843
2844 opt.filter_options = &filter_options;
2845 opt.prefix = prefix;
2846
2847 if (opt.update_default)
2848 opt.update_strategy.type = opt.update_default;
2849
2850 if (module_list_compute(argv, prefix, &pathspec, &opt.list) < 0) {
2851 ret = 1;
2852 goto cleanup;
2853 }
2854
2855 if (pathspec.nr)
2856 opt.warn_if_uninitialized = 1;
2857
2858 if (opt.init) {
2859 struct module_list list = MODULE_LIST_INIT;
2860 struct init_cb info = INIT_CB_INIT;
2861
2862 if (module_list_compute(argv, opt.prefix,
2863 &pathspec2, &list) < 0) {
2864 module_list_release(&list);
2865 ret = 1;
2866 goto cleanup;
2867 }
2868
2869 /*
2870 * If there are no path args and submodule.active is set then,
2871 * by default, only initialize 'active' modules.
2872 */
2873 if (!argc && !repo_config_get(the_repository, "submodule.active"))
2874 module_list_active(&list);
2875
2876 info.prefix = opt.prefix;
2877 info.super_prefix = opt.super_prefix;
2878 if (opt.quiet)
2879 info.flags |= OPT_QUIET;
2880
2881 for_each_listed_submodule(&list, init_submodule_cb, &info);
2882 module_list_release(&list);
2883 }
2884
2885 ret = update_submodules(&opt);
2886cleanup:
2887 update_data_release(&opt);
2888 list_objects_filter_release(&filter_options);
2889 clear_pathspec(&pathspec);
2890 clear_pathspec(&pathspec2);
2891 return ret;
2892}
2893
2894static int push_check(int argc, const char **argv, const char *prefix UNUSED,
2895 struct repository *repo UNUSED)
2896{
2897 struct remote *remote;
2898 const char *superproject_head;
2899 char *head;
2900 int detached_head = 0;
2901 struct object_id head_oid;
2902
2903 if (argc < 3)
2904 die("submodule--helper push-check requires at least 2 arguments");
2905
2906 /*
2907 * superproject's resolved head ref.
2908 * if HEAD then the superproject is in a detached head state, otherwise
2909 * it will be the resolved head ref.
2910 */
2911 superproject_head = argv[1];
2912 argv++;
2913 argc--;
2914 /* Get the submodule's head ref and determine if it is detached */
2915 head = refs_resolve_refdup(get_main_ref_store(the_repository), "HEAD",
2916 0, &head_oid, NULL);
2917 if (!head)
2918 die(_("Failed to resolve HEAD as a valid ref."));
2919 if (!strcmp(head, "HEAD"))
2920 detached_head = 1;
2921
2922 /*
2923 * The remote must be configured.
2924 * This is to avoid pushing to the exact same URL as the parent.
2925 */
2926 remote = pushremote_get(argv[1]);
2927 if (!remote || remote->origin == REMOTE_UNCONFIGURED)
2928 die("remote '%s' not configured", argv[1]);
2929
2930 /* Check the refspec */
2931 if (argc > 2) {
2932 int i;
2933 struct ref *local_refs = get_local_heads();
2934 struct refspec refspec = REFSPEC_INIT_PUSH;
2935
2936 refspec_appendn(&refspec, argv + 2, argc - 2);
2937
2938 for (i = 0; i < refspec.nr; i++) {
2939 const struct refspec_item *rs = &refspec.items[i];
2940
2941 if (rs->pattern || rs->matching)
2942 continue;
2943
2944 /* LHS must match a single ref */
2945 switch (count_refspec_match(rs->src, local_refs, NULL)) {
2946 case 1:
2947 break;
2948 case 0:
2949 /*
2950 * If LHS matches 'HEAD' then we need to ensure
2951 * that it matches the same named branch
2952 * checked out in the superproject.
2953 */
2954 if (!strcmp(rs->src, "HEAD")) {
2955 if (!detached_head &&
2956 !strcmp(head, superproject_head))
2957 break;
2958 die("HEAD does not match the named branch in the superproject");
2959 }
2960 /* fallthrough */
2961 default:
2962 die("src refspec '%s' must name a ref",
2963 rs->src);
2964 }
2965 }
2966
2967 refspec_clear(&refspec);
2968 free_refs(local_refs);
2969 }
2970 free(head);
2971
2972 return 0;
2973}
2974
2975static int absorb_git_dirs(int argc, const char **argv, const char *prefix,
2976 struct repository *repo UNUSED)
2977{
2978 int i;
2979 struct pathspec pathspec = { 0 };
2980 struct module_list list = MODULE_LIST_INIT;
2981 const char *super_prefix = NULL;
2982 struct option embed_gitdir_options[] = {
2983 OPT__SUPER_PREFIX(&super_prefix),
2984 OPT_END()
2985 };
2986 const char *const git_submodule_helper_usage[] = {
2987 N_("git submodule absorbgitdirs [<options>] [<path>...]"),
2988 NULL
2989 };
2990 int ret = 1;
2991
2992 argc = parse_options(argc, argv, prefix, embed_gitdir_options,
2993 git_submodule_helper_usage, 0);
2994
2995 if (module_list_compute(argv, prefix, &pathspec, &list) < 0)
2996 goto cleanup;
2997
2998 for (i = 0; i < list.nr; i++)
2999 absorb_git_dir_into_superproject(list.entries[i]->name,
3000 super_prefix);
3001
3002 ret = 0;
3003cleanup:
3004 clear_pathspec(&pathspec);
3005 module_list_release(&list);
3006 return ret;
3007}
3008
3009static int module_set_url(int argc, const char **argv, const char *prefix,
3010 struct repository *repo UNUSED)
3011{
3012 int quiet = 0, ret;
3013 const char *newurl;
3014 const char *path;
3015 char *config_name;
3016 struct option options[] = {
3017 OPT__QUIET(&quiet, N_("suppress output for setting url of a submodule")),
3018 OPT_END()
3019 };
3020 const char *const usage[] = {
3021 N_("git submodule set-url [--quiet] <path> <newurl>"),
3022 NULL
3023 };
3024 const struct submodule *sub;
3025
3026 argc = parse_options(argc, argv, prefix, options, usage, 0);
3027
3028 if (argc != 2 || !(path = argv[0]) || !(newurl = argv[1]))
3029 usage_with_options(usage, options);
3030
3031 sub = submodule_from_path(the_repository, null_oid(the_hash_algo), path);
3032
3033 if (!sub)
3034 die(_("no submodule mapping found in .gitmodules for path '%s'"),
3035 path);
3036
3037 config_name = xstrfmt("submodule.%s.url", sub->name);
3038 ret = config_set_in_gitmodules_file_gently(config_name, newurl);
3039
3040 if (!ret) {
3041 repo_read_gitmodules(the_repository, 0);
3042 sync_submodule(sub->path, prefix, NULL, quiet ? OPT_QUIET : 0);
3043 }
3044
3045 free(config_name);
3046 return !!ret;
3047}
3048
3049static int module_set_branch(int argc, const char **argv, const char *prefix,
3050 struct repository *repo UNUSED)
3051{
3052 int opt_default = 0, ret;
3053 const char *opt_branch = NULL;
3054 const char *path;
3055 char *config_name;
3056 struct option options[] = {
3057 /*
3058 * We accept the `quiet` option for uniformity across subcommands,
3059 * though there is nothing to make less verbose in this subcommand.
3060 */
3061 OPT_NOOP_NOARG('q', "quiet"),
3062
3063 OPT_BOOL('d', "default", &opt_default,
3064 N_("set the default tracking branch to master")),
3065 OPT_STRING('b', "branch", &opt_branch, N_("branch"),
3066 N_("set the default tracking branch")),
3067 OPT_END()
3068 };
3069 const char *const usage[] = {
3070 N_("git submodule set-branch [-q|--quiet] (-d|--default) <path>"),
3071 N_("git submodule set-branch [-q|--quiet] (-b|--branch) <branch> <path>"),
3072 NULL
3073 };
3074 const struct submodule *sub;
3075
3076 argc = parse_options(argc, argv, prefix, options, usage, 0);
3077
3078 if (!opt_branch && !opt_default)
3079 die(_("--branch or --default required"));
3080
3081 if (opt_branch && opt_default)
3082 die(_("options '%s' and '%s' cannot be used together"), "--branch", "--default");
3083
3084 if (argc != 1 || !(path = argv[0]))
3085 usage_with_options(usage, options);
3086
3087 sub = submodule_from_path(the_repository, null_oid(the_hash_algo), path);
3088
3089 if (!sub)
3090 die(_("no submodule mapping found in .gitmodules for path '%s'"),
3091 path);
3092
3093 config_name = xstrfmt("submodule.%s.branch", sub->name);
3094 ret = config_set_in_gitmodules_file_gently(config_name, opt_branch);
3095
3096 free(config_name);
3097 return !!ret;
3098}
3099
3100static int module_create_branch(int argc, const char **argv, const char *prefix,
3101 struct repository *repo UNUSED)
3102{
3103 enum branch_track track;
3104 int quiet = 0, force = 0, reflog = 0, dry_run = 0;
3105 struct option options[] = {
3106 OPT__QUIET(&quiet, N_("print only error messages")),
3107 OPT__FORCE(&force, N_("force creation"), 0),
3108 OPT_BOOL(0, "create-reflog", &reflog,
3109 N_("create the branch's reflog")),
3110 OPT_CALLBACK_F('t', "track", &track, "(direct|inherit)",
3111 N_("set branch tracking configuration"),
3112 PARSE_OPT_OPTARG,
3113 parse_opt_tracking_mode),
3114 OPT__DRY_RUN(&dry_run,
3115 N_("show whether the branch would be created")),
3116 OPT_END()
3117 };
3118 const char *const usage[] = {
3119 N_("git submodule--helper create-branch [-f|--force] [--create-reflog] [-q|--quiet] [-t|--track] [-n|--dry-run] <name> <start-oid> <start-name>"),
3120 NULL
3121 };
3122
3123 repo_config(the_repository, git_default_config, NULL);
3124 track = git_branch_track;
3125 argc = parse_options(argc, argv, prefix, options, usage, 0);
3126
3127 if (argc != 3)
3128 usage_with_options(usage, options);
3129
3130 if (!quiet && !dry_run)
3131 printf_ln(_("creating branch '%s'"), argv[0]);
3132
3133 create_branches_recursively(the_repository, argv[0], argv[1], argv[2],
3134 force, reflog, quiet, track, dry_run);
3135 return 0;
3136}
3137
3138struct add_data {
3139 const char *prefix;
3140 const char *branch;
3141 const char *reference_path;
3142 char *sm_path;
3143 const char *sm_name;
3144 const char *repo;
3145 const char *realrepo;
3146 enum ref_storage_format ref_storage_format;
3147 int depth;
3148 unsigned int force: 1;
3149 unsigned int quiet: 1;
3150 unsigned int progress: 1;
3151 unsigned int dissociate: 1;
3152};
3153#define ADD_DATA_INIT { \
3154 .depth = -1, \
3155 .ref_storage_format = REF_STORAGE_FORMAT_UNKNOWN, \
3156}
3157
3158static void append_fetch_remotes(struct strbuf *msg, const char *git_dir_path)
3159{
3160 struct child_process cp_remote = CHILD_PROCESS_INIT;
3161 struct strbuf sb_remote_out = STRBUF_INIT;
3162
3163 cp_remote.git_cmd = 1;
3164 strvec_pushf(&cp_remote.env,
3165 "GIT_DIR=%s", git_dir_path);
3166 strvec_push(&cp_remote.env, "GIT_WORK_TREE=.");
3167 strvec_pushl(&cp_remote.args, "remote", "-v", NULL);
3168 if (!capture_command(&cp_remote, &sb_remote_out, 0)) {
3169 char *next_line;
3170 char *line = sb_remote_out.buf;
3171
3172 while ((next_line = strchr(line, '\n')) != NULL) {
3173 size_t len = next_line - line;
3174
3175 if (strip_suffix_mem(line, &len, " (fetch)"))
3176 strbuf_addf(msg, " %.*s\n", (int)len, line);
3177 line = next_line + 1;
3178 }
3179 }
3180
3181 strbuf_release(&sb_remote_out);
3182}
3183
3184static int add_submodule(const struct add_data *add_data)
3185{
3186 char *submod_gitdir_path;
3187 struct module_clone_data clone_data = MODULE_CLONE_DATA_INIT;
3188 struct string_list reference = STRING_LIST_INIT_NODUP;
3189 int ret = -1;
3190
3191 /* perhaps the path already exists and is already a git repo, else clone it */
3192 if (is_directory(add_data->sm_path)) {
3193 struct strbuf sm_path = STRBUF_INIT;
3194 strbuf_addstr(&sm_path, add_data->sm_path);
3195 submod_gitdir_path = xstrfmt("%s/.git", add_data->sm_path);
3196 if (is_nonbare_repository_dir(&sm_path))
3197 printf(_("Adding existing repo at '%s' to the index\n"),
3198 add_data->sm_path);
3199 else
3200 die(_("'%s' already exists and is not a valid git repo"),
3201 add_data->sm_path);
3202 strbuf_release(&sm_path);
3203 free(submod_gitdir_path);
3204 } else {
3205 struct child_process cp = CHILD_PROCESS_INIT;
3206
3207 submod_gitdir_path = xstrfmt(".git/modules/%s", add_data->sm_name);
3208
3209 if (is_directory(submod_gitdir_path)) {
3210 if (!add_data->force) {
3211 struct strbuf msg = STRBUF_INIT;
3212 char *die_msg;
3213
3214 strbuf_addf(&msg, _("A git directory for '%s' is found "
3215 "locally with remote(s):\n"),
3216 add_data->sm_name);
3217
3218 append_fetch_remotes(&msg, submod_gitdir_path);
3219 free(submod_gitdir_path);
3220
3221 strbuf_addf(&msg, _("If you want to reuse this local git "
3222 "directory instead of cloning again from\n"
3223 " %s\n"
3224 "use the '--force' option. If the local git "
3225 "directory is not the correct repo\n"
3226 "or you are unsure what this means choose "
3227 "another name with the '--name' option."),
3228 add_data->realrepo);
3229
3230 die_msg = strbuf_detach(&msg, NULL);
3231 die("%s", die_msg);
3232 } else {
3233 printf(_("Reactivating local git directory for "
3234 "submodule '%s'\n"), add_data->sm_name);
3235 }
3236 }
3237 free(submod_gitdir_path);
3238
3239 clone_data.prefix = add_data->prefix;
3240 clone_data.path = add_data->sm_path;
3241 clone_data.name = add_data->sm_name;
3242 clone_data.url = add_data->realrepo;
3243 clone_data.quiet = add_data->quiet;
3244 clone_data.progress = add_data->progress;
3245 if (add_data->reference_path) {
3246 char *p = xstrdup(add_data->reference_path);
3247
3248 string_list_append(&reference, p)->util = p;
3249 }
3250 clone_data.ref_storage_format = add_data->ref_storage_format;
3251 clone_data.dissociate = add_data->dissociate;
3252 if (add_data->depth >= 0)
3253 clone_data.depth = add_data->depth;
3254
3255 if (clone_submodule(&clone_data, &reference))
3256 goto cleanup;
3257
3258 prepare_submodule_repo_env(&cp.env);
3259 cp.git_cmd = 1;
3260 cp.dir = add_data->sm_path;
3261 /*
3262 * NOTE: we only get here if add_data->force is true, so
3263 * passing --force to checkout is reasonable.
3264 */
3265 strvec_pushl(&cp.args, "checkout", "-f", "-q", NULL);
3266
3267 if (add_data->branch) {
3268 strvec_pushl(&cp.args, "-B", add_data->branch, NULL);
3269 strvec_pushf(&cp.args, "origin/%s", add_data->branch);
3270 }
3271
3272 if (run_command(&cp))
3273 die(_("unable to checkout submodule '%s'"), add_data->sm_path);
3274 }
3275 ret = 0;
3276
3277cleanup:
3278 string_list_clear(&reference, 1);
3279 return ret;
3280}
3281
3282static int config_submodule_in_gitmodules(const char *name, const char *var, const char *value)
3283{
3284 char *key;
3285 int ret;
3286
3287 if (!is_writing_gitmodules_ok())
3288 die(_("please make sure that the .gitmodules file is in the working tree"));
3289
3290 key = xstrfmt("submodule.%s.%s", name, var);
3291 ret = config_set_in_gitmodules_file_gently(key, value);
3292 free(key);
3293
3294 return ret;
3295}
3296
3297static void configure_added_submodule(struct add_data *add_data)
3298{
3299 char *key;
3300 struct child_process add_submod = CHILD_PROCESS_INIT;
3301 struct child_process add_gitmodules = CHILD_PROCESS_INIT;
3302 const struct string_list *values;
3303 int matched = 0;
3304
3305 key = xstrfmt("submodule.%s.url", add_data->sm_name);
3306 repo_config_set_gently(the_repository, key, add_data->realrepo);
3307 free(key);
3308
3309 add_submod.git_cmd = 1;
3310 strvec_pushl(&add_submod.args, "add",
3311 "--no-warn-embedded-repo", NULL);
3312 if (add_data->force)
3313 strvec_push(&add_submod.args, "--force");
3314 strvec_pushl(&add_submod.args, "--", add_data->sm_path, NULL);
3315
3316 if (run_command(&add_submod))
3317 die(_("Failed to add submodule '%s'"), add_data->sm_path);
3318
3319 if (config_submodule_in_gitmodules(add_data->sm_name, "path", add_data->sm_path) ||
3320 config_submodule_in_gitmodules(add_data->sm_name, "url", add_data->repo))
3321 die(_("Failed to register submodule '%s'"), add_data->sm_path);
3322
3323 if (add_data->branch) {
3324 if (config_submodule_in_gitmodules(add_data->sm_name,
3325 "branch", add_data->branch))
3326 die(_("Failed to register submodule '%s'"), add_data->sm_path);
3327 }
3328
3329 add_gitmodules.git_cmd = 1;
3330 strvec_pushl(&add_gitmodules.args,
3331 "add", "--force", "--", ".gitmodules", NULL);
3332
3333 if (run_command(&add_gitmodules))
3334 die(_("Failed to register submodule '%s'"), add_data->sm_path);
3335
3336 /*
3337 * NEEDSWORK: In a multi-working-tree world this needs to be
3338 * set in the per-worktree config.
3339 */
3340 /*
3341 * NEEDSWORK: In the longer run, we need to get rid of this
3342 * pattern of querying "submodule.active" before calling
3343 * is_submodule_active(), since that function needs to find
3344 * out the value of "submodule.active" again anyway.
3345 */
3346 if (repo_config_get(the_repository, "submodule.active") || /* key absent */
3347 repo_config_get_string_multi(the_repository, "submodule.active", &values)) {
3348 /*
3349 * If the submodule being added isn't already covered by the
3350 * current configured pathspec, set the submodule's active flag
3351 */
3352 key = xstrfmt("submodule.%s.active", add_data->sm_name);
3353 repo_config_set_gently(the_repository, key, "true");
3354 free(key);
3355 } else {
3356 for (size_t i = 0; i < values->nr; i++) {
3357 const char *pat = values->items[i].string;
3358 if (!wildmatch(pat, add_data->sm_path, 0)) { /* match found */
3359 matched = 1;
3360 break;
3361 }
3362 }
3363 if (!matched) { /* no pattern matched -> force-enable */
3364 key = xstrfmt("submodule.%s.active", add_data->sm_name);
3365 repo_config_set_gently(the_repository, key, "true");
3366 free(key);
3367 }
3368 }
3369}
3370
3371static void die_on_index_match(const char *path, int force)
3372{
3373 struct pathspec ps;
3374 const char *args[] = { path, NULL };
3375 parse_pathspec(&ps, 0, PATHSPEC_PREFER_CWD, NULL, args);
3376
3377 if (repo_read_index_preload(the_repository, NULL, 0) < 0)
3378 die(_("index file corrupt"));
3379
3380 if (ps.nr) {
3381 char *ps_matched = xcalloc(ps.nr, 1);
3382
3383 /* TODO: audit for interaction with sparse-index. */
3384 ensure_full_index(the_repository->index);
3385
3386 /*
3387 * Since there is only one pathspec, we just need to
3388 * check ps_matched[0] to know if a cache entry matched.
3389 */
3390 for (size_t i = 0; i < the_repository->index->cache_nr; i++) {
3391 ce_path_match(the_repository->index, the_repository->index->cache[i], &ps,
3392 ps_matched);
3393
3394 if (ps_matched[0]) {
3395 if (!force)
3396 die(_("'%s' already exists in the index"),
3397 path);
3398 if (!S_ISGITLINK(the_repository->index->cache[i]->ce_mode))
3399 die(_("'%s' already exists in the index "
3400 "and is not a submodule"), path);
3401 break;
3402 }
3403 }
3404 free(ps_matched);
3405 }
3406 clear_pathspec(&ps);
3407}
3408
3409static void die_on_repo_without_commits(const char *path)
3410{
3411 struct strbuf sb = STRBUF_INIT;
3412 strbuf_addstr(&sb, path);
3413 if (is_nonbare_repository_dir(&sb)) {
3414 struct object_id oid;
3415 if (repo_resolve_gitlink_ref(the_repository, path, "HEAD", &oid) < 0)
3416 die(_("'%s' does not have a commit checked out"), path);
3417 }
3418 strbuf_release(&sb);
3419}
3420
3421static int module_add(int argc, const char **argv, const char *prefix,
3422 struct repository *repo UNUSED)
3423{
3424 int force = 0, quiet = 0, progress = 0, dissociate = 0;
3425 struct add_data add_data = ADD_DATA_INIT;
3426 const char *ref_storage_format = NULL;
3427 char *to_free = NULL;
3428 const struct submodule *existing;
3429 struct strbuf buf = STRBUF_INIT;
3430 char *sm_name_to_free = NULL;
3431 struct option options[] = {
3432 OPT_STRING('b', "branch", &add_data.branch, N_("branch"),
3433 N_("branch of repository to add as submodule")),
3434 OPT__FORCE(&force, N_("allow adding an otherwise ignored submodule path"),
3435 PARSE_OPT_NOCOMPLETE),
3436 OPT__QUIET(&quiet, N_("print only error messages")),
3437 OPT_BOOL(0, "progress", &progress, N_("force cloning progress")),
3438 OPT_STRING(0, "reference", &add_data.reference_path, N_("repository"),
3439 N_("reference repository")),
3440 OPT_STRING(0, "ref-format", &ref_storage_format, N_("format"),
3441 N_("specify the reference format to use")),
3442 OPT_BOOL(0, "dissociate", &dissociate, N_("borrow the objects from reference repositories")),
3443 OPT_STRING(0, "name", &add_data.sm_name, N_("name"),
3444 N_("sets the submodule's name to the given string "
3445 "instead of defaulting to its path")),
3446 OPT_INTEGER(0, "depth", &add_data.depth, N_("depth for shallow clones")),
3447 OPT_END()
3448 };
3449 const char *const usage[] = {
3450 N_("git submodule add [<options>] [--] <repository> [<path>]"),
3451 NULL
3452 };
3453 struct strbuf sb = STRBUF_INIT;
3454 int ret = 1;
3455
3456 argc = parse_options(argc, argv, prefix, options, usage, 0);
3457
3458 if (!is_writing_gitmodules_ok())
3459 die(_("please make sure that the .gitmodules file is in the working tree"));
3460
3461 if (prefix && *prefix &&
3462 add_data.reference_path && !is_absolute_path(add_data.reference_path))
3463 add_data.reference_path = xstrfmt("%s%s", prefix, add_data.reference_path);
3464
3465 if (argc == 0 || argc > 2)
3466 usage_with_options(usage, options);
3467
3468 if (ref_storage_format) {
3469 add_data.ref_storage_format = ref_storage_format_by_name(ref_storage_format);
3470 if (add_data.ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
3471 die(_("unknown ref storage format '%s'"), ref_storage_format);
3472 }
3473
3474 add_data.repo = argv[0];
3475 if (argc == 1)
3476 add_data.sm_path = git_url_basename(add_data.repo, 0, 0);
3477 else
3478 add_data.sm_path = xstrdup(argv[1]);
3479
3480 if (prefix && *prefix && !is_absolute_path(add_data.sm_path)) {
3481 char *sm_path = add_data.sm_path;
3482
3483 add_data.sm_path = xstrfmt("%s%s", prefix, sm_path);
3484 free(sm_path);
3485 }
3486
3487 if (starts_with_dot_dot_slash(add_data.repo) ||
3488 starts_with_dot_slash(add_data.repo)) {
3489 if (prefix)
3490 die(_("Relative path can only be used from the toplevel "
3491 "of the working tree"));
3492
3493 /* dereference source url relative to parent's url */
3494 to_free = resolve_relative_url(add_data.repo, NULL, 1);
3495 add_data.realrepo = to_free;
3496 } else if (is_dir_sep(add_data.repo[0]) || strchr(add_data.repo, ':')) {
3497 add_data.realrepo = add_data.repo;
3498 } else {
3499 die(_("repo URL: '%s' must be absolute or begin with ./|../"),
3500 add_data.repo);
3501 }
3502
3503 /*
3504 * normalize path:
3505 * multiple //; leading ./; /./; /../;
3506 */
3507 normalize_path_copy(add_data.sm_path, add_data.sm_path);
3508 strip_dir_trailing_slashes(add_data.sm_path);
3509
3510 if (validate_submodule_path(add_data.sm_path) < 0)
3511 die(NULL);
3512
3513 die_on_index_match(add_data.sm_path, force);
3514 die_on_repo_without_commits(add_data.sm_path);
3515
3516 if (!force) {
3517 struct child_process cp = CHILD_PROCESS_INIT;
3518
3519 cp.git_cmd = 1;
3520 cp.no_stdout = 1;
3521 strvec_pushl(&cp.args, "add", "--dry-run", "--ignore-missing",
3522 "--no-warn-embedded-repo", add_data.sm_path, NULL);
3523 if ((ret = pipe_command(&cp, NULL, 0, NULL, 0, &sb, 0))) {
3524 strbuf_complete_line(&sb);
3525 fputs(sb.buf, stderr);
3526 goto cleanup;
3527 }
3528 }
3529
3530 if(!add_data.sm_name)
3531 add_data.sm_name = add_data.sm_path;
3532
3533 existing = submodule_from_name(the_repository,
3534 null_oid(the_hash_algo),
3535 add_data.sm_name);
3536
3537 if (existing && strcmp(existing->path, add_data.sm_path)) {
3538 if (!force) {
3539 die(_("submodule name '%s' already used for path '%s'"),
3540 add_data.sm_name, existing->path);
3541 }
3542 /* --force: build <name><n> until unique */
3543 for (int i = 1; ; i++) {
3544 strbuf_reset(&buf);
3545 strbuf_addf(&buf, "%s%d", add_data.sm_name, i);
3546 if (!submodule_from_name(the_repository,
3547 null_oid(the_hash_algo),
3548 buf.buf)) {
3549 break;
3550 }
3551 }
3552 add_data.sm_name = sm_name_to_free = strbuf_detach(&buf, NULL);
3553 }
3554
3555 if (check_submodule_name(add_data.sm_name))
3556 die(_("'%s' is not a valid submodule name"), add_data.sm_name);
3557
3558 add_data.prefix = prefix;
3559 add_data.force = !!force;
3560 add_data.quiet = !!quiet;
3561 add_data.progress = !!progress;
3562 add_data.dissociate = !!dissociate;
3563
3564 if (add_submodule(&add_data))
3565 goto cleanup;
3566 configure_added_submodule(&add_data);
3567
3568 ret = 0;
3569cleanup:
3570 free(sm_name_to_free);
3571 free(add_data.sm_path);
3572 free(to_free);
3573 strbuf_release(&sb);
3574
3575 return ret;
3576}
3577
3578int cmd_submodule__helper(int argc,
3579 const char **argv,
3580 const char *prefix,
3581 struct repository *repo)
3582{
3583 parse_opt_subcommand_fn *fn = NULL;
3584 const char *const usage[] = {
3585 N_("git submodule--helper <command>"),
3586 NULL
3587 };
3588 struct option options[] = {
3589 OPT_SUBCOMMAND("clone", &fn, module_clone),
3590 OPT_SUBCOMMAND("add", &fn, module_add),
3591 OPT_SUBCOMMAND("update", &fn, module_update),
3592 OPT_SUBCOMMAND("foreach", &fn, module_foreach),
3593 OPT_SUBCOMMAND("init", &fn, module_init),
3594 OPT_SUBCOMMAND("status", &fn, module_status),
3595 OPT_SUBCOMMAND("sync", &fn, module_sync),
3596 OPT_SUBCOMMAND("deinit", &fn, module_deinit),
3597 OPT_SUBCOMMAND("summary", &fn, module_summary),
3598 OPT_SUBCOMMAND("push-check", &fn, push_check),
3599 OPT_SUBCOMMAND("absorbgitdirs", &fn, absorb_git_dirs),
3600 OPT_SUBCOMMAND("set-url", &fn, module_set_url),
3601 OPT_SUBCOMMAND("set-branch", &fn, module_set_branch),
3602 OPT_SUBCOMMAND("create-branch", &fn, module_create_branch),
3603 OPT_END()
3604 };
3605 argc = parse_options(argc, argv, prefix, options, usage, 0);
3606
3607 return fn(argc, argv, prefix, repo);
3608}