Search in sources :

Example 1 with Revision

use of org.eclipse.che.api.git.shared.Revision in project che by eclipse.

the class BranchCreateTest method testBranchCreateWithStartPoint.

@Test(dataProvider = "GitConnectionFactory", dataProviderClass = org.eclipse.che.git.impl.GitConnectionFactoryProvider.class)
public void testBranchCreateWithStartPoint(GitConnectionFactory connectionFactory) throws GitException, IOException {
    //given
    GitConnection connection = connectToInitializedGitRepository(connectionFactory, repository);
    addFile(connection, "newfile1", "file 1 content");
    connection.add(AddParams.create(singletonList(".")));
    connection.commit(CommitParams.create("Commit message"));
    //change content
    addFile(connection, "newfile1", "new file 1 content");
    connection.commit(CommitParams.create("Commit message").withAll(true));
    //get list of master branch commits
    List<Revision> revCommitList = connection.log(LogParams.create()).getCommits();
    int beforeCheckoutCommitsCount = revCommitList.size();
    //when
    //create new branch to 2nd commit
    Branch branch = connection.branchCreate("new-branch", revCommitList.get(1).getId());
    //then
    connection.checkout(CheckoutParams.create(branch.getDisplayName()));
    int afterCheckoutCommitsCount = connection.log(LogParams.create()).getCommits().size();
    assertEquals(afterCheckoutCommitsCount, beforeCheckoutCommitsCount - 1);
}
Also used : Revision(org.eclipse.che.api.git.shared.Revision) Branch(org.eclipse.che.api.git.shared.Branch) GitConnection(org.eclipse.che.api.git.GitConnection) Test(org.testng.annotations.Test)

Example 2 with Revision

use of org.eclipse.che.api.git.shared.Revision in project che by eclipse.

the class CommitTest method testAmendCommit.

@Test(dataProvider = "GitConnectionFactory", dataProviderClass = org.eclipse.che.git.impl.GitConnectionFactoryProvider.class)
public void testAmendCommit(GitConnectionFactory connectionFactory) throws GitException, IOException {
    //given
    GitConnection connection = connectToInitializedGitRepository(connectionFactory, repository);
    addFile(connection, "README.txt", CONTENT);
    connection.add(AddParams.create(ImmutableList.of("README.txt")));
    connection.commit(CommitParams.create("Initial addd"));
    int beforeCommitsCount = connection.log(LogParams.create()).getCommits().size();
    //when
    //change existing README
    addFile(connection, "README.txt", "some new content");
    CommitParams commitParams = CommitParams.create("Amend commit").withAmend(true).withAll(true);
    //then
    Revision revision = connection.commit(commitParams);
    int afterCommitsCount = connection.log(LogParams.create()).getCommits().size();
    assertEquals(revision.getMessage(), commitParams.getMessage());
    assertEquals(beforeCommitsCount, afterCommitsCount);
}
Also used : CommitParams(org.eclipse.che.api.git.params.CommitParams) Revision(org.eclipse.che.api.git.shared.Revision) GitConnection(org.eclipse.che.api.git.GitConnection) Test(org.testng.annotations.Test)

Example 3 with Revision

use of org.eclipse.che.api.git.shared.Revision in project che by eclipse.

the class CommitTest method testCommitWithAddAll.

@Test(dataProvider = "GitConnectionFactory", dataProviderClass = org.eclipse.che.git.impl.GitConnectionFactoryProvider.class)
public void testCommitWithAddAll(GitConnectionFactory connectionFactory) throws GitException, IOException {
    //given
    GitConnection connection = connectToInitializedGitRepository(connectionFactory, repository);
    addFile(connection, "README.txt", CONTENT);
    connection.add(AddParams.create(ImmutableList.of("README.txt")));
    connection.commit(CommitParams.create("Initial addd"));
    //when
    //change existing README
    addFile(connection, "README.txt", "not secret");
    //then
    CommitParams commitParams = CommitParams.create("Other commit message").withAmend(false).withAll(true);
    Revision revision = connection.commit(commitParams);
    assertEquals(revision.getMessage(), commitParams.getMessage());
}
Also used : CommitParams(org.eclipse.che.api.git.params.CommitParams) Revision(org.eclipse.che.api.git.shared.Revision) GitConnection(org.eclipse.che.api.git.GitConnection) Test(org.testng.annotations.Test)

Example 4 with Revision

use of org.eclipse.che.api.git.shared.Revision in project che by eclipse.

the class JGitConnection method commit.

@Override
public Revision commit(CommitParams params) throws GitException {
    try {
        // Check repository state
        RepositoryState repositoryState = repository.getRepositoryState();
        if (!repositoryState.canCommit()) {
            throw new GitException(format(MESSAGE_COMMIT_NOT_POSSIBLE, repositoryState.getDescription()));
        }
        if (params.isAmend() && !repositoryState.canAmend()) {
            throw new GitException(format(MESSAGE_COMMIT_AMEND_NOT_POSSIBLE, repositoryState.getDescription()));
        }
        // Check committer
        GitUser committer = getUser();
        if (committer == null) {
            throw new GitException("Committer can't be null");
        }
        String committerName = committer.getName();
        String committerEmail = committer.getEmail();
        if (committerName == null || committerEmail == null) {
            throw new GitException("Git user name and (or) email wasn't set", ErrorCodes.NO_COMMITTER_NAME_OR_EMAIL_DEFINED);
        }
        // Check commit message
        String message = params.getMessage();
        if (message == null) {
            throw new GitException("Message wasn't set");
        }
        Status status = status(StatusFormat.SHORT);
        List<String> specified = params.getFiles();
        List<String> staged = new ArrayList<>();
        staged.addAll(status.getAdded());
        staged.addAll(status.getChanged());
        staged.addAll(status.getRemoved());
        List<String> changed = new ArrayList<>(staged);
        changed.addAll(status.getModified());
        changed.addAll(status.getMissing());
        List<String> specifiedStaged = specified.stream().filter(path -> staged.stream().anyMatch(s -> s.startsWith(path))).collect(Collectors.toList());
        List<String> specifiedChanged = specified.stream().filter(path -> changed.stream().anyMatch(c -> c.startsWith(path))).collect(Collectors.toList());
        // Check that there are changes present for commit, if 'isAmend' is disabled
        if (!params.isAmend()) {
            // Check that there are staged changes present for commit, or any changes if 'isAll' is enabled
            if (status.isClean()) {
                throw new GitException("Nothing to commit, working directory clean");
            } else if (!params.isAll() && (specified.isEmpty() ? staged.isEmpty() : specifiedStaged.isEmpty())) {
                throw new GitException("No changes added to commit");
            }
        } else {
            /*
                By default Jgit doesn't allow to commit not changed specified paths. According to setAllowEmpty method documentation,
                setting this flag to true must allow such commit, but it won't because Jgit has a bug:
                https://bugs.eclipse.org/bugs/show_bug.cgi?id=510685. As a workaround, specified paths of the commit command will contain
                only changed and specified paths. If other changes are present, but the list of changed and specified paths is empty,
                throw exception to prevent committing other paths. TODO Remove this check when the bug will be fixed.
                */
            if (!specified.isEmpty() && !(params.isAll() ? changed.isEmpty() : staged.isEmpty()) && specifiedChanged.isEmpty()) {
                throw new GitException(format("Changes are present but not changed path%s specified for commit.", specified.size() > 1 ? "s were" : " was"));
            }
        }
        // TODO add 'setAllowEmpty(params.isAmend())' when https://bugs.eclipse.org/bugs/show_bug.cgi?id=510685 will be fixed
        CommitCommand commitCommand = getGit().commit().setCommitter(committerName, committerEmail).setAuthor(committerName, committerEmail).setMessage(message).setAll(params.isAll()).setAmend(params.isAmend());
        if (!params.isAll()) {
            // TODO change to 'specified.forEach(commitCommand::setOnly)' when https://bugs.eclipse.org/bugs/show_bug.cgi?id=510685 will be fixed. See description above.
            specifiedChanged.forEach(commitCommand::setOnly);
        }
        // Check if repository is configured with Gerrit Support
        String gerritSupportConfigValue = repository.getConfig().getString(ConfigConstants.CONFIG_GERRIT_SECTION, null, ConfigConstants.CONFIG_KEY_CREATECHANGEID);
        boolean isGerritSupportConfigured = gerritSupportConfigValue != null ? Boolean.valueOf(gerritSupportConfigValue) : false;
        commitCommand.setInsertChangeId(isGerritSupportConfigured);
        RevCommit result = commitCommand.call();
        GitUser gitUser = newDto(GitUser.class).withName(committerName).withEmail(committerEmail);
        return newDto(Revision.class).withBranch(getCurrentBranch()).withId(result.getId().getName()).withMessage(result.getFullMessage()).withCommitTime(MILLISECONDS.convert(result.getCommitTime(), SECONDS)).withCommitter(gitUser);
    } catch (GitAPIException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
}
Also used : RebaseStatus(org.eclipse.che.api.git.shared.RebaseResponse.RebaseStatus) Status(org.eclipse.che.api.git.shared.Status) InvalidRefNameException(org.eclipse.jgit.api.errors.InvalidRefNameException) Arrays(java.util.Arrays) LsFilesParams(org.eclipse.che.api.git.params.LsFilesParams) RevObject(org.eclipse.jgit.revwalk.RevObject) RebaseResponse(org.eclipse.che.api.git.shared.RebaseResponse) RemoteConfig(org.eclipse.jgit.transport.RemoteConfig) RepositoryState(org.eclipse.jgit.lib.RepositoryState) PullParams(org.eclipse.che.api.git.params.PullParams) SshTransport(org.eclipse.jgit.transport.SshTransport) RevWalk(org.eclipse.jgit.revwalk.RevWalk) CloneParams(org.eclipse.che.api.git.params.CloneParams) RevTag(org.eclipse.jgit.revwalk.RevTag) ResetCommand(org.eclipse.jgit.api.ResetCommand) PathFilter(org.eclipse.jgit.treewalk.filter.PathFilter) Map(java.util.Map) URIish(org.eclipse.jgit.transport.URIish) PullResponse(org.eclipse.che.api.git.shared.PullResponse) TrueFileFilter(org.apache.commons.io.filefilter.TrueFileFilter) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) RebaseStatus(org.eclipse.che.api.git.shared.RebaseResponse.RebaseStatus) GitConflictException(org.eclipse.che.api.git.exception.GitConflictException) EnumSet(java.util.EnumSet) TagCommand(org.eclipse.jgit.api.TagCommand) RepositoryCache(org.eclipse.jgit.lib.RepositoryCache) Result(org.eclipse.jgit.lib.RefUpdate.Result) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) TreeFilter(org.eclipse.jgit.treewalk.filter.TreeFilter) GitConnection(org.eclipse.che.api.git.GitConnection) RefSpec(org.eclipse.jgit.transport.RefSpec) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) RebaseResult(org.eclipse.jgit.api.RebaseResult) CommitCommand(org.eclipse.jgit.api.CommitCommand) Config(org.eclipse.che.api.git.Config) RefUpdate(org.eclipse.jgit.lib.RefUpdate) OpenSshConfig(org.eclipse.jgit.transport.OpenSshConfig) Set(java.util.Set) Status(org.eclipse.che.api.git.shared.Status) Constants(org.eclipse.jgit.lib.Constants) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) TransportCommand(org.eclipse.jgit.api.TransportCommand) Nullable(org.eclipse.che.commons.annotation.Nullable) RevTree(org.eclipse.jgit.revwalk.RevTree) DirectoryFileFilter(org.apache.commons.io.filefilter.DirectoryFileFilter) RemoteUpdateParams(org.eclipse.che.api.git.params.RemoteUpdateParams) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GitInvalidRefNameException(org.eclipse.che.api.git.exception.GitInvalidRefNameException) StatusFormat(org.eclipse.che.api.git.shared.StatusFormat) FileUtils(org.eclipse.jgit.util.FileUtils) Stream(java.util.stream.Stream) CredentialsLoader(org.eclipse.che.api.git.CredentialsLoader) Session(com.jcraft.jsch.Session) PushResult(org.eclipse.jgit.transport.PushResult) DirCache(org.eclipse.jgit.dircache.DirCache) GitRefNotFoundException(org.eclipse.che.api.git.exception.GitRefNotFoundException) FS(org.eclipse.jgit.util.FS) JSchException(com.jcraft.jsch.JSchException) Revision(org.eclipse.che.api.git.shared.Revision) FilenameFilter(java.io.FilenameFilter) RevCommit(org.eclipse.jgit.revwalk.RevCommit) LogCommand(org.eclipse.jgit.api.LogCommand) LogPage(org.eclipse.che.api.git.LogPage) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) PROVIDER_NAME(org.eclipse.che.api.git.shared.ProviderInfo.PROVIDER_NAME) ArrayList(java.util.ArrayList) LogParams(org.eclipse.che.api.git.params.LogParams) SetupUpstreamMode(org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode) ListMode(org.eclipse.jgit.api.ListBranchCommand.ListMode) ResetParams(org.eclipse.che.api.git.params.ResetParams) PushResponse(org.eclipse.che.api.git.shared.PushResponse) DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) PushCommand(org.eclipse.jgit.api.PushCommand) RefAlreadyExistsException(org.eclipse.jgit.api.errors.RefAlreadyExistsException) PathFilterGroup(org.eclipse.jgit.treewalk.filter.PathFilterGroup) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) DiffPage(org.eclipse.che.api.git.DiffPage) ErrorCodes(org.eclipse.che.api.core.ErrorCodes) BranchListMode(org.eclipse.che.api.git.shared.BranchListMode) Tag(org.eclipse.che.api.git.shared.Tag) AddRequest(org.eclipse.che.api.git.shared.AddRequest) FileOutputStream(java.io.FileOutputStream) MergeResult(org.eclipse.che.api.git.shared.MergeResult) ProviderInfo(org.eclipse.che.api.git.shared.ProviderInfo) IOException(java.io.IOException) File(java.io.File) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException) DiffParams(org.eclipse.che.api.git.params.DiffParams) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) ServerException(org.eclipse.che.api.core.ServerException) StoredConfig(org.eclipse.jgit.lib.StoredConfig) Repository(org.eclipse.jgit.lib.Repository) IOFileFilter(org.apache.commons.io.filefilter.IOFileFilter) PushParams(org.eclipse.che.api.git.params.PushParams) LineConsumerFactory(org.eclipse.che.api.core.util.LineConsumerFactory) FetchParams(org.eclipse.che.api.git.params.FetchParams) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) GitRefAlreadyExistsException(org.eclipse.che.api.git.exception.GitRefAlreadyExistsException) AddCommand(org.eclipse.jgit.api.AddCommand) UserCredential(org.eclipse.che.api.git.UserCredential) CheckoutConflictException(org.eclipse.jgit.api.errors.CheckoutConflictException) NullOutputStream(org.eclipse.jgit.util.io.NullOutputStream) FetchResult(org.eclipse.jgit.transport.FetchResult) CommitParams(org.eclipse.che.api.git.params.CommitParams) ProxyAuthenticator(org.eclipse.che.commons.proxy.ProxyAuthenticator) ResetType(org.eclipse.jgit.api.ResetCommand.ResetType) RemoteAddParams(org.eclipse.che.api.git.params.RemoteAddParams) AUTHENTICATE_URL(org.eclipse.che.api.git.shared.ProviderInfo.AUTHENTICATE_URL) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) GitException(org.eclipse.che.api.git.exception.GitException) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) DtoFactory.newDto(org.eclipse.che.dto.server.DtoFactory.newDto) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) List(java.util.List) Branch(org.eclipse.che.api.git.shared.Branch) RemoteReference(org.eclipse.che.api.git.shared.RemoteReference) Ref(org.eclipse.jgit.lib.Ref) TagCreateParams(org.eclipse.che.api.git.params.TagCreateParams) Optional(java.util.Optional) ListBranchCommand(org.eclipse.jgit.api.ListBranchCommand) Pattern(java.util.regex.Pattern) RmCommand(org.eclipse.jgit.api.RmCommand) GitUrlUtils(org.eclipse.che.api.git.GitUrlUtils) Remote(org.eclipse.che.api.git.shared.Remote) System.lineSeparator(java.lang.System.lineSeparator) JSch(com.jcraft.jsch.JSch) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) LineConsumer(org.eclipse.che.api.core.util.LineConsumer) CloneCommand(org.eclipse.jgit.api.CloneCommand) HashMap(java.util.HashMap) RebaseCommand(org.eclipse.jgit.api.RebaseCommand) LIST_ALL(org.eclipse.che.api.git.shared.BranchListMode.LIST_ALL) LIST_LOCAL(org.eclipse.che.api.git.shared.BranchListMode.LIST_LOCAL) FetchCommand(org.eclipse.jgit.api.FetchCommand) Inject(javax.inject.Inject) HashSet(java.util.HashSet) RmParams(org.eclipse.che.api.git.params.RmParams) LIST_REMOTE(org.eclipse.che.api.git.shared.BranchListMode.LIST_REMOTE) Files(com.google.common.io.Files) SshKeyProvider(org.eclipse.che.plugin.ssh.key.script.SshKeyProvider) SshSessionFactory(org.eclipse.jgit.transport.SshSessionFactory) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) BatchingProgressMonitor(org.eclipse.jgit.lib.BatchingProgressMonitor) AndTreeFilter(org.eclipse.jgit.treewalk.filter.AndTreeFilter) EmptyTreeIterator(org.eclipse.jgit.treewalk.EmptyTreeIterator) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) AddParams(org.eclipse.che.api.git.params.AddParams) GitUserResolver(org.eclipse.che.api.git.GitUserResolver) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) CreateBranchCommand(org.eclipse.jgit.api.CreateBranchCommand) ConfigConstants(org.eclipse.jgit.lib.ConfigConstants) ShowFileContentResponse(org.eclipse.che.api.git.shared.ShowFileContentResponse) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) ObjectId(org.eclipse.jgit.lib.ObjectId) TransportException(org.eclipse.jgit.api.errors.TransportException) OWNER_READ(java.nio.file.attribute.PosixFilePermission.OWNER_READ) RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) LsRemoteCommand(org.eclipse.jgit.api.LsRemoteCommand) CheckoutParams(org.eclipse.che.api.git.params.CheckoutParams) TrackingRefUpdate(org.eclipse.jgit.transport.TrackingRefUpdate) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Git(org.eclipse.jgit.api.Git) DetachedHeadException(org.eclipse.jgit.api.errors.DetachedHeadException) DiffEntry(org.eclipse.jgit.diff.DiffEntry) OWNER_WRITE(java.nio.file.attribute.PosixFilePermission.OWNER_WRITE) GitUser(org.eclipse.che.api.git.shared.GitUser) Collections(java.util.Collections) JschConfigSessionFactory(org.eclipse.jgit.transport.JschConfigSessionFactory) SECONDS(java.util.concurrent.TimeUnit.SECONDS) GitException(org.eclipse.che.api.git.exception.GitException) ArrayList(java.util.ArrayList) RepositoryState(org.eclipse.jgit.lib.RepositoryState) GitUser(org.eclipse.che.api.git.shared.GitUser) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Revision(org.eclipse.che.api.git.shared.Revision) CommitCommand(org.eclipse.jgit.api.CommitCommand) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 5 with Revision

use of org.eclipse.che.api.git.shared.Revision in project che by eclipse.

the class JGitConnection method log.

/** @see org.eclipse.che.api.git.GitConnection#log(LogParams) */
@Override
public LogPage log(LogParams params) throws GitException {
    LogCommand logCommand = getGit().log();
    try {
        setRevisionRange(logCommand, params);
        logCommand.setSkip(params.getSkip());
        logCommand.setMaxCount(params.getMaxCount());
        List<String> fileFilter = params.getFileFilter();
        if (fileFilter != null) {
            fileFilter.forEach(logCommand::addPath);
        }
        String filePath = params.getFilePath();
        if (!isNullOrEmpty(filePath)) {
            logCommand.addPath(filePath);
        }
        Iterator<RevCommit> revIterator = logCommand.call().iterator();
        List<Revision> commits = new ArrayList<>();
        while (revIterator.hasNext()) {
            RevCommit commit = revIterator.next();
            Revision revision = getRevision(commit, filePath);
            commits.add(revision);
        }
        return new LogPage(commits);
    } catch (GitAPIException | IOException exception) {
        String errorMessage = exception.getMessage();
        if (ERROR_LOG_NO_HEAD_EXISTS.equals(errorMessage)) {
            throw new GitException(errorMessage, ErrorCodes.INIT_COMMIT_WAS_NOT_PERFORMED);
        } else {
            LOG.error("Failed to retrieve log. ", exception);
            throw new GitException(exception);
        }
    }
}
Also used : GitException(org.eclipse.che.api.git.exception.GitException) LogPage(org.eclipse.che.api.git.LogPage) ArrayList(java.util.ArrayList) IOException(java.io.IOException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Revision(org.eclipse.che.api.git.shared.Revision) LogCommand(org.eclipse.jgit.api.LogCommand) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Aggregations

Revision (org.eclipse.che.api.git.shared.Revision)23 GitConnection (org.eclipse.che.api.git.GitConnection)10 Test (org.testng.annotations.Test)9 ArrayList (java.util.ArrayList)6 LogResponse (org.eclipse.che.api.git.shared.LogResponse)5 BaseTest (org.eclipse.che.ide.ext.git.client.BaseTest)5 Test (org.junit.Test)5 CommitParams (org.eclipse.che.api.git.params.CommitParams)4 TextCell (com.google.gwt.cell.client.TextCell)3 Column (com.google.gwt.user.cellview.client.Column)3 SelectionChangeEvent (com.google.gwt.view.client.SelectionChangeEvent)3 GitUser (org.eclipse.che.api.git.shared.GitUser)3 DoubleClickEvent (com.google.gwt.event.dom.client.DoubleClickEvent)2 DoubleClickHandler (com.google.gwt.event.dom.client.DoubleClickHandler)2 IOException (java.io.IOException)2 Date (java.util.Date)2 LogPage (org.eclipse.che.api.git.LogPage)2 GitException (org.eclipse.che.api.git.exception.GitException)2 Branch (org.eclipse.che.api.git.shared.Branch)2 CommitRequest (org.eclipse.che.api.git.shared.CommitRequest)2