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:org.kuali.student.svn.model.AbstractGitRespositoryTestCase.java

License:Educational Community License

protected void storeFile(ObjectInserter inserter, GitTreeData branch, String path, String fileContent)
        throws IOException {

    ObjectId blobSha1 = inserter.insert(Constants.OBJ_BLOB, fileContent.getBytes());

    branch.addBlob(path, blobSha1);//from   ww  w  . ja va2 s . co m

}

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

License:Apache License

/**
 * Create an orphaned branch in a repository.
 * /*from   ww w  . j a  v  a 2s .c  o m*/
 * @param repository
 * @param branchName
 * @param author
 *            if unspecified, Moxie will be the author of this new branch
 * @return true if successful
 */
public static boolean createOrphanBranch(Repository repository, String branchName, PersonIdent author) {
    boolean success = false;
    String message = "Created branch " + branchName;
    if (author == null) {
        author = new PersonIdent("Moxie", "moxie@localhost");
    }
    try {
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create a blob object to insert into a tree
            ObjectId blobId = odi.insert(Constants.OBJ_BLOB, message.getBytes(Constants.CHARACTER_ENCODING));

            // Create a tree object to reference from a commit
            TreeFormatter tree = new TreeFormatter();
            tree.append("NEWBRANCH", FileMode.REGULAR_FILE, blobId);
            ObjectId treeId = odi.insert(tree);

            // Create a commit object
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(author);
            commit.setCommitter(author);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage(message);
            commit.setTreeId(treeId);

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

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                if (!branchName.startsWith("refs/")) {
                    branchName = "refs/heads/" + branchName;
                }
                RefUpdate ru = repository.updateRef(branchName);
                ru.setNewObjectId(commitId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    success = true;
                    break;
                default:
                    success = false;
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return success;
}

From source file:org.oecd.ant.git.custom.CustomAddCommand.java

License:Eclipse Distribution License

/**
 * Executes the {@code Add} 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./*from w  w w .  j  a v  a  2  s . c o m*/
 *
 * @return the DirCache after Add
 */
@Override
public DirCache call() throws GitAPIException, NoFilepatternException {

    if (filepatterns.isEmpty())
        throw new NoFilepatternException(JGitText.get().atLeastOnePatternIsRequired);
    checkCallable();
    DirCache dc = null;
    boolean addAll = false;
    if (filepatterns.contains(".")) //$NON-NLS-1$
        addAll = true;

    try (ObjectInserter inserter = repo.newObjectInserter(); final TreeWalk tw = new TreeWalk(repo)) {
        dc = repo.lockDirCache();
        DirCacheIterator c;

        DirCacheBuilder builder = dc.builder();
        tw.addTree(new DirCacheBuildIterator(builder));
        if (workingTreeIterator == null)
            workingTreeIterator = new FileTreeIterator(repo);
        tw.addTree(workingTreeIterator);
        tw.setRecursive(true);
        if (!addAll)
            tw.setFilter(PathFilterGroup.createFromStrings(filepatterns));

        String lastAddedFile = null;

        while (tw.next()) {
            String path = tw.getPathString();

            WorkingTreeIterator f = tw.getTree(1, WorkingTreeIterator.class);
            if (tw.getTree(0, DirCacheIterator.class) == null && f != null && f.isEntryIgnored()) {
                // file is not in index but is ignored, do nothing
            }
            // In case of an existing merge conflict the
            // DirCacheBuildIterator iterates over all stages of
            // this path, we however want to add only one
            // new DirCacheEntry per path.
            else if (!(path.equals(lastAddedFile))) {
                if (all || !(update && tw.getTree(0, DirCacheIterator.class) == null)) {
                    c = tw.getTree(0, DirCacheIterator.class);
                    if (f != null) { // the file exists
                        long sz = f.getEntryLength();
                        DirCacheEntry entry = new DirCacheEntry(path);
                        if (c == null || c.getDirCacheEntry() == null
                                || !c.getDirCacheEntry().isAssumeValid()) {
                            FileMode mode = f.getIndexFileMode(c);
                            entry.setFileMode(mode);

                            if (FileMode.GITLINK != mode) {
                                entry.setLength(sz);
                                entry.setLastModified(f.getEntryLastModified());
                                long contentSize = f.getEntryContentLength();
                                InputStream in = f.openEntryStream();
                                try {
                                    entry.setObjectId(inserter.insert(Constants.OBJ_BLOB, contentSize, in));
                                } finally {
                                    in.close();
                                }
                            } else
                                entry.setObjectId(f.getEntryObjectId());
                            builder.add(entry);
                            lastAddedFile = path;
                        } else {
                            builder.add(c.getDirCacheEntry());
                        }

                    } else if (c != null && (!(all || update) || FileMode.GITLINK == c.getEntryFileMode()))
                        builder.add(c.getDirCacheEntry());
                }
            }
        }
        inserter.flush();
        builder.commit();
        setCallable(false);
    } catch (IOException e) {
        throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfAddCommand, e);
    } finally {
        if (dc != null)
            dc.unlock();
    }

    return dc;
}

From source file:org.openflexo.hannah.IterativeFileGenerator.java

License:Open Source License

private RawText getRawText(ObjectId id) throws IOException {
    if (ObjectId.zeroId().equals(id)) {
        return RawText.EMPTY_TEXT;
    }//from ww w.ja va2  s  .c om
    final ObjectLoader loader = git.getRepository().open(id, Constants.OBJ_BLOB);
    return new RawText(loader.getCachedBytes());
}

From source file:org.uberfire.java.nio.fs.jgit.JGitSubdirectoryCloneTest.java

License:Apache License

private void writeBlob(final DirCacheEditor editor, ObjectInserter inserter, TestFile data) throws IOException {
    final ObjectId blobId = inserter.insert(Constants.OBJ_BLOB, data.content.length(),
            IOUtils.toInputStream(data.content, "UTF-8"));
    editor.add(new PathEdit(data.path) {
        @Override//w  w w  .j ava  2 s .c om
        public void apply(DirCacheEntry ent) {
            ent.setFileMode(FileMode.REGULAR_FILE);
            ent.setObjectId(blobId);
        }
    });
}

From source file:org.uberfire.java.nio.fs.jgit.util.commands.BlobAsInputStream.java

License:Apache License

public Optional<InputStream> execute() {
    try (final TreeWalk tw = new TreeWalk(git.getRepository())) {
        final ObjectId tree = git.getTreeFromRef(treeRef);
        tw.setFilter(PathFilter.create(path));
        tw.reset(tree);/*from w  ww  . jav  a 2  s  .  c o  m*/
        while (tw.next()) {
            if (tw.isSubtree() && !path.equals(tw.getPathString())) {
                tw.enterSubtree();
                continue;
            }
            return Optional.of(new ByteArrayInputStream(
                    git.getRepository().open(tw.getObjectId(0), Constants.OBJ_BLOB).getBytes()));
        }
    } catch (final Throwable t) {
        LOG.debug("Unexpected exception, this will trigger a NoSuchFileException.", t);
        throw new NoSuchFileException("Can't find '" + path + "' in tree '" + treeRef + "'");
    }
    throw new NoSuchFileException("Can't find '" + path + "' in tree '" + treeRef + "'");
}

From source file:org.uberfire.java.nio.fs.jgit.util.commands.CreateDefaultCommitTree.java

License:Apache License

private static Map<String, Pair<File, ObjectId>> storePathsIntoHashMap(final ObjectInserter inserter,
        final Map.Entry<String, File> pathAndContent, final String gPath) {
    try (final InputStream inputStream = new FileInputStream(pathAndContent.getValue())) {
        final Map<String, Pair<File, ObjectId>> paths = new HashMap<>();
        final ObjectId objectId = inserter.insert(Constants.OBJ_BLOB, pathAndContent.getValue().length(),
                inputStream);//from   w  w  w .  java  2 s .  c  om
        paths.put(gPath, Pair.newPair(pathAndContent.getValue(), objectId));
        return paths;
    } catch (final Exception ex) {
        throw new RuntimeException(ex);
    }
}

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

License:Apache License

public static InputStream resolveInputStream(final Git git, final String treeRef, final String path) {
    checkNotNull("git", git);
    checkNotEmpty("treeRef", treeRef);
    checkNotEmpty("path", path);

    final String gitPath = fixPath(path);

    RevWalk rw = null;/* w  ww .j ava2s  .  co m*/
    TreeWalk tw = null;
    try {
        final ObjectId tree = git.getRepository().resolve(treeRef + "^{tree}");
        rw = new RevWalk(git.getRepository());
        tw = new TreeWalk(git.getRepository());
        tw.setFilter(createFromStrings(singleton(gitPath)));
        tw.reset(tree);
        while (tw.next()) {
            if (tw.isSubtree() && !gitPath.equals(tw.getPathString())) {
                tw.enterSubtree();
                continue;
            }
            return new ByteArrayInputStream(
                    git.getRepository().open(tw.getObjectId(0), Constants.OBJ_BLOB).getBytes());
        }
    } catch (final Throwable t) {
        throw new NoSuchFileException("Can't find '" + gitPath + "' in tree '" + treeRef + "'");
    } finally {
        if (rw != null) {
            rw.dispose();
        }
        if (tw != null) {
            tw.release();
        }
    }
    throw new NoSuchFileException("");
}

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

License:Apache License

/**
 * Creates an in-memory index of the issue change.
 *///from www .  ja v  a  2s  . com
private static DirCache createTemporaryIndex(final Git git, final ObjectId headId,
        final DefaultCommitContent commitContent) {

    final Map<String, File> content = commitContent.getContent();

    final Map<String, Pair<File, ObjectId>> paths = new HashMap<String, Pair<File, ObjectId>>(content.size());
    final Set<String> path2delete = new HashSet<String>();

    final DirCache inCoreIndex = DirCache.newInCore();
    final ObjectInserter inserter = git.getRepository().newObjectInserter();
    final DirCacheEditor editor = inCoreIndex.editor();

    try {
        for (final Map.Entry<String, File> pathAndContent : content.entrySet()) {
            final String gPath = fixPath(pathAndContent.getKey());
            if (pathAndContent.getValue() == null) {
                final TreeWalk treeWalk = new TreeWalk(git.getRepository());
                treeWalk.addTree(new RevWalk(git.getRepository()).parseTree(headId));
                treeWalk.setRecursive(true);
                treeWalk.setFilter(PathFilter.create(gPath));

                while (treeWalk.next()) {
                    path2delete.add(treeWalk.getPathString());
                }
                treeWalk.release();
            } else {
                try {
                    final InputStream inputStream = new FileInputStream(pathAndContent.getValue());
                    try {
                        final ObjectId objectId = inserter.insert(Constants.OBJ_BLOB,
                                pathAndContent.getValue().length(), inputStream);
                        paths.put(gPath, Pair.newPair(pathAndContent.getValue(), objectId));
                    } finally {
                        inputStream.close();
                    }
                } catch (final Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        }

        if (headId != null) {
            final TreeWalk treeWalk = new TreeWalk(git.getRepository());
            final int hIdx = treeWalk.addTree(new RevWalk(git.getRepository()).parseTree(headId));
            treeWalk.setRecursive(true);

            while (treeWalk.next()) {
                final String walkPath = treeWalk.getPathString();
                final CanonicalTreeParser hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);

                if (paths.containsKey(walkPath)
                        && paths.get(walkPath).getK2().equals(hTree.getEntryObjectId())) {
                    paths.remove(walkPath);
                }

                if (paths.get(walkPath) == null && !path2delete.contains(walkPath)) {
                    final DirCacheEntry dcEntry = new DirCacheEntry(walkPath);
                    final ObjectId _objectId = hTree.getEntryObjectId();
                    final FileMode _fileMode = hTree.getEntryFileMode();

                    // add to temporary in-core index
                    editor.add(new DirCacheEditor.PathEdit(dcEntry) {
                        @Override
                        public void apply(final DirCacheEntry ent) {
                            ent.setObjectId(_objectId);
                            ent.setFileMode(_fileMode);
                        }
                    });
                }
            }
            treeWalk.release();
        }

        for (final Map.Entry<String, Pair<File, ObjectId>> pathAndContent : paths.entrySet()) {
            if (pathAndContent.getValue().getK1() != null) {
                editor.add(new DirCacheEditor.PathEdit(new DirCacheEntry(pathAndContent.getKey())) {
                    @Override
                    public void apply(final DirCacheEntry ent) {
                        ent.setLength(pathAndContent.getValue().getK1().length());
                        ent.setLastModified(pathAndContent.getValue().getK1().lastModified());
                        ent.setFileMode(REGULAR_FILE);
                        ent.setObjectId(pathAndContent.getValue().getK2());
                    }
                });
            }
        }

        editor.finish();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        inserter.release();
    }

    if (path2delete.isEmpty() && paths.isEmpty()) {
        //no changes!
        return null;
    }

    return inCoreIndex;
}

From source file:org.webcat.core.git.GitRepository.java

License:Open Source License

/**
 * Copies an item from the repository into a container. If the item is a
 * blob, it will be copied into the destination with the specified name; if
 * the item is a tree or commit, its children will be recursively copied.
 *
 * @param objectId the id of the object to copy
 * @param name the destination name to use (only when the item is a blob)
 * @param container the container where the items should be copied
 * @throws IOException if an I/O error occurred
 *//* w  ww  .j av a 2s. co  m*/
public void copyItemToContainer(ObjectId objectId, String name, IWritableContainer container)
        throws IOException {
    int type = typeOfObject(objectId);

    if (type == Constants.OBJ_BLOB) {
        OutputStream fileStream = container.createFile(name, -1);
        writeBlobToStream(objectId, fileStream);
        fileStream.close();
    } else if (type == Constants.OBJ_TREE || type == Constants.OBJ_COMMIT) {
        GitTreeIterator iterator = new GitTreeIterator(this, objectId);

        try {
            for (GitTreeEntry entry : iterator) {
                if (entry.isTree()) {
                    IWritableContainer childContainer = container.createContainer(entry.name());

                    copyItemToContainer(entry.objectId(), entry.name(), childContainer);

                    childContainer.finish();
                } else {
                    copyItemToContainer(entry.objectId(), entry.name(), container);
                }
            }
        } finally {
            iterator.release();
        }
    }
}