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