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