]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/submodule--helper.c
The fifth batch for 2.18
[thirdparty/git.git] / builtin / submodule--helper.c
CommitLineData
74703a1e 1#include "builtin.h"
627d9342 2#include "repository.h"
74703a1e 3#include "cache.h"
b2141fc1 4#include "config.h"
74703a1e
SB
5#include "parse-options.h"
6#include "quote.h"
7#include "pathspec.h"
8#include "dir.h"
0ea306ef
SB
9#include "submodule.h"
10#include "submodule-config.h"
11#include "string-list.h"
ee8838d1 12#include "run-command.h"
63e95beb
SB
13#include "remote.h"
14#include "refs.h"
15#include "connect.h"
a9f8a375
PC
16#include "revision.h"
17#include "diffcore.h"
18#include "diff.h"
0d4a1321 19#include "object-store.h"
63e95beb 20
9f580a62 21#define OPT_QUIET (1 << 0)
a9f8a375
PC
22#define OPT_CACHED (1 << 1)
23#define OPT_RECURSIVE (1 << 2)
2e612731 24#define OPT_FORCE (1 << 3)
9f580a62
PC
25
26typedef void (*each_submodule_fn)(const struct cache_entry *list_item,
27 void *cb_data);
63e95beb
SB
28
29static char *get_default_remote(void)
30{
31 char *dest = NULL, *ret;
63e95beb 32 struct strbuf sb = STRBUF_INIT;
744c040b 33 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
63e95beb
SB
34
35 if (!refname)
36 die(_("No such ref: %s"), "HEAD");
37
38 /* detached HEAD */
39 if (!strcmp(refname, "HEAD"))
40 return xstrdup("origin");
41
42 if (!skip_prefix(refname, "refs/heads/", &refname))
43 die(_("Expecting a full ref name, got %s"), refname);
44
45 strbuf_addf(&sb, "branch.%s.remote", refname);
46 if (git_config_get_string(sb.buf, &dest))
47 ret = xstrdup("origin");
48 else
49 ret = dest;
50
51 strbuf_release(&sb);
52 return ret;
53}
54
13424764
PC
55static int print_default_remote(int argc, const char **argv, const char *prefix)
56{
57 const char *remote;
58
59 if (argc != 1)
60 die(_("submodule--helper print-default-remote takes no arguments"));
61
62 remote = get_default_remote();
63 if (remote)
64 printf("%s\n", remote);
65
66 return 0;
67}
68
63e95beb
SB
69static int starts_with_dot_slash(const char *str)
70{
71 return str[0] == '.' && is_dir_sep(str[1]);
72}
73
74static int starts_with_dot_dot_slash(const char *str)
75{
76 return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
77}
78
79/*
80 * Returns 1 if it was the last chop before ':'.
81 */
82static int chop_last_dir(char **remoteurl, int is_relative)
83{
84 char *rfind = find_last_dir_sep(*remoteurl);
85 if (rfind) {
86 *rfind = '\0';
87 return 0;
88 }
89
90 rfind = strrchr(*remoteurl, ':');
91 if (rfind) {
92 *rfind = '\0';
93 return 1;
94 }
95
96 if (is_relative || !strcmp(".", *remoteurl))
97 die(_("cannot strip one component off url '%s'"),
98 *remoteurl);
99
100 free(*remoteurl);
101 *remoteurl = xstrdup(".");
102 return 0;
103}
104
105/*
106 * The `url` argument is the URL that navigates to the submodule origin
107 * repo. When relative, this URL is relative to the superproject origin
108 * URL repo. The `up_path` argument, if specified, is the relative
109 * path that navigates from the submodule working tree to the superproject
110 * working tree. Returns the origin URL of the submodule.
111 *
112 * Return either an absolute URL or filesystem path (if the superproject
113 * origin URL is an absolute URL or filesystem path, respectively) or a
114 * relative file system path (if the superproject origin URL is a relative
115 * file system path).
116 *
117 * When the output is a relative file system path, the path is either
118 * relative to the submodule working tree, if up_path is specified, or to
119 * the superproject working tree otherwise.
120 *
121 * NEEDSWORK: This works incorrectly on the domain and protocol part.
122 * remote_url url outcome expectation
123 * http://a.com/b ../c http://a.com/c as is
08788504
SB
124 * http://a.com/b/ ../c http://a.com/c same as previous line, but
125 * ignore trailing slash in url
63e95beb
SB
126 * http://a.com/b ../../c http://c error out
127 * http://a.com/b ../../../c http:/c error out
128 * http://a.com/b ../../../../c http:c error out
129 * http://a.com/b ../../../../../c .:c error out
130 * NEEDSWORK: Given how chop_last_dir() works, this function is broken
131 * when a local part has a colon in its path component, too.
132 */
133static char *relative_url(const char *remote_url,
134 const char *url,
135 const char *up_path)
136{
137 int is_relative = 0;
138 int colonsep = 0;
139 char *out;
140 char *remoteurl = xstrdup(remote_url);
141 struct strbuf sb = STRBUF_INIT;
142 size_t len = strlen(remoteurl);
143
08788504
SB
144 if (is_dir_sep(remoteurl[len-1]))
145 remoteurl[len-1] = '\0';
63e95beb
SB
146
147 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
148 is_relative = 0;
149 else {
150 is_relative = 1;
151 /*
152 * Prepend a './' to ensure all relative
153 * remoteurls start with './' or '../'
154 */
155 if (!starts_with_dot_slash(remoteurl) &&
156 !starts_with_dot_dot_slash(remoteurl)) {
157 strbuf_reset(&sb);
158 strbuf_addf(&sb, "./%s", remoteurl);
159 free(remoteurl);
160 remoteurl = strbuf_detach(&sb, NULL);
161 }
162 }
163 /*
164 * When the url starts with '../', remove that and the
165 * last directory in remoteurl.
166 */
167 while (url) {
168 if (starts_with_dot_dot_slash(url)) {
169 url += 3;
170 colonsep |= chop_last_dir(&remoteurl, is_relative);
171 } else if (starts_with_dot_slash(url))
172 url += 2;
173 else
174 break;
175 }
176 strbuf_reset(&sb);
177 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
3389e78e
SB
178 if (ends_with(url, "/"))
179 strbuf_setlen(&sb, sb.len - 1);
63e95beb
SB
180 free(remoteurl);
181
182 if (starts_with_dot_slash(sb.buf))
183 out = xstrdup(sb.buf + 2);
184 else
185 out = xstrdup(sb.buf);
186 strbuf_reset(&sb);
187
188 if (!up_path || !is_relative)
189 return out;
190
191 strbuf_addf(&sb, "%s%s", up_path, out);
192 free(out);
193 return strbuf_detach(&sb, NULL);
194}
195
196static int resolve_relative_url(int argc, const char **argv, const char *prefix)
197{
198 char *remoteurl = NULL;
199 char *remote = get_default_remote();
200 const char *up_path = NULL;
201 char *res;
202 const char *url;
203 struct strbuf sb = STRBUF_INIT;
204
205 if (argc != 2 && argc != 3)
206 die("resolve-relative-url only accepts one or two arguments");
207
208 url = argv[1];
209 strbuf_addf(&sb, "remote.%s.url", remote);
210 free(remote);
211
212 if (git_config_get_string(sb.buf, &remoteurl))
213 /* the repository is its own authoritative upstream */
214 remoteurl = xgetcwd();
215
216 if (argc == 3)
217 up_path = argv[2];
218
219 res = relative_url(remoteurl, url, up_path);
220 puts(res);
221 free(res);
222 free(remoteurl);
223 return 0;
224}
225
226static int resolve_relative_url_test(int argc, const char **argv, const char *prefix)
227{
228 char *remoteurl, *res;
229 const char *up_path, *url;
230
231 if (argc != 4)
232 die("resolve-relative-url-test only accepts three arguments: <up_path> <remoteurl> <url>");
233
234 up_path = argv[1];
235 remoteurl = xstrdup(argv[2]);
236 url = argv[3];
237
238 if (!strcmp(up_path, "(null)"))
239 up_path = NULL;
240
241 res = relative_url(remoteurl, url, up_path);
242 puts(res);
243 free(res);
244 free(remoteurl);
245 return 0;
246}
74703a1e 247
74a10642
PC
248/* the result should be freed by the caller. */
249static char *get_submodule_displaypath(const char *path, const char *prefix)
250{
251 const char *super_prefix = get_super_prefix();
252
253 if (prefix && super_prefix) {
254 BUG("cannot have prefix '%s' and superprefix '%s'",
255 prefix, super_prefix);
256 } else if (prefix) {
257 struct strbuf sb = STRBUF_INIT;
258 char *displaypath = xstrdup(relative_path(path, prefix, &sb));
259 strbuf_release(&sb);
260 return displaypath;
261 } else if (super_prefix) {
262 return xstrfmt("%s%s", super_prefix, path);
263 } else {
264 return xstrdup(path);
265 }
266}
267
a9f8a375
PC
268static char *compute_rev_name(const char *sub_path, const char* object_id)
269{
270 struct strbuf sb = STRBUF_INIT;
271 const char ***d;
272
273 static const char *describe_bare[] = { NULL };
274
275 static const char *describe_tags[] = { "--tags", NULL };
276
277 static const char *describe_contains[] = { "--contains", NULL };
278
279 static const char *describe_all_always[] = { "--all", "--always", NULL };
280
281 static const char **describe_argv[] = { describe_bare, describe_tags,
282 describe_contains,
283 describe_all_always, NULL };
284
285 for (d = describe_argv; *d; d++) {
286 struct child_process cp = CHILD_PROCESS_INIT;
287 prepare_submodule_repo_env(&cp.env_array);
288 cp.dir = sub_path;
289 cp.git_cmd = 1;
290 cp.no_stderr = 1;
291
292 argv_array_push(&cp.args, "describe");
293 argv_array_pushv(&cp.args, *d);
294 argv_array_push(&cp.args, object_id);
295
296 if (!capture_command(&cp, &sb, 0)) {
297 strbuf_strip_suffix(&sb, "\n");
298 return strbuf_detach(&sb, NULL);
299 }
300 }
301
302 strbuf_release(&sb);
303 return NULL;
304}
305
74703a1e
SB
306struct module_list {
307 const struct cache_entry **entries;
308 int alloc, nr;
309};
310#define MODULE_LIST_INIT { NULL, 0, 0 }
311
312static int module_list_compute(int argc, const char **argv,
313 const char *prefix,
314 struct pathspec *pathspec,
315 struct module_list *list)
316{
317 int i, result = 0;
2b56bb7a 318 char *ps_matched = NULL;
74703a1e 319 parse_pathspec(pathspec, 0,
2249d4db 320 PATHSPEC_PREFER_FULL,
74703a1e
SB
321 prefix, argv);
322
74703a1e
SB
323 if (pathspec->nr)
324 ps_matched = xcalloc(pathspec->nr, 1);
325
326 if (read_cache() < 0)
327 die(_("index file corrupt"));
328
329 for (i = 0; i < active_nr; i++) {
330 const struct cache_entry *ce = active_cache[i];
331
84ba959b
SB
332 if (!match_pathspec(pathspec, ce->name, ce_namelen(ce),
333 0, ps_matched, 1) ||
334 !S_ISGITLINK(ce->ce_mode))
74703a1e
SB
335 continue;
336
337 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
338 list->entries[list->nr++] = ce;
339 while (i + 1 < active_nr &&
340 !strcmp(ce->name, active_cache[i + 1]->name))
341 /*
342 * Skip entries with the same name in different stages
343 * to make sure an entry is returned only once.
344 */
345 i++;
346 }
74703a1e
SB
347
348 if (ps_matched && report_path_error(ps_matched, pathspec, prefix))
349 result = -1;
350
351 free(ps_matched);
352
353 return result;
354}
355
3e7eaed0
BW
356static void module_list_active(struct module_list *list)
357{
358 int i;
359 struct module_list active_modules = MODULE_LIST_INIT;
360
3e7eaed0
BW
361 for (i = 0; i < list->nr; i++) {
362 const struct cache_entry *ce = list->entries[i];
363
627d9342 364 if (!is_submodule_active(the_repository, ce->name))
3e7eaed0
BW
365 continue;
366
367 ALLOC_GROW(active_modules.entries,
368 active_modules.nr + 1,
369 active_modules.alloc);
370 active_modules.entries[active_modules.nr++] = ce;
371 }
372
373 free(list->entries);
374 *list = active_modules;
375}
376
13424764
PC
377static char *get_up_path(const char *path)
378{
379 int i;
380 struct strbuf sb = STRBUF_INIT;
381
382 for (i = count_slashes(path); i; i--)
383 strbuf_addstr(&sb, "../");
384
385 /*
386 * Check if 'path' ends with slash or not
387 * for having the same output for dir/sub_dir
388 * and dir/sub_dir/
389 */
390 if (!is_dir_sep(path[strlen(path) - 1]))
391 strbuf_addstr(&sb, "../");
392
393 return strbuf_detach(&sb, NULL);
394}
395
74703a1e
SB
396static int module_list(int argc, const char **argv, const char *prefix)
397{
398 int i;
399 struct pathspec pathspec;
400 struct module_list list = MODULE_LIST_INIT;
401
402 struct option module_list_options[] = {
403 OPT_STRING(0, "prefix", &prefix,
404 N_("path"),
405 N_("alternative anchor for relative paths")),
406 OPT_END()
407 };
408
409 const char *const git_submodule_helper_usage[] = {
410 N_("git submodule--helper list [--prefix=<path>] [<path>...]"),
411 NULL
412 };
413
414 argc = parse_options(argc, argv, prefix, module_list_options,
415 git_submodule_helper_usage, 0);
416
b0f4b408 417 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
74703a1e 418 return 1;
74703a1e
SB
419
420 for (i = 0; i < list.nr; i++) {
421 const struct cache_entry *ce = list.entries[i];
422
423 if (ce_stage(ce))
424 printf("%06o %s U\t", ce->ce_mode, sha1_to_hex(null_sha1));
425 else
99d1a986 426 printf("%06o %s %d\t", ce->ce_mode,
427 oid_to_hex(&ce->oid), ce_stage(ce));
74703a1e 428
dc4b4a61 429 fprintf(stdout, "%s\n", ce->name);
74703a1e
SB
430 }
431 return 0;
432}
433
9f580a62
PC
434static void for_each_listed_submodule(const struct module_list *list,
435 each_submodule_fn fn, void *cb_data)
436{
437 int i;
438 for (i = 0; i < list->nr; i++)
439 fn(list->entries[i], cb_data);
440}
441
442struct init_cb {
443 const char *prefix;
444 unsigned int flags;
445};
446
447#define INIT_CB_INIT { NULL, 0 }
448
449static void init_submodule(const char *path, const char *prefix,
450 unsigned int flags)
3604242f
SB
451{
452 const struct submodule *sub;
453 struct strbuf sb = STRBUF_INIT;
454 char *upd = NULL, *url = NULL, *displaypath;
455
74a10642 456 displaypath = get_submodule_displaypath(path, prefix);
d92028a5 457
3b8fb393 458 sub = submodule_from_path(the_repository, &null_oid, path);
d92028a5
SB
459
460 if (!sub)
461 die(_("No url found for submodule path '%s' in .gitmodules"),
462 displaypath);
3604242f 463
1f8d7115
BW
464 /*
465 * NEEDSWORK: In a multi-working-tree world, this needs to be
466 * set in the per-worktree config.
467 *
468 * Set active flag for the submodule being initialized
469 */
627d9342 470 if (!is_submodule_active(the_repository, path)) {
1f8d7115
BW
471 strbuf_addf(&sb, "submodule.%s.active", sub->name);
472 git_config_set_gently(sb.buf, "true");
74a10642 473 strbuf_reset(&sb);
1f8d7115
BW
474 }
475
3604242f
SB
476 /*
477 * Copy url setting when it is not set yet.
478 * To look up the url in .git/config, we must not fall back to
479 * .gitmodules, so look it up directly.
480 */
3604242f
SB
481 strbuf_addf(&sb, "submodule.%s.url", sub->name);
482 if (git_config_get_string(sb.buf, &url)) {
627fde10 483 if (!sub->url)
3604242f
SB
484 die(_("No url found for submodule path '%s' in .gitmodules"),
485 displaypath);
486
627fde10
JK
487 url = xstrdup(sub->url);
488
3604242f
SB
489 /* Possibly a url relative to parent */
490 if (starts_with_dot_dot_slash(url) ||
491 starts_with_dot_slash(url)) {
492 char *remoteurl, *relurl;
493 char *remote = get_default_remote();
494 struct strbuf remotesb = STRBUF_INIT;
495 strbuf_addf(&remotesb, "remote.%s.url", remote);
496 free(remote);
497
d1b3b81a
SB
498 if (git_config_get_string(remotesb.buf, &remoteurl)) {
499 warning(_("could not lookup configuration '%s'. Assuming this repository is its own authoritative upstream."), remotesb.buf);
3604242f 500 remoteurl = xgetcwd();
d1b3b81a 501 }
3604242f
SB
502 relurl = relative_url(remoteurl, url, NULL);
503 strbuf_release(&remotesb);
504 free(remoteurl);
505 free(url);
506 url = relurl;
507 }
508
509 if (git_config_set_gently(sb.buf, url))
510 die(_("Failed to register url for submodule path '%s'"),
511 displaypath);
9f580a62 512 if (!(flags & OPT_QUIET))
c66410ed
SB
513 fprintf(stderr,
514 _("Submodule '%s' (%s) registered for path '%s'\n"),
3604242f
SB
515 sub->name, url, displaypath);
516 }
74a10642 517 strbuf_reset(&sb);
3604242f
SB
518
519 /* Copy "update" setting when it is not set yet */
3604242f
SB
520 strbuf_addf(&sb, "submodule.%s.update", sub->name);
521 if (git_config_get_string(sb.buf, &upd) &&
522 sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
523 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
524 fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
525 sub->name);
526 upd = xstrdup("none");
527 } else
528 upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
529
530 if (git_config_set_gently(sb.buf, upd))
531 die(_("Failed to register update mode for submodule path '%s'"), displaypath);
532 }
533 strbuf_release(&sb);
534 free(displaypath);
535 free(url);
536 free(upd);
537}
538
9f580a62
PC
539static void init_submodule_cb(const struct cache_entry *list_item, void *cb_data)
540{
541 struct init_cb *info = cb_data;
542 init_submodule(list_item->name, info->prefix, info->flags);
543}
544
3604242f
SB
545static int module_init(int argc, const char **argv, const char *prefix)
546{
9f580a62 547 struct init_cb info = INIT_CB_INIT;
3604242f
SB
548 struct pathspec pathspec;
549 struct module_list list = MODULE_LIST_INIT;
550 int quiet = 0;
3604242f
SB
551
552 struct option module_init_options[] = {
3604242f
SB
553 OPT__QUIET(&quiet, N_("Suppress output for initializing a submodule")),
554 OPT_END()
555 };
556
557 const char *const git_submodule_helper_usage[] = {
558 N_("git submodule--helper init [<path>]"),
559 NULL
560 };
561
562 argc = parse_options(argc, argv, prefix, module_init_options,
563 git_submodule_helper_usage, 0);
564
565 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
566 return 1;
567
3e7eaed0
BW
568 /*
569 * If there are no path args and submodule.active is set then,
570 * by default, only initialize 'active' modules.
571 */
572 if (!argc && git_config_get_value_multi("submodule.active"))
573 module_list_active(&list);
574
9f580a62
PC
575 info.prefix = prefix;
576 if (quiet)
577 info.flags |= OPT_QUIET;
578
579 for_each_listed_submodule(&list, init_submodule_cb, &info);
3604242f
SB
580
581 return 0;
582}
583
a9f8a375
PC
584struct status_cb {
585 const char *prefix;
586 unsigned int flags;
587};
588
589#define STATUS_CB_INIT { NULL, 0 }
590
591static void print_status(unsigned int flags, char state, const char *path,
592 const struct object_id *oid, const char *displaypath)
593{
594 if (flags & OPT_QUIET)
595 return;
596
597 printf("%c%s %s", state, oid_to_hex(oid), displaypath);
598
0b5e2ea7
NTND
599 if (state == ' ' || state == '+') {
600 const char *name = compute_rev_name(path, oid_to_hex(oid));
601
602 if (name)
603 printf(" (%s)", name);
604 }
a9f8a375
PC
605
606 printf("\n");
607}
608
609static int handle_submodule_head_ref(const char *refname,
610 const struct object_id *oid, int flags,
611 void *cb_data)
612{
613 struct object_id *output = cb_data;
614 if (oid)
615 oidcpy(output, oid);
616
617 return 0;
618}
619
620static void status_submodule(const char *path, const struct object_id *ce_oid,
621 unsigned int ce_flags, const char *prefix,
622 unsigned int flags)
623{
624 char *displaypath;
625 struct argv_array diff_files_args = ARGV_ARRAY_INIT;
626 struct rev_info rev;
627 int diff_files_result;
628
3b8fb393 629 if (!submodule_from_path(the_repository, &null_oid, path))
a9f8a375
PC
630 die(_("no submodule mapping found in .gitmodules for path '%s'"),
631 path);
632
633 displaypath = get_submodule_displaypath(path, prefix);
634
635 if ((CE_STAGEMASK & ce_flags) >> CE_STAGESHIFT) {
636 print_status(flags, 'U', path, &null_oid, displaypath);
637 goto cleanup;
638 }
639
640 if (!is_submodule_active(the_repository, path)) {
641 print_status(flags, '-', path, ce_oid, displaypath);
642 goto cleanup;
643 }
644
645 argv_array_pushl(&diff_files_args, "diff-files",
646 "--ignore-submodules=dirty", "--quiet", "--",
647 path, NULL);
648
649 git_config(git_diff_basic_config, NULL);
650 init_revisions(&rev, prefix);
651 rev.abbrev = 0;
652 diff_files_args.argc = setup_revisions(diff_files_args.argc,
653 diff_files_args.argv,
654 &rev, NULL);
655 diff_files_result = run_diff_files(&rev, 0);
656
657 if (!diff_result_code(&rev.diffopt, diff_files_result)) {
658 print_status(flags, ' ', path, ce_oid,
659 displaypath);
660 } else if (!(flags & OPT_CACHED)) {
661 struct object_id oid;
74b6bda3 662 struct ref_store *refs = get_submodule_ref_store(path);
a9f8a375 663
74b6bda3
RS
664 if (!refs) {
665 print_status(flags, '-', path, ce_oid, displaypath);
666 goto cleanup;
667 }
668 if (refs_head_ref(refs, handle_submodule_head_ref, &oid))
ed5bdd5b 669 die(_("could not resolve HEAD ref inside the "
a9f8a375
PC
670 "submodule '%s'"), path);
671
672 print_status(flags, '+', path, &oid, displaypath);
673 } else {
674 print_status(flags, '+', path, ce_oid, displaypath);
675 }
676
677 if (flags & OPT_RECURSIVE) {
678 struct child_process cpr = CHILD_PROCESS_INIT;
679
680 cpr.git_cmd = 1;
681 cpr.dir = path;
682 prepare_submodule_repo_env(&cpr.env_array);
683
684 argv_array_push(&cpr.args, "--super-prefix");
685 argv_array_pushf(&cpr.args, "%s/", displaypath);
686 argv_array_pushl(&cpr.args, "submodule--helper", "status",
687 "--recursive", NULL);
688
689 if (flags & OPT_CACHED)
690 argv_array_push(&cpr.args, "--cached");
691
692 if (flags & OPT_QUIET)
693 argv_array_push(&cpr.args, "--quiet");
694
695 if (run_command(&cpr))
696 die(_("failed to recurse into submodule '%s'"), path);
697 }
698
699cleanup:
700 argv_array_clear(&diff_files_args);
701 free(displaypath);
702}
703
704static void status_submodule_cb(const struct cache_entry *list_item,
705 void *cb_data)
706{
707 struct status_cb *info = cb_data;
708 status_submodule(list_item->name, &list_item->oid, list_item->ce_flags,
709 info->prefix, info->flags);
710}
711
712static int module_status(int argc, const char **argv, const char *prefix)
713{
714 struct status_cb info = STATUS_CB_INIT;
715 struct pathspec pathspec;
716 struct module_list list = MODULE_LIST_INIT;
717 int quiet = 0;
718
719 struct option module_status_options[] = {
720 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
721 OPT_BIT(0, "cached", &info.flags, N_("Use commit stored in the index instead of the one stored in the submodule HEAD"), OPT_CACHED),
722 OPT_BIT(0, "recursive", &info.flags, N_("recurse into nested submodules"), OPT_RECURSIVE),
723 OPT_END()
724 };
725
726 const char *const git_submodule_helper_usage[] = {
727 N_("git submodule status [--quiet] [--cached] [--recursive] [<path>...]"),
728 NULL
729 };
730
731 argc = parse_options(argc, argv, prefix, module_status_options,
732 git_submodule_helper_usage, 0);
733
734 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
735 return 1;
736
737 info.prefix = prefix;
738 if (quiet)
739 info.flags |= OPT_QUIET;
740
741 for_each_listed_submodule(&list, status_submodule_cb, &info);
3604242f
SB
742
743 return 0;
744}
745
0ea306ef
SB
746static int module_name(int argc, const char **argv, const char *prefix)
747{
748 const struct submodule *sub;
749
750 if (argc != 2)
751 usage(_("git submodule--helper name <path>"));
752
3b8fb393 753 sub = submodule_from_path(the_repository, &null_oid, argv[1]);
0ea306ef
SB
754
755 if (!sub)
756 die(_("no submodule mapping found in .gitmodules for path '%s'"),
757 argv[1]);
758
759 printf("%s\n", sub->name);
760
761 return 0;
762}
14111fc4 763
13424764
PC
764struct sync_cb {
765 const char *prefix;
766 unsigned int flags;
767};
768
769#define SYNC_CB_INIT { NULL, 0 }
770
771static void sync_submodule(const char *path, const char *prefix,
772 unsigned int flags)
773{
774 const struct submodule *sub;
775 char *remote_key = NULL;
776 char *sub_origin_url, *super_config_url, *displaypath;
777 struct strbuf sb = STRBUF_INIT;
778 struct child_process cp = CHILD_PROCESS_INIT;
779 char *sub_config_path = NULL;
780
781 if (!is_submodule_active(the_repository, path))
782 return;
783
3b8fb393 784 sub = submodule_from_path(the_repository, &null_oid, path);
13424764
PC
785
786 if (sub && sub->url) {
787 if (starts_with_dot_dot_slash(sub->url) ||
788 starts_with_dot_slash(sub->url)) {
789 char *remote_url, *up_path;
790 char *remote = get_default_remote();
791 strbuf_addf(&sb, "remote.%s.url", remote);
792
793 if (git_config_get_string(sb.buf, &remote_url))
794 remote_url = xgetcwd();
795
796 up_path = get_up_path(path);
797 sub_origin_url = relative_url(remote_url, sub->url, up_path);
798 super_config_url = relative_url(remote_url, sub->url, NULL);
799
800 free(remote);
801 free(up_path);
802 free(remote_url);
803 } else {
804 sub_origin_url = xstrdup(sub->url);
805 super_config_url = xstrdup(sub->url);
806 }
807 } else {
808 sub_origin_url = xstrdup("");
809 super_config_url = xstrdup("");
810 }
811
812 displaypath = get_submodule_displaypath(path, prefix);
813
814 if (!(flags & OPT_QUIET))
815 printf(_("Synchronizing submodule url for '%s'\n"),
816 displaypath);
817
818 strbuf_reset(&sb);
819 strbuf_addf(&sb, "submodule.%s.url", sub->name);
820 if (git_config_set_gently(sb.buf, super_config_url))
821 die(_("failed to register url for submodule path '%s'"),
822 displaypath);
823
824 if (!is_submodule_populated_gently(path, NULL))
825 goto cleanup;
826
827 prepare_submodule_repo_env(&cp.env_array);
828 cp.git_cmd = 1;
829 cp.dir = path;
830 argv_array_pushl(&cp.args, "submodule--helper",
831 "print-default-remote", NULL);
832
833 strbuf_reset(&sb);
834 if (capture_command(&cp, &sb, 0))
835 die(_("failed to get the default remote for submodule '%s'"),
836 path);
837
838 strbuf_strip_suffix(&sb, "\n");
839 remote_key = xstrfmt("remote.%s.url", sb.buf);
840
841 strbuf_reset(&sb);
842 submodule_to_gitdir(&sb, path);
843 strbuf_addstr(&sb, "/config");
844
845 if (git_config_set_in_file_gently(sb.buf, remote_key, sub_origin_url))
846 die(_("failed to update remote for submodule '%s'"),
847 path);
848
849 if (flags & OPT_RECURSIVE) {
850 struct child_process cpr = CHILD_PROCESS_INIT;
851
852 cpr.git_cmd = 1;
853 cpr.dir = path;
854 prepare_submodule_repo_env(&cpr.env_array);
855
856 argv_array_push(&cpr.args, "--super-prefix");
857 argv_array_pushf(&cpr.args, "%s/", displaypath);
858 argv_array_pushl(&cpr.args, "submodule--helper", "sync",
859 "--recursive", NULL);
860
861 if (flags & OPT_QUIET)
862 argv_array_push(&cpr.args, "--quiet");
863
864 if (run_command(&cpr))
865 die(_("failed to recurse into submodule '%s'"),
866 path);
867 }
868
869cleanup:
870 free(super_config_url);
871 free(sub_origin_url);
872 strbuf_release(&sb);
873 free(remote_key);
874 free(displaypath);
875 free(sub_config_path);
876}
877
878static void sync_submodule_cb(const struct cache_entry *list_item, void *cb_data)
879{
880 struct sync_cb *info = cb_data;
881 sync_submodule(list_item->name, info->prefix, info->flags);
882
883}
884
885static int module_sync(int argc, const char **argv, const char *prefix)
886{
887 struct sync_cb info = SYNC_CB_INIT;
888 struct pathspec pathspec;
889 struct module_list list = MODULE_LIST_INIT;
890 int quiet = 0;
891 int recursive = 0;
892
893 struct option module_sync_options[] = {
894 OPT__QUIET(&quiet, N_("Suppress output of synchronizing submodule url")),
895 OPT_BOOL(0, "recursive", &recursive,
896 N_("Recurse into nested submodules")),
897 OPT_END()
898 };
899
900 const char *const git_submodule_helper_usage[] = {
901 N_("git submodule--helper sync [--quiet] [--recursive] [<path>]"),
902 NULL
903 };
904
905 argc = parse_options(argc, argv, prefix, module_sync_options,
906 git_submodule_helper_usage, 0);
907
908 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
909 return 1;
910
911 info.prefix = prefix;
912 if (quiet)
913 info.flags |= OPT_QUIET;
914 if (recursive)
915 info.flags |= OPT_RECURSIVE;
916
917 for_each_listed_submodule(&list, sync_submodule_cb, &info);
918
919 return 0;
920}
921
2e612731
PC
922struct deinit_cb {
923 const char *prefix;
924 unsigned int flags;
925};
926#define DEINIT_CB_INIT { NULL, 0 }
927
928static void deinit_submodule(const char *path, const char *prefix,
929 unsigned int flags)
930{
931 const struct submodule *sub;
932 char *displaypath = NULL;
933 struct child_process cp_config = CHILD_PROCESS_INIT;
934 struct strbuf sb_config = STRBUF_INIT;
935 char *sub_git_dir = xstrfmt("%s/.git", path);
936
3b8fb393 937 sub = submodule_from_path(the_repository, &null_oid, path);
2e612731
PC
938
939 if (!sub || !sub->name)
940 goto cleanup;
941
942 displaypath = get_submodule_displaypath(path, prefix);
943
944 /* remove the submodule work tree (unless the user already did it) */
945 if (is_directory(path)) {
946 struct strbuf sb_rm = STRBUF_INIT;
947 const char *format;
948
949 /*
950 * protect submodules containing a .git directory
951 * NEEDSWORK: instead of dying, automatically call
952 * absorbgitdirs and (possibly) warn.
953 */
954 if (is_directory(sub_git_dir))
955 die(_("Submodule work tree '%s' contains a .git "
956 "directory (use 'rm -rf' if you really want "
957 "to remove it including all of its history)"),
958 displaypath);
959
960 if (!(flags & OPT_FORCE)) {
961 struct child_process cp_rm = CHILD_PROCESS_INIT;
962 cp_rm.git_cmd = 1;
963 argv_array_pushl(&cp_rm.args, "rm", "-qn",
964 path, NULL);
965
966 if (run_command(&cp_rm))
967 die(_("Submodule work tree '%s' contains local "
968 "modifications; use '-f' to discard them"),
969 displaypath);
970 }
971
972 strbuf_addstr(&sb_rm, path);
973
974 if (!remove_dir_recursively(&sb_rm, 0))
975 format = _("Cleared directory '%s'\n");
976 else
977 format = _("Could not remove submodule work tree '%s'\n");
978
979 if (!(flags & OPT_QUIET))
980 printf(format, displaypath);
981
982 strbuf_release(&sb_rm);
983 }
984
985 if (mkdir(path, 0777))
986 printf(_("could not create empty submodule directory %s"),
987 displaypath);
988
989 cp_config.git_cmd = 1;
990 argv_array_pushl(&cp_config.args, "config", "--get-regexp", NULL);
991 argv_array_pushf(&cp_config.args, "submodule.%s\\.", sub->name);
992
993 /* remove the .git/config entries (unless the user already did it) */
994 if (!capture_command(&cp_config, &sb_config, 0) && sb_config.len) {
995 char *sub_key = xstrfmt("submodule.%s", sub->name);
996 /*
997 * remove the whole section so we have a clean state when
998 * the user later decides to init this submodule again
999 */
1000 git_config_rename_section_in_file(NULL, sub_key, NULL);
1001 if (!(flags & OPT_QUIET))
1002 printf(_("Submodule '%s' (%s) unregistered for path '%s'\n"),
1003 sub->name, sub->url, displaypath);
1004 free(sub_key);
1005 }
1006
1007cleanup:
1008 free(displaypath);
1009 free(sub_git_dir);
1010 strbuf_release(&sb_config);
1011}
1012
1013static void deinit_submodule_cb(const struct cache_entry *list_item,
1014 void *cb_data)
1015{
1016 struct deinit_cb *info = cb_data;
1017 deinit_submodule(list_item->name, info->prefix, info->flags);
1018}
1019
1020static int module_deinit(int argc, const char **argv, const char *prefix)
1021{
1022 struct deinit_cb info = DEINIT_CB_INIT;
1023 struct pathspec pathspec;
1024 struct module_list list = MODULE_LIST_INIT;
1025 int quiet = 0;
1026 int force = 0;
1027 int all = 0;
1028
1029 struct option module_deinit_options[] = {
1030 OPT__QUIET(&quiet, N_("Suppress submodule status output")),
7fb6aefd 1031 OPT__FORCE(&force, N_("Remove submodule working trees even if they contain local changes"), 0),
2e612731
PC
1032 OPT_BOOL(0, "all", &all, N_("Unregister all submodules")),
1033 OPT_END()
1034 };
1035
1036 const char *const git_submodule_helper_usage[] = {
1037 N_("git submodule deinit [--quiet] [-f | --force] [--all | [--] [<path>...]]"),
1038 NULL
1039 };
1040
1041 argc = parse_options(argc, argv, prefix, module_deinit_options,
1042 git_submodule_helper_usage, 0);
1043
1044 if (all && argc) {
1045 error("pathspec and --all are incompatible");
1046 usage_with_options(git_submodule_helper_usage,
1047 module_deinit_options);
1048 }
1049
1050 if (!argc && !all)
1051 die(_("Use '--all' if you really want to deinitialize all submodules"));
1052
1053 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
9748e39d 1054 return 1;
2e612731
PC
1055
1056 info.prefix = prefix;
1057 if (quiet)
1058 info.flags |= OPT_QUIET;
1059 if (force)
1060 info.flags |= OPT_FORCE;
1061
1062 for_each_listed_submodule(&list, deinit_submodule_cb, &info);
1063
1064 return 0;
1065}
1066
ee8838d1 1067static int clone_submodule(const char *path, const char *gitdir, const char *url,
72c5f883
JK
1068 const char *depth, struct string_list *reference,
1069 int quiet, int progress)
ee8838d1 1070{
542aa25d 1071 struct child_process cp = CHILD_PROCESS_INIT;
ee8838d1
SB
1072
1073 argv_array_push(&cp.args, "clone");
1074 argv_array_push(&cp.args, "--no-checkout");
1075 if (quiet)
1076 argv_array_push(&cp.args, "--quiet");
72c5f883
JK
1077 if (progress)
1078 argv_array_push(&cp.args, "--progress");
ee8838d1
SB
1079 if (depth && *depth)
1080 argv_array_pushl(&cp.args, "--depth", depth, NULL);
965dbea0
SB
1081 if (reference->nr) {
1082 struct string_list_item *item;
1083 for_each_string_list_item(item, reference)
1084 argv_array_pushl(&cp.args, "--reference",
1085 item->string, NULL);
1086 }
ee8838d1
SB
1087 if (gitdir && *gitdir)
1088 argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
1089
1090 argv_array_push(&cp.args, url);
1091 argv_array_push(&cp.args, path);
1092
1093 cp.git_cmd = 1;
14111fc4 1094 prepare_submodule_repo_env(&cp.env_array);
ee8838d1
SB
1095 cp.no_stdin = 1;
1096
1097 return run_command(&cp);
1098}
1099
31224cbd
SB
1100struct submodule_alternate_setup {
1101 const char *submodule_name;
1102 enum SUBMODULE_ALTERNATE_ERROR_MODE {
1103 SUBMODULE_ALTERNATE_ERROR_DIE,
1104 SUBMODULE_ALTERNATE_ERROR_INFO,
1105 SUBMODULE_ALTERNATE_ERROR_IGNORE
1106 } error_mode;
1107 struct string_list *reference;
1108};
1109#define SUBMODULE_ALTERNATE_SETUP_INIT { NULL, \
1110 SUBMODULE_ALTERNATE_ERROR_IGNORE, NULL }
1111
1112static int add_possible_reference_from_superproject(
1113 struct alternate_object_database *alt, void *sas_cb)
1114{
1115 struct submodule_alternate_setup *sas = sas_cb;
1116
31224cbd
SB
1117 /*
1118 * If the alternate object store is another repository, try the
bf03b790 1119 * standard layout with .git/(modules/<name>)+/objects
31224cbd 1120 */
bf03b790 1121 if (ends_with(alt->path, "/objects")) {
31224cbd
SB
1122 char *sm_alternate;
1123 struct strbuf sb = STRBUF_INIT;
1124 struct strbuf err = STRBUF_INIT;
597f9134
JK
1125 strbuf_add(&sb, alt->path, strlen(alt->path) - strlen("objects"));
1126
31224cbd
SB
1127 /*
1128 * We need to end the new path with '/' to mark it as a dir,
1129 * otherwise a submodule name containing '/' will be broken
1130 * as the last part of a missing submodule reference would
1131 * be taken as a file name.
1132 */
1133 strbuf_addf(&sb, "modules/%s/", sas->submodule_name);
1134
1135 sm_alternate = compute_alternate_path(sb.buf, &err);
1136 if (sm_alternate) {
1137 string_list_append(sas->reference, xstrdup(sb.buf));
1138 free(sm_alternate);
1139 } else {
1140 switch (sas->error_mode) {
1141 case SUBMODULE_ALTERNATE_ERROR_DIE:
1142 die(_("submodule '%s' cannot add alternate: %s"),
1143 sas->submodule_name, err.buf);
1144 case SUBMODULE_ALTERNATE_ERROR_INFO:
1145 fprintf(stderr, _("submodule '%s' cannot add alternate: %s"),
1146 sas->submodule_name, err.buf);
1147 case SUBMODULE_ALTERNATE_ERROR_IGNORE:
1148 ; /* nothing */
1149 }
1150 }
1151 strbuf_release(&sb);
1152 }
1153
31224cbd
SB
1154 return 0;
1155}
1156
1157static void prepare_possible_alternates(const char *sm_name,
1158 struct string_list *reference)
1159{
1160 char *sm_alternate = NULL, *error_strategy = NULL;
1161 struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
1162
1163 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1164 if (!sm_alternate)
1165 return;
1166
1167 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1168
1169 if (!error_strategy)
1170 error_strategy = xstrdup("die");
1171
1172 sas.submodule_name = sm_name;
1173 sas.reference = reference;
1174 if (!strcmp(error_strategy, "die"))
1175 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
1176 else if (!strcmp(error_strategy, "info"))
1177 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
1178 else if (!strcmp(error_strategy, "ignore"))
1179 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
1180 else
1181 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
1182
1183 if (!strcmp(sm_alternate, "superproject"))
1184 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
1185 else if (!strcmp(sm_alternate, "no"))
1186 ; /* do nothing */
1187 else
1188 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
1189
1190 free(sm_alternate);
1191 free(error_strategy);
1192}
1193
ee8838d1
SB
1194static int module_clone(int argc, const char **argv, const char *prefix)
1195{
965dbea0 1196 const char *name = NULL, *url = NULL, *depth = NULL;
ee8838d1 1197 int quiet = 0;
72c5f883 1198 int progress = 0;
1ea4d9b7 1199 char *p, *path = NULL, *sm_gitdir;
ee8838d1 1200 struct strbuf sb = STRBUF_INIT;
965dbea0 1201 struct string_list reference = STRING_LIST_INIT_NODUP;
bf03b790 1202 char *sm_alternate = NULL, *error_strategy = NULL;
ee8838d1
SB
1203
1204 struct option module_clone_options[] = {
1205 OPT_STRING(0, "prefix", &prefix,
1206 N_("path"),
1207 N_("alternative anchor for relative paths")),
1208 OPT_STRING(0, "path", &path,
1209 N_("path"),
1210 N_("where the new submodule will be cloned to")),
1211 OPT_STRING(0, "name", &name,
1212 N_("string"),
1213 N_("name of the new submodule")),
1214 OPT_STRING(0, "url", &url,
1215 N_("string"),
1216 N_("url where to clone the submodule from")),
965dbea0
SB
1217 OPT_STRING_LIST(0, "reference", &reference,
1218 N_("repo"),
ee8838d1
SB
1219 N_("reference repository")),
1220 OPT_STRING(0, "depth", &depth,
1221 N_("string"),
1222 N_("depth for shallow clones")),
1223 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
72c5f883
JK
1224 OPT_BOOL(0, "progress", &progress,
1225 N_("force cloning progress")),
ee8838d1
SB
1226 OPT_END()
1227 };
1228
1229 const char *const git_submodule_helper_usage[] = {
1230 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
7dad2633
JK
1231 "[--reference <repository>] [--name <name>] [--depth <depth>] "
1232 "--url <url> --path <path>"),
ee8838d1
SB
1233 NULL
1234 };
1235
1236 argc = parse_options(argc, argv, prefix, module_clone_options,
1237 git_submodule_helper_usage, 0);
1238
deef3cdc 1239 if (argc || !url || !path || !*path)
08e0970a
JK
1240 usage_with_options(git_submodule_helper_usage,
1241 module_clone_options);
1242
ee8838d1 1243 strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
0aaad415 1244 sm_gitdir = absolute_pathdup(sb.buf);
1ea4d9b7 1245 strbuf_reset(&sb);
f8eaa0ba
SB
1246
1247 if (!is_absolute_path(path)) {
1248 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
1249 path = strbuf_detach(&sb, NULL);
1250 } else
1251 path = xstrdup(path);
ee8838d1
SB
1252
1253 if (!file_exists(sm_gitdir)) {
1254 if (safe_create_leading_directories_const(sm_gitdir) < 0)
1255 die(_("could not create directory '%s'"), sm_gitdir);
31224cbd
SB
1256
1257 prepare_possible_alternates(name, &reference);
1258
72c5f883
JK
1259 if (clone_submodule(path, sm_gitdir, url, depth, &reference,
1260 quiet, progress))
ee8838d1
SB
1261 die(_("clone of '%s' into submodule path '%s' failed"),
1262 url, path);
1263 } else {
1264 if (safe_create_leading_directories_const(path) < 0)
1265 die(_("could not create directory '%s'"), path);
1266 strbuf_addf(&sb, "%s/index", sm_gitdir);
1267 unlink_or_warn(sb.buf);
1268 strbuf_reset(&sb);
1269 }
1270
da62f786 1271 connect_work_tree_and_git_dir(path, sm_gitdir, 0);
ee8838d1 1272
ee8838d1
SB
1273 p = git_pathdup_submodule(path, "config");
1274 if (!p)
1275 die(_("could not get submodule directory for '%s'"), path);
bf03b790
VS
1276
1277 /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
1278 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1279 if (sm_alternate)
1280 git_config_set_in_file(p, "submodule.alternateLocation",
1281 sm_alternate);
1282 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1283 if (error_strategy)
1284 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
1285 error_strategy);
1286
1287 free(sm_alternate);
1288 free(error_strategy);
1289
ee8838d1 1290 strbuf_release(&sb);
ee8838d1 1291 free(sm_gitdir);
f8eaa0ba 1292 free(path);
ee8838d1
SB
1293 free(p);
1294 return 0;
1295}
74703a1e 1296
48308681
SB
1297struct submodule_update_clone {
1298 /* index into 'list', the list of submodules to look into for cloning */
1299 int current;
1300 struct module_list list;
1301 unsigned warn_if_uninitialized : 1;
1302
1303 /* update parameter passed via commandline */
1304 struct submodule_update_strategy update;
1305
1306 /* configuration parameters which are passed on to the children */
72c5f883 1307 int progress;
48308681 1308 int quiet;
abed000a 1309 int recommend_shallow;
5f50f33e 1310 struct string_list references;
48308681
SB
1311 const char *depth;
1312 const char *recursive_prefix;
1313 const char *prefix;
1314
1315 /* Machine-readable status lines to be consumed by git-submodule.sh */
1316 struct string_list projectlines;
1317
1318 /* If we want to stop as fast as possible and return an error */
1319 unsigned quickstop : 1;
665b35ec
SB
1320
1321 /* failed clones to be retried again */
1322 const struct cache_entry **failed_clones;
1323 int failed_clones_nr, failed_clones_alloc;
48308681
SB
1324};
1325#define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
72c5f883 1326 SUBMODULE_UPDATE_STRATEGY_INIT, 0, 0, -1, STRING_LIST_INIT_DUP, \
5f50f33e 1327 NULL, NULL, NULL, \
665b35ec 1328 STRING_LIST_INIT_DUP, 0, NULL, 0, 0}
48308681 1329
08fdbdb1
SB
1330
1331static void next_submodule_warn_missing(struct submodule_update_clone *suc,
1332 struct strbuf *out, const char *displaypath)
1333{
1334 /*
1335 * Only mention uninitialized submodules when their
1336 * paths have been specified.
1337 */
1338 if (suc->warn_if_uninitialized) {
1339 strbuf_addf(out,
1340 _("Submodule path '%s' not initialized"),
1341 displaypath);
1342 strbuf_addch(out, '\n');
1343 strbuf_addstr(out,
1344 _("Maybe you want to use 'update --init'?"));
1345 strbuf_addch(out, '\n');
1346 }
1347}
1348
48308681
SB
1349/**
1350 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
1351 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
1352 */
1353static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
1354 struct child_process *child,
1355 struct submodule_update_clone *suc,
1356 struct strbuf *out)
1357{
1358 const struct submodule *sub = NULL;
ec6141a0
BW
1359 const char *url = NULL;
1360 const char *update_string;
1361 enum submodule_update_type update_type;
1362 char *key;
48308681
SB
1363 struct strbuf displaypath_sb = STRBUF_INIT;
1364 struct strbuf sb = STRBUF_INIT;
1365 const char *displaypath = NULL;
48308681
SB
1366 int needs_cloning = 0;
1367
1368 if (ce_stage(ce)) {
1369 if (suc->recursive_prefix)
1370 strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
1371 else
92d52fab 1372 strbuf_addstr(&sb, ce->name);
48308681
SB
1373 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
1374 strbuf_addch(out, '\n');
1375 goto cleanup;
1376 }
1377
3b8fb393 1378 sub = submodule_from_path(the_repository, &null_oid, ce->name);
48308681
SB
1379
1380 if (suc->recursive_prefix)
1381 displaypath = relative_path(suc->recursive_prefix,
1382 ce->name, &displaypath_sb);
1383 else
1384 displaypath = ce->name;
1385
08fdbdb1
SB
1386 if (!sub) {
1387 next_submodule_warn_missing(suc, out, displaypath);
1388 goto cleanup;
1389 }
1390
ec6141a0
BW
1391 key = xstrfmt("submodule.%s.update", sub->name);
1392 if (!repo_config_get_string_const(the_repository, key, &update_string)) {
1393 update_type = parse_submodule_update_type(update_string);
1394 } else {
1395 update_type = sub->update_strategy.type;
1396 }
1397 free(key);
1398
48308681
SB
1399 if (suc->update.type == SM_UPDATE_NONE
1400 || (suc->update.type == SM_UPDATE_UNSPECIFIED
ec6141a0 1401 && update_type == SM_UPDATE_NONE)) {
48308681
SB
1402 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
1403 strbuf_addch(out, '\n');
1404 goto cleanup;
1405 }
1406
ee92ab99 1407 /* Check if the submodule has been initialized. */
627d9342 1408 if (!is_submodule_active(the_repository, ce->name)) {
08fdbdb1 1409 next_submodule_warn_missing(suc, out, displaypath);
48308681
SB
1410 goto cleanup;
1411 }
1412
ec6141a0
BW
1413 strbuf_reset(&sb);
1414 strbuf_addf(&sb, "submodule.%s.url", sub->name);
1415 if (repo_config_get_string_const(the_repository, sb.buf, &url))
1416 url = sub->url;
1417
48308681
SB
1418 strbuf_reset(&sb);
1419 strbuf_addf(&sb, "%s/.git", ce->name);
1420 needs_cloning = !file_exists(sb.buf);
1421
1422 strbuf_reset(&sb);
1423 strbuf_addf(&sb, "%06o %s %d %d\t%s\n", ce->ce_mode,
99d1a986 1424 oid_to_hex(&ce->oid), ce_stage(ce),
48308681
SB
1425 needs_cloning, ce->name);
1426 string_list_append(&suc->projectlines, sb.buf);
1427
1428 if (!needs_cloning)
1429 goto cleanup;
1430
1431 child->git_cmd = 1;
1432 child->no_stdin = 1;
1433 child->stdout_to_stderr = 1;
1434 child->err = -1;
1435 argv_array_push(&child->args, "submodule--helper");
1436 argv_array_push(&child->args, "clone");
72c5f883
JK
1437 if (suc->progress)
1438 argv_array_push(&child->args, "--progress");
48308681
SB
1439 if (suc->quiet)
1440 argv_array_push(&child->args, "--quiet");
1441 if (suc->prefix)
1442 argv_array_pushl(&child->args, "--prefix", suc->prefix, NULL);
abed000a
SB
1443 if (suc->recommend_shallow && sub->recommend_shallow == 1)
1444 argv_array_push(&child->args, "--depth=1");
48308681
SB
1445 argv_array_pushl(&child->args, "--path", sub->path, NULL);
1446 argv_array_pushl(&child->args, "--name", sub->name, NULL);
ec6141a0 1447 argv_array_pushl(&child->args, "--url", url, NULL);
5f50f33e
SB
1448 if (suc->references.nr) {
1449 struct string_list_item *item;
1450 for_each_string_list_item(item, &suc->references)
1451 argv_array_pushl(&child->args, "--reference", item->string, NULL);
1452 }
48308681
SB
1453 if (suc->depth)
1454 argv_array_push(&child->args, suc->depth);
1455
1456cleanup:
48308681
SB
1457 strbuf_reset(&displaypath_sb);
1458 strbuf_reset(&sb);
1459
1460 return needs_cloning;
1461}
1462
1463static int update_clone_get_next_task(struct child_process *child,
1464 struct strbuf *err,
1465 void *suc_cb,
665b35ec 1466 void **idx_task_cb)
48308681
SB
1467{
1468 struct submodule_update_clone *suc = suc_cb;
665b35ec
SB
1469 const struct cache_entry *ce;
1470 int index;
48308681
SB
1471
1472 for (; suc->current < suc->list.nr; suc->current++) {
665b35ec 1473 ce = suc->list.entries[suc->current];
48308681 1474 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
665b35ec
SB
1475 int *p = xmalloc(sizeof(*p));
1476 *p = suc->current;
1477 *idx_task_cb = p;
48308681
SB
1478 suc->current++;
1479 return 1;
1480 }
1481 }
665b35ec
SB
1482
1483 /*
1484 * The loop above tried cloning each submodule once, now try the
1485 * stragglers again, which we can imagine as an extension of the
1486 * entry list.
1487 */
1488 index = suc->current - suc->list.nr;
1489 if (index < suc->failed_clones_nr) {
1490 int *p;
1491 ce = suc->failed_clones[index];
2201ee09
SB
1492 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
1493 suc->current ++;
a22ae753
RS
1494 strbuf_addstr(err, "BUG: submodule considered for "
1495 "cloning, doesn't need cloning "
1496 "any more?\n");
2201ee09
SB
1497 return 0;
1498 }
665b35ec
SB
1499 p = xmalloc(sizeof(*p));
1500 *p = suc->current;
1501 *idx_task_cb = p;
1502 suc->current ++;
1503 return 1;
1504 }
1505
48308681
SB
1506 return 0;
1507}
1508
1509static int update_clone_start_failure(struct strbuf *err,
1510 void *suc_cb,
665b35ec 1511 void *idx_task_cb)
48308681
SB
1512{
1513 struct submodule_update_clone *suc = suc_cb;
1514 suc->quickstop = 1;
1515 return 1;
1516}
1517
1518static int update_clone_task_finished(int result,
1519 struct strbuf *err,
1520 void *suc_cb,
665b35ec 1521 void *idx_task_cb)
48308681 1522{
665b35ec 1523 const struct cache_entry *ce;
48308681
SB
1524 struct submodule_update_clone *suc = suc_cb;
1525
c1e860f1 1526 int *idxP = idx_task_cb;
665b35ec
SB
1527 int idx = *idxP;
1528 free(idxP);
1529
48308681
SB
1530 if (!result)
1531 return 0;
1532
665b35ec
SB
1533 if (idx < suc->list.nr) {
1534 ce = suc->list.entries[idx];
1535 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
1536 ce->name);
1537 strbuf_addch(err, '\n');
1538 ALLOC_GROW(suc->failed_clones,
1539 suc->failed_clones_nr + 1,
1540 suc->failed_clones_alloc);
1541 suc->failed_clones[suc->failed_clones_nr++] = ce;
1542 return 0;
1543 } else {
eb09121b 1544 idx -= suc->list.nr;
665b35ec
SB
1545 ce = suc->failed_clones[idx];
1546 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
1547 ce->name);
1548 strbuf_addch(err, '\n');
1549 suc->quickstop = 1;
1550 return 1;
1551 }
1552
1553 return 0;
48308681
SB
1554}
1555
f20e7c1e
BW
1556static int gitmodules_update_clone_config(const char *var, const char *value,
1557 void *cb)
1558{
1559 int *max_jobs = cb;
1560 if (!strcmp(var, "submodule.fetchjobs"))
1561 *max_jobs = parse_submodule_fetchjobs(var, value);
1562 return 0;
1563}
1564
48308681
SB
1565static int update_clone(int argc, const char **argv, const char *prefix)
1566{
1567 const char *update = NULL;
f20e7c1e 1568 int max_jobs = 1;
48308681
SB
1569 struct string_list_item *item;
1570 struct pathspec pathspec;
1571 struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
1572
1573 struct option module_update_clone_options[] = {
1574 OPT_STRING(0, "prefix", &prefix,
1575 N_("path"),
1576 N_("path into the working tree")),
1577 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
1578 N_("path"),
1579 N_("path into the working tree, across nested "
1580 "submodule boundaries")),
1581 OPT_STRING(0, "update", &update,
1582 N_("string"),
1583 N_("rebase, merge, checkout or none")),
5f50f33e 1584 OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
48308681
SB
1585 N_("reference repository")),
1586 OPT_STRING(0, "depth", &suc.depth, "<depth>",
1587 N_("Create a shallow clone truncated to the "
1588 "specified number of revisions")),
2335b870
SB
1589 OPT_INTEGER('j', "jobs", &max_jobs,
1590 N_("parallel jobs")),
abed000a
SB
1591 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
1592 N_("whether the initial clone should follow the shallow recommendation")),
48308681 1593 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
72c5f883
JK
1594 OPT_BOOL(0, "progress", &suc.progress,
1595 N_("force cloning progress")),
48308681
SB
1596 OPT_END()
1597 };
1598
1599 const char *const git_submodule_helper_usage[] = {
1600 N_("git submodule--helper update_clone [--prefix=<path>] [<path>...]"),
1601 NULL
1602 };
1603 suc.prefix = prefix;
1604
f20e7c1e
BW
1605 config_from_gitmodules(gitmodules_update_clone_config, &max_jobs);
1606 git_config(gitmodules_update_clone_config, &max_jobs);
1607
48308681
SB
1608 argc = parse_options(argc, argv, prefix, module_update_clone_options,
1609 git_submodule_helper_usage, 0);
1610
1611 if (update)
1612 if (parse_submodule_update_strategy(update, &suc.update) < 0)
1613 die(_("bad value for update parameter"));
1614
1615 if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
1616 return 1;
1617
1618 if (pathspec.nr)
1619 suc.warn_if_uninitialized = 1;
1620
2335b870 1621 run_processes_parallel(max_jobs,
48308681
SB
1622 update_clone_get_next_task,
1623 update_clone_start_failure,
1624 update_clone_task_finished,
1625 &suc);
1626
1627 /*
1628 * We saved the output and put it out all at once now.
1629 * That means:
1630 * - the listener does not have to interleave their (checkout)
1631 * work with our fetching. The writes involved in a
1632 * checkout involve more straightforward sequential I/O.
1633 * - the listener can avoid doing any work if fetching failed.
1634 */
1635 if (suc.quickstop)
1636 return 1;
1637
1638 for_each_string_list_item(item, &suc.projectlines)
dc4b4a61 1639 fprintf(stdout, "%s", item->string);
48308681
SB
1640
1641 return 0;
1642}
1643
44431df0
SB
1644static int resolve_relative_path(int argc, const char **argv, const char *prefix)
1645{
1646 struct strbuf sb = STRBUF_INIT;
1647 if (argc != 3)
2de26ae1 1648 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
44431df0
SB
1649
1650 printf("%s", relative_path(argv[1], argv[2], &sb));
1651 strbuf_release(&sb);
1652 return 0;
1653}
1654
92bbe7cc
SB
1655static const char *remote_submodule_branch(const char *path)
1656{
1657 const struct submodule *sub;
177257cc
BW
1658 const char *branch = NULL;
1659 char *key;
92bbe7cc 1660
3b8fb393 1661 sub = submodule_from_path(the_repository, &null_oid, path);
92bbe7cc
SB
1662 if (!sub)
1663 return NULL;
1664
177257cc
BW
1665 key = xstrfmt("submodule.%s.branch", sub->name);
1666 if (repo_config_get_string_const(the_repository, key, &branch))
1667 branch = sub->branch;
1668 free(key);
1669
1670 if (!branch)
92bbe7cc
SB
1671 return "master";
1672
177257cc 1673 if (!strcmp(branch, ".")) {
744c040b 1674 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
4d7bc52b
SB
1675
1676 if (!refname)
1677 die(_("No such ref: %s"), "HEAD");
1678
1679 /* detached HEAD */
1680 if (!strcmp(refname, "HEAD"))
1681 die(_("Submodule (%s) branch configured to inherit "
1682 "branch from superproject, but the superproject "
1683 "is not on any branch"), sub->name);
1684
1685 if (!skip_prefix(refname, "refs/heads/", &refname))
1686 die(_("Expecting a full ref name, got %s"), refname);
1687 return refname;
1688 }
1689
177257cc 1690 return branch;
92bbe7cc
SB
1691}
1692
1693static int resolve_remote_submodule_branch(int argc, const char **argv,
1694 const char *prefix)
1695{
1696 const char *ret;
1697 struct strbuf sb = STRBUF_INIT;
1698 if (argc != 2)
1699 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
1700
1701 ret = remote_submodule_branch(argv[1]);
1702 if (!ret)
1703 die("submodule %s doesn't exist", argv[1]);
1704
1705 printf("%s", ret);
1706 strbuf_release(&sb);
1707 return 0;
1708}
1709
93481a6b
BW
1710static int push_check(int argc, const char **argv, const char *prefix)
1711{
1712 struct remote *remote;
c7be7201
BW
1713 const char *superproject_head;
1714 char *head;
1715 int detached_head = 0;
1716 struct object_id head_oid;
93481a6b 1717
c7be7201
BW
1718 if (argc < 3)
1719 die("submodule--helper push-check requires at least 2 arguments");
1720
1721 /*
1722 * superproject's resolved head ref.
1723 * if HEAD then the superproject is in a detached head state, otherwise
1724 * it will be the resolved head ref.
1725 */
1726 superproject_head = argv[1];
1727 argv++;
1728 argc--;
1729 /* Get the submodule's head ref and determine if it is detached */
0f2dc722 1730 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
c7be7201
BW
1731 if (!head)
1732 die(_("Failed to resolve HEAD as a valid ref."));
1733 if (!strcmp(head, "HEAD"))
1734 detached_head = 1;
93481a6b
BW
1735
1736 /*
1737 * The remote must be configured.
1738 * This is to avoid pushing to the exact same URL as the parent.
1739 */
1740 remote = pushremote_get(argv[1]);
1741 if (!remote || remote->origin == REMOTE_UNCONFIGURED)
1742 die("remote '%s' not configured", argv[1]);
1743
1744 /* Check the refspec */
1745 if (argc > 2) {
1746 int i, refspec_nr = argc - 2;
1747 struct ref *local_refs = get_local_heads();
1748 struct refspec *refspec = parse_push_refspec(refspec_nr,
1749 argv + 2);
1750
1751 for (i = 0; i < refspec_nr; i++) {
1752 struct refspec *rs = refspec + i;
1753
1754 if (rs->pattern || rs->matching)
1755 continue;
1756
c7be7201
BW
1757 /* LHS must match a single ref */
1758 switch (count_refspec_match(rs->src, local_refs, NULL)) {
1759 case 1:
1760 break;
1761 case 0:
1762 /*
1763 * If LHS matches 'HEAD' then we need to ensure
1764 * that it matches the same named branch
1765 * checked out in the superproject.
1766 */
1767 if (!strcmp(rs->src, "HEAD")) {
1768 if (!detached_head &&
1769 !strcmp(head, superproject_head))
1770 break;
1771 die("HEAD does not match the named branch in the superproject");
1772 }
1cf01a34 1773 /* fallthrough */
c7be7201 1774 default:
93481a6b
BW
1775 die("src refspec '%s' must name a ref",
1776 rs->src);
c7be7201 1777 }
93481a6b
BW
1778 }
1779 free_refspec(refspec_nr, refspec);
1780 }
c7be7201 1781 free(head);
93481a6b
BW
1782
1783 return 0;
1784}
1785
f6f85861
SB
1786static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
1787{
1788 int i;
1789 struct pathspec pathspec;
1790 struct module_list list = MODULE_LIST_INIT;
1791 unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
1792
1793 struct option embed_gitdir_options[] = {
1794 OPT_STRING(0, "prefix", &prefix,
1795 N_("path"),
1796 N_("path into the working tree")),
1797 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
1798 ABSORB_GITDIR_RECURSE_SUBMODULES),
1799 OPT_END()
1800 };
1801
1802 const char *const git_submodule_helper_usage[] = {
1803 N_("git submodule--helper embed-git-dir [<path>...]"),
1804 NULL
1805 };
1806
1807 argc = parse_options(argc, argv, prefix, embed_gitdir_options,
1808 git_submodule_helper_usage, 0);
1809
f6f85861
SB
1810 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1811 return 1;
1812
1813 for (i = 0; i < list.nr; i++)
1814 absorb_git_dir_into_superproject(prefix,
1815 list.entries[i]->name, flags);
1816
1817 return 0;
1818}
1819
5c2bd8b7
BW
1820static int is_active(int argc, const char **argv, const char *prefix)
1821{
1822 if (argc != 2)
9af7ec30 1823 die("submodule--helper is-active takes exactly 1 argument");
5c2bd8b7 1824
627d9342 1825 return !is_submodule_active(the_repository, argv[1]);
5c2bd8b7
BW
1826}
1827
89c86265
SB
1828#define SUPPORT_SUPER_PREFIX (1<<0)
1829
74703a1e
SB
1830struct cmd_struct {
1831 const char *cmd;
1832 int (*fn)(int, const char **, const char *);
89c86265 1833 unsigned option;
74703a1e
SB
1834};
1835
1836static struct cmd_struct commands[] = {
89c86265
SB
1837 {"list", module_list, 0},
1838 {"name", module_name, 0},
1839 {"clone", module_clone, 0},
1840 {"update-clone", update_clone, 0},
1841 {"relative-path", resolve_relative_path, 0},
1842 {"resolve-relative-url", resolve_relative_url, 0},
1843 {"resolve-relative-url-test", resolve_relative_url_test, 0},
6e7c14e6 1844 {"init", module_init, SUPPORT_SUPER_PREFIX},
a9f8a375 1845 {"status", module_status, SUPPORT_SUPER_PREFIX},
13424764
PC
1846 {"print-default-remote", print_default_remote, 0},
1847 {"sync", module_sync, SUPPORT_SUPER_PREFIX},
2e612731 1848 {"deinit", module_deinit, 0},
89c86265 1849 {"remote-branch", resolve_remote_submodule_branch, 0},
93481a6b 1850 {"push-check", push_check, 0},
f6f85861 1851 {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
5c2bd8b7 1852 {"is-active", is_active, 0},
74703a1e
SB
1853};
1854
1855int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
1856{
1857 int i;
f0994fa8
JK
1858 if (argc < 2 || !strcmp(argv[1], "-h"))
1859 usage("git submodule--helper <command>");
74703a1e 1860
89c86265
SB
1861 for (i = 0; i < ARRAY_SIZE(commands); i++) {
1862 if (!strcmp(argv[1], commands[i].cmd)) {
1863 if (get_super_prefix() &&
1864 !(commands[i].option & SUPPORT_SUPER_PREFIX))
1865 die(_("%s doesn't support --super-prefix"),
1866 commands[i].cmd);
74703a1e 1867 return commands[i].fn(argc - 1, argv + 1, prefix);
89c86265
SB
1868 }
1869 }
74703a1e 1870
cdc04b65 1871 die(_("'%s' is not a valid submodule--helper "
74703a1e
SB
1872 "subcommand"), argv[1]);
1873}