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