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#include "worktree.h"
18
19static int config_fetch_recurse_submodules = RECURSE_SUBMODULES_ON_DEMAND;
20static int config_update_recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
21static int parallel_jobs = 1;
22static struct string_list changed_submodule_paths = STRING_LIST_INIT_NODUP;
23static int initialized_fetch_ref_tips;
24static struct sha1_array ref_tips_before_fetch;
25static struct sha1_array ref_tips_after_fetch;
26
27/*
28 * The following flag is set if the .gitmodules file is unmerged. We then
29 * disable recursion for all submodules where .git/config doesn't have a
30 * matching config entry because we can't guess what might be configured in
31 * .gitmodules unless the user resolves the conflict. When a command line
32 * option is given (which always overrides configuration) this flag will be
33 * ignored.
34 */
35static int gitmodules_is_unmerged;
36
37/*
38 * This flag is set if the .gitmodules file had unstaged modifications on
39 * startup. This must be checked before allowing modifications to the
40 * .gitmodules file with the intention to stage them later, because when
41 * continuing we would stage the modifications the user didn't stage herself
42 * too. That might change in a future version when we learn to stage the
43 * changes we do ourselves without staging any previous modifications.
44 */
45static int gitmodules_is_modified;
46
47int is_staging_gitmodules_ok(void)
48{
49 return !gitmodules_is_modified;
50}
51
52/*
53 * Try to update the "path" entry in the "submodule.<name>" section of the
54 * .gitmodules file. Return 0 only if a .gitmodules file was found, a section
55 * with the correct path=<oldpath> setting was found and we could update it.
56 */
57int update_path_in_gitmodules(const char *oldpath, const char *newpath)
58{
59 struct strbuf entry = STRBUF_INIT;
60 const struct submodule *submodule;
61
62 if (!file_exists(".gitmodules")) /* Do nothing without .gitmodules */
63 return -1;
64
65 if (gitmodules_is_unmerged)
66 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
67
68 submodule = submodule_from_path(null_sha1, oldpath);
69 if (!submodule || !submodule->name) {
70 warning(_("Could not find section in .gitmodules where path=%s"), oldpath);
71 return -1;
72 }
73 strbuf_addstr(&entry, "submodule.");
74 strbuf_addstr(&entry, submodule->name);
75 strbuf_addstr(&entry, ".path");
76 if (git_config_set_in_file_gently(".gitmodules", entry.buf, newpath) < 0) {
77 /* Maybe the user already did that, don't error out here */
78 warning(_("Could not update .gitmodules entry %s"), entry.buf);
79 strbuf_release(&entry);
80 return -1;
81 }
82 strbuf_release(&entry);
83 return 0;
84}
85
86/*
87 * Try to remove the "submodule.<name>" section from .gitmodules where the given
88 * path is configured. Return 0 only if a .gitmodules file was found, a section
89 * with the correct path=<path> setting was found and we could remove it.
90 */
91int remove_path_from_gitmodules(const char *path)
92{
93 struct strbuf sect = STRBUF_INIT;
94 const struct submodule *submodule;
95
96 if (!file_exists(".gitmodules")) /* Do nothing without .gitmodules */
97 return -1;
98
99 if (gitmodules_is_unmerged)
100 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
101
102 submodule = submodule_from_path(null_sha1, path);
103 if (!submodule || !submodule->name) {
104 warning(_("Could not find section in .gitmodules where path=%s"), path);
105 return -1;
106 }
107 strbuf_addstr(§, "submodule.");
108 strbuf_addstr(§, submodule->name);
109 if (git_config_rename_section_in_file(".gitmodules", sect.buf, NULL) < 0) {
110 /* Maybe the user already did that, don't error out here */
111 warning(_("Could not remove .gitmodules entry for %s"), path);
112 strbuf_release(§);
113 return -1;
114 }
115 strbuf_release(§);
116 return 0;
117}
118
119void stage_updated_gitmodules(void)
120{
121 if (add_file_to_cache(".gitmodules", 0))
122 die(_("staging updated .gitmodules failed"));
123}
124
125static int add_submodule_odb(const char *path)
126{
127 struct strbuf objects_directory = STRBUF_INIT;
128 int ret = 0;
129
130 ret = strbuf_git_path_submodule(&objects_directory, path, "objects/");
131 if (ret)
132 goto done;
133 if (!is_directory(objects_directory.buf)) {
134 ret = -1;
135 goto done;
136 }
137 add_to_alternates_memory(objects_directory.buf);
138done:
139 strbuf_release(&objects_directory);
140 return ret;
141}
142
143void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
144 const char *path)
145{
146 const struct submodule *submodule = submodule_from_path(null_sha1, path);
147 if (submodule) {
148 if (submodule->ignore)
149 handle_ignore_submodules_arg(diffopt, submodule->ignore);
150 else if (gitmodules_is_unmerged)
151 DIFF_OPT_SET(diffopt, IGNORE_SUBMODULES);
152 }
153}
154
155int submodule_config(const char *var, const char *value, void *cb)
156{
157 if (!strcmp(var, "submodule.fetchjobs")) {
158 parallel_jobs = git_config_int(var, value);
159 if (parallel_jobs < 0)
160 die(_("negative values not allowed for submodule.fetchJobs"));
161 return 0;
162 } else if (starts_with(var, "submodule."))
163 return parse_submodule_config_option(var, value);
164 else if (!strcmp(var, "fetch.recursesubmodules")) {
165 config_fetch_recurse_submodules = parse_fetch_recurse_submodules_arg(var, value);
166 return 0;
167 }
168 return 0;
169}
170
171void gitmodules_config(void)
172{
173 const char *work_tree = get_git_work_tree();
174 if (work_tree) {
175 struct strbuf gitmodules_path = STRBUF_INIT;
176 int pos;
177 strbuf_addstr(&gitmodules_path, work_tree);
178 strbuf_addstr(&gitmodules_path, "/.gitmodules");
179 if (read_cache() < 0)
180 die("index file corrupt");
181 pos = cache_name_pos(".gitmodules", 11);
182 if (pos < 0) { /* .gitmodules not found or isn't merged */
183 pos = -1 - pos;
184 if (active_nr > pos) { /* there is a .gitmodules */
185 const struct cache_entry *ce = active_cache[pos];
186 if (ce_namelen(ce) == 11 &&
187 !memcmp(ce->name, ".gitmodules", 11))
188 gitmodules_is_unmerged = 1;
189 }
190 } else if (pos < active_nr) {
191 struct stat st;
192 if (lstat(".gitmodules", &st) == 0 &&
193 ce_match_stat(active_cache[pos], &st, 0) & DATA_CHANGED)
194 gitmodules_is_modified = 1;
195 }
196
197 if (!gitmodules_is_unmerged)
198 git_config_from_file(submodule_config, gitmodules_path.buf, NULL);
199 strbuf_release(&gitmodules_path);
200 }
201}
202
203void gitmodules_config_sha1(const unsigned char *commit_sha1)
204{
205 struct strbuf rev = STRBUF_INIT;
206 unsigned char sha1[20];
207
208 if (gitmodule_sha1_from_commit(commit_sha1, sha1, &rev)) {
209 git_config_from_blob_sha1(submodule_config, rev.buf,
210 sha1, NULL);
211 }
212 strbuf_release(&rev);
213}
214
215/*
216 * NEEDSWORK: With the addition of different configuration options to determine
217 * if a submodule is of interests, the validity of this function's name comes
218 * into question. Once the dust has settled and more concrete terminology is
219 * decided upon, come up with a more proper name for this function. One
220 * potential candidate could be 'is_submodule_active()'.
221 *
222 * Determine if a submodule has been initialized at a given 'path'
223 */
224int is_submodule_initialized(const char *path)
225{
226 int ret = 0;
227 char *key = NULL;
228 char *value = NULL;
229 const struct string_list *sl;
230 const struct submodule *module = submodule_from_path(null_sha1, path);
231
232 /* early return if there isn't a path->module mapping */
233 if (!module)
234 return 0;
235
236 /* submodule.<name>.active is set */
237 key = xstrfmt("submodule.%s.active", module->name);
238 if (!git_config_get_bool(key, &ret)) {
239 free(key);
240 return ret;
241 }
242 free(key);
243
244 /* submodule.active is set */
245 sl = git_config_get_value_multi("submodule.active");
246 if (sl) {
247 struct pathspec ps;
248 struct argv_array args = ARGV_ARRAY_INIT;
249 const struct string_list_item *item;
250
251 for_each_string_list_item(item, sl) {
252 argv_array_push(&args, item->string);
253 }
254
255 parse_pathspec(&ps, 0, 0, NULL, args.argv);
256 ret = match_pathspec(&ps, path, strlen(path), 0, NULL, 1);
257
258 argv_array_clear(&args);
259 clear_pathspec(&ps);
260 return ret;
261 }
262
263 /* fallback to checking if the URL is set */
264 key = xstrfmt("submodule.%s.url", module->name);
265 ret = !git_config_get_string(key, &value);
266
267 free(value);
268 free(key);
269 return ret;
270}
271
272int is_submodule_populated_gently(const char *path, int *return_error_code)
273{
274 int ret = 0;
275 char *gitdir = xstrfmt("%s/.git", path);
276
277 if (resolve_gitdir_gently(gitdir, return_error_code))
278 ret = 1;
279
280 free(gitdir);
281 return ret;
282}
283
284int parse_submodule_update_strategy(const char *value,
285 struct submodule_update_strategy *dst)
286{
287 free((void*)dst->command);
288 dst->command = NULL;
289 if (!strcmp(value, "none"))
290 dst->type = SM_UPDATE_NONE;
291 else if (!strcmp(value, "checkout"))
292 dst->type = SM_UPDATE_CHECKOUT;
293 else if (!strcmp(value, "rebase"))
294 dst->type = SM_UPDATE_REBASE;
295 else if (!strcmp(value, "merge"))
296 dst->type = SM_UPDATE_MERGE;
297 else if (skip_prefix(value, "!", &value)) {
298 dst->type = SM_UPDATE_COMMAND;
299 dst->command = xstrdup(value);
300 } else
301 return -1;
302 return 0;
303}
304
305const char *submodule_strategy_to_string(const struct submodule_update_strategy *s)
306{
307 struct strbuf sb = STRBUF_INIT;
308 switch (s->type) {
309 case SM_UPDATE_CHECKOUT:
310 return "checkout";
311 case SM_UPDATE_MERGE:
312 return "merge";
313 case SM_UPDATE_REBASE:
314 return "rebase";
315 case SM_UPDATE_NONE:
316 return "none";
317 case SM_UPDATE_UNSPECIFIED:
318 return NULL;
319 case SM_UPDATE_COMMAND:
320 strbuf_addf(&sb, "!%s", s->command);
321 return strbuf_detach(&sb, NULL);
322 }
323 return NULL;
324}
325
326void handle_ignore_submodules_arg(struct diff_options *diffopt,
327 const char *arg)
328{
329 DIFF_OPT_CLR(diffopt, IGNORE_SUBMODULES);
330 DIFF_OPT_CLR(diffopt, IGNORE_UNTRACKED_IN_SUBMODULES);
331 DIFF_OPT_CLR(diffopt, IGNORE_DIRTY_SUBMODULES);
332
333 if (!strcmp(arg, "all"))
334 DIFF_OPT_SET(diffopt, IGNORE_SUBMODULES);
335 else if (!strcmp(arg, "untracked"))
336 DIFF_OPT_SET(diffopt, IGNORE_UNTRACKED_IN_SUBMODULES);
337 else if (!strcmp(arg, "dirty"))
338 DIFF_OPT_SET(diffopt, IGNORE_DIRTY_SUBMODULES);
339 else if (strcmp(arg, "none"))
340 die("bad --ignore-submodules argument: %s", arg);
341}
342
343static int prepare_submodule_summary(struct rev_info *rev, const char *path,
344 struct commit *left, struct commit *right,
345 struct commit_list *merge_bases)
346{
347 struct commit_list *list;
348
349 init_revisions(rev, NULL);
350 setup_revisions(0, NULL, rev, NULL);
351 rev->left_right = 1;
352 rev->first_parent_only = 1;
353 left->object.flags |= SYMMETRIC_LEFT;
354 add_pending_object(rev, &left->object, path);
355 add_pending_object(rev, &right->object, path);
356 for (list = merge_bases; list; list = list->next) {
357 list->item->object.flags |= UNINTERESTING;
358 add_pending_object(rev, &list->item->object,
359 oid_to_hex(&list->item->object.oid));
360 }
361 return prepare_revision_walk(rev);
362}
363
364static void print_submodule_summary(struct rev_info *rev, FILE *f,
365 const char *line_prefix,
366 const char *del, const char *add, const char *reset)
367{
368 static const char format[] = " %m %s";
369 struct strbuf sb = STRBUF_INIT;
370 struct commit *commit;
371
372 while ((commit = get_revision(rev))) {
373 struct pretty_print_context ctx = {0};
374 ctx.date_mode = rev->date_mode;
375 ctx.output_encoding = get_log_output_encoding();
376 strbuf_setlen(&sb, 0);
377 strbuf_addstr(&sb, line_prefix);
378 if (commit->object.flags & SYMMETRIC_LEFT) {
379 if (del)
380 strbuf_addstr(&sb, del);
381 }
382 else if (add)
383 strbuf_addstr(&sb, add);
384 format_commit_message(commit, format, &sb, &ctx);
385 if (reset)
386 strbuf_addstr(&sb, reset);
387 strbuf_addch(&sb, '\n');
388 fprintf(f, "%s", sb.buf);
389 }
390 strbuf_release(&sb);
391}
392
393static void prepare_submodule_repo_env_no_git_dir(struct argv_array *out)
394{
395 const char * const *var;
396
397 for (var = local_repo_env; *var; var++) {
398 if (strcmp(*var, CONFIG_DATA_ENVIRONMENT))
399 argv_array_push(out, *var);
400 }
401}
402
403void prepare_submodule_repo_env(struct argv_array *out)
404{
405 prepare_submodule_repo_env_no_git_dir(out);
406 argv_array_pushf(out, "%s=%s", GIT_DIR_ENVIRONMENT,
407 DEFAULT_GIT_DIR_ENVIRONMENT);
408}
409
410/* Helper function to display the submodule header line prior to the full
411 * summary output. If it can locate the submodule objects directory it will
412 * attempt to lookup both the left and right commits and put them into the
413 * left and right pointers.
414 */
415static void show_submodule_header(FILE *f, const char *path,
416 const char *line_prefix,
417 struct object_id *one, struct object_id *two,
418 unsigned dirty_submodule, const char *meta,
419 const char *reset,
420 struct commit **left, struct commit **right,
421 struct commit_list **merge_bases)
422{
423 const char *message = NULL;
424 struct strbuf sb = STRBUF_INIT;
425 int fast_forward = 0, fast_backward = 0;
426
427 if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
428 fprintf(f, "%sSubmodule %s contains untracked content\n",
429 line_prefix, path);
430 if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
431 fprintf(f, "%sSubmodule %s contains modified content\n",
432 line_prefix, path);
433
434 if (is_null_oid(one))
435 message = "(new submodule)";
436 else if (is_null_oid(two))
437 message = "(submodule deleted)";
438
439 if (add_submodule_odb(path)) {
440 if (!message)
441 message = "(not initialized)";
442 goto output_header;
443 }
444
445 /*
446 * Attempt to lookup the commit references, and determine if this is
447 * a fast forward or fast backwards update.
448 */
449 *left = lookup_commit_reference(one->hash);
450 *right = lookup_commit_reference(two->hash);
451
452 /*
453 * Warn about missing commits in the submodule project, but only if
454 * they aren't null.
455 */
456 if ((!is_null_oid(one) && !*left) ||
457 (!is_null_oid(two) && !*right))
458 message = "(commits not present)";
459
460 *merge_bases = get_merge_bases(*left, *right);
461 if (*merge_bases) {
462 if ((*merge_bases)->item == *left)
463 fast_forward = 1;
464 else if ((*merge_bases)->item == *right)
465 fast_backward = 1;
466 }
467
468 if (!oidcmp(one, two)) {
469 strbuf_release(&sb);
470 return;
471 }
472
473output_header:
474 strbuf_addf(&sb, "%s%sSubmodule %s ", line_prefix, meta, path);
475 strbuf_add_unique_abbrev(&sb, one->hash, DEFAULT_ABBREV);
476 strbuf_addstr(&sb, (fast_backward || fast_forward) ? ".." : "...");
477 strbuf_add_unique_abbrev(&sb, two->hash, DEFAULT_ABBREV);
478 if (message)
479 strbuf_addf(&sb, " %s%s\n", message, reset);
480 else
481 strbuf_addf(&sb, "%s:%s\n", fast_backward ? " (rewind)" : "", reset);
482 fwrite(sb.buf, sb.len, 1, f);
483
484 strbuf_release(&sb);
485}
486
487void show_submodule_summary(FILE *f, const char *path,
488 const char *line_prefix,
489 struct object_id *one, struct object_id *two,
490 unsigned dirty_submodule, const char *meta,
491 const char *del, const char *add, const char *reset)
492{
493 struct rev_info rev;
494 struct commit *left = NULL, *right = NULL;
495 struct commit_list *merge_bases = NULL;
496
497 show_submodule_header(f, path, line_prefix, one, two, dirty_submodule,
498 meta, reset, &left, &right, &merge_bases);
499
500 /*
501 * If we don't have both a left and a right pointer, there is no
502 * reason to try and display a summary. The header line should contain
503 * all the information the user needs.
504 */
505 if (!left || !right)
506 goto out;
507
508 /* Treat revision walker failure the same as missing commits */
509 if (prepare_submodule_summary(&rev, path, left, right, merge_bases)) {
510 fprintf(f, "%s(revision walker failed)\n", line_prefix);
511 goto out;
512 }
513
514 print_submodule_summary(&rev, f, line_prefix, del, add, reset);
515
516out:
517 if (merge_bases)
518 free_commit_list(merge_bases);
519 clear_commit_marks(left, ~0);
520 clear_commit_marks(right, ~0);
521}
522
523void show_submodule_inline_diff(FILE *f, const char *path,
524 const char *line_prefix,
525 struct object_id *one, struct object_id *two,
526 unsigned dirty_submodule, const char *meta,
527 const char *del, const char *add, const char *reset,
528 const struct diff_options *o)
529{
530 const struct object_id *old = &empty_tree_oid, *new = &empty_tree_oid;
531 struct commit *left = NULL, *right = NULL;
532 struct commit_list *merge_bases = NULL;
533 struct strbuf submodule_dir = STRBUF_INIT;
534 struct child_process cp = CHILD_PROCESS_INIT;
535
536 show_submodule_header(f, path, line_prefix, one, two, dirty_submodule,
537 meta, reset, &left, &right, &merge_bases);
538
539 /* We need a valid left and right commit to display a difference */
540 if (!(left || is_null_oid(one)) ||
541 !(right || is_null_oid(two)))
542 goto done;
543
544 if (left)
545 old = one;
546 if (right)
547 new = two;
548
549 fflush(f);
550 cp.git_cmd = 1;
551 cp.dir = path;
552 cp.out = dup(fileno(f));
553 cp.no_stdin = 1;
554
555 /* TODO: other options may need to be passed here. */
556 argv_array_push(&cp.args, "diff");
557 argv_array_pushf(&cp.args, "--line-prefix=%s", line_prefix);
558 if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
559 argv_array_pushf(&cp.args, "--src-prefix=%s%s/",
560 o->b_prefix, path);
561 argv_array_pushf(&cp.args, "--dst-prefix=%s%s/",
562 o->a_prefix, path);
563 } else {
564 argv_array_pushf(&cp.args, "--src-prefix=%s%s/",
565 o->a_prefix, path);
566 argv_array_pushf(&cp.args, "--dst-prefix=%s%s/",
567 o->b_prefix, path);
568 }
569 argv_array_push(&cp.args, oid_to_hex(old));
570 /*
571 * If the submodule has modified content, we will diff against the
572 * work tree, under the assumption that the user has asked for the
573 * diff format and wishes to actually see all differences even if they
574 * haven't yet been committed to the submodule yet.
575 */
576 if (!(dirty_submodule & DIRTY_SUBMODULE_MODIFIED))
577 argv_array_push(&cp.args, oid_to_hex(new));
578
579 if (run_command(&cp))
580 fprintf(f, "(diff failed)\n");
581
582done:
583 strbuf_release(&submodule_dir);
584 if (merge_bases)
585 free_commit_list(merge_bases);
586 if (left)
587 clear_commit_marks(left, ~0);
588 if (right)
589 clear_commit_marks(right, ~0);
590}
591
592void set_config_fetch_recurse_submodules(int value)
593{
594 config_fetch_recurse_submodules = value;
595}
596
597void set_config_update_recurse_submodules(int value)
598{
599 config_update_recurse_submodules = value;
600}
601
602int should_update_submodules(void)
603{
604 return config_update_recurse_submodules == RECURSE_SUBMODULES_ON;
605}
606
607const struct submodule *submodule_from_ce(const struct cache_entry *ce)
608{
609 if (!S_ISGITLINK(ce->ce_mode))
610 return NULL;
611
612 if (!should_update_submodules())
613 return NULL;
614
615 return submodule_from_path(null_sha1, ce->name);
616}
617
618static int has_remote(const char *refname, const struct object_id *oid,
619 int flags, void *cb_data)
620{
621 return 1;
622}
623
624static int append_sha1_to_argv(const unsigned char sha1[20], void *data)
625{
626 struct argv_array *argv = data;
627 argv_array_push(argv, sha1_to_hex(sha1));
628 return 0;
629}
630
631static int check_has_commit(const unsigned char sha1[20], void *data)
632{
633 int *has_commit = data;
634
635 if (!lookup_commit_reference(sha1))
636 *has_commit = 0;
637
638 return 0;
639}
640
641static int submodule_has_commits(const char *path, struct sha1_array *commits)
642{
643 int has_commit = 1;
644
645 if (add_submodule_odb(path))
646 return 0;
647
648 sha1_array_for_each_unique(commits, check_has_commit, &has_commit);
649 return has_commit;
650}
651
652static int submodule_needs_pushing(const char *path, struct sha1_array *commits)
653{
654 if (!submodule_has_commits(path, commits))
655 /*
656 * NOTE: We do consider it safe to return "no" here. The
657 * correct answer would be "We do not know" instead of
658 * "No push needed", but it is quite hard to change
659 * the submodule pointer without having the submodule
660 * around. If a user did however change the submodules
661 * without having the submodule around, this indicates
662 * an expert who knows what they are doing or a
663 * maintainer integrating work from other people. In
664 * both cases it should be safe to skip this check.
665 */
666 return 0;
667
668 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
669 struct child_process cp = CHILD_PROCESS_INIT;
670 struct strbuf buf = STRBUF_INIT;
671 int needs_pushing = 0;
672
673 argv_array_push(&cp.args, "rev-list");
674 sha1_array_for_each_unique(commits, append_sha1_to_argv, &cp.args);
675 argv_array_pushl(&cp.args, "--not", "--remotes", "-n", "1" , NULL);
676
677 prepare_submodule_repo_env(&cp.env_array);
678 cp.git_cmd = 1;
679 cp.no_stdin = 1;
680 cp.out = -1;
681 cp.dir = path;
682 if (start_command(&cp))
683 die("Could not run 'git rev-list <commits> --not --remotes -n 1' command in submodule %s",
684 path);
685 if (strbuf_read(&buf, cp.out, 41))
686 needs_pushing = 1;
687 finish_command(&cp);
688 close(cp.out);
689 strbuf_release(&buf);
690 return needs_pushing;
691 }
692
693 return 0;
694}
695
696static struct sha1_array *submodule_commits(struct string_list *submodules,
697 const char *path)
698{
699 struct string_list_item *item;
700
701 item = string_list_insert(submodules, path);
702 if (item->util)
703 return (struct sha1_array *) item->util;
704
705 /* NEEDSWORK: should we have sha1_array_init()? */
706 item->util = xcalloc(1, sizeof(struct sha1_array));
707 return (struct sha1_array *) item->util;
708}
709
710static void collect_submodules_from_diff(struct diff_queue_struct *q,
711 struct diff_options *options,
712 void *data)
713{
714 int i;
715 struct string_list *submodules = data;
716
717 for (i = 0; i < q->nr; i++) {
718 struct diff_filepair *p = q->queue[i];
719 struct sha1_array *commits;
720 if (!S_ISGITLINK(p->two->mode))
721 continue;
722 commits = submodule_commits(submodules, p->two->path);
723 sha1_array_append(commits, p->two->oid.hash);
724 }
725}
726
727static void find_unpushed_submodule_commits(struct commit *commit,
728 struct string_list *needs_pushing)
729{
730 struct rev_info rev;
731
732 init_revisions(&rev, NULL);
733 rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
734 rev.diffopt.format_callback = collect_submodules_from_diff;
735 rev.diffopt.format_callback_data = needs_pushing;
736 diff_tree_combined_merge(commit, 1, &rev);
737}
738
739static void free_submodules_sha1s(struct string_list *submodules)
740{
741 struct string_list_item *item;
742 for_each_string_list_item(item, submodules)
743 sha1_array_clear((struct sha1_array *) item->util);
744 string_list_clear(submodules, 1);
745}
746
747int find_unpushed_submodules(struct sha1_array *commits,
748 const char *remotes_name, struct string_list *needs_pushing)
749{
750 struct rev_info rev;
751 struct commit *commit;
752 struct string_list submodules = STRING_LIST_INIT_DUP;
753 struct string_list_item *submodule;
754 struct argv_array argv = ARGV_ARRAY_INIT;
755
756 init_revisions(&rev, NULL);
757
758 /* argv.argv[0] will be ignored by setup_revisions */
759 argv_array_push(&argv, "find_unpushed_submodules");
760 sha1_array_for_each_unique(commits, append_sha1_to_argv, &argv);
761 argv_array_push(&argv, "--not");
762 argv_array_pushf(&argv, "--remotes=%s", remotes_name);
763
764 setup_revisions(argv.argc, argv.argv, &rev, NULL);
765 if (prepare_revision_walk(&rev))
766 die("revision walk setup failed");
767
768 while ((commit = get_revision(&rev)) != NULL)
769 find_unpushed_submodule_commits(commit, &submodules);
770
771 reset_revision_walk();
772 argv_array_clear(&argv);
773
774 for_each_string_list_item(submodule, &submodules) {
775 struct sha1_array *commits = (struct sha1_array *) submodule->util;
776
777 if (submodule_needs_pushing(submodule->string, commits))
778 string_list_insert(needs_pushing, submodule->string);
779 }
780 free_submodules_sha1s(&submodules);
781
782 return needs_pushing->nr;
783}
784
785static int push_submodule(const char *path, int dry_run)
786{
787 if (add_submodule_odb(path))
788 return 1;
789
790 if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
791 struct child_process cp = CHILD_PROCESS_INIT;
792 argv_array_push(&cp.args, "push");
793 if (dry_run)
794 argv_array_push(&cp.args, "--dry-run");
795
796 prepare_submodule_repo_env(&cp.env_array);
797 cp.git_cmd = 1;
798 cp.no_stdin = 1;
799 cp.dir = path;
800 if (run_command(&cp))
801 return 0;
802 close(cp.out);
803 }
804
805 return 1;
806}
807
808int push_unpushed_submodules(struct sha1_array *commits,
809 const char *remotes_name,
810 int dry_run)
811{
812 int i, ret = 1;
813 struct string_list needs_pushing = STRING_LIST_INIT_DUP;
814
815 if (!find_unpushed_submodules(commits, remotes_name, &needs_pushing))
816 return 1;
817
818 for (i = 0; i < needs_pushing.nr; i++) {
819 const char *path = needs_pushing.items[i].string;
820 fprintf(stderr, "Pushing submodule '%s'\n", path);
821 if (!push_submodule(path, dry_run)) {
822 fprintf(stderr, "Unable to push submodule '%s'\n", path);
823 ret = 0;
824 }
825 }
826
827 string_list_clear(&needs_pushing, 0);
828
829 return ret;
830}
831
832static int is_submodule_commit_present(const char *path, unsigned char sha1[20])
833{
834 int is_present = 0;
835 if (!add_submodule_odb(path) && lookup_commit_reference(sha1)) {
836 /* Even if the submodule is checked out and the commit is
837 * present, make sure it is reachable from a ref. */
838 struct child_process cp = CHILD_PROCESS_INIT;
839 const char *argv[] = {"rev-list", "-n", "1", NULL, "--not", "--all", NULL};
840 struct strbuf buf = STRBUF_INIT;
841
842 argv[3] = sha1_to_hex(sha1);
843 cp.argv = argv;
844 prepare_submodule_repo_env(&cp.env_array);
845 cp.git_cmd = 1;
846 cp.no_stdin = 1;
847 cp.dir = path;
848 if (!capture_command(&cp, &buf, 1024) && !buf.len)
849 is_present = 1;
850
851 strbuf_release(&buf);
852 }
853 return is_present;
854}
855
856static void submodule_collect_changed_cb(struct diff_queue_struct *q,
857 struct diff_options *options,
858 void *data)
859{
860 int i;
861 for (i = 0; i < q->nr; i++) {
862 struct diff_filepair *p = q->queue[i];
863 if (!S_ISGITLINK(p->two->mode))
864 continue;
865
866 if (S_ISGITLINK(p->one->mode)) {
867 /* NEEDSWORK: We should honor the name configured in
868 * the .gitmodules file of the commit we are examining
869 * here to be able to correctly follow submodules
870 * being moved around. */
871 struct string_list_item *path;
872 path = unsorted_string_list_lookup(&changed_submodule_paths, p->two->path);
873 if (!path && !is_submodule_commit_present(p->two->path, p->two->oid.hash))
874 string_list_append(&changed_submodule_paths, xstrdup(p->two->path));
875 } else {
876 /* Submodule is new or was moved here */
877 /* NEEDSWORK: When the .git directories of submodules
878 * live inside the superprojects .git directory some
879 * day we should fetch new submodules directly into
880 * that location too when config or options request
881 * that so they can be checked out from there. */
882 continue;
883 }
884 }
885}
886
887static int add_sha1_to_array(const char *ref, const struct object_id *oid,
888 int flags, void *data)
889{
890 sha1_array_append(data, oid->hash);
891 return 0;
892}
893
894void check_for_new_submodule_commits(unsigned char new_sha1[20])
895{
896 if (!initialized_fetch_ref_tips) {
897 for_each_ref(add_sha1_to_array, &ref_tips_before_fetch);
898 initialized_fetch_ref_tips = 1;
899 }
900
901 sha1_array_append(&ref_tips_after_fetch, new_sha1);
902}
903
904static int add_sha1_to_argv(const unsigned char sha1[20], void *data)
905{
906 argv_array_push(data, sha1_to_hex(sha1));
907 return 0;
908}
909
910static void calculate_changed_submodule_paths(void)
911{
912 struct rev_info rev;
913 struct commit *commit;
914 struct argv_array argv = ARGV_ARRAY_INIT;
915
916 /* No need to check if there are no submodules configured */
917 if (!submodule_from_path(NULL, NULL))
918 return;
919
920 init_revisions(&rev, NULL);
921 argv_array_push(&argv, "--"); /* argv[0] program name */
922 sha1_array_for_each_unique(&ref_tips_after_fetch,
923 add_sha1_to_argv, &argv);
924 argv_array_push(&argv, "--not");
925 sha1_array_for_each_unique(&ref_tips_before_fetch,
926 add_sha1_to_argv, &argv);
927 setup_revisions(argv.argc, argv.argv, &rev, NULL);
928 if (prepare_revision_walk(&rev))
929 die("revision walk setup failed");
930
931 /*
932 * Collect all submodules (whether checked out or not) for which new
933 * commits have been recorded upstream in "changed_submodule_paths".
934 */
935 while ((commit = get_revision(&rev))) {
936 struct commit_list *parent = commit->parents;
937 while (parent) {
938 struct diff_options diff_opts;
939 diff_setup(&diff_opts);
940 DIFF_OPT_SET(&diff_opts, RECURSIVE);
941 diff_opts.output_format |= DIFF_FORMAT_CALLBACK;
942 diff_opts.format_callback = submodule_collect_changed_cb;
943 diff_setup_done(&diff_opts);
944 diff_tree_sha1(parent->item->object.oid.hash, commit->object.oid.hash, "", &diff_opts);
945 diffcore_std(&diff_opts);
946 diff_flush(&diff_opts);
947 parent = parent->next;
948 }
949 }
950
951 argv_array_clear(&argv);
952 sha1_array_clear(&ref_tips_before_fetch);
953 sha1_array_clear(&ref_tips_after_fetch);
954 initialized_fetch_ref_tips = 0;
955}
956
957struct submodule_parallel_fetch {
958 int count;
959 struct argv_array args;
960 const char *work_tree;
961 const char *prefix;
962 int command_line_option;
963 int quiet;
964 int result;
965};
966#define SPF_INIT {0, ARGV_ARRAY_INIT, NULL, NULL, 0, 0, 0}
967
968static int get_next_submodule(struct child_process *cp,
969 struct strbuf *err, void *data, void **task_cb)
970{
971 int ret = 0;
972 struct submodule_parallel_fetch *spf = data;
973
974 for (; spf->count < active_nr; spf->count++) {
975 struct strbuf submodule_path = STRBUF_INIT;
976 struct strbuf submodule_git_dir = STRBUF_INIT;
977 struct strbuf submodule_prefix = STRBUF_INIT;
978 const struct cache_entry *ce = active_cache[spf->count];
979 const char *git_dir, *default_argv;
980 const struct submodule *submodule;
981
982 if (!S_ISGITLINK(ce->ce_mode))
983 continue;
984
985 submodule = submodule_from_path(null_sha1, ce->name);
986 if (!submodule)
987 submodule = submodule_from_name(null_sha1, ce->name);
988
989 default_argv = "yes";
990 if (spf->command_line_option == RECURSE_SUBMODULES_DEFAULT) {
991 if (submodule &&
992 submodule->fetch_recurse !=
993 RECURSE_SUBMODULES_NONE) {
994 if (submodule->fetch_recurse ==
995 RECURSE_SUBMODULES_OFF)
996 continue;
997 if (submodule->fetch_recurse ==
998 RECURSE_SUBMODULES_ON_DEMAND) {
999 if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
1000 continue;
1001 default_argv = "on-demand";
1002 }
1003 } else {
1004 if ((config_fetch_recurse_submodules == RECURSE_SUBMODULES_OFF) ||
1005 gitmodules_is_unmerged)
1006 continue;
1007 if (config_fetch_recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND) {
1008 if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
1009 continue;
1010 default_argv = "on-demand";
1011 }
1012 }
1013 } else if (spf->command_line_option == RECURSE_SUBMODULES_ON_DEMAND) {
1014 if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
1015 continue;
1016 default_argv = "on-demand";
1017 }
1018
1019 strbuf_addf(&submodule_path, "%s/%s", spf->work_tree, ce->name);
1020 strbuf_addf(&submodule_git_dir, "%s/.git", submodule_path.buf);
1021 strbuf_addf(&submodule_prefix, "%s%s/", spf->prefix, ce->name);
1022 git_dir = read_gitfile(submodule_git_dir.buf);
1023 if (!git_dir)
1024 git_dir = submodule_git_dir.buf;
1025 if (is_directory(git_dir)) {
1026 child_process_init(cp);
1027 cp->dir = strbuf_detach(&submodule_path, NULL);
1028 prepare_submodule_repo_env(&cp->env_array);
1029 cp->git_cmd = 1;
1030 if (!spf->quiet)
1031 strbuf_addf(err, "Fetching submodule %s%s\n",
1032 spf->prefix, ce->name);
1033 argv_array_init(&cp->args);
1034 argv_array_pushv(&cp->args, spf->args.argv);
1035 argv_array_push(&cp->args, default_argv);
1036 argv_array_push(&cp->args, "--submodule-prefix");
1037 argv_array_push(&cp->args, submodule_prefix.buf);
1038 ret = 1;
1039 }
1040 strbuf_release(&submodule_path);
1041 strbuf_release(&submodule_git_dir);
1042 strbuf_release(&submodule_prefix);
1043 if (ret) {
1044 spf->count++;
1045 return 1;
1046 }
1047 }
1048 return 0;
1049}
1050
1051static int fetch_start_failure(struct strbuf *err,
1052 void *cb, void *task_cb)
1053{
1054 struct submodule_parallel_fetch *spf = cb;
1055
1056 spf->result = 1;
1057
1058 return 0;
1059}
1060
1061static int fetch_finish(int retvalue, struct strbuf *err,
1062 void *cb, void *task_cb)
1063{
1064 struct submodule_parallel_fetch *spf = cb;
1065
1066 if (retvalue)
1067 spf->result = 1;
1068
1069 return 0;
1070}
1071
1072int fetch_populated_submodules(const struct argv_array *options,
1073 const char *prefix, int command_line_option,
1074 int quiet, int max_parallel_jobs)
1075{
1076 int i;
1077 struct submodule_parallel_fetch spf = SPF_INIT;
1078
1079 spf.work_tree = get_git_work_tree();
1080 spf.command_line_option = command_line_option;
1081 spf.quiet = quiet;
1082 spf.prefix = prefix;
1083
1084 if (!spf.work_tree)
1085 goto out;
1086
1087 if (read_cache() < 0)
1088 die("index file corrupt");
1089
1090 argv_array_push(&spf.args, "fetch");
1091 for (i = 0; i < options->argc; i++)
1092 argv_array_push(&spf.args, options->argv[i]);
1093 argv_array_push(&spf.args, "--recurse-submodules-default");
1094 /* default value, "--submodule-prefix" and its value are added later */
1095
1096 if (max_parallel_jobs < 0)
1097 max_parallel_jobs = parallel_jobs;
1098
1099 calculate_changed_submodule_paths();
1100 run_processes_parallel(max_parallel_jobs,
1101 get_next_submodule,
1102 fetch_start_failure,
1103 fetch_finish,
1104 &spf);
1105
1106 argv_array_clear(&spf.args);
1107out:
1108 string_list_clear(&changed_submodule_paths, 1);
1109 return spf.result;
1110}
1111
1112unsigned is_submodule_modified(const char *path, int ignore_untracked)
1113{
1114 ssize_t len;
1115 struct child_process cp = CHILD_PROCESS_INIT;
1116 const char *argv[] = {
1117 "status",
1118 "--porcelain",
1119 NULL,
1120 NULL,
1121 };
1122 struct strbuf buf = STRBUF_INIT;
1123 unsigned dirty_submodule = 0;
1124 const char *line, *next_line;
1125 const char *git_dir;
1126
1127 strbuf_addf(&buf, "%s/.git", path);
1128 git_dir = read_gitfile(buf.buf);
1129 if (!git_dir)
1130 git_dir = buf.buf;
1131 if (!is_directory(git_dir)) {
1132 strbuf_release(&buf);
1133 /* The submodule is not checked out, so it is not modified */
1134 return 0;
1135
1136 }
1137 strbuf_reset(&buf);
1138
1139 if (ignore_untracked)
1140 argv[2] = "-uno";
1141
1142 cp.argv = argv;
1143 prepare_submodule_repo_env(&cp.env_array);
1144 cp.git_cmd = 1;
1145 cp.no_stdin = 1;
1146 cp.out = -1;
1147 cp.dir = path;
1148 if (start_command(&cp))
1149 die("Could not run 'git status --porcelain' in submodule %s", path);
1150
1151 len = strbuf_read(&buf, cp.out, 1024);
1152 line = buf.buf;
1153 while (len > 2) {
1154 if ((line[0] == '?') && (line[1] == '?')) {
1155 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1156 if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
1157 break;
1158 } else {
1159 dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
1160 if (ignore_untracked ||
1161 (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED))
1162 break;
1163 }
1164 next_line = strchr(line, '\n');
1165 if (!next_line)
1166 break;
1167 next_line++;
1168 len -= (next_line - line);
1169 line = next_line;
1170 }
1171 close(cp.out);
1172
1173 if (finish_command(&cp))
1174 die("'git status --porcelain' failed in submodule %s", path);
1175
1176 strbuf_release(&buf);
1177 return dirty_submodule;
1178}
1179
1180int submodule_uses_gitfile(const char *path)
1181{
1182 struct child_process cp = CHILD_PROCESS_INIT;
1183 const char *argv[] = {
1184 "submodule",
1185 "foreach",
1186 "--quiet",
1187 "--recursive",
1188 "test -f .git",
1189 NULL,
1190 };
1191 struct strbuf buf = STRBUF_INIT;
1192 const char *git_dir;
1193
1194 strbuf_addf(&buf, "%s/.git", path);
1195 git_dir = read_gitfile(buf.buf);
1196 if (!git_dir) {
1197 strbuf_release(&buf);
1198 return 0;
1199 }
1200 strbuf_release(&buf);
1201
1202 /* Now test that all nested submodules use a gitfile too */
1203 cp.argv = argv;
1204 prepare_submodule_repo_env(&cp.env_array);
1205 cp.git_cmd = 1;
1206 cp.no_stdin = 1;
1207 cp.no_stderr = 1;
1208 cp.no_stdout = 1;
1209 cp.dir = path;
1210 if (run_command(&cp))
1211 return 0;
1212
1213 return 1;
1214}
1215
1216/*
1217 * Check if it is a bad idea to remove a submodule, i.e. if we'd lose data
1218 * when doing so.
1219 *
1220 * Return 1 if we'd lose data, return 0 if the removal is fine,
1221 * and negative values for errors.
1222 */
1223int bad_to_remove_submodule(const char *path, unsigned flags)
1224{
1225 ssize_t len;
1226 struct child_process cp = CHILD_PROCESS_INIT;
1227 struct strbuf buf = STRBUF_INIT;
1228 int ret = 0;
1229
1230 if (!file_exists(path) || is_empty_dir(path))
1231 return 0;
1232
1233 if (!submodule_uses_gitfile(path))
1234 return 1;
1235
1236 argv_array_pushl(&cp.args, "status", "--porcelain",
1237 "--ignore-submodules=none", NULL);
1238
1239 if (flags & SUBMODULE_REMOVAL_IGNORE_UNTRACKED)
1240 argv_array_push(&cp.args, "-uno");
1241 else
1242 argv_array_push(&cp.args, "-uall");
1243
1244 if (!(flags & SUBMODULE_REMOVAL_IGNORE_IGNORED_UNTRACKED))
1245 argv_array_push(&cp.args, "--ignored");
1246
1247 prepare_submodule_repo_env(&cp.env_array);
1248 cp.git_cmd = 1;
1249 cp.no_stdin = 1;
1250 cp.out = -1;
1251 cp.dir = path;
1252 if (start_command(&cp)) {
1253 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
1254 die(_("could not start 'git status in submodule '%s'"),
1255 path);
1256 ret = -1;
1257 goto out;
1258 }
1259
1260 len = strbuf_read(&buf, cp.out, 1024);
1261 if (len > 2)
1262 ret = 1;
1263 close(cp.out);
1264
1265 if (finish_command(&cp)) {
1266 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
1267 die(_("could not run 'git status in submodule '%s'"),
1268 path);
1269 ret = -1;
1270 }
1271out:
1272 strbuf_release(&buf);
1273 return ret;
1274}
1275
1276static const char *get_super_prefix_or_empty(void)
1277{
1278 const char *s = get_super_prefix();
1279 if (!s)
1280 s = "";
1281 return s;
1282}
1283
1284static int submodule_has_dirty_index(const struct submodule *sub)
1285{
1286 struct child_process cp = CHILD_PROCESS_INIT;
1287
1288 prepare_submodule_repo_env_no_git_dir(&cp.env_array);
1289
1290 cp.git_cmd = 1;
1291 argv_array_pushl(&cp.args, "diff-index", "--quiet",
1292 "--cached", "HEAD", NULL);
1293 cp.no_stdin = 1;
1294 cp.no_stdout = 1;
1295 cp.dir = sub->path;
1296 if (start_command(&cp))
1297 die("could not recurse into submodule '%s'", sub->path);
1298
1299 return finish_command(&cp);
1300}
1301
1302static void submodule_reset_index(const char *path)
1303{
1304 struct child_process cp = CHILD_PROCESS_INIT;
1305 prepare_submodule_repo_env_no_git_dir(&cp.env_array);
1306
1307 cp.git_cmd = 1;
1308 cp.no_stdin = 1;
1309 cp.dir = path;
1310
1311 argv_array_pushf(&cp.args, "--super-prefix=%s%s/",
1312 get_super_prefix_or_empty(), path);
1313 argv_array_pushl(&cp.args, "read-tree", "-u", "--reset", NULL);
1314
1315 argv_array_push(&cp.args, EMPTY_TREE_SHA1_HEX);
1316
1317 if (run_command(&cp))
1318 die("could not reset submodule index");
1319}
1320
1321/**
1322 * Moves a submodule at a given path from a given head to another new head.
1323 * For edge cases (a submodule coming into existence or removing a submodule)
1324 * pass NULL for old or new respectively.
1325 */
1326int submodule_move_head(const char *path,
1327 const char *old,
1328 const char *new,
1329 unsigned flags)
1330{
1331 int ret = 0;
1332 struct child_process cp = CHILD_PROCESS_INIT;
1333 const struct submodule *sub;
1334
1335 sub = submodule_from_path(null_sha1, path);
1336
1337 if (!sub)
1338 die("BUG: could not get submodule information for '%s'", path);
1339
1340 if (old && !(flags & SUBMODULE_MOVE_HEAD_FORCE)) {
1341 /* Check if the submodule has a dirty index. */
1342 if (submodule_has_dirty_index(sub))
1343 return error(_("submodule '%s' has dirty index"), path);
1344 }
1345
1346 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
1347 if (old) {
1348 if (!submodule_uses_gitfile(path))
1349 absorb_git_dir_into_superproject("", path,
1350 ABSORB_GITDIR_RECURSE_SUBMODULES);
1351 } else {
1352 struct strbuf sb = STRBUF_INIT;
1353 strbuf_addf(&sb, "%s/modules/%s",
1354 get_git_common_dir(), sub->name);
1355 connect_work_tree_and_git_dir(path, sb.buf);
1356 strbuf_release(&sb);
1357
1358 /* make sure the index is clean as well */
1359 submodule_reset_index(path);
1360 }
1361 }
1362
1363 prepare_submodule_repo_env_no_git_dir(&cp.env_array);
1364
1365 cp.git_cmd = 1;
1366 cp.no_stdin = 1;
1367 cp.dir = path;
1368
1369 argv_array_pushf(&cp.args, "--super-prefix=%s%s/",
1370 get_super_prefix_or_empty(), path);
1371 argv_array_pushl(&cp.args, "read-tree", NULL);
1372
1373 if (flags & SUBMODULE_MOVE_HEAD_DRY_RUN)
1374 argv_array_push(&cp.args, "-n");
1375 else
1376 argv_array_push(&cp.args, "-u");
1377
1378 if (flags & SUBMODULE_MOVE_HEAD_FORCE)
1379 argv_array_push(&cp.args, "--reset");
1380 else
1381 argv_array_push(&cp.args, "-m");
1382
1383 argv_array_push(&cp.args, old ? old : EMPTY_TREE_SHA1_HEX);
1384 argv_array_push(&cp.args, new ? new : EMPTY_TREE_SHA1_HEX);
1385
1386 if (run_command(&cp)) {
1387 ret = -1;
1388 goto out;
1389 }
1390
1391 if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
1392 if (new) {
1393 struct child_process cp1 = CHILD_PROCESS_INIT;
1394 /* also set the HEAD accordingly */
1395 cp1.git_cmd = 1;
1396 cp1.no_stdin = 1;
1397 cp1.dir = path;
1398
1399 argv_array_pushl(&cp1.args, "update-ref", "HEAD",
1400 new ? new : EMPTY_TREE_SHA1_HEX, NULL);
1401
1402 if (run_command(&cp1)) {
1403 ret = -1;
1404 goto out;
1405 }
1406 } else {
1407 struct strbuf sb = STRBUF_INIT;
1408
1409 strbuf_addf(&sb, "%s/.git", path);
1410 unlink_or_warn(sb.buf);
1411 strbuf_release(&sb);
1412
1413 if (is_empty_dir(path))
1414 rmdir_or_warn(path);
1415 }
1416 }
1417out:
1418 return ret;
1419}
1420
1421static int find_first_merges(struct object_array *result, const char *path,
1422 struct commit *a, struct commit *b)
1423{
1424 int i, j;
1425 struct object_array merges = OBJECT_ARRAY_INIT;
1426 struct commit *commit;
1427 int contains_another;
1428
1429 char merged_revision[42];
1430 const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
1431 "--all", merged_revision, NULL };
1432 struct rev_info revs;
1433 struct setup_revision_opt rev_opts;
1434
1435 memset(result, 0, sizeof(struct object_array));
1436 memset(&rev_opts, 0, sizeof(rev_opts));
1437
1438 /* get all revisions that merge commit a */
1439 snprintf(merged_revision, sizeof(merged_revision), "^%s",
1440 oid_to_hex(&a->object.oid));
1441 init_revisions(&revs, NULL);
1442 rev_opts.submodule = path;
1443 setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
1444
1445 /* save all revisions from the above list that contain b */
1446 if (prepare_revision_walk(&revs))
1447 die("revision walk setup failed");
1448 while ((commit = get_revision(&revs)) != NULL) {
1449 struct object *o = &(commit->object);
1450 if (in_merge_bases(b, commit))
1451 add_object_array(o, NULL, &merges);
1452 }
1453 reset_revision_walk();
1454
1455 /* Now we've got all merges that contain a and b. Prune all
1456 * merges that contain another found merge and save them in
1457 * result.
1458 */
1459 for (i = 0; i < merges.nr; i++) {
1460 struct commit *m1 = (struct commit *) merges.objects[i].item;
1461
1462 contains_another = 0;
1463 for (j = 0; j < merges.nr; j++) {
1464 struct commit *m2 = (struct commit *) merges.objects[j].item;
1465 if (i != j && in_merge_bases(m2, m1)) {
1466 contains_another = 1;
1467 break;
1468 }
1469 }
1470
1471 if (!contains_another)
1472 add_object_array(merges.objects[i].item, NULL, result);
1473 }
1474
1475 free(merges.objects);
1476 return result->nr;
1477}
1478
1479static void print_commit(struct commit *commit)
1480{
1481 struct strbuf sb = STRBUF_INIT;
1482 struct pretty_print_context ctx = {0};
1483 ctx.date_mode.type = DATE_NORMAL;
1484 format_commit_message(commit, " %h: %m %s", &sb, &ctx);
1485 fprintf(stderr, "%s\n", sb.buf);
1486 strbuf_release(&sb);
1487}
1488
1489#define MERGE_WARNING(path, msg) \
1490 warning("Failed to merge submodule %s (%s)", path, msg);
1491
1492int merge_submodule(unsigned char result[20], const char *path,
1493 const unsigned char base[20], const unsigned char a[20],
1494 const unsigned char b[20], int search)
1495{
1496 struct commit *commit_base, *commit_a, *commit_b;
1497 int parent_count;
1498 struct object_array merges;
1499
1500 int i;
1501
1502 /* store a in result in case we fail */
1503 hashcpy(result, a);
1504
1505 /* we can not handle deletion conflicts */
1506 if (is_null_sha1(base))
1507 return 0;
1508 if (is_null_sha1(a))
1509 return 0;
1510 if (is_null_sha1(b))
1511 return 0;
1512
1513 if (add_submodule_odb(path)) {
1514 MERGE_WARNING(path, "not checked out");
1515 return 0;
1516 }
1517
1518 if (!(commit_base = lookup_commit_reference(base)) ||
1519 !(commit_a = lookup_commit_reference(a)) ||
1520 !(commit_b = lookup_commit_reference(b))) {
1521 MERGE_WARNING(path, "commits not present");
1522 return 0;
1523 }
1524
1525 /* check whether both changes are forward */
1526 if (!in_merge_bases(commit_base, commit_a) ||
1527 !in_merge_bases(commit_base, commit_b)) {
1528 MERGE_WARNING(path, "commits don't follow merge-base");
1529 return 0;
1530 }
1531
1532 /* Case #1: a is contained in b or vice versa */
1533 if (in_merge_bases(commit_a, commit_b)) {
1534 hashcpy(result, b);
1535 return 1;
1536 }
1537 if (in_merge_bases(commit_b, commit_a)) {
1538 hashcpy(result, a);
1539 return 1;
1540 }
1541
1542 /*
1543 * Case #2: There are one or more merges that contain a and b in
1544 * the submodule. If there is only one, then present it as a
1545 * suggestion to the user, but leave it marked unmerged so the
1546 * user needs to confirm the resolution.
1547 */
1548
1549 /* Skip the search if makes no sense to the calling context. */
1550 if (!search)
1551 return 0;
1552
1553 /* find commit which merges them */
1554 parent_count = find_first_merges(&merges, path, commit_a, commit_b);
1555 switch (parent_count) {
1556 case 0:
1557 MERGE_WARNING(path, "merge following commits not found");
1558 break;
1559
1560 case 1:
1561 MERGE_WARNING(path, "not fast-forward");
1562 fprintf(stderr, "Found a possible merge resolution "
1563 "for the submodule:\n");
1564 print_commit((struct commit *) merges.objects[0].item);
1565 fprintf(stderr,
1566 "If this is correct simply add it to the index "
1567 "for example\n"
1568 "by using:\n\n"
1569 " git update-index --cacheinfo 160000 %s \"%s\"\n\n"
1570 "which will accept this suggestion.\n",
1571 oid_to_hex(&merges.objects[0].item->oid), path);
1572 break;
1573
1574 default:
1575 MERGE_WARNING(path, "multiple merges found");
1576 for (i = 0; i < merges.nr; i++)
1577 print_commit((struct commit *) merges.objects[i].item);
1578 }
1579
1580 free(merges.objects);
1581 return 0;
1582}
1583
1584int parallel_submodules(void)
1585{
1586 return parallel_jobs;
1587}
1588
1589/*
1590 * Embeds a single submodules git directory into the superprojects git dir,
1591 * non recursively.
1592 */
1593static void relocate_single_git_dir_into_superproject(const char *prefix,
1594 const char *path)
1595{
1596 char *old_git_dir = NULL, *real_old_git_dir = NULL, *real_new_git_dir = NULL;
1597 const char *new_git_dir;
1598 const struct submodule *sub;
1599
1600 if (submodule_uses_worktrees(path))
1601 die(_("relocate_gitdir for submodule '%s' with "
1602 "more than one worktree not supported"), path);
1603
1604 old_git_dir = xstrfmt("%s/.git", path);
1605 if (read_gitfile(old_git_dir))
1606 /* If it is an actual gitfile, it doesn't need migration. */
1607 return;
1608
1609 real_old_git_dir = real_pathdup(old_git_dir, 1);
1610
1611 sub = submodule_from_path(null_sha1, path);
1612 if (!sub)
1613 die(_("could not lookup name for submodule '%s'"), path);
1614
1615 new_git_dir = git_path("modules/%s", sub->name);
1616 if (safe_create_leading_directories_const(new_git_dir) < 0)
1617 die(_("could not create directory '%s'"), new_git_dir);
1618 real_new_git_dir = real_pathdup(new_git_dir, 1);
1619
1620 fprintf(stderr, _("Migrating git directory of '%s%s' from\n'%s' to\n'%s'\n"),
1621 get_super_prefix_or_empty(), path,
1622 real_old_git_dir, real_new_git_dir);
1623
1624 relocate_gitdir(path, real_old_git_dir, real_new_git_dir);
1625
1626 free(old_git_dir);
1627 free(real_old_git_dir);
1628 free(real_new_git_dir);
1629}
1630
1631/*
1632 * Migrate the git directory of the submodule given by path from
1633 * having its git directory within the working tree to the git dir nested
1634 * in its superprojects git dir under modules/.
1635 */
1636void absorb_git_dir_into_superproject(const char *prefix,
1637 const char *path,
1638 unsigned flags)
1639{
1640 int err_code;
1641 const char *sub_git_dir;
1642 struct strbuf gitdir = STRBUF_INIT;
1643 strbuf_addf(&gitdir, "%s/.git", path);
1644 sub_git_dir = resolve_gitdir_gently(gitdir.buf, &err_code);
1645
1646 /* Not populated? */
1647 if (!sub_git_dir) {
1648 const struct submodule *sub;
1649
1650 if (err_code == READ_GITFILE_ERR_STAT_FAILED) {
1651 /* unpopulated as expected */
1652 strbuf_release(&gitdir);
1653 return;
1654 }
1655
1656 if (err_code != READ_GITFILE_ERR_NOT_A_REPO)
1657 /* We don't know what broke here. */
1658 read_gitfile_error_die(err_code, path, NULL);
1659
1660 /*
1661 * Maybe populated, but no git directory was found?
1662 * This can happen if the superproject is a submodule
1663 * itself and was just absorbed. The absorption of the
1664 * superproject did not rewrite the git file links yet,
1665 * fix it now.
1666 */
1667 sub = submodule_from_path(null_sha1, path);
1668 if (!sub)
1669 die(_("could not lookup name for submodule '%s'"), path);
1670 connect_work_tree_and_git_dir(path,
1671 git_path("modules/%s", sub->name));
1672 } else {
1673 /* Is it already absorbed into the superprojects git dir? */
1674 char *real_sub_git_dir = real_pathdup(sub_git_dir, 1);
1675 char *real_common_git_dir = real_pathdup(get_git_common_dir(), 1);
1676
1677 if (!starts_with(real_sub_git_dir, real_common_git_dir))
1678 relocate_single_git_dir_into_superproject(prefix, path);
1679
1680 free(real_sub_git_dir);
1681 free(real_common_git_dir);
1682 }
1683 strbuf_release(&gitdir);
1684
1685 if (flags & ABSORB_GITDIR_RECURSE_SUBMODULES) {
1686 struct child_process cp = CHILD_PROCESS_INIT;
1687 struct strbuf sb = STRBUF_INIT;
1688
1689 if (flags & ~ABSORB_GITDIR_RECURSE_SUBMODULES)
1690 die("BUG: we don't know how to pass the flags down?");
1691
1692 strbuf_addstr(&sb, get_super_prefix_or_empty());
1693 strbuf_addstr(&sb, path);
1694 strbuf_addch(&sb, '/');
1695
1696 cp.dir = path;
1697 cp.git_cmd = 1;
1698 cp.no_stdin = 1;
1699 argv_array_pushl(&cp.args, "--super-prefix", sb.buf,
1700 "submodule--helper",
1701 "absorb-git-dirs", NULL);
1702 prepare_submodule_repo_env(&cp.env_array);
1703 if (run_command(&cp))
1704 die(_("could not recurse into submodule '%s'"), path);
1705
1706 strbuf_release(&sb);
1707 }
1708}
1709
1710const char *get_superproject_working_tree(void)
1711{
1712 struct child_process cp = CHILD_PROCESS_INIT;
1713 struct strbuf sb = STRBUF_INIT;
1714 const char *one_up = real_path_if_valid("../");
1715 const char *cwd = xgetcwd();
1716 const char *ret = NULL;
1717 const char *subpath;
1718 int code;
1719 ssize_t len;
1720
1721 if (!is_inside_work_tree())
1722 /*
1723 * FIXME:
1724 * We might have a superproject, but it is harder
1725 * to determine.
1726 */
1727 return NULL;
1728
1729 if (!one_up)
1730 return NULL;
1731
1732 subpath = relative_path(cwd, one_up, &sb);
1733
1734 prepare_submodule_repo_env(&cp.env_array);
1735 argv_array_pop(&cp.env_array);
1736
1737 argv_array_pushl(&cp.args, "--literal-pathspecs", "-C", "..",
1738 "ls-files", "-z", "--stage", "--full-name", "--",
1739 subpath, NULL);
1740 strbuf_reset(&sb);
1741
1742 cp.no_stdin = 1;
1743 cp.no_stderr = 1;
1744 cp.out = -1;
1745 cp.git_cmd = 1;
1746
1747 if (start_command(&cp))
1748 die(_("could not start ls-files in .."));
1749
1750 len = strbuf_read(&sb, cp.out, PATH_MAX);
1751 close(cp.out);
1752
1753 if (starts_with(sb.buf, "160000")) {
1754 int super_sub_len;
1755 int cwd_len = strlen(cwd);
1756 char *super_sub, *super_wt;
1757
1758 /*
1759 * There is a superproject having this repo as a submodule.
1760 * The format is <mode> SP <hash> SP <stage> TAB <full name> \0,
1761 * We're only interested in the name after the tab.
1762 */
1763 super_sub = strchr(sb.buf, '\t') + 1;
1764 super_sub_len = sb.buf + sb.len - super_sub - 1;
1765
1766 if (super_sub_len > cwd_len ||
1767 strcmp(&cwd[cwd_len - super_sub_len], super_sub))
1768 die (_("BUG: returned path string doesn't match cwd?"));
1769
1770 super_wt = xstrdup(cwd);
1771 super_wt[cwd_len - super_sub_len] = '\0';
1772
1773 ret = real_path(super_wt);
1774 free(super_wt);
1775 }
1776 strbuf_release(&sb);
1777
1778 code = finish_command(&cp);
1779
1780 if (code == 128)
1781 /* '../' is not a git repository */
1782 return NULL;
1783 if (code == 0 && len == 0)
1784 /* There is an unrelated git repository at '../' */
1785 return NULL;
1786 if (code)
1787 die(_("ls-tree returned unexpected return code %d"), code);
1788
1789 return ret;
1790}