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