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