Use try-with-resource to close resources in CommitCommand

Change-Id: Ibbbc74acfd050f28e68f318970660b5959caf7e3
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
This commit is contained in:
Matthias Sohn 2015-04-03 00:52:41 +02:00
parent bb2ca576ff
commit d726f0c1e0
1 changed files with 158 additions and 163 deletions

View File

@ -165,9 +165,7 @@ public RevCommit call() throws GitAPIException, NoHeadException,
checkCallable(); checkCallable();
Collections.sort(only); Collections.sort(only);
RevWalk rw = new RevWalk(repo); try (RevWalk rw = new RevWalk(repo)) {
try {
RepositoryState state = repo.getRepositoryState(); RepositoryState state = repo.getRepositoryState();
if (!state.canCommit()) if (!state.canCommit())
throw new WrongRepositoryStateException(MessageFormat.format( throw new WrongRepositoryStateException(MessageFormat.format(
@ -181,8 +179,7 @@ public RevCommit call() throws GitAPIException, NoHeadException,
processOptions(state, rw); processOptions(state, rw);
if (all && !repo.isBare() && repo.getWorkTree() != null) { if (all && !repo.isBare() && repo.getWorkTree() != null) {
Git git = new Git(repo); try (Git git = new Git(repo)) {
try {
git.add() git.add()
.addFilepattern(".") //$NON-NLS-1$ .addFilepattern(".") //$NON-NLS-1$
.setUpdate(true).call(); .setUpdate(true).call();
@ -221,80 +218,74 @@ public RevCommit call() throws GitAPIException, NoHeadException,
// lock the index // lock the index
DirCache index = repo.lockDirCache(); DirCache index = repo.lockDirCache();
try { try (ObjectInserter odi = repo.newObjectInserter()) {
if (!only.isEmpty()) if (!only.isEmpty())
index = createTemporaryIndex(headId, index, rw); index = createTemporaryIndex(headId, index, rw);
ObjectInserter odi = repo.newObjectInserter(); // Write the index as tree to the object database. This may
try { // fail for example when the index contains unmerged paths
// Write the index as tree to the object database. This may // (unresolved conflicts)
// fail for example when the index contains unmerged paths ObjectId indexTreeId = index.writeTree(odi);
// (unresolved conflicts)
ObjectId indexTreeId = index.writeTree(odi);
if (insertChangeId) if (insertChangeId)
insertChangeId(indexTreeId); insertChangeId(indexTreeId);
// Create a Commit object, populate it and write it // Create a Commit object, populate it and write it
CommitBuilder commit = new CommitBuilder(); CommitBuilder commit = new CommitBuilder();
commit.setCommitter(committer); commit.setCommitter(committer);
commit.setAuthor(author); commit.setAuthor(author);
commit.setMessage(message); commit.setMessage(message);
commit.setParentIds(parents); commit.setParentIds(parents);
commit.setTreeId(indexTreeId); commit.setTreeId(indexTreeId);
ObjectId commitId = odi.insert(commit); ObjectId commitId = odi.insert(commit);
odi.flush(); odi.flush();
RevCommit revCommit = rw.parseCommit(commitId); RevCommit revCommit = rw.parseCommit(commitId);
RefUpdate ru = repo.updateRef(Constants.HEAD); RefUpdate ru = repo.updateRef(Constants.HEAD);
ru.setNewObjectId(commitId); ru.setNewObjectId(commitId);
if (reflogComment != null) { if (reflogComment != null) {
ru.setRefLogMessage(reflogComment, false); ru.setRefLogMessage(reflogComment, false);
} else { } else {
String prefix = amend ? "commit (amend): " //$NON-NLS-1$ String prefix = amend ? "commit (amend): " //$NON-NLS-1$
: parents.size() == 0 ? "commit (initial): " //$NON-NLS-1$ : parents.size() == 0 ? "commit (initial): " //$NON-NLS-1$
: "commit: "; //$NON-NLS-1$ : "commit: "; //$NON-NLS-1$
ru.setRefLogMessage( ru.setRefLogMessage(prefix + revCommit.getShortMessage(),
prefix + revCommit.getShortMessage(), false); false);
}
if (headId != null)
ru.setExpectedOldObjectId(headId);
else
ru.setExpectedOldObjectId(ObjectId.zeroId());
Result rc = ru.forceUpdate();
switch (rc) {
case NEW:
case FORCED:
case FAST_FORWARD: {
setCallable(false);
if (state == RepositoryState.MERGING_RESOLVED
|| isMergeDuringRebase(state)) {
// Commit was successful. Now delete the files
// used for merge commits
repo.writeMergeCommitMsg(null);
repo.writeMergeHeads(null);
} else if (state == RepositoryState.CHERRY_PICKING_RESOLVED) {
repo.writeMergeCommitMsg(null);
repo.writeCherryPickHead(null);
} else if (state == RepositoryState.REVERTING_RESOLVED) {
repo.writeMergeCommitMsg(null);
repo.writeRevertHead(null);
} }
if (headId != null) return revCommit;
ru.setExpectedOldObjectId(headId); }
else case REJECTED:
ru.setExpectedOldObjectId(ObjectId.zeroId()); case LOCK_FAILURE:
Result rc = ru.forceUpdate(); throw new ConcurrentRefUpdateException(
switch (rc) { JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
case NEW: default:
case FORCED: throw new JGitInternalException(MessageFormat.format(
case FAST_FORWARD: { JGitText.get().updatingRefFailed, Constants.HEAD,
setCallable(false); commitId.toString(), rc));
if (state == RepositoryState.MERGING_RESOLVED
|| isMergeDuringRebase(state)) {
// Commit was successful. Now delete the files
// used for merge commits
repo.writeMergeCommitMsg(null);
repo.writeMergeHeads(null);
} else if (state == RepositoryState.CHERRY_PICKING_RESOLVED) {
repo.writeMergeCommitMsg(null);
repo.writeCherryPickHead(null);
} else if (state == RepositoryState.REVERTING_RESOLVED) {
repo.writeMergeCommitMsg(null);
repo.writeRevertHead(null);
}
return revCommit;
}
case REJECTED:
case LOCK_FAILURE:
throw new ConcurrentRefUpdateException(
JGitText.get().couldNotLockHEAD, ru.getRef(),
rc);
default:
throw new JGitInternalException(MessageFormat.format(
JGitText.get().updatingRefFailed,
Constants.HEAD, commitId.toString(), rc));
}
} finally {
odi.release();
} }
} finally { } finally {
index.unlock(); index.unlock();
@ -304,8 +295,6 @@ public RevCommit call() throws GitAPIException, NoHeadException,
} catch (IOException e) { } catch (IOException e) {
throw new JGitInternalException( throw new JGitInternalException(
JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e); JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
} finally {
rw.dispose();
} }
} }
@ -338,114 +327,120 @@ private DirCache createTemporaryIndex(ObjectId headId, DirCache index,
onlyProcessed = new boolean[only.size()]; onlyProcessed = new boolean[only.size()];
boolean emptyCommit = true; boolean emptyCommit = true;
TreeWalk treeWalk = new TreeWalk(repo); try (TreeWalk treeWalk = new TreeWalk(repo)) {
int dcIdx = treeWalk.addTree(new DirCacheBuildIterator(existingBuilder)); int dcIdx = treeWalk
int fIdx = treeWalk.addTree(new FileTreeIterator(repo)); .addTree(new DirCacheBuildIterator(existingBuilder));
int hIdx = -1; int fIdx = treeWalk.addTree(new FileTreeIterator(repo));
if (headId != null) int hIdx = -1;
hIdx = treeWalk.addTree(rw.parseTree(headId)); if (headId != null)
treeWalk.setRecursive(true); hIdx = treeWalk.addTree(rw.parseTree(headId));
treeWalk.setRecursive(true);
String lastAddedFile = null; String lastAddedFile = null;
while (treeWalk.next()) { while (treeWalk.next()) {
String path = treeWalk.getPathString(); String path = treeWalk.getPathString();
// check if current entry's path matches a specified path // check if current entry's path matches a specified path
int pos = lookupOnly(path); int pos = lookupOnly(path);
CanonicalTreeParser hTree = null; CanonicalTreeParser hTree = null;
if (hIdx != -1) if (hIdx != -1)
hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class); hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
DirCacheIterator dcTree = treeWalk.getTree(dcIdx, DirCacheIterator dcTree = treeWalk.getTree(dcIdx,
DirCacheIterator.class); DirCacheIterator.class);
if (pos >= 0) { if (pos >= 0) {
// include entry in commit // include entry in commit
FileTreeIterator fTree = treeWalk.getTree(fIdx, FileTreeIterator fTree = treeWalk.getTree(fIdx,
FileTreeIterator.class); FileTreeIterator.class);
// check if entry refers to a tracked file // check if entry refers to a tracked file
boolean tracked = dcTree != null || hTree != null; boolean tracked = dcTree != null || hTree != null;
if (!tracked) if (!tracked)
break; break;
// for an unmerged path, DirCacheBuildIterator will yield 3 // for an unmerged path, DirCacheBuildIterator will yield 3
// entries, we only want to add one // entries, we only want to add one
if (path.equals(lastAddedFile)) if (path.equals(lastAddedFile))
continue; continue;
lastAddedFile = path; lastAddedFile = path;
if (fTree != null) { if (fTree != null) {
// create a new DirCacheEntry with data retrieved from disk // create a new DirCacheEntry with data retrieved from
final DirCacheEntry dcEntry = new DirCacheEntry(path); // disk
long entryLength = fTree.getEntryLength(); final DirCacheEntry dcEntry = new DirCacheEntry(path);
dcEntry.setLength(entryLength); long entryLength = fTree.getEntryLength();
dcEntry.setLastModified(fTree.getEntryLastModified()); dcEntry.setLength(entryLength);
dcEntry.setFileMode(fTree.getIndexFileMode(dcTree)); dcEntry.setLastModified(fTree.getEntryLastModified());
dcEntry.setFileMode(fTree.getIndexFileMode(dcTree));
boolean objectExists = (dcTree != null && fTree boolean objectExists = (dcTree != null
.idEqual(dcTree)) && fTree.idEqual(dcTree))
|| (hTree != null && fTree.idEqual(hTree)); || (hTree != null && fTree.idEqual(hTree));
if (objectExists) { if (objectExists) {
dcEntry.setObjectId(fTree.getEntryObjectId());
} else {
if (FileMode.GITLINK.equals(dcEntry.getFileMode()))
dcEntry.setObjectId(fTree.getEntryObjectId()); dcEntry.setObjectId(fTree.getEntryObjectId());
else { } else {
// insert object if (FileMode.GITLINK.equals(dcEntry.getFileMode()))
if (inserter == null) dcEntry.setObjectId(fTree.getEntryObjectId());
inserter = repo.newObjectInserter(); else {
long contentLength = fTree.getEntryContentLength(); // insert object
InputStream inputStream = fTree.openEntryStream(); if (inserter == null)
try { inserter = repo.newObjectInserter();
dcEntry.setObjectId(inserter.insert( long contentLength = fTree
Constants.OBJ_BLOB, contentLength, .getEntryContentLength();
inputStream)); InputStream inputStream = fTree
} finally { .openEntryStream();
inputStream.close(); try {
dcEntry.setObjectId(inserter.insert(
Constants.OBJ_BLOB, contentLength,
inputStream));
} finally {
inputStream.close();
}
} }
} }
// add to existing index
existingBuilder.add(dcEntry);
// add to temporary in-core index
tempBuilder.add(dcEntry);
if (emptyCommit
&& (hTree == null || !hTree.idEqual(fTree)
|| hTree.getEntryRawMode() != fTree
.getEntryRawMode()))
// this is a change
emptyCommit = false;
} else {
// if no file exists on disk, neither add it to
// index nor to temporary in-core index
if (emptyCommit && hTree != null)
// this is a change
emptyCommit = false;
} }
// add to existing index // keep track of processed path
existingBuilder.add(dcEntry); onlyProcessed[pos] = true;
// add to temporary in-core index
tempBuilder.add(dcEntry);
if (emptyCommit
&& (hTree == null || !hTree.idEqual(fTree) || hTree
.getEntryRawMode() != fTree
.getEntryRawMode()))
// this is a change
emptyCommit = false;
} else { } else {
// if no file exists on disk, neither add it to // add entries from HEAD for all other paths
// index nor to temporary in-core index if (hTree != null) {
// create a new DirCacheEntry with data retrieved from
// HEAD
final DirCacheEntry dcEntry = new DirCacheEntry(path);
dcEntry.setObjectId(hTree.getEntryObjectId());
dcEntry.setFileMode(hTree.getEntryFileMode());
if (emptyCommit && hTree != null) // add to temporary in-core index
// this is a change tempBuilder.add(dcEntry);
emptyCommit = false; }
// preserve existing entry in index
if (dcTree != null)
existingBuilder.add(dcTree.getDirCacheEntry());
} }
// keep track of processed path
onlyProcessed[pos] = true;
} else {
// add entries from HEAD for all other paths
if (hTree != null) {
// create a new DirCacheEntry with data retrieved from HEAD
final DirCacheEntry dcEntry = new DirCacheEntry(path);
dcEntry.setObjectId(hTree.getEntryObjectId());
dcEntry.setFileMode(hTree.getEntryFileMode());
// add to temporary in-core index
tempBuilder.add(dcEntry);
}
// preserve existing entry in index
if (dcTree != null)
existingBuilder.add(dcTree.getDirCacheEntry());
} }
} }