update submodules: add a config option to determine if submodules are updated
[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 static int has_remote(const char *refname, const struct object_id *oid,
552                       int flags, void *cb_data)
553 {
554         return 1;
555 }
556
557 static int append_sha1_to_argv(const unsigned char sha1[20], void *data)
558 {
559         struct argv_array *argv = data;
560         argv_array_push(argv, sha1_to_hex(sha1));
561         return 0;
562 }
563
564 static int check_has_commit(const unsigned char sha1[20], void *data)
565 {
566         int *has_commit = data;
567
568         if (!lookup_commit_reference(sha1))
569                 *has_commit = 0;
570
571         return 0;
572 }
573
574 static int submodule_has_commits(const char *path, struct sha1_array *commits)
575 {
576         int has_commit = 1;
577
578         if (add_submodule_odb(path))
579                 return 0;
580
581         sha1_array_for_each_unique(commits, check_has_commit, &has_commit);
582         return has_commit;
583 }
584
585 static int submodule_needs_pushing(const char *path, struct sha1_array *commits)
586 {
587         if (!submodule_has_commits(path, commits))
588                 /*
589                  * NOTE: We do consider it safe to return "no" here. The
590                  * correct answer would be "We do not know" instead of
591                  * "No push needed", but it is quite hard to change
592                  * the submodule pointer without having the submodule
593                  * around. If a user did however change the submodules
594                  * without having the submodule around, this indicates
595                  * an expert who knows what they are doing or a
596                  * maintainer integrating work from other people. In
597                  * both cases it should be safe to skip this check.
598                  */
599                 return 0;
600
601         if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
602                 struct child_process cp = CHILD_PROCESS_INIT;
603                 struct strbuf buf = STRBUF_INIT;
604                 int needs_pushing = 0;
605
606                 argv_array_push(&cp.args, "rev-list");
607                 sha1_array_for_each_unique(commits, append_sha1_to_argv, &cp.args);
608                 argv_array_pushl(&cp.args, "--not", "--remotes", "-n", "1" , NULL);
609
610                 prepare_submodule_repo_env(&cp.env_array);
611                 cp.git_cmd = 1;
612                 cp.no_stdin = 1;
613                 cp.out = -1;
614                 cp.dir = path;
615                 if (start_command(&cp))
616                         die("Could not run 'git rev-list <commits> --not --remotes -n 1' command in submodule %s",
617                                         path);
618                 if (strbuf_read(&buf, cp.out, 41))
619                         needs_pushing = 1;
620                 finish_command(&cp);
621                 close(cp.out);
622                 strbuf_release(&buf);
623                 return needs_pushing;
624         }
625
626         return 0;
627 }
628
629 static struct sha1_array *submodule_commits(struct string_list *submodules,
630                                             const char *path)
631 {
632         struct string_list_item *item;
633
634         item = string_list_insert(submodules, path);
635         if (item->util)
636                 return (struct sha1_array *) item->util;
637
638         /* NEEDSWORK: should we have sha1_array_init()? */
639         item->util = xcalloc(1, sizeof(struct sha1_array));
640         return (struct sha1_array *) item->util;
641 }
642
643 static void collect_submodules_from_diff(struct diff_queue_struct *q,
644                                          struct diff_options *options,
645                                          void *data)
646 {
647         int i;
648         struct string_list *submodules = data;
649
650         for (i = 0; i < q->nr; i++) {
651                 struct diff_filepair *p = q->queue[i];
652                 struct sha1_array *commits;
653                 if (!S_ISGITLINK(p->two->mode))
654                         continue;
655                 commits = submodule_commits(submodules, p->two->path);
656                 sha1_array_append(commits, p->two->oid.hash);
657         }
658 }
659
660 static void find_unpushed_submodule_commits(struct commit *commit,
661                 struct string_list *needs_pushing)
662 {
663         struct rev_info rev;
664
665         init_revisions(&rev, NULL);
666         rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
667         rev.diffopt.format_callback = collect_submodules_from_diff;
668         rev.diffopt.format_callback_data = needs_pushing;
669         diff_tree_combined_merge(commit, 1, &rev);
670 }
671
672 static void free_submodules_sha1s(struct string_list *submodules)
673 {
674         struct string_list_item *item;
675         for_each_string_list_item(item, submodules)
676                 sha1_array_clear((struct sha1_array *) item->util);
677         string_list_clear(submodules, 1);
678 }
679
680 int find_unpushed_submodules(struct sha1_array *commits,
681                 const char *remotes_name, struct string_list *needs_pushing)
682 {
683         struct rev_info rev;
684         struct commit *commit;
685         struct string_list submodules = STRING_LIST_INIT_DUP;
686         struct string_list_item *submodule;
687         struct argv_array argv = ARGV_ARRAY_INIT;
688
689         init_revisions(&rev, NULL);
690
691         /* argv.argv[0] will be ignored by setup_revisions */
692         argv_array_push(&argv, "find_unpushed_submodules");
693         sha1_array_for_each_unique(commits, append_sha1_to_argv, &argv);
694         argv_array_push(&argv, "--not");
695         argv_array_pushf(&argv, "--remotes=%s", remotes_name);
696
697         setup_revisions(argv.argc, argv.argv, &rev, NULL);
698         if (prepare_revision_walk(&rev))
699                 die("revision walk setup failed");
700
701         while ((commit = get_revision(&rev)) != NULL)
702                 find_unpushed_submodule_commits(commit, &submodules);
703
704         reset_revision_walk();
705         argv_array_clear(&argv);
706
707         for_each_string_list_item(submodule, &submodules) {
708                 struct sha1_array *commits = (struct sha1_array *) submodule->util;
709
710                 if (submodule_needs_pushing(submodule->string, commits))
711                         string_list_insert(needs_pushing, submodule->string);
712         }
713         free_submodules_sha1s(&submodules);
714
715         return needs_pushing->nr;
716 }
717
718 static int push_submodule(const char *path, int dry_run)
719 {
720         if (add_submodule_odb(path))
721                 return 1;
722
723         if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
724                 struct child_process cp = CHILD_PROCESS_INIT;
725                 argv_array_push(&cp.args, "push");
726                 if (dry_run)
727                         argv_array_push(&cp.args, "--dry-run");
728
729                 prepare_submodule_repo_env(&cp.env_array);
730                 cp.git_cmd = 1;
731                 cp.no_stdin = 1;
732                 cp.dir = path;
733                 if (run_command(&cp))
734                         return 0;
735                 close(cp.out);
736         }
737
738         return 1;
739 }
740
741 int push_unpushed_submodules(struct sha1_array *commits,
742                              const char *remotes_name,
743                              int dry_run)
744 {
745         int i, ret = 1;
746         struct string_list needs_pushing = STRING_LIST_INIT_DUP;
747
748         if (!find_unpushed_submodules(commits, remotes_name, &needs_pushing))
749                 return 1;
750
751         for (i = 0; i < needs_pushing.nr; i++) {
752                 const char *path = needs_pushing.items[i].string;
753                 fprintf(stderr, "Pushing submodule '%s'\n", path);
754                 if (!push_submodule(path, dry_run)) {
755                         fprintf(stderr, "Unable to push submodule '%s'\n", path);
756                         ret = 0;
757                 }
758         }
759
760         string_list_clear(&needs_pushing, 0);
761
762         return ret;
763 }
764
765 static int is_submodule_commit_present(const char *path, unsigned char sha1[20])
766 {
767         int is_present = 0;
768         if (!add_submodule_odb(path) && lookup_commit_reference(sha1)) {
769                 /* Even if the submodule is checked out and the commit is
770                  * present, make sure it is reachable from a ref. */
771                 struct child_process cp = CHILD_PROCESS_INIT;
772                 const char *argv[] = {"rev-list", "-n", "1", NULL, "--not", "--all", NULL};
773                 struct strbuf buf = STRBUF_INIT;
774
775                 argv[3] = sha1_to_hex(sha1);
776                 cp.argv = argv;
777                 prepare_submodule_repo_env(&cp.env_array);
778                 cp.git_cmd = 1;
779                 cp.no_stdin = 1;
780                 cp.dir = path;
781                 if (!capture_command(&cp, &buf, 1024) && !buf.len)
782                         is_present = 1;
783
784                 strbuf_release(&buf);
785         }
786         return is_present;
787 }
788
789 static void submodule_collect_changed_cb(struct diff_queue_struct *q,
790                                          struct diff_options *options,
791                                          void *data)
792 {
793         int i;
794         for (i = 0; i < q->nr; i++) {
795                 struct diff_filepair *p = q->queue[i];
796                 if (!S_ISGITLINK(p->two->mode))
797                         continue;
798
799                 if (S_ISGITLINK(p->one->mode)) {
800                         /* NEEDSWORK: We should honor the name configured in
801                          * the .gitmodules file of the commit we are examining
802                          * here to be able to correctly follow submodules
803                          * being moved around. */
804                         struct string_list_item *path;
805                         path = unsorted_string_list_lookup(&changed_submodule_paths, p->two->path);
806                         if (!path && !is_submodule_commit_present(p->two->path, p->two->oid.hash))
807                                 string_list_append(&changed_submodule_paths, xstrdup(p->two->path));
808                 } else {
809                         /* Submodule is new or was moved here */
810                         /* NEEDSWORK: When the .git directories of submodules
811                          * live inside the superprojects .git directory some
812                          * day we should fetch new submodules directly into
813                          * that location too when config or options request
814                          * that so they can be checked out from there. */
815                         continue;
816                 }
817         }
818 }
819
820 static int add_sha1_to_array(const char *ref, const struct object_id *oid,
821                              int flags, void *data)
822 {
823         sha1_array_append(data, oid->hash);
824         return 0;
825 }
826
827 void check_for_new_submodule_commits(unsigned char new_sha1[20])
828 {
829         if (!initialized_fetch_ref_tips) {
830                 for_each_ref(add_sha1_to_array, &ref_tips_before_fetch);
831                 initialized_fetch_ref_tips = 1;
832         }
833
834         sha1_array_append(&ref_tips_after_fetch, new_sha1);
835 }
836
837 static int add_sha1_to_argv(const unsigned char sha1[20], void *data)
838 {
839         argv_array_push(data, sha1_to_hex(sha1));
840         return 0;
841 }
842
843 static void calculate_changed_submodule_paths(void)
844 {
845         struct rev_info rev;
846         struct commit *commit;
847         struct argv_array argv = ARGV_ARRAY_INIT;
848
849         /* No need to check if there are no submodules configured */
850         if (!submodule_from_path(NULL, NULL))
851                 return;
852
853         init_revisions(&rev, NULL);
854         argv_array_push(&argv, "--"); /* argv[0] program name */
855         sha1_array_for_each_unique(&ref_tips_after_fetch,
856                                    add_sha1_to_argv, &argv);
857         argv_array_push(&argv, "--not");
858         sha1_array_for_each_unique(&ref_tips_before_fetch,
859                                    add_sha1_to_argv, &argv);
860         setup_revisions(argv.argc, argv.argv, &rev, NULL);
861         if (prepare_revision_walk(&rev))
862                 die("revision walk setup failed");
863
864         /*
865          * Collect all submodules (whether checked out or not) for which new
866          * commits have been recorded upstream in "changed_submodule_paths".
867          */
868         while ((commit = get_revision(&rev))) {
869                 struct commit_list *parent = commit->parents;
870                 while (parent) {
871                         struct diff_options diff_opts;
872                         diff_setup(&diff_opts);
873                         DIFF_OPT_SET(&diff_opts, RECURSIVE);
874                         diff_opts.output_format |= DIFF_FORMAT_CALLBACK;
875                         diff_opts.format_callback = submodule_collect_changed_cb;
876                         diff_setup_done(&diff_opts);
877                         diff_tree_sha1(parent->item->object.oid.hash, commit->object.oid.hash, "", &diff_opts);
878                         diffcore_std(&diff_opts);
879                         diff_flush(&diff_opts);
880                         parent = parent->next;
881                 }
882         }
883
884         argv_array_clear(&argv);
885         sha1_array_clear(&ref_tips_before_fetch);
886         sha1_array_clear(&ref_tips_after_fetch);
887         initialized_fetch_ref_tips = 0;
888 }
889
890 struct submodule_parallel_fetch {
891         int count;
892         struct argv_array args;
893         const char *work_tree;
894         const char *prefix;
895         int command_line_option;
896         int quiet;
897         int result;
898 };
899 #define SPF_INIT {0, ARGV_ARRAY_INIT, NULL, NULL, 0, 0, 0}
900
901 static int get_next_submodule(struct child_process *cp,
902                               struct strbuf *err, void *data, void **task_cb)
903 {
904         int ret = 0;
905         struct submodule_parallel_fetch *spf = data;
906
907         for (; spf->count < active_nr; spf->count++) {
908                 struct strbuf submodule_path = STRBUF_INIT;
909                 struct strbuf submodule_git_dir = STRBUF_INIT;
910                 struct strbuf submodule_prefix = STRBUF_INIT;
911                 const struct cache_entry *ce = active_cache[spf->count];
912                 const char *git_dir, *default_argv;
913                 const struct submodule *submodule;
914
915                 if (!S_ISGITLINK(ce->ce_mode))
916                         continue;
917
918                 submodule = submodule_from_path(null_sha1, ce->name);
919                 if (!submodule)
920                         submodule = submodule_from_name(null_sha1, ce->name);
921
922                 default_argv = "yes";
923                 if (spf->command_line_option == RECURSE_SUBMODULES_DEFAULT) {
924                         if (submodule &&
925                             submodule->fetch_recurse !=
926                                                 RECURSE_SUBMODULES_NONE) {
927                                 if (submodule->fetch_recurse ==
928                                                 RECURSE_SUBMODULES_OFF)
929                                         continue;
930                                 if (submodule->fetch_recurse ==
931                                                 RECURSE_SUBMODULES_ON_DEMAND) {
932                                         if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
933                                                 continue;
934                                         default_argv = "on-demand";
935                                 }
936                         } else {
937                                 if ((config_fetch_recurse_submodules == RECURSE_SUBMODULES_OFF) ||
938                                     gitmodules_is_unmerged)
939                                         continue;
940                                 if (config_fetch_recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND) {
941                                         if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
942                                                 continue;
943                                         default_argv = "on-demand";
944                                 }
945                         }
946                 } else if (spf->command_line_option == RECURSE_SUBMODULES_ON_DEMAND) {
947                         if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
948                                 continue;
949                         default_argv = "on-demand";
950                 }
951
952                 strbuf_addf(&submodule_path, "%s/%s", spf->work_tree, ce->name);
953                 strbuf_addf(&submodule_git_dir, "%s/.git", submodule_path.buf);
954                 strbuf_addf(&submodule_prefix, "%s%s/", spf->prefix, ce->name);
955                 git_dir = read_gitfile(submodule_git_dir.buf);
956                 if (!git_dir)
957                         git_dir = submodule_git_dir.buf;
958                 if (is_directory(git_dir)) {
959                         child_process_init(cp);
960                         cp->dir = strbuf_detach(&submodule_path, NULL);
961                         prepare_submodule_repo_env(&cp->env_array);
962                         cp->git_cmd = 1;
963                         if (!spf->quiet)
964                                 strbuf_addf(err, "Fetching submodule %s%s\n",
965                                             spf->prefix, ce->name);
966                         argv_array_init(&cp->args);
967                         argv_array_pushv(&cp->args, spf->args.argv);
968                         argv_array_push(&cp->args, default_argv);
969                         argv_array_push(&cp->args, "--submodule-prefix");
970                         argv_array_push(&cp->args, submodule_prefix.buf);
971                         ret = 1;
972                 }
973                 strbuf_release(&submodule_path);
974                 strbuf_release(&submodule_git_dir);
975                 strbuf_release(&submodule_prefix);
976                 if (ret) {
977                         spf->count++;
978                         return 1;
979                 }
980         }
981         return 0;
982 }
983
984 static int fetch_start_failure(struct strbuf *err,
985                                void *cb, void *task_cb)
986 {
987         struct submodule_parallel_fetch *spf = cb;
988
989         spf->result = 1;
990
991         return 0;
992 }
993
994 static int fetch_finish(int retvalue, struct strbuf *err,
995                         void *cb, void *task_cb)
996 {
997         struct submodule_parallel_fetch *spf = cb;
998
999         if (retvalue)
1000                 spf->result = 1;
1001
1002         return 0;
1003 }
1004
1005 int fetch_populated_submodules(const struct argv_array *options,
1006                                const char *prefix, int command_line_option,
1007                                int quiet, int max_parallel_jobs)
1008 {
1009         int i;
1010         struct submodule_parallel_fetch spf = SPF_INIT;
1011
1012         spf.work_tree = get_git_work_tree();
1013         spf.command_line_option = command_line_option;
1014         spf.quiet = quiet;
1015         spf.prefix = prefix;
1016
1017         if (!spf.work_tree)
1018                 goto out;
1019
1020         if (read_cache() < 0)
1021                 die("index file corrupt");
1022
1023         argv_array_push(&spf.args, "fetch");
1024         for (i = 0; i < options->argc; i++)
1025                 argv_array_push(&spf.args, options->argv[i]);
1026         argv_array_push(&spf.args, "--recurse-submodules-default");
1027         /* default value, "--submodule-prefix" and its value are added later */
1028
1029         if (max_parallel_jobs < 0)
1030                 max_parallel_jobs = parallel_jobs;
1031
1032         calculate_changed_submodule_paths();
1033         run_processes_parallel(max_parallel_jobs,
1034                                get_next_submodule,
1035                                fetch_start_failure,
1036                                fetch_finish,
1037                                &spf);
1038
1039         argv_array_clear(&spf.args);
1040 out:
1041         string_list_clear(&changed_submodule_paths, 1);
1042         return spf.result;
1043 }
1044
1045 unsigned is_submodule_modified(const char *path, int ignore_untracked)
1046 {
1047         ssize_t len;
1048         struct child_process cp = CHILD_PROCESS_INIT;
1049         const char *argv[] = {
1050                 "status",
1051                 "--porcelain",
1052                 NULL,
1053                 NULL,
1054         };
1055         struct strbuf buf = STRBUF_INIT;
1056         unsigned dirty_submodule = 0;
1057         const char *line, *next_line;
1058         const char *git_dir;
1059
1060         strbuf_addf(&buf, "%s/.git", path);
1061         git_dir = read_gitfile(buf.buf);
1062         if (!git_dir)
1063                 git_dir = buf.buf;
1064         if (!is_directory(git_dir)) {
1065                 strbuf_release(&buf);
1066                 /* The submodule is not checked out, so it is not modified */
1067                 return 0;
1068
1069         }
1070         strbuf_reset(&buf);
1071
1072         if (ignore_untracked)
1073                 argv[2] = "-uno";
1074
1075         cp.argv = argv;
1076         prepare_submodule_repo_env(&cp.env_array);
1077         cp.git_cmd = 1;
1078         cp.no_stdin = 1;
1079         cp.out = -1;
1080         cp.dir = path;
1081         if (start_command(&cp))
1082                 die("Could not run 'git status --porcelain' in submodule %s", path);
1083
1084         len = strbuf_read(&buf, cp.out, 1024);
1085         line = buf.buf;
1086         while (len > 2) {
1087                 if ((line[0] == '?') && (line[1] == '?')) {
1088                         dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1089                         if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
1090                                 break;
1091                 } else {
1092                         dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
1093                         if (ignore_untracked ||
1094                             (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED))
1095                                 break;
1096                 }
1097                 next_line = strchr(line, '\n');
1098                 if (!next_line)
1099                         break;
1100                 next_line++;
1101                 len -= (next_line - line);
1102                 line = next_line;
1103         }
1104         close(cp.out);
1105
1106         if (finish_command(&cp))
1107                 die("'git status --porcelain' failed in submodule %s", path);
1108
1109         strbuf_release(&buf);
1110         return dirty_submodule;
1111 }
1112
1113 int submodule_uses_gitfile(const char *path)
1114 {
1115         struct child_process cp = CHILD_PROCESS_INIT;
1116         const char *argv[] = {
1117                 "submodule",
1118                 "foreach",
1119                 "--quiet",
1120                 "--recursive",
1121                 "test -f .git",
1122                 NULL,
1123         };
1124         struct strbuf buf = STRBUF_INIT;
1125         const char *git_dir;
1126
1127         strbuf_addf(&buf, "%s/.git", path);
1128         git_dir = read_gitfile(buf.buf);
1129         if (!git_dir) {
1130                 strbuf_release(&buf);
1131                 return 0;
1132         }
1133         strbuf_release(&buf);
1134
1135         /* Now test that all nested submodules use a gitfile too */
1136         cp.argv = argv;
1137         prepare_submodule_repo_env(&cp.env_array);
1138         cp.git_cmd = 1;
1139         cp.no_stdin = 1;
1140         cp.no_stderr = 1;
1141         cp.no_stdout = 1;
1142         cp.dir = path;
1143         if (run_command(&cp))
1144                 return 0;
1145
1146         return 1;
1147 }
1148
1149 /*
1150  * Check if it is a bad idea to remove a submodule, i.e. if we'd lose data
1151  * when doing so.
1152  *
1153  * Return 1 if we'd lose data, return 0 if the removal is fine,
1154  * and negative values for errors.
1155  */
1156 int bad_to_remove_submodule(const char *path, unsigned flags)
1157 {
1158         ssize_t len;
1159         struct child_process cp = CHILD_PROCESS_INIT;
1160         struct strbuf buf = STRBUF_INIT;
1161         int ret = 0;
1162
1163         if (!file_exists(path) || is_empty_dir(path))
1164                 return 0;
1165
1166         if (!submodule_uses_gitfile(path))
1167                 return 1;
1168
1169         argv_array_pushl(&cp.args, "status", "--porcelain",
1170                                    "--ignore-submodules=none", NULL);
1171
1172         if (flags & SUBMODULE_REMOVAL_IGNORE_UNTRACKED)
1173                 argv_array_push(&cp.args, "-uno");
1174         else
1175                 argv_array_push(&cp.args, "-uall");
1176
1177         if (!(flags & SUBMODULE_REMOVAL_IGNORE_IGNORED_UNTRACKED))
1178                 argv_array_push(&cp.args, "--ignored");
1179
1180         prepare_submodule_repo_env(&cp.env_array);
1181         cp.git_cmd = 1;
1182         cp.no_stdin = 1;
1183         cp.out = -1;
1184         cp.dir = path;
1185         if (start_command(&cp)) {
1186                 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
1187                         die(_("could not start 'git status in submodule '%s'"),
1188                                 path);
1189                 ret = -1;
1190                 goto out;
1191         }
1192
1193         len = strbuf_read(&buf, cp.out, 1024);
1194         if (len > 2)
1195                 ret = 1;
1196         close(cp.out);
1197
1198         if (finish_command(&cp)) {
1199                 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
1200                         die(_("could not run 'git status in submodule '%s'"),
1201                                 path);
1202                 ret = -1;
1203         }
1204 out:
1205         strbuf_release(&buf);
1206         return ret;
1207 }
1208
1209 static int find_first_merges(struct object_array *result, const char *path,
1210                 struct commit *a, struct commit *b)
1211 {
1212         int i, j;
1213         struct object_array merges = OBJECT_ARRAY_INIT;
1214         struct commit *commit;
1215         int contains_another;
1216
1217         char merged_revision[42];
1218         const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
1219                                    "--all", merged_revision, NULL };
1220         struct rev_info revs;
1221         struct setup_revision_opt rev_opts;
1222
1223         memset(result, 0, sizeof(struct object_array));
1224         memset(&rev_opts, 0, sizeof(rev_opts));
1225
1226         /* get all revisions that merge commit a */
1227         snprintf(merged_revision, sizeof(merged_revision), "^%s",
1228                         oid_to_hex(&a->object.oid));
1229         init_revisions(&revs, NULL);
1230         rev_opts.submodule = path;
1231         setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
1232
1233         /* save all revisions from the above list that contain b */
1234         if (prepare_revision_walk(&revs))
1235                 die("revision walk setup failed");
1236         while ((commit = get_revision(&revs)) != NULL) {
1237                 struct object *o = &(commit->object);
1238                 if (in_merge_bases(b, commit))
1239                         add_object_array(o, NULL, &merges);
1240         }
1241         reset_revision_walk();
1242
1243         /* Now we've got all merges that contain a and b. Prune all
1244          * merges that contain another found merge and save them in
1245          * result.
1246          */
1247         for (i = 0; i < merges.nr; i++) {
1248                 struct commit *m1 = (struct commit *) merges.objects[i].item;
1249
1250                 contains_another = 0;
1251                 for (j = 0; j < merges.nr; j++) {
1252                         struct commit *m2 = (struct commit *) merges.objects[j].item;
1253                         if (i != j && in_merge_bases(m2, m1)) {
1254                                 contains_another = 1;
1255                                 break;
1256                         }
1257                 }
1258
1259                 if (!contains_another)
1260                         add_object_array(merges.objects[i].item, NULL, result);
1261         }
1262
1263         free(merges.objects);
1264         return result->nr;
1265 }
1266
1267 static void print_commit(struct commit *commit)
1268 {
1269         struct strbuf sb = STRBUF_INIT;
1270         struct pretty_print_context ctx = {0};
1271         ctx.date_mode.type = DATE_NORMAL;
1272         format_commit_message(commit, " %h: %m %s", &sb, &ctx);
1273         fprintf(stderr, "%s\n", sb.buf);
1274         strbuf_release(&sb);
1275 }
1276
1277 #define MERGE_WARNING(path, msg) \
1278         warning("Failed to merge submodule %s (%s)", path, msg);
1279
1280 int merge_submodule(unsigned char result[20], const char *path,
1281                     const unsigned char base[20], const unsigned char a[20],
1282                     const unsigned char b[20], int search)
1283 {
1284         struct commit *commit_base, *commit_a, *commit_b;
1285         int parent_count;
1286         struct object_array merges;
1287
1288         int i;
1289
1290         /* store a in result in case we fail */
1291         hashcpy(result, a);
1292
1293         /* we can not handle deletion conflicts */
1294         if (is_null_sha1(base))
1295                 return 0;
1296         if (is_null_sha1(a))
1297                 return 0;
1298         if (is_null_sha1(b))
1299                 return 0;
1300
1301         if (add_submodule_odb(path)) {
1302                 MERGE_WARNING(path, "not checked out");
1303                 return 0;
1304         }
1305
1306         if (!(commit_base = lookup_commit_reference(base)) ||
1307             !(commit_a = lookup_commit_reference(a)) ||
1308             !(commit_b = lookup_commit_reference(b))) {
1309                 MERGE_WARNING(path, "commits not present");
1310                 return 0;
1311         }
1312
1313         /* check whether both changes are forward */
1314         if (!in_merge_bases(commit_base, commit_a) ||
1315             !in_merge_bases(commit_base, commit_b)) {
1316                 MERGE_WARNING(path, "commits don't follow merge-base");
1317                 return 0;
1318         }
1319
1320         /* Case #1: a is contained in b or vice versa */
1321         if (in_merge_bases(commit_a, commit_b)) {
1322                 hashcpy(result, b);
1323                 return 1;
1324         }
1325         if (in_merge_bases(commit_b, commit_a)) {
1326                 hashcpy(result, a);
1327                 return 1;
1328         }
1329
1330         /*
1331          * Case #2: There are one or more merges that contain a and b in
1332          * the submodule. If there is only one, then present it as a
1333          * suggestion to the user, but leave it marked unmerged so the
1334          * user needs to confirm the resolution.
1335          */
1336
1337         /* Skip the search if makes no sense to the calling context.  */
1338         if (!search)
1339                 return 0;
1340
1341         /* find commit which merges them */
1342         parent_count = find_first_merges(&merges, path, commit_a, commit_b);
1343         switch (parent_count) {
1344         case 0:
1345                 MERGE_WARNING(path, "merge following commits not found");
1346                 break;
1347
1348         case 1:
1349                 MERGE_WARNING(path, "not fast-forward");
1350                 fprintf(stderr, "Found a possible merge resolution "
1351                                 "for the submodule:\n");
1352                 print_commit((struct commit *) merges.objects[0].item);
1353                 fprintf(stderr,
1354                         "If this is correct simply add it to the index "
1355                         "for example\n"
1356                         "by using:\n\n"
1357                         "  git update-index --cacheinfo 160000 %s \"%s\"\n\n"
1358                         "which will accept this suggestion.\n",
1359                         oid_to_hex(&merges.objects[0].item->oid), path);
1360                 break;
1361
1362         default:
1363                 MERGE_WARNING(path, "multiple merges found");
1364                 for (i = 0; i < merges.nr; i++)
1365                         print_commit((struct commit *) merges.objects[i].item);
1366         }
1367
1368         free(merges.objects);
1369         return 0;
1370 }
1371
1372 int parallel_submodules(void)
1373 {
1374         return parallel_jobs;
1375 }
1376
1377 void prepare_submodule_repo_env(struct argv_array *out)
1378 {
1379         const char * const *var;
1380
1381         for (var = local_repo_env; *var; var++) {
1382                 if (strcmp(*var, CONFIG_DATA_ENVIRONMENT))
1383                         argv_array_push(out, *var);
1384         }
1385         argv_array_pushf(out, "%s=%s", GIT_DIR_ENVIRONMENT,
1386                          DEFAULT_GIT_DIR_ENVIRONMENT);
1387 }
1388
1389 /*
1390  * Embeds a single submodules git directory into the superprojects git dir,
1391  * non recursively.
1392  */
1393 static void relocate_single_git_dir_into_superproject(const char *prefix,
1394                                                       const char *path)
1395 {
1396         char *old_git_dir = NULL, *real_old_git_dir = NULL, *real_new_git_dir = NULL;
1397         const char *new_git_dir;
1398         const struct submodule *sub;
1399
1400         if (submodule_uses_worktrees(path))
1401                 die(_("relocate_gitdir for submodule '%s' with "
1402                       "more than one worktree not supported"), path);
1403
1404         old_git_dir = xstrfmt("%s/.git", path);
1405         if (read_gitfile(old_git_dir))
1406                 /* If it is an actual gitfile, it doesn't need migration. */
1407                 return;
1408
1409         real_old_git_dir = real_pathdup(old_git_dir);
1410
1411         sub = submodule_from_path(null_sha1, path);
1412         if (!sub)
1413                 die(_("could not lookup name for submodule '%s'"), path);
1414
1415         new_git_dir = git_path("modules/%s", sub->name);
1416         if (safe_create_leading_directories_const(new_git_dir) < 0)
1417                 die(_("could not create directory '%s'"), new_git_dir);
1418         real_new_git_dir = real_pathdup(new_git_dir);
1419
1420         if (!prefix)
1421                 prefix = get_super_prefix();
1422
1423         fprintf(stderr, _("Migrating git directory of '%s%s' from\n'%s' to\n'%s'\n"),
1424                 prefix ? prefix : "", path,
1425                 real_old_git_dir, real_new_git_dir);
1426
1427         relocate_gitdir(path, real_old_git_dir, real_new_git_dir);
1428
1429         free(old_git_dir);
1430         free(real_old_git_dir);
1431         free(real_new_git_dir);
1432 }
1433
1434 /*
1435  * Migrate the git directory of the submodule given by path from
1436  * having its git directory within the working tree to the git dir nested
1437  * in its superprojects git dir under modules/.
1438  */
1439 void absorb_git_dir_into_superproject(const char *prefix,
1440                                       const char *path,
1441                                       unsigned flags)
1442 {
1443         int err_code;
1444         const char *sub_git_dir;
1445         struct strbuf gitdir = STRBUF_INIT;
1446         strbuf_addf(&gitdir, "%s/.git", path);
1447         sub_git_dir = resolve_gitdir_gently(gitdir.buf, &err_code);
1448
1449         /* Not populated? */
1450         if (!sub_git_dir) {
1451                 const struct submodule *sub;
1452
1453                 if (err_code == READ_GITFILE_ERR_STAT_FAILED) {
1454                         /* unpopulated as expected */
1455                         strbuf_release(&gitdir);
1456                         return;
1457                 }
1458
1459                 if (err_code != READ_GITFILE_ERR_NOT_A_REPO)
1460                         /* We don't know what broke here. */
1461                         read_gitfile_error_die(err_code, path, NULL);
1462
1463                 /*
1464                 * Maybe populated, but no git directory was found?
1465                 * This can happen if the superproject is a submodule
1466                 * itself and was just absorbed. The absorption of the
1467                 * superproject did not rewrite the git file links yet,
1468                 * fix it now.
1469                 */
1470                 sub = submodule_from_path(null_sha1, path);
1471                 if (!sub)
1472                         die(_("could not lookup name for submodule '%s'"), path);
1473                 connect_work_tree_and_git_dir(path,
1474                         git_path("modules/%s", sub->name));
1475         } else {
1476                 /* Is it already absorbed into the superprojects git dir? */
1477                 char *real_sub_git_dir = real_pathdup(sub_git_dir);
1478                 char *real_common_git_dir = real_pathdup(get_git_common_dir());
1479
1480                 if (!starts_with(real_sub_git_dir, real_common_git_dir))
1481                         relocate_single_git_dir_into_superproject(prefix, path);
1482
1483                 free(real_sub_git_dir);
1484                 free(real_common_git_dir);
1485         }
1486         strbuf_release(&gitdir);
1487
1488         if (flags & ABSORB_GITDIR_RECURSE_SUBMODULES) {
1489                 struct child_process cp = CHILD_PROCESS_INIT;
1490                 struct strbuf sb = STRBUF_INIT;
1491
1492                 if (flags & ~ABSORB_GITDIR_RECURSE_SUBMODULES)
1493                         die("BUG: we don't know how to pass the flags down?");
1494
1495                 if (get_super_prefix())
1496                         strbuf_addstr(&sb, get_super_prefix());
1497                 strbuf_addstr(&sb, path);
1498                 strbuf_addch(&sb, '/');
1499
1500                 cp.dir = path;
1501                 cp.git_cmd = 1;
1502                 cp.no_stdin = 1;
1503                 argv_array_pushl(&cp.args, "--super-prefix", sb.buf,
1504                                            "submodule--helper",
1505                                            "absorb-git-dirs", NULL);
1506                 prepare_submodule_repo_env(&cp.env_array);
1507                 if (run_command(&cp))
1508                         die(_("could not recurse into submodule '%s'"), path);
1509
1510                 strbuf_release(&sb);
1511         }
1512 }