List of usage examples for org.eclipse.jgit.util ChangeIdUtil computeChangeId
public static ObjectId computeChangeId(final ObjectId treeId, final ObjectId firstParentId, final PersonIdent author, final PersonIdent committer, final String message)
From source file:com.google.gerrit.acceptance.git.GitUtil.java
License:Apache License
private static ObjectId computeChangeId(Git git, PersonIdent i, String msg) throws IOException { RevWalk rw = new RevWalk(git.getRepository()); try {/*from w w w . j a va 2 s.c o m*/ Ref head = git.getRepository().getRef(Constants.HEAD); if (head.getObjectId() != null) { RevCommit parent = rw.lookupCommit(head.getObjectId()); return ChangeIdUtil.computeChangeId(parent.getTree(), parent.getId(), i, i, msg); } else { return ChangeIdUtil.computeChangeId(null, null, i, i, msg); } } finally { rw.release(); } }
From source file:com.google.gerrit.acceptance.git.ssh.GitUtil.java
License:Apache License
private static ObjectId computeChangeId(Git git, PersonIdent i, String msg) throws IOException { RevWalk rw = new RevWalk(git.getRepository()); try {//from w w w. ja v a 2 s . co m RevCommit parent = rw.lookupCommit(git.getRepository().getRef(Constants.HEAD).getObjectId()); return ChangeIdUtil.computeChangeId(parent.getTree(), parent.getId(), i, i, msg); } finally { rw.release(); } }
From source file:com.google.gerrit.server.change.CherryPickChange.java
License:Apache License
public Change.Id cherryPick(Change change, PatchSet patch, final String message, final String ref, final RefControl refControl) throws NoSuchChangeException, OrmException, MissingObjectException, IncorrectObjectTypeException, IOException, InvalidChangeOperationException, MergeException { if (Strings.isNullOrEmpty(ref)) { throw new InvalidChangeOperationException("Cherry Pick: Destination branch cannot be null or empty"); }//from w ww. j ava 2 s. c om Project.NameKey project = change.getProject(); String destinationBranch = RefNames.shortName(ref); IdentifiedUser identifiedUser = (IdentifiedUser) currentUser.get(); try (Repository git = gitManager.openRepository(project); CodeReviewRevWalk revWalk = CodeReviewCommit.newRevWalk(git)) { Ref destRef = git.getRefDatabase().exactRef(ref); if (destRef == null) { throw new InvalidChangeOperationException( String.format("Branch %s does not exist.", destinationBranch)); } CodeReviewCommit mergeTip = revWalk.parseCommit(destRef.getObjectId()); CodeReviewCommit commitToCherryPick = revWalk .parseCommit(ObjectId.fromString(patch.getRevision().get())); PersonIdent committerIdent = identifiedUser.newCommitterIdent(TimeUtil.nowTs(), serverTimeZone); final ObjectId computedChangeId = ChangeIdUtil.computeChangeId(commitToCherryPick.getTree(), mergeTip, commitToCherryPick.getAuthorIdent(), committerIdent, message); String commitMessage = ChangeIdUtil.insertId(message, computedChangeId).trim() + '\n'; CodeReviewCommit cherryPickCommit; try (ObjectInserter oi = git.newObjectInserter()) { ProjectState projectState = refControl.getProjectControl().getProjectState(); cherryPickCommit = mergeUtilFactory.create(projectState).createCherryPickFromCommit(git, oi, mergeTip, commitToCherryPick, committerIdent, commitMessage, revWalk); } catch (MergeIdenticalTreeException | MergeConflictException e) { throw new MergeException("Cherry pick failed: " + e.getMessage()); } Change.Key changeKey; final List<String> idList = cherryPickCommit.getFooterLines(FooterConstants.CHANGE_ID); if (!idList.isEmpty()) { final String idStr = idList.get(idList.size() - 1).trim(); changeKey = new Change.Key(idStr); } else { changeKey = new Change.Key("I" + computedChangeId.name()); } Branch.NameKey newDest = new Branch.NameKey(change.getProject(), destRef.getName()); List<ChangeData> destChanges = queryProvider.get().setLimit(2).byBranchKey(newDest, changeKey); if (destChanges.size() > 1) { throw new InvalidChangeOperationException("Several changes with key " + changeKey + " reside on the same branch. " + "Cannot create a new patch set."); } else if (destChanges.size() == 1) { // The change key exists on the destination branch. The cherry pick // will be added as a new patch set. return insertPatchSet(git, revWalk, destChanges.get(0).change(), cherryPickCommit, refControl, identifiedUser); } else { // Change key not found on destination branch. We can create a new // change. String newTopic = null; if (!Strings.isNullOrEmpty(change.getTopic())) { newTopic = change.getTopic() + "-" + newDest.getShortName(); } Change newChange = createNewChange(git, revWalk, changeKey, project, destRef, cherryPickCommit, refControl, identifiedUser, newTopic); addMessageToSourceChange(change, patch.getId(), destinationBranch, cherryPickCommit, identifiedUser, refControl); addMessageToDestinationChange(newChange, change.getDest().getShortName(), identifiedUser, refControl); return newChange.getId(); } } catch (RepositoryNotFoundException e) { throw new NoSuchChangeException(change.getId(), e); } }
From source file:com.google.gerrit.server.change.CreateChange.java
License:Apache License
@Override public Response<ChangeInfo> apply(TopLevelResource parent, ChangeInfo input) throws AuthException, OrmException, BadRequestException, UnprocessableEntityException, IOException, InvalidChangeOperationException, ResourceNotFoundException, MethodNotAllowedException, ResourceConflictException { if (Strings.isNullOrEmpty(input.project)) { throw new BadRequestException("project must be non-empty"); }// w ww . j a v a 2 s .com if (Strings.isNullOrEmpty(input.branch)) { throw new BadRequestException("branch must be non-empty"); } if (Strings.isNullOrEmpty(input.subject)) { throw new BadRequestException("commit message must be non-empty"); } if (input.status != null) { if (input.status != ChangeStatus.NEW && input.status != ChangeStatus.DRAFT) { throw new BadRequestException("unsupported change status"); } if (!allowDrafts && input.status == ChangeStatus.DRAFT) { throw new MethodNotAllowedException("draft workflow is disabled"); } } String refName = RefNames.fullName(input.branch); ProjectResource rsrc = projectsCollection.parse(input.project); Capable r = rsrc.getControl().canPushToAtLeastOneRef(); if (r != Capable.OK) { throw new AuthException(r.getMessage()); } RefControl refControl = rsrc.getControl().controlForRef(refName); if (!refControl.canUpload() || !refControl.canRead()) { throw new AuthException("cannot upload review"); } Project.NameKey project = rsrc.getNameKey(); try (Repository git = gitManager.openRepository(project); RevWalk rw = new RevWalk(git)) { ObjectId parentCommit; List<String> groups; if (input.baseChange != null) { List<Change> changes = changeUtil.findChanges(input.baseChange); if (changes.size() != 1) { throw new InvalidChangeOperationException("Base change not found: " + input.baseChange); } Change change = Iterables.getOnlyElement(changes); if (!rsrc.getControl().controlFor(change).isVisible(db.get())) { throw new InvalidChangeOperationException("Base change not found: " + input.baseChange); } PatchSet ps = db.get().patchSets() .get(new PatchSet.Id(change.getId(), change.currentPatchSetId().get())); parentCommit = ObjectId.fromString(ps.getRevision().get()); groups = ps.getGroups(); } else { Ref destRef = git.getRefDatabase().exactRef(refName); if (destRef == null) { throw new UnprocessableEntityException(String.format("Branch %s does not exist.", refName)); } parentCommit = destRef.getObjectId(); groups = null; } RevCommit mergeTip = rw.parseCommit(parentCommit); Timestamp now = TimeUtil.nowTs(); IdentifiedUser me = (IdentifiedUser) userProvider.get(); PersonIdent author = me.newCommitterIdent(now, serverTimeZone); ObjectId id = ChangeIdUtil.computeChangeId(mergeTip.getTree(), mergeTip, author, author, input.subject); String commitMessage = ChangeIdUtil.insertId(input.subject, id); RevCommit c = newCommit(git, rw, author, mergeTip, commitMessage); Change change = new Change(getChangeId(id, c), new Change.Id(db.get().nextChangeId()), me.getAccountId(), new Branch.NameKey(project, refName), now); ChangeInserter ins = changeInserterFactory.create(refControl.getProjectControl(), change, c); ChangeMessage msg = new ChangeMessage( new ChangeMessage.Key(change.getId(), ChangeUtil.messageUUID(db.get())), me.getAccountId(), ins.getPatchSet().getCreatedOn(), ins.getPatchSet().getId()); msg.setMessage(String.format("Uploaded patch set %s.", ins.getPatchSet().getPatchSetId())); ins.setMessage(msg); validateCommit(git, refControl, c, me, ins); updateRef(git, rw, c, change, ins.getPatchSet()); String topic = input.topic; if (topic != null) { topic = Strings.emptyToNull(topic.trim()); } change.setTopic(topic); ins.setDraft(input.status != null && input.status == ChangeStatus.DRAFT); ins.setGroups(groups); ins.insert(); ChangeJson json = jsonFactory.create(ChangeJson.NO_OPTIONS); return Response.created(json.format(change.getId())); } }
From source file:com.google.gerrit.server.ChangeUtil.java
License:Apache License
public Change.Id revert(ChangeControl ctl, PatchSet.Id patchSetId, String message, PersonIdent myIdent, SshInfo sshInfo) throws NoSuchChangeException, OrmException, MissingObjectException, IncorrectObjectTypeException, IOException, InvalidChangeOperationException { Change.Id changeId = patchSetId.getParentKey(); PatchSet patch = db.get().patchSets().get(patchSetId); if (patch == null) { throw new NoSuchChangeException(changeId); }//from w ww .j a v a2s .c o m Change changeToRevert = db.get().changes().get(changeId); Project.NameKey project = ctl.getChange().getProject(); try (Repository git = gitManager.openRepository(project); RevWalk revWalk = new RevWalk(git)) { RevCommit commitToRevert = revWalk.parseCommit(ObjectId.fromString(patch.getRevision().get())); PersonIdent authorIdent = user().newCommitterIdent(myIdent.getWhen(), myIdent.getTimeZone()); RevCommit parentToCommitToRevert = commitToRevert.getParent(0); revWalk.parseHeaders(parentToCommitToRevert); CommitBuilder revertCommitBuilder = new CommitBuilder(); revertCommitBuilder.addParentId(commitToRevert); revertCommitBuilder.setTreeId(parentToCommitToRevert.getTree()); revertCommitBuilder.setAuthor(authorIdent); revertCommitBuilder.setCommitter(authorIdent); if (message == null) { message = MessageFormat.format(ChangeMessages.get().revertChangeDefaultMessage, changeToRevert.getSubject(), patch.getRevision().get()); } ObjectId computedChangeId = ChangeIdUtil.computeChangeId(parentToCommitToRevert.getTree(), commitToRevert, authorIdent, myIdent, message); revertCommitBuilder.setMessage(ChangeIdUtil.insertId(message, computedChangeId, true)); RevCommit revertCommit; try (ObjectInserter oi = git.newObjectInserter()) { ObjectId id = oi.insert(revertCommitBuilder); oi.flush(); revertCommit = revWalk.parseCommit(id); } RefControl refControl = ctl.getRefControl(); Change change = new Change(new Change.Key("I" + computedChangeId.name()), new Change.Id(db.get().nextChangeId()), user().getAccountId(), changeToRevert.getDest(), TimeUtil.nowTs()); change.setTopic(changeToRevert.getTopic()); ChangeInserter ins = changeInserterFactory.create(refControl.getProjectControl(), change, revertCommit); PatchSet ps = ins.getPatchSet(); String ref = refControl.getRefName(); String cmdRef = MagicBranch.NEW_PUBLISH_CHANGE + ref.substring(ref.lastIndexOf('/') + 1); CommitReceivedEvent commitReceivedEvent = new CommitReceivedEvent( new ReceiveCommand(ObjectId.zeroId(), revertCommit.getId(), cmdRef), refControl.getProjectControl().getProject(), refControl.getRefName(), revertCommit, user()); try { commitValidatorsFactory.create(refControl, sshInfo, git) .validateForGerritCommits(commitReceivedEvent); } catch (CommitValidationException e) { throw new InvalidChangeOperationException(e.getMessage()); } RefUpdate ru = git.updateRef(ps.getRefName()); ru.setExpectedOldObjectId(ObjectId.zeroId()); ru.setNewObjectId(revertCommit); ru.disableRefLog(); if (ru.update(revWalk) != RefUpdate.Result.NEW) { throw new IOException(String.format("Failed to create ref %s in %s: %s", ps.getRefName(), change.getDest().getParentKey().get(), ru.getResult())); } ChangeMessage cmsg = new ChangeMessage(new ChangeMessage.Key(changeId, messageUUID(db.get())), user().getAccountId(), TimeUtil.nowTs(), patchSetId); StringBuilder msgBuf = new StringBuilder(); msgBuf.append("Patch Set ").append(patchSetId.get()).append(": Reverted"); msgBuf.append("\n\n"); msgBuf.append("This patchset was reverted in change: ").append(change.getKey().get()); cmsg.setMessage(msgBuf.toString()); ins.setMessage(cmsg).insert(); try { RevertedSender cm = revertedSenderFactory.create(change.getId()); cm.setFrom(user().getAccountId()); cm.setChangeMessage(cmsg); cm.send(); } catch (Exception err) { log.error("Cannot send email for revert change " + change.getId(), err); } return change.getId(); } catch (RepositoryNotFoundException e) { throw new NoSuchChangeException(changeId, e); } }
From source file:com.google.gerrit.server.git.VersionedMetaData.java
License:Apache License
/** * Open a batch of updates to the same metadata ref. * <p>// www . ja v a 2s .c om * This allows making multiple commits to a single metadata ref, at the end of * which is a single ref update. For batching together updates to multiple * refs (each consisting of one or more commits against their respective * refs), create the {@link MetaDataUpdate} with a {@link BatchRefUpdate}. * <p> * A ref update produced by this {@link BatchMetaDataUpdate} is only committed * if there is no associated {@link BatchRefUpdate}. As a result, the * configured ref updated event is not fired if there is an associated batch. * * @param update helper info about the update. * @throws IOException if the update failed. */ public BatchMetaDataUpdate openUpdate(final MetaDataUpdate update) throws IOException { final Repository db = update.getRepository(); reader = db.newObjectReader(); inserter = db.newObjectInserter(); final RevWalk rw = new RevWalk(reader); final RevTree tree = revision != null ? rw.parseTree(revision) : null; newTree = readTree(tree); return new BatchMetaDataUpdate() { AnyObjectId src = revision; AnyObjectId srcTree = tree; @Override public void write(CommitBuilder commit) throws IOException { write(VersionedMetaData.this, commit); } private boolean doSave(VersionedMetaData config, CommitBuilder commit) throws IOException { DirCache nt = config.newTree; ObjectReader r = config.reader; ObjectInserter i = config.inserter; try { config.newTree = newTree; config.reader = reader; config.inserter = inserter; return config.onSave(commit); } catch (ConfigInvalidException e) { throw new IOException( "Cannot update " + getRefName() + " in " + db.getDirectory() + ": " + e.getMessage(), e); } finally { config.newTree = nt; config.reader = r; config.inserter = i; } } @Override public void write(VersionedMetaData config, CommitBuilder commit) throws IOException { if (!doSave(config, commit)) { return; } // Reuse tree from parent commit unless there are contents in newTree or // there is no tree for a parent commit. ObjectId res = newTree.getEntryCount() != 0 || srcTree == null ? newTree.writeTree(inserter) : srcTree.copy(); if (res.equals(srcTree) && !update.allowEmpty() && (commit.getTreeId() == null)) { // If there are no changes to the content, don't create the commit. return; } // If changes are made to the DirCache and those changes are written as // a commit and then the tree ID is set for the CommitBuilder, then // those previous DirCache changes will be ignored and the commit's // tree will be replaced with the ID in the CommitBuilder. The same is // true if you explicitly set tree ID in a commit and then make changes // to the DirCache; that tree ID will be ignored and replaced by that of // the tree for the updated DirCache. if (commit.getTreeId() == null) { commit.setTreeId(res); } else { // In this case, the caller populated the tree without using DirCache. res = commit.getTreeId(); } if (src != null) { commit.addParentId(src); } if (update.insertChangeId()) { ObjectId id = ChangeIdUtil.computeChangeId(res, getRevision(), commit.getAuthor(), commit.getCommitter(), commit.getMessage()); commit.setMessage(ChangeIdUtil.insertId(commit.getMessage(), id)); } src = inserter.insert(commit); srcTree = res; } @Override public RevCommit createRef(String refName) throws IOException { if (Objects.equals(src, revision)) { return revision; } return updateRef(ObjectId.zeroId(), src, refName); } @Override public void removeRef(String refName) throws IOException { RefUpdate ru = db.updateRef(refName); ru.setForceUpdate(true); if (revision != null) { ru.setExpectedOldObjectId(revision); } RefUpdate.Result result = ru.delete(); switch (result) { case FORCED: update.fireGitRefUpdatedEvent(ru); return; default: throw new IOException( "Cannot delete " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult()); } } @Override public RevCommit commit() throws IOException { return commitAt(revision); } @Override public RevCommit commitAt(ObjectId expected) throws IOException { if (Objects.equals(src, expected)) { return revision; } return updateRef(MoreObjects.firstNonNull(expected, ObjectId.zeroId()), src, getRefName()); } @Override public void close() { newTree = null; rw.close(); if (inserter != null) { inserter.close(); inserter = null; } if (reader != null) { reader.close(); reader = null; } } private RevCommit updateRef(AnyObjectId oldId, AnyObjectId newId, String refName) throws IOException { BatchRefUpdate bru = update.getBatch(); if (bru != null) { bru.addCommand(new ReceiveCommand(oldId.toObjectId(), newId.toObjectId(), refName)); inserter.flush(); revision = rw.parseCommit(newId); return revision; } RefUpdate ru = db.updateRef(refName); ru.setExpectedOldObjectId(oldId); ru.setNewObjectId(src); ru.setRefLogIdent(update.getCommitBuilder().getAuthor()); String message = update.getCommitBuilder().getMessage(); if (message == null) { message = "meta data update"; } try (BufferedReader reader = new BufferedReader(new StringReader(message))) { // read the subject line and use it as reflog message ru.setRefLogMessage("commit: " + reader.readLine(), true); } inserter.flush(); RefUpdate.Result result = ru.update(); switch (result) { case NEW: case FAST_FORWARD: revision = rw.parseCommit(ru.getNewObjectId()); update.fireGitRefUpdatedEvent(ru); return revision; default: throw new IOException( "Cannot update " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult()); } } }; }
From source file:com.googlesource.gerrit.plugins.changefabricator.ChangeFabricator.java
License:Apache License
@Override public Response<String> apply(ProjectResource rsrc, Input input) throws AuthException, OrmException, InvalidChangeOperationException, IOException { String ref = input.ref;//from ww w. j a va 2 s . co m String msg = input.msg; if (Strings.isNullOrEmpty(ref)) { throw new InvalidChangeOperationException("Change baker: Destination branch cannot be null or empty"); } if (Strings.isNullOrEmpty(msg)) { throw new InvalidChangeOperationException("Change baker: Commit message cannot be null or empty"); } if (!userProvider.get().isIdentifiedUser()) { throw new AuthException("User must be authenticated to create a change"); } RefControl refControl = rsrc.getControl().controlForRef(ref); if (!refControl.canUpload()) { throw new AuthException(String.format("Not allowed to create a change to %s", ref)); } Project.NameKey project = rsrc.getNameKey(); final Repository git; try { git = gitManager.openRepository(project); } catch (RepositoryNotFoundException e) { throw new InvalidChangeOperationException("Cannot open repo"); } try { RevWalk rw = new RevWalk(git); try { Ref destRef = git.getRef(ref); if (destRef == null) { throw new InvalidChangeOperationException("Branch " + ref + " does not exist."); } RevCommit mergeTip = rw.parseCommit(destRef.getObjectId()); PersonIdent authorIdent = ((IdentifiedUser) userProvider.get()).newCommitterIdent(myIdent.getWhen(), myIdent.getTimeZone()); ObjectId computedChangeId = ChangeIdUtil.computeChangeId(mergeTip.getTree(), mergeTip, mergeTip.getAuthorIdent(), myIdent, msg); String commitMessage = ChangeIdUtil.insertId(msg, computedChangeId); RevCommit emptyCommit; ObjectInserter oi = git.newObjectInserter(); try { CommitBuilder commit = new CommitBuilder(); commit.setTreeId(mergeTip.getTree().getId()); commit.setParentId(mergeTip); commit.setAuthor(authorIdent); commit.setCommitter(authorIdent); commit.setMessage(commitMessage); emptyCommit = rw.parseCommit(insert(oi, commit)); } finally { oi.release(); } if (emptyCommit == null) { throw new IllegalStateException("Cannot create empty change"); } Preconditions.checkNotNull(emptyCommit); Change.Key changeKey; final List<String> idList = emptyCommit.getFooterLines(CHANGE_ID); if (!idList.isEmpty()) { final String idStr = idList.get(idList.size() - 1).trim(); changeKey = new Change.Key(idStr); } else { changeKey = new Change.Key("I" + computedChangeId.name()); } Id changeId = createNewChange(git, rw, changeKey, project, destRef, emptyCommit, refControl); return Response.ok(String.valueOf(changeId.get())); } finally { rw.release(); } } finally { git.close(); } }
From source file:com.googlesource.gerrit.plugins.github.git.PullRequestCreateChange.java
License:Apache License
public Change.Id addCommitToChange(final ReviewDb db, final Project project, final Repository git, final String destinationBranch, final Account.Id pullRequestOwner, final RevCommit pullRequestCommit, final String pullRequestMesage, final String topic, boolean doValidation) throws NoSuchChangeException, EmailException, OrmException, MissingObjectException, IncorrectObjectTypeException, IOException, InvalidChangeOperationException, MergeException, NoSuchProjectException { Id newChange = null;/*from ww w . j a va2s .co m*/ if (destinationBranch == null || destinationBranch.length() == 0) { throw new InvalidChangeOperationException("Destination branch cannot be null or empty"); } RefControl refControl = projectControlFactory.controlFor(project.getNameKey()) .controlForRef(destinationBranch); try { RevWalk revWalk = new RevWalk(git); try { Ref destRef = git.getRef(destinationBranch); if (destRef == null) { throw new InvalidChangeOperationException("Branch " + destinationBranch + " does not exist."); } String pullRequestSha1 = pullRequestCommit.getId().getName(); ResultSet<PatchSet> existingPatchSet = db.patchSets().byRevision(new RevId(pullRequestSha1)); Iterator<PatchSet> patchSetIterator = existingPatchSet.iterator(); if (patchSetIterator.hasNext()) { PatchSet patchSet = patchSetIterator.next(); LOG.debug("Pull request commit ID " + pullRequestSha1 + " has been already uploaded as PatchSetID=" + patchSet.getPatchSetId() + " in ChangeID=" + patchSet.getId()); return null; } Change.Key changeKey; final List<String> idList = pullRequestCommit.getFooterLines(CHANGE_ID); if (!idList.isEmpty()) { final String idStr = idList.get(idList.size() - 1).trim(); changeKey = new Change.Key(idStr); } else { final ObjectId computedChangeId = ChangeIdUtil.computeChangeId(pullRequestCommit.getTree(), pullRequestCommit, pullRequestCommit.getAuthorIdent(), pullRequestCommit.getCommitterIdent(), pullRequestMesage); changeKey = new Change.Key("I" + computedChangeId.name()); } List<Change> destChanges = db.changes() .byBranchKey(new Branch.NameKey(project.getNameKey(), destRef.getName()), changeKey) .toList(); if (destChanges.size() > 1) { throw new InvalidChangeOperationException("Multiple Changes with Change-ID " + changeKey + " already exist on the target branch: cannot add a new patch-set " + destinationBranch); } else if (destChanges.size() == 1) { // The change key exists on the destination branch: adding a new // patch-set Change destChange = destChanges.get(0); ChangeControl changeControl = projectControlFactory.controlFor(project.getNameKey()) .controlFor(destChange).forUser(userFactory.create(pullRequestOwner)); return insertPatchSet(git, revWalk, destChange, pullRequestCommit, changeControl, pullRequestOwner, pullRequestMesage, doValidation); } else { // Change key not found on destination branch. We can create a new // change. return (newChange = createNewChange(db, git, revWalk, changeKey, project.getNameKey(), destRef, pullRequestOwner, pullRequestCommit, refControl, pullRequestMesage, topic, doValidation)); } } finally { revWalk.release(); if (newChange == null) { db.rollback(); } } } finally { git.close(); } }
From source file:com.googlesrouce.gerrit.plugins.github.git.PullRequestCreateChange.java
License:Apache License
public Change.Id addCommitToChange(final ReviewDb db, final Project project, final Repository git, final String destinationBranch, final Account.Id pullRequestOwner, final RevCommit pullRequestCommit, final String pullRequestMesage, final String topic, boolean doValidation) throws NoSuchChangeException, EmailException, OrmException, MissingObjectException, IncorrectObjectTypeException, IOException, InvalidChangeOperationException, MergeException, NoSuchProjectException { Id newChange = null;/* w w w .j a v a2 s.c o m*/ if (destinationBranch == null || destinationBranch.length() == 0) { throw new InvalidChangeOperationException("Destination branch cannot be null or empty"); } RefControl refControl = projectControlFactor.controlFor(project.getNameKey()) .controlForRef(destinationBranch); try { RevWalk revWalk = new RevWalk(git); try { Ref destRef = git.getRef(destinationBranch); if (destRef == null) { throw new InvalidChangeOperationException("Branch " + destinationBranch + " does not exist."); } String pullRequestSha1 = pullRequestCommit.getId().getName(); ResultSet<PatchSet> existingPatchSet = db.patchSets().byRevision(new RevId(pullRequestSha1)); Iterator<PatchSet> patchSetIterator = existingPatchSet.iterator(); if (patchSetIterator.hasNext()) { PatchSet patchSet = patchSetIterator.next(); LOG.debug("Pull request commit ID " + pullRequestSha1 + " has been already uploaded as PatchSetID=" + patchSet.getPatchSetId() + " in ChangeID=" + patchSet.getId()); return null; } Change.Key changeKey; final List<String> idList = pullRequestCommit.getFooterLines(CHANGE_ID); if (!idList.isEmpty()) { final String idStr = idList.get(idList.size() - 1).trim(); changeKey = new Change.Key(idStr); } else { final ObjectId computedChangeId = ChangeIdUtil.computeChangeId(pullRequestCommit.getTree(), pullRequestCommit, pullRequestCommit.getAuthorIdent(), pullRequestCommit.getCommitterIdent(), pullRequestMesage); changeKey = new Change.Key("I" + computedChangeId.name()); } List<Change> destChanges = db.changes() .byBranchKey(new Branch.NameKey(project.getNameKey(), destRef.getName()), changeKey) .toList(); if (destChanges.size() > 1) { throw new InvalidChangeOperationException("Multiple Changes with Change-ID " + changeKey + " already exist on the target branch: cannot add a new patch-set " + destinationBranch); } else if (destChanges.size() == 1) { // The change key exists on the destination branch: adding a new // patch-set Change destChange = destChanges.get(0); ChangeControl changeControl = projectControlFactor.controlFor(project.getNameKey()) .controlFor(destChange); return insertPatchSet(git, revWalk, destChange, pullRequestCommit, changeControl, pullRequestOwner, pullRequestMesage, doValidation); } else { // Change key not found on destination branch. We can create a new // change. return (newChange = createNewChange(db, git, revWalk, changeKey, project.getNameKey(), destRef, pullRequestOwner, pullRequestCommit, refControl, pullRequestMesage, topic, doValidation)); } } finally { revWalk.release(); if (newChange == null) { db.rollback(); } } } finally { git.close(); } }
From source file:com.mangosolutions.rcloud.rawgist.repository.git.BareCommitCommand.java
private void insertChangeId(ObjectId treeId) { ObjectId firstParentId = null;/*from w w w .j a va 2 s. co m*/ if (!parents.isEmpty()) { firstParentId = parents.get(0); } ObjectId changeId = ChangeIdUtil.computeChangeId(treeId, firstParentId, author, committer, message); message = ChangeIdUtil.insertId(message, changeId); if (changeId != null) { message = message.replaceAll("\nChange-Id: I" //$NON-NLS-1$ + ObjectId.zeroId().getName() + "\n", //$NON-NLS-1$ "\nChange-Id: I" //$NON-NLS-1$ + changeId.getName() + "\n"); //$NON-NLS-1$ } }