List of usage examples for org.eclipse.jgit.lib RefUpdate getName
public String getName()
From source file:com.gitblit.git.PatchsetReceivePack.java
License:Apache License
private void updateReflog(RefUpdate ru) { if (ru == null) { return;/*from w ww .j a va2 s . c o m*/ } ReceiveCommand.Type type = null; switch (ru.getResult()) { case NEW: type = Type.CREATE; break; case FAST_FORWARD: type = Type.UPDATE; break; case FORCED: type = Type.UPDATE_NONFASTFORWARD; break; default: LOGGER.error( MessageFormat.format("unexpected ref update type {0} for {1}", ru.getResult(), ru.getName())); return; } ReceiveCommand cmd = new ReceiveCommand(ru.getOldObjectId(), ru.getNewObjectId(), ru.getName(), type); RefLogUtils.updateRefLog(user, getRepository(), Arrays.asList(cmd)); }
From source file:com.google.gerrit.server.extensions.events.GitReferenceUpdated.java
License:Apache License
public void fire(Project.NameKey project, RefUpdate refUpdate, ReceiveCommand.Type type) { fire(project, refUpdate.getName(), refUpdate.getOldObjectId(), refUpdate.getNewObjectId(), type); }
From source file:com.google.gerrit.server.extensions.events.GitReferenceUpdated.java
License:Apache License
public void fire(Project.NameKey project, RefUpdate refUpdate) { fire(project, refUpdate.getName(), refUpdate.getOldObjectId(), refUpdate.getNewObjectId(), ReceiveCommand.Type.UPDATE); }
From source file:com.google.gerrit.server.git.MergeOp.java
License:Apache License
private RefUpdate updateBranch(Branch.NameKey destBranch) throws MergeException { RefUpdate branchUpdate = getPendingRefUpdate(destBranch); CodeReviewCommit branchTip = getBranchTip(destBranch); MergeTip mergeTip = mergeTips.get(destBranch); CodeReviewCommit currentTip = mergeTip != null ? mergeTip.getCurrentTip() : null; if (Objects.equals(branchTip, currentTip)) { if (currentTip != null) { logDebug("Branch already at merge tip {}, no update to perform", currentTip.name()); } else {//from ww w.ja va2 s.c o m logDebug("Both branch and merge tip are nonexistent, no update"); } return null; } else if (currentTip == null) { logDebug("No merge tip, no update to perform"); return null; } if (RefNames.REFS_CONFIG.equals(branchUpdate.getName())) { logDebug("Loading new configuration from {}", RefNames.REFS_CONFIG); try { ProjectConfig cfg = new ProjectConfig(destProject.getProject().getNameKey()); cfg.load(repo, currentTip); } catch (Exception e) { throw new MergeException("Submit would store invalid" + " project configuration " + currentTip.name() + " for " + destProject.getProject().getName(), e); } } branchUpdate.setRefLogIdent(refLogIdent); branchUpdate.setForceUpdate(false); branchUpdate.setNewObjectId(currentTip); branchUpdate.setRefLogMessage("merged", true); try { RefUpdate.Result result = branchUpdate.update(rw); logDebug("Update of {}: {}..{} returned status {}", branchUpdate.getName(), branchUpdate.getOldObjectId(), branchUpdate.getNewObjectId(), result); switch (result) { case NEW: case FAST_FORWARD: if (branchUpdate.getResult() == RefUpdate.Result.FAST_FORWARD) { tagCache.updateFastForward(destBranch.getParentKey(), branchUpdate.getName(), branchUpdate.getOldObjectId(), currentTip); } if (RefNames.REFS_CONFIG.equals(branchUpdate.getName())) { Project p = destProject.getProject(); projectCache.evict(p); destProject = projectCache.get(p.getNameKey()); repoManager.setProjectDescription(p.getNameKey(), p.getDescription()); } return branchUpdate; case LOCK_FAILURE: throw new MergeException("Failed to lock " + branchUpdate.getName()); default: throw new IOException(branchUpdate.getResult().name() + '\n' + branchUpdate); } } catch (IOException e) { throw new MergeException("Cannot update " + branchUpdate.getName(), e); } }
From source file:com.google.gerrit.server.git.MergeOp.java
License:Apache License
private void fireRefUpdated(Branch.NameKey destBranch, RefUpdate branchUpdate) { logDebug("Firing ref updated hooks for {}", branchUpdate.getName()); gitRefUpdated.fire(destBranch.getParentKey(), branchUpdate); hooks.doRefUpdatedHook(destBranch, branchUpdate, getAccount(mergeTips.get(destBranch).getCurrentTip())); }
From source file:com.google.gerrit.server.git.SubmoduleOpTest.java
License:Apache License
/** * It tests SubmoduleOp.update in a scenario considering no .gitmodules file * in a merged commit to a destination project/branch that is a source one to * one called "target-project".//www. jav a 2 s . co m * <p> * It expects to update the git link called "source-project" to be in target * repository. * </p> * * @throws Exception If an exception occurs. */ @Test public void testOneSubscriberToUpdate() throws Exception { expect(schemaFactory.open()).andReturn(schema); final Repository sourceRepository = createWorkRepository(); final Git sourceGit = new Git(sourceRepository); addRegularFileToIndex("file.txt", "test content", sourceRepository); final RevCommit sourceMergeTip = sourceGit.commit().setMessage("test").call(); final Branch.NameKey sourceBranchNameKey = new Branch.NameKey(new Project.NameKey("source-project"), "refs/heads/master"); final CodeReviewCommit codeReviewCommit = new CodeReviewCommit(sourceMergeTip.toObjectId()); final Change submittedChange = new Change(new Change.Key(sourceMergeTip.toObjectId().getName()), new Change.Id(1), new Account.Id(1), sourceBranchNameKey, TimeUtil.nowTs()); final Map<Change.Id, CodeReviewCommit> mergedCommits = new HashMap<>(); mergedCommits.put(submittedChange.getId(), codeReviewCommit); final List<Change> submitted = new ArrayList<>(); submitted.add(submittedChange); final Repository targetRepository = createWorkRepository(); final Git targetGit = new Git(targetRepository); addGitLinkToIndex("a", sourceMergeTip.copy(), targetRepository); targetGit.commit().setMessage("test").call(); final Branch.NameKey targetBranchNameKey = new Branch.NameKey(new Project.NameKey("target-project"), sourceBranchNameKey.get()); expect(urlProvider.get()).andReturn("http://localhost:8080"); expect(schema.submoduleSubscriptions()).andReturn(subscriptions); final ResultSet<SubmoduleSubscription> subscribers = new ListResultSet<>(Collections.singletonList( new SubmoduleSubscription(targetBranchNameKey, sourceBranchNameKey, "source-project"))); expect(subscriptions.bySubmodule(sourceBranchNameKey)).andReturn(subscribers); expect(repoManager.openRepository(targetBranchNameKey.getParentKey())).andReturn(targetRepository) .anyTimes(); Capture<RefUpdate> ruCapture = new Capture<>(); gitRefUpdated.fire(eq(targetBranchNameKey.getParentKey()), capture(ruCapture)); changeHooks.doRefUpdatedHook(eq(targetBranchNameKey), anyObject(RefUpdate.class), EasyMock.<Account>isNull()); expect(schema.submoduleSubscriptions()).andReturn(subscriptions); final ResultSet<SubmoduleSubscription> emptySubscriptions = new ListResultSet<>( new ArrayList<SubmoduleSubscription>()); expect(subscriptions.bySubmodule(targetBranchNameKey)).andReturn(emptySubscriptions); schema.close(); final PersonIdent myIdent = new PersonIdent("test-user", "test-user@email.com"); doReplay(); final SubmoduleOp submoduleOp = new SubmoduleOp(sourceBranchNameKey, sourceMergeTip, new RevWalk(sourceRepository), urlProvider, schemaFactory, sourceRepository, new Project(sourceBranchNameKey.getParentKey()), submitted, mergedCommits, myIdent, repoManager, gitRefUpdated, null, changeHooks); submoduleOp.update(); doVerify(); RefUpdate ru = ruCapture.getValue(); assertEquals(ru.getName(), targetBranchNameKey.get()); }
From source file:com.google.gerrit.server.git.SubmoduleOpTest.java
License:Apache License
/** * It tests SubmoduleOp.update in a scenario considering established circular * reference in submodule_subscriptions table. * <p>//from w ww .jav a 2s .c om * In the tested scenario there is no .gitmodules file in a merged commit to a * destination project/branch that is a source one to one called * "target-project". * <p> * submodule_subscriptions table will be incorrect due source appearing as a * subscriber or target-project: according to database target-project has as * source the source-project, and source-project has as source the * target-project. * <p> * It expects to update the git link called "source-project" to be in target * repository and ignoring the incorrect row in database establishing the * circular reference. * </p> * * @throws Exception If an exception occurs. */ @Test public void testAvoidingCircularReference() throws Exception { expect(schemaFactory.open()).andReturn(schema); final Repository sourceRepository = createWorkRepository(); final Git sourceGit = new Git(sourceRepository); addRegularFileToIndex("file.txt", "test content", sourceRepository); final RevCommit sourceMergeTip = sourceGit.commit().setMessage("test").call(); final Branch.NameKey sourceBranchNameKey = new Branch.NameKey(new Project.NameKey("source-project"), "refs/heads/master"); final CodeReviewCommit codeReviewCommit = new CodeReviewCommit(sourceMergeTip.toObjectId()); final Change submittedChange = new Change(new Change.Key(sourceMergeTip.toObjectId().getName()), new Change.Id(1), new Account.Id(1), sourceBranchNameKey, TimeUtil.nowTs()); final Map<Change.Id, CodeReviewCommit> mergedCommits = new HashMap<>(); mergedCommits.put(submittedChange.getId(), codeReviewCommit); final List<Change> submitted = new ArrayList<>(); submitted.add(submittedChange); final Repository targetRepository = createWorkRepository(); final Git targetGit = new Git(targetRepository); addGitLinkToIndex("a", sourceMergeTip.copy(), targetRepository); targetGit.commit().setMessage("test").call(); final Branch.NameKey targetBranchNameKey = new Branch.NameKey(new Project.NameKey("target-project"), sourceBranchNameKey.get()); expect(urlProvider.get()).andReturn("http://localhost:8080"); expect(schema.submoduleSubscriptions()).andReturn(subscriptions); final ResultSet<SubmoduleSubscription> subscribers = new ListResultSet<>(Collections.singletonList( new SubmoduleSubscription(targetBranchNameKey, sourceBranchNameKey, "source-project"))); expect(subscriptions.bySubmodule(sourceBranchNameKey)).andReturn(subscribers); expect(repoManager.openRepository(targetBranchNameKey.getParentKey())).andReturn(targetRepository) .anyTimes(); Capture<RefUpdate> ruCapture = new Capture<>(); gitRefUpdated.fire(eq(targetBranchNameKey.getParentKey()), capture(ruCapture)); changeHooks.doRefUpdatedHook(eq(targetBranchNameKey), anyObject(RefUpdate.class), EasyMock.<Account>isNull()); expect(schema.submoduleSubscriptions()).andReturn(subscriptions); final ResultSet<SubmoduleSubscription> incorrectSubscriptions = new ListResultSet<>( Collections.singletonList( new SubmoduleSubscription(sourceBranchNameKey, targetBranchNameKey, "target-project"))); expect(subscriptions.bySubmodule(targetBranchNameKey)).andReturn(incorrectSubscriptions); schema.close(); final PersonIdent myIdent = new PersonIdent("test-user", "test-user@email.com"); doReplay(); final SubmoduleOp submoduleOp = new SubmoduleOp(sourceBranchNameKey, sourceMergeTip, new RevWalk(sourceRepository), urlProvider, schemaFactory, sourceRepository, new Project(sourceBranchNameKey.getParentKey()), submitted, mergedCommits, myIdent, repoManager, gitRefUpdated, null, changeHooks); submoduleOp.update(); doVerify(); RefUpdate ru = ruCapture.getValue(); assertEquals(ru.getName(), targetBranchNameKey.get()); }
From source file:com.google.gerrit.server.git.validators.RefOperationValidators.java
License:Apache License
public static ReceiveCommand getCommand(RefUpdate update, ReceiveCommand.Type type) { return new ReceiveCommand(update.getOldObjectId(), update.getNewObjectId(), update.getName(), type); }
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 . java 2 s . com*/ * 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: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();// w w w. j a v a 2 s. c o m 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)); } } }