Example usage for org.eclipse.jgit.lib Repository getWorkTree

List of usage examples for org.eclipse.jgit.lib Repository getWorkTree

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository getWorkTree.

Prototype

@NonNull
public File getWorkTree() throws NoWorkTreeException 

Source Link

Document

Get the root directory of the working tree, where files are checked out for viewing and editing.

Usage

From source file:io.fabric8.maven.rt.BaseBoosterIT.java

License:Apache License

private void modifyPomFileToProjectVersion(Repository aRepository, String relativePomPath)
        throws IOException, XmlPullParserException {
    /**// w w  w  . j  a v  a 2s  .c o  m
     * Read Maven model from the project pom file(Here the pom file is not the test repository is cloned
     * for the test suite. It refers to the rt/ project and fetches the current version of fabric8-maven-plugin
     * (any SNAPSHOT version) and updates that accordingly in the sample cloned project's pom.
     */
    File clonedRepositoryPomFile = new File(aRepository.getWorkTree().getAbsolutePath(), relativePomPath);
    String fmpCurrentVersion = readPomModelFromFile(new File("pom.xml")).getVersion();
    Model model = readPomModelFromFile(clonedRepositoryPomFile);
    testsuiteRepositoryArtifactId = model.getArtifactId();

    // Check if fmp is not present in openshift profile
    model = updatePomIfFmpNotPresent(model, clonedRepositoryPomFile);
    Build build = model.getBuild();

    /*
     * Handle the scenarios where build is in outermost scope or present
     * specifically in openshift profile.
     */
    List<Profile> profiles = model.getProfiles();
    if (build != null
            && build.getPluginsAsMap().get(fabric8PluginGroupId + ":" + fabric8PluginArtifactId) != null) {
        build.getPluginsAsMap().get(fabric8PluginGroupId + ":" + fabric8PluginArtifactId)
                .setVersion(fmpCurrentVersion);
    } else {
        for (Profile profile : profiles) {
            if (profile.getBuild() != null && profile.getBuild().getPluginsAsMap()
                    .get(fabric8PluginGroupId + ":" + fabric8PluginArtifactId) != null) {
                profile.getBuild().getPluginsAsMap().get(fabric8PluginGroupId + ":" + fabric8PluginArtifactId)
                        .setVersion(fmpCurrentVersion);
            }
        }
    }

    // Write back the updated model to the pom file
    writePomModelToFile(clonedRepositoryPomFile, model);
}

From source file:io.fabric8.maven.rt.BaseBoosterIT.java

License:Apache License

protected void updateSourceCode(Repository repository, String relativePomPath)
        throws XmlPullParserException, IOException {
    MavenXpp3Reader reader = new MavenXpp3Reader();
    String baseDir = repository.getWorkTree().getAbsolutePath();
    Model model = reader.read(new FileInputStream(new File(baseDir, relativePomPath)));

    Dependency dependency = new Dependency();
    dependency.setGroupId("org.apache.commons");
    dependency.setArtifactId("commons-lang3");
    dependency.setVersion("3.5");
    model.getDependencies().add(dependency);

    MavenXpp3Writer writer = new MavenXpp3Writer();
    writer.write(new FileOutputStream(new File(baseDir, relativePomPath)), model);
    model.getArtifactId();//w w w  .j a v  a 2 s  .  co m
}

From source file:io.fabric8.maven.rt.BaseBoosterIT.java

License:Apache License

protected void runEmbeddedMavenBuild(Repository sampleRepository, String goals, String profiles) {
    String baseDir = sampleRepository.getWorkTree().getAbsolutePath();
    EmbeddedMaven.forProject(baseDir + "/pom.xml").setGoals(goals).setQuiet(true).setProfiles(profiles).build();
}

From source file:io.fabric8.maven.rt.BaseBoosterIT.java

License:Apache License

/**
 * Appends some annotation properties to the fmp's configuration in test repository's pom
 * just to distinguish whether the application is re-deployed or not.
 *
 * @param testRepository//from  w w w .  ja  v a2s .co m
 * @throws Exception
 */
protected void addRedeploymentAnnotations(Repository testRepository, String relativePomPath,
        String annotationKey, String annotationValue, String fmpConfigFragmentFile)
        throws IOException, XmlPullParserException {
    File pomFile = new File(testRepository.getWorkTree().getAbsolutePath(), relativePomPath);
    Model model = readPomModelFromFile(pomFile);

    File pomFragment = new File(getClass().getResource(fmpConfigFragmentFile).getFile());
    String pomFragmentStr = String.format(FileUtils.readFileToString(pomFragment), annotationKey,
            annotationValue, annotationKey, annotationValue);

    Xpp3Dom configurationDom = Xpp3DomBuilder.build(new ByteArrayInputStream(pomFragmentStr.getBytes()),
            "UTF-8");

    int nOpenShiftProfile = getProfileIndexUsingFmp(model, fabric8MavenPluginKey);
    model.getProfiles().get(nOpenShiftProfile).getBuild().getPluginsAsMap().get(fabric8MavenPluginKey)
            .setConfiguration(configurationDom);
    writePomModelToFile(pomFile, model);
}

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

License:Open Source License

/**
 * Create a text file stating the repository name and commit it. This creates a
 * root commit for history so that we can actually wield the repo.
 *
 * @param releaserepo//from   w  w w  .  j  av  a2s .  co m
 */
void makeReleaseRepoFoundingCommit(Repository releaserepo) {
    // write readme file
    try {
        IOForge.saveFile("This is the releases repo for " + name + ".\n",
                new File(path, "README").getCanonicalFile());
    } catch (IOException e) {
        throw new MdmRepositoryIOException("create a release repo", true, path, e);
    }

    // add and commit
    String currentAction = "commit into the new releases repo";
    try {
        new Git(releaserepo).add().addFilepattern("README").call();
    } catch (NoFilepatternException e) {
        throw new MajorBug(e); // why would an api throw exceptions like this *checked*?
    } catch (GitAPIException e) {
        throw new MdmUnrecognizedError(e);
    }
    try {
        new Git(releaserepo).commit().setOnly("README").setMessage("initialize releases repo for " + name + ".")
                .call();
    } catch (NoHeadException e) {
        throw new MdmConcurrentException(
                new MdmRepositoryStateException(currentAction, releaserepo.getWorkTree().toString(), e));
    } catch (WrongRepositoryStateException e) {
        throw new MdmConcurrentException(
                new MdmRepositoryStateException(currentAction, releaserepo.getWorkTree().toString(), e));
    } catch (UnmergedPathsException e) {
        throw new MdmConcurrentException(
                new MdmRepositoryStateException(currentAction, releaserepo.getWorkTree().toString(), e));
    } catch (ConcurrentRefUpdateException e) {
        throw new MdmConcurrentException(e);
    } catch (NoMessageException e) {
        throw new MajorBug(e); // why would an api throw exceptions like this *checked*?
    } catch (GitAPIException e) {
        throw new MdmUnrecognizedError(e);
    }
}

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

License:Open Source License

/**
 * Label the current commit (which in context is the root commit) with the
 * 'mdm/init' branch./*from   w ww .  ja  va 2 s .  c  o m*/
 *
 * This branch has two roles; firstly, it is the metadata that is considered the
 * official declaration of this repo as a valid mdm releases repo; secondly, when
 * mdm is fetching a dependency, this essentially empty branch is used as a safe
 * default for the remote.origin.fetch configuration of the submodule.
 *
 * @param releaserepo
 */
void makeReleaseRepoInitBranch(Repository releaserepo) {
    String currentAction = "create branches in the new releases repo";
    try {
        new Git(releaserepo).branchCreate().setName("mdm/init").call();
    } catch (RefAlreadyExistsException e) {
        throw new MdmConcurrentException(
                new MdmRepositoryStateException(currentAction, releaserepo.getWorkTree().toString(), e));
    } catch (RefNotFoundException e) {
        throw new MdmConcurrentException(
                new MdmRepositoryStateException(currentAction, releaserepo.getWorkTree().toString(), e));
    } catch (InvalidRefNameException e) {
        throw new MajorBug(e); // branch name is fixed at compile time here and is quite valid, thanks
    } catch (GitAPIException e) {
        throw new MdmUnrecognizedError(e);
    }
}

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

License:Open Source License

/**
 * Writes a new submodule block to the parentRepo's .gitmodules file declaring the
 * release repo, and initializes the local .git/config file to match.
 *
 * @param parentRepo/*from w  w  w .j  a  v  a  2s.  co  m*/
 * @throws IOException
 * @throws ConfigInvalidException
 */
void writeParentGitmoduleConfig(Repository parentRepo) throws IOException, ConfigInvalidException {
    // write gitmodule config for the new submodule
    StoredConfig gitmodulesCfg = new FileBasedConfig(
            new File(parentRepo.getWorkTree(), Constants.DOT_GIT_MODULES), parentRepo.getFS());
    gitmodulesCfg.load();
    gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_PATH,
            path);
    gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_URL,
            remotePublicUrl);
    gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path,
            MdmConfigConstants.Module.MODULE_TYPE.toString(), MdmModuleType.RELEASES.toString());
    gitmodulesCfg.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_UPDATE,
            "none");
    gitmodulesCfg.save();

    // initialize local parent repo config for the submodule
    MdmModuleRelease module = MdmModuleRelease.load(parentRepo, path, gitmodulesCfg);
    Plumbing.initLocalConfig(parentRepo, module);
    parentRepo.getConfig().save();
}

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

License:Open Source License

/**
 * Commits the release repo path and the gitmodules file.
 *
 * @param repo/*from ww w  .  ja va  2  s . c  o m*/
 * @throws MdmRepositoryStateException
 * @throws NoWorkTreeException
 */
void makeParentRepoLinkCommit(Repository repo) throws MdmRepositoryStateException {
    String currentAction = "commit a link to the new releases repo into the parent repo";
    try {
        new Git(repo).add().addFilepattern(path).addFilepattern(Constants.DOT_GIT_MODULES).call();
    } catch (NoFilepatternException e) {
        throw new MajorBug(e); // why would an api throw exceptions like this *checked*?
    } catch (GitAPIException e) {
        throw new MdmUnrecognizedError(e);
    }
    try {
        new Git(repo).commit().setOnly(path).setOnly(Constants.DOT_GIT_MODULES)
                .setMessage("initialize releases repo for " + name + ".").call();
    } catch (NoHeadException e) {
        throw new MdmRepositoryStateException(currentAction, repo.getWorkTree().toString(), e);
    } catch (UnmergedPathsException e) {
        throw new MdmRepositoryStateException(currentAction, repo.getWorkTree().toString(), e);
    } catch (WrongRepositoryStateException e) {
        throw new MdmRepositoryStateException(currentAction, repo.getWorkTree().toString(), e);
    } catch (ConcurrentRefUpdateException e) {
        throw new MdmConcurrentException(e);
    } catch (NoMessageException e) {
        throw new MajorBug(e); // why would an api throw exceptions like this *checked*?
    } catch (GitAPIException e) {
        throw new MdmUnrecognizedError(e);
    }
}

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

License:Open Source License

/**
 * @param repo/*from w  ww  .  j a  v a  2s . co m*/
 *                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();//from www .j a v a  2 s .  c  o  m

    /*
     * 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;
        }
    }
}