Search in sources :

Example 11 with MergeResult

use of org.eclipse.jgit.api.MergeResult in project spring-cloud-config by spring-cloud.

the class JGitEnvironmentRepository method merge.

private MergeResult merge(Git git, String label) {
    try {
        MergeCommand merge = git.merge();
        merge.include(git.getRepository().findRef("origin/" + label));
        MergeResult result = merge.call();
        if (!result.getMergeStatus().isSuccessful()) {
            this.logger.warn("Merged from remote " + label + " with result " + result.getMergeStatus());
        }
        return result;
    } catch (Exception ex) {
        String message = "Could not merge remote for " + label + " remote: " + git.getRepository().getConfig().getString("remote", "origin", "url");
        warn(message, ex);
        return null;
    }
}
Also used : MergeCommand(org.eclipse.jgit.api.MergeCommand) MergeResult(org.eclipse.jgit.api.MergeResult) 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 12 with MergeResult

use of org.eclipse.jgit.api.MergeResult 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)

Example 13 with MergeResult

use of org.eclipse.jgit.api.MergeResult in project fabric8 by jboss-fuse.

the class DefaultPullPushPolicy method doPull.

@Override
public synchronized PullPolicyResult doPull(GitContext context, CredentialsProvider credentialsProvider, boolean allowVersionDelete, boolean allowPush, int timeoutInSeconds) {
    Repository repository = git.getRepository();
    StoredConfig config = repository.getConfig();
    String remoteUrl = config.getString("remote", remoteRef, "url");
    if (remoteUrl == null) {
        LOGGER.info("No remote repository defined, so not doing a pull");
        return new AbstractPullPolicyResult();
    }
    LOGGER.info("Performing a pull on remote URL: {}", remoteUrl);
    // Get local and remote branches
    Map<String, Ref> localBranches = new HashMap<String, Ref>();
    Map<String, Ref> remoteBranches = new HashMap<String, Ref>();
    Set<String> allBranches = new HashSet<String>();
    Exception lastException = null;
    try {
        // when trying to fast-forward to commit done upstream between fetch and ls-remote!
        for (Ref ref : git.lsRemote().setTimeout(timeoutInSeconds).setCredentialsProvider(credentialsProvider).setTags(false).setHeads(true).setRemote(remoteRef).call()) {
            if (ref.getName().startsWith("refs/heads/")) {
                String name = ref.getName().substring(("refs/heads/").length());
                remoteBranches.put(name, ref);
                allBranches.add(name);
            }
        }
        git.fetch().setTimeout(timeoutInSeconds).setCredentialsProvider(credentialsProvider).setTagOpt(TagOpt.FETCH_TAGS).setRemote(remoteRef).call();
    } catch (Exception ex) {
        lastException = ex;
    }
    // No meaningful processing after GitAPIException
    if (lastException != null) {
        logPullException(lastException);
        return new AbstractPullPolicyResult(lastException);
    }
    try {
        // list local branches
        for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
            // }
            if (ref.getName().startsWith("refs/heads/")) {
                String name = ref.getName().substring(("refs/heads/").length());
                localBranches.put(name, ref);
                allBranches.add(name);
            }
        }
        Map<String, BranchChange> localUpdate = new HashMap<>();
        boolean remoteUpdate = false;
        Set<String> versions = new TreeSet<>();
        // Remote repository has no branches, force a push
        if (remoteBranches.isEmpty()) {
            LOGGER.info("Pulled from an empty remote repository");
            return new AbstractPullPolicyResult(versions, localUpdate, !localBranches.isEmpty(), null);
        } else {
            LOGGER.debug("Processing remote branches: {}", remoteBranches);
        }
        // Verify master branch and do a checkout of it when we have it locally (already)
        IllegalStateAssertion.assertTrue(remoteBranches.containsKey(GitHelpers.MASTER_BRANCH), "Remote repository does not have a master branch");
        // Iterate over all local/remote branches
        for (String branch : allBranches) {
            // Delete a local branch that does not exist remotely, but not master
            boolean allowDelete = allowVersionDelete && !GitHelpers.MASTER_BRANCH.equals(branch);
            if (localBranches.containsKey(branch) && !remoteBranches.containsKey(branch)) {
                if (allowDelete) {
                    String remotebranchRef = String.format("remotes/%s/%s", remoteRef, branch);
                    LOGGER.info("Deleting local branch: {} and local reference to remote branch: {}", branch, remotebranchRef);
                    // which can't be deleted
                    if (branch.equals(git.getRepository().getBranch())) {
                        // 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();
                        git.checkout().setName("master").call();
                    }
                    git.branchDelete().setBranchNames(branch, remotebranchRef).setForce(true).call();
                    localUpdate.put(branch, new BranchChange(branch).removed());
                } else {
                    remoteUpdate = true;
                }
            } else // Create a local branch that exists remotely
            if (!localBranches.containsKey(branch) && remoteBranches.containsKey(branch)) {
                LOGGER.info("Adding new local branch: {}", branch);
                git.checkout().setCreateBranch(true).setName(branch).setStartPoint(remoteRef + "/" + branch).setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call();
                versions.add(branch);
                localUpdate.put(branch, new BranchChange(branch).created());
            } else // Update a local branch that also exists remotely
            if (localBranches.containsKey(branch) && remoteBranches.containsKey(branch)) {
                ObjectId localObjectId = localBranches.get(branch).getObjectId();
                ObjectId remoteObjectId = remoteBranches.get(branch).getObjectId();
                String localCommit = localObjectId.getName();
                String remoteCommit = remoteObjectId.getName();
                if (!localCommit.equals(remoteCommit)) {
                    git.clean().setCleanDirectories(true).call();
                    git.checkout().setName(branch).setForce(true).call();
                    MergeResult mergeResult = git.merge().setFastForward(FastForwardMode.FF_ONLY).include(remoteObjectId).call();
                    MergeStatus mergeStatus = mergeResult.getMergeStatus();
                    LOGGER.info("Updating local branch {} with status: {} ({}..{})", branch, mergeStatus, localCommit, remoteCommit);
                    if (mergeStatus == MergeStatus.FAST_FORWARD) {
                        localUpdate.put(branch, new BranchChange(branch).updated(localObjectId, remoteObjectId, "fast forward"));
                    } else if (mergeStatus == MergeStatus.ALREADY_UP_TO_DATE) {
                        if (allowPush) {
                            LOGGER.info("Remote branch {} is behind local version - changes will be pushed", branch);
                            remoteUpdate = true;
                        } else {
                            LOGGER.info("Remote branch {} is behind local version - changes won't be pushed - restoring remote tracking branch", branch);
                            GitHelpers.createOrCheckoutBranch(git, GitHelpers.MASTER_BRANCH, GitHelpers.REMOTE_ORIGIN);
                            git.branchDelete().setBranchNames(branch).setForce(true).call();
                            git.checkout().setCreateBranch(true).setName(branch).setStartPoint(remoteRef + "/" + branch).setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call();
                            localUpdate.put(branch, new BranchChange(branch).updated(localObjectId, remoteObjectId, "reset"));
                        }
                    } else if (mergeStatus == MergeStatus.ABORTED) {
                        // failure to merge using FastForwardMode.FF_ONLY always ends with MergeStatus.ABORTED
                        RebaseResult.Status rebaseStatus = null;
                        if (allowPush) {
                            LOGGER.info("Cannot fast forward branch {}, attempting rebase", branch);
                            RebaseResult rebaseResult = git.rebase().setUpstream(remoteCommit).call();
                            rebaseStatus = rebaseResult.getStatus();
                        }
                        if (rebaseStatus == RebaseResult.Status.OK) {
                            LOGGER.info("Rebase successful for branch {}", branch);
                            localUpdate.put(branch, new BranchChange(branch).updated(localObjectId, remoteObjectId, "rebase"));
                            remoteUpdate = true;
                        } else {
                            if (allowPush) {
                                LOGGER.warn("Rebase on branch {} failed, restoring remote tracking branch", branch);
                                git.rebase().setOperation(Operation.ABORT).call();
                            } else {
                                LOGGER.info("Restoring remote tracking branch {}", branch);
                            }
                            GitHelpers.createOrCheckoutBranch(git, GitHelpers.MASTER_BRANCH, GitHelpers.REMOTE_ORIGIN, remoteCommit);
                            git.branchDelete().setBranchNames(branch).setForce(true).call();
                            git.checkout().setCreateBranch(true).setName(branch).setStartPoint(remoteRef + "/" + branch).setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call();
                            localUpdate.put(branch, new BranchChange(branch).updated(localObjectId, remoteObjectId, "reset"));
                        }
                    }
                } else if (!git.status().call().isClean()) {
                    LOGGER.info("Local branch {} is up to date, but not clean. Cleaning working copy now.", branch);
                    // 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();
                }
                versions.add(branch);
            }
        }
        if (localUpdate.size() > 0) {
            if (--mergesWithoutGC < 0) {
                mergesWithoutGC = MAX_MERGES_WITHOUT_GC;
                LOGGER.info("Performing 'git gc' after {} merges", MAX_MERGES_WITHOUT_GC);
                try {
                    git.gc().setAggressive(true).call();
                } catch (Exception e) {
                    LOGGER.warn("Problem invoking 'git gc': {}", e.getMessage());
                }
            }
        }
        PullPolicyResult result = new AbstractPullPolicyResult(versions, localUpdate, remoteUpdate, null);
        LOGGER.info("Pull result: {}", result);
        return result;
    } catch (Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
        return new AbstractPullPolicyResult(ex);
    }
}
Also used : HashMap(java.util.HashMap) ObjectId(org.eclipse.jgit.lib.ObjectId) MergeResult(org.eclipse.jgit.api.MergeResult) 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) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) TreeSet(java.util.TreeSet) MergeStatus(org.eclipse.jgit.api.MergeResult.MergeStatus) RebaseResult(org.eclipse.jgit.api.RebaseResult) HashSet(java.util.HashSet)

Example 14 with MergeResult

use of org.eclipse.jgit.api.MergeResult in project archi-modelrepository-plugin by archi-contribs.

the class ConflictsDialog method createTableControl.

private void createTableControl(Composite parent) {
    Composite tableComp = new Composite(parent, SWT.BORDER);
    TableColumnLayout tableLayout = new TableColumnLayout();
    tableComp.setLayout(tableLayout);
    tableComp.setLayoutData(new GridData(GridData.FILL_BOTH));
    Table table = new Table(tableComp, SWT.MULTI | SWT.FULL_SELECTION | SWT.CHECK);
    table.setHeaderVisible(true);
    fTableViewer = new CheckboxTableViewer(table);
    fTableViewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH));
    fTableViewer.getTable().setLinesVisible(true);
    fTableViewer.setComparator(new ViewerComparator());
    // Columns
    TableViewerColumn column1 = new TableViewerColumn(fTableViewer, SWT.NONE, 0);
    column1.getColumn().setText(Messages.ConflictsDialog_5);
    tableLayout.setColumnData(column1.getColumn(), new ColumnWeightData(100, true));
    // Content Provider
    fTableViewer.setContentProvider(new IStructuredContentProvider() {

        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
        }

        public void dispose() {
        }

        public Object[] getElements(Object inputElement) {
            MergeResult result = fHandler.getMergeResult();
            return result.getConflicts().keySet().toArray();
        }
    });
    fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            String path = (String) ((StructuredSelection) event.getSelection()).getFirstElement();
            try {
                fFileViewerOurs.setText(fHandler.getArchiRepository().getFileContents(path, IGraficoConstants.HEAD));
                fFileViewerTheirs.setText(fHandler.getArchiRepository().getFileContents(path, IGraficoConstants.ORIGIN_MASTER));
                fFileViewerDiff.setText(fHandler.getArchiRepository().getWorkingTreeFileContents(path));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });
    // Label Provider
    fTableViewer.setLabelProvider(new LabelProvider());
    // Start the table
    // anything will do //$NON-NLS-1$
    fTableViewer.setInput("");
}
Also used : ColumnWeightData(org.eclipse.jface.viewers.ColumnWeightData) Table(org.eclipse.swt.widgets.Table) Composite(org.eclipse.swt.widgets.Composite) CheckboxTableViewer(org.eclipse.jface.viewers.CheckboxTableViewer) ViewerComparator(org.eclipse.jface.viewers.ViewerComparator) ISelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) MergeResult(org.eclipse.jgit.api.MergeResult) StructuredSelection(org.eclipse.jface.viewers.StructuredSelection) CheckboxTableViewer(org.eclipse.jface.viewers.CheckboxTableViewer) Viewer(org.eclipse.jface.viewers.Viewer) SelectionChangedEvent(org.eclipse.jface.viewers.SelectionChangedEvent) IOException(java.io.IOException) TableColumnLayout(org.eclipse.jface.layout.TableColumnLayout) GridData(org.eclipse.swt.layout.GridData) IStructuredContentProvider(org.eclipse.jface.viewers.IStructuredContentProvider) LabelProvider(org.eclipse.jface.viewers.LabelProvider) TableViewerColumn(org.eclipse.jface.viewers.TableViewerColumn)

Example 15 with MergeResult

use of org.eclipse.jgit.api.MergeResult in project egit by eclipse.

the class DecoratableResourceMappingTest method testAnyConflictsIsConflicts.

@Test
public void testAnyConflictsIsConflicts() throws Exception {
    // commit changes on master
    gitAdd(git, rmContentA);
    gitAdd(git, rmContentB);
    RevCommit masterCommit = gitCommit(git);
    // add change on new branch first_topic
    git.checkout().setCreateBranch(true).setName("first_topic").call();
    rmContentA = findFile(project, RM_CONTENT_A_FILE_NAME);
    write(rmContentA.getLocation().toFile(), "First Topic Content");
    project.refreshLocal(IResource.DEPTH_INFINITE, null);
    gitAdd(git, rmContentA);
    RevCommit firstTopicCommit = gitCommit(git);
    // add change on new branch second_topic
    git.checkout().setCreateBranch(true).setStartPoint(masterCommit).setName("second_topic").call();
    rmContentA = findFile(project, RM_CONTENT_A_FILE_NAME);
    write(rmContentA.getLocation().toFile(), "Second Topic Content");
    project.refreshLocal(IResource.DEPTH_INFINITE, null);
    gitAdd(git, rmContentA);
    gitCommit(git);
    // merge second_topic with first_topic
    MergeResult mergeResult = git.merge().include(firstTopicCommit).call();
    assertEquals(MergeStatus.CONFLICTING, mergeResult.getMergeStatus());
    IDecoratableResource[] expectedDRs = new IDecoratableResource[] { newExpectedDecoratableResource(rmContentA).tracked().conflicts(), newExpectedDecoratableResource(rmContentB).tracked(), newExpectedDecoratableResourceMapping().tracked().conflicts() };
    IndexDiffData indexDiffData = waitForIndexDiff(true);
    IDecoratableResource[] actualDRs = { newDecoratableResource(indexDiffData, rmContentA), newDecoratableResource(indexDiffData, rmContentB), newDecoratableResourceMapping(resourceMapping) };
    assertArrayEquals(expectedDRs, actualDRs);
    assertDecorationConflicts(resourceMapping);
}
Also used : MergeResult(org.eclipse.jgit.api.MergeResult) IndexDiffData(org.eclipse.egit.core.internal.indexdiff.IndexDiffData) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Test(org.junit.Test)

Aggregations

MergeResult (org.eclipse.jgit.api.MergeResult)22 IOException (java.io.IOException)10 Test (org.junit.Test)9 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)7 RevCommit (org.eclipse.jgit.revwalk.RevCommit)7 Git (org.eclipse.jgit.api.Git)6 CoreException (org.eclipse.core.runtime.CoreException)4 IndexDiffData (org.eclipse.egit.core.internal.indexdiff.IndexDiffData)4 MergeCommand (org.eclipse.jgit.api.MergeCommand)3 MergeStatus (org.eclipse.jgit.api.MergeResult.MergeStatus)3 Ref (org.eclipse.jgit.lib.Ref)3 File (java.io.File)2 IFile (org.eclipse.core.resources.IFile)2 SubMonitor (org.eclipse.core.runtime.SubMonitor)2 CheckoutCommand (org.eclipse.jgit.api.CheckoutCommand)2 CloneCommand (org.eclipse.jgit.api.CloneCommand)2 NoRemoteRepositoryException (org.eclipse.jgit.errors.NoRemoteRepositoryException)2 ObjectId (org.eclipse.jgit.lib.ObjectId)2 Repository (org.eclipse.jgit.lib.Repository)2 StoredConfig (org.eclipse.jgit.lib.StoredConfig)2