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