Search in sources :

Example 1 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project zeppelin by apache.

the class GitNotebookRepo method revisionHistory.

@Override
public List<Revision> revisionHistory(String noteId, AuthenticationInfo subject) {
    List<Revision> history = Lists.newArrayList();
    LOG.debug("Listing history for {}:", noteId);
    try {
        Iterable<RevCommit> logs = git.log().addPath(noteId).call();
        for (RevCommit log : logs) {
            history.add(new Revision(log.getName(), log.getShortMessage(), log.getCommitTime()));
            LOG.debug(" - ({},{},{})", log.getName(), log.getCommitTime(), log.getFullMessage());
        }
    } catch (NoHeadException e) {
        //when no initial commit exists
        LOG.warn("No Head found for {}, {}", noteId, e.getMessage());
    } catch (GitAPIException e) {
        LOG.error("Failed to get logs for {}", noteId, e);
    }
    return history;
}
Also used : NoHeadException(org.eclipse.jgit.api.errors.NoHeadException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 2 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project checkstyle by checkstyle.

the class CommitValidationTest method resolveRevCommitsPair.

private static RevCommitsPair resolveRevCommitsPair(Repository repo) {
    RevCommitsPair revCommitIteratorPair;
    try (RevWalk revWalk = new RevWalk(repo)) {
        final Iterator<RevCommit> first;
        final Iterator<RevCommit> second;
        final ObjectId headId = repo.resolve(Constants.HEAD);
        final RevCommit headCommit = revWalk.parseCommit(headId);
        if (isMergeCommit(headCommit)) {
            final RevCommit firstParent = headCommit.getParent(0);
            final RevCommit secondParent = headCommit.getParent(1);
            try (Git git = new Git(repo)) {
                first = git.log().add(firstParent).call().iterator();
                second = git.log().add(secondParent).call().iterator();
            }
        } else {
            try (Git git = new Git(repo)) {
                first = git.log().call().iterator();
            }
            second = Collections.emptyIterator();
        }
        revCommitIteratorPair = new RevCommitsPair(new OmitMergeCommitsIterator(first), new OmitMergeCommitsIterator(second));
    } catch (GitAPIException | IOException ex) {
        revCommitIteratorPair = new RevCommitsPair();
    }
    return revCommitIteratorPair;
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) ObjectId(org.eclipse.jgit.lib.ObjectId) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 3 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project che by eclipse.

the class JGitConnection method fetch.

@Override
public void fetch(FetchParams params) throws GitException, UnauthorizedException {
    String remoteName = params.getRemote();
    String remoteUri;
    try {
        List<RefSpec> fetchRefSpecs;
        List<String> refSpec = params.getRefSpec();
        if (!refSpec.isEmpty()) {
            fetchRefSpecs = new ArrayList<>(refSpec.size());
            for (String refSpecItem : refSpec) {
                RefSpec fetchRefSpec = //
                (refSpecItem.indexOf(':') < 0) ? //
                new RefSpec(Constants.R_HEADS + refSpecItem + ":") : new RefSpec(refSpecItem);
                fetchRefSpecs.add(fetchRefSpec);
            }
        } else {
            fetchRefSpecs = Collections.emptyList();
        }
        FetchCommand fetchCommand = getGit().fetch();
        // (otherwise JGit fails)
        if (remoteName != null && refSpec.isEmpty()) {
            boolean found = false;
            List<Remote> configRemotes = remoteList(null, false);
            for (Remote configRemote : configRemotes) {
                if (remoteName.equals(configRemote.getName())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                fetchRefSpecs = Collections.singletonList(new RefSpec(Constants.HEAD + ":" + Constants.FETCH_HEAD));
            }
        }
        if (remoteName == null) {
            remoteName = Constants.DEFAULT_REMOTE_NAME;
        }
        fetchCommand.setRemote(remoteName);
        remoteUri = getRepository().getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName, ConfigConstants.CONFIG_KEY_URL);
        fetchCommand.setRefSpecs(fetchRefSpecs);
        int timeout = params.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }
        fetchCommand.setRemoveDeletedRefs(params.isRemoveDeletedRefs());
        executeRemoteCommand(remoteUri, fetchCommand, params.getUsername(), params.getPassword());
    } catch (GitException | GitAPIException exception) {
        String errorMessage;
        if (exception.getMessage().contains("Invalid remote: ")) {
            errorMessage = ERROR_NO_REMOTE_REPOSITORY;
        } else if ("Nothing to fetch.".equals(exception.getMessage())) {
            return;
        } else {
            errorMessage = generateExceptionMessage(exception);
        }
        throw new GitException(errorMessage, exception);
    }
}
Also used : GitException(org.eclipse.che.api.git.exception.GitException) Remote(org.eclipse.che.api.git.shared.Remote) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RefSpec(org.eclipse.jgit.transport.RefSpec) FetchCommand(org.eclipse.jgit.api.FetchCommand)

Example 4 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project che by eclipse.

the class JGitConnection method merge.

@Override
public MergeResult merge(String commit) throws GitException {
    org.eclipse.jgit.api.MergeResult jGitMergeResult;
    MergeResult.MergeStatus status;
    try {
        Ref ref = repository.findRef(commit);
        if (ref == null) {
            throw new GitException("Invalid reference to commit for merge " + commit);
        }
        // Shorten local branch names by removing '/refs/heads/' from the beginning
        String name = ref.getName();
        if (name.startsWith(Constants.R_HEADS)) {
            name = name.substring(Constants.R_HEADS.length());
        }
        jGitMergeResult = getGit().merge().include(name, ref.getObjectId()).call();
    } catch (CheckoutConflictException exception) {
        jGitMergeResult = new org.eclipse.jgit.api.MergeResult(exception.getConflictingPaths());
    } catch (IOException | GitAPIException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
    switch(jGitMergeResult.getMergeStatus()) {
        case ALREADY_UP_TO_DATE:
            status = MergeResult.MergeStatus.ALREADY_UP_TO_DATE;
            break;
        case CONFLICTING:
            status = MergeResult.MergeStatus.CONFLICTING;
            break;
        case FAILED:
            status = MergeResult.MergeStatus.FAILED;
            break;
        case FAST_FORWARD:
            status = MergeResult.MergeStatus.FAST_FORWARD;
            break;
        case MERGED:
            status = MergeResult.MergeStatus.MERGED;
            break;
        case NOT_SUPPORTED:
            status = MergeResult.MergeStatus.NOT_SUPPORTED;
            break;
        case CHECKOUT_CONFLICT:
            status = MergeResult.MergeStatus.CONFLICTING;
            break;
        default:
            throw new IllegalStateException("Unknown merge status " + jGitMergeResult.getMergeStatus());
    }
    ObjectId[] jGitMergedCommits = jGitMergeResult.getMergedCommits();
    List<String> mergedCommits = new ArrayList<>();
    if (jGitMergedCommits != null) {
        for (ObjectId jGitMergedCommit : jGitMergedCommits) {
            mergedCommits.add(jGitMergedCommit.getName());
        }
    }
    List<String> conflicts;
    if (org.eclipse.jgit.api.MergeResult.MergeStatus.CHECKOUT_CONFLICT.equals(jGitMergeResult.getMergeStatus())) {
        conflicts = jGitMergeResult.getCheckoutConflicts();
    } else {
        Map<String, int[][]> jGitConflicts = jGitMergeResult.getConflicts();
        conflicts = jGitConflicts != null ? new ArrayList<>(jGitConflicts.keySet()) : Collections.emptyList();
    }
    Map<String, ResolveMerger.MergeFailureReason> jGitFailing = jGitMergeResult.getFailingPaths();
    ObjectId newHead = jGitMergeResult.getNewHead();
    return newDto(MergeResult.class).withFailed(jGitFailing != null ? new ArrayList<>(jGitFailing.keySet()) : Collections.emptyList()).withNewHead(newHead != null ? newHead.getName() : null).withMergeStatus(status).withConflicts(conflicts).withMergedCommits(mergedCommits);
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) GitException(org.eclipse.che.api.git.exception.GitException) MergeResult(org.eclipse.che.api.git.shared.MergeResult) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CheckoutConflictException(org.eclipse.jgit.api.errors.CheckoutConflictException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Ref(org.eclipse.jgit.lib.Ref)

Example 5 with GitAPIException

use of org.eclipse.jgit.api.errors.GitAPIException in project che by eclipse.

the class JGitConnection method push.

@Override
public PushResponse push(PushParams params) throws GitException, UnauthorizedException {
    List<Map<String, String>> updates = new ArrayList<>();
    String currentBranch = getCurrentBranch();
    String remoteName = params.getRemote();
    String remoteUri = getRepository().getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName, ConfigConstants.CONFIG_KEY_URL);
    PushCommand pushCommand = getGit().push();
    if (params.getRemote() != null) {
        pushCommand.setRemote(remoteName);
    }
    List<String> refSpec = params.getRefSpec();
    if (!refSpec.isEmpty()) {
        pushCommand.setRefSpecs(refSpec.stream().map(RefSpec::new).collect(Collectors.toList()));
    }
    pushCommand.setForce(params.isForce());
    int timeout = params.getTimeout();
    if (timeout > 0) {
        pushCommand.setTimeout(timeout);
    }
    try {
        @SuppressWarnings("unchecked") Iterable<PushResult> pushResults = (Iterable<PushResult>) executeRemoteCommand(remoteUri, pushCommand, params.getUsername(), params.getPassword());
        PushResult pushResult = pushResults.iterator().next();
        String commandOutput = pushResult.getMessages().isEmpty() ? "Successfully pushed to " + remoteUri : pushResult.getMessages();
        Collection<RemoteRefUpdate> refUpdates = pushResult.getRemoteUpdates();
        for (RemoteRefUpdate remoteRefUpdate : refUpdates) {
            final String remoteRefName = remoteRefUpdate.getRemoteName();
            // check status only for branch given in the URL or tags - (handle special "refs/for" case)
            String shortenRefFor = remoteRefName.startsWith("refs/for/") ? remoteRefName.substring("refs/for/".length()) : remoteRefName;
            if (!currentBranch.equals(Repository.shortenRefName(remoteRefName)) && !currentBranch.equals(shortenRefFor) && !remoteRefName.startsWith(Constants.R_TAGS)) {
                continue;
            }
            Map<String, String> update = new HashMap<>();
            RemoteRefUpdate.Status status = remoteRefUpdate.getStatus();
            if (status != RemoteRefUpdate.Status.OK) {
                List<String> refSpecs = params.getRefSpec();
                if (remoteRefUpdate.getStatus() == RemoteRefUpdate.Status.UP_TO_DATE) {
                    commandOutput = INFO_PUSH_IGNORED_UP_TO_DATE;
                } else {
                    String remoteBranch = !refSpecs.isEmpty() ? refSpecs.get(0).split(REFSPEC_COLON)[1] : "master";
                    String errorMessage = format(ERROR_PUSH_CONFLICTS_PRESENT, currentBranch + BRANCH_REFSPEC_SEPERATOR + remoteBranch, remoteUri);
                    if (remoteRefUpdate.getMessage() != null) {
                        errorMessage += "\nError errorMessage: " + remoteRefUpdate.getMessage() + ".";
                    }
                    throw new GitException(errorMessage);
                }
            }
            if (status != RemoteRefUpdate.Status.UP_TO_DATE || !remoteRefName.startsWith(Constants.R_TAGS)) {
                update.put(KEY_COMMIT_MESSAGE, remoteRefUpdate.getMessage());
                update.put(KEY_RESULT, status.name());
                TrackingRefUpdate refUpdate = remoteRefUpdate.getTrackingRefUpdate();
                if (refUpdate != null) {
                    update.put(KEY_REMOTENAME, Repository.shortenRefName(refUpdate.getLocalName()));
                    update.put(KEY_LOCALNAME, Repository.shortenRefName(refUpdate.getRemoteName()));
                } else {
                    update.put(KEY_REMOTENAME, Repository.shortenRefName(remoteRefUpdate.getSrcRef()));
                    update.put(KEY_LOCALNAME, Repository.shortenRefName(remoteRefUpdate.getRemoteName()));
                }
                updates.add(update);
            }
        }
        return newDto(PushResponse.class).withCommandOutput(commandOutput).withUpdates(updates);
    } catch (GitAPIException exception) {
        if ("origin: not found.".equals(exception.getMessage())) {
            throw new GitException(ERROR_NO_REMOTE_REPOSITORY, exception);
        } else {
            String message = generateExceptionMessage(exception);
            throw new GitException(message, exception);
        }
    }
}
Also used : RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) HashMap(java.util.HashMap) GitException(org.eclipse.che.api.git.exception.GitException) ArrayList(java.util.ArrayList) PushResult(org.eclipse.jgit.transport.PushResult) TrackingRefUpdate(org.eclipse.jgit.transport.TrackingRefUpdate) PushCommand(org.eclipse.jgit.api.PushCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RefSpec(org.eclipse.jgit.transport.RefSpec) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap)

Aggregations

GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)49 IOException (java.io.IOException)23 GitException (org.eclipse.che.api.git.exception.GitException)18 Git (org.eclipse.jgit.api.Git)18 File (java.io.File)14 RevCommit (org.eclipse.jgit.revwalk.RevCommit)12 ArrayList (java.util.ArrayList)11 ObjectId (org.eclipse.jgit.lib.ObjectId)11 Ref (org.eclipse.jgit.lib.Ref)10 Repository (org.eclipse.jgit.lib.Repository)9 UsernamePasswordCredentialsProvider (org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider)8 RevWalk (org.eclipse.jgit.revwalk.RevWalk)7 RefSpec (org.eclipse.jgit.transport.RefSpec)7 PushResult (org.eclipse.jgit.transport.PushResult)6 HashMap (java.util.HashMap)5 DiffCommitFile (org.eclipse.che.api.git.shared.DiffCommitFile)5 CheckoutConflictException (org.eclipse.jgit.api.errors.CheckoutConflictException)5 GitUser (org.eclipse.che.api.git.shared.GitUser)4 AddCommand (org.eclipse.jgit.api.AddCommand)4 CloneCommand (org.eclipse.jgit.api.CloneCommand)4