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

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

Introduction

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

Prototype

@Nullable
public ObjectId resolve(String revstr)
        throws AmbiguousObjectException, IncorrectObjectTypeException, RevisionSyntaxException, IOException 

Source Link

Document

Parse a git revision string and return an object id.

Usage

From source file:org.kie.commons.java.nio.fs.jgit.util.JGitUtil.java

License:Apache License

public static ObjectId getTreeRefObjectId(final Repository repo, final String treeRef) {
    try {/*w w  w  .ja va  2s  . c om*/
        return repo.resolve(treeRef + "^{tree}");
    } catch (java.io.IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.komodo.storage.git.TestGitStorageConnector.java

License:Open Source License

@Test
public void testWriteToRepository() throws Exception {
    localTmpDir = new File(tmpDir, "localTmpDir-" + timestamp);
    Properties parameters = new Properties();
    parameters.setProperty(GitStorageConnector.REPO_DEST_PROPERTY, localTmpDir.getAbsolutePath());
    parameters.setProperty(GitStorageConnector.REPO_PATH_PROPERTY, myGitDir.getAbsolutePath());

    connector = new GitStorageConnector(parameters);
    connector.refresh();/*w  w w  .j  ava2s  . c  o m*/

    UnitOfWork transaction = mock(UnitOfWork.class);
    when(transaction.getState()).thenReturn(State.NOT_STARTED);

    parameters = new Properties();
    parameters.setProperty(GitStorageConnector.FILE_PATH_PROPERTY, TEST_VDB_2_XML);

    Exportable artifact = mock(Exportable.class);
    String sampleExample = TestUtilities.streamToString(TestUtilities.sampleExample());
    when(artifact.export(transaction, parameters)).thenReturn(sampleExample.getBytes());
    when(artifact.getName(transaction)).thenReturn(TestUtilities.SAMPLE_VDB_FILE);

    connector.write(artifact, transaction, parameters);

    //
    // Test the artifact was pushed by walking the origin repository
    //
    Repository repository = myGit.getRepository();
    ObjectId commitId = repository.resolve(Constants.HEAD);
    try (RevWalk revWalk = new RevWalk(repository)) {
        RevCommit commit = revWalk.parseCommit(commitId);
        RevTree tree = commit.getTree();
        try (TreeWalk treeWalk = new TreeWalk(repository)) {
            treeWalk.addTree(tree);
            treeWalk.setRecursive(true);
            treeWalk.setFilter(PathFilter.create(TEST_VDB_2_XML));
            assertTrue(treeWalk.next());

            //
            // Found the file has been successfully pushed now
            // conclude it contains the same contents
            //
            ObjectId objectId = treeWalk.getObjectId(0);
            ObjectLoader loader = repository.open(objectId);

            File tmpFile1 = createTempFile("myGitTestFile", XML_SUFFIX);
            FileUtils.write(loader.getBytes(), tmpFile1);

            File tmpFile2 = createTempFile("sampleExampleFile", XML_SUFFIX);
            FileUtils.write(TestUtilities.sampleExample(), tmpFile2);
            compareFileContents(tmpFile1, tmpFile2);
        }
    }
}

From source file:org.komodo.storage.git.TestGitStorageConnector.java

License:Open Source License

@Test
public void testWriteZipToRepositoryAsDirectory() throws Exception {
    localTmpDir = new File(tmpDir, "localTmpDir-" + timestamp);
    Properties parameters = new Properties();
    parameters.setProperty(GitStorageConnector.REPO_DEST_PROPERTY, localTmpDir.getAbsolutePath());
    parameters.setProperty(GitStorageConnector.REPO_PATH_PROPERTY, myGitDir.getAbsolutePath());

    connector = new GitStorageConnector(parameters);
    connector.refresh();// w  w  w . j  a v a  2s. c  o  m

    String dsName = TestUtilities.US_STATES_VDB_NAME;

    UnitOfWork transaction = mock(UnitOfWork.class);
    when(transaction.getState()).thenReturn(State.NOT_STARTED);

    Exportable artifact = mock(Exportable.class);
    InputStream usStatesExample = TestUtilities.usStatesDataserviceExample();
    byte[] usStatesArr = FileUtils.streamToByteArray(usStatesExample);

    parameters = new Properties();
    parameters.setProperty(GitStorageConnector.FILE_PATH_PROPERTY, DocumentType.ZIP.fileName(dsName));

    when(artifact.export(transaction, parameters)).thenReturn(usStatesArr);
    when(artifact.getName(transaction)).thenReturn(dsName);
    when(artifact.getDocumentType(transaction)).thenReturn(DocumentType.ZIP);

    connector.write(artifact, transaction, parameters);

    //
    // Test the artifact was pushed by walking the origin repository
    //
    usStatesExample = TestUtilities.usStatesDataserviceExample();
    List<String> zipEntries = TestUtilities.zipEntries(dsName, usStatesExample);

    Repository repository = myGit.getRepository();
    ObjectId commitId = repository.resolve(Constants.HEAD);
    try (RevWalk revWalk = new RevWalk(repository)) {
        RevCommit commit = revWalk.parseCommit(commitId);
        RevTree tree = commit.getTree();

        try (TreeWalk treeWalk = new TreeWalk(repository)) {
            treeWalk.addTree(tree);
            treeWalk.setRecursive(false);
            while (treeWalk.next()) {
                zipEntries.remove(treeWalk.getPathString());

                if (treeWalk.isSubtree())
                    treeWalk.enterSubtree();
            }
        }

        //
        // All entries in the original zip have been extracted
        // and pushed to the git repository
        //
        assertTrue("Remaining entries: " + Arrays.toString(zipEntries.toArray(new String[0])),
                zipEntries.isEmpty());
    }
}

From source file:org.libx4j.maven.plugin.version.OriginalResolver.java

License:Open Source License

public OriginalResolver(final Repository repository)
        throws IncorrectObjectTypeException, IOException, MissingObjectException {
    // Resolve the revision specification
    final ObjectId id = repository.resolve(Constants.HEAD);

    this.reader = repository.newObjectReader();
    this.walk = new RevWalk(reader);
    this.commit = walk.parseCommit(id);
}

From source file:org.modeshape.connector.git.GitFunction.java

License:Apache License

/**
 * Resolve the branch name, tag name, or commit ID into the appropriate ObjectId. Note that the branch names are assumed to be
 * from the {@link GitConnector#remoteName() remote}.
 * /*from w  w  w .j  a  va2s  .c o m*/
 * @param repository the Repository object; may not be null
 * @param branchOrTagOrCommitId the branch name, tag name, or commit ID; may not be null
 * @return the resolved ObjectId, or null if the supplied string does not resolve to an object ID
 * @throws IOException if there is a problem reading the Git repository
 */
protected ObjectId resolveBranchOrTagOrCommitId(Repository repository, String branchOrTagOrCommitId)
        throws IOException {
    ObjectId objId = repository.resolve(branchOrTagOrCommitId);
    if (objId == null) {
        for (String remoteName : connector.remoteNames()) {
            String branchRef = branchRefForName(branchOrTagOrCommitId, remoteName);
            objId = repository.resolve(branchRef);
            if (objId != null)
                break;
        }
    }
    return objId;
}

From source file:org.modeshape.connector.git.GitFunction.java

License:Apache License

/**
 * Add an additional page of commits in the history names of the tags as children of the current node.
 * /*  w w  w  . j a  v a 2  s.  co m*/
 * @param git the Git object; may not be null
 * @param repository the Repository object; may not be null
 * @param spec the call specification; may not be null
 * @param writer the page writer for the current node; may not be null
 * @param pageKey the page key for this page; may not be null
 * @throws GitAPIException if there is a problem accessing the Git repository
 * @throws IOException if there is a problem reading the Git repository
 */
protected void addCommitsAsPageOfChildren(Git git, Repository repository, CallSpecification spec,
        PageWriter writer, PageKey pageKey) throws GitAPIException, IOException {
    RevWalk walker = new RevWalk(repository);
    try {
        // The offset is the ID of the last commit we read, so we'll need to skip the first commit
        String lastCommitIdName = pageKey.getOffsetString();
        ObjectId lastCommitId = repository.resolve(lastCommitIdName);
        int pageSize = (int) pageKey.getBlockSize();
        // int offset = pageKey.getOffsetInt();
        // int maxCount = pageSize + offset;
        LogCommand command = git.log();
        command.add(lastCommitId);
        command.setMaxCount(pageSize + 1);
        // Add the first set of commits ...
        int actual = 0;
        String commitId = null;
        for (RevCommit commit : command.call()) {
            commitId = commit.getName();
            if (commitId.equals(lastCommitIdName))
                continue;
            writer.addChild(spec.childId(commitId), commitId);
            ++actual;
        }
        if (actual == pageSize) {
            assert commitId != null;
            // We wrote the maximum number of commits, so there's (probably) another page ...
            writer.addPage(pageKey.getParentId(), commitId, pageSize, PageWriter.UNKNOWN_TOTAL_SIZE);
        }
    } finally {
        walker.dispose();
    }
}

From source file:org.modeshape.connector.git.GitHistory.java

License:Apache License

@Override
public Document execute(Repository repository, Git git, CallSpecification spec, DocumentWriter writer,
        Values values) throws GitAPIException, IOException {
    if (spec.parameterCount() == 0) {
        // This is the top-level "/commits" node
        writer.setPrimaryType(GitLexicon.COMMITS);

        // Generate the child references to the branches, tags, and commits in the history ...
        addBranchesAsChildren(git, spec, writer);
        addTagsAsChildren(git, spec, writer);
        addCommitsAsChildren(git, spec, writer, pageSize);

    } else if (spec.parameterCount() == 1) {
        // This is the top-level "/commits/{branchOrTagNameOrObjectId}" node
        writer.setPrimaryType(GitLexicon.OBJECT);

        // Generate the child references to the (latest) commits on this branch/tag ...
        String branchOrTagNameOrObjectId = spec.parameter(0);
        ObjectId objId = resolveBranchOrTagOrCommitId(repository, branchOrTagNameOrObjectId);
        RevWalk walker = new RevWalk(repository);
        try {/*w w  w.j  av a 2s. c  o m*/
            RevCommit commit = walker.parseCommit(objId);
            LogCommand command = git.log();
            command.add(commit.getId());
            command.setMaxCount(pageSize);
            for (RevCommit rev : command.call()) {
                String commitId = rev.getId().getName();
                writer.addChild(spec.childId(commitId), commitId);
            }
            // Handle paging ...
            writer.addPage(spec.getParentId(), pageSize, pageSize, PageWriter.UNKNOWN_TOTAL_SIZE);
        } finally {
            walker.dispose();
        }

    } else if (spec.parameterCount() == 2) {
        // This is a specific commit in the history, via "/commits/{branchOrTagNameOrObjectId}/{objectId}"
        writer.setPrimaryType(GitLexicon.COMMIT);

        // so we need to show the commit information ...
        RevWalk walker = new RevWalk(repository);
        try {
            String commitId = spec.parameter(1);
            ObjectId objId = repository.resolve(commitId);
            RevCommit commit = walker.parseCommit(objId);
            writer.addProperty(GitLexicon.OBJECT_ID, objId.name());
            writer.addProperty(GitLexicon.AUTHOR, authorName(commit));
            writer.addProperty(GitLexicon.COMMITTER, commiterName(commit));
            writer.addProperty(GitLexicon.COMMITTED, values.dateFrom(commit.getCommitTime()));
            writer.addProperty(GitLexicon.TITLE, commit.getShortMessage());
            writer.addProperty(GitLexicon.TREE, GitTree.referenceToTree(objId, objId.name(), values));
            writer.addProperty(GitLexicon.DETAIL, GitCommitDetails.referenceToCommit(objId, values));
            // And there are no children
        } finally {
            walker.dispose();
        }
    } else {
        return null;
    }

    return writer.document();
}

From source file:org.modeshape.connector.git.GitHistory.java

License:Apache License

@Override
public Document execute(Repository repository, Git git, CallSpecification spec, PageWriter writer,
        Values values, PageKey pageKey) throws GitAPIException, IOException {
    if (spec.parameterCount() == 0) {
        // List the next page of commits ...
        addCommitsAsPageOfChildren(git, repository, spec, writer, pageKey);
    } else {//www .ja va 2  s . c  om
        // We know the branch, tag, or commit for the history ...
        String branchOrTagNameOrObjectId = spec.parameter(0);
        ObjectId objId = repository.resolve(branchOrTagNameOrObjectId);
        RevWalk walker = new RevWalk(repository);
        try {
            int offset = pageKey.getOffsetInt();
            RevCommit commit = walker.parseCommit(objId);
            LogCommand command = git.log();
            command.add(commit.getId());
            command.setSkip(offset);
            command.setMaxCount(pageSize);
            for (RevCommit rev : command.call()) {
                String commitId = rev.getId().toString();
                writer.addChild(spec.childId(commitId), commitId);
            }

            // Handle paging ...
            int nextOffset = offset + pageSize;
            writer.addPage(pageKey.getParentId(), nextOffset, pageSize, PageWriter.UNKNOWN_TOTAL_SIZE);
        } finally {
            walker.dispose();
        }
    }
    return writer.document();
}

From source file:org.moxie.utils.JGitUtils.java

License:Apache License

public static String getCommitId(File folder) {
    // try specified folder or subfolder
    File gitDir = FileKey.resolve(folder, FS.DETECTED);

    if (gitDir == null || !gitDir.exists()) {
        // try parent folder
        gitDir = FileKey.resolve(folder.getParentFile(), FS.DETECTED);
    }//from   w ww  .  j  a v a2 s .  co m
    if (gitDir == null || !gitDir.exists()) {
        throw new MoxieException("Can not find .git folder for " + folder);
    }

    String hashid = "";
    try {
        Repository repository = new FileRepository(gitDir);
        ObjectId objectId = repository.resolve(org.eclipse.jgit.lib.Constants.HEAD);
        hashid = objectId.getName().toString();
        repository.close();
    } catch (IOException io) {
        io.printStackTrace();
        throw new MoxieException("IOException accessing " + gitDir.getAbsolutePath(), io);
    }
    return hashid;
}

From source file:org.moxie.utils.JGitUtils.java

License:Apache License

public static void updateGhPages(File repositoryFolder, File sourceFolder, boolean obliterate) {
    String ghpages = "refs/heads/gh-pages";
    try {//from ww  w.  j  a v  a2 s  .c  om
        File gitDir = FileKey.resolve(repositoryFolder, FS.DETECTED);
        Repository repository = new FileRepository(gitDir);

        ObjectId objectId = repository.resolve(ghpages);
        if (objectId == null) {
            JGitUtils.createOrphanBranch(repository, "gh-pages", null);
        }

        System.out.println("Updating gh-pages branch...");
        ObjectId headId = repository.resolve(ghpages + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the new/updated issue.
            DirCache index = createIndex(repository, headId, sourceFolder, obliterate);
            ObjectId indexTreeId = index.writeTree(odi);

            // Create a commit object
            PersonIdent author = new PersonIdent("Moxie", "moxie@localhost");
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(author);
            commit.setCommitter(author);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage("updated pages");
            commit.setParentId(headId);
            commit.setTreeId(indexTreeId);

            // Insert the commit into the repository
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                RefUpdate ru = repository.updateRef(ghpages);
                ru.setNewObjectId(commitId);
                ru.setExpectedOldObjectId(headId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            ghpages, commitId.toString(), rc));
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
        System.out.println("gh-pages updated.");
    } catch (Throwable t) {
        t.printStackTrace();
    }
}