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