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