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