]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/submodule--helper.c
submodule--helper run-update-procedure: remove --suboid
[thirdparty/git.git] / builtin / submodule--helper.c
CommitLineData
f8adbec9 1#define USE_THE_INDEX_COMPATIBILITY_MACROS
74703a1e 2#include "builtin.h"
627d9342 3#include "repository.h"
74703a1e 4#include "cache.h"
b2141fc1 5#include "config.h"
74703a1e
SB
6#include "parse-options.h"
7#include "quote.h"
8#include "pathspec.h"
9#include "dir.h"
0ea306ef
SB
10#include "submodule.h"
11#include "submodule-config.h"
12#include "string-list.h"
ee8838d1 13#include "run-command.h"
63e95beb
SB
14#include "remote.h"
15#include "refs.h"
ec0cb496 16#include "refspec.h"
63e95beb 17#include "connect.h"
a9f8a375
PC
18#include "revision.h"
19#include "diffcore.h"
20#include "diff.h"
0d4a1321 21#include "object-store.h"
4f3e57ef 22#include "advice.h"
961b130d 23#include "branch.h"
f05da2b4 24#include "list-objects-filter-options.h"
63e95beb 25
9f580a62 26#define OPT_QUIET (1 << 0)
a9f8a375
PC
27#define OPT_CACHED (1 << 1)
28#define OPT_RECURSIVE (1 << 2)
2e612731 29#define OPT_FORCE (1 << 3)
9f580a62
PC
30
31typedef void (*each_submodule_fn)(const struct cache_entry *list_item,
32 void *cb_data);
63e95beb
SB
33
34static char *get_default_remote(void)
35{
36 char *dest = NULL, *ret;
63e95beb 37 struct strbuf sb = STRBUF_INIT;
744c040b 38 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
63e95beb
SB
39
40 if (!refname)
41 die(_("No such ref: %s"), "HEAD");
42
43 /* detached HEAD */
44 if (!strcmp(refname, "HEAD"))
45 return xstrdup("origin");
46
47 if (!skip_prefix(refname, "refs/heads/", &refname))
48 die(_("Expecting a full ref name, got %s"), refname);
49
50 strbuf_addf(&sb, "branch.%s.remote", refname);
51 if (git_config_get_string(sb.buf, &dest))
52 ret = xstrdup("origin");
53 else
54 ret = dest;
55
56 strbuf_release(&sb);
57 return ret;
58}
59
13424764
PC
60static int print_default_remote(int argc, const char **argv, const char *prefix)
61{
e6be8e2f 62 char *remote;
13424764
PC
63
64 if (argc != 1)
65 die(_("submodule--helper print-default-remote takes no arguments"));
66
67 remote = get_default_remote();
68 if (remote)
69 printf("%s\n", remote);
70
e6be8e2f 71 free(remote);
13424764
PC
72 return 0;
73}
74
63e95beb
SB
75static int starts_with_dot_slash(const char *str)
76{
77 return str[0] == '.' && is_dir_sep(str[1]);
78}
79
80static int starts_with_dot_dot_slash(const char *str)
81{
82 return str[0] == '.' && str[1] == '.' && is_dir_sep(str[2]);
83}
84
85/*
86 * Returns 1 if it was the last chop before ':'.
87 */
88static int chop_last_dir(char **remoteurl, int is_relative)
89{
90 char *rfind = find_last_dir_sep(*remoteurl);
91 if (rfind) {
92 *rfind = '\0';
93 return 0;
94 }
95
96 rfind = strrchr(*remoteurl, ':');
97 if (rfind) {
98 *rfind = '\0';
99 return 1;
100 }
101
102 if (is_relative || !strcmp(".", *remoteurl))
103 die(_("cannot strip one component off url '%s'"),
104 *remoteurl);
105
106 free(*remoteurl);
107 *remoteurl = xstrdup(".");
108 return 0;
109}
110
111/*
112 * The `url` argument is the URL that navigates to the submodule origin
113 * repo. When relative, this URL is relative to the superproject origin
114 * URL repo. The `up_path` argument, if specified, is the relative
115 * path that navigates from the submodule working tree to the superproject
116 * working tree. Returns the origin URL of the submodule.
117 *
118 * Return either an absolute URL or filesystem path (if the superproject
119 * origin URL is an absolute URL or filesystem path, respectively) or a
120 * relative file system path (if the superproject origin URL is a relative
121 * file system path).
122 *
123 * When the output is a relative file system path, the path is either
124 * relative to the submodule working tree, if up_path is specified, or to
125 * the superproject working tree otherwise.
126 *
127 * NEEDSWORK: This works incorrectly on the domain and protocol part.
128 * remote_url url outcome expectation
129 * http://a.com/b ../c http://a.com/c as is
08788504
SB
130 * http://a.com/b/ ../c http://a.com/c same as previous line, but
131 * ignore trailing slash in url
63e95beb
SB
132 * http://a.com/b ../../c http://c error out
133 * http://a.com/b ../../../c http:/c error out
134 * http://a.com/b ../../../../c http:c error out
135 * http://a.com/b ../../../../../c .:c error out
136 * NEEDSWORK: Given how chop_last_dir() works, this function is broken
137 * when a local part has a colon in its path component, too.
138 */
139static char *relative_url(const char *remote_url,
140 const char *url,
141 const char *up_path)
142{
143 int is_relative = 0;
144 int colonsep = 0;
145 char *out;
146 char *remoteurl = xstrdup(remote_url);
147 struct strbuf sb = STRBUF_INIT;
148 size_t len = strlen(remoteurl);
149
08788504
SB
150 if (is_dir_sep(remoteurl[len-1]))
151 remoteurl[len-1] = '\0';
63e95beb
SB
152
153 if (!url_is_local_not_ssh(remoteurl) || is_absolute_path(remoteurl))
154 is_relative = 0;
155 else {
156 is_relative = 1;
157 /*
158 * Prepend a './' to ensure all relative
159 * remoteurls start with './' or '../'
160 */
161 if (!starts_with_dot_slash(remoteurl) &&
162 !starts_with_dot_dot_slash(remoteurl)) {
163 strbuf_reset(&sb);
164 strbuf_addf(&sb, "./%s", remoteurl);
165 free(remoteurl);
166 remoteurl = strbuf_detach(&sb, NULL);
167 }
168 }
169 /*
170 * When the url starts with '../', remove that and the
171 * last directory in remoteurl.
172 */
173 while (url) {
174 if (starts_with_dot_dot_slash(url)) {
175 url += 3;
176 colonsep |= chop_last_dir(&remoteurl, is_relative);
177 } else if (starts_with_dot_slash(url))
178 url += 2;
179 else
180 break;
181 }
182 strbuf_reset(&sb);
183 strbuf_addf(&sb, "%s%s%s", remoteurl, colonsep ? ":" : "/", url);
3389e78e
SB
184 if (ends_with(url, "/"))
185 strbuf_setlen(&sb, sb.len - 1);
63e95beb
SB
186 free(remoteurl);
187
188 if (starts_with_dot_slash(sb.buf))
189 out = xstrdup(sb.buf + 2);
190 else
191 out = xstrdup(sb.buf);
63e95beb 192
edfc7449
AH
193 if (!up_path || !is_relative) {
194 strbuf_release(&sb);
63e95beb 195 return out;
edfc7449 196 }
63e95beb 197
edfc7449 198 strbuf_reset(&sb);
63e95beb
SB
199 strbuf_addf(&sb, "%s%s", up_path, out);
200 free(out);
201 return strbuf_detach(&sb, NULL);
202}
203
de0fcbe0 204static char *resolve_relative_url(const char *rel_url, const char *up_path, int quiet)
63e95beb 205{
ab6f23b7 206 char *remoteurl, *resolved_url;
63e95beb 207 char *remote = get_default_remote();
ab6f23b7 208 struct strbuf remotesb = STRBUF_INIT;
63e95beb 209
ab6f23b7
AR
210 strbuf_addf(&remotesb, "remote.%s.url", remote);
211 if (git_config_get_string(remotesb.buf, &remoteurl)) {
212 if (!quiet)
213 warning(_("could not look up configuration '%s'. "
214 "Assuming this repository is its own "
215 "authoritative upstream."),
216 remotesb.buf);
63e95beb 217 remoteurl = xgetcwd();
ab6f23b7
AR
218 }
219 resolved_url = relative_url(remoteurl, rel_url, up_path);
63e95beb 220
ab6f23b7 221 free(remote);
63e95beb 222 free(remoteurl);
ab6f23b7
AR
223 strbuf_release(&remotesb);
224
225 return resolved_url;
63e95beb
SB
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
22f9b7f3
JK
294 strvec_push(&cp.args, "describe");
295 strvec_pushv(&cp.args, *d);
296 strvec_push(&cp.args, object_id);
a9f8a375
PC
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};
9865b6e6 312#define MODULE_LIST_INIT { 0 }
74703a1e
SB
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 349
c5c33504 350 if (ps_matched && report_path_error(ps_matched, pathspec))
74703a1e
SB
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))
14228447 426 printf("%06o %s U\t", ce->ce_mode,
427 oid_to_hex(null_oid()));
74703a1e 428 else
99d1a986 429 printf("%06o %s %d\t", ce->ce_mode,
430 oid_to_hex(&ce->oid), ce_stage(ce));
74703a1e 431
dc4b4a61 432 fprintf(stdout, "%s\n", ce->name);
74703a1e
SB
433 }
434 return 0;
435}
436
9f580a62
PC
437static void for_each_listed_submodule(const struct module_list *list,
438 each_submodule_fn fn, void *cb_data)
439{
440 int i;
441 for (i = 0; i < list->nr; i++)
442 fn(list->entries[i], cb_data);
443}
444
d00a5bdd 445struct foreach_cb {
fc1b9243
PC
446 int argc;
447 const char **argv;
448 const char *prefix;
449 int quiet;
450 int recursive;
451};
d00a5bdd 452#define FOREACH_CB_INIT { 0 }
fc1b9243
PC
453
454static void runcommand_in_submodule_cb(const struct cache_entry *list_item,
455 void *cb_data)
456{
d00a5bdd 457 struct foreach_cb *info = cb_data;
fc1b9243
PC
458 const char *path = list_item->name;
459 const struct object_id *ce_oid = &list_item->oid;
460
461 const struct submodule *sub;
462 struct child_process cp = CHILD_PROCESS_INIT;
463 char *displaypath;
464
465 displaypath = get_submodule_displaypath(path, info->prefix);
466
14228447 467 sub = submodule_from_path(the_repository, null_oid(), path);
fc1b9243
PC
468
469 if (!sub)
470 die(_("No url found for submodule path '%s' in .gitmodules"),
471 displaypath);
472
473 if (!is_submodule_populated_gently(path, NULL))
474 goto cleanup;
475
476 prepare_submodule_repo_env(&cp.env_array);
477
478 /*
479 * For the purpose of executing <command> in the submodule,
480 * separate shell is used for the purpose of running the
481 * child process.
482 */
483 cp.use_shell = 1;
484 cp.dir = path;
485
486 /*
487 * NEEDSWORK: the command currently has access to the variables $name,
488 * $sm_path, $displaypath, $sha1 and $toplevel only when the command
489 * contains a single argument. This is done for maintaining a faithful
490 * translation from shell script.
491 */
492 if (info->argc == 1) {
493 char *toplevel = xgetcwd();
494 struct strbuf sb = STRBUF_INIT;
495
22f9b7f3
JK
496 strvec_pushf(&cp.env_array, "name=%s", sub->name);
497 strvec_pushf(&cp.env_array, "sm_path=%s", path);
498 strvec_pushf(&cp.env_array, "displaypath=%s", displaypath);
499 strvec_pushf(&cp.env_array, "sha1=%s",
f6d8942b 500 oid_to_hex(ce_oid));
22f9b7f3 501 strvec_pushf(&cp.env_array, "toplevel=%s", toplevel);
fc1b9243
PC
502
503 /*
504 * Since the path variable was accessible from the script
505 * before porting, it is also made available after porting.
506 * The environment variable "PATH" has a very special purpose
507 * on windows. And since environment variables are
508 * case-insensitive in windows, it interferes with the
509 * existing PATH variable. Hence, to avoid that, we expose
22f9b7f3 510 * path via the args strvec and not via env_array.
fc1b9243
PC
511 */
512 sq_quote_buf(&sb, path);
22f9b7f3 513 strvec_pushf(&cp.args, "path=%s; %s",
f6d8942b 514 sb.buf, info->argv[0]);
fc1b9243
PC
515 strbuf_release(&sb);
516 free(toplevel);
517 } else {
22f9b7f3 518 strvec_pushv(&cp.args, info->argv);
fc1b9243
PC
519 }
520
521 if (!info->quiet)
522 printf(_("Entering '%s'\n"), displaypath);
523
524 if (info->argv[0] && run_command(&cp))
525 die(_("run_command returned non-zero status for %s\n."),
526 displaypath);
527
528 if (info->recursive) {
529 struct child_process cpr = CHILD_PROCESS_INIT;
530
531 cpr.git_cmd = 1;
532 cpr.dir = path;
533 prepare_submodule_repo_env(&cpr.env_array);
534
22f9b7f3
JK
535 strvec_pushl(&cpr.args, "--super-prefix", NULL);
536 strvec_pushf(&cpr.args, "%s/", displaypath);
537 strvec_pushl(&cpr.args, "submodule--helper", "foreach", "--recursive",
f6d8942b 538 NULL);
fc1b9243
PC
539
540 if (info->quiet)
22f9b7f3 541 strvec_push(&cpr.args, "--quiet");
fc1b9243 542
22f9b7f3
JK
543 strvec_push(&cpr.args, "--");
544 strvec_pushv(&cpr.args, info->argv);
fc1b9243
PC
545
546 if (run_command(&cpr))
27c929ed 547 die(_("run_command returned non-zero status while "
fc1b9243
PC
548 "recursing in the nested submodules of %s\n."),
549 displaypath);
550 }
551
552cleanup:
553 free(displaypath);
554}
555
556static int module_foreach(int argc, const char **argv, const char *prefix)
557{
d00a5bdd 558 struct foreach_cb info = FOREACH_CB_INIT;
fc1b9243
PC
559 struct pathspec pathspec;
560 struct module_list list = MODULE_LIST_INIT;
561
562 struct option module_foreach_options[] = {
e73fe3dd 563 OPT__QUIET(&info.quiet, N_("suppress output of entering each submodule command")),
fc1b9243 564 OPT_BOOL(0, "recursive", &info.recursive,
e73fe3dd 565 N_("recurse into nested submodules")),
fc1b9243
PC
566 OPT_END()
567 };
568
569 const char *const git_submodule_helper_usage[] = {
a282f5a9 570 N_("git submodule--helper foreach [--quiet] [--recursive] [--] <command>"),
fc1b9243
PC
571 NULL
572 };
573
574 argc = parse_options(argc, argv, prefix, module_foreach_options,
a282f5a9 575 git_submodule_helper_usage, 0);
fc1b9243
PC
576
577 if (module_list_compute(0, NULL, prefix, &pathspec, &list) < 0)
578 return 1;
579
580 info.argc = argc;
581 info.argv = argv;
582 info.prefix = prefix;
583
584 for_each_listed_submodule(&list, runcommand_in_submodule_cb, &info);
585
586 return 0;
587}
588
9f580a62
PC
589struct init_cb {
590 const char *prefix;
591 unsigned int flags;
592};
9865b6e6 593#define INIT_CB_INIT { 0 }
9f580a62
PC
594
595static void init_submodule(const char *path, const char *prefix,
596 unsigned int flags)
3604242f
SB
597{
598 const struct submodule *sub;
599 struct strbuf sb = STRBUF_INIT;
600 char *upd = NULL, *url = NULL, *displaypath;
601
74a10642 602 displaypath = get_submodule_displaypath(path, prefix);
d92028a5 603
14228447 604 sub = submodule_from_path(the_repository, null_oid(), path);
d92028a5
SB
605
606 if (!sub)
607 die(_("No url found for submodule path '%s' in .gitmodules"),
608 displaypath);
3604242f 609
1f8d7115
BW
610 /*
611 * NEEDSWORK: In a multi-working-tree world, this needs to be
612 * set in the per-worktree config.
613 *
614 * Set active flag for the submodule being initialized
615 */
627d9342 616 if (!is_submodule_active(the_repository, path)) {
1f8d7115
BW
617 strbuf_addf(&sb, "submodule.%s.active", sub->name);
618 git_config_set_gently(sb.buf, "true");
74a10642 619 strbuf_reset(&sb);
1f8d7115
BW
620 }
621
3604242f
SB
622 /*
623 * Copy url setting when it is not set yet.
624 * To look up the url in .git/config, we must not fall back to
625 * .gitmodules, so look it up directly.
626 */
3604242f
SB
627 strbuf_addf(&sb, "submodule.%s.url", sub->name);
628 if (git_config_get_string(sb.buf, &url)) {
627fde10 629 if (!sub->url)
3604242f
SB
630 die(_("No url found for submodule path '%s' in .gitmodules"),
631 displaypath);
632
627fde10
JK
633 url = xstrdup(sub->url);
634
3604242f
SB
635 /* Possibly a url relative to parent */
636 if (starts_with_dot_dot_slash(url) ||
637 starts_with_dot_slash(url)) {
e0a862fd 638 char *oldurl = url;
de0fcbe0 639 url = resolve_relative_url(oldurl, NULL, 0);
e0a862fd 640 free(oldurl);
3604242f
SB
641 }
642
643 if (git_config_set_gently(sb.buf, url))
644 die(_("Failed to register url for submodule path '%s'"),
645 displaypath);
9f580a62 646 if (!(flags & OPT_QUIET))
c66410ed
SB
647 fprintf(stderr,
648 _("Submodule '%s' (%s) registered for path '%s'\n"),
3604242f
SB
649 sub->name, url, displaypath);
650 }
74a10642 651 strbuf_reset(&sb);
3604242f
SB
652
653 /* Copy "update" setting when it is not set yet */
3604242f
SB
654 strbuf_addf(&sb, "submodule.%s.update", sub->name);
655 if (git_config_get_string(sb.buf, &upd) &&
656 sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
657 if (sub->update_strategy.type == SM_UPDATE_COMMAND) {
658 fprintf(stderr, _("warning: command update mode suggested for submodule '%s'\n"),
659 sub->name);
660 upd = xstrdup("none");
661 } else
662 upd = xstrdup(submodule_strategy_to_string(&sub->update_strategy));
663
664 if (git_config_set_gently(sb.buf, upd))
665 die(_("Failed to register update mode for submodule path '%s'"), displaypath);
666 }
667 strbuf_release(&sb);
668 free(displaypath);
669 free(url);
670 free(upd);
671}
672
9f580a62
PC
673static void init_submodule_cb(const struct cache_entry *list_item, void *cb_data)
674{
675 struct init_cb *info = cb_data;
676 init_submodule(list_item->name, info->prefix, info->flags);
677}
678
3604242f
SB
679static int module_init(int argc, const char **argv, const char *prefix)
680{
9f580a62 681 struct init_cb info = INIT_CB_INIT;
3604242f
SB
682 struct pathspec pathspec;
683 struct module_list list = MODULE_LIST_INIT;
684 int quiet = 0;
3604242f
SB
685
686 struct option module_init_options[] = {
e73fe3dd 687 OPT__QUIET(&quiet, N_("suppress output for initializing a submodule")),
3604242f
SB
688 OPT_END()
689 };
690
691 const char *const git_submodule_helper_usage[] = {
a282f5a9 692 N_("git submodule--helper init [<options>] [<path>]"),
3604242f
SB
693 NULL
694 };
695
696 argc = parse_options(argc, argv, prefix, module_init_options,
697 git_submodule_helper_usage, 0);
698
699 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
700 return 1;
701
3e7eaed0
BW
702 /*
703 * If there are no path args and submodule.active is set then,
704 * by default, only initialize 'active' modules.
705 */
706 if (!argc && git_config_get_value_multi("submodule.active"))
707 module_list_active(&list);
708
9f580a62
PC
709 info.prefix = prefix;
710 if (quiet)
711 info.flags |= OPT_QUIET;
712
713 for_each_listed_submodule(&list, init_submodule_cb, &info);
3604242f
SB
714
715 return 0;
716}
717
a9f8a375
PC
718struct status_cb {
719 const char *prefix;
720 unsigned int flags;
721};
9865b6e6 722#define STATUS_CB_INIT { 0 }
a9f8a375
PC
723
724static void print_status(unsigned int flags, char state, const char *path,
725 const struct object_id *oid, const char *displaypath)
726{
727 if (flags & OPT_QUIET)
728 return;
729
730 printf("%c%s %s", state, oid_to_hex(oid), displaypath);
731
0b5e2ea7
NTND
732 if (state == ' ' || state == '+') {
733 const char *name = compute_rev_name(path, oid_to_hex(oid));
734
735 if (name)
736 printf(" (%s)", name);
737 }
a9f8a375
PC
738
739 printf("\n");
740}
741
742static int handle_submodule_head_ref(const char *refname,
743 const struct object_id *oid, int flags,
744 void *cb_data)
745{
746 struct object_id *output = cb_data;
747 if (oid)
748 oidcpy(output, oid);
749
750 return 0;
751}
752
753static void status_submodule(const char *path, const struct object_id *ce_oid,
754 unsigned int ce_flags, const char *prefix,
755 unsigned int flags)
756{
757 char *displaypath;
22f9b7f3 758 struct strvec diff_files_args = STRVEC_INIT;
a9f8a375
PC
759 struct rev_info rev;
760 int diff_files_result;
3b2885ec
PK
761 struct strbuf buf = STRBUF_INIT;
762 const char *git_dir;
a9f8a375 763
14228447 764 if (!submodule_from_path(the_repository, null_oid(), path))
a9f8a375
PC
765 die(_("no submodule mapping found in .gitmodules for path '%s'"),
766 path);
767
768 displaypath = get_submodule_displaypath(path, prefix);
769
770 if ((CE_STAGEMASK & ce_flags) >> CE_STAGESHIFT) {
14228447 771 print_status(flags, 'U', path, null_oid(), displaypath);
a9f8a375
PC
772 goto cleanup;
773 }
774
3b2885ec
PK
775 strbuf_addf(&buf, "%s/.git", path);
776 git_dir = read_gitfile(buf.buf);
777 if (!git_dir)
778 git_dir = buf.buf;
779
780 if (!is_submodule_active(the_repository, path) ||
781 !is_git_directory(git_dir)) {
a9f8a375 782 print_status(flags, '-', path, ce_oid, displaypath);
3b2885ec 783 strbuf_release(&buf);
a9f8a375
PC
784 goto cleanup;
785 }
3b2885ec 786 strbuf_release(&buf);
a9f8a375 787
22f9b7f3 788 strvec_pushl(&diff_files_args, "diff-files",
f6d8942b
JK
789 "--ignore-submodules=dirty", "--quiet", "--",
790 path, NULL);
a9f8a375
PC
791
792 git_config(git_diff_basic_config, NULL);
1f3aea22
MG
793
794 repo_init_revisions(the_repository, &rev, NULL);
a9f8a375 795 rev.abbrev = 0;
d70a9eb6
JK
796 diff_files_args.nr = setup_revisions(diff_files_args.nr,
797 diff_files_args.v,
798 &rev, NULL);
a9f8a375
PC
799 diff_files_result = run_diff_files(&rev, 0);
800
801 if (!diff_result_code(&rev.diffopt, diff_files_result)) {
802 print_status(flags, ' ', path, ce_oid,
803 displaypath);
804 } else if (!(flags & OPT_CACHED)) {
805 struct object_id oid;
74b6bda3 806 struct ref_store *refs = get_submodule_ref_store(path);
a9f8a375 807
74b6bda3
RS
808 if (!refs) {
809 print_status(flags, '-', path, ce_oid, displaypath);
810 goto cleanup;
811 }
812 if (refs_head_ref(refs, handle_submodule_head_ref, &oid))
ed5bdd5b 813 die(_("could not resolve HEAD ref inside the "
a9f8a375
PC
814 "submodule '%s'"), path);
815
816 print_status(flags, '+', path, &oid, displaypath);
817 } else {
818 print_status(flags, '+', path, ce_oid, displaypath);
819 }
820
821 if (flags & OPT_RECURSIVE) {
822 struct child_process cpr = CHILD_PROCESS_INIT;
823
824 cpr.git_cmd = 1;
825 cpr.dir = path;
826 prepare_submodule_repo_env(&cpr.env_array);
827
22f9b7f3
JK
828 strvec_push(&cpr.args, "--super-prefix");
829 strvec_pushf(&cpr.args, "%s/", displaypath);
830 strvec_pushl(&cpr.args, "submodule--helper", "status",
f6d8942b 831 "--recursive", NULL);
a9f8a375
PC
832
833 if (flags & OPT_CACHED)
22f9b7f3 834 strvec_push(&cpr.args, "--cached");
a9f8a375
PC
835
836 if (flags & OPT_QUIET)
22f9b7f3 837 strvec_push(&cpr.args, "--quiet");
a9f8a375
PC
838
839 if (run_command(&cpr))
840 die(_("failed to recurse into submodule '%s'"), path);
841 }
842
843cleanup:
22f9b7f3 844 strvec_clear(&diff_files_args);
a9f8a375
PC
845 free(displaypath);
846}
847
848static void status_submodule_cb(const struct cache_entry *list_item,
849 void *cb_data)
850{
851 struct status_cb *info = cb_data;
852 status_submodule(list_item->name, &list_item->oid, list_item->ce_flags,
853 info->prefix, info->flags);
854}
855
856static int module_status(int argc, const char **argv, const char *prefix)
857{
858 struct status_cb info = STATUS_CB_INIT;
859 struct pathspec pathspec;
860 struct module_list list = MODULE_LIST_INIT;
861 int quiet = 0;
862
863 struct option module_status_options[] = {
e73fe3dd
ZH
864 OPT__QUIET(&quiet, N_("suppress submodule status output")),
865 OPT_BIT(0, "cached", &info.flags, N_("use commit stored in the index instead of the one stored in the submodule HEAD"), OPT_CACHED),
a9f8a375
PC
866 OPT_BIT(0, "recursive", &info.flags, N_("recurse into nested submodules"), OPT_RECURSIVE),
867 OPT_END()
868 };
869
870 const char *const git_submodule_helper_usage[] = {
871 N_("git submodule status [--quiet] [--cached] [--recursive] [<path>...]"),
872 NULL
873 };
874
875 argc = parse_options(argc, argv, prefix, module_status_options,
876 git_submodule_helper_usage, 0);
877
878 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
879 return 1;
880
881 info.prefix = prefix;
882 if (quiet)
883 info.flags |= OPT_QUIET;
884
885 for_each_listed_submodule(&list, status_submodule_cb, &info);
3604242f
SB
886
887 return 0;
888}
889
0ea306ef
SB
890static int module_name(int argc, const char **argv, const char *prefix)
891{
892 const struct submodule *sub;
893
894 if (argc != 2)
895 usage(_("git submodule--helper name <path>"));
896
14228447 897 sub = submodule_from_path(the_repository, null_oid(), argv[1]);
0ea306ef
SB
898
899 if (!sub)
900 die(_("no submodule mapping found in .gitmodules for path '%s'"),
901 argv[1]);
902
903 printf("%s\n", sub->name);
904
905 return 0;
906}
14111fc4 907
e83e3333
PC
908struct module_cb {
909 unsigned int mod_src;
910 unsigned int mod_dst;
911 struct object_id oid_src;
912 struct object_id oid_dst;
913 char status;
914 const char *sm_path;
915};
9865b6e6 916#define MODULE_CB_INIT { 0 }
e83e3333
PC
917
918struct module_cb_list {
919 struct module_cb **entries;
920 int alloc, nr;
921};
9865b6e6 922#define MODULE_CB_LIST_INIT { 0 }
e83e3333
PC
923
924struct summary_cb {
925 int argc;
926 const char **argv;
927 const char *prefix;
928 unsigned int cached: 1;
929 unsigned int for_status: 1;
930 unsigned int files: 1;
931 int summary_limit;
932};
9865b6e6 933#define SUMMARY_CB_INIT { 0 }
e83e3333
PC
934
935enum diff_cmd {
936 DIFF_INDEX,
937 DIFF_FILES
938};
939
f0c6b646 940static char *verify_submodule_committish(const char *sm_path,
e83e3333
PC
941 const char *committish)
942{
943 struct child_process cp_rev_parse = CHILD_PROCESS_INIT;
944 struct strbuf result = STRBUF_INIT;
945
946 cp_rev_parse.git_cmd = 1;
947 cp_rev_parse.dir = sm_path;
948 prepare_submodule_repo_env(&cp_rev_parse.env_array);
949 strvec_pushl(&cp_rev_parse.args, "rev-parse", "-q", "--short", NULL);
950 strvec_pushf(&cp_rev_parse.args, "%s^0", committish);
951 strvec_push(&cp_rev_parse.args, "--");
952
953 if (capture_command(&cp_rev_parse, &result, 0))
954 return NULL;
955
956 strbuf_trim_trailing_newline(&result);
957 return strbuf_detach(&result, NULL);
958}
959
f0c6b646 960static void print_submodule_summary(struct summary_cb *info, char *errmsg,
e83e3333
PC
961 int total_commits, const char *displaypath,
962 const char *src_abbrev, const char *dst_abbrev,
e83e3333
PC
963 struct module_cb *p)
964{
965 if (p->status == 'T') {
966 if (S_ISGITLINK(p->mod_dst))
967 printf(_("* %s %s(blob)->%s(submodule)"),
968 displaypath, src_abbrev, dst_abbrev);
969 else
970 printf(_("* %s %s(submodule)->%s(blob)"),
971 displaypath, src_abbrev, dst_abbrev);
972 } else {
973 printf("* %s %s...%s",
974 displaypath, src_abbrev, dst_abbrev);
975 }
976
977 if (total_commits < 0)
978 printf(":\n");
979 else
980 printf(" (%d):\n", total_commits);
981
982 if (errmsg) {
983 printf(_("%s"), errmsg);
984 } else if (total_commits > 0) {
985 struct child_process cp_log = CHILD_PROCESS_INIT;
986
987 cp_log.git_cmd = 1;
988 cp_log.dir = p->sm_path;
989 prepare_submodule_repo_env(&cp_log.env_array);
990 strvec_pushl(&cp_log.args, "log", NULL);
991
992 if (S_ISGITLINK(p->mod_src) && S_ISGITLINK(p->mod_dst)) {
993 if (info->summary_limit > 0)
994 strvec_pushf(&cp_log.args, "-%d",
995 info->summary_limit);
996
997 strvec_pushl(&cp_log.args, "--pretty= %m %s",
998 "--first-parent", NULL);
999 strvec_pushf(&cp_log.args, "%s...%s",
1000 src_abbrev, dst_abbrev);
1001 } else if (S_ISGITLINK(p->mod_dst)) {
1002 strvec_pushl(&cp_log.args, "--pretty= > %s",
1003 "-1", dst_abbrev, NULL);
1004 } else {
1005 strvec_pushl(&cp_log.args, "--pretty= < %s",
1006 "-1", src_abbrev, NULL);
1007 }
1008 run_command(&cp_log);
1009 }
1010 printf("\n");
1011}
1012
1013static void generate_submodule_summary(struct summary_cb *info,
1014 struct module_cb *p)
1015{
d79b1455 1016 char *displaypath, *src_abbrev = NULL, *dst_abbrev;
e83e3333
PC
1017 int missing_src = 0, missing_dst = 0;
1018 char *errmsg = NULL;
1019 int total_commits = -1;
1020
14228447 1021 if (!info->cached && oideq(&p->oid_dst, null_oid())) {
e83e3333
PC
1022 if (S_ISGITLINK(p->mod_dst)) {
1023 struct ref_store *refs = get_submodule_ref_store(p->sm_path);
1024 if (refs)
1025 refs_head_ref(refs, handle_submodule_head_ref, &p->oid_dst);
1026 } else if (S_ISLNK(p->mod_dst) || S_ISREG(p->mod_dst)) {
1027 struct stat st;
1028 int fd = open(p->sm_path, O_RDONLY);
1029
1030 if (fd < 0 || fstat(fd, &st) < 0 ||
1031 index_fd(&the_index, &p->oid_dst, fd, &st, OBJ_BLOB,
1032 p->sm_path, 0))
1033 error(_("couldn't hash object from '%s'"), p->sm_path);
1034 } else {
1035 /* for a submodule removal (mode:0000000), don't warn */
1036 if (p->mod_dst)
f0c6b646 1037 warning(_("unexpected mode %o\n"), p->mod_dst);
e83e3333
PC
1038 }
1039 }
1040
1041 if (S_ISGITLINK(p->mod_src)) {
d79b1455
SS
1042 if (p->status != 'D')
1043 src_abbrev = verify_submodule_committish(p->sm_path,
1044 oid_to_hex(&p->oid_src));
e83e3333
PC
1045 if (!src_abbrev) {
1046 missing_src = 1;
1047 /*
1048 * As `rev-parse` failed, we fallback to getting
1049 * the abbreviated hash using oid_src. We do
1050 * this as we might still need the abbreviated
1051 * hash in cases like a submodule type change, etc.
1052 */
1053 src_abbrev = xstrndup(oid_to_hex(&p->oid_src), 7);
1054 }
1055 } else {
1056 /*
1057 * The source does not point to a submodule.
1058 * So, we fallback to getting the abbreviation using
1059 * oid_src as we might still need the abbreviated
1060 * hash in cases like submodule add, etc.
1061 */
1062 src_abbrev = xstrndup(oid_to_hex(&p->oid_src), 7);
1063 }
1064
1065 if (S_ISGITLINK(p->mod_dst)) {
1066 dst_abbrev = verify_submodule_committish(p->sm_path,
1067 oid_to_hex(&p->oid_dst));
1068 if (!dst_abbrev) {
1069 missing_dst = 1;
1070 /*
1071 * As `rev-parse` failed, we fallback to getting
1072 * the abbreviated hash using oid_dst. We do
1073 * this as we might still need the abbreviated
1074 * hash in cases like a submodule type change, etc.
1075 */
1076 dst_abbrev = xstrndup(oid_to_hex(&p->oid_dst), 7);
1077 }
1078 } else {
1079 /*
1080 * The destination does not point to a submodule.
1081 * So, we fallback to getting the abbreviation using
1082 * oid_dst as we might still need the abbreviated
1083 * hash in cases like a submodule removal, etc.
1084 */
1085 dst_abbrev = xstrndup(oid_to_hex(&p->oid_dst), 7);
1086 }
1087
1088 displaypath = get_submodule_displaypath(p->sm_path, info->prefix);
1089
1090 if (!missing_src && !missing_dst) {
1091 struct child_process cp_rev_list = CHILD_PROCESS_INIT;
1092 struct strbuf sb_rev_list = STRBUF_INIT;
1093
1094 strvec_pushl(&cp_rev_list.args, "rev-list",
1095 "--first-parent", "--count", NULL);
1096 if (S_ISGITLINK(p->mod_src) && S_ISGITLINK(p->mod_dst))
1097 strvec_pushf(&cp_rev_list.args, "%s...%s",
1098 src_abbrev, dst_abbrev);
1099 else
1100 strvec_push(&cp_rev_list.args, S_ISGITLINK(p->mod_src) ?
1101 src_abbrev : dst_abbrev);
1102 strvec_push(&cp_rev_list.args, "--");
1103
1104 cp_rev_list.git_cmd = 1;
1105 cp_rev_list.dir = p->sm_path;
1106 prepare_submodule_repo_env(&cp_rev_list.env_array);
1107
1108 if (!capture_command(&cp_rev_list, &sb_rev_list, 0))
1109 total_commits = atoi(sb_rev_list.buf);
1110
1111 strbuf_release(&sb_rev_list);
1112 } else {
1113 /*
1114 * Don't give error msg for modification whose dst is not
1115 * submodule, i.e., deleted or changed to blob
1116 */
1117 if (S_ISGITLINK(p->mod_dst)) {
1118 struct strbuf errmsg_str = STRBUF_INIT;
1119 if (missing_src && missing_dst) {
1120 strbuf_addf(&errmsg_str, " Warn: %s doesn't contain commits %s and %s\n",
1121 displaypath, oid_to_hex(&p->oid_src),
1122 oid_to_hex(&p->oid_dst));
1123 } else {
1124 strbuf_addf(&errmsg_str, " Warn: %s doesn't contain commit %s\n",
1125 displaypath, missing_src ?
1126 oid_to_hex(&p->oid_src) :
1127 oid_to_hex(&p->oid_dst));
1128 }
1129 errmsg = strbuf_detach(&errmsg_str, NULL);
1130 }
1131 }
1132
1133 print_submodule_summary(info, errmsg, total_commits,
1134 displaypath, src_abbrev,
e0f7ae56 1135 dst_abbrev, p);
e83e3333
PC
1136
1137 free(displaypath);
1138 free(src_abbrev);
1139 free(dst_abbrev);
1140}
1141
1142static void prepare_submodule_summary(struct summary_cb *info,
1143 struct module_cb_list *list)
1144{
1145 int i;
1146 for (i = 0; i < list->nr; i++) {
1147 const struct submodule *sub;
1148 struct module_cb *p = list->entries[i];
1149 struct strbuf sm_gitdir = STRBUF_INIT;
1150
1151 if (p->status == 'D' || p->status == 'T') {
1152 generate_submodule_summary(info, p);
1153 continue;
1154 }
1155
1156 if (info->for_status && p->status != 'A' &&
1157 (sub = submodule_from_path(the_repository,
14228447 1158 null_oid(), p->sm_path))) {
e83e3333
PC
1159 char *config_key = NULL;
1160 const char *value;
1161 int ignore_all = 0;
1162
1163 config_key = xstrfmt("submodule.%s.ignore",
1164 sub->name);
bbdba3d8 1165 if (!git_config_get_string_tmp(config_key, &value))
e83e3333
PC
1166 ignore_all = !strcmp(value, "all");
1167 else if (sub->ignore)
1168 ignore_all = !strcmp(sub->ignore, "all");
1169
1170 free(config_key);
1171 if (ignore_all)
1172 continue;
1173 }
1174
1175 /* Also show added or modified modules which are checked out */
1176 strbuf_addstr(&sm_gitdir, p->sm_path);
1177 if (is_nonbare_repository_dir(&sm_gitdir))
1178 generate_submodule_summary(info, p);
1179 strbuf_release(&sm_gitdir);
1180 }
1181}
1182
1183static void submodule_summary_callback(struct diff_queue_struct *q,
1184 struct diff_options *options,
1185 void *data)
1186{
1187 int i;
1188 struct module_cb_list *list = data;
1189 for (i = 0; i < q->nr; i++) {
1190 struct diff_filepair *p = q->queue[i];
1191 struct module_cb *temp;
1192
1193 if (!S_ISGITLINK(p->one->mode) && !S_ISGITLINK(p->two->mode))
1194 continue;
1195 temp = (struct module_cb*)malloc(sizeof(struct module_cb));
1196 temp->mod_src = p->one->mode;
1197 temp->mod_dst = p->two->mode;
1198 temp->oid_src = p->one->oid;
1199 temp->oid_dst = p->two->oid;
1200 temp->status = p->status;
1201 temp->sm_path = xstrdup(p->one->path);
1202
1203 ALLOC_GROW(list->entries, list->nr + 1, list->alloc);
1204 list->entries[list->nr++] = temp;
1205 }
1206}
1207
1208static const char *get_diff_cmd(enum diff_cmd diff_cmd)
1209{
1210 switch (diff_cmd) {
1211 case DIFF_INDEX: return "diff-index";
1212 case DIFF_FILES: return "diff-files";
1213 default: BUG("bad diff_cmd value %d", diff_cmd);
1214 }
1215}
1216
1217static int compute_summary_module_list(struct object_id *head_oid,
1218 struct summary_cb *info,
1219 enum diff_cmd diff_cmd)
1220{
1221 struct strvec diff_args = STRVEC_INIT;
1222 struct rev_info rev;
1223 struct module_cb_list list = MODULE_CB_LIST_INIT;
1224
1225 strvec_push(&diff_args, get_diff_cmd(diff_cmd));
1226 if (info->cached)
1227 strvec_push(&diff_args, "--cached");
1228 strvec_pushl(&diff_args, "--ignore-submodules=dirty", "--raw", NULL);
1229 if (head_oid)
1230 strvec_push(&diff_args, oid_to_hex(head_oid));
1231 strvec_push(&diff_args, "--");
1232 if (info->argc)
1233 strvec_pushv(&diff_args, info->argv);
1234
1235 git_config(git_diff_basic_config, NULL);
1236 init_revisions(&rev, info->prefix);
1237 rev.abbrev = 0;
5c327502 1238 precompose_argv_prefix(diff_args.nr, diff_args.v, NULL);
e83e3333
PC
1239 setup_revisions(diff_args.nr, diff_args.v, &rev, NULL);
1240 rev.diffopt.output_format = DIFF_FORMAT_NO_OUTPUT | DIFF_FORMAT_CALLBACK;
1241 rev.diffopt.format_callback = submodule_summary_callback;
1242 rev.diffopt.format_callback_data = &list;
1243
1244 if (!info->cached) {
1245 if (diff_cmd == DIFF_INDEX)
1246 setup_work_tree();
1247 if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
1248 perror("read_cache_preload");
1249 return -1;
1250 }
1251 } else if (read_cache() < 0) {
1252 perror("read_cache");
1253 return -1;
1254 }
1255
1256 if (diff_cmd == DIFF_INDEX)
1257 run_diff_index(&rev, info->cached);
1258 else
1259 run_diff_files(&rev, 0);
1260 prepare_submodule_summary(info, &list);
1261 strvec_clear(&diff_args);
1262 return 0;
1263}
1264
1265static int module_summary(int argc, const char **argv, const char *prefix)
1266{
1267 struct summary_cb info = SUMMARY_CB_INIT;
1268 int cached = 0;
1269 int for_status = 0;
1270 int files = 0;
1271 int summary_limit = -1;
1272 enum diff_cmd diff_cmd = DIFF_INDEX;
1273 struct object_id head_oid;
1274 int ret;
1275
1276 struct option module_summary_options[] = {
1277 OPT_BOOL(0, "cached", &cached,
1278 N_("use the commit stored in the index instead of the submodule HEAD")),
1279 OPT_BOOL(0, "files", &files,
f5f5a61d 1280 N_("compare the commit in the index with that in the submodule HEAD")),
e83e3333
PC
1281 OPT_BOOL(0, "for-status", &for_status,
1282 N_("skip submodules with 'ignore_config' value set to 'all'")),
1283 OPT_INTEGER('n', "summary-limit", &summary_limit,
1284 N_("limit the summary size")),
1285 OPT_END()
1286 };
1287
1288 const char *const git_submodule_helper_usage[] = {
9f443f55 1289 N_("git submodule--helper summary [<options>] [<commit>] [--] [<path>]"),
e83e3333
PC
1290 NULL
1291 };
1292
1293 argc = parse_options(argc, argv, prefix, module_summary_options,
1294 git_submodule_helper_usage, 0);
1295
1296 if (!summary_limit)
1297 return 0;
1298
1299 if (!get_oid(argc ? argv[0] : "HEAD", &head_oid)) {
1300 if (argc) {
1301 argv++;
1302 argc--;
1303 }
1304 } else if (!argc || !strcmp(argv[0], "HEAD")) {
1305 /* before the first commit: compare with an empty tree */
1306 oidcpy(&head_oid, the_hash_algo->empty_tree);
1307 if (argc) {
1308 argv++;
1309 argc--;
1310 }
1311 } else {
1312 if (get_oid("HEAD", &head_oid))
1313 die(_("could not fetch a revision for HEAD"));
1314 }
1315
1316 if (files) {
1317 if (cached)
43ea635c 1318 die(_("options '%s' and '%s' cannot be used together"), "--cached", "--files");
e83e3333
PC
1319 diff_cmd = DIFF_FILES;
1320 }
1321
1322 info.argc = argc;
1323 info.argv = argv;
1324 info.prefix = prefix;
1325 info.cached = !!cached;
1326 info.files = !!files;
1327 info.for_status = !!for_status;
1328 info.summary_limit = summary_limit;
1329
1330 ret = compute_summary_module_list((diff_cmd == DIFF_INDEX) ? &head_oid : NULL,
1331 &info, diff_cmd);
1332 return ret;
1333}
1334
13424764
PC
1335struct sync_cb {
1336 const char *prefix;
1337 unsigned int flags;
1338};
9865b6e6 1339#define SYNC_CB_INIT { 0 }
13424764
PC
1340
1341static void sync_submodule(const char *path, const char *prefix,
1342 unsigned int flags)
1343{
1344 const struct submodule *sub;
1345 char *remote_key = NULL;
1346 char *sub_origin_url, *super_config_url, *displaypath;
1347 struct strbuf sb = STRBUF_INIT;
1348 struct child_process cp = CHILD_PROCESS_INIT;
1349 char *sub_config_path = NULL;
1350
1351 if (!is_submodule_active(the_repository, path))
1352 return;
1353
14228447 1354 sub = submodule_from_path(the_repository, null_oid(), path);
13424764
PC
1355
1356 if (sub && sub->url) {
1357 if (starts_with_dot_dot_slash(sub->url) ||
1358 starts_with_dot_slash(sub->url)) {
0c61041e 1359 char *up_path = get_up_path(path);
de0fcbe0
AR
1360 sub_origin_url = resolve_relative_url(sub->url, up_path, 1);
1361 super_config_url = resolve_relative_url(sub->url, NULL, 1);
13424764 1362 free(up_path);
13424764
PC
1363 } else {
1364 sub_origin_url = xstrdup(sub->url);
1365 super_config_url = xstrdup(sub->url);
1366 }
1367 } else {
1368 sub_origin_url = xstrdup("");
1369 super_config_url = xstrdup("");
1370 }
1371
1372 displaypath = get_submodule_displaypath(path, prefix);
1373
1374 if (!(flags & OPT_QUIET))
1375 printf(_("Synchronizing submodule url for '%s'\n"),
1376 displaypath);
1377
1378 strbuf_reset(&sb);
1379 strbuf_addf(&sb, "submodule.%s.url", sub->name);
1380 if (git_config_set_gently(sb.buf, super_config_url))
1381 die(_("failed to register url for submodule path '%s'"),
1382 displaypath);
1383
1384 if (!is_submodule_populated_gently(path, NULL))
1385 goto cleanup;
1386
1387 prepare_submodule_repo_env(&cp.env_array);
1388 cp.git_cmd = 1;
1389 cp.dir = path;
22f9b7f3 1390 strvec_pushl(&cp.args, "submodule--helper",
f6d8942b 1391 "print-default-remote", NULL);
13424764
PC
1392
1393 strbuf_reset(&sb);
1394 if (capture_command(&cp, &sb, 0))
1395 die(_("failed to get the default remote for submodule '%s'"),
1396 path);
1397
1398 strbuf_strip_suffix(&sb, "\n");
1399 remote_key = xstrfmt("remote.%s.url", sb.buf);
1400
1401 strbuf_reset(&sb);
1402 submodule_to_gitdir(&sb, path);
1403 strbuf_addstr(&sb, "/config");
1404
1405 if (git_config_set_in_file_gently(sb.buf, remote_key, sub_origin_url))
1406 die(_("failed to update remote for submodule '%s'"),
1407 path);
1408
1409 if (flags & OPT_RECURSIVE) {
1410 struct child_process cpr = CHILD_PROCESS_INIT;
1411
1412 cpr.git_cmd = 1;
1413 cpr.dir = path;
1414 prepare_submodule_repo_env(&cpr.env_array);
1415
22f9b7f3
JK
1416 strvec_push(&cpr.args, "--super-prefix");
1417 strvec_pushf(&cpr.args, "%s/", displaypath);
1418 strvec_pushl(&cpr.args, "submodule--helper", "sync",
f6d8942b 1419 "--recursive", NULL);
13424764
PC
1420
1421 if (flags & OPT_QUIET)
22f9b7f3 1422 strvec_push(&cpr.args, "--quiet");
13424764
PC
1423
1424 if (run_command(&cpr))
1425 die(_("failed to recurse into submodule '%s'"),
1426 path);
1427 }
1428
1429cleanup:
1430 free(super_config_url);
1431 free(sub_origin_url);
1432 strbuf_release(&sb);
1433 free(remote_key);
1434 free(displaypath);
1435 free(sub_config_path);
1436}
1437
1438static void sync_submodule_cb(const struct cache_entry *list_item, void *cb_data)
1439{
1440 struct sync_cb *info = cb_data;
1441 sync_submodule(list_item->name, info->prefix, info->flags);
13424764
PC
1442}
1443
1444static int module_sync(int argc, const char **argv, const char *prefix)
1445{
1446 struct sync_cb info = SYNC_CB_INIT;
1447 struct pathspec pathspec;
1448 struct module_list list = MODULE_LIST_INIT;
1449 int quiet = 0;
1450 int recursive = 0;
1451
1452 struct option module_sync_options[] = {
e73fe3dd 1453 OPT__QUIET(&quiet, N_("suppress output of synchronizing submodule url")),
13424764 1454 OPT_BOOL(0, "recursive", &recursive,
e73fe3dd 1455 N_("recurse into nested submodules")),
13424764
PC
1456 OPT_END()
1457 };
1458
1459 const char *const git_submodule_helper_usage[] = {
1460 N_("git submodule--helper sync [--quiet] [--recursive] [<path>]"),
1461 NULL
1462 };
1463
1464 argc = parse_options(argc, argv, prefix, module_sync_options,
1465 git_submodule_helper_usage, 0);
1466
1467 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
1468 return 1;
1469
1470 info.prefix = prefix;
1471 if (quiet)
1472 info.flags |= OPT_QUIET;
1473 if (recursive)
1474 info.flags |= OPT_RECURSIVE;
1475
1476 for_each_listed_submodule(&list, sync_submodule_cb, &info);
1477
1478 return 0;
1479}
1480
2e612731
PC
1481struct deinit_cb {
1482 const char *prefix;
1483 unsigned int flags;
1484};
9865b6e6 1485#define DEINIT_CB_INIT { 0 }
2e612731
PC
1486
1487static void deinit_submodule(const char *path, const char *prefix,
1488 unsigned int flags)
1489{
1490 const struct submodule *sub;
1491 char *displaypath = NULL;
1492 struct child_process cp_config = CHILD_PROCESS_INIT;
1493 struct strbuf sb_config = STRBUF_INIT;
1494 char *sub_git_dir = xstrfmt("%s/.git", path);
1495
14228447 1496 sub = submodule_from_path(the_repository, null_oid(), path);
2e612731
PC
1497
1498 if (!sub || !sub->name)
1499 goto cleanup;
1500
1501 displaypath = get_submodule_displaypath(path, prefix);
1502
1503 /* remove the submodule work tree (unless the user already did it) */
1504 if (is_directory(path)) {
1505 struct strbuf sb_rm = STRBUF_INIT;
1506 const char *format;
1507
0adc8ba6
MP
1508 if (is_directory(sub_git_dir)) {
1509 if (!(flags & OPT_QUIET))
1510 warning(_("Submodule work tree '%s' contains a .git "
1511 "directory. This will be replaced with a "
1512 ".git file by using absorbgitdirs."),
1513 displaypath);
1514
1515 absorb_git_dir_into_superproject(path,
1516 ABSORB_GITDIR_RECURSE_SUBMODULES);
1517
1518 }
2e612731
PC
1519
1520 if (!(flags & OPT_FORCE)) {
1521 struct child_process cp_rm = CHILD_PROCESS_INIT;
1522 cp_rm.git_cmd = 1;
22f9b7f3 1523 strvec_pushl(&cp_rm.args, "rm", "-qn",
f6d8942b 1524 path, NULL);
2e612731
PC
1525
1526 if (run_command(&cp_rm))
1527 die(_("Submodule work tree '%s' contains local "
1528 "modifications; use '-f' to discard them"),
1529 displaypath);
1530 }
1531
1532 strbuf_addstr(&sb_rm, path);
1533
1534 if (!remove_dir_recursively(&sb_rm, 0))
1535 format = _("Cleared directory '%s'\n");
1536 else
1537 format = _("Could not remove submodule work tree '%s'\n");
1538
1539 if (!(flags & OPT_QUIET))
1540 printf(format, displaypath);
1541
8eda5efa
SB
1542 submodule_unset_core_worktree(sub);
1543
2e612731
PC
1544 strbuf_release(&sb_rm);
1545 }
1546
1547 if (mkdir(path, 0777))
1548 printf(_("could not create empty submodule directory %s"),
1549 displaypath);
1550
1551 cp_config.git_cmd = 1;
22f9b7f3
JK
1552 strvec_pushl(&cp_config.args, "config", "--get-regexp", NULL);
1553 strvec_pushf(&cp_config.args, "submodule.%s\\.", sub->name);
2e612731
PC
1554
1555 /* remove the .git/config entries (unless the user already did it) */
1556 if (!capture_command(&cp_config, &sb_config, 0) && sb_config.len) {
1557 char *sub_key = xstrfmt("submodule.%s", sub->name);
1558 /*
1559 * remove the whole section so we have a clean state when
1560 * the user later decides to init this submodule again
1561 */
1562 git_config_rename_section_in_file(NULL, sub_key, NULL);
1563 if (!(flags & OPT_QUIET))
1564 printf(_("Submodule '%s' (%s) unregistered for path '%s'\n"),
1565 sub->name, sub->url, displaypath);
1566 free(sub_key);
1567 }
1568
1569cleanup:
1570 free(displaypath);
1571 free(sub_git_dir);
1572 strbuf_release(&sb_config);
1573}
1574
1575static void deinit_submodule_cb(const struct cache_entry *list_item,
1576 void *cb_data)
1577{
1578 struct deinit_cb *info = cb_data;
1579 deinit_submodule(list_item->name, info->prefix, info->flags);
1580}
1581
1582static int module_deinit(int argc, const char **argv, const char *prefix)
1583{
1584 struct deinit_cb info = DEINIT_CB_INIT;
1585 struct pathspec pathspec;
1586 struct module_list list = MODULE_LIST_INIT;
1587 int quiet = 0;
1588 int force = 0;
1589 int all = 0;
1590
1591 struct option module_deinit_options[] = {
e73fe3dd
ZH
1592 OPT__QUIET(&quiet, N_("suppress submodule status output")),
1593 OPT__FORCE(&force, N_("remove submodule working trees even if they contain local changes"), 0),
1594 OPT_BOOL(0, "all", &all, N_("unregister all submodules")),
2e612731
PC
1595 OPT_END()
1596 };
1597
1598 const char *const git_submodule_helper_usage[] = {
1599 N_("git submodule deinit [--quiet] [-f | --force] [--all | [--] [<path>...]]"),
1600 NULL
1601 };
1602
1603 argc = parse_options(argc, argv, prefix, module_deinit_options,
1604 git_submodule_helper_usage, 0);
1605
1606 if (all && argc) {
1607 error("pathspec and --all are incompatible");
1608 usage_with_options(git_submodule_helper_usage,
1609 module_deinit_options);
1610 }
1611
1612 if (!argc && !all)
1613 die(_("Use '--all' if you really want to deinitialize all submodules"));
1614
1615 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
9748e39d 1616 return 1;
2e612731
PC
1617
1618 info.prefix = prefix;
1619 if (quiet)
1620 info.flags |= OPT_QUIET;
1621 if (force)
1622 info.flags |= OPT_FORCE;
1623
1624 for_each_listed_submodule(&list, deinit_submodule_cb, &info);
1625
1626 return 0;
1627}
1628
a98b02c1
AR
1629struct module_clone_data {
1630 const char *prefix;
1631 const char *path;
1632 const char *name;
1633 const char *url;
1634 const char *depth;
f05da2b4 1635 struct list_objects_filter_options *filter_options;
a98b02c1
AR
1636 struct string_list reference;
1637 unsigned int quiet: 1;
1638 unsigned int progress: 1;
1639 unsigned int dissociate: 1;
1640 unsigned int require_init: 1;
1641 int single_branch;
1642};
1643#define MODULE_CLONE_DATA_INIT { .reference = STRING_LIST_INIT_NODUP, .single_branch = -1 }
ee8838d1 1644
31224cbd
SB
1645struct submodule_alternate_setup {
1646 const char *submodule_name;
1647 enum SUBMODULE_ALTERNATE_ERROR_MODE {
1648 SUBMODULE_ALTERNATE_ERROR_DIE,
1649 SUBMODULE_ALTERNATE_ERROR_INFO,
1650 SUBMODULE_ALTERNATE_ERROR_IGNORE
1651 } error_mode;
1652 struct string_list *reference;
1653};
f69a6e4f
ÆAB
1654#define SUBMODULE_ALTERNATE_SETUP_INIT { \
1655 .error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE, \
1656}
31224cbd 1657
4f3e57ef
JT
1658static const char alternate_error_advice[] = N_(
1659"An alternate computed from a superproject's alternate is invalid.\n"
1660"To allow Git to clone without an alternate in such a case, set\n"
1661"submodule.alternateErrorStrategy to 'info' or, equivalently, clone with\n"
1662"'--reference-if-able' instead of '--reference'."
1663);
1664
31224cbd 1665static int add_possible_reference_from_superproject(
263db403 1666 struct object_directory *odb, void *sas_cb)
31224cbd
SB
1667{
1668 struct submodule_alternate_setup *sas = sas_cb;
b2ac148f 1669 size_t len;
31224cbd 1670
31224cbd
SB
1671 /*
1672 * If the alternate object store is another repository, try the
bf03b790 1673 * standard layout with .git/(modules/<name>)+/objects
31224cbd 1674 */
263db403 1675 if (strip_suffix(odb->path, "/objects", &len)) {
ce125d43 1676 struct repository alternate;
31224cbd
SB
1677 char *sm_alternate;
1678 struct strbuf sb = STRBUF_INIT;
1679 struct strbuf err = STRBUF_INIT;
263db403 1680 strbuf_add(&sb, odb->path, len);
597f9134 1681
ce125d43
JT
1682 repo_init(&alternate, sb.buf, NULL);
1683
31224cbd
SB
1684 /*
1685 * We need to end the new path with '/' to mark it as a dir,
1686 * otherwise a submodule name containing '/' will be broken
1687 * as the last part of a missing submodule reference would
1688 * be taken as a file name.
1689 */
ce125d43
JT
1690 strbuf_reset(&sb);
1691 submodule_name_to_gitdir(&sb, &alternate, sas->submodule_name);
1692 strbuf_addch(&sb, '/');
1693 repo_clear(&alternate);
31224cbd
SB
1694
1695 sm_alternate = compute_alternate_path(sb.buf, &err);
1696 if (sm_alternate) {
1697 string_list_append(sas->reference, xstrdup(sb.buf));
1698 free(sm_alternate);
1699 } else {
1700 switch (sas->error_mode) {
1701 case SUBMODULE_ALTERNATE_ERROR_DIE:
ed9bff08 1702 if (advice_enabled(ADVICE_SUBMODULE_ALTERNATE_ERROR_STRATEGY_DIE))
4f3e57ef 1703 advise(_(alternate_error_advice));
31224cbd
SB
1704 die(_("submodule '%s' cannot add alternate: %s"),
1705 sas->submodule_name, err.buf);
1706 case SUBMODULE_ALTERNATE_ERROR_INFO:
1a878714 1707 fprintf_ln(stderr, _("submodule '%s' cannot add alternate: %s"),
31224cbd
SB
1708 sas->submodule_name, err.buf);
1709 case SUBMODULE_ALTERNATE_ERROR_IGNORE:
1710 ; /* nothing */
1711 }
1712 }
1713 strbuf_release(&sb);
1714 }
1715
31224cbd
SB
1716 return 0;
1717}
1718
1719static void prepare_possible_alternates(const char *sm_name,
1720 struct string_list *reference)
1721{
1722 char *sm_alternate = NULL, *error_strategy = NULL;
1723 struct submodule_alternate_setup sas = SUBMODULE_ALTERNATE_SETUP_INIT;
1724
1725 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1726 if (!sm_alternate)
1727 return;
1728
1729 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1730
1731 if (!error_strategy)
1732 error_strategy = xstrdup("die");
1733
1734 sas.submodule_name = sm_name;
1735 sas.reference = reference;
1736 if (!strcmp(error_strategy, "die"))
1737 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_DIE;
1738 else if (!strcmp(error_strategy, "info"))
1739 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_INFO;
1740 else if (!strcmp(error_strategy, "ignore"))
1741 sas.error_mode = SUBMODULE_ALTERNATE_ERROR_IGNORE;
1742 else
1743 die(_("Value '%s' for submodule.alternateErrorStrategy is not recognized"), error_strategy);
1744
1745 if (!strcmp(sm_alternate, "superproject"))
1746 foreach_alt_odb(add_possible_reference_from_superproject, &sas);
1747 else if (!strcmp(sm_alternate, "no"))
1748 ; /* do nothing */
1749 else
1750 die(_("Value '%s' for submodule.alternateLocation is not recognized"), sm_alternate);
1751
1752 free(sm_alternate);
1753 free(error_strategy);
1754}
1755
a98b02c1 1756static int clone_submodule(struct module_clone_data *clone_data)
ee8838d1 1757{
a98b02c1 1758 char *p, *sm_gitdir;
bf03b790 1759 char *sm_alternate = NULL, *error_strategy = NULL;
a98b02c1
AR
1760 struct strbuf sb = STRBUF_INIT;
1761 struct child_process cp = CHILD_PROCESS_INIT;
1762
ce125d43 1763 submodule_name_to_gitdir(&sb, the_repository, clone_data->name);
a98b02c1
AR
1764 sm_gitdir = absolute_pathdup(sb.buf);
1765 strbuf_reset(&sb);
1766
1767 if (!is_absolute_path(clone_data->path)) {
1768 strbuf_addf(&sb, "%s/%s", get_git_work_tree(), clone_data->path);
1769 clone_data->path = strbuf_detach(&sb, NULL);
1770 } else {
1771 clone_data->path = xstrdup(clone_data->path);
1772 }
1773
1774 if (validate_submodule_git_dir(sm_gitdir, clone_data->name) < 0)
1775 die(_("refusing to create/use '%s' in another submodule's "
1776 "git dir"), sm_gitdir);
1777
1778 if (!file_exists(sm_gitdir)) {
1779 if (safe_create_leading_directories_const(sm_gitdir) < 0)
1780 die(_("could not create directory '%s'"), sm_gitdir);
1781
1782 prepare_possible_alternates(clone_data->name, &clone_data->reference);
1783
1784 strvec_push(&cp.args, "clone");
1785 strvec_push(&cp.args, "--no-checkout");
1786 if (clone_data->quiet)
1787 strvec_push(&cp.args, "--quiet");
1788 if (clone_data->progress)
1789 strvec_push(&cp.args, "--progress");
1790 if (clone_data->depth && *(clone_data->depth))
1791 strvec_pushl(&cp.args, "--depth", clone_data->depth, NULL);
1792 if (clone_data->reference.nr) {
1793 struct string_list_item *item;
1794 for_each_string_list_item(item, &clone_data->reference)
1795 strvec_pushl(&cp.args, "--reference",
1796 item->string, NULL);
1797 }
1798 if (clone_data->dissociate)
1799 strvec_push(&cp.args, "--dissociate");
1800 if (sm_gitdir && *sm_gitdir)
1801 strvec_pushl(&cp.args, "--separate-git-dir", sm_gitdir, NULL);
f05da2b4
JS
1802 if (clone_data->filter_options && clone_data->filter_options->choice)
1803 strvec_pushf(&cp.args, "--filter=%s",
1804 expand_list_objects_filter_spec(
1805 clone_data->filter_options));
a98b02c1
AR
1806 if (clone_data->single_branch >= 0)
1807 strvec_push(&cp.args, clone_data->single_branch ?
1808 "--single-branch" :
1809 "--no-single-branch");
1810
1811 strvec_push(&cp.args, "--");
1812 strvec_push(&cp.args, clone_data->url);
1813 strvec_push(&cp.args, clone_data->path);
1814
1815 cp.git_cmd = 1;
1816 prepare_submodule_repo_env(&cp.env_array);
1817 cp.no_stdin = 1;
1818
1819 if(run_command(&cp))
1820 die(_("clone of '%s' into submodule path '%s' failed"),
1821 clone_data->url, clone_data->path);
1822 } else {
1823 if (clone_data->require_init && !access(clone_data->path, X_OK) &&
1824 !is_empty_dir(clone_data->path))
1825 die(_("directory not empty: '%s'"), clone_data->path);
1826 if (safe_create_leading_directories_const(clone_data->path) < 0)
1827 die(_("could not create directory '%s'"), clone_data->path);
1828 strbuf_addf(&sb, "%s/index", sm_gitdir);
1829 unlink_or_warn(sb.buf);
1830 strbuf_reset(&sb);
1831 }
1832
1833 connect_work_tree_and_git_dir(clone_data->path, sm_gitdir, 0);
1834
1835 p = git_pathdup_submodule(clone_data->path, "config");
1836 if (!p)
1837 die(_("could not get submodule directory for '%s'"), clone_data->path);
1838
1839 /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */
1840 git_config_get_string("submodule.alternateLocation", &sm_alternate);
1841 if (sm_alternate)
1842 git_config_set_in_file(p, "submodule.alternateLocation",
1843 sm_alternate);
1844 git_config_get_string("submodule.alternateErrorStrategy", &error_strategy);
1845 if (error_strategy)
1846 git_config_set_in_file(p, "submodule.alternateErrorStrategy",
1847 error_strategy);
1848
1849 free(sm_alternate);
1850 free(error_strategy);
1851
1852 strbuf_release(&sb);
1853 free(sm_gitdir);
1854 free(p);
1855 return 0;
1856}
1857
1858static int module_clone(int argc, const char **argv, const char *prefix)
1859{
1860 int dissociate = 0, quiet = 0, progress = 0, require_init = 0;
1861 struct module_clone_data clone_data = MODULE_CLONE_DATA_INIT;
f05da2b4 1862 struct list_objects_filter_options filter_options;
ee8838d1
SB
1863
1864 struct option module_clone_options[] = {
a98b02c1 1865 OPT_STRING(0, "prefix", &clone_data.prefix,
ee8838d1
SB
1866 N_("path"),
1867 N_("alternative anchor for relative paths")),
a98b02c1 1868 OPT_STRING(0, "path", &clone_data.path,
ee8838d1
SB
1869 N_("path"),
1870 N_("where the new submodule will be cloned to")),
a98b02c1 1871 OPT_STRING(0, "name", &clone_data.name,
ee8838d1
SB
1872 N_("string"),
1873 N_("name of the new submodule")),
a98b02c1 1874 OPT_STRING(0, "url", &clone_data.url,
ee8838d1
SB
1875 N_("string"),
1876 N_("url where to clone the submodule from")),
a98b02c1 1877 OPT_STRING_LIST(0, "reference", &clone_data.reference,
965dbea0 1878 N_("repo"),
ee8838d1 1879 N_("reference repository")),
a0ef2934
CF
1880 OPT_BOOL(0, "dissociate", &dissociate,
1881 N_("use --reference only while cloning")),
a98b02c1 1882 OPT_STRING(0, "depth", &clone_data.depth,
ee8838d1
SB
1883 N_("string"),
1884 N_("depth for shallow clones")),
1885 OPT__QUIET(&quiet, "Suppress output for cloning a submodule"),
72c5f883
JK
1886 OPT_BOOL(0, "progress", &progress,
1887 N_("force cloning progress")),
0060fd15
JS
1888 OPT_BOOL(0, "require-init", &require_init,
1889 N_("disallow cloning into non-empty directory")),
a98b02c1 1890 OPT_BOOL(0, "single-branch", &clone_data.single_branch,
132f600b 1891 N_("clone only one branch, HEAD or --branch")),
f05da2b4 1892 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
ee8838d1
SB
1893 OPT_END()
1894 };
1895
1896 const char *const git_submodule_helper_usage[] = {
1897 N_("git submodule--helper clone [--prefix=<path>] [--quiet] "
7dad2633 1898 "[--reference <repository>] [--name <name>] [--depth <depth>] "
f05da2b4 1899 "[--single-branch] [--filter <filter-spec>]"
7dad2633 1900 "--url <url> --path <path>"),
ee8838d1
SB
1901 NULL
1902 };
1903
f05da2b4 1904 memset(&filter_options, 0, sizeof(filter_options));
ee8838d1
SB
1905 argc = parse_options(argc, argv, prefix, module_clone_options,
1906 git_submodule_helper_usage, 0);
1907
a98b02c1
AR
1908 clone_data.dissociate = !!dissociate;
1909 clone_data.quiet = !!quiet;
1910 clone_data.progress = !!progress;
1911 clone_data.require_init = !!require_init;
f05da2b4 1912 clone_data.filter_options = &filter_options;
a98b02c1
AR
1913
1914 if (argc || !clone_data.url || !clone_data.path || !*(clone_data.path))
08e0970a
JK
1915 usage_with_options(git_submodule_helper_usage,
1916 module_clone_options);
1917
a98b02c1 1918 clone_submodule(&clone_data);
f05da2b4 1919 list_objects_filter_release(&filter_options);
ee8838d1
SB
1920 return 0;
1921}
74703a1e 1922
ee69b2a9
SB
1923static void determine_submodule_update_strategy(struct repository *r,
1924 int just_cloned,
1925 const char *path,
1926 const char *update,
1927 struct submodule_update_strategy *out)
1928{
14228447 1929 const struct submodule *sub = submodule_from_path(r, null_oid(), path);
ee69b2a9
SB
1930 char *key;
1931 const char *val;
1932
1933 key = xstrfmt("submodule.%s.update", sub->name);
1934
1935 if (update) {
ee69b2a9
SB
1936 if (parse_submodule_update_strategy(update, out) < 0)
1937 die(_("Invalid update mode '%s' for submodule path '%s'"),
1938 update, path);
f1de981e 1939 } else if (!repo_config_get_string_tmp(r, key, &val)) {
ee69b2a9
SB
1940 if (parse_submodule_update_strategy(val, out) < 0)
1941 die(_("Invalid update mode '%s' configured for submodule path '%s'"),
1942 val, path);
1943 } else if (sub->update_strategy.type != SM_UPDATE_UNSPECIFIED) {
c1547450
JN
1944 if (sub->update_strategy.type == SM_UPDATE_COMMAND)
1945 BUG("how did we read update = !command from .gitmodules?");
ee69b2a9
SB
1946 out->type = sub->update_strategy.type;
1947 out->command = sub->update_strategy.command;
1948 } else
1949 out->type = SM_UPDATE_CHECKOUT;
1950
1951 if (just_cloned &&
1952 (out->type == SM_UPDATE_MERGE ||
1953 out->type == SM_UPDATE_REBASE ||
1954 out->type == SM_UPDATE_NONE))
1955 out->type = SM_UPDATE_CHECKOUT;
1956
1957 free(key);
1958}
1959
f1d15713
SB
1960struct update_clone_data {
1961 const struct submodule *sub;
1962 struct object_id oid;
1963 unsigned just_cloned;
1964};
1965
48308681
SB
1966struct submodule_update_clone {
1967 /* index into 'list', the list of submodules to look into for cloning */
1968 int current;
1969 struct module_list list;
1970 unsigned warn_if_uninitialized : 1;
1971
1972 /* update parameter passed via commandline */
1973 struct submodule_update_strategy update;
1974
1975 /* configuration parameters which are passed on to the children */
72c5f883 1976 int progress;
48308681 1977 int quiet;
abed000a 1978 int recommend_shallow;
5f50f33e 1979 struct string_list references;
a0ef2934 1980 int dissociate;
0060fd15 1981 unsigned require_init;
48308681
SB
1982 const char *depth;
1983 const char *recursive_prefix;
1984 const char *prefix;
132f600b 1985 int single_branch;
f05da2b4 1986 struct list_objects_filter_options *filter_options;
48308681 1987
f1d15713
SB
1988 /* to be consumed by git-submodule.sh */
1989 struct update_clone_data *update_clone;
1990 int update_clone_nr; int update_clone_alloc;
48308681
SB
1991
1992 /* If we want to stop as fast as possible and return an error */
1993 unsigned quickstop : 1;
665b35ec
SB
1994
1995 /* failed clones to be retried again */
1996 const struct cache_entry **failed_clones;
1997 int failed_clones_nr, failed_clones_alloc;
90efe595
SB
1998
1999 int max_jobs;
48308681 2000};
47319576
ES
2001#define SUBMODULE_UPDATE_CLONE_INIT { \
2002 .list = MODULE_LIST_INIT, \
2003 .update = SUBMODULE_UPDATE_STRATEGY_INIT, \
2004 .recommend_shallow = -1, \
2005 .references = STRING_LIST_INIT_DUP, \
132f600b 2006 .single_branch = -1, \
47319576
ES
2007 .max_jobs = 1, \
2008}
48308681 2009
c51f8f94
AR
2010struct update_data {
2011 const char *recursive_prefix;
2012 const char *sm_path;
2013 const char *displaypath;
2014 struct object_id oid;
2015 struct object_id suboid;
2016 struct submodule_update_strategy update_strategy;
2017 int depth;
2018 unsigned int force: 1;
2019 unsigned int quiet: 1;
2020 unsigned int nofetch: 1;
2021 unsigned int just_cloned: 1;
2022};
2023#define UPDATE_DATA_INIT { .update_strategy = SUBMODULE_UPDATE_STRATEGY_INIT }
08fdbdb1
SB
2024
2025static void next_submodule_warn_missing(struct submodule_update_clone *suc,
2026 struct strbuf *out, const char *displaypath)
2027{
2028 /*
2029 * Only mention uninitialized submodules when their
2030 * paths have been specified.
2031 */
2032 if (suc->warn_if_uninitialized) {
2033 strbuf_addf(out,
2034 _("Submodule path '%s' not initialized"),
2035 displaypath);
2036 strbuf_addch(out, '\n');
2037 strbuf_addstr(out,
2038 _("Maybe you want to use 'update --init'?"));
2039 strbuf_addch(out, '\n');
2040 }
2041}
2042
48308681
SB
2043/**
2044 * Determine whether 'ce' needs to be cloned. If so, prepare the 'child' to
2045 * run the clone. Returns 1 if 'ce' needs to be cloned, 0 otherwise.
2046 */
2047static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
2048 struct child_process *child,
2049 struct submodule_update_clone *suc,
2050 struct strbuf *out)
2051{
2052 const struct submodule *sub = NULL;
ec6141a0
BW
2053 const char *url = NULL;
2054 const char *update_string;
2055 enum submodule_update_type update_type;
2056 char *key;
48308681
SB
2057 struct strbuf displaypath_sb = STRBUF_INIT;
2058 struct strbuf sb = STRBUF_INIT;
2059 const char *displaypath = NULL;
48308681 2060 int needs_cloning = 0;
e0a862fd 2061 int need_free_url = 0;
48308681
SB
2062
2063 if (ce_stage(ce)) {
2064 if (suc->recursive_prefix)
2065 strbuf_addf(&sb, "%s/%s", suc->recursive_prefix, ce->name);
2066 else
92d52fab 2067 strbuf_addstr(&sb, ce->name);
48308681
SB
2068 strbuf_addf(out, _("Skipping unmerged submodule %s"), sb.buf);
2069 strbuf_addch(out, '\n');
2070 goto cleanup;
2071 }
2072
14228447 2073 sub = submodule_from_path(the_repository, null_oid(), ce->name);
48308681
SB
2074
2075 if (suc->recursive_prefix)
2076 displaypath = relative_path(suc->recursive_prefix,
2077 ce->name, &displaypath_sb);
2078 else
2079 displaypath = ce->name;
2080
08fdbdb1
SB
2081 if (!sub) {
2082 next_submodule_warn_missing(suc, out, displaypath);
2083 goto cleanup;
2084 }
2085
ec6141a0 2086 key = xstrfmt("submodule.%s.update", sub->name);
f1de981e 2087 if (!repo_config_get_string_tmp(the_repository, key, &update_string)) {
ec6141a0
BW
2088 update_type = parse_submodule_update_type(update_string);
2089 } else {
2090 update_type = sub->update_strategy.type;
2091 }
2092 free(key);
2093
48308681
SB
2094 if (suc->update.type == SM_UPDATE_NONE
2095 || (suc->update.type == SM_UPDATE_UNSPECIFIED
ec6141a0 2096 && update_type == SM_UPDATE_NONE)) {
48308681
SB
2097 strbuf_addf(out, _("Skipping submodule '%s'"), displaypath);
2098 strbuf_addch(out, '\n');
2099 goto cleanup;
2100 }
2101
ee92ab99 2102 /* Check if the submodule has been initialized. */
627d9342 2103 if (!is_submodule_active(the_repository, ce->name)) {
08fdbdb1 2104 next_submodule_warn_missing(suc, out, displaypath);
48308681
SB
2105 goto cleanup;
2106 }
2107
ec6141a0
BW
2108 strbuf_reset(&sb);
2109 strbuf_addf(&sb, "submodule.%s.url", sub->name);
f1de981e 2110 if (repo_config_get_string_tmp(the_repository, sb.buf, &url)) {
e0a862fd
SB
2111 if (starts_with_dot_slash(sub->url) ||
2112 starts_with_dot_dot_slash(sub->url)) {
de0fcbe0 2113 url = resolve_relative_url(sub->url, NULL, 0);
e0a862fd
SB
2114 need_free_url = 1;
2115 } else
2116 url = sub->url;
2117 }
ec6141a0 2118
48308681
SB
2119 strbuf_reset(&sb);
2120 strbuf_addf(&sb, "%s/.git", ce->name);
2121 needs_cloning = !file_exists(sb.buf);
2122
f1d15713
SB
2123 ALLOC_GROW(suc->update_clone, suc->update_clone_nr + 1,
2124 suc->update_clone_alloc);
2125 oidcpy(&suc->update_clone[suc->update_clone_nr].oid, &ce->oid);
2126 suc->update_clone[suc->update_clone_nr].just_cloned = needs_cloning;
2127 suc->update_clone[suc->update_clone_nr].sub = sub;
2128 suc->update_clone_nr++;
48308681
SB
2129
2130 if (!needs_cloning)
2131 goto cleanup;
2132
2133 child->git_cmd = 1;
2134 child->no_stdin = 1;
2135 child->stdout_to_stderr = 1;
2136 child->err = -1;
22f9b7f3
JK
2137 strvec_push(&child->args, "submodule--helper");
2138 strvec_push(&child->args, "clone");
72c5f883 2139 if (suc->progress)
22f9b7f3 2140 strvec_push(&child->args, "--progress");
48308681 2141 if (suc->quiet)
22f9b7f3 2142 strvec_push(&child->args, "--quiet");
48308681 2143 if (suc->prefix)
22f9b7f3 2144 strvec_pushl(&child->args, "--prefix", suc->prefix, NULL);
abed000a 2145 if (suc->recommend_shallow && sub->recommend_shallow == 1)
22f9b7f3 2146 strvec_push(&child->args, "--depth=1");
f05da2b4
JS
2147 if (suc->filter_options && suc->filter_options->choice)
2148 strvec_pushf(&child->args, "--filter=%s",
2149 expand_list_objects_filter_spec(suc->filter_options));
0060fd15 2150 if (suc->require_init)
22f9b7f3
JK
2151 strvec_push(&child->args, "--require-init");
2152 strvec_pushl(&child->args, "--path", sub->path, NULL);
2153 strvec_pushl(&child->args, "--name", sub->name, NULL);
2154 strvec_pushl(&child->args, "--url", url, NULL);
5f50f33e
SB
2155 if (suc->references.nr) {
2156 struct string_list_item *item;
2157 for_each_string_list_item(item, &suc->references)
22f9b7f3 2158 strvec_pushl(&child->args, "--reference", item->string, NULL);
5f50f33e 2159 }
a0ef2934 2160 if (suc->dissociate)
22f9b7f3 2161 strvec_push(&child->args, "--dissociate");
48308681 2162 if (suc->depth)
22f9b7f3 2163 strvec_push(&child->args, suc->depth);
132f600b 2164 if (suc->single_branch >= 0)
22f9b7f3 2165 strvec_push(&child->args, suc->single_branch ?
132f600b
ES
2166 "--single-branch" :
2167 "--no-single-branch");
48308681
SB
2168
2169cleanup:
9101c8ea
JK
2170 strbuf_release(&displaypath_sb);
2171 strbuf_release(&sb);
e0a862fd
SB
2172 if (need_free_url)
2173 free((void*)url);
48308681
SB
2174
2175 return needs_cloning;
2176}
2177
2178static int update_clone_get_next_task(struct child_process *child,
2179 struct strbuf *err,
2180 void *suc_cb,
665b35ec 2181 void **idx_task_cb)
48308681
SB
2182{
2183 struct submodule_update_clone *suc = suc_cb;
665b35ec
SB
2184 const struct cache_entry *ce;
2185 int index;
48308681
SB
2186
2187 for (; suc->current < suc->list.nr; suc->current++) {
665b35ec 2188 ce = suc->list.entries[suc->current];
48308681 2189 if (prepare_to_clone_next_submodule(ce, child, suc, err)) {
665b35ec
SB
2190 int *p = xmalloc(sizeof(*p));
2191 *p = suc->current;
2192 *idx_task_cb = p;
48308681
SB
2193 suc->current++;
2194 return 1;
2195 }
2196 }
665b35ec
SB
2197
2198 /*
2199 * The loop above tried cloning each submodule once, now try the
2200 * stragglers again, which we can imagine as an extension of the
2201 * entry list.
2202 */
2203 index = suc->current - suc->list.nr;
2204 if (index < suc->failed_clones_nr) {
2205 int *p;
2206 ce = suc->failed_clones[index];
2201ee09
SB
2207 if (!prepare_to_clone_next_submodule(ce, child, suc, err)) {
2208 suc->current ++;
a22ae753
RS
2209 strbuf_addstr(err, "BUG: submodule considered for "
2210 "cloning, doesn't need cloning "
2211 "any more?\n");
2201ee09
SB
2212 return 0;
2213 }
665b35ec
SB
2214 p = xmalloc(sizeof(*p));
2215 *p = suc->current;
2216 *idx_task_cb = p;
2217 suc->current ++;
2218 return 1;
2219 }
2220
48308681
SB
2221 return 0;
2222}
2223
2224static int update_clone_start_failure(struct strbuf *err,
2225 void *suc_cb,
665b35ec 2226 void *idx_task_cb)
48308681
SB
2227{
2228 struct submodule_update_clone *suc = suc_cb;
2229 suc->quickstop = 1;
2230 return 1;
2231}
2232
2233static int update_clone_task_finished(int result,
2234 struct strbuf *err,
2235 void *suc_cb,
665b35ec 2236 void *idx_task_cb)
48308681 2237{
665b35ec 2238 const struct cache_entry *ce;
48308681
SB
2239 struct submodule_update_clone *suc = suc_cb;
2240
c1e860f1 2241 int *idxP = idx_task_cb;
665b35ec
SB
2242 int idx = *idxP;
2243 free(idxP);
2244
48308681
SB
2245 if (!result)
2246 return 0;
2247
665b35ec
SB
2248 if (idx < suc->list.nr) {
2249 ce = suc->list.entries[idx];
2250 strbuf_addf(err, _("Failed to clone '%s'. Retry scheduled"),
2251 ce->name);
2252 strbuf_addch(err, '\n');
2253 ALLOC_GROW(suc->failed_clones,
2254 suc->failed_clones_nr + 1,
2255 suc->failed_clones_alloc);
2256 suc->failed_clones[suc->failed_clones_nr++] = ce;
2257 return 0;
2258 } else {
eb09121b 2259 idx -= suc->list.nr;
665b35ec
SB
2260 ce = suc->failed_clones[idx];
2261 strbuf_addf(err, _("Failed to clone '%s' a second time, aborting"),
2262 ce->name);
2263 strbuf_addch(err, '\n');
2264 suc->quickstop = 1;
2265 return 1;
2266 }
2267
2268 return 0;
48308681
SB
2269}
2270
05744997
AO
2271static int git_update_clone_config(const char *var, const char *value,
2272 void *cb)
f20e7c1e
BW
2273{
2274 int *max_jobs = cb;
2275 if (!strcmp(var, "submodule.fetchjobs"))
2276 *max_jobs = parse_submodule_fetchjobs(var, value);
2277 return 0;
2278}
2279
c51f8f94
AR
2280static int is_tip_reachable(const char *path, struct object_id *oid)
2281{
2282 struct child_process cp = CHILD_PROCESS_INIT;
2283 struct strbuf rev = STRBUF_INIT;
2284 char *hex = oid_to_hex(oid);
2285
2286 cp.git_cmd = 1;
2287 cp.dir = xstrdup(path);
2288 cp.no_stderr = 1;
2289 strvec_pushl(&cp.args, "rev-list", "-n", "1", hex, "--not", "--all", NULL);
2290
2291 prepare_submodule_repo_env(&cp.env_array);
2292
2293 if (capture_command(&cp, &rev, GIT_MAX_HEXSZ + 1) || rev.len)
2294 return 0;
2295
2296 return 1;
2297}
2298
2299static int fetch_in_submodule(const char *module_path, int depth, int quiet, struct object_id *oid)
2300{
2301 struct child_process cp = CHILD_PROCESS_INIT;
2302
2303 prepare_submodule_repo_env(&cp.env_array);
2304 cp.git_cmd = 1;
2305 cp.dir = xstrdup(module_path);
2306
2307 strvec_push(&cp.args, "fetch");
2308 if (quiet)
2309 strvec_push(&cp.args, "--quiet");
2310 if (depth)
2311 strvec_pushf(&cp.args, "--depth=%d", depth);
2312 if (oid) {
2313 char *hex = oid_to_hex(oid);
2314 char *remote = get_default_remote();
2315 strvec_pushl(&cp.args, remote, hex, NULL);
2316 }
2317
2318 return run_command(&cp);
2319}
2320
2321static int run_update_command(struct update_data *ud, int subforce)
2322{
2323 struct strvec args = STRVEC_INIT;
2324 struct strvec child_env = STRVEC_INIT;
2325 char *oid = oid_to_hex(&ud->oid);
2326 int must_die_on_failure = 0;
2327 int git_cmd;
2328
2329 switch (ud->update_strategy.type) {
2330 case SM_UPDATE_CHECKOUT:
2331 git_cmd = 1;
2332 strvec_pushl(&args, "checkout", "-q", NULL);
2333 if (subforce)
2334 strvec_push(&args, "-f");
2335 break;
2336 case SM_UPDATE_REBASE:
2337 git_cmd = 1;
2338 strvec_push(&args, "rebase");
2339 if (ud->quiet)
2340 strvec_push(&args, "--quiet");
2341 must_die_on_failure = 1;
2342 break;
2343 case SM_UPDATE_MERGE:
2344 git_cmd = 1;
2345 strvec_push(&args, "merge");
2346 if (ud->quiet)
2347 strvec_push(&args, "--quiet");
2348 must_die_on_failure = 1;
2349 break;
2350 case SM_UPDATE_COMMAND:
2351 git_cmd = 0;
2352 strvec_push(&args, ud->update_strategy.command);
2353 must_die_on_failure = 1;
2354 break;
2355 default:
2356 BUG("unexpected update strategy type: %s",
2357 submodule_strategy_to_string(&ud->update_strategy));
2358 }
2359 strvec_push(&args, oid);
2360
2361 prepare_submodule_repo_env(&child_env);
2362 if (run_command_v_opt_cd_env(args.v, git_cmd ? RUN_GIT_CMD : RUN_USING_SHELL,
2363 ud->sm_path, child_env.v)) {
2364 switch (ud->update_strategy.type) {
2365 case SM_UPDATE_CHECKOUT:
2366 printf(_("Unable to checkout '%s' in submodule path '%s'"),
2367 oid, ud->displaypath);
2368 break;
2369 case SM_UPDATE_REBASE:
2370 printf(_("Unable to rebase '%s' in submodule path '%s'"),
2371 oid, ud->displaypath);
2372 break;
2373 case SM_UPDATE_MERGE:
2374 printf(_("Unable to merge '%s' in submodule path '%s'"),
2375 oid, ud->displaypath);
2376 break;
2377 case SM_UPDATE_COMMAND:
2378 printf(_("Execution of '%s %s' failed in submodule path '%s'"),
2379 ud->update_strategy.command, oid, ud->displaypath);
2380 break;
2381 default:
2382 BUG("unexpected update strategy type: %s",
2383 submodule_strategy_to_string(&ud->update_strategy));
2384 }
2385 /*
2386 * NEEDSWORK: We are currently printing to stdout with error
2387 * return so that the shell caller handles the error output
2388 * properly. Once we start handling the error messages within
2389 * C, we should use die() instead.
2390 */
2391 if (must_die_on_failure)
2392 return 2;
2393 /*
2394 * This signifies to the caller in shell that the command
2395 * failed without dying
2396 */
2397 return 1;
2398 }
2399
2400 switch (ud->update_strategy.type) {
2401 case SM_UPDATE_CHECKOUT:
2402 printf(_("Submodule path '%s': checked out '%s'\n"),
2403 ud->displaypath, oid);
2404 break;
2405 case SM_UPDATE_REBASE:
2406 printf(_("Submodule path '%s': rebased into '%s'\n"),
2407 ud->displaypath, oid);
2408 break;
2409 case SM_UPDATE_MERGE:
2410 printf(_("Submodule path '%s': merged in '%s'\n"),
2411 ud->displaypath, oid);
2412 break;
2413 case SM_UPDATE_COMMAND:
2414 printf(_("Submodule path '%s': '%s %s'\n"),
2415 ud->displaypath, ud->update_strategy.command, oid);
2416 break;
2417 default:
2418 BUG("unexpected update strategy type: %s",
2419 submodule_strategy_to_string(&ud->update_strategy));
2420 }
2421
2422 return 0;
2423}
2424
2425static int do_run_update_procedure(struct update_data *ud)
2426{
2427 int subforce = is_null_oid(&ud->suboid) || ud->force;
2428
2429 if (!ud->nofetch) {
2430 /*
2431 * Run fetch only if `oid` isn't present or it
2432 * is not reachable from a ref.
2433 */
2434 if (!is_tip_reachable(ud->sm_path, &ud->oid) &&
2435 fetch_in_submodule(ud->sm_path, ud->depth, ud->quiet, NULL) &&
2436 !ud->quiet)
2437 fprintf_ln(stderr,
2438 _("Unable to fetch in submodule path '%s'; "
2439 "trying to directly fetch %s:"),
2440 ud->displaypath, oid_to_hex(&ud->oid));
2441 /*
2442 * Now we tried the usual fetch, but `oid` may
2443 * not be reachable from any of the refs.
2444 */
2445 if (!is_tip_reachable(ud->sm_path, &ud->oid) &&
2446 fetch_in_submodule(ud->sm_path, ud->depth, ud->quiet, &ud->oid))
2447 die(_("Fetched in submodule path '%s', but it did not "
2448 "contain %s. Direct fetching of that commit failed."),
2449 ud->displaypath, oid_to_hex(&ud->oid));
2450 }
2451
2452 return run_update_command(ud, subforce);
2453}
2454
1a0b78c9
GC
2455/*
2456 * NEEDSWORK: As we convert "git submodule update" to C,
2457 * update_submodule2() will invoke more and more functions, making it
2458 * difficult to preserve the function ordering without forward
2459 * declarations.
2460 *
2461 * When the conversion is complete, this forward declaration will be
2462 * unnecessary and should be removed.
2463 */
2464static int update_submodule2(struct update_data *update_data);
c94d9dc2
SB
2465static void update_submodule(struct update_clone_data *ucd)
2466{
2467 fprintf(stdout, "dummy %s %d\t%s\n",
2468 oid_to_hex(&ucd->oid),
2469 ucd->just_cloned,
2470 ucd->sub->path);
2471}
2472
90efe595
SB
2473static int update_submodules(struct submodule_update_clone *suc)
2474{
f1d15713 2475 int i;
90efe595 2476
ee4512ed
JH
2477 run_processes_parallel_tr2(suc->max_jobs, update_clone_get_next_task,
2478 update_clone_start_failure,
2479 update_clone_task_finished, suc, "submodule",
2480 "parallel/update");
90efe595
SB
2481
2482 /*
2483 * We saved the output and put it out all at once now.
2484 * That means:
2485 * - the listener does not have to interleave their (checkout)
2486 * work with our fetching. The writes involved in a
2487 * checkout involve more straightforward sequential I/O.
2488 * - the listener can avoid doing any work if fetching failed.
2489 */
2490 if (suc->quickstop)
2491 return 1;
2492
c94d9dc2
SB
2493 for (i = 0; i < suc->update_clone_nr; i++)
2494 update_submodule(&suc->update_clone[i]);
90efe595
SB
2495
2496 return 0;
2497}
2498
48308681
SB
2499static int update_clone(int argc, const char **argv, const char *prefix)
2500{
2501 const char *update = NULL;
48308681
SB
2502 struct pathspec pathspec;
2503 struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
f05da2b4
JS
2504 struct list_objects_filter_options filter_options;
2505 int ret;
48308681
SB
2506
2507 struct option module_update_clone_options[] = {
2508 OPT_STRING(0, "prefix", &prefix,
2509 N_("path"),
2510 N_("path into the working tree")),
2511 OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix,
2512 N_("path"),
2513 N_("path into the working tree, across nested "
2514 "submodule boundaries")),
2515 OPT_STRING(0, "update", &update,
2516 N_("string"),
2517 N_("rebase, merge, checkout or none")),
5f50f33e 2518 OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
48308681 2519 N_("reference repository")),
a0ef2934
CF
2520 OPT_BOOL(0, "dissociate", &suc.dissociate,
2521 N_("use --reference only while cloning")),
48308681 2522 OPT_STRING(0, "depth", &suc.depth, "<depth>",
e73fe3dd 2523 N_("create a shallow clone truncated to the "
48308681 2524 "specified number of revisions")),
90efe595 2525 OPT_INTEGER('j', "jobs", &suc.max_jobs,
2335b870 2526 N_("parallel jobs")),
abed000a
SB
2527 OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow,
2528 N_("whether the initial clone should follow the shallow recommendation")),
48308681 2529 OPT__QUIET(&suc.quiet, N_("don't print cloning progress")),
72c5f883
JK
2530 OPT_BOOL(0, "progress", &suc.progress,
2531 N_("force cloning progress")),
0060fd15
JS
2532 OPT_BOOL(0, "require-init", &suc.require_init,
2533 N_("disallow cloning into non-empty directory")),
132f600b
ES
2534 OPT_BOOL(0, "single-branch", &suc.single_branch,
2535 N_("clone only one branch, HEAD or --branch")),
f05da2b4 2536 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
48308681
SB
2537 OPT_END()
2538 };
2539
2540 const char *const git_submodule_helper_usage[] = {
cda0d497 2541 N_("git submodule--helper update-clone [--prefix=<path>] [<path>...]"),
48308681
SB
2542 NULL
2543 };
2544 suc.prefix = prefix;
2545
90efe595
SB
2546 update_clone_config_from_gitmodules(&suc.max_jobs);
2547 git_config(git_update_clone_config, &suc.max_jobs);
f20e7c1e 2548
f05da2b4 2549 memset(&filter_options, 0, sizeof(filter_options));
48308681
SB
2550 argc = parse_options(argc, argv, prefix, module_update_clone_options,
2551 git_submodule_helper_usage, 0);
f05da2b4 2552 suc.filter_options = &filter_options;
48308681
SB
2553
2554 if (update)
2555 if (parse_submodule_update_strategy(update, &suc.update) < 0)
2556 die(_("bad value for update parameter"));
2557
f05da2b4
JS
2558 if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0) {
2559 list_objects_filter_release(&filter_options);
48308681 2560 return 1;
f05da2b4 2561 }
48308681
SB
2562
2563 if (pathspec.nr)
2564 suc.warn_if_uninitialized = 1;
2565
f05da2b4
JS
2566 ret = update_submodules(&suc);
2567 list_objects_filter_release(&filter_options);
2568 return ret;
48308681
SB
2569}
2570
c51f8f94
AR
2571static int run_update_procedure(int argc, const char **argv, const char *prefix)
2572{
2573 int force = 0, quiet = 0, nofetch = 0, just_cloned = 0;
2574 char *prefixed_path, *update = NULL;
2575 struct update_data update_data = UPDATE_DATA_INIT;
2576
2577 struct option options[] = {
2578 OPT__QUIET(&quiet, N_("suppress output for update by rebase or merge")),
2579 OPT__FORCE(&force, N_("force checkout updates"), 0),
2580 OPT_BOOL('N', "no-fetch", &nofetch,
2581 N_("don't fetch new objects from the remote site")),
2582 OPT_BOOL(0, "just-cloned", &just_cloned,
2583 N_("overrides update mode in case the repository is a fresh clone")),
2584 OPT_INTEGER(0, "depth", &update_data.depth, N_("depth for shallow fetch")),
2585 OPT_STRING(0, "prefix", &prefix,
2586 N_("path"),
2587 N_("path into the working tree")),
2588 OPT_STRING(0, "update", &update,
2589 N_("string"),
2590 N_("rebase, merge, checkout or none")),
2591 OPT_STRING(0, "recursive-prefix", &update_data.recursive_prefix, N_("path"),
2592 N_("path into the working tree, across nested "
2593 "submodule boundaries")),
2594 OPT_CALLBACK_F(0, "oid", &update_data.oid, N_("sha1"),
2595 N_("SHA1 expected by superproject"), PARSE_OPT_NONEG,
2596 parse_opt_object_id),
c51f8f94
AR
2597 OPT_END()
2598 };
2599
2600 const char *const usage[] = {
2601 N_("git submodule--helper run-update-procedure [<options>] <path>"),
2602 NULL
2603 };
2604
2605 argc = parse_options(argc, argv, prefix, options, usage, 0);
2606
2607 if (argc != 1)
2608 usage_with_options(usage, options);
2609
2610 update_data.force = !!force;
2611 update_data.quiet = !!quiet;
2612 update_data.nofetch = !!nofetch;
2613 update_data.just_cloned = !!just_cloned;
2614 update_data.sm_path = argv[0];
2615
2616 if (update_data.recursive_prefix)
2617 prefixed_path = xstrfmt("%s%s", update_data.recursive_prefix, update_data.sm_path);
2618 else
2619 prefixed_path = xstrdup(update_data.sm_path);
2620
2621 update_data.displaypath = get_submodule_displaypath(prefixed_path, prefix);
2622
2623 determine_submodule_update_strategy(the_repository, update_data.just_cloned,
2624 update_data.sm_path, update,
2625 &update_data.update_strategy);
2626
2627 free(prefixed_path);
1a0b78c9 2628 return update_submodule2(&update_data);
c51f8f94
AR
2629}
2630
44431df0
SB
2631static int resolve_relative_path(int argc, const char **argv, const char *prefix)
2632{
2633 struct strbuf sb = STRBUF_INIT;
2634 if (argc != 3)
2de26ae1 2635 die("submodule--helper relative-path takes exactly 2 arguments, got %d", argc);
44431df0
SB
2636
2637 printf("%s", relative_path(argv[1], argv[2], &sb));
2638 strbuf_release(&sb);
2639 return 0;
2640}
2641
92bbe7cc
SB
2642static const char *remote_submodule_branch(const char *path)
2643{
2644 const struct submodule *sub;
177257cc
BW
2645 const char *branch = NULL;
2646 char *key;
92bbe7cc 2647
14228447 2648 sub = submodule_from_path(the_repository, null_oid(), path);
92bbe7cc
SB
2649 if (!sub)
2650 return NULL;
2651
177257cc 2652 key = xstrfmt("submodule.%s.branch", sub->name);
f1de981e 2653 if (repo_config_get_string_tmp(the_repository, key, &branch))
177257cc
BW
2654 branch = sub->branch;
2655 free(key);
2656
2657 if (!branch)
f0a96e8d 2658 return "HEAD";
92bbe7cc 2659
177257cc 2660 if (!strcmp(branch, ".")) {
744c040b 2661 const char *refname = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
4d7bc52b
SB
2662
2663 if (!refname)
2664 die(_("No such ref: %s"), "HEAD");
2665
2666 /* detached HEAD */
2667 if (!strcmp(refname, "HEAD"))
2668 die(_("Submodule (%s) branch configured to inherit "
2669 "branch from superproject, but the superproject "
2670 "is not on any branch"), sub->name);
2671
2672 if (!skip_prefix(refname, "refs/heads/", &refname))
2673 die(_("Expecting a full ref name, got %s"), refname);
2674 return refname;
2675 }
2676
177257cc 2677 return branch;
92bbe7cc
SB
2678}
2679
2680static int resolve_remote_submodule_branch(int argc, const char **argv,
2681 const char *prefix)
2682{
2683 const char *ret;
2684 struct strbuf sb = STRBUF_INIT;
2685 if (argc != 2)
2686 die("submodule--helper remote-branch takes exactly one arguments, got %d", argc);
2687
2688 ret = remote_submodule_branch(argv[1]);
2689 if (!ret)
2690 die("submodule %s doesn't exist", argv[1]);
2691
2692 printf("%s", ret);
2693 strbuf_release(&sb);
2694 return 0;
2695}
2696
93481a6b
BW
2697static int push_check(int argc, const char **argv, const char *prefix)
2698{
2699 struct remote *remote;
c7be7201
BW
2700 const char *superproject_head;
2701 char *head;
2702 int detached_head = 0;
2703 struct object_id head_oid;
93481a6b 2704
c7be7201
BW
2705 if (argc < 3)
2706 die("submodule--helper push-check requires at least 2 arguments");
2707
2708 /*
2709 * superproject's resolved head ref.
2710 * if HEAD then the superproject is in a detached head state, otherwise
2711 * it will be the resolved head ref.
2712 */
2713 superproject_head = argv[1];
2714 argv++;
2715 argc--;
2716 /* Get the submodule's head ref and determine if it is detached */
0f2dc722 2717 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
c7be7201
BW
2718 if (!head)
2719 die(_("Failed to resolve HEAD as a valid ref."));
2720 if (!strcmp(head, "HEAD"))
2721 detached_head = 1;
93481a6b
BW
2722
2723 /*
2724 * The remote must be configured.
2725 * This is to avoid pushing to the exact same URL as the parent.
2726 */
2727 remote = pushremote_get(argv[1]);
2728 if (!remote || remote->origin == REMOTE_UNCONFIGURED)
2729 die("remote '%s' not configured", argv[1]);
2730
2731 /* Check the refspec */
2732 if (argc > 2) {
9c8361b2 2733 int i;
93481a6b 2734 struct ref *local_refs = get_local_heads();
9c8361b2 2735 struct refspec refspec = REFSPEC_INIT_PUSH;
93481a6b 2736
9c8361b2
BW
2737 refspec_appendn(&refspec, argv + 2, argc - 2);
2738
2739 for (i = 0; i < refspec.nr; i++) {
2740 const struct refspec_item *rs = &refspec.items[i];
93481a6b
BW
2741
2742 if (rs->pattern || rs->matching)
2743 continue;
2744
c7be7201
BW
2745 /* LHS must match a single ref */
2746 switch (count_refspec_match(rs->src, local_refs, NULL)) {
2747 case 1:
2748 break;
2749 case 0:
2750 /*
2751 * If LHS matches 'HEAD' then we need to ensure
2752 * that it matches the same named branch
2753 * checked out in the superproject.
2754 */
2755 if (!strcmp(rs->src, "HEAD")) {
2756 if (!detached_head &&
2757 !strcmp(head, superproject_head))
2758 break;
2759 die("HEAD does not match the named branch in the superproject");
2760 }
1cf01a34 2761 /* fallthrough */
c7be7201 2762 default:
93481a6b
BW
2763 die("src refspec '%s' must name a ref",
2764 rs->src);
c7be7201 2765 }
93481a6b 2766 }
9c8361b2 2767 refspec_clear(&refspec);
93481a6b 2768 }
c7be7201 2769 free(head);
93481a6b
BW
2770
2771 return 0;
2772}
2773
74d4731d
SB
2774static int ensure_core_worktree(int argc, const char **argv, const char *prefix)
2775{
74d4731d 2776 const char *path;
55fe225d 2777 const char *cw;
74d4731d
SB
2778 struct repository subrepo;
2779
2780 if (argc != 2)
820a647e 2781 BUG("submodule--helper ensure-core-worktree <path>");
74d4731d
SB
2782
2783 path = argv[1];
2784
8eb8dcf9 2785 if (repo_submodule_init(&subrepo, the_repository, path, null_oid()))
74d4731d
SB
2786 die(_("could not get a repository handle for submodule '%s'"), path);
2787
55fe225d 2788 if (!repo_config_get_string_tmp(&subrepo, "core.worktree", &cw)) {
74d4731d
SB
2789 char *cfg_file, *abs_path;
2790 const char *rel_path;
2791 struct strbuf sb = STRBUF_INIT;
2792
2793 cfg_file = repo_git_path(&subrepo, "config");
2794
2795 abs_path = absolute_pathdup(path);
2796 rel_path = relative_path(abs_path, subrepo.gitdir, &sb);
2797
2798 git_config_set_in_file(cfg_file, "core.worktree", rel_path);
2799
2800 free(cfg_file);
2801 free(abs_path);
2802 strbuf_release(&sb);
2803 }
2804
2805 return 0;
2806}
2807
f6f85861
SB
2808static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
2809{
2810 int i;
2811 struct pathspec pathspec;
2812 struct module_list list = MODULE_LIST_INIT;
2813 unsigned flags = ABSORB_GITDIR_RECURSE_SUBMODULES;
2814
2815 struct option embed_gitdir_options[] = {
2816 OPT_STRING(0, "prefix", &prefix,
2817 N_("path"),
2818 N_("path into the working tree")),
2819 OPT_BIT(0, "--recursive", &flags, N_("recurse into submodules"),
2820 ABSORB_GITDIR_RECURSE_SUBMODULES),
2821 OPT_END()
2822 };
2823
2824 const char *const git_submodule_helper_usage[] = {
a282f5a9 2825 N_("git submodule--helper absorb-git-dirs [<options>] [<path>...]"),
f6f85861
SB
2826 NULL
2827 };
2828
2829 argc = parse_options(argc, argv, prefix, embed_gitdir_options,
2830 git_submodule_helper_usage, 0);
2831
f6f85861
SB
2832 if (module_list_compute(argc, argv, prefix, &pathspec, &list) < 0)
2833 return 1;
2834
2835 for (i = 0; i < list.nr; i++)
cf7a901a 2836 absorb_git_dir_into_superproject(list.entries[i]->name, flags);
f6f85861
SB
2837
2838 return 0;
2839}
2840
5c2bd8b7
BW
2841static int is_active(int argc, const char **argv, const char *prefix)
2842{
2843 if (argc != 2)
9af7ec30 2844 die("submodule--helper is-active takes exactly 1 argument");
5c2bd8b7 2845
627d9342 2846 return !is_submodule_active(the_repository, argv[1]);
5c2bd8b7
BW
2847}
2848
0383bbb9
JK
2849/*
2850 * Exit non-zero if any of the submodule names given on the command line is
2851 * invalid. If no names are given, filter stdin to print only valid names
2852 * (which is primarily intended for testing).
2853 */
2854static int check_name(int argc, const char **argv, const char *prefix)
2855{
2856 if (argc > 1) {
2857 while (*++argv) {
2858 if (check_submodule_name(*argv) < 0)
2859 return 1;
2860 }
2861 } else {
2862 struct strbuf buf = STRBUF_INIT;
2863 while (strbuf_getline(&buf, stdin) != EOF) {
2864 if (!check_submodule_name(buf.buf))
2865 printf("%s\n", buf.buf);
2866 }
2867 strbuf_release(&buf);
2868 }
2869 return 0;
2870}
2871
2502ffc0
AO
2872static int module_config(int argc, const char **argv, const char *prefix)
2873{
b5c259f2 2874 enum {
c89c4942
DL
2875 CHECK_WRITEABLE = 1,
2876 DO_UNSET = 2
b5c259f2
AO
2877 } command = 0;
2878
2879 struct option module_config_options[] = {
2880 OPT_CMDMODE(0, "check-writeable", &command,
2881 N_("check if it is safe to write to the .gitmodules file"),
2882 CHECK_WRITEABLE),
c89c4942
DL
2883 OPT_CMDMODE(0, "unset", &command,
2884 N_("unset the config in the .gitmodules file"),
2885 DO_UNSET),
b5c259f2
AO
2886 OPT_END()
2887 };
2888 const char *const git_submodule_helper_usage[] = {
c89c4942
DL
2889 N_("git submodule--helper config <name> [<value>]"),
2890 N_("git submodule--helper config --unset <name>"),
959d670d 2891 "git submodule--helper config --check-writeable",
b5c259f2
AO
2892 NULL
2893 };
2894
2895 argc = parse_options(argc, argv, prefix, module_config_options,
2896 git_submodule_helper_usage, PARSE_OPT_KEEP_ARGV0);
2897
2898 if (argc == 1 && command == CHECK_WRITEABLE)
2899 return is_writing_gitmodules_ok() ? 0 : -1;
2900
2502ffc0 2901 /* Equivalent to ACTION_GET in builtin/config.c */
c89c4942 2902 if (argc == 2 && command != DO_UNSET)
2502ffc0
AO
2903 return print_config_from_gitmodules(the_repository, argv[1]);
2904
2905 /* Equivalent to ACTION_SET in builtin/config.c */
c89c4942
DL
2906 if (argc == 3 || (argc == 2 && command == DO_UNSET)) {
2907 const char *value = (argc == 3) ? argv[2] : NULL;
2908
76e9bdc4
AO
2909 if (!is_writing_gitmodules_ok())
2910 die(_("please make sure that the .gitmodules file is in the working tree"));
2911
c89c4942 2912 return config_set_in_gitmodules_file_gently(argv[1], value);
76e9bdc4 2913 }
2502ffc0 2914
b5c259f2 2915 usage_with_options(git_submodule_helper_usage, module_config_options);
2502ffc0
AO
2916}
2917
6417cf9c
SS
2918static int module_set_url(int argc, const char **argv, const char *prefix)
2919{
2920 int quiet = 0;
2921 const char *newurl;
2922 const char *path;
2923 char *config_name;
2924
2925 struct option options[] = {
e73fe3dd 2926 OPT__QUIET(&quiet, N_("suppress output for setting url of a submodule")),
6417cf9c
SS
2927 OPT_END()
2928 };
2929 const char *const usage[] = {
2930 N_("git submodule--helper set-url [--quiet] <path> <newurl>"),
2931 NULL
2932 };
2933
2934 argc = parse_options(argc, argv, prefix, options, usage, 0);
2935
2936 if (argc != 2 || !(path = argv[0]) || !(newurl = argv[1]))
2937 usage_with_options(usage, options);
2938
2939 config_name = xstrfmt("submodule.%s.url", path);
2940
2941 config_set_in_gitmodules_file_gently(config_name, newurl);
2942 sync_submodule(path, prefix, quiet ? OPT_QUIET : 0);
2943
2944 free(config_name);
2945
2946 return 0;
2947}
2948
2964d6e5
SS
2949static int module_set_branch(int argc, const char **argv, const char *prefix)
2950{
2951 int opt_default = 0, ret;
2952 const char *opt_branch = NULL;
2953 const char *path;
2954 char *config_name;
2955
2956 /*
2957 * We accept the `quiet` option for uniformity across subcommands,
2958 * though there is nothing to make less verbose in this subcommand.
2959 */
2960 struct option options[] = {
2961 OPT_NOOP_NOARG('q', "quiet"),
2962 OPT_BOOL('d', "default", &opt_default,
2963 N_("set the default tracking branch to master")),
2964 OPT_STRING('b', "branch", &opt_branch, N_("branch"),
2965 N_("set the default tracking branch")),
2966 OPT_END()
2967 };
2968 const char *const usage[] = {
2969 N_("git submodule--helper set-branch [-q|--quiet] (-d|--default) <path>"),
2970 N_("git submodule--helper set-branch [-q|--quiet] (-b|--branch) <branch> <path>"),
2971 NULL
2972 };
2973
2974 argc = parse_options(argc, argv, prefix, options, usage, 0);
2975
2976 if (!opt_branch && !opt_default)
2977 die(_("--branch or --default required"));
2978
2979 if (opt_branch && opt_default)
43ea635c 2980 die(_("options '%s' and '%s' cannot be used together"), "--branch", "--default");
2964d6e5
SS
2981
2982 if (argc != 1 || !(path = argv[0]))
2983 usage_with_options(usage, options);
2984
2985 config_name = xstrfmt("submodule.%s.branch", path);
2986 ret = config_set_in_gitmodules_file_gently(config_name, opt_branch);
2987
2988 free(config_name);
2989 return !!ret;
2990}
2991
961b130d
GC
2992static int module_create_branch(int argc, const char **argv, const char *prefix)
2993{
2994 enum branch_track track;
2995 int quiet = 0, force = 0, reflog = 0, dry_run = 0;
2996
2997 struct option options[] = {
2998 OPT__QUIET(&quiet, N_("print only error messages")),
2999 OPT__FORCE(&force, N_("force creation"), 0),
3000 OPT_BOOL(0, "create-reflog", &reflog,
3001 N_("create the branch's reflog")),
3002 OPT_SET_INT('t', "track", &track,
3003 N_("set up tracking mode (see git-pull(1))"),
3004 BRANCH_TRACK_EXPLICIT),
3005 OPT__DRY_RUN(&dry_run,
3006 N_("show whether the branch would be created")),
3007 OPT_END()
3008 };
3009 const char *const usage[] = {
3010 N_("git submodule--helper create-branch [-f|--force] [--create-reflog] [-q|--quiet] [-t|--track] [-n|--dry-run] <name> <start_oid> <start_name>"),
3011 NULL
3012 };
3013
3014 git_config(git_default_config, NULL);
3015 track = git_branch_track;
3016 argc = parse_options(argc, argv, prefix, options, usage, 0);
3017
3018 if (argc != 3)
3019 usage_with_options(usage, options);
3020
3021 if (!quiet && !dry_run)
3022 printf_ln(_("creating branch '%s'"), argv[0]);
3023
3024 create_branches_recursively(the_repository, argv[0], argv[1], argv[2],
3025 force, reflog, quiet, track, dry_run);
3026 return 0;
3027}
1a0b78c9
GC
3028
3029/* NEEDSWORK: this is a temporary name until we delete update_submodule() */
3030static int update_submodule2(struct update_data *update_data)
3031{
e4419665
GC
3032 if (update_data->just_cloned)
3033 oidcpy(&update_data->suboid, null_oid());
3034 else if (resolve_gitlink_ref(update_data->sm_path, "HEAD", &update_data->suboid))
3035 die(_("Unable to find current revision in submodule path '%s'"),
3036 update_data->displaypath);
3037
1a0b78c9
GC
3038 if (!oideq(&update_data->oid, &update_data->suboid) || update_data->force)
3039 return do_run_update_procedure(update_data);
3040
3041 return 3;
3042}
3043
8c8195e9
AR
3044struct add_data {
3045 const char *prefix;
3046 const char *branch;
3047 const char *reference_path;
a6226fd7 3048 char *sm_path;
8c8195e9
AR
3049 const char *sm_name;
3050 const char *repo;
3051 const char *realrepo;
3052 int depth;
3053 unsigned int force: 1;
3054 unsigned int quiet: 1;
3055 unsigned int progress: 1;
3056 unsigned int dissociate: 1;
3057};
3058#define ADD_DATA_INIT { .depth = -1 }
3059
6b615dbe 3060static void append_fetch_remotes(struct strbuf *msg, const char *git_dir_path)
8c8195e9
AR
3061{
3062 struct child_process cp_remote = CHILD_PROCESS_INIT;
3063 struct strbuf sb_remote_out = STRBUF_INIT;
3064
3065 cp_remote.git_cmd = 1;
3066 strvec_pushf(&cp_remote.env_array,
3067 "GIT_DIR=%s", git_dir_path);
3068 strvec_push(&cp_remote.env_array, "GIT_WORK_TREE=.");
3069 strvec_pushl(&cp_remote.args, "remote", "-v", NULL);
3070 if (!capture_command(&cp_remote, &sb_remote_out, 0)) {
3071 char *next_line;
3072 char *line = sb_remote_out.buf;
3073 while ((next_line = strchr(line, '\n')) != NULL) {
3074 size_t len = next_line - line;
3075 if (strip_suffix_mem(line, &len, " (fetch)"))
c21fb467 3076 strbuf_addf(msg, " %.*s\n", (int)len, line);
8c8195e9
AR
3077 line = next_line + 1;
3078 }
3079 }
3080
3081 strbuf_release(&sb_remote_out);
3082}
3083
3084static int add_submodule(const struct add_data *add_data)
3085{
3086 char *submod_gitdir_path;
3087 struct module_clone_data clone_data = MODULE_CLONE_DATA_INIT;
3088
3089 /* perhaps the path already exists and is already a git repo, else clone it */
3090 if (is_directory(add_data->sm_path)) {
3091 struct strbuf sm_path = STRBUF_INIT;
3092 strbuf_addstr(&sm_path, add_data->sm_path);
3093 submod_gitdir_path = xstrfmt("%s/.git", add_data->sm_path);
3094 if (is_nonbare_repository_dir(&sm_path))
3095 printf(_("Adding existing repo at '%s' to the index\n"),
3096 add_data->sm_path);
3097 else
3098 die(_("'%s' already exists and is not a valid git repo"),
3099 add_data->sm_path);
3100 strbuf_release(&sm_path);
3101 free(submod_gitdir_path);
3102 } else {
3103 struct child_process cp = CHILD_PROCESS_INIT;
3104 submod_gitdir_path = xstrfmt(".git/modules/%s", add_data->sm_name);
3105
3106 if (is_directory(submod_gitdir_path)) {
3107 if (!add_data->force) {
c21fb467
KS
3108 struct strbuf msg = STRBUF_INIT;
3109 char *die_msg;
3110
3111 strbuf_addf(&msg, _("A git directory for '%s' is found "
3112 "locally with remote(s):\n"),
3113 add_data->sm_name);
3114
6b615dbe 3115 append_fetch_remotes(&msg, submod_gitdir_path);
8c8195e9 3116 free(submod_gitdir_path);
c21fb467
KS
3117
3118 strbuf_addf(&msg, _("If you want to reuse this local git "
3119 "directory instead of cloning again from\n"
3120 " %s\n"
3121 "use the '--force' option. If the local git "
3122 "directory is not the correct repo\n"
3123 "or you are unsure what this means choose "
3124 "another name with the '--name' option."),
3125 add_data->realrepo);
3126
3127 die_msg = strbuf_detach(&msg, NULL);
3128 die("%s", die_msg);
8c8195e9
AR
3129 } else {
3130 printf(_("Reactivating local git directory for "
3131 "submodule '%s'\n"), add_data->sm_name);
3132 }
3133 }
3134 free(submod_gitdir_path);
3135
3136 clone_data.prefix = add_data->prefix;
3137 clone_data.path = add_data->sm_path;
3138 clone_data.name = add_data->sm_name;
3139 clone_data.url = add_data->realrepo;
3140 clone_data.quiet = add_data->quiet;
3141 clone_data.progress = add_data->progress;
3142 if (add_data->reference_path)
3143 string_list_append(&clone_data.reference,
3144 xstrdup(add_data->reference_path));
3145 clone_data.dissociate = add_data->dissociate;
3146 if (add_data->depth >= 0)
3147 clone_data.depth = xstrfmt("%d", add_data->depth);
3148
3149 if (clone_submodule(&clone_data))
3150 return -1;
3151
3152 prepare_submodule_repo_env(&cp.env_array);
3153 cp.git_cmd = 1;
3154 cp.dir = add_data->sm_path;
94b7f156
EN
3155 /*
3156 * NOTE: we only get here if add_data->force is true, so
3157 * passing --force to checkout is reasonable.
3158 */
8c8195e9
AR
3159 strvec_pushl(&cp.args, "checkout", "-f", "-q", NULL);
3160
3161 if (add_data->branch) {
3162 strvec_pushl(&cp.args, "-B", add_data->branch, NULL);
3163 strvec_pushf(&cp.args, "origin/%s", add_data->branch);
3164 }
3165
3166 if (run_command(&cp))
3167 die(_("unable to checkout submodule '%s'"), add_data->sm_path);
3168 }
3169 return 0;
3170}
3171
a452128a
AR
3172static int config_submodule_in_gitmodules(const char *name, const char *var, const char *value)
3173{
3174 char *key;
3175 int ret;
3176
3177 if (!is_writing_gitmodules_ok())
3178 die(_("please make sure that the .gitmodules file is in the working tree"));
3179
3180 key = xstrfmt("submodule.%s.%s", name, var);
3181 ret = config_set_in_gitmodules_file_gently(key, value);
3182 free(key);
3183
3184 return ret;
3185}
3186
3187static void configure_added_submodule(struct add_data *add_data)
3188{
3189 char *key;
3190 char *val = NULL;
3191 struct child_process add_submod = CHILD_PROCESS_INIT;
3192 struct child_process add_gitmodules = CHILD_PROCESS_INIT;
3193
3194 key = xstrfmt("submodule.%s.url", add_data->sm_name);
3195 git_config_set_gently(key, add_data->realrepo);
3196 free(key);
3197
3198 add_submod.git_cmd = 1;
3199 strvec_pushl(&add_submod.args, "add",
3200 "--no-warn-embedded-repo", NULL);
3201 if (add_data->force)
3202 strvec_push(&add_submod.args, "--force");
3203 strvec_pushl(&add_submod.args, "--", add_data->sm_path, NULL);
3204
3205 if (run_command(&add_submod))
3206 die(_("Failed to add submodule '%s'"), add_data->sm_path);
3207
3208 if (config_submodule_in_gitmodules(add_data->sm_name, "path", add_data->sm_path) ||
3209 config_submodule_in_gitmodules(add_data->sm_name, "url", add_data->repo))
3210 die(_("Failed to register submodule '%s'"), add_data->sm_path);
3211
3212 if (add_data->branch) {
3213 if (config_submodule_in_gitmodules(add_data->sm_name,
3214 "branch", add_data->branch))
3215 die(_("Failed to register submodule '%s'"), add_data->sm_path);
3216 }
3217
3218 add_gitmodules.git_cmd = 1;
3219 strvec_pushl(&add_gitmodules.args,
3220 "add", "--force", "--", ".gitmodules", NULL);
3221
3222 if (run_command(&add_gitmodules))
3223 die(_("Failed to register submodule '%s'"), add_data->sm_path);
3224
3225 /*
3226 * NEEDSWORK: In a multi-working-tree world this needs to be
3227 * set in the per-worktree config.
3228 */
3229 /*
3230 * NEEDSWORK: In the longer run, we need to get rid of this
3231 * pattern of querying "submodule.active" before calling
3232 * is_submodule_active(), since that function needs to find
3233 * out the value of "submodule.active" again anyway.
3234 */
3235 if (!git_config_get_string("submodule.active", &val) && val) {
3236 /*
3237 * If the submodule being added isn't already covered by the
3238 * current configured pathspec, set the submodule's active flag
3239 */
3240 if (!is_submodule_active(the_repository, add_data->sm_path)) {
3241 key = xstrfmt("submodule.%s.active", add_data->sm_name);
3242 git_config_set_gently(key, "true");
3243 free(key);
3244 }
3245 } else {
3246 key = xstrfmt("submodule.%s.active", add_data->sm_name);
3247 git_config_set_gently(key, "true");
3248 free(key);
3249 }
3250}
3251
a6226fd7 3252static void die_on_index_match(const char *path, int force)
a452128a 3253{
a6226fd7
AR
3254 struct pathspec ps;
3255 const char *args[] = { path, NULL };
3256 parse_pathspec(&ps, 0, PATHSPEC_PREFER_CWD, NULL, args);
3257
3258 if (read_cache_preload(NULL) < 0)
3259 die(_("index file corrupt"));
3260
3261 if (ps.nr) {
3262 int i;
3263 char *ps_matched = xcalloc(ps.nr, 1);
3264
3265 /* TODO: audit for interaction with sparse-index. */
3266 ensure_full_index(&the_index);
3267
3268 /*
3269 * Since there is only one pathspec, we just need
3270 * need to check ps_matched[0] to know if a cache
3271 * entry matched.
3272 */
3273 for (i = 0; i < active_nr; i++) {
3274 ce_path_match(&the_index, active_cache[i], &ps,
3275 ps_matched);
3276
3277 if (ps_matched[0]) {
3278 if (!force)
3279 die(_("'%s' already exists in the index"),
3280 path);
3281 if (!S_ISGITLINK(active_cache[i]->ce_mode))
3282 die(_("'%s' already exists in the index "
3283 "and is not a submodule"), path);
3284 break;
3285 }
3286 }
3287 free(ps_matched);
3288 }
c270b055 3289 clear_pathspec(&ps);
a6226fd7
AR
3290}
3291
3292static void die_on_repo_without_commits(const char *path)
3293{
3294 struct strbuf sb = STRBUF_INIT;
3295 strbuf_addstr(&sb, path);
3296 if (is_nonbare_repository_dir(&sb)) {
3297 struct object_id oid;
3298 if (resolve_gitlink_ref(path, "HEAD", &oid) < 0)
3299 die(_("'%s' does not have a commit checked out"), path);
3300 }
c270b055 3301 strbuf_release(&sb);
a6226fd7
AR
3302}
3303
3304static int module_add(int argc, const char **argv, const char *prefix)
3305{
3306 int force = 0, quiet = 0, progress = 0, dissociate = 0;
a452128a
AR
3307 struct add_data add_data = ADD_DATA_INIT;
3308
3309 struct option options[] = {
a6226fd7
AR
3310 OPT_STRING('b', "branch", &add_data.branch, N_("branch"),
3311 N_("branch of repository to add as submodule")),
a452128a
AR
3312 OPT__FORCE(&force, N_("allow adding an otherwise ignored submodule path"),
3313 PARSE_OPT_NOCOMPLETE),
a6226fd7
AR
3314 OPT__QUIET(&quiet, N_("print only error messages")),
3315 OPT_BOOL(0, "progress", &progress, N_("force cloning progress")),
3316 OPT_STRING(0, "reference", &add_data.reference_path, N_("repository"),
3317 N_("reference repository")),
3318 OPT_BOOL(0, "dissociate", &dissociate, N_("borrow the objects from reference repositories")),
3319 OPT_STRING(0, "name", &add_data.sm_name, N_("name"),
3320 N_("sets the submodule’s name to the given string "
3321 "instead of defaulting to its path")),
3322 OPT_INTEGER(0, "depth", &add_data.depth, N_("depth for shallow clones")),
a452128a
AR
3323 OPT_END()
3324 };
3325
3326 const char *const usage[] = {
a6226fd7 3327 N_("git submodule--helper add [<options>] [--] <repository> [<path>]"),
a452128a
AR
3328 NULL
3329 };
3330
3331 argc = parse_options(argc, argv, prefix, options, usage, 0);
3332
a6226fd7
AR
3333 if (!is_writing_gitmodules_ok())
3334 die(_("please make sure that the .gitmodules file is in the working tree"));
3335
3336 if (prefix && *prefix &&
3337 add_data.reference_path && !is_absolute_path(add_data.reference_path))
3338 add_data.reference_path = xstrfmt("%s%s", prefix, add_data.reference_path);
3339
3340 if (argc == 0 || argc > 2)
a452128a
AR
3341 usage_with_options(usage, options);
3342
a6226fd7
AR
3343 add_data.repo = argv[0];
3344 if (argc == 1)
3345 add_data.sm_path = git_url_basename(add_data.repo, 0, 0);
3346 else
3347 add_data.sm_path = xstrdup(argv[1]);
3348
3349 if (prefix && *prefix && !is_absolute_path(add_data.sm_path))
3350 add_data.sm_path = xstrfmt("%s%s", prefix, add_data.sm_path);
3351
3352 if (starts_with_dot_dot_slash(add_data.repo) ||
3353 starts_with_dot_slash(add_data.repo)) {
3354 if (prefix)
3355 die(_("Relative path can only be used from the toplevel "
3356 "of the working tree"));
3357
3358 /* dereference source url relative to parent's url */
de0fcbe0 3359 add_data.realrepo = resolve_relative_url(add_data.repo, NULL, 1);
a6226fd7
AR
3360 } else if (is_dir_sep(add_data.repo[0]) || strchr(add_data.repo, ':')) {
3361 add_data.realrepo = add_data.repo;
3362 } else {
3363 die(_("repo URL: '%s' must be absolute or begin with ./|../"),
3364 add_data.repo);
3365 }
3366
3367 /*
3368 * normalize path:
3369 * multiple //; leading ./; /./; /../;
3370 */
3371 normalize_path_copy(add_data.sm_path, add_data.sm_path);
3372 strip_dir_trailing_slashes(add_data.sm_path);
3373
3374 die_on_index_match(add_data.sm_path, force);
3375 die_on_repo_without_commits(add_data.sm_path);
3376
3377 if (!force) {
3378 int exit_code = -1;
3379 struct strbuf sb = STRBUF_INIT;
3380 struct child_process cp = CHILD_PROCESS_INIT;
3381 cp.git_cmd = 1;
3382 cp.no_stdout = 1;
3383 strvec_pushl(&cp.args, "add", "--dry-run", "--ignore-missing",
3384 "--no-warn-embedded-repo", add_data.sm_path, NULL);
3385 if ((exit_code = pipe_command(&cp, NULL, 0, NULL, 0, &sb, 0))) {
3386 strbuf_complete_line(&sb);
3387 fputs(sb.buf, stderr);
3388 free(add_data.sm_path);
3389 return exit_code;
3390 }
3391 strbuf_release(&sb);
3392 }
3393
3394 if(!add_data.sm_name)
3395 add_data.sm_name = add_data.sm_path;
3396
3397 if (check_submodule_name(add_data.sm_name))
3398 die(_("'%s' is not a valid submodule name"), add_data.sm_name);
3399
3400 add_data.prefix = prefix;
a452128a 3401 add_data.force = !!force;
a6226fd7
AR
3402 add_data.quiet = !!quiet;
3403 add_data.progress = !!progress;
3404 add_data.dissociate = !!dissociate;
3405
3406 if (add_submodule(&add_data)) {
3407 free(add_data.sm_path);
3408 return 1;
3409 }
a452128a 3410 configure_added_submodule(&add_data);
a6226fd7 3411 free(add_data.sm_path);
a452128a
AR
3412
3413 return 0;
3414}
3415
89c86265
SB
3416#define SUPPORT_SUPER_PREFIX (1<<0)
3417
74703a1e
SB
3418struct cmd_struct {
3419 const char *cmd;
3420 int (*fn)(int, const char **, const char *);
89c86265 3421 unsigned option;
74703a1e
SB
3422};
3423
3424static struct cmd_struct commands[] = {
89c86265
SB
3425 {"list", module_list, 0},
3426 {"name", module_name, 0},
3427 {"clone", module_clone, 0},
a6226fd7 3428 {"add", module_add, SUPPORT_SUPER_PREFIX},
89c86265 3429 {"update-clone", update_clone, 0},
c51f8f94 3430 {"run-update-procedure", run_update_procedure, 0},
74d4731d 3431 {"ensure-core-worktree", ensure_core_worktree, 0},
89c86265 3432 {"relative-path", resolve_relative_path, 0},
89c86265 3433 {"resolve-relative-url-test", resolve_relative_url_test, 0},
fc1b9243 3434 {"foreach", module_foreach, SUPPORT_SUPER_PREFIX},
6e7c14e6 3435 {"init", module_init, SUPPORT_SUPER_PREFIX},
a9f8a375 3436 {"status", module_status, SUPPORT_SUPER_PREFIX},
13424764
PC
3437 {"print-default-remote", print_default_remote, 0},
3438 {"sync", module_sync, SUPPORT_SUPER_PREFIX},
2e612731 3439 {"deinit", module_deinit, 0},
e83e3333 3440 {"summary", module_summary, SUPPORT_SUPER_PREFIX},
89c86265 3441 {"remote-branch", resolve_remote_submodule_branch, 0},
93481a6b 3442 {"push-check", push_check, 0},
f6f85861 3443 {"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
5c2bd8b7 3444 {"is-active", is_active, 0},
0383bbb9 3445 {"check-name", check_name, 0},
2502ffc0 3446 {"config", module_config, 0},
6417cf9c 3447 {"set-url", module_set_url, 0},
2964d6e5 3448 {"set-branch", module_set_branch, 0},
961b130d 3449 {"create-branch", module_create_branch, 0},
74703a1e
SB
3450};
3451
3452int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
3453{
3454 int i;
f0994fa8
JK
3455 if (argc < 2 || !strcmp(argv[1], "-h"))
3456 usage("git submodule--helper <command>");
74703a1e 3457
89c86265
SB
3458 for (i = 0; i < ARRAY_SIZE(commands); i++) {
3459 if (!strcmp(argv[1], commands[i].cmd)) {
3460 if (get_super_prefix() &&
3461 !(commands[i].option & SUPPORT_SUPER_PREFIX))
3462 die(_("%s doesn't support --super-prefix"),
3463 commands[i].cmd);
74703a1e 3464 return commands[i].fn(argc - 1, argv + 1, prefix);
89c86265
SB
3465 }
3466 }
74703a1e 3467
cdc04b65 3468 die(_("'%s' is not a valid submodule--helper "
74703a1e
SB
3469 "subcommand"), argv[1]);
3470}