Example usage for org.eclipse.jgit.lib ObjectInserter insert

List of usage examples for org.eclipse.jgit.lib ObjectInserter insert

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib ObjectInserter insert.

Prototype

public abstract ObjectId insert(int objectType, long length, InputStream in) throws IOException;

Source Link

Document

Insert a single object into the store, returning its unique name.

Usage

From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java

License:Open Source License

@Override
public void saveReview(URI uri, ModelReview modelReview, User currentReviewer, IProgressMonitor monitor)
        throws InvalidReviewRepositoryException, InvalidReviewException, RepositoryIOException {

    monitor.beginTask("Connecting to repository", IProgressMonitor.UNKNOWN);

    String repoFileURI = COMMENTS_FILE_URI;

    try {//from   ww  w .  ja v a  2  s. co  m
        Git git = Git.open(new File(uri));
        Repository repository = git.getRepository();
        ObjectInserter objectInserter = repository.newObjectInserter();

        String commentRefName = getCommentRefName(modelReview);
        Ref commentRef = repository.exactRef(commentRefName);

        DirCache index = DirCache.newInCore();
        DirCacheBuilder dirCacheBuilder = index.builder();

        monitor.beginTask("Preparing commit...", IProgressMonitor.UNKNOWN);

        if (commentRef != null) {

            /*
             * The ref already exists so we have to copy the previous
             * RevTree to keep all already attached files
             */

            RevWalk revWalk = new RevWalk(repository);
            RevCommit prevCommit = revWalk.parseCommit(commentRef.getObjectId());
            RevTree tree = prevCommit.getTree();

            List<String> ignoredFiles = new ArrayList<>();
            /*
             * add file path of the new file to the ignored file paths, as
             * we don't want any already existing old file in our new tree
             */
            ignoredFiles.add(repoFileURI);
            buildDirCacheFromTree(tree, repository, dirCacheBuilder, ignoredFiles);

            revWalk.close();
        }

        monitor.beginTask("Writing comments file...", IProgressMonitor.UNKNOWN);

        ResourceSet resourceSet = new ResourceSetImpl();
        Resource resource = resourceSet.createResource(org.eclipse.emf.common.util.URI.createURI(repoFileURI));

        addCommentsToResource(modelReview, resource);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        resource.save(outputStream, null);

        // insert file as object
        byte[] content = outputStream.toByteArray();
        long length = content.length;
        InputStream inputStream = new ByteArrayInputStream(content);
        ObjectId objectId = objectInserter.insert(Constants.OBJ_BLOB, length, inputStream);
        inputStream.close();

        // create tree entry
        DirCacheEntry entry = new DirCacheEntry(repoFileURI);
        entry.setFileMode(FileMode.REGULAR_FILE);
        entry.setLastModified(System.currentTimeMillis());
        entry.setLength(length);
        entry.setObjectId(objectId);
        dirCacheBuilder.add(entry);

        dirCacheBuilder.finish();

        // write new tree in database
        ObjectId indexTreeId = index.writeTree(objectInserter);

        monitor.beginTask("Commiting comments...", IProgressMonitor.UNKNOWN);

        // create commit
        CommitBuilder commitBuilder = new CommitBuilder();
        PersonIdent personIdent = new PersonIdent("Mervin", "mervin@mervin.modelreview");
        commitBuilder.setCommitter(personIdent);
        commitBuilder.setAuthor(personIdent);
        commitBuilder.setMessage(
                MessageFormat.format("Updated comments by user \"{0}\"", currentReviewer.getName()));

        if (commentRef != null) {
            commitBuilder.setParentId(commentRef.getObjectId());
        }
        commitBuilder.setTreeId(indexTreeId);

        // commit
        ObjectId commitId = objectInserter.insert(commitBuilder);
        objectInserter.flush();

        RefUpdate refUpdate = repository.updateRef(commentRefName);
        refUpdate.setNewObjectId(commitId);
        if (commentRef != null)
            refUpdate.setExpectedOldObjectId(commentRef.getObjectId());
        else
            refUpdate.setExpectedOldObjectId(ObjectId.zeroId());

        /*
         * TODO the result handling below is copied from the CommitCommand
         * class, I don't know if this is really necessary in our case
         */
        Result result = refUpdate.forceUpdate();
        switch (result) {
        case NEW:
        case FORCED:
        case FAST_FORWARD: {
            if (repository.getRepositoryState() == RepositoryState.MERGING_RESOLVED) {
                /*
                 * Commit was successful. Now delete the files used for
                 * merge commits
                 */
                repository.writeMergeCommitMsg(null);
                repository.writeMergeHeads(null);
            } else if (repository.getRepositoryState() == RepositoryState.CHERRY_PICKING_RESOLVED) {
                repository.writeMergeCommitMsg(null);
                repository.writeCherryPickHead(null);
            } else if (repository.getRepositoryState() == RepositoryState.REVERTING_RESOLVED) {
                repository.writeMergeCommitMsg(null);
                repository.writeRevertHead(null);
            }
            break;
        }
        case REJECTED:
        case LOCK_FAILURE:
            throw new RepositoryIOException("Error occured during writing to the git repository",
                    new ConcurrentRefUpdateException("Could not lock ref " + refUpdate.getRef().getName(),
                            refUpdate.getRef(), result));
        default:
            throw new RepositoryIOException("Error occured during writing to the git repository",
                    new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            refUpdate.getRef().getName(), commitId.toString(), result)));
        }

    } catch (IOException e) {
        throw new InvalidReviewRepositoryException("Could not open local git repository", e);
    } finally {
        monitor.done();
    }

}

From source file:com.gitblit.build.BuildGhPages.java

License:Apache License

/**
 * Creates an in-memory index of the issue change.
 * /*from   w  w w.  j  a  v a  2 s.  c om*/
 * @param repo
 * @param headId
 * @param sourceFolder
 * @param obliterate
 *            if true the source folder tree is used as the new tree for
 *            gh-pages and non-existent files are considered deleted
 * @return an in-memory index
 * @throws IOException
 */
private static DirCache createIndex(Repository repo, ObjectId headId, File sourceFolder, boolean obliterate)
        throws IOException {

    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder dcBuilder = inCoreIndex.builder();
    ObjectInserter inserter = repo.newObjectInserter();

    try {
        // Add all files to the temporary index
        Set<String> ignorePaths = new TreeSet<String>();
        List<File> files = listFiles(sourceFolder);
        for (File file : files) {
            // create an index entry for the file
            final DirCacheEntry dcEntry = new DirCacheEntry(
                    StringUtils.getRelativePath(sourceFolder.getPath(), file.getPath()));
            dcEntry.setLength(file.length());
            dcEntry.setLastModified(file.lastModified());
            dcEntry.setFileMode(FileMode.REGULAR_FILE);

            // add this entry to the ignore paths set
            ignorePaths.add(dcEntry.getPathString());

            // insert object
            InputStream inputStream = new FileInputStream(file);
            try {
                dcEntry.setObjectId(inserter.insert(Constants.OBJ_BLOB, file.length(), inputStream));
            } finally {
                inputStream.close();
            }

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

        if (!obliterate) {
            // Traverse HEAD to add all other paths
            TreeWalk treeWalk = new TreeWalk(repo);
            int hIdx = -1;
            if (headId != null)
                hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
            treeWalk.setRecursive(true);

            while (treeWalk.next()) {
                String path = treeWalk.getPathString();
                CanonicalTreeParser hTree = null;
                if (hIdx != -1)
                    hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
                if (!ignorePaths.contains(path)) {
                    // 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
                        dcBuilder.add(dcEntry);
                    }
                }
            }

            // release the treewalk
            treeWalk.release();
        }

        // finish temporary in-core index used for this commit
        dcBuilder.finish();
    } finally {
        inserter.release();
    }
    return inCoreIndex;
}

From source file:com.google.gerrit.server.git.ReviewNoteMerger.java

License:Eclipse Distribution License

@Override
public Note merge(Note base, Note ours, Note theirs, ObjectReader reader, ObjectInserter inserter)
        throws IOException {
    if (ours == null) {
        return theirs;
    }/*from   w  w  w .  jav a 2  s . co m*/
    if (theirs == null) {
        return ours;
    }
    if (ours.getData().equals(theirs.getData())) {
        return ours;
    }

    ObjectLoader lo = reader.open(ours.getData());
    byte[] sep = new byte[] { '\n' };
    ObjectLoader lt = reader.open(theirs.getData());
    try (ObjectStream os = lo.openStream();
            ByteArrayInputStream b = new ByteArrayInputStream(sep);
            ObjectStream ts = lt.openStream();
            UnionInputStream union = new UnionInputStream(os, b, ts)) {
        ObjectId noteData = inserter.insert(Constants.OBJ_BLOB, lo.getSize() + sep.length + lt.getSize(),
                union);
        return new Note(ours, noteData);
    }
}

From source file:com.google.gerrit.server.patch.AutoMerger.java

License:Apache License

/**
 * Perform an auto-merge of the parents of the given merge commit.
 *
 * @return auto-merge commit or {@code null} if an auto-merge commit
 *     couldn't be created. Headers of the returned RevCommit are parsed.
 *///from   w  w  w .jav a  2  s.c  o m
public RevCommit merge(Repository repo, RevWalk rw, final ObjectInserter ins, RevCommit merge,
        ThreeWayMergeStrategy mergeStrategy) throws IOException {
    rw.parseHeaders(merge);
    String hash = merge.name();
    String refName = RefNames.REFS_CACHE_AUTOMERGE + hash.substring(0, 2) + "/" + hash.substring(2);
    Ref ref = repo.getRefDatabase().exactRef(refName);
    if (ref != null && ref.getObjectId() != null) {
        RevObject obj = rw.parseAny(ref.getObjectId());
        if (obj instanceof RevCommit) {
            return (RevCommit) obj;
        }
        return commit(repo, rw, ins, refName, obj, merge);
    }

    ResolveMerger m = (ResolveMerger) mergeStrategy.newMerger(repo, true);
    DirCache dc = DirCache.newInCore();
    m.setDirCache(dc);
    m.setObjectInserter(new ObjectInserter.Filter() {
        @Override
        protected ObjectInserter delegate() {
            return ins;
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() {
        }
    });

    boolean couldMerge;
    try {
        couldMerge = m.merge(merge.getParents());
    } catch (IOException e) {
        // It is not safe to continue further down in this method as throwing
        // an exception most likely means that the merge tree was not created
        // and m.getMergeResults() is empty. This would mean that all paths are
        // unmerged and Gerrit UI would show all paths in the patch list.
        log.warn("Error attempting automerge " + refName, e);
        return null;
    }

    ObjectId treeId;
    if (couldMerge) {
        treeId = m.getResultTreeId();

    } else {
        RevCommit ours = merge.getParent(0);
        RevCommit theirs = merge.getParent(1);
        rw.parseBody(ours);
        rw.parseBody(theirs);
        String oursMsg = ours.getShortMessage();
        String theirsMsg = theirs.getShortMessage();

        String oursName = String.format("HEAD   (%s %s)", ours.abbreviate(6).name(),
                oursMsg.substring(0, Math.min(oursMsg.length(), 60)));
        String theirsName = String.format("BRANCH (%s %s)", theirs.abbreviate(6).name(),
                theirsMsg.substring(0, Math.min(theirsMsg.length(), 60)));

        MergeFormatter fmt = new MergeFormatter();
        Map<String, MergeResult<? extends Sequence>> r = m.getMergeResults();
        Map<String, ObjectId> resolved = new HashMap<>();
        for (Map.Entry<String, MergeResult<? extends Sequence>> entry : r.entrySet()) {
            MergeResult<? extends Sequence> p = entry.getValue();
            try (TemporaryBuffer buf = new TemporaryBuffer.LocalFile(null, 10 * 1024 * 1024)) {
                fmt.formatMerge(buf, p, "BASE", oursName, theirsName, UTF_8.name());
                buf.close();

                try (InputStream in = buf.openInputStream()) {
                    resolved.put(entry.getKey(), ins.insert(Constants.OBJ_BLOB, buf.length(), in));
                }
            }
        }

        DirCacheBuilder builder = dc.builder();
        int cnt = dc.getEntryCount();
        for (int i = 0; i < cnt;) {
            DirCacheEntry entry = dc.getEntry(i);
            if (entry.getStage() == 0) {
                builder.add(entry);
                i++;
                continue;
            }

            int next = dc.nextEntry(i);
            String path = entry.getPathString();
            DirCacheEntry res = new DirCacheEntry(path);
            if (resolved.containsKey(path)) {
                // For a file with content merge conflict that we produced a result
                // above on, collapse the file down to a single stage 0 with just
                // the blob content, and a randomly selected mode (the lowest stage,
                // which should be the merge base, or ours).
                res.setFileMode(entry.getFileMode());
                res.setObjectId(resolved.get(path));

            } else if (next == i + 1) {
                // If there is exactly one stage present, shouldn't be a conflict...
                res.setFileMode(entry.getFileMode());
                res.setObjectId(entry.getObjectId());

            } else if (next == i + 2) {
                // Two stages suggests a delete/modify conflict. Pick the higher
                // stage as the automatic result.
                entry = dc.getEntry(i + 1);
                res.setFileMode(entry.getFileMode());
                res.setObjectId(entry.getObjectId());

            } else {
                // 3 stage conflict, no resolve above
                // Punt on the 3-stage conflict and show the base, for now.
                res.setFileMode(entry.getFileMode());
                res.setObjectId(entry.getObjectId());
            }
            builder.add(res);
            i = next;
        }
        builder.finish();
        treeId = dc.writeTree(ins);
    }
    ins.flush();

    return commit(repo, rw, ins, refName, treeId, merge);
}

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;

    // 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));
        }//from w  w  w.  java 2 s.  c  o  m
        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.microsoft.gittf.core.tasks.CreateCommitForChangesetVersionSpecTask.java

License:Open Source License

private void createBlob(final ObjectInserter repositoryInserter,
        final Map<CommitTreePath, Map<CommitTreePath, CommitTreeEntry>> treeHierarchy,
        final ChangesetCommitItemReader previousChangesetCommitReader, final Item item,
        final TaskProgressMonitor progressMonitor) throws Exception {
    Check.notNull(repositoryInserter, "repositoryInserter"); //$NON-NLS-1$
    Check.notNull(treeHierarchy, "treeHierarchy"); //$NON-NLS-1$
    Check.notNull(previousChangesetCommitReader, "previousChangesetCommitReader"); //$NON-NLS-1$
    Check.notNull(item, "item"); //$NON-NLS-1$
    Check.notNull(progressMonitor, "progressMonitor"); //$NON-NLS-1$

    if (item.getItemType() == ItemType.FOLDER) {
        return;/*from   w  w  w. jav a 2  s . c o  m*/
    }

    File tempFile = null;
    InputStream tempInputStream = null;
    ObjectId blobID = null;

    try {
        blobID = previousChangesetCommitReader.getFileObjectId(item.getServerItem(), item.getChangeSetID());

        if (blobID == null || ObjectId.equals(blobID, ObjectId.zeroId())) {
            tempFile = File.createTempFile(GitTFConstants.GIT_TF_NAME, null, tempDir);

            try {
                versionControlService.downloadFile(item, tempFile.getAbsolutePath());
            } catch (VersionControlException e) {
                // if the user is denied read permissions on the file an
                // exception will be thrown here.

                final String itemName = item.getServerItem() == null ? "" : item.getServerItem(); //$NON-NLS-1$

                progressMonitor.displayWarning(Messages.formatString(
                        "CreateCommitForChangesetVersionSpecTask.NoContentDueToPermissionOrDestroyFormat", //$NON-NLS-1$
                        itemName));

                log.error(e);

                return;
            }

            if (tempFile.exists()) {
                tempInputStream = new FileInputStream(tempFile);
                blobID = repositoryInserter.insert(OBJ_BLOB, tempFile.length(), tempInputStream);
            } else {
                blobID = ObjectId.zeroId();
            }
        }

        FileMode fileMode = FileMode.REGULAR_FILE;

        /* handle executable files */
        if (item.getPropertyValues() != null) {
            if (PropertyConstants.EXECUTABLE_ENABLED_VALUE.equals(
                    PropertyUtils.selectMatching(item.getPropertyValues(), PropertyConstants.EXECUTABLE_KEY))) {
                fileMode = FileMode.EXECUTABLE_FILE;
            }
        }

        createBlob(repositoryInserter, treeHierarchy, item.getServerItem(), blobID, fileMode, progressMonitor);
    } finally {
        if (tempInputStream != null) {
            tempInputStream.close();
        }

        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:com.microsoft.gittf.core.tasks.CreateCommitForPendingSetsTask.java

License:Open Source License

private void createBlob(final ObjectInserter repositoryInserter,
        final Map<CommitTreePath, Map<CommitTreePath, CommitTreeEntry>> treeHierarchy,
        final PendingChange pendingChange, final boolean addBaseContent,
        final TaskProgressMonitor progressMonitor) throws Exception {
    if (pendingChange.getItemType() == ItemType.FOLDER) {
        return;/*from w ww  .  j  a v  a2  s. c om*/
    }

    File tempFile = null;
    InputStream tempInputStream = null;
    ObjectId blobID = null;

    try {
        tempFile = File.createTempFile(GitTFConstants.GIT_TF_NAME, null, tempDir);

        if (addBaseContent) {
            versionControlService.downloadBaseFile(pendingChange, tempFile.getAbsolutePath());
        } else {
            versionControlService.downloadShelvedFile(pendingChange, tempFile.getAbsolutePath());
        }

        if (tempFile.exists()) {
            tempInputStream = new FileInputStream(tempFile);
            blobID = repositoryInserter.insert(OBJ_BLOB, tempFile.length(), tempInputStream);
        } else {
            blobID = ObjectId.zeroId();
        }

        FileMode fileMode;

        /* handle executable files */
        if (pendingChange.getPropertyValues() != null) {
            if (PropertyConstants.EXECUTABLE_ENABLED_VALUE.equals(PropertyUtils
                    .selectMatching(pendingChange.getPropertyValues(), PropertyConstants.EXECUTABLE_KEY))) {
                fileMode = addBaseContent ? FileMode.REGULAR_FILE : FileMode.EXECUTABLE_FILE;
            } else {
                fileMode = addBaseContent ? FileMode.EXECUTABLE_FILE : FileMode.REGULAR_FILE;
            }
        } else {
            fileMode = FileMode.MISSING;
        }

        String serverItem = pendingChange.getSourceServerItem() != null && addBaseContent
                ? pendingChange.getSourceServerItem()
                : pendingChange.getServerItem();

        createBlob(repositoryInserter, treeHierarchy, serverItem, blobID, fileMode, progressMonitor);
    } finally {
        if (tempInputStream != null) {
            tempInputStream.close();
        }

        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:org.eclipse.egit.ui.internal.actions.CompareWithIndexActionHandler.java

License:Open Source License

private ITypedElement getHeadTypedElement(final IFile baseFile) throws IOException {
    final RepositoryMapping mapping = RepositoryMapping.getMapping(baseFile.getProject());
    final Repository repository = mapping.getRepository();
    final String gitPath = mapping.getRepoRelativePath(baseFile);

    DirCache dc = repository.lockDirCache();
    final DirCacheEntry entry = dc.getEntry(gitPath);
    dc.unlock();//from w  ww .  j a va 2s  .  c  om
    if (entry == null) {
        // the file cannot be found in the index
        return new GitCompareFileRevisionEditorInput.EmptyTypedElement(
                NLS.bind(UIText.CompareWithIndexAction_FileNotInIndex, baseFile.getName()));
    }

    IFileRevision nextFile = GitFileRevision.inIndex(repository, gitPath);
    final EditableRevision next = new EditableRevision(nextFile);

    IContentChangeListener listener = new IContentChangeListener() {
        public void contentChanged(IContentChangeNotifier source) {
            final byte[] newContent = next.getModifiedContent();
            DirCache cache = null;
            try {
                cache = repository.lockDirCache();
                DirCacheEditor editor = cache.editor();
                editor.add(new PathEdit(gitPath) {
                    @Override
                    public void apply(DirCacheEntry ent) {
                        ent.copyMetaData(entry);

                        ObjectInserter inserter = repository.newObjectInserter();
                        ent.copyMetaData(entry);
                        ent.setLength(newContent.length);
                        ent.setLastModified(System.currentTimeMillis());
                        InputStream in = new ByteArrayInputStream(newContent);
                        try {
                            ent.setObjectId(inserter.insert(Constants.OBJ_BLOB, newContent.length, in));
                            inserter.flush();
                        } catch (IOException ex) {
                            throw new RuntimeException(ex);
                        } finally {
                            try {
                                in.close();
                            } catch (IOException e) {
                                // ignore here
                            }
                        }
                    }
                });
                try {
                    editor.commit();
                } catch (RuntimeException e) {
                    if (e.getCause() instanceof IOException)
                        throw (IOException) e.getCause();
                    else
                        throw e;
                }

            } catch (IOException e) {
                Activator.handleError(UIText.CompareWithIndexAction_errorOnAddToIndex, e, true);
            } finally {
                if (cache != null)
                    cache.unlock();
            }
        }
    };

    next.addContentChangeListener(listener);
    return next;
}

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

License:Apache License

/**
 * Creates an in-memory index of the issue change.
 *//*from   ww  w. jav a 2s .c  om*/
private static DirCache createTemporaryIndex(final Git git, final ObjectId headId,
        final Map<String, File> content) {

    final DirCache inCoreIndex = DirCache.newInCore();
    final DirCacheBuilder dcBuilder = inCoreIndex.builder();
    final ObjectInserter inserter = git.getRepository().newObjectInserter();
    boolean hadFile = false;
    final Set<String> paths = new HashSet<String>(content.size());

    try {
        for (final Map.Entry<String, File> pathAndContent : content.entrySet()) {
            final String gPath = fixPath(pathAndContent.getKey());
            paths.add(gPath);
            if (pathAndContent.getValue() != null) {
                hadFile = true;
                final DirCacheEntry dcEntry = new DirCacheEntry(gPath);
                dcEntry.setLength(pathAndContent.getValue().length());
                dcEntry.setLastModified(pathAndContent.getValue().lastModified());
                dcEntry.setFileMode(REGULAR_FILE);

                final InputStream inputStream = new FileInputStream(pathAndContent.getValue());
                try {
                    final ObjectId objectId = inserter.insert(Constants.OBJ_BLOB,
                            pathAndContent.getValue().length(), inputStream);
                    dcEntry.setObjectId(objectId);
                } finally {
                    inputStream.close();
                }

                dcBuilder.add(dcEntry);
            }

            if (!hadFile) {
                final DirCacheEditor editor = inCoreIndex.editor();
                editor.add(new DirCacheEditor.DeleteTree(gPath));
                editor.finish();
            }
        }

        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.contains(walkPath)) {
                    // add entries from HEAD for all other paths
                    // create a new DirCacheEntry with data retrieved from HEAD
                    final DirCacheEntry dcEntry = new DirCacheEntry(walkPath);
                    dcEntry.setObjectId(hTree.getEntryObjectId());
                    dcEntry.setFileMode(hTree.getEntryFileMode());

                    // add to temporary in-core index
                    dcBuilder.add(dcEntry);
                }
            }
            treeWalk.release();
        }

        dcBuilder.finish();

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

    return inCoreIndex;
}

From source file:org.kuali.student.git.model.NodeProcessor.java

License:Educational Community License

private ObjectId storeBlob(GitBranchData gbd, String path, long contentLength, long propContentLength) {

    try {/*from  w w  w  .  j  a va2s .  co  m*/

        long adjustedContentLength = contentLength - propContentLength;

        if (propContentLength > 0) {
            getInputStream().skip(propContentLength);
        }

        /*
         * We want to replace the contents of the path file with the content
         * that we read from the input stream.
         */

        ObjectInserter objectInserter = repo.newObjectInserter();

        ObjectId id = objectInserter.insert(Constants.OBJ_BLOB, adjustedContentLength,
                new BoundedInputStream(getInputStream(), adjustedContentLength));

        objectInserter.flush();
        objectInserter.release();

        return id;

    } catch (Exception e) {

        log.error("onNodeContentChanged failed: ", e);
        throw new RuntimeException("onNodeContentLength failed", e);
    }
}