Search in sources :

Example 1 with CheckoutCommand

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);
    }
}
Also used : CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) Optional(java.util.Optional) GitException(org.eclipse.che.api.git.exception.GitException) CheckoutConflictException(org.eclipse.jgit.api.errors.CheckoutConflictException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) GitRefNotFoundException(org.eclipse.che.api.git.exception.GitRefNotFoundException) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException) Branch(org.eclipse.che.api.git.shared.Branch) RefAlreadyExistsException(org.eclipse.jgit.api.errors.RefAlreadyExistsException) GitRefAlreadyExistsException(org.eclipse.che.api.git.exception.GitRefAlreadyExistsException) GitRefAlreadyExistsException(org.eclipse.che.api.git.exception.GitRefAlreadyExistsException) InvalidRefNameException(org.eclipse.jgit.api.errors.InvalidRefNameException) GitInvalidRefNameException(org.eclipse.che.api.git.exception.GitInvalidRefNameException) ArrayList(java.util.ArrayList) List(java.util.List) GitConflictException(org.eclipse.che.api.git.exception.GitConflictException) GitRefNotFoundException(org.eclipse.che.api.git.exception.GitRefNotFoundException) GitInvalidRefNameException(org.eclipse.che.api.git.exception.GitInvalidRefNameException) DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) File(java.io.File)

Example 2 with CheckoutCommand

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);
    }
}
Also used : URIish(org.eclipse.jgit.transport.URIish) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) User(hudson.model.User) RemoteRemoveCommand(org.eclipse.jgit.api.RemoteRemoveCommand) RemoteAddCommand(org.eclipse.jgit.api.RemoteAddCommand) URISyntaxException(java.net.URISyntaxException) BasicSSHUserPrivateKey(com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) ServiceException(io.jenkins.blueocean.commons.ServiceException) FetchCommand(org.eclipse.jgit.api.FetchCommand) File(java.io.File) Nonnull(javax.annotation.Nonnull)

Example 3 with CheckoutCommand

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();
}
Also used : CloneCommand(org.eclipse.jgit.api.CloneCommand) Status(org.eclipse.jgit.api.Status) NotMergedException(org.eclipse.jgit.api.errors.NotMergedException) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) FetchResult(org.eclipse.jgit.transport.FetchResult) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) MergeCommand(org.eclipse.jgit.api.MergeCommand) StatusCommand(org.eclipse.jgit.api.StatusCommand) StoredConfig(org.eclipse.jgit.lib.StoredConfig) ListBranchCommand(org.eclipse.jgit.api.ListBranchCommand) 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 4 with CheckoutCommand

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();
}
Also used : CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) Ref(org.eclipse.jgit.lib.Ref)

Example 5 with CheckoutCommand

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();
}
Also used : CloneCommand(org.eclipse.jgit.api.CloneCommand) Status(org.eclipse.jgit.api.Status) NotMergedException(org.eclipse.jgit.api.errors.NotMergedException) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) FetchResult(org.eclipse.jgit.transport.FetchResult) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) MergeCommand(org.eclipse.jgit.api.MergeCommand) StatusCommand(org.eclipse.jgit.api.StatusCommand) StoredConfig(org.eclipse.jgit.lib.StoredConfig) ListBranchCommand(org.eclipse.jgit.api.ListBranchCommand) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) FetchCommand(org.eclipse.jgit.api.FetchCommand) ResetCommand(org.eclipse.jgit.api.ResetCommand) Test(org.junit.Test)

Aggregations

CheckoutCommand (org.eclipse.jgit.api.CheckoutCommand)14 Git (org.eclipse.jgit.api.Git)10 Ref (org.eclipse.jgit.lib.Ref)7 ArrayList (java.util.ArrayList)6 CloneCommand (org.eclipse.jgit.api.CloneCommand)5 FetchCommand (org.eclipse.jgit.api.FetchCommand)5 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)5 Repository (org.eclipse.jgit.lib.Repository)5 File (java.io.File)4 IOException (java.io.IOException)4 ListBranchCommand (org.eclipse.jgit.api.ListBranchCommand)4 MergeCommand (org.eclipse.jgit.api.MergeCommand)4 Status (org.eclipse.jgit.api.Status)4 StatusCommand (org.eclipse.jgit.api.StatusCommand)4 JGitInternalException (org.eclipse.jgit.api.errors.JGitInternalException)4 NotMergedException (org.eclipse.jgit.api.errors.NotMergedException)4 ObjectId (org.eclipse.jgit.lib.ObjectId)4 StoredConfig (org.eclipse.jgit.lib.StoredConfig)4 Test (org.junit.Test)4 FetchResult (org.eclipse.jgit.transport.FetchResult)3