GitModules: Fix resource leak flagged by infer Bug: Issue 5198 Change-Id: Id22a48ab05980bedbff03b9e0eb2305e2f122439
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/git/GitModules.java b/gerrit-server/src/main/java/com/google/gerrit/server/git/GitModules.java index 26c59c2..192691d 100644 --- a/gerrit-server/src/main/java/com/google/gerrit/server/git/GitModules.java +++ b/gerrit-server/src/main/java/com/google/gerrit/server/git/GitModules.java
@@ -65,35 +65,40 @@ this.submissionId = orm.getSubmissionId(); Project.NameKey project = branch.getParentKey(); logDebug("Loading .gitmodules of {} for project {}", branch, project); - OpenRepo or; + OpenRepo or = null; try { or = orm.openRepo(project); + ObjectId id = or.repo.resolve(branch.get()); + if (id == null) { + throw new IOException("Cannot open branch " + branch.get()); + } + RevCommit commit = or.rw.parseCommit(id); + + try (TreeWalk tw = + TreeWalk.forPath(or.repo, GIT_MODULES, commit.getTree())) { + if (tw == null + || (tw.getRawMode(0) & FileMode.TYPE_MASK) != FileMode.TYPE_FILE) { + subscriptions = Collections.emptySet(); + logDebug("The .gitmodules file doesn't exist in " + branch); + return; + } + } + BlobBasedConfig bbc; + try { + bbc = new BlobBasedConfig(null, or.repo, commit, GIT_MODULES); + } catch (ConfigInvalidException e) { + throw new IOException("Could not read .gitmodules of super project: " + + branch.getParentKey(), e); + } + subscriptions = new SubmoduleSectionParser(bbc, canonicalWebUrl, + branch).parseAllSections(); } catch (NoSuchProjectException e) { throw new IOException(e); + } finally { + if (or != null) { + or.close(); + } } - - ObjectId id = or.repo.resolve(branch.get()); - if (id == null) { - throw new IOException("Cannot open branch " + branch.get()); - } - RevCommit commit = or.rw.parseCommit(id); - - TreeWalk tw = TreeWalk.forPath(or.repo, GIT_MODULES, commit.getTree()); - if (tw == null - || (tw.getRawMode(0) & FileMode.TYPE_MASK) != FileMode.TYPE_FILE) { - subscriptions = Collections.emptySet(); - logDebug("The .gitmodules file doesn't exist in " + branch); - return; - } - BlobBasedConfig bbc; - try { - bbc = new BlobBasedConfig(null, or.repo, commit, GIT_MODULES); - } catch (ConfigInvalidException e) { - throw new IOException("Could not read .gitmodules of super project: " + - branch.getParentKey(), e); - } - subscriptions = new SubmoduleSectionParser(bbc, canonicalWebUrl, - branch).parseAllSections(); } public Collection<SubmoduleSubscription> subscribedTo(Branch.NameKey src) {