cache.h: move hash/oid functions to hash.h
[git] / submodule.c
1
2 #include "cache.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "submodule-config.h"
6 #include "submodule.h"
7 #include "dir.h"
8 #include "diff.h"
9 #include "commit.h"
10 #include "revision.h"
11 #include "run-command.h"
12 #include "diffcore.h"
13 #include "refs.h"
14 #include "string-list.h"
15 #include "oid-array.h"
16 #include "strvec.h"
17 #include "blob.h"
18 #include "thread-utils.h"
19 #include "quote.h"
20 #include "remote.h"
21 #include "worktree.h"
22 #include "parse-options.h"
23 #include "object-store.h"
24 #include "commit-reach.h"
25
26 static int config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
27 static int initialized_fetch_ref_tips;
28 static struct oid_array ref_tips_before_fetch;
29 static struct oid_array ref_tips_after_fetch;
30
31 /*
32  * Check if the .gitmodules file is unmerged. Parsing of the .gitmodules file
33  * will be disabled because we can't guess what might be configured in
34  * .gitmodules unless the user resolves the conflict.
35  */
36 int is_gitmodules_unmerged(const struct index_state *istate)
37 {
38         int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
39         if (pos < 0) { /* .gitmodules not found or isn't merged */
40                 pos = -1 - pos;
41                 if (istate->cache_nr > pos) {  /* there is a .gitmodules */
42                         const struct cache_entry *ce = istate->cache[pos];
43                         if (ce_namelen(ce) == strlen(GITMODULES_FILE) &&
44                             !strcmp(ce->name, GITMODULES_FILE))
45                                 return 1;
46                 }
47         }
48
49         return 0;
50 }
51
52 /*
53  * Check if the .gitmodules file is safe to write.
54  *
55  * Writing to the .gitmodules file requires that the file exists in the
56  * working tree or, if it doesn't, that a brand new .gitmodules file is going
57  * to be created (i.e. it's neither in the index nor in the current branch).
58  *
59  * It is not safe to write to .gitmodules if it's not in the working tree but
60  * it is in the index or in the current branch, because writing new values
61  * (and staging them) would blindly overwrite ALL the old content.
62  */
63 int is_writing_gitmodules_ok(void)
64 {
65         struct object_id oid;
66         return file_exists(GITMODULES_FILE) ||
67                 (get_oid(GITMODULES_INDEX, &oid) < 0 && get_oid(GITMODULES_HEAD, &oid) < 0);
68 }
69
70 /*
71  * Check if the .gitmodules file has unstaged modifications.  This must be
72  * checked before allowing modifications to the .gitmodules file with the
73  * intention to stage them later, because when continuing we would stage the
74  * modifications the user didn't stage herself too. That might change in a
75  * future version when we learn to stage the changes we do ourselves without
76  * staging any previous modifications.
77  */
78 int is_staging_gitmodules_ok(struct index_state *istate)
79 {
80         int pos = index_name_pos(istate, GITMODULES_FILE, strlen(GITMODULES_FILE));
81
82         if ((pos >= 0) && (pos < istate->cache_nr)) {
83                 struct stat st;
84                 if (lstat(GITMODULES_FILE, &st) == 0 &&
85                     ie_modified(istate, istate->cache[pos], &st, 0) & DATA_CHANGED)
86                         return 0;
87         }
88
89         return 1;
90 }
91
92 static int for_each_remote_ref_submodule(const char *submodule,
93                                          each_ref_fn fn, void *cb_data)
94 {
95         return refs_for_each_remote_ref(get_submodule_ref_store(submodule),
96                                         fn, cb_data);
97 }
98
99 /*
100  * Try to update the "path" entry in the "submodule.<name>" section of the
101  * .gitmodules file. Return 0 only if a .gitmodules file was found, a section
102  * with the correct path=<oldpath> setting was found and we could update it.
103  */
104 int update_path_in_gitmodules(const char *oldpath, const char *newpath)
105 {
106         struct strbuf entry = STRBUF_INIT;
107         const struct submodule *submodule;
108         int ret;
109
110         if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
111                 return -1;
112
113         if (is_gitmodules_unmerged(the_repository->index))
114                 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
115
116         submodule = submodule_from_path(the_repository, &null_oid, oldpath);
117         if (!submodule || !submodule->name) {
118                 warning(_("Could not find section in .gitmodules where path=%s"), oldpath);
119                 return -1;
120         }
121         strbuf_addstr(&entry, "submodule.");
122         strbuf_addstr(&entry, submodule->name);
123         strbuf_addstr(&entry, ".path");
124         ret = config_set_in_gitmodules_file_gently(entry.buf, newpath);
125         strbuf_release(&entry);
126         return ret;
127 }
128
129 /*
130  * Try to remove the "submodule.<name>" section from .gitmodules where the given
131  * path is configured. Return 0 only if a .gitmodules file was found, a section
132  * with the correct path=<path> setting was found and we could remove it.
133  */
134 int remove_path_from_gitmodules(const char *path)
135 {
136         struct strbuf sect = STRBUF_INIT;
137         const struct submodule *submodule;
138
139         if (!file_exists(GITMODULES_FILE)) /* Do nothing without .gitmodules */
140                 return -1;
141
142         if (is_gitmodules_unmerged(the_repository->index))
143                 die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
144
145         submodule = submodule_from_path(the_repository, &null_oid, path);
146         if (!submodule || !submodule->name) {
147                 warning(_("Could not find section in .gitmodules where path=%s"), path);
148                 return -1;
149         }
150         strbuf_addstr(&sect, "submodule.");
151         strbuf_addstr(&sect, submodule->name);
152         if (git_config_rename_section_in_file(GITMODULES_FILE, sect.buf, NULL) < 0) {
153                 /* Maybe the user already did that, don't error out here */
154                 warning(_("Could not remove .gitmodules entry for %s"), path);
155                 strbuf_release(&sect);
156                 return -1;
157         }
158         strbuf_release(&sect);
159         return 0;
160 }
161
162 void stage_updated_gitmodules(struct index_state *istate)
163 {
164         if (add_file_to_index(istate, GITMODULES_FILE, 0))
165                 die(_("staging updated .gitmodules failed"));
166 }
167
168 /* TODO: remove this function, use repo_submodule_init instead. */
169 int add_submodule_odb(const char *path)
170 {
171         struct strbuf objects_directory = STRBUF_INIT;
172         int ret = 0;
173
174         ret = strbuf_git_path_submodule(&objects_directory, path, "objects/");
175         if (ret)
176                 goto done;
177         if (!is_directory(objects_directory.buf)) {
178                 ret = -1;
179                 goto done;
180         }
181         add_to_alternates_memory(objects_directory.buf);
182 done:
183         strbuf_release(&objects_directory);
184         return ret;
185 }
186
187 void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
188                                              const char *path)
189 {
190         const struct submodule *submodule = submodule_from_path(the_repository,
191                                                                 &null_oid, path);
192         if (submodule) {
193                 const char *ignore;
194                 char *key;
195
196                 key = xstrfmt("submodule.%s.ignore", submodule->name);
197                 if (repo_config_get_string_tmp(the_repository, key, &ignore))
198                         ignore = submodule->ignore;
199                 free(key);
200
201                 if (ignore)
202                         handle_ignore_submodules_arg(diffopt, ignore);
203                 else if (is_gitmodules_unmerged(the_repository->index))
204                         diffopt->flags.ignore_submodules = 1;
205         }
206 }
207
208 /* Cheap function that only determines if we're interested in submodules at all */
209 int git_default_submodule_config(const char *var, const char *value, void *cb)
210 {
211         if (!strcmp(var, "submodule.recurse")) {
212                 int v = git_config_bool(var, value) ?
213                         RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
214                 config_update_recurse_submodules = v;
215         }
216         return 0;
217 }
218
219 int option_parse_recurse_submodules_worktree_updater(const struct option *opt,
220                                                      const char *arg, int unset)
221 {
222         if (unset) {
223                 config_update_recurse_submodules = RECURSE_SUBMODULES_OFF;
224                 return 0;
225         }
226         if (arg)
227                 config_update_recurse_submodules =
228                         parse_update_recurse_submodules_arg(opt->long_name,
229                                                             arg);
230         else
231                 config_update_recurse_submodules = RECURSE_SUBMODULES_ON;
232
233         return 0;
234 }
235
236 /*
237  * Determine if a submodule has been initialized at a given 'path'
238  */
239 int is_submodule_active(struct repository *repo, const char *path)
240 {
241         int ret = 0;
242         char *key = NULL;
243         char *value = NULL;
244         const struct string_list *sl;
245         const struct submodule *module;
246
247         module = submodule_from_path(repo, &null_oid, path);
248
249         /* early return if there isn't a path->module mapping */
250         if (!module)
251                 return 0;
252
253         /* submodule.<name>.active is set */
254         key = xstrfmt("submodule.%s.active", module->name);
255         if (!repo_config_get_bool(repo, key, &ret)) {
256                 free(key);
257                 return ret;
258         }
259         free(key);
260
261         /* submodule.active is set */
262         sl = repo_config_get_value_multi(repo, "submodule.active");
263         if (sl) {
264                 struct pathspec ps;
265                 struct strvec args = STRVEC_INIT;
266                 const struct string_list_item *item;
267
268                 for_each_string_list_item(item, sl) {
269                         strvec_push(&args, item->string);
270                 }
271
272                 parse_pathspec(&ps, 0, 0, NULL, args.v);
273                 ret = match_pathspec(repo->index, &ps, path, strlen(path), 0, NULL, 1);
274
275                 strvec_clear(&args);
276                 clear_pathspec(&ps);
277                 return ret;
278         }
279
280         /* fallback to checking if the URL is set */
281         key = xstrfmt("submodule.%s.url", module->name);
282         ret = !repo_config_get_string(repo, key, &value);
283
284         free(value);
285         free(key);
286         return ret;
287 }
288
289 int is_submodule_populated_gently(const char *path, int *return_error_code)
290 {
291         int ret = 0;
292         char *gitdir = xstrfmt("%s/.git", path);
293
294         if (resolve_gitdir_gently(gitdir, return_error_code))
295                 ret = 1;
296
297         free(gitdir);
298         return ret;
299 }
300
301 /*
302  * Dies if the provided 'prefix' corresponds to an unpopulated submodule
303  */
304 void die_in_unpopulated_submodule(const struct index_state *istate,
305                                   const char *prefix)
306 {
307         int i, prefixlen;
308
309         if (!prefix)
310                 return;
311
312         prefixlen = strlen(prefix);
313
314         for (i = 0; i < istate->cache_nr; i++) {
315                 struct cache_entry *ce = istate->cache[i];
316                 int ce_len = ce_namelen(ce);
317
318                 if (!S_ISGITLINK(ce->ce_mode))
319                         continue;
320                 if (prefixlen <= ce_len)
321                         continue;
322                 if (strncmp(ce->name, prefix, ce_len))
323                         continue;
324                 if (prefix[ce_len] != '/')
325                         continue;
326
327                 die(_("in unpopulated submodule '%s'"), ce->name);
328         }
329 }
330
331 /*
332  * Dies if any paths in the provided pathspec descends into a submodule
333  */
334 void die_path_inside_submodule(const struct index_state *istate,
335                                const struct pathspec *ps)
336 {
337         int i, j;
338
339         for (i = 0; i < istate->cache_nr; i++) {
340                 struct cache_entry *ce = istate->cache[i];
341                 int ce_len = ce_namelen(ce);
342
343                 if (!S_ISGITLINK(ce->ce_mode))
344                         continue;
345
346                 for (j = 0; j < ps->nr ; j++) {
347                         const struct pathspec_item *item = &ps->items[j];
348
349                         if (item->len <= ce_len)
350                                 continue;
351                         if (item->match[ce_len] != '/')
352                                 continue;
353                         if (strncmp(ce->name, item->match, ce_len))
354                                 continue;
355                         if (item->len == ce_len + 1)
356                                 continue;
357
358                         die(_("Pathspec '%s' is in submodule '%.*s'"),
359                             item->original, ce_len, ce->name);
360                 }
361         }
362 }
363
364 enum submodule_update_type parse_submodule_update_type(const char *value)
365 {
366         if (!strcmp(value, "none"))
367                 return SM_UPDATE_NONE;
368         else if (!strcmp(value, "checkout"))
369                 return SM_UPDATE_CHECKOUT;
370         else if (!strcmp(value, "rebase"))
371                 return SM_UPDATE_REBASE;
372         else if (!strcmp(value, "merge"))
373                 return SM_UPDATE_MERGE;
374         else if (*value == '!')
375                 return SM_UPDATE_COMMAND;
376         else
377                 return SM_UPDATE_UNSPECIFIED;
378 }
379
380 int parse_submodule_update_strategy(const char *value,
381                 struct submodule_update_strategy *dst)
382 {
383         enum submodule_update_type type;
384
385         free((void*)dst->command);
386         dst->command = NULL;
387
388         type = parse_submodule_update_type(value);
389         if (type == SM_UPDATE_UNSPECIFIED)
390                 return -1;
391
392         dst->type = type;
393         if (type == SM_UPDATE_COMMAND)
394                 dst->command = xstrdup(value + 1);
395
396         return 0;
397 }
398
399 const char *submodule_strategy_to_string(const struct submodule_update_strategy *s)
400 {
401         struct strbuf sb = STRBUF_INIT;
402         switch (s->type) {
403         case SM_UPDATE_CHECKOUT:
404                 return "checkout";
405         case SM_UPDATE_MERGE:
406                 return "merge";
407         case SM_UPDATE_REBASE:
408                 return "rebase";
409         case SM_UPDATE_NONE:
410                 return "none";
411         case SM_UPDATE_UNSPECIFIED:
412                 return NULL;
413         case SM_UPDATE_COMMAND:
414                 strbuf_addf(&sb, "!%s", s->command);
415                 return strbuf_detach(&sb, NULL);
416         }
417         return NULL;
418 }
419
420 void handle_ignore_submodules_arg(struct diff_options *diffopt,
421                                   const char *arg)
422 {
423         diffopt->flags.ignore_submodules = 0;
424         diffopt->flags.ignore_untracked_in_submodules = 0;
425         diffopt->flags.ignore_dirty_submodules = 0;
426
427         if (!strcmp(arg, "all"))
428                 diffopt->flags.ignore_submodules = 1;
429         else if (!strcmp(arg, "untracked"))
430                 diffopt->flags.ignore_untracked_in_submodules = 1;
431         else if (!strcmp(arg, "dirty"))
432                 diffopt->flags.ignore_dirty_submodules = 1;
433         else if (strcmp(arg, "none"))
434                 die(_("bad --ignore-submodules argument: %s"), arg);
435         /*
436          * Please update _git_status() in git-completion.bash when you
437          * add new options
438          */
439 }
440
441 static int prepare_submodule_diff_summary(struct repository *r, struct rev_info *rev,
442                                           const char *path,
443                                           struct commit *left, struct commit *right,
444                                           struct commit_list *merge_bases)
445 {
446         struct commit_list *list;
447
448         repo_init_revisions(r, rev, NULL);
449         setup_revisions(0, NULL, rev, NULL);
450         rev->left_right = 1;
451         rev->first_parent_only = 1;
452         left->object.flags |= SYMMETRIC_LEFT;
453         add_pending_object(rev, &left->object, path);
454         add_pending_object(rev, &right->object, path);
455         for (list = merge_bases; list; list = list->next) {
456                 list->item->object.flags |= UNINTERESTING;
457                 add_pending_object(rev, &list->item->object,
458                         oid_to_hex(&list->item->object.oid));
459         }
460         return prepare_revision_walk(rev);
461 }
462
463 static void print_submodule_diff_summary(struct repository *r, struct rev_info *rev, struct diff_options *o)
464 {
465         static const char format[] = "  %m %s";
466         struct strbuf sb = STRBUF_INIT;
467         struct commit *commit;
468
469         while ((commit = get_revision(rev))) {
470                 struct pretty_print_context ctx = {0};
471                 ctx.date_mode = rev->date_mode;
472                 ctx.output_encoding = get_log_output_encoding();
473                 strbuf_setlen(&sb, 0);
474                 repo_format_commit_message(r, commit, format, &sb,
475                                       &ctx);
476                 strbuf_addch(&sb, '\n');
477                 if (commit->object.flags & SYMMETRIC_LEFT)
478                         diff_emit_submodule_del(o, sb.buf);
479                 else
480                         diff_emit_submodule_add(o, sb.buf);
481         }
482         strbuf_release(&sb);
483 }
484
485 static void prepare_submodule_repo_env_no_git_dir(struct strvec *out)
486 {
487         const char * const *var;
488
489         for (var = local_repo_env; *var; var++) {
490                 if (strcmp(*var, CONFIG_DATA_ENVIRONMENT))
491                         strvec_push(out, *var);
492         }
493 }
494
495 void prepare_submodule_repo_env(struct strvec *out)
496 {
497         prepare_submodule_repo_env_no_git_dir(out);
498         strvec_pushf(out, "%s=%s", GIT_DIR_ENVIRONMENT,
499                      DEFAULT_GIT_DIR_ENVIRONMENT);
500 }
501
502 static void prepare_submodule_repo_env_in_gitdir(struct strvec *out)
503 {
504         prepare_submodule_repo_env_no_git_dir(out);
505         strvec_pushf(out, "%s=.", GIT_DIR_ENVIRONMENT);
506 }
507
508 /*
509  * Initialize a repository struct for a submodule based on the provided 'path'.
510  *
511  * Unlike repo_submodule_init, this tolerates submodules not present
512  * in .gitmodules. This function exists only to preserve historical behavior,
513  *
514  * Returns the repository struct on success,
515  * NULL when the submodule is not present.
516  */
517 static struct repository *open_submodule(const char *path)
518 {
519         struct strbuf sb = STRBUF_INIT;
520         struct repository *out = xmalloc(sizeof(*out));
521
522         if (submodule_to_gitdir(&sb, path) || repo_init(out, sb.buf, NULL)) {
523                 strbuf_release(&sb);
524                 free(out);
525                 return NULL;
526         }
527
528         /* Mark it as a submodule */
529         out->submodule_prefix = xstrdup(path);
530
531         strbuf_release(&sb);
532         return out;
533 }
534
535 /*
536  * Helper function to display the submodule header line prior to the full
537  * summary output.
538  *
539  * If it can locate the submodule git directory it will create a repository
540  * handle for the submodule and lookup both the left and right commits and
541  * put them into the left and right pointers.
542  */
543 static void show_submodule_header(struct diff_options *o,
544                 const char *path,
545                 struct object_id *one, struct object_id *two,
546                 unsigned dirty_submodule,
547                 struct repository *sub,
548                 struct commit **left, struct commit **right,
549                 struct commit_list **merge_bases)
550 {
551         const char *message = NULL;
552         struct strbuf sb = STRBUF_INIT;
553         int fast_forward = 0, fast_backward = 0;
554
555         if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
556                 diff_emit_submodule_untracked(o, path);
557
558         if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
559                 diff_emit_submodule_modified(o, path);
560
561         if (is_null_oid(one))
562                 message = "(new submodule)";
563         else if (is_null_oid(two))
564                 message = "(submodule deleted)";
565
566         if (!sub) {
567                 if (!message)
568                         message = "(commits not present)";
569                 goto output_header;
570         }
571
572         /*
573          * Attempt to lookup the commit references, and determine if this is
574          * a fast forward or fast backwards update.
575          */
576         *left = lookup_commit_reference(sub, one);
577         *right = lookup_commit_reference(sub, two);
578
579         /*
580          * Warn about missing commits in the submodule project, but only if
581          * they aren't null.
582          */
583         if ((!is_null_oid(one) && !*left) ||
584              (!is_null_oid(two) && !*right))
585                 message = "(commits not present)";
586
587         *merge_bases = repo_get_merge_bases(sub, *left, *right);
588         if (*merge_bases) {
589                 if ((*merge_bases)->item == *left)
590                         fast_forward = 1;
591                 else if ((*merge_bases)->item == *right)
592                         fast_backward = 1;
593         }
594
595         if (oideq(one, two)) {
596                 strbuf_release(&sb);
597                 return;
598         }
599
600 output_header:
601         strbuf_addf(&sb, "Submodule %s ", path);
602         strbuf_add_unique_abbrev(&sb, one, DEFAULT_ABBREV);
603         strbuf_addstr(&sb, (fast_backward || fast_forward) ? ".." : "...");
604         strbuf_add_unique_abbrev(&sb, two, DEFAULT_ABBREV);
605         if (message)
606                 strbuf_addf(&sb, " %s\n", message);
607         else
608                 strbuf_addf(&sb, "%s:\n", fast_backward ? " (rewind)" : "");
609         diff_emit_submodule_header(o, sb.buf);
610
611         strbuf_release(&sb);
612 }
613
614 void show_submodule_diff_summary(struct diff_options *o, const char *path,
615                 struct object_id *one, struct object_id *two,
616                 unsigned dirty_submodule)
617 {
618         struct rev_info rev;
619         struct commit *left = NULL, *right = NULL;
620         struct commit_list *merge_bases = NULL;
621         struct repository *sub;
622
623         sub = open_submodule(path);
624         show_submodule_header(o, path, one, two, dirty_submodule,
625                               sub, &left, &right, &merge_bases);
626
627         /*
628          * If we don't have both a left and a right pointer, there is no
629          * reason to try and display a summary. The header line should contain
630          * all the information the user needs.
631          */
632         if (!left || !right || !sub)
633                 goto out;
634
635         /* Treat revision walker failure the same as missing commits */
636         if (prepare_submodule_diff_summary(sub, &rev, path, left, right, merge_bases)) {
637                 diff_emit_submodule_error(o, "(revision walker failed)\n");
638                 goto out;
639         }
640
641         print_submodule_diff_summary(sub, &rev, o);
642
643 out:
644         if (merge_bases)
645                 free_commit_list(merge_bases);
646         clear_commit_marks(left, ~0);
647         clear_commit_marks(right, ~0);
648         if (sub) {
649                 repo_clear(sub);
650                 free(sub);
651         }
652 }
653
654 void show_submodule_inline_diff(struct diff_options *o, const char *path,
655                 struct object_id *one, struct object_id *two,
656                 unsigned dirty_submodule)
657 {
658         const struct object_id *old_oid = the_hash_algo->empty_tree, *new_oid = the_hash_algo->empty_tree;
659         struct commit *left = NULL, *right = NULL;
660         struct commit_list *merge_bases = NULL;
661         struct child_process cp = CHILD_PROCESS_INIT;
662         struct strbuf sb = STRBUF_INIT;
663         struct repository *sub;
664
665         sub = open_submodule(path);
666         show_submodule_header(o, path, one, two, dirty_submodule,
667                               sub, &left, &right, &merge_bases);
668
669         /* We need a valid left and right commit to display a difference */
670         if (!(left || is_null_oid(one)) ||
671             !(right || is_null_oid(two)))
672                 goto done;
673
674         if (left)
675                 old_oid = one;
676         if (right)
677                 new_oid = two;
678
679         cp.git_cmd = 1;
680         cp.dir = path;
681         cp.out = -1;
682         cp.no_stdin = 1;
683
684         /* TODO: other options may need to be passed here. */
685         strvec_pushl(&cp.args, "diff", "--submodule=diff", NULL);
686         strvec_pushf(&cp.args, "--color=%s", want_color(o->use_color) ?
687                          "always" : "never");
688
689         if (o->flags.reverse_diff) {
690                 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
691                              o->b_prefix, path);
692                 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
693                              o->a_prefix, path);
694         } else {
695                 strvec_pushf(&cp.args, "--src-prefix=%s%s/",
696                              o->a_prefix, path);
697                 strvec_pushf(&cp.args, "--dst-prefix=%s%s/",
698                              o->b_prefix, path);
699         }
700         strvec_push(&cp.args, oid_to_hex(old_oid));
701         /*
702          * If the submodule has modified content, we will diff against the
703          * work tree, under the assumption that the user has asked for the
704          * diff format and wishes to actually see all differences even if they
705          * haven't yet been committed to the submodule yet.
706          */
707         if (!(dirty_submodule & DIRTY_SUBMODULE_MODIFIED))
708                 strvec_push(&cp.args, oid_to_hex(new_oid));
709
710         prepare_submodule_repo_env(&cp.env_array);
711         if (start_command(&cp))
712                 diff_emit_submodule_error(o, "(diff failed)\n");
713
714         while (strbuf_getwholeline_fd(&sb, cp.out, '\n') != EOF)
715                 diff_emit_submodule_pipethrough(o, sb.buf, sb.len);
716
717         if (finish_command(&cp))
718                 diff_emit_submodule_error(o, "(diff failed)\n");
719
720 done:
721         strbuf_release(&sb);
722         if (merge_bases)
723                 free_commit_list(merge_bases);
724         if (left)
725                 clear_commit_marks(left, ~0);
726         if (right)
727                 clear_commit_marks(right, ~0);
728         if (sub) {
729                 repo_clear(sub);
730                 free(sub);
731         }
732 }
733
734 int should_update_submodules(void)
735 {
736         return config_update_recurse_submodules == RECURSE_SUBMODULES_ON;
737 }
738
739 const struct submodule *submodule_from_ce(const struct cache_entry *ce)
740 {
741         if (!S_ISGITLINK(ce->ce_mode))
742                 return NULL;
743
744         if (!should_update_submodules())
745                 return NULL;
746
747         return submodule_from_path(the_repository, &null_oid, ce->name);
748 }
749
750 static struct oid_array *submodule_commits(struct string_list *submodules,
751                                            const char *name)
752 {
753         struct string_list_item *item;
754
755         item = string_list_insert(submodules, name);
756         if (item->util)
757                 return (struct oid_array *) item->util;
758
759         /* NEEDSWORK: should we have oid_array_init()? */
760         item->util = xcalloc(1, sizeof(struct oid_array));
761         return (struct oid_array *) item->util;
762 }
763
764 struct collect_changed_submodules_cb_data {
765         struct repository *repo;
766         struct string_list *changed;
767         const struct object_id *commit_oid;
768 };
769
770 /*
771  * this would normally be two functions: default_name_from_path() and
772  * path_from_default_name(). Since the default name is the same as
773  * the submodule path we can get away with just one function which only
774  * checks whether there is a submodule in the working directory at that
775  * location.
776  */
777 static const char *default_name_or_path(const char *path_or_name)
778 {
779         int error_code;
780
781         if (!is_submodule_populated_gently(path_or_name, &error_code))
782                 return NULL;
783
784         return path_or_name;
785 }
786
787 static void collect_changed_submodules_cb(struct diff_queue_struct *q,
788                                           struct diff_options *options,
789                                           void *data)
790 {
791         struct collect_changed_submodules_cb_data *me = data;
792         struct string_list *changed = me->changed;
793         const struct object_id *commit_oid = me->commit_oid;
794         int i;
795
796         for (i = 0; i < q->nr; i++) {
797                 struct diff_filepair *p = q->queue[i];
798                 struct oid_array *commits;
799                 const struct submodule *submodule;
800                 const char *name;
801
802                 if (!S_ISGITLINK(p->two->mode))
803                         continue;
804
805                 submodule = submodule_from_path(me->repo,
806                                                 commit_oid, p->two->path);
807                 if (submodule)
808                         name = submodule->name;
809                 else {
810                         name = default_name_or_path(p->two->path);
811                         /* make sure name does not collide with existing one */
812                         if (name)
813                                 submodule = submodule_from_name(me->repo,
814                                                                 commit_oid, name);
815                         if (submodule) {
816                                 warning(_("Submodule in commit %s at path: "
817                                         "'%s' collides with a submodule named "
818                                         "the same. Skipping it."),
819                                         oid_to_hex(commit_oid), p->two->path);
820                                 name = NULL;
821                         }
822                 }
823
824                 if (!name)
825                         continue;
826
827                 commits = submodule_commits(changed, name);
828                 oid_array_append(commits, &p->two->oid);
829         }
830 }
831
832 /*
833  * Collect the paths of submodules in 'changed' which have changed based on
834  * the revisions as specified in 'argv'.  Each entry in 'changed' will also
835  * have a corresponding 'struct oid_array' (in the 'util' field) which lists
836  * what the submodule pointers were updated to during the change.
837  */
838 static void collect_changed_submodules(struct repository *r,
839                                        struct string_list *changed,
840                                        struct strvec *argv)
841 {
842         struct rev_info rev;
843         const struct commit *commit;
844         int save_warning;
845         struct setup_revision_opt s_r_opt = {
846                 .assume_dashdash = 1,
847         };
848
849         save_warning = warn_on_object_refname_ambiguity;
850         warn_on_object_refname_ambiguity = 0;
851         repo_init_revisions(r, &rev, NULL);
852         setup_revisions(argv->nr, argv->v, &rev, &s_r_opt);
853         warn_on_object_refname_ambiguity = save_warning;
854         if (prepare_revision_walk(&rev))
855                 die(_("revision walk setup failed"));
856
857         while ((commit = get_revision(&rev))) {
858                 struct rev_info diff_rev;
859                 struct collect_changed_submodules_cb_data data;
860                 data.repo = r;
861                 data.changed = changed;
862                 data.commit_oid = &commit->object.oid;
863
864                 repo_init_revisions(r, &diff_rev, NULL);
865                 diff_rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
866                 diff_rev.diffopt.format_callback = collect_changed_submodules_cb;
867                 diff_rev.diffopt.format_callback_data = &data;
868                 diff_rev.dense_combined_merges = 1;
869                 diff_tree_combined_merge(commit, &diff_rev);
870         }
871
872         reset_revision_walk();
873 }
874
875 static void free_submodules_oids(struct string_list *submodules)
876 {
877         struct string_list_item *item;
878         for_each_string_list_item(item, submodules)
879                 oid_array_clear((struct oid_array *) item->util);
880         string_list_clear(submodules, 1);
881 }
882
883 static int has_remote(const char *refname, const struct object_id *oid,
884                       int flags, void *cb_data)
885 {
886         return 1;
887 }
888
889 static int append_oid_to_argv(const struct object_id *oid, void *data)
890 {
891         struct strvec *argv = data;
892         strvec_push(argv, oid_to_hex(oid));
893         return 0;
894 }
895
896 struct has_commit_data {
897         struct repository *repo;
898         int result;
899         const char *path;
900 };
901
902 static int check_has_commit(const struct object_id *oid, void *data)
903 {
904         struct has_commit_data *cb = data;
905
906         enum object_type type = oid_object_info(cb->repo, oid, NULL);
907
908         switch (type) {
909         case OBJ_COMMIT:
910                 return 0;
911         case OBJ_BAD:
912                 /*
913                  * Object is missing or invalid. If invalid, an error message
914                  * has already been printed.
915                  */
916                 cb->result = 0;
917                 return 0;
918         default:
919                 die(_("submodule entry '%s' (%s) is a %s, not a commit"),
920                     cb->path, oid_to_hex(oid), type_name(type));
921         }
922 }
923
924 static int submodule_has_commits(struct repository *r,
925                                  const char *path,
926                                  struct oid_array *commits)
927 {
928         struct has_commit_data has_commit = { r, 1, path };
929
930         /*
931          * Perform a cheap, but incorrect check for the existence of 'commits'.
932          * This is done by adding the submodule's object store to the in-core
933          * object store, and then querying for each commit's existence.  If we
934          * do not have the commit object anywhere, there is no chance we have
935          * it in the object store of the correct submodule and have it
936          * reachable from a ref, so we can fail early without spawning rev-list
937          * which is expensive.
938          */
939         if (add_submodule_odb(path))
940                 return 0;
941
942         oid_array_for_each_unique(commits, check_has_commit, &has_commit);
943
944         if (has_commit.result) {
945                 /*
946                  * Even if the submodule is checked out and the commit is
947                  * present, make sure it exists in the submodule's object store
948                  * and that it is reachable from a ref.
949                  */
950                 struct child_process cp = CHILD_PROCESS_INIT;
951                 struct strbuf out = STRBUF_INIT;
952
953                 strvec_pushl(&cp.args, "rev-list", "-n", "1", NULL);
954                 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
955                 strvec_pushl(&cp.args, "--not", "--all", NULL);
956
957                 prepare_submodule_repo_env(&cp.env_array);
958                 cp.git_cmd = 1;
959                 cp.no_stdin = 1;
960                 cp.dir = path;
961
962                 if (capture_command(&cp, &out, GIT_MAX_HEXSZ + 1) || out.len)
963                         has_commit.result = 0;
964
965                 strbuf_release(&out);
966         }
967
968         return has_commit.result;
969 }
970
971 static int submodule_needs_pushing(struct repository *r,
972                                    const char *path,
973                                    struct oid_array *commits)
974 {
975         if (!submodule_has_commits(r, path, commits))
976                 /*
977                  * NOTE: We do consider it safe to return "no" here. The
978                  * correct answer would be "We do not know" instead of
979                  * "No push needed", but it is quite hard to change
980                  * the submodule pointer without having the submodule
981                  * around. If a user did however change the submodules
982                  * without having the submodule around, this indicates
983                  * an expert who knows what they are doing or a
984                  * maintainer integrating work from other people. In
985                  * both cases it should be safe to skip this check.
986                  */
987                 return 0;
988
989         if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
990                 struct child_process cp = CHILD_PROCESS_INIT;
991                 struct strbuf buf = STRBUF_INIT;
992                 int needs_pushing = 0;
993
994                 strvec_push(&cp.args, "rev-list");
995                 oid_array_for_each_unique(commits, append_oid_to_argv, &cp.args);
996                 strvec_pushl(&cp.args, "--not", "--remotes", "-n", "1" , NULL);
997
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 rev-list <commits> --not --remotes -n 1' command in submodule %s"),
1005                                         path);
1006                 if (strbuf_read(&buf, cp.out, the_hash_algo->hexsz + 1))
1007                         needs_pushing = 1;
1008                 finish_command(&cp);
1009                 close(cp.out);
1010                 strbuf_release(&buf);
1011                 return needs_pushing;
1012         }
1013
1014         return 0;
1015 }
1016
1017 int find_unpushed_submodules(struct repository *r,
1018                              struct oid_array *commits,
1019                              const char *remotes_name,
1020                              struct string_list *needs_pushing)
1021 {
1022         struct string_list submodules = STRING_LIST_INIT_DUP;
1023         struct string_list_item *name;
1024         struct strvec argv = STRVEC_INIT;
1025
1026         /* argv.v[0] will be ignored by setup_revisions */
1027         strvec_push(&argv, "find_unpushed_submodules");
1028         oid_array_for_each_unique(commits, append_oid_to_argv, &argv);
1029         strvec_push(&argv, "--not");
1030         strvec_pushf(&argv, "--remotes=%s", remotes_name);
1031
1032         collect_changed_submodules(r, &submodules, &argv);
1033
1034         for_each_string_list_item(name, &submodules) {
1035                 struct oid_array *commits = name->util;
1036                 const struct submodule *submodule;
1037                 const char *path = NULL;
1038
1039                 submodule = submodule_from_name(r, &null_oid, name->string);
1040                 if (submodule)
1041                         path = submodule->path;
1042                 else
1043                         path = default_name_or_path(name->string);
1044
1045                 if (!path)
1046                         continue;
1047
1048                 if (submodule_needs_pushing(r, path, commits))
1049                         string_list_insert(needs_pushing, path);
1050         }
1051
1052         free_submodules_oids(&submodules);
1053         strvec_clear(&argv);
1054
1055         return needs_pushing->nr;
1056 }
1057
1058 static int push_submodule(const char *path,
1059                           const struct remote *remote,
1060                           const struct refspec *rs,
1061                           const struct string_list *push_options,
1062                           int dry_run)
1063 {
1064         if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
1065                 struct child_process cp = CHILD_PROCESS_INIT;
1066                 strvec_push(&cp.args, "push");
1067                 if (dry_run)
1068                         strvec_push(&cp.args, "--dry-run");
1069
1070                 if (push_options && push_options->nr) {
1071                         const struct string_list_item *item;
1072                         for_each_string_list_item(item, push_options)
1073                                 strvec_pushf(&cp.args, "--push-option=%s",
1074                                              item->string);
1075                 }
1076
1077                 if (remote->origin != REMOTE_UNCONFIGURED) {
1078                         int i;
1079                         strvec_push(&cp.args, remote->name);
1080                         for (i = 0; i < rs->raw_nr; i++)
1081                                 strvec_push(&cp.args, rs->raw[i]);
1082                 }
1083
1084                 prepare_submodule_repo_env(&cp.env_array);
1085                 cp.git_cmd = 1;
1086                 cp.no_stdin = 1;
1087                 cp.dir = path;
1088                 if (run_command(&cp))
1089                         return 0;
1090                 close(cp.out);
1091         }
1092
1093         return 1;
1094 }
1095
1096 /*
1097  * Perform a check in the submodule to see if the remote and refspec work.
1098  * Die if the submodule can't be pushed.
1099  */
1100 static void submodule_push_check(const char *path, const char *head,
1101                                  const struct remote *remote,
1102                                  const struct refspec *rs)
1103 {
1104         struct child_process cp = CHILD_PROCESS_INIT;
1105         int i;
1106
1107         strvec_push(&cp.args, "submodule--helper");
1108         strvec_push(&cp.args, "push-check");
1109         strvec_push(&cp.args, head);
1110         strvec_push(&cp.args, remote->name);
1111
1112         for (i = 0; i < rs->raw_nr; i++)
1113                 strvec_push(&cp.args, rs->raw[i]);
1114
1115         prepare_submodule_repo_env(&cp.env_array);
1116         cp.git_cmd = 1;
1117         cp.no_stdin = 1;
1118         cp.no_stdout = 1;
1119         cp.dir = path;
1120
1121         /*
1122          * Simply indicate if 'submodule--helper push-check' failed.
1123          * More detailed error information will be provided by the
1124          * child process.
1125          */
1126         if (run_command(&cp))
1127                 die(_("process for submodule '%s' failed"), path);
1128 }
1129
1130 int push_unpushed_submodules(struct repository *r,
1131                              struct oid_array *commits,
1132                              const struct remote *remote,
1133                              const struct refspec *rs,
1134                              const struct string_list *push_options,
1135                              int dry_run)
1136 {
1137         int i, ret = 1;
1138         struct string_list needs_pushing = STRING_LIST_INIT_DUP;
1139
1140         if (!find_unpushed_submodules(r, commits,
1141                                       remote->name, &needs_pushing))
1142                 return 1;
1143
1144         /*
1145          * Verify that the remote and refspec can be propagated to all
1146          * submodules.  This check can be skipped if the remote and refspec
1147          * won't be propagated due to the remote being unconfigured (e.g. a URL
1148          * instead of a remote name).
1149          */
1150         if (remote->origin != REMOTE_UNCONFIGURED) {
1151                 char *head;
1152                 struct object_id head_oid;
1153
1154                 head = resolve_refdup("HEAD", 0, &head_oid, NULL);
1155                 if (!head)
1156                         die(_("Failed to resolve HEAD as a valid ref."));
1157
1158                 for (i = 0; i < needs_pushing.nr; i++)
1159                         submodule_push_check(needs_pushing.items[i].string,
1160                                              head, remote, rs);
1161                 free(head);
1162         }
1163
1164         /* Actually push the submodules */
1165         for (i = 0; i < needs_pushing.nr; i++) {
1166                 const char *path = needs_pushing.items[i].string;
1167                 fprintf(stderr, _("Pushing submodule '%s'\n"), path);
1168                 if (!push_submodule(path, remote, rs,
1169                                     push_options, dry_run)) {
1170                         fprintf(stderr, _("Unable to push submodule '%s'\n"), path);
1171                         ret = 0;
1172                 }
1173         }
1174
1175         string_list_clear(&needs_pushing, 0);
1176
1177         return ret;
1178 }
1179
1180 static int append_oid_to_array(const char *ref, const struct object_id *oid,
1181                                int flags, void *data)
1182 {
1183         struct oid_array *array = data;
1184         oid_array_append(array, oid);
1185         return 0;
1186 }
1187
1188 void check_for_new_submodule_commits(struct object_id *oid)
1189 {
1190         if (!initialized_fetch_ref_tips) {
1191                 for_each_ref(append_oid_to_array, &ref_tips_before_fetch);
1192                 initialized_fetch_ref_tips = 1;
1193         }
1194
1195         oid_array_append(&ref_tips_after_fetch, oid);
1196 }
1197
1198 static void calculate_changed_submodule_paths(struct repository *r,
1199                 struct string_list *changed_submodule_names)
1200 {
1201         struct strvec argv = STRVEC_INIT;
1202         struct string_list_item *name;
1203
1204         /* No need to check if there are no submodules configured */
1205         if (!submodule_from_path(r, NULL, NULL))
1206                 return;
1207
1208         strvec_push(&argv, "--"); /* argv[0] program name */
1209         oid_array_for_each_unique(&ref_tips_after_fetch,
1210                                    append_oid_to_argv, &argv);
1211         strvec_push(&argv, "--not");
1212         oid_array_for_each_unique(&ref_tips_before_fetch,
1213                                    append_oid_to_argv, &argv);
1214
1215         /*
1216          * Collect all submodules (whether checked out or not) for which new
1217          * commits have been recorded upstream in "changed_submodule_names".
1218          */
1219         collect_changed_submodules(r, changed_submodule_names, &argv);
1220
1221         for_each_string_list_item(name, changed_submodule_names) {
1222                 struct oid_array *commits = name->util;
1223                 const struct submodule *submodule;
1224                 const char *path = NULL;
1225
1226                 submodule = submodule_from_name(r, &null_oid, name->string);
1227                 if (submodule)
1228                         path = submodule->path;
1229                 else
1230                         path = default_name_or_path(name->string);
1231
1232                 if (!path)
1233                         continue;
1234
1235                 if (submodule_has_commits(r, path, commits)) {
1236                         oid_array_clear(commits);
1237                         *name->string = '\0';
1238                 }
1239         }
1240
1241         string_list_remove_empty_items(changed_submodule_names, 1);
1242
1243         strvec_clear(&argv);
1244         oid_array_clear(&ref_tips_before_fetch);
1245         oid_array_clear(&ref_tips_after_fetch);
1246         initialized_fetch_ref_tips = 0;
1247 }
1248
1249 int submodule_touches_in_range(struct repository *r,
1250                                struct object_id *excl_oid,
1251                                struct object_id *incl_oid)
1252 {
1253         struct string_list subs = STRING_LIST_INIT_DUP;
1254         struct strvec args = STRVEC_INIT;
1255         int ret;
1256
1257         /* No need to check if there are no submodules configured */
1258         if (!submodule_from_path(r, NULL, NULL))
1259                 return 0;
1260
1261         strvec_push(&args, "--"); /* args[0] program name */
1262         strvec_push(&args, oid_to_hex(incl_oid));
1263         if (!is_null_oid(excl_oid)) {
1264                 strvec_push(&args, "--not");
1265                 strvec_push(&args, oid_to_hex(excl_oid));
1266         }
1267
1268         collect_changed_submodules(r, &subs, &args);
1269         ret = subs.nr;
1270
1271         strvec_clear(&args);
1272
1273         free_submodules_oids(&subs);
1274         return ret;
1275 }
1276
1277 struct submodule_parallel_fetch {
1278         int count;
1279         struct strvec args;
1280         struct repository *r;
1281         const char *prefix;
1282         int command_line_option;
1283         int default_option;
1284         int quiet;
1285         int result;
1286
1287         struct string_list changed_submodule_names;
1288
1289         /* Pending fetches by OIDs */
1290         struct fetch_task **oid_fetch_tasks;
1291         int oid_fetch_tasks_nr, oid_fetch_tasks_alloc;
1292
1293         struct strbuf submodules_with_errors;
1294 };
1295 #define SPF_INIT {0, STRVEC_INIT, NULL, NULL, 0, 0, 0, 0, \
1296                   STRING_LIST_INIT_DUP, \
1297                   NULL, 0, 0, STRBUF_INIT}
1298
1299 static int get_fetch_recurse_config(const struct submodule *submodule,
1300                                     struct submodule_parallel_fetch *spf)
1301 {
1302         if (spf->command_line_option != RECURSE_SUBMODULES_DEFAULT)
1303                 return spf->command_line_option;
1304
1305         if (submodule) {
1306                 char *key;
1307                 const char *value;
1308
1309                 int fetch_recurse = submodule->fetch_recurse;
1310                 key = xstrfmt("submodule.%s.fetchRecurseSubmodules", submodule->name);
1311                 if (!repo_config_get_string_tmp(spf->r, key, &value)) {
1312                         fetch_recurse = parse_fetch_recurse_submodules_arg(key, value);
1313                 }
1314                 free(key);
1315
1316                 if (fetch_recurse != RECURSE_SUBMODULES_NONE)
1317                         /* local config overrules everything except commandline */
1318                         return fetch_recurse;
1319         }
1320
1321         return spf->default_option;
1322 }
1323
1324 /*
1325  * Fetch in progress (if callback data) or
1326  * pending (if in oid_fetch_tasks in struct submodule_parallel_fetch)
1327  */
1328 struct fetch_task {
1329         struct repository *repo;
1330         const struct submodule *sub;
1331         unsigned free_sub : 1; /* Do we need to free the submodule? */
1332
1333         struct oid_array *commits; /* Ensure these commits are fetched */
1334 };
1335
1336 /**
1337  * When a submodule is not defined in .gitmodules, we cannot access it
1338  * via the regular submodule-config. Create a fake submodule, which we can
1339  * work on.
1340  */
1341 static const struct submodule *get_non_gitmodules_submodule(const char *path)
1342 {
1343         struct submodule *ret = NULL;
1344         const char *name = default_name_or_path(path);
1345
1346         if (!name)
1347                 return NULL;
1348
1349         ret = xmalloc(sizeof(*ret));
1350         memset(ret, 0, sizeof(*ret));
1351         ret->path = name;
1352         ret->name = name;
1353
1354         return (const struct submodule *) ret;
1355 }
1356
1357 static struct fetch_task *fetch_task_create(struct repository *r,
1358                                             const char *path)
1359 {
1360         struct fetch_task *task = xmalloc(sizeof(*task));
1361         memset(task, 0, sizeof(*task));
1362
1363         task->sub = submodule_from_path(r, &null_oid, path);
1364         if (!task->sub) {
1365                 /*
1366                  * No entry in .gitmodules? Technically not a submodule,
1367                  * but historically we supported repositories that happen to be
1368                  * in-place where a gitlink is. Keep supporting them.
1369                  */
1370                 task->sub = get_non_gitmodules_submodule(path);
1371                 if (!task->sub) {
1372                         free(task);
1373                         return NULL;
1374                 }
1375
1376                 task->free_sub = 1;
1377         }
1378
1379         return task;
1380 }
1381
1382 static void fetch_task_release(struct fetch_task *p)
1383 {
1384         if (p->free_sub)
1385                 free((void*)p->sub);
1386         p->free_sub = 0;
1387         p->sub = NULL;
1388
1389         if (p->repo)
1390                 repo_clear(p->repo);
1391         FREE_AND_NULL(p->repo);
1392 }
1393
1394 static struct repository *get_submodule_repo_for(struct repository *r,
1395                                                  const struct submodule *sub)
1396 {
1397         struct repository *ret = xmalloc(sizeof(*ret));
1398
1399         if (repo_submodule_init(ret, r, sub)) {
1400                 /*
1401                  * No entry in .gitmodules? Technically not a submodule,
1402                  * but historically we supported repositories that happen to be
1403                  * in-place where a gitlink is. Keep supporting them.
1404                  */
1405                 struct strbuf gitdir = STRBUF_INIT;
1406                 strbuf_repo_worktree_path(&gitdir, r, "%s/.git", sub->path);
1407                 if (repo_init(ret, gitdir.buf, NULL)) {
1408                         strbuf_release(&gitdir);
1409                         free(ret);
1410                         return NULL;
1411                 }
1412                 strbuf_release(&gitdir);
1413         }
1414
1415         return ret;
1416 }
1417
1418 static int get_next_submodule(struct child_process *cp,
1419                               struct strbuf *err, void *data, void **task_cb)
1420 {
1421         struct submodule_parallel_fetch *spf = data;
1422
1423         for (; spf->count < spf->r->index->cache_nr; spf->count++) {
1424                 const struct cache_entry *ce = spf->r->index->cache[spf->count];
1425                 const char *default_argv;
1426                 struct fetch_task *task;
1427
1428                 if (!S_ISGITLINK(ce->ce_mode))
1429                         continue;
1430
1431                 task = fetch_task_create(spf->r, ce->name);
1432                 if (!task)
1433                         continue;
1434
1435                 switch (get_fetch_recurse_config(task->sub, spf))
1436                 {
1437                 default:
1438                 case RECURSE_SUBMODULES_DEFAULT:
1439                 case RECURSE_SUBMODULES_ON_DEMAND:
1440                         if (!task->sub ||
1441                             !string_list_lookup(
1442                                         &spf->changed_submodule_names,
1443                                         task->sub->name))
1444                                 continue;
1445                         default_argv = "on-demand";
1446                         break;
1447                 case RECURSE_SUBMODULES_ON:
1448                         default_argv = "yes";
1449                         break;
1450                 case RECURSE_SUBMODULES_OFF:
1451                         continue;
1452                 }
1453
1454                 task->repo = get_submodule_repo_for(spf->r, task->sub);
1455                 if (task->repo) {
1456                         struct strbuf submodule_prefix = STRBUF_INIT;
1457                         child_process_init(cp);
1458                         cp->dir = task->repo->gitdir;
1459                         prepare_submodule_repo_env_in_gitdir(&cp->env_array);
1460                         cp->git_cmd = 1;
1461                         if (!spf->quiet)
1462                                 strbuf_addf(err, _("Fetching submodule %s%s\n"),
1463                                             spf->prefix, ce->name);
1464                         strvec_init(&cp->args);
1465                         strvec_pushv(&cp->args, spf->args.v);
1466                         strvec_push(&cp->args, default_argv);
1467                         strvec_push(&cp->args, "--submodule-prefix");
1468
1469                         strbuf_addf(&submodule_prefix, "%s%s/",
1470                                                        spf->prefix,
1471                                                        task->sub->path);
1472                         strvec_push(&cp->args, submodule_prefix.buf);
1473
1474                         spf->count++;
1475                         *task_cb = task;
1476
1477                         strbuf_release(&submodule_prefix);
1478                         return 1;
1479                 } else {
1480
1481                         fetch_task_release(task);
1482                         free(task);
1483
1484                         /*
1485                          * An empty directory is normal,
1486                          * the submodule is not initialized
1487                          */
1488                         if (S_ISGITLINK(ce->ce_mode) &&
1489                             !is_empty_dir(ce->name)) {
1490                                 spf->result = 1;
1491                                 strbuf_addf(err,
1492                                             _("Could not access submodule '%s'\n"),
1493                                             ce->name);
1494                         }
1495                 }
1496         }
1497
1498         if (spf->oid_fetch_tasks_nr) {
1499                 struct fetch_task *task =
1500                         spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr - 1];
1501                 struct strbuf submodule_prefix = STRBUF_INIT;
1502                 spf->oid_fetch_tasks_nr--;
1503
1504                 strbuf_addf(&submodule_prefix, "%s%s/",
1505                             spf->prefix, task->sub->path);
1506
1507                 child_process_init(cp);
1508                 prepare_submodule_repo_env_in_gitdir(&cp->env_array);
1509                 cp->git_cmd = 1;
1510                 cp->dir = task->repo->gitdir;
1511
1512                 strvec_init(&cp->args);
1513                 strvec_pushv(&cp->args, spf->args.v);
1514                 strvec_push(&cp->args, "on-demand");
1515                 strvec_push(&cp->args, "--submodule-prefix");
1516                 strvec_push(&cp->args, submodule_prefix.buf);
1517
1518                 /* NEEDSWORK: have get_default_remote from submodule--helper */
1519                 strvec_push(&cp->args, "origin");
1520                 oid_array_for_each_unique(task->commits,
1521                                           append_oid_to_argv, &cp->args);
1522
1523                 *task_cb = task;
1524                 strbuf_release(&submodule_prefix);
1525                 return 1;
1526         }
1527
1528         return 0;
1529 }
1530
1531 static int fetch_start_failure(struct strbuf *err,
1532                                void *cb, void *task_cb)
1533 {
1534         struct submodule_parallel_fetch *spf = cb;
1535         struct fetch_task *task = task_cb;
1536
1537         spf->result = 1;
1538
1539         fetch_task_release(task);
1540         return 0;
1541 }
1542
1543 static int commit_missing_in_sub(const struct object_id *oid, void *data)
1544 {
1545         struct repository *subrepo = data;
1546
1547         enum object_type type = oid_object_info(subrepo, oid, NULL);
1548
1549         return type != OBJ_COMMIT;
1550 }
1551
1552 static int fetch_finish(int retvalue, struct strbuf *err,
1553                         void *cb, void *task_cb)
1554 {
1555         struct submodule_parallel_fetch *spf = cb;
1556         struct fetch_task *task = task_cb;
1557
1558         struct string_list_item *it;
1559         struct oid_array *commits;
1560
1561         if (!task || !task->sub)
1562                 BUG("callback cookie bogus");
1563
1564         if (retvalue) {
1565                 /*
1566                  * NEEDSWORK: This indicates that the overall fetch
1567                  * failed, even though there may be a subsequent fetch
1568                  * by commit hash that might work. It may be a good
1569                  * idea to not indicate failure in this case, and only
1570                  * indicate failure if the subsequent fetch fails.
1571                  */
1572                 spf->result = 1;
1573
1574                 strbuf_addf(&spf->submodules_with_errors, "\t%s\n",
1575                             task->sub->name);
1576         }
1577
1578         /* Is this the second time we process this submodule? */
1579         if (task->commits)
1580                 goto out;
1581
1582         it = string_list_lookup(&spf->changed_submodule_names, task->sub->name);
1583         if (!it)
1584                 /* Could be an unchanged submodule, not contained in the list */
1585                 goto out;
1586
1587         commits = it->util;
1588         oid_array_filter(commits,
1589                          commit_missing_in_sub,
1590                          task->repo);
1591
1592         /* Are there commits we want, but do not exist? */
1593         if (commits->nr) {
1594                 task->commits = commits;
1595                 ALLOC_GROW(spf->oid_fetch_tasks,
1596                            spf->oid_fetch_tasks_nr + 1,
1597                            spf->oid_fetch_tasks_alloc);
1598                 spf->oid_fetch_tasks[spf->oid_fetch_tasks_nr] = task;
1599                 spf->oid_fetch_tasks_nr++;
1600                 return 0;
1601         }
1602
1603 out:
1604         fetch_task_release(task);
1605
1606         return 0;
1607 }
1608
1609 int fetch_populated_submodules(struct repository *r,
1610                                const struct strvec *options,
1611                                const char *prefix, int command_line_option,
1612                                int default_option,
1613                                int quiet, int max_parallel_jobs)
1614 {
1615         int i;
1616         struct submodule_parallel_fetch spf = SPF_INIT;
1617
1618         spf.r = r;
1619         spf.command_line_option = command_line_option;
1620         spf.default_option = default_option;
1621         spf.quiet = quiet;
1622         spf.prefix = prefix;
1623
1624         if (!r->worktree)
1625                 goto out;
1626
1627         if (repo_read_index(r) < 0)
1628                 die(_("index file corrupt"));
1629
1630         strvec_push(&spf.args, "fetch");
1631         for (i = 0; i < options->nr; i++)
1632                 strvec_push(&spf.args, options->v[i]);
1633         strvec_push(&spf.args, "--recurse-submodules-default");
1634         /* default value, "--submodule-prefix" and its value are added later */
1635
1636         calculate_changed_submodule_paths(r, &spf.changed_submodule_names);
1637         string_list_sort(&spf.changed_submodule_names);
1638         run_processes_parallel_tr2(max_parallel_jobs,
1639                                    get_next_submodule,
1640                                    fetch_start_failure,
1641                                    fetch_finish,
1642                                    &spf,
1643                                    "submodule", "parallel/fetch");
1644
1645         if (spf.submodules_with_errors.len > 0)
1646                 fprintf(stderr, _("Errors during submodule fetch:\n%s"),
1647                         spf.submodules_with_errors.buf);
1648
1649
1650         strvec_clear(&spf.args);
1651 out:
1652         free_submodules_oids(&spf.changed_submodule_names);
1653         return spf.result;
1654 }
1655
1656 unsigned is_submodule_modified(const char *path, int ignore_untracked)
1657 {
1658         struct child_process cp = CHILD_PROCESS_INIT;
1659         struct strbuf buf = STRBUF_INIT;
1660         FILE *fp;
1661         unsigned dirty_submodule = 0;
1662         const char *git_dir;
1663         int ignore_cp_exit_code = 0;
1664
1665         strbuf_addf(&buf, "%s/.git", path);
1666         git_dir = read_gitfile(buf.buf);
1667         if (!git_dir)
1668                 git_dir = buf.buf;
1669         if (!is_git_directory(git_dir)) {
1670                 if (is_directory(git_dir))
1671                         die(_("'%s' not recognized as a git repository"), git_dir);
1672                 strbuf_release(&buf);
1673                 /* The submodule is not checked out, so it is not modified */
1674                 return 0;
1675         }
1676         strbuf_reset(&buf);
1677
1678         strvec_pushl(&cp.args, "status", "--porcelain=2", NULL);
1679         if (ignore_untracked)
1680                 strvec_push(&cp.args, "-uno");
1681
1682         prepare_submodule_repo_env(&cp.env_array);
1683         cp.git_cmd = 1;
1684         cp.no_stdin = 1;
1685         cp.out = -1;
1686         cp.dir = path;
1687         if (start_command(&cp))
1688                 die(_("Could not run 'git status --porcelain=2' in submodule %s"), path);
1689
1690         fp = xfdopen(cp.out, "r");
1691         while (strbuf_getwholeline(&buf, fp, '\n') != EOF) {
1692                 /* regular untracked files */
1693                 if (buf.buf[0] == '?')
1694                         dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1695
1696                 if (buf.buf[0] == 'u' ||
1697                     buf.buf[0] == '1' ||
1698                     buf.buf[0] == '2') {
1699                         /* T = line type, XY = status, SSSS = submodule state */
1700                         if (buf.len < strlen("T XY SSSS"))
1701                                 BUG("invalid status --porcelain=2 line %s",
1702                                     buf.buf);
1703
1704                         if (buf.buf[5] == 'S' && buf.buf[8] == 'U')
1705                                 /* nested untracked file */
1706                                 dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
1707
1708                         if (buf.buf[0] == 'u' ||
1709                             buf.buf[0] == '2' ||
1710                             memcmp(buf.buf + 5, "S..U", 4))
1711                                 /* other change */
1712                                 dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
1713                 }
1714
1715                 if ((dirty_submodule & DIRTY_SUBMODULE_MODIFIED) &&
1716                     ((dirty_submodule & DIRTY_SUBMODULE_UNTRACKED) ||
1717                      ignore_untracked)) {
1718                         /*
1719                          * We're not interested in any further information from
1720                          * the child any more, neither output nor its exit code.
1721                          */
1722                         ignore_cp_exit_code = 1;
1723                         break;
1724                 }
1725         }
1726         fclose(fp);
1727
1728         if (finish_command(&cp) && !ignore_cp_exit_code)
1729                 die(_("'git status --porcelain=2' failed in submodule %s"), path);
1730
1731         strbuf_release(&buf);
1732         return dirty_submodule;
1733 }
1734
1735 int submodule_uses_gitfile(const char *path)
1736 {
1737         struct child_process cp = CHILD_PROCESS_INIT;
1738         struct strbuf buf = STRBUF_INIT;
1739         const char *git_dir;
1740
1741         strbuf_addf(&buf, "%s/.git", path);
1742         git_dir = read_gitfile(buf.buf);
1743         if (!git_dir) {
1744                 strbuf_release(&buf);
1745                 return 0;
1746         }
1747         strbuf_release(&buf);
1748
1749         /* Now test that all nested submodules use a gitfile too */
1750         strvec_pushl(&cp.args,
1751                      "submodule", "foreach", "--quiet", "--recursive",
1752                      "test -f .git", NULL);
1753
1754         prepare_submodule_repo_env(&cp.env_array);
1755         cp.git_cmd = 1;
1756         cp.no_stdin = 1;
1757         cp.no_stderr = 1;
1758         cp.no_stdout = 1;
1759         cp.dir = path;
1760         if (run_command(&cp))
1761                 return 0;
1762
1763         return 1;
1764 }
1765
1766 /*
1767  * Check if it is a bad idea to remove a submodule, i.e. if we'd lose data
1768  * when doing so.
1769  *
1770  * Return 1 if we'd lose data, return 0 if the removal is fine,
1771  * and negative values for errors.
1772  */
1773 int bad_to_remove_submodule(const char *path, unsigned flags)
1774 {
1775         ssize_t len;
1776         struct child_process cp = CHILD_PROCESS_INIT;
1777         struct strbuf buf = STRBUF_INIT;
1778         int ret = 0;
1779
1780         if (!file_exists(path) || is_empty_dir(path))
1781                 return 0;
1782
1783         if (!submodule_uses_gitfile(path))
1784                 return 1;
1785
1786         strvec_pushl(&cp.args, "status", "--porcelain",
1787                      "--ignore-submodules=none", NULL);
1788
1789         if (flags & SUBMODULE_REMOVAL_IGNORE_UNTRACKED)
1790                 strvec_push(&cp.args, "-uno");
1791         else
1792                 strvec_push(&cp.args, "-uall");
1793
1794         if (!(flags & SUBMODULE_REMOVAL_IGNORE_IGNORED_UNTRACKED))
1795                 strvec_push(&cp.args, "--ignored");
1796
1797         prepare_submodule_repo_env(&cp.env_array);
1798         cp.git_cmd = 1;
1799         cp.no_stdin = 1;
1800         cp.out = -1;
1801         cp.dir = path;
1802         if (start_command(&cp)) {
1803                 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
1804                         die(_("could not start 'git status' in submodule '%s'"),
1805                                 path);
1806                 ret = -1;
1807                 goto out;
1808         }
1809
1810         len = strbuf_read(&buf, cp.out, 1024);
1811         if (len > 2)
1812                 ret = 1;
1813         close(cp.out);
1814
1815         if (finish_command(&cp)) {
1816                 if (flags & SUBMODULE_REMOVAL_DIE_ON_ERROR)
1817                         die(_("could not run 'git status' in submodule '%s'"),
1818                                 path);
1819                 ret = -1;
1820         }
1821 out:
1822         strbuf_release(&buf);
1823         return ret;
1824 }
1825
1826 void submodule_unset_core_worktree(const struct submodule *sub)
1827 {
1828         char *config_path = xstrfmt("%s/modules/%s/config",
1829                                     get_git_dir(), sub->name);
1830
1831         if (git_config_set_in_file_gently(config_path, "core.worktree", NULL))
1832                 warning(_("Could not unset core.worktree setting in submodule '%s'"),
1833                           sub->path);
1834
1835         free(config_path);
1836 }
1837
1838 static const char *get_super_prefix_or_empty(void)
1839 {
1840         const char *s = get_super_prefix();
1841         if (!s)
1842                 s = "";
1843         return s;
1844 }
1845
1846 static int submodule_has_dirty_index(const struct submodule *sub)
1847 {
1848         struct child_process cp = CHILD_PROCESS_INIT;
1849
1850         prepare_submodule_repo_env(&cp.env_array);
1851
1852         cp.git_cmd = 1;
1853         strvec_pushl(&cp.args, "diff-index", "--quiet",
1854                      "--cached", "HEAD", NULL);
1855         cp.no_stdin = 1;
1856         cp.no_stdout = 1;
1857         cp.dir = sub->path;
1858         if (start_command(&cp))
1859                 die(_("could not recurse into submodule '%s'"), sub->path);
1860
1861         return finish_command(&cp);
1862 }
1863
1864 static void submodule_reset_index(const char *path)
1865 {
1866         struct child_process cp = CHILD_PROCESS_INIT;
1867         prepare_submodule_repo_env(&cp.env_array);
1868
1869         cp.git_cmd = 1;
1870         cp.no_stdin = 1;
1871         cp.dir = path;
1872
1873         strvec_pushf(&cp.args, "--super-prefix=%s%s/",
1874                      get_super_prefix_or_empty(), path);
1875         strvec_pushl(&cp.args, "read-tree", "-u", "--reset", NULL);
1876
1877         strvec_push(&cp.args, empty_tree_oid_hex());
1878
1879         if (run_command(&cp))
1880                 die(_("could not reset submodule index"));
1881 }
1882
1883 /**
1884  * Moves a submodule at a given path from a given head to another new head.
1885  * For edge cases (a submodule coming into existence or removing a submodule)
1886  * pass NULL for old or new respectively.
1887  */
1888 int submodule_move_head(const char *path,
1889                          const char *old_head,
1890                          const char *new_head,
1891                          unsigned flags)
1892 {
1893         int ret = 0;
1894         struct child_process cp = CHILD_PROCESS_INIT;
1895         const struct submodule *sub;
1896         int *error_code_ptr, error_code;
1897
1898         if (!is_submodule_active(the_repository, path))
1899                 return 0;
1900
1901         if (flags & SUBMODULE_MOVE_HEAD_FORCE)
1902                 /*
1903                  * Pass non NULL pointer to is_submodule_populated_gently
1904                  * to prevent die()-ing. We'll use connect_work_tree_and_git_dir
1905                  * to fixup the submodule in the force case later.
1906                  */
1907                 error_code_ptr = &error_code;
1908         else
1909                 error_code_ptr = NULL;
1910
1911         if (old_head && !is_submodule_populated_gently(path, error_code_ptr))
1912                 return 0;
1913
1914         sub = submodule_from_path(the_repository, &null_oid, path);
1915
1916         if (!sub)
1917                 BUG("could not get submodule information for '%s'", path);
1918
1919         if (old_head && !(flags & SUBMODULE_MOVE_HEAD_FORCE)) {
1920                 /* Check if the submodule has a dirty index. */
1921                 if (submodule_has_dirty_index(sub))
1922                         return error(_("submodule '%s' has dirty index"), path);
1923         }
1924
1925         if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
1926                 if (old_head) {
1927                         if (!submodule_uses_gitfile(path))
1928                                 absorb_git_dir_into_superproject(path,
1929                                         ABSORB_GITDIR_RECURSE_SUBMODULES);
1930                 } else {
1931                         char *gitdir = xstrfmt("%s/modules/%s",
1932                                     get_git_dir(), sub->name);
1933                         connect_work_tree_and_git_dir(path, gitdir, 0);
1934                         free(gitdir);
1935
1936                         /* make sure the index is clean as well */
1937                         submodule_reset_index(path);
1938                 }
1939
1940                 if (old_head && (flags & SUBMODULE_MOVE_HEAD_FORCE)) {
1941                         char *gitdir = xstrfmt("%s/modules/%s",
1942                                     get_git_dir(), sub->name);
1943                         connect_work_tree_and_git_dir(path, gitdir, 1);
1944                         free(gitdir);
1945                 }
1946         }
1947
1948         prepare_submodule_repo_env(&cp.env_array);
1949
1950         cp.git_cmd = 1;
1951         cp.no_stdin = 1;
1952         cp.dir = path;
1953
1954         strvec_pushf(&cp.args, "--super-prefix=%s%s/",
1955                      get_super_prefix_or_empty(), path);
1956         strvec_pushl(&cp.args, "read-tree", "--recurse-submodules", NULL);
1957
1958         if (flags & SUBMODULE_MOVE_HEAD_DRY_RUN)
1959                 strvec_push(&cp.args, "-n");
1960         else
1961                 strvec_push(&cp.args, "-u");
1962
1963         if (flags & SUBMODULE_MOVE_HEAD_FORCE)
1964                 strvec_push(&cp.args, "--reset");
1965         else
1966                 strvec_push(&cp.args, "-m");
1967
1968         if (!(flags & SUBMODULE_MOVE_HEAD_FORCE))
1969                 strvec_push(&cp.args, old_head ? old_head : empty_tree_oid_hex());
1970
1971         strvec_push(&cp.args, new_head ? new_head : empty_tree_oid_hex());
1972
1973         if (run_command(&cp)) {
1974                 ret = error(_("Submodule '%s' could not be updated."), path);
1975                 goto out;
1976         }
1977
1978         if (!(flags & SUBMODULE_MOVE_HEAD_DRY_RUN)) {
1979                 if (new_head) {
1980                         child_process_init(&cp);
1981                         /* also set the HEAD accordingly */
1982                         cp.git_cmd = 1;
1983                         cp.no_stdin = 1;
1984                         cp.dir = path;
1985
1986                         prepare_submodule_repo_env(&cp.env_array);
1987                         strvec_pushl(&cp.args, "update-ref", "HEAD",
1988                                      "--no-deref", new_head, NULL);
1989
1990                         if (run_command(&cp)) {
1991                                 ret = -1;
1992                                 goto out;
1993                         }
1994                 } else {
1995                         struct strbuf sb = STRBUF_INIT;
1996
1997                         strbuf_addf(&sb, "%s/.git", path);
1998                         unlink_or_warn(sb.buf);
1999                         strbuf_release(&sb);
2000
2001                         if (is_empty_dir(path))
2002                                 rmdir_or_warn(path);
2003
2004                         submodule_unset_core_worktree(sub);
2005                 }
2006         }
2007 out:
2008         return ret;
2009 }
2010
2011 int validate_submodule_git_dir(char *git_dir, const char *submodule_name)
2012 {
2013         size_t len = strlen(git_dir), suffix_len = strlen(submodule_name);
2014         char *p;
2015         int ret = 0;
2016
2017         if (len <= suffix_len || (p = git_dir + len - suffix_len)[-1] != '/' ||
2018             strcmp(p, submodule_name))
2019                 BUG("submodule name '%s' not a suffix of git dir '%s'",
2020                     submodule_name, git_dir);
2021
2022         /*
2023          * We prevent the contents of sibling submodules' git directories to
2024          * clash.
2025          *
2026          * Example: having a submodule named `hippo` and another one named
2027          * `hippo/hooks` would result in the git directories
2028          * `.git/modules/hippo/` and `.git/modules/hippo/hooks/`, respectively,
2029          * but the latter directory is already designated to contain the hooks
2030          * of the former.
2031          */
2032         for (; *p; p++) {
2033                 if (is_dir_sep(*p)) {
2034                         char c = *p;
2035
2036                         *p = '\0';
2037                         if (is_git_directory(git_dir))
2038                                 ret = -1;
2039                         *p = c;
2040
2041                         if (ret < 0)
2042                                 return error(_("submodule git dir '%s' is "
2043                                                "inside git dir '%.*s'"),
2044                                              git_dir,
2045                                              (int)(p - git_dir), git_dir);
2046                 }
2047         }
2048
2049         return 0;
2050 }
2051
2052 /*
2053  * Embeds a single submodules git directory into the superprojects git dir,
2054  * non recursively.
2055  */
2056 static void relocate_single_git_dir_into_superproject(const char *path)
2057 {
2058         char *old_git_dir = NULL, *real_old_git_dir = NULL, *real_new_git_dir = NULL;
2059         char *new_git_dir;
2060         const struct submodule *sub;
2061
2062         if (submodule_uses_worktrees(path))
2063                 die(_("relocate_gitdir for submodule '%s' with "
2064                       "more than one worktree not supported"), path);
2065
2066         old_git_dir = xstrfmt("%s/.git", path);
2067         if (read_gitfile(old_git_dir))
2068                 /* If it is an actual gitfile, it doesn't need migration. */
2069                 return;
2070
2071         real_old_git_dir = real_pathdup(old_git_dir, 1);
2072
2073         sub = submodule_from_path(the_repository, &null_oid, path);
2074         if (!sub)
2075                 die(_("could not lookup name for submodule '%s'"), path);
2076
2077         new_git_dir = git_pathdup("modules/%s", sub->name);
2078         if (validate_submodule_git_dir(new_git_dir, sub->name) < 0)
2079                 die(_("refusing to move '%s' into an existing git dir"),
2080                     real_old_git_dir);
2081         if (safe_create_leading_directories_const(new_git_dir) < 0)
2082                 die(_("could not create directory '%s'"), new_git_dir);
2083         real_new_git_dir = real_pathdup(new_git_dir, 1);
2084         free(new_git_dir);
2085
2086         fprintf(stderr, _("Migrating git directory of '%s%s' from\n'%s' to\n'%s'\n"),
2087                 get_super_prefix_or_empty(), path,
2088                 real_old_git_dir, real_new_git_dir);
2089
2090         relocate_gitdir(path, real_old_git_dir, real_new_git_dir);
2091
2092         free(old_git_dir);
2093         free(real_old_git_dir);
2094         free(real_new_git_dir);
2095 }
2096
2097 /*
2098  * Migrate the git directory of the submodule given by path from
2099  * having its git directory within the working tree to the git dir nested
2100  * in its superprojects git dir under modules/.
2101  */
2102 void absorb_git_dir_into_superproject(const char *path,
2103                                       unsigned flags)
2104 {
2105         int err_code;
2106         const char *sub_git_dir;
2107         struct strbuf gitdir = STRBUF_INIT;
2108         strbuf_addf(&gitdir, "%s/.git", path);
2109         sub_git_dir = resolve_gitdir_gently(gitdir.buf, &err_code);
2110
2111         /* Not populated? */
2112         if (!sub_git_dir) {
2113                 const struct submodule *sub;
2114
2115                 if (err_code == READ_GITFILE_ERR_STAT_FAILED) {
2116                         /* unpopulated as expected */
2117                         strbuf_release(&gitdir);
2118                         return;
2119                 }
2120
2121                 if (err_code != READ_GITFILE_ERR_NOT_A_REPO)
2122                         /* We don't know what broke here. */
2123                         read_gitfile_error_die(err_code, path, NULL);
2124
2125                 /*
2126                 * Maybe populated, but no git directory was found?
2127                 * This can happen if the superproject is a submodule
2128                 * itself and was just absorbed. The absorption of the
2129                 * superproject did not rewrite the git file links yet,
2130                 * fix it now.
2131                 */
2132                 sub = submodule_from_path(the_repository, &null_oid, path);
2133                 if (!sub)
2134                         die(_("could not lookup name for submodule '%s'"), path);
2135                 connect_work_tree_and_git_dir(path,
2136                         git_path("modules/%s", sub->name), 0);
2137         } else {
2138                 /* Is it already absorbed into the superprojects git dir? */
2139                 char *real_sub_git_dir = real_pathdup(sub_git_dir, 1);
2140                 char *real_common_git_dir = real_pathdup(get_git_common_dir(), 1);
2141
2142                 if (!starts_with(real_sub_git_dir, real_common_git_dir))
2143                         relocate_single_git_dir_into_superproject(path);
2144
2145                 free(real_sub_git_dir);
2146                 free(real_common_git_dir);
2147         }
2148         strbuf_release(&gitdir);
2149
2150         if (flags & ABSORB_GITDIR_RECURSE_SUBMODULES) {
2151                 struct child_process cp = CHILD_PROCESS_INIT;
2152                 struct strbuf sb = STRBUF_INIT;
2153
2154                 if (flags & ~ABSORB_GITDIR_RECURSE_SUBMODULES)
2155                         BUG("we don't know how to pass the flags down?");
2156
2157                 strbuf_addstr(&sb, get_super_prefix_or_empty());
2158                 strbuf_addstr(&sb, path);
2159                 strbuf_addch(&sb, '/');
2160
2161                 cp.dir = path;
2162                 cp.git_cmd = 1;
2163                 cp.no_stdin = 1;
2164                 strvec_pushl(&cp.args, "--super-prefix", sb.buf,
2165                              "submodule--helper",
2166                              "absorb-git-dirs", NULL);
2167                 prepare_submodule_repo_env(&cp.env_array);
2168                 if (run_command(&cp))
2169                         die(_("could not recurse into submodule '%s'"), path);
2170
2171                 strbuf_release(&sb);
2172         }
2173 }
2174
2175 int get_superproject_working_tree(struct strbuf *buf)
2176 {
2177         struct child_process cp = CHILD_PROCESS_INIT;
2178         struct strbuf sb = STRBUF_INIT;
2179         struct strbuf one_up = STRBUF_INIT;
2180         const char *cwd = xgetcwd();
2181         int ret = 0;
2182         const char *subpath;
2183         int code;
2184         ssize_t len;
2185
2186         if (!is_inside_work_tree())
2187                 /*
2188                  * FIXME:
2189                  * We might have a superproject, but it is harder
2190                  * to determine.
2191                  */
2192                 return 0;
2193
2194         if (!strbuf_realpath(&one_up, "../", 0))
2195                 return 0;
2196
2197         subpath = relative_path(cwd, one_up.buf, &sb);
2198         strbuf_release(&one_up);
2199
2200         prepare_submodule_repo_env(&cp.env_array);
2201         strvec_pop(&cp.env_array);
2202
2203         strvec_pushl(&cp.args, "--literal-pathspecs", "-C", "..",
2204                      "ls-files", "-z", "--stage", "--full-name", "--",
2205                      subpath, NULL);
2206         strbuf_reset(&sb);
2207
2208         cp.no_stdin = 1;
2209         cp.no_stderr = 1;
2210         cp.out = -1;
2211         cp.git_cmd = 1;
2212
2213         if (start_command(&cp))
2214                 die(_("could not start ls-files in .."));
2215
2216         len = strbuf_read(&sb, cp.out, PATH_MAX);
2217         close(cp.out);
2218
2219         if (starts_with(sb.buf, "160000")) {
2220                 int super_sub_len;
2221                 int cwd_len = strlen(cwd);
2222                 char *super_sub, *super_wt;
2223
2224                 /*
2225                  * There is a superproject having this repo as a submodule.
2226                  * The format is <mode> SP <hash> SP <stage> TAB <full name> \0,
2227                  * We're only interested in the name after the tab.
2228                  */
2229                 super_sub = strchr(sb.buf, '\t') + 1;
2230                 super_sub_len = strlen(super_sub);
2231
2232                 if (super_sub_len > cwd_len ||
2233                     strcmp(&cwd[cwd_len - super_sub_len], super_sub))
2234                         BUG("returned path string doesn't match cwd?");
2235
2236                 super_wt = xstrdup(cwd);
2237                 super_wt[cwd_len - super_sub_len] = '\0';
2238
2239                 strbuf_realpath(buf, super_wt, 1);
2240                 ret = 1;
2241                 free(super_wt);
2242         }
2243         strbuf_release(&sb);
2244
2245         code = finish_command(&cp);
2246
2247         if (code == 128)
2248                 /* '../' is not a git repository */
2249                 return 0;
2250         if (code == 0 && len == 0)
2251                 /* There is an unrelated git repository at '../' */
2252                 return 0;
2253         if (code)
2254                 die(_("ls-tree returned unexpected return code %d"), code);
2255
2256         return ret;
2257 }
2258
2259 /*
2260  * Put the gitdir for a submodule (given relative to the main
2261  * repository worktree) into `buf`, or return -1 on error.
2262  */
2263 int submodule_to_gitdir(struct strbuf *buf, const char *submodule)
2264 {
2265         const struct submodule *sub;
2266         const char *git_dir;
2267         int ret = 0;
2268
2269         strbuf_reset(buf);
2270         strbuf_addstr(buf, submodule);
2271         strbuf_complete(buf, '/');
2272         strbuf_addstr(buf, ".git");
2273
2274         git_dir = read_gitfile(buf->buf);
2275         if (git_dir) {
2276                 strbuf_reset(buf);
2277                 strbuf_addstr(buf, git_dir);
2278         }
2279         if (!is_git_directory(buf->buf)) {
2280                 sub = submodule_from_path(the_repository, &null_oid, submodule);
2281                 if (!sub) {
2282                         ret = -1;
2283                         goto cleanup;
2284                 }
2285                 strbuf_reset(buf);
2286                 strbuf_git_path(buf, "%s/%s", "modules", sub->name);
2287         }
2288
2289 cleanup:
2290         return ret;
2291 }