use of org.eclipse.jgit.api.CommitCommand 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);
}
}
use of org.eclipse.jgit.api.CommitCommand in project indy by Commonjava.
the class GitManager method addAndCommitPaths.
public GitManager addAndCommitPaths(final ChangeSummary summary, final Collection<String> paths) throws GitSubsystemException {
lockAnd(me -> {
if (!verifyChangesExist(paths)) {
logger.info("No actual changes in:\n {}\n\nSkipping commit.", join(paths, "\n "));
return this;
}
try {
final AddCommand add = git.add();
final CommitCommand commit = git.commit();
for (final String filepath : paths) {
add.addFilepattern(filepath);
}
logger.info("Adding:\n " + join(paths, "\n ") + "\n\nSummary: " + summary);
add.call();
commit.setMessage(buildMessage(summary, paths)).setAuthor(summary.getUser(), email).call();
} catch (final NoFilepatternException e) {
throw new GitSubsystemException("Cannot add to git: " + e.getMessage(), e);
} catch (final GitAPIException e) {
throw new GitSubsystemException("Cannot add to git: " + e.getMessage(), e);
}
return me;
});
return this;
}
use of org.eclipse.jgit.api.CommitCommand in project archi-modelrepository-plugin by archi-contribs.
the class ArchiRepositoryTests method getFileContents_IsCorrect.
@Test
public void getFileContents_IsCorrect() throws Exception {
File localRepoFolder = new File(GitHelper.getTempTestsFolder(), "testRepo");
IArchiRepository repo = new ArchiRepository(localRepoFolder);
String contents = "Hello World!\nTesting.";
try (Repository repos = GitHelper.createNewRepository(localRepoFolder)) {
File file = new File(localRepoFolder, "test.txt");
try (FileWriter fw = new FileWriter(file)) {
fw.write(contents);
fw.flush();
}
assertTrue(file.exists());
// Add file to index
AddCommand addCommand = new AddCommand(repos);
// $NON-NLS-1$
addCommand.addFilepattern(".");
addCommand.setUpdate(false);
addCommand.call();
// Commit file
CommitCommand commitCommand = Git.wrap(repos).commit();
commitCommand.setAuthor("Test", "Test");
commitCommand.setMessage("Message");
commitCommand.call();
assertEquals(contents, repo.getFileContents("test.txt", IGraficoConstants.HEAD));
}
}
use of org.eclipse.jgit.api.CommitCommand in project maven-scm by apache.
the class JGitCheckInCommand method executeCheckInCommand.
/**
* {@inheritDoc}
*/
protected CheckInScmResult executeCheckInCommand(ScmProviderRepository repo, ScmFileSet fileSet, String message, ScmVersion version) throws ScmException {
Git git = null;
try {
File basedir = fileSet.getBasedir();
git = JGitUtils.openRepo(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);
}
}
use of org.eclipse.jgit.api.CommitCommand in project egit by eclipse.
the class CommitOperation method commitAll.
// TODO: can the commit message be change by the user in case of a merge commit?
private void commitAll() throws TeamException {
try (Git git = new Git(repo)) {
CommitCommand commitCommand = git.commit();
setAuthorAndCommitter(commitCommand);
commit = commitCommand.setAll(true).setMessage(message).setInsertChangeId(createChangeId).call();
} catch (JGitInternalException e) {
throw new TeamException(CoreText.MergeOperation_InternalError, e);
} catch (GitAPIException e) {
throw new TeamException(e.getLocalizedMessage(), e);
}
}
Aggregations