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

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

Introduction

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

Prototype

@NonNull
public ObjectLoader open(AnyObjectId objectId) throws MissingObjectException, IOException 

Source Link

Document

Open an object from this repository.

Usage

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();//from  w w  w .j a va  2  s .  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.modeshape.connector.git.GitTree.java

License:Apache License

protected void addInformationForPath(Repository repository, Git git, DocumentWriter writer, RevCommit commit,
        String path, CallSpecification spec, Values values) throws GitAPIException, IOException {
    // Make sure the path is in the canonical form we need ...
    if (path.startsWith("/")) {
        if (path.length() == 1)
            path = "";
        else/*from w  w  w.j a v  a2 s  . co  m*/
            path = path.substring(1);
    }

    // Now see if we're actually referring to the "jcr:content" node ...
    boolean isContentNode = false;
    if (path.endsWith(JCR_CONTENT_SUFFIX)) {
        isContentNode = true;
        path = path.substring(0, path.length() - JCR_CONTENT_SUFFIX.length());
    }

    // Create the TreeWalk that we'll use to navigate the files/directories ...
    final TreeWalk tw = new TreeWalk(repository);
    tw.addTree(commit.getTree());
    if ("".equals(path)) {
        // This is the top-level directory, so we don't need to pre-walk to find anything ...
        tw.setRecursive(false);
        while (tw.next()) {
            String childName = tw.getNameString();
            String childId = spec.childId(childName);
            writer.addChild(childId, childName);
        }
    } else {
        // We need to first find our path *before* we can walk the children ...
        PathFilter filter = PathFilter.create(path);
        tw.setFilter(filter);
        while (tw.next()) {
            if (filter.isDone(tw)) {
                break;
            } else if (tw.isSubtree()) {
                tw.enterSubtree();
            }
        }
        // Now that the TreeWalk is the in right location given by the 'path', we can get the
        if (tw.isSubtree()) {
            // The object at the 'path' is a directory, so go into it ...
            tw.enterSubtree();

            // Find the commit in which this folder was last modified ...
            // This may not be terribly efficient, but it seems to work faster on subsequent runs ...
            RevCommit folderCommit = git.log().addPath(path).call().iterator().next();
            writer.setPrimaryType(GitLexicon.FOLDER);

            // could happen if not enough permissions, for example
            if (folderCommit != null) {
                // Add folder-related properties ...
                String committer = commiterName(folderCommit);
                String author = authorName(folderCommit);
                DateTime committed = values.dateFrom(folderCommit.getCommitTime());
                writer.addProperty(JcrLexicon.CREATED, committed);
                writer.addProperty(JcrLexicon.CREATED_BY, committer);
                writer.addProperty(GitLexicon.OBJECT_ID, folderCommit.getId().name());
                writer.addProperty(GitLexicon.AUTHOR, author);
                writer.addProperty(GitLexicon.COMMITTER, committer);
                writer.addProperty(GitLexicon.COMMITTED, committed);
                writer.addProperty(GitLexicon.TITLE, folderCommit.getShortMessage());
            } else {
                connector.getLogger().warn(GitI18n.cannotReadCommit, path);
            }

            // And now walk the contents of the directory ...
            while (tw.next()) {
                String childName = tw.getNameString();
                String childId = spec.childId(childName);
                writer.addChild(childId, childName);
            }
        } else {
            // The path specifies a file (or a content node) ...

            // Find the commit in which this folder was last modified ...
            // This may not be terribly efficient, but it seems to work faster on subsequent runs ...
            RevCommit fileCommit = git.log().addPath(path).call().iterator().next();

            if (isContentNode) {
                writer.setPrimaryType(GitLexicon.RESOURCE);
                if (fileCommit == null) {
                    // could happen if not enough permissions, for example
                    connector.getLogger().warn(GitI18n.cannotReadCommit, path);
                    return;
                }
                // Add file-related properties ...
                String committer = commiterName(fileCommit);
                String author = authorName(fileCommit);
                DateTime committed = values.dateFrom(fileCommit.getCommitTime());

                writer.addProperty(JcrLexicon.LAST_MODIFIED, committed);
                writer.addProperty(JcrLexicon.LAST_MODIFIED_BY, committer);
                writer.addProperty(GitLexicon.OBJECT_ID, fileCommit.getId().name());
                writer.addProperty(GitLexicon.AUTHOR, author);
                writer.addProperty(GitLexicon.COMMITTER, committer);
                writer.addProperty(GitLexicon.COMMITTED, committed);
                writer.addProperty(GitLexicon.TITLE, fileCommit.getShortMessage());
                // Create the BinaryValue ...
                ObjectId fileObjectId = tw.getObjectId(0);
                ObjectLoader fileLoader = repository.open(fileObjectId);
                BinaryKey key = new BinaryKey(fileObjectId.getName());
                BinaryValue value = values.binaryFor(key, fileLoader.getSize());
                if (value == null) {
                    // It wasn't found in the binary store ...
                    if (fileLoader.isLarge()) {
                        // Too large to hold in memory, so use the binary store (which reads the file immediately) ...
                        value = values.binaryFrom(fileLoader.openStream());
                    } else {
                        // This is small enough to fit into a byte[], but it still may be pretty big ...
                        value = new GitBinaryValue(fileObjectId, fileLoader, connector.getSourceName(), name,
                                connector.getMimeTypeDetector());
                    }
                }
                writer.addProperty(JcrLexicon.DATA, value);
                if (connector.includeMimeType()) {
                    try {
                        String filename = spec.parameter(spec.parameterCount() - 1); // the last is 'jcr:content'
                        String mimeType = value.getMimeType(filename);
                        if (mimeType != null)
                            writer.addProperty(JcrLexicon.MIMETYPE, mimeType);
                    } catch (RepositoryException e) {
                        // do nothing
                    } catch (IOException e) {
                        // do nothing
                    }
                }
            } else {
                writer.setPrimaryType(GitLexicon.FILE);
                if (fileCommit == null) {
                    // could happen if not enough permissions, for example
                    connector.getLogger().warn(GitI18n.cannotReadCommit, path);
                    return;
                }
                // Add file-related properties ...
                String committer = commiterName(fileCommit);
                String author = authorName(fileCommit);
                DateTime committed = values.dateFrom(fileCommit.getCommitTime());

                writer.addProperty(JcrLexicon.CREATED, committed);
                writer.addProperty(JcrLexicon.CREATED_BY, committer);
                writer.addProperty(GitLexicon.OBJECT_ID, fileCommit.getId().name());
                writer.addProperty(GitLexicon.AUTHOR, author);
                writer.addProperty(GitLexicon.COMMITTER, committer);
                writer.addProperty(GitLexicon.COMMITTED, committed);
                writer.addProperty(GitLexicon.TITLE, fileCommit.getShortMessage());

                // Add the "jcr:content" child node ...
                String childId = spec.childId(JCR_CONTENT);
                writer.addChild(childId, JCR_CONTENT);
            }
        }
    }
}

From source file:persistence.git.document.GitObjectRepository.java

License:Open Source License

String getObjectContent(final ObjectId objectId, final Repository repository) throws IOException {
    ObjectLoader loader = repository.open(objectId);
    return new String(loader.getBytes(), CONTENT_FORMAT);
}

From source file:playRepository.BareRepository.java

License:Apache License

/**
 * read project README file with readme filename filter from repository
 *
 * @param project/* www . jav  a2s .c o  m*/
 * @return
 */
public static String readREADME(Project project) {
    Repository repository;
    ObjectLoader loader = null;
    repository = getRepository(project);
    try {
        loader = repository.open(getFirstFoundREADMEfileObjectId(repository));
    } catch (IOException e) {
        e.printStackTrace();
        play.Logger.error(e.getMessage());
    }
    if (loader == null) {
        return null;
    }
    return new String(loader.getCachedBytes(), utils.Config.getCharset());
}

From source file:playRepository.BareRepository.java

License:Apache License

public static EndingType findFileLineEnding(Repository repository, String fileNameWithPath) throws IOException {
    ObjectId oldObjectId = BareRepository.getFileObjectId(repository, fileNameWithPath);
    if (oldObjectId.equals(ObjectId.zeroId())) {
        return EndingType.UNDEFINED;
    } else {/* ww  w. j a va  2 s  .c o  m*/
        String fileContents = new String(repository.open(oldObjectId).getBytes(), utils.Config.getCharset());
        return findLineEnding(fileContents);
    }
}

From source file:playRepository.GitRepository.java

License:Apache License

private static List<FileDiff> getFileDiffs(final Repository repositoryA, Repository repositoryB,
        ObjectId commitA, ObjectId commitB) throws IOException {
    class MultipleRepositoryObjectReader extends ObjectReader {
        Collection<ObjectReader> readers = new HashSet<>();

        @Override//from  ww  w.  j  a  v a2 s.  c  o m
        public ObjectReader newReader() {
            return new MultipleRepositoryObjectReader(readers);
        }

        public MultipleRepositoryObjectReader(Collection<ObjectReader> readers) {
            this.readers = readers;
        }

        public MultipleRepositoryObjectReader() {
            this.readers = new HashSet<>();
        }

        public void addObjectReader(ObjectReader reader) {
            this.readers.add(reader);
        }

        @Override
        public Collection<ObjectId> resolve(AbbreviatedObjectId id) throws IOException {
            Set<ObjectId> result = new HashSet<>();
            for (ObjectReader reader : readers) {
                result.addAll(reader.resolve(id));
            }
            return result;
        }

        @Override
        public ObjectLoader open(AnyObjectId objectId, int typeHint) throws IOException {
            for (ObjectReader reader : readers) {
                if (reader.has(objectId, typeHint)) {
                    return reader.open(objectId, typeHint);
                }
            }
            return null;
        }

        @Override
        public Set<ObjectId> getShallowCommits() throws IOException {
            Set<ObjectId> union = new HashSet<>();
            for (ObjectReader reader : readers) {
                union.addAll(reader.getShallowCommits());
            }
            return union;
        }
    }

    final MultipleRepositoryObjectReader reader = new MultipleRepositoryObjectReader();
    reader.addObjectReader(repositoryA.newObjectReader());
    reader.addObjectReader(repositoryB.newObjectReader());

    @SuppressWarnings("rawtypes")
    Repository fakeRepo = new Repository(new BaseRepositoryBuilder()) {

        @Override
        public void create(boolean bare) throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public ObjectDatabase getObjectDatabase() {
            throw new UnsupportedOperationException();
        }

        @Override
        public RefDatabase getRefDatabase() {
            throw new UnsupportedOperationException();
        }

        @Override
        public StoredConfig getConfig() {
            return repositoryA.getConfig();
        }

        @Override
        public void scanForRepoChanges() throws IOException {
            throw new UnsupportedOperationException();
        }

        @Override
        public void notifyIndexChanged() {
            throw new UnsupportedOperationException();
        }

        @Override
        public ReflogReader getReflogReader(String refName) throws IOException {
            throw new UnsupportedOperationException();
        }

        public ObjectReader newObjectReader() {
            return reader;
        }
    };

    DiffFormatter formatter = new DiffFormatter(NullOutputStream.INSTANCE);
    formatter.setRepository(fakeRepo);
    formatter.setDetectRenames(true);

    AbstractTreeIterator treeParserA, treeParserB;
    RevTree treeA = null, treeB = null;

    if (commitA != null) {
        treeA = new RevWalk(repositoryA).parseTree(commitA);
        treeParserA = new CanonicalTreeParser();
        ((CanonicalTreeParser) treeParserA).reset(reader, treeA);
    } else {
        treeParserA = new EmptyTreeIterator();
    }

    if (commitB != null) {
        treeB = new RevWalk(repositoryB).parseTree(commitB);
        treeParserB = new CanonicalTreeParser();
        ((CanonicalTreeParser) treeParserB).reset(reader, treeB);
    } else {
        treeParserB = new EmptyTreeIterator();
    }

    List<FileDiff> result = new ArrayList<>();
    int size = 0;
    int lines = 0;

    for (DiffEntry diff : formatter.scan(treeParserA, treeParserB)) {
        FileDiff fileDiff = new FileDiff();
        fileDiff.commitA = commitA != null ? commitA.getName() : null;
        fileDiff.commitB = commitB != null ? commitB.getName() : null;

        fileDiff.changeType = diff.getChangeType();

        fileDiff.oldMode = diff.getOldMode();
        fileDiff.newMode = diff.getNewMode();

        String pathA = diff.getPath(DiffEntry.Side.OLD);
        String pathB = diff.getPath(DiffEntry.Side.NEW);

        byte[] rawA = null;
        if (treeA != null && Arrays.asList(DELETE, MODIFY, RENAME, COPY).contains(diff.getChangeType())) {
            TreeWalk t1 = TreeWalk.forPath(repositoryA, pathA, treeA);
            ObjectId blobA = t1.getObjectId(0);
            fileDiff.pathA = pathA;

            try {
                rawA = repositoryA.open(blobA).getBytes();
                fileDiff.isBinaryA = RawText.isBinary(rawA);
                fileDiff.a = fileDiff.isBinaryA ? null : new RawText(rawA);
            } catch (org.eclipse.jgit.errors.LargeObjectException e) {
                fileDiff.addError(FileDiff.Error.A_SIZE_EXCEEDED);
            }
        }

        byte[] rawB = null;
        if (treeB != null && Arrays.asList(ADD, MODIFY, RENAME, COPY).contains(diff.getChangeType())) {
            TreeWalk t2 = TreeWalk.forPath(repositoryB, pathB, treeB);
            ObjectId blobB = t2.getObjectId(0);
            fileDiff.pathB = pathB;

            try {
                rawB = repositoryB.open(blobB).getBytes();
                fileDiff.isBinaryB = RawText.isBinary(rawB);
                fileDiff.b = fileDiff.isBinaryB ? null : new RawText(rawB);
            } catch (org.eclipse.jgit.errors.LargeObjectException e) {
                fileDiff.addError(FileDiff.Error.B_SIZE_EXCEEDED);
            }
        }

        if (size > DIFF_SIZE_LIMIT || lines > DIFF_LINE_LIMIT) {
            fileDiff.addError(FileDiff.Error.OTHERS_SIZE_EXCEEDED);
            result.add(fileDiff);
            continue;
        }

        // Get diff if necessary
        if (fileDiff.a != null && fileDiff.b != null && !(fileDiff.isBinaryA || fileDiff.isBinaryB)
                && Arrays.asList(MODIFY, RENAME).contains(diff.getChangeType())) {
            DiffAlgorithm diffAlgorithm = DiffAlgorithm
                    .getAlgorithm(repositoryB.getConfig().getEnum(ConfigConstants.CONFIG_DIFF_SECTION, null,
                            ConfigConstants.CONFIG_KEY_ALGORITHM, DiffAlgorithm.SupportedAlgorithm.HISTOGRAM));
            fileDiff.editList = diffAlgorithm.diff(RawTextComparator.DEFAULT, fileDiff.a, fileDiff.b);
            size += fileDiff.getHunks().size;
            lines += fileDiff.getHunks().lines;
        }

        // update lines and sizes
        if (fileDiff.b != null && !fileDiff.isBinaryB && diff.getChangeType().equals(ADD)) {
            lines += fileDiff.b.size();
            size += rawB.length;
        }

        // update lines and sizes
        if (fileDiff.a != null && !fileDiff.isBinaryA && diff.getChangeType().equals(DELETE)) {
            lines += fileDiff.a.size();
            size += rawA.length;
        }

        // Stop if exceeds the limit for total number of files
        if (result.size() > DIFF_FILE_LIMIT) {
            break;
        }

        result.add(fileDiff);
    }

    return result;
}

From source file:playRepository.GitRepositoryTest.java

License:Apache License

private byte[] getRawFile(Repository repository, String path) throws IOException {
    RevTree tree = new RevWalk(repository).parseTree(repository.resolve(Constants.HEAD));
    TreeWalk treeWalk = TreeWalk.forPath(repository, path, tree);
    if (treeWalk.isSubtree()) {
        return null;
    } else {// ww  w . ja v  a 2s . c o m
        return repository.open(treeWalk.getObjectId(0)).getBytes();
    }
}

From source file:uk.ac.cam.cl.dtg.segue.database.GitDb.java

License:Apache License

/**
 * getFileByCommitSHA/* w ww  .  j a  v a  2s .  c  o  m*/
 * 
 * This method will access the git repository given a particular SHA and will attempt to locate a unique file and
 * return a bytearrayoutputstream of the files contents.
 * 
 * @param sha
 *            to search in.
 * @param fullFilePath
 *            file path to search for e.g. /src/filename.json
 * @return the ByteArrayOutputStream - which you can extract the file contents via the toString method.
 * @throws IOException
 *             - if we cannot access the repo location.
 * @throws UnsupportedOperationException
 *             - This method is intended to only locate one file at a time. If your search matches multiple files
 *             then this exception will be thrown.
 */
public ByteArrayOutputStream getFileByCommitSHA(final String sha, final String fullFilePath)
        throws IOException, UnsupportedOperationException {
    if (null == sha || null == fullFilePath) {
        return null;
    }

    ObjectId objectId = this.findGitObject(sha, fullFilePath);

    if (null == objectId) {
        return null;
    }

    Repository repository = gitHandle.getRepository();
    ObjectLoader loader = repository.open(objectId);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    loader.copyTo(out);

    repository.close();
    return out;
}

From source file:uk.ac.cam.UROP.twentyfourteen.database.GitDb.java

/**
 * getFileByCommitSHA//from w  ww. jav a  2  s . com
 *
 * This method will access the git repository given a particular SHA and
 * will attempt to locate a unique file and return a bytearrayoutputstream
 * of the files contents.
 *
 * @param SHA
 *            to search in.
 * @param Full
 *            file path to search for e.g. /src/filename.json
 * @return the ByteArrayOutputStream - which you can extract the file
 *         contents via the toString method.
 * @throws IOException
 * @throws UnsupportedOperationException
 *             - This method is intended to only locate one file at a time.
 *             If your search matches multiple files then this exception
 *             will be thrown.
 */
public ByteArrayOutputStream getFileByCommitSHA(String sha, String fullFilePath)
        throws IOException, UnsupportedOperationException {
    if (null == sha || null == fullFilePath)
        return null;

    ObjectId objectId = this.findGitObject(sha, fullFilePath);

    if (null == objectId) {
        return null;
    }

    Repository repository = gitHandle.getRepository();
    ObjectLoader loader = repository.open(objectId);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    loader.copyTo(out);

    repository.close();
    return out;
}