at commit a0189536

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