use of org.eclipse.jgit.api.errors.GitAPIException in project che by eclipse.
the class JGitConnection method branchList.
@Override
public List<Branch> branchList(BranchListMode listMode) throws GitException {
ListBranchCommand listBranchCommand = getGit().branchList();
if (LIST_ALL == listMode || listMode == null) {
listBranchCommand.setListMode(ListMode.ALL);
} else if (LIST_REMOTE == listMode) {
listBranchCommand.setListMode(ListMode.REMOTE);
}
List<Ref> refs;
String currentRef;
try {
refs = listBranchCommand.call();
String headBranch = getRepository().getBranch();
Optional<Ref> currentTag = getGit().tagList().call().stream().filter(tag -> tag.getObjectId().getName().equals(headBranch)).findFirst();
if (currentTag.isPresent()) {
currentRef = currentTag.get().getName();
} else {
currentRef = "refs/heads/" + headBranch;
}
} catch (GitAPIException | IOException exception) {
throw new GitException(exception.getMessage(), exception);
}
List<Branch> branches = new ArrayList<>();
for (Ref ref : refs) {
String refName = ref.getName();
boolean isCommitOrTag = Constants.HEAD.equals(refName);
String branchName = isCommitOrTag ? currentRef : refName;
String branchDisplayName;
if (isCommitOrTag) {
branchDisplayName = "(detached from " + Repository.shortenRefName(currentRef) + ")";
} else {
branchDisplayName = Repository.shortenRefName(refName);
}
Branch branch = newDto(Branch.class).withName(branchName).withActive(isCommitOrTag || refName.equals(currentRef)).withDisplayName(branchDisplayName).withRemote(refName.startsWith("refs/remotes"));
branches.add(branch);
}
return branches;
}
use of org.eclipse.jgit.api.errors.GitAPIException 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.errors.GitAPIException in project che by eclipse.
the class JGitConnection method checkout.
@Override
public void checkout(CheckoutParams params) throws GitException {
CheckoutCommand checkoutCommand = getGit().checkout();
String startPoint = params.getStartPoint();
String name = params.getName();
String trackBranch = params.getTrackBranch();
// checkout files?
List<String> files = params.getFiles();
boolean shouldCheckoutToFile = name != null && new File(getWorkingDir(), name).exists();
if (shouldCheckoutToFile || !files.isEmpty()) {
if (shouldCheckoutToFile) {
checkoutCommand.addPath(params.getName());
} else {
files.forEach(checkoutCommand::addPath);
}
} else {
// checkout branch
if (startPoint != null && trackBranch != null) {
throw new GitException("Start point and track branch can not be used together.");
}
if (params.isCreateNew() && name == null) {
throw new GitException("Branch name must be set when createNew equals to true.");
}
if (startPoint != null) {
checkoutCommand.setStartPoint(startPoint);
}
if (params.isCreateNew()) {
checkoutCommand.setCreateBranch(true);
checkoutCommand.setName(name);
} else if (name != null) {
checkoutCommand.setName(name);
List<String> localBranches = branchList(LIST_LOCAL).stream().map(Branch::getDisplayName).collect(Collectors.toList());
if (!localBranches.contains(name)) {
Optional<Branch> remoteBranch = branchList(LIST_REMOTE).stream().filter(branch -> branch.getName().contains(name)).findFirst();
if (remoteBranch.isPresent()) {
checkoutCommand.setCreateBranch(true);
checkoutCommand.setStartPoint(remoteBranch.get().getName());
}
}
}
if (trackBranch != null) {
if (name == null) {
checkoutCommand.setName(cleanRemoteName(trackBranch));
}
checkoutCommand.setCreateBranch(true);
checkoutCommand.setStartPoint(trackBranch);
}
checkoutCommand.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
}
try {
checkoutCommand.call();
} catch (CheckoutConflictException exception) {
throw new GitConflictException(exception.getMessage(), exception.getConflictingPaths());
} catch (RefAlreadyExistsException exception) {
throw new GitRefAlreadyExistsException(exception.getMessage());
} catch (RefNotFoundException exception) {
throw new GitRefNotFoundException(exception.getMessage());
} catch (InvalidRefNameException exception) {
throw new GitInvalidRefNameException(exception.getMessage());
} catch (GitAPIException exception) {
if (exception.getMessage().endsWith("already exists")) {
throw new GitException(format(ERROR_CHECKOUT_BRANCH_NAME_EXISTS, name != null ? name : cleanRemoteName(trackBranch)));
}
throw new GitException(exception.getMessage(), exception);
}
}
use of org.eclipse.jgit.api.errors.GitAPIException in project che by eclipse.
the class JGitConnection method rebase.
@Override
public RebaseResponse rebase(String operation, String branch) throws GitException {
RebaseResult result;
RebaseStatus status;
List<String> failed;
List<String> conflicts;
try {
RebaseCommand rebaseCommand = getGit().rebase();
setRebaseOperation(rebaseCommand, operation);
if (branch != null && !branch.isEmpty()) {
rebaseCommand.setUpstream(branch);
}
result = rebaseCommand.call();
} catch (GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
switch(result.getStatus()) {
case ABORTED:
status = RebaseStatus.ABORTED;
break;
case CONFLICTS:
status = RebaseStatus.CONFLICTING;
break;
case UP_TO_DATE:
status = RebaseStatus.ALREADY_UP_TO_DATE;
break;
case FAST_FORWARD:
status = RebaseStatus.FAST_FORWARD;
break;
case NOTHING_TO_COMMIT:
status = RebaseStatus.NOTHING_TO_COMMIT;
break;
case OK:
status = RebaseStatus.OK;
break;
case STOPPED:
status = RebaseStatus.STOPPED;
break;
case UNCOMMITTED_CHANGES:
status = RebaseStatus.UNCOMMITTED_CHANGES;
break;
case EDIT:
status = RebaseStatus.EDITED;
break;
case INTERACTIVE_PREPARED:
status = RebaseStatus.INTERACTIVE_PREPARED;
break;
case STASH_APPLY_CONFLICTS:
status = RebaseStatus.STASH_APPLY_CONFLICTS;
break;
default:
status = RebaseStatus.FAILED;
}
conflicts = result.getConflicts() != null ? result.getConflicts() : Collections.emptyList();
failed = result.getFailingPaths() != null ? new ArrayList<>(result.getFailingPaths().keySet()) : Collections.emptyList();
return newDto(RebaseResponse.class).withStatus(status).withConflicts(conflicts).withFailed(failed);
}
use of org.eclipse.jgit.api.errors.GitAPIException in project che by eclipse.
the class JGitConnection method pull.
@Override
public PullResponse pull(PullParams params) throws GitException, UnauthorizedException {
String remoteName = params.getRemote();
String remoteUri;
try {
if (repository.getRepositoryState().equals(RepositoryState.MERGING)) {
throw new GitException(ERROR_PULL_MERGING);
}
String fullBranch = repository.getFullBranch();
if (!fullBranch.startsWith(Constants.R_HEADS)) {
throw new DetachedHeadException(ERROR_PULL_HEAD_DETACHED);
}
String branch = fullBranch.substring(Constants.R_HEADS.length());
StoredConfig config = repository.getConfig();
if (remoteName == null) {
remoteName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_REMOTE);
if (remoteName == null) {
remoteName = Constants.DEFAULT_REMOTE_NAME;
}
}
remoteUri = config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName, ConfigConstants.CONFIG_KEY_URL);
String remoteBranch;
RefSpec fetchRefSpecs = null;
String refSpec = params.getRefSpec();
if (refSpec != null) {
fetchRefSpecs = //
(refSpec.indexOf(':') < 0) ? //
new RefSpec(Constants.R_HEADS + refSpec + ":" + fullBranch) : new RefSpec(refSpec);
remoteBranch = fetchRefSpecs.getSource();
} else {
remoteBranch = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch, ConfigConstants.CONFIG_KEY_MERGE);
}
if (remoteBranch == null) {
remoteBranch = fullBranch;
}
FetchCommand fetchCommand = getGit().fetch();
fetchCommand.setRemote(remoteName);
if (fetchRefSpecs != null) {
fetchCommand.setRefSpecs(fetchRefSpecs);
}
int timeout = params.getTimeout();
if (timeout > 0) {
fetchCommand.setTimeout(timeout);
}
FetchResult fetchResult = (FetchResult) executeRemoteCommand(remoteUri, fetchCommand, params.getUsername(), params.getPassword());
Ref remoteBranchRef = fetchResult.getAdvertisedRef(remoteBranch);
if (remoteBranchRef == null) {
remoteBranchRef = fetchResult.getAdvertisedRef(Constants.R_HEADS + remoteBranch);
}
if (remoteBranchRef == null) {
throw new GitException(format(ERROR_PULL_REF_MISSING, remoteBranch));
}
org.eclipse.jgit.api.MergeResult mergeResult = getGit().merge().include(remoteBranchRef).call();
if (mergeResult.getMergeStatus().equals(org.eclipse.jgit.api.MergeResult.MergeStatus.ALREADY_UP_TO_DATE)) {
return newDto(PullResponse.class).withCommandOutput("Already up-to-date");
}
if (mergeResult.getConflicts() != null) {
StringBuilder message = new StringBuilder(ERROR_PULL_MERGE_CONFLICT_IN_FILES);
message.append(lineSeparator());
Map<String, int[][]> allConflicts = mergeResult.getConflicts();
for (String path : allConflicts.keySet()) {
message.append(path).append(lineSeparator());
}
message.append(ERROR_PULL_AUTO_MERGE_FAILED);
throw new GitException(message.toString());
}
} catch (CheckoutConflictException exception) {
StringBuilder message = new StringBuilder(ERROR_CHECKOUT_CONFLICT);
message.append(lineSeparator());
for (String path : exception.getConflictingPaths()) {
message.append(path).append(lineSeparator());
}
message.append(ERROR_PULL_COMMIT_BEFORE_MERGE);
throw new GitException(message.toString(), exception);
} catch (IOException | GitAPIException exception) {
String errorMessage;
if (exception.getMessage().equals("Invalid remote: " + remoteName)) {
errorMessage = ERROR_NO_REMOTE_REPOSITORY;
} else {
errorMessage = generateExceptionMessage(exception);
}
throw new GitException(errorMessage, exception);
}
return newDto(PullResponse.class).withCommandOutput("Successfully pulled from " + remoteUri);
}
Aggregations