Search in sources :

Example 1 with FetchResult

use of org.eclipse.jgit.transport.FetchResult in project che by eclipse.

the class JGitConnection method pull.

@Override
public PullResponse pull(PullParams params) throws GitException, UnauthorizedException {
    String remoteName = params.getRemote();
    String remoteUri;
    try {
        if (repository.getRepositoryState().equals(RepositoryState.MERGING)) {
            throw new GitException(ERROR_PULL_MERGING);
        }
        String fullBranch = repository.getFullBranch();
        if (!fullBranch.startsWith(Constants.R_HEADS)) {
            throw new DetachedHeadException(ERROR_PULL_HEAD_DETACHED);
        }
        String branch = fullBranch.substring(Constants.R_HEADS.length());
        StoredConfig config = repository.getConfig();
        if (remoteName == null) {
            remoteName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_REMOTE);
            if (remoteName == null) {
                remoteName = Constants.DEFAULT_REMOTE_NAME;
            }
        }
        remoteUri = config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName, ConfigConstants.CONFIG_KEY_URL);
        String remoteBranch;
        RefSpec fetchRefSpecs = null;
        String refSpec = params.getRefSpec();
        if (refSpec != null) {
            fetchRefSpecs = //
            (refSpec.indexOf(':') < 0) ? //
            new RefSpec(Constants.R_HEADS + refSpec + ":" + fullBranch) : new RefSpec(refSpec);
            remoteBranch = fetchRefSpecs.getSource();
        } else {
            remoteBranch = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_MERGE);
        }
        if (remoteBranch == null) {
            remoteBranch = fullBranch;
        }
        FetchCommand fetchCommand = getGit().fetch();
        fetchCommand.setRemote(remoteName);
        if (fetchRefSpecs != null) {
            fetchCommand.setRefSpecs(fetchRefSpecs);
        }
        int timeout = params.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }
        FetchResult fetchResult = (FetchResult) executeRemoteCommand(remoteUri, fetchCommand, params.getUsername(), params.getPassword());
        Ref remoteBranchRef = fetchResult.getAdvertisedRef(remoteBranch);
        if (remoteBranchRef == null) {
            remoteBranchRef = fetchResult.getAdvertisedRef(Constants.R_HEADS + remoteBranch);
        }
        if (remoteBranchRef == null) {
            throw new GitException(format(ERROR_PULL_REF_MISSING, remoteBranch));
        }
        org.eclipse.jgit.api.MergeResult mergeResult = getGit().merge().include(remoteBranchRef).call();
        if (mergeResult.getMergeStatus().equals(org.eclipse.jgit.api.MergeResult.MergeStatus.ALREADY_UP_TO_DATE)) {
            return newDto(PullResponse.class).withCommandOutput("Already up-to-date");
        }
        if (mergeResult.getConflicts() != null) {
            StringBuilder message = new StringBuilder(ERROR_PULL_MERGE_CONFLICT_IN_FILES);
            message.append(lineSeparator());
            Map<String, int[][]> allConflicts = mergeResult.getConflicts();
            for (String path : allConflicts.keySet()) {
                message.append(path).append(lineSeparator());
            }
            message.append(ERROR_PULL_AUTO_MERGE_FAILED);
            throw new GitException(message.toString());
        }
    } catch (CheckoutConflictException exception) {
        StringBuilder message = new StringBuilder(ERROR_CHECKOUT_CONFLICT);
        message.append(lineSeparator());
        for (String path : exception.getConflictingPaths()) {
            message.append(path).append(lineSeparator());
        }
        message.append(ERROR_PULL_COMMIT_BEFORE_MERGE);
        throw new GitException(message.toString(), exception);
    } catch (IOException | GitAPIException exception) {
        String errorMessage;
        if (exception.getMessage().equals("Invalid remote: " + remoteName)) {
            errorMessage = ERROR_NO_REMOTE_REPOSITORY;
        } else {
            errorMessage = generateExceptionMessage(exception);
        }
        throw new GitException(errorMessage, exception);
    }
    return newDto(PullResponse.class).withCommandOutput("Successfully pulled from " + remoteUri);
}
Also used : FetchResult(org.eclipse.jgit.transport.FetchResult) GitException(org.eclipse.che.api.git.exception.GitException) IOException(java.io.IOException) CheckoutConflictException(org.eclipse.jgit.api.errors.CheckoutConflictException) StoredConfig(org.eclipse.jgit.lib.StoredConfig) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Ref(org.eclipse.jgit.lib.Ref) RefSpec(org.eclipse.jgit.transport.RefSpec) PullResponse(org.eclipse.che.api.git.shared.PullResponse) FetchCommand(org.eclipse.jgit.api.FetchCommand) DetachedHeadException(org.eclipse.jgit.api.errors.DetachedHeadException)

Example 2 with FetchResult

use of org.eclipse.jgit.transport.FetchResult in project fabric8 by jboss-fuse.

the class DefaultPullPushPolicy method doPush.

@Override
public synchronized PushPolicyResult doPush(GitContext context, CredentialsProvider credentialsProvider) {
    StoredConfig config = git.getRepository().getConfig();
    String remoteUrl = config.getString("remote", remoteRef, "url");
    if (remoteUrl == null) {
        LOGGER.debug("No remote repository defined, so not doing a push");
        return new AbstractPushPolicyResult();
    }
    LOGGER.info("Pushing last change to: {}", remoteUrl);
    Iterator<PushResult> resit = null;
    Exception lastException = null;
    try {
        // clean working copy before the push
        // to remove not-tracked files
        git.clean().setCleanDirectories(true).call();
        // for file permissions
        git.reset().setMode(ResetCommand.ResetType.MIXED).call();
        // for other changes
        git.reset().setMode(ResetCommand.ResetType.HARD).call();
        resit = git.push().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider).setPushTags().setPushAll().call().iterator();
    } catch (Exception ex) {
        lastException = ex;
    }
    // Allow the commit to stay in the repository in case of push failure
    if (lastException != null) {
        LOGGER.warn("Cannot push because of: " + lastException.toString(), lastException);
        return new AbstractPushPolicyResult(lastException);
    }
    List<PushResult> pushResults = new ArrayList<>();
    Map<String, RemoteBranchChange> acceptedUpdates = new TreeMap<>();
    Map<String, RemoteBranchChange> rejectedUpdates = new TreeMap<>();
    // Collect the updates that are not ok
    while (resit.hasNext()) {
        PushResult pushResult = resit.next();
        pushResults.add(pushResult);
        for (RemoteRefUpdate refUpdate : pushResult.getRemoteUpdates()) {
            Status status = refUpdate.getStatus();
            ObjectId from = refUpdate.getTrackingRefUpdate() == null || refUpdate.getTrackingRefUpdate().getOldObjectId() == null ? refUpdate.getExpectedOldObjectId() : refUpdate.getTrackingRefUpdate().getOldObjectId();
            ObjectId to = refUpdate.getTrackingRefUpdate() == null || refUpdate.getTrackingRefUpdate().getNewObjectId() == null ? refUpdate.getNewObjectId() : refUpdate.getTrackingRefUpdate().getNewObjectId();
            if (status == Status.OK) {
                acceptedUpdates.put(refUpdate.getSrcRef(), new RemoteBranchChange(refUpdate.getSrcRef(), refUpdate).updated(from, to, "fast-forward"));
            } else if (status == Status.UP_TO_DATE) {
                acceptedUpdates.put(refUpdate.getSrcRef(), new RemoteBranchChange(refUpdate.getSrcRef(), refUpdate));
            } else {
                switch(status) {
                    case REJECTED_NONFASTFORWARD:
                        // typical problem when repos are not synced
                        rejectedUpdates.put(refUpdate.getSrcRef(), new RemoteBranchChange(refUpdate.getSrcRef(), refUpdate).rejected(from, to, "non fast-forward update"));
                        break;
                    case NOT_ATTEMPTED:
                    case REJECTED_NODELETE:
                    case REJECTED_REMOTE_CHANGED:
                    case REJECTED_OTHER_REASON:
                    case NON_EXISTING:
                    case AWAITING_REPORT:
                    default:
                        // ?
                        rejectedUpdates.put(refUpdate.getSrcRef(), new RemoteBranchChange(refUpdate.getSrcRef(), refUpdate).rejected(from, to, status.toString()));
                        break;
                }
            }
        }
    }
    // Reset to the last known good rev and make the commit/push fail
    for (String rejectedRefName : rejectedUpdates.keySet()) {
        RemoteRefUpdate rejectedRef = rejectedUpdates.get(rejectedRefName).getRemoteRefUpdate();
        LOGGER.warn("Rejected push: {}. Attempting to recreate local branch.", rejectedRef);
        String refName = rejectedRef.getRemoteName();
        String branch = refName.substring(refName.lastIndexOf('/') + 1);
        try {
            GitHelpers.checkoutBranch(git, branch);
            FetchResult fetchResult = git.fetch().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider).setRemote(remoteRef).setRefSpecs(new RefSpec("refs/heads/" + branch)).call();
            Ref fetchRef = fetchResult.getAdvertisedRef("refs/heads/" + branch);
            git.branchRename().setOldName(branch).setNewName(branch + "-tmp").call();
            git.checkout().setCreateBranch(true).setName(branch).setStartPoint(fetchRef.getObjectId().getName()).call();
            git.branchDelete().setBranchNames(branch + "-tmp").setForce(true).call();
            LOGGER.info("Local branch {} recreated from {}", branch, fetchRef.toString());
        } catch (Exception ex) {
            LOGGER.warn("Cannot recreate branch " + branch + " because of: " + ex.toString(), ex);
        }
    }
    PushPolicyResult result = new AbstractPushPolicyResult(pushResults, acceptedUpdates, rejectedUpdates, null);
    LOGGER.info("Push result: {}", result);
    return result;
}
Also used : RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) Status(org.eclipse.jgit.transport.RemoteRefUpdate.Status) MergeStatus(org.eclipse.jgit.api.MergeResult.MergeStatus) FetchResult(org.eclipse.jgit.transport.FetchResult) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) PushResult(org.eclipse.jgit.transport.PushResult) TreeMap(java.util.TreeMap) SocketTimeoutException(java.net.SocketTimeoutException) NoRemoteRepositoryException(org.eclipse.jgit.errors.NoRemoteRepositoryException) ConnectException(java.net.ConnectException) InvalidRemoteException(org.eclipse.jgit.api.errors.InvalidRemoteException) StoredConfig(org.eclipse.jgit.lib.StoredConfig) Ref(org.eclipse.jgit.lib.Ref) RefSpec(org.eclipse.jgit.transport.RefSpec)

Example 3 with FetchResult

use of org.eclipse.jgit.transport.FetchResult in project spring-cloud-config by spring-cloud.

the class JGitEnvironmentRepositoryTests method testMergeException.

@Test
public void testMergeException() throws Exception {
    Git git = mock(Git.class);
    CloneCommand cloneCommand = mock(CloneCommand.class);
    MockGitFactory factory = new MockGitFactory(git, cloneCommand);
    this.repository.setGitFactory(factory);
    // refresh()->shouldPull
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    when(git.status()).thenReturn(statusCommand);
    Repository repository = mock(Repository.class);
    when(git.getRepository()).thenReturn(repository);
    StoredConfig storedConfig = mock(StoredConfig.class);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(true);
    // refresh()->fetch
    FetchCommand fetchCommand = mock(FetchCommand.class);
    FetchResult fetchResult = mock(FetchResult.class);
    when(git.fetch()).thenReturn(fetchCommand);
    when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand);
    when(fetchCommand.call()).thenReturn(fetchResult);
    when(fetchResult.getTrackingRefUpdates()).thenReturn(Collections.<TrackingRefUpdate>emptyList());
    // refresh()->checkout
    CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
    // refresh()->checkout->containsBranch
    ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
    when(git.checkout()).thenReturn(checkoutCommand);
    when(git.branchList()).thenReturn(listBranchCommand);
    List<Ref> refs = new ArrayList<>();
    Ref ref = mock(Ref.class);
    refs.add(ref);
    when(ref.getName()).thenReturn("/master");
    when(listBranchCommand.call()).thenReturn(refs);
    // refresh()->merge
    MergeCommand mergeCommand = mock(MergeCommand.class);
    when(git.merge()).thenReturn(mergeCommand);
    // here is our exception we are testing
    when(mergeCommand.call()).thenThrow(new NotMergedException());
    // refresh()->return git.getRepository().findRef("HEAD").getObjectId().getName();
    Ref headRef = mock(Ref.class);
    when(repository.findRef(anyString())).thenReturn(headRef);
    ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 });
    when(headRef.getObjectId()).thenReturn(newObjectId);
    SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", "master");
    assertEquals(locations.getVersion(), newObjectId.getName());
    verify(git, times(0)).branchDelete();
}
Also used : CloneCommand(org.eclipse.jgit.api.CloneCommand) Status(org.eclipse.jgit.api.Status) NotMergedException(org.eclipse.jgit.api.errors.NotMergedException) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) FetchResult(org.eclipse.jgit.transport.FetchResult) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) MergeCommand(org.eclipse.jgit.api.MergeCommand) StatusCommand(org.eclipse.jgit.api.StatusCommand) StoredConfig(org.eclipse.jgit.lib.StoredConfig) ListBranchCommand(org.eclipse.jgit.api.ListBranchCommand) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) FetchCommand(org.eclipse.jgit.api.FetchCommand) Test(org.junit.Test)

Example 4 with FetchResult

use of org.eclipse.jgit.transport.FetchResult in project spring-cloud-config by spring-cloud.

the class JGitEnvironmentRepositoryTests method testResetHardException.

@Test
public void testResetHardException() throws Exception {
    Git git = mock(Git.class);
    CloneCommand cloneCommand = mock(CloneCommand.class);
    MockGitFactory factory = new MockGitFactory(git, cloneCommand);
    this.repository.setGitFactory(factory);
    // refresh()->shouldPull
    StatusCommand statusCommand = mock(StatusCommand.class);
    Status status = mock(Status.class);
    when(git.status()).thenReturn(statusCommand);
    Repository repository = mock(Repository.class);
    when(git.getRepository()).thenReturn(repository);
    StoredConfig storedConfig = mock(StoredConfig.class);
    when(repository.getConfig()).thenReturn(storedConfig);
    when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git");
    when(statusCommand.call()).thenReturn(status);
    when(status.isClean()).thenReturn(true).thenReturn(false);
    // refresh()->fetch
    FetchCommand fetchCommand = mock(FetchCommand.class);
    FetchResult fetchResult = mock(FetchResult.class);
    when(git.fetch()).thenReturn(fetchCommand);
    when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand);
    when(fetchCommand.call()).thenReturn(fetchResult);
    when(fetchResult.getTrackingRefUpdates()).thenReturn(Collections.<TrackingRefUpdate>emptyList());
    // refresh()->checkout
    CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
    // refresh()->checkout->containsBranch
    ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
    when(git.checkout()).thenReturn(checkoutCommand);
    when(git.branchList()).thenReturn(listBranchCommand);
    List<Ref> refs = new ArrayList<>();
    Ref ref = mock(Ref.class);
    refs.add(ref);
    when(ref.getName()).thenReturn("/master");
    when(listBranchCommand.call()).thenReturn(refs);
    // refresh()->merge
    MergeCommand mergeCommand = mock(MergeCommand.class);
    when(git.merge()).thenReturn(mergeCommand);
    // here
    when(mergeCommand.call()).thenThrow(new NotMergedException());
    // is
    // our
    // exception
    // we
    // are
    // testing
    // refresh()->hardReset
    ResetCommand resetCommand = mock(ResetCommand.class);
    when(git.reset()).thenReturn(resetCommand);
    when(resetCommand.call()).thenReturn(ref);
    // refresh()->return
    // git.getRepository().findRef("HEAD").getObjectId().getName();
    Ref headRef = mock(Ref.class);
    when(repository.findRef(anyString())).thenReturn(headRef);
    ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 });
    when(headRef.getObjectId()).thenReturn(newObjectId);
    SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", "master");
    assertEquals(locations.getVersion(), newObjectId.getName());
    verify(git, times(0)).branchDelete();
}
Also used : CloneCommand(org.eclipse.jgit.api.CloneCommand) Status(org.eclipse.jgit.api.Status) NotMergedException(org.eclipse.jgit.api.errors.NotMergedException) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) FetchResult(org.eclipse.jgit.transport.FetchResult) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) MergeCommand(org.eclipse.jgit.api.MergeCommand) StatusCommand(org.eclipse.jgit.api.StatusCommand) StoredConfig(org.eclipse.jgit.lib.StoredConfig) ListBranchCommand(org.eclipse.jgit.api.ListBranchCommand) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) FetchCommand(org.eclipse.jgit.api.FetchCommand) ResetCommand(org.eclipse.jgit.api.ResetCommand) Test(org.junit.Test)

Example 5 with FetchResult

use of org.eclipse.jgit.transport.FetchResult in project egit by eclipse.

the class FetchGerritChangePage method fetchChange.

private RevCommit fetchChange(String uri, RefSpec spec, IProgressMonitor monitor) throws CoreException, URISyntaxException, IOException {
    int timeout = Activator.getDefault().getPreferenceStore().getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT);
    List<RefSpec> specs = new ArrayList<>(1);
    specs.add(spec);
    String taskName = NLS.bind(UIText.FetchGerritChangePage_FetchingTaskName, spec.getSource());
    monitor.subTask(taskName);
    FetchResult fetchRes = new FetchOperationUI(repository, new URIish(uri), specs, timeout, false).execute(monitor);
    monitor.worked(1);
    try (RevWalk rw = new RevWalk(repository)) {
        return rw.parseCommit(fetchRes.getAdvertisedRef(spec.getSource()).getObjectId());
    }
}
Also used : URIish(org.eclipse.jgit.transport.URIish) RefSpec(org.eclipse.jgit.transport.RefSpec) FetchResult(org.eclipse.jgit.transport.FetchResult) ArrayList(java.util.ArrayList) RevWalk(org.eclipse.jgit.revwalk.RevWalk)

Aggregations

FetchResult (org.eclipse.jgit.transport.FetchResult)20 Ref (org.eclipse.jgit.lib.Ref)8 FetchCommand (org.eclipse.jgit.api.FetchCommand)7 ArrayList (java.util.ArrayList)6 Git (org.eclipse.jgit.api.Git)6 StoredConfig (org.eclipse.jgit.lib.StoredConfig)6 RefSpec (org.eclipse.jgit.transport.RefSpec)6 ObjectId (org.eclipse.jgit.lib.ObjectId)5 Repository (org.eclipse.jgit.lib.Repository)5 IOException (java.io.IOException)4 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)4 CheckoutCommand (org.eclipse.jgit.api.CheckoutCommand)3 CloneCommand (org.eclipse.jgit.api.CloneCommand)3 ListBranchCommand (org.eclipse.jgit.api.ListBranchCommand)3 MergeCommand (org.eclipse.jgit.api.MergeCommand)3 Status (org.eclipse.jgit.api.Status)3 StatusCommand (org.eclipse.jgit.api.StatusCommand)3 NotMergedException (org.eclipse.jgit.api.errors.NotMergedException)3 NoRemoteRepositoryException (org.eclipse.jgit.errors.NoRemoteRepositoryException)3 Test (org.junit.Test)3