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