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