Search in sources :

Example 21 with GitException

use of org.eclipse.che.api.git.exception.GitException in project che by eclipse.

the class JGitConnection method writePrivateKeyFile.

/**
     * Writes private SSH key into file.
     *
     * @return file that contains SSH key
     * @throws GitException
     *         if other error occurs
     */
private File writePrivateKeyFile(String url, File keyDirectory) throws GitException {
    final File keyFile = new File(keyDirectory, "identity");
    try (FileOutputStream fos = new FileOutputStream(keyFile)) {
        byte[] sshKey = sshKeyProvider.getPrivateKey(url);
        fos.write(sshKey);
    } catch (IOException | ServerException exception) {
        String errorMessage = "Can't store ssh key. ".concat(exception.getMessage());
        LOG.error(errorMessage, exception);
        throw new GitException(errorMessage, ErrorCodes.UNABLE_GET_PRIVATE_SSH_KEY);
    }
    Set<PosixFilePermission> permissions = EnumSet.of(OWNER_READ, OWNER_WRITE);
    try {
        java.nio.file.Files.setPosixFilePermissions(keyFile.toPath(), permissions);
    } catch (IOException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
    return keyFile;
}
Also used : ServerException(org.eclipse.che.api.core.ServerException) GitException(org.eclipse.che.api.git.exception.GitException) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) File(java.io.File)

Example 22 with GitException

use of org.eclipse.che.api.git.exception.GitException in project che by eclipse.

the class JGitConnection method remoteUpdate.

@Override
public void remoteUpdate(RemoteUpdateParams params) throws GitException {
    String remoteName = params.getName();
    if (isNullOrEmpty(remoteName)) {
        throw new GitException(ERROR_UPDATE_REMOTE_NAME_MISSING);
    }
    StoredConfig config = repository.getConfig();
    Set<String> remoteNames = config.getSubsections(ConfigConstants.CONFIG_KEY_REMOTE);
    if (!remoteNames.contains(remoteName)) {
        throw new GitException("Remote " + remoteName + " not found. ");
    }
    RemoteConfig remoteConfig;
    try {
        remoteConfig = new RemoteConfig(config, remoteName);
    } catch (URISyntaxException e) {
        throw new GitException(e.getMessage(), e);
    }
    List<String> branches = params.getBranches();
    if (!branches.isEmpty()) {
        if (!params.isAddBranches()) {
            remoteConfig.setFetchRefSpecs(Collections.emptyList());
            remoteConfig.setPushRefSpecs(Collections.emptyList());
        } else {
            // Replace wildcard refSpec if any.
            remoteConfig.removeFetchRefSpec(new RefSpec(Constants.R_HEADS + "*" + ":" + Constants.R_REMOTES + remoteName + "/*").setForceUpdate(true));
            remoteConfig.removeFetchRefSpec(new RefSpec(Constants.R_HEADS + "*" + ":" + Constants.R_REMOTES + remoteName + "/*"));
        }
        // Add new refSpec.
        for (String branch : branches) {
            remoteConfig.addFetchRefSpec(new RefSpec(Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remoteName + "/" + branch).setForceUpdate(true));
        }
    }
    // Remove URLs first.
    for (String url : params.getRemoveUrl()) {
        try {
            remoteConfig.removeURI(new URIish(url));
        } catch (URISyntaxException e) {
            LOG.debug(ERROR_UPDATE_REMOTE_REMOVE_INVALID_URL);
        }
    }
    // Add new URLs.
    for (String url : params.getAddUrl()) {
        try {
            remoteConfig.addURI(new URIish(url));
        } catch (URISyntaxException e) {
            throw new GitException("Remote url " + url + " is invalid. ");
        }
    }
    // Remove URLs for pushing.
    for (String url : params.getRemovePushUrl()) {
        try {
            remoteConfig.removePushURI(new URIish(url));
        } catch (URISyntaxException e) {
            LOG.debug(ERROR_UPDATE_REMOTE_REMOVE_INVALID_URL);
        }
    }
    // Add URLs for pushing.
    for (String url : params.getAddPushUrl()) {
        try {
            remoteConfig.addPushURI(new URIish(url));
        } catch (URISyntaxException e) {
            throw new GitException("Remote push url " + url + " is invalid. ");
        }
    }
    remoteConfig.update(config);
    try {
        config.save();
    } catch (IOException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
}
Also used : StoredConfig(org.eclipse.jgit.lib.StoredConfig) URIish(org.eclipse.jgit.transport.URIish) RefSpec(org.eclipse.jgit.transport.RefSpec) GitException(org.eclipse.che.api.git.exception.GitException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) RemoteConfig(org.eclipse.jgit.transport.RemoteConfig)

Example 23 with GitException

use of org.eclipse.che.api.git.exception.GitException in project che by eclipse.

the class JGitConnection method tagCreate.

@Override
public Tag tagCreate(TagCreateParams params) throws GitException {
    String commit = params.getCommit();
    if (commit == null) {
        commit = Constants.HEAD;
    }
    try {
        RevWalk revWalk = new RevWalk(repository);
        RevObject revObject;
        try {
            revObject = revWalk.parseAny(repository.resolve(commit));
        } finally {
            revWalk.close();
        }
        TagCommand tagCommand = getGit().tag().setName(params.getName()).setObjectId(revObject).setMessage(params.getMessage()).setForceUpdate(params.isForce());
        GitUser tagger = getUser();
        if (tagger != null) {
            tagCommand.setTagger(new PersonIdent(tagger.getName(), tagger.getEmail()));
        }
        Ref revTagRef = tagCommand.call();
        RevTag revTag = revWalk.parseTag(revTagRef.getLeaf().getObjectId());
        return newDto(Tag.class).withName(revTag.getTagName());
    } catch (IOException | GitAPIException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
}
Also used : RevTag(org.eclipse.jgit.revwalk.RevTag) RevObject(org.eclipse.jgit.revwalk.RevObject) GitException(org.eclipse.che.api.git.exception.GitException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) TagCommand(org.eclipse.jgit.api.TagCommand) GitUser(org.eclipse.che.api.git.shared.GitUser) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Ref(org.eclipse.jgit.lib.Ref) PersonIdent(org.eclipse.jgit.lib.PersonIdent) RevTag(org.eclipse.jgit.revwalk.RevTag) Tag(org.eclipse.che.api.git.shared.Tag)

Example 24 with GitException

use of org.eclipse.che.api.git.exception.GitException in project che by eclipse.

the class JGitConnection method reset.

@Override
public void reset(ResetParams params) throws GitException {
    try {
        ResetCommand resetCommand = getGit().reset();
        resetCommand.setRef(params.getCommit());
        List<String> patterns = params.getFilePattern();
        patterns.forEach(resetCommand::addPath);
        if (params.getType() != null && patterns.isEmpty()) {
            switch(params.getType()) {
                case HARD:
                    resetCommand.setMode(ResetType.HARD);
                    break;
                case KEEP:
                    resetCommand.setMode(ResetType.KEEP);
                    break;
                case MERGE:
                    resetCommand.setMode(ResetType.MERGE);
                    break;
                case MIXED:
                    resetCommand.setMode(ResetType.MIXED);
                    break;
                case SOFT:
                    resetCommand.setMode(ResetType.SOFT);
                    break;
            }
        }
        resetCommand.call();
    } catch (GitAPIException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) GitException(org.eclipse.che.api.git.exception.GitException) ResetCommand(org.eclipse.jgit.api.ResetCommand)

Example 25 with GitException

use of org.eclipse.che.api.git.exception.GitException in project che by eclipse.

the class JGitConnection method executeRemoteCommand.

/**
     * Execute remote jgit command.
     *
     * @param remoteUrl
     *         remote url
     * @param command
     *         command to execute
     * @return executed command
     * @throws GitException
     * @throws GitAPIException
     * @throws UnauthorizedException
     */
@VisibleForTesting
Object executeRemoteCommand(String remoteUrl, TransportCommand command, @Nullable String username, @Nullable String password) throws GitException, GitAPIException, UnauthorizedException {
    File keyDirectory = null;
    UserCredential credentials = null;
    try {
        if (GitUrlUtils.isSSH(remoteUrl)) {
            keyDirectory = Files.createTempDir();
            final File sshKey = writePrivateKeyFile(remoteUrl, keyDirectory);
            SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {

                @Override
                protected void configure(OpenSshConfig.Host host, Session session) {
                    session.setConfig("StrictHostKeyChecking", "no");
                }

                @Override
                protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
                    JSch jsch = super.getJSch(hc, fs);
                    jsch.removeAllIdentity();
                    jsch.addIdentity(sshKey.getAbsolutePath());
                    return jsch;
                }
            };
            command.setTransportConfigCallback(transport -> {
                if (transport instanceof SshTransport) {
                    ((SshTransport) transport).setSshSessionFactory(sshSessionFactory);
                }
            });
        } else {
            if (remoteUrl != null && GIT_URL_WITH_CREDENTIALS_PATTERN.matcher(remoteUrl).matches()) {
                username = remoteUrl.substring(remoteUrl.indexOf("://") + 3, remoteUrl.lastIndexOf(":"));
                password = remoteUrl.substring(remoteUrl.lastIndexOf(":") + 1, remoteUrl.indexOf("@"));
                command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
            } else {
                if (username != null && password != null) {
                    command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
                } else {
                    credentials = credentialsLoader.getUserCredential(remoteUrl);
                    if (credentials != null) {
                        command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(credentials.getUserName(), credentials.getPassword()));
                    }
                }
            }
        }
        ProxyAuthenticator.initAuthenticator(remoteUrl);
        return command.call();
    } catch (GitException | TransportException exception) {
        if ("Unable get private ssh key".equals(exception.getMessage())) {
            throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNABLE_GET_PRIVATE_SSH_KEY);
        } else if (exception.getMessage().contains(ERROR_AUTHENTICATION_REQUIRED)) {
            final ProviderInfo info = credentialsLoader.getProviderInfo(remoteUrl);
            if (info != null) {
                throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION, ImmutableMap.of(PROVIDER_NAME, info.getProviderName(), AUTHENTICATE_URL, info.getAuthenticateUrl(), "authenticated", Boolean.toString(credentials != null)));
            }
            throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION);
        } else {
            throw exception;
        }
    } finally {
        if (keyDirectory != null && keyDirectory.exists()) {
            try {
                FileUtils.delete(keyDirectory, FileUtils.RECURSIVE);
            } catch (IOException exception) {
                throw new GitException("Can't remove SSH key directory", exception);
            }
        }
        ProxyAuthenticator.resetAuthenticator();
    }
}
Also used : UserCredential(org.eclipse.che.api.git.UserCredential) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) GitException(org.eclipse.che.api.git.exception.GitException) IOException(java.io.IOException) SshSessionFactory(org.eclipse.jgit.transport.SshSessionFactory) JSch(com.jcraft.jsch.JSch) FS(org.eclipse.jgit.util.FS) TransportException(org.eclipse.jgit.api.errors.TransportException) ProviderInfo(org.eclipse.che.api.git.shared.ProviderInfo) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) File(java.io.File) SshTransport(org.eclipse.jgit.transport.SshTransport) Session(com.jcraft.jsch.Session) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

GitException (org.eclipse.che.api.git.exception.GitException)33 IOException (java.io.IOException)20 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)18 ArrayList (java.util.ArrayList)10 File (java.io.File)9 DiffCommitFile (org.eclipse.che.api.git.shared.DiffCommitFile)9 StoredConfig (org.eclipse.jgit.lib.StoredConfig)9 Ref (org.eclipse.jgit.lib.Ref)8 URISyntaxException (java.net.URISyntaxException)6 RefSpec (org.eclipse.jgit.transport.RefSpec)6 GitConnection (org.eclipse.che.api.git.GitConnection)5 CheckoutConflictException (org.eclipse.jgit.api.errors.CheckoutConflictException)5 Branch (org.eclipse.che.api.git.shared.Branch)4 GitUser (org.eclipse.che.api.git.shared.GitUser)4 MergeResult (org.eclipse.che.api.git.shared.MergeResult)4 Remote (org.eclipse.che.api.git.shared.Remote)4 FetchCommand (org.eclipse.jgit.api.FetchCommand)4 RebaseResult (org.eclipse.jgit.api.RebaseResult)4 FetchResult (org.eclipse.jgit.transport.FetchResult)4 PushResult (org.eclipse.jgit.transport.PushResult)4