use of org.eclipse.jgit.api.CheckoutCommand in project che by eclipse.
the class JGitConnection method checkout.
@Override
public void checkout(CheckoutParams params) throws GitException {
CheckoutCommand checkoutCommand = getGit().checkout();
String startPoint = params.getStartPoint();
String name = params.getName();
String trackBranch = params.getTrackBranch();
// checkout files?
List<String> files = params.getFiles();
boolean shouldCheckoutToFile = name != null && new File(getWorkingDir(), name).exists();
if (shouldCheckoutToFile || !files.isEmpty()) {
if (shouldCheckoutToFile) {
checkoutCommand.addPath(params.getName());
} else {
files.forEach(checkoutCommand::addPath);
}
} else {
// checkout branch
if (startPoint != null && trackBranch != null) {
throw new GitException("Start point and track branch can not be used together.");
}
if (params.isCreateNew() && name == null) {
throw new GitException("Branch name must be set when createNew equals to true.");
}
if (startPoint != null) {
checkoutCommand.setStartPoint(startPoint);
}
if (params.isCreateNew()) {
checkoutCommand.setCreateBranch(true);
checkoutCommand.setName(name);
} else if (name != null) {
checkoutCommand.setName(name);
List<String> localBranches = branchList(LIST_LOCAL).stream().map(Branch::getDisplayName).collect(Collectors.toList());
if (!localBranches.contains(name)) {
Optional<Branch> remoteBranch = branchList(LIST_REMOTE).stream().filter(branch -> branch.getName().contains(name)).findFirst();
if (remoteBranch.isPresent()) {
checkoutCommand.setCreateBranch(true);
checkoutCommand.setStartPoint(remoteBranch.get().getName());
}
}
}
if (trackBranch != null) {
if (name == null) {
checkoutCommand.setName(cleanRemoteName(trackBranch));
}
checkoutCommand.setCreateBranch(true);
checkoutCommand.setStartPoint(trackBranch);
}
checkoutCommand.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
}
try {
checkoutCommand.call();
} catch (CheckoutConflictException exception) {
throw new GitConflictException(exception.getMessage(), exception.getConflictingPaths());
} catch (RefAlreadyExistsException exception) {
throw new GitRefAlreadyExistsException(exception.getMessage());
} catch (RefNotFoundException exception) {
throw new GitRefNotFoundException(exception.getMessage());
} catch (InvalidRefNameException exception) {
throw new GitInvalidRefNameException(exception.getMessage());
} catch (GitAPIException exception) {
if (exception.getMessage().endsWith("already exists")) {
throw new GitException(format(ERROR_CHECKOUT_BRANCH_NAME_EXISTS, name != null ? name : cleanRemoteName(trackBranch)));
}
throw new GitException(exception.getMessage(), exception);
}
}
use of org.eclipse.jgit.api.CheckoutCommand in project blueocean-plugin by jenkinsci.
the class GitCacheCloneReadSaveRequest method getActiveRepository.
@Nonnull
private Git getActiveRepository(Repository repository) throws IOException {
try {
// Clone the bare repository
File cloneDir = File.createTempFile("clone", "");
if (cloneDir.exists()) {
if (cloneDir.isDirectory()) {
FileUtils.deleteDirectory(cloneDir);
} else {
if (!cloneDir.delete()) {
throw new ServiceException.UnexpectedErrorException("Unable to delete repository clone");
}
}
}
if (!cloneDir.mkdirs()) {
throw new ServiceException.UnexpectedErrorException("Unable to create repository clone directory");
}
String url = repository.getConfig().getString("remote", "origin", "url");
Git gitClient = Git.cloneRepository().setCloneAllBranches(false).setProgressMonitor(new CloneProgressMonitor(url)).setURI(repository.getDirectory().getCanonicalPath()).setDirectory(cloneDir).call();
RemoteRemoveCommand remove = gitClient.remoteRemove();
remove.setName("origin");
remove.call();
RemoteAddCommand add = gitClient.remoteAdd();
add.setName("origin");
add.setUri(new URIish(gitSource.getRemote()));
add.call();
if (GitUtils.isSshUrl(gitSource.getRemote())) {
// Get committer info and credentials
User user = User.current();
if (user == null) {
throw new ServiceException.UnauthorizedException("Not authenticated");
}
BasicSSHUserPrivateKey privateKey = UserSSHKeyManager.getOrCreate(user);
// Make sure up-to-date and credentials work
GitUtils.fetch(repository, privateKey);
} else {
FetchCommand fetch = gitClient.fetch();
fetch.call();
}
if (!StringUtils.isEmpty(sourceBranch) && !sourceBranch.equals(branch)) {
CheckoutCommand checkout = gitClient.checkout();
checkout.setStartPoint("origin/" + sourceBranch);
checkout.setName(sourceBranch);
// to create a new local branch
checkout.setCreateBranch(true);
checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
checkout.call();
checkout = gitClient.checkout();
checkout.setName(branch);
// this *should* be a new branch
checkout.setCreateBranch(true);
checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
checkout.call();
} else {
CheckoutCommand checkout = gitClient.checkout();
checkout.setStartPoint("origin/" + branch);
checkout.setName(branch);
// to create a new local branch
checkout.setCreateBranch(true);
checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
checkout.call();
}
return gitClient;
} catch (GitAPIException | URISyntaxException ex) {
throw new ServiceException.UnexpectedErrorException("Unable to get working repository directory", ex);
}
}
use of org.eclipse.jgit.api.CheckoutCommand 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();
}
use of org.eclipse.jgit.api.CheckoutCommand in project spring-cloud-config by spring-cloud.
the class JGitEnvironmentRepositoryIntegrationTests method getCommitID.
private String getCommitID(Git git, String label) throws GitAPIException {
CheckoutCommand checkout = git.checkout();
checkout.setName(label);
Ref localRef = checkout.call();
return localRef.getObjectId().getName();
}
use of org.eclipse.jgit.api.CheckoutCommand 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();
}
Aggregations