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;
}
}
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();
}
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);
}
}
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("");
}
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);
}
Aggregations