Merge branch 'js/regexec-buf'
[git.git] / submodule.c
blob733332035b3c19279885175e0689665a34dc13ef
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"
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;
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.
33 static int gitmodules_is_unmerged;
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.
43 static int gitmodules_is_modified;
45 int is_staging_gitmodules_ok(void)
47 return !gitmodules_is_modified;
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.
55 int update_path_in_gitmodules(const char *oldpath, const char *newpath)
57 struct strbuf entry = STRBUF_INIT;
58 const struct submodule *submodule;
60 if (!file_exists(".gitmodules")) /* Do nothing without .gitmodules */
61 return -1;
63 if (gitmodules_is_unmerged)
64 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
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;
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;
80 strbuf_release(&entry);
81 return 0;
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.
89 int remove_path_from_gitmodules(const char *path)
91 struct strbuf sect = STRBUF_INIT;
92 const struct submodule *submodule;
94 if (!file_exists(".gitmodules")) /* Do nothing without .gitmodules */
95 return -1;
97 if (gitmodules_is_unmerged)
98 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
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;
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;
113 strbuf_release(&sect);
114 return 0;
117 void stage_updated_gitmodules(void)
119 if (add_file_to_cache(".gitmodules", 0))
120 die(_("staging updated .gitmodules failed"));
123 static int add_submodule_odb(const char *path)
125 struct strbuf objects_directory = STRBUF_INIT;
126 int ret = 0;
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;
135 add_to_alternates_memory(objects_directory.buf);
136 done:
137 strbuf_release(&objects_directory);
138 return ret;
141 void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
142 const char *path)
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);
153 int submodule_config(const char *var, const char *value, void *cb)
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;
166 return 0;
169 void gitmodules_config(void)
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;
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;
195 if (!gitmodules_is_unmerged)
196 git_config_from_file(submodule_config, gitmodules_path.buf, NULL);
197 strbuf_release(&gitmodules_path);
201 int parse_submodule_update_strategy(const char *value,
202 struct submodule_update_strategy *dst)
204 free((void*)dst->command);
205 dst->command = NULL;
206 if (!strcmp(value, "none"))
207 dst->type = SM_UPDATE_NONE;
208 else if (!strcmp(value, "checkout"))
209 dst->type = SM_UPDATE_CHECKOUT;
210 else if (!strcmp(value, "rebase"))
211 dst->type = SM_UPDATE_REBASE;
212 else if (!strcmp(value, "merge"))
213 dst->type = SM_UPDATE_MERGE;
214 else if (skip_prefix(value, "!", &value)) {
215 dst->type = SM_UPDATE_COMMAND;
216 dst->command = xstrdup(value);
217 } else
218 return -1;
219 return 0;
222 const char *submodule_strategy_to_string(const struct submodule_update_strategy *s)
224 struct strbuf sb = STRBUF_INIT;
225 switch (s->type) {
226 case SM_UPDATE_CHECKOUT:
227 return "checkout";
228 case SM_UPDATE_MERGE:
229 return "merge";
230 case SM_UPDATE_REBASE:
231 return "rebase";
232 case SM_UPDATE_NONE:
233 return "none";
234 case SM_UPDATE_UNSPECIFIED:
235 return NULL;
236 case SM_UPDATE_COMMAND:
237 strbuf_addf(&sb, "!%s", s->command);
238 return strbuf_detach(&sb, NULL);
240 return NULL;
243 void handle_ignore_submodules_arg(struct diff_options *diffopt,
244 const char *arg)
246 DIFF_OPT_CLR(diffopt, IGNORE_SUBMODULES);
247 DIFF_OPT_CLR(diffopt, IGNORE_UNTRACKED_IN_SUBMODULES);
248 DIFF_OPT_CLR(diffopt, IGNORE_DIRTY_SUBMODULES);
250 if (!strcmp(arg, "all"))
251 DIFF_OPT_SET(diffopt, IGNORE_SUBMODULES);
252 else if (!strcmp(arg, "untracked"))
253 DIFF_OPT_SET(diffopt, IGNORE_UNTRACKED_IN_SUBMODULES);
254 else if (!strcmp(arg, "dirty"))
255 DIFF_OPT_SET(diffopt, IGNORE_DIRTY_SUBMODULES);
256 else if (strcmp(arg, "none"))
257 die("bad --ignore-submodules argument: %s", arg);
260 static int prepare_submodule_summary(struct rev_info *rev, const char *path,
261 struct commit *left, struct commit *right,
262 struct commit_list *merge_bases)
264 struct commit_list *list;
266 init_revisions(rev, NULL);
267 setup_revisions(0, NULL, rev, NULL);
268 rev->left_right = 1;
269 rev->first_parent_only = 1;
270 left->object.flags |= SYMMETRIC_LEFT;
271 add_pending_object(rev, &left->object, path);
272 add_pending_object(rev, &right->object, path);
273 for (list = merge_bases; list; list = list->next) {
274 list->item->object.flags |= UNINTERESTING;
275 add_pending_object(rev, &list->item->object,
276 oid_to_hex(&list->item->object.oid));
278 return prepare_revision_walk(rev);
281 static void print_submodule_summary(struct rev_info *rev, FILE *f,
282 const char *line_prefix,
283 const char *del, const char *add, const char *reset)
285 static const char format[] = " %m %s";
286 struct strbuf sb = STRBUF_INIT;
287 struct commit *commit;
289 while ((commit = get_revision(rev))) {
290 struct pretty_print_context ctx = {0};
291 ctx.date_mode = rev->date_mode;
292 ctx.output_encoding = get_log_output_encoding();
293 strbuf_setlen(&sb, 0);
294 strbuf_addstr(&sb, line_prefix);
295 if (commit->object.flags & SYMMETRIC_LEFT) {
296 if (del)
297 strbuf_addstr(&sb, del);
299 else if (add)
300 strbuf_addstr(&sb, add);
301 format_commit_message(commit, format, &sb, &ctx);
302 if (reset)
303 strbuf_addstr(&sb, reset);
304 strbuf_addch(&sb, '\n');
305 fprintf(f, "%s", sb.buf);
307 strbuf_release(&sb);
310 /* Helper function to display the submodule header line prior to the full
311 * summary output. If it can locate the submodule objects directory it will
312 * attempt to lookup both the left and right commits and put them into the
313 * left and right pointers.
315 static void show_submodule_header(FILE *f, const char *path,
316 const char *line_prefix,
317 struct object_id *one, struct object_id *two,
318 unsigned dirty_submodule, const char *meta,
319 const char *reset,
320 struct commit **left, struct commit **right,
321 struct commit_list **merge_bases)
323 const char *message = NULL;
324 struct strbuf sb = STRBUF_INIT;
325 int fast_forward = 0, fast_backward = 0;
327 if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
328 fprintf(f, "%sSubmodule %s contains untracked content\n",
329 line_prefix, path);
330 if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
331 fprintf(f, "%sSubmodule %s contains modified content\n",
332 line_prefix, path);
334 if (is_null_oid(one))
335 message = "(new submodule)";
336 else if (is_null_oid(two))
337 message = "(submodule deleted)";
339 if (add_submodule_odb(path)) {
340 if (!message)
341 message = "(not initialized)";
342 goto output_header;
346 * Attempt to lookup the commit references, and determine if this is
347 * a fast forward or fast backwards update.
349 *left = lookup_commit_reference(one->hash);
350 *right = lookup_commit_reference(two->hash);
353 * Warn about missing commits in the submodule project, but only if
354 * they aren't null.
356 if ((!is_null_oid(one) && !*left) ||
357 (!is_null_oid(two) && !*right))
358 message = "(commits not present)";
360 *merge_bases = get_merge_bases(*left, *right);
361 if (*merge_bases) {
362 if ((*merge_bases)->item == *left)
363 fast_forward = 1;
364 else if ((*merge_bases)->item == *right)
365 fast_backward = 1;
368 if (!oidcmp(one, two)) {
369 strbuf_release(&sb);
370 return;
373 output_header:
374 strbuf_addf(&sb, "%s%sSubmodule %s %s..", line_prefix, meta, path,
375 find_unique_abbrev(one->hash, DEFAULT_ABBREV));
376 if (!fast_backward && !fast_forward)
377 strbuf_addch(&sb, '.');
378 strbuf_add_unique_abbrev(&sb, two->hash, DEFAULT_ABBREV);
379 if (message)
380 strbuf_addf(&sb, " %s%s\n", message, reset);
381 else
382 strbuf_addf(&sb, "%s:%s\n", fast_backward ? " (rewind)" : "", reset);
383 fwrite(sb.buf, sb.len, 1, f);
385 strbuf_release(&sb);
388 void show_submodule_summary(FILE *f, const char *path,
389 const char *line_prefix,
390 struct object_id *one, struct object_id *two,
391 unsigned dirty_submodule, const char *meta,
392 const char *del, const char *add, const char *reset)
394 struct rev_info rev;
395 struct commit *left = NULL, *right = NULL;
396 struct commit_list *merge_bases = NULL;
398 show_submodule_header(f, path, line_prefix, one, two, dirty_submodule,
399 meta, reset, &left, &right, &merge_bases);
402 * If we don't have both a left and a right pointer, there is no
403 * reason to try and display a summary. The header line should contain
404 * all the information the user needs.
406 if (!left || !right)
407 goto out;
409 /* Treat revision walker failure the same as missing commits */
410 if (prepare_submodule_summary(&rev, path, left, right, merge_bases)) {
411 fprintf(f, "%s(revision walker failed)\n", line_prefix);
412 goto out;
415 print_submodule_summary(&rev, f, line_prefix, del, add, reset);
417 out:
418 if (merge_bases)
419 free_commit_list(merge_bases);
420 clear_commit_marks(left, ~0);
421 clear_commit_marks(right, ~0);
424 void show_submodule_inline_diff(FILE *f, const char *path,
425 const char *line_prefix,
426 struct object_id *one, struct object_id *two,
427 unsigned dirty_submodule, const char *meta,
428 const char *del, const char *add, const char *reset,
429 const struct diff_options *o)
431 const struct object_id *old = &empty_tree_oid, *new = &empty_tree_oid;
432 struct commit *left = NULL, *right = NULL;
433 struct commit_list *merge_bases = NULL;
434 struct strbuf submodule_dir = STRBUF_INIT;
435 struct child_process cp = CHILD_PROCESS_INIT;
437 show_submodule_header(f, path, line_prefix, one, two, dirty_submodule,
438 meta, reset, &left, &right, &merge_bases);
440 /* We need a valid left and right commit to display a difference */
441 if (!(left || is_null_oid(one)) ||
442 !(right || is_null_oid(two)))
443 goto done;
445 if (left)
446 old = one;
447 if (right)
448 new = two;
450 fflush(f);
451 cp.git_cmd = 1;
452 cp.dir = path;
453 cp.out = dup(fileno(f));
454 cp.no_stdin = 1;
456 /* TODO: other options may need to be passed here. */
457 argv_array_push(&cp.args, "diff");
458 argv_array_pushf(&cp.args, "--line-prefix=%s", line_prefix);
459 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
460 argv_array_pushf(&cp.args, "--src-prefix=%s%s/",
461 o->b_prefix, path);
462 argv_array_pushf(&cp.args, "--dst-prefix=%s%s/",
463 o->a_prefix, path);
464 } else {
465 argv_array_pushf(&cp.args, "--src-prefix=%s%s/",
466 o->a_prefix, path);
467 argv_array_pushf(&cp.args, "--dst-prefix=%s%s/",
468 o->b_prefix, path);
470 argv_array_push(&cp.args, oid_to_hex(old));
472 * If the submodule has modified content, we will diff against the
473 * work tree, under the assumption that the user has asked for the
474 * diff format and wishes to actually see all differences even if they
475 * haven't yet been committed to the submodule yet.
477 if (!(dirty_submodule & DIRTY_SUBMODULE_MODIFIED))
478 argv_array_push(&cp.args, oid_to_hex(new));
480 if (run_command(&cp))
481 fprintf(f, "(diff failed)\n");
483 done:
484 strbuf_release(&submodule_dir);
485 if (merge_bases)
486 free_commit_list(merge_bases);
487 if (left)
488 clear_commit_marks(left, ~0);
489 if (right)
490 clear_commit_marks(right, ~0);
493 void set_config_fetch_recurse_submodules(int value)
495 config_fetch_recurse_submodules = value;
498 static int has_remote(const char *refname, const struct object_id *oid,
499 int flags, void *cb_data)
501 return 1;
504 static int submodule_needs_pushing(const char *path, const unsigned char sha1[20])
506 if (add_submodule_odb(path) || !lookup_commit_reference(sha1))
507 return 0;
509 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
510 struct child_process cp = CHILD_PROCESS_INIT;
511 const char *argv[] = {"rev-list", NULL, "--not", "--remotes", "-n", "1" , NULL};
512 struct strbuf buf = STRBUF_INIT;
513 int needs_pushing = 0;
515 argv[1] = sha1_to_hex(sha1);
516 cp.argv = argv;
517 prepare_submodule_repo_env(&cp.env_array);
518 cp.git_cmd = 1;
519 cp.no_stdin = 1;
520 cp.out = -1;
521 cp.dir = path;
522 if (start_command(&cp))
523 die("Could not run 'git rev-list %s --not --remotes -n 1' command in submodule %s",
524 sha1_to_hex(sha1), path);
525 if (strbuf_read(&buf, cp.out, 41))
526 needs_pushing = 1;
527 finish_command(&cp);
528 close(cp.out);
529 strbuf_release(&buf);
530 return needs_pushing;
533 return 0;
536 static void collect_submodules_from_diff(struct diff_queue_struct *q,
537 struct diff_options *options,
538 void *data)
540 int i;
541 struct string_list *needs_pushing = data;
543 for (i = 0; i < q->nr; i++) {
544 struct diff_filepair *p = q->queue[i];
545 if (!S_ISGITLINK(p->two->mode))
546 continue;
547 if (submodule_needs_pushing(p->two->path, p->two->oid.hash))
548 string_list_insert(needs_pushing, p->two->path);
552 static void find_unpushed_submodule_commits(struct commit *commit,
553 struct string_list *needs_pushing)
555 struct rev_info rev;
557 init_revisions(&rev, NULL);
558 rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
559 rev.diffopt.format_callback = collect_submodules_from_diff;
560 rev.diffopt.format_callback_data = needs_pushing;
561 diff_tree_combined_merge(commit, 1, &rev);
564 int find_unpushed_submodules(unsigned char new_sha1[20],
565 const char *remotes_name, struct string_list *needs_pushing)
567 struct rev_info rev;
568 struct commit *commit;
569 const char *argv[] = {NULL, NULL, "--not", "NULL", NULL};
570 int argc = ARRAY_SIZE(argv) - 1;
571 char *sha1_copy;
573 struct strbuf remotes_arg = STRBUF_INIT;
575 strbuf_addf(&remotes_arg, "--remotes=%s", remotes_name);
576 init_revisions(&rev, NULL);
577 sha1_copy = xstrdup(sha1_to_hex(new_sha1));
578 argv[1] = sha1_copy;
579 argv[3] = remotes_arg.buf;
580 setup_revisions(argc, argv, &rev, NULL);
581 if (prepare_revision_walk(&rev))
582 die("revision walk setup failed");
584 while ((commit = get_revision(&rev)) != NULL)
585 find_unpushed_submodule_commits(commit, needs_pushing);
587 reset_revision_walk();
588 free(sha1_copy);
589 strbuf_release(&remotes_arg);
591 return needs_pushing->nr;
594 static int push_submodule(const char *path)
596 if (add_submodule_odb(path))
597 return 1;
599 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
600 struct child_process cp = CHILD_PROCESS_INIT;
601 const char *argv[] = {"push", NULL};
603 cp.argv = argv;
604 prepare_submodule_repo_env(&cp.env_array);
605 cp.git_cmd = 1;
606 cp.no_stdin = 1;
607 cp.dir = path;
608 if (run_command(&cp))
609 return 0;
610 close(cp.out);
613 return 1;
616 int push_unpushed_submodules(unsigned char new_sha1[20], const char *remotes_name)
618 int i, ret = 1;
619 struct string_list needs_pushing = STRING_LIST_INIT_DUP;
621 if (!find_unpushed_submodules(new_sha1, remotes_name, &needs_pushing))
622 return 1;
624 for (i = 0; i < needs_pushing.nr; i++) {
625 const char *path = needs_pushing.items[i].string;
626 fprintf(stderr, "Pushing submodule '%s'\n", path);
627 if (!push_submodule(path)) {
628 fprintf(stderr, "Unable to push submodule '%s'\n", path);
629 ret = 0;
633 string_list_clear(&needs_pushing, 0);
635 return ret;
638 static int is_submodule_commit_present(const char *path, unsigned char sha1[20])
640 int is_present = 0;
641 if (!add_submodule_odb(path) && lookup_commit_reference(sha1)) {
642 /* Even if the submodule is checked out and the commit is
643 * present, make sure it is reachable from a ref. */
644 struct child_process cp = CHILD_PROCESS_INIT;
645 const char *argv[] = {"rev-list", "-n", "1", NULL, "--not", "--all", NULL};
646 struct strbuf buf = STRBUF_INIT;
648 argv[3] = sha1_to_hex(sha1);
649 cp.argv = argv;
650 prepare_submodule_repo_env(&cp.env_array);
651 cp.git_cmd = 1;
652 cp.no_stdin = 1;
653 cp.dir = path;
654 if (!capture_command(&cp, &buf, 1024) && !buf.len)
655 is_present = 1;
657 strbuf_release(&buf);
659 return is_present;
662 static void submodule_collect_changed_cb(struct diff_queue_struct *q,
663 struct diff_options *options,
664 void *data)
666 int i;
667 for (i = 0; i < q->nr; i++) {
668 struct diff_filepair *p = q->queue[i];
669 if (!S_ISGITLINK(p->two->mode))
670 continue;
672 if (S_ISGITLINK(p->one->mode)) {
673 /* NEEDSWORK: We should honor the name configured in
674 * the .gitmodules file of the commit we are examining
675 * here to be able to correctly follow submodules
676 * being moved around. */
677 struct string_list_item *path;
678 path = unsorted_string_list_lookup(&changed_submodule_paths, p->two->path);
679 if (!path && !is_submodule_commit_present(p->two->path, p->two->oid.hash))
680 string_list_append(&changed_submodule_paths, xstrdup(p->two->path));
681 } else {
682 /* Submodule is new or was moved here */
683 /* NEEDSWORK: When the .git directories of submodules
684 * live inside the superprojects .git directory some
685 * day we should fetch new submodules directly into
686 * that location too when config or options request
687 * that so they can be checked out from there. */
688 continue;
693 static int add_sha1_to_array(const char *ref, const struct object_id *oid,
694 int flags, void *data)
696 sha1_array_append(data, oid->hash);
697 return 0;
700 void check_for_new_submodule_commits(unsigned char new_sha1[20])
702 if (!initialized_fetch_ref_tips) {
703 for_each_ref(add_sha1_to_array, &ref_tips_before_fetch);
704 initialized_fetch_ref_tips = 1;
707 sha1_array_append(&ref_tips_after_fetch, new_sha1);
710 static int add_sha1_to_argv(const unsigned char sha1[20], void *data)
712 argv_array_push(data, sha1_to_hex(sha1));
713 return 0;
716 static void calculate_changed_submodule_paths(void)
718 struct rev_info rev;
719 struct commit *commit;
720 struct argv_array argv = ARGV_ARRAY_INIT;
722 /* No need to check if there are no submodules configured */
723 if (!submodule_from_path(NULL, NULL))
724 return;
726 init_revisions(&rev, NULL);
727 argv_array_push(&argv, "--"); /* argv[0] program name */
728 sha1_array_for_each_unique(&ref_tips_after_fetch,
729 add_sha1_to_argv, &argv);
730 argv_array_push(&argv, "--not");
731 sha1_array_for_each_unique(&ref_tips_before_fetch,
732 add_sha1_to_argv, &argv);
733 setup_revisions(argv.argc, argv.argv, &rev, NULL);
734 if (prepare_revision_walk(&rev))
735 die("revision walk setup failed");
738 * Collect all submodules (whether checked out or not) for which new
739 * commits have been recorded upstream in "changed_submodule_paths".
741 while ((commit = get_revision(&rev))) {
742 struct commit_list *parent = commit->parents;
743 while (parent) {
744 struct diff_options diff_opts;
745 diff_setup(&diff_opts);
746 DIFF_OPT_SET(&diff_opts, RECURSIVE);
747 diff_opts.output_format |= DIFF_FORMAT_CALLBACK;
748 diff_opts.format_callback = submodule_collect_changed_cb;
749 diff_setup_done(&diff_opts);
750 diff_tree_sha1(parent->item->object.oid.hash, commit->object.oid.hash, "", &diff_opts);
751 diffcore_std(&diff_opts);
752 diff_flush(&diff_opts);
753 parent = parent->next;
757 argv_array_clear(&argv);
758 sha1_array_clear(&ref_tips_before_fetch);
759 sha1_array_clear(&ref_tips_after_fetch);
760 initialized_fetch_ref_tips = 0;
763 struct submodule_parallel_fetch {
764 int count;
765 struct argv_array args;
766 const char *work_tree;
767 const char *prefix;
768 int command_line_option;
769 int quiet;
770 int result;
772 #define SPF_INIT {0, ARGV_ARRAY_INIT, NULL, NULL, 0, 0, 0}
774 static int get_next_submodule(struct child_process *cp,
775 struct strbuf *err, void *data, void **task_cb)
777 int ret = 0;
778 struct submodule_parallel_fetch *spf = data;
780 for (; spf->count < active_nr; spf->count++) {
781 struct strbuf submodule_path = STRBUF_INIT;
782 struct strbuf submodule_git_dir = STRBUF_INIT;
783 struct strbuf submodule_prefix = STRBUF_INIT;
784 const struct cache_entry *ce = active_cache[spf->count];
785 const char *git_dir, *default_argv;
786 const struct submodule *submodule;
788 if (!S_ISGITLINK(ce->ce_mode))
789 continue;
791 submodule = submodule_from_path(null_sha1, ce->name);
792 if (!submodule)
793 submodule = submodule_from_name(null_sha1, ce->name);
795 default_argv = "yes";
796 if (spf->command_line_option == RECURSE_SUBMODULES_DEFAULT) {
797 if (submodule &&
798 submodule->fetch_recurse !=
799 RECURSE_SUBMODULES_NONE) {
800 if (submodule->fetch_recurse ==
801 RECURSE_SUBMODULES_OFF)
802 continue;
803 if (submodule->fetch_recurse ==
804 RECURSE_SUBMODULES_ON_DEMAND) {
805 if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
806 continue;
807 default_argv = "on-demand";
809 } else {
810 if ((config_fetch_recurse_submodules == RECURSE_SUBMODULES_OFF) ||
811 gitmodules_is_unmerged)
812 continue;
813 if (config_fetch_recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND) {
814 if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
815 continue;
816 default_argv = "on-demand";
819 } else if (spf->command_line_option == RECURSE_SUBMODULES_ON_DEMAND) {
820 if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
821 continue;
822 default_argv = "on-demand";
825 strbuf_addf(&submodule_path, "%s/%s", spf->work_tree, ce->name);
826 strbuf_addf(&submodule_git_dir, "%s/.git", submodule_path.buf);
827 strbuf_addf(&submodule_prefix, "%s%s/", spf->prefix, ce->name);
828 git_dir = read_gitfile(submodule_git_dir.buf);
829 if (!git_dir)
830 git_dir = submodule_git_dir.buf;
831 if (is_directory(git_dir)) {
832 child_process_init(cp);
833 cp->dir = strbuf_detach(&submodule_path, NULL);
834 prepare_submodule_repo_env(&cp->env_array);
835 cp->git_cmd = 1;
836 if (!spf->quiet)
837 strbuf_addf(err, "Fetching submodule %s%s\n",
838 spf->prefix, ce->name);
839 argv_array_init(&cp->args);
840 argv_array_pushv(&cp->args, spf->args.argv);
841 argv_array_push(&cp->args, default_argv);
842 argv_array_push(&cp->args, "--submodule-prefix");
843 argv_array_push(&cp->args, submodule_prefix.buf);
844 ret = 1;
846 strbuf_release(&submodule_path);
847 strbuf_release(&submodule_git_dir);
848 strbuf_release(&submodule_prefix);
849 if (ret) {
850 spf->count++;
851 return 1;
854 return 0;
857 static int fetch_start_failure(struct strbuf *err,
858 void *cb, void *task_cb)
860 struct submodule_parallel_fetch *spf = cb;
862 spf->result = 1;
864 return 0;
867 static int fetch_finish(int retvalue, struct strbuf *err,
868 void *cb, void *task_cb)
870 struct submodule_parallel_fetch *spf = cb;
872 if (retvalue)
873 spf->result = 1;
875 return 0;
878 int fetch_populated_submodules(const struct argv_array *options,
879 const char *prefix, int command_line_option,
880 int quiet, int max_parallel_jobs)
882 int i;
883 struct submodule_parallel_fetch spf = SPF_INIT;
885 spf.work_tree = get_git_work_tree();
886 spf.command_line_option = command_line_option;
887 spf.quiet = quiet;
888 spf.prefix = prefix;
890 if (!spf.work_tree)
891 goto out;
893 if (read_cache() < 0)
894 die("index file corrupt");
896 argv_array_push(&spf.args, "fetch");
897 for (i = 0; i < options->argc; i++)
898 argv_array_push(&spf.args, options->argv[i]);
899 argv_array_push(&spf.args, "--recurse-submodules-default");
900 /* default value, "--submodule-prefix" and its value are added later */
902 if (max_parallel_jobs < 0)
903 max_parallel_jobs = parallel_jobs;
905 calculate_changed_submodule_paths();
906 run_processes_parallel(max_parallel_jobs,
907 get_next_submodule,
908 fetch_start_failure,
909 fetch_finish,
910 &spf);
912 argv_array_clear(&spf.args);
913 out:
914 string_list_clear(&changed_submodule_paths, 1);
915 return spf.result;
918 unsigned is_submodule_modified(const char *path, int ignore_untracked)
920 ssize_t len;
921 struct child_process cp = CHILD_PROCESS_INIT;
922 const char *argv[] = {
923 "status",
924 "--porcelain",
925 NULL,
926 NULL,
928 struct strbuf buf = STRBUF_INIT;
929 unsigned dirty_submodule = 0;
930 const char *line, *next_line;
931 const char *git_dir;
933 strbuf_addf(&buf, "%s/.git", path);
934 git_dir = read_gitfile(buf.buf);
935 if (!git_dir)
936 git_dir = buf.buf;
937 if (!is_directory(git_dir)) {
938 strbuf_release(&buf);
939 /* The submodule is not checked out, so it is not modified */
940 return 0;
943 strbuf_reset(&buf);
945 if (ignore_untracked)
946 argv[2] = "-uno";
948 cp.argv = argv;
949 prepare_submodule_repo_env(&cp.env_array);
950 cp.git_cmd = 1;
951 cp.no_stdin = 1;
952 cp.out = -1;
953 cp.dir = path;
954 if (start_command(&cp))
955 die("Could not run 'git status --porcelain' in submodule %s", path);
957 len = strbuf_read(&buf, cp.out, 1024);
958 line = buf.buf;
959 while (len > 2) {
960 if ((line[0] == '?') && (line[1] == '?')) {
961 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
962 if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
963 break;
964 } else {
965 dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
966 if (ignore_untracked ||
967 (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED))
968 break;
970 next_line = strchr(line, '\n');
971 if (!next_line)
972 break;
973 next_line++;
974 len -= (next_line - line);
975 line = next_line;
977 close(cp.out);
979 if (finish_command(&cp))
980 die("'git status --porcelain' failed in submodule %s", path);
982 strbuf_release(&buf);
983 return dirty_submodule;
986 int submodule_uses_gitfile(const char *path)
988 struct child_process cp = CHILD_PROCESS_INIT;
989 const char *argv[] = {
990 "submodule",
991 "foreach",
992 "--quiet",
993 "--recursive",
994 "test -f .git",
995 NULL,
997 struct strbuf buf = STRBUF_INIT;
998 const char *git_dir;
1000 strbuf_addf(&buf, "%s/.git", path);
1001 git_dir = read_gitfile(buf.buf);
1002 if (!git_dir) {
1003 strbuf_release(&buf);
1004 return 0;
1006 strbuf_release(&buf);
1008 /* Now test that all nested submodules use a gitfile too */
1009 cp.argv = argv;
1010 prepare_submodule_repo_env(&cp.env_array);
1011 cp.git_cmd = 1;
1012 cp.no_stdin = 1;
1013 cp.no_stderr = 1;
1014 cp.no_stdout = 1;
1015 cp.dir = path;
1016 if (run_command(&cp))
1017 return 0;
1019 return 1;
1022 int ok_to_remove_submodule(const char *path)
1024 ssize_t len;
1025 struct child_process cp = CHILD_PROCESS_INIT;
1026 const char *argv[] = {
1027 "status",
1028 "--porcelain",
1029 "-u",
1030 "--ignore-submodules=none",
1031 NULL,
1033 struct strbuf buf = STRBUF_INIT;
1034 int ok_to_remove = 1;
1036 if (!file_exists(path) || is_empty_dir(path))
1037 return 1;
1039 if (!submodule_uses_gitfile(path))
1040 return 0;
1042 cp.argv = argv;
1043 prepare_submodule_repo_env(&cp.env_array);
1044 cp.git_cmd = 1;
1045 cp.no_stdin = 1;
1046 cp.out = -1;
1047 cp.dir = path;
1048 if (start_command(&cp))
1049 die("Could not run 'git status --porcelain -uall --ignore-submodules=none' in submodule %s", path);
1051 len = strbuf_read(&buf, cp.out, 1024);
1052 if (len > 2)
1053 ok_to_remove = 0;
1054 close(cp.out);
1056 if (finish_command(&cp))
1057 die("'git status --porcelain -uall --ignore-submodules=none' failed in submodule %s", path);
1059 strbuf_release(&buf);
1060 return ok_to_remove;
1063 static int find_first_merges(struct object_array *result, const char *path,
1064 struct commit *a, struct commit *b)
1066 int i, j;
1067 struct object_array merges = OBJECT_ARRAY_INIT;
1068 struct commit *commit;
1069 int contains_another;
1071 char merged_revision[42];
1072 const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
1073 "--all", merged_revision, NULL };
1074 struct rev_info revs;
1075 struct setup_revision_opt rev_opts;
1077 memset(result, 0, sizeof(struct object_array));
1078 memset(&rev_opts, 0, sizeof(rev_opts));
1080 /* get all revisions that merge commit a */
1081 snprintf(merged_revision, sizeof(merged_revision), "^%s",
1082 oid_to_hex(&a->object.oid));
1083 init_revisions(&revs, NULL);
1084 rev_opts.submodule = path;
1085 setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
1087 /* save all revisions from the above list that contain b */
1088 if (prepare_revision_walk(&revs))
1089 die("revision walk setup failed");
1090 while ((commit = get_revision(&revs)) != NULL) {
1091 struct object *o = &(commit->object);
1092 if (in_merge_bases(b, commit))
1093 add_object_array(o, NULL, &merges);
1095 reset_revision_walk();
1097 /* Now we've got all merges that contain a and b. Prune all
1098 * merges that contain another found merge and save them in
1099 * result.
1101 for (i = 0; i < merges.nr; i++) {
1102 struct commit *m1 = (struct commit *) merges.objects[i].item;
1104 contains_another = 0;
1105 for (j = 0; j < merges.nr; j++) {
1106 struct commit *m2 = (struct commit *) merges.objects[j].item;
1107 if (i != j && in_merge_bases(m2, m1)) {
1108 contains_another = 1;
1109 break;
1113 if (!contains_another)
1114 add_object_array(merges.objects[i].item, NULL, result);
1117 free(merges.objects);
1118 return result->nr;
1121 static void print_commit(struct commit *commit)
1123 struct strbuf sb = STRBUF_INIT;
1124 struct pretty_print_context ctx = {0};
1125 ctx.date_mode.type = DATE_NORMAL;
1126 format_commit_message(commit, " %h: %m %s", &sb, &ctx);
1127 fprintf(stderr, "%s\n", sb.buf);
1128 strbuf_release(&sb);
1131 #define MERGE_WARNING(path, msg) \
1132 warning("Failed to merge submodule %s (%s)", path, msg);
1134 int merge_submodule(unsigned char result[20], const char *path,
1135 const unsigned char base[20], const unsigned char a[20],
1136 const unsigned char b[20], int search)
1138 struct commit *commit_base, *commit_a, *commit_b;
1139 int parent_count;
1140 struct object_array merges;
1142 int i;
1144 /* store a in result in case we fail */
1145 hashcpy(result, a);
1147 /* we can not handle deletion conflicts */
1148 if (is_null_sha1(base))
1149 return 0;
1150 if (is_null_sha1(a))
1151 return 0;
1152 if (is_null_sha1(b))
1153 return 0;
1155 if (add_submodule_odb(path)) {
1156 MERGE_WARNING(path, "not checked out");
1157 return 0;
1160 if (!(commit_base = lookup_commit_reference(base)) ||
1161 !(commit_a = lookup_commit_reference(a)) ||
1162 !(commit_b = lookup_commit_reference(b))) {
1163 MERGE_WARNING(path, "commits not present");
1164 return 0;
1167 /* check whether both changes are forward */
1168 if (!in_merge_bases(commit_base, commit_a) ||
1169 !in_merge_bases(commit_base, commit_b)) {
1170 MERGE_WARNING(path, "commits don't follow merge-base");
1171 return 0;
1174 /* Case #1: a is contained in b or vice versa */
1175 if (in_merge_bases(commit_a, commit_b)) {
1176 hashcpy(result, b);
1177 return 1;
1179 if (in_merge_bases(commit_b, commit_a)) {
1180 hashcpy(result, a);
1181 return 1;
1185 * Case #2: There are one or more merges that contain a and b in
1186 * the submodule. If there is only one, then present it as a
1187 * suggestion to the user, but leave it marked unmerged so the
1188 * user needs to confirm the resolution.
1191 /* Skip the search if makes no sense to the calling context. */
1192 if (!search)
1193 return 0;
1195 /* find commit which merges them */
1196 parent_count = find_first_merges(&merges, path, commit_a, commit_b);
1197 switch (parent_count) {
1198 case 0:
1199 MERGE_WARNING(path, "merge following commits not found");
1200 break;
1202 case 1:
1203 MERGE_WARNING(path, "not fast-forward");
1204 fprintf(stderr, "Found a possible merge resolution "
1205 "for the submodule:\n");
1206 print_commit((struct commit *) merges.objects[0].item);
1207 fprintf(stderr,
1208 "If this is correct simply add it to the index "
1209 "for example\n"
1210 "by using:\n\n"
1211 " git update-index --cacheinfo 160000 %s \"%s\"\n\n"
1212 "which will accept this suggestion.\n",
1213 oid_to_hex(&merges.objects[0].item->oid), path);
1214 break;
1216 default:
1217 MERGE_WARNING(path, "multiple merges found");
1218 for (i = 0; i < merges.nr; i++)
1219 print_commit((struct commit *) merges.objects[i].item);
1222 free(merges.objects);
1223 return 0;
1226 /* Update gitfile and core.worktree setting to connect work tree and git dir */
1227 void connect_work_tree_and_git_dir(const char *work_tree, const char *git_dir)
1229 struct strbuf file_name = STRBUF_INIT;
1230 struct strbuf rel_path = STRBUF_INIT;
1231 const char *real_work_tree = xstrdup(real_path(work_tree));
1233 /* Update gitfile */
1234 strbuf_addf(&file_name, "%s/.git", work_tree);
1235 write_file(file_name.buf, "gitdir: %s",
1236 relative_path(git_dir, real_work_tree, &rel_path));
1238 /* Update core.worktree setting */
1239 strbuf_reset(&file_name);
1240 strbuf_addf(&file_name, "%s/config", git_dir);
1241 git_config_set_in_file(file_name.buf, "core.worktree",
1242 relative_path(real_work_tree, git_dir,
1243 &rel_path));
1245 strbuf_release(&file_name);
1246 strbuf_release(&rel_path);
1247 free((void *)real_work_tree);
1250 int parallel_submodules(void)
1252 return parallel_jobs;
1255 void prepare_submodule_repo_env(struct argv_array *out)
1257 const char * const *var;
1259 for (var = local_repo_env; *var; var++) {
1260 if (strcmp(*var, CONFIG_DATA_ENVIRONMENT))
1261 argv_array_push(out, *var);
1263 argv_array_push(out, "GIT_DIR=.git");