Example usage for org.eclipse.jgit.api Git getRepository

List of usage examples for org.eclipse.jgit.api Git getRepository

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git getRepository.

Prototype

public Repository getRepository() 

Source Link

Document

Get repository

Usage

From source file:eu.mihosoft.vrl.io.VersionedFile.java

License:Open Source License

/**
 * Returns a list containing the paths to all files in the specified
 * version.//ww  w .  j  a  va2s  .co  m
 *
 * @param c version identifier (commit)
 * @return a list containing the paths to all files in the specified version
 * @throws IllegalStateException if this file is currently not open
 */
private Collection<String> getFilesInVersion(RevCommit c) {

    Collection<String> result = new ArrayList<String>();

    // file has to be opened
    if (!isOpened()) {
        throw new IllegalStateException("File\"" + getFile().getPath() + "\" not opened!");
    }

    Git git = null;

    try {
        git = Git.open(tmpFolder);
        // create a tree walk to search for files
        TreeWalk walk = new TreeWalk(git.getRepository());
        if (walk != null) {

            // recursively search fo files
            walk.setRecursive(true);
            // add the tree the specified commit belongs to
            walk.addTree(c.getTree());

            // walk through the tree
            while (walk.next()) {

                // TODO: is it a problem if mode is treemode?
                final FileMode mode = walk.getFileMode(0);
                if (mode == FileMode.TREE) {
                    System.out.print("VersionedFile." + "getFilesInVersion(): FileMode unexpected!");
                }

                // retrieve the path name of the current element
                String fileName = walk.getPathString();

                // we do not want to commit/checkout this file
                if (!fileName.equals(FILE_INFO_NAME)) {
                    result.add(walk.getPathString());
                }
            }
        }

    } catch (IOException ex) {
        closeGit(git);
        Logger.getLogger(VersionedFile.class.getName()).log(Level.SEVERE, null, ex);
    }

    closeGit(git);

    return result;

}

From source file:eu.mihosoft.vrl.io.VersionedFile.java

License:Open Source License

/**
 * Checks out all files in the specified version.
 *
 * @param c version identifier (commit)//from  w w  w.j a  v  a 2  s . c o  m
 * @throws IllegalStateException if this file is currently not open
 */
private void checkoutFilesInVersion(RevCommit c) {

    // file has to be opened
    if (!isOpened()) {
        throw new IllegalStateException("File\"" + getFile().getPath() + "\" not opened!");
    }

    System.out.println(">>> commit-id (SHA-1): " + c.getName());

    Git git = null;

    TreeWalk walk = null;

    try {

        git = Git.open(tmpFolder);

        // create a tree walk to search for files.
        walk = new TreeWalk(git.getRepository());
        if (walk != null) {
            // recursively search fo files
            walk.setRecursive(true);
            // add the tree the specified commit belongs to
            walk.addTree(c.getTree());

            while (walk.next()) {

                // TODO: is it a problem if mode is treemode?
                final FileMode mode = walk.getFileMode(0);
                if (mode == FileMode.TREE) {
                    System.out.print('0');
                }

                String fileName = walk.getPathString();

                if (!fileName.equals(FILE_INFO_NAME)) {
                    // checks out the current file
                    checkoutFile(fileName, walk.getObjectId(0));
                }
            }
        }

    } catch (IOException ex) {
        closeGit(git);
        Logger.getLogger(VersionedFile.class.getName()).log(Level.SEVERE, null, ex);
    }

    closeGit(git);
}

From source file:eu.mihosoft.vrl.io.VersionedFile.java

License:Open Source License

/**
 * Checks out the specified file (it is necessary to specifiy the file name
 * and the object id).//w  w  w.ja va 2 s  . co m
 *
 * @param fileName file name (path relative to content dir)
 * @param id object id of this file
 * @throws IOException
 * @throws IllegalStateException if this file is currently not open
 */
private void checkoutFile(String fileName, ObjectId id) throws IOException {

    // file has to be opened
    if (!isOpened()) {
        throw new IllegalStateException("File\"" + getFile().getPath() + "\" not opened!");
    }

    System.out.println(">>> checkout file: " + fileName);

    // file that shall be checked out
    File checkoutFile = new File(tmpFolder.getAbsolutePath() + "/" + fileName);

    // the parent directory of the file to be checked out
    File parentDirectory = checkoutFile.getParentFile();

    // create the parent directory if it is not the content directory to
    // allow the output stream to save the file there
    if (parentDirectory != null && !parentDirectory.equals(tmpFolder)) {
        parentDirectory.mkdirs();
    }

    BufferedOutputStream out = null;

    Git git = null;

    try {

        git = Git.open(tmpFolder);

        // checkout the file via an object loader
        ObjectLoader loader = git.getRepository().open(id);
        out = new BufferedOutputStream(new FileOutputStream(checkoutFile));

        loader.copyTo(out);

        closeGit(git);

    } catch (IOException ex) {
        closeGit(git);
        Logger.getLogger(VersionedFile.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        closeGit(git);
        // we are responsible to close the stream
        if (out != null) {
            out.close();
        }
    }
}

From source file:eu.mihosoft.vrl.io.VersionedFile.java

License:Open Source License

/**
 * Returns a list containing commit objects of all versions. This method can
 * be used to show the version messages, e.g., for creating a ui that does
 * allow the selection of the version that shall be checked out.
 *
 * @return a list containing commit objects of all versions
 * @throws IOException/* w w w .  j  a va 2s  .c  o  m*/
 * @throws IllegalStateException if this file is currently not open
 */
@Override
public ArrayList<RevCommit> getVersions() throws IOException {

    // use cached results if possible
    if (commits != null) {
        return commits;
    }

    // file has to be opened
    if (!isOpened()) {
        throw new IllegalStateException("File\"" + getFile().getPath() + "\" not opened!");
    }

    RevWalk walk = null;

    Git git = null;

    try {

        // open the git repository
        git = Git.open(tmpFolder);
        walk = new RevWalk(git.getRepository());

        // retrieve the object id of the current HEAD version
        // (latest/youngest version)
        ObjectId headId = git.getRepository().resolve(Constants.HEAD);

        // tell the walk to start from HEAD
        walk.markStart(walk.parseCommit(headId));

        // change sorting order
        walk.sort(RevSort.TOPO, true);
        walk.sort(RevSort.REVERSE, true);

        commits = new ArrayList<RevCommit>();

        // walk through all versions and add them to the list
        for (RevCommit commit : walk) {
            commits.add(commit);
        }

        closeGit(git);

    } catch (IOException ex) {
        throw new IOException("Git exception", ex);
    } finally {
        closeGit(git);
        // we are responsible for disposing the walk object
        if (walk != null) {
            walk.dispose();
        }
    }

    return commits;
}

From source file:eu.mihosoft.vrl.io.VersionedFile.java

License:Open Source License

/**
 * Initializes git repository./*from   w ww . java2s  . c  o  m*/
 *
 * <p><b>Warning:</b> Be careful when calling this method. It will destroy
 * any existing repository!</p>
 *
 * @throws IOException
 */
private void initGit() throws IOException {

    File repoFile = new File(tmpFolder.getAbsolutePath() + "/.git");

    // delete existing repository
    if (repoFile.exists()) {
        IOUtil.deleteDirectory(repoFile);
    }

    Git git = null;

    try {
        // initialize git repository
        Git.init().setDirectory(tmpFolder).call();
        git = Git.open(tmpFolder);
        git.add().addFilepattern(".").call();
        // perform initial commit
        git.commit().setMessage("initial commit").setAuthor("VRL-User", "").call();

        git.getRepository().close();

    } catch (NoHeadException ex) {
        throw new IOException("Git exception", ex);
    } catch (NoMessageException ex) {
        throw new IOException("Git exception", ex);
    } catch (UnmergedPathException ex) {
        throw new IOException("Git exception", ex);
    } catch (ConcurrentRefUpdateException ex) {
        throw new IOException("Git exception", ex);
    } catch (JGitInternalException ex) {
        throw new IOException("Git exception", ex);
    } catch (WrongRepositoryStateException ex) {
        throw new IOException("Git exception", ex);
    } catch (NoFilepatternException ex) {
        throw new IOException("Git exception", ex);
    } catch (IOException ex) {
        throw new IOException("Git exception", ex);
    } finally {
        if (git != null) {
            git.getRepository().close();
        }
    }
}

From source file:ezbake.deployer.publishers.openShift.RhcApplication.java

License:Apache License

/**
 * Sets the git repository object.  Probably not useful but here for Java Bean completeness
 *
 * @param gitRepo - git repository to set it to
 *//*from  w ww.  j  av a  2s  .  co m*/
public void setGitRepo(Git gitRepo) throws DeploymentException {
    this.gitRepo = gitRepo;

    try {
        StoredConfig config = gitRepo.getRepository().getConfig();
        config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_FILEMODE, true);
        config.save();
    } catch (IOException e) {
        log.error("There was an error saving the  git configuration to disk", e);
        throw new DeploymentException("Could not save git configuration: " + e.getMessage());
    }
}

From source file:facade.GitFacade.java

static String getRepoName(Git git) throws IOException {
    String[] directoryPieces = git.getRepository().getDirectory().toString().split("\\\\");
    String name = directoryPieces[directoryPieces.length - 2];
    return name + " [" + git.getRepository().getBranch() + "]";

}

From source file:fr.duminy.tools.jgit.JGitToolbox.java

License:Open Source License

public String track(Parameters parameters) throws GitToolboxException {
    try {/*w  w w.ja v  a2s  .c  o m*/
        Git targetGit = Git.open(parameters.getGitDirectory());
        ProgressMonitor progressMonitor = new TextProgressMonitor();
        PullCommand pullCommand = targetGit.pull().setProgressMonitor(progressMonitor);
        PullResult result = pullCommand.call();
        System.out.println(result);
        if (!result.isSuccessful()) {
            throw new GitToolboxException("Failed to update tracking branch : " + result.toString());
        }

        MergeResult.MergeStatus mergeStatus = result.getMergeResult().getMergeStatus();
        if (!ALREADY_UP_TO_DATE.equals(mergeStatus) && !FAST_FORWARD.equals(mergeStatus)) {
            throw new GitToolboxException("Failed to update tracking branch : " + result.toString());
        }

        return targetGit.getRepository().getRef(Constants.HEAD).getName();
    } catch (Exception e) {
        throw new GitToolboxException("Error while updating tracking branch", e);
    }
}

From source file:fr.duminy.tools.jgit.JGitToolboxTest.java

License:Open Source License

@Test
public void testTrack() throws Exception {
    // prepare/*ww w . j ava 2  s.co m*/
    Git sourceGit = createGitRepository("source");
    Git targetGit = cloneRepository(sourceGit);
    addAndCommitFile(sourceGit);
    JGitToolbox toolbox = new JGitToolbox();
    Parameters parameters = new Parameters();
    parameters.setGitDirectory(targetGit.getRepository().getDirectory());

    // test
    String targetHead = toolbox.track(parameters);

    // verify
    log(sourceGit);
    log(targetGit);
    assertThat(targetHead).isEqualTo(getHead(sourceGit).getName());
}

From source file:fr.duminy.tools.jgit.JGitToolboxTest.java

License:Open Source License

@Test(expected = GitToolboxException.class)
public void testTrack_mergeConflict() throws Exception {
    // prepare// w w  w  .  j a v a  2 s .co  m
    Git sourceGit = createGitRepository("source");
    Git targetGit = cloneRepository(sourceGit);
    addAndCommitFile(sourceGit);
    addAndCommitFile(targetGit);
    JGitToolbox toolbox = new JGitToolbox();
    Parameters parameters = new Parameters();
    parameters.setGitDirectory(targetGit.getRepository().getDirectory());

    // test
    toolbox.track(parameters);

    // verify
    log(sourceGit);
    log(targetGit);
}