Convert to new AutoCloseable instances coming in JGit 4.0

Repository, RevWalk, and friends have been converted to AutoCloseable.
Use them in try-with-resources blocks in order to avoid warnings about
unclosed resources or calls to deprecated release() methods. Where a
larger rewrite might have been possible to reduce try/finally blocks,
err on the side of keeping the same behavior.

The proximate goal of this change was to eliminate all Eclipse
warnings about deprecated method calls (namely release()) and leaked
resources. Some of these warnings were in fact potential leaks;
Eclipse finding such cases is a side benefit of having these classes
implement AutoCloseable. However, this change certainly does not cover
all cases where try-with-resources could have been used, where it was
not causing a leak.

Fixes all such warnings in plugin submodules as well.

Change-Id: I5d151996ae012d0e8fdfa27cce8cf5e2bfc856a2
This commit is contained in:
Dave Borowitz 2015-03-10 16:10:59 -07:00
parent 81061fc2bc
commit 16f552165a
55 changed files with 1107 additions and 1446 deletions

View File

@ -222,53 +222,37 @@ public class SubmitOnPushIT extends AbstractDaemonTest {
} }
private void assertCommit(Project.NameKey project, String branch) throws IOException { private void assertCommit(Project.NameKey project, String branch) throws IOException {
Repository r = repoManager.openRepository(project); try (Repository r = repoManager.openRepository(project);
try { RevWalk rw = new RevWalk(r)) {
RevWalk rw = new RevWalk(r); RevCommit c = rw.parseCommit(r.getRef(branch).getObjectId());
try { assertThat(c.getShortMessage()).isEqualTo(PushOneCommit.SUBJECT);
RevCommit c = rw.parseCommit(r.getRef(branch).getObjectId()); assertThat(c.getAuthorIdent().getEmailAddress()).isEqualTo(admin.email);
assertThat(c.getShortMessage()).isEqualTo(PushOneCommit.SUBJECT); assertThat(c.getCommitterIdent().getEmailAddress()).isEqualTo(
assertThat(c.getAuthorIdent().getEmailAddress()).isEqualTo(admin.email); admin.email);
assertThat(c.getCommitterIdent().getEmailAddress()).isEqualTo(
admin.email);
} finally {
rw.release();
}
} finally {
r.close();
} }
} }
private void assertMergeCommit(String branch, String subject) throws IOException { private void assertMergeCommit(String branch, String subject) throws IOException {
Repository r = repoManager.openRepository(project); try (Repository r = repoManager.openRepository(project);
try { RevWalk rw = new RevWalk(r)) {
RevWalk rw = new RevWalk(r); RevCommit c = rw.parseCommit(r.getRef(branch).getObjectId());
try { assertThat(c.getParentCount()).is(2);
RevCommit c = rw.parseCommit(r.getRef(branch).getObjectId()); assertThat(c.getShortMessage()).isEqualTo("Merge \"" + subject + "\"");
assertThat(c.getParentCount()).is(2); assertThat(c.getAuthorIdent().getEmailAddress()).isEqualTo(admin.email);
assertThat(c.getShortMessage()).isEqualTo("Merge \"" + subject + "\""); assertThat(c.getCommitterIdent().getEmailAddress()).isEqualTo(
assertThat(c.getAuthorIdent().getEmailAddress()).isEqualTo(admin.email); serverIdent.getEmailAddress());
assertThat(c.getCommitterIdent().getEmailAddress()).isEqualTo(
serverIdent.getEmailAddress());
} finally {
rw.release();
}
} finally {
r.close();
} }
} }
private void assertTag(Project.NameKey project, String branch, private void assertTag(Project.NameKey project, String branch,
PushOneCommit.Tag tag) throws IOException { PushOneCommit.Tag tag) throws IOException {
Repository repo = repoManager.openRepository(project); try (Repository repo = repoManager.openRepository(project)) {
try {
Ref tagRef = repo.getRef(tag.name); Ref tagRef = repo.getRef(tag.name);
assertThat(tagRef).isNotNull(); assertThat(tagRef).isNotNull();
ObjectId taggedCommit = null; ObjectId taggedCommit = null;
if (tag instanceof PushOneCommit.AnnotatedTag) { if (tag instanceof PushOneCommit.AnnotatedTag) {
PushOneCommit.AnnotatedTag annotatedTag = (PushOneCommit.AnnotatedTag)tag; PushOneCommit.AnnotatedTag annotatedTag = (PushOneCommit.AnnotatedTag)tag;
RevWalk rw = new RevWalk(repo); try (RevWalk rw = new RevWalk(repo)) {
try {
RevObject object = rw.parseAny(tagRef.getObjectId()); RevObject object = rw.parseAny(tagRef.getObjectId());
assertThat(object).isInstanceOf(RevTag.class); assertThat(object).isInstanceOf(RevTag.class);
RevTag tagObject = (RevTag) object; RevTag tagObject = (RevTag) object;
@ -276,8 +260,6 @@ public class SubmitOnPushIT extends AbstractDaemonTest {
.isEqualTo(annotatedTag.message); .isEqualTo(annotatedTag.message);
assertThat(tagObject.getTaggerIdent()).isEqualTo(annotatedTag.tagger); assertThat(tagObject.getTaggerIdent()).isEqualTo(annotatedTag.tagger);
taggedCommit = tagObject.getObject(); taggedCommit = tagObject.getObject();
} finally {
rw.dispose();
} }
} else { } else {
taggedCommit = tagRef.getObjectId(); taggedCommit = tagRef.getObjectId();
@ -285,8 +267,6 @@ public class SubmitOnPushIT extends AbstractDaemonTest {
ObjectId headCommit = repo.getRef(branch).getObjectId(); ObjectId headCommit = repo.getRef(branch).getObjectId();
assertThat(taggedCommit).isNotNull(); assertThat(taggedCommit).isNotNull();
assertThat(taggedCommit).isEqualTo(headCommit); assertThat(taggedCommit).isEqualTo(headCommit);
} finally {
repo.close();
} }
} }

View File

@ -359,40 +359,23 @@ public abstract class AbstractSubmit extends AbstractDaemonTest {
} }
protected RevCommit getRemoteHead() throws IOException { protected RevCommit getRemoteHead() throws IOException {
Repository repo = repoManager.openRepository(project); try (Repository repo = repoManager.openRepository(project)) {
try {
return getHead(repo, "refs/heads/master"); return getHead(repo, "refs/heads/master");
} finally {
repo.close();
} }
} }
protected List<RevCommit> getRemoteLog() throws IOException { protected List<RevCommit> getRemoteLog() throws IOException {
Repository repo = repoManager.openRepository(project); try (Repository repo = repoManager.openRepository(project);
try { RevWalk rw = new RevWalk(repo)) {
RevWalk rw = new RevWalk(repo); rw.markStart(rw.parseCommit(
try { repo.getRef("refs/heads/master").getObjectId()));
rw.markStart(rw.parseCommit( return Lists.newArrayList(rw);
repo.getRef("refs/heads/master").getObjectId()));
return Lists.newArrayList(rw);
} finally {
rw.release();
}
} finally {
repo.close();
} }
} }
private RevCommit getHead(Repository repo, String name) throws IOException { private RevCommit getHead(Repository repo, String name) throws IOException {
try { try (RevWalk rw = new RevWalk(repo)) {
RevWalk rw = new RevWalk(repo); return rw.parseCommit(repo.getRef(name).getObjectId());
try {
return rw.parseCommit(repo.getRef(name).getObjectId());
} finally {
rw.release();
}
} finally {
repo.close();
} }
} }
@ -403,28 +386,22 @@ public abstract class AbstractSubmit extends AbstractDaemonTest {
} }
private String getLatestRemoteDiff() throws IOException { private String getLatestRemoteDiff() throws IOException {
Repository repo = repoManager.openRepository(project); try (Repository repo = repoManager.openRepository(project);
try { RevWalk rw = new RevWalk(repo)) {
RevWalk rw = new RevWalk(repo); ObjectId oldTreeId = repo.resolve("refs/heads/master~1^{tree}");
try { ObjectId newTreeId = repo.resolve("refs/heads/master^{tree}");
ObjectId oldTreeId = repo.resolve("refs/heads/master~1^{tree}"); return getLatestDiff(repo, oldTreeId, newTreeId);
ObjectId newTreeId = repo.resolve("refs/heads/master^{tree}");
return getLatestDiff(repo, oldTreeId, newTreeId);
} finally {
rw.release();
}
} finally {
repo.close();
} }
} }
private String getLatestDiff(Repository repo, ObjectId oldTreeId, private String getLatestDiff(Repository repo, ObjectId oldTreeId,
ObjectId newTreeId) throws IOException { ObjectId newTreeId) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
DiffFormatter fmt = new DiffFormatter(out); try (DiffFormatter fmt = new DiffFormatter(out)) {
fmt.setRepository(repo); fmt.setRepository(repo);
fmt.format(oldTreeId, newTreeId); fmt.format(oldTreeId, newTreeId);
fmt.flush(); fmt.flush();
return out.toString(); return out.toString();
}
} }
} }

View File

@ -238,11 +238,10 @@ public class CreateProjectIT extends AbstractDaemonTest {
private void assertEmptyCommit(String projectName, String... refs) private void assertEmptyCommit(String projectName, String... refs)
throws RepositoryNotFoundException, IOException { throws RepositoryNotFoundException, IOException {
Repository repo = Project.NameKey projectKey = new Project.NameKey(projectName);
repoManager.openRepository(new Project.NameKey(projectName)); try (Repository repo = repoManager.openRepository(projectKey);
RevWalk rw = new RevWalk(repo); RevWalk rw = new RevWalk(repo);
TreeWalk tw = new TreeWalk(repo); TreeWalk tw = new TreeWalk(rw.getObjectReader())) {
try {
for (String ref : refs) { for (String ref : refs) {
RevCommit commit = rw.lookupCommit(repo.getRef(ref).getObjectId()); RevCommit commit = rw.lookupCommit(repo.getRef(ref).getObjectId());
rw.parseBody(commit); rw.parseBody(commit);
@ -250,9 +249,6 @@ public class CreateProjectIT extends AbstractDaemonTest {
assertThat(tw.next()).isFalse(); assertThat(tw.next()).isFalse();
tw.reset(); tw.reset();
} }
} finally {
rw.release();
repo.close();
} }
} }
} }

View File

@ -202,32 +202,29 @@ public class CatServlet extends HttpServlet {
final RevCommit fromCommit; final RevCommit fromCommit;
final String suffix; final String suffix;
final String path = patchKey.getFileName(); final String path = patchKey.getFileName();
try { try (ObjectReader reader = repo.newObjectReader();
final ObjectReader reader = repo.newObjectReader(); RevWalk rw = new RevWalk(reader)) {
try { final RevCommit c;
final RevWalk rw = new RevWalk(reader);
final RevCommit c;
final TreeWalk tw;
c = rw.parseCommit(ObjectId.fromString(revision)); c = rw.parseCommit(ObjectId.fromString(revision));
if (side == 0) { if (side == 0) {
fromCommit = c; fromCommit = c;
suffix = "new"; suffix = "new";
} else if (1 <= side && side - 1 < c.getParentCount()) {
fromCommit = rw.parseCommit(c.getParent(side - 1));
if (c.getParentCount() == 1) {
suffix = "old";
} else {
suffix = "old" + side;
}
} else if (1 <= side && side - 1 < c.getParentCount()) {
fromCommit = rw.parseCommit(c.getParent(side - 1));
if (c.getParentCount() == 1) {
suffix = "old";
} else { } else {
rsp.sendError(HttpServletResponse.SC_NOT_FOUND); suffix = "old" + side;
return;
} }
tw = TreeWalk.forPath(reader, path, fromCommit.getTree()); } else {
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
try (TreeWalk tw = TreeWalk.forPath(reader, path, fromCommit.getTree())) {
if (tw == null) { if (tw == null) {
rsp.sendError(HttpServletResponse.SC_NOT_FOUND); rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
return; return;
@ -240,8 +237,6 @@ public class CatServlet extends HttpServlet {
rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return; return;
} }
} finally {
reader.release();
} }
} catch (IOException e) { } catch (IOException e) {
getServletContext().log("Cannot read repository", e); getServletContext().log("Cannot read repository", e);

View File

@ -185,11 +185,8 @@ public class RebuildNotedb extends SiteProgram {
private static void execute(BatchRefUpdate bru, Repository repo) private static void execute(BatchRefUpdate bru, Repository repo)
throws IOException { throws IOException {
RevWalk rw = new RevWalk(repo); try (RevWalk rw = new RevWalk(repo)) {
try {
bru.execute(rw, NullProgressMonitor.INSTANCE); bru.execute(rw, NullProgressMonitor.INSTANCE);
} finally {
rw.release();
} }
} }

View File

@ -137,49 +137,41 @@ public class AllProjectsConfig extends VersionedMetaData {
throw new IOException("All-Projects does not exist."); throw new IOException("All-Projects does not exist.");
} }
Repository repo = new FileRepository(path); try (Repository repo = new FileRepository(path)) {
try {
inserter = repo.newObjectInserter(); inserter = repo.newObjectInserter();
reader = repo.newObjectReader(); reader = repo.newObjectReader();
try { try (RevWalk rw = new RevWalk(reader)) {
RevWalk rw = new RevWalk(reader); RevTree srcTree = revision != null ? rw.parseTree(revision) : null;
try { newTree = readTree(srcTree);
RevTree srcTree = revision != null ? rw.parseTree(revision) : null; saveConfig(ProjectConfig.PROJECT_CONFIG, cfg);
newTree = readTree(srcTree); saveGroupList();
saveConfig(ProjectConfig.PROJECT_CONFIG, cfg); ObjectId res = newTree.writeTree(inserter);
saveGroupList(); if (res.equals(srcTree)) {
ObjectId res = newTree.writeTree(inserter); // If there are no changes to the content, don't create the commit.
if (res.equals(srcTree)) { return;
// If there are no changes to the content, don't create the commit.
return;
}
CommitBuilder commit = new CommitBuilder();
commit.setAuthor(ident);
commit.setCommitter(ident);
commit.setMessage(msg);
commit.setTreeId(res);
if (revision != null) {
commit.addParentId(revision);
}
ObjectId newRevision = inserter.insert(commit);
updateRef(repo, ident, newRevision, "commit: " + msg);
revision = newRevision;
} finally {
rw.release();
} }
CommitBuilder commit = new CommitBuilder();
commit.setAuthor(ident);
commit.setCommitter(ident);
commit.setMessage(msg);
commit.setTreeId(res);
if (revision != null) {
commit.addParentId(revision);
}
ObjectId newRevision = inserter.insert(commit);
updateRef(repo, ident, newRevision, "commit: " + msg);
revision = newRevision;
} finally { } finally {
if (inserter != null) { if (inserter != null) {
inserter.release(); inserter.close();
inserter = null; inserter = null;
} }
if (reader != null) { if (reader != null) {
reader.release(); reader.close();
reader = null; reader = null;
} }
} }
} finally {
repo.close();
} }
// we need to invalidate the JGit cache if the group list is invalidated in // we need to invalidate the JGit cache if the group list is invalidated in

View File

@ -26,6 +26,7 @@ import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.ChangeMessage; import com.google.gerrit.reviewdb.client.ChangeMessage;
import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.PatchSetAncestor; import com.google.gerrit.reviewdb.client.PatchSetAncestor;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.client.RevId; import com.google.gerrit.reviewdb.client.RevId;
import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.change.ChangeInserter; import com.google.gerrit.server.change.ChangeInserter;
@ -227,119 +228,107 @@ public class ChangeUtil {
} }
Change changeToRevert = db.get().changes().get(changeId); Change changeToRevert = db.get().changes().get(changeId);
Repository git; Project.NameKey project = ctl.getChange().getProject();
try { try (Repository git = gitManager.openRepository(project);
git = gitManager.openRepository(ctl.getChange().getProject()); 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);
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) { } catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e); throw new NoSuchChangeException(changeId, e);
} }
try {
RevWalk revWalk = new RevWalk(git);
try {
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;
ObjectInserter oi = git.newObjectInserter();
try {
ObjectId id = oi.insert(revertCommitBuilder);
oi.flush();
revertCommit = revWalk.parseCommit(id);
} finally {
oi.release();
}
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);
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();
} finally {
revWalk.release();
}
} finally {
git.close();
}
} }
public Change.Id editCommitMessage(ChangeControl ctl, PatchSet ps, public Change.Id editCommitMessage(ChangeControl ctl, PatchSet ps,
@ -354,68 +343,56 @@ public class ChangeUtil {
"The commit message cannot be empty"); "The commit message cannot be empty");
} }
Repository git; Project.NameKey project = ctl.getChange().getProject();
try { try (Repository git = gitManager.openRepository(project);
git = gitManager.openRepository(ctl.getChange().getProject()); RevWalk revWalk = new RevWalk(git)) {
RevCommit commit =
revWalk.parseCommit(ObjectId.fromString(ps.getRevision()
.get()));
if (commit.getFullMessage().equals(message)) {
throw new InvalidChangeOperationException(
"New commit message cannot be same as existing commit message");
}
Date now = myIdent.getWhen();
PersonIdent authorIdent =
user().newCommitterIdent(now, myIdent.getTimeZone());
CommitBuilder commitBuilder = new CommitBuilder();
commitBuilder.setTreeId(commit.getTree());
commitBuilder.setParentIds(commit.getParents());
commitBuilder.setAuthor(commit.getAuthorIdent());
commitBuilder.setCommitter(authorIdent);
commitBuilder.setMessage(message);
RevCommit newCommit;
try (ObjectInserter oi = git.newObjectInserter()) {
ObjectId id = oi.insert(commitBuilder);
oi.flush();
newCommit = revWalk.parseCommit(id);
}
PatchSet.Id id = nextPatchSetId(git, change.currentPatchSetId());
PatchSet newPatchSet = new PatchSet(id);
newPatchSet.setCreatedOn(new Timestamp(now.getTime()));
newPatchSet.setUploader(user().getAccountId());
newPatchSet.setRevision(new RevId(newCommit.name()));
String msg = "Patch Set " + newPatchSet.getPatchSetId()
+ ": Commit message was updated";
change = patchSetInserterFactory
.create(git, revWalk, ctl, newCommit)
.setPatchSet(newPatchSet)
.setMessage(msg)
.setValidatePolicy(RECEIVE_COMMITS)
.setDraft(ps.isDraft())
.insert();
return change.getId();
} catch (RepositoryNotFoundException e) { } catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e); throw new NoSuchChangeException(changeId, e);
} }
try {
RevWalk revWalk = new RevWalk(git);
try {
RevCommit commit =
revWalk.parseCommit(ObjectId.fromString(ps.getRevision()
.get()));
if (commit.getFullMessage().equals(message)) {
throw new InvalidChangeOperationException(
"New commit message cannot be same as existing commit message");
}
Date now = myIdent.getWhen();
PersonIdent authorIdent =
user().newCommitterIdent(now, myIdent.getTimeZone());
CommitBuilder commitBuilder = new CommitBuilder();
commitBuilder.setTreeId(commit.getTree());
commitBuilder.setParentIds(commit.getParents());
commitBuilder.setAuthor(commit.getAuthorIdent());
commitBuilder.setCommitter(authorIdent);
commitBuilder.setMessage(message);
RevCommit newCommit;
ObjectInserter oi = git.newObjectInserter();
try {
ObjectId id = oi.insert(commitBuilder);
oi.flush();
newCommit = revWalk.parseCommit(id);
} finally {
oi.release();
}
PatchSet.Id id = nextPatchSetId(git, change.currentPatchSetId());
PatchSet newPatchSet = new PatchSet(id);
newPatchSet.setCreatedOn(new Timestamp(now.getTime()));
newPatchSet.setUploader(user().getAccountId());
newPatchSet.setRevision(new RevId(newCommit.name()));
String msg = "Patch Set " + newPatchSet.getPatchSetId()
+ ": Commit message was updated";
change = patchSetInserterFactory
.create(git, revWalk, ctl, newCommit)
.setPatchSet(newPatchSet)
.setMessage(msg)
.setValidatePolicy(RECEIVE_COMMITS)
.setDraft(ps.isDraft())
.insert();
return change.getId();
} finally {
revWalk.release();
}
} finally {
git.close();
}
} }
public String getMessage(Change change) public String getMessage(Change change)
@ -427,25 +404,14 @@ public class ChangeUtil {
throw new NoSuchChangeException(changeId); throw new NoSuchChangeException(changeId);
} }
Repository git; try (Repository git = gitManager.openRepository(change.getProject());
try { RevWalk revWalk = new RevWalk(git)) {
git = gitManager.openRepository(change.getProject()); RevCommit commit = revWalk.parseCommit(
ObjectId.fromString(ps.getRevision().get()));
return commit.getFullMessage();
} catch (RepositoryNotFoundException e) { } catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e); throw new NoSuchChangeException(changeId, e);
} }
try {
RevWalk revWalk = new RevWalk(git);
try {
RevCommit commit =
revWalk.parseCommit(ObjectId.fromString(ps.getRevision()
.get()));
return commit.getFullMessage();
} finally {
revWalk.release();
}
} finally {
git.close();
}
} }
public void deleteDraftChange(Change change) public void deleteDraftChange(Change change)

View File

@ -189,8 +189,7 @@ public class ChangeKindCacheImpl implements ChangeKindCache {
return ChangeKind.NO_CODE_CHANGE; return ChangeKind.NO_CODE_CHANGE;
} }
RevWalk walk = new RevWalk(key.repo); try (RevWalk walk = new RevWalk(key.repo)) {
try {
RevCommit prior = walk.parseCommit(key.prior); RevCommit prior = walk.parseCommit(key.prior);
walk.parseBody(prior); walk.parseBody(prior);
RevCommit next = walk.parseCommit(key.next); RevCommit next = walk.parseCommit(key.next);
@ -227,7 +226,6 @@ public class ChangeKindCacheImpl implements ChangeKindCache {
} }
} finally { } finally {
key.repo = null; key.repo = null;
walk.release();
} }
} }

View File

@ -121,96 +121,82 @@ public class CherryPickChange {
Project.NameKey project = change.getProject(); Project.NameKey project = change.getProject();
IdentifiedUser identifiedUser = (IdentifiedUser) currentUser.get(); IdentifiedUser identifiedUser = (IdentifiedUser) currentUser.get();
final Repository git; try (Repository git = gitManager.openRepository(project);
try { RevWalk revWalk = new RevWalk(git)) {
git = gitManager.openRepository(project); Ref destRef = git.getRef(destinationBranch);
if (destRef == null) {
throw new InvalidChangeOperationException("Branch "
+ destinationBranch + " does not exist.");
}
final RevCommit mergeTip = revWalk.parseCommit(destRef.getObjectId());
RevCommit 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';
RevCommit 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.
Change newChange = createNewChange(git, revWalk, changeKey, project,
destRef, cherryPickCommit, refControl,
identifiedUser, change.getTopic());
addMessageToSourceChange(change, patch.getId(), destinationBranch,
cherryPickCommit, identifiedUser, refControl);
addMessageToDestinationChange(newChange, change.getDest().getShortName(),
identifiedUser, refControl);
return newChange.getId();
}
} catch (RepositoryNotFoundException e) { } catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(change.getId(), e); throw new NoSuchChangeException(change.getId(), e);
} }
try {
RevWalk revWalk = new RevWalk(git);
try {
Ref destRef = git.getRef(destinationBranch);
if (destRef == null) {
throw new InvalidChangeOperationException("Branch "
+ destinationBranch + " does not exist.");
}
final RevCommit mergeTip = revWalk.parseCommit(destRef.getObjectId());
RevCommit 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';
RevCommit cherryPickCommit;
ObjectInserter oi = git.newObjectInserter();
try {
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());
} finally {
oi.release();
}
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.
Change newChange = createNewChange(git, revWalk, changeKey, project,
destRef, cherryPickCommit, refControl,
identifiedUser, change.getTopic());
addMessageToSourceChange(change, patch.getId(), destinationBranch,
cherryPickCommit, identifiedUser, refControl);
addMessageToDestinationChange(newChange, change.getDest().getShortName(),
identifiedUser, refControl);
return newChange.getId();
}
} finally {
revWalk.release();
}
} finally {
git.close();
}
} }
private Change.Id insertPatchSet(Repository git, RevWalk revWalk, Change change, private Change.Id insertPatchSet(Repository git, RevWalk revWalk, Change change,

View File

@ -153,7 +153,7 @@ public class ConsistencyChecker {
return Result.create(c, problems); return Result.create(c, problems);
} finally { } finally {
if (rw != null) { if (rw != null) {
rw.release(); rw.close();
} }
if (repo != null) { if (repo != null) {
repo.close(); repo.close();

View File

@ -158,71 +158,63 @@ public class CreateChange implements
} }
Project.NameKey project = rsrc.getNameKey(); Project.NameKey project = rsrc.getNameKey();
Repository git = gitManager.openRepository(project); try (Repository git = gitManager.openRepository(project);
RevWalk rw = new RevWalk(git)) {
try { ObjectId parentCommit;
RevWalk rw = new RevWalk(git); if (input.baseChange != null) {
try { List<Change> changes = changeUtil.findChanges(input.baseChange);
ObjectId parentCommit; if (changes.size() != 1) {
if (input.baseChange != null) { throw new InvalidChangeOperationException(
List<Change> changes = changeUtil.findChanges(input.baseChange); "Base change not found: " + 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());
} else {
Ref destRef = git.getRef(refName);
if (destRef == null) {
throw new UnprocessableEntityException(String.format(
"Branch %s does not exist.", refName));
}
parentCommit = destRef.getObjectId();
} }
RevCommit mergeTip = rw.parseCommit(parentCommit); Change change = Iterables.getOnlyElement(changes);
if (!rsrc.getControl().controlFor(change).isVisible(db.get())) {
Timestamp now = TimeUtil.nowTs(); throw new InvalidChangeOperationException(
IdentifiedUser me = (IdentifiedUser) userProvider.get(); "Base change not found: " + input.baseChange);
PersonIdent author = me.newCommitterIdent(now, serverTimeZone); }
PatchSet ps = db.get().patchSets().get(
ObjectId id = ChangeIdUtil.computeChangeId(mergeTip.getTree(), new PatchSet.Id(change.getId(),
mergeTip, author, author, input.subject); change.currentPatchSetId().get()));
String commitMessage = ChangeIdUtil.insertId(input.subject, id); parentCommit = ObjectId.fromString(ps.getRevision().get());
} else {
RevCommit c = newCommit(git, rw, author, mergeTip, commitMessage); Ref destRef = git.getRef(refName);
if (destRef == null) {
Change change = new Change( throw new UnprocessableEntityException(String.format(
getChangeId(id, c), "Branch %s does not exist.", refName));
new Change.Id(db.get().nextChangeId()), }
me.getAccountId(), parentCommit = destRef.getObjectId();
new Branch.NameKey(project, refName),
now);
ChangeInserter ins =
changeInserterFactory.create(refControl.getProjectControl(),
change, c);
validateCommit(git, refControl, c, me, ins);
updateRef(git, rw, c, change, ins.getPatchSet());
change.setTopic(input.topic);
ins.setDraft(input.status != null && input.status == ChangeStatus.DRAFT);
ins.insert();
return Response.created(json.format(change.getId()));
} finally {
rw.release();
} }
} finally { RevCommit mergeTip = rw.parseCommit(parentCommit);
git.close();
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);
validateCommit(git, refControl, c, me, ins);
updateRef(git, rw, c, change, ins.getPatchSet());
change.setTopic(input.topic);
ins.setDraft(input.status != null && input.status == ChangeStatus.DRAFT);
ins.insert();
return Response.created(json.format(change.getId()));
} }
} }
@ -275,8 +267,7 @@ public class CreateChange implements
PersonIdent authorIdent, RevCommit mergeTip, String commitMessage) PersonIdent authorIdent, RevCommit mergeTip, String commitMessage)
throws IOException { throws IOException {
RevCommit emptyCommit; RevCommit emptyCommit;
ObjectInserter oi = git.newObjectInserter(); try (ObjectInserter oi = git.newObjectInserter()) {
try {
CommitBuilder commit = new CommitBuilder(); CommitBuilder commit = new CommitBuilder();
commit.setTreeId(mergeTip.getTree().getId()); commit.setTreeId(mergeTip.getTree().getId());
commit.setParentId(mergeTip); commit.setParentId(mergeTip);
@ -284,8 +275,6 @@ public class CreateChange implements
commit.setCommitter(authorIdent); commit.setCommitter(authorIdent);
commit.setMessage(commitMessage); commit.setMessage(commitMessage);
emptyCommit = rw.parseCommit(insert(oi, commit)); emptyCommit = rw.parseCommit(insert(oi, commit));
} finally {
oi.release();
} }
return emptyCommit; return emptyCommit;
} }

View File

@ -58,64 +58,57 @@ public class FileContentUtil {
public BinaryResult getContent(ProjectState project, ObjectId revstr, public BinaryResult getContent(ProjectState project, ObjectId revstr,
String path) throws ResourceNotFoundException, IOException { String path) throws ResourceNotFoundException, IOException {
Repository repo = openRepository(project); try (Repository repo = openRepository(project);
try { RevWalk rw = new RevWalk(repo)) {
RevWalk rw = new RevWalk(repo); RevCommit commit = rw.parseCommit(revstr);
try { ObjectReader reader = rw.getObjectReader();
RevCommit commit = rw.parseCommit(revstr); TreeWalk tw = TreeWalk.forPath(reader, path, commit.getTree());
ObjectReader reader = rw.getObjectReader(); if (tw == null) {
TreeWalk tw = TreeWalk.forPath(reader, path, commit.getTree()); throw new ResourceNotFoundException();
if (tw == null) {
throw new ResourceNotFoundException();
}
org.eclipse.jgit.lib.FileMode mode = tw.getFileMode(0);
ObjectId id = tw.getObjectId(0);
if (mode == org.eclipse.jgit.lib.FileMode.GITLINK) {
return BinaryResult.create(id.name())
.setContentType(X_GIT_GITLINK)
.base64();
}
final ObjectLoader obj = repo.open(id, OBJ_BLOB);
byte[] raw;
try {
raw = obj.getCachedBytes(MAX_SIZE);
} catch (LargeObjectException e) {
raw = null;
}
BinaryResult result;
if (raw != null) {
result = BinaryResult.create(raw);
} else {
result = asBinaryResult(obj);
}
String type;
if (mode == org.eclipse.jgit.lib.FileMode.SYMLINK) {
type = X_GIT_SYMLINK;
} else {
type = registry.getMimeType(path, raw).toString();
type = resolveContentType(project, path, FileMode.FILE, type);
}
return result.setContentType(type).base64();
} finally {
rw.release();
} }
} finally {
repo.close(); org.eclipse.jgit.lib.FileMode mode = tw.getFileMode(0);
ObjectId id = tw.getObjectId(0);
if (mode == org.eclipse.jgit.lib.FileMode.GITLINK) {
return BinaryResult.create(id.name())
.setContentType(X_GIT_GITLINK)
.base64();
}
final ObjectLoader obj = repo.open(id, OBJ_BLOB);
byte[] raw;
try {
raw = obj.getCachedBytes(MAX_SIZE);
} catch (LargeObjectException e) {
raw = null;
}
BinaryResult result;
if (raw != null) {
result = BinaryResult.create(raw);
} else {
result = asBinaryResult(obj);
}
String type;
if (mode == org.eclipse.jgit.lib.FileMode.SYMLINK) {
type = X_GIT_SYMLINK;
} else {
type = registry.getMimeType(path, raw).toString();
type = resolveContentType(project, path, FileMode.FILE, type);
}
return result.setContentType(type).base64();
} }
} }
private static BinaryResult asBinaryResult(final ObjectLoader obj) { private static BinaryResult asBinaryResult(final ObjectLoader obj) {
@SuppressWarnings("resource")
BinaryResult result = new BinaryResult() { BinaryResult result = new BinaryResult() {
@Override @Override
public void writeTo(OutputStream os) throws IOException { public void writeTo(OutputStream os) throws IOException {
obj.copyTo(os); obj.copyTo(os);
} }
}.setContentLength(obj.getSize()); };
result.setContentLength(obj.getSize());
return result; return result;
} }

View File

@ -31,6 +31,7 @@ import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountPatchReview; import com.google.gerrit.reviewdb.client.AccountPatchReview;
import com.google.gerrit.reviewdb.client.Patch; import com.google.gerrit.reviewdb.client.Patch;
import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.IdentifiedUser;
@ -178,30 +179,24 @@ public class Files implements ChildCollection<RevisionResource, FileResource> {
private List<String> query(RevisionResource resource) private List<String> query(RevisionResource resource)
throws RepositoryNotFoundException, IOException { throws RepositoryNotFoundException, IOException {
Repository git = Project.NameKey project = resource.getChange().getProject();
gitManager.openRepository(resource.getChange().getProject()); try (Repository git = gitManager.openRepository(project);
try { ObjectReader or = git.newObjectReader();
TreeWalk tw = new TreeWalk(git); RevWalk rw = new RevWalk(or);
try { TreeWalk tw = new TreeWalk(or)) {
RevCommit c = new RevWalk(tw.getObjectReader()) RevCommit c = rw.parseCommit(
.parseCommit(ObjectId.fromString( ObjectId.fromString(resource.getPatchSet().getRevision().get()));
resource.getPatchSet().getRevision().get()));
tw.addTree(c.getTree()); tw.addTree(c.getTree());
tw.setRecursive(true); tw.setRecursive(true);
List<String> paths = new ArrayList<>(); List<String> paths = new ArrayList<>();
while (tw.next() && paths.size() < 20) { while (tw.next() && paths.size() < 20) {
String s = tw.getPathString(); String s = tw.getPathString();
if (s.contains(query)) { if (s.contains(query)) {
paths.add(s); paths.add(s);
}
} }
return paths;
} finally {
tw.release();
} }
} finally { return paths;
git.close();
} }
} }
@ -261,76 +256,69 @@ public class Files implements ChildCollection<RevisionResource, FileResource> {
private List<String> copy(Set<String> paths, PatchSet.Id old, private List<String> copy(Set<String> paths, PatchSet.Id old,
RevisionResource resource, Account.Id userId) throws IOException, RevisionResource resource, Account.Id userId) throws IOException,
PatchListNotAvailableException, OrmException { PatchListNotAvailableException, OrmException {
Repository git = Project.NameKey project = resource.getChange().getProject();
gitManager.openRepository(resource.getChange().getProject()); try (Repository git = gitManager.openRepository(project);
try { ObjectReader reader = git.newObjectReader();
ObjectReader reader = git.newObjectReader();
try {
PatchList oldList = patchListCache.get(
resource.getChange(),
db.get().patchSets().get(old));
PatchList curList = patchListCache.get(
resource.getChange(),
resource.getPatchSet());
int sz = paths.size();
List<AccountPatchReview> inserts = Lists.newArrayListWithCapacity(sz);
List<String> pathList = Lists.newArrayListWithCapacity(sz);
RevWalk rw = new RevWalk(reader); RevWalk rw = new RevWalk(reader);
TreeWalk tw = new TreeWalk(reader); TreeWalk tw = new TreeWalk(reader)) {
tw.setFilter(PathFilterGroup.createFromStrings(paths)); PatchList oldList = patchListCache.get(
tw.setRecursive(true); resource.getChange(),
int o = tw.addTree(rw.parseCommit(oldList.getNewId()).getTree()); db.get().patchSets().get(old));
int c = tw.addTree(rw.parseCommit(curList.getNewId()).getTree());
int op = -1; PatchList curList = patchListCache.get(
if (oldList.getOldId() != null) { resource.getChange(),
op = tw.addTree(rw.parseTree(oldList.getOldId())); resource.getPatchSet());
}
int cp = -1; int sz = paths.size();
if (curList.getOldId() != null) { List<AccountPatchReview> inserts = Lists.newArrayListWithCapacity(sz);
cp = tw.addTree(rw.parseTree(curList.getOldId())); List<String> pathList = Lists.newArrayListWithCapacity(sz);
}
while (tw.next()) { tw.setFilter(PathFilterGroup.createFromStrings(paths));
String path = tw.getPathString(); tw.setRecursive(true);
if (tw.getRawMode(o) != 0 && tw.getRawMode(c) != 0 int o = tw.addTree(rw.parseCommit(oldList.getNewId()).getTree());
&& tw.idEqual(o, c) int c = tw.addTree(rw.parseCommit(curList.getNewId()).getTree());
&& paths.contains(path)) {
// File exists in previously reviewed oldList and in curList. int op = -1;
// File content is identical. if (oldList.getOldId() != null) {
inserts.add(new AccountPatchReview( op = tw.addTree(rw.parseTree(oldList.getOldId()));
new Patch.Key(
resource.getPatchSet().getId(),
path),
userId));
pathList.add(path);
} else if (op >= 0 && cp >= 0
&& tw.getRawMode(o) == 0 && tw.getRawMode(c) == 0
&& tw.getRawMode(op) != 0 && tw.getRawMode(cp) != 0
&& tw.idEqual(op, cp)
&& paths.contains(path)) {
// File was deleted in previously reviewed oldList and curList.
// File exists in ancestor of oldList and curList.
// File content is identical in ancestors.
inserts.add(new AccountPatchReview(
new Patch.Key(
resource.getPatchSet().getId(),
path),
userId));
pathList.add(path);
}
}
db.get().accountPatchReviews().insert(inserts);
return pathList;
} finally {
reader.release();
} }
} finally {
git.close(); int cp = -1;
if (curList.getOldId() != null) {
cp = tw.addTree(rw.parseTree(curList.getOldId()));
}
while (tw.next()) {
String path = tw.getPathString();
if (tw.getRawMode(o) != 0 && tw.getRawMode(c) != 0
&& tw.idEqual(o, c)
&& paths.contains(path)) {
// File exists in previously reviewed oldList and in curList.
// File content is identical.
inserts.add(new AccountPatchReview(
new Patch.Key(
resource.getPatchSet().getId(),
path),
userId));
pathList.add(path);
} else if (op >= 0 && cp >= 0
&& tw.getRawMode(o) == 0 && tw.getRawMode(c) == 0
&& tw.getRawMode(op) != 0 && tw.getRawMode(cp) != 0
&& tw.idEqual(op, cp)
&& paths.contains(path)) {
// File was deleted in previously reviewed oldList and curList.
// File exists in ancestor of oldList and curList.
// File content is identical in ancestors.
inserts.add(new AccountPatchReview(
new Patch.Key(
resource.getPatchSet().getId(),
path),
userId));
pathList.add(path);
}
}
db.get().accountPatchReviews().insert(inserts);
return pathList;
} }
} }

View File

@ -126,7 +126,7 @@ public class GetArchive implements RestReadView<RevisionResource> {
@Override @Override
public void close() throws IOException { public void close() throws IOException {
rw.release(); rw.close();
repo.close(); repo.close();
} }
}; };
@ -139,7 +139,7 @@ public class GetArchive implements RestReadView<RevisionResource> {
return bin; return bin;
} finally { } finally {
if (close) { if (close) {
rw.release(); rw.close();
} }
} }
} finally { } finally {

View File

@ -94,15 +94,16 @@ public class GetPatch implements RestReadView<RevisionResource> {
private void format(OutputStream out) throws IOException { private void format(OutputStream out) throws IOException {
out.write(formatEmailHeader(commit).getBytes(UTF_8)); out.write(formatEmailHeader(commit).getBytes(UTF_8));
DiffFormatter fmt = new DiffFormatter(out); try (DiffFormatter fmt = new DiffFormatter(out)) {
fmt.setRepository(repo); fmt.setRepository(repo);
fmt.format(base.getTree(), commit.getTree()); fmt.format(base.getTree(), commit.getTree());
fmt.flush(); fmt.flush();
}
} }
@Override @Override
public void close() throws IOException { public void close() throws IOException {
rw.release(); rw.close();
repo.close(); repo.close();
} }
}; };
@ -123,7 +124,7 @@ public class GetPatch implements RestReadView<RevisionResource> {
return bin; return bin;
} finally { } finally {
if (close) { if (close) {
rw.release(); rw.close();
} }
} }
} finally { } finally {

View File

@ -80,19 +80,12 @@ public class GetRelated implements RestReadView<RevisionResource> {
@Override @Override
public RelatedInfo apply(RevisionResource rsrc) public RelatedInfo apply(RevisionResource rsrc)
throws RepositoryNotFoundException, IOException, OrmException { throws RepositoryNotFoundException, IOException, OrmException {
Repository git = gitMgr.openRepository(rsrc.getChange().getProject()); try (Repository git = gitMgr.openRepository(rsrc.getChange().getProject());
try { RevWalk rw = new RevWalk(git)) {
Ref ref = git.getRef(rsrc.getChange().getDest().get()); Ref ref = git.getRef(rsrc.getChange().getDest().get());
RevWalk rw = new RevWalk(git); RelatedInfo info = new RelatedInfo();
try { info.changes = walk(rsrc, rw, ref);
RelatedInfo info = new RelatedInfo(); return info;
info.changes = walk(rsrc, rw, ref);
return info;
} finally {
rw.release();
}
} finally {
git.close();
} }
} }

View File

@ -19,6 +19,7 @@ import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.extensions.restapi.RestReadView; import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.project.ChangeControl; import com.google.gerrit.server.project.ChangeControl;
@ -55,26 +56,19 @@ class IncludedIn implements RestReadView<ChangeResource> {
ChangeControl ctl = rsrc.getControl(); ChangeControl ctl = rsrc.getControl();
PatchSet ps = PatchSet ps =
db.get().patchSets().get(ctl.getChange().currentPatchSetId()); db.get().patchSets().get(ctl.getChange().currentPatchSetId());
Repository r = Project.NameKey project = ctl.getProject().getNameKey();
repoManager.openRepository(ctl.getProject().getNameKey()); try (Repository r = repoManager.openRepository(project);
try { RevWalk rw = new RevWalk(r)) {
RevWalk rw = new RevWalk(r); rw.setRetainBody(false);
RevCommit rev;
try { try {
rw.setRetainBody(false); rev = rw.parseCommit(ObjectId.fromString(ps.getRevision().get()));
RevCommit rev; } catch (IncorrectObjectTypeException err) {
try { throw new BadRequestException(err.getMessage());
rev = rw.parseCommit(ObjectId.fromString(ps.getRevision().get())); } catch (MissingObjectException err) {
} catch (IncorrectObjectTypeException err) { throw new ResourceConflictException(err.getMessage());
throw new BadRequestException(err.getMessage());
} catch (MissingObjectException err) {
throw new ResourceConflictException(err.getMessage());
}
return new IncludedInInfo(IncludedInResolver.resolve(r, rw, rev));
} finally {
rw.release();
} }
} finally { return new IncludedInInfo(IncludedInResolver.resolve(r, rw, rev));
r.close();
} }
} }
@ -87,4 +81,4 @@ class IncludedIn implements RestReadView<ChangeResource> {
tags = in.getTags(); tags = in.getTags();
} }
} }
} }

View File

@ -225,8 +225,7 @@ public class MergeabilityCacheImpl implements MergeabilityCache {
} }
try { try {
Map<String, Ref> refs = key.load.repo.getAllRefs(); Map<String, Ref> refs = key.load.repo.getAllRefs();
RevWalk rw = CodeReviewCommit.newRevWalk(key.load.repo); try (RevWalk rw = CodeReviewCommit.newRevWalk(key.load.repo)) {
try {
RevFlag canMerge = rw.newFlag("CAN_MERGE"); RevFlag canMerge = rw.newFlag("CAN_MERGE");
CodeReviewCommit rev = parse(rw, key.commit); CodeReviewCommit rev = parse(rw, key.commit);
rev.add(canMerge); rev.add(canMerge);
@ -243,8 +242,6 @@ public class MergeabilityCacheImpl implements MergeabilityCache {
canMerge, canMerge,
accepted, accepted,
key.load.dest).dryRun(tip, rev); key.load.dest).dryRun(tip, rev);
} finally {
rw.release();
} }
} finally { } finally {
key.load = null; key.load = null;

View File

@ -119,14 +119,9 @@ public class RebaseChange {
"Cannot rebase: New patch sets are not allowed to be added to change: " "Cannot rebase: New patch sets are not allowed to be added to change: "
+ changeId.toString()); + changeId.toString());
} }
Repository git = null; try (Repository git = gitManager.openRepository(change.getProject());
RevWalk rw = null; RevWalk rw = new RevWalk(git);
ObjectInserter inserter = null; ObjectInserter inserter = git.newObjectInserter()) {
try {
git = gitManager.openRepository(change.getProject());
rw = new RevWalk(git);
inserter = git.newObjectInserter();
String baseRev = newBaseRev; String baseRev = newBaseRev;
if (baseRev == null) { if (baseRev == null) {
baseRev = findBaseRevision(patchSetId, db.get(), baseRev = findBaseRevision(patchSetId, db.get(),
@ -149,16 +144,6 @@ public class RebaseChange {
committerIdent, true, ValidatePolicy.GERRIT); committerIdent, true, ValidatePolicy.GERRIT);
} catch (MergeConflictException e) { } catch (MergeConflictException e) {
throw new IOException(e.getMessage()); throw new IOException(e.getMessage());
} finally {
if (inserter != null) {
inserter.release();
}
if (rw != null) {
rw.release();
}
if (git != null) {
git.close();
}
} }
} }

View File

@ -29,6 +29,7 @@ import com.google.gerrit.extensions.restapi.RawInput;
import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.GerritPersonIdent; import com.google.gerrit.server.GerritPersonIdent;
import com.google.gerrit.server.IdentifiedUser; import com.google.gerrit.server.IdentifiedUser;
@ -115,26 +116,20 @@ public class ChangeEditModifier {
} }
IdentifiedUser me = (IdentifiedUser) currentUser.get(); IdentifiedUser me = (IdentifiedUser) currentUser.get();
Repository repo = gitManager.openRepository(change.getProject());
String refPrefix = editRefPrefix(me.getAccountId(), change.getId()); String refPrefix = editRefPrefix(me.getAccountId(), change.getId());
try { try (Repository repo = gitManager.openRepository(change.getProject())) {
Map<String, Ref> refs = repo.getRefDatabase().getRefs(refPrefix); Map<String, Ref> refs = repo.getRefDatabase().getRefs(refPrefix);
if (!refs.isEmpty()) { if (!refs.isEmpty()) {
throw new ResourceConflictException("edit already exists"); throw new ResourceConflictException("edit already exists");
} }
RevWalk rw = new RevWalk(repo); try (RevWalk rw = new RevWalk(repo)) {
try {
ObjectId revision = ObjectId.fromString(ps.getRevision().get()); ObjectId revision = ObjectId.fromString(ps.getRevision().get());
String editRefName = editRefName(me.getAccountId(), change.getId(), String editRefName = editRefName(me.getAccountId(), change.getId(),
ps.getId()); ps.getId());
return update(repo, me, editRefName, rw, ObjectId.zeroId(), revision); return update(repo, me, editRefName, rw, ObjectId.zeroId(), revision);
} finally {
rw.release();
} }
} finally {
repo.close();
} }
} }
@ -159,59 +154,51 @@ public class ChangeEditModifier {
IdentifiedUser me = (IdentifiedUser) currentUser.get(); IdentifiedUser me = (IdentifiedUser) currentUser.get();
String refName = editRefName(me.getAccountId(), change.getId(), String refName = editRefName(me.getAccountId(), change.getId(),
current.getId()); current.getId());
Repository repo = gitManager.openRepository(change.getProject()); try (Repository repo = gitManager.openRepository(change.getProject());
try { RevWalk rw = new RevWalk(repo);
RevWalk rw = new RevWalk(repo); ObjectInserter inserter = repo.newObjectInserter()) {
BatchRefUpdate ru = repo.getRefDatabase().newBatchUpdate(); BatchRefUpdate ru = repo.getRefDatabase().newBatchUpdate();
ObjectInserter inserter = repo.newObjectInserter(); RevCommit editCommit = edit.getEditCommit();
try { if (editCommit.getParentCount() == 0) {
RevCommit editCommit = edit.getEditCommit(); throw new InvalidChangeOperationException(
if (editCommit.getParentCount() == 0) { "Rebase edit against root commit not supported");
throw new InvalidChangeOperationException( }
"Rebase edit against root commit not supported"); RevCommit tip = rw.parseCommit(ObjectId.fromString(
} current.getRevision().get()));
RevCommit tip = rw.parseCommit(ObjectId.fromString( ThreeWayMerger m = MergeStrategy.RESOLVE.newMerger(repo, true);
current.getRevision().get())); m.setObjectInserter(inserter);
ThreeWayMerger m = MergeStrategy.RESOLVE.newMerger(repo, true); m.setBase(ObjectId.fromString(
m.setObjectInserter(inserter); edit.getBasePatchSet().getRevision().get()));
m.setBase(ObjectId.fromString(
edit.getBasePatchSet().getRevision().get())); if (m.merge(tip, editCommit)) {
ObjectId tree = m.getResultTreeId();
if (m.merge(tip, editCommit)) {
ObjectId tree = m.getResultTreeId(); CommitBuilder commit = new CommitBuilder();
commit.setTreeId(tree);
CommitBuilder commit = new CommitBuilder(); for (int i = 0; i < tip.getParentCount(); i++) {
commit.setTreeId(tree); commit.addParentId(tip.getParent(i));
for (int i = 0; i < tip.getParentCount(); i++) { }
commit.addParentId(tip.getParent(i)); commit.setAuthor(editCommit.getAuthorIdent());
} commit.setCommitter(new PersonIdent(
commit.setAuthor(editCommit.getAuthorIdent()); editCommit.getCommitterIdent(), TimeUtil.nowTs()));
commit.setCommitter(new PersonIdent( commit.setMessage(editCommit.getFullMessage());
editCommit.getCommitterIdent(), TimeUtil.nowTs())); ObjectId newEdit = inserter.insert(commit);
commit.setMessage(editCommit.getFullMessage()); inserter.flush();
ObjectId newEdit = inserter.insert(commit);
inserter.flush(); ru.addCommand(new ReceiveCommand(ObjectId.zeroId(), newEdit,
refName));
ru.addCommand(new ReceiveCommand(ObjectId.zeroId(), newEdit, ru.addCommand(new ReceiveCommand(edit.getRef().getObjectId(),
refName)); ObjectId.zeroId(), edit.getRefName()));
ru.addCommand(new ReceiveCommand(edit.getRef().getObjectId(), ru.execute(rw, NullProgressMonitor.INSTANCE);
ObjectId.zeroId(), edit.getRefName())); for (ReceiveCommand cmd : ru.getCommands()) {
ru.execute(rw, NullProgressMonitor.INSTANCE); if (cmd.getResult() != ReceiveCommand.Result.OK) {
for (ReceiveCommand cmd : ru.getCommands()) { throw new IOException("failed: " + cmd);
if (cmd.getResult() != ReceiveCommand.Result.OK) { }
throw new IOException("failed: " + cmd); }
} } else {
} // TODO(davido): Allow to resolve conflicts inline
} else { throw new ResourceConflictException("merge conflict");
// TODO(davido): Allow to resolve conflicts inline
throw new ResourceConflictException("merge conflict");
}
} finally {
rw.release();
inserter.release();
} }
} finally {
repo.close();
} }
} }
@ -240,23 +227,16 @@ public class ChangeEditModifier {
} }
IdentifiedUser me = (IdentifiedUser) currentUser.get(); IdentifiedUser me = (IdentifiedUser) currentUser.get();
Repository repo = gitManager.openRepository(edit.getChange().getProject()); Project.NameKey project = edit.getChange().getProject();
try { try (Repository repo = gitManager.openRepository(project);
RevWalk rw = new RevWalk(repo); RevWalk rw = new RevWalk(repo);
ObjectInserter inserter = repo.newObjectInserter(); ObjectInserter inserter = repo.newObjectInserter()) {
try { String refName = edit.getRefName();
String refName = edit.getRefName(); ObjectId commit = createCommit(me, inserter, prevEdit,
ObjectId commit = createCommit(me, inserter, prevEdit, prevEdit.getTree(),
prevEdit.getTree(), msg);
msg); inserter.flush();
inserter.flush(); return update(repo, me, refName, rw, prevEdit, commit);
return update(repo, me, refName, rw, prevEdit, commit);
} finally {
rw.release();
inserter.release();
}
} finally {
repo.close();
} }
} }
@ -333,36 +313,28 @@ public class ChangeEditModifier {
throw new AuthException("Authentication required"); throw new AuthException("Authentication required");
} }
IdentifiedUser me = (IdentifiedUser) currentUser.get(); IdentifiedUser me = (IdentifiedUser) currentUser.get();
Repository repo = gitManager.openRepository(edit.getChange().getProject()); Project.NameKey project = edit.getChange().getProject();
try { try (Repository repo = gitManager.openRepository(project);
RevWalk rw = new RevWalk(repo); RevWalk rw = new RevWalk(repo);
ObjectInserter inserter = repo.newObjectInserter(); ObjectInserter inserter = repo.newObjectInserter();
ObjectReader reader = repo.newObjectReader(); ObjectReader reader = repo.newObjectReader()) {
try { String refName = edit.getRefName();
String refName = edit.getRefName(); RevCommit prevEdit = edit.getEditCommit();
RevCommit prevEdit = edit.getEditCommit(); ObjectId newTree = writeNewTree(op,
ObjectId newTree = writeNewTree(op, rw,
rw, inserter,
inserter, prevEdit,
prevEdit, reader,
reader, file,
file, newFile,
newFile, toBlob(inserter, content));
toBlob(inserter, content)); if (ObjectId.equals(newTree, prevEdit.getTree())) {
if (ObjectId.equals(newTree, prevEdit.getTree())) { throw new InvalidChangeOperationException("no changes were made");
throw new InvalidChangeOperationException("no changes were made");
}
ObjectId commit = createCommit(me, inserter, prevEdit, newTree);
inserter.flush();
return update(repo, me, refName, rw, prevEdit, commit);
} finally {
rw.release();
inserter.release();
reader.release();
} }
} finally {
repo.close(); ObjectId commit = createCommit(me, inserter, prevEdit, newTree);
inserter.flush();
return update(repo, me, refName, rw, prevEdit, commit);
} }
} }

View File

@ -109,8 +109,7 @@ public class ChangeEditUtil {
*/ */
public Optional<ChangeEdit> byChange(Change change, IdentifiedUser user) public Optional<ChangeEdit> byChange(Change change, IdentifiedUser user)
throws IOException { throws IOException {
Repository repo = gitManager.openRepository(change.getProject()); try (Repository repo = gitManager.openRepository(change.getProject())) {
try {
String editRefPrefix = editRefPrefix(user.getAccountId(), change.getId()); String editRefPrefix = editRefPrefix(user.getAccountId(), change.getId());
Map<String, Ref> refs = repo.getRefDatabase().getRefs(editRefPrefix); Map<String, Ref> refs = repo.getRefDatabase().getRefs(editRefPrefix);
if (refs.isEmpty()) { if (refs.isEmpty()) {
@ -121,16 +120,11 @@ public class ChangeEditUtil {
// where there is more than one ref, we could silently delete all but the // where there is more than one ref, we could silently delete all but the
// current one. // current one.
Ref ref = Iterables.getOnlyElement(refs.values()); Ref ref = Iterables.getOnlyElement(refs.values());
RevWalk rw = new RevWalk(repo); try (RevWalk rw = new RevWalk(repo)) {
try {
RevCommit commit = rw.parseCommit(ref.getObjectId()); RevCommit commit = rw.parseCommit(ref.getObjectId());
PatchSet basePs = getBasePatchSet(change, ref); PatchSet basePs = getBasePatchSet(change, ref);
return Optional.of(new ChangeEdit(user, change, ref, commit, basePs)); return Optional.of(new ChangeEdit(user, change, ref, commit, basePs));
} finally {
rw.release();
} }
} finally {
repo.close();
} }
} }
@ -150,29 +144,19 @@ public class ChangeEditUtil {
NoSuchChangeException, IOException, InvalidChangeOperationException, NoSuchChangeException, IOException, InvalidChangeOperationException,
OrmException, ResourceConflictException { OrmException, ResourceConflictException {
Change change = edit.getChange(); Change change = edit.getChange();
Repository repo = gitManager.openRepository(change.getProject()); try (Repository repo = gitManager.openRepository(change.getProject());
try { RevWalk rw = new RevWalk(repo);
RevWalk rw = new RevWalk(repo); ObjectInserter inserter = repo.newObjectInserter()) {
ObjectInserter inserter = repo.newObjectInserter(); PatchSet basePatchSet = edit.getBasePatchSet();
try { if (!basePatchSet.getId().equals(change.currentPatchSetId())) {
throw new ResourceConflictException(
PatchSet basePatchSet = edit.getBasePatchSet(); "only edit for current patch set can be published");
if (!basePatchSet.getId().equals(change.currentPatchSetId())) {
throw new ResourceConflictException(
"only edit for current patch set can be published");
}
insertPatchSet(edit, change, repo, rw, basePatchSet,
squashEdit(rw, inserter, edit.getEditCommit(), basePatchSet));
} finally {
inserter.release();
rw.release();
} }
insertPatchSet(edit, change, repo, rw, basePatchSet,
squashEdit(rw, inserter, edit.getEditCommit(), basePatchSet));
// TODO(davido): This should happen in the same BatchRefUpdate. // TODO(davido): This should happen in the same BatchRefUpdate.
deleteRef(repo, edit); deleteRef(repo, edit);
} finally {
repo.close();
} }
} }

View File

@ -101,46 +101,38 @@ public class BanCommit {
NoteMap banCommitNotes = NoteMap.newEmptyMap(); NoteMap banCommitNotes = NoteMap.newEmptyMap();
// Add a note for each banned commit to notes. // Add a note for each banned commit to notes.
final Project.NameKey project = projectControl.getProject().getNameKey(); final Project.NameKey project = projectControl.getProject().getNameKey();
final Repository repo = repoManager.openRepository(project); try (Repository repo = repoManager.openRepository(project);
try { RevWalk revWalk = new RevWalk(repo);
final RevWalk revWalk = new RevWalk(repo); ObjectInserter inserter = repo.newObjectInserter()) {
final ObjectInserter inserter = repo.newObjectInserter(); ObjectId noteId = null;
try { for (final ObjectId commitToBan : commitsToBan) {
ObjectId noteId = null; try {
for (final ObjectId commitToBan : commitsToBan) { revWalk.parseCommit(commitToBan);
try { } catch (MissingObjectException e) {
revWalk.parseCommit(commitToBan); // Ignore exception, non-existing commits can be banned.
} catch (MissingObjectException e) { } catch (IncorrectObjectTypeException e) {
// Ignore exception, non-existing commits can be banned. result.notACommit(commitToBan);
} catch (IncorrectObjectTypeException e) { continue;
result.notACommit(commitToBan);
continue;
}
if (noteId == null) {
noteId = createNoteContent(reason, inserter);
}
banCommitNotes.set(commitToBan, noteId);
} }
NotesBranchUtil notesBranchUtil = if (noteId == null) {
notesBranchUtilFactory.create(project, repo, inserter); noteId = createNoteContent(reason, inserter);
NoteMap newlyCreated =
notesBranchUtil.commitNewNotes(banCommitNotes, REFS_REJECT_COMMITS,
createPersonIdent(), buildCommitMessage(commitsToBan, reason));
for (Note n : banCommitNotes) {
if (newlyCreated.contains(n)) {
result.commitBanned(n);
} else {
result.commitAlreadyBanned(n);
}
} }
return result; banCommitNotes.set(commitToBan, noteId);
} finally {
revWalk.release();
inserter.release();
} }
} finally { NotesBranchUtil notesBranchUtil =
repo.close(); notesBranchUtilFactory.create(project, repo, inserter);
NoteMap newlyCreated =
notesBranchUtil.commitNewNotes(banCommitNotes, REFS_REJECT_COMMITS,
createPersonIdent(), buildCommitMessage(commitsToBan, reason));
for (Note n : banCommitNotes) {
if (newlyCreated.contains(n)) {
result.commitBanned(n);
} else {
result.commitAlreadyBanned(n);
}
}
return result;
} }
} }

View File

@ -332,10 +332,10 @@ public class MergeOp {
throw new MergeException("Cannot query the database", e); throw new MergeException("Cannot query the database", e);
} finally { } finally {
if (inserter != null) { if (inserter != null) {
inserter.release(); inserter.close();
} }
if (rw != null) { if (rw != null) {
rw.release(); rw.close();
} }
if (repo != null) { if (repo != null) {
repo.close(); repo.close();

View File

@ -153,8 +153,8 @@ public class NotesBranchUtil {
} }
updateRef(notesBranch); updateRef(notesBranch);
} finally { } finally {
revWalk.release(); revWalk.close();
reader.release(); reader.close();
} }
} }

View File

@ -382,7 +382,7 @@ public class SubmoduleOp {
+ subscriber.get(), e); + subscriber.get(), e);
} finally { } finally {
if (recRw != null) { if (recRw != null) {
recRw.release(); recRw.close();
} }
if (pdb != null) { if (pdb != null) {
pdb.close(); pdb.close();
@ -392,8 +392,7 @@ public class SubmoduleOp {
private static DirCache readTree(final Repository pdb, final Ref branch) private static DirCache readTree(final Repository pdb, final Ref branch)
throws MissingObjectException, IncorrectObjectTypeException, IOException { throws MissingObjectException, IncorrectObjectTypeException, IOException {
final RevWalk rw = new RevWalk(pdb); try (RevWalk rw = new RevWalk(pdb)) {
try {
final DirCache dc = DirCache.newInCore(); final DirCache dc = DirCache.newInCore();
final DirCacheBuilder b = dc.builder(); final DirCacheBuilder b = dc.builder();
b.addTree(new byte[0], // no prefix path b.addTree(new byte[0], // no prefix path
@ -401,8 +400,6 @@ public class SubmoduleOp {
pdb.newObjectReader(), rw.parseTree(branch.getObjectId())); pdb.newObjectReader(), rw.parseTree(branch.getObjectId()));
b.finish(); b.finish();
return dc; return dc;
} finally {
rw.release();
} }
} }

View File

@ -147,7 +147,7 @@ class TagSet {
} }
} finally { } finally {
if (rw != null) { if (rw != null) {
rw.release(); rw.close();
} }
} }
} }
@ -157,9 +157,8 @@ class TagSet {
return; return;
} }
TagWalk rw = new TagWalk(git); try (TagWalk rw = new TagWalk(git)) {
rw.setRetainBody(false); rw.setRetainBody(false);
try {
for (Ref ref : git.getRefDatabase().getRefs(RefDatabase.ALL).values()) { for (Ref ref : git.getRefDatabase().getRefs(RefDatabase.ALL).values()) {
if (skip(ref)) { if (skip(ref)) {
continue; continue;
@ -188,8 +187,6 @@ class TagSet {
} }
} catch (IOException e) { } catch (IOException e) {
log.warn("Error building tags for repository " + projectName, e); log.warn("Error building tags for repository " + projectName, e);
} finally {
rw.release();
} }
} }

View File

@ -122,7 +122,7 @@ public abstract class VersionedMetaData {
revision = id != null ? new RevWalk(reader).parseCommit(id) : null; revision = id != null ? new RevWalk(reader).parseCommit(id) : null;
onLoad(); onLoad();
} finally { } finally {
reader.release(); reader.close();
reader = null; reader = null;
} }
} }
@ -319,13 +319,14 @@ public abstract class VersionedMetaData {
public void close() { public void close() {
newTree = null; newTree = null;
rw.close();
if (inserter != null) { if (inserter != null) {
inserter.release(); inserter.close();
inserter = null; inserter = null;
} }
if (reader != null) { if (reader != null) {
reader.release(); reader.close();
reader = null; reader = null;
} }
} }

View File

@ -323,41 +323,36 @@ public class SiteIndexer {
getPathsAndIndex(id); getPathsAndIndex(id);
} }
} finally { } finally {
walk.release(); walk.close();
} }
return null; return null;
} }
private void getPathsAndIndex(ObjectId b) throws Exception { private void getPathsAndIndex(ObjectId b) throws Exception {
List<ChangeData> cds = Lists.newArrayList(byId.get(b)); List<ChangeData> cds = Lists.newArrayList(byId.get(b));
try { try (DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE)) {
RevCommit bCommit = walk.parseCommit(b); RevCommit bCommit = walk.parseCommit(b);
RevTree bTree = bCommit.getTree(); RevTree bTree = bCommit.getTree();
RevTree aTree = aFor(bCommit, walk); RevTree aTree = aFor(bCommit, walk);
DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setRepository(repo);
try { if (!cds.isEmpty()) {
df.setRepository(repo); List<String> paths = (aTree != null)
if (!cds.isEmpty()) { ? getPaths(df.scan(aTree, bTree))
List<String> paths = (aTree != null) : Collections.<String>emptyList();
? getPaths(df.scan(aTree, bTree)) Iterator<ChangeData> cdit = cds.iterator();
: Collections.<String>emptyList(); for (ChangeData cd ; cdit.hasNext(); cdit.remove()) {
Iterator<ChangeData> cdit = cds.iterator(); cd = cdit.next();
for (ChangeData cd ; cdit.hasNext(); cdit.remove()) { try {
cd = cdit.next(); cd.setCurrentFilePaths(paths);
try { indexer.index(cd);
cd.setCurrentFilePaths(paths); done.update(1);
indexer.index(cd); if (verboseWriter != null) {
done.update(1); verboseWriter.println("Reindexed change " + cd.getId());
if (verboseWriter != null) {
verboseWriter.println("Reindexed change " + cd.getId());
}
} catch (Exception e) {
fail("Failed to index change " + cd.getId(), true, e);
} }
} catch (Exception e) {
fail("Failed to index change " + cd.getId(), true, e);
} }
} }
} finally {
df.release();
} }
} catch (Exception e) { } catch (Exception e) {
fail("Failed to index commit " + b.name(), false, e); fail("Failed to index commit " + b.name(), false, e);
@ -396,13 +391,10 @@ public class SiteIndexer {
} }
private ObjectId emptyTree() throws IOException { private ObjectId emptyTree() throws IOException {
ObjectInserter oi = repo.newObjectInserter(); try (ObjectInserter oi = repo.newObjectInserter()) {
try {
ObjectId id = oi.insert(Constants.OBJ_TREE, new byte[] {}); ObjectId id = oi.insert(Constants.OBJ_TREE, new byte[] {});
oi.flush(); oi.flush();
return id; return id;
} finally {
oi.release();
} }
} }

View File

@ -396,28 +396,28 @@ public abstract class ChangeEmail extends NotificationEmail {
TemporaryBuffer.Heap buf = TemporaryBuffer.Heap buf =
new TemporaryBuffer.Heap(args.settings.maximumDiffSize); new TemporaryBuffer.Heap(args.settings.maximumDiffSize);
DiffFormatter fmt = new DiffFormatter(buf); try (DiffFormatter fmt = new DiffFormatter(buf)) {
Repository git; Repository git;
try { try {
git = args.server.openRepository(change.getProject()); git = args.server.openRepository(change.getProject());
} catch (IOException e) { } catch (IOException e) {
log.error("Cannot open repository to format patch", e); log.error("Cannot open repository to format patch", e);
return "";
}
try {
fmt.setRepository(git);
fmt.setDetectRenames(true);
fmt.format(patchList.getOldId(), patchList.getNewId());
return RawParseUtils.decode(buf.toByteArray());
} catch (IOException e) {
if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) {
return ""; return "";
} }
log.error("Cannot format patch", e); try {
return ""; fmt.setRepository(git);
} finally { fmt.setDetectRenames(true);
fmt.release(); fmt.format(patchList.getOldId(), patchList.getNewId());
git.close(); return RawParseUtils.decode(buf.toByteArray());
} catch (IOException e) {
if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) {
return "";
}
log.error("Cannot format patch", e);
return "";
} finally {
git.close();
}
} }
} }
} }

View File

@ -82,15 +82,11 @@ public class PatchSetNotificationSender {
final Change updatedChange, final PatchSet updatedPatchSet, final Change updatedChange, final PatchSet updatedPatchSet,
final LabelTypes labelTypes) final LabelTypes labelTypes)
throws OrmException, IOException { throws OrmException, IOException {
final Repository git = repoManager.openRepository(updatedChange.getProject()); try (Repository git = repoManager.openRepository(updatedChange.getProject())) {
try {
final RevWalk revWalk = new RevWalk(git);
final RevCommit commit; final RevCommit commit;
try { try (RevWalk revWalk = new RevWalk(git)) {
commit = revWalk.parseCommit(ObjectId.fromString( commit = revWalk.parseCommit(ObjectId.fromString(
updatedPatchSet.getRevision().get())); updatedPatchSet.getRevision().get()));
} finally {
revWalk.release();
} }
final PatchSetInfo info = patchSetInfoFactory.get(commit, updatedPatchSet.getId()); final PatchSetInfo info = patchSetInfoFactory.get(commit, updatedPatchSet.getId());
final List<FooterLine> footerLines = commit.getFooterLines(); final List<FooterLine> footerLines = commit.getFooterLines();
@ -134,8 +130,6 @@ public class PatchSetNotificationSender {
log.error("Cannot send email for new patch set " + updatedPatchSet.getId(), e); log.error("Cannot send email for new patch set " + updatedPatchSet.getId(), e);
} }
} }
} finally {
git.close();
} }
} }
} }

View File

@ -272,9 +272,9 @@ public class ChangeNotes extends AbstractChangeNotes<ChangeNotes> {
loadDefaults(); loadDefaults();
return; return;
} }
RevWalk walk = new RevWalk(reader); try (RevWalk walk = new RevWalk(reader);
try (ChangeNotesParser parser = ChangeNotesParser parser =
new ChangeNotesParser(change, rev, walk, repoManager)) { new ChangeNotesParser(change, rev, walk, repoManager)) {
parser.parseAll(); parser.parseAll();
if (parser.status != null) { if (parser.status != null) {
@ -301,8 +301,6 @@ public class ChangeNotes extends AbstractChangeNotes<ChangeNotes> {
this.allPastReviewers = ImmutableList.copyOf(parser.allPastReviewers); this.allPastReviewers = ImmutableList.copyOf(parser.allPastReviewers);
submitRecords = ImmutableList.copyOf(parser.submitRecords); submitRecords = ImmutableList.copyOf(parser.submitRecords);
} finally {
walk.release();
} }
} }

View File

@ -200,12 +200,9 @@ public class ChangeRebuilder {
private void writeToBatch(BatchMetaDataUpdate batch, private void writeToBatch(BatchMetaDataUpdate batch,
AbstractChangeUpdate update, Repository repo) throws IOException, AbstractChangeUpdate update, Repository repo) throws IOException,
OrmException { OrmException {
ObjectInserter inserter = repo.newObjectInserter(); try (ObjectInserter inserter = repo.newObjectInserter()) {
try {
update.setInserter(inserter); update.setInserter(inserter);
update.writeCommit(batch); update.writeCommit(batch);
} finally {
inserter.release();
} }
} }

View File

@ -132,16 +132,14 @@ public class DraftCommentNotes extends AbstractChangeNotes<DraftCommentNotes> {
return; return;
} }
RevWalk walk = new RevWalk(reader); try (RevWalk walk = new RevWalk(reader);
try (DraftCommentNotesParser parser = new DraftCommentNotesParser( DraftCommentNotesParser parser = new DraftCommentNotesParser(
getChangeId(), walk, rev, repoManager, draftsProject, author)) { getChangeId(), walk, rev, repoManager, draftsProject, author)) {
parser.parseDraftComments(); parser.parseDraftComments();
buildCommentTable(draftBaseComments, parser.draftBaseComments); buildCommentTable(draftBaseComments, parser.draftBaseComments);
buildCommentTable(draftPsComments, parser.draftPsComments); buildCommentTable(draftPsComments, parser.draftPsComments);
noteMap = parser.noteMap; noteMap = parser.noteMap;
} finally {
walk.release();
} }
} }

View File

@ -48,9 +48,8 @@ public class PatchFile {
this.repo = repo; this.repo = repo;
this.entry = patchList.get(fileName); this.entry = patchList.get(fileName);
final ObjectReader reader = repo.newObjectReader(); try (ObjectReader reader = repo.newObjectReader();
try { RevWalk rw = new RevWalk(reader)) {
final RevWalk rw = new RevWalk(reader);
final RevCommit bCommit = rw.parseCommit(patchList.getNewId()); final RevCommit bCommit = rw.parseCommit(patchList.getNewId());
if (Patch.COMMIT_MSG.equals(fileName)) { if (Patch.COMMIT_MSG.equals(fileName)) {
@ -74,8 +73,6 @@ public class PatchFile {
} }
bTree = bCommit.getTree(); bTree = bCommit.getTree();
} }
} finally {
reader.release();
} }
} }

View File

@ -116,9 +116,9 @@ public class PatchListLoader extends CacheLoader<PatchListKey, PatchList> {
private PatchList readPatchList(final PatchListKey key, final Repository repo) private PatchList readPatchList(final PatchListKey key, final Repository repo)
throws IOException, PatchListNotAvailableException { throws IOException, PatchListNotAvailableException {
final RawTextComparator cmp = comparatorFor(key.getWhitespace()); final RawTextComparator cmp = comparatorFor(key.getWhitespace());
final ObjectReader reader = repo.newObjectReader(); try (ObjectReader reader = repo.newObjectReader();
try { RevWalk rw = new RevWalk(reader);
final RevWalk rw = new RevWalk(reader); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE)) {
final RevCommit b = rw.parseCommit(key.getNewId()); final RevCommit b = rw.parseCommit(key.getNewId());
final RevObject a = aFor(key, repo, rw, b); final RevObject a = aFor(key, repo, rw, b);
@ -138,7 +138,6 @@ public class PatchListLoader extends CacheLoader<PatchListKey, PatchList> {
RevTree aTree = rw.parseTree(a); RevTree aTree = rw.parseTree(a);
RevTree bTree = b.getTree(); RevTree bTree = b.getTree();
DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
df.setRepository(repo); df.setRepository(repo);
df.setDiffComparator(cmp); df.setDiffComparator(cmp);
df.setDetectRenames(true); df.setDetectRenames(true);
@ -170,8 +169,6 @@ public class PatchListLoader extends CacheLoader<PatchListKey, PatchList> {
} }
return new PatchList(a, b, againstParent, return new PatchList(a, b, againstParent,
entries.toArray(new PatchListEntry[entries.size()])); entries.toArray(new PatchListEntry[entries.size()]));
} finally {
reader.release();
} }
} }
@ -271,8 +268,7 @@ public class PatchListLoader extends CacheLoader<PatchListKey, PatchList> {
} }
ResolveMerger m = (ResolveMerger) mergeStrategy.newMerger(repo, true); ResolveMerger m = (ResolveMerger) mergeStrategy.newMerger(repo, true);
final ObjectInserter ins = repo.newObjectInserter(); try (ObjectInserter ins = repo.newObjectInserter()) {
try {
DirCache dc = DirCache.newInCore(); DirCache dc = DirCache.newInCore();
m.setDirCache(dc); m.setDirCache(dc);
m.setObjectInserter(new ObjectInserter.Filter() { m.setObjectInserter(new ObjectInserter.Filter() {
@ -397,19 +393,14 @@ public class PatchListLoader extends CacheLoader<PatchListKey, PatchList> {
} }
return rw.lookupTree(treeId); return rw.lookupTree(treeId);
} finally {
ins.release();
} }
} }
private static ObjectId emptyTree(final Repository repo) throws IOException { private static ObjectId emptyTree(final Repository repo) throws IOException {
ObjectInserter oi = repo.newObjectInserter(); try (ObjectInserter oi = repo.newObjectInserter()) {
try {
ObjectId id = oi.insert(Constants.OBJ_TREE, new byte[] {}); ObjectId id = oi.insert(Constants.OBJ_TREE, new byte[] {});
oi.flush(); oi.flush();
return id; return id;
} finally {
oi.release();
} }
} }
} }

View File

@ -119,7 +119,7 @@ class PatchScriptBuilder {
try { try {
return build(content, comments, history); return build(content, comments, history);
} finally { } finally {
reader.release(); reader.close();
} }
} }
@ -514,9 +514,10 @@ class PatchScriptBuilder {
if (path == null || within == null) { if (path == null || within == null) {
return null; return null;
} }
final RevWalk rw = new RevWalk(reader); try (RevWalk rw = new RevWalk(reader)) {
final RevTree tree = rw.parseTree(within); final RevTree tree = rw.parseTree(within);
return TreeWalk.forPath(reader, path, tree); return TreeWalk.forPath(reader, path, tree);
}
} }
} }

View File

@ -85,17 +85,12 @@ public class PatchSetInfoFactory {
} catch (IOException e) { } catch (IOException e) {
throw new PatchSetInfoNotAvailableException(e); throw new PatchSetInfoNotAvailableException(e);
} }
try { try (RevWalk rw = new RevWalk(repo)) {
final RevWalk rw = new RevWalk(repo); final RevCommit src =
try { rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get()));
final RevCommit src = PatchSetInfo info = get(src, patchSet.getId());
rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get())); info.setParents(toParentInfos(src.getParents(), rw));
PatchSetInfo info = get(src, patchSet.getId()); return info;
info.setParents(toParentInfos(src.getParents(), rw));
return info;
} finally {
rw.release();
}
} catch (IOException e) { } catch (IOException e) {
throw new PatchSetInfoNotAvailableException(e); throw new PatchSetInfoNotAvailableException(e);
} finally { } finally {

View File

@ -44,44 +44,45 @@ public class Text extends RawText {
public static final Text EMPTY = new Text(NO_BYTES); public static final Text EMPTY = new Text(NO_BYTES);
public static Text forCommit(ObjectReader reader, AnyObjectId commitId) throws IOException { public static Text forCommit(ObjectReader reader, AnyObjectId commitId) throws IOException {
RevWalk rw = new RevWalk(reader); try (RevWalk rw = new RevWalk(reader)) {
RevCommit c; RevCommit c;
if (commitId instanceof RevCommit) { if (commitId instanceof RevCommit) {
c = (RevCommit) commitId; c = (RevCommit) commitId;
} else { } else {
c = rw.parseCommit(commitId); c = rw.parseCommit(commitId);
}
StringBuilder b = new StringBuilder();
switch (c.getParentCount()) {
case 0:
break;
case 1: {
RevCommit p = c.getParent(0);
rw.parseBody(p);
b.append("Parent: ");
b.append(reader.abbreviate(p, 8).name());
b.append(" (");
b.append(p.getShortMessage());
b.append(")\n");
break;
} }
default:
for (int i = 0; i < c.getParentCount(); i++) { StringBuilder b = new StringBuilder();
RevCommit p = c.getParent(i); switch (c.getParentCount()) {
case 0:
break;
case 1: {
RevCommit p = c.getParent(0);
rw.parseBody(p); rw.parseBody(p);
b.append(i == 0 ? "Merge Of: " : " "); b.append("Parent: ");
b.append(reader.abbreviate(p, 8).name()); b.append(reader.abbreviate(p, 8).name());
b.append(" ("); b.append(" (");
b.append(p.getShortMessage()); b.append(p.getShortMessage());
b.append(")\n"); b.append(")\n");
break;
} }
default:
for (int i = 0; i < c.getParentCount(); i++) {
RevCommit p = c.getParent(i);
rw.parseBody(p);
b.append(i == 0 ? "Merge Of: " : " ");
b.append(reader.abbreviate(p, 8).name());
b.append(" (");
b.append(p.getShortMessage());
b.append(")\n");
}
}
appendPersonIdent(b, "Author", c.getAuthorIdent());
appendPersonIdent(b, "Commit", c.getCommitterIdent());
b.append("\n");
b.append(c.getFullMessage());
return new Text(b.toString().getBytes("UTF-8"));
} }
appendPersonIdent(b, "Author", c.getAuthorIdent());
appendPersonIdent(b, "Commit", c.getCommitterIdent());
b.append("\n");
b.append(c.getFullMessage());
return new Text(b.toString().getBytes("UTF-8"));
} }
private static void appendPersonIdent(StringBuilder b, String field, private static void appendPersonIdent(StringBuilder b, String field,

View File

@ -65,26 +65,19 @@ public class CommitsCollection implements
throw new ResourceNotFoundException(id); throw new ResourceNotFoundException(id);
} }
Repository repo = repoManager.openRepository(parent.getNameKey()); try (Repository repo = repoManager.openRepository(parent.getNameKey());
try { RevWalk rw = new RevWalk(repo)) {
RevWalk rw = new RevWalk(repo); RevCommit commit = rw.parseCommit(objectId);
try { rw.parseBody(commit);
RevCommit commit = rw.parseCommit(objectId); if (!parent.getControl().canReadCommit(db.get(), rw, commit)) {
rw.parseBody(commit);
if (!parent.getControl().canReadCommit(db.get(), rw, commit)) {
throw new ResourceNotFoundException(id);
}
for (int i = 0; i < commit.getParentCount(); i++) {
rw.parseBody(rw.parseCommit(commit.getParent(i)));
}
return new CommitResource(parent, commit);
} catch (MissingObjectException | IncorrectObjectTypeException e) {
throw new ResourceNotFoundException(id); throw new ResourceNotFoundException(id);
} finally {
rw.release();
} }
} finally { for (int i = 0; i < commit.getParentCount(); i++) {
repo.close(); rw.parseBody(rw.parseCommit(commit.getParent(i)));
}
return new CommitResource(parent, commit);
} catch (MissingObjectException | IncorrectObjectTypeException e) {
throw new ResourceNotFoundException(id);
} }
} }

View File

@ -99,11 +99,8 @@ class DeleteBranches implements RestModifyView<ProjectResource, Input> {
for (String branch : input.branches) { for (String branch : input.branches) {
batchUpdate.addCommand(createDeleteCommand(project, r, branch)); batchUpdate.addCommand(createDeleteCommand(project, r, branch));
} }
RevWalk rw = new RevWalk(r); try (RevWalk rw = new RevWalk(r)) {
try {
batchUpdate.execute(rw, NullProgressMonitor.INSTANCE); batchUpdate.execute(rw, NullProgressMonitor.INSTANCE);
} finally {
rw.release();
} }
StringBuilder errorMessages = new StringBuilder(); StringBuilder errorMessages = new StringBuilder();
for (ReceiveCommand command : batchUpdate.getCommands()) { for (ReceiveCommand command : batchUpdate.getCommands()) {

View File

@ -49,9 +49,7 @@ public class GetHead implements RestReadView<ProjectResource> {
@Override @Override
public String apply(ProjectResource rsrc) throws AuthException, public String apply(ProjectResource rsrc) throws AuthException,
ResourceNotFoundException, IOException { ResourceNotFoundException, IOException {
Repository repo = null; try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
try {
repo = repoManager.openRepository(rsrc.getNameKey());
Ref head = repo.getRef(Constants.HEAD); Ref head = repo.getRef(Constants.HEAD);
if (head == null) { if (head == null) {
throw new ResourceNotFoundException(Constants.HEAD); throw new ResourceNotFoundException(Constants.HEAD);
@ -62,8 +60,7 @@ public class GetHead implements RestReadView<ProjectResource> {
} }
throw new AuthException("not allowed to see HEAD"); throw new AuthException("not allowed to see HEAD");
} else if (head.getObjectId() != null) { } else if (head.getObjectId() != null) {
RevWalk rw = new RevWalk(repo); try (RevWalk rw = new RevWalk(repo)) {
try {
RevCommit commit = rw.parseCommit(head.getObjectId()); RevCommit commit = rw.parseCommit(head.getObjectId());
if (rsrc.getControl().canReadCommit(db.get(), rw, commit)) { if (rsrc.getControl().canReadCommit(db.get(), rw, commit)) {
return head.getObjectId().name(); return head.getObjectId().name();
@ -74,17 +71,11 @@ public class GetHead implements RestReadView<ProjectResource> {
return head.getObjectId().name(); return head.getObjectId().name();
} }
throw new AuthException("not allowed to see HEAD"); throw new AuthException("not allowed to see HEAD");
} finally {
rw.release();
} }
} }
throw new ResourceNotFoundException(Constants.HEAD); throw new ResourceNotFoundException(Constants.HEAD);
} catch (RepositoryNotFoundException e) { } catch (RepositoryNotFoundException e) {
throw new ResourceNotFoundException(rsrc.getName()); throw new ResourceNotFoundException(rsrc.getName());
} finally {
if (repo != null) {
repo.close();
}
} }
} }
} }

View File

@ -82,53 +82,45 @@ class ListDashboards implements RestReadView<ProjectResource> {
private List<DashboardInfo> scan(ProjectControl ctl, String project, private List<DashboardInfo> scan(ProjectControl ctl, String project,
boolean setDefault) throws ResourceNotFoundException, IOException { boolean setDefault) throws ResourceNotFoundException, IOException {
Repository git; Project.NameKey projectName = ctl.getProject().getNameKey();
try { try (Repository git = gitManager.openRepository(projectName);
git = gitManager.openRepository(ctl.getProject().getNameKey()); RevWalk rw = new RevWalk(git)) {
List<DashboardInfo> all = Lists.newArrayList();
for (Ref ref : git.getRefDatabase().getRefs(REFS_DASHBOARDS).values()) {
if (ctl.controlForRef(ref.getName()).canRead()) {
all.addAll(scanDashboards(ctl.getProject(), git, rw, ref,
project, setDefault));
}
}
return all;
} catch (RepositoryNotFoundException e) { } catch (RepositoryNotFoundException e) {
throw new ResourceNotFoundException(); throw new ResourceNotFoundException();
} }
try {
RevWalk rw = new RevWalk(git);
try {
List<DashboardInfo> all = Lists.newArrayList();
for (Ref ref : git.getRefDatabase().getRefs(REFS_DASHBOARDS).values()) {
if (ctl.controlForRef(ref.getName()).canRead()) {
all.addAll(scanDashboards(ctl.getProject(), git, rw, ref,
project, setDefault));
}
}
return all;
} finally {
rw.release();
}
} finally {
git.close();
}
} }
private List<DashboardInfo> scanDashboards(Project definingProject, private List<DashboardInfo> scanDashboards(Project definingProject,
Repository git, RevWalk rw, Ref ref, String project, boolean setDefault) Repository git, RevWalk rw, Ref ref, String project, boolean setDefault)
throws IOException { throws IOException {
List<DashboardInfo> list = Lists.newArrayList(); List<DashboardInfo> list = Lists.newArrayList();
TreeWalk tw = new TreeWalk(rw.getObjectReader()); try (TreeWalk tw = new TreeWalk(rw.getObjectReader())) {
tw.addTree(rw.parseTree(ref.getObjectId())); tw.addTree(rw.parseTree(ref.getObjectId()));
tw.setRecursive(true); tw.setRecursive(true);
while (tw.next()) { while (tw.next()) {
if (tw.getFileMode(0) == FileMode.REGULAR_FILE) { if (tw.getFileMode(0) == FileMode.REGULAR_FILE) {
try { try {
list.add(DashboardsCollection.parse( list.add(DashboardsCollection.parse(
definingProject, definingProject,
ref.getName().substring(REFS_DASHBOARDS.length()), ref.getName().substring(REFS_DASHBOARDS.length()),
tw.getPathString(), tw.getPathString(),
new BlobBasedConfig(null, git, tw.getObjectId(0)), new BlobBasedConfig(null, git, tw.getObjectId(0)),
project, project,
setDefault)); setDefault));
} catch (ConfigInvalidException e) { } catch (ConfigInvalidException e) {
log.warn(String.format( log.warn(String.format(
"Cannot parse dashboard %s:%s:%s: %s", "Cannot parse dashboard %s:%s:%s: %s",
definingProject.getName(), ref.getName(), tw.getPathString(), definingProject.getName(), ref.getName(), tw.getPathString(),
e.getMessage())); e.getMessage()));
}
} }
} }
} }

View File

@ -98,26 +98,17 @@ public class ListTags implements RestReadView<ProjectResource> {
public TagInfo get(ProjectResource resource, IdString id) public TagInfo get(ProjectResource resource, IdString id)
throws ResourceNotFoundException, IOException { throws ResourceNotFoundException, IOException {
Repository repo = getRepository(resource.getNameKey()); try (Repository repo = getRepository(resource.getNameKey());
RevWalk rw = new RevWalk(repo)) {
String tagName = id.get(); String tagName = id.get();
if (!tagName.startsWith(Constants.R_TAGS)) { if (!tagName.startsWith(Constants.R_TAGS)) {
tagName = Constants.R_TAGS + tagName; tagName = Constants.R_TAGS + tagName;
} }
Ref ref = repo.getRefDatabase().getRef(tagName);
try { if (ref != null && !visibleTags(resource.getControl(), repo,
RevWalk rw = new RevWalk(repo); ImmutableMap.of(ref.getName(), ref)).isEmpty()) {
try { return createTagInfo(ref, rw);
Ref ref = repo.getRefDatabase().getRef(tagName);
if (ref != null && !visibleTags(resource.getControl(), repo,
ImmutableMap.of(ref.getName(), ref)).isEmpty()) {
return createTagInfo(ref, rw);
}
} finally {
rw.dispose();
} }
} finally {
repo.close();
} }
throw new ResourceNotFoundException(id); throw new ResourceNotFoundException(id);
} }

View File

@ -270,8 +270,7 @@ public class PerformCreateProject {
private void createEmptyCommits(final Repository repo, private void createEmptyCommits(final Repository repo,
final Project.NameKey project, final List<String> refs) final Project.NameKey project, final List<String> refs)
throws IOException { throws IOException {
ObjectInserter oi = repo.newObjectInserter(); try (ObjectInserter oi = repo.newObjectInserter()) {
try {
CommitBuilder cb = new CommitBuilder(); CommitBuilder cb = new CommitBuilder();
cb.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {})); cb.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {}));
cb.setAuthor(metaDataUpdateFactory.getUserPersonIdent()); cb.setAuthor(metaDataUpdateFactory.getUserPersonIdent());
@ -300,8 +299,6 @@ public class PerformCreateProject {
"Cannot create empty commit for " "Cannot create empty commit for "
+ createProjectArgs.getProjectName(), e); + createProjectArgs.getProjectName(), e);
throw e; throw e;
} finally {
oi.release();
} }
} }
} }

View File

@ -523,18 +523,11 @@ public class ChangeData {
return false; return false;
} }
String sha1 = ps.getRevision().get(); String sha1 = ps.getRevision().get();
Repository repo = repoManager.openRepository(change().getProject()); try (Repository repo = repoManager.openRepository(change().getProject());
try { RevWalk walk = new RevWalk(repo)) {
RevWalk walk = new RevWalk(repo); RevCommit c = walk.parseCommit(ObjectId.fromString(sha1));
try { commitMessage = c.getFullMessage();
RevCommit c = walk.parseCommit(ObjectId.fromString(sha1)); commitFooters = c.getFooterLines();
commitMessage = c.getFullMessage();
commitFooters = c.getFooterLines();
} finally {
walk.release();
}
} finally {
repo.close();
} }
return true; return true;
} }

View File

@ -107,37 +107,24 @@ class ConflictsPredicate extends OrPredicate<ChangeData> {
if (conflicts != null) { if (conflicts != null) {
return conflicts; return conflicts;
} }
try { try (Repository repo =
Repository repo =
args.repoManager.openRepository(otherChange.getProject()); args.repoManager.openRepository(otherChange.getProject());
try { RevWalk rw = CodeReviewCommit.newRevWalk(repo)) {
RevWalk rw = CodeReviewCommit.newRevWalk(repo); RevFlag canMergeFlag = rw.newFlag("CAN_MERGE");
try { CodeReviewCommit commit =
RevFlag canMergeFlag = rw.newFlag("CAN_MERGE"); (CodeReviewCommit) rw.parseCommit(changeDataCache.getTestAgainst());
CodeReviewCommit commit = SubmitStrategy strategy =
(CodeReviewCommit) rw.parseCommit(changeDataCache.getTestAgainst()); args.submitStrategyFactory.create(submitType,
SubmitStrategy strategy = db.get(), repo, rw, null, canMergeFlag,
args.submitStrategyFactory.create(submitType, getAlreadyAccepted(repo, rw, commit),
db.get(), repo, rw, null, canMergeFlag, otherChange.getDest());
getAlreadyAccepted(repo, rw, commit), CodeReviewCommit otherCommit =
otherChange.getDest()); (CodeReviewCommit) rw.parseCommit(other);
CodeReviewCommit otherCommit = otherCommit.add(canMergeFlag);
(CodeReviewCommit) rw.parseCommit(other); conflicts = !strategy.dryRun(commit, otherCommit);
otherCommit.add(canMergeFlag); args.conflictsCache.put(conflictsKey, conflicts);
conflicts = !strategy.dryRun(commit, otherCommit); return conflicts;
args.conflictsCache.put(conflictsKey, conflicts); } catch (MergeException | NoSuchProjectException | IOException e) {
return conflicts;
} catch (MergeException e) {
throw new IllegalStateException(e);
} catch (NoSuchProjectException e) {
throw new IllegalStateException(e);
} finally {
rw.release();
}
} finally {
repo.close();
}
} catch (IOException e) {
throw new IllegalStateException(e); throw new IllegalStateException(e);
} }
} }

View File

@ -102,18 +102,9 @@ public abstract class RevWalkPredicate extends OperatorPredicate<ChangeData> {
Arguments args = new Arguments(patchSet, revision, objectId, change, projectName); Arguments args = new Arguments(patchSet, revision, objectId, change, projectName);
try { try (Repository repo = repoManager.openRepository(projectName);
final Repository repo = repoManager.openRepository(projectName); RevWalk rw = new RevWalk(repo)) {
try { return match(repo, rw, args);
final RevWalk rw = new RevWalk(repo);
try {
return match(repo, rw, args);
} finally {
rw.release();
}
} finally {
repo.close();
}
} catch (RepositoryNotFoundException e) { } catch (RepositoryNotFoundException e) {
log.error("Repository \"" + projectName.get() + "\" unknown.", e); log.error("Repository \"" + projectName.get() + "\" unknown.", e);
} catch (IOException e) { } catch (IOException e) {

View File

@ -73,11 +73,10 @@ public class PRED_commit_edits_2 extends Predicate.P2 {
PatchList pl = StoredValues.PATCH_LIST.get(engine); PatchList pl = StoredValues.PATCH_LIST.get(engine);
Repository repo = StoredValues.REPOSITORY.get(engine); Repository repo = StoredValues.REPOSITORY.get(engine);
final ObjectReader reader = repo.newObjectReader(); try (ObjectReader reader = repo.newObjectReader();
final RevTree aTree; RevWalk rw = new RevWalk(reader)) {
final RevTree bTree; final RevTree aTree;
try { final RevTree bTree;
final RevWalk rw = new RevWalk(reader);
final RevCommit bCommit = rw.parseCommit(pl.getNewId()); final RevCommit bCommit = rw.parseCommit(pl.getNewId());
if (pl.getOldId() != null) { if (pl.getOldId() != null) {
@ -129,8 +128,6 @@ public class PRED_commit_edits_2 extends Predicate.P2 {
} }
} catch (IOException err) { } catch (IOException err) {
throw new JavaException(this, 1, err); throw new JavaException(this, 1, err);
} finally {
reader.release();
} }
return engine.fail(); return engine.fail();
@ -161,4 +158,4 @@ public class PRED_commit_edits_2 extends Predicate.P2 {
} }
return new Text(reader.open(tw.getObjectId(0), Constants.OBJ_BLOB)); return new Text(reader.open(tw.getObjectId(0), Constants.OBJ_BLOB));
} }
} }

View File

@ -86,6 +86,8 @@ public class IncludedInResolverTest extends RepositoryTestCase {
*/ */
// TODO(dborowitz): Use try/finally when this doesn't double-close the repo.
@SuppressWarnings("resource")
Git git = new Git(db); Git git = new Git(db);
revWalk = new RevWalk(db); revWalk = new RevWalk(db);
// Version 1.0 // Version 1.0
@ -129,7 +131,7 @@ public class IncludedInResolverTest extends RepositoryTestCase {
@Override @Override
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
revWalk.release(); revWalk.close();
super.tearDown(); super.tearDown();
} }

View File

@ -118,34 +118,37 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
public void testEmptyCommit() throws Exception { public void testEmptyCommit() throws Exception {
expect(schemaFactory.open()).andReturn(schema); expect(schemaFactory.open()).andReturn(schema);
final Repository realDb = createWorkRepository(); try (Repository realDb = createWorkRepository()) {
final Git git = new Git(realDb); // TODO(dborowitz): Use try/finally when this doesn't double-close the repo.
@SuppressWarnings("resource")
final Git git = new Git(realDb);
final RevCommit mergeTip = git.commit().setMessage("test").call(); final RevCommit mergeTip = git.commit().setMessage("test").call();
final Branch.NameKey branchNameKey = final Branch.NameKey branchNameKey =
new Branch.NameKey(new Project.NameKey("test-project"), "test-branch"); new Branch.NameKey(new Project.NameKey("test-project"), "test-branch");
expect(urlProvider.get()).andReturn("http://localhost:8080"); expect(urlProvider.get()).andReturn("http://localhost:8080");
expect(schema.submoduleSubscriptions()).andReturn(subscriptions); expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
final ResultSet<SubmoduleSubscription> emptySubscriptions = final ResultSet<SubmoduleSubscription> emptySubscriptions =
new ListResultSet<>(new ArrayList<SubmoduleSubscription>()); new ListResultSet<>(new ArrayList<SubmoduleSubscription>());
expect(subscriptions.bySubmodule(branchNameKey)).andReturn( expect(subscriptions.bySubmodule(branchNameKey)).andReturn(
emptySubscriptions); emptySubscriptions);
schema.close(); schema.close();
doReplay(); doReplay();
final SubmoduleOp submoduleOp = final SubmoduleOp submoduleOp =
new SubmoduleOp(branchNameKey, mergeTip, new RevWalk(realDb), urlProvider, new SubmoduleOp(branchNameKey, mergeTip, new RevWalk(realDb), urlProvider,
schemaFactory, realDb, null, new ArrayList<Change>(), null, null, schemaFactory, realDb, null, new ArrayList<Change>(), null, null,
null, null, null, null); null, null, null, null);
submoduleOp.update(); submoduleOp.update();
doVerify(); doVerify();
}
} }
/** /**
@ -588,85 +591,89 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
public void testOneSubscriberToUpdate() throws Exception { public void testOneSubscriberToUpdate() throws Exception {
expect(schemaFactory.open()).andReturn(schema); expect(schemaFactory.open()).andReturn(schema);
final Repository sourceRepository = createWorkRepository(); try (Repository sourceRepository = createWorkRepository();
final Git sourceGit = new Git(sourceRepository); Repository targetRepository = createWorkRepository()) {
// TODO(dborowitz): Use try/finally when this doesn't double-close the repo.
@SuppressWarnings("resource")
final Git sourceGit = new Git(sourceRepository);
// TODO(dborowitz): Use try/finally when this doesn't double-close the repo.
@SuppressWarnings("resource")
final Git targetGit = new Git(targetRepository);
addRegularFileToIndex("file.txt", "test content", sourceRepository); addRegularFileToIndex("file.txt", "test content", sourceRepository);
final RevCommit sourceMergeTip = final RevCommit sourceMergeTip =
sourceGit.commit().setMessage("test").call(); sourceGit.commit().setMessage("test").call();
final Branch.NameKey sourceBranchNameKey = final Branch.NameKey sourceBranchNameKey =
new Branch.NameKey(new Project.NameKey("source-project"), new Branch.NameKey(new Project.NameKey("source-project"),
"refs/heads/master"); "refs/heads/master");
final CodeReviewCommit codeReviewCommit = final CodeReviewCommit codeReviewCommit =
new CodeReviewCommit(sourceMergeTip.toObjectId()); new CodeReviewCommit(sourceMergeTip.toObjectId());
final Change submittedChange = new Change( final Change submittedChange = new Change(
new Change.Key(sourceMergeTip.toObjectId().getName()), new Change.Id(1), new Change.Key(sourceMergeTip.toObjectId().getName()), new Change.Id(1),
new Account.Id(1), sourceBranchNameKey, TimeUtil.nowTs()); new Account.Id(1), sourceBranchNameKey, TimeUtil.nowTs());
final Map<Change.Id, CodeReviewCommit> mergedCommits = new HashMap<>(); final Map<Change.Id, CodeReviewCommit> mergedCommits = new HashMap<>();
mergedCommits.put(submittedChange.getId(), codeReviewCommit); mergedCommits.put(submittedChange.getId(), codeReviewCommit);
final List<Change> submitted = new ArrayList<>(); final List<Change> submitted = new ArrayList<>();
submitted.add(submittedChange); submitted.add(submittedChange);
final Repository targetRepository = createWorkRepository(); addGitLinkToIndex("a", sourceMergeTip.copy(), targetRepository);
final Git targetGit = new Git(targetRepository);
addGitLinkToIndex("a", sourceMergeTip.copy(), targetRepository); targetGit.commit().setMessage("test").call();
targetGit.commit().setMessage("test").call(); final Branch.NameKey targetBranchNameKey =
new Branch.NameKey(new Project.NameKey("target-project"),
sourceBranchNameKey.get());
final Branch.NameKey targetBranchNameKey = expect(urlProvider.get()).andReturn("http://localhost:8080");
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(schema.submoduleSubscriptions()).andReturn(subscriptions); expect(repoManager.openRepository(targetBranchNameKey.getParentKey()))
final ResultSet<SubmoduleSubscription> subscribers = .andReturn(targetRepository).anyTimes();
new ListResultSet<>(Collections
.singletonList(new SubmoduleSubscription(targetBranchNameKey,
sourceBranchNameKey, "source-project")));
expect(subscriptions.bySubmodule(sourceBranchNameKey)).andReturn(
subscribers);
expect(repoManager.openRepository(targetBranchNameKey.getParentKey())) Capture<RefUpdate> ruCapture = new Capture<>();
.andReturn(targetRepository).anyTimes(); gitRefUpdated.fire(eq(targetBranchNameKey.getParentKey()),
capture(ruCapture));
changeHooks.doRefUpdatedHook(eq(targetBranchNameKey),
anyObject(RefUpdate.class), EasyMock.<Account>isNull());
Capture<RefUpdate> ruCapture = new Capture<>(); expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
gitRefUpdated.fire(eq(targetBranchNameKey.getParentKey()), final ResultSet<SubmoduleSubscription> emptySubscriptions =
capture(ruCapture)); new ListResultSet<>(new ArrayList<SubmoduleSubscription>());
changeHooks.doRefUpdatedHook(eq(targetBranchNameKey), expect(subscriptions.bySubmodule(targetBranchNameKey)).andReturn(
anyObject(RefUpdate.class), EasyMock.<Account>isNull()); emptySubscriptions);
expect(schema.submoduleSubscriptions()).andReturn(subscriptions); schema.close();
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");
final PersonIdent myIdent = doReplay();
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);
final SubmoduleOp submoduleOp = submoduleOp.update();
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();
doVerify(); assertEquals(ru.getName(), targetBranchNameKey.get());
RefUpdate ru = ruCapture.getValue(); }
assertEquals(ru.getName(), targetBranchNameKey.get());
} }
/** /**
@ -693,86 +700,90 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
public void testAvoidingCircularReference() throws Exception { public void testAvoidingCircularReference() throws Exception {
expect(schemaFactory.open()).andReturn(schema); expect(schemaFactory.open()).andReturn(schema);
final Repository sourceRepository = createWorkRepository(); try (Repository sourceRepository = createWorkRepository();
final Git sourceGit = new Git(sourceRepository); Repository targetRepository = createWorkRepository()) {
// TODO(dborowitz): Use try/finally when this doesn't double-close the repo.
@SuppressWarnings("resource")
final Git sourceGit = new Git(sourceRepository);
// TODO(dborowitz): Use try/finally when this doesn't double-close the repo.
@SuppressWarnings("resource")
final Git targetGit = new Git(targetRepository);
addRegularFileToIndex("file.txt", "test content", sourceRepository); addRegularFileToIndex("file.txt", "test content", sourceRepository);
final RevCommit sourceMergeTip = final RevCommit sourceMergeTip =
sourceGit.commit().setMessage("test").call(); sourceGit.commit().setMessage("test").call();
final Branch.NameKey sourceBranchNameKey = final Branch.NameKey sourceBranchNameKey =
new Branch.NameKey(new Project.NameKey("source-project"), new Branch.NameKey(new Project.NameKey("source-project"),
"refs/heads/master"); "refs/heads/master");
final CodeReviewCommit codeReviewCommit = final CodeReviewCommit codeReviewCommit =
new CodeReviewCommit(sourceMergeTip.toObjectId()); new CodeReviewCommit(sourceMergeTip.toObjectId());
final Change submittedChange = new Change( final Change submittedChange = new Change(
new Change.Key(sourceMergeTip.toObjectId().getName()), new Change.Id(1), new Change.Key(sourceMergeTip.toObjectId().getName()), new Change.Id(1),
new Account.Id(1), sourceBranchNameKey, TimeUtil.nowTs()); new Account.Id(1), sourceBranchNameKey, TimeUtil.nowTs());
final Map<Change.Id, CodeReviewCommit> mergedCommits = new HashMap<>(); final Map<Change.Id, CodeReviewCommit> mergedCommits = new HashMap<>();
mergedCommits.put(submittedChange.getId(), codeReviewCommit); mergedCommits.put(submittedChange.getId(), codeReviewCommit);
final List<Change> submitted = new ArrayList<>(); final List<Change> submitted = new ArrayList<>();
submitted.add(submittedChange); submitted.add(submittedChange);
final Repository targetRepository = createWorkRepository(); addGitLinkToIndex("a", sourceMergeTip.copy(), targetRepository);
final Git targetGit = new Git(targetRepository);
addGitLinkToIndex("a", sourceMergeTip.copy(), targetRepository); targetGit.commit().setMessage("test").call();
targetGit.commit().setMessage("test").call(); final Branch.NameKey targetBranchNameKey =
new Branch.NameKey(new Project.NameKey("target-project"),
sourceBranchNameKey.get());
final Branch.NameKey targetBranchNameKey = expect(urlProvider.get()).andReturn("http://localhost:8080");
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(schema.submoduleSubscriptions()).andReturn(subscriptions); expect(repoManager.openRepository(targetBranchNameKey.getParentKey()))
final ResultSet<SubmoduleSubscription> subscribers = .andReturn(targetRepository).anyTimes();
new ListResultSet<>(Collections
.singletonList(new SubmoduleSubscription(targetBranchNameKey,
sourceBranchNameKey, "source-project")));
expect(subscriptions.bySubmodule(sourceBranchNameKey)).andReturn(
subscribers);
expect(repoManager.openRepository(targetBranchNameKey.getParentKey())) Capture<RefUpdate> ruCapture = new Capture<>();
.andReturn(targetRepository).anyTimes(); gitRefUpdated.fire(eq(targetBranchNameKey.getParentKey()),
capture(ruCapture));
changeHooks.doRefUpdatedHook(eq(targetBranchNameKey),
anyObject(RefUpdate.class), EasyMock.<Account>isNull());
Capture<RefUpdate> ruCapture = new Capture<>(); expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
gitRefUpdated.fire(eq(targetBranchNameKey.getParentKey()), final ResultSet<SubmoduleSubscription> incorrectSubscriptions =
capture(ruCapture)); new ListResultSet<>(Collections
changeHooks.doRefUpdatedHook(eq(targetBranchNameKey), .singletonList(new SubmoduleSubscription(sourceBranchNameKey,
anyObject(RefUpdate.class), EasyMock.<Account>isNull()); targetBranchNameKey, "target-project")));
expect(subscriptions.bySubmodule(targetBranchNameKey)).andReturn(
incorrectSubscriptions);
expect(schema.submoduleSubscriptions()).andReturn(subscriptions); schema.close();
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");
final PersonIdent myIdent = doReplay();
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);
final SubmoduleOp submoduleOp = submoduleOp.update();
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();
doVerify(); assertEquals(ru.getName(), targetBranchNameKey.get());
RefUpdate ru = ruCapture.getValue(); }
assertEquals(ru.getName(), targetBranchNameKey.get());
} }
/** /**
@ -862,67 +873,70 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
final List<SubmoduleSubscription> previousSubscriptions) throws Exception { final List<SubmoduleSubscription> previousSubscriptions) throws Exception {
expect(schemaFactory.open()).andReturn(schema); expect(schemaFactory.open()).andReturn(schema);
final Repository realDb = createWorkRepository(); try (Repository realDb = createWorkRepository()) {
final Git git = new Git(realDb); // TODO(dborowitz): Use try/finally when this doesn't double-close the repo.
@SuppressWarnings("resource")
final Git git = new Git(realDb);
addRegularFileToIndex(".gitmodules", gitModulesFileContent, realDb); addRegularFileToIndex(".gitmodules", gitModulesFileContent, realDb);
final RevCommit mergeTip = git.commit().setMessage("test").call(); final RevCommit mergeTip = git.commit().setMessage("test").call();
expect(urlProvider.get()).andReturn("http://localhost:8080").times(2); expect(urlProvider.get()).andReturn("http://localhost:8080").times(2);
expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
expect(subscriptions.bySuperProject(mergedBranch)).andReturn(
new ListResultSet<>(previousSubscriptions));
SortedSet<Project.NameKey> existingProjects = new TreeSet<>();
for (SubmoduleSubscription extracted : extractedSubscriptions) {
existingProjects.add(extracted.getSubmodule().getParentKey());
}
for (int index = 0; index < extractedSubscriptions.size(); index++) {
expect(repoManager.list()).andReturn(existingProjects);
}
final Set<SubmoduleSubscription> alreadySubscribeds = new HashSet<>();
for (SubmoduleSubscription s : extractedSubscriptions) {
if (previousSubscriptions.contains(s)) {
alreadySubscribeds.add(s);
}
}
final Set<SubmoduleSubscription> subscriptionsToRemove =
new HashSet<>(previousSubscriptions);
final List<SubmoduleSubscription> subscriptionsToInsert =
new ArrayList<>(extractedSubscriptions);
subscriptionsToRemove.removeAll(subscriptionsToInsert);
subscriptionsToInsert.removeAll(alreadySubscribeds);
if (!subscriptionsToRemove.isEmpty()) {
expect(schema.submoduleSubscriptions()).andReturn(subscriptions); expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
subscriptions.delete(subscriptionsToRemove); expect(subscriptions.bySuperProject(mergedBranch)).andReturn(
new ListResultSet<>(previousSubscriptions));
SortedSet<Project.NameKey> existingProjects = new TreeSet<>();
for (SubmoduleSubscription extracted : extractedSubscriptions) {
existingProjects.add(extracted.getSubmodule().getParentKey());
}
for (int index = 0; index < extractedSubscriptions.size(); index++) {
expect(repoManager.list()).andReturn(existingProjects);
}
final Set<SubmoduleSubscription> alreadySubscribeds = new HashSet<>();
for (SubmoduleSubscription s : extractedSubscriptions) {
if (previousSubscriptions.contains(s)) {
alreadySubscribeds.add(s);
}
}
final Set<SubmoduleSubscription> subscriptionsToRemove =
new HashSet<>(previousSubscriptions);
final List<SubmoduleSubscription> subscriptionsToInsert =
new ArrayList<>(extractedSubscriptions);
subscriptionsToRemove.removeAll(subscriptionsToInsert);
subscriptionsToInsert.removeAll(alreadySubscribeds);
if (!subscriptionsToRemove.isEmpty()) {
expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
subscriptions.delete(subscriptionsToRemove);
}
expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
subscriptions.insert(subscriptionsToInsert);
expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
expect(subscriptions.bySubmodule(mergedBranch)).andReturn(
new ListResultSet<>(new ArrayList<SubmoduleSubscription>()));
schema.close();
doReplay();
final SubmoduleOp submoduleOp =
new SubmoduleOp(mergedBranch, mergeTip, new RevWalk(realDb),
urlProvider, schemaFactory, realDb, new Project(mergedBranch
.getParentKey()), new ArrayList<Change>(), null, null,
repoManager, null, null, null);
submoduleOp.update();
} }
expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
subscriptions.insert(subscriptionsToInsert);
expect(schema.submoduleSubscriptions()).andReturn(subscriptions);
expect(subscriptions.bySubmodule(mergedBranch)).andReturn(
new ListResultSet<>(new ArrayList<SubmoduleSubscription>()));
schema.close();
doReplay();
final SubmoduleOp submoduleOp =
new SubmoduleOp(mergedBranch, mergeTip, new RevWalk(realDb),
urlProvider, schemaFactory, realDb, new Project(mergedBranch
.getParentKey()), new ArrayList<Change>(), null, null,
repoManager, null, null, null);
submoduleOp.update();
} }
/** /**

View File

@ -43,7 +43,7 @@ public class ChangeNotesParserTest extends AbstractChangeNotesTest {
@After @After
public void tearDownTestRepo() throws Exception { public void tearDownTestRepo() throws Exception {
walk.release(); walk.close();
} }
@Test @Test
@ -176,8 +176,7 @@ public class ChangeNotesParserTest extends AbstractChangeNotesTest {
private RevCommit writeCommit(String body, PersonIdent author) private RevCommit writeCommit(String body, PersonIdent author)
throws Exception { throws Exception {
ObjectInserter ins = testRepo.getRepository().newObjectInserter(); try (ObjectInserter ins = testRepo.getRepository().newObjectInserter()) {
try {
CommitBuilder cb = new CommitBuilder(); CommitBuilder cb = new CommitBuilder();
cb.setAuthor(author); cb.setAuthor(author);
cb.setCommitter(new PersonIdent(serverIdent, author.getWhen())); cb.setCommitter(new PersonIdent(serverIdent, author.getWhen()));
@ -188,8 +187,6 @@ public class ChangeNotesParserTest extends AbstractChangeNotesTest {
RevCommit commit = walk.parseCommit(id); RevCommit commit = walk.parseCommit(id);
walk.parseBody(commit); walk.parseBody(commit);
return commit; return commit;
} finally {
ins.release();
} }
} }

View File

@ -348,13 +348,10 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
hashtags.add("tag2"); hashtags.add("tag2");
update.setHashtags(hashtags); update.setHashtags(hashtags);
update.commit(); update.commit();
RevWalk walk = new RevWalk(repo); try (RevWalk walk = new RevWalk(repo)) {
try {
RevCommit commit = walk.parseCommit(update.getRevision()); RevCommit commit = walk.parseCommit(update.getRevision());
walk.parseBody(commit); walk.parseBody(commit);
assertTrue(commit.getFullMessage().endsWith("Hashtags: tag1,tag2\n")); assertTrue(commit.getFullMessage().endsWith("Hashtags: tag1,tag2\n"));
} finally {
walk.release();
} }
} }
@ -433,8 +430,7 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
update2.putApproval("Code-Review", (short) 2); update2.putApproval("Code-Review", (short) 2);
update2.writeCommit(batch); update2.writeCommit(batch);
RevWalk rw = new RevWalk(repo); try (RevWalk rw = new RevWalk(repo)) {
try {
batch.commit(); batch.commit();
bru.execute(rw, NullProgressMonitor.INSTANCE); bru.execute(rw, NullProgressMonitor.INSTANCE);
@ -464,7 +460,6 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
notesWithApprovals.close(); notesWithApprovals.close();
} finally { } finally {
batch.close(); batch.close();
rw.release();
} }
} }
@ -506,11 +501,8 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
assertEquals(update1.getRefName(), cmds.get(0).getRefName()); assertEquals(update1.getRefName(), cmds.get(0).getRefName());
assertEquals(update2.getRefName(), cmds.get(1).getRefName()); assertEquals(update2.getRefName(), cmds.get(1).getRefName());
RevWalk rw = new RevWalk(repo); try (RevWalk rw = new RevWalk(repo)) {
try {
bru.execute(rw, NullProgressMonitor.INSTANCE); bru.execute(rw, NullProgressMonitor.INSTANCE);
} finally {
rw.release();
} }
assertEquals(ReceiveCommand.Result.OK, cmds.get(0).getResult()); assertEquals(ReceiveCommand.Result.OK, cmds.get(0).getResult());
@ -712,43 +704,44 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
ChangeNotes notes = newNotes(c); ChangeNotes notes = newNotes(c);
RevWalk walk = new RevWalk(repo); try (RevWalk walk = new RevWalk(repo)) {
ArrayList<Note> notesInTree = ArrayList<Note> notesInTree =
Lists.newArrayList(notes.getNoteMap().iterator()); Lists.newArrayList(notes.getNoteMap().iterator());
Note note = Iterables.getOnlyElement(notesInTree); Note note = Iterables.getOnlyElement(notesInTree);
byte[] bytes = byte[] bytes =
walk.getObjectReader().open( walk.getObjectReader().open(
note.getData(), Constants.OBJ_BLOB).getBytes(); note.getData(), Constants.OBJ_BLOB).getBytes();
String noteString = new String(bytes, UTF_8); String noteString = new String(bytes, UTF_8);
assertEquals("Patch-set: 1\n" assertEquals("Patch-set: 1\n"
+ "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n" + "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
+ "File: file1\n" + "File: file1\n"
+ "\n" + "\n"
+ "1:1-2:1\n" + "1:1-2:1\n"
+ CommentsInNotesUtil.formatTime(serverIdent, time1) + "\n" + CommentsInNotesUtil.formatTime(serverIdent, time1) + "\n"
+ "Author: Other Account <2@gerrit>\n" + "Author: Other Account <2@gerrit>\n"
+ "UUID: uuid1\n" + "UUID: uuid1\n"
+ "Bytes: 9\n" + "Bytes: 9\n"
+ "comment 1\n" + "comment 1\n"
+ "\n" + "\n"
+ "2:1-3:1\n" + "2:1-3:1\n"
+ CommentsInNotesUtil.formatTime(serverIdent, time2) + "\n" + CommentsInNotesUtil.formatTime(serverIdent, time2) + "\n"
+ "Author: Other Account <2@gerrit>\n" + "Author: Other Account <2@gerrit>\n"
+ "UUID: uuid2\n" + "UUID: uuid2\n"
+ "Bytes: 9\n" + "Bytes: 9\n"
+ "comment 2\n" + "comment 2\n"
+ "\n" + "\n"
+ "File: file2\n" + "File: file2\n"
+ "\n" + "\n"
+ "3:1-4:1\n" + "3:1-4:1\n"
+ CommentsInNotesUtil.formatTime(serverIdent, time3) + "\n" + CommentsInNotesUtil.formatTime(serverIdent, time3) + "\n"
+ "Author: Other Account <2@gerrit>\n" + "Author: Other Account <2@gerrit>\n"
+ "UUID: uuid3\n" + "UUID: uuid3\n"
+ "Bytes: 9\n" + "Bytes: 9\n"
+ "comment 3\n" + "comment 3\n"
+ "\n", + "\n",
noteString); noteString);
}
} }
@Test @Test
@ -782,34 +775,35 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
ChangeNotes notes = newNotes(c); ChangeNotes notes = newNotes(c);
RevWalk walk = new RevWalk(repo); try (RevWalk walk = new RevWalk(repo)) {
ArrayList<Note> notesInTree = ArrayList<Note> notesInTree =
Lists.newArrayList(notes.getNoteMap().iterator()); Lists.newArrayList(notes.getNoteMap().iterator());
Note note = Iterables.getOnlyElement(notesInTree); Note note = Iterables.getOnlyElement(notesInTree);
byte[] bytes = byte[] bytes =
walk.getObjectReader().open( walk.getObjectReader().open(
note.getData(), Constants.OBJ_BLOB).getBytes(); note.getData(), Constants.OBJ_BLOB).getBytes();
String noteString = new String(bytes, UTF_8); String noteString = new String(bytes, UTF_8);
assertEquals("Base-for-patch-set: 1\n" assertEquals("Base-for-patch-set: 1\n"
+ "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n" + "Revision: abcd1234abcd1234abcd1234abcd1234abcd1234\n"
+ "File: file1\n" + "File: file1\n"
+ "\n" + "\n"
+ "1:1-2:1\n" + "1:1-2:1\n"
+ CommentsInNotesUtil.formatTime(serverIdent, time1) + "\n" + CommentsInNotesUtil.formatTime(serverIdent, time1) + "\n"
+ "Author: Other Account <2@gerrit>\n" + "Author: Other Account <2@gerrit>\n"
+ "UUID: uuid1\n" + "UUID: uuid1\n"
+ "Bytes: 9\n" + "Bytes: 9\n"
+ "comment 1\n" + "comment 1\n"
+ "\n" + "\n"
+ "2:1-3:1\n" + "2:1-3:1\n"
+ CommentsInNotesUtil.formatTime(serverIdent, time2) + "\n" + CommentsInNotesUtil.formatTime(serverIdent, time2) + "\n"
+ "Author: Other Account <2@gerrit>\n" + "Author: Other Account <2@gerrit>\n"
+ "UUID: uuid2\n" + "UUID: uuid2\n"
+ "Bytes: 9\n" + "Bytes: 9\n"
+ "comment 2\n" + "comment 2\n"
+ "\n", + "\n",
noteString); noteString);
}
} }
@Test @Test

View File

@ -242,13 +242,10 @@ public class CommitMessageOutputTest extends AbstractChangeNotesTest {
if (id instanceof RevCommit) { if (id instanceof RevCommit) {
return (RevCommit) id; return (RevCommit) id;
} }
RevWalk walk = new RevWalk(repo); try (RevWalk walk = new RevWalk(repo)) {
try {
RevCommit commit = walk.parseCommit(id); RevCommit commit = walk.parseCommit(id);
walk.parseBody(commit); walk.parseBody(commit);
return commit; return commit;
} finally {
walk.release();
} }
} }

View File

@ -423,21 +423,17 @@ public class CommitMsgHookTest extends HookTestCase {
} }
private DirCacheEntry file(final String name) throws IOException { private DirCacheEntry file(final String name) throws IOException {
final ObjectInserter oi = repository.newObjectInserter(); try (ObjectInserter oi = repository.newObjectInserter()) {
try {
final DirCacheEntry e = new DirCacheEntry(name); final DirCacheEntry e = new DirCacheEntry(name);
e.setFileMode(FileMode.REGULAR_FILE); e.setFileMode(FileMode.REGULAR_FILE);
e.setObjectId(oi.insert(Constants.OBJ_BLOB, Constants.encode(name))); e.setObjectId(oi.insert(Constants.OBJ_BLOB, Constants.encode(name)));
oi.flush(); oi.flush();
return e; return e;
} finally {
oi.release();
} }
} }
private void setHEAD() throws Exception { private void setHEAD() throws Exception {
final ObjectInserter oi = repository.newObjectInserter(); try (ObjectInserter oi = repository.newObjectInserter()) {
try {
final CommitBuilder commit = new CommitBuilder(); final CommitBuilder commit = new CommitBuilder();
commit.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {})); commit.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {}));
commit.setAuthor(author); commit.setAuthor(author);
@ -456,8 +452,6 @@ public class CommitMsgHookTest extends HookTestCase {
default: default:
fail(Constants.HEAD + " did not change: " + ref.getResult()); fail(Constants.HEAD + " did not change: " + ref.getResult());
} }
} finally {
oi.release();
} }
} }
} }

@ -1 +1 @@
Subproject commit ba824869c6b24348647f26e04cf80e1ae82266ec Subproject commit 603b7b3885a1d2953ca891f58d2a6095e72e5313