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