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

View File

@ -359,40 +359,23 @@ public abstract class AbstractSubmit extends AbstractDaemonTest {
}
protected RevCommit getRemoteHead() throws IOException {
Repository repo = repoManager.openRepository(project);
try {
try (Repository repo = repoManager.openRepository(project)) {
return getHead(repo, "refs/heads/master");
} finally {
repo.close();
}
}
protected List<RevCommit> getRemoteLog() throws IOException {
Repository repo = repoManager.openRepository(project);
try {
RevWalk rw = new RevWalk(repo);
try {
try (Repository repo = repoManager.openRepository(project);
RevWalk rw = new RevWalk(repo)) {
rw.markStart(rw.parseCommit(
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 {
try {
RevWalk rw = new RevWalk(repo);
try {
try (RevWalk rw = new RevWalk(repo)) {
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 {
Repository repo = repoManager.openRepository(project);
try {
RevWalk rw = new RevWalk(repo);
try {
try (Repository repo = repoManager.openRepository(project);
RevWalk rw = new RevWalk(repo)) {
ObjectId oldTreeId = repo.resolve("refs/heads/master~1^{tree}");
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,
ObjectId newTreeId) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DiffFormatter fmt = new DiffFormatter(out);
try (DiffFormatter fmt = new DiffFormatter(out)) {
fmt.setRepository(repo);
fmt.format(oldTreeId, newTreeId);
fmt.flush();
return out.toString();
}
}
}

View File

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

View File

@ -202,12 +202,9 @@ public class CatServlet extends HttpServlet {
final RevCommit fromCommit;
final String suffix;
final String path = patchKey.getFileName();
try {
final ObjectReader reader = repo.newObjectReader();
try {
final RevWalk rw = new RevWalk(reader);
try (ObjectReader reader = repo.newObjectReader();
RevWalk rw = new RevWalk(reader)) {
final RevCommit c;
final TreeWalk tw;
c = rw.parseCommit(ObjectId.fromString(revision));
if (side == 0) {
@ -227,7 +224,7 @@ public class CatServlet extends HttpServlet {
return;
}
tw = TreeWalk.forPath(reader, path, fromCommit.getTree());
try (TreeWalk tw = TreeWalk.forPath(reader, path, fromCommit.getTree())) {
if (tw == null) {
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
@ -240,8 +237,6 @@ public class CatServlet extends HttpServlet {
rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
} finally {
reader.release();
}
} catch (IOException 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)
throws IOException {
RevWalk rw = new RevWalk(repo);
try {
try (RevWalk rw = new RevWalk(repo)) {
bru.execute(rw, NullProgressMonitor.INSTANCE);
} finally {
rw.release();
}
}

View File

@ -137,13 +137,10 @@ public class AllProjectsConfig extends VersionedMetaData {
throw new IOException("All-Projects does not exist.");
}
Repository repo = new FileRepository(path);
try {
try (Repository repo = new FileRepository(path)) {
inserter = repo.newObjectInserter();
reader = repo.newObjectReader();
try {
RevWalk rw = new RevWalk(reader);
try {
try (RevWalk rw = new RevWalk(reader)) {
RevTree srcTree = revision != null ? rw.parseTree(revision) : null;
newTree = readTree(srcTree);
saveConfig(ProjectConfig.PROJECT_CONFIG, cfg);
@ -165,21 +162,16 @@ public class AllProjectsConfig extends VersionedMetaData {
ObjectId newRevision = inserter.insert(commit);
updateRef(repo, ident, newRevision, "commit: " + msg);
revision = newRevision;
} finally {
rw.release();
}
} finally {
if (inserter != null) {
inserter.release();
inserter.close();
inserter = null;
}
if (reader != null) {
reader.release();
reader.close();
reader = null;
}
}
} finally {
repo.close();
}
// 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.PatchSet;
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.server.ReviewDb;
import com.google.gerrit.server.change.ChangeInserter;
@ -227,15 +228,9 @@ public class ChangeUtil {
}
Change changeToRevert = db.get().changes().get(changeId);
Repository git;
try {
git = gitManager.openRepository(ctl.getChange().getProject());
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e);
}
try {
RevWalk revWalk = new RevWalk(git);
try {
Project.NameKey project = ctl.getChange().getProject();
try (Repository git = gitManager.openRepository(project);
RevWalk revWalk = new RevWalk(git)) {
RevCommit commitToRevert =
revWalk.parseCommit(ObjectId.fromString(patch.getRevision().get()));
@ -264,13 +259,10 @@ public class ChangeUtil {
ChangeIdUtil.insertId(message, computedChangeId, true));
RevCommit revertCommit;
ObjectInserter oi = git.newObjectInserter();
try {
try (ObjectInserter oi = git.newObjectInserter()) {
ObjectId id = oi.insert(revertCommitBuilder);
oi.flush();
revertCommit = revWalk.parseCommit(id);
} finally {
oi.release();
}
RefControl refControl = ctl.getRefControl();
@ -334,11 +326,8 @@ public class ChangeUtil {
}
return change.getId();
} finally {
revWalk.release();
}
} finally {
git.close();
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e);
}
}
@ -354,15 +343,9 @@ public class ChangeUtil {
"The commit message cannot be empty");
}
Repository git;
try {
git = gitManager.openRepository(ctl.getChange().getProject());
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e);
}
try {
RevWalk revWalk = new RevWalk(git);
try {
Project.NameKey project = ctl.getChange().getProject();
try (Repository git = gitManager.openRepository(project);
RevWalk revWalk = new RevWalk(git)) {
RevCommit commit =
revWalk.parseCommit(ObjectId.fromString(ps.getRevision()
.get()));
@ -383,13 +366,10 @@ public class ChangeUtil {
commitBuilder.setMessage(message);
RevCommit newCommit;
ObjectInserter oi = git.newObjectInserter();
try {
try (ObjectInserter oi = git.newObjectInserter()) {
ObjectId id = oi.insert(commitBuilder);
oi.flush();
newCommit = revWalk.parseCommit(id);
} finally {
oi.release();
}
PatchSet.Id id = nextPatchSetId(git, change.currentPatchSetId());
@ -410,11 +390,8 @@ public class ChangeUtil {
.insert();
return change.getId();
} finally {
revWalk.release();
}
} finally {
git.close();
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e);
}
}
@ -427,25 +404,14 @@ public class ChangeUtil {
throw new NoSuchChangeException(changeId);
}
Repository git;
try {
git = gitManager.openRepository(change.getProject());
try (Repository git = gitManager.openRepository(change.getProject());
RevWalk revWalk = new RevWalk(git)) {
RevCommit commit = revWalk.parseCommit(
ObjectId.fromString(ps.getRevision().get()));
return commit.getFullMessage();
} catch (RepositoryNotFoundException 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)

View File

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

View File

@ -121,16 +121,8 @@ public class CherryPickChange {
Project.NameKey project = change.getProject();
IdentifiedUser identifiedUser = (IdentifiedUser) currentUser.get();
final Repository git;
try {
git = gitManager.openRepository(project);
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(change.getId(), e);
}
try {
RevWalk revWalk = new RevWalk(git);
try {
try (Repository git = gitManager.openRepository(project);
RevWalk revWalk = new RevWalk(git)) {
Ref destRef = git.getRef(destinationBranch);
if (destRef == null) {
throw new InvalidChangeOperationException("Branch "
@ -154,16 +146,13 @@ public class CherryPickChange {
ChangeIdUtil.insertId(message, computedChangeId).trim() + '\n';
RevCommit cherryPickCommit;
ObjectInserter oi = git.newObjectInserter();
try {
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());
} finally {
oi.release();
}
Change.Key changeKey;
@ -205,11 +194,8 @@ public class CherryPickChange {
return newChange.getId();
}
} finally {
revWalk.release();
}
} finally {
git.close();
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(change.getId(), e);
}
}

View File

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

View File

@ -158,11 +158,8 @@ public class CreateChange implements
}
Project.NameKey project = rsrc.getNameKey();
Repository git = gitManager.openRepository(project);
try {
RevWalk rw = new RevWalk(git);
try {
try (Repository git = gitManager.openRepository(project);
RevWalk rw = new RevWalk(git)) {
ObjectId parentCommit;
if (input.baseChange != null) {
List<Change> changes = changeUtil.findChanges(input.baseChange);
@ -218,11 +215,6 @@ public class CreateChange implements
ins.insert();
return Response.created(json.format(change.getId()));
} finally {
rw.release();
}
} finally {
git.close();
}
}
@ -275,8 +267,7 @@ public class CreateChange implements
PersonIdent authorIdent, RevCommit mergeTip, String commitMessage)
throws IOException {
RevCommit emptyCommit;
ObjectInserter oi = git.newObjectInserter();
try {
try (ObjectInserter oi = git.newObjectInserter()) {
CommitBuilder commit = new CommitBuilder();
commit.setTreeId(mergeTip.getTree().getId());
commit.setParentId(mergeTip);
@ -284,8 +275,6 @@ public class CreateChange implements
commit.setCommitter(authorIdent);
commit.setMessage(commitMessage);
emptyCommit = rw.parseCommit(insert(oi, commit));
} finally {
oi.release();
}
return emptyCommit;
}

View File

@ -58,10 +58,8 @@ public class FileContentUtil {
public BinaryResult getContent(ProjectState project, ObjectId revstr,
String path) throws ResourceNotFoundException, IOException {
Repository repo = openRepository(project);
try {
RevWalk rw = new RevWalk(repo);
try {
try (Repository repo = openRepository(project);
RevWalk rw = new RevWalk(repo)) {
RevCommit commit = rw.parseCommit(revstr);
ObjectReader reader = rw.getObjectReader();
TreeWalk tw = TreeWalk.forPath(reader, path, commit.getTree());
@ -100,22 +98,17 @@ public class FileContentUtil {
type = resolveContentType(project, path, FileMode.FILE, type);
}
return result.setContentType(type).base64();
} finally {
rw.release();
}
} finally {
repo.close();
}
}
private static BinaryResult asBinaryResult(final ObjectLoader obj) {
@SuppressWarnings("resource")
BinaryResult result = new BinaryResult() {
@Override
public void writeTo(OutputStream os) throws IOException {
obj.copyTo(os);
}
}.setContentLength(obj.getSize());
};
result.setContentLength(obj.getSize());
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.Patch;
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.server.CurrentUser;
import com.google.gerrit.server.IdentifiedUser;
@ -178,14 +179,13 @@ public class Files implements ChildCollection<RevisionResource, FileResource> {
private List<String> query(RevisionResource resource)
throws RepositoryNotFoundException, IOException {
Repository git =
gitManager.openRepository(resource.getChange().getProject());
try {
TreeWalk tw = new TreeWalk(git);
try {
RevCommit c = new RevWalk(tw.getObjectReader())
.parseCommit(ObjectId.fromString(
resource.getPatchSet().getRevision().get()));
Project.NameKey project = resource.getChange().getProject();
try (Repository git = gitManager.openRepository(project);
ObjectReader or = git.newObjectReader();
RevWalk rw = new RevWalk(or);
TreeWalk tw = new TreeWalk(or)) {
RevCommit c = rw.parseCommit(
ObjectId.fromString(resource.getPatchSet().getRevision().get()));
tw.addTree(c.getTree());
tw.setRecursive(true);
@ -197,11 +197,6 @@ public class Files implements ChildCollection<RevisionResource, FileResource> {
}
}
return paths;
} finally {
tw.release();
}
} finally {
git.close();
}
}
@ -261,11 +256,11 @@ public class Files implements ChildCollection<RevisionResource, FileResource> {
private List<String> copy(Set<String> paths, PatchSet.Id old,
RevisionResource resource, Account.Id userId) throws IOException,
PatchListNotAvailableException, OrmException {
Repository git =
gitManager.openRepository(resource.getChange().getProject());
try {
Project.NameKey project = resource.getChange().getProject();
try (Repository git = gitManager.openRepository(project);
ObjectReader reader = git.newObjectReader();
try {
RevWalk rw = new RevWalk(reader);
TreeWalk tw = new TreeWalk(reader)) {
PatchList oldList = patchListCache.get(
resource.getChange(),
db.get().patchSets().get(old));
@ -278,8 +273,6 @@ public class Files implements ChildCollection<RevisionResource, FileResource> {
List<AccountPatchReview> inserts = Lists.newArrayListWithCapacity(sz);
List<String> pathList = Lists.newArrayListWithCapacity(sz);
RevWalk rw = new RevWalk(reader);
TreeWalk tw = new TreeWalk(reader);
tw.setFilter(PathFilterGroup.createFromStrings(paths));
tw.setRecursive(true);
int o = tw.addTree(rw.parseCommit(oldList.getNewId()).getTree());
@ -326,11 +319,6 @@ public class Files implements ChildCollection<RevisionResource, FileResource> {
}
db.get().accountPatchReviews().insert(inserts);
return pathList;
} finally {
reader.release();
}
} finally {
git.close();
}
}

View File

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

View File

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

View File

@ -80,19 +80,12 @@ public class GetRelated implements RestReadView<RevisionResource> {
@Override
public RelatedInfo apply(RevisionResource rsrc)
throws RepositoryNotFoundException, IOException, OrmException {
Repository git = gitMgr.openRepository(rsrc.getChange().getProject());
try {
try (Repository git = gitMgr.openRepository(rsrc.getChange().getProject());
RevWalk rw = new RevWalk(git)) {
Ref ref = git.getRef(rsrc.getChange().getDest().get());
RevWalk rw = new RevWalk(git);
try {
RelatedInfo info = new RelatedInfo();
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.RestReadView;
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.server.git.GitRepositoryManager;
import com.google.gerrit.server.project.ChangeControl;
@ -55,11 +56,9 @@ class IncludedIn implements RestReadView<ChangeResource> {
ChangeControl ctl = rsrc.getControl();
PatchSet ps =
db.get().patchSets().get(ctl.getChange().currentPatchSetId());
Repository r =
repoManager.openRepository(ctl.getProject().getNameKey());
try {
RevWalk rw = new RevWalk(r);
try {
Project.NameKey project = ctl.getProject().getNameKey();
try (Repository r = repoManager.openRepository(project);
RevWalk rw = new RevWalk(r)) {
rw.setRetainBody(false);
RevCommit rev;
try {
@ -70,11 +69,6 @@ class IncludedIn implements RestReadView<ChangeResource> {
throw new ResourceConflictException(err.getMessage());
}
return new IncludedInInfo(IncludedInResolver.resolve(r, rw, rev));
} finally {
rw.release();
}
} finally {
r.close();
}
}

View File

@ -225,8 +225,7 @@ public class MergeabilityCacheImpl implements MergeabilityCache {
}
try {
Map<String, Ref> refs = key.load.repo.getAllRefs();
RevWalk rw = CodeReviewCommit.newRevWalk(key.load.repo);
try {
try (RevWalk rw = CodeReviewCommit.newRevWalk(key.load.repo)) {
RevFlag canMerge = rw.newFlag("CAN_MERGE");
CodeReviewCommit rev = parse(rw, key.commit);
rev.add(canMerge);
@ -243,8 +242,6 @@ public class MergeabilityCacheImpl implements MergeabilityCache {
canMerge,
accepted,
key.load.dest).dryRun(tip, rev);
} finally {
rw.release();
}
} finally {
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: "
+ changeId.toString());
}
Repository git = null;
RevWalk rw = null;
ObjectInserter inserter = null;
try {
git = gitManager.openRepository(change.getProject());
rw = new RevWalk(git);
inserter = git.newObjectInserter();
try (Repository git = gitManager.openRepository(change.getProject());
RevWalk rw = new RevWalk(git);
ObjectInserter inserter = git.newObjectInserter()) {
String baseRev = newBaseRev;
if (baseRev == null) {
baseRev = findBaseRevision(patchSetId, db.get(),
@ -149,16 +144,6 @@ public class RebaseChange {
committerIdent, true, ValidatePolicy.GERRIT);
} catch (MergeConflictException e) {
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.reviewdb.client.Change;
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.GerritPersonIdent;
import com.google.gerrit.server.IdentifiedUser;
@ -115,26 +116,20 @@ public class ChangeEditModifier {
}
IdentifiedUser me = (IdentifiedUser) currentUser.get();
Repository repo = gitManager.openRepository(change.getProject());
String refPrefix = editRefPrefix(me.getAccountId(), change.getId());
try {
try (Repository repo = gitManager.openRepository(change.getProject())) {
Map<String, Ref> refs = repo.getRefDatabase().getRefs(refPrefix);
if (!refs.isEmpty()) {
throw new ResourceConflictException("edit already exists");
}
RevWalk rw = new RevWalk(repo);
try {
try (RevWalk rw = new RevWalk(repo)) {
ObjectId revision = ObjectId.fromString(ps.getRevision().get());
String editRefName = editRefName(me.getAccountId(), change.getId(),
ps.getId());
return update(repo, me, editRefName, rw, ObjectId.zeroId(), revision);
} finally {
rw.release();
}
} finally {
repo.close();
}
}
@ -159,12 +154,10 @@ public class ChangeEditModifier {
IdentifiedUser me = (IdentifiedUser) currentUser.get();
String refName = editRefName(me.getAccountId(), change.getId(),
current.getId());
Repository repo = gitManager.openRepository(change.getProject());
try {
try (Repository repo = gitManager.openRepository(change.getProject());
RevWalk rw = new RevWalk(repo);
ObjectInserter inserter = repo.newObjectInserter()) {
BatchRefUpdate ru = repo.getRefDatabase().newBatchUpdate();
ObjectInserter inserter = repo.newObjectInserter();
try {
RevCommit editCommit = edit.getEditCommit();
if (editCommit.getParentCount() == 0) {
throw new InvalidChangeOperationException(
@ -206,12 +199,6 @@ public class ChangeEditModifier {
// 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();
Repository repo = gitManager.openRepository(edit.getChange().getProject());
try {
Project.NameKey project = edit.getChange().getProject();
try (Repository repo = gitManager.openRepository(project);
RevWalk rw = new RevWalk(repo);
ObjectInserter inserter = repo.newObjectInserter();
try {
ObjectInserter inserter = repo.newObjectInserter()) {
String refName = edit.getRefName();
ObjectId commit = createCommit(me, inserter, prevEdit,
prevEdit.getTree(),
msg);
inserter.flush();
return update(repo, me, refName, rw, prevEdit, commit);
} finally {
rw.release();
inserter.release();
}
} finally {
repo.close();
}
}
@ -333,12 +313,11 @@ public class ChangeEditModifier {
throw new AuthException("Authentication required");
}
IdentifiedUser me = (IdentifiedUser) currentUser.get();
Repository repo = gitManager.openRepository(edit.getChange().getProject());
try {
Project.NameKey project = edit.getChange().getProject();
try (Repository repo = gitManager.openRepository(project);
RevWalk rw = new RevWalk(repo);
ObjectInserter inserter = repo.newObjectInserter();
ObjectReader reader = repo.newObjectReader();
try {
ObjectReader reader = repo.newObjectReader()) {
String refName = edit.getRefName();
RevCommit prevEdit = edit.getEditCommit();
ObjectId newTree = writeNewTree(op,
@ -356,13 +335,6 @@ public class ChangeEditModifier {
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();
}
}

View File

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

View File

@ -101,11 +101,9 @@ public class BanCommit {
NoteMap banCommitNotes = NoteMap.newEmptyMap();
// Add a note for each banned commit to notes.
final Project.NameKey project = projectControl.getProject().getNameKey();
final Repository repo = repoManager.openRepository(project);
try {
final RevWalk revWalk = new RevWalk(repo);
final ObjectInserter inserter = repo.newObjectInserter();
try {
try (Repository repo = repoManager.openRepository(project);
RevWalk revWalk = new RevWalk(repo);
ObjectInserter inserter = repo.newObjectInserter()) {
ObjectId noteId = null;
for (final ObjectId commitToBan : commitsToBan) {
try {
@ -135,12 +133,6 @@ public class BanCommit {
}
}
return result;
} finally {
revWalk.release();
inserter.release();
}
} finally {
repo.close();
}
}

View File

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

View File

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

View File

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

View File

@ -147,7 +147,7 @@ class TagSet {
}
} finally {
if (rw != null) {
rw.release();
rw.close();
}
}
}
@ -157,9 +157,8 @@ class TagSet {
return;
}
TagWalk rw = new TagWalk(git);
try (TagWalk rw = new TagWalk(git)) {
rw.setRetainBody(false);
try {
for (Ref ref : git.getRefDatabase().getRefs(RefDatabase.ALL).values()) {
if (skip(ref)) {
continue;
@ -188,8 +187,6 @@ class TagSet {
}
} catch (IOException 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;
onLoad();
} finally {
reader.release();
reader.close();
reader = null;
}
}
@ -319,13 +319,14 @@ public abstract class VersionedMetaData {
public void close() {
newTree = null;
rw.close();
if (inserter != null) {
inserter.release();
inserter.close();
inserter = null;
}
if (reader != null) {
reader.release();
reader.close();
reader = null;
}
}

View File

@ -323,19 +323,17 @@ public class SiteIndexer {
getPathsAndIndex(id);
}
} finally {
walk.release();
walk.close();
}
return null;
}
private void getPathsAndIndex(ObjectId b) throws Exception {
List<ChangeData> cds = Lists.newArrayList(byId.get(b));
try {
try (DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE)) {
RevCommit bCommit = walk.parseCommit(b);
RevTree bTree = bCommit.getTree();
RevTree aTree = aFor(bCommit, walk);
DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
try {
df.setRepository(repo);
if (!cds.isEmpty()) {
List<String> paths = (aTree != null)
@ -356,9 +354,6 @@ public class SiteIndexer {
}
}
}
} finally {
df.release();
}
} catch (Exception e) {
fail("Failed to index commit " + b.name(), false, e);
for (ChangeData cd : cds) {
@ -396,13 +391,10 @@ public class SiteIndexer {
}
private ObjectId emptyTree() throws IOException {
ObjectInserter oi = repo.newObjectInserter();
try {
try (ObjectInserter oi = repo.newObjectInserter()) {
ObjectId id = oi.insert(Constants.OBJ_TREE, new byte[] {});
oi.flush();
return id;
} finally {
oi.release();
}
}

View File

@ -396,7 +396,7 @@ public abstract class ChangeEmail extends NotificationEmail {
TemporaryBuffer.Heap buf =
new TemporaryBuffer.Heap(args.settings.maximumDiffSize);
DiffFormatter fmt = new DiffFormatter(buf);
try (DiffFormatter fmt = new DiffFormatter(buf)) {
Repository git;
try {
git = args.server.openRepository(change.getProject());
@ -416,8 +416,8 @@ public abstract class ChangeEmail extends NotificationEmail {
log.error("Cannot format patch", e);
return "";
} finally {
fmt.release();
git.close();
}
}
}
}

View File

@ -82,15 +82,11 @@ public class PatchSetNotificationSender {
final Change updatedChange, final PatchSet updatedPatchSet,
final LabelTypes labelTypes)
throws OrmException, IOException {
final Repository git = repoManager.openRepository(updatedChange.getProject());
try {
final RevWalk revWalk = new RevWalk(git);
try (Repository git = repoManager.openRepository(updatedChange.getProject())) {
final RevCommit commit;
try {
try (RevWalk revWalk = new RevWalk(git)) {
commit = revWalk.parseCommit(ObjectId.fromString(
updatedPatchSet.getRevision().get()));
} finally {
revWalk.release();
}
final PatchSetInfo info = patchSetInfoFactory.get(commit, updatedPatchSet.getId());
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);
}
}
} finally {
git.close();
}
}
}

View File

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

View File

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

View File

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

View File

@ -48,9 +48,8 @@ public class PatchFile {
this.repo = repo;
this.entry = patchList.get(fileName);
final ObjectReader reader = repo.newObjectReader();
try {
final RevWalk rw = new RevWalk(reader);
try (ObjectReader reader = repo.newObjectReader();
RevWalk rw = new RevWalk(reader)) {
final RevCommit bCommit = rw.parseCommit(patchList.getNewId());
if (Patch.COMMIT_MSG.equals(fileName)) {
@ -74,8 +73,6 @@ public class PatchFile {
}
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)
throws IOException, PatchListNotAvailableException {
final RawTextComparator cmp = comparatorFor(key.getWhitespace());
final ObjectReader reader = repo.newObjectReader();
try {
final RevWalk rw = new RevWalk(reader);
try (ObjectReader reader = repo.newObjectReader();
RevWalk rw = new RevWalk(reader);
DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE)) {
final RevCommit b = rw.parseCommit(key.getNewId());
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 bTree = b.getTree();
DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
df.setRepository(repo);
df.setDiffComparator(cmp);
df.setDetectRenames(true);
@ -170,8 +169,6 @@ public class PatchListLoader extends CacheLoader<PatchListKey, PatchList> {
}
return new PatchList(a, b, againstParent,
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);
final ObjectInserter ins = repo.newObjectInserter();
try {
try (ObjectInserter ins = repo.newObjectInserter()) {
DirCache dc = DirCache.newInCore();
m.setDirCache(dc);
m.setObjectInserter(new ObjectInserter.Filter() {
@ -397,19 +393,14 @@ public class PatchListLoader extends CacheLoader<PatchListKey, PatchList> {
}
return rw.lookupTree(treeId);
} finally {
ins.release();
}
}
private static ObjectId emptyTree(final Repository repo) throws IOException {
ObjectInserter oi = repo.newObjectInserter();
try {
try (ObjectInserter oi = repo.newObjectInserter()) {
ObjectId id = oi.insert(Constants.OBJ_TREE, new byte[] {});
oi.flush();
return id;
} finally {
oi.release();
}
}
}

View File

@ -119,7 +119,7 @@ class PatchScriptBuilder {
try {
return build(content, comments, history);
} finally {
reader.release();
reader.close();
}
}
@ -514,11 +514,12 @@ class PatchScriptBuilder {
if (path == null || within == null) {
return null;
}
final RevWalk rw = new RevWalk(reader);
try (RevWalk rw = new RevWalk(reader)) {
final RevTree tree = rw.parseTree(within);
return TreeWalk.forPath(reader, path, tree);
}
}
}
private static boolean isBothFile(FileMode a, FileMode b) {
return (a.getBits() & FileMode.TYPE_FILE) == FileMode.TYPE_FILE

View File

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

View File

@ -44,7 +44,7 @@ public class Text extends RawText {
public static final Text EMPTY = new Text(NO_BYTES);
public static Text forCommit(ObjectReader reader, AnyObjectId commitId) throws IOException {
RevWalk rw = new RevWalk(reader);
try (RevWalk rw = new RevWalk(reader)) {
RevCommit c;
if (commitId instanceof RevCommit) {
c = (RevCommit) commitId;
@ -83,6 +83,7 @@ public class Text extends RawText {
b.append(c.getFullMessage());
return new Text(b.toString().getBytes("UTF-8"));
}
}
private static void appendPersonIdent(StringBuilder b, String field,
PersonIdent person) {

View File

@ -65,10 +65,8 @@ public class CommitsCollection implements
throw new ResourceNotFoundException(id);
}
Repository repo = repoManager.openRepository(parent.getNameKey());
try {
RevWalk rw = new RevWalk(repo);
try {
try (Repository repo = repoManager.openRepository(parent.getNameKey());
RevWalk rw = new RevWalk(repo)) {
RevCommit commit = rw.parseCommit(objectId);
rw.parseBody(commit);
if (!parent.getControl().canReadCommit(db.get(), rw, commit)) {
@ -80,11 +78,6 @@ public class CommitsCollection implements
return new CommitResource(parent, commit);
} catch (MissingObjectException | IncorrectObjectTypeException e) {
throw new ResourceNotFoundException(id);
} finally {
rw.release();
}
} finally {
repo.close();
}
}

View File

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

View File

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

View File

@ -82,15 +82,9 @@ class ListDashboards implements RestReadView<ProjectResource> {
private List<DashboardInfo> scan(ProjectControl ctl, String project,
boolean setDefault) throws ResourceNotFoundException, IOException {
Repository git;
try {
git = gitManager.openRepository(ctl.getProject().getNameKey());
} catch (RepositoryNotFoundException e) {
throw new ResourceNotFoundException();
}
try {
RevWalk rw = new RevWalk(git);
try {
Project.NameKey projectName = ctl.getProject().getNameKey();
try (Repository git = gitManager.openRepository(projectName);
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()) {
@ -99,11 +93,8 @@ class ListDashboards implements RestReadView<ProjectResource> {
}
}
return all;
} finally {
rw.release();
}
} finally {
git.close();
} catch (RepositoryNotFoundException e) {
throw new ResourceNotFoundException();
}
}
@ -111,7 +102,7 @@ class ListDashboards implements RestReadView<ProjectResource> {
Repository git, RevWalk rw, Ref ref, String project, boolean setDefault)
throws IOException {
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.setRecursive(true);
while (tw.next()) {
@ -132,6 +123,7 @@ class ListDashboards implements RestReadView<ProjectResource> {
}
}
}
}
return list;
}
}

View File

@ -98,26 +98,17 @@ public class ListTags implements RestReadView<ProjectResource> {
public TagInfo get(ProjectResource resource, IdString id)
throws ResourceNotFoundException, IOException {
Repository repo = getRepository(resource.getNameKey());
try (Repository repo = getRepository(resource.getNameKey());
RevWalk rw = new RevWalk(repo)) {
String tagName = id.get();
if (!tagName.startsWith(Constants.R_TAGS)) {
tagName = Constants.R_TAGS + tagName;
}
try {
RevWalk rw = new RevWalk(repo);
try {
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);
}

View File

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

View File

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

View File

@ -107,12 +107,9 @@ class ConflictsPredicate extends OrPredicate<ChangeData> {
if (conflicts != null) {
return conflicts;
}
try {
Repository repo =
try (Repository repo =
args.repoManager.openRepository(otherChange.getProject());
try {
RevWalk rw = CodeReviewCommit.newRevWalk(repo);
try {
RevWalk rw = CodeReviewCommit.newRevWalk(repo)) {
RevFlag canMergeFlag = rw.newFlag("CAN_MERGE");
CodeReviewCommit commit =
(CodeReviewCommit) rw.parseCommit(changeDataCache.getTestAgainst());
@ -127,17 +124,7 @@ class ConflictsPredicate extends OrPredicate<ChangeData> {
conflicts = !strategy.dryRun(commit, otherCommit);
args.conflictsCache.put(conflictsKey, conflicts);
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) {
} catch (MergeException | NoSuchProjectException | IOException 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);
try {
final Repository repo = repoManager.openRepository(projectName);
try {
final RevWalk rw = new RevWalk(repo);
try {
try (Repository repo = repoManager.openRepository(projectName);
RevWalk rw = new RevWalk(repo)) {
return match(repo, rw, args);
} finally {
rw.release();
}
} finally {
repo.close();
}
} catch (RepositoryNotFoundException e) {
log.error("Repository \"" + projectName.get() + "\" unknown.", 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);
Repository repo = StoredValues.REPOSITORY.get(engine);
final ObjectReader reader = repo.newObjectReader();
try (ObjectReader reader = repo.newObjectReader();
RevWalk rw = new RevWalk(reader)) {
final RevTree aTree;
final RevTree bTree;
try {
final RevWalk rw = new RevWalk(reader);
final RevCommit bCommit = rw.parseCommit(pl.getNewId());
if (pl.getOldId() != null) {
@ -129,8 +128,6 @@ public class PRED_commit_edits_2 extends Predicate.P2 {
}
} catch (IOException err) {
throw new JavaException(this, 1, err);
} finally {
reader.release();
}
return engine.fail();

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);
revWalk = new RevWalk(db);
// Version 1.0
@ -129,7 +131,7 @@ public class IncludedInResolverTest extends RepositoryTestCase {
@Override
@After
public void tearDown() throws Exception {
revWalk.release();
revWalk.close();
super.tearDown();
}

View File

@ -118,7 +118,9 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
public void testEmptyCommit() throws Exception {
expect(schemaFactory.open()).andReturn(schema);
final Repository realDb = createWorkRepository();
try (Repository realDb = createWorkRepository()) {
// 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();
@ -147,6 +149,7 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
doVerify();
}
}
/**
* It tests SubmoduleOp.update in a scenario considering:
@ -588,8 +591,14 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
public void testOneSubscriberToUpdate() throws Exception {
expect(schemaFactory.open()).andReturn(schema);
final Repository sourceRepository = createWorkRepository();
try (Repository sourceRepository = createWorkRepository();
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);
@ -612,9 +621,6 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
final List<Change> submitted = new ArrayList<>();
submitted.add(submittedChange);
final Repository targetRepository = createWorkRepository();
final Git targetGit = new Git(targetRepository);
addGitLinkToIndex("a", sourceMergeTip.copy(), targetRepository);
targetGit.commit().setMessage("test").call();
@ -668,6 +674,7 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
RefUpdate ru = ruCapture.getValue();
assertEquals(ru.getName(), targetBranchNameKey.get());
}
}
/**
* It tests SubmoduleOp.update in a scenario considering established circular
@ -693,8 +700,14 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
public void testAvoidingCircularReference() throws Exception {
expect(schemaFactory.open()).andReturn(schema);
final Repository sourceRepository = createWorkRepository();
try (Repository sourceRepository = createWorkRepository();
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);
@ -717,9 +730,6 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
final List<Change> submitted = new ArrayList<>();
submitted.add(submittedChange);
final Repository targetRepository = createWorkRepository();
final Git targetGit = new Git(targetRepository);
addGitLinkToIndex("a", sourceMergeTip.copy(), targetRepository);
targetGit.commit().setMessage("test").call();
@ -774,6 +784,7 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
RefUpdate ru = ruCapture.getValue();
assertEquals(ru.getName(), targetBranchNameKey.get());
}
}
/**
* It calls SubmoduleOp.update considering only one insert on Subscriptions
@ -862,7 +873,9 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
final List<SubmoduleSubscription> previousSubscriptions) throws Exception {
expect(schemaFactory.open()).andReturn(schema);
final Repository realDb = createWorkRepository();
try (Repository realDb = createWorkRepository()) {
// 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);
@ -924,6 +937,7 @@ public class SubmoduleOpTest extends LocalDiskRepositoryTestCase {
submoduleOp.update();
}
}
/**
* It creates and adds a regular file to git index of a repository.

View File

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

View File

@ -348,13 +348,10 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
hashtags.add("tag2");
update.setHashtags(hashtags);
update.commit();
RevWalk walk = new RevWalk(repo);
try {
try (RevWalk walk = new RevWalk(repo)) {
RevCommit commit = walk.parseCommit(update.getRevision());
walk.parseBody(commit);
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.writeCommit(batch);
RevWalk rw = new RevWalk(repo);
try {
try (RevWalk rw = new RevWalk(repo)) {
batch.commit();
bru.execute(rw, NullProgressMonitor.INSTANCE);
@ -464,7 +460,6 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
notesWithApprovals.close();
} finally {
batch.close();
rw.release();
}
}
@ -506,11 +501,8 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
assertEquals(update1.getRefName(), cmds.get(0).getRefName());
assertEquals(update2.getRefName(), cmds.get(1).getRefName());
RevWalk rw = new RevWalk(repo);
try {
try (RevWalk rw = new RevWalk(repo)) {
bru.execute(rw, NullProgressMonitor.INSTANCE);
} finally {
rw.release();
}
assertEquals(ReceiveCommand.Result.OK, cmds.get(0).getResult());
@ -712,7 +704,7 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
ChangeNotes notes = newNotes(c);
RevWalk walk = new RevWalk(repo);
try (RevWalk walk = new RevWalk(repo)) {
ArrayList<Note> notesInTree =
Lists.newArrayList(notes.getNoteMap().iterator());
Note note = Iterables.getOnlyElement(notesInTree);
@ -750,6 +742,7 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
+ "\n",
noteString);
}
}
@Test
public void patchLineCommentNotesFormatSide0() throws Exception {
@ -782,7 +775,7 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
ChangeNotes notes = newNotes(c);
RevWalk walk = new RevWalk(repo);
try (RevWalk walk = new RevWalk(repo)) {
ArrayList<Note> notesInTree =
Lists.newArrayList(notes.getNoteMap().iterator());
Note note = Iterables.getOnlyElement(notesInTree);
@ -811,6 +804,7 @@ public class ChangeNotesTest extends AbstractChangeNotesTest {
+ "\n",
noteString);
}
}
@Test
public void patchLineCommentMultipleOnePatchsetOneFileBothSides()

View File

@ -242,13 +242,10 @@ public class CommitMessageOutputTest extends AbstractChangeNotesTest {
if (id instanceof RevCommit) {
return (RevCommit) id;
}
RevWalk walk = new RevWalk(repo);
try {
try (RevWalk walk = new RevWalk(repo)) {
RevCommit commit = walk.parseCommit(id);
walk.parseBody(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 {
final ObjectInserter oi = repository.newObjectInserter();
try {
try (ObjectInserter oi = repository.newObjectInserter()) {
final DirCacheEntry e = new DirCacheEntry(name);
e.setFileMode(FileMode.REGULAR_FILE);
e.setObjectId(oi.insert(Constants.OBJ_BLOB, Constants.encode(name)));
oi.flush();
return e;
} finally {
oi.release();
}
}
private void setHEAD() throws Exception {
final ObjectInserter oi = repository.newObjectInserter();
try {
try (ObjectInserter oi = repository.newObjectInserter()) {
final CommitBuilder commit = new CommitBuilder();
commit.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {}));
commit.setAuthor(author);
@ -456,8 +452,6 @@ public class CommitMsgHookTest extends HookTestCase {
default:
fail(Constants.HEAD + " did not change: " + ref.getResult());
}
} finally {
oi.release();
}
}
}

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