List of usage examples for org.eclipse.jgit.util ChangeIdUtil insertId
public static String insertId(String message, ObjectId changeId)
From source file:com.google.gerrit.acceptance.git.GitUtil.java
License:Apache License
public static Commit amendCommit(Git git, PersonIdent i, String msg, String changeId) throws GitAPIException, IOException { msg = ChangeIdUtil.insertId(msg, ObjectId.fromString(changeId.substring(1))); return createCommit(git, i, msg, changeId); }
From source file:com.google.gerrit.acceptance.git.GitUtil.java
License:Apache License
private static Commit createCommit(Git git, PersonIdent i, String msg, String changeId) throws GitAPIException, IOException { final CommitCommand commitCmd = git.commit(); commitCmd.setAmend(changeId != null); commitCmd.setAuthor(i);//from w w w . j a v a 2 s . c o m commitCmd.setCommitter(i); if (changeId == null) { ObjectId id = computeChangeId(git, i, msg); changeId = "I" + id.getName(); } msg = ChangeIdUtil.insertId(msg, ObjectId.fromString(changeId.substring(1))); commitCmd.setMessage(msg); RevCommit c = commitCmd.call(); return new Commit(c, changeId); }
From source file:com.google.gerrit.acceptance.git.ssh.GitUtil.java
License:Apache License
public static String createCommit(Git git, PersonIdent i, String msg, boolean insertChangeId) throws GitAPIException, IOException { ObjectId changeId = null;//from w w w . j a v a 2 s . c om if (insertChangeId) { changeId = computeChangeId(git, i, msg); msg = ChangeIdUtil.insertId(msg, changeId); } final CommitCommand commitCmd = git.commit(); commitCmd.setAuthor(i); commitCmd.setCommitter(i); commitCmd.setMessage(msg); commitCmd.call(); return changeId != null ? "I" + changeId.getName() : null; }
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 ww w .ja v a2 s .c o m*/ 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"); }/*from ww w .ja va 2 s . co m*/ 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.change.CreateMergePatchSet.java
License:Apache License
private RevCommit createMergeCommit(MergePatchSetInput in, ProjectControl projectControl, Branch.NameKey dest, Repository git, ObjectInserter oi, RevWalk rw, RevCommit currentPsCommit, RevCommit sourceCommit, PersonIdent author, ObjectId changeId) throws ResourceNotFoundException, MergeIdenticalTreeException, MergeConflictException, IOException { ObjectId parentCommit;//from w ww .j av a2 s . co m if (in.inheritParent) { // inherit first parent from previous patch set parentCommit = currentPsCommit.getParent(0); } else { // get the current branch tip of destination branch Ref destRef = git.getRefDatabase().exactRef(dest.get()); if (destRef != null) { parentCommit = destRef.getObjectId(); } else { throw new ResourceNotFoundException("cannot find destination branch"); } } RevCommit mergeTip = rw.parseCommit(parentCommit); String commitMsg; if (Strings.emptyToNull(in.subject) != null) { commitMsg = ChangeIdUtil.insertId(in.subject, changeId); } else { // reuse previous patch set commit message commitMsg = currentPsCommit.getFullMessage(); } String mergeStrategy = MoreObjects.firstNonNull(Strings.emptyToNull(in.merge.strategy), mergeUtilFactory.create(projectControl.getProjectState()).mergeStrategyName()); return MergeUtil.createMergeCommit(oi, git.getConfig(), mergeTip, sourceCommit, mergeStrategy, author, commitMsg, rw); }
From source file:com.google.gerrit.server.git.VersionedMetaData.java
License:Apache License
/** * Open a batch of updates to the same metadata ref. * <p>/*from ww w.j a va 2 s . 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 w w w .ja va 2 s. c o 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.mangosolutions.rcloud.rawgist.repository.git.BareCommitCommand.java
private void insertChangeId(ObjectId treeId) { ObjectId firstParentId = null;/*from w ww . j a v a 2 s.c o 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$ } }
From source file:org.eclipse.egit.core.op.CommitOperation.java
License:Open Source License
private void doCommits(String actMessage, HashMap<Repository, Tree> treeMap) throws IOException, TeamException { String commitMessage = actMessage; final Date commitDate = new Date(); final TimeZone timeZone = TimeZone.getDefault(); final PersonIdent authorIdent = RawParseUtils.parsePersonIdent(author); final PersonIdent committerIdent = RawParseUtils.parsePersonIdent(committer); for (java.util.Map.Entry<Repository, Tree> entry : treeMap.entrySet()) { Tree tree = entry.getValue();/*from w w w . j a v a 2 s . c om*/ Repository repo = tree.getRepository(); repo.getIndex().write(); writeTreeWithSubTrees(tree); ObjectId currentHeadId = repo.resolve(Constants.HEAD); ObjectId[] parentIds; if (amending) { RevCommit[] parents = previousCommit.getParents(); parentIds = new ObjectId[parents.length]; for (int i = 0; i < parents.length; i++) parentIds[i] = parents[i].getId(); } else { if (currentHeadId != null) parentIds = new ObjectId[] { currentHeadId }; else parentIds = new ObjectId[0]; } if (createChangeId) { ObjectId parentId; if (parentIds.length > 0) parentId = parentIds[0]; else parentId = null; ObjectId changeId = ChangeIdUtil.computeChangeId(tree.getId(), parentId, authorIdent, committerIdent, commitMessage); commitMessage = ChangeIdUtil.insertId(commitMessage, changeId); if (changeId != null) commitMessage = commitMessage.replaceAll( "\nChange-Id: I0000000000000000000000000000000000000000\n", //$NON-NLS-1$ "\nChange-Id: I" + changeId.getName() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ } CommitBuilder commit = new CommitBuilder(); commit.setTreeId(tree.getTreeId()); commit.setParentIds(parentIds); commit.setMessage(commitMessage); commit.setAuthor(new PersonIdent(authorIdent, commitDate, timeZone)); commit.setCommitter(new PersonIdent(committerIdent, commitDate, timeZone)); ObjectInserter inserter = repo.newObjectInserter(); ObjectId commitId; try { commitId = inserter.insert(commit); inserter.flush(); } finally { inserter.release(); } final RefUpdate ru = repo.updateRef(Constants.HEAD); ru.setNewObjectId(commitId); ru.setRefLogMessage(buildReflogMessage(commitMessage), false); if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE) { throw new TeamException(NLS.bind(CoreText.CommitOperation_failedToUpdate, ru.getName(), commitId)); } } }