submodule init: initialize active submodules
[git] / submodule.c
1 #include "cache.h"
2 #include "submodule-config.h"
3 #include "submodule.h"
4 #include "dir.h"
5 #include "diff.h"
6 #include "commit.h"
7 #include "revision.h"
8 #include "run-command.h"
9 #include "diffcore.h"
10 #include "refs.h"
11 #include "string-list.h"
12 #include "sha1-array.h"
13 #include "argv-array.h"
14 #include "blob.h"
15 #include "thread-utils.h"
16 #include "quote.h"
17 #include "worktree.h"
18
19 static int config_fetch_recurse_submodules = RECURSE_SUBMODULES_ON_DEMAND;
20 static int parallel_jobs = 1;
21 static struct string_list changed_submodule_paths = STRING_LIST_INIT_NODUP;
22 static int initialized_fetch_ref_tips;
23 static struct sha1_array ref_tips_before_fetch;
24 static struct sha1_array ref_tips_after_fetch;
25
26 /*
27  * The following flag is set if the .gitmodules file is unmerged. We then
28  * disable recursion for all submodules where .git/config doesn't have a
29  * matching config entry because we can't guess what might be configured in
30  * .gitmodules unless the user resolves the conflict. When a command line
31  * option is given (which always overrides configuration) this flag will be
32  * ignored.
33  */
34 static int gitmodules_is_unmerged;
35
36 /*
37  * This flag is set if the .gitmodules file had unstaged modifications on
38  * startup. This must be checked before allowing modifications to the
39  * .gitmodules file with the intention to stage them later, because when
40  * continuing we would stage the modifications the user didn't stage herself
41  * too. That might change in a future version when we learn to stage the
42  * changes we do ourselves without staging any previous modifications.
43  */
44 static int gitmodules_is_modified;
45
46 int is_staging_gitmodules_ok(void)
47 {
48         return !gitmodules_is_modified;
49 }
50
51 /*
52  * Try to update the "path" entry in the "submodule.<name>" section of the
53  * .gitmodules file. Return 0 only if a .gitmodules file was found, a section
54  * with the correct path=<oldpath> setting was found and we could update it.
55  */
56 int update_path_in_gitmodules(const char *oldpath, const char *newpath)
57 {
58         struct strbuf entry = STRBUF_INIT;
59         const struct submodule *submodule;
60
61         if (!file_exists(".gitmodules")) /* Do nothing without .gitmodules */
62                 return -1;
63
64         if (gitmodules_is_unmerged)
65                 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
66
67         submodule = submodule_from_path(null_sha1, oldpath);
68         if (!submodule || !submodule->name) {
69                 warning(_("Could not find section in .gitmodules where path=%s"), oldpath);
70                 return -1;
71         }
72         strbuf_addstr(&entry, "submodule.");
73         strbuf_addstr(&entry, submodule->name);
74         strbuf_addstr(&entry, ".path");
75         if (git_config_set_in_file_gently(".gitmodules", entry.buf, newpath) < 0) {
76                 /* Maybe the user already did that, don't error out here */
77                 warning(_("Could not update .gitmodules entry %s"), entry.buf);
78                 strbuf_release(&entry);
79                 return -1;
80         }
81         strbuf_release(&entry);
82         return 0;
83 }
84
85 /*
86  * Try to remove the "submodule.<name>" section from .gitmodules where the given
87  * path is configured. Return 0 only if a .gitmodules file was found, a section
88  * with the correct path=<path> setting was found and we could remove it.
89  */
90 int remove_path_from_gitmodules(const char *path)
91 {
92         struct strbuf sect = STRBUF_INIT;
93         const struct submodule *submodule;
94
95         if (!file_exists(".gitmodules")) /* Do nothing without .gitmodules */
96                 return -1;
97
98         if (gitmodules_is_unmerged)
99                 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
100
101         submodule = submodule_from_path(null_sha1, path);
102         if (!submodule || !submodule->name) {
103                 warning(_("Could not find section in .gitmodules where path=%s"), path);
104                 return -1;
105         }
106         strbuf_addstr(&sect, "submodule.");
107         strbuf_addstr(&sect, submodule->name);
108         if (git_config_rename_section_in_file(".gitmodules", sect.buf, NULL) < 0) {
109                 /* Maybe the user already did that, don't error out here */
110                 warning(_("Could not remove .gitmodules entry for %s"), path);
111                 strbuf_release(&sect);
112                 return -1;
113         }
114         strbuf_release(&sect);
115         return 0;
116 }
117
118 void stage_updated_gitmodules(void)
119 {
120         if (add_file_to_cache(".gitmodules", 0))
121                 die(_("staging updated .gitmodules failed"));
122 }
123
124 static int add_submodule_odb(const char *path)
125 {
126         struct strbuf objects_directory = STRBUF_INIT;
127         int ret = 0;
128
129         ret = strbuf_git_path_submodule(&objects_directory, path, "objects/");
130         if (ret)
131                 goto done;
132         if (!is_directory(objects_directory.buf)) {
133                 ret = -1;
134                 goto done;
135         }
136         add_to_alternates_memory(objects_directory.buf);
137 done:
138         strbuf_release(&objects_directory);
139         return ret;
140 }
141
142 void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
143                                              const char *path)
144 {
145         const struct submodule *submodule = submodule_from_path(null_sha1, path);
146         if (submodule) {
147                 if (submodule->ignore)
148                         handle_ignore_submodules_arg(diffopt, submodule->ignore);
149                 else if (gitmodules_is_unmerged)
150                         DIFF_OPT_SET(diffopt, IGNORE_SUBMODULES);
151         }
152 }
153
154 int submodule_config(const char *var, const char *value, void *cb)
155 {
156         if (!strcmp(var, "submodule.fetchjobs")) {
157                 parallel_jobs = git_config_int(var, value);
158                 if (parallel_jobs < 0)
159                         die(_("negative values not allowed for submodule.fetchJobs"));
160                 return 0;
161         } else if (starts_with(var, "submodule."))
162                 return parse_submodule_config_option(var, value);
163         else if (!strcmp(var, "fetch.recursesubmodules")) {
164                 config_fetch_recurse_submodules = parse_fetch_recurse_submodules_arg(var, value);
165                 return 0;
166         }
167         return 0;
168 }
169
170 void gitmodules_config(void)
171 {
172         const char *work_tree = get_git_work_tree();
173         if (work_tree) {
174                 struct strbuf gitmodules_path = STRBUF_INIT;
175                 int pos;
176                 strbuf_addstr(&gitmodules_path, work_tree);
177                 strbuf_addstr(&gitmodules_path, "/.gitmodules");
178                 if (read_cache() < 0)
179                         die("index file corrupt");
180                 pos = cache_name_pos(".gitmodules", 11);
181                 if (pos < 0) { /* .gitmodules not found or isn't merged */
182                         pos = -1 - pos;
183                         if (active_nr > pos) {  /* there is a .gitmodules */
184                                 const struct cache_entry *ce = active_cache[pos];
185                                 if (ce_namelen(ce) == 11 &&
186                                     !memcmp(ce->name, ".gitmodules", 11))
187                                         gitmodules_is_unmerged = 1;
188                         }
189                 } else if (pos < active_nr) {
190                         struct stat st;
191                         if (lstat(".gitmodules", &st) == 0 &&
192                             ce_match_stat(active_cache[pos], &st, 0) & DATA_CHANGED)
193                                 gitmodules_is_modified = 1;
194                 }
195
196                 if (!gitmodules_is_unmerged)
197                         git_config_from_file(submodule_config, gitmodules_path.buf, NULL);
198                 strbuf_release(&gitmodules_path);
199         }
200 }
201
202 void gitmodules_config_sha1(const unsigned char *commit_sha1)
203 {
204         struct strbuf rev = STRBUF_INIT;
205         unsigned char sha1[20];
206
207         if (gitmodule_sha1_from_commit(commit_sha1, sha1, &rev)) {
208                 git_config_from_blob_sha1(submodule_config, rev.buf,
209                                           sha1, NULL);
210         }
211         strbuf_release(&rev);
212 }
213
214 /*
215  * NEEDSWORK: With the addition of different configuration options to determine
216  * if a submodule is of interests, the validity of this function's name comes
217  * into question.  Once the dust has settled and more concrete terminology is
218  * decided upon, come up with a more proper name for this function.  One
219  * potential candidate could be 'is_submodule_active()'.
220  *
221  * Determine if a submodule has been initialized at a given 'path'
222  */
223 int is_submodule_initialized(const char *path)
224 {
225         int ret = 0;
226         char *key = NULL;
227         char *value = NULL;
228         const struct string_list *sl;
229         const struct submodule *module = submodule_from_path(null_sha1, path);
230
231         /* early return if there isn't a path->module mapping */
232         if (!module)
233                 return 0;
234
235         /* submodule.<name>.active is set */
236         key = xstrfmt("submodule.%s.active", module->name);
237         if (!git_config_get_bool(key, &ret)) {
238                 free(key);
239                 return ret;
240         }
241         free(key);
242
243         /* submodule.active is set */
244         sl = git_config_get_value_multi("submodule.active");
245         if (sl) {
246                 struct pathspec ps;
247                 struct argv_array args = ARGV_ARRAY_INIT;
248                 const struct string_list_item *item;
249
250                 for_each_string_list_item(item, sl) {
251                         argv_array_push(&args, item->string);
252                 }
253
254                 parse_pathspec(&ps, 0, 0, NULL, args.argv);
255                 ret = match_pathspec(&ps, path, strlen(path), 0, NULL, 1);
256
257                 argv_array_clear(&args);
258                 clear_pathspec(&ps);
259                 return ret;
260         }
261
262         /* fallback to checking if the URL is set */
263         key = xstrfmt("submodule.%s.url", module->name);
264         ret = !git_config_get_string(key, &value);
265
266         free(value);
267         free(key);
268         return ret;
269 }
270
271 /*
272  * Determine if a submodule has been populated at a given 'path'
273  */
274 int is_submodule_populated(const char *path)
275 {
276         int ret = 0;
277         char *gitdir = xstrfmt("%s/.git", path);
278
279         if (resolve_gitdir(gitdir))
280                 ret = 1;
281
282         free(gitdir);
283         return ret;
284 }
285
286 int parse_submodule_update_strategy(const char *value,
287                 struct submodule_update_strategy *dst)
288 {
289         free((void*)dst->command);
290         dst->command = NULL;
291         if (!strcmp(value, "none"))
292                 dst->type = SM_UPDATE_NONE;
293         else if (!strcmp(value, "checkout"))
294                 dst->type = SM_UPDATE_CHECKOUT;
295         else if (!strcmp(value, "rebase"))
296                 dst->type = SM_UPDATE_REBASE;
297         else if (!strcmp(value, "merge"))
298                 dst->type = SM_UPDATE_MERGE;
299         else if (skip_prefix(value, "!", &value)) {
300                 dst->type = SM_UPDATE_COMMAND;
301                 dst->command = xstrdup(value);
302         } else
303                 return -1;
304         return 0;
305 }
306
307 const char *submodule_strategy_to_string(const struct submodule_update_strategy *s)
308 {
309         struct strbuf sb = STRBUF_INIT;
310         switch (s->type) {
311         case SM_UPDATE_CHECKOUT:
312                 return "checkout";
313         case SM_UPDATE_MERGE:
314                 return "merge";
315         case SM_UPDATE_REBASE:
316                 return "rebase";
317         case SM_UPDATE_NONE:
318                 return "none";
319         case SM_UPDATE_UNSPECIFIED:
320                 return NULL;
321         case SM_UPDATE_COMMAND:
322                 strbuf_addf(&sb, "!%s", s->command);
323                 return strbuf_detach(&sb, NULL);
324         }
325         return NULL;
326 }
327
328 void handle_ignore_submodules_arg(struct diff_options *diffopt,
329                                   const char *arg)
330 {
331         DIFF_OPT_CLR(diffopt, IGNORE_SUBMODULES);
332         DIFF_OPT_CLR(diffopt, IGNORE_UNTRACKED_IN_SUBMODULES);
333         DIFF_OPT_CLR(diffopt, IGNORE_DIRTY_SUBMODULES);
334
335         if (!strcmp(arg, "all"))
336                 DIFF_OPT_SET(diffopt, IGNORE_SUBMODULES);
337         else if (!strcmp(arg, "untracked"))
338                 DIFF_OPT_SET(diffopt, IGNORE_UNTRACKED_IN_SUBMODULES);
339         else if (!strcmp(arg, "dirty"))
340                 DIFF_OPT_SET(diffopt, IGNORE_DIRTY_SUBMODULES);
341         else if (strcmp(arg, "none"))
342                 die("bad --ignore-submodules argument: %s", arg);
343 }
344
345 static int prepare_submodule_summary(struct rev_info *rev, const char *path,
346                 struct commit *left, struct commit *right,
347                 struct commit_list *merge_bases)
348 {
349         struct commit_list *list;
350
351         init_revisions(rev, NULL);
352         setup_revisions(0, NULL, rev, NULL);
353         rev->left_right = 1;
354         rev->first_parent_only = 1;
355         left->object.flags |= SYMMETRIC_LEFT;
356         add_pending_object(rev, &left->object, path);
357         add_pending_object(rev, &right->object, path);
358         for (list = merge_bases; list; list = list->next) {
359                 list->item->object.flags |= UNINTERESTING;
360                 add_pending_object(rev, &list->item->object,
361                         oid_to_hex(&list->item->object.oid));
362         }
363         return prepare_revision_walk(rev);
364 }
365
366 static void print_submodule_summary(struct rev_info *rev, FILE *f,
367                 const char *line_prefix,
368                 const char *del, const char *add, const char *reset)
369 {
370         static const char format[] = "  %m %s";
371         struct strbuf sb = STRBUF_INIT;
372         struct commit *commit;
373
374         while ((commit = get_revision(rev))) {
375                 struct pretty_print_context ctx = {0};
376                 ctx.date_mode = rev->date_mode;
377                 ctx.output_encoding = get_log_output_encoding();
378                 strbuf_setlen(&sb, 0);
379                 strbuf_addstr(&sb, line_prefix);
380                 if (commit->object.flags & SYMMETRIC_LEFT) {
381                         if (del)
382                                 strbuf_addstr(&sb, del);
383                 }
384                 else if (add)
385                         strbuf_addstr(&sb, add);
386                 format_commit_message(commit, format, &sb, &ctx);
387                 if (reset)
388                         strbuf_addstr(&sb, reset);
389                 strbuf_addch(&sb, '\n');
390                 fprintf(f, "%s", sb.buf);
391         }
392         strbuf_release(&sb);
393 }
394
395 /* Helper function to display the submodule header line prior to the full
396  * summary output. If it can locate the submodule objects directory it will
397  * attempt to lookup both the left and right commits and put them into the
398  * left and right pointers.
399  */
400 static void show_submodule_header(FILE *f, const char *path,
401                 const char *line_prefix,
402                 struct object_id *one, struct object_id *two,
403                 unsigned dirty_submodule, const char *meta,
404                 const char *reset,
405                 struct commit **left, struct commit **right,
406                 struct commit_list **merge_bases)
407 {
408         const char *message = NULL;
409         struct strbuf sb = STRBUF_INIT;
410         int fast_forward = 0, fast_backward = 0;
411
412         if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
413                 fprintf(f, "%sSubmodule %s contains untracked content\n",
414                         line_prefix, path);
415         if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
416                 fprintf(f, "%sSubmodule %s contains modified content\n",
417                         line_prefix, path);
418
419         if (is_null_oid(one))
420                 message = "(new submodule)";
421         else if (is_null_oid(two))
422                 message = "(submodule deleted)";
423
424         if (add_submodule_odb(path)) {
425                 if (!message)
426                         message = "(not initialized)";
427                 goto output_header;
428         }
429
430         /*
431          * Attempt to lookup the commit references, and determine if this is
432          * a fast forward or fast backwards update.
433          */
434         *left = lookup_commit_reference(one->hash);
435         *right = lookup_commit_reference(two->hash);
436
437         /*
438          * Warn about missing commits in the submodule project, but only if
439          * they aren't null.
440          */
441         if ((!is_null_oid(one) && !*left) ||
442              (!is_null_oid(two) && !*right))
443                 message = "(commits not present)";
444
445         *merge_bases = get_merge_bases(*left, *right);
446         if (*merge_bases) {
447                 if ((*merge_bases)->item == *left)
448                         fast_forward = 1;
449                 else if ((*merge_bases)->item == *right)
450                         fast_backward = 1;
451         }
452
453         if (!oidcmp(one, two)) {
454                 strbuf_release(&sb);
455                 return;
456         }
457
458 output_header:
459         strbuf_addf(&sb, "%s%sSubmodule %s ", line_prefix, meta, path);
460         strbuf_add_unique_abbrev(&sb, one->hash, DEFAULT_ABBREV);
461         strbuf_addstr(&sb, (fast_backward || fast_forward) ? ".." : "...");
462         strbuf_add_unique_abbrev(&sb, two->hash, DEFAULT_ABBREV);
463         if (message)
464                 strbuf_addf(&sb, " %s%s\n", message, reset);
465         else
466                 strbuf_addf(&sb, "%s:%s\n", fast_backward ? " (rewind)" : "", reset);
467         fwrite(sb.buf, sb.len, 1, f);
468
469         strbuf_release(&sb);
470 }
471
472 void show_submodule_summary(FILE *f, const char *path,
473                 const char *line_prefix,
474                 struct object_id *one, struct object_id *two,
475                 unsigned dirty_submodule, const char *meta,
476                 const char *del, const char *add, const char *reset)
477 {
478         struct rev_info rev;
479         struct commit *left = NULL, *right = NULL;
480         struct commit_list *merge_bases = NULL;
481
482         show_submodule_header(f, path, line_prefix, one, two, dirty_submodule,
483                               meta, reset, &left, &right, &merge_bases);
484
485         /*
486          * If we don't have both a left and a right pointer, there is no
487          * reason to try and display a summary. The header line should contain
488          * all the information the user needs.
489          */
490         if (!left || !right)
491                 goto out;
492
493         /* Treat revision walker failure the same as missing commits */
494         if (prepare_submodule_summary(&rev, path, left, right, merge_bases)) {
495                 fprintf(f, "%s(revision walker failed)\n", line_prefix);
496                 goto out;
497         }
498
499         print_submodule_summary(&rev, f, line_prefix, del, add, reset);
500
501 out:
502         if (merge_bases)
503                 free_commit_list(merge_bases);
504         clear_commit_marks(left, ~0);
505         clear_commit_marks(right, ~0);
506 }
507
508 void show_submodule_inline_diff(FILE *f, const char *path,
509                 const char *line_prefix,
510                 struct object_id *one, struct object_id *two,
511                 unsigned dirty_submodule, const char *meta,
512                 const char *del, const char *add, const char *reset,
513                 const struct diff_options *o)
514 {
515         const struct object_id *old = &empty_tree_oid, *new = &empty_tree_oid;
516         struct commit *left = NULL, *right = NULL;
517         struct commit_list *merge_bases = NULL;
518         struct strbuf submodule_dir = STRBUF_INIT;
519         struct child_process cp = CHILD_PROCESS_INIT;
520
521         show_submodule_header(f, path, line_prefix, one, two, dirty_submodule,
522                               meta, reset, &left, &right, &merge_bases);
523
524         /* We need a valid left and right commit to display a difference */
525         if (!(left || is_null_oid(one)) ||
526             !(right || is_null_oid(two)))
527                 goto done;
528
529         if (left)
530                 old = one;
531         if (right)
532                 new = two;
533
534         fflush(f);
535         cp.git_cmd = 1;
536         cp.dir = path;
537         cp.out = dup(fileno(f));
538         cp.no_stdin = 1;
539
540         /* TODO: other options may need to be passed here. */
541         argv_array_push(&cp.args, "diff");
542         argv_array_pushf(&cp.args, "--line-prefix=%s", line_prefix);
543         if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
544                 argv_array_pushf(&cp.args, "--src-prefix=%s%s/",
545                                  o->b_prefix, path);
546                 argv_array_pushf(&cp.args, "--dst-prefix=%s%s/",
547                                  o->a_prefix, path);
548         } else {
549                 argv_array_pushf(&cp.args, "--src-prefix=%s%s/",
550                                  o->a_prefix, path);
551                 argv_array_pushf(&cp.args, "--dst-prefix=%s%s/",
552                                  o->b_prefix, path);
553         }
554         argv_array_push(&cp.args, oid_to_hex(old));
555         /*
556          * If the submodule has modified content, we will diff against the
557          * work tree, under the assumption that the user has asked for the
558          * diff format and wishes to actually see all differences even if they
559          * haven't yet been committed to the submodule yet.
560          */
561         if (!(dirty_submodule & DIRTY_SUBMODULE_MODIFIED))
562                 argv_array_push(&cp.args, oid_to_hex(new));
563
564         if (run_command(&cp))
565                 fprintf(f, "(diff failed)\n");
566
567 done:
568         strbuf_release(&submodule_dir);
569         if (merge_bases)
570                 free_commit_list(merge_bases);
571         if (left)
572                 clear_commit_marks(left, ~0);
573         if (right)
574                 clear_commit_marks(right, ~0);
575 }
576
577 void set_config_fetch_recurse_submodules(int value)
578 {
579         config_fetch_recurse_submodules = value;
580 }
581
582 static int has_remote(const char *refname, const struct object_id *oid,
583                       int flags, void *cb_data)
584 {
585         return 1;
586 }
587
588 static int append_sha1_to_argv(const unsigned char sha1[20], void *data)
589 {
590         struct argv_array *argv = data;
591         argv_array_push(argv, sha1_to_hex(sha1));
592         return 0;
593 }
594
595 static int check_has_commit(const unsigned char sha1[20], void *data)
596 {
597         int *has_commit = data;
598
599         if (!lookup_commit_reference(sha1))
600                 *has_commit = 0;
601
602         return 0;
603 }
604
605 static int submodule_has_commits(const char *path, struct sha1_array *commits)
606 {
607         int has_commit = 1;
608
609         if (add_submodule_odb(path))
610                 return 0;
611
612         sha1_array_for_each_unique(commits, check_has_commit, &has_commit);
613         return has_commit;
614 }
615
616 static int submodule_needs_pushing(const char *path, struct sha1_array *commits)
617 {
618         if (!submodule_has_commits(path, commits))
619                 /*
620                  * NOTE: We do consider it safe to return "no" here. The
621                  * correct answer would be "We do not know" instead of
622                  * "No push needed", but it is quite hard to change
623                  * the submodule pointer without having the submodule
624                  * around. If a user did however change the submodules
625                  * without having the submodule around, this indicates
626                  * an expert who knows what they are doing or a
627                  * maintainer integrating work from other people. In
628                  * both cases it should be safe to skip this check.
629                  */
630                 return 0;
631
632         if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
633                 struct child_process cp = CHILD_PROCESS_INIT;
634                 struct strbuf buf = STRBUF_INIT;
635                 int needs_pushing = 0;
636
637                 argv_array_push(&cp.args, "rev-list");
638                 sha1_array_for_each_unique(commits, append_sha1_to_argv, &cp.args);
639                 argv_array_pushl(&cp.args, "--not", "--remotes", "-n", "1" , NULL);
640
641                 prepare_submodule_repo_env(&cp.env_array);
642                 cp.git_cmd = 1;
643                 cp.no_stdin = 1;
644                 cp.out = -1;
645                 cp.dir = path;
646                 if (start_command(&cp))
647                         die("Could not run 'git rev-list <commits> --not --remotes -n 1' command in submodule %s",
648                                         path);
649                 if (strbuf_read(&buf, cp.out, 41))
650                         needs_pushing = 1;
651                 finish_command(&cp);
652                 close(cp.out);
653                 strbuf_release(&buf);
654                 return needs_pushing;
655         }
656
657         return 0;
658 }
659
660 static struct sha1_array *submodule_commits(struct string_list *submodules,
661                                             const char *path)
662 {
663         struct string_list_item *item;
664
665         item = string_list_insert(submodules, path);
666         if (item->util)
667                 return (struct sha1_array *) item->util;
668
669         /* NEEDSWORK: should we have sha1_array_init()? */
670         item->util = xcalloc(1, sizeof(struct sha1_array));
671         return (struct sha1_array *) item->util;
672 }
673
674 static void collect_submodules_from_diff(struct diff_queue_struct *q,
675                                          struct diff_options *options,
676                                          void *data)
677 {
678         int i;
679         struct string_list *submodules = data;
680
681         for (i = 0; i < q->nr; i++) {
682                 struct diff_filepair *p = q->queue[i];
683                 struct sha1_array *commits;
684                 if (!S_ISGITLINK(p->two->mode))
685                         continue;
686                 commits = submodule_commits(submodules, p->two->path);
687                 sha1_array_append(commits, p->two->oid.hash);
688         }
689 }
690
691 static void find_unpushed_submodule_commits(struct commit *commit,
692                 struct string_list *needs_pushing)
693 {
694         struct rev_info rev;
695
696         init_revisions(&rev, NULL);
697         rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
698         rev.diffopt.format_callback = collect_submodules_from_diff;
699         rev.diffopt.format_callback_data = needs_pushing;
700         diff_tree_combined_merge(commit, 1, &rev);
701 }
702
703 static void free_submodules_sha1s(struct string_list *submodules)
704 {
705         struct string_list_item *item;
706         for_each_string_list_item(item, submodules)
707                 sha1_array_clear((struct sha1_array *) item->util);
708         string_list_clear(submodules, 1);
709 }
710
711 int find_unpushed_submodules(struct sha1_array *commits,
712                 const char *remotes_name, struct string_list *needs_pushing)
713 {
714         struct rev_info rev;
715         struct commit *commit;
716         struct string_list submodules = STRING_LIST_INIT_DUP;
717         struct string_list_item *submodule;
718         struct argv_array argv = ARGV_ARRAY_INIT;
719
720         init_revisions(&rev, NULL);
721
722         /* argv.argv[0] will be ignored by setup_revisions */
723         argv_array_push(&argv, "find_unpushed_submodules");
724         sha1_array_for_each_unique(commits, append_sha1_to_argv, &argv);
725         argv_array_push(&argv, "--not");
726         argv_array_pushf(&argv, "--remotes=%s", remotes_name);
727
728         setup_revisions(argv.argc, argv.argv, &rev, NULL);
729         if (prepare_revision_walk(&rev))
730                 die("revision walk setup failed");
731
732         while ((commit = get_revision(&rev)) != NULL)
733                 find_unpushed_submodule_commits(commit, &submodules);
734
735         reset_revision_walk();
736         argv_array_clear(&argv);
737
738         for_each_string_list_item(submodule, &submodules) {
739                 struct sha1_array *commits = (struct sha1_array *) submodule->util;
740
741                 if (submodule_needs_pushing(submodule->string, commits))
742                         string_list_insert(needs_pushing, submodule->string);
743         }
744         free_submodules_sha1s(&submodules);
745
746         return needs_pushing->nr;
747 }
748
749 static int push_submodule(const char *path, int dry_run)
750 {
751         if (add_submodule_odb(path))
752                 return 1;
753
754         if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
755                 struct child_process cp = CHILD_PROCESS_INIT;
756                 argv_array_push(&cp.args, "push");
757                 if (dry_run)
758                         argv_array_push(&cp.args, "--dry-run");
759
760                 prepare_submodule_repo_env(&cp.env_array);
761                 cp.git_cmd = 1;
762                 cp.no_stdin = 1;
763                 cp.dir = path;
764                 if (run_command(&cp))
765                         return 0;
766                 close(cp.out);
767         }
768
769         return 1;
770 }
771
772 int push_unpushed_submodules(struct sha1_array *commits,
773                              const char *remotes_name,
774                              int dry_run)
775 {
776         int i, ret = 1;
777         struct string_list needs_pushing = STRING_LIST_INIT_DUP;
778
779         if (!find_unpushed_submodules(commits, remotes_name, &needs_pushing))
780                 return 1;
781
782         for (i = 0; i < needs_pushing.nr; i++) {
783                 const char *path = needs_pushing.items[i].string;
784                 fprintf(stderr, "Pushing submodule '%s'\n", path);
785                 if (!push_submodule(path, dry_run)) {
786                         fprintf(stderr, "Unable to push submodule '%s'\n", path);
787                         ret = 0;
788                 }
789         }
790
791         string_list_clear(&needs_pushing, 0);
792
793         return ret;
794 }
795
796 static int is_submodule_commit_present(const char *path, unsigned char sha1[20])
797 {
798         int is_present = 0;
799         if (!add_submodule_odb(path) && lookup_commit_reference(sha1)) {
800                 /* Even if the submodule is checked out and the commit is
801                  * present, make sure it is reachable from a ref. */
802                 struct child_process cp = CHILD_PROCESS_INIT;
803                 const char *argv[] = {"rev-list", "-n", "1", NULL, "--not", "--all", NULL};
804                 struct strbuf buf = STRBUF_INIT;
805
806                 argv[3] = sha1_to_hex(sha1);
807                 cp.argv = argv;
808                 prepare_submodule_repo_env(&cp.env_array);
809                 cp.git_cmd = 1;
810                 cp.no_stdin = 1;
811                 cp.dir = path;
812                 if (!capture_command(&cp, &buf, 1024) && !buf.len)
813                         is_present = 1;
814
815                 strbuf_release(&buf);
816         }
817         return is_present;
818 }
819
820 static void submodule_collect_changed_cb(struct diff_queue_struct *q,
821                                          struct diff_options *options,
822                                          void *data)
823 {
824         int i;
825         for (i = 0; i < q->nr; i++) {
826                 struct diff_filepair *p = q->queue[i];
827                 if (!S_ISGITLINK(p->two->mode))
828                         continue;
829
830                 if (S_ISGITLINK(p->one->mode)) {
831                         /* NEEDSWORK: We should honor the name configured in
832                          * the .gitmodules file of the commit we are examining
833                          * here to be able to correctly follow submodules
834                          * being moved around. */
835                         struct string_list_item *path;
836                         path = unsorted_string_list_lookup(&changed_submodule_paths, p->two->path);
837                         if (!path && !is_submodule_commit_present(p->two->path, p->two->oid.hash))
838                                 string_list_append(&changed_submodule_paths, xstrdup(p->two->path));
839                 } else {
840                         /* Submodule is new or was moved here */
841                         /* NEEDSWORK: When the .git directories of submodules
842                          * live inside the superprojects .git directory some
843                          * day we should fetch new submodules directly into
844                          * that location too when config or options request
845                          * that so they can be checked out from there. */
846                         continue;
847                 }
848         }
849 }
850
851 static int add_sha1_to_array(const char *ref, const struct object_id *oid,
852                              int flags, void *data)
853 {
854         sha1_array_append(data, oid->hash);
855         return 0;
856 }
857
858 void check_for_new_submodule_commits(unsigned char new_sha1[20])
859 {
860         if (!initialized_fetch_ref_tips) {
861                 for_each_ref(add_sha1_to_array, &ref_tips_before_fetch);
862                 initialized_fetch_ref_tips = 1;
863         }
864
865         sha1_array_append(&ref_tips_after_fetch, new_sha1);
866 }
867
868 static int add_sha1_to_argv(const unsigned char sha1[20], void *data)
869 {
870         argv_array_push(data, sha1_to_hex(sha1));
871         return 0;
872 }
873
874 static void calculate_changed_submodule_paths(void)
875 {
876         struct rev_info rev;
877         struct commit *commit;
878         struct argv_array argv = ARGV_ARRAY_INIT;
879
880         /* No need to check if there are no submodules configured */
881         if (!submodule_from_path(NULL, NULL))
882                 return;
883
884         init_revisions(&rev, NULL);
885         argv_array_push(&argv, "--"); /* argv[0] program name */
886         sha1_array_for_each_unique(&ref_tips_after_fetch,
887                                    add_sha1_to_argv, &argv);
888         argv_array_push(&argv, "--not");
889         sha1_array_for_each_unique(&ref_tips_before_fetch,
890                                    add_sha1_to_argv, &argv);
891         setup_revisions(argv.argc, argv.argv, &rev, NULL);
892         if (prepare_revision_walk(&rev))
893                 die("revision walk setup failed");
894
895         /*
896          * Collect all submodules (whether checked out or not) for which new
897          * commits have been recorded upstream in "changed_submodule_paths".
898          */
899         while ((commit = get_revision(&rev))) {
900                 struct commit_list *parent = commit->parents;
901                 while (parent) {
902                         struct diff_options diff_opts;
903                         diff_setup(&diff_opts);
904                         DIFF_OPT_SET(&diff_opts, RECURSIVE);
905                         diff_opts.output_format |= DIFF_FORMAT_CALLBACK;
906                         diff_opts.format_callback = submodule_collect_changed_cb;
907                         diff_setup_done(&diff_opts);
908                         diff_tree_sha1(parent->item->object.oid.hash, commit->object.oid.hash, "", &diff_opts);
909                         diffcore_std(&diff_opts);
910                         diff_flush(&diff_opts);
911                         parent = parent->next;
912                 }
913         }
914
915         argv_array_clear(&argv);
916         sha1_array_clear(&ref_tips_before_fetch);
917         sha1_array_clear(&ref_tips_after_fetch);
918         initialized_fetch_ref_tips = 0;
919 }
920
921 struct submodule_parallel_fetch {
922         int count;
923         struct argv_array args;
924         const char *work_tree;
925         const char *prefix;
926         int command_line_option;
927         int quiet;
928         int result;
929 };
930 #define SPF_INIT {0, ARGV_ARRAY_INIT, NULL, NULL, 0, 0, 0}
931
932 static int get_next_submodule(struct child_process *cp,
933                               struct strbuf *err, void *data, void **task_cb)
934 {
935         int ret = 0;
936         struct submodule_parallel_fetch *spf = data;
937
938         for (; spf->count < active_nr; spf->count++) {
939                 struct strbuf submodule_path = STRBUF_INIT;
940                 struct strbuf submodule_git_dir = STRBUF_INIT;
941                 struct strbuf submodule_prefix = STRBUF_INIT;
942                 const struct cache_entry *ce = active_cache[spf->count];
943                 const char *git_dir, *default_argv;
944                 const struct submodule *submodule;
945
946                 if (!S_ISGITLINK(ce->ce_mode))
947                         continue;
948
949                 submodule = submodule_from_path(null_sha1, ce->name);
950                 if (!submodule)
951                         submodule = submodule_from_name(null_sha1, ce->name);
952
953                 default_argv = "yes";
954                 if (spf->command_line_option == RECURSE_SUBMODULES_DEFAULT) {
955                         if (submodule &&
956                             submodule->fetch_recurse !=
957                                                 RECURSE_SUBMODULES_NONE) {
958                                 if (submodule->fetch_recurse ==
959                                                 RECURSE_SUBMODULES_OFF)
960                                         continue;
961                                 if (submodule->fetch_recurse ==
962                                                 RECURSE_SUBMODULES_ON_DEMAND) {
963                                         if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
964                                                 continue;
965                                         default_argv = "on-demand";
966                                 }
967                         } else {
968                                 if ((config_fetch_recurse_submodules == RECURSE_SUBMODULES_OFF) ||
969                                     gitmodules_is_unmerged)
970                                         continue;
971                                 if (config_fetch_recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND) {
972                                         if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
973                                                 continue;
974                                         default_argv = "on-demand";
975                                 }
976                         }
977                 } else if (spf->command_line_option == RECURSE_SUBMODULES_ON_DEMAND) {
978                         if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
979                                 continue;
980                         default_argv = "on-demand";
981                 }
982
983                 strbuf_addf(&submodule_path, "%s/%s", spf->work_tree, ce->name);
984                 strbuf_addf(&submodule_git_dir, "%s/.git", submodule_path.buf);
985                 strbuf_addf(&submodule_prefix, "%s%s/", spf->prefix, ce->name);
986                 git_dir = read_gitfile(submodule_git_dir.buf);
987                 if (!git_dir)
988                         git_dir = submodule_git_dir.buf;
989                 if (is_directory(git_dir)) {
990                         child_process_init(cp);
991                         cp->dir = strbuf_detach(&submodule_path, NULL);
992                         prepare_submodule_repo_env(&cp->env_array);
993                         cp->git_cmd = 1;
994                         if (!spf->quiet)
995                                 strbuf_addf(err, "Fetching submodule %s%s\n",
996                                             spf->prefix, ce->name);
997                         argv_array_init(&cp->args);
998                         argv_array_pushv(&cp->args, spf->args.argv);
999                         argv_array_push(&cp->args, default_argv);
1000                         argv_array_push(&cp->args, "--submodule-prefix");
1001                         argv_array_push(&cp->args, submodule_prefix.buf);
1002                         ret = 1;
1003                 }
1004                 strbuf_release(&submodule_path);
1005                 strbuf_release(&submodule_git_dir);
1006                 strbuf_release(&submodule_prefix);
1007                 if (ret) {
1008                         spf->count++;
1009                         return 1;
1010                 }
1011         }
1012         return 0;
1013 }
1014
1015 static int fetch_start_failure(struct strbuf *err,
1016                                void *cb, void *task_cb)
1017 {
1018         struct submodule_parallel_fetch *spf = cb;
1019
1020         spf->result = 1;
1021
1022         return 0;
1023 }
1024
1025 static int fetch_finish(int retvalue, struct strbuf *err,
1026                         void *cb, void *task_cb)
1027 {
1028         struct submodule_parallel_fetch *spf = cb;
1029
1030         if (retvalue)
1031                 spf->result = 1;
1032
1033         return 0;
1034 }
1035
1036 int fetch_populated_submodules(const struct argv_array *options,
1037                                const char *prefix, int command_line_option,
1038                                int quiet, int max_parallel_jobs)
1039 {
1040         int i;
1041         struct submodule_parallel_fetch spf = SPF_INIT;
1042
1043         spf.work_tree = get_git_work_tree();
1044         spf.command_line_option = command_line_option;
1045         spf.quiet = quiet;
1046         spf.prefix = prefix;
1047
1048         if (!spf.work_tree)
1049                 goto out;
1050
1051         if (read_cache() < 0)
1052                 die("index file corrupt");
1053
1054         argv_array_push(&spf.args, "fetch");
1055         for (i = 0; i < options->argc; i++)
1056                 argv_array_push(&spf.args, options->argv[i]);
1057         argv_array_push(&spf.args, "--recurse-submodules-default");
1058         /* default value, "--submodule-prefix" and its value are added later */
1059
1060         if (max_parallel_jobs < 0)
1061                 max_parallel_jobs = parallel_jobs;
1062
1063         calculate_changed_submodule_paths();
1064         run_processes_parallel(max_parallel_jobs,
1065                                get_next_submodule,
1066                                fetch_start_failure,
1067                                fetch_finish,
1068                                &spf);
1069
1070         argv_array_clear(&spf.args);
1071 out:
1072         string_list_clear(&changed_submodule_paths, 1);
1073         return spf.result;
1074 }
1075
1076 unsigned is_submodule_modified(const char *path, int ignore_untracked)
1077 {
1078         ssize_t len;
1079         struct child_process cp = CHILD_PROCESS_INIT;
1080         const char *argv[] = {
1081                 "status",
1082                 "--porcelain",
1083                 NULL,
1084                 NULL,
1085         };
1086         struct strbuf buf = STRBUF_INIT;
1087         unsigned dirty_submodule = 0;
1088         const char *line, *next_line;
1089         const char *git_dir;
1090
1091         strbuf_addf(&buf, "%s/.git", path);
1092         git_dir = read_gitfile(buf.buf);
1093         if (!git_dir)
1094                 git_dir = buf.buf;
1095         if (!is_directory(git_dir)) {
1096                 strbuf_release(&buf);
1097                 /* The submodule is not checked out, so it is not modified */
1098                 return 0;
1099
1100         }
1101         strbuf_reset(&buf);
1102
1103         if (ignore_untracked)
1104                 argv[2] = "-uno";
1105
1106         cp.argv = argv;
1107         prepare_submodule_repo_env(&cp.env_array);
1108         cp.git_cmd = 1;
1109         cp.no_stdin = 1;
1110         cp.out = -1;
1111         cp.dir = path;
1112         if (start_command(&cp))
1113                 die("Could not run 'git status --porcelain' in submodule %s", path);
1114
1115         len = strbuf_read(&buf, cp.out, 1024);
1116         line = buf.buf;
1117         while (len > 2) {
1118                 if ((line[0] == '?') && (line[1] == '?')) {
1119                         dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1120                         if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
1121                                 break;
1122                 } else {
1123                         dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
1124                         if (ignore_untracked ||
1125                             (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED))
1126                                 break;
1127                 }
1128                 next_line = strchr(line, '\n');
1129                 if (!next_line)
1130                         break;
1131                 next_line++;
1132                 len -= (next_line - line);
1133                 line = next_line;
1134         }
1135         close(cp.out);
1136
1137         if (finish_command(&cp))
1138                 die("'git status --porcelain' failed in submodule %s", path);
1139
1140         strbuf_release(&buf);
1141         return dirty_submodule;
1142 }
1143
1144 int submodule_uses_gitfile(const char *path)
1145 {
1146         struct child_process cp = CHILD_PROCESS_INIT;
1147         const char *argv[] = {
1148                 "submodule",
1149                 "foreach",
1150                 "--quiet",
1151                 "--recursive",
1152                 "test -f .git",
1153                 NULL,
1154         };
1155         struct strbuf buf = STRBUF_INIT;
1156         const char *git_dir;
1157
1158         strbuf_addf(&buf, "%s/.git", path);
1159         git_dir = read_gitfile(buf.buf);
1160         if (!git_dir) {
1161                 strbuf_release(&buf);
1162                 return 0;
1163         }
1164         strbuf_release(&buf);
1165
1166         /* Now test that all nested submodules use a gitfile too */
1167         cp.argv = argv;
1168         prepare_submodule_repo_env(&cp.env_array);
1169         cp.git_cmd = 1;
1170         cp.no_stdin = 1;
1171         cp.no_stderr = 1;
1172         cp.no_stdout = 1;
1173         cp.dir = path;
1174         if (run_command(&cp))
1175                 return 0;
1176
1177         return 1;
1178 }
1179
1180 /*
1181  * Check if it is a bad idea to remove a submodule, i.e. if we'd lose data
1182  * when doing so.
1183  *
1184  * Return 1 if we'd lose data, return 0 if the removal is fine,
1185  * and negative values for errors.
1186  */
1187 int bad_to_remove_submodule(const char *path, unsigned flags)
1188 {
1189         ssize_t len;
1190         struct child_process cp = CHILD_PROCESS_INIT;
1191         struct strbuf buf = STRBUF_INIT;
1192         int ret = 0;
1193
1194         if (!file_exists(path) || is_empty_dir(path))
1195                 return 0;
1196
1197         if (!submodule_uses_gitfile(path))
1198                 return 1;
1199
1200         argv_array_pushl(&cp.args, "status", "--porcelain",
1201                                    "--ignore-submodules=none", NULL);
1202
1203         if (flags & SUBMODULE_REMOVAL_IGNORE_UNTRACKED)
1204                 argv_array_push(&cp.args, "-uno");
1205         else
1206                 argv_array_push(&cp.args, "-uall");
1207
1208         if (!(flags & SUBMODULE_REMOVAL_IGNORE_IGNORED_UNTRACKED))
1209                 argv_array_push(&cp.args, "--ignored");
1210
1211         prepare_submodule_repo_env(&cp.env_array);
1212         cp.git_cmd = 1;
1213         cp.no_stdin = 1;
1214         cp.out = -1;
1215         cp.dir = path;
1216         if (start_command(&cp)) {
1217                 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
1218                         die(_("could not start 'git status in submodule '%s'"),
1219                                 path);
1220                 ret = -1;
1221                 goto out;
1222         }
1223
1224         len = strbuf_read(&buf, cp.out, 1024);
1225         if (len > 2)
1226                 ret = 1;
1227         close(cp.out);
1228
1229         if (finish_command(&cp)) {
1230                 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
1231                         die(_("could not run 'git status in submodule '%s'"),
1232                                 path);
1233                 ret = -1;
1234         }
1235 out:
1236         strbuf_release(&buf);
1237         return ret;
1238 }
1239
1240 static int find_first_merges(struct object_array *result, const char *path,
1241                 struct commit *a, struct commit *b)
1242 {
1243         int i, j;
1244         struct object_array merges = OBJECT_ARRAY_INIT;
1245         struct commit *commit;
1246         int contains_another;
1247
1248         char merged_revision[42];
1249         const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
1250                                    "--all", merged_revision, NULL };
1251         struct rev_info revs;
1252         struct setup_revision_opt rev_opts;
1253
1254         memset(result, 0, sizeof(struct object_array));
1255         memset(&rev_opts, 0, sizeof(rev_opts));
1256
1257         /* get all revisions that merge commit a */
1258         snprintf(merged_revision, sizeof(merged_revision), "^%s",
1259                         oid_to_hex(&a->object.oid));
1260         init_revisions(&revs, NULL);
1261         rev_opts.submodule = path;
1262         setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
1263
1264         /* save all revisions from the above list that contain b */
1265         if (prepare_revision_walk(&revs))
1266                 die("revision walk setup failed");
1267         while ((commit = get_revision(&revs)) != NULL) {
1268                 struct object *o = &(commit->object);
1269                 if (in_merge_bases(b, commit))
1270                         add_object_array(o, NULL, &merges);
1271         }
1272         reset_revision_walk();
1273
1274         /* Now we've got all merges that contain a and b. Prune all
1275          * merges that contain another found merge and save them in
1276          * result.
1277          */
1278         for (i = 0; i < merges.nr; i++) {
1279                 struct commit *m1 = (struct commit *) merges.objects[i].item;
1280
1281                 contains_another = 0;
1282                 for (j = 0; j < merges.nr; j++) {
1283                         struct commit *m2 = (struct commit *) merges.objects[j].item;
1284                         if (i != j && in_merge_bases(m2, m1)) {
1285                                 contains_another = 1;
1286                                 break;
1287                         }
1288                 }
1289
1290                 if (!contains_another)
1291                         add_object_array(merges.objects[i].item, NULL, result);
1292         }
1293
1294         free(merges.objects);
1295         return result->nr;
1296 }
1297
1298 static void print_commit(struct commit *commit)
1299 {
1300         struct strbuf sb = STRBUF_INIT;
1301         struct pretty_print_context ctx = {0};
1302         ctx.date_mode.type = DATE_NORMAL;
1303         format_commit_message(commit, " %h: %m %s", &sb, &ctx);
1304         fprintf(stderr, "%s\n", sb.buf);
1305         strbuf_release(&sb);
1306 }
1307
1308 #define MERGE_WARNING(path, msg) \
1309         warning("Failed to merge submodule %s (%s)", path, msg);
1310
1311 int merge_submodule(unsigned char result[20], const char *path,
1312                     const unsigned char base[20], const unsigned char a[20],
1313                     const unsigned char b[20], int search)
1314 {
1315         struct commit *commit_base, *commit_a, *commit_b;
1316         int parent_count;
1317         struct object_array merges;
1318
1319         int i;
1320
1321         /* store a in result in case we fail */
1322         hashcpy(result, a);
1323
1324         /* we can not handle deletion conflicts */
1325         if (is_null_sha1(base))
1326                 return 0;
1327         if (is_null_sha1(a))
1328                 return 0;
1329         if (is_null_sha1(b))
1330                 return 0;
1331
1332         if (add_submodule_odb(path)) {
1333                 MERGE_WARNING(path, "not checked out");
1334                 return 0;
1335         }
1336
1337         if (!(commit_base = lookup_commit_reference(base)) ||
1338             !(commit_a = lookup_commit_reference(a)) ||
1339             !(commit_b = lookup_commit_reference(b))) {
1340                 MERGE_WARNING(path, "commits not present");
1341                 return 0;
1342         }
1343
1344         /* check whether both changes are forward */
1345         if (!in_merge_bases(commit_base, commit_a) ||
1346             !in_merge_bases(commit_base, commit_b)) {
1347                 MERGE_WARNING(path, "commits don't follow merge-base");
1348                 return 0;
1349         }
1350
1351         /* Case #1: a is contained in b or vice versa */
1352         if (in_merge_bases(commit_a, commit_b)) {
1353                 hashcpy(result, b);
1354                 return 1;
1355         }
1356         if (in_merge_bases(commit_b, commit_a)) {
1357                 hashcpy(result, a);
1358                 return 1;
1359         }
1360
1361         /*
1362          * Case #2: There are one or more merges that contain a and b in
1363          * the submodule. If there is only one, then present it as a
1364          * suggestion to the user, but leave it marked unmerged so the
1365          * user needs to confirm the resolution.
1366          */
1367
1368         /* Skip the search if makes no sense to the calling context.  */
1369         if (!search)
1370                 return 0;
1371
1372         /* find commit which merges them */
1373         parent_count = find_first_merges(&merges, path, commit_a, commit_b);
1374         switch (parent_count) {
1375         case 0:
1376                 MERGE_WARNING(path, "merge following commits not found");
1377                 break;
1378
1379         case 1:
1380                 MERGE_WARNING(path, "not fast-forward");
1381                 fprintf(stderr, "Found a possible merge resolution "
1382                                 "for the submodule:\n");
1383                 print_commit((struct commit *) merges.objects[0].item);
1384                 fprintf(stderr,
1385                         "If this is correct simply add it to the index "
1386                         "for example\n"
1387                         "by using:\n\n"
1388                         "  git update-index --cacheinfo 160000 %s \"%s\"\n\n"
1389                         "which will accept this suggestion.\n",
1390                         oid_to_hex(&merges.objects[0].item->oid), path);
1391                 break;
1392
1393         default:
1394                 MERGE_WARNING(path, "multiple merges found");
1395                 for (i = 0; i < merges.nr; i++)
1396                         print_commit((struct commit *) merges.objects[i].item);
1397         }
1398
1399         free(merges.objects);
1400         return 0;
1401 }
1402
1403 int parallel_submodules(void)
1404 {
1405         return parallel_jobs;
1406 }
1407
1408 void prepare_submodule_repo_env(struct argv_array *out)
1409 {
1410         const char * const *var;
1411
1412         for (var = local_repo_env; *var; var++) {
1413                 if (strcmp(*var, CONFIG_DATA_ENVIRONMENT))
1414                         argv_array_push(out, *var);
1415         }
1416         argv_array_pushf(out, "%s=%s", GIT_DIR_ENVIRONMENT,
1417                          DEFAULT_GIT_DIR_ENVIRONMENT);
1418 }
1419
1420 /*
1421  * Embeds a single submodules git directory into the superprojects git dir,
1422  * non recursively.
1423  */
1424 static void relocate_single_git_dir_into_superproject(const char *prefix,
1425                                                       const char *path)
1426 {
1427         char *old_git_dir = NULL, *real_old_git_dir = NULL, *real_new_git_dir = NULL;
1428         const char *new_git_dir;
1429         const struct submodule *sub;
1430
1431         if (submodule_uses_worktrees(path))
1432                 die(_("relocate_gitdir for submodule '%s' with "
1433                       "more than one worktree not supported"), path);
1434
1435         old_git_dir = xstrfmt("%s/.git", path);
1436         if (read_gitfile(old_git_dir))
1437                 /* If it is an actual gitfile, it doesn't need migration. */
1438                 return;
1439
1440         real_old_git_dir = real_pathdup(old_git_dir, 1);
1441
1442         sub = submodule_from_path(null_sha1, path);
1443         if (!sub)
1444                 die(_("could not lookup name for submodule '%s'"), path);
1445
1446         new_git_dir = git_path("modules/%s", sub->name);
1447         if (safe_create_leading_directories_const(new_git_dir) < 0)
1448                 die(_("could not create directory '%s'"), new_git_dir);
1449         real_new_git_dir = real_pathdup(new_git_dir, 1);
1450
1451         if (!prefix)
1452                 prefix = get_super_prefix();
1453
1454         fprintf(stderr, _("Migrating git directory of '%s%s' from\n'%s' to\n'%s'\n"),
1455                 prefix ? prefix : "", path,
1456                 real_old_git_dir, real_new_git_dir);
1457
1458         relocate_gitdir(path, real_old_git_dir, real_new_git_dir);
1459
1460         free(old_git_dir);
1461         free(real_old_git_dir);
1462         free(real_new_git_dir);
1463 }
1464
1465 /*
1466  * Migrate the git directory of the submodule given by path from
1467  * having its git directory within the working tree to the git dir nested
1468  * in its superprojects git dir under modules/.
1469  */
1470 void absorb_git_dir_into_superproject(const char *prefix,
1471                                       const char *path,
1472                                       unsigned flags)
1473 {
1474         int err_code;
1475         const char *sub_git_dir;
1476         struct strbuf gitdir = STRBUF_INIT;
1477         strbuf_addf(&gitdir, "%s/.git", path);
1478         sub_git_dir = resolve_gitdir_gently(gitdir.buf, &err_code);
1479
1480         /* Not populated? */
1481         if (!sub_git_dir) {
1482                 char *real_new_git_dir;
1483                 const char *new_git_dir;
1484                 const struct submodule *sub;
1485
1486                 if (err_code == READ_GITFILE_ERR_STAT_FAILED) {
1487                         /* unpopulated as expected */
1488                         strbuf_release(&gitdir);
1489                         return;
1490                 }
1491
1492                 if (err_code != READ_GITFILE_ERR_NOT_A_REPO)
1493                         /* We don't know what broke here. */
1494                         read_gitfile_error_die(err_code, path, NULL);
1495
1496                 /*
1497                 * Maybe populated, but no git directory was found?
1498                 * This can happen if the superproject is a submodule
1499                 * itself and was just absorbed. The absorption of the
1500                 * superproject did not rewrite the git file links yet,
1501                 * fix it now.
1502                 */
1503                 sub = submodule_from_path(null_sha1, path);
1504                 if (!sub)
1505                         die(_("could not lookup name for submodule '%s'"), path);
1506                 new_git_dir = git_path("modules/%s", sub->name);
1507                 if (safe_create_leading_directories_const(new_git_dir) < 0)
1508                         die(_("could not create directory '%s'"), new_git_dir);
1509                 real_new_git_dir = real_pathdup(new_git_dir, 1);
1510                 connect_work_tree_and_git_dir(path, real_new_git_dir);
1511
1512                 free(real_new_git_dir);
1513         } else {
1514                 /* Is it already absorbed into the superprojects git dir? */
1515                 char *real_sub_git_dir = real_pathdup(sub_git_dir, 1);
1516                 char *real_common_git_dir = real_pathdup(get_git_common_dir(), 1);
1517
1518                 if (!starts_with(real_sub_git_dir, real_common_git_dir))
1519                         relocate_single_git_dir_into_superproject(prefix, path);
1520
1521                 free(real_sub_git_dir);
1522                 free(real_common_git_dir);
1523         }
1524         strbuf_release(&gitdir);
1525
1526         if (flags & ABSORB_GITDIR_RECURSE_SUBMODULES) {
1527                 struct child_process cp = CHILD_PROCESS_INIT;
1528                 struct strbuf sb = STRBUF_INIT;
1529
1530                 if (flags & ~ABSORB_GITDIR_RECURSE_SUBMODULES)
1531                         die("BUG: we don't know how to pass the flags down?");
1532
1533                 if (get_super_prefix())
1534                         strbuf_addstr(&sb, get_super_prefix());
1535                 strbuf_addstr(&sb, path);
1536                 strbuf_addch(&sb, '/');
1537
1538                 cp.dir = path;
1539                 cp.git_cmd = 1;
1540                 cp.no_stdin = 1;
1541                 argv_array_pushl(&cp.args, "--super-prefix", sb.buf,
1542                                            "submodule--helper",
1543                                            "absorb-git-dirs", NULL);
1544                 prepare_submodule_repo_env(&cp.env_array);
1545                 if (run_command(&cp))
1546                         die(_("could not recurse into submodule '%s'"), path);
1547
1548                 strbuf_release(&sb);
1549         }
1550 }