Example usage for org.eclipse.jgit.submodule SubmoduleWalk forIndex

List of usage examples for org.eclipse.jgit.submodule SubmoduleWalk forIndex

Introduction

In this page you can find the example usage for org.eclipse.jgit.submodule SubmoduleWalk forIndex.

Prototype

public static SubmoduleWalk forIndex(Repository repository) throws IOException 

Source Link

Document

Create a generator to walk over the submodule entries currently in the index The .gitmodules file is read from the index.

Usage

From source file:com.bacoder.scmtools.git.internal.CloneAndProcessCommand.java

License:Apache License

@Override
protected void cloneSubmodules(Repository repository) throws IOException, GitAPIException {
    SubmoduleWalk generator;//from ww w  . j  av  a 2s .  c  om
    if (isInMemory()) {
        generator = new InMemorySubmoduleWalk(repository, submodulesConfig);
        try {
            DirCache index = repository.readDirCache();
            generator.setTree(new DirCacheIterator(index));
        } catch (IOException e) {
            generator.release();
            throw e;
        }
    } else {
        generator = SubmoduleWalk.forIndex(repository);
    }

    try {
        while (generator.next()) {
            if (generator.getConfigUrl() != null) {
                continue;
            }

            String path = generator.getPath();
            String url = generator.getRemoteUrl();

            CloneAndProcessCommand command = new CloneAndProcessCommand(path, config).setProcessor(processor);
            command.setURI(url).setCloneSubmodules(true);
            command.call();
        }
    } catch (ConfigInvalidException e) {
        throw new IOException("Config invalid", e);
    }
}

From source file:jbyoshi.gitupdate.GitUpdate.java

License:Apache License

private static void update(Repository repo, Task root) {
    File dir = repo.getDirectory();
    if (dir.getName().equals(Constants.DOT_GIT)) {
        dir = dir.getParentFile();/*from  www  .  j av a  2 s . com*/
    }
    try {
        dir = dir.toPath().toRealPath().toFile();
    } catch (IOException e) {
        dir = dir.toPath().normalize().toFile();
    }
    if (!updated.add(dir)) {
        return;
    }

    List<String> failures = new ArrayList<>();

    try {
        if (SubmoduleWalk.containsGitModulesFile(repo)) {
            try (SubmoduleWalk submodules = SubmoduleWalk.forIndex(repo)) {
                while (submodules.next()) {
                    if (submodules.getRepository() == null) {
                        failures.add("Submodule " + submodules.getDirectory().getName() + " - does not exist");
                    } else {
                        update(submodules.getRepository(), root);
                    }
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    Task repoTask = root.newChild(dir.getName());
    for (String error : failures) {
        repoTask.report.newChild(error).error();
    }

    try (Git git = Git.wrap(repo)) {
        for (Processor processor : processors) {
            try {
                processor.registerTasks(repo, git, repoTask);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:net.polydawn.mdm.commands.MdmAddCommand.java

License:Open Source License

public MdmExitMessage call() throws ConfigInvalidException, IOException, MdmException {
    assertInRepoRoot();//from   ww  w  .  jav  a2  s  . c om

    // load other config (so we can error early on in case there's a problem)
    StoredConfig gitmodulesCfg = new FileBasedConfig(new File(repo.getWorkTree(), Constants.DOT_GIT_MODULES),
            repo.getFS());
    try {
        gitmodulesCfg.load();
    } catch (ConfigInvalidException e) {
        throw new MdmExitInvalidConfig(Constants.DOT_GIT_MODULES);
    }

    // git's behavior of assuming relative urls should be relative to the remote origin instead of relative to the local filesystem is almost certainly not what you want.
    if (url.startsWith("../") || url.startsWith("./"))
        os.println(
                "hey, heads up: when you use a relative url to describe a submodule location, git assumes it's relative to the remote origin of the parent project (NOT relative to the project location on the local filesystem, which is what you might have expected).  this... works, but it's not recommended because of the potential it has to surprise.");

    // give a look at the remote url and see what versions are physically available.
    List<String> versions = fetchVersions();
    if (versions.size() == 0)
        throw new MdmExitMessage(":(",
                "no releases could be found at the url you gave for a releases repository -- it doesn't look like releases that mdm understands are there.\nare you sure this is the releases repo?  keep in mind that the release repo and the source repo isn't the same for most projects -- check the project readme for the location of their release repo.");

    // if we didn't get a name argument yet, prompt for one.
    // note that this is *after* we tried to check that something at least exists on the far side of the url, in order to minimize bother.
    if (name == null)
        name = inputPrompt(os, "dependency name: ");

    File path = new File(pathLibs, name);

    // check for presence of other crap here already.  (`git submodule add` will also do this, but it's a more pleasant user experience to check this before popping up a prompt for version name.)
    if (path.exists())
        throw new MdmExitMessage(":'(", "there are already files at " + path
                + " !\nWe can't pull down a dependency there until this conflict is cleared away.");
    if (SubmoduleWalk.forIndex(repo).setFilter(PathFilter.create(path.getPath())).next())
        throw new MdmExitMessage(":'(", "there is already a submodule in the git index at " + path
                + " !\nWe can't pull down a dependency there until this conflict is cleared away.");

    // if a specific version name was given, we'll just go straight at it; otherwise we present options interactively from the manifest of versions the remote reported.
    if (version == null)
        version = Loco.promptForVersion(os, versions);

    // check yourself before you wreck yourself
    if (!versions.contains(version))
        throw new MdmExitMessage(":(",
                "no version labelled " + version + " available from the provided remote url.");

    // finally, let's actually do the submodule/dependency adding
    doSubmoduleConfig(gitmodulesCfg, path);
    gitmodulesCfg.save();
    doSubmoduleFetch(path, gitmodulesCfg);

    // commit the changes
    doGitStage(path);
    doGitCommit(path);

    return new MdmExitMessage(":D", "added dependency on " + name + "-" + version + " successfully!");
}

From source file:net.polydawn.mdm.commands.MdmReleaseInitCommand.java

License:Open Source License

/**
 * Check that the releases area free of clutter.
 *
 * @throws MdmExitMessage/*w w w  .j av a 2s.c  o  m*/
 *                 if the location intended for the release repo is not empty or
 *                 if there are other submodules in the git index for that
 *                 location.
 */
void assertReleaseRepoAreaClean() throws IOException {
    File pathFile = new File(path).getCanonicalFile();
    if (asSubmodule && SubmoduleWalk.forIndex(repo).setFilter(PathFilter.create(path)).next())
        throw new MdmExitMessage(":I", "there's already a releases module!  No changes made.");
    if (pathFile.exists() && !pathFile.isDirectory() || new File(pathFile, ".git").exists())
        throw new MdmExitMessage(":(",
                "something already exists at the location we want to initialize the releases repo.  clear it out and try again.");
}

From source file:net.polydawn.mdm.MdmModule.java

License:Open Source License

/**
 * @param repo//from w  w w  .ja va 2  s. c om
 *                required.
 *
 *                well, unless you're about to create one, in which case not even.
 * @param handle
 *                required.
 * @param parent
 *                null if repository stands alone, otherwise if we are a submodule
 *                required.
 * @param gitmodulesCfg
 *                ignored if parent null, otherwise required.
 * @param indexId
 *                ignored if parent null, otherwise will be automatically loaded
 *                if not provided.
 *
 *                the commit hash known to the parent repo index for this
 *                submodule (or null if it's not handy; we'll load it in that
 *                case).
 *
 * @throws MdmModuleTypeException
 *                 if the {@code gitmodulesCfg} entries for {@code handle} don't
 *                 concur with the {@code type} expected.
 * @throws MdmRepositoryIOException
 *                 if disks reject our advances
 */
protected MdmModule(Repository repo, String handle, Repository parent, Config gitmodulesCfg, ObjectId indexId)
        throws MdmRepositoryIOException, MdmModuleTypeException {
    handle = (File.separatorChar != '/') ? handle.replace(File.separatorChar, '/') : handle;
    this.handle = handle;
    this.repo = repo;

    if (repo == null) {
        this.headId = null;
        this.dirtyFiles = false;
    } else {
        try {
            this.headId = repo.resolve(Constants.HEAD);
        } catch (IOException e) {
            throw new MdmRepositoryIOException(false, handle, e);
        }

        boolean dirtyFiles;
        try {
            dirtyFiles = !new Git(repo).status().call().isClean();
        } catch (NoWorkTreeException e) {
            throw new RuntimeException("wat", e);
        } catch (GitAPIException e) {
            dirtyFiles = false;
        }
        this.dirtyFiles = dirtyFiles;
    }

    if (parent != null) {
        // sanity check the expected module type if we're a submodule (if we're not a submodule, we can't make any such check since there's no gitmodules file to refer to).
        MdmModuleType type = getType();
        MdmModuleType type_configured = MdmModuleType
                .fromString(gitmodulesCfg.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle,
                        MdmConfigConstants.Module.MODULE_TYPE.toString()));
        if (type == null)
            throw new MdmModuleTypeException("expected module of type " + type + " for repository " + handle
                    + ", but gitmodules file has no known type for this module.");
        if (type != type_configured)
            throw new MdmModuleTypeException("expected module of type " + type + " for repository " + handle
                    + ", but gitmodules file states this is a " + type_configured + " module.");

        // load real path from gitmodule config (probably same as handle, but theoretically allowed to be different)
        String path = gitmodulesCfg.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle,
                ConfigConstants.CONFIG_KEY_PATH);
        this.path = (File.separatorChar != '/') ? path.replace(File.separatorChar, '/') : path;

        // load remote urls
        this.urlHistoric = gitmodulesCfg.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle,
                ConfigConstants.CONFIG_KEY_URL);
        this.urlLocal = parent.getConfig().getString(ConfigConstants.CONFIG_SUBMODULE_SECTION, handle,
                ConfigConstants.CONFIG_KEY_URL);

        // load indexId the parent expects the submodule to be at (if not already provided)
        if (indexId != null)
            this.indexId = indexId;
        else
            try {
                SubmoduleWalk generator = SubmoduleWalk.forIndex(parent).setFilter(PathFilter.create(path));
                this.indexId = generator.next() ? generator.getObjectId() : null;
            } catch (IOException e) {
                throw new MdmRepositoryIOException(false, parent.getWorkTree().getPath(), e);
            }

        // review the submodule and summarize a status.
        SubmoduleStatusType statusType;
        if (path == null)
            // jgit report SubmoduleStatusType.MISSING if no path in .gitmodules file, but I don't even want to deal with that.
            throw new MdmModuleTypeException("no path for module " + handle + " listed in gitmodules file.");
        else if (urlLocal == null)
            // Report uninitialized if no URL in config file
            statusType = SubmoduleStatusType.UNINITIALIZED;
        else if (repo == null)
            // Report uninitialized if no submodule repository
            statusType = SubmoduleStatusType.UNINITIALIZED;
        else if (headId == null)
            // Report uninitialized if no HEAD commit in submodule repository
            statusType = SubmoduleStatusType.UNINITIALIZED;
        else if (!headId.equals(indexId))
            // Report checked out if HEAD commit is different than index commit
            statusType = SubmoduleStatusType.REV_CHECKED_OUT;
        else
            // Report initialized if HEAD commit is the same as the index commit
            statusType = SubmoduleStatusType.INITIALIZED;
        this.status = new SubmoduleStatus(statusType, path, indexId, headId);
    } else {
        this.path = handle;
        this.indexId = null;
        this.urlHistoric = null;
        this.urlLocal = null;
        this.status = null;
    }
}

From source file:net.polydawn.mdm.MdmModuleSet.java

License:Open Source License

public MdmModuleSet(Repository repo) throws IOException, ConfigInvalidException {
    gitmodulesCfg = new FileBasedConfig(new File(repo.getWorkTree(), Constants.DOT_GIT_MODULES), repo.getFS());
    gitmodulesCfg.load();//  www .j  av  a  2 s  . com

    /*
     * To maximize similarity with how the `git submodule` command behaves, we treat the SubmoduleWalk as canonical and the content of the .gitmodules file as tertiary.
     * However, that may change.  There's a lot about MdmModule that doesn't work without a .gitmodules entry anyway, so if it's faster to start from that list, we might as well.
     */

    SubmoduleWalk mw = new SubmoduleWalk(repo);
    mw.setModulesConfig(gitmodulesCfg);

    SubmoduleWalk generator = SubmoduleWalk.forIndex(repo);
    while (generator.next()) {
        try {
            // get the handle.  which we presume to be rather like the path, but git config always uses forward slashes.
            // (the MdmModule constructor will also enforce this, but here we have to walk config ourselves before we get that far.)
            String handle = (File.separatorChar != '/') ? generator.getPath().replace(File.separatorChar, '/')
                    : generator.getPath();

            // get submodule.[handle].mdm config value from gitmodules config file
            String type_configured_string = gitmodulesCfg.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION,
                    handle, MdmConfigConstants.Module.MODULE_TYPE.toString());
            MdmModuleType type_configured = MdmModuleType.fromString(type_configured_string);

            // if the submodule.[handle].mdm config value was unrecognized or missing, ignore; it's not ours.
            if (type_configured == null)
                continue;

            // load whichever type of mdm module it is
            switch (type_configured) {
            case DEPENDENCY:
                MdmModuleDependency modDep = MdmModuleDependency.load(repo, generator, gitmodulesCfg);
                dependencyModules.put(modDep.getHandle(), modDep);
                allModules.put(modDep.getHandle(), modDep);
                break;
            case RELEASES:
                MdmModuleRelease modRel = MdmModuleRelease.load(repo, generator, gitmodulesCfg);
                releasesModules.put(modRel.getHandle(), modRel);
                allModules.put(modRel.getHandle(), modRel);
                break;
            }
        } catch (MdmModuleTypeException e) {
            throw new MajorBug(e);
        } catch (MdmRepositoryNonexistant e) {
            throw e;
        } catch (MdmRepositoryIOException e) {
            throw e;
        }
    }
}

From source file:net.polydawn.mdm.Plumbing.java

License:Open Source License

public static boolean isCommitedGitlink(Repository repo, String path) throws IOException {
    return SubmoduleWalk.forIndex(repo).setFilter(PathFilter.create(path)).next();
}

From source file:org.eclipse.egit.ui.internal.staging.StagingViewContentProvider.java

License:Open Source License

public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
    if (!(newInput instanceof StagingViewUpdate))
        return;//www  . j  a v a  2  s  . co m

    StagingViewUpdate update = (StagingViewUpdate) newInput;

    if (update.repository == null || update.indexDiff == null) {
        content = new StagingEntry[0];
        return;
    }

    Set<StagingEntry> nodes = new TreeSet<StagingEntry>(new Comparator<StagingEntry>() {
        public int compare(StagingEntry o1, StagingEntry o2) {
            return o1.getPath().compareTo(o2.getPath());
        }
    });

    if (update.changedResources != null && !update.changedResources.isEmpty()) {
        nodes.addAll(Arrays.asList(content));
        for (String res : update.changedResources)
            for (StagingEntry entry : content)
                if (entry.getPath().equals(res))
                    nodes.remove(entry);
    }

    final IndexDiffData indexDiff = update.indexDiff;
    final Repository repository = update.repository;
    if (isWorkspace) {
        for (String file : indexDiff.getMissing())
            nodes.add(new StagingEntry(repository, MISSING, file));
        for (String file : indexDiff.getModified())
            if (indexDiff.getChanged().contains(file))
                nodes.add(new StagingEntry(repository, PARTIALLY_MODIFIED, file));
            else
                nodes.add(new StagingEntry(repository, MODIFIED, file));
        for (String file : indexDiff.getUntracked())
            nodes.add(new StagingEntry(repository, UNTRACKED, file));
        for (String file : indexDiff.getConflicting())
            nodes.add(new StagingEntry(repository, CONFLICTING, file));
    } else {
        for (String file : indexDiff.getAdded())
            nodes.add(new StagingEntry(repository, ADDED, file));
        for (String file : indexDiff.getChanged())
            nodes.add(new StagingEntry(repository, CHANGED, file));
        for (String file : indexDiff.getRemoved())
            nodes.add(new StagingEntry(repository, REMOVED, file));
    }

    try {
        SubmoduleWalk walk = SubmoduleWalk.forIndex(repository);
        while (walk.next())
            for (StagingEntry entry : nodes)
                entry.setSubmodule(entry.getPath().equals(walk.getPath()));
    } catch (IOException e) {
        Activator.error(UIText.StagingViewContentProvider_SubmoduleError, e);
    }

    content = nodes.toArray(new StagingEntry[nodes.size()]);
}

From source file:org.gradle.vcs.fixtures.GitFileRepository.java

License:Apache License

/**
 * Updates any submodules in this repository to the latest in the submodule origin repository
 *//*  ww  w  . j a  v  a  2 s  .c o m*/
public RevCommit updateSubmodulesToLatest() throws GitAPIException {
    List<String> submodulePaths = Lists.newArrayList();
    try {
        SubmoduleWalk walker = SubmoduleWalk.forIndex(git.getRepository());
        try {
            while (walker.next()) {
                Repository submodule = walker.getRepository();
                try {
                    submodulePaths.add(walker.getPath());
                    Git.wrap(submodule).pull().call();
                } finally {
                    submodule.close();
                }
            }
        } finally {
            walker.close();
        }
        return commit("update submodules", submodulePaths.toArray(new String[submodulePaths.size()]));
    } catch (IOException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}

From source file:org.gradle.vcs.git.internal.GitVersionControlSystem.java

License:Apache License

private static void updateSubModules(Git git) throws IOException, GitAPIException {
    SubmoduleWalk walker = SubmoduleWalk.forIndex(git.getRepository());
    try {/*from  ww w.j  a v  a  2  s  . co  m*/
        while (walker.next()) {
            Repository submodule = walker.getRepository();
            try {
                Git submoduleGit = Git.wrap(submodule);
                submoduleGit.fetch().call();
                git.submoduleUpdate().addPath(walker.getPath()).call();
                submoduleGit.reset().setMode(ResetCommand.ResetType.HARD).call();
                updateSubModules(submoduleGit);
            } finally {
                submodule.close();
            }
        }
    } finally {
        walker.close();
    }
}