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