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