List of usage examples for org.eclipse.jgit.lib RefUpdate getResult
public Result getResult()
From source file:com.google.gerrit.server.git.SubmoduleOp.java
License:Apache License
/** * Update the submodules in one branch of one repository. * * @param subscriber the branch of the repository which should be changed. * @param updates submodule updates which should be updated to. * @throws SubmoduleException/*from w ww . j ava 2s . c o m*/ */ private void updateGitlinks(ReviewDb db, Branch.NameKey subscriber, Collection<SubmoduleSubscription> updates) throws SubmoduleException { PersonIdent author = null; StringBuilder msgbuf = new StringBuilder("Updated git submodules\n\n"); boolean sameAuthorForAll = true; try (Repository pdb = repoManager.openRepository(subscriber.getParentKey())) { if (pdb.getRef(subscriber.get()) == null) { throw new SubmoduleException("The branch was probably deleted from the subscriber repository"); } DirCache dc = readTree(pdb, pdb.getRef(subscriber.get())); DirCacheEditor ed = dc.editor(); for (SubmoduleSubscription s : updates) { try (Repository subrepo = repoManager.openRepository(s.getSubmodule().getParentKey()); RevWalk rw = CodeReviewCommit.newRevWalk(subrepo)) { Ref ref = subrepo.getRefDatabase().exactRef(s.getSubmodule().get()); if (ref == null) { ed.add(new DeletePath(s.getPath())); continue; } final ObjectId updateTo = ref.getObjectId(); RevCommit newCommit = rw.parseCommit(updateTo); if (author == null) { author = newCommit.getAuthorIdent(); } else if (!author.equals(newCommit.getAuthorIdent())) { sameAuthorForAll = false; } DirCacheEntry dce = dc.getEntry(s.getPath()); ObjectId oldId; if (dce != null) { if (!dce.getFileMode().equals(FileMode.GITLINK)) { log.error("Requested to update gitlink " + s.getPath() + " in " + s.getSubmodule().getParentKey().get() + " but entry " + "doesn't have gitlink file mode."); continue; } oldId = dce.getObjectId(); } else { // This submodule did not exist before. We do not want to add // the full submodule history to the commit message, so omit it. oldId = updateTo; } ed.add(new PathEdit(s.getPath()) { @Override public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.GITLINK); ent.setObjectId(updateTo); } }); if (verboseSuperProject) { msgbuf.append("Project: " + s.getSubmodule().getParentKey().get()); msgbuf.append(" " + s.getSubmodule().getShortName()); msgbuf.append(" " + updateTo.getName()); msgbuf.append("\n\n"); try { rw.markStart(newCommit); rw.markUninteresting(rw.parseCommit(oldId)); for (RevCommit c : rw) { msgbuf.append(c.getFullMessage() + "\n\n"); } } catch (IOException e) { logAndThrowSubmoduleException( "Could not perform a revwalk to " + "create superproject commit message", e); } } } } ed.finish(); if (!sameAuthorForAll || author == null) { author = myIdent; } ObjectInserter oi = pdb.newObjectInserter(); ObjectId tree = dc.writeTree(oi); ObjectId currentCommitId = pdb.getRef(subscriber.get()).getObjectId(); CommitBuilder commit = new CommitBuilder(); commit.setTreeId(tree); commit.setParentIds(new ObjectId[] { currentCommitId }); commit.setAuthor(author); commit.setCommitter(myIdent); commit.setMessage(msgbuf.toString()); oi.insert(commit); oi.flush(); ObjectId commitId = oi.idFor(Constants.OBJ_COMMIT, commit.build()); final RefUpdate rfu = pdb.updateRef(subscriber.get()); rfu.setForceUpdate(false); rfu.setNewObjectId(commitId); rfu.setExpectedOldObjectId(currentCommitId); rfu.setRefLogMessage("Submit to " + subscriber.getParentKey().get(), true); switch (rfu.update()) { case NEW: case FAST_FORWARD: gitRefUpdated.fire(subscriber.getParentKey(), rfu); changeHooks.doRefUpdatedHook(subscriber, rfu, account); // TODO since this is performed "in the background" no mail will be // sent to inform users about the updated branch break; default: throw new IOException(rfu.getResult().name()); } // Recursive call: update subscribers of the subscriber updateSuperProjects(db, Sets.newHashSet(subscriber)); } catch (IOException e) { throw new SubmoduleException("Cannot update gitlinks for " + subscriber.get(), 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>//from w w w . j a v a2s . c o m * 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.google.gerrit.server.tools.hooks.CommitMsgHookTest.java
License:Apache License
private void setHEAD() throws Exception { try (ObjectInserter oi = repository.newObjectInserter()) { final CommitBuilder commit = new CommitBuilder(); commit.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {})); commit.setAuthor(author);//from w w w. j a v a 2s.c om commit.setCommitter(committer); commit.setMessage("test\n"); ObjectId commitId = oi.insert(commit); final RefUpdate ref = repository.updateRef(Constants.HEAD); ref.setNewObjectId(commitId); Result result = ref.forceUpdate(); assert_().withFailureMessage(Constants.HEAD + " did not change: " + ref.getResult()).that(result) .isAnyOf(Result.FAST_FORWARD, Result.FORCED, Result.NEW, Result.NO_CHANGE); } }
From source file:com.googlesource.gerrit.plugins.changefabricator.ChangeFabricator.java
License:Apache License
private Change.Id createNewChange(Repository git, RevWalk revWalk, Change.Key changeKey, Project.NameKey project, Ref destRef, RevCommit emptyCommit, RefControl refControl) throws OrmException, InvalidChangeOperationException, IOException { IdentifiedUser me = (IdentifiedUser) userProvider.get(); Change change = new Change(changeKey, new Change.Id(db.nextChangeId()), me.getAccountId(), new Branch.NameKey(project, destRef.getName()), TimeUtil.nowTs()); ChangeInserter ins = changeInserterFactory.create(refControl, change, emptyCommit); PatchSet newPatchSet = ins.getPatchSet(); CommitValidators commitValidators = commitValidatorsFactory.create(refControl, new NoSshInfo(), git); CommitReceivedEvent commitReceivedEvent = new CommitReceivedEvent( new ReceiveCommand(ObjectId.zeroId(), emptyCommit.getId(), newPatchSet.getRefName()), refControl.getProjectControl().getProject(), refControl.getRefName(), emptyCommit, me); try {//from www .j a v a2s .c om commitValidators.validateForGerritCommits(commitReceivedEvent); } catch (CommitValidationException e) { throw new InvalidChangeOperationException(e.getMessage()); } final RefUpdate ru = git.updateRef(newPatchSet.getRefName()); ru.setExpectedOldObjectId(ObjectId.zeroId()); ru.setNewObjectId(emptyCommit); ru.disableRefLog(); if (ru.update(revWalk) != RefUpdate.Result.NEW) { throw new IOException(String.format("Failed to create ref %s in %s: %s", newPatchSet.getRefName(), change.getDest().getParentKey().get(), ru.getResult())); } ins.insert(); return change.getId(); }
From source file:com.googlesource.gerrit.plugins.github.git.PullRequestCreateChange.java
License:Apache License
private Change.Id createNewChange(ReviewDb db, Repository git, RevWalk revWalk, Change.Key changeKey, Project.NameKey project, Ref destRef, Account.Id pullRequestOwner, RevCommit pullRequestCommit, RefControl refControl, String pullRequestMessage, String topic, boolean doValidation) throws OrmException, InvalidChangeOperationException, IOException { Change change = new Change(changeKey, new Change.Id(db.nextChangeId()), pullRequestOwner, new Branch.NameKey(project, destRef.getName()), TimeUtil.nowTs()); if (topic != null) { change.setTopic(topic);/* w ww. j a v a2 s .co m*/ } ChangeInserter ins = changeInserterFactory.create(refControl, change, pullRequestCommit); PatchSet newPatchSet = ins.getPatchSet(); if (doValidation) { validate(git, pullRequestCommit, refControl, newPatchSet); } final RefUpdate ru = git.updateRef(newPatchSet.getRefName()); ru.setExpectedOldObjectId(ObjectId.zeroId()); ru.setNewObjectId(pullRequestCommit); ru.disableRefLog(); if (ru.update(revWalk) != RefUpdate.Result.NEW) { throw new IOException(String.format("Failed to create ref %s in %s: %s", newPatchSet.getRefName(), change.getDest().getParentKey().get(), ru.getResult())); } ins.setMessage(buildChangeMessage(db, change, newPatchSet, pullRequestOwner, pullRequestMessage)).insert(); return change.getId(); }
From source file:org.commonjava.gitwrap.GitRepository.java
License:Open Source License
public GitRepository checkoutBranch(final String name) throws GitWrapException { final String refName; if (name == null) { refName = Constants.HEAD;/* ww w .j ava 2 s. co m*/ } else if (name.startsWith(Constants.R_HEADS) || name.startsWith(Constants.R_TAGS)) { refName = name; } else { refName = Constants.R_HEADS + name; } if (hasBranch(refName)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Checking out: " + refName); } final FileRepository repository = getRepository(); final boolean detach = !refName.startsWith(Constants.R_HEADS); try { final RevWalk walk = new RevWalk(repository); final RevCommit newCommit = walk.parseCommit(repository.resolve(refName)); final RevCommit oldCommit = walk.parseCommit(repository.resolve(Constants.HEAD)); final GitIndex index = repository.getIndex(); final RevTree newTree = newCommit.getTree(); final RevTree oldTree = oldCommit.getTree(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Checking out: " + newCommit + " (resolved from: " + refName + ")"); } final WorkDirCheckout checkout = new WorkDirCheckout(repository, repository.getWorkTree(), repository.mapTree(oldTree), index, repository.mapTree(newTree)); checkout.checkout(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Writing index..."); } index.write(); final RefUpdate u = repository.updateRef(Constants.HEAD, detach); Result result; if (detach) { u.setNewObjectId(newCommit.getId()); u.setRefLogMessage("Switching to detached branch: " + refName, false); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Updating head ref to point to: " + newCommit.getId()); } result = u.forceUpdate(); } else { u.setRefLogMessage("Switching to linked branch: " + refName, false); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Linking head ref to: " + refName); } result = u.link(refName); } switch (result) { case NEW: case FORCED: case NO_CHANGE: case FAST_FORWARD: break; default: throw new GitWrapException("Error checking out branch: %s. Result: %s", refName, u.getResult().name()); } } catch (final IOException e) { throw new GitWrapException("Failed to checkout branch: %s.\nReason: %s", e, refName, e.getMessage()); } } else { throw new GitWrapException( "Cannot checkout non-existent branch: %s. Perhaps you meant to call createBranch(..)?", refName); } return this; }
From source file:org.eclipse.egit.core.op.BranchOperation.java
License:Open Source License
private void updateHeadRef() throws TeamException { boolean detach = false; // in case of a non-local branch or a tag, // we "detach" HEAD, i.e. point it to the // underlying commit instead of to the Ref if (refName == null || !refName.startsWith(Constants.R_HEADS)) detach = true;// w w w .j av a 2s . c om try { RefUpdate u = repository.updateRef(Constants.HEAD, detach); Result res; if (detach) { u.setNewObjectId(newCommit.getId()); // using forceUpdate instead of update avoids // the merge tests which would otherwise make // this fail u.setRefLogMessage(NLS.bind(CoreText.BranchOperation_checkoutMovingTo, newCommit.getId().name()), false); res = u.forceUpdate(); } else { u.setRefLogMessage(NLS.bind(CoreText.BranchOperation_checkoutMovingTo, refName), false); res = u.link(refName); } switch (res) { case NEW: case FORCED: case NO_CHANGE: case FAST_FORWARD: break; default: throw new IOException(u.getResult().name()); } } catch (IOException e) { throw new TeamException(NLS.bind(CoreText.BranchOperation_updatingHeadToRef, refName), e); } }
From source file:org.nbgit.client.CommitBuilder.java
License:Open Source License
private boolean updateRef(RefUpdate ru, ObjectId id) throws IOException { ru.setNewObjectId(id);//w ww . j av a2 s . c om ru.setRefLogMessage(buildReflogMessage(), false); ru.update(); return ru.getOldObjectId() != null ? ru.getResult() == RefUpdate.Result.FAST_FORWARD : ru.getResult() == RefUpdate.Result.NEW; }