Example usage for org.eclipse.jgit.api.errors JGitInternalException JGitInternalException

List of usage examples for org.eclipse.jgit.api.errors JGitInternalException JGitInternalException

Introduction

In this page you can find the example usage for org.eclipse.jgit.api.errors JGitInternalException JGitInternalException.

Prototype

public JGitInternalException(String message, Throwable cause) 

Source Link

Document

Construct an exception for low-level internal exceptions

Usage

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

@Override
public DirCache call() throws GitAPIException {
    if (filepatterns.isEmpty()) {
        throw new NoFilepatternException(JGitText.get().atLeastOnePatternIsRequired);
    }//from  w  w  w.  j  av a 2 s  .c o m
    checkCallable();
    boolean addAll = filepatterns.contains("."); //$NON-NLS-1$
    try (ObjectInserter inserter = repo.newObjectInserter();
            NameConflictTreeWalk tw = new NameConflictTreeWalk(repo)) {
        tw.setOperationType(OperationType.CHECKIN_OP);
        dirCache.lock();
        DirCacheBuilder builder = dirCache.builder();
        tw.addTree(new DirCacheBuildIterator(builder));
        if (workingTreeIterator == null)
            workingTreeIterator = new FileTreeIterator(repo);
        workingTreeIterator.setDirCacheIterator(tw, 0);
        tw.addTree(workingTreeIterator);
        if (!addAll) {
            tw.setFilter(PathFilterGroup.createFromStrings(filepatterns));
        }

        byte[] lastAdded = null;

        while (tw.next()) {
            DirCacheIterator c = tw.getTree(0, DirCacheIterator.class);
            WorkingTreeIterator f = tw.getTree(1, WorkingTreeIterator.class);
            if (c == null && f != null && f.isEntryIgnored()) {
                // file is not in index but is ignored, do nothing
                continue;
            } else if (c == null && update) {
                // Only update of existing entries was requested.
                continue;
            }

            DirCacheEntry entry = c != null ? c.getDirCacheEntry() : null;
            if (entry != null && entry.getStage() > 0 && lastAdded != null
                    && lastAdded.length == tw.getPathLength()
                    && tw.isPathPrefix(lastAdded, lastAdded.length) == 0) {
                // 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.
                continue;
            }

            if (tw.isSubtree() && !tw.isDirectoryFileConflict()) {
                tw.enterSubtree();
                continue;
            }

            if (f == null) { // working tree file does not exist
                if (entry != null && (!update || GITLINK == entry.getFileMode())) {
                    builder.add(entry);
                }
                continue;
            }

            if (entry != null && entry.isAssumeValid()) {
                // Index entry is marked assume valid. Even though
                // the user specified the file to be added JGit does
                // not consider the file for addition.
                builder.add(entry);
                continue;
            }

            if ((f.getEntryRawMode() == TYPE_TREE && f.getIndexFileMode(c) != FileMode.GITLINK)
                    || (f.getEntryRawMode() == TYPE_GITLINK && f.getIndexFileMode(c) == FileMode.TREE)) {
                // Index entry exists and is symlink, gitlink or file,
                // otherwise the tree would have been entered above.
                // Replace the index entry by diving into tree of files.
                tw.enterSubtree();
                continue;
            }

            byte[] path = tw.getRawPath();
            if (entry == null || entry.getStage() > 0) {
                entry = new DirCacheEntry(path);
            }
            FileMode mode = f.getIndexFileMode(c);
            entry.setFileMode(mode);

            if (GITLINK != mode) {
                entry.setLength(f.getEntryLength());
                entry.setLastModified(f.getEntryLastModified());
                long len = f.getEntryContentLength();
                try (InputStream in = f.openEntryStream()) {
                    ObjectId id = inserter.insert(OBJ_BLOB, len, in);
                    entry.setObjectId(id);
                }
            } else {
                entry.setLength(0);
                entry.setLastModified(0);
                entry.setObjectId(f.getEntryObjectId());
            }
            builder.add(entry);
            lastAdded = path;
        }
        inserter.flush();
        builder.commit();
        setCallable(false);
    } catch (IOException e) {
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof FilterFailedException)
            throw (FilterFailedException) cause;
        throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfAddCommand, e);
    } finally {
        if (dirCache != null) {
            dirCache.unlock();
        }
    }
    return dirCache;

}

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

/**
 * Executes the {@code commit} command with all the options and parameters
 * collected by the setter methods of this class. Each instance of this
 * class should only be used for one invocation of the command (means: one
 * call to {@link #call()})/*from  ww w  .  java  2s  .c om*/
 *
 * @return a {@link RevCommit} object representing the successful commit.
 * @throws NoHeadException
 *             when called on a git repo without a HEAD reference
 * @throws NoMessageException
 *             when called without specifying a commit message
 * @throws UnmergedPathsException
 *             when the current index contained unmerged paths (conflicts)
 * @throws ConcurrentRefUpdateException
 *             when HEAD or branch ref is updated concurrently by someone
 *             else
 * @throws WrongRepositoryStateException
 *             when repository is not in the right state for committing
 * @throws AbortedByHookException
 *             if there are either pre-commit or commit-msg hooks present in
 *             the repository and one of them rejects the commit.
 */
public RevCommit call() throws GitAPIException, NoHeadException, NoMessageException, UnmergedPathsException,
        ConcurrentRefUpdateException, WrongRepositoryStateException, AbortedByHookException {
    checkCallable();
    Collections.sort(only);

    try (RevWalk rw = new RevWalk(repo)) {
        RepositoryState state = repo.getRepositoryState();

        if (!noVerify) {
            Hooks.preCommit(repo, hookOutRedirect).call();
        }

        processOptions(state, rw);

        if (all && !repo.isBare()) {
            try (Git git = new Git(repo)) {
                git.add().addFilepattern(".") //$NON-NLS-1$
                        .setUpdate(true).call();
            } catch (NoFilepatternException e) {
                // should really not happen
                throw new JGitInternalException(e.getMessage(), e);
            }
        }

        Ref head = repo.findRef(Constants.HEAD);
        if (head == null) {
            throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
        }

        // determine the current HEAD and the commit it is referring to
        ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$
        if (headId == null && amend)
            throw new WrongRepositoryStateException(JGitText.get().commitAmendOnInitialNotPossible);

        if (headId != null) {
            if (amend) {
                RevCommit previousCommit = rw.parseCommit(headId);
                for (RevCommit p : previousCommit.getParents())
                    parents.add(p.getId());
                if (author == null)
                    author = previousCommit.getAuthorIdent();
            } else {
                parents.add(0, headId);
            }
        }
        if (!noVerify) {
            message = Hooks.commitMsg(repo, hookOutRedirect).setCommitMessage(message).call();
        }

        // lock the index
        //         DirCache index = repo.lockDirCache();
        index.lock();
        try (ObjectInserter odi = repo.newObjectInserter()) {
            if (!only.isEmpty())
                index = createTemporaryIndex(headId, index, rw);

            // Write the index as tree to the object database. This may
            // fail for example when the index contains unmerged paths
            // (unresolved conflicts)
            ObjectId indexTreeId = index.writeTree(odi);

            if (insertChangeId)
                insertChangeId(indexTreeId);

            // Check for empty commits
            if (headId != null && !allowEmpty.booleanValue()) {
                RevCommit headCommit = rw.parseCommit(headId);
                headCommit.getTree();
                if (indexTreeId.equals(headCommit.getTree())) {
                    return null;
                }
            }

            // Create a Commit object, populate it and write it
            CommitBuilder commit = new CommitBuilder();
            commit.setCommitter(committer);
            commit.setAuthor(author);
            commit.setMessage(message);

            commit.setParentIds(parents);
            commit.setTreeId(indexTreeId);
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevCommit revCommit = rw.parseCommit(commitId);
            RefUpdate ru = repo.updateRef(Constants.HEAD);
            ru.setNewObjectId(commitId);
            if (reflogComment != null) {
                ru.setRefLogMessage(reflogComment, false);
            } else {
                String prefix = amend ? "commit (amend): " //$NON-NLS-1$
                        : parents.size() == 0 ? "commit (initial): " //$NON-NLS-1$
                                : "commit: "; //$NON-NLS-1$
                ru.setRefLogMessage(prefix + revCommit.getShortMessage(), false);
            }
            if (headId != null) {
                ru.setExpectedOldObjectId(headId);
            } else {
                ru.setExpectedOldObjectId(ObjectId.zeroId());
            }
            Result rc = ru.forceUpdate();
            switch (rc) {
            case NEW:
            case FORCED:
            case FAST_FORWARD: {
                setCallable(false);
                if (state == RepositoryState.MERGING_RESOLVED || isMergeDuringRebase(state)) {
                    // Commit was successful. Now delete the files
                    // used for merge commits
                    repo.writeMergeCommitMsg(null);
                    repo.writeMergeHeads(null);
                } else if (state == RepositoryState.CHERRY_PICKING_RESOLVED) {
                    repo.writeMergeCommitMsg(null);
                    repo.writeCherryPickHead(null);
                } else if (state == RepositoryState.REVERTING_RESOLVED) {
                    repo.writeMergeCommitMsg(null);
                    repo.writeRevertHead(null);
                }
                return revCommit;
            }
            case REJECTED:
            case LOCK_FAILURE:
                throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
            default:
                throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                        Constants.HEAD, commitId.toString(), rc));
            }
        } finally {
            index.unlock();
        }
    } catch (UnmergedPathException e) {
        throw new UnmergedPathsException(e);
    } catch (IOException e) {
        throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
    }
}

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

/**
 * Sets default values for not explicitly specified options. Then validates
 * that all required data has been provided.
 *
 * @param state//from   w  ww. ja v  a2s  .  c om
 *            the state of the repository we are working on
 * @param rw
 *            the RevWalk to use
 *
 * @throws NoMessageException
 *             if the commit message has not been specified
 */
private void processOptions(RepositoryState state, RevWalk rw) throws NoMessageException {
    if (committer == null) {
        committer = new PersonIdent(repo);
    }
    if (author == null && !amend) {
        author = committer;
    }
    if (allowEmpty == null) {
        // JGit allows empty commits by default. Only when pathes are
        // specified the commit should not be empty. This behaviour differs
        // from native git but can only be adapted in the next release.
        // TODO(ch) align the defaults with native git
        allowEmpty = (only.isEmpty()) ? Boolean.TRUE : Boolean.FALSE;
    }
    // when doing a merge commit parse MERGE_HEAD and MERGE_MSG files
    if (state == RepositoryState.MERGING_RESOLVED || isMergeDuringRebase(state)) {
        try {
            parents = repo.readMergeHeads();
            if (parents != null) {
                for (int i = 0; i < parents.size(); i++) {
                    RevObject ro = rw.parseAny(parents.get(i));
                    if (ro instanceof RevTag)
                        parents.set(i, rw.peel(ro));
                }
            }
        } catch (IOException e) {
            throw new JGitInternalException(MessageFormat.format(
                    JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR, Constants.MERGE_HEAD, e), e);
        }
        if (message == null) {
            try {
                message = repo.readMergeCommitMsg();
            } catch (IOException e) {
                throw new JGitInternalException(MessageFormat.format(
                        JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR, Constants.MERGE_MSG, e), e);
            }
        }
    } else if (state == RepositoryState.SAFE && message == null) {
        try {
            message = repo.readSquashCommitMsg();
            if (message != null) {
                repo.writeSquashCommitMsg(null /* delete */);
            }
        } catch (IOException e) {
            throw new JGitInternalException(MessageFormat
                    .format(JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR, Constants.MERGE_MSG, e), e);
        }

    }
    if (message == null) {
        // as long as we don't support -C option we have to have
        // an explicit message
        throw new NoMessageException(JGitText.get().commitMessageNotSpecified);
    }
}

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

private boolean isMergeDuringRebase(RepositoryState state) {
    if (state != RepositoryState.REBASING_INTERACTIVE && state != RepositoryState.REBASING_MERGE) {
        return false;
    }/*from  w w  w .j a  va 2s.  c o  m*/
    try {
        return repo.readMergeHeads() != null;
    } catch (IOException e) {
        throw new JGitInternalException(MessageFormat
                .format(JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR, Constants.MERGE_HEAD, e), e);
    }
}

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 v a2  s .  com
 *
 * @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.tasktop.c2c.server.scm.service.GitServiceBean.java

License:Open Source License

/**
 * @param repo/*from  ww  w.  ja  v a  2  s.  c  o  m*/
 * @param git
 */
private void setBranchesAndTags(ScmRepository repo, Git git) {
    repo.setBranches(new ArrayList<String>());
    try {
        for (Ref ref : git.branchList().call()) {
            String refName = ref.getName();
            if (refName.startsWith(Constants.R_HEADS)) {
                refName = refName.substring(Constants.R_HEADS.length());
            }
            repo.getBranches().add(refName);
        }
    } catch (GitAPIException e) {
        throw new JGitInternalException(e.getMessage(), e);
    }

    RevWalk revWalk = new RevWalk(git.getRepository());
    Map<String, Ref> refList;
    repo.setTags(new ArrayList<String>());
    try {
        refList = git.getRepository().getRefDatabase().getRefs(Constants.R_TAGS);
        for (Ref ref : refList.values()) {
            repo.getTags().add(ref.getName().substring(Constants.R_TAGS.length()));
        }
    } catch (IOException e) {
        throw new JGitInternalException(e.getMessage(), e);
    } finally {
        revWalk.release();
    }
    Collections.sort(repo.getTags());

}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.agent.command.impl.CleanCommandImpl.java

License:Apache License

@NotNull
private WorkingDirStatus getWorkingDirStatus(@NotNull Repository repo) {
    FileTreeIterator workingTreeIt = new FileTreeIterator(repo);
    try {//from w ww . j  a  v a2  s .c om
        IndexDiff diff = new IndexDiff(repo, Constants.HEAD, workingTreeIt);
        diff.diff();
        return new WorkingDirStatus(diff);
    } catch (IOException e) {
        throw new JGitInternalException(e.getMessage(), e);
    }
}

From source file:org.craftercms.studio.impl.v1.util.git.CherryPickCommandEx.java

License:Eclipse Distribution License

/**
 * Executes the {@code Cherry-Pick} command with all the options and
 * parameters collected by the setter methods (e.g. {@link #include(Ref)} of
 * this class. Each instance of this class should only be used for one
 * invocation of the command. Don't call this method twice on an instance.
 *
 * @return the result of the cherry-pick
 * @throws GitAPIException//from   w w  w. j  a  v  a 2  s . c o m
 * @throws WrongRepositoryStateException
 * @throws ConcurrentRefUpdateException
 * @throws UnmergedPathsException
 * @throws NoMessageException
 * @throws NoHeadException
 */
@Override
public CherryPickResult call() throws GitAPIException {
    RevCommit newHead = null;
    List<Ref> cherryPickedRefs = new LinkedList<>();
    checkCallable();

    try (RevWalk revWalk = new RevWalk(repo)) {

        // get the head commit
        Ref headRef = repo.exactRef(Constants.HEAD);
        if (headRef == null)
            throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);

        newHead = revWalk.parseCommit(headRef.getObjectId());

        // loop through all refs to be cherry-picked
        for (Ref src : commits) {
            // get the commit to be cherry-picked
            // handle annotated tags
            ObjectId srcObjectId = src.getPeeledObjectId();
            if (srcObjectId == null)
                srcObjectId = src.getObjectId();
            RevCommit srcCommit = revWalk.parseCommit(srcObjectId);

            Merger merger = strategy.newMerger(repo);
            if (merger.merge(newHead, srcCommit)) {
                if (AnyObjectId.equals(newHead.getTree().getId(), merger.getResultTreeId()))
                    continue;
                DirCacheCheckout dco = new DirCacheCheckout(repo, newHead.getTree(), repo.lockDirCache(),
                        merger.getResultTreeId());
                dco.setFailOnConflict(true);
                dco.checkout();
                if (!noCommit)
                    newHead = new Git(getRepository()).commit().setMessage(srcCommit.getFullMessage())
                            .setReflogComment(reflogPrefix + " " //$NON-NLS-1$
                                    + srcCommit.getShortMessage())
                            .setAuthor(srcCommit.getAuthorIdent()).setNoVerify(true).call();
                cherryPickedRefs.add(src);
            } else {
                return CherryPickResult.CONFLICT;
            }
        }
    } catch (IOException e) {
        throw new JGitInternalException(
                MessageFormat.format(JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand, e), e);
    }
    return new CherryPickResult(newHead, cherryPickedRefs);
}

From source file:org.eclipse.orion.server.gerritfs.DiffCommand.java

License:Eclipse Distribution License

/**
 * Executes the {@code Diff} command with all the options and parameters collected by the setter methods (e.g. {@link #setCached(boolean)} of this class.
 * Each instance of this class should only be used for one invocation of the command. Don't call this method twice on an instance.
 *
 * @return a DiffEntry for each path which is different
 *///from   w  w w .  ja  v a 2 s. co m
@Override
public List<DiffEntry> call() throws GitAPIException {
    final DiffFormatter diffFmt;
    if (out != null && !showNameAndStatusOnly)
        diffFmt = new DiffFormatter(new BufferedOutputStream(out));
    else
        diffFmt = new DiffFormatter(NullOutputStream.INSTANCE);
    if (ignoreWS)
        diffFmt.setDiffComparator(RawTextComparator.WS_IGNORE_ALL);
    diffFmt.setRepository(repo);
    diffFmt.setProgressMonitor(monitor);
    try {
        if (cached) {
            if (oldTree == null) {
                ObjectId head = repo.resolve(HEAD + "^{tree}"); //$NON-NLS-1$
                if (head == null)
                    throw new NoHeadException(JGitText.get().cannotReadTree);
                CanonicalTreeParser p = new CanonicalTreeParser();
                ObjectReader reader = repo.newObjectReader();
                try {
                    p.reset(reader, head);
                } finally {
                    reader.release();
                }
                oldTree = p;
            }
            newTree = new DirCacheIterator(repo.readDirCache());
        } else {
            if (oldTree == null)
                oldTree = new DirCacheIterator(repo.readDirCache());
            if (newTree == null)
                newTree = new FileTreeIterator(repo);
        }

        diffFmt.setPathFilter(pathFilter);

        List<DiffEntry> result = diffFmt.scan(oldTree, newTree);
        if (showNameAndStatusOnly)
            return result;
        else {
            if (contextLines >= 0)
                diffFmt.setContext(contextLines);
            if (destinationPrefix != null)
                diffFmt.setNewPrefix(destinationPrefix);
            if (sourcePrefix != null)
                diffFmt.setOldPrefix(sourcePrefix);
            diffFmt.format(result);
            diffFmt.flush();
            return result;
        }
    } catch (IOException e) {
        throw new JGitInternalException(e.getMessage(), e);
    } finally {
        diffFmt.release();
    }
}

From source file:org.eclipse.orion.server.git.jobs.LogCommand.java

License:Eclipse Distribution License

/**
 * Executes the {@code Log} command with all the options and parameters collected by the setter methods (e.g. {@link #add(AnyObjectId)},
 * {@link #not(AnyObjectId)}, ..) of this class. Each instance of this class should only be used for one invocation of the command. Don't call this method
 * twice on an instance.//  w w w  .j  a  v  a 2 s  . c o  m
 *
 * @return an iteration over RevCommits
 * @throws NoHeadException
 *             of the references ref cannot be resolved
 */
@Override
public Iterable<RevCommit> call() throws GitAPIException, NoHeadException {
    checkCallable();
    ArrayList<RevFilter> filters = new ArrayList<RevFilter>();

    if (pathFilters.size() > 0)
        walk.setTreeFilter(AndTreeFilter.create(PathFilterGroup.create(pathFilters), TreeFilter.ANY_DIFF));

    if (msgFilter != null)
        filters.add(msgFilter);
    if (authorFilter != null)
        filters.add(authorFilter);
    if (committerFilter != null)
        filters.add(committerFilter);
    if (sha1Filter != null)
        filters.add(sha1Filter);
    if (dateFilter != null)
        filters.add(dateFilter);
    if (skip > -1)
        filters.add(SkipRevFilter.create(skip));
    if (maxCount > -1)
        filters.add(MaxCountRevFilter.create(maxCount));
    RevFilter filter = null;
    if (filters.size() > 1) {
        filter = AndRevFilter.create(filters);
    } else if (filters.size() == 1) {
        filter = filters.get(0);
    }

    if (filter != null)
        walk.setRevFilter(filter);

    if (!startSpecified) {
        try {
            ObjectId headId = repo.resolve(Constants.HEAD);
            if (headId == null)
                throw new NoHeadException(JGitText.get().noHEADExistsAndNoExplicitStartingRevisionWasSpecified);
            add(headId);
        } catch (IOException e) {
            // all exceptions thrown by add() shouldn't occur and represent
            // severe low-level exception which are therefore wrapped
            throw new JGitInternalException(JGitText.get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD, e);
        }
    }
    setCallable(false);
    return walk;
}