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