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