submodule.con commit submodule: allow erroneous values for the fetchRecurseSubmodules option (027771f)
   1#include "cache.h"
   2#include "submodule-config.h"
   3#include "submodule.h"
   4#include "dir.h"
   5#include "diff.h"
   6#include "commit.h"
   7#include "revision.h"
   8#include "run-command.h"
   9#include "diffcore.h"
  10#include "refs.h"
  11#include "string-list.h"
  12#include "sha1-array.h"
  13#include "argv-array.h"
  14#include "blob.h"
  15
  16static int config_fetch_recurse_submodules = RECURSE_SUBMODULES_ON_DEMAND;
  17static struct string_list changed_submodule_paths;
  18static int initialized_fetch_ref_tips;
  19static struct sha1_array ref_tips_before_fetch;
  20static struct sha1_array ref_tips_after_fetch;
  21
  22/*
  23 * The following flag is set if the .gitmodules file is unmerged. We then
  24 * disable recursion for all submodules where .git/config doesn't have a
  25 * matching config entry because we can't guess what might be configured in
  26 * .gitmodules unless the user resolves the conflict. When a command line
  27 * option is given (which always overrides configuration) this flag will be
  28 * ignored.
  29 */
  30static int gitmodules_is_unmerged;
  31
  32/*
  33 * This flag is set if the .gitmodules file had unstaged modifications on
  34 * startup. This must be checked before allowing modifications to the
  35 * .gitmodules file with the intention to stage them later, because when
  36 * continuing we would stage the modifications the user didn't stage herself
  37 * too. That might change in a future version when we learn to stage the
  38 * changes we do ourselves without staging any previous modifications.
  39 */
  40static int gitmodules_is_modified;
  41
  42int is_staging_gitmodules_ok(void)
  43{
  44        return !gitmodules_is_modified;
  45}
  46
  47/*
  48 * Try to update the "path" entry in the "submodule.<name>" section of the
  49 * .gitmodules file. Return 0 only if a .gitmodules file was found, a section
  50 * with the correct path=<oldpath> setting was found and we could update it.
  51 */
  52int update_path_in_gitmodules(const char *oldpath, const char *newpath)
  53{
  54        struct strbuf entry = STRBUF_INIT;
  55        const struct submodule *submodule;
  56
  57        if (!file_exists(".gitmodules")) /* Do nothing without .gitmodules */
  58                return -1;
  59
  60        if (gitmodules_is_unmerged)
  61                die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
  62
  63        submodule = submodule_from_path(null_sha1, oldpath);
  64        if (!submodule || !submodule->name) {
  65                warning(_("Could not find section in .gitmodules where path=%s"), oldpath);
  66                return -1;
  67        }
  68        strbuf_addstr(&entry, "submodule.");
  69        strbuf_addstr(&entry, submodule->name);
  70        strbuf_addstr(&entry, ".path");
  71        if (git_config_set_in_file(".gitmodules", entry.buf, newpath) < 0) {
  72                /* Maybe the user already did that, don't error out here */
  73                warning(_("Could not update .gitmodules entry %s"), entry.buf);
  74                strbuf_release(&entry);
  75                return -1;
  76        }
  77        strbuf_release(&entry);
  78        return 0;
  79}
  80
  81/*
  82 * Try to remove the "submodule.<name>" section from .gitmodules where the given
  83 * path is configured. Return 0 only if a .gitmodules file was found, a section
  84 * with the correct path=<path> setting was found and we could remove it.
  85 */
  86int remove_path_from_gitmodules(const char *path)
  87{
  88        struct strbuf sect = STRBUF_INIT;
  89        const struct submodule *submodule;
  90
  91        if (!file_exists(".gitmodules")) /* Do nothing without .gitmodules */
  92                return -1;
  93
  94        if (gitmodules_is_unmerged)
  95                die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
  96
  97        submodule = submodule_from_path(null_sha1, path);
  98        if (!submodule || !submodule->name) {
  99                warning(_("Could not find section in .gitmodules where path=%s"), path);
 100                return -1;
 101        }
 102        strbuf_addstr(&sect, "submodule.");
 103        strbuf_addstr(&sect, submodule->name);
 104        if (git_config_rename_section_in_file(".gitmodules", sect.buf, NULL) < 0) {
 105                /* Maybe the user already did that, don't error out here */
 106                warning(_("Could not remove .gitmodules entry for %s"), path);
 107                strbuf_release(&sect);
 108                return -1;
 109        }
 110        strbuf_release(&sect);
 111        return 0;
 112}
 113
 114void stage_updated_gitmodules(void)
 115{
 116        if (add_file_to_cache(".gitmodules", 0))
 117                die(_("staging updated .gitmodules failed"));
 118}
 119
 120static int add_submodule_odb(const char *path)
 121{
 122        struct strbuf objects_directory = STRBUF_INIT;
 123        struct alternate_object_database *alt_odb;
 124        int ret = 0;
 125        const char *git_dir;
 126
 127        strbuf_addf(&objects_directory, "%s/.git", path);
 128        git_dir = read_gitfile(objects_directory.buf);
 129        if (git_dir) {
 130                strbuf_reset(&objects_directory);
 131                strbuf_addstr(&objects_directory, git_dir);
 132        }
 133        strbuf_addstr(&objects_directory, "/objects/");
 134        if (!is_directory(objects_directory.buf)) {
 135                ret = -1;
 136                goto done;
 137        }
 138        /* avoid adding it twice */
 139        for (alt_odb = alt_odb_list; alt_odb; alt_odb = alt_odb->next)
 140                if (alt_odb->name - alt_odb->base == objects_directory.len &&
 141                                !strncmp(alt_odb->base, objects_directory.buf,
 142                                        objects_directory.len))
 143                        goto done;
 144
 145        alt_odb = xmalloc(objects_directory.len + 42 + sizeof(*alt_odb));
 146        alt_odb->next = alt_odb_list;
 147        strcpy(alt_odb->base, objects_directory.buf);
 148        alt_odb->name = alt_odb->base + objects_directory.len;
 149        alt_odb->name[2] = '/';
 150        alt_odb->name[40] = '\0';
 151        alt_odb->name[41] = '\0';
 152        alt_odb_list = alt_odb;
 153
 154        /* add possible alternates from the submodule */
 155        read_info_alternates(objects_directory.buf, 0);
 156        prepare_alt_odb();
 157done:
 158        strbuf_release(&objects_directory);
 159        return ret;
 160}
 161
 162void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
 163                                             const char *path)
 164{
 165        const struct submodule *submodule = submodule_from_path(null_sha1, path);
 166        if (submodule) {
 167                if (submodule->ignore)
 168                        handle_ignore_submodules_arg(diffopt, submodule->ignore);
 169                else if (gitmodules_is_unmerged)
 170                        DIFF_OPT_SET(diffopt, IGNORE_SUBMODULES);
 171        }
 172}
 173
 174int submodule_config(const char *var, const char *value, void *cb)
 175{
 176        if (starts_with(var, "submodule."))
 177                return parse_submodule_config_option(var, value);
 178        else if (!strcmp(var, "fetch.recursesubmodules")) {
 179                config_fetch_recurse_submodules = parse_fetch_recurse_submodules_arg(var, value);
 180                return 0;
 181        }
 182        return 0;
 183}
 184
 185void gitmodules_config(void)
 186{
 187        const char *work_tree = get_git_work_tree();
 188        if (work_tree) {
 189                struct strbuf gitmodules_path = STRBUF_INIT;
 190                int pos;
 191                strbuf_addstr(&gitmodules_path, work_tree);
 192                strbuf_addstr(&gitmodules_path, "/.gitmodules");
 193                if (read_cache() < 0)
 194                        die("index file corrupt");
 195                pos = cache_name_pos(".gitmodules", 11);
 196                if (pos < 0) { /* .gitmodules not found or isn't merged */
 197                        pos = -1 - pos;
 198                        if (active_nr > pos) {  /* there is a .gitmodules */
 199                                const struct cache_entry *ce = active_cache[pos];
 200                                if (ce_namelen(ce) == 11 &&
 201                                    !memcmp(ce->name, ".gitmodules", 11))
 202                                        gitmodules_is_unmerged = 1;
 203                        }
 204                } else if (pos < active_nr) {
 205                        struct stat st;
 206                        if (lstat(".gitmodules", &st) == 0 &&
 207                            ce_match_stat(active_cache[pos], &st, 0) & DATA_CHANGED)
 208                                gitmodules_is_modified = 1;
 209                }
 210
 211                if (!gitmodules_is_unmerged)
 212                        git_config_from_file(submodule_config, gitmodules_path.buf, NULL);
 213                strbuf_release(&gitmodules_path);
 214        }
 215}
 216
 217void handle_ignore_submodules_arg(struct diff_options *diffopt,
 218                                  const char *arg)
 219{
 220        DIFF_OPT_CLR(diffopt, IGNORE_SUBMODULES);
 221        DIFF_OPT_CLR(diffopt, IGNORE_UNTRACKED_IN_SUBMODULES);
 222        DIFF_OPT_CLR(diffopt, IGNORE_DIRTY_SUBMODULES);
 223
 224        if (!strcmp(arg, "all"))
 225                DIFF_OPT_SET(diffopt, IGNORE_SUBMODULES);
 226        else if (!strcmp(arg, "untracked"))
 227                DIFF_OPT_SET(diffopt, IGNORE_UNTRACKED_IN_SUBMODULES);
 228        else if (!strcmp(arg, "dirty"))
 229                DIFF_OPT_SET(diffopt, IGNORE_DIRTY_SUBMODULES);
 230        else if (strcmp(arg, "none"))
 231                die("bad --ignore-submodules argument: %s", arg);
 232}
 233
 234static int prepare_submodule_summary(struct rev_info *rev, const char *path,
 235                struct commit *left, struct commit *right,
 236                int *fast_forward, int *fast_backward)
 237{
 238        struct commit_list *merge_bases, *list;
 239
 240        init_revisions(rev, NULL);
 241        setup_revisions(0, NULL, rev, NULL);
 242        rev->left_right = 1;
 243        rev->first_parent_only = 1;
 244        left->object.flags |= SYMMETRIC_LEFT;
 245        add_pending_object(rev, &left->object, path);
 246        add_pending_object(rev, &right->object, path);
 247        merge_bases = get_merge_bases(left, right);
 248        if (merge_bases) {
 249                if (merge_bases->item == left)
 250                        *fast_forward = 1;
 251                else if (merge_bases->item == right)
 252                        *fast_backward = 1;
 253        }
 254        for (list = merge_bases; list; list = list->next) {
 255                list->item->object.flags |= UNINTERESTING;
 256                add_pending_object(rev, &list->item->object,
 257                        sha1_to_hex(list->item->object.sha1));
 258        }
 259        return prepare_revision_walk(rev);
 260}
 261
 262static void print_submodule_summary(struct rev_info *rev, FILE *f,
 263                const char *line_prefix,
 264                const char *del, const char *add, const char *reset)
 265{
 266        static const char format[] = "  %m %s";
 267        struct strbuf sb = STRBUF_INIT;
 268        struct commit *commit;
 269
 270        while ((commit = get_revision(rev))) {
 271                struct pretty_print_context ctx = {0};
 272                ctx.date_mode = rev->date_mode;
 273                ctx.output_encoding = get_log_output_encoding();
 274                strbuf_setlen(&sb, 0);
 275                strbuf_addstr(&sb, line_prefix);
 276                if (commit->object.flags & SYMMETRIC_LEFT) {
 277                        if (del)
 278                                strbuf_addstr(&sb, del);
 279                }
 280                else if (add)
 281                        strbuf_addstr(&sb, add);
 282                format_commit_message(commit, format, &sb, &ctx);
 283                if (reset)
 284                        strbuf_addstr(&sb, reset);
 285                strbuf_addch(&sb, '\n');
 286                fprintf(f, "%s", sb.buf);
 287        }
 288        strbuf_release(&sb);
 289}
 290
 291void show_submodule_summary(FILE *f, const char *path,
 292                const char *line_prefix,
 293                unsigned char one[20], unsigned char two[20],
 294                unsigned dirty_submodule, const char *meta,
 295                const char *del, const char *add, const char *reset)
 296{
 297        struct rev_info rev;
 298        struct commit *left = NULL, *right = NULL;
 299        const char *message = NULL;
 300        struct strbuf sb = STRBUF_INIT;
 301        int fast_forward = 0, fast_backward = 0;
 302
 303        if (is_null_sha1(two))
 304                message = "(submodule deleted)";
 305        else if (add_submodule_odb(path))
 306                message = "(not checked out)";
 307        else if (is_null_sha1(one))
 308                message = "(new submodule)";
 309        else if (!(left = lookup_commit_reference(one)) ||
 310                 !(right = lookup_commit_reference(two)))
 311                message = "(commits not present)";
 312        else if (prepare_submodule_summary(&rev, path, left, right,
 313                                           &fast_forward, &fast_backward))
 314                message = "(revision walker failed)";
 315
 316        if (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED)
 317                fprintf(f, "%sSubmodule %s contains untracked content\n",
 318                        line_prefix, path);
 319        if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
 320                fprintf(f, "%sSubmodule %s contains modified content\n",
 321                        line_prefix, path);
 322
 323        if (!hashcmp(one, two)) {
 324                strbuf_release(&sb);
 325                return;
 326        }
 327
 328        strbuf_addf(&sb, "%s%sSubmodule %s %s..", line_prefix, meta, path,
 329                        find_unique_abbrev(one, DEFAULT_ABBREV));
 330        if (!fast_backward && !fast_forward)
 331                strbuf_addch(&sb, '.');
 332        strbuf_addf(&sb, "%s", find_unique_abbrev(two, DEFAULT_ABBREV));
 333        if (message)
 334                strbuf_addf(&sb, " %s%s\n", message, reset);
 335        else
 336                strbuf_addf(&sb, "%s:%s\n", fast_backward ? " (rewind)" : "", reset);
 337        fwrite(sb.buf, sb.len, 1, f);
 338
 339        if (!message) /* only NULL if we succeeded in setting up the walk */
 340                print_submodule_summary(&rev, f, line_prefix, del, add, reset);
 341        if (left)
 342                clear_commit_marks(left, ~0);
 343        if (right)
 344                clear_commit_marks(right, ~0);
 345
 346        strbuf_release(&sb);
 347}
 348
 349void set_config_fetch_recurse_submodules(int value)
 350{
 351        config_fetch_recurse_submodules = value;
 352}
 353
 354static int has_remote(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
 355{
 356        return 1;
 357}
 358
 359static int submodule_needs_pushing(const char *path, const unsigned char sha1[20])
 360{
 361        if (add_submodule_odb(path) || !lookup_commit_reference(sha1))
 362                return 0;
 363
 364        if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
 365                struct child_process cp = CHILD_PROCESS_INIT;
 366                const char *argv[] = {"rev-list", NULL, "--not", "--remotes", "-n", "1" , NULL};
 367                struct strbuf buf = STRBUF_INIT;
 368                int needs_pushing = 0;
 369
 370                argv[1] = sha1_to_hex(sha1);
 371                cp.argv = argv;
 372                cp.env = local_repo_env;
 373                cp.git_cmd = 1;
 374                cp.no_stdin = 1;
 375                cp.out = -1;
 376                cp.dir = path;
 377                if (start_command(&cp))
 378                        die("Could not run 'git rev-list %s --not --remotes -n 1' command in submodule %s",
 379                                sha1_to_hex(sha1), path);
 380                if (strbuf_read(&buf, cp.out, 41))
 381                        needs_pushing = 1;
 382                finish_command(&cp);
 383                close(cp.out);
 384                strbuf_release(&buf);
 385                return needs_pushing;
 386        }
 387
 388        return 0;
 389}
 390
 391static void collect_submodules_from_diff(struct diff_queue_struct *q,
 392                                         struct diff_options *options,
 393                                         void *data)
 394{
 395        int i;
 396        struct string_list *needs_pushing = data;
 397
 398        for (i = 0; i < q->nr; i++) {
 399                struct diff_filepair *p = q->queue[i];
 400                if (!S_ISGITLINK(p->two->mode))
 401                        continue;
 402                if (submodule_needs_pushing(p->two->path, p->two->sha1))
 403                        string_list_insert(needs_pushing, p->two->path);
 404        }
 405}
 406
 407static void find_unpushed_submodule_commits(struct commit *commit,
 408                struct string_list *needs_pushing)
 409{
 410        struct rev_info rev;
 411
 412        init_revisions(&rev, NULL);
 413        rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
 414        rev.diffopt.format_callback = collect_submodules_from_diff;
 415        rev.diffopt.format_callback_data = needs_pushing;
 416        diff_tree_combined_merge(commit, 1, &rev);
 417}
 418
 419int find_unpushed_submodules(unsigned char new_sha1[20],
 420                const char *remotes_name, struct string_list *needs_pushing)
 421{
 422        struct rev_info rev;
 423        struct commit *commit;
 424        const char *argv[] = {NULL, NULL, "--not", "NULL", NULL};
 425        int argc = ARRAY_SIZE(argv) - 1;
 426        char *sha1_copy;
 427
 428        struct strbuf remotes_arg = STRBUF_INIT;
 429
 430        strbuf_addf(&remotes_arg, "--remotes=%s", remotes_name);
 431        init_revisions(&rev, NULL);
 432        sha1_copy = xstrdup(sha1_to_hex(new_sha1));
 433        argv[1] = sha1_copy;
 434        argv[3] = remotes_arg.buf;
 435        setup_revisions(argc, argv, &rev, NULL);
 436        if (prepare_revision_walk(&rev))
 437                die("revision walk setup failed");
 438
 439        while ((commit = get_revision(&rev)) != NULL)
 440                find_unpushed_submodule_commits(commit, needs_pushing);
 441
 442        reset_revision_walk();
 443        free(sha1_copy);
 444        strbuf_release(&remotes_arg);
 445
 446        return needs_pushing->nr;
 447}
 448
 449static int push_submodule(const char *path)
 450{
 451        if (add_submodule_odb(path))
 452                return 1;
 453
 454        if (for_each_remote_ref_submodule(path, has_remote, NULL) > 0) {
 455                struct child_process cp = CHILD_PROCESS_INIT;
 456                const char *argv[] = {"push", NULL};
 457
 458                cp.argv = argv;
 459                cp.env = local_repo_env;
 460                cp.git_cmd = 1;
 461                cp.no_stdin = 1;
 462                cp.dir = path;
 463                if (run_command(&cp))
 464                        return 0;
 465                close(cp.out);
 466        }
 467
 468        return 1;
 469}
 470
 471int push_unpushed_submodules(unsigned char new_sha1[20], const char *remotes_name)
 472{
 473        int i, ret = 1;
 474        struct string_list needs_pushing = STRING_LIST_INIT_DUP;
 475
 476        if (!find_unpushed_submodules(new_sha1, remotes_name, &needs_pushing))
 477                return 1;
 478
 479        for (i = 0; i < needs_pushing.nr; i++) {
 480                const char *path = needs_pushing.items[i].string;
 481                fprintf(stderr, "Pushing submodule '%s'\n", path);
 482                if (!push_submodule(path)) {
 483                        fprintf(stderr, "Unable to push submodule '%s'\n", path);
 484                        ret = 0;
 485                }
 486        }
 487
 488        string_list_clear(&needs_pushing, 0);
 489
 490        return ret;
 491}
 492
 493static int is_submodule_commit_present(const char *path, unsigned char sha1[20])
 494{
 495        int is_present = 0;
 496        if (!add_submodule_odb(path) && lookup_commit_reference(sha1)) {
 497                /* Even if the submodule is checked out and the commit is
 498                 * present, make sure it is reachable from a ref. */
 499                struct child_process cp = CHILD_PROCESS_INIT;
 500                const char *argv[] = {"rev-list", "-n", "1", NULL, "--not", "--all", NULL};
 501                struct strbuf buf = STRBUF_INIT;
 502
 503                argv[3] = sha1_to_hex(sha1);
 504                cp.argv = argv;
 505                cp.env = local_repo_env;
 506                cp.git_cmd = 1;
 507                cp.no_stdin = 1;
 508                cp.dir = path;
 509                if (!capture_command(&cp, &buf, 1024) && !buf.len)
 510                        is_present = 1;
 511
 512                strbuf_release(&buf);
 513        }
 514        return is_present;
 515}
 516
 517static void submodule_collect_changed_cb(struct diff_queue_struct *q,
 518                                         struct diff_options *options,
 519                                         void *data)
 520{
 521        int i;
 522        for (i = 0; i < q->nr; i++) {
 523                struct diff_filepair *p = q->queue[i];
 524                if (!S_ISGITLINK(p->two->mode))
 525                        continue;
 526
 527                if (S_ISGITLINK(p->one->mode)) {
 528                        /* NEEDSWORK: We should honor the name configured in
 529                         * the .gitmodules file of the commit we are examining
 530                         * here to be able to correctly follow submodules
 531                         * being moved around. */
 532                        struct string_list_item *path;
 533                        path = unsorted_string_list_lookup(&changed_submodule_paths, p->two->path);
 534                        if (!path && !is_submodule_commit_present(p->two->path, p->two->sha1))
 535                                string_list_append(&changed_submodule_paths, xstrdup(p->two->path));
 536                } else {
 537                        /* Submodule is new or was moved here */
 538                        /* NEEDSWORK: When the .git directories of submodules
 539                         * live inside the superprojects .git directory some
 540                         * day we should fetch new submodules directly into
 541                         * that location too when config or options request
 542                         * that so they can be checked out from there. */
 543                        continue;
 544                }
 545        }
 546}
 547
 548static int add_sha1_to_array(const char *ref, const unsigned char *sha1,
 549                             int flags, void *data)
 550{
 551        sha1_array_append(data, sha1);
 552        return 0;
 553}
 554
 555void check_for_new_submodule_commits(unsigned char new_sha1[20])
 556{
 557        if (!initialized_fetch_ref_tips) {
 558                for_each_ref(add_sha1_to_array, &ref_tips_before_fetch);
 559                initialized_fetch_ref_tips = 1;
 560        }
 561
 562        sha1_array_append(&ref_tips_after_fetch, new_sha1);
 563}
 564
 565static void add_sha1_to_argv(const unsigned char sha1[20], void *data)
 566{
 567        argv_array_push(data, sha1_to_hex(sha1));
 568}
 569
 570static void calculate_changed_submodule_paths(void)
 571{
 572        struct rev_info rev;
 573        struct commit *commit;
 574        struct argv_array argv = ARGV_ARRAY_INIT;
 575
 576        /* No need to check if there are no submodules configured */
 577        if (!submodule_from_path(NULL, NULL))
 578                return;
 579
 580        init_revisions(&rev, NULL);
 581        argv_array_push(&argv, "--"); /* argv[0] program name */
 582        sha1_array_for_each_unique(&ref_tips_after_fetch,
 583                                   add_sha1_to_argv, &argv);
 584        argv_array_push(&argv, "--not");
 585        sha1_array_for_each_unique(&ref_tips_before_fetch,
 586                                   add_sha1_to_argv, &argv);
 587        setup_revisions(argv.argc, argv.argv, &rev, NULL);
 588        if (prepare_revision_walk(&rev))
 589                die("revision walk setup failed");
 590
 591        /*
 592         * Collect all submodules (whether checked out or not) for which new
 593         * commits have been recorded upstream in "changed_submodule_paths".
 594         */
 595        while ((commit = get_revision(&rev))) {
 596                struct commit_list *parent = commit->parents;
 597                while (parent) {
 598                        struct diff_options diff_opts;
 599                        diff_setup(&diff_opts);
 600                        DIFF_OPT_SET(&diff_opts, RECURSIVE);
 601                        diff_opts.output_format |= DIFF_FORMAT_CALLBACK;
 602                        diff_opts.format_callback = submodule_collect_changed_cb;
 603                        diff_setup_done(&diff_opts);
 604                        diff_tree_sha1(parent->item->object.sha1, commit->object.sha1, "", &diff_opts);
 605                        diffcore_std(&diff_opts);
 606                        diff_flush(&diff_opts);
 607                        parent = parent->next;
 608                }
 609        }
 610
 611        argv_array_clear(&argv);
 612        sha1_array_clear(&ref_tips_before_fetch);
 613        sha1_array_clear(&ref_tips_after_fetch);
 614        initialized_fetch_ref_tips = 0;
 615}
 616
 617int fetch_populated_submodules(const struct argv_array *options,
 618                               const char *prefix, int command_line_option,
 619                               int quiet)
 620{
 621        int i, result = 0;
 622        struct child_process cp = CHILD_PROCESS_INIT;
 623        struct argv_array argv = ARGV_ARRAY_INIT;
 624        const char *work_tree = get_git_work_tree();
 625        if (!work_tree)
 626                goto out;
 627
 628        if (read_cache() < 0)
 629                die("index file corrupt");
 630
 631        argv_array_push(&argv, "fetch");
 632        for (i = 0; i < options->argc; i++)
 633                argv_array_push(&argv, options->argv[i]);
 634        argv_array_push(&argv, "--recurse-submodules-default");
 635        /* default value, "--submodule-prefix" and its value are added later */
 636
 637        cp.env = local_repo_env;
 638        cp.git_cmd = 1;
 639        cp.no_stdin = 1;
 640
 641        calculate_changed_submodule_paths();
 642
 643        for (i = 0; i < active_nr; i++) {
 644                struct strbuf submodule_path = STRBUF_INIT;
 645                struct strbuf submodule_git_dir = STRBUF_INIT;
 646                struct strbuf submodule_prefix = STRBUF_INIT;
 647                const struct cache_entry *ce = active_cache[i];
 648                const char *git_dir, *default_argv;
 649                const struct submodule *submodule;
 650
 651                if (!S_ISGITLINK(ce->ce_mode))
 652                        continue;
 653
 654                submodule = submodule_from_path(null_sha1, ce->name);
 655                if (!submodule)
 656                        submodule = submodule_from_name(null_sha1, ce->name);
 657
 658                default_argv = "yes";
 659                if (command_line_option == RECURSE_SUBMODULES_DEFAULT) {
 660                        if (submodule &&
 661                            submodule->fetch_recurse !=
 662                                                RECURSE_SUBMODULES_NONE) {
 663                                if (submodule->fetch_recurse ==
 664                                                RECURSE_SUBMODULES_OFF)
 665                                        continue;
 666                                if (submodule->fetch_recurse ==
 667                                                RECURSE_SUBMODULES_ON_DEMAND) {
 668                                        if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
 669                                                continue;
 670                                        default_argv = "on-demand";
 671                                }
 672                        } else {
 673                                if ((config_fetch_recurse_submodules == RECURSE_SUBMODULES_OFF) ||
 674                                    gitmodules_is_unmerged)
 675                                        continue;
 676                                if (config_fetch_recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND) {
 677                                        if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
 678                                                continue;
 679                                        default_argv = "on-demand";
 680                                }
 681                        }
 682                } else if (command_line_option == RECURSE_SUBMODULES_ON_DEMAND) {
 683                        if (!unsorted_string_list_lookup(&changed_submodule_paths, ce->name))
 684                                continue;
 685                        default_argv = "on-demand";
 686                }
 687
 688                strbuf_addf(&submodule_path, "%s/%s", work_tree, ce->name);
 689                strbuf_addf(&submodule_git_dir, "%s/.git", submodule_path.buf);
 690                strbuf_addf(&submodule_prefix, "%s%s/", prefix, ce->name);
 691                git_dir = read_gitfile(submodule_git_dir.buf);
 692                if (!git_dir)
 693                        git_dir = submodule_git_dir.buf;
 694                if (is_directory(git_dir)) {
 695                        if (!quiet)
 696                                printf("Fetching submodule %s%s\n", prefix, ce->name);
 697                        cp.dir = submodule_path.buf;
 698                        argv_array_push(&argv, default_argv);
 699                        argv_array_push(&argv, "--submodule-prefix");
 700                        argv_array_push(&argv, submodule_prefix.buf);
 701                        cp.argv = argv.argv;
 702                        if (run_command(&cp))
 703                                result = 1;
 704                        argv_array_pop(&argv);
 705                        argv_array_pop(&argv);
 706                        argv_array_pop(&argv);
 707                }
 708                strbuf_release(&submodule_path);
 709                strbuf_release(&submodule_git_dir);
 710                strbuf_release(&submodule_prefix);
 711        }
 712        argv_array_clear(&argv);
 713out:
 714        string_list_clear(&changed_submodule_paths, 1);
 715        return result;
 716}
 717
 718unsigned is_submodule_modified(const char *path, int ignore_untracked)
 719{
 720        ssize_t len;
 721        struct child_process cp = CHILD_PROCESS_INIT;
 722        const char *argv[] = {
 723                "status",
 724                "--porcelain",
 725                NULL,
 726                NULL,
 727        };
 728        struct strbuf buf = STRBUF_INIT;
 729        unsigned dirty_submodule = 0;
 730        const char *line, *next_line;
 731        const char *git_dir;
 732
 733        strbuf_addf(&buf, "%s/.git", path);
 734        git_dir = read_gitfile(buf.buf);
 735        if (!git_dir)
 736                git_dir = buf.buf;
 737        if (!is_directory(git_dir)) {
 738                strbuf_release(&buf);
 739                /* The submodule is not checked out, so it is not modified */
 740                return 0;
 741
 742        }
 743        strbuf_reset(&buf);
 744
 745        if (ignore_untracked)
 746                argv[2] = "-uno";
 747
 748        cp.argv = argv;
 749        cp.env = local_repo_env;
 750        cp.git_cmd = 1;
 751        cp.no_stdin = 1;
 752        cp.out = -1;
 753        cp.dir = path;
 754        if (start_command(&cp))
 755                die("Could not run 'git status --porcelain' in submodule %s", path);
 756
 757        len = strbuf_read(&buf, cp.out, 1024);
 758        line = buf.buf;
 759        while (len > 2) {
 760                if ((line[0] == '?') && (line[1] == '?')) {
 761                        dirty_submodule |= DIRTY_SUBMODULE_UNTRACKED;
 762                        if (dirty_submodule & DIRTY_SUBMODULE_MODIFIED)
 763                                break;
 764                } else {
 765                        dirty_submodule |= DIRTY_SUBMODULE_MODIFIED;
 766                        if (ignore_untracked ||
 767                            (dirty_submodule & DIRTY_SUBMODULE_UNTRACKED))
 768                                break;
 769                }
 770                next_line = strchr(line, '\n');
 771                if (!next_line)
 772                        break;
 773                next_line++;
 774                len -= (next_line - line);
 775                line = next_line;
 776        }
 777        close(cp.out);
 778
 779        if (finish_command(&cp))
 780                die("'git status --porcelain' failed in submodule %s", path);
 781
 782        strbuf_release(&buf);
 783        return dirty_submodule;
 784}
 785
 786int submodule_uses_gitfile(const char *path)
 787{
 788        struct child_process cp = CHILD_PROCESS_INIT;
 789        const char *argv[] = {
 790                "submodule",
 791                "foreach",
 792                "--quiet",
 793                "--recursive",
 794                "test -f .git",
 795                NULL,
 796        };
 797        struct strbuf buf = STRBUF_INIT;
 798        const char *git_dir;
 799
 800        strbuf_addf(&buf, "%s/.git", path);
 801        git_dir = read_gitfile(buf.buf);
 802        if (!git_dir) {
 803                strbuf_release(&buf);
 804                return 0;
 805        }
 806        strbuf_release(&buf);
 807
 808        /* Now test that all nested submodules use a gitfile too */
 809        cp.argv = argv;
 810        cp.env = local_repo_env;
 811        cp.git_cmd = 1;
 812        cp.no_stdin = 1;
 813        cp.no_stderr = 1;
 814        cp.no_stdout = 1;
 815        cp.dir = path;
 816        if (run_command(&cp))
 817                return 0;
 818
 819        return 1;
 820}
 821
 822int ok_to_remove_submodule(const char *path)
 823{
 824        ssize_t len;
 825        struct child_process cp = CHILD_PROCESS_INIT;
 826        const char *argv[] = {
 827                "status",
 828                "--porcelain",
 829                "-u",
 830                "--ignore-submodules=none",
 831                NULL,
 832        };
 833        struct strbuf buf = STRBUF_INIT;
 834        int ok_to_remove = 1;
 835
 836        if (!file_exists(path) || is_empty_dir(path))
 837                return 1;
 838
 839        if (!submodule_uses_gitfile(path))
 840                return 0;
 841
 842        cp.argv = argv;
 843        cp.env = local_repo_env;
 844        cp.git_cmd = 1;
 845        cp.no_stdin = 1;
 846        cp.out = -1;
 847        cp.dir = path;
 848        if (start_command(&cp))
 849                die("Could not run 'git status --porcelain -uall --ignore-submodules=none' in submodule %s", path);
 850
 851        len = strbuf_read(&buf, cp.out, 1024);
 852        if (len > 2)
 853                ok_to_remove = 0;
 854        close(cp.out);
 855
 856        if (finish_command(&cp))
 857                die("'git status --porcelain -uall --ignore-submodules=none' failed in submodule %s", path);
 858
 859        strbuf_release(&buf);
 860        return ok_to_remove;
 861}
 862
 863static int find_first_merges(struct object_array *result, const char *path,
 864                struct commit *a, struct commit *b)
 865{
 866        int i, j;
 867        struct object_array merges = OBJECT_ARRAY_INIT;
 868        struct commit *commit;
 869        int contains_another;
 870
 871        char merged_revision[42];
 872        const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
 873                                   "--all", merged_revision, NULL };
 874        struct rev_info revs;
 875        struct setup_revision_opt rev_opts;
 876
 877        memset(result, 0, sizeof(struct object_array));
 878        memset(&rev_opts, 0, sizeof(rev_opts));
 879
 880        /* get all revisions that merge commit a */
 881        snprintf(merged_revision, sizeof(merged_revision), "^%s",
 882                        sha1_to_hex(a->object.sha1));
 883        init_revisions(&revs, NULL);
 884        rev_opts.submodule = path;
 885        setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
 886
 887        /* save all revisions from the above list that contain b */
 888        if (prepare_revision_walk(&revs))
 889                die("revision walk setup failed");
 890        while ((commit = get_revision(&revs)) != NULL) {
 891                struct object *o = &(commit->object);
 892                if (in_merge_bases(b, commit))
 893                        add_object_array(o, NULL, &merges);
 894        }
 895        reset_revision_walk();
 896
 897        /* Now we've got all merges that contain a and b. Prune all
 898         * merges that contain another found merge and save them in
 899         * result.
 900         */
 901        for (i = 0; i < merges.nr; i++) {
 902                struct commit *m1 = (struct commit *) merges.objects[i].item;
 903
 904                contains_another = 0;
 905                for (j = 0; j < merges.nr; j++) {
 906                        struct commit *m2 = (struct commit *) merges.objects[j].item;
 907                        if (i != j && in_merge_bases(m2, m1)) {
 908                                contains_another = 1;
 909                                break;
 910                        }
 911                }
 912
 913                if (!contains_another)
 914                        add_object_array(merges.objects[i].item, NULL, result);
 915        }
 916
 917        free(merges.objects);
 918        return result->nr;
 919}
 920
 921static void print_commit(struct commit *commit)
 922{
 923        struct strbuf sb = STRBUF_INIT;
 924        struct pretty_print_context ctx = {0};
 925        ctx.date_mode = DATE_NORMAL;
 926        format_commit_message(commit, " %h: %m %s", &sb, &ctx);
 927        fprintf(stderr, "%s\n", sb.buf);
 928        strbuf_release(&sb);
 929}
 930
 931#define MERGE_WARNING(path, msg) \
 932        warning("Failed to merge submodule %s (%s)", path, msg);
 933
 934int merge_submodule(unsigned char result[20], const char *path,
 935                    const unsigned char base[20], const unsigned char a[20],
 936                    const unsigned char b[20], int search)
 937{
 938        struct commit *commit_base, *commit_a, *commit_b;
 939        int parent_count;
 940        struct object_array merges;
 941
 942        int i;
 943
 944        /* store a in result in case we fail */
 945        hashcpy(result, a);
 946
 947        /* we can not handle deletion conflicts */
 948        if (is_null_sha1(base))
 949                return 0;
 950        if (is_null_sha1(a))
 951                return 0;
 952        if (is_null_sha1(b))
 953                return 0;
 954
 955        if (add_submodule_odb(path)) {
 956                MERGE_WARNING(path, "not checked out");
 957                return 0;
 958        }
 959
 960        if (!(commit_base = lookup_commit_reference(base)) ||
 961            !(commit_a = lookup_commit_reference(a)) ||
 962            !(commit_b = lookup_commit_reference(b))) {
 963                MERGE_WARNING(path, "commits not present");
 964                return 0;
 965        }
 966
 967        /* check whether both changes are forward */
 968        if (!in_merge_bases(commit_base, commit_a) ||
 969            !in_merge_bases(commit_base, commit_b)) {
 970                MERGE_WARNING(path, "commits don't follow merge-base");
 971                return 0;
 972        }
 973
 974        /* Case #1: a is contained in b or vice versa */
 975        if (in_merge_bases(commit_a, commit_b)) {
 976                hashcpy(result, b);
 977                return 1;
 978        }
 979        if (in_merge_bases(commit_b, commit_a)) {
 980                hashcpy(result, a);
 981                return 1;
 982        }
 983
 984        /*
 985         * Case #2: There are one or more merges that contain a and b in
 986         * the submodule. If there is only one, then present it as a
 987         * suggestion to the user, but leave it marked unmerged so the
 988         * user needs to confirm the resolution.
 989         */
 990
 991        /* Skip the search if makes no sense to the calling context.  */
 992        if (!search)
 993                return 0;
 994
 995        /* find commit which merges them */
 996        parent_count = find_first_merges(&merges, path, commit_a, commit_b);
 997        switch (parent_count) {
 998        case 0:
 999                MERGE_WARNING(path, "merge following commits not found");
1000                break;
1001
1002        case 1:
1003                MERGE_WARNING(path, "not fast-forward");
1004                fprintf(stderr, "Found a possible merge resolution "
1005                                "for the submodule:\n");
1006                print_commit((struct commit *) merges.objects[0].item);
1007                fprintf(stderr,
1008                        "If this is correct simply add it to the index "
1009                        "for example\n"
1010                        "by using:\n\n"
1011                        "  git update-index --cacheinfo 160000 %s \"%s\"\n\n"
1012                        "which will accept this suggestion.\n",
1013                        sha1_to_hex(merges.objects[0].item->sha1), path);
1014                break;
1015
1016        default:
1017                MERGE_WARNING(path, "multiple merges found");
1018                for (i = 0; i < merges.nr; i++)
1019                        print_commit((struct commit *) merges.objects[i].item);
1020        }
1021
1022        free(merges.objects);
1023        return 0;
1024}
1025
1026/* Update gitfile and core.worktree setting to connect work tree and git dir */
1027void connect_work_tree_and_git_dir(const char *work_tree, const char *git_dir)
1028{
1029        struct strbuf file_name = STRBUF_INIT;
1030        struct strbuf rel_path = STRBUF_INIT;
1031        const char *real_work_tree = xstrdup(real_path(work_tree));
1032
1033        /* Update gitfile */
1034        strbuf_addf(&file_name, "%s/.git", work_tree);
1035        write_file(file_name.buf, 1, "gitdir: %s\n",
1036                   relative_path(git_dir, real_work_tree, &rel_path));
1037
1038        /* Update core.worktree setting */
1039        strbuf_reset(&file_name);
1040        strbuf_addf(&file_name, "%s/config", git_dir);
1041        if (git_config_set_in_file(file_name.buf, "core.worktree",
1042                                   relative_path(real_work_tree, git_dir,
1043                                                 &rel_path)))
1044                die(_("Could not set core.worktree in %s"),
1045                    file_name.buf);
1046
1047        strbuf_release(&file_name);
1048        strbuf_release(&rel_path);
1049        free((void *)real_work_tree);
1050}