Implement line-history search (git log -L)
[git] / submodule.c
1 #include "cache.h"
2 #include "submodule.h"
3 #include "dir.h"
4 #include "diff.h"
5 #include "commit.h"
6 #include "revision.h"
7 #include "run-command.h"
8 #include "diffcore.h"
9 #include "refs.h"
10 #include "string-list.h"
11 #include "sha1-array.h"
12 #include "argv-array.h"
13
14 static struct string_list config_name_for_path;
15 static struct string_list config_fetch_recurse_submodules_for_name;
16 static struct string_list config_ignore_for_name;
17 static int config_fetch_recurse_submodules = RECURSE_SUBMODULES_ON_DEMAND;
18 static struct string_list changed_submodule_paths;
19 static int initialized_fetch_ref_tips;
20 static struct sha1_array ref_tips_before_fetch;
21 static struct sha1_array ref_tips_after_fetch;
22
23 /*
24  * The following flag is set if the .gitmodules file is unmerged. We then
25  * disable recursion for all submodules where .git/config doesn't have a
26  * matching config entry because we can't guess what might be configured in
27  * .gitmodules unless the user resolves the conflict. When a command line
28  * option is given (which always overrides configuration) this flag will be
29  * ignored.
30  */
31 static int gitmodules_is_unmerged;
32
33 static int add_submodule_odb(const char *path)
34 {
35         struct strbuf objects_directory = STRBUF_INIT;
36         struct alternate_object_database *alt_odb;
37         int ret = 0;
38         const char *git_dir;
39
40         strbuf_addf(&objects_directory, "%s/.git", path);
41         git_dir = read_gitfile(objects_directory.buf);
42         if (git_dir) {
43                 strbuf_reset(&objects_directory);
44                 strbuf_addstr(&objects_directory, git_dir);
45         }
46         strbuf_addstr(&objects_directory, "/objects/");
47         if (!is_directory(objects_directory.buf)) {
48                 ret = -1;
49                 goto done;
50         }
51         /* avoid adding it twice */
52         for (alt_odb = alt_odb_list; alt_odb; alt_odb = alt_odb->next)
53                 if (alt_odb->name - alt_odb->base == objects_directory.len &&
54                                 !strncmp(alt_odb->base, objects_directory.buf,
55                                         objects_directory.len))
56                         goto done;
57
58         alt_odb = xmalloc(objects_directory.len + 42 + sizeof(*alt_odb));
59         alt_odb->next = alt_odb_list;
60         strcpy(alt_odb->base, objects_directory.buf);
61         alt_odb->name = alt_odb->base + objects_directory.len;
62         alt_odb->name[2] = '/';
63         alt_odb->name[40] = '\0';
64         alt_odb->name[41] = '\0';
65         alt_odb_list = alt_odb;
66
67         /* add possible alternates from the submodule */
68         read_info_alternates(objects_directory.buf, 0);
69         prepare_alt_odb();
70 done:
71         strbuf_release(&objects_directory);
72         return ret;
73 }
74
75 void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
76                                              const char *path)
77 {
78         struct string_list_item *path_option, *ignore_option;
79         path_option = unsorted_string_list_lookup(&config_name_for_path, path);
80         if (path_option) {
81                 ignore_option = unsorted_string_list_lookup(&config_ignore_for_name, path_option->util);
82                 if (ignore_option)
83                         handle_ignore_submodules_arg(diffopt, ignore_option->util);
84                 else if (gitmodules_is_unmerged)
85                         DIFF_OPT_SET(diffopt, IGNORE_SUBMODULES);
86         }
87 }
88
89 int submodule_config(const char *var, const char *value, void *cb)
90 {
91         if (!prefixcmp(var, "submodule."))
92                 return parse_submodule_config_option(var, value);
93         else if (!strcmp(var, "fetch.recursesubmodules")) {
94                 config_fetch_recurse_submodules = parse_fetch_recurse_submodules_arg(var, value);
95                 return 0;
96         }
97         return 0;
98 }
99
100 void gitmodules_config(void)
101 {
102         const char *work_tree = get_git_work_tree();
103         if (work_tree) {
104                 struct strbuf gitmodules_path = STRBUF_INIT;
105                 int pos;
106                 strbuf_addstr(&gitmodules_path, work_tree);
107                 strbuf_addstr(&gitmodules_path, "/.gitmodules");
108                 if (read_cache() < 0)
109                         die("index file corrupt");
110                 pos = cache_name_pos(".gitmodules", 11);
111                 if (pos < 0) { /* .gitmodules not found or isn't merged */
112                         pos = -1 - pos;
113                         if (active_nr > pos) {  /* there is a .gitmodules */
114                                 const struct cache_entry *ce = active_cache[pos];
115                                 if (ce_namelen(ce) == 11 &&
116                                     !memcmp(ce->name, ".gitmodules", 11))
117                                         gitmodules_is_unmerged = 1;
118                         }
119                 }
120
121                 if (!gitmodules_is_unmerged)
122                         git_config_from_file(submodule_config, gitmodules_path.buf, NULL);
123                 strbuf_release(&gitmodules_path);
124         }
125 }
126
127 int parse_submodule_config_option(const char *var, const char *value)
128 {
129         struct string_list_item *config;
130         const char *name, *key;
131         int namelen;
132
133         if (parse_config_key(var, "submodule", &name, &namelen, &key) < 0 || !name)
134                 return 0;
135
136         if (!strcmp(key, "path")) {
137                 config = unsorted_string_list_lookup(&config_name_for_path, value);
138                 if (config)
139                         free(config->util);
140                 else
141                         config = string_list_append(&config_name_for_path, xstrdup(value));
142                 config->util = xmemdupz(name, namelen);
143         } else if (!strcmp(key, "fetchrecursesubmodules")) {
144                 char *name_cstr = xmemdupz(name, namelen);
145                 config = unsorted_string_list_lookup(&config_fetch_recurse_submodules_for_name, name_cstr);
146                 if (!config)
147                         config = string_list_append(&config_fetch_recurse_submodules_for_name, name_cstr);
148                 else
149                         free(name_cstr);
150                 config->util = (void *)(intptr_t)parse_fetch_recurse_submodules_arg(var, value);
151         } else if (!strcmp(key, "ignore")) {
152                 char *name_cstr;
153
154                 if (strcmp(value, "untracked") && strcmp(value, "dirty") &&
155                     strcmp(value, "all") && strcmp(value, "none")) {
156                         warning("Invalid parameter \"%s\" for config option \"submodule.%s.ignore\"", value, var);
157                         return 0;
158                 }
159
160                 name_cstr = xmemdupz(name, namelen);
161                 config = unsorted_string_list_lookup(&config_ignore_for_name, name_cstr);
162                 if (config) {
163                         free(config->util);
164                         free(name_cstr);
165                 } else
166                         config = string_list_append(&config_ignore_for_name, name_cstr);
167                 config->util = xstrdup(value);
168                 return 0;
169         }
170         return 0;
171 }
172
173 void handle_ignore_submodules_arg(struct diff_options *diffopt,
174                                   const char *arg)
175 {
176         DIFF_OPT_CLR(diffopt, IGNORE_SUBMODULES);
177         DIFF_OPT_CLR(diffopt, IGNORE_UNTRACKED_IN_SUBMODULES);
178         DIFF_OPT_CLR(diffopt, IGNORE_DIRTY_SUBMODULES);
179
180         if (!strcmp(arg, "all"))
181                 DIFF_OPT_SET(diffopt, IGNORE_SUBMODULES);
182         else if (!strcmp(arg, "untracked"))
183                 DIFF_OPT_SET(diffopt, IGNORE_UNTRACKED_IN_SUBMODULES);
184         else if (!strcmp(arg, "dirty"))
185                 DIFF_OPT_SET(diffopt, IGNORE_DIRTY_SUBMODULES);
186         else if (strcmp(arg, "none"))
187                 die("bad --ignore-submodules argument: %s", arg);
188 }
189
190 static int prepare_submodule_summary(struct rev_info *rev, const char *path,
191                 struct commit *left, struct commit *right,
192                 int *fast_forward, int *fast_backward)
193 {
194         struct commit_list *merge_bases, *list;
195
196         init_revisions(rev, NULL);
197         setup_revisions(0, NULL, rev, NULL);
198         rev->left_right = 1;
199         rev->first_parent_only = 1;
200         left->object.flags |= SYMMETRIC_LEFT;
201         add_pending_object(rev, &left->object, path);
202         add_pending_object(rev, &right->object, path);
203         merge_bases = get_merge_bases(left, right, 1);
204         if (merge_bases) {
205                 if (merge_bases->item == left)
206                         *fast_forward = 1;
207                 else if (merge_bases->item == right)
208                         *fast_backward = 1;
209         }
210         for (list = merge_bases; list; list = list->next) {
211                 list->item->object.flags |= UNINTERESTING;
212                 add_pending_object(rev, &list->item->object,
213                         sha1_to_hex(list->item->object.sha1));
214         }
215         return prepare_revision_walk(rev);
216 }
217
218 static void print_submodule_summary(struct rev_info *rev, FILE *f,
219                 const char *del, const char *add, const char *reset)
220 {
221         static const char format[] = "  %m %s";
222         struct strbuf sb = STRBUF_INIT;
223         struct commit *commit;
224
225         while ((commit = get_revision(rev))) {
226                 struct pretty_print_context ctx = {0};
227                 ctx.date_mode = rev->date_mode;
228                 strbuf_setlen(&sb, 0);
229                 if (commit->object.flags & SYMMETRIC_LEFT) {
230                         if (del)
231                                 strbuf_addstr(&sb, del);
232                 }
233                 else if (add)
234                         strbuf_addstr(&sb, add);
235                 format_commit_message(commit, format, &sb, &ctx);
236                 if (reset)
237                         strbuf_addstr(&sb, reset);
238                 strbuf_addch(&sb, '\n');
239                 fprintf(f, "%s", sb.buf);
240         }
241         strbuf_release(&sb);
242 }
243
244 int parse_fetch_recurse_submodules_arg(const char *opt, const char *arg)
245 {
246         switch (git_config_maybe_bool(opt, arg)) {
247         case 1:
248                 return RECURSE_SUBMODULES_ON;
249         case 0:
250                 return RECURSE_SUBMODULES_OFF;
251         default:
252                 if (!strcmp(arg, "on-demand"))
253                         return RECURSE_SUBMODULES_ON_DEMAND;
254                 die("bad %s argument: %s", opt, arg);
255         }
256 }
257
258 void show_submodule_summary(FILE *f, const char *path,
259                 unsigned char one[20], unsigned char two[20],
260                 unsigned dirty_submodule, const char *meta,
261                 const char *del, const char *add, const char *reset)
262 {
263         struct rev_info rev;
264         struct commit *left = left, *right = right;
265         const char *message = NULL;
266         struct strbuf sb = STRBUF_INIT;
267         int fast_forward = 0, fast_backward = 0;
268
269         if (is_null_sha1(two))
270                 message = "(submodule deleted)";
271         else if (add_submodule_odb(path))
272                 message = "(not checked out)";
273         else if (is_null_sha1(one))
274                 message = "(new submodule)";
275         else if (!(left = lookup_commit_reference(one)) ||
276                  !(right = lookup_commit_reference(two)))
277                 message = "(commits not present)";
278
279         if (!message &&
280             prepare_submodule_summary(&rev, path, left, right,
281                                         &fast_forward, &fast_backward))
282                 message = "(revision walker failed)";
283
284         if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
285                 fprintf(f, "Submodule %s contains untracked content\n", path);
286         if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
287                 fprintf(f, "Submodule %s contains modified content\n", path);
288
289         if (!hashcmp(one, two)) {
290                 strbuf_release(&sb);
291                 return;
292         }
293
294         strbuf_addf(&sb, "%sSubmodule %s %s..", meta, path,
295                         find_unique_abbrev(one, DEFAULT_ABBREV));
296         if (!fast_backward && !fast_forward)
297                 strbuf_addch(&sb, '.');
298         strbuf_addf(&sb, "%s", find_unique_abbrev(two, DEFAULT_ABBREV));
299         if (message)
300                 strbuf_addf(&sb, " %s%s\n", message, reset);
301         else
302                 strbuf_addf(&sb, "%s:%s\n", fast_backward ? " (rewind)" : "", reset);
303         fwrite(sb.buf, sb.len, 1, f);
304
305         if (!message) {
306                 print_submodule_summary(&rev, f, del, add, reset);
307                 clear_commit_marks(left, ~0);
308                 clear_commit_marks(right, ~0);
309         }
310
311         strbuf_release(&sb);
312 }
313
314 void set_config_fetch_recurse_submodules(int value)
315 {
316         config_fetch_recurse_submodules = value;
317 }
318
319 static int has_remote(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
320 {
321         return 1;
322 }
323
324 static int submodule_needs_pushing(const char *path, const unsigned char sha1[20])
325 {
326         if (add_submodule_odb(path) || !lookup_commit_reference(sha1))
327                 return 0;
328
329         if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
330                 struct child_process cp;
331                 const char *argv[] = {"rev-list", NULL, "--not", "--remotes", "-n", "1" , NULL};
332                 struct strbuf buf = STRBUF_INIT;
333                 int needs_pushing = 0;
334
335                 argv[1] = sha1_to_hex(sha1);
336                 memset(&cp, 0, sizeof(cp));
337                 cp.argv = argv;
338                 cp.env = local_repo_env;
339                 cp.git_cmd = 1;
340                 cp.no_stdin = 1;
341                 cp.out = -1;
342                 cp.dir = path;
343                 if (start_command(&cp))
344                         die("Could not run 'git rev-list %s --not --remotes -n 1' command in submodule %s",
345                                 sha1_to_hex(sha1), path);
346                 if (strbuf_read(&buf, cp.out, 41))
347                         needs_pushing = 1;
348                 finish_command(&cp);
349                 close(cp.out);
350                 strbuf_release(&buf);
351                 return needs_pushing;
352         }
353
354         return 0;
355 }
356
357 static void collect_submodules_from_diff(struct diff_queue_struct *q,
358                                          struct diff_options *options,
359                                          void *data)
360 {
361         int i;
362         struct string_list *needs_pushing = data;
363
364         for (i = 0; i < q->nr; i++) {
365                 struct diff_filepair *p = q->queue[i];
366                 if (!S_ISGITLINK(p->two->mode))
367                         continue;
368                 if (submodule_needs_pushing(p->two->path, p->two->sha1))
369                         string_list_insert(needs_pushing, p->two->path);
370         }
371 }
372
373 static void find_unpushed_submodule_commits(struct commit *commit,
374                 struct string_list *needs_pushing)
375 {
376         struct rev_info rev;
377
378         init_revisions(&rev, NULL);
379         rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
380         rev.diffopt.format_callback = collect_submodules_from_diff;
381         rev.diffopt.format_callback_data = needs_pushing;
382         diff_tree_combined_merge(commit, 1, &rev);
383 }
384
385 int find_unpushed_submodules(unsigned char new_sha1[20],
386                 const char *remotes_name, struct string_list *needs_pushing)
387 {
388         struct rev_info rev;
389         struct commit *commit;
390         const char *argv[] = {NULL, NULL, "--not", "NULL", NULL};
391         int argc = ARRAY_SIZE(argv) - 1;
392         char *sha1_copy;
393
394         struct strbuf remotes_arg = STRBUF_INIT;
395
396         strbuf_addf(&remotes_arg, "--remotes=%s", remotes_name);
397         init_revisions(&rev, NULL);
398         sha1_copy = xstrdup(sha1_to_hex(new_sha1));
399         argv[1] = sha1_copy;
400         argv[3] = remotes_arg.buf;
401         setup_revisions(argc, argv, &rev, NULL);
402         if (prepare_revision_walk(&rev))
403                 die("revision walk setup failed");
404
405         while ((commit = get_revision(&rev)) != NULL)
406                 find_unpushed_submodule_commits(commit, needs_pushing);
407
408         reset_revision_walk();
409         free(sha1_copy);
410         strbuf_release(&remotes_arg);
411
412         return needs_pushing->nr;
413 }
414
415 static int push_submodule(const char *path)
416 {
417         if (add_submodule_odb(path))
418                 return 1;
419
420         if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
421                 struct child_process cp;
422                 const char *argv[] = {"push", NULL};
423
424                 memset(&cp, 0, sizeof(cp));
425                 cp.argv = argv;
426                 cp.env = local_repo_env;
427                 cp.git_cmd = 1;
428                 cp.no_stdin = 1;
429                 cp.dir = path;
430                 if (run_command(&cp))
431                         return 0;
432                 close(cp.out);
433         }
434
435         return 1;
436 }
437
438 int push_unpushed_submodules(unsigned char new_sha1[20], const char *remotes_name)
439 {
440         int i, ret = 1;
441         struct string_list needs_pushing;
442
443         memset(&needs_pushing, 0, sizeof(struct string_list));
444         needs_pushing.strdup_strings = 1;
445
446         if (!find_unpushed_submodules(new_sha1, remotes_name, &needs_pushing))
447                 return 1;
448
449         for (i = 0; i < needs_pushing.nr; i++) {
450                 const char *path = needs_pushing.items[i].string;
451                 fprintf(stderr, "Pushing submodule '%s'\n", path);
452                 if (!push_submodule(path)) {
453                         fprintf(stderr, "Unable to push submodule '%s'\n", path);
454                         ret = 0;
455                 }
456         }
457
458         string_list_clear(&needs_pushing, 0);
459
460         return ret;
461 }
462
463 static int is_submodule_commit_present(const char *path, unsigned char sha1[20])
464 {
465         int is_present = 0;
466         if (!add_submodule_odb(path) && lookup_commit_reference(sha1)) {
467                 /* Even if the submodule is checked out and the commit is
468                  * present, make sure it is reachable from a ref. */
469                 struct child_process cp;
470                 const char *argv[] = {"rev-list", "-n", "1", NULL, "--not", "--all", NULL};
471                 struct strbuf buf = STRBUF_INIT;
472
473                 argv[3] = sha1_to_hex(sha1);
474                 memset(&cp, 0, sizeof(cp));
475                 cp.argv = argv;
476                 cp.env = local_repo_env;
477                 cp.git_cmd = 1;
478                 cp.no_stdin = 1;
479                 cp.out = -1;
480                 cp.dir = path;
481                 if (!run_command(&cp) && !strbuf_read(&buf, cp.out, 1024))
482                         is_present = 1;
483
484                 close(cp.out);
485                 strbuf_release(&buf);
486         }
487         return is_present;
488 }
489
490 static void submodule_collect_changed_cb(struct diff_queue_struct *q,
491                                          struct diff_options *options,
492                                          void *data)
493 {
494         int i;
495         for (i = 0; i < q->nr; i++) {
496                 struct diff_filepair *p = q->queue[i];
497                 if (!S_ISGITLINK(p->two->mode))
498                         continue;
499
500                 if (S_ISGITLINK(p->one->mode)) {
501                         /* NEEDSWORK: We should honor the name configured in
502                          * the .gitmodules file of the commit we are examining
503                          * here to be able to correctly follow submodules
504                          * being moved around. */
505                         struct string_list_item *path;
506                         path = unsorted_string_list_lookup(&changed_submodule_paths, p->two->path);
507                         if (!path && !is_submodule_commit_present(p->two->path, p->two->sha1))
508                                 string_list_append(&changed_submodule_paths, xstrdup(p->two->path));
509                 } else {
510                         /* Submodule is new or was moved here */
511                         /* NEEDSWORK: When the .git directories of submodules
512                          * live inside the superprojects .git directory some
513                          * day we should fetch new submodules directly into
514                          * that location too when config or options request
515                          * that so they can be checked out from there. */
516                         continue;
517                 }
518         }
519 }
520
521 static int add_sha1_to_array(const char *ref, const unsigned char *sha1,
522                              int flags, void *data)
523 {
524         sha1_array_append(data, sha1);
525         return 0;
526 }
527
528 void check_for_new_submodule_commits(unsigned char new_sha1[20])
529 {
530         if (!initialized_fetch_ref_tips) {
531                 for_each_ref(add_sha1_to_array, &ref_tips_before_fetch);
532                 initialized_fetch_ref_tips = 1;
533         }
534
535         sha1_array_append(&ref_tips_after_fetch, new_sha1);
536 }
537
538 static void add_sha1_to_argv(const unsigned char sha1[20], void *data)
539 {
540         argv_array_push(data, sha1_to_hex(sha1));
541 }
542
543 static void calculate_changed_submodule_paths(void)
544 {
545         struct rev_info rev;
546         struct commit *commit;
547         struct argv_array argv = ARGV_ARRAY_INIT;
548
549         /* No need to check if there are no submodules configured */
550         if (!config_name_for_path.nr)
551                 return;
552
553         init_revisions(&rev, NULL);
554         argv_array_push(&argv, "--"); /* argv[0] program name */
555         sha1_array_for_each_unique(&ref_tips_after_fetch,
556                                    add_sha1_to_argv, &argv);
557         argv_array_push(&argv, "--not");
558         sha1_array_for_each_unique(&ref_tips_before_fetch,
559                                    add_sha1_to_argv, &argv);
560         setup_revisions(argv.argc, argv.argv, &rev, NULL);
561         if (prepare_revision_walk(&rev))
562                 die("revision walk setup failed");
563
564         /*
565          * Collect all submodules (whether checked out or not) for which new
566          * commits have been recorded upstream in "changed_submodule_paths".
567          */
568         while ((commit = get_revision(&rev))) {
569                 struct commit_list *parent = commit->parents;
570                 while (parent) {
571                         struct diff_options diff_opts;
572                         diff_setup(&diff_opts);
573                         DIFF_OPT_SET(&diff_opts, RECURSIVE);
574                         diff_opts.output_format |= DIFF_FORMAT_CALLBACK;
575                         diff_opts.format_callback = submodule_collect_changed_cb;
576                         diff_setup_done(&diff_opts);
577                         diff_tree_sha1(parent->item->object.sha1, commit->object.sha1, "", &diff_opts);
578                         diffcore_std(&diff_opts);
579                         diff_flush(&diff_opts);
580                         parent = parent->next;
581                 }
582         }
583
584         argv_array_clear(&argv);
585         sha1_array_clear(&ref_tips_before_fetch);
586         sha1_array_clear(&ref_tips_after_fetch);
587         initialized_fetch_ref_tips = 0;
588 }
589
590 int fetch_populated_submodules(const struct argv_array *options,
591                                const char *prefix, int command_line_option,
592                                int quiet)
593 {
594         int i, result = 0;
595         struct child_process cp;
596         struct argv_array argv = ARGV_ARRAY_INIT;
597         struct string_list_item *name_for_path;
598         const char *work_tree = get_git_work_tree();
599         if (!work_tree)
600                 goto out;
601
602         if (!the_index.initialized)
603                 if (read_cache() < 0)
604                         die("index file corrupt");
605
606         argv_array_push(&argv, "fetch");
607         for (i = 0; i < options->argc; i++)
608                 argv_array_push(&argv, options->argv[i]);
609         argv_array_push(&argv, "--recurse-submodules-default");
610         /* default value, "--submodule-prefix" and its value are added later */
611
612         memset(&cp, 0, sizeof(cp));
613         cp.env = local_repo_env;
614         cp.git_cmd = 1;
615         cp.no_stdin = 1;
616
617         calculate_changed_submodule_paths();
618
619         for (i = 0; i < active_nr; i++) {
620                 struct strbuf submodule_path = STRBUF_INIT;
621                 struct strbuf submodule_git_dir = STRBUF_INIT;
622                 struct strbuf submodule_prefix = STRBUF_INIT;
623                 struct cache_entry *ce = active_cache[i];
624                 const char *git_dir, *name, *default_argv;
625
626                 if (!S_ISGITLINK(ce->ce_mode))
627                         continue;
628
629                 name = ce->name;
630                 name_for_path = unsorted_string_list_lookup(&config_name_for_path, ce->name);
631                 if (name_for_path)
632                         name = name_for_path->util;
633
634                 default_argv = "yes";
635                 if (command_line_option == RECURSE_SUBMODULES_DEFAULT) {
636                         struct string_list_item *fetch_recurse_submodules_option;
637                         fetch_recurse_submodules_option = unsorted_string_list_lookup(&config_fetch_recurse_submodules_for_name, name);
638                         if (fetch_recurse_submodules_option) {
639                                 if ((intptr_t)fetch_recurse_submodules_option->util == RECURSE_SUBMODULES_OFF)
640                                         continue;
641                                 if ((intptr_t)fetch_recurse_submodules_option->util == RECURSE_SUBMODULES_ON_DEMAND) {
642                                         if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
643                                                 continue;
644                                         default_argv = "on-demand";
645                                 }
646                         } else {
647                                 if ((config_fetch_recurse_submodules == RECURSE_SUBMODULES_OFF) ||
648                                     gitmodules_is_unmerged)
649                                         continue;
650                                 if (config_fetch_recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND) {
651                                         if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
652                                                 continue;
653                                         default_argv = "on-demand";
654                                 }
655                         }
656                 } else if (command_line_option == RECURSE_SUBMODULES_ON_DEMAND) {
657                         if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
658                                 continue;
659                         default_argv = "on-demand";
660                 }
661
662                 strbuf_addf(&submodule_path, "%s/%s", work_tree, ce->name);
663                 strbuf_addf(&submodule_git_dir, "%s/.git", submodule_path.buf);
664                 strbuf_addf(&submodule_prefix, "%s%s/", prefix, ce->name);
665                 git_dir = read_gitfile(submodule_git_dir.buf);
666                 if (!git_dir)
667                         git_dir = submodule_git_dir.buf;
668                 if (is_directory(git_dir)) {
669                         if (!quiet)
670                                 printf("Fetching submodule %s%s\n", prefix, ce->name);
671                         cp.dir = submodule_path.buf;
672                         argv_array_push(&argv, default_argv);
673                         argv_array_push(&argv, "--submodule-prefix");
674                         argv_array_push(&argv, submodule_prefix.buf);
675                         cp.argv = argv.argv;
676                         if (run_command(&cp))
677                                 result = 1;
678                         argv_array_pop(&argv);
679                         argv_array_pop(&argv);
680                         argv_array_pop(&argv);
681                 }
682                 strbuf_release(&submodule_path);
683                 strbuf_release(&submodule_git_dir);
684                 strbuf_release(&submodule_prefix);
685         }
686         argv_array_clear(&argv);
687 out:
688         string_list_clear(&changed_submodule_paths, 1);
689         return result;
690 }
691
692 unsigned is_submodule_modified(const char *path, int ignore_untracked)
693 {
694         ssize_t len;
695         struct child_process cp;
696         const char *argv[] = {
697                 "status",
698                 "--porcelain",
699                 NULL,
700                 NULL,
701         };
702         struct strbuf buf = STRBUF_INIT;
703         unsigned dirty_submodule = 0;
704         const char *line, *next_line;
705         const char *git_dir;
706
707         strbuf_addf(&buf, "%s/.git", path);
708         git_dir = read_gitfile(buf.buf);
709         if (!git_dir)
710                 git_dir = buf.buf;
711         if (!is_directory(git_dir)) {
712                 strbuf_release(&buf);
713                 /* The submodule is not checked out, so it is not modified */
714                 return 0;
715
716         }
717         strbuf_reset(&buf);
718
719         if (ignore_untracked)
720                 argv[2] = "-uno";
721
722         memset(&cp, 0, sizeof(cp));
723         cp.argv = argv;
724         cp.env = local_repo_env;
725         cp.git_cmd = 1;
726         cp.no_stdin = 1;
727         cp.out = -1;
728         cp.dir = path;
729         if (start_command(&cp))
730                 die("Could not run 'git status --porcelain' in submodule %s", path);
731
732         len = strbuf_read(&buf, cp.out, 1024);
733         line = buf.buf;
734         while (len > 2) {
735                 if ((line[0] == '?') && (line[1] == '?')) {
736                         dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
737                         if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
738                                 break;
739                 } else {
740                         dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
741                         if (ignore_untracked ||
742                             (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED))
743                                 break;
744                 }
745                 next_line = strchr(line, '\n');
746                 if (!next_line)
747                         break;
748                 next_line++;
749                 len -= (next_line - line);
750                 line = next_line;
751         }
752         close(cp.out);
753
754         if (finish_command(&cp))
755                 die("'git status --porcelain' failed in submodule %s", path);
756
757         strbuf_release(&buf);
758         return dirty_submodule;
759 }
760
761 int submodule_uses_gitfile(const char *path)
762 {
763         struct child_process cp;
764         const char *argv[] = {
765                 "submodule",
766                 "foreach",
767                 "--quiet",
768                 "--recursive",
769                 "test -f .git",
770                 NULL,
771         };
772         struct strbuf buf = STRBUF_INIT;
773         const char *git_dir;
774
775         strbuf_addf(&buf, "%s/.git", path);
776         git_dir = read_gitfile(buf.buf);
777         if (!git_dir) {
778                 strbuf_release(&buf);
779                 return 0;
780         }
781         strbuf_release(&buf);
782
783         /* Now test that all nested submodules use a gitfile too */
784         memset(&cp, 0, sizeof(cp));
785         cp.argv = argv;
786         cp.env = local_repo_env;
787         cp.git_cmd = 1;
788         cp.no_stdin = 1;
789         cp.no_stderr = 1;
790         cp.no_stdout = 1;
791         cp.dir = path;
792         if (run_command(&cp))
793                 return 0;
794
795         return 1;
796 }
797
798 int ok_to_remove_submodule(const char *path)
799 {
800         struct stat st;
801         ssize_t len;
802         struct child_process cp;
803         const char *argv[] = {
804                 "status",
805                 "--porcelain",
806                 "-u",
807                 "--ignore-submodules=none",
808                 NULL,
809         };
810         struct strbuf buf = STRBUF_INIT;
811         int ok_to_remove = 1;
812
813         if ((lstat(path, &st) < 0) || is_empty_dir(path))
814                 return 1;
815
816         if (!submodule_uses_gitfile(path))
817                 return 0;
818
819         memset(&cp, 0, sizeof(cp));
820         cp.argv = argv;
821         cp.env = local_repo_env;
822         cp.git_cmd = 1;
823         cp.no_stdin = 1;
824         cp.out = -1;
825         cp.dir = path;
826         if (start_command(&cp))
827                 die("Could not run 'git status --porcelain -uall --ignore-submodules=none' in submodule %s", path);
828
829         len = strbuf_read(&buf, cp.out, 1024);
830         if (len > 2)
831                 ok_to_remove = 0;
832         close(cp.out);
833
834         if (finish_command(&cp))
835                 die("'git status --porcelain -uall --ignore-submodules=none' failed in submodule %s", path);
836
837         strbuf_release(&buf);
838         return ok_to_remove;
839 }
840
841 static int find_first_merges(struct object_array *result, const char *path,
842                 struct commit *a, struct commit *b)
843 {
844         int i, j;
845         struct object_array merges;
846         struct commit *commit;
847         int contains_another;
848
849         char merged_revision[42];
850         const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
851                                    "--all", merged_revision, NULL };
852         struct rev_info revs;
853         struct setup_revision_opt rev_opts;
854
855         memset(&merges, 0, sizeof(merges));
856         memset(result, 0, sizeof(struct object_array));
857         memset(&rev_opts, 0, sizeof(rev_opts));
858
859         /* get all revisions that merge commit a */
860         snprintf(merged_revision, sizeof(merged_revision), "^%s",
861                         sha1_to_hex(a->object.sha1));
862         init_revisions(&revs, NULL);
863         rev_opts.submodule = path;
864         setup_revisions(sizeof(rev_args)/sizeof(char *)-1, rev_args, &revs, &rev_opts);
865
866         /* save all revisions from the above list that contain b */
867         if (prepare_revision_walk(&revs))
868                 die("revision walk setup failed");
869         while ((commit = get_revision(&revs)) != NULL) {
870                 struct object *o = &(commit->object);
871                 if (in_merge_bases(b, commit))
872                         add_object_array(o, NULL, &merges);
873         }
874         reset_revision_walk();
875
876         /* Now we've got all merges that contain a and b. Prune all
877          * merges that contain another found merge and save them in
878          * result.
879          */
880         for (i = 0; i < merges.nr; i++) {
881                 struct commit *m1 = (struct commit *) merges.objects[i].item;
882
883                 contains_another = 0;
884                 for (j = 0; j < merges.nr; j++) {
885                         struct commit *m2 = (struct commit *) merges.objects[j].item;
886                         if (i != j && in_merge_bases(m2, m1)) {
887                                 contains_another = 1;
888                                 break;
889                         }
890                 }
891
892                 if (!contains_another)
893                         add_object_array(merges.objects[i].item,
894                                          merges.objects[i].name, result);
895         }
896
897         free(merges.objects);
898         return result->nr;
899 }
900
901 static void print_commit(struct commit *commit)
902 {
903         struct strbuf sb = STRBUF_INIT;
904         struct pretty_print_context ctx = {0};
905         ctx.date_mode = DATE_NORMAL;
906         format_commit_message(commit, " %h: %m %s", &sb, &ctx);
907         fprintf(stderr, "%s\n", sb.buf);
908         strbuf_release(&sb);
909 }
910
911 #define MERGE_WARNING(path, msg) \
912         warning("Failed to merge submodule %s (%s)", path, msg);
913
914 int merge_submodule(unsigned char result[20], const char *path,
915                     const unsigned char base[20], const unsigned char a[20],
916                     const unsigned char b[20], int search)
917 {
918         struct commit *commit_base, *commit_a, *commit_b;
919         int parent_count;
920         struct object_array merges;
921
922         int i;
923
924         /* store a in result in case we fail */
925         hashcpy(result, a);
926
927         /* we can not handle deletion conflicts */
928         if (is_null_sha1(base))
929                 return 0;
930         if (is_null_sha1(a))
931                 return 0;
932         if (is_null_sha1(b))
933                 return 0;
934
935         if (add_submodule_odb(path)) {
936                 MERGE_WARNING(path, "not checked out");
937                 return 0;
938         }
939
940         if (!(commit_base = lookup_commit_reference(base)) ||
941             !(commit_a = lookup_commit_reference(a)) ||
942             !(commit_b = lookup_commit_reference(b))) {
943                 MERGE_WARNING(path, "commits not present");
944                 return 0;
945         }
946
947         /* check whether both changes are forward */
948         if (!in_merge_bases(commit_base, commit_a) ||
949             !in_merge_bases(commit_base, commit_b)) {
950                 MERGE_WARNING(path, "commits don't follow merge-base");
951                 return 0;
952         }
953
954         /* Case #1: a is contained in b or vice versa */
955         if (in_merge_bases(commit_a, commit_b)) {
956                 hashcpy(result, b);
957                 return 1;
958         }
959         if (in_merge_bases(commit_b, commit_a)) {
960                 hashcpy(result, a);
961                 return 1;
962         }
963
964         /*
965          * Case #2: There are one or more merges that contain a and b in
966          * the submodule. If there is only one, then present it as a
967          * suggestion to the user, but leave it marked unmerged so the
968          * user needs to confirm the resolution.
969          */
970
971         /* Skip the search if makes no sense to the calling context.  */
972         if (!search)
973                 return 0;
974
975         /* find commit which merges them */
976         parent_count = find_first_merges(&merges, path, commit_a, commit_b);
977         switch (parent_count) {
978         case 0:
979                 MERGE_WARNING(path, "merge following commits not found");
980                 break;
981
982         case 1:
983                 MERGE_WARNING(path, "not fast-forward");
984                 fprintf(stderr, "Found a possible merge resolution "
985                                 "for the submodule:\n");
986                 print_commit((struct commit *) merges.objects[0].item);
987                 fprintf(stderr,
988                         "If this is correct simply add it to the index "
989                         "for example\n"
990                         "by using:\n\n"
991                         "  git update-index --cacheinfo 160000 %s \"%s\"\n\n"
992                         "which will accept this suggestion.\n",
993                         sha1_to_hex(merges.objects[0].item->sha1), path);
994                 break;
995
996         default:
997                 MERGE_WARNING(path, "multiple merges found");
998                 for (i = 0; i < merges.nr; i++)
999                         print_commit((struct commit *) merges.objects[i].item);
1000         }
1001
1002         free(merges.objects);
1003         return 0;
1004 }