List of usage examples for org.eclipse.jgit.lib RepositoryState CHERRY_PICKING_RESOLVED
RepositoryState CHERRY_PICKING_RESOLVED
To view the source code for org.eclipse.jgit.lib RepositoryState CHERRY_PICKING_RESOLVED.
Click Source Link
From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java
License:Open Source License
@Override public void saveReview(URI uri, ModelReview modelReview, User currentReviewer, IProgressMonitor monitor) throws InvalidReviewRepositoryException, InvalidReviewException, RepositoryIOException { monitor.beginTask("Connecting to repository", IProgressMonitor.UNKNOWN); String repoFileURI = COMMENTS_FILE_URI; try {/*from ww w.j a va 2 s . c om*/ Git git = Git.open(new File(uri)); Repository repository = git.getRepository(); ObjectInserter objectInserter = repository.newObjectInserter(); String commentRefName = getCommentRefName(modelReview); Ref commentRef = repository.exactRef(commentRefName); DirCache index = DirCache.newInCore(); DirCacheBuilder dirCacheBuilder = index.builder(); monitor.beginTask("Preparing commit...", IProgressMonitor.UNKNOWN); if (commentRef != null) { /* * The ref already exists so we have to copy the previous * RevTree to keep all already attached files */ RevWalk revWalk = new RevWalk(repository); RevCommit prevCommit = revWalk.parseCommit(commentRef.getObjectId()); RevTree tree = prevCommit.getTree(); List<String> ignoredFiles = new ArrayList<>(); /* * add file path of the new file to the ignored file paths, as * we don't want any already existing old file in our new tree */ ignoredFiles.add(repoFileURI); buildDirCacheFromTree(tree, repository, dirCacheBuilder, ignoredFiles); revWalk.close(); } monitor.beginTask("Writing comments file...", IProgressMonitor.UNKNOWN); ResourceSet resourceSet = new ResourceSetImpl(); Resource resource = resourceSet.createResource(org.eclipse.emf.common.util.URI.createURI(repoFileURI)); addCommentsToResource(modelReview, resource); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); resource.save(outputStream, null); // insert file as object byte[] content = outputStream.toByteArray(); long length = content.length; InputStream inputStream = new ByteArrayInputStream(content); ObjectId objectId = objectInserter.insert(Constants.OBJ_BLOB, length, inputStream); inputStream.close(); // create tree entry DirCacheEntry entry = new DirCacheEntry(repoFileURI); entry.setFileMode(FileMode.REGULAR_FILE); entry.setLastModified(System.currentTimeMillis()); entry.setLength(length); entry.setObjectId(objectId); dirCacheBuilder.add(entry); dirCacheBuilder.finish(); // write new tree in database ObjectId indexTreeId = index.writeTree(objectInserter); monitor.beginTask("Commiting comments...", IProgressMonitor.UNKNOWN); // create commit CommitBuilder commitBuilder = new CommitBuilder(); PersonIdent personIdent = new PersonIdent("Mervin", "mervin@mervin.modelreview"); commitBuilder.setCommitter(personIdent); commitBuilder.setAuthor(personIdent); commitBuilder.setMessage( MessageFormat.format("Updated comments by user \"{0}\"", currentReviewer.getName())); if (commentRef != null) { commitBuilder.setParentId(commentRef.getObjectId()); } commitBuilder.setTreeId(indexTreeId); // commit ObjectId commitId = objectInserter.insert(commitBuilder); objectInserter.flush(); RefUpdate refUpdate = repository.updateRef(commentRefName); refUpdate.setNewObjectId(commitId); if (commentRef != null) refUpdate.setExpectedOldObjectId(commentRef.getObjectId()); else refUpdate.setExpectedOldObjectId(ObjectId.zeroId()); /* * TODO the result handling below is copied from the CommitCommand * class, I don't know if this is really necessary in our case */ Result result = refUpdate.forceUpdate(); switch (result) { case NEW: case FORCED: case FAST_FORWARD: { if (repository.getRepositoryState() == RepositoryState.MERGING_RESOLVED) { /* * Commit was successful. Now delete the files used for * merge commits */ repository.writeMergeCommitMsg(null); repository.writeMergeHeads(null); } else if (repository.getRepositoryState() == RepositoryState.CHERRY_PICKING_RESOLVED) { repository.writeMergeCommitMsg(null); repository.writeCherryPickHead(null); } else if (repository.getRepositoryState() == RepositoryState.REVERTING_RESOLVED) { repository.writeMergeCommitMsg(null); repository.writeRevertHead(null); } break; } case REJECTED: case LOCK_FAILURE: throw new RepositoryIOException("Error occured during writing to the git repository", new ConcurrentRefUpdateException("Could not lock ref " + refUpdate.getRef().getName(), refUpdate.getRef(), result)); default: throw new RepositoryIOException("Error occured during writing to the git repository", new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, refUpdate.getRef().getName(), commitId.toString(), result))); } } catch (IOException e) { throw new InvalidReviewRepositoryException("Could not open local git repository", e); } finally { monitor.done(); } }
From source file:com.mangosolutions.rcloud.rawgist.repository.git.BareCommitCommand.java
/** * Executes the {@code commit} command with all the options and parameters * collected by the setter methods of this class. Each instance of this * class should only be used for one invocation of the command (means: one * call to {@link #call()})//from w ww .j a v a2s. c om * * @return a {@link RevCommit} object representing the successful commit. * @throws NoHeadException * when called on a git repo without a HEAD reference * @throws NoMessageException * when called without specifying a commit message * @throws UnmergedPathsException * when the current index contained unmerged paths (conflicts) * @throws ConcurrentRefUpdateException * when HEAD or branch ref is updated concurrently by someone * else * @throws WrongRepositoryStateException * when repository is not in the right state for committing * @throws AbortedByHookException * if there are either pre-commit or commit-msg hooks present in * the repository and one of them rejects the commit. */ public RevCommit call() throws GitAPIException, NoHeadException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException, AbortedByHookException { checkCallable(); Collections.sort(only); try (RevWalk rw = new RevWalk(repo)) { RepositoryState state = repo.getRepositoryState(); if (!noVerify) { Hooks.preCommit(repo, hookOutRedirect).call(); } processOptions(state, rw); if (all && !repo.isBare()) { try (Git git = new Git(repo)) { git.add().addFilepattern(".") //$NON-NLS-1$ .setUpdate(true).call(); } catch (NoFilepatternException e) { // should really not happen throw new JGitInternalException(e.getMessage(), e); } } Ref head = repo.findRef(Constants.HEAD); if (head == null) { throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported); } // determine the current HEAD and the commit it is referring to ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$ if (headId == null && amend) throw new WrongRepositoryStateException(JGitText.get().commitAmendOnInitialNotPossible); if (headId != null) { if (amend) { RevCommit previousCommit = rw.parseCommit(headId); for (RevCommit p : previousCommit.getParents()) parents.add(p.getId()); if (author == null) author = previousCommit.getAuthorIdent(); } else { parents.add(0, headId); } } if (!noVerify) { message = Hooks.commitMsg(repo, hookOutRedirect).setCommitMessage(message).call(); } // lock the index // DirCache index = repo.lockDirCache(); index.lock(); try (ObjectInserter odi = repo.newObjectInserter()) { if (!only.isEmpty()) index = createTemporaryIndex(headId, index, rw); // Write the index as tree to the object database. This may // fail for example when the index contains unmerged paths // (unresolved conflicts) ObjectId indexTreeId = index.writeTree(odi); if (insertChangeId) insertChangeId(indexTreeId); // Check for empty commits if (headId != null && !allowEmpty.booleanValue()) { RevCommit headCommit = rw.parseCommit(headId); headCommit.getTree(); if (indexTreeId.equals(headCommit.getTree())) { return null; } } // Create a Commit object, populate it and write it CommitBuilder commit = new CommitBuilder(); commit.setCommitter(committer); commit.setAuthor(author); commit.setMessage(message); commit.setParentIds(parents); commit.setTreeId(indexTreeId); ObjectId commitId = odi.insert(commit); odi.flush(); RevCommit revCommit = rw.parseCommit(commitId); RefUpdate ru = repo.updateRef(Constants.HEAD); ru.setNewObjectId(commitId); if (reflogComment != null) { ru.setRefLogMessage(reflogComment, false); } else { String prefix = amend ? "commit (amend): " //$NON-NLS-1$ : parents.size() == 0 ? "commit (initial): " //$NON-NLS-1$ : "commit: "; //$NON-NLS-1$ ru.setRefLogMessage(prefix + revCommit.getShortMessage(), false); } if (headId != null) { ru.setExpectedOldObjectId(headId); } else { ru.setExpectedOldObjectId(ObjectId.zeroId()); } Result rc = ru.forceUpdate(); switch (rc) { case NEW: case FORCED: case FAST_FORWARD: { setCallable(false); if (state == RepositoryState.MERGING_RESOLVED || isMergeDuringRebase(state)) { // Commit was successful. Now delete the files // used for merge commits repo.writeMergeCommitMsg(null); repo.writeMergeHeads(null); } else if (state == RepositoryState.CHERRY_PICKING_RESOLVED) { repo.writeMergeCommitMsg(null); repo.writeCherryPickHead(null); } else if (state == RepositoryState.REVERTING_RESOLVED) { repo.writeMergeCommitMsg(null); repo.writeRevertHead(null); } return revCommit; } case REJECTED: case LOCK_FAILURE: throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc); default: throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, Constants.HEAD, commitId.toString(), rc)); } } finally { index.unlock(); } } catch (UnmergedPathException e) { throw new UnmergedPathsException(e); } catch (IOException e) { throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e); } }
From source file:org.eclipse.egit.ui.internal.commit.CommitHelper.java
License:Open Source License
private void calculateCommitInfo() { Repository mergeRepository = null;/*from w w w . ja va 2 s. c o m*/ isMergedResolved = false; isCherryPickResolved = false; RepositoryState state = repository.getRepositoryState(); canCommit = state.canCommit(); if (!canCommit) { cannotCommitMessage = NLS.bind(UIText.CommitAction_repositoryState, state.getDescription()); return; } if (state.equals(RepositoryState.MERGING_RESOLVED)) { isMergedResolved = true; mergeRepository = repository; } else if (state.equals(RepositoryState.CHERRY_PICKING_RESOLVED)) { isCherryPickResolved = true; mergeRepository = repository; } previousCommit = getHeadCommit(repository); final UserConfig config = repository.getConfig().get(UserConfig.KEY); author = config.getAuthorName(); final String authorEmail = config.getAuthorEmail(); author = author + " <" + authorEmail + ">"; //$NON-NLS-1$ //$NON-NLS-2$ committer = config.getCommitterName(); final String committerEmail = config.getCommitterEmail(); committer = committer + " <" + committerEmail + ">"; //$NON-NLS-1$ //$NON-NLS-2$ if (isMergedResolved || isCherryPickResolved) { commitMessage = getMergeResolveMessage(mergeRepository); } if (isCherryPickResolved) { author = getCherryPickOriginalAuthor(mergeRepository); } }
From source file:org.flowerplatform.web.git.operation.CommitOperation.java
License:Open Source License
public CommitPageDto getPageDto() { try {//w ww . j av a 2 s.c o m repository = getRepository(selection); if (repository == null) { channel.appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), GitPlugin.getInstance().getMessage("git.commit.errorDifferentRepositories"), DisplaySimpleMessageClientCommand.ICON_ERROR)); return null; } RepositoryState state = repository.getRepositoryState(); if (!state.canCommit()) { channel.appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), GitPlugin.getInstance().getMessage("git.commit.repositoryState", new Object[] { state.getDescription() }), DisplaySimpleMessageClientCommand.ICON_ERROR)); return null; } boolean isMergedResolved = false; boolean isCherryPickResolved = false; if (state.equals(RepositoryState.MERGING_RESOLVED)) { isMergedResolved = true; } else if (state.equals(RepositoryState.CHERRY_PICKING_RESOLVED)) { isCherryPickResolved = true; } User user = (User) CommunicationPlugin.tlCurrentPrincipal.get().getUser(); String committer = user.getName() + " <" + user.getEmail() + ">"; String author = user.getName() + " <" + user.getEmail() + ">"; if (isCherryPickResolved) { author = getCherryPickOriginalAuthor(repository); } if (author == null) { author = user.getName() + " <" + user.getEmail() + ">"; } String message = null; if (isMergedResolved || isCherryPickResolved) { message = getMergeResolveMessage(repository); } org.eclipse.jgit.api.Status repoStatus = new Git(repository).status().call(); Set<String> files = new HashSet<String>(); includeList(repoStatus.getAdded(), files); includeList(repoStatus.getChanged(), files); includeList(repoStatus.getRemoved(), files); includeList(repoStatus.getMissing(), files); includeList(repoStatus.getModified(), files); includeList(repoStatus.getUntracked(), files); List<CommitResourceDto> commitResources = new ArrayList<CommitResourceDto>(); for (String path : files) { CommitResourceDto commitDto = new CommitResourceDto(); commitDto.setLabel(path); commitDto.setPath(path); commitDto.setImage("images/file.gif"); if (repoStatus.getUntracked().contains(path)) { commitDto.setState(CommitResourceDto.UNTRACKED); } commitResources.add(commitDto); } CommitPageDto dto = new CommitPageDto(); dto.setCommitResources(commitResources); dto.setAuthor(author); dto.setCommitter(committer); dto.setMessage(message); dto.setRepository(repository.getDirectory().getAbsolutePath()); return dto; } catch (Exception e) { logger.debug(GitPlugin.getInstance().getMessage("git.commit.error"), e); channel.appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), GitPlugin.getInstance().getMessage("git.commit.error"), e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR)); return null; } }
From source file:org.jboss.tools.openshift.express.internal.ui.server.CommitDialog.java
License:Open Source License
private Composite createMessageAndPersonArea(Composite container) { Composite messageAndPersonArea = toolkit.createComposite(container); GridDataFactory.fillDefaults().grab(true, true).applyTo(messageAndPersonArea); GridLayoutFactory.swtDefaults().margins(0, 0).spacing(0, 0).applyTo(messageAndPersonArea); Section messageSection = toolkit.createSection(messageAndPersonArea, ExpandableComposite.TITLE_BAR | ExpandableComposite.CLIENT_INDENT); messageSection.setText(UIText.CommitDialog_CommitMessage); Composite messageArea = toolkit.createComposite(messageSection); GridLayoutFactory.fillDefaults().spacing(0, 0).extendedMargins(2, 2, 2, 2).applyTo(messageArea); toolkit.paintBordersFor(messageArea); GridDataFactory.fillDefaults().grab(true, true).applyTo(messageSection); GridLayoutFactory.swtDefaults().applyTo(messageSection); Composite headerArea = new Composite(messageSection, SWT.NONE); GridLayoutFactory.fillDefaults().spacing(0, 0).numColumns(2).applyTo(headerArea); ToolBar messageToolbar = new ToolBar(headerArea, SWT.FLAT | SWT.HORIZONTAL); GridDataFactory.fillDefaults().align(SWT.END, SWT.FILL).grab(true, false).applyTo(messageToolbar); addMessageDropDown(headerArea);/* w w w . j av a 2 s . co m*/ messageSection.setTextClient(headerArea); final CommitProposalProcessor commitProposalProcessor = new CommitProposalProcessor() { @Override protected Collection<String> computeFileNameProposals() { return getFileList(); } @Override protected Collection<String> computeMessageProposals() { return CommitMessageHistory.getCommitHistory(); } }; commitText = new CommitMessageArea(messageArea, commitMessage, SWT.NONE) { @Override protected CommitProposalProcessor getCommitProposalProcessor() { return commitProposalProcessor; } }; commitText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); messageSection.setClient(messageArea); Point size = commitText.getTextWidget().getSize(); int minHeight = commitText.getTextWidget().getLineHeight() * 3; commitText.setLayoutData(GridDataFactory.fillDefaults().grab(true, true).hint(size) .minSize(size.x, minHeight).align(SWT.FILL, SWT.FILL).create()); UIUtils.addBulbDecorator(commitText.getTextWidget(), UIText.CommitDialog_ContentAssist); Composite personArea = toolkit.createComposite(messageAndPersonArea); toolkit.paintBordersFor(personArea); GridLayoutFactory.swtDefaults().numColumns(2).applyTo(personArea); GridDataFactory.fillDefaults().grab(true, false).applyTo(personArea); toolkit.createLabel(personArea, UIText.CommitDialog_Author) .setForeground(toolkit.getColors().getColor(IFormColors.TB_TOGGLE)); authorText = toolkit.createText(personArea, null); authorText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); authorText.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create()); if (repository != null && repository.getRepositoryState().equals(RepositoryState.CHERRY_PICKING_RESOLVED)) authorText.setEnabled(false); toolkit.createLabel(personArea, UIText.CommitDialog_Committer) .setForeground(toolkit.getColors().getColor(IFormColors.TB_TOGGLE)); committerText = toolkit.createText(personArea, null); committerText.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create()); if (committer != null) committerText.setText(committer); amendingItem = new ToolItem(messageToolbar, SWT.CHECK); amendingItem.setSelection(amending); if (amending) amendingItem.setEnabled(false); // if already set, don't allow any // changes else if (!amendAllowed) amendingItem.setEnabled(false); amendingItem.setToolTipText(UIText.CommitDialog_AmendPreviousCommit); Image amendImage = UIIcons.AMEND_COMMIT.createImage(); UIUtils.hookDisposal(amendingItem, amendImage); amendingItem.setImage(amendImage); signedOffItem = new ToolItem(messageToolbar, SWT.CHECK); signedOffItem.setToolTipText(UIText.CommitDialog_AddSOB); Image signedOffImage = UIIcons.SIGNED_OFF.createImage(); UIUtils.hookDisposal(signedOffItem, signedOffImage); signedOffItem.setImage(signedOffImage); changeIdItem = new ToolItem(messageToolbar, SWT.CHECK); Image changeIdImage = UIIcons.GERRIT.createImage(); UIUtils.hookDisposal(changeIdItem, changeIdImage); changeIdItem.setImage(changeIdImage); changeIdItem.setToolTipText(UIText.CommitDialog_AddChangeIdLabel); final ICommitMessageComponentNotifications listener = new ICommitMessageComponentNotifications() { @Override public void updateSignedOffToggleSelection(boolean selection) { signedOffItem.setSelection(selection); } @Override public void updateChangeIdToggleSelection(boolean selection) { changeIdItem.setSelection(selection); } @Override public void statusUpdated() { updateMessage(); } }; commitMessageComponent = new CommitMessageComponent(repository, listener); commitMessageComponent.enableListeners(false); commitMessageComponent.setDefaults(); commitMessageComponent.attachControls(commitText, authorText, committerText); commitMessageComponent.setCommitMessage(commitMessage); commitMessageComponent.setAuthor(author); commitMessageComponent.setCommitter(committer); commitMessageComponent.setAmending(amending); commitMessageComponent.setFilesToCommit(getFileList()); amendingItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { commitMessageComponent.setAmendingButtonSelection(amendingItem.getSelection()); } }); changeIdItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { commitMessageComponent.setChangeIdButtonSelection(changeIdItem.getSelection()); } }); signedOffItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { commitMessageComponent.setSignedOffButtonSelection(signedOffItem.getSelection()); } }); commitMessageComponent.updateUI(); commitMessageComponent.enableListeners(true); return messageAndPersonArea; }