]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/submodule--helper.c
curl_trace(): eliminate switch fallthrough
[thirdparty/git.git] / builtin / submodule--helper.c
CommitLineData
74703a1e 1#include "builtin.h"
627d9342 2#include "repository.h"
74703a1e 3#include "cache.h"
b2141fc1 4#include "config.h"
74703a1e
SB
5#include "parse-options.h"
6#include "quote.h"
7#include "pathspec.h"
8#include "dir.h"
0ea306ef
SB
9#include "submodule.h"
10#include "submodule-config.h"
11#include "string-list.h"
ee8838d1 12#include "run-command.h"
63e95beb
SB
13#include "remote.h"
14#include "refs.h"
15#include "connect.h"
16
17static char *get_default_remote(void)
18{
19 char *dest = NULL, *ret;
20 unsigned char sha1[20];
21 struct strbuf sb = STRBUF_INIT;
22 const char *refname = resolve_ref_unsafe("HEAD", 0, sha1, NULL);
23
24 if (!refname)
25 die(_("No such ref: %s"), "HEAD");
26
27 /* detached HEAD */
28 if (!strcmp(refname, "HEAD"))
29 return xstrdup("origin");
30
31 if (!skip_prefix(refname, "refs/heads/", &refname))
32 die(_("Expecting a full ref name, got %s"), refname);
33
34 strbuf_addf(&sb, "branch.%s.remote", refname);
35 if (git_config_get_string(sb.buf, &dest))
36 ret = xstrdup("origin");
37 else
38 ret = dest;
39
40 strbuf_release(&sb);
41 return ret;
42}
43
44static int starts_with_dot_slash(const char *str)
45{
46 return str[0] == '.' && is_dir_sep(str[1]);
47}
48
49static int starts_with_dot_dot_slash(const char *str)
50{
51 return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
52}
53
54/*
55 * Returns 1 if it was the last chop before ':'.
56 */
57static int chop_last_dir(char **remoteurl, int is_relative)
58{
59 char *rfind = find_last_dir_sep(*remoteurl);
60 if (rfind) {
61 *rfind = '\0';
62 return 0;
63 }
64
65 rfind = strrchr(*remoteurl, ':');
66 if (rfind) {
67 *rfind = '\0';
68 return 1;
69 }
70
71 if (is_relative || !strcmp(".", *remoteurl))
72 die(_("cannot strip one component off url '%s'"),
73 *remoteurl);
74
75 free(*remoteurl);
76 *remoteurl = xstrdup(".");
77 return 0;
78}
79
80/*
81 * The `url` argument is the URL that navigates to the submodule origin
82 * repo. When relative, this URL is relative to the superproject origin
83 * URL repo. The `up_path` argument, if specified, is the relative
84 * path that navigates from the submodule working tree to the superproject
85 * working tree. Returns the origin URL of the submodule.
86 *
87 * Return either an absolute URL or filesystem path (if the superproject
88 * origin URL is an absolute URL or filesystem path, respectively) or a
89 * relative file system path (if the superproject origin URL is a relative
90 * file system path).
91 *
92 * When the output is a relative file system path, the path is either
93 * relative to the submodule working tree, if up_path is specified, or to
94 * the superproject working tree otherwise.
95 *
96 * NEEDSWORK: This works incorrectly on the domain and protocol part.
97 * remote_url url outcome expectation
98 * http://a.com/b ../c http://a.com/c as is
08788504
SB
99 * http://a.com/b/ ../c http://a.com/c same as previous line, but
100 * ignore trailing slash in url
63e95beb
SB
101 * http://a.com/b ../../c http://c error out
102 * http://a.com/b ../../../c http:/c error out
103 * http://a.com/b ../../../../c http:c error out
104 * http://a.com/b ../../../../../c .:c error out
105 * NEEDSWORK: Given how chop_last_dir() works, this function is broken
106 * when a local part has a colon in its path component, too.
107 */
108static char *relative_url(const char *remote_url,
109 const char *url,
110 const char *up_path)
111{
112 int is_relative = 0;
113 int colonsep = 0;
114 char *out;
115 char *remoteurl = xstrdup(remote_url);
116 struct strbuf sb = STRBUF_INIT;
117 size_t len = strlen(remoteurl);
118
08788504
SB
119 if (is_dir_sep(remoteurl[len-1]))
120 remoteurl[len-1] = '\0';
63e95beb
SB
121
122 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
123 is_relative = 0;
124 else {
125 is_relative = 1;
126 /*
127 * Prepend a './' to ensure all relative
128 * remoteurls start with './' or '../'
129 */
130 if (!starts_with_dot_slash(remoteurl) &&
131 !starts_with_dot_dot_slash(remoteurl)) {
132 strbuf_reset(&sb);
133 strbuf_addf(&sb, "./%s", remoteurl);
134 free(remoteurl);
135 remoteurl = strbuf_detach(&sb, NULL);
136 }
137 }
138 /*
139 * When the url starts with '../', remove that and the
140 * last directory in remoteurl.
141 */
142 while (url) {
143 if (starts_with_dot_dot_slash(url)) {
144 url += 3;
145 colonsep |= chop_last_dir(&remoteurl, is_relative);
146 } else if (starts_with_dot_slash(url))
147 url += 2;
148 else
149 break;
150 }
151 strbuf_reset(&sb);
152 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
3389e78e
SB
153 if (ends_with(url, "/"))
154 strbuf_setlen(&sb, sb.len - 1);
63e95beb
SB
155 free(remoteurl);
156
157 if (starts_with_dot_slash(sb.buf))
158 out = xstrdup(sb.buf + 2);
159 else
160 out = xstrdup(sb.buf);
161 strbuf_reset(&sb);
162
163 if (!up_path || !is_relative)
164 return out;
165
166 strbuf_addf(&sb, "%s%s", up_path, out);
167 free(out);
168 return strbuf_detach(&sb, NULL);
169}
170
171static int resolve_relative_url(int argc, const char **argv, const char *prefix)
172{
173 char *remoteurl = NULL;
174 char *remote = get_default_remote();
175 const char *up_path = NULL;
176 char *res;
177 const char *url;
178 struct strbuf sb = STRBUF_INIT;
179
180 if (argc != 2 && argc != 3)
181 die("resolve-relative-url only accepts one or two arguments");
182
183 url = argv[1];
184 strbuf_addf(&sb, "remote.%s.url", remote);
185 free(remote);
186
187 if (git_config_get_string(sb.buf, &remoteurl))
188 /* the repository is its own authoritative upstream */
189 remoteurl = xgetcwd();
190
191 if (argc == 3)
192 up_path = argv[2];
193
194 res = relative_url(remoteurl, url, up_path);
195 puts(res);
196 free(res);
197 free(remoteurl);
198 return 0;
199}
200
201static int resolve_relative_url_test(int argc, const char **argv, const char *prefix)
202{
203 char *remoteurl, *res;
204 const char *up_path, *url;
205
206 if (argc != 4)
207 die("resolve-relative-url-test only accepts three arguments: <up_path> <remoteurl> <url>");
208
209 up_path = argv[1];
210 remoteurl = xstrdup(argv[2]);
211 url = argv[3];
212
213 if (!strcmp(up_path, "(null)"))
214 up_path = NULL;
215
216 res = relative_url(remoteurl, url, up_path);
217 puts(res);
218 free(res);
219 free(remoteurl);
220 return 0;
221}
74703a1e
SB
222
223struct module_list {
224 const struct cache_entry **entries;
225 int alloc, nr;
226};
227#define MODULE_LIST_INIT { NULL, 0, 0 }
228
229static int module_list_compute(int argc, const char **argv,
230 const char *prefix,
231 struct pathspec *pathspec,
232 struct module_list *list)
233{
234 int i, result = 0;
2b56bb7a 235 char *ps_matched = NULL;
74703a1e 236 parse_pathspec(pathspec, 0,
2249d4db 237 PATHSPEC_PREFER_FULL,
74703a1e
SB
238 prefix, argv);
239
74703a1e
SB
240 if (pathspec->nr)
241 ps_matched = xcalloc(pathspec->nr, 1);
242
243 if (read_cache() < 0)
244 die(_("index file corrupt"));
245
246 for (i = 0; i < active_nr; i++) {
247 const struct cache_entry *ce = active_cache[i];
248
84ba959b
SB
249 if (!match_pathspec(pathspec, ce->name, ce_namelen(ce),
250 0, ps_matched, 1) ||
251 !S_ISGITLINK(ce->ce_mode))
74703a1e
SB
252 continue;
253
254 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
255 list->entries[list->nr++] = ce;
256 while (i + 1 < active_nr &&
257 !strcmp(ce->name, active_cache[i + 1]->name))
258 /*
259 * Skip entries with the same name in different stages
260 * to make sure an entry is returned only once.
261 */
262 i++;
263 }
74703a1e
SB
264
265 if (ps_matched && report_path_error(ps_matched, pathspec, prefix))
266 result = -1;
267
268 free(ps_matched);
269
270 return result;
271}
272
3e7eaed0
BW
273static void module_list_active(struct module_list *list)
274{
275 int i;
276 struct module_list active_modules = MODULE_LIST_INIT;
277
3e7eaed0
BW
278 for (i = 0; i < list->nr; i++) {
279 const struct cache_entry *ce = list->entries[i];
280
627d9342 281 if (!is_submodule_active(the_repository, ce->name))
3e7eaed0
BW
282 continue;
283
284 ALLOC_GROW(active_modules.entries,
285 active_modules.nr + 1,
286 active_modules.alloc);
287 active_modules.entries[active_modules.nr++] = ce;
288 }
289
290 free(list->entries);
291 *list = active_modules;
292}
293
74703a1e
SB
294static int module_list(int argc, const char **argv, const char *prefix)
295{
296 int i;
297 struct pathspec pathspec;
298 struct module_list list = MODULE_LIST_INIT;
299
300 struct option module_list_options[] = {
301 OPT_STRING(0, "prefix", &prefix,
302 N_("path"),
303 N_("alternative anchor for relative paths")),
304 OPT_END()
305 };
306
307 const char *const git_submodule_helper_usage[] = {
308 N_("git submodule--helper list [--prefix=<path>] [<path>...]"),
309 NULL
310 };
311
312 argc = parse_options(argc, argv, prefix, module_list_options,
313 git_submodule_helper_usage, 0);
314
b0f4b408 315 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
74703a1e 316 return 1;
74703a1e
SB
317
318 for (i = 0; i < list.nr; i++) {
319 const struct cache_entry *ce = list.entries[i];
320
321 if (ce_stage(ce))
322 printf("%06o %s U\t", ce->ce_mode, sha1_to_hex(null_sha1));
323 else
99d1a986 324 printf("%06o %s %d\t", ce->ce_mode,
325 oid_to_hex(&ce->oid), ce_stage(ce));
74703a1e 326
dc4b4a61 327 fprintf(stdout, "%s\n", ce->name);
74703a1e
SB
328 }
329 return 0;
330}
331
3604242f
SB
332static void init_submodule(const char *path, const char *prefix, int quiet)
333{
334 const struct submodule *sub;
335 struct strbuf sb = STRBUF_INIT;
336 char *upd = NULL, *url = NULL, *displaypath;
337
6e7c14e6
SB
338 if (prefix && get_super_prefix())
339 die("BUG: cannot have prefix and superprefix");
340 else if (prefix)
341 displaypath = xstrdup(relative_path(path, prefix, &sb));
342 else if (get_super_prefix()) {
343 strbuf_addf(&sb, "%s%s", get_super_prefix(), path);
3604242f
SB
344 displaypath = strbuf_detach(&sb, NULL);
345 } else
d92028a5
SB
346 displaypath = xstrdup(path);
347
cd73de47 348 sub = submodule_from_path(&null_oid, path);
d92028a5
SB
349
350 if (!sub)
351 die(_("No url found for submodule path '%s' in .gitmodules"),
352 displaypath);
3604242f 353
1f8d7115
BW
354 /*
355 * NEEDSWORK: In a multi-working-tree world, this needs to be
356 * set in the per-worktree config.
357 *
358 * Set active flag for the submodule being initialized
359 */
627d9342 360 if (!is_submodule_active(the_repository, path)) {
1f8d7115
BW
361 strbuf_reset(&sb);
362 strbuf_addf(&sb, "submodule.%s.active", sub->name);
363 git_config_set_gently(sb.buf, "true");
364 }
365
3604242f
SB
366 /*
367 * Copy url setting when it is not set yet.
368 * To look up the url in .git/config, we must not fall back to
369 * .gitmodules, so look it up directly.
370 */
371 strbuf_reset(&sb);
372 strbuf_addf(&sb, "submodule.%s.url", sub->name);
373 if (git_config_get_string(sb.buf, &url)) {
627fde10 374 if (!sub->url)
3604242f
SB
375 die(_("No url found for submodule path '%s' in .gitmodules"),
376 displaypath);
377
627fde10
JK
378 url = xstrdup(sub->url);
379
3604242f
SB
380 /* Possibly a url relative to parent */
381 if (starts_with_dot_dot_slash(url) ||
382 starts_with_dot_slash(url)) {
383 char *remoteurl, *relurl;
384 char *remote = get_default_remote();
385 struct strbuf remotesb = STRBUF_INIT;
386 strbuf_addf(&remotesb, "remote.%s.url", remote);
387 free(remote);
388
d1b3b81a
SB
389 if (git_config_get_string(remotesb.buf, &remoteurl)) {
390 warning(_("could not lookup configuration '%s'. Assuming this repository is its own authoritative upstream."), remotesb.buf);
3604242f 391 remoteurl = xgetcwd();
d1b3b81a 392 }
3604242f
SB
393 relurl = relative_url(remoteurl, url, NULL);
394 strbuf_release(&remotesb);
395 free(remoteurl);
396 free(url);
397 url = relurl;
398 }
399
400 if (git_config_set_gently(sb.buf, url))
401 die(_("Failed to register url for submodule path '%s'"),
402 displaypath);
403 if (!quiet)
c66410ed
SB
404 fprintf(stderr,
405 _("Submodule '%s' (%s) registered for path '%s'\n"),
3604242f
SB
406 sub->name, url, displaypath);
407 }
408
409 /* Copy "update" setting when it is not set yet */
410 strbuf_reset(&sb);
411 strbuf_addf(&sb, "submodule.%s.update", sub->name);
412 if (git_config_get_string(sb.buf, &upd) &&
413 sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
414 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
415 fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
416 sub->name);
417 upd = xstrdup("none");
418 } else
419 upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
420
421 if (git_config_set_gently(sb.buf, upd))
422 die(_("Failed to register update mode for submodule path '%s'"), displaypath);
423 }
424 strbuf_release(&sb);
425 free(displaypath);
426 free(url);
427 free(upd);
428}
429
430static int module_init(int argc, const char **argv, const char *prefix)
431{
432 struct pathspec pathspec;
433 struct module_list list = MODULE_LIST_INIT;
434 int quiet = 0;
435 int i;
436
437 struct option module_init_options[] = {
3604242f
SB
438 OPT__QUIET(&quiet, N_("Suppress output for initializing a submodule")),
439 OPT_END()
440 };
441
442 const char *const git_submodule_helper_usage[] = {
443 N_("git submodule--helper init [<path>]"),
444 NULL
445 };
446
447 argc = parse_options(argc, argv, prefix, module_init_options,
448 git_submodule_helper_usage, 0);
449
450 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
451 return 1;
452
3e7eaed0
BW
453 /*
454 * If there are no path args and submodule.active is set then,
455 * by default, only initialize 'active' modules.
456 */
457 if (!argc && git_config_get_value_multi("submodule.active"))
458 module_list_active(&list);
459
3604242f
SB
460 for (i = 0; i < list.nr; i++)
461 init_submodule(list.entries[i]->name, prefix, quiet);
462
463 return 0;
464}
465
0ea306ef
SB
466static int module_name(int argc, const char **argv, const char *prefix)
467{
468 const struct submodule *sub;
469
470 if (argc != 2)
471 usage(_("git submodule--helper name <path>"));
472
cd73de47 473 sub = submodule_from_path(&null_oid, argv[1]);
0ea306ef
SB
474
475 if (!sub)
476 die(_("no submodule mapping found in .gitmodules for path '%s'"),
477 argv[1]);
478
479 printf("%s\n", sub->name);
480
481 return 0;
482}
14111fc4 483
ee8838d1 484static int clone_submodule(const char *path, const char *gitdir, const char *url,
72c5f883
JK
485 const char *depth, struct string_list *reference,
486 int quiet, int progress)
ee8838d1 487{
542aa25d 488 struct child_process cp = CHILD_PROCESS_INIT;
ee8838d1
SB
489
490 argv_array_push(&cp.args, "clone");
491 argv_array_push(&cp.args, "--no-checkout");
492 if (quiet)
493 argv_array_push(&cp.args, "--quiet");
72c5f883
JK
494 if (progress)
495 argv_array_push(&cp.args, "--progress");
ee8838d1
SB
496 if (depth && *depth)
497 argv_array_pushl(&cp.args, "--depth", depth, NULL);
965dbea0
SB
498 if (reference->nr) {
499 struct string_list_item *item;
500 for_each_string_list_item(item, reference)
501 argv_array_pushl(&cp.args, "--reference",
502 item->string, NULL);
503 }
ee8838d1
SB
504 if (gitdir && *gitdir)
505 argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
506
507 argv_array_push(&cp.args, url);
508 argv_array_push(&cp.args, path);
509
510 cp.git_cmd = 1;
14111fc4 511 prepare_submodule_repo_env(&cp.env_array);
ee8838d1
SB
512 cp.no_stdin = 1;
513
514 return run_command(&cp);
515}
516
31224cbd
SB
517struct submodule_alternate_setup {
518 const char *submodule_name;
519 enum SUBMODULE_ALTERNATE_ERROR_MODE {
520 SUBMODULE_ALTERNATE_ERROR_DIE,
521 SUBMODULE_ALTERNATE_ERROR_INFO,
522 SUBMODULE_ALTERNATE_ERROR_IGNORE
523 } error_mode;
524 struct string_list *reference;
525};
526#define SUBMODULE_ALTERNATE_SETUP_INIT { NULL, \
527 SUBMODULE_ALTERNATE_ERROR_IGNORE, NULL }
528
529static int add_possible_reference_from_superproject(
530 struct alternate_object_database *alt, void *sas_cb)
531{
532 struct submodule_alternate_setup *sas = sas_cb;
533
31224cbd
SB
534 /*
535 * If the alternate object store is another repository, try the
bf03b790 536 * standard layout with .git/(modules/<name>)+/objects
31224cbd 537 */
bf03b790 538 if (ends_with(alt->path, "/objects")) {
31224cbd
SB
539 char *sm_alternate;
540 struct strbuf sb = STRBUF_INIT;
541 struct strbuf err = STRBUF_INIT;
597f9134
JK
542 strbuf_add(&sb, alt->path, strlen(alt->path) - strlen("objects"));
543
31224cbd
SB
544 /*
545 * We need to end the new path with '/' to mark it as a dir,
546 * otherwise a submodule name containing '/' will be broken
547 * as the last part of a missing submodule reference would
548 * be taken as a file name.
549 */
550 strbuf_addf(&sb, "modules/%s/", sas->submodule_name);
551
552 sm_alternate = compute_alternate_path(sb.buf, &err);
553 if (sm_alternate) {
554 string_list_append(sas->reference, xstrdup(sb.buf));
555 free(sm_alternate);
556 } else {
557 switch (sas->error_mode) {
558 case SUBMODULE_ALTERNATE_ERROR_DIE:
559 die(_("submodule '%s' cannot add alternate: %s"),
560 sas->submodule_name, err.buf);
561 case SUBMODULE_ALTERNATE_ERROR_INFO:
562 fprintf(stderr, _("submodule '%s' cannot add alternate: %s"),
563 sas->submodule_name, err.buf);
564 case SUBMODULE_ALTERNATE_ERROR_IGNORE:
565 ; /* nothing */
566 }
567 }
568 strbuf_release(&sb);
569 }
570
31224cbd
SB
571 return 0;
572}
573
574static void prepare_possible_alternates(const char *sm_name,
575 struct string_list *reference)
576{
577 char *sm_alternate = NULL, *error_strategy = NULL;
578 struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
579
580 git_config_get_string("submodule.alternateLocation", &sm_alternate);
581 if (!sm_alternate)
582 return;
583
584 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
585
586 if (!error_strategy)
587 error_strategy = xstrdup("die");
588
589 sas.submodule_name = sm_name;
590 sas.reference = reference;
591 if (!strcmp(error_strategy, "die"))
592 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
593 else if (!strcmp(error_strategy, "info"))
594 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
595 else if (!strcmp(error_strategy, "ignore"))
596 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
597 else
598 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
599
600 if (!strcmp(sm_alternate, "superproject"))
601 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
602 else if (!strcmp(sm_alternate, "no"))
603 ; /* do nothing */
604 else
605 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
606
607 free(sm_alternate);
608 free(error_strategy);
609}
610
ee8838d1
SB
611static int module_clone(int argc, const char **argv, const char *prefix)
612{
965dbea0 613 const char *name = NULL, *url = NULL, *depth = NULL;
ee8838d1 614 int quiet = 0;
72c5f883 615 int progress = 0;
1ea4d9b7 616 char *p, *path = NULL, *sm_gitdir;
ee8838d1 617 struct strbuf sb = STRBUF_INIT;
965dbea0 618 struct string_list reference = STRING_LIST_INIT_NODUP;
bf03b790 619 char *sm_alternate = NULL, *error_strategy = NULL;
ee8838d1
SB
620
621 struct option module_clone_options[] = {
622 OPT_STRING(0, "prefix", &prefix,
623 N_("path"),
624 N_("alternative anchor for relative paths")),
625 OPT_STRING(0, "path", &path,
626 N_("path"),
627 N_("where the new submodule will be cloned to")),
628 OPT_STRING(0, "name", &name,
629 N_("string"),
630 N_("name of the new submodule")),
631 OPT_STRING(0, "url", &url,
632 N_("string"),
633 N_("url where to clone the submodule from")),
965dbea0
SB
634 OPT_STRING_LIST(0, "reference", &reference,
635 N_("repo"),
ee8838d1
SB
636 N_("reference repository")),
637 OPT_STRING(0, "depth", &depth,
638 N_("string"),
639 N_("depth for shallow clones")),
640 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
72c5f883
JK
641 OPT_BOOL(0, "progress", &progress,
642 N_("force cloning progress")),
ee8838d1
SB
643 OPT_END()
644 };
645
646 const char *const git_submodule_helper_usage[] = {
647 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
7dad2633
JK
648 "[--reference <repository>] [--name <name>] [--depth <depth>] "
649 "--url <url> --path <path>"),
ee8838d1
SB
650 NULL
651 };
652
653 argc = parse_options(argc, argv, prefix, module_clone_options,
654 git_submodule_helper_usage, 0);
655
deef3cdc 656 if (argc || !url || !path || !*path)
08e0970a
JK
657 usage_with_options(git_submodule_helper_usage,
658 module_clone_options);
659
ee8838d1 660 strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name);
0aaad415 661 sm_gitdir = absolute_pathdup(sb.buf);
1ea4d9b7 662 strbuf_reset(&sb);
f8eaa0ba
SB
663
664 if (!is_absolute_path(path)) {
665 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path);
666 path = strbuf_detach(&sb, NULL);
667 } else
668 path = xstrdup(path);
ee8838d1
SB
669
670 if (!file_exists(sm_gitdir)) {
671 if (safe_create_leading_directories_const(sm_gitdir) < 0)
672 die(_("could not create directory '%s'"), sm_gitdir);
31224cbd
SB
673
674 prepare_possible_alternates(name, &reference);
675
72c5f883
JK
676 if (clone_submodule(path, sm_gitdir, url, depth, &reference,
677 quiet, progress))
ee8838d1
SB
678 die(_("clone of '%s' into submodule path '%s' failed"),
679 url, path);
680 } else {
681 if (safe_create_leading_directories_const(path) < 0)
682 die(_("could not create directory '%s'"), path);
683 strbuf_addf(&sb, "%s/index", sm_gitdir);
684 unlink_or_warn(sb.buf);
685 strbuf_reset(&sb);
686 }
687
4682085c
VT
688 /* Connect module worktree and git dir */
689 connect_work_tree_and_git_dir(path, sm_gitdir);
ee8838d1 690
ee8838d1
SB
691 p = git_pathdup_submodule(path, "config");
692 if (!p)
693 die(_("could not get submodule directory for '%s'"), path);
bf03b790
VS
694
695 /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
696 git_config_get_string("submodule.alternateLocation", &sm_alternate);
697 if (sm_alternate)
698 git_config_set_in_file(p, "submodule.alternateLocation",
699 sm_alternate);
700 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
701 if (error_strategy)
702 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
703 error_strategy);
704
705 free(sm_alternate);
706 free(error_strategy);
707
ee8838d1 708 strbuf_release(&sb);
ee8838d1 709 free(sm_gitdir);
f8eaa0ba 710 free(path);
ee8838d1
SB
711 free(p);
712 return 0;
713}
74703a1e 714
48308681
SB
715struct submodule_update_clone {
716 /* index into 'list', the list of submodules to look into for cloning */
717 int current;
718 struct module_list list;
719 unsigned warn_if_uninitialized : 1;
720
721 /* update parameter passed via commandline */
722 struct submodule_update_strategy update;
723
724 /* configuration parameters which are passed on to the children */
72c5f883 725 int progress;
48308681 726 int quiet;
abed000a 727 int recommend_shallow;
5f50f33e 728 struct string_list references;
48308681
SB
729 const char *depth;
730 const char *recursive_prefix;
731 const char *prefix;
732
733 /* Machine-readable status lines to be consumed by git-submodule.sh */
734 struct string_list projectlines;
735
736 /* If we want to stop as fast as possible and return an error */
737 unsigned quickstop : 1;
665b35ec
SB
738
739 /* failed clones to be retried again */
740 const struct cache_entry **failed_clones;
741 int failed_clones_nr, failed_clones_alloc;
48308681
SB
742};
743#define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
72c5f883 744 SUBMODULE_UPDATE_STRATEGY_INIT, 0, 0, -1, STRING_LIST_INIT_DUP, \
5f50f33e 745 NULL, NULL, NULL, \
665b35ec 746 STRING_LIST_INIT_DUP, 0, NULL, 0, 0}
48308681 747
08fdbdb1
SB
748
749static void next_submodule_warn_missing(struct submodule_update_clone *suc,
750 struct strbuf *out, const char *displaypath)
751{
752 /*
753 * Only mention uninitialized submodules when their
754 * paths have been specified.
755 */
756 if (suc->warn_if_uninitialized) {
757 strbuf_addf(out,
758 _("Submodule path '%s' not initialized"),
759 displaypath);
760 strbuf_addch(out, '\n');
761 strbuf_addstr(out,
762 _("Maybe you want to use 'update --init'?"));
763 strbuf_addch(out, '\n');
764 }
765}
766
48308681
SB
767/**
768 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
769 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
770 */
771static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
772 struct child_process *child,
773 struct submodule_update_clone *suc,
774 struct strbuf *out)
775{
776 const struct submodule *sub = NULL;
ec6141a0
BW
777 const char *url = NULL;
778 const char *update_string;
779 enum submodule_update_type update_type;
780 char *key;
48308681
SB
781 struct strbuf displaypath_sb = STRBUF_INIT;
782 struct strbuf sb = STRBUF_INIT;
783 const char *displaypath = NULL;
48308681
SB
784 int needs_cloning = 0;
785
786 if (ce_stage(ce)) {
787 if (suc->recursive_prefix)
788 strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
789 else
92d52fab 790 strbuf_addstr(&sb, ce->name);
48308681
SB
791 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
792 strbuf_addch(out, '\n');
793 goto cleanup;
794 }
795
cd73de47 796 sub = submodule_from_path(&null_oid, ce->name);
48308681
SB
797
798 if (suc->recursive_prefix)
799 displaypath = relative_path(suc->recursive_prefix,
800 ce->name, &displaypath_sb);
801 else
802 displaypath = ce->name;
803
08fdbdb1
SB
804 if (!sub) {
805 next_submodule_warn_missing(suc, out, displaypath);
806 goto cleanup;
807 }
808
ec6141a0
BW
809 key = xstrfmt("submodule.%s.update", sub->name);
810 if (!repo_config_get_string_const(the_repository, key, &update_string)) {
811 update_type = parse_submodule_update_type(update_string);
812 } else {
813 update_type = sub->update_strategy.type;
814 }
815 free(key);
816
48308681
SB
817 if (suc->update.type == SM_UPDATE_NONE
818 || (suc->update.type == SM_UPDATE_UNSPECIFIED
ec6141a0 819 && update_type == SM_UPDATE_NONE)) {
48308681
SB
820 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
821 strbuf_addch(out, '\n');
822 goto cleanup;
823 }
824
ee92ab99 825 /* Check if the submodule has been initialized. */
627d9342 826 if (!is_submodule_active(the_repository, ce->name)) {
08fdbdb1 827 next_submodule_warn_missing(suc, out, displaypath);
48308681
SB
828 goto cleanup;
829 }
830
ec6141a0
BW
831 strbuf_reset(&sb);
832 strbuf_addf(&sb, "submodule.%s.url", sub->name);
833 if (repo_config_get_string_const(the_repository, sb.buf, &url))
834 url = sub->url;
835
48308681
SB
836 strbuf_reset(&sb);
837 strbuf_addf(&sb, "%s/.git", ce->name);
838 needs_cloning = !file_exists(sb.buf);
839
840 strbuf_reset(&sb);
841 strbuf_addf(&sb, "%06o %s %d %d\t%s\n", ce->ce_mode,
99d1a986 842 oid_to_hex(&ce->oid), ce_stage(ce),
48308681
SB
843 needs_cloning, ce->name);
844 string_list_append(&suc->projectlines, sb.buf);
845
846 if (!needs_cloning)
847 goto cleanup;
848
849 child->git_cmd = 1;
850 child->no_stdin = 1;
851 child->stdout_to_stderr = 1;
852 child->err = -1;
853 argv_array_push(&child->args, "submodule--helper");
854 argv_array_push(&child->args, "clone");
72c5f883
JK
855 if (suc->progress)
856 argv_array_push(&child->args, "--progress");
48308681
SB
857 if (suc->quiet)
858 argv_array_push(&child->args, "--quiet");
859 if (suc->prefix)
860 argv_array_pushl(&child->args, "--prefix", suc->prefix, NULL);
abed000a
SB
861 if (suc->recommend_shallow && sub->recommend_shallow == 1)
862 argv_array_push(&child->args, "--depth=1");
48308681
SB
863 argv_array_pushl(&child->args, "--path", sub->path, NULL);
864 argv_array_pushl(&child->args, "--name", sub->name, NULL);
ec6141a0 865 argv_array_pushl(&child->args, "--url", url, NULL);
5f50f33e
SB
866 if (suc->references.nr) {
867 struct string_list_item *item;
868 for_each_string_list_item(item, &suc->references)
869 argv_array_pushl(&child->args, "--reference", item->string, NULL);
870 }
48308681
SB
871 if (suc->depth)
872 argv_array_push(&child->args, suc->depth);
873
874cleanup:
48308681
SB
875 strbuf_reset(&displaypath_sb);
876 strbuf_reset(&sb);
877
878 return needs_cloning;
879}
880
881static int update_clone_get_next_task(struct child_process *child,
882 struct strbuf *err,
883 void *suc_cb,
665b35ec 884 void **idx_task_cb)
48308681
SB
885{
886 struct submodule_update_clone *suc = suc_cb;
665b35ec
SB
887 const struct cache_entry *ce;
888 int index;
48308681
SB
889
890 for (; suc->current < suc->list.nr; suc->current++) {
665b35ec 891 ce = suc->list.entries[suc->current];
48308681 892 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
665b35ec
SB
893 int *p = xmalloc(sizeof(*p));
894 *p = suc->current;
895 *idx_task_cb = p;
48308681
SB
896 suc->current++;
897 return 1;
898 }
899 }
665b35ec
SB
900
901 /*
902 * The loop above tried cloning each submodule once, now try the
903 * stragglers again, which we can imagine as an extension of the
904 * entry list.
905 */
906 index = suc->current - suc->list.nr;
907 if (index < suc->failed_clones_nr) {
908 int *p;
909 ce = suc->failed_clones[index];
2201ee09
SB
910 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
911 suc->current ++;
a22ae753
RS
912 strbuf_addstr(err, "BUG: submodule considered for "
913 "cloning, doesn't need cloning "
914 "any more?\n");
2201ee09
SB
915 return 0;
916 }
665b35ec
SB
917 p = xmalloc(sizeof(*p));
918 *p = suc->current;
919 *idx_task_cb = p;
920 suc->current ++;
921 return 1;
922 }
923
48308681
SB
924 return 0;
925}
926
927static int update_clone_start_failure(struct strbuf *err,
928 void *suc_cb,
665b35ec 929 void *idx_task_cb)
48308681
SB
930{
931 struct submodule_update_clone *suc = suc_cb;
932 suc->quickstop = 1;
933 return 1;
934}
935
936static int update_clone_task_finished(int result,
937 struct strbuf *err,
938 void *suc_cb,
665b35ec 939 void *idx_task_cb)
48308681 940{
665b35ec 941 const struct cache_entry *ce;
48308681
SB
942 struct submodule_update_clone *suc = suc_cb;
943
c1e860f1 944 int *idxP = idx_task_cb;
665b35ec
SB
945 int idx = *idxP;
946 free(idxP);
947
48308681
SB
948 if (!result)
949 return 0;
950
665b35ec
SB
951 if (idx < suc->list.nr) {
952 ce = suc->list.entries[idx];
953 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
954 ce->name);
955 strbuf_addch(err, '\n');
956 ALLOC_GROW(suc->failed_clones,
957 suc->failed_clones_nr + 1,
958 suc->failed_clones_alloc);
959 suc->failed_clones[suc->failed_clones_nr++] = ce;
960 return 0;
961 } else {
eb09121b 962 idx -= suc->list.nr;
665b35ec
SB
963 ce = suc->failed_clones[idx];
964 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
965 ce->name);
966 strbuf_addch(err, '\n');
967 suc->quickstop = 1;
968 return 1;
969 }
970
971 return 0;
48308681
SB
972}
973
f20e7c1e
BW
974static int gitmodules_update_clone_config(const char *var, const char *value,
975 void *cb)
976{
977 int *max_jobs = cb;
978 if (!strcmp(var, "submodule.fetchjobs"))
979 *max_jobs = parse_submodule_fetchjobs(var, value);
980 return 0;
981}
982
48308681
SB
983static int update_clone(int argc, const char **argv, const char *prefix)
984{
985 const char *update = NULL;
f20e7c1e 986 int max_jobs = 1;
48308681
SB
987 struct string_list_item *item;
988 struct pathspec pathspec;
989 struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
990
991 struct option module_update_clone_options[] = {
992 OPT_STRING(0, "prefix", &prefix,
993 N_("path"),
994 N_("path into the working tree")),
995 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
996 N_("path"),
997 N_("path into the working tree, across nested "
998 "submodule boundaries")),
999 OPT_STRING(0, "update", &update,
1000 N_("string"),
1001 N_("rebase, merge, checkout or none")),
5f50f33e 1002 OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
48308681
SB
1003 N_("reference repository")),
1004 OPT_STRING(0, "depth", &suc.depth, "<depth>",
1005 N_("Create a shallow clone truncated to the "
1006 "specified number of revisions")),
2335b870
SB
1007 OPT_INTEGER('j', "jobs", &max_jobs,
1008 N_("parallel jobs")),
abed000a
SB
1009 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
1010 N_("whether the initial clone should follow the shallow recommendation")),
48308681 1011 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
72c5f883
JK
1012 OPT_BOOL(0, "progress", &suc.progress,
1013 N_("force cloning progress")),
48308681
SB
1014 OPT_END()
1015 };
1016
1017 const char *const git_submodule_helper_usage[] = {
1018 N_("git submodule--helper update_clone [--prefix=<path>] [<path>...]"),
1019 NULL
1020 };
1021 suc.prefix = prefix;
1022
f20e7c1e
BW
1023 config_from_gitmodules(gitmodules_update_clone_config, &max_jobs);
1024 git_config(gitmodules_update_clone_config, &max_jobs);
1025
48308681
SB
1026 argc = parse_options(argc, argv, prefix, module_update_clone_options,
1027 git_submodule_helper_usage, 0);
1028
1029 if (update)
1030 if (parse_submodule_update_strategy(update, &suc.update) < 0)
1031 die(_("bad value for update parameter"));
1032
1033 if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0)
1034 return 1;
1035
1036 if (pathspec.nr)
1037 suc.warn_if_uninitialized = 1;
1038
2335b870 1039 run_processes_parallel(max_jobs,
48308681
SB
1040 update_clone_get_next_task,
1041 update_clone_start_failure,
1042 update_clone_task_finished,
1043 &suc);
1044
1045 /*
1046 * We saved the output and put it out all at once now.
1047 * That means:
1048 * - the listener does not have to interleave their (checkout)
1049 * work with our fetching. The writes involved in a
1050 * checkout involve more straightforward sequential I/O.
1051 * - the listener can avoid doing any work if fetching failed.
1052 */
1053 if (suc.quickstop)
1054 return 1;
1055
1056 for_each_string_list_item(item, &suc.projectlines)
dc4b4a61 1057 fprintf(stdout, "%s", item->string);
48308681
SB
1058
1059 return 0;
1060}
1061
44431df0
SB
1062static int resolve_relative_path(int argc, const char **argv, const char *prefix)
1063{
1064 struct strbuf sb = STRBUF_INIT;
1065 if (argc != 3)
2de26ae1 1066 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
44431df0
SB
1067
1068 printf("%s", relative_path(argv[1], argv[2], &sb));
1069 strbuf_release(&sb);
1070 return 0;
1071}
1072
92bbe7cc
SB
1073static const char *remote_submodule_branch(const char *path)
1074{
1075 const struct submodule *sub;
177257cc
BW
1076 const char *branch = NULL;
1077 char *key;
92bbe7cc 1078
cd73de47 1079 sub = submodule_from_path(&null_oid, path);
92bbe7cc
SB
1080 if (!sub)
1081 return NULL;
1082
177257cc
BW
1083 key = xstrfmt("submodule.%s.branch", sub->name);
1084 if (repo_config_get_string_const(the_repository, key, &branch))
1085 branch = sub->branch;
1086 free(key);
1087
1088 if (!branch)
92bbe7cc
SB
1089 return "master";
1090
177257cc 1091 if (!strcmp(branch, ".")) {
4d7bc52b
SB
1092 unsigned char sha1[20];
1093 const char *refname = resolve_ref_unsafe("HEAD", 0, sha1, NULL);
1094
1095 if (!refname)
1096 die(_("No such ref: %s"), "HEAD");
1097
1098 /* detached HEAD */
1099 if (!strcmp(refname, "HEAD"))
1100 die(_("Submodule (%s) branch configured to inherit "
1101 "branch from superproject, but the superproject "
1102 "is not on any branch"), sub->name);
1103
1104 if (!skip_prefix(refname, "refs/heads/", &refname))
1105 die(_("Expecting a full ref name, got %s"), refname);
1106 return refname;
1107 }
1108
177257cc 1109 return branch;
92bbe7cc
SB
1110}
1111
1112static int resolve_remote_submodule_branch(int argc, const char **argv,
1113 const char *prefix)
1114{
1115 const char *ret;
1116 struct strbuf sb = STRBUF_INIT;
1117 if (argc != 2)
1118 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
1119
1120 ret = remote_submodule_branch(argv[1]);
1121 if (!ret)
1122 die("submodule %s doesn't exist", argv[1]);
1123
1124 printf("%s", ret);
1125 strbuf_release(&sb);
1126 return 0;
1127}
1128
93481a6b
BW
1129static int push_check(int argc, const char **argv, const char *prefix)
1130{
1131 struct remote *remote;
c7be7201
BW
1132 const char *superproject_head;
1133 char *head;
1134 int detached_head = 0;
1135 struct object_id head_oid;
93481a6b 1136
c7be7201
BW
1137 if (argc < 3)
1138 die("submodule--helper push-check requires at least 2 arguments");
1139
1140 /*
1141 * superproject's resolved head ref.
1142 * if HEAD then the superproject is in a detached head state, otherwise
1143 * it will be the resolved head ref.
1144 */
1145 superproject_head = argv[1];
1146 argv++;
1147 argc--;
1148 /* Get the submodule's head ref and determine if it is detached */
1149 head = resolve_refdup("HEAD", 0, head_oid.hash, NULL);
1150 if (!head)
1151 die(_("Failed to resolve HEAD as a valid ref."));
1152 if (!strcmp(head, "HEAD"))
1153 detached_head = 1;
93481a6b
BW
1154
1155 /*
1156 * The remote must be configured.
1157 * This is to avoid pushing to the exact same URL as the parent.
1158 */
1159 remote = pushremote_get(argv[1]);
1160 if (!remote || remote->origin == REMOTE_UNCONFIGURED)
1161 die("remote '%s' not configured", argv[1]);
1162
1163 /* Check the refspec */
1164 if (argc > 2) {
1165 int i, refspec_nr = argc - 2;
1166 struct ref *local_refs = get_local_heads();
1167 struct refspec *refspec = parse_push_refspec(refspec_nr,
1168 argv + 2);
1169
1170 for (i = 0; i < refspec_nr; i++) {
1171 struct refspec *rs = refspec + i;
1172
1173 if (rs->pattern || rs->matching)
1174 continue;
1175
c7be7201
BW
1176 /* LHS must match a single ref */
1177 switch (count_refspec_match(rs->src, local_refs, NULL)) {
1178 case 1:
1179 break;
1180 case 0:
1181 /*
1182 * If LHS matches 'HEAD' then we need to ensure
1183 * that it matches the same named branch
1184 * checked out in the superproject.
1185 */
1186 if (!strcmp(rs->src, "HEAD")) {
1187 if (!detached_head &&
1188 !strcmp(head, superproject_head))
1189 break;
1190 die("HEAD does not match the named branch in the superproject");
1191 }
1192 default:
93481a6b
BW
1193 die("src refspec '%s' must name a ref",
1194 rs->src);
c7be7201 1195 }
93481a6b
BW
1196 }
1197 free_refspec(refspec_nr, refspec);
1198 }
c7be7201 1199 free(head);
93481a6b
BW
1200
1201 return 0;
1202}
1203
f6f85861
SB
1204static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
1205{
1206 int i;
1207 struct pathspec pathspec;
1208 struct module_list list = MODULE_LIST_INIT;
1209 unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
1210
1211 struct option embed_gitdir_options[] = {
1212 OPT_STRING(0, "prefix", &prefix,
1213 N_("path"),
1214 N_("path into the working tree")),
1215 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
1216 ABSORB_GITDIR_RECURSE_SUBMODULES),
1217 OPT_END()
1218 };
1219
1220 const char *const git_submodule_helper_usage[] = {
1221 N_("git submodule--helper embed-git-dir [<path>...]"),
1222 NULL
1223 };
1224
1225 argc = parse_options(argc, argv, prefix, embed_gitdir_options,
1226 git_submodule_helper_usage, 0);
1227
f6f85861
SB
1228 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1229 return 1;
1230
1231 for (i = 0; i < list.nr; i++)
1232 absorb_git_dir_into_superproject(prefix,
1233 list.entries[i]->name, flags);
1234
1235 return 0;
1236}
1237
5c2bd8b7
BW
1238static int is_active(int argc, const char **argv, const char *prefix)
1239{
1240 if (argc != 2)
9af7ec30 1241 die("submodule--helper is-active takes exactly 1 argument");
5c2bd8b7 1242
627d9342 1243 return !is_submodule_active(the_repository, argv[1]);
5c2bd8b7
BW
1244}
1245
89c86265
SB
1246#define SUPPORT_SUPER_PREFIX (1<<0)
1247
74703a1e
SB
1248struct cmd_struct {
1249 const char *cmd;
1250 int (*fn)(int, const char **, const char *);
89c86265 1251 unsigned option;
74703a1e
SB
1252};
1253
1254static struct cmd_struct commands[] = {
89c86265
SB
1255 {"list", module_list, 0},
1256 {"name", module_name, 0},
1257 {"clone", module_clone, 0},
1258 {"update-clone", update_clone, 0},
1259 {"relative-path", resolve_relative_path, 0},
1260 {"resolve-relative-url", resolve_relative_url, 0},
1261 {"resolve-relative-url-test", resolve_relative_url_test, 0},
6e7c14e6 1262 {"init", module_init, SUPPORT_SUPER_PREFIX},
89c86265 1263 {"remote-branch", resolve_remote_submodule_branch, 0},
93481a6b 1264 {"push-check", push_check, 0},
f6f85861 1265 {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
5c2bd8b7 1266 {"is-active", is_active, 0},
74703a1e
SB
1267};
1268
1269int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
1270{
1271 int i;
f0994fa8
JK
1272 if (argc < 2 || !strcmp(argv[1], "-h"))
1273 usage("git submodule--helper <command>");
74703a1e 1274
89c86265
SB
1275 for (i = 0; i < ARRAY_SIZE(commands); i++) {
1276 if (!strcmp(argv[1], commands[i].cmd)) {
1277 if (get_super_prefix() &&
1278 !(commands[i].option & SUPPORT_SUPER_PREFIX))
1279 die(_("%s doesn't support --super-prefix"),
1280 commands[i].cmd);
74703a1e 1281 return commands[i].fn(argc - 1, argv + 1, prefix);
89c86265
SB
1282 }
1283 }
74703a1e 1284
cdc04b65 1285 die(_("'%s' is not a valid submodule--helper "
74703a1e
SB
1286 "subcommand"), argv[1]);
1287}