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

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

Introduction

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

Prototype

public CommitCommand setCommitter(String name, String email) 

Source Link

Document

Sets the committer for this commit .

Usage

From source file:com.sap.dirigible.ide.jgit.connector.JGitConnector.java

License:Open Source License

/**
 * /*from  w  w w  . ja  v  a  2  s  . c o  m*/
 * Adds changes to the staging index. Then makes commit.
 * 
 * @param message
 *            the commit message
 * @param name
 *            the name of the committer used for the commit
 * @param email
 *            the email of the committer used for the commit
 * @param all
 *            if set to true, command will automatically stages files that
 *            have been modified and deleted, but new files not known by the
 *            repository are not affected. This corresponds to the parameter
 *            -a on the command line.
 * 
 * @throws NoHeadException
 * @throws NoMessageException
 * @throws UnmergedPathsException
 * @throws ConcurrentRefUpdateException
 * @throws WrongRepositoryStateException
 * @throws GitAPIException
 * @throws IOException
 */
public void commit(String message, String name, String email, boolean all)
        throws NoHeadException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException,
        WrongRepositoryStateException, GitAPIException, IOException {
    CommitCommand commitCommand = git.commit();
    commitCommand.setMessage(message);
    commitCommand.setCommitter(name, email);
    commitCommand.setAuthor(name, email);
    commitCommand.setAll(all);
    commitCommand.call();
}

From source file:com.verigreen.jgit.JGitOperator.java

License:Apache License

@Override
public String commit(String author, String email, String message) {

    RevCommit revCommit = null;/*from w w  w  .j  a  v a2  s .c o  m*/
    CommitCommand command = _git.commit();
    command.setCommitter(author, email);
    command.setMessage(message);
    command.setAll(true);
    try {
        revCommit = command.call();
    } catch (Throwable e) {
        throw new RuntimeException("Failed to commit", e);
    }

    return revCommit.getId().getName();
}

From source file:org.apache.maven.scm.provider.git.jgit.command.checkin.JGitCheckInCommand.java

License:Apache License

/**
 * {@inheritDoc}/*www .  j  av  a  2s .com*/
 */
protected CheckInScmResult executeCheckInCommand(ScmProviderRepository repo, ScmFileSet fileSet, String message,
        ScmVersion version) throws ScmException {

    Git git = null;
    try {
        File basedir = fileSet.getBasedir();
        git = Git.open(basedir);

        boolean doCommit = false;

        if (!fileSet.getFileList().isEmpty()) {
            doCommit = JGitUtils.addAllFiles(git, fileSet).size() > 0;
        } else {
            // add all tracked files which are modified manually
            Set<String> changeds = git.status().call().getModified();
            if (changeds.isEmpty()) {
                // warn there is nothing to add
                getLogger().warn("there are no files to be added");
                doCommit = false;
            } else {
                AddCommand add = git.add();
                for (String changed : changeds) {
                    getLogger().debug("add manualy: " + changed);
                    add.addFilepattern(changed);
                    doCommit = true;
                }
                add.call();
            }
        }

        List<ScmFile> checkedInFiles = Collections.emptyList();
        if (doCommit) {
            UserInfo author = getAuthor(repo, git);
            UserInfo committer = getCommitter(repo, git);

            CommitCommand command = git.commit().setMessage(message).setAuthor(author.name, author.email);
            command.setCommitter(committer.name, committer.email);
            RevCommit commitRev = command.call();

            getLogger().info("commit done: " + commitRev.getShortMessage());
            checkedInFiles = JGitUtils.getFilesInCommit(git.getRepository(), commitRev);
            if (getLogger().isDebugEnabled()) {
                for (ScmFile scmFile : checkedInFiles) {
                    getLogger().debug("in commit: " + scmFile);
                }
            }
        }

        if (repo.isPushChanges()) {
            String branch = version != null ? version.getName() : null;
            if (StringUtils.isBlank(branch)) {
                branch = git.getRepository().getBranch();
            }
            RefSpec refSpec = new RefSpec(Constants.R_HEADS + branch + ":" + Constants.R_HEADS + branch);
            getLogger().info("push changes to remote... " + refSpec.toString());
            JGitUtils.push(getLogger(), git, (GitScmProviderRepository) repo, refSpec);
        }

        return new CheckInScmResult("JGit checkin", checkedInFiles);
    } catch (Exception e) {
        throw new ScmException("JGit checkin failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

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);//from w  ww  .j  a  v  a 2s . c  om

    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.orion.server.git.servlets.GitCommitHandlerV1.java

License:Open Source License

private boolean handlePost(HttpServletRequest request, HttpServletResponse response, Repository db, Path path)
        throws ServletException, NoFilepatternException, IOException, JSONException, CoreException,
        URISyntaxException {//from  ww  w  .ja v  a2 s .c  o m
    IPath filePath = path.hasTrailingSeparator() ? path.removeFirstSegments(1)
            : path.removeFirstSegments(1).removeLastSegments(1);
    Set<Entry<IPath, File>> set = GitUtils.getGitDirs(filePath, Traverse.GO_UP).entrySet();
    File gitDir = set.iterator().next().getValue();
    if (gitDir == null)
        return false; // TODO: or an error response code, 405?
    db = new FileRepository(gitDir);

    JSONObject requestObject = OrionServlet.readJSONRequest(request);
    String commitToMerge = requestObject.optString(GitConstants.KEY_MERGE, null);
    if (commitToMerge != null) {
        return merge(request, response, db, commitToMerge);
    }

    String commitToRebase = requestObject.optString(GitConstants.KEY_REBASE, null);
    String rebaseOperation = requestObject.optString(GitConstants.KEY_OPERATION, null);
    if (commitToRebase != null) {
        return rebase(request, response, db, commitToRebase, rebaseOperation);
    }

    String commitToCherryPick = requestObject.optString(GitConstants.KEY_CHERRY_PICK, null);
    if (commitToCherryPick != null) {
        return cherryPick(request, response, db, commitToCherryPick);
    }

    // continue with creating new commit location

    String newCommitToCreatelocation = requestObject.optString(GitConstants.KEY_COMMIT_NEW, null);
    if (newCommitToCreatelocation != null)
        return createCommitLocation(request, response, db, newCommitToCreatelocation);

    ObjectId refId = db.resolve(path.segment(0));
    if (refId == null || !Constants.HEAD.equals(path.segment(0))) {
        String msg = NLS.bind("Commit failed. Ref must be HEAD and is {0}", path.segment(0));
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
    }

    String message = requestObject.optString(GitConstants.KEY_COMMIT_MESSAGE, null);
    if (message == null || message.isEmpty()) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "Missing commit message.", null));
    }

    boolean amend = Boolean.parseBoolean(requestObject.optString(GitConstants.KEY_COMMIT_AMEND, null));

    String committerName = requestObject.optString(GitConstants.KEY_COMMITTER_NAME, null);
    String committerEmail = requestObject.optString(GitConstants.KEY_COMMITTER_EMAIL, null);
    String authorName = requestObject.optString(GitConstants.KEY_AUTHOR_NAME, null);
    String authorEmail = requestObject.optString(GitConstants.KEY_AUTHOR_EMAIL, null);

    Git git = new Git(db);
    CommitCommand commit = git.commit();

    // workaround of a bug in JGit which causes invalid 
    // support of null values of author/committer name/email 
    PersonIdent defPersonIdent = new PersonIdent(db);
    if (committerName == null)
        committerName = defPersonIdent.getName();
    if (committerEmail == null)
        committerEmail = defPersonIdent.getEmailAddress();
    if (authorName == null)
        authorName = committerName;
    if (authorEmail == null)
        authorEmail = committerEmail;
    commit.setCommitter(committerName, committerEmail);
    commit.setAuthor(authorName, authorEmail);

    // support for committing by path: "git commit -o path"
    boolean isRoot = true;
    String pattern = GitUtils.getRelativePath(path.removeFirstSegments(1), set.iterator().next().getKey());
    if (!pattern.isEmpty()) {
        commit.setOnly(pattern);
        isRoot = false;
    }

    try {
        // "git commit [--amend] -m '{message}' [-a|{path}]"
        RevCommit lastCommit = commit.setAmend(amend).setMessage(message).call();
        Map<ObjectId, JSONArray> commitToBranchMap = getCommitToBranchMap(db);

        JSONObject result = toJSON(db, lastCommit, commitToBranchMap, getURI(request), null, isRoot);
        OrionServlet.writeJSONResponse(request, response, result);
        return true;
    } catch (GitAPIException e) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "An error occured when commiting.", e));
    } catch (JGitInternalException e) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An internal error occured when commiting.", e));
    }
}

From source file:org.jabylon.team.git.GitTeamProvider.java

License:Open Source License

@Override
public void commit(ProjectVersion project, IProgressMonitor monitor) throws TeamProviderException {
    try {/*from w  ww . j av a 2 s . c  o m*/
        Repository repository = createRepository(project);
        SubMonitor subMon = SubMonitor.convert(monitor, "Commit", 100);
        Git git = new Git(repository);
        // AddCommand addCommand = git.add();
        List<String> changedFiles = addNewFiles(git, subMon.newChild(30));
        if (!changedFiles.isEmpty()) {
            checkCanceled(subMon);
            CommitCommand commit = git.commit();
            Preferences node = PreferencesUtil.scopeFor(project.getParent());
            String username = node.get(GitConstants.KEY_USERNAME, "Jabylon");
            String email = node.get(GitConstants.KEY_EMAIL, "jabylon@example.org");
            String message = node.get(GitConstants.KEY_MESSAGE, "Auto Sync-up by Jabylon");
            boolean insertChangeId = node.getBoolean(GitConstants.KEY_INSERT_CHANGE_ID, false);
            commit.setAuthor(username, email);
            commit.setCommitter(username, email);
            commit.setInsertChangeId(insertChangeId);
            commit.setMessage(message);
            for (String path : changedFiles) {
                checkCanceled(subMon);
                commit.setOnly(path);

            }
            commit.call();
            subMon.worked(10);
        } else {
            LOGGER.info("No changed files, skipping commit phase");
        }
        checkCanceled(subMon);
        PushCommand push = git.push();
        URI uri = project.getParent().getRepositoryURI();
        if (uri != null)
            push.setRemote(stripUserInfo(uri).toString());
        push.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(60)));
        if (!"https".equals(uri.scheme()) && !"http".equals(uri.scheme()))
            push.setTransportConfigCallback(createTransportConfigCallback(project.getParent()));
        push.setCredentialsProvider(createCredentialsProvider(project.getParent()));

        RefSpec spec = createRefSpec(project);
        push.setRefSpecs(spec);

        Iterable<PushResult> result = push.call();
        for (PushResult r : result) {
            for (RemoteRefUpdate rru : r.getRemoteUpdates()) {
                if (rru.getStatus() != RemoteRefUpdate.Status.OK
                        && rru.getStatus() != RemoteRefUpdate.Status.UP_TO_DATE) {
                    String error = "Push failed: " + rru.getStatus();
                    LOGGER.error(error);
                    throw new TeamProviderException(error);
                }
            }
        }

        Ref ref = repository.getRef(project.getName());
        if (ref != null) {
            LOGGER.info("Successfully pushed {} to {}", ref.getObjectId(),
                    project.getParent().getRepositoryURI());
        }
    } catch (NoHeadException e) {
        throw new TeamProviderException(e);
    } catch (NoMessageException e) {
        throw new TeamProviderException(e);
    } catch (ConcurrentRefUpdateException e) {
        throw new TeamProviderException(e);
    } catch (JGitInternalException e) {
        throw new TeamProviderException(e);
    } catch (WrongRepositoryStateException e) {
        throw new TeamProviderException(e);
    } catch (InvalidRemoteException e) {
        throw new TeamProviderException(e);
    } catch (IOException e) {
        throw new TeamProviderException(e);
    } catch (GitAPIException e) {
        throw new TeamProviderException(e);
    } finally {
        if (monitor != null)
            monitor.done();
    }
}

From source file:org.mule.module.git.GitConnector.java

License:Open Source License

/**
 * Record changes to the repository/*from w ww. j a va  2s.co  m*/
 *
 * {@sample.xml ../../../doc/mule-module-git.xml.sample git:commit}
 *
 * @param msg            Commit message
 * @param committerName  Name of the person performing this commit
 * @param committerEmail Email of the person performing this commit
 * @param authorName     Name of the author of the changes to commit
 * @param authorEmail    Email of the author of the changes to commit
 * @param overrideDirectory Name of the directory to use for git repository
 */
@Processor
public void commit(String msg, String committerName, String committerEmail, @Optional String authorName,
        @Optional String authorEmail, @Optional String overrideDirectory) {
    try {
        Git git = new Git(getGitRepo(overrideDirectory));
        CommitCommand commit = git.commit();
        if (authorName != null && authorEmail != null) {
            commit.setAuthor(authorName, authorEmail);
        }

        commit.setCommitter(committerName, committerEmail);
        commit.setMessage(msg);

        commit.call();
    } catch (Exception e) {
        throw new RuntimeException("Unable to commit", e);
    }
}

From source file:org.webcat.core.git.GitUtilities.java

License:Open Source License

/**
 * Sets up a new base Git repository for the specified object.
 *
 * @param object the object whose file store is desired
 * @param location the file system location for the repository
 * @return the newly created repository// w ww.  j a v  a  2 s  .c  om
 */
private static Repository setUpNewRepository(EOEnterpriseObject object, File location) throws IOException {
    // This method performs the following actions to set up a new
    // repository:
    //
    // 1) Creates a new bare repository in the location requested by the
    //    method argument.
    // 2) Creates a temporary non-bare repository in the system temp
    //    directory, which is then configured to use the bare repository
    //    as a remote repository.
    // 3) Creates a README.txt file in the temporary repository's working
    //    directory, which contains a welcome message determined by the
    //    type of object that created the repo.
    // 4) Adds the README.txt to the repository, commits the change, and
    //    then pushes the changes to the bare repository.
    // 5) Finally, the temporary repository is deleted.
    //
    // This results in a usable bare repository being created, which a user
    // can now clone locally in order to manage their Web-CAT file store.

    // Create the bare repository.
    InitCommand init = new InitCommand();
    init.setDirectory(location);
    init.setBare(true);
    Repository bareRepository = init.call().getRepository();

    // Create the temporary repository.
    File tempRepoDir = File.createTempFile("newgitrepo", null);
    tempRepoDir.delete();
    tempRepoDir.mkdirs();

    init = new InitCommand();
    init.setDirectory(tempRepoDir);
    Repository tempRepository = init.call().getRepository();

    // Create the welcome files in the temporary repo.

    if (object instanceof RepositoryProvider) {
        RepositoryProvider provider = (RepositoryProvider) object;

        try {
            provider.initializeRepositoryContents(tempRepoDir);
        } catch (Exception e) {
            log.error(
                    "The following exception occurred when trying to "
                            + "initialize the repository contents at " + location.getAbsolutePath()
                            + ", but I'm continuing " + "anyway to ensure that the repository isn't corrupt.",
                    e);
        }
    }

    // Make sure we created at least one file, since we can't do much with
    // an empty repository. If the object didn't put anything in the
    // staging area, we'll just create a dummy README file.

    File[] files = tempRepoDir.listFiles();
    boolean foundFile = false;

    for (File file : files) {
        String name = file.getName();
        if (!".".equals(name) && !"..".equals(name) && !".git".equalsIgnoreCase(name)) {
            foundFile = true;
            break;
        }
    }

    if (!foundFile) {
        PrintWriter writer = new PrintWriter(new File(tempRepoDir, "README.txt"));
        writer.println("This readme file is provided so that the initial repository\n"
                + "has some content. You may delete it when you push other files\n"
                + "into the repository, if you wish.");
        writer.close();
    }

    // Create an appropriate default .gitignore file.
    PrintWriter writer = new PrintWriter(new File(tempRepoDir, ".gitignore"));
    writer.println("~*");
    writer.println("._*");
    writer.println(".TemporaryItems");
    writer.println(".DS_Store");
    writer.println("Thumbs.db");
    writer.close();

    // Add the files to the temporary repository.
    AddCommand add = new AddCommand(tempRepository);
    add.addFilepattern(".");
    add.setUpdate(false);

    try {
        add.call();
    } catch (NoFilepatternException e) {
        log.error("An exception occurred when adding the welcome files " + "to the repository: ", e);
        return bareRepository;
    }

    // Commit the changes.
    String email = Application.configurationProperties().getProperty("coreAdminEmail");
    CommitCommand commit = new Git(tempRepository).commit();
    commit.setAuthor("Web-CAT", email);
    commit.setCommitter("Web-CAT", email);
    commit.setMessage("Initial repository setup.");

    try {
        commit.call();
    } catch (Exception e) {
        log.error("An exception occurred when committing the welcome files " + "to the repository: ", e);
        return bareRepository;
    }

    // Push the changes to the bare repository.
    PushCommand push = new Git(tempRepository).push();
    @SuppressWarnings("deprecation")
    String url = location.toURL().toString();
    push.setRemote(url);
    push.setRefSpecs(new RefSpec("master"), new RefSpec("master"));

    try {
        push.call();
    } catch (Exception e) {
        log.error("An exception occurred when pushing the welcome files " + "to the repository: ", e);
        return bareRepository;
    }

    // Cleanup after ourselves.
    FileUtilities.deleteDirectory(tempRepoDir);

    return bareRepository;
}

From source file:org.zanata.sync.plugin.git.service.impl.GitSyncService.java

License:Open Source License

@Override
public void syncTranslationToRepo(String repoUrl, String branch, File baseDir) throws RepoSyncException {
    try {/*w  w w  . ja  v a  2 s .c o m*/
        Git git = Git.open(baseDir);
        StatusCommand statusCommand = git.status();
        Status status = statusCommand.call();
        Set<String> uncommittedChanges = status.getUncommittedChanges();
        uncommittedChanges.addAll(status.getUntracked());
        if (!uncommittedChanges.isEmpty()) {
            log.info("uncommitted files in git repo: {}", uncommittedChanges);
            AddCommand addCommand = git.add();
            addCommand.addFilepattern(".");
            addCommand.call();

            log.info("commit changed files");
            CommitCommand commitCommand = git.commit();
            commitCommand.setCommitter("Zanata Auto Repo Sync", "zanata-users@redhat.com");
            commitCommand.setMessage("Zanata Auto Repo Sync (pushing translations)");
            commitCommand.call();

            log.info("push to remote repo");
            PushCommand pushCommand = git.push();
            UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider(
                    getCredentials().getUsername(), getCredentials().getSecret());
            pushCommand.setCredentialsProvider(user);
            pushCommand.call();
        } else {
            log.info("nothing changed so nothing to do");
        }
    } catch (IOException e) {
        throw new RepoSyncException("failed opening " + baseDir + " as git repo", e);
    } catch (GitAPIException e) {
        throw new RepoSyncException("Failed committing translations into the repo", e);
    }
}