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