Merge branch 'rt/commentchar-fmt-merge-msg'
[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 = NULL, *right = NULL;
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         else if (prepare_submodule_summary(&rev, path, left, right,
279                                            &fast_forward, &fast_backward))
280                 message = "(revision walker failed)";
281
282         if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
283                 fprintf(f, "Submodule %s contains untracked content\n", path);
284         if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
285                 fprintf(f, "Submodule %s contains modified content\n", path);
286
287         if (!hashcmp(one, two)) {
288                 strbuf_release(&sb);
289                 return;
290         }
291
292         strbuf_addf(&sb, "%sSubmodule %s %s..", meta, path,
293                         find_unique_abbrev(one, DEFAULT_ABBREV));
294         if (!fast_backward && !fast_forward)
295                 strbuf_addch(&sb, '.');
296         strbuf_addf(&sb, "%s", find_unique_abbrev(two, DEFAULT_ABBREV));
297         if (message)
298                 strbuf_addf(&sb, " %s%s\n", message, reset);
299         else
300                 strbuf_addf(&sb, "%s:%s\n", fast_backward ? " (rewind)" : "", reset);
301         fwrite(sb.buf, sb.len, 1, f);
302
303         if (!message) /* only NULL if we succeeded in setting up the walk */
304                 print_submodule_summary(&rev, f, del, add, reset);
305         if (left)
306                 clear_commit_marks(left, ~0);
307         if (right)
308                 clear_commit_marks(right, ~0);
309
310         strbuf_release(&sb);
311 }
312
313 void set_config_fetch_recurse_submodules(int value)
314 {
315         config_fetch_recurse_submodules = value;
316 }
317
318 static int has_remote(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
319 {
320         return 1;
321 }
322
323 static int submodule_needs_pushing(const char *path, const unsigned char sha1[20])
324 {
325         if (add_submodule_odb(path) || !lookup_commit_reference(sha1))
326                 return 0;
327
328         if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
329                 struct child_process cp;
330                 const char *argv[] = {"rev-list", NULL, "--not", "--remotes", "-n", "1" , NULL};
331                 struct strbuf buf = STRBUF_INIT;
332                 int needs_pushing = 0;
333
334                 argv[1] = sha1_to_hex(sha1);
335                 memset(&cp, 0, sizeof(cp));
336                 cp.argv = argv;
337                 cp.env = local_repo_env;
338                 cp.git_cmd = 1;
339                 cp.no_stdin = 1;
340                 cp.out = -1;
341                 cp.dir = path;
342                 if (start_command(&cp))
343                         die("Could not run 'git rev-list %s --not --remotes -n 1' command in submodule %s",
344                                 sha1_to_hex(sha1), path);
345                 if (strbuf_read(&buf, cp.out, 41))
346                         needs_pushing = 1;
347                 finish_command(&cp);
348                 close(cp.out);
349                 strbuf_release(&buf);
350                 return needs_pushing;
351         }
352
353         return 0;
354 }
355
356 static void collect_submodules_from_diff(struct diff_queue_struct *q,
357                                          struct diff_options *options,
358                                          void *data)
359 {
360         int i;
361         struct string_list *needs_pushing = data;
362
363         for (i = 0; i < q->nr; i++) {
364                 struct diff_filepair *p = q->queue[i];
365                 if (!S_ISGITLINK(p->two->mode))
366                         continue;
367                 if (submodule_needs_pushing(p->two->path, p->two->sha1))
368                         string_list_insert(needs_pushing, p->two->path);
369         }
370 }
371
372 static void find_unpushed_submodule_commits(struct commit *commit,
373                 struct string_list *needs_pushing)
374 {
375         struct rev_info rev;
376
377         init_revisions(&rev, NULL);
378         rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
379         rev.diffopt.format_callback = collect_submodules_from_diff;
380         rev.diffopt.format_callback_data = needs_pushing;
381         diff_tree_combined_merge(commit, 1, &rev);
382 }
383
384 int find_unpushed_submodules(unsigned char new_sha1[20],
385                 const char *remotes_name, struct string_list *needs_pushing)
386 {
387         struct rev_info rev;
388         struct commit *commit;
389         const char *argv[] = {NULL, NULL, "--not", "NULL", NULL};
390         int argc = ARRAY_SIZE(argv) - 1;
391         char *sha1_copy;
392
393         struct strbuf remotes_arg = STRBUF_INIT;
394
395         strbuf_addf(&remotes_arg, "--remotes=%s", remotes_name);
396         init_revisions(&rev, NULL);
397         sha1_copy = xstrdup(sha1_to_hex(new_sha1));
398         argv[1] = sha1_copy;
399         argv[3] = remotes_arg.buf;
400         setup_revisions(argc, argv, &rev, NULL);
401         if (prepare_revision_walk(&rev))
402                 die("revision walk setup failed");
403
404         while ((commit = get_revision(&rev)) != NULL)
405                 find_unpushed_submodule_commits(commit, needs_pushing);
406
407         reset_revision_walk();
408         free(sha1_copy);
409         strbuf_release(&remotes_arg);
410
411         return needs_pushing->nr;
412 }
413
414 static int push_submodule(const char *path)
415 {
416         if (add_submodule_odb(path))
417                 return 1;
418
419         if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
420                 struct child_process cp;
421                 const char *argv[] = {"push", NULL};
422
423                 memset(&cp, 0, sizeof(cp));
424                 cp.argv = argv;
425                 cp.env = local_repo_env;
426                 cp.git_cmd = 1;
427                 cp.no_stdin = 1;
428                 cp.dir = path;
429                 if (run_command(&cp))
430                         return 0;
431                 close(cp.out);
432         }
433
434         return 1;
435 }
436
437 int push_unpushed_submodules(unsigned char new_sha1[20], const char *remotes_name)
438 {
439         int i, ret = 1;
440         struct string_list needs_pushing;
441
442         memset(&needs_pushing, 0, sizeof(struct string_list));
443         needs_pushing.strdup_strings = 1;
444
445         if (!find_unpushed_submodules(new_sha1, remotes_name, &needs_pushing))
446                 return 1;
447
448         for (i = 0; i < needs_pushing.nr; i++) {
449                 const char *path = needs_pushing.items[i].string;
450                 fprintf(stderr, "Pushing submodule '%s'\n", path);
451                 if (!push_submodule(path)) {
452                         fprintf(stderr, "Unable to push submodule '%s'\n", path);
453                         ret = 0;
454                 }
455         }
456
457         string_list_clear(&needs_pushing, 0);
458
459         return ret;
460 }
461
462 static int is_submodule_commit_present(const char *path, unsigned char sha1[20])
463 {
464         int is_present = 0;
465         if (!add_submodule_odb(path) && lookup_commit_reference(sha1)) {
466                 /* Even if the submodule is checked out and the commit is
467                  * present, make sure it is reachable from a ref. */
468                 struct child_process cp;
469                 const char *argv[] = {"rev-list", "-n", "1", NULL, "--not", "--all", NULL};
470                 struct strbuf buf = STRBUF_INIT;
471
472                 argv[3] = sha1_to_hex(sha1);
473                 memset(&cp, 0, sizeof(cp));
474                 cp.argv = argv;
475                 cp.env = local_repo_env;
476                 cp.git_cmd = 1;
477                 cp.no_stdin = 1;
478                 cp.out = -1;
479                 cp.dir = path;
480                 if (!run_command(&cp) && !strbuf_read(&buf, cp.out, 1024))
481                         is_present = 1;
482
483                 close(cp.out);
484                 strbuf_release(&buf);
485         }
486         return is_present;
487 }
488
489 static void submodule_collect_changed_cb(struct diff_queue_struct *q,
490                                          struct diff_options *options,
491                                          void *data)
492 {
493         int i;
494         for (i = 0; i < q->nr; i++) {
495                 struct diff_filepair *p = q->queue[i];
496                 if (!S_ISGITLINK(p->two->mode))
497                         continue;
498
499                 if (S_ISGITLINK(p->one->mode)) {
500                         /* NEEDSWORK: We should honor the name configured in
501                          * the .gitmodules file of the commit we are examining
502                          * here to be able to correctly follow submodules
503                          * being moved around. */
504                         struct string_list_item *path;
505                         path = unsorted_string_list_lookup(&changed_submodule_paths, p->two->path);
506                         if (!path && !is_submodule_commit_present(p->two->path, p->two->sha1))
507                                 string_list_append(&changed_submodule_paths, xstrdup(p->two->path));
508                 } else {
509                         /* Submodule is new or was moved here */
510                         /* NEEDSWORK: When the .git directories of submodules
511                          * live inside the superprojects .git directory some
512                          * day we should fetch new submodules directly into
513                          * that location too when config or options request
514                          * that so they can be checked out from there. */
515                         continue;
516                 }
517         }
518 }
519
520 static int add_sha1_to_array(const char *ref, const unsigned char *sha1,
521                              int flags, void *data)
522 {
523         sha1_array_append(data, sha1);
524         return 0;
525 }
526
527 void check_for_new_submodule_commits(unsigned char new_sha1[20])
528 {
529         if (!initialized_fetch_ref_tips) {
530                 for_each_ref(add_sha1_to_array, &ref_tips_before_fetch);
531                 initialized_fetch_ref_tips = 1;
532         }
533
534         sha1_array_append(&ref_tips_after_fetch, new_sha1);
535 }
536
537 static void add_sha1_to_argv(const unsigned char sha1[20], void *data)
538 {
539         argv_array_push(data, sha1_to_hex(sha1));
540 }
541
542 static void calculate_changed_submodule_paths(void)
543 {
544         struct rev_info rev;
545         struct commit *commit;
546         struct argv_array argv = ARGV_ARRAY_INIT;
547
548         /* No need to check if there are no submodules configured */
549         if (!config_name_for_path.nr)
550                 return;
551
552         init_revisions(&rev, NULL);
553         argv_array_push(&argv, "--"); /* argv[0] program name */
554         sha1_array_for_each_unique(&ref_tips_after_fetch,
555                                    add_sha1_to_argv, &argv);
556         argv_array_push(&argv, "--not");
557         sha1_array_for_each_unique(&ref_tips_before_fetch,
558                                    add_sha1_to_argv, &argv);
559         setup_revisions(argv.argc, argv.argv, &rev, NULL);
560         if (prepare_revision_walk(&rev))
561                 die("revision walk setup failed");
562
563         /*
564          * Collect all submodules (whether checked out or not) for which new
565          * commits have been recorded upstream in "changed_submodule_paths".
566          */
567         while ((commit = get_revision(&rev))) {
568                 struct commit_list *parent = commit->parents;
569                 while (parent) {
570                         struct diff_options diff_opts;
571                         diff_setup(&diff_opts);
572                         DIFF_OPT_SET(&diff_opts, RECURSIVE);
573                         diff_opts.output_format |= DIFF_FORMAT_CALLBACK;
574                         diff_opts.format_callback = submodule_collect_changed_cb;
575                         diff_setup_done(&diff_opts);
576                         diff_tree_sha1(parent->item->object.sha1, commit->object.sha1, "", &diff_opts);
577                         diffcore_std(&diff_opts);
578                         diff_flush(&diff_opts);
579                         parent = parent->next;
580                 }
581         }
582
583         argv_array_clear(&argv);
584         sha1_array_clear(&ref_tips_before_fetch);
585         sha1_array_clear(&ref_tips_after_fetch);
586         initialized_fetch_ref_tips = 0;
587 }
588
589 int fetch_populated_submodules(const struct argv_array *options,
590                                const char *prefix, int command_line_option,
591                                int quiet)
592 {
593         int i, result = 0;
594         struct child_process cp;
595         struct argv_array argv = ARGV_ARRAY_INIT;
596         struct string_list_item *name_for_path;
597         const char *work_tree = get_git_work_tree();
598         if (!work_tree)
599                 goto out;
600
601         if (!the_index.initialized)
602                 if (read_cache() < 0)
603                         die("index file corrupt");
604
605         argv_array_push(&argv, "fetch");
606         for (i = 0; i < options->argc; i++)
607                 argv_array_push(&argv, options->argv[i]);
608         argv_array_push(&argv, "--recurse-submodules-default");
609         /* default value, "--submodule-prefix" and its value are added later */
610
611         memset(&cp, 0, sizeof(cp));
612         cp.env = local_repo_env;
613         cp.git_cmd = 1;
614         cp.no_stdin = 1;
615
616         calculate_changed_submodule_paths();
617
618         for (i = 0; i < active_nr; i++) {
619                 struct strbuf submodule_path = STRBUF_INIT;
620                 struct strbuf submodule_git_dir = STRBUF_INIT;
621                 struct strbuf submodule_prefix = STRBUF_INIT;
622                 struct cache_entry *ce = active_cache[i];
623                 const char *git_dir, *name, *default_argv;
624
625                 if (!S_ISGITLINK(ce->ce_mode))
626                         continue;
627
628                 name = ce->name;
629                 name_for_path = unsorted_string_list_lookup(&config_name_for_path, ce->name);
630                 if (name_for_path)
631                         name = name_for_path->util;
632
633                 default_argv = "yes";
634                 if (command_line_option == RECURSE_SUBMODULES_DEFAULT) {
635                         struct string_list_item *fetch_recurse_submodules_option;
636                         fetch_recurse_submodules_option = unsorted_string_list_lookup(&config_fetch_recurse_submodules_for_name, name);
637                         if (fetch_recurse_submodules_option) {
638                                 if ((intptr_t)fetch_recurse_submodules_option->util == RECURSE_SUBMODULES_OFF)
639                                         continue;
640                                 if ((intptr_t)fetch_recurse_submodules_option->util == RECURSE_SUBMODULES_ON_DEMAND) {
641                                         if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
642                                                 continue;
643                                         default_argv = "on-demand";
644                                 }
645                         } else {
646                                 if ((config_fetch_recurse_submodules == RECURSE_SUBMODULES_OFF) ||
647                                     gitmodules_is_unmerged)
648                                         continue;
649                                 if (config_fetch_recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND) {
650                                         if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
651                                                 continue;
652                                         default_argv = "on-demand";
653                                 }
654                         }
655                 } else if (command_line_option == RECURSE_SUBMODULES_ON_DEMAND) {
656                         if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
657                                 continue;
658                         default_argv = "on-demand";
659                 }
660
661                 strbuf_addf(&submodule_path, "%s/%s", work_tree, ce->name);
662                 strbuf_addf(&submodule_git_dir, "%s/.git", submodule_path.buf);
663                 strbuf_addf(&submodule_prefix, "%s%s/", prefix, ce->name);
664                 git_dir = read_gitfile(submodule_git_dir.buf);
665                 if (!git_dir)
666                         git_dir = submodule_git_dir.buf;
667                 if (is_directory(git_dir)) {
668                         if (!quiet)
669                                 printf("Fetching submodule %s%s\n", prefix, ce->name);
670                         cp.dir = submodule_path.buf;
671                         argv_array_push(&argv, default_argv);
672                         argv_array_push(&argv, "--submodule-prefix");
673                         argv_array_push(&argv, submodule_prefix.buf);
674                         cp.argv = argv.argv;
675                         if (run_command(&cp))
676                                 result = 1;
677                         argv_array_pop(&argv);
678                         argv_array_pop(&argv);
679                         argv_array_pop(&argv);
680                 }
681                 strbuf_release(&submodule_path);
682                 strbuf_release(&submodule_git_dir);
683                 strbuf_release(&submodule_prefix);
684         }
685         argv_array_clear(&argv);
686 out:
687         string_list_clear(&changed_submodule_paths, 1);
688         return result;
689 }
690
691 unsigned is_submodule_modified(const char *path, int ignore_untracked)
692 {
693         ssize_t len;
694         struct child_process cp;
695         const char *argv[] = {
696                 "status",
697                 "--porcelain",
698                 NULL,
699                 NULL,
700         };
701         struct strbuf buf = STRBUF_INIT;
702         unsigned dirty_submodule = 0;
703         const char *line, *next_line;
704         const char *git_dir;
705
706         strbuf_addf(&buf, "%s/.git", path);
707         git_dir = read_gitfile(buf.buf);
708         if (!git_dir)
709                 git_dir = buf.buf;
710         if (!is_directory(git_dir)) {
711                 strbuf_release(&buf);
712                 /* The submodule is not checked out, so it is not modified */
713                 return 0;
714
715         }
716         strbuf_reset(&buf);
717
718         if (ignore_untracked)
719                 argv[2] = "-uno";
720
721         memset(&cp, 0, sizeof(cp));
722         cp.argv = argv;
723         cp.env = local_repo_env;
724         cp.git_cmd = 1;
725         cp.no_stdin = 1;
726         cp.out = -1;
727         cp.dir = path;
728         if (start_command(&cp))
729                 die("Could not run 'git status --porcelain' in submodule %s", path);
730
731         len = strbuf_read(&buf, cp.out, 1024);
732         line = buf.buf;
733         while (len > 2) {
734                 if ((line[0] == '?') && (line[1] == '?')) {
735                         dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
736                         if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
737                                 break;
738                 } else {
739                         dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
740                         if (ignore_untracked ||
741                             (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED))
742                                 break;
743                 }
744                 next_line = strchr(line, '\n');
745                 if (!next_line)
746                         break;
747                 next_line++;
748                 len -= (next_line - line);
749                 line = next_line;
750         }
751         close(cp.out);
752
753         if (finish_command(&cp))
754                 die("'git status --porcelain' failed in submodule %s", path);
755
756         strbuf_release(&buf);
757         return dirty_submodule;
758 }
759
760 int submodule_uses_gitfile(const char *path)
761 {
762         struct child_process cp;
763         const char *argv[] = {
764                 "submodule",
765                 "foreach",
766                 "--quiet",
767                 "--recursive",
768                 "test -f .git",
769                 NULL,
770         };
771         struct strbuf buf = STRBUF_INIT;
772         const char *git_dir;
773
774         strbuf_addf(&buf, "%s/.git", path);
775         git_dir = read_gitfile(buf.buf);
776         if (!git_dir) {
777                 strbuf_release(&buf);
778                 return 0;
779         }
780         strbuf_release(&buf);
781
782         /* Now test that all nested submodules use a gitfile too */
783         memset(&cp, 0, sizeof(cp));
784         cp.argv = argv;
785         cp.env = local_repo_env;
786         cp.git_cmd = 1;
787         cp.no_stdin = 1;
788         cp.no_stderr = 1;
789         cp.no_stdout = 1;
790         cp.dir = path;
791         if (run_command(&cp))
792                 return 0;
793
794         return 1;
795 }
796
797 int ok_to_remove_submodule(const char *path)
798 {
799         struct stat st;
800         ssize_t len;
801         struct child_process cp;
802         const char *argv[] = {
803                 "status",
804                 "--porcelain",
805                 "-u",
806                 "--ignore-submodules=none",
807                 NULL,
808         };
809         struct strbuf buf = STRBUF_INIT;
810         int ok_to_remove = 1;
811
812         if ((lstat(path, &st) < 0) || is_empty_dir(path))
813                 return 1;
814
815         if (!submodule_uses_gitfile(path))
816                 return 0;
817
818         memset(&cp, 0, sizeof(cp));
819         cp.argv = argv;
820         cp.env = local_repo_env;
821         cp.git_cmd = 1;
822         cp.no_stdin = 1;
823         cp.out = -1;
824         cp.dir = path;
825         if (start_command(&cp))
826                 die("Could not run 'git status --porcelain -uall --ignore-submodules=none' in submodule %s", path);
827
828         len = strbuf_read(&buf, cp.out, 1024);
829         if (len > 2)
830                 ok_to_remove = 0;
831         close(cp.out);
832
833         if (finish_command(&cp))
834                 die("'git status --porcelain -uall --ignore-submodules=none' failed in submodule %s", path);
835
836         strbuf_release(&buf);
837         return ok_to_remove;
838 }
839
840 static int find_first_merges(struct object_array *result, const char *path,
841                 struct commit *a, struct commit *b)
842 {
843         int i, j;
844         struct object_array merges;
845         struct commit *commit;
846         int contains_another;
847
848         char merged_revision[42];
849         const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
850                                    "--all", merged_revision, NULL };
851         struct rev_info revs;
852         struct setup_revision_opt rev_opts;
853
854         memset(&merges, 0, sizeof(merges));
855         memset(result, 0, sizeof(struct object_array));
856         memset(&rev_opts, 0, sizeof(rev_opts));
857
858         /* get all revisions that merge commit a */
859         snprintf(merged_revision, sizeof(merged_revision), "^%s",
860                         sha1_to_hex(a->object.sha1));
861         init_revisions(&revs, NULL);
862         rev_opts.submodule = path;
863         setup_revisions(sizeof(rev_args)/sizeof(char *)-1, rev_args, &revs, &rev_opts);
864
865         /* save all revisions from the above list that contain b */
866         if (prepare_revision_walk(&revs))
867                 die("revision walk setup failed");
868         while ((commit = get_revision(&revs)) != NULL) {
869                 struct object *o = &(commit->object);
870                 if (in_merge_bases(b, commit))
871                         add_object_array(o, NULL, &merges);
872         }
873         reset_revision_walk();
874
875         /* Now we've got all merges that contain a and b. Prune all
876          * merges that contain another found merge and save them in
877          * result.
878          */
879         for (i = 0; i < merges.nr; i++) {
880                 struct commit *m1 = (struct commit *) merges.objects[i].item;
881
882                 contains_another = 0;
883                 for (j = 0; j < merges.nr; j++) {
884                         struct commit *m2 = (struct commit *) merges.objects[j].item;
885                         if (i != j && in_merge_bases(m2, m1)) {
886                                 contains_another = 1;
887                                 break;
888                         }
889                 }
890
891                 if (!contains_another)
892                         add_object_array(merges.objects[i].item,
893                                          merges.objects[i].name, result);
894         }
895
896         free(merges.objects);
897         return result->nr;
898 }
899
900 static void print_commit(struct commit *commit)
901 {
902         struct strbuf sb = STRBUF_INIT;
903         struct pretty_print_context ctx = {0};
904         ctx.date_mode = DATE_NORMAL;
905         format_commit_message(commit, " %h: %m %s", &sb, &ctx);
906         fprintf(stderr, "%s\n", sb.buf);
907         strbuf_release(&sb);
908 }
909
910 #define MERGE_WARNING(path, msg) \
911         warning("Failed to merge submodule %s (%s)", path, msg);
912
913 int merge_submodule(unsigned char result[20], const char *path,
914                     const unsigned char base[20], const unsigned char a[20],
915                     const unsigned char b[20], int search)
916 {
917         struct commit *commit_base, *commit_a, *commit_b;
918         int parent_count;
919         struct object_array merges;
920
921         int i;
922
923         /* store a in result in case we fail */
924         hashcpy(result, a);
925
926         /* we can not handle deletion conflicts */
927         if (is_null_sha1(base))
928                 return 0;
929         if (is_null_sha1(a))
930                 return 0;
931         if (is_null_sha1(b))
932                 return 0;
933
934         if (add_submodule_odb(path)) {
935                 MERGE_WARNING(path, "not checked out");
936                 return 0;
937         }
938
939         if (!(commit_base = lookup_commit_reference(base)) ||
940             !(commit_a = lookup_commit_reference(a)) ||
941             !(commit_b = lookup_commit_reference(b))) {
942                 MERGE_WARNING(path, "commits not present");
943                 return 0;
944         }
945
946         /* check whether both changes are forward */
947         if (!in_merge_bases(commit_base, commit_a) ||
948             !in_merge_bases(commit_base, commit_b)) {
949                 MERGE_WARNING(path, "commits don't follow merge-base");
950                 return 0;
951         }
952
953         /* Case #1: a is contained in b or vice versa */
954         if (in_merge_bases(commit_a, commit_b)) {
955                 hashcpy(result, b);
956                 return 1;
957         }
958         if (in_merge_bases(commit_b, commit_a)) {
959                 hashcpy(result, a);
960                 return 1;
961         }
962
963         /*
964          * Case #2: There are one or more merges that contain a and b in
965          * the submodule. If there is only one, then present it as a
966          * suggestion to the user, but leave it marked unmerged so the
967          * user needs to confirm the resolution.
968          */
969
970         /* Skip the search if makes no sense to the calling context.  */
971         if (!search)
972                 return 0;
973
974         /* find commit which merges them */
975         parent_count = find_first_merges(&merges, path, commit_a, commit_b);
976         switch (parent_count) {
977         case 0:
978                 MERGE_WARNING(path, "merge following commits not found");
979                 break;
980
981         case 1:
982                 MERGE_WARNING(path, "not fast-forward");
983                 fprintf(stderr, "Found a possible merge resolution "
984                                 "for the submodule:\n");
985                 print_commit((struct commit *) merges.objects[0].item);
986                 fprintf(stderr,
987                         "If this is correct simply add it to the index "
988                         "for example\n"
989                         "by using:\n\n"
990                         "  git update-index --cacheinfo 160000 %s \"%s\"\n\n"
991                         "which will accept this suggestion.\n",
992                         sha1_to_hex(merges.objects[0].item->sha1), path);
993                 break;
994
995         default:
996                 MERGE_WARNING(path, "multiple merges found");
997                 for (i = 0; i < merges.nr; i++)
998                         print_commit((struct commit *) merges.objects[i].item);
999         }
1000
1001         free(merges.objects);
1002         return 0;
1003 }