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