Example usage for org.eclipse.jgit.lib Constants OBJ_BLOB

List of usage examples for org.eclipse.jgit.lib Constants OBJ_BLOB

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Constants OBJ_BLOB.

Prototype

int OBJ_BLOB

To view the source code for org.eclipse.jgit.lib Constants OBJ_BLOB.

Click Source Link

Document

In-pack object type: blob.

Usage

From source file:com.madgag.agit.diff.LineContextDiffer.java

License:Open Source License

private byte[] open(ObjectReader reader, FileMode mode, AbbreviatedObjectId id) throws IOException {
    if (mode == FileMode.MISSING)
        return new byte[] {};

    if (mode.getObjectType() != Constants.OBJ_BLOB)
        return new byte[] {};

    if (!id.isComplete()) {
        Collection<ObjectId> ids = reader.resolve(id);
        if (ids.size() == 1)
            id = AbbreviatedObjectId.fromObjectId(ids.iterator().next());
        else if (ids.size() == 0)
            throw new MissingObjectException(id, Constants.OBJ_BLOB);
        else/*from   w  w w  .ja  v  a  2 s.c  o m*/
            throw new AmbiguousObjectException(id, ids);
    }

    ObjectLoader ldr = reader.open(id.toObjectId());
    return ldr.getCachedBytes(bigFileThreshold);
}

From source file:com.mangosolutions.rcloud.rawgist.repository.git.BareCommitCommand.java

private DirCache createTemporaryIndex(ObjectId headId, DirCache index, RevWalk rw) throws IOException {
    ObjectInserter inserter = null;//w ww.j  ava 2  s  .  c o  m

    // get DirCacheBuilder for existing index
    DirCacheBuilder existingBuilder = index.builder();

    // get DirCacheBuilder for newly created in-core index to build a
    // temporary index for this commit
    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder tempBuilder = inCoreIndex.builder();

    onlyProcessed = new boolean[only.size()];
    boolean emptyCommit = true;

    try (TreeWalk treeWalk = new TreeWalk(repo)) {
        treeWalk.setOperationType(OperationType.CHECKIN_OP);
        int dcIdx = treeWalk.addTree(new DirCacheBuildIterator(existingBuilder));

        FileModeStrategy fileModeStrategy = this.getRepository().getConfig().get(WorkingTreeOptions.KEY)
                .isDirNoGitLinks() ? NoGitlinksStrategy.INSTANCE : DefaultFileModeStrategy.INSTANCE;

        FileTreeIterator fti = new FileTreeIterator(this.workingFolder, this.getRepository().getFS(),
                this.getRepository().getConfig().get(WorkingTreeOptions.KEY), fileModeStrategy);

        fti.setDirCacheIterator(treeWalk, 0);
        int fIdx = treeWalk.addTree(fti);
        int hIdx = -1;
        if (headId != null) {
            hIdx = treeWalk.addTree(rw.parseTree(headId));
        }
        treeWalk.setRecursive(true);

        String lastAddedFile = null;
        while (treeWalk.next()) {
            String path = treeWalk.getPathString();
            // check if current entry's path matches a specified path
            int pos = lookupOnly(path);

            CanonicalTreeParser hTree = null;
            if (hIdx != -1) {
                hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
            }

            DirCacheIterator dcTree = treeWalk.getTree(dcIdx, DirCacheIterator.class);

            if (pos >= 0) {
                // include entry in commit

                FileTreeIterator fTree = treeWalk.getTree(fIdx, FileTreeIterator.class);

                // check if entry refers to a tracked file
                boolean tracked = dcTree != null || hTree != null;
                if (!tracked) {
                    continue;
                }

                // for an unmerged path, DirCacheBuildIterator will yield 3
                // entries, we only want to add one
                if (path.equals(lastAddedFile)) {
                    continue;
                }

                lastAddedFile = path;

                if (fTree != null) {
                    // create a new DirCacheEntry with data retrieved from
                    // disk
                    final DirCacheEntry dcEntry = new DirCacheEntry(path);
                    long entryLength = fTree.getEntryLength();
                    dcEntry.setLength(entryLength);
                    dcEntry.setLastModified(fTree.getEntryLastModified());
                    dcEntry.setFileMode(fTree.getIndexFileMode(dcTree));

                    boolean objectExists = (dcTree != null && fTree.idEqual(dcTree))
                            || (hTree != null && fTree.idEqual(hTree));
                    if (objectExists) {
                        dcEntry.setObjectId(fTree.getEntryObjectId());
                    } else {
                        if (FileMode.GITLINK.equals(dcEntry.getFileMode())) {
                            dcEntry.setObjectId(fTree.getEntryObjectId());
                        } else {
                            // insert object
                            if (inserter == null) {
                                inserter = repo.newObjectInserter();
                            }
                            long contentLength = fTree.getEntryContentLength();
                            InputStream inputStream = fTree.openEntryStream();
                            try {
                                dcEntry.setObjectId(
                                        inserter.insert(Constants.OBJ_BLOB, contentLength, inputStream));
                            } finally {
                                inputStream.close();
                            }
                        }
                    }

                    // add to existing index
                    existingBuilder.add(dcEntry);
                    // add to temporary in-core index
                    tempBuilder.add(dcEntry);

                    if (emptyCommit && (hTree == null || !hTree.idEqual(fTree)
                            || hTree.getEntryRawMode() != fTree.getEntryRawMode())) {
                        // this is a change
                        emptyCommit = false;
                    }
                } else {
                    // if no file exists on disk, neither add it to
                    // index nor to temporary in-core index

                    if (emptyCommit && hTree != null) {
                        // this is a change
                        emptyCommit = false;
                    }
                }

                // keep track of processed path
                onlyProcessed[pos] = true;
            } else {
                // add entries from HEAD for all other paths
                if (hTree != null) {
                    // create a new DirCacheEntry with data retrieved from
                    // HEAD
                    final DirCacheEntry dcEntry = new DirCacheEntry(path);
                    dcEntry.setObjectId(hTree.getEntryObjectId());
                    dcEntry.setFileMode(hTree.getEntryFileMode());

                    // add to temporary in-core index
                    tempBuilder.add(dcEntry);
                }

                // preserve existing entry in index
                if (dcTree != null) {
                    existingBuilder.add(dcTree.getDirCacheEntry());
                }
            }
        }
    }

    // there must be no unprocessed paths left at this point; otherwise an
    // untracked or unknown path has been specified
    for (int i = 0; i < onlyProcessed.length; i++) {
        if (!onlyProcessed[i]) {
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().entryNotFoundByPath, only.get(i)));
        }
    }

    // there must be at least one change
    if (emptyCommit) {
        // Would like to throw a EmptyCommitException. But this would break the API
        // TODO(ch): Change this in the next release
        //         throw new JGitInternalException(JGitText.get().emptyCommit);
    }

    // update index
    existingBuilder.commit();
    // finish temporary in-core index used for this commit
    tempBuilder.finish();
    return inCoreIndex;
}

From source file:com.mangosolutions.rcloud.rawgist.repository.git.BareRmCommand.java

/**
 * Executes the {@code Rm} command. Each instance of this class should only
 * be used for one invocation of the command. Don't call this method twice
 * on an instance./*ww w.  j  a  va2 s  .c  om*/
 *
 * @return the DirCache after Rm
 */
public DirCache call() throws GitAPIException, NoFilepatternException {

    if (filepatterns.isEmpty()) {
        throw new NoFilepatternException(JGitText.get().atLeastOnePatternIsRequired);
    }
    checkCallable();

    try (final TreeWalk tw = new TreeWalk(repo)) {
        index.lock();
        DirCacheBuilder builder = index.builder();
        tw.reset(); // drop the first empty tree, which we do not need here
        tw.setRecursive(true);
        tw.setFilter(PathFilterGroup.createFromStrings(filepatterns));
        tw.addTree(new DirCacheBuildIterator(builder));

        while (tw.next()) {
            if (!cached) {
                final FileMode mode = tw.getFileMode(0);
                if (mode.getObjectType() == Constants.OBJ_BLOB) {
                    final File path = new File(repo.getWorkTree(), tw.getPathString());
                    // Deleting a blob is simply a matter of removing
                    // the file or symlink named by the tree entry.
                    delete(path);
                }
            }
        }
        builder.commit();
        setCallable(false);
    } catch (IOException e) {
        throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfRmCommand, e);
    } finally {
        if (index != null) {
            index.unlock();
        }
    }

    return index;
}

From source file:com.netbeetle.reboot.git.CachedRepository.java

License:Apache License

public ObjectId lookupBlob(ObjectId tree, String path) throws IOException {
    TreeWalk treeWalk = TreeWalk.forPath(repository, path, tree);
    if (treeWalk == null) {
        return null;
    }/*from  w  w w  . j av a2 s.  c om*/
    try {
        FileMode fileMode = treeWalk.getFileMode(0);
        if (fileMode.getObjectType() != Constants.OBJ_BLOB
                || (fileMode != FileMode.REGULAR_FILE && fileMode != FileMode.EXECUTABLE_FILE)) {
            return null;
        }

        return treeWalk.getObjectId(0);
    } finally {
        treeWalk.release();
    }
}

From source file:com.palantir.gerrit.gerritci.servlets.JobsServlet.java

License:Apache License

public static ObjectId createGitFileId(Repository repository, FileBasedConfig jobConfig,
        ObjectInserter objectInserter, String jobName) throws UnsupportedEncodingException, IOException {
    ObjectId fileId = objectInserter.insert(Constants.OBJ_BLOB, jobConfig.toText().getBytes("utf-8"));
    objectInserter.flush();/*w  w  w  .java  2  s. c  om*/
    logger.info("Created blobId " + fileId + " for " + jobName);
    return fileId;
}

From source file:com.pramati.gerrit.plugin.helpers.GetFileFromRepo.java

License:Apache License

/**
 * returns the File Stream from the gerrit repository. returns "null" if the
 * given file not found in the repository.<br>
 * patchStr should like in given format::"changeid/patchsetID/filename" <br>
 * eg: 1/2/readme.md/*from  w ww  . j a v  a 2s. c  om*/
 * 
 * @param patchStr
 * @return
 * @throws IOException
 */
public static BufferedInputStream doGetFile(String patchStr) throws IOException {
    final Patch.Key patchKey;
    final Change.Id changeId;
    final Project project;
    final PatchSet patchSet;
    final Repository repo;
    final ReviewDb db;
    final ChangeControl control;
    try {
        patchKey = Patch.Key.parse(patchStr);
    } catch (NumberFormatException e) {
        return null;
    }
    changeId = patchKey.getParentKey().getParentKey();

    try {
        db = requestDb.get();
        control = changeControl.validateFor(changeId);

        project = control.getProject();
        patchSet = db.patchSets().get(patchKey.getParentKey());
        if (patchSet == null) {
            return null;
            // rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (NoSuchChangeException e) {
        // rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    } catch (OrmException e) {
        // getServletContext().log("Cannot query database", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }

    try {
        repo = repoManager.openRepository(project.getNameKey());
    } catch (RepositoryNotFoundException e) {
        // getServletContext().log("Cannot open repository", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }

    final ObjectLoader blobLoader;
    final RevCommit fromCommit;
    final String path = patchKey.getFileName();
    try {
        final ObjectReader reader = repo.newObjectReader();
        try {
            final RevWalk rw = new RevWalk(reader);
            final RevCommit c;
            final TreeWalk tw;

            c = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get()));
            fromCommit = c;

            tw = TreeWalk.forPath(reader, path, fromCommit.getTree());
            if (tw == null) {
                // rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
                return null;
            }

            if (tw.getFileMode(0).getObjectType() == Constants.OBJ_BLOB) {
                blobLoader = reader.open(tw.getObjectId(0), Constants.OBJ_BLOB);

            } else {
                // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return null;
            }
        } finally {
            reader.release();
        }
    } catch (IOException e) {
        // getServletContext().log("Cannot read repository", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    } catch (RuntimeException e) {
        // getServletContext().log("Cannot read repository", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    } finally {
        repo.close();
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    blobLoader.copyTo(out);
    byte[] b = out.toByteArray();
    BufferedInputStream br = new BufferedInputStream(new ByteArrayInputStream(b));
    return br;
}

From source file:com.smartitengineering.version.impl.jgit.JGitImpl.java

License:Open Source License

public byte[] readObject(final String objectIdStr) throws IOException, IllegalArgumentException {
    if (StringUtils.isBlank(objectIdStr)) {
        throw new IllegalArgumentException("Invalid Object id!");
    }// w ww. j  a  v a 2s . c  o  m
    ObjectId objectId = ObjectId.fromString(objectIdStr);
    ObjectLoader objectLoader = getReadRepository().openObject(objectId);
    if (objectLoader.getType() != Constants.OBJ_BLOB) {
        throw new IllegalArgumentException("Not a blob: " + objectIdStr);
    }
    return objectLoader.getBytes();
}

From source file:com.smartitengineering.version.impl.jgit.JGitImpl.java

License:Open Source License

protected Set<ObjectId> getGraphForResourceId(String resourceId)
        throws MissingObjectException, IncorrectObjectTypeException, IOException {
    final Set<ObjectId> versions = new LinkedHashSet<ObjectId>();
    final RevWalk rw = new RevWalk(getReadRepository());
    final TreeWalk tw = new TreeWalk(getReadRepository());
    rw.markStart(rw.parseCommit(getReadRepository().resolve(Constants.HEAD)));
    tw.setFilter(TreeFilter.ANY_DIFF);// w  w w .j  a  v a  2 s .  co m
    RevCommit c;
    while ((c = rw.next()) != null) {
        final ObjectId[] p = new ObjectId[c.getParentCount() + 1];
        for (int i = 0; i < c.getParentCount(); i++) {
            rw.parseAny(c.getParent(i));
            p[i] = c.getParent(i).getTree();
        }
        final int me = p.length - 1;
        p[me] = c.getTree();
        tw.reset(p);
        while (tw.next()) {
            if (tw.getFileMode(me).getObjectType() == Constants.OBJ_BLOB) {
                // This path was modified relative to the ancestor(s)
                String s = tw.getPathString();
                if (s != null && s.equals(resourceId)) {
                    versions.add(tw.getObjectId(me));
                }
            }
            if (tw.isSubtree()) {
                // make sure we recurse into modified directories
                tw.enterSubtree();
            }
        }
    }
    return versions;
}

From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java

License:Open Source License

public static Blob getBlob(Repository r, String revision, String path)
        throws IOException, EntityNotFoundException {

    if (path.startsWith("/")) {
        path = path.substring(1);//from  ww  w  . j  a v  a2  s  . c  o  m
    }

    String id = resolve(r, r.resolve(revision), path);
    if (id == null) {
        throw new EntityNotFoundException();
    }
    ObjectId objectId = ObjectId.fromString(id);

    ObjectLoader loader = r.getObjectDatabase().open(objectId, Constants.OBJ_BLOB);

    Blob b = new Blob(id);

    if (loader.isLarge()) {
        b.setLarge(true);
        InputStream is = null;
        IOException ioex = null;
        try {
            is = loader.openStream();
            b.setBinary(RawText.isBinary(is));
        } catch (IOException ex) {
            ioex = ex;
        } finally {
            if (is != null) {
                is.close();
            }
            if (ioex != null) {
                throw ioex;
            }
        }

    } else {
        byte[] raw = loader.getBytes();

        boolean binary = RawText.isBinary(raw);

        if (binary) {
            b.setBinary(true);
            b.setLines(Collections.<String>emptyList());
        } else {

            RawText rt = new RawText(raw);
            List<String> lines = new ArrayList<String>(rt.size());

            for (int i = 0; i < rt.size(); i++) {
                lines.add(rt.getString(i));
            }

            b.setLines(lines);
        }
    }

    return b;
}

From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java

License:Open Source License

private static Item.Type getType(int type) {
    switch (type) {
    case Constants.OBJ_BLOB:
        return Item.Type.BLOB;
    case Constants.OBJ_TREE:
        return Item.Type.TREE;
    case Constants.OBJ_COMMIT:
        return Item.Type.COMMIT;
    // XXX add more
    default://from w  w w.  j  a  v  a2  s.c  o  m
        return null;
    }
}