use of org.eclipse.jgit.transport.ReceiveCommand in project gitblit by gitblit.
the class GroovyScriptTest method testSendMail.
@Test
public void testSendMail() throws Exception {
MockGitblit gitblit = new MockGitblit();
MockLogger logger = new MockLogger();
MockClientLogger clientLogger = new MockClientLogger();
List<ReceiveCommand> commands = new ArrayList<ReceiveCommand>();
commands.add(new ReceiveCommand(ObjectId.fromString("c18877690322dfc6ae3e37bb7f7085a24e94e887"), ObjectId.fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"), "refs/heads/master"));
commands.add(new ReceiveCommand(ObjectId.fromString("c18877690322dfc6ae3e37bb7f7085a24e94e887"), ObjectId.fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"), "refs/heads/master2"));
RepositoryModel repository = repositories().getRepositoryModel("helloworld.git");
repository.mailingLists.add("list@helloworld.git");
test("sendmail.groovy", gitblit, logger, clientLogger, commands, repository);
assertEquals(1, logger.messages.size());
assertEquals(1, gitblit.messages.size());
MockMail m = gitblit.messages.get(0);
assertEquals(5, m.toAddresses.size());
assertTrue(m.message.contains("BIT"));
}
use of org.eclipse.jgit.transport.ReceiveCommand in project gerrit by GerritCodeReview.
the class AbstractSubmit method submitWithValidationMultiRepo.
@Test
public void submitWithValidationMultiRepo() throws Exception {
assume().that(isSubmitWholeTopicEnabled()).isTrue();
String topic = "test-topic";
// Create test projects
TestRepository<?> repoA = createProjectWithPush("project-a", null, getSubmitType());
TestRepository<?> repoB = createProjectWithPush("project-b", null, getSubmitType());
// Create changes on project-a
PushOneCommit.Result change1 = createChange(repoA, "master", "Change 1", "a.txt", "content", topic);
PushOneCommit.Result change2 = createChange(repoA, "master", "Change 2", "b.txt", "content", topic);
// Create changes on project-b
PushOneCommit.Result change3 = createChange(repoB, "master", "Change 3", "a.txt", "content", topic);
PushOneCommit.Result change4 = createChange(repoB, "master", "Change 4", "b.txt", "content", topic);
List<PushOneCommit.Result> changes = Lists.newArrayList(change1, change2, change3, change4);
for (PushOneCommit.Result change : changes) {
approve(change.getChangeId());
}
// Construct validator which will throw on a second call.
// Since there are 2 repos, first submit attempt will fail, the second will
// succeed.
List<String> projectsCalled = new ArrayList<>(4);
this.addOnSubmitValidationListener(new OnSubmitValidationListener() {
@Override
public void preBranchUpdate(Arguments args) throws ValidationException {
String master = "refs/heads/master";
assertThat(args.getCommands()).containsKey(master);
ReceiveCommand cmd = args.getCommands().get(master);
ObjectId newMasterId = cmd.getNewId();
try (Repository repo = repoManager.openRepository(args.getProject())) {
assertThat(repo.exactRef(master).getObjectId()).isEqualTo(cmd.getOldId());
assertThat(args.getRef(master)).hasValue(newMasterId);
args.getRevWalk().parseBody(args.getRevWalk().parseCommit(newMasterId));
} catch (IOException e) {
throw new AssertionError("failed checking new ref value", e);
}
projectsCalled.add(args.getProject().get());
if (projectsCalled.size() == 2) {
throw new ValidationException("time to fail");
}
}
});
submitWithConflict(change4.getChangeId(), "time to fail");
assertThat(projectsCalled).containsExactly(name("project-a"), name("project-b"));
for (PushOneCommit.Result change : changes) {
change.assertChange(Change.Status.NEW, name(topic), admin);
}
submit(change4.getChangeId());
assertThat(projectsCalled).containsExactly(name("project-a"), name("project-b"), name("project-a"), name("project-b"));
for (PushOneCommit.Result change : changes) {
change.assertChange(Change.Status.MERGED, name(topic), admin);
}
}
use of org.eclipse.jgit.transport.ReceiveCommand in project gerrit by GerritCodeReview.
the class StarredChangesUtil method unstarAll.
public void unstarAll(Project.NameKey project, Change.Id changeId) throws OrmException {
try (Repository repo = repoManager.openRepository(allUsers);
RevWalk rw = new RevWalk(repo)) {
BatchRefUpdate batchUpdate = repo.getRefDatabase().newBatchUpdate();
batchUpdate.setAllowNonFastForwards(true);
batchUpdate.setRefLogIdent(serverIdent);
batchUpdate.setRefLogMessage("Unstar change " + changeId.get(), true);
for (Account.Id accountId : byChangeFromIndex(changeId).keySet()) {
String refName = RefNames.refsStarredChanges(changeId, accountId);
Ref ref = repo.getRefDatabase().getRef(refName);
batchUpdate.addCommand(new ReceiveCommand(ref.getObjectId(), ObjectId.zeroId(), refName));
}
batchUpdate.execute(rw, NullProgressMonitor.INSTANCE);
for (ReceiveCommand command : batchUpdate.getCommands()) {
if (command.getResult() != ReceiveCommand.Result.OK) {
throw new IOException(String.format("Unstar change %d failed, ref %s could not be deleted: %s", changeId.get(), command.getRefName(), command.getResult()));
}
}
indexer.index(dbProvider.get(), project, changeId);
} catch (IOException e) {
throw new OrmException(String.format("Unstar change %d failed", changeId.get()), e);
}
}
use of org.eclipse.jgit.transport.ReceiveCommand in project gerrit by GerritCodeReview.
the class SubmitStrategyOp method updateRepo.
@Override
public final void updateRepo(RepoContext ctx) throws Exception {
logDebug("{}#updateRepo for change {}", getClass().getSimpleName(), toMerge.change().getId());
checkState(ctx.getRevWalk() == args.rw, "SubmitStrategyOp requires callers to call BatchUpdate#setRepository with exactly the same" + " CodeReviewRevWalk instance from the SubmitStrategy.Arguments: %s != %s", ctx.getRevWalk(), args.rw);
// Run the submit strategy implementation and record the merge tip state so
// we can create the ref update.
CodeReviewCommit tipBefore = args.mergeTip.getCurrentTip();
alreadyMerged = getAlreadyMergedCommit(ctx);
if (alreadyMerged == null) {
updateRepoImpl(ctx);
} else {
logDebug("Already merged as {}", alreadyMerged.name());
}
CodeReviewCommit tipAfter = args.mergeTip.getCurrentTip();
if (Objects.equals(tipBefore, tipAfter)) {
logDebug("Did not move tip", getClass().getSimpleName());
return;
} else if (tipAfter == null) {
logDebug("No merge tip, no update to perform");
return;
}
logDebug("Moved tip from {} to {}", tipBefore, tipAfter);
checkProjectConfig(ctx, tipAfter);
// Needed by postUpdate, at which point mergeTip will have advanced further,
// so it's easier to just snapshot the command.
command = new ReceiveCommand(firstNonNull(tipBefore, ObjectId.zeroId()), tipAfter, getDest().get());
ctx.addRefUpdate(command);
args.submoduleOp.addBranchTip(getDest(), tipAfter);
}
use of org.eclipse.jgit.transport.ReceiveCommand in project gerrit by GerritCodeReview.
the class VersionedMetaData method openUpdate.
/**
* Open a batch of updates to the same metadata ref.
*
* <p>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;
}
ObjectId res = newTree.writeTree(inserter);
if (res.equals(srcTree) && !update.allowEmpty() && (commit.getTreeId() == null)) {
// If there are no changes to the content, don't create the commit.
return;
}
// 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;
case LOCK_FAILURE:
throw new LockFailureException("Cannot delete " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
case FAST_FORWARD:
case IO_FAILURE:
case NEW:
case NOT_ATTEMPTED:
case NO_CHANGE:
case REJECTED:
case REJECTED_CURRENT_BRANCH:
case RENAMED:
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;
case LOCK_FAILURE:
throw new LockFailureException("Cannot update " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
case FORCED:
case IO_FAILURE:
case NOT_ATTEMPTED:
case NO_CHANGE:
case REJECTED:
case REJECTED_CURRENT_BRANCH:
case RENAMED:
default:
throw new IOException("Cannot update " + ru.getName() + " in " + db.getDirectory() + ": " + ru.getResult());
}
}
};
}
Aggregations