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