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