Example usage for org.eclipse.jgit.api CommitCommand call

List of usage examples for org.eclipse.jgit.api CommitCommand call

Introduction

In this page you can find the example usage for org.eclipse.jgit.api CommitCommand call.

Prototype

@Override
public RevCommit call() throws GitAPIException, NoHeadException, NoMessageException, UnmergedPathsException,
        ConcurrentRefUpdateException, WrongRepositoryStateException, AbortedByHookException 

Source Link

Document

Executes the commit command with all the options and parameters collected by the setter methods of this class.

Usage

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public Revision commit(CommitRequest request) throws GitException {
    try {/*from w w w .jav a2 s.co m*/
        String message = request.getMessage();
        GitUser committer = getUser();
        if (message == null) {
            throw new GitException("Message wasn't set");
        }
        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);
        }
        if (!repository.getRepositoryState().canCommit()) {
            Revision rev = newDto(Revision.class);
            rev.setMessage(String.format(MESSAGE_COMMIT_NOT_POSSIBLE,
                    repository.getRepositoryState().getDescription()));
            return rev;
        }

        if (request.isAmend() && !repository.getRepositoryState().canAmend()) {
            Revision rev = newDto(Revision.class);
            rev.setMessage(String.format(MESSAGE_AMEND_NOT_POSSIBLE,
                    repository.getRepositoryState().getDescription()));
            return rev;
        }

        CommitCommand commitCommand = getGit().commit().setCommitter(committerName, committerEmail)
                .setAuthor(committerName, committerEmail).setMessage(message).setAll(request.isAll())
                .setAmend(request.isAmend());

        // 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);
    }
}

From source file:org.eclipse.egit.core.synchronize.GitSyncInfoTest.java

License:Open Source License

private RevCommit commit() throws Exception {
    Git git = new Git(repo);
    CommitCommand commit = git.commit();
    commit.setMessage("Initial  commit");
    commit.setAuthor("EGit", "egi@eclipse.org");
    return commit.call();
}

From source file:org.eclipse.egit.core.test.TestRepository.java

License:Open Source License

/**
 * Commits the current index/*w  ww. j  a  v  a 2 s .  c  om*/
 *
 * @param message
 *            commit message
 * @return commit object
 *
 * @throws NoHeadException
 * @throws NoMessageException
 * @throws UnmergedPathException
 * @throws ConcurrentRefUpdateException
 * @throws JGitInternalException
 * @throws WrongRepositoryStateException
 */
public RevCommit commit(String message) throws NoHeadException, NoMessageException, UnmergedPathException,
        ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException {
    Git git = new Git(repository);
    CommitCommand commitCommand = git.commit();
    commitCommand.setAuthor("J. Git", "j.git@egit.org");
    commitCommand.setCommitter(commitCommand.getAuthor());
    commitCommand.setMessage(message);
    return commitCommand.call();
}

From source file:org.eclipse.egit.ui.gitflow.AbstractGitflowHandlerTest.java

License:Open Source License

protected RevCommit setContentAddAndCommit(String newContent)
        throws Exception, GitAPIException, NoHeadException, NoMessageException, UnmergedPathsException,
        ConcurrentRefUpdateException, WrongRepositoryStateException, AbortedByHookException, IOException {
    setTestFileContent(newContent);/*w w w.  ja  v  a 2s  .c o m*/

    Git git = Git.wrap(repository);
    git.add().addFilepattern(".").call();
    CommitCommand commit = git.commit().setMessage(newContent);
    commit.setAuthor(TestUtil.TESTCOMMITTER_NAME, TestUtil.TESTCOMMITTER_EMAIL);
    commit.setCommitter(TestUtil.TESTCOMMITTER_NAME, TestUtil.TESTCOMMITTER_EMAIL);
    return commit.call();
}

From source file:org.eclipse.emf.compare.diagram.papyrus.tests.egit.fixture.GitTestRepository.java

License:Open Source License

/**
 * Commits the current index./*  ww  w.  ja v a2  s.c om*/
 * 
 * @param message
 *            commit message
 * @return commit object
 */
public RevCommit commit(String message) throws Exception {
    Git git = new Git(repository);
    try {
        CommitCommand commitCommand = git.commit();
        commitCommand.setAuthor("J. Git", "j.git@egit.org");
        commitCommand.setCommitter(commitCommand.getAuthor());
        commitCommand.setMessage(message);
        return commitCommand.call();
    } finally {
        git.close();
    }
}

From source file:org.eclipse.orion.server.filesystem.git.GitFileStore.java

License:Open Source License

private void rm() throws CoreException {
    // TODO: use org.eclipse.jgit.api.RmCommand, see Enhancement 379
    if (!isRoot()) {
        try {//  w  ww  .  j av a2 s. com
            Repository local = getLocalRepo();
            Git git = new Git(local);
            CommitCommand commit = git.commit();
            commit.setAll(true);
            commit.setMessage("auto-commit of " + toString());
            commit.call();
        } catch (Exception e) {
            throw new CoreException(
                    new Status(IStatus.ERROR, Activator.PI_GIT, IStatus.ERROR, e.getMessage(), e));
        }
        push();
    } // else {cannot commit/push root removal}
}

From source file:org.eclipse.orion.server.filesystem.git.GitFileStore.java

License:Open Source License

private void commit(boolean dir) throws CoreException {
    try {//from   ww w  .  j  a va  2 s . c om
        Repository local = getLocalRepo();
        Git git = new Git(local);
        String folderPattern = null;
        String filePattern = null;
        if (dir) {
            // add empty dir - http://stackoverflow.com/questions/115983/how-do-i-add-an-empty-directory-to-a-git-repository
            File folder = getLocalFile();
            File gitignoreFile = new File(folder.getPath() + "/" + Constants.DOT_GIT_IGNORE);
            // /<folder>/.gitignore
            gitignoreFile.createNewFile();
            String query = getUrl().getQuery();
            if (query.equals("/")) { // root
                filePattern = Constants.DOT_GIT_IGNORE;
            } else {
                folderPattern = new Path(query).toString().substring(1);
                // <folder>/
                filePattern = folderPattern + "/" + Constants.DOT_GIT_IGNORE;
                // <folder>/.gitignore
            }
        } else {
            // /<folder>/<file>
            IPath f = new Path(getUrl().getQuery()).removeLastSegments(1);
            // /<folder>/
            String s = f.toString().substring(1);
            // <folder>/
            folderPattern = s.equals("") ? null : s;
            // /<folder>/<file>
            s = getUrl().getQuery().substring(1);
            filePattern = s;
        }

        // TODO: folder may already exist, no need to add it again
        AddCommand add = git.add();
        if (folderPattern != null) {
            add.addFilepattern(folderPattern);
        }
        add.addFilepattern(filePattern);
        add.call();

        CommitCommand commit = git.commit();
        commit.setMessage("auto-commit of " + this);
        commit.call();
        LogHelper.log(new Status(IStatus.INFO, Activator.PI_GIT, 1, "Auto-commit of " + this + " done.", null));
    } catch (Exception e) {
        throw new CoreException(new Status(IStatus.ERROR, Activator.PI_GIT, IStatus.ERROR, e.getMessage(), e));
    }
}

From source file:org.eclipse.ptp.internal.rdt.sync.git.core.JGitRepo.java

License:Open Source License

/**
 * Commit files in working directory.//from w  w  w . j  av a 2 s  .  co m
 * 
 * assumes that no files are in conflict (do not call during merge)
 *
 * @param monitor
 *
 * @return whether any changes were committed
 * @throws GitAPIException
 *          on JGit-specific problems
 * @throws IOException
 *          on file system problems
 */
public boolean commit(IProgressMonitor monitor) throws GitAPIException, IOException {
    RecursiveSubMonitor subMon = RecursiveSubMonitor.convert(monitor, 10);

    assert (!inUnresolvedMergeState());
    try {
        DiffFiles diffFiles = fileFilter.getDiffFiles();

        // Create and add an empty file to all synchronized directories to force sync'ing of empty directories
        for (String dirName : diffFiles.dirSet) {
            IPath emptyFilePath = new Path(this.getRepository().getWorkTree().getAbsolutePath());
            emptyFilePath = emptyFilePath.append(dirName);
            // Bug 439609 - directory may have been deleted
            File emptyFileDir = new File(emptyFilePath.toOSString());
            if (!emptyFileDir.exists()) {
                continue;
            }
            emptyFilePath = emptyFilePath.append(EMPTY_FILE_NAME);
            File emptyFile = new File(emptyFilePath.toOSString());
            boolean fileWasCreated = emptyFile.createNewFile();
            if (fileWasCreated) {
                diffFiles.added.add(emptyFilePath.toString());
            }
        }

        subMon.subTask(Messages.JGitRepo_2);
        if (!diffFiles.added.isEmpty()) {
            final AddCommand addCommand = git.add();
            //Bug 401161 doesn't matter here because files are already filtered anyhow. It would be OK
            //if the tree iterator would always return false in isEntryIgnored
            addCommand.setWorkingTreeIterator(new SyncFileTreeIterator(git.getRepository(), fileFilter));
            for (String fileName : diffFiles.added) {
                addCommand.addFilepattern(fileName);
            }
            addCommand.call();
        }
        subMon.worked(3);

        subMon.subTask(Messages.JGitRepo_3);
        if (!diffFiles.removed.isEmpty()) {
            final RmCommand rmCommand = new RmCommand(git.getRepository());
            rmCommand.setCached(true);
            for (String fileName : diffFiles.removed) {
                rmCommand.addFilepattern(fileName);
            }
            rmCommand.call();
        }
        subMon.worked(3);

        // Check if a commit is required.
        subMon.subTask(Messages.JGitRepo_4);
        if (anyDiffInIndex() || inMergeState()) {
            final CommitCommand commitCommand = git.commit();
            commitCommand.setMessage(GitSyncService.commitMessage);
            commitCommand.call();
            return true;
        } else {
            return false;
        }
    } finally {
        if (monitor != null) {
            monitor.done();
        }
    }
}

From source file:org.eclipse.ptp.rdt.sync.git.core.GitRemoteSyncConnection.java

License:Open Source License

/**
 * Commits files in working directory. For now, we just commit all files. So
 * adding ".", handles all files, including newly created files, and setting
 * the all flag (-a) ensures that deleted files are updated. TODO: Figure
 * out how to do this more efficiently, as was done remotely (using git
 * ls-files)//from   w ww.jav  a2s .  c o m
 * 
 * @throws RemoteSyncException
 *             on problems committing.
 * @return whether any changes were committed
 */
private boolean doCommit() throws RemoteSyncException {
    Set<String> filesToAdd = new HashSet<String>();
    Set<String> filesToRemove = new HashSet<String>();
    this.getFileStatus(filesToAdd, filesToRemove, true);

    try {
        if (!filesToAdd.isEmpty()) {
            final AddCommand addCommand = git.add();
            for (String fileName : filesToAdd) {
                addCommand.addFilepattern(fileName);
            }
            addCommand.call();
        }

        if (!filesToRemove.isEmpty()) {
            final RmCommand rmCommand = git.rm();
            for (String fileName : filesToRemove) {
                rmCommand.addFilepattern(fileName);
            }
            rmCommand.call();
        }
        if (!filesToAdd.isEmpty() || !filesToRemove.isEmpty()) {
            final CommitCommand commitCommand = git.commit();
            commitCommand.setMessage(commitMessage);
            commitCommand.call();
            return true;
        } else {
            return false;
        }
    } catch (final GitAPIException e) {
        throw new RemoteSyncException(e);
    } catch (final UnmergedPathException e) {
        throw new RemoteSyncException(e);
    }
}

From source file:org.eclipse.winery.repository.backend.filebased.GitBasedRepository.java

License:Open Source License

public void addCommit(String[] patterns, String message) throws GitAPIException {
    if (!message.isEmpty()) {
        synchronized (COMMIT_LOCK) {
            AddCommand add = this.git.add();
            Status status = this.git.status().call();

            for (String pattern : patterns) {
                add.addFilepattern(pattern);
            }/*from   www  .j a  v a2s .  c om*/

            if (!status.getMissing().isEmpty() || !status.getRemoved().isEmpty()) {
                RmCommand remove = this.git.rm();
                for (String file : Iterables.concat(status.getMissing(), status.getRemoved())) {
                    remove.addFilepattern(file);
                }
                remove.call();
            }

            add.call();

            CommitCommand commit = this.git.commit();
            commit.setMessage(message);
            commit.call();
        }
    }
    postEventMap();
}