use of org.eclipse.jgit.lib.RefUpdate.Result 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.lib.RefUpdate.Result in project che by eclipse.
the class JGitConnection method tagDelete.
@Override
public void tagDelete(String name) throws GitException {
try {
Ref tagRef = repository.findRef(name);
if (tagRef == null) {
throw new GitException("Tag " + name + " not found. ");
}
RefUpdate updateRef = repository.updateRef(tagRef.getName());
updateRef.setRefLogMessage("tag deleted", false);
updateRef.setForceUpdate(true);
Result deleteResult = updateRef.delete();
if (deleteResult != Result.FORCED && deleteResult != Result.FAST_FORWARD) {
throw new GitException(format(ERROR_TAG_DELETE, name, deleteResult));
}
} catch (IOException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
use of org.eclipse.jgit.lib.RefUpdate.Result in project gitblit by gitblit.
the class RefLogUtils method updateRefLog.
/**
* Updates the reflog with the received commands.
*
* @param user
* @param repository
* @param commands
* @return true, if the update was successful
*/
public static boolean updateRefLog(UserModel user, Repository repository, Collection<ReceiveCommand> commands) {
// only track branches and tags
List<ReceiveCommand> filteredCommands = new ArrayList<ReceiveCommand>();
for (ReceiveCommand cmd : commands) {
if (!cmd.getRefName().startsWith(Constants.R_HEADS) && !cmd.getRefName().startsWith(Constants.R_TAGS)) {
continue;
}
filteredCommands.add(cmd);
}
if (filteredCommands.isEmpty()) {
// nothing to log
return true;
}
RefModel reflogBranch = getRefLogBranch(repository);
if (reflogBranch == null) {
JGitUtils.createOrphanBranch(repository, GB_REFLOG, null);
}
boolean success = false;
String message = "push";
try {
ObjectId headId = repository.resolve(GB_REFLOG + "^{commit}");
ObjectInserter odi = repository.newObjectInserter();
try {
// Create the in-memory index of the reflog log entry
DirCache index = createIndex(repository, headId, commands);
ObjectId indexTreeId = index.writeTree(odi);
PersonIdent ident;
if (UserModel.ANONYMOUS.equals(user)) {
// anonymous push
ident = new PersonIdent(user.username + "/" + user.username, user.username);
} else {
// construct real pushing account
ident = new PersonIdent(MessageFormat.format("{0}/{1}", user.getDisplayName(), user.username), user.emailAddress == null ? user.username : user.emailAddress);
}
// Create a commit object
CommitBuilder commit = new CommitBuilder();
commit.setAuthor(ident);
commit.setCommitter(ident);
commit.setEncoding(Constants.ENCODING);
commit.setMessage(message);
commit.setParentId(headId);
commit.setTreeId(indexTreeId);
// Insert the commit into the repository
ObjectId commitId = odi.insert(commit);
odi.flush();
RevWalk revWalk = new RevWalk(repository);
try {
RevCommit revCommit = revWalk.parseCommit(commitId);
RefUpdate ru = repository.updateRef(GB_REFLOG);
ru.setNewObjectId(commitId);
ru.setExpectedOldObjectId(headId);
ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
Result rc = ru.forceUpdate();
switch(rc) {
case NEW:
case FORCED:
case FAST_FORWARD:
success = true;
break;
case REJECTED:
case LOCK_FAILURE:
throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
default:
throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, GB_REFLOG, commitId.toString(), rc));
}
} finally {
revWalk.close();
}
} finally {
odi.close();
}
} catch (Throwable t) {
error(t, repository, "Failed to commit reflog entry to {0}");
}
return success;
}
use of org.eclipse.jgit.lib.RefUpdate.Result in project gitblit by gitblit.
the class JGitUtils method createOrphanBranch.
/**
* Create an orphaned branch in a repository.
*
* @param repository
* @param branchName
* @param author
* if unspecified, Gitblit will be the author of this new branch
* @return true if successful
*/
public static boolean createOrphanBranch(Repository repository, String branchName, PersonIdent author) {
boolean success = false;
String message = "Created branch " + branchName;
if (author == null) {
author = new PersonIdent("Gitblit", "gitblit@localhost");
}
try {
ObjectInserter odi = repository.newObjectInserter();
try {
// Create a blob object to insert into a tree
ObjectId blobId = odi.insert(Constants.OBJ_BLOB, message.getBytes(Constants.CHARACTER_ENCODING));
// Create a tree object to reference from a commit
TreeFormatter tree = new TreeFormatter();
tree.append(".branch", FileMode.REGULAR_FILE, blobId);
ObjectId treeId = odi.insert(tree);
// Create a commit object
CommitBuilder commit = new CommitBuilder();
commit.setAuthor(author);
commit.setCommitter(author);
commit.setEncoding(Constants.CHARACTER_ENCODING);
commit.setMessage(message);
commit.setTreeId(treeId);
// Insert the commit into the repository
ObjectId commitId = odi.insert(commit);
odi.flush();
RevWalk revWalk = new RevWalk(repository);
try {
RevCommit revCommit = revWalk.parseCommit(commitId);
if (!branchName.startsWith("refs/")) {
branchName = "refs/heads/" + branchName;
}
RefUpdate ru = repository.updateRef(branchName);
ru.setNewObjectId(commitId);
ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
Result rc = ru.forceUpdate();
switch(rc) {
case NEW:
case FORCED:
case FAST_FORWARD:
success = true;
break;
default:
success = false;
}
} finally {
revWalk.close();
}
} finally {
odi.close();
}
} catch (Throwable t) {
error(t, repository, "Failed to create orphan branch {1} in repository {0}", branchName);
}
return success;
}
use of org.eclipse.jgit.lib.RefUpdate.Result in project gitblit by gitblit.
the class JGitUtils method setHEADtoRef.
/**
* Sets the symbolic ref HEAD to the specified target ref. The
* HEAD will be detached if the target ref is not a branch.
*
* @param repository
* @param targetRef
* @return true if successful
*/
public static boolean setHEADtoRef(Repository repository, String targetRef) {
try {
// detach HEAD if target ref is not a branch
boolean detach = !targetRef.startsWith(Constants.R_HEADS);
RefUpdate.Result result;
RefUpdate head = repository.updateRef(Constants.HEAD, detach);
if (detach) {
// Tag
RevCommit commit = getCommit(repository, targetRef);
head.setNewObjectId(commit.getId());
result = head.forceUpdate();
} else {
result = head.link(targetRef);
}
switch(result) {
case NEW:
case FORCED:
case NO_CHANGE:
case FAST_FORWARD:
return true;
default:
LOGGER.error(MessageFormat.format("{0} HEAD update to {1} returned result {2}", repository.getDirectory().getAbsolutePath(), targetRef, result));
}
} catch (Throwable t) {
error(t, repository, "{0} failed to set HEAD to {1}", targetRef);
}
return false;
}
Aggregations