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