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