Search in sources :

Example 1 with FetchCommand

use of org.eclipse.jgit.api.FetchCommand in project che by eclipse.

the class JGitConnection method fetch.

@Override
public void fetch(FetchParams params) throws GitException, UnauthorizedException {
    String remoteName = params.getRemote();
    String remoteUri;
    try {
        List<RefSpec> fetchRefSpecs;
        List<String> refSpec = params.getRefSpec();
        if (!refSpec.isEmpty()) {
            fetchRefSpecs = new ArrayList<>(refSpec.size());
            for (String refSpecItem : refSpec) {
                RefSpec fetchRefSpec = //
                (refSpecItem.indexOf(':') < 0) ? //
                new RefSpec(Constants.R_HEADS + refSpecItem + ":") : new RefSpec(refSpecItem);
                fetchRefSpecs.add(fetchRefSpec);
            }
        } else {
            fetchRefSpecs = Collections.emptyList();
        }
        FetchCommand fetchCommand = getGit().fetch();
        // (otherwise JGit fails)
        if (remoteName != null && refSpec.isEmpty()) {
            boolean found = false;
            List<Remote> configRemotes = remoteList(null, false);
            for (Remote configRemote : configRemotes) {
                if (remoteName.equals(configRemote.getName())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                fetchRefSpecs = Collections.singletonList(new RefSpec(Constants.HEAD + ":" + Constants.FETCH_HEAD));
            }
        }
        if (remoteName == null) {
            remoteName = Constants.DEFAULT_REMOTE_NAME;
        }
        fetchCommand.setRemote(remoteName);
        remoteUri = getRepository().getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName, ConfigConstants.CONFIG_KEY_URL);
        fetchCommand.setRefSpecs(fetchRefSpecs);
        int timeout = params.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }
        fetchCommand.setRemoveDeletedRefs(params.isRemoveDeletedRefs());
        executeRemoteCommand(remoteUri, fetchCommand, params.getUsername(), params.getPassword());
    } catch (GitException | GitAPIException exception) {
        String errorMessage;
        if (exception.getMessage().contains("Invalid remote: ")) {
            errorMessage = ERROR_NO_REMOTE_REPOSITORY;
        } else if ("Nothing to fetch.".equals(exception.getMessage())) {
            return;
        } else {
            errorMessage = generateExceptionMessage(exception);
        }
        throw new GitException(errorMessage, exception);
    }
}
Also used : GitException(org.eclipse.che.api.git.exception.GitException) Remote(org.eclipse.che.api.git.shared.Remote) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RefSpec(org.eclipse.jgit.transport.RefSpec) FetchCommand(org.eclipse.jgit.api.FetchCommand)

Example 2 with FetchCommand

use of org.eclipse.jgit.api.FetchCommand in project che by eclipse.

the class JGitConnection method pull.

@Override
public PullResponse pull(PullParams params) throws GitException, UnauthorizedException {
    String remoteName = params.getRemote();
    String remoteUri;
    try {
        if (repository.getRepositoryState().equals(RepositoryState.MERGING)) {
            throw new GitException(ERROR_PULL_MERGING);
        }
        String fullBranch = repository.getFullBranch();
        if (!fullBranch.startsWith(Constants.R_HEADS)) {
            throw new DetachedHeadException(ERROR_PULL_HEAD_DETACHED);
        }
        String branch = fullBranch.substring(Constants.R_HEADS.length());
        StoredConfig config = repository.getConfig();
        if (remoteName == null) {
            remoteName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_REMOTE);
            if (remoteName == null) {
                remoteName = Constants.DEFAULT_REMOTE_NAME;
            }
        }
        remoteUri = config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName, ConfigConstants.CONFIG_KEY_URL);
        String remoteBranch;
        RefSpec fetchRefSpecs = null;
        String refSpec = params.getRefSpec();
        if (refSpec != null) {
            fetchRefSpecs = //
            (refSpec.indexOf(':') < 0) ? //
            new RefSpec(Constants.R_HEADS + refSpec + ":" + fullBranch) : new RefSpec(refSpec);
            remoteBranch = fetchRefSpecs.getSource();
        } else {
            remoteBranch = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_MERGE);
        }
        if (remoteBranch == null) {
            remoteBranch = fullBranch;
        }
        FetchCommand fetchCommand = getGit().fetch();
        fetchCommand.setRemote(remoteName);
        if (fetchRefSpecs != null) {
            fetchCommand.setRefSpecs(fetchRefSpecs);
        }
        int timeout = params.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }
        FetchResult fetchResult = (FetchResult) executeRemoteCommand(remoteUri, fetchCommand, params.getUsername(), params.getPassword());
        Ref remoteBranchRef = fetchResult.getAdvertisedRef(remoteBranch);
        if (remoteBranchRef == null) {
            remoteBranchRef = fetchResult.getAdvertisedRef(Constants.R_HEADS + remoteBranch);
        }
        if (remoteBranchRef == null) {
            throw new GitException(format(ERROR_PULL_REF_MISSING, remoteBranch));
        }
        org.eclipse.jgit.api.MergeResult mergeResult = getGit().merge().include(remoteBranchRef).call();
        if (mergeResult.getMergeStatus().equals(org.eclipse.jgit.api.MergeResult.MergeStatus.ALREADY_UP_TO_DATE)) {
            return newDto(PullResponse.class).withCommandOutput("Already up-to-date");
        }
        if (mergeResult.getConflicts() != null) {
            StringBuilder message = new StringBuilder(ERROR_PULL_MERGE_CONFLICT_IN_FILES);
            message.append(lineSeparator());
            Map<String, int[][]> allConflicts = mergeResult.getConflicts();
            for (String path : allConflicts.keySet()) {
                message.append(path).append(lineSeparator());
            }
            message.append(ERROR_PULL_AUTO_MERGE_FAILED);
            throw new GitException(message.toString());
        }
    } catch (CheckoutConflictException exception) {
        StringBuilder message = new StringBuilder(ERROR_CHECKOUT_CONFLICT);
        message.append(lineSeparator());
        for (String path : exception.getConflictingPaths()) {
            message.append(path).append(lineSeparator());
        }
        message.append(ERROR_PULL_COMMIT_BEFORE_MERGE);
        throw new GitException(message.toString(), exception);
    } catch (IOException | GitAPIException exception) {
        String errorMessage;
        if (exception.getMessage().equals("Invalid remote: " + remoteName)) {
            errorMessage = ERROR_NO_REMOTE_REPOSITORY;
        } else {
            errorMessage = generateExceptionMessage(exception);
        }
        throw new GitException(errorMessage, exception);
    }
    return newDto(PullResponse.class).withCommandOutput("Successfully pulled from " + remoteUri);
}
Also used : FetchResult(org.eclipse.jgit.transport.FetchResult) GitException(org.eclipse.che.api.git.exception.GitException) IOException(java.io.IOException) CheckoutConflictException(org.eclipse.jgit.api.errors.CheckoutConflictException) StoredConfig(org.eclipse.jgit.lib.StoredConfig) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Ref(org.eclipse.jgit.lib.Ref) RefSpec(org.eclipse.jgit.transport.RefSpec) PullResponse(org.eclipse.che.api.git.shared.PullResponse) FetchCommand(org.eclipse.jgit.api.FetchCommand) DetachedHeadException(org.eclipse.jgit.api.errors.DetachedHeadException)

Example 3 with FetchCommand

use of org.eclipse.jgit.api.FetchCommand 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 4 with FetchCommand

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

the class ArchiRepository method fetchFromRemote.

@Override
public FetchResult fetchFromRemote(String userName, String userPassword, ProgressMonitor monitor, boolean isDryrun) throws IOException, GitAPIException {
    try (Git git = Git.open(getLocalRepositoryFolder())) {
        // Check and set tracked master branch
        setTrackedMasterBranch(git);
        FetchCommand fetchCommand = git.fetch();
        fetchCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, userPassword));
        fetchCommand.setProgressMonitor(monitor);
        fetchCommand.setDryRun(isDryrun);
        return fetchCommand.call();
    }
}
Also used : UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) Git(org.eclipse.jgit.api.Git) FetchCommand(org.eclipse.jgit.api.FetchCommand)

Example 5 with FetchCommand

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

the class JGitEnvironmentRepositoryTests method shouldSetRemoveBranchesFlagToFetchCommand.

@Test
public void shouldSetRemoveBranchesFlagToFetchCommand() throws Exception {
    Git mockGit = mock(Git.class);
    FetchCommand fetchCommand = mock(FetchCommand.class);
    when(mockGit.fetch()).thenReturn(fetchCommand);
    when(fetchCommand.call()).thenReturn(mock(FetchResult.class));
    JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, new JGitEnvironmentProperties());
    envRepository.setGitFactory(new MockGitFactory(mockGit, mock(CloneCommand.class)));
    envRepository.setUri("http://somegitserver/somegitrepo");
    envRepository.setDeleteUntrackedBranches(true);
    envRepository.fetch(mockGit, "master");
    verify(fetchCommand, times(1)).setRemoveDeletedRefs(true);
    verify(fetchCommand, times(1)).call();
}
Also used : Git(org.eclipse.jgit.api.Git) FetchResult(org.eclipse.jgit.transport.FetchResult) FetchCommand(org.eclipse.jgit.api.FetchCommand) Test(org.junit.Test)

Aggregations

FetchCommand (org.eclipse.jgit.api.FetchCommand)19 Git (org.eclipse.jgit.api.Git)13 FetchResult (org.eclipse.jgit.transport.FetchResult)9 ArrayList (java.util.ArrayList)6 CloneCommand (org.eclipse.jgit.api.CloneCommand)6 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)6 Ref (org.eclipse.jgit.lib.Ref)6 RefSpec (org.eclipse.jgit.transport.RefSpec)6 Test (org.junit.Test)6 CheckoutCommand (org.eclipse.jgit.api.CheckoutCommand)5 Repository (org.eclipse.jgit.lib.Repository)5 StoredConfig (org.eclipse.jgit.lib.StoredConfig)5 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 NotMergedException (org.eclipse.jgit.api.errors.NotMergedException)4 ObjectId (org.eclipse.jgit.lib.ObjectId)4 File (java.io.File)3