Search in sources :

Example 1 with TrackingRefUpdate

use of org.eclipse.jgit.transport.TrackingRefUpdate 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)

Example 2 with TrackingRefUpdate

use of org.eclipse.jgit.transport.TrackingRefUpdate in project statecharts by Yakindu.

the class GitRepositoryExampleService method isUpToDate.

@Override
public boolean isUpToDate(IProgressMonitor monitor) {
    java.nio.file.Path storageLocation = getStorageLocation();
    try {
        FetchCommand fetch = Git.open(storageLocation.toFile()).fetch();
        FetchResult result = fetch.setProgressMonitor(new EclipseGitProgressTransformer(monitor)).setDryRun(true).call();
        Collection<TrackingRefUpdate> trackingRefUpdates = result.getTrackingRefUpdates();
        return trackingRefUpdates.size() == 0;
    } catch (RepositoryNotFoundException ex) {
        // This is the case when the examples are imported manually
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
        return true;
    }
}
Also used : FetchResult(org.eclipse.jgit.transport.FetchResult) FetchCommand(org.eclipse.jgit.api.FetchCommand) TrackingRefUpdate(org.eclipse.jgit.transport.TrackingRefUpdate) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException)

Example 3 with TrackingRefUpdate

use of org.eclipse.jgit.transport.TrackingRefUpdate in project gerrit by GerritCodeReview.

the class PushPermissionsIT method forceFetch.

private ObjectId forceFetch(String ref) throws Exception {
    TrackingRefUpdate u = testRepo.git().fetch().setRefSpecs("+" + ref + ":" + ref).call().getTrackingRefUpdate(ref);
    assertThat(u).isNotNull();
    switch(u.getResult()) {
        case NEW:
        case FAST_FORWARD:
        case FORCED:
            break;
        case IO_FAILURE:
        case LOCK_FAILURE:
        case NOT_ATTEMPTED:
        case NO_CHANGE:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case REJECTED_MISSING_OBJECT:
        case REJECTED_OTHER_REASON:
        case RENAMED:
        default:
            assertWithMessage("fetch failed to update local %s: %s", ref, u.getResult()).fail();
            break;
    }
    return u.getNewObjectId();
}
Also used : TrackingRefUpdate(org.eclipse.jgit.transport.TrackingRefUpdate)

Example 4 with TrackingRefUpdate

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

the class JGitEnvironmentRepository method deleteUntrackedLocalBranches.

/**
 * Deletes local branches if corresponding remote branch was removed.
 *
 * @param trackingRefUpdates list of tracking ref updates
 * @param git                git instance
 * @return list of deleted branches
 */
private Collection<String> deleteUntrackedLocalBranches(Collection<TrackingRefUpdate> trackingRefUpdates, Git git) {
    if (CollectionUtils.isEmpty(trackingRefUpdates)) {
        return Collections.emptyList();
    }
    Collection<String> branchesToDelete = new ArrayList<>();
    for (TrackingRefUpdate trackingRefUpdate : trackingRefUpdates) {
        ReceiveCommand receiveCommand = trackingRefUpdate.asReceiveCommand();
        if (receiveCommand.getType() == DELETE) {
            String localRefName = trackingRefUpdate.getLocalName();
            if (StringUtils.startsWithIgnoreCase(localRefName, LOCAL_BRANCH_REF_PREFIX)) {
                String localBranchName = localRefName.substring(LOCAL_BRANCH_REF_PREFIX.length(), localRefName.length());
                branchesToDelete.add(localBranchName);
            }
        }
    }
    if (CollectionUtils.isEmpty(branchesToDelete)) {
        return Collections.emptyList();
    }
    try {
        // make sure that deleted branch not a current one
        checkout(git, defaultLabel);
        return deleteBranches(git, branchesToDelete);
    } catch (Exception ex) {
        String message = format("Failed to delete %s branches.", branchesToDelete);
        warn(message, ex);
        return Collections.emptyList();
    }
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) ArrayList(java.util.ArrayList) TrackingRefUpdate(org.eclipse.jgit.transport.TrackingRefUpdate) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) NoRemoteRepositoryException(org.eclipse.jgit.errors.NoRemoteRepositoryException) IOException(java.io.IOException) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException)

Example 5 with TrackingRefUpdate

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

the class JGitEnvironmentRepositoryTests method shouldHandleExceptionWhileRemovingBranches.

@Test
public void shouldHandleExceptionWhileRemovingBranches() throws Exception {
    Git git = mock(Git.class);
    CloneCommand cloneCommand = mock(CloneCommand.class);
    MockGitFactory factory = new MockGitFactory(git, cloneCommand);
    this.repository.setGitFactory(factory);
    this.repository.setDeleteUntrackedBranches(true);
    // 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);
    TrackingRefUpdate trackingRefUpdate = mock(TrackingRefUpdate.class);
    Collection<TrackingRefUpdate> trackingRefUpdates = Collections.singletonList(trackingRefUpdate);
    when(git.fetch()).thenReturn(fetchCommand);
    when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand);
    when(fetchCommand.call()).thenReturn(fetchResult);
    when(fetchResult.getTrackingRefUpdates()).thenReturn(trackingRefUpdates);
    // refresh()->deleteBranch
    ReceiveCommand receiveCommand = mock(ReceiveCommand.class);
    when(trackingRefUpdate.asReceiveCommand()).thenReturn(receiveCommand);
    when(receiveCommand.getType()).thenReturn(ReceiveCommand.Type.DELETE);
    when(trackingRefUpdate.getLocalName()).thenReturn("refs/remotes/origin/feature/deletedBranchFromOrigin");
    DeleteBranchCommand deleteBranchCommand = mock(DeleteBranchCommand.class);
    when(git.branchDelete()).thenReturn(deleteBranchCommand);
    when(deleteBranchCommand.setBranchNames(eq("feature/deletedBranchFromOrigin"))).thenReturn(deleteBranchCommand);
    when(deleteBranchCommand.setForce(true)).thenReturn(deleteBranchCommand);
    // here
    when(deleteBranchCommand.call()).thenThrow(new NotMergedException());
    // is
    // our
    // exception
    // we
    // are
    // testing
    // 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
    MergeResult mergeResult = mock(MergeResult.class);
    MergeResult.MergeStatus mergeStatus = mock(MergeResult.MergeStatus.class);
    MergeCommand mergeCommand = mock(MergeCommand.class);
    when(git.merge()).thenReturn(mergeCommand);
    when(mergeCommand.call()).thenReturn(mergeResult);
    when(mergeResult.getMergeStatus()).thenReturn(mergeStatus);
    when(mergeStatus.isSuccessful()).thenReturn(true);
    // 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(deleteBranchCommand).setBranchNames(eq("feature/deletedBranchFromOrigin"));
    verify(deleteBranchCommand).setForce(true);
    verify(deleteBranchCommand).call();
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) FetchResult(org.eclipse.jgit.transport.FetchResult) ArrayList(java.util.ArrayList) MergeResult(org.eclipse.jgit.api.MergeResult) MergeCommand(org.eclipse.jgit.api.MergeCommand) TrackingRefUpdate(org.eclipse.jgit.transport.TrackingRefUpdate) StoredConfig(org.eclipse.jgit.lib.StoredConfig) ListBranchCommand(org.eclipse.jgit.api.ListBranchCommand) CloneCommand(org.eclipse.jgit.api.CloneCommand) Status(org.eclipse.jgit.api.Status) NotMergedException(org.eclipse.jgit.api.errors.NotMergedException) DeleteBranchCommand(org.eclipse.jgit.api.DeleteBranchCommand) ObjectId(org.eclipse.jgit.lib.ObjectId) StatusCommand(org.eclipse.jgit.api.StatusCommand) 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)

Aggregations

TrackingRefUpdate (org.eclipse.jgit.transport.TrackingRefUpdate)6 ArrayList (java.util.ArrayList)3 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)3 FetchResult (org.eclipse.jgit.transport.FetchResult)3 ReceiveCommand (org.eclipse.jgit.transport.ReceiveCommand)3 IOException (java.io.IOException)2 FetchCommand (org.eclipse.jgit.api.FetchCommand)2 Git (org.eclipse.jgit.api.Git)2 Repository (org.eclipse.jgit.lib.Repository)2 StoredConfig (org.eclipse.jgit.lib.StoredConfig)2 ReceiveCommandEvent (com.gitblit.git.ReceiveCommandEvent)1 RepositoryModel (com.gitblit.models.RepositoryModel)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 GitException (org.eclipse.che.api.git.exception.GitException)1 CheckoutCommand (org.eclipse.jgit.api.CheckoutCommand)1 CloneCommand (org.eclipse.jgit.api.CloneCommand)1 DeleteBranchCommand (org.eclipse.jgit.api.DeleteBranchCommand)1 ListBranchCommand (org.eclipse.jgit.api.ListBranchCommand)1