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

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

Introduction

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

Prototype

public CommitCommand setOnly(String only) 

Source Link

Document

Commit dedicated path only.

Usage

From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public void commit(List<String> paths, String msg) throws Exception {
    CommitCommand commit = git.commit().setMessage(msg);
    for (String path : paths)
        commit.setOnly(path);
    commit.call();/* w  ww  .  j a  v  a 2s. c o  m*/
}

From source file:com.rimerosolutions.ant.git.tasks.CommitTask.java

License:Apache License

@Override
protected void doExecute() throws BuildException {
    try {/*from   w  w  w. j a v  a 2 s.  c  om*/
        setFailOnError(true);
        CommitCommand cmd = git.commit();

        if (!GitTaskUtils.isNullOrBlankString(message)) {
            cmd.setMessage(brandedMessage ? GitTaskUtils.BRANDING_MESSAGE + " " : "" + message);
        } else {
            cmd.setMessage(GitTaskUtils.BRANDING_MESSAGE);
        }

        String prefix = getDirectory().getCanonicalPath();
        String[] allFiles = getPath().list();

        if (!GitTaskUtils.isNullOrBlankString(only)) {
            cmd.setOnly(only);
        } else if (allFiles.length > 0) {
            for (String file : allFiles) {
                String modifiedFile = translateFilePathUsingPrefix(file, prefix);
                log("Will commit " + modifiedFile);
                cmd.setOnly(modifiedFile);
            }
        } else {
            cmd.setAll(true);
        }

        GitSettings gitSettings = lookupSettings();

        if (gitSettings == null) {
            throw new MissingRequiredGitSettingsException();
        }

        cmd.setAmend(amend).setAuthor(gitSettings.getIdentity()).setCommitter(gitSettings.getIdentity());

        if (reflogComment != null) {
            cmd.setReflogComment(reflogComment);
        }

        RevCommit revCommit = cmd.call();

        if (revCommitIdProperty != null) {
            String revisionId = ObjectId.toString(revCommit.getId());
            getProject().setProperty(revCommitIdProperty, revisionId);
        }

        log(revCommit.getFullMessage());
    } catch (IOException ioe) {
        throw new GitBuildException(MESSAGE_COMMIT_FAILED, ioe);
    } catch (GitAPIException ex) {
        throw new GitBuildException(MESSAGE_COMMIT_FAILED, ex);
    }
}

From source file:com.stormcloud.ide.api.git.GitManager.java

License:Open Source License

@Override
public void commit(String repository, String message, String[] files, boolean all) throws GitManagerException {

    try {//from  w  w w  .j  a v  a2  s .  c  o  m

        Git git = Git.open(new File(repository));

        CommitCommand commit = git.commit();

        commit.setMessage(message);

        if (all) {

            commit.setAll(true);

        } else {

            for (String file : files) {

                commit.setOnly(file);
            }

        }

        RevCommit result = commit.call();

        // result....

    } catch (IOException e) {
        LOG.error(e);
        throw new GitManagerException(e);
    } catch (GitAPIException e) {
        LOG.error(e);
        throw new GitManagerException(e);
    }
}

From source file:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * @throws MergeFailure // ww  w  .j  a  v  a2s.  co  m
 * @throws AuthenticationException 
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#updateCommitAndPush(java.io.File, java.lang.String, java.lang.String, java.lang.String,
 * java.lang.String[])
 */
@Override
public Set<String> updateCommitAndPush(String commitMessage, String username, String password,
        MergeFailOption mergeFailOption, String... files)
        throws IllegalArgumentException, IOException, MergeFailure, AuthenticationException {
    try {
        log.info("Commit Files called {}", (files == null ? "-null-" : Arrays.toString(files)));
        Git git = getGit();

        if (git.status().call().getConflicting().size() > 0) {
            log.info("Previous merge failure not yet resolved");
            throw new MergeFailure(git.status().call().getConflicting(), new HashSet<>());
        }

        if (files == null) {
            files = git.status().call().getUncommittedChanges().toArray(new String[0]);
            log.info("Will commit the uncommitted files {}", Arrays.toString(files));
        }

        if (StringUtils.isEmptyOrNull(commitMessage) && files.length > 0) {
            throw new IllegalArgumentException("The commit message is required when files are specified");
        }

        if (files.length > 0) {
            CommitCommand commit = git.commit();
            for (String file : files) {
                commit.setOnly(file);
            }

            commit.setAuthor(username, "42");
            commit.setMessage(commitMessage);
            RevCommit rv = commit.call();
            log.debug("Local commit completed: " + rv.getFullMessage());
        }

        //need to merge origin/master into master now, prior to push
        Set<String> result = updateFromRemote(username, password, mergeFailOption);

        log.debug("Pushing");
        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                (password == null ? new char[] {} : password.toCharArray()));

        Iterable<PushResult> pr = git.push().setCredentialsProvider(cp).call();
        pr.forEach(new Consumer<PushResult>() {
            @Override
            public void accept(PushResult t) {
                log.debug("Push Result Messages: " + t.getMessages());
            }
        });

        log.info("commit and push complete.  Current status: " + statusToString(git.status().call()));
        return result;
    } catch (TransportException te) {
        if (te.getMessage().contains("Auth fail")) {
            log.info("Auth fail", te);
            throw new AuthenticationException("Auth fail");
        } else {
            log.error("Unexpected", te);
            throw new IOException("Internal error", te);
        }
    } catch (GitAPIException e) {
        log.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}

From source file:org.ajoberstar.gradle.git.tasks.GitCommit.java

License:Apache License

/**
 * Commits changes to the Git repository.
 *//*from w ww .ja v  a2  s. com*/
@TaskAction
public void commit() {
    final CommitCommand cmd = getGit().commit();
    cmd.setMessage(getMessage());
    cmd.setAll(getCommitAll());
    if (committer != null) {
        cmd.setCommitter(getCommitter());
    }
    if (author != null) {
        cmd.setAuthor(getAuthor());
    }

    if (!patternSet.getExcludes().isEmpty() || !patternSet.getIncludes().isEmpty()) {
        getSource().visit(new FileVisitor() {
            public void visitDir(FileVisitDetails arg0) {
                visitFile(arg0);
            }

            public void visitFile(FileVisitDetails arg0) {
                cmd.setOnly(arg0.getPath());
            }
        });
    }

    try {
        cmd.call();
    } catch (Exception e) {
        throw new GradleException("Problem committing changes.", e);
    }
}

From source file:org.commonjava.aprox.subsys.git.GitManager.java

License:Apache License

public GitManager deleteAndCommitPaths(final ChangeSummary summary, final Collection<String> paths)
        throws GitSubsystemException {
    try {/*from w w  w . j  a v  a  2s.com*/
        RmCommand rm = git.rm();
        CommitCommand commit = git.commit();

        for (final String path : paths) {
            rm = rm.addFilepattern(path);
            commit = commit.setOnly(path);
        }

        logger.info("Deleting:\n  " + join(paths, "\n  ") + "\n\nSummary: " + summary);

        rm.call();

        commit.setMessage(buildMessage(summary, paths)).setAuthor(summary.getUser(), email).call();
    } catch (final NoFilepatternException e) {
        throw new GitSubsystemException("Cannot remove from git: " + e.getMessage(), e);
    } catch (final GitAPIException e) {
        throw new GitSubsystemException("Cannot remove from git: " + e.getMessage(), e);
    }

    return this;
}

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 {/* www. j  a v  a 2 s  .com*/
    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.exist.git.xquery.Commit.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {//ww  w  .java  2s  .c o  m
        String localPath = args[0].getStringValue();
        if (!(localPath.endsWith("/")))
            localPath += File.separator;

        Git git = Git.open(new Resource(localPath), FS);

        CommitCommand command = git.commit().setMessage(args[1].getStringValue());
        //              .setAuthor(name, email)
        //              .setCommitter(name, email)

        if (args.length >= 3) {
            for (int i = 0; i < args[2].getItemCount(); i++) {
                command.setOnly(args[2].itemAt(i).getStringValue());
            }
        }
        //           command.setAll(true);
        command.call();

        return BooleanValue.TRUE;
    } catch (Throwable e) {
        Throwable cause = e.getCause();
        if (cause != null) {
            throw new XPathException(this, Module.EXGIT001, cause.getMessage());
        }

        throw new XPathException(this, Module.EXGIT001, e);
    }
}

From source file:org.flowerplatform.web.git.operation.CommitOperation.java

License:Open Source License

public boolean commit(String repositoryLocation, List<CommitResourceDto> files, String author, String committer,
        String message, boolean amending) {
    ProgressMonitor monitor = ProgressMonitor
            .create(GitPlugin.getInstance().getMessage("git.commit.monitor.title"), channel);

    try {// ww  w  .j av  a  2 s  .  c o  m
        Repository repo = GitPlugin.getInstance().getUtils().getRepository(new File(repositoryLocation));

        Collection<String> notTracked = new HashSet<String>();
        Collection<String> resources = new HashSet<String>();

        for (CommitResourceDto file : files) {
            resources.add(file.getPath());
            if (file.getState() == CommitResourceDto.UNTRACKED) {
                notTracked.add(file.getPath());
            }
        }

        monitor.beginTask(GitPlugin.getInstance().getMessage("git.commit.monitor.message"), 10);
        addUntracked(notTracked, repo);
        monitor.worked(1);

        CommitCommand commitCommand = new Git(repo).commit();
        commitCommand.setAmend(amending).setMessage(message);

        for (String path : resources) {
            commitCommand.setOnly(path);
        }

        Date commitDate = new Date();
        TimeZone timeZone = TimeZone.getDefault();

        PersonIdent enteredAuthor = RawParseUtils.parsePersonIdent(author);
        PersonIdent enteredCommitter = RawParseUtils.parsePersonIdent(committer);
        if (enteredAuthor == null) {
            channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                    CommonPlugin.getInstance().getMessage("error"), GitPlugin.getInstance()
                            .getMessage("git.commit.errorParsingPersonIdent", new Object[] { author }),
                    DisplaySimpleMessageClientCommand.ICON_ERROR));
            return false;
        }
        if (enteredCommitter == null) {
            channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                    CommonPlugin.getInstance().getMessage("error"), GitPlugin.getInstance()
                            .getMessage("git.commit.errorParsingPersonIdent", new Object[] { committer }),
                    DisplaySimpleMessageClientCommand.ICON_ERROR));
            return false;
        }

        PersonIdent authorIdent = new PersonIdent(enteredAuthor, commitDate, timeZone);
        PersonIdent committerIdent = new PersonIdent(enteredCommitter, commitDate, timeZone);

        if (amending) {
            RevCommit headCommit = GitPlugin.getInstance().getUtils().getHeadCommit(repo);
            if (headCommit != null) {
                PersonIdent headAuthor = headCommit.getAuthorIdent();
                authorIdent = new PersonIdent(enteredAuthor, headAuthor.getWhen(), headAuthor.getTimeZone());
            }
        }
        commitCommand.setAuthor(authorIdent);
        commitCommand.setCommitter(committerIdent);

        monitor.worked(1);
        commitCommand.call();
        if (monitor.isCanceled()) {
            return false;
        }
        monitor.worked(8);

        //         GitLightweightDecorator.refresh();
        //         
        //         updateDispatcher.dispatchContentUpdate(null, repo, GitTreeUpdateDispatcher.COMMIT, null);

        return true;
    } catch (Exception e) {
        logger.debug(GitPlugin.getInstance().getMessage("git.commit.error"), e);
        channel.appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    } finally {
        monitor.done();
    }
}

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

License:Open Source License

@Override
public void commit(ProjectVersion project, IProgressMonitor monitor) throws TeamProviderException {
    try {/*  w  w  w.j  a va2  s . c om*/
        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();
    }
}