Merge branch 'master' into stable-4.0

* master:
  Silence non-externalized string warnings in org.eclipse.jgit
  Externalize translatable texts in org.eclipse.jgit
  Don't invalidate pack file on InterruptedIOException
  Update Mars target platforms to use Mars RC2 orbit
  Update build to use eclipse-jarsigner-plugin 1.1.2
  Guard agains null ReflogReader if named ref does not exist
  FS: Allow to manually set the path to the Git system config file
  FS: Fix a minor typo in runInShell() docs
  FS: Improve javadoc of some recently introduced methods
  Cleanup code and Eclipse compile errors in new gitrepo API
  Refactor to expose ManifestParser.
  FS: Remove the gitprefix logic
  SystemReader: Use discoverGitSystemConfig() in openSystemConfig()
  FS: Add a method to discover the system-wide config file
  FS: Extend readPipe() to optionally take additional environment
  FS: Document readpipe()'s encoding parameter
  Split discoverGitPrefix() code out into discoverGitExe()
  Equalize discoverGitPrefix() implementations between POSIX and Win32
  Move resolveGrandparentFile() to the base class for wider use
  Replace deprecated release() methods by close()
  Use AutoClosable to close resources in bundle org.eclipse.jgit
  ReceivePack: support quiet capability
  Fix ObjectReader resources leak

Change-Id: I0cd9f7ad57f26f0a0cbf412845d00ba1efbea346
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
This commit is contained in:
Matthias Sohn 2015-05-26 11:39:19 +02:00
commit 04b3cd0e15
128 changed files with 2082 additions and 1656 deletions

View File

@ -94,9 +94,9 @@ Warnings/Caveats
Git is installed. Make sure Git can be found via the PATH Git is installed. Make sure Git can be found via the PATH
environment variable. When installing Git for Windows check the "Run environment variable. When installing Git for Windows check the "Run
Git from the Windows Command Prompt" option. There are other options Git from the Windows Command Prompt" option. There are other options
like the jgit.gitprefix system property or Eclipse settings that can like Eclipse settings that can be used for pointing out where C Git
be used for pointing out where C Git is installed. Modifying PATH is is installed. Modifying PATH is the recommended option if C Git is
the recommended option if C Git is installed. installed.
- We try to use the same notation of $HOME as C Git does. On Windows - We try to use the same notation of $HOME as C Git does. On Windows
this is often not the same value as the user.home system property. this is often not the same value as the user.home system property.

View File

@ -117,7 +117,7 @@ protected void advertise(HttpServletRequest req,
try { try {
rp.sendAdvertisedRefs(pck); rp.sendAdvertisedRefs(pck);
} finally { } finally {
rp.getRevWalk().release(); rp.getRevWalk().close();
} }
} }
} }

View File

@ -117,7 +117,7 @@ protected void advertise(HttpServletRequest req,
up.setBiDirectionalPipe(false); up.setBiDirectionalPipe(false);
up.sendAdvertisedRefs(pck); up.sendAdvertisedRefs(pck);
} finally { } finally {
up.getRevWalk().release(); up.getRevWalk().close();
} }
} }
} }

View File

@ -307,7 +307,7 @@ public String indexState(int includedOptions)
*/ */
protected void resetIndex(FileTreeIterator treeItr) protected void resetIndex(FileTreeIterator treeItr)
throws FileNotFoundException, IOException { throws FileNotFoundException, IOException {
ObjectInserter inserter = db.newObjectInserter(); try (ObjectInserter inserter = db.newObjectInserter()) {
DirCacheBuilder builder = db.lockDirCache().builder(); DirCacheBuilder builder = db.lockDirCache().builder();
DirCacheEntry dce; DirCacheEntry dce;
@ -318,7 +318,8 @@ protected void resetIndex(FileTreeIterator treeItr)
dce.setFileMode(treeItr.getEntryFileMode()); dce.setFileMode(treeItr.getEntryFileMode());
dce.setLastModified(treeItr.getEntryLastModified()); dce.setLastModified(treeItr.getEntryLastModified());
dce.setLength((int) len); dce.setLength((int) len);
FileInputStream in = new FileInputStream(treeItr.getEntryFile()); FileInputStream in = new FileInputStream(
treeItr.getEntryFile());
dce.setObjectId(inserter.insert(Constants.OBJ_BLOB, len, in)); dce.setObjectId(inserter.insert(Constants.OBJ_BLOB, len, in));
in.close(); in.close();
builder.add(dce); builder.add(dce);
@ -326,7 +327,7 @@ protected void resetIndex(FileTreeIterator treeItr)
} }
builder.commit(); builder.commit();
inserter.flush(); inserter.flush();
inserter.release(); }
} }
/** /**
@ -410,14 +411,15 @@ protected void createBranch(ObjectId objectId, String branchName)
protected void checkoutBranch(String branchName) protected void checkoutBranch(String branchName)
throws IllegalStateException, IOException { throws IllegalStateException, IOException {
RevWalk walk = new RevWalk(db); try (RevWalk walk = new RevWalk(db)) {
RevCommit head = walk.parseCommit(db.resolve(Constants.HEAD)); RevCommit head = walk.parseCommit(db.resolve(Constants.HEAD));
RevCommit branch = walk.parseCommit(db.resolve(branchName)); RevCommit branch = walk.parseCommit(db.resolve(branchName));
DirCacheCheckout dco = new DirCacheCheckout(db, head.getTree().getId(), DirCacheCheckout dco = new DirCacheCheckout(db,
db.lockDirCache(), branch.getTree().getId()); head.getTree().getId(), db.lockDirCache(),
branch.getTree().getId());
dco.setFailOnConflict(true); dco.setFailOnConflict(true);
dco.checkout(); dco.checkout();
walk.release(); }
// update the HEAD // update the HEAD
RefUpdate refUpdate = db.updateRef(Constants.HEAD); RefUpdate refUpdate = db.updateRef(Constants.HEAD);
refUpdate.setRefLogMessage("checkout: moving to " + branchName, false); refUpdate.setRefLogMessage("checkout: moving to " + branchName, false);

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?pde?> <?pde?>
<!-- generated with https://github.com/mbarbero/fr.obeo.releng.targetplatform --> <!-- generated with https://github.com/mbarbero/fr.obeo.releng.targetplatform -->
<target name="jgit-4.5" sequenceNumber="1431244072"> <target name="jgit-4.5" sequenceNumber="1432590632">
<locations> <locations>
<location includeMode="slicer" includeAllPlatforms="false" includeSource="true" includeConfigurePhase="true" type="InstallableUnit"> <location includeMode="slicer" includeAllPlatforms="false" includeSource="true" includeConfigurePhase="true" type="InstallableUnit">
<unit id="org.eclipse.jetty.client" version="9.2.10.v20150310"/> <unit id="org.eclipse.jetty.client" version="9.2.10.v20150310"/>
@ -23,8 +23,8 @@
<repository id="jetty-9.2.10" location="http://download.eclipse.org/jetty/updates/jetty-bundles-9.x/9.2.10.v20150310/"/> <repository id="jetty-9.2.10" location="http://download.eclipse.org/jetty/updates/jetty-bundles-9.x/9.2.10.v20150310/"/>
</location> </location>
<location includeMode="slicer" includeAllPlatforms="false" includeSource="true" includeConfigurePhase="true" type="InstallableUnit"> <location includeMode="slicer" includeAllPlatforms="false" includeSource="true" includeConfigurePhase="true" type="InstallableUnit">
<unit id="org.apache.ant" version="1.9.4.v201410062020"/> <unit id="org.apache.ant" version="1.9.4.v201504302020"/>
<unit id="org.apache.ant.source" version="1.9.4.v201410062020"/> <unit id="org.apache.ant.source" version="1.9.4.v201504302020"/>
<unit id="org.apache.commons.compress" version="1.6.0.v201310281400"/> <unit id="org.apache.commons.compress" version="1.6.0.v201310281400"/>
<unit id="org.apache.commons.compress.source" version="1.6.0.v201310281400"/> <unit id="org.apache.commons.compress.source" version="1.6.0.v201310281400"/>
<unit id="org.apache.commons.logging" version="1.1.1.v201101211721"/> <unit id="org.apache.commons.logging" version="1.1.1.v201101211721"/>
@ -41,8 +41,8 @@
<unit id="org.hamcrest.core.source" version="1.3.0.v201303031735"/> <unit id="org.hamcrest.core.source" version="1.3.0.v201303031735"/>
<unit id="javaewah" version="0.7.9.v201401101600"/> <unit id="javaewah" version="0.7.9.v201401101600"/>
<unit id="javaewah.source" version="0.7.9.v201401101600"/> <unit id="javaewah.source" version="0.7.9.v201401101600"/>
<unit id="org.objenesis" version="1.0.0.v201105211943"/> <unit id="org.objenesis" version="1.0.0.v201505121915"/>
<unit id="org.objenesis.source" version="1.0.0.v201105211943"/> <unit id="org.objenesis.source" version="1.0.0.v201505121915"/>
<unit id="org.mockito" version="1.8.4.v201303031500"/> <unit id="org.mockito" version="1.8.4.v201303031500"/>
<unit id="org.mockito.source" version="1.8.4.v201303031500"/> <unit id="org.mockito.source" version="1.8.4.v201303031500"/>
<unit id="com.jcraft.jsch" version="0.1.51.v201410302000"/> <unit id="com.jcraft.jsch" version="0.1.51.v201410302000"/>
@ -57,7 +57,7 @@
<unit id="org.slf4j.api.source" version="1.7.2.v20121108-1250"/> <unit id="org.slf4j.api.source" version="1.7.2.v20121108-1250"/>
<unit id="org.slf4j.impl.log4j12" version="1.7.2.v20131105-2200"/> <unit id="org.slf4j.impl.log4j12" version="1.7.2.v20131105-2200"/>
<unit id="org.slf4j.impl.log4j12.source" version="1.7.2.v20131105-2200"/> <unit id="org.slf4j.impl.log4j12.source" version="1.7.2.v20131105-2200"/>
<repository location="http://download.eclipse.org/tools/orbit/downloads/drops/S20150202203538/repository/"/> <repository location="http://download.eclipse.org/tools/orbit/downloads/drops/S20150519210750/repository/"/>
</location> </location>
<location includeMode="slicer" includeAllPlatforms="false" includeSource="true" includeConfigurePhase="true" type="InstallableUnit"> <location includeMode="slicer" includeAllPlatforms="false" includeSource="true" includeConfigurePhase="true" type="InstallableUnit">
<unit id="org.eclipse.osgi" version="0.0.0"/> <unit id="org.eclipse.osgi" version="0.0.0"/>

View File

@ -1,7 +1,7 @@
target "jgit-4.5" with source configurePhase target "jgit-4.5" with source configurePhase
include "projects/jetty-9.2.10.tpd" include "projects/jetty-9.2.10.tpd"
include "orbit/S20150202203538-Mars-M5.tpd" include "orbit/S20150519210750-Mars-RC2.tpd"
location "http://download.eclipse.org/releases/mars/" { location "http://download.eclipse.org/releases/mars/" {
org.eclipse.osgi lazy org.eclipse.osgi lazy

View File

@ -1,9 +1,9 @@
target "S20141023165154-Mars-M3" with source configurePhase target "S20141023165154-Mars-M3" with source configurePhase
// see http://download.eclipse.org/tools/orbit/downloads/ // see http://download.eclipse.org/tools/orbit/downloads/
location "http://download.eclipse.org/tools/orbit/downloads/drops/S20150202203538/repository/" { location "http://download.eclipse.org/tools/orbit/downloads/drops/S20150519210750/repository/" {
org.apache.ant [1.9.4.v201410062020,1.9.4.v201410062020] org.apache.ant [1.9.4.v201504302020,1.9.4.v201504302020]
org.apache.ant.source [1.9.4.v201410062020,1.9.4.v201410062020] org.apache.ant.source [1.9.4.v201504302020,1.9.4.v201504302020]
org.apache.commons.compress [1.6.0.v201310281400,1.6.0.v201310281400] org.apache.commons.compress [1.6.0.v201310281400,1.6.0.v201310281400]
org.apache.commons.compress.source [1.6.0.v201310281400,1.6.0.v201310281400] org.apache.commons.compress.source [1.6.0.v201310281400,1.6.0.v201310281400]
org.apache.commons.logging [1.1.1.v201101211721,1.1.1.v201101211721] org.apache.commons.logging [1.1.1.v201101211721,1.1.1.v201101211721]
@ -20,8 +20,8 @@ location "http://download.eclipse.org/tools/orbit/downloads/drops/S2015020220353
org.hamcrest.core.source [1.3.0.v201303031735,1.3.0.v201303031735] org.hamcrest.core.source [1.3.0.v201303031735,1.3.0.v201303031735]
javaewah [0.7.9.v201401101600,0.7.9.v201401101600] javaewah [0.7.9.v201401101600,0.7.9.v201401101600]
javaewah.source [0.7.9.v201401101600,0.7.9.v201401101600] javaewah.source [0.7.9.v201401101600,0.7.9.v201401101600]
org.objenesis [1.0.0.v201105211943,1.0.0.v201105211943] org.objenesis [1.0.0.v201505121915,1.0.0.v201505121915]
org.objenesis.source [1.0.0.v201105211943,1.0.0.v201105211943] org.objenesis.source [1.0.0.v201505121915,1.0.0.v201505121915]
org.mockito [1.8.4.v201303031500,1.8.4.v201303031500] org.mockito [1.8.4.v201303031500,1.8.4.v201303031500]
org.mockito.source [1.8.4.v201303031500,1.8.4.v201303031500] org.mockito.source [1.8.4.v201303031500,1.8.4.v201303031500]
com.jcraft.jsch [0.1.51.v201410302000,0.1.51.v201410302000] com.jcraft.jsch [0.1.51.v201410302000,0.1.51.v201410302000]

View File

@ -214,7 +214,7 @@
<plugin> <plugin>
<groupId>org.eclipse.cbi.maven.plugins</groupId> <groupId>org.eclipse.cbi.maven.plugins</groupId>
<artifactId>eclipse-jarsigner-plugin</artifactId> <artifactId>eclipse-jarsigner-plugin</artifactId>
<version>1.1.2-SNAPSHOT</version> <version>1.1.2</version>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>

View File

@ -67,8 +67,7 @@ abstract class AbstractFetchCommand extends TextBuiltin {
private boolean verbose; private boolean verbose;
protected void showFetchResult(final FetchResult r) throws IOException { protected void showFetchResult(final FetchResult r) throws IOException {
ObjectReader reader = db.newObjectReader(); try (ObjectReader reader = db.newObjectReader()) {
try {
boolean shownURI = false; boolean shownURI = false;
for (final TrackingRefUpdate u : r.getTrackingRefUpdates()) { for (final TrackingRefUpdate u : r.getTrackingRefUpdates()) {
if (!verbose && u.getResult() == RefUpdate.Result.NO_CHANGE) if (!verbose && u.getResult() == RefUpdate.Result.NO_CHANGE)
@ -89,8 +88,6 @@ protected void showFetchResult(final FetchResult r) throws IOException {
src, dst); src, dst);
outw.println(); outw.println();
} }
} finally {
reader.release();
} }
showRemoteMessages(errw, r.getMessages()); showRemoteMessages(errw, r.getMessages());
} }

View File

@ -156,10 +156,9 @@ protected void run() throws Exception {
else else
dateFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ZZZZ"); //$NON-NLS-1$ dateFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ZZZZ"); //$NON-NLS-1$
BlameGenerator generator = new BlameGenerator(db, file);
RevFlag scanned = generator.newFlag("SCANNED"); //$NON-NLS-1$
reader = db.newObjectReader(); reader = db.newObjectReader();
try { try (BlameGenerator generator = new BlameGenerator(db, file)) {
RevFlag scanned = generator.newFlag("SCANNED"); //$NON-NLS-1$
generator.setTextComparator(comparator); generator.setTextComparator(comparator);
if (!reverseRange.isEmpty()) { if (!reverseRange.isEmpty()) {
@ -247,8 +246,7 @@ protected void run() throws Exception {
} while (++line < end && blame.getSourceCommit(line) == c); } while (++line < end && blame.getSourceCommit(line) == c);
} }
} finally { } finally {
generator.release(); reader.close();
reader.release();
} }
} }

View File

@ -204,15 +204,12 @@ else if (remote)
addRefs(refs, Constants.R_HEADS); addRefs(refs, Constants.R_HEADS);
addRefs(refs, Constants.R_REMOTES); addRefs(refs, Constants.R_REMOTES);
ObjectReader reader = db.newObjectReader(); try (ObjectReader reader = db.newObjectReader()) {
try {
for (final Entry<String, Ref> e : printRefs.entrySet()) { for (final Entry<String, Ref> e : printRefs.entrySet()) {
final Ref ref = e.getValue(); final Ref ref = e.getValue();
printHead(reader, e.getKey(), printHead(reader, e.getKey(),
current.equals(ref.getName()), ref); current.equals(ref.getName()), ref);
} }
} finally {
reader.release();
} }
} }
} }

View File

@ -184,11 +184,8 @@ protected void run() throws Exception {
if (head == null) if (head == null)
die(MessageFormat.format(CLIText.get().notATree, HEAD)); die(MessageFormat.format(CLIText.get().notATree, HEAD));
CanonicalTreeParser p = new CanonicalTreeParser(); CanonicalTreeParser p = new CanonicalTreeParser();
ObjectReader reader = db.newObjectReader(); try (ObjectReader reader = db.newObjectReader()) {
try {
p.reset(reader, head); p.reset(reader, head);
} finally {
reader.release();
} }
oldTree = p; oldTree = p;
} }
@ -219,7 +216,7 @@ protected void run() throws Exception {
diffFmt.flush(); diffFmt.flush();
} }
} finally { } finally {
diffFmt.release(); diffFmt.close();
} }
} }

View File

@ -63,8 +63,7 @@ class IndexPack extends TextBuiltin {
@Override @Override
protected void run() throws Exception { protected void run() throws Exception {
BufferedInputStream in = new BufferedInputStream(ins); BufferedInputStream in = new BufferedInputStream(ins);
ObjectInserter inserter = db.newObjectInserter(); try (ObjectInserter inserter = db.newObjectInserter()) {
try {
PackParser p = inserter.newPackParser(in); PackParser p = inserter.newPackParser(in);
p.setAllowThin(fixThin); p.setAllowThin(fixThin);
if (indexVersion != -1 && p instanceof ObjectDirectoryPackParser) { if (indexVersion != -1 && p instanceof ObjectDirectoryPackParser) {
@ -73,8 +72,6 @@ protected void run() throws Exception {
} }
p.parse(new TextProgressMonitor(errw)); p.parse(new TextProgressMonitor(errw));
inserter.flush(); inserter.flush();
} finally {
inserter.release();
} }
} }
} }

View File

@ -223,7 +223,7 @@ protected void run() throws Exception {
super.run(); super.run();
} finally { } finally {
diffFmt.release(); diffFmt.close();
} }
} }

View File

@ -125,11 +125,8 @@ protected void run() throws Exception {
push.setTimeout(timeout); push.setTimeout(timeout);
Iterable<PushResult> results = push.call(); Iterable<PushResult> results = push.call();
for (PushResult result : results) { for (PushResult result : results) {
ObjectReader reader = db.newObjectReader(); try (ObjectReader reader = db.newObjectReader()) {
try {
printPushResult(reader, result.getURI(), result); printPushResult(reader, result.getURI(), result);
} finally {
reader.release();
} }
} }
} }

View File

@ -184,8 +184,7 @@ protected void run() throws Exception {
else else
objectId = db.resolve(objectName); objectId = db.resolve(objectName);
RevWalk rw = new RevWalk(db); try (RevWalk rw = new RevWalk(db)) {
try {
RevObject obj = rw.parseAny(objectId); RevObject obj = rw.parseAny(objectId);
while (obj instanceof RevTag) { while (obj instanceof RevTag) {
show((RevTag) obj); show((RevTag) obj);
@ -216,11 +215,9 @@ protected void run() throws Exception {
CLIText.get().cannotReadBecause, obj.name(), CLIText.get().cannotReadBecause, obj.name(),
obj.getType())); obj.getType()));
} }
} finally {
rw.release();
} }
} finally { } finally {
diffFmt.release(); diffFmt.close();
} }
} }

View File

@ -173,8 +173,7 @@ private void run(Repository db) throws Exception {
int maxN = 0; int maxN = 0;
AbbreviatedObjectId startId; AbbreviatedObjectId startId;
ObjectReader or = db.newObjectReader(); try (ObjectReader or = db.newObjectReader()) {
try {
final MutableObjectId id = new MutableObjectId(); final MutableObjectId id = new MutableObjectId();
RevWalk rw = new RevWalk(or); RevWalk rw = new RevWalk(or);
TreeWalk tw = new TreeWalk(or); TreeWalk tw = new TreeWalk(or);
@ -232,8 +231,6 @@ private void run(Repository db) throws Exception {
if (count > 0 && files > count) if (count > 0 && files > count)
break; break;
} }
} finally {
or.release();
} }
Collections.sort(all, new Comparator<Test>() { Collections.sort(all, new Comparator<Test>() {

View File

@ -134,12 +134,12 @@ protected void run() throws Exception {
} }
private void recreateCommitGraph() throws IOException { private void recreateCommitGraph() throws IOException {
final RevWalk rw = new RevWalk(db);
final Map<ObjectId, ToRewrite> toRewrite = new HashMap<ObjectId, ToRewrite>(); final Map<ObjectId, ToRewrite> toRewrite = new HashMap<ObjectId, ToRewrite>();
List<ToRewrite> queue = new ArrayList<ToRewrite>(); List<ToRewrite> queue = new ArrayList<ToRewrite>();
final BufferedReader br = new BufferedReader(new InputStreamReader( try (RevWalk rw = new RevWalk(db);
new FileInputStream(graph), Constants.CHARSET)); final BufferedReader br = new BufferedReader(
try { new InputStreamReader(new FileInputStream(graph),
Constants.CHARSET))) {
String line; String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
final String[] parts = line.split("[ \t]{1,}"); //$NON-NLS-1$ final String[] parts = line.split("[ \t]{1,}"); //$NON-NLS-1$
@ -162,13 +162,12 @@ private void recreateCommitGraph() throws IOException {
toRewrite.put(oldId, t); toRewrite.put(oldId, t);
queue.add(t); queue.add(t);
} }
} finally {
br.close();
} }
pm.beginTask("Rewriting commits", queue.size()); pm.beginTask("Rewriting commits", queue.size());
final ObjectInserter oi = db.newObjectInserter(); try (ObjectInserter oi = db.newObjectInserter()) {
final ObjectId emptyTree = oi.insert(Constants.OBJ_TREE, new byte[] {}); final ObjectId emptyTree = oi.insert(Constants.OBJ_TREE,
new byte[] {});
final PersonIdent me = new PersonIdent("jgit rebuild-commitgraph", //$NON-NLS-1$ final PersonIdent me = new PersonIdent("jgit rebuild-commitgraph", //$NON-NLS-1$
"rebuild-commitgraph@localhost"); //$NON-NLS-1$ "rebuild-commitgraph@localhost"); //$NON-NLS-1$
while (!queue.isEmpty()) { while (!queue.isEmpty()) {
@ -182,7 +181,8 @@ private void recreateCommitGraph() throws IOException {
final ToRewrite p = toRewrite.get(t.oldParents[k]); final ToRewrite p = toRewrite.get(t.oldParents[k]);
if (p != null) { if (p != null) {
if (p.newId == null) { if (p.newId == null) {
// Must defer until after the parent is rewritten. // Must defer until after the parent is
// rewritten.
queue.add(t); queue.add(t);
continue REWRITE; continue REWRITE;
} else { } else {
@ -207,7 +207,7 @@ private void recreateCommitGraph() throws IOException {
} }
} }
oi.flush(); oi.flush();
oi.release(); }
pm.endTask(); pm.endTask();
} }
@ -275,11 +275,11 @@ protected void writeFile(final String name, final byte[] content)
} }
private Map<String, Ref> computeNewRefs() throws IOException { private Map<String, Ref> computeNewRefs() throws IOException {
final RevWalk rw = new RevWalk(db);
final Map<String, Ref> refs = new HashMap<String, Ref>(); final Map<String, Ref> refs = new HashMap<String, Ref>();
final BufferedReader br = new BufferedReader(new InputStreamReader( try (RevWalk rw = new RevWalk(db);
new FileInputStream(refList), Constants.CHARSET)); BufferedReader br = new BufferedReader(
try { new InputStreamReader(new FileInputStream(refList),
Constants.CHARSET))) {
String line; String line;
while ((line = br.readLine()) != null) { while ((line = br.readLine()) != null) {
final String[] parts = line.split("[ \t]{1,}"); //$NON-NLS-1$ final String[] parts = line.split("[ \t]{1,}"); //$NON-NLS-1$
@ -302,9 +302,6 @@ private Map<String, Ref> computeNewRefs() throws IOException {
refs.put(name, new ObjectIdRef.Unpeeled(Ref.Storage.PACKED, refs.put(name, new ObjectIdRef.Unpeeled(Ref.Storage.PACKED,
name, id)); name, id));
} }
} finally {
rw.release();
br.close();
} }
return refs; return refs;
} }

View File

@ -300,8 +300,7 @@ private void run(Repository db) throws Exception {
long fileCnt = 0; long fileCnt = 0;
long lineCnt = 0; long lineCnt = 0;
ObjectReader or = db.newObjectReader(); try (ObjectReader or = db.newObjectReader()) {
try {
final MutableObjectId id = new MutableObjectId(); final MutableObjectId id = new MutableObjectId();
RevWalk rw = new RevWalk(or); RevWalk rw = new RevWalk(or);
TreeWalk tw = new TreeWalk(or); TreeWalk tw = new TreeWalk(or);
@ -340,8 +339,6 @@ private void run(Repository db) throws Exception {
for (Function fun : all) for (Function fun : all)
testOne(fun, txt, lines, cnt); testOne(fun, txt, lines, cnt);
} }
} finally {
or.release();
} }
if (db.getDirectory() != null) { if (db.getDirectory() != null) {

View File

@ -125,8 +125,7 @@ public int parseArguments(final Parameters params) throws CmdLineException {
throw new CmdLineException(MessageFormat.format(CLIText.get().notATree, name)); throw new CmdLineException(MessageFormat.format(CLIText.get().notATree, name));
final CanonicalTreeParser p = new CanonicalTreeParser(); final CanonicalTreeParser p = new CanonicalTreeParser();
final ObjectReader curs = clp.getRepository().newObjectReader(); try (ObjectReader curs = clp.getRepository().newObjectReader()) {
try {
p.reset(curs, clp.getRevWalk().parseTree(id)); p.reset(curs, clp.getRevWalk().parseTree(id));
} catch (MissingObjectException e) { } catch (MissingObjectException e) {
throw new CmdLineException(MessageFormat.format(CLIText.get().notATree, name)); throw new CmdLineException(MessageFormat.format(CLIText.get().notATree, name));
@ -134,8 +133,6 @@ public int parseArguments(final Parameters params) throws CmdLineException {
throw new CmdLineException(MessageFormat.format(CLIText.get().notATree, name)); throw new CmdLineException(MessageFormat.format(CLIText.get().notATree, name));
} catch (IOException e) { } catch (IOException e) {
throw new CmdLineException(MessageFormat.format(CLIText.get().cannotReadBecause, name, e.getMessage())); throw new CmdLineException(MessageFormat.format(CLIText.get().cannotReadBecause, name, e.getMessage()));
} finally {
curs.release();
} }
setter.addValue(p); setter.addValue(p);

View File

@ -624,7 +624,7 @@ public FS newInstance() {
return this; return this;
} }
protected File discoverGitPrefix() { protected File discoverGitExe() {
return null; return null;
} }
@ -669,7 +669,7 @@ public FS newInstance() {
return this; return this;
} }
protected File discoverGitPrefix() { protected File discoverGitExe() {
return null; return null;
} }

View File

@ -414,17 +414,19 @@ public void testCloneRepositoryWithSubmodules() throws Exception {
assertEquals(commit, pathStatus.getHeadId()); assertEquals(commit, pathStatus.getHeadId());
assertEquals(commit, pathStatus.getIndexId()); assertEquals(commit, pathStatus.getIndexId());
SubmoduleWalk walk = SubmoduleWalk.forIndex(git2.getRepository()); try (SubmoduleWalk walk = SubmoduleWalk
.forIndex(git2.getRepository())) {
assertTrue(walk.next()); assertTrue(walk.next());
Repository clonedSub1 = walk.getRepository(); Repository clonedSub1 = walk.getRepository();
addRepoToClose(clonedSub1); addRepoToClose(clonedSub1);
assertNotNull(clonedSub1); assertNotNull(clonedSub1);
assertEquals(new File(git2.getRepository().getWorkTree(),
walk.getPath()), clonedSub1.getWorkTree());
assertEquals( assertEquals(
new File(git2.getRepository().getWorkTree(), walk.getPath()), new File(new File(git2.getRepository().getDirectory(),
clonedSub1.getWorkTree()); "modules"), walk.getPath()),
assertEquals(new File(new File(git2.getRepository().getDirectory(), clonedSub1.getDirectory());
"modules"), walk.getPath()), clonedSub1.getDirectory()); }
walk.release();
} }
@Test @Test

View File

@ -108,7 +108,7 @@ public FS newInstance() {
return this; return this;
} }
protected File discoverGitPrefix() { protected File discoverGitExe() {
return null; return null;
} }
@ -153,7 +153,7 @@ public FS newInstance() {
return this; return this;
} }
protected File discoverGitPrefix() { protected File discoverGitExe() {
return null; return null;
} }
@ -509,9 +509,9 @@ public void commitOnlyShouldCommitUnmergedPathAndNotAffectOthers()
+ "[unmerged2, mode:100644, stage:3]", + "[unmerged2, mode:100644, stage:3]",
indexState(0)); indexState(0));
TreeWalk walk = TreeWalk.forPath(db, "unmerged1", commit.getTree()); try (TreeWalk walk = TreeWalk.forPath(db, "unmerged1", commit.getTree())) {
assertEquals(FileMode.REGULAR_FILE, walk.getFileMode(0)); assertEquals(FileMode.REGULAR_FILE, walk.getFileMode(0));
walk.release(); }
} }
private static void addUnmergedEntry(String file, DirCacheBuilder builder) { private static void addUnmergedEntry(String file, DirCacheBuilder builder) {

View File

@ -247,12 +247,9 @@ private AbstractTreeIterator getTreeIterator(String name)
if (id == null) if (id == null)
throw new IllegalArgumentException(name); throw new IllegalArgumentException(name);
final CanonicalTreeParser p = new CanonicalTreeParser(); final CanonicalTreeParser p = new CanonicalTreeParser();
final ObjectReader or = db.newObjectReader(); try (ObjectReader or = db.newObjectReader()) {
try {
p.reset(or, new RevWalk(db).parseTree(id)); p.reset(or, new RevWalk(db).parseTree(id));
return p; return p;
} finally {
or.release();
} }
} }
} }

View File

@ -193,8 +193,8 @@ public void testUpdateWorkingDirectoryFromIndex2() throws Exception {
public static void validateIndex(Git git) throws NoWorkTreeException, public static void validateIndex(Git git) throws NoWorkTreeException,
IOException { IOException {
DirCache dc = git.getRepository().lockDirCache(); DirCache dc = git.getRepository().lockDirCache();
ObjectReader r = git.getRepository().getObjectDatabase().newReader(); try (ObjectReader r = git.getRepository().getObjectDatabase()
try { .newReader()) {
for (int i = 0; i < dc.getEntryCount(); ++i) { for (int i = 0; i < dc.getEntryCount(); ++i) {
DirCacheEntry entry = dc.getEntry(i); DirCacheEntry entry = dc.getEntry(i);
if (entry.getLength() > 0) if (entry.getLength() > 0)
@ -203,7 +203,6 @@ public static void validateIndex(Git git) throws NoWorkTreeException,
} }
} finally { } finally {
dc.unlock(); dc.unlock();
r.release();
} }
} }

View File

@ -474,7 +474,7 @@ private void doTestPullWithRebase(Callable<PullResult> pullSetup,
} }
assertFileContentsEqual(sourceFile, "content"); assertFileContentsEqual(sourceFile, "content");
RevWalk rw = new RevWalk(dbTarget); try (RevWalk rw = new RevWalk(dbTarget)) {
rw.sort(RevSort.TOPO); rw.sort(RevSort.TOPO);
rw.markStart(rw.parseCommit(dbTarget.resolve("refs/heads/master"))); rw.markStart(rw.parseCommit(dbTarget.resolve("refs/heads/master")));
@ -497,11 +497,12 @@ private void doTestPullWithRebase(Callable<PullResult> pullSetup,
next = rw.next(); next = rw.next();
assertEquals(sourceCommit, next); assertEquals(sourceCommit, next);
next = rw.next(); next = rw.next();
assertEquals("Initial commit for source", next.getShortMessage()); assertEquals("Initial commit for source",
next.getShortMessage());
next = rw.next(); next = rw.next();
assertNull(next); assertNull(next);
} }
rw.release(); }
} }
@Override @Override

View File

@ -114,13 +114,14 @@ public void setUp() throws Exception {
private void checkoutCommit(RevCommit commit) throws IllegalStateException, private void checkoutCommit(RevCommit commit) throws IllegalStateException,
IOException { IOException {
RevWalk walk = new RevWalk(db); RevCommit head;
RevCommit head = walk.parseCommit(db.resolve(Constants.HEAD)); try (RevWalk walk = new RevWalk(db)) {
DirCacheCheckout dco = new DirCacheCheckout(db, head.getTree(), db head = walk.parseCommit(db.resolve(Constants.HEAD));
.lockDirCache(), commit.getTree()); DirCacheCheckout dco = new DirCacheCheckout(db, head.getTree(),
db.lockDirCache(), commit.getTree());
dco.setFailOnConflict(true); dco.setFailOnConflict(true);
dco.checkout(); dco.checkout();
walk.release(); }
// update the HEAD // update the HEAD
RefUpdate refUpdate = db.updateRef(Constants.HEAD, true); RefUpdate refUpdate = db.updateRef(Constants.HEAD, true);
refUpdate.setNewObjectId(commit); refUpdate.setNewObjectId(commit);
@ -472,12 +473,13 @@ private void doTestRebasePreservingMerges(boolean testConflict)
} }
private String readFile(String path, RevCommit commit) throws IOException { private String readFile(String path, RevCommit commit) throws IOException {
TreeWalk walk = TreeWalk.forPath(db, path, commit.getTree()); try (TreeWalk walk = TreeWalk.forPath(db, path, commit.getTree())) {
ObjectLoader loader = db.open(walk.getObjectId(0), Constants.OBJ_BLOB); ObjectLoader loader = db.open(walk.getObjectId(0),
Constants.OBJ_BLOB);
String result = RawParseUtils.decode(loader.getCachedBytes()); String result = RawParseUtils.decode(loader.getCachedBytes());
walk.release();
return result; return result;
} }
}
@Test @Test
public void testRebasePreservingMergesWithUnrelatedSide1() throws Exception { public void testRebasePreservingMergesWithUnrelatedSide1() throws Exception {
@ -2073,14 +2075,11 @@ private TreeWalk createTreeWalk() {
private List<DiffEntry> diffWorkingAgainstHead(final RevCommit commit, private List<DiffEntry> diffWorkingAgainstHead(final RevCommit commit,
RevWalk revWalk) RevWalk revWalk)
throws IOException { throws IOException {
TreeWalk walk = createTreeWalk();
RevCommit parentCommit = revWalk.parseCommit(commit.getParent(0)); RevCommit parentCommit = revWalk.parseCommit(commit.getParent(0));
try { try (TreeWalk walk = createTreeWalk()) {
walk.addTree(parentCommit.getTree()); walk.addTree(parentCommit.getTree());
walk.addTree(commit.getTree()); walk.addTree(commit.getTree());
return DiffEntry.scan(walk); return DiffEntry.scan(walk);
} finally {
walk.release();
} }
} }

View File

@ -537,16 +537,10 @@ private void assertReflog(ObjectId prevHead, ObjectId head)
*/ */
private boolean inHead(String path) throws IOException { private boolean inHead(String path) throws IOException {
ObjectId headId = db.resolve(Constants.HEAD); ObjectId headId = db.resolve(Constants.HEAD);
RevWalk rw = new RevWalk(db); try (RevWalk rw = new RevWalk(db);
TreeWalk tw = null; TreeWalk tw = TreeWalk.forPath(db, path,
try { rw.parseTree(headId))) {
tw = TreeWalk.forPath(db, path, rw.parseTree(headId));
return tw != null; return tw != null;
} finally {
rw.release();
rw.dispose();
if (tw != null)
tw.release();
} }
} }

View File

@ -118,12 +118,9 @@ private void validateStashedCommit(final RevCommit commit,
assertEquals(parentCount, commit.getParentCount()); assertEquals(parentCount, commit.getParentCount());
// Load parents // Load parents
RevWalk walk = new RevWalk(db); try (RevWalk walk = new RevWalk(db)) {
try {
for (RevCommit parent : commit.getParents()) for (RevCommit parent : commit.getParents())
walk.parseBody(parent); walk.parseBody(parent);
} finally {
walk.release();
} }
assertEquals(1, commit.getParent(1).getParentCount()); assertEquals(1, commit.getParent(1).getParentCount());
@ -144,37 +141,28 @@ private TreeWalk createTreeWalk() {
private List<DiffEntry> diffWorkingAgainstHead(final RevCommit commit) private List<DiffEntry> diffWorkingAgainstHead(final RevCommit commit)
throws IOException { throws IOException {
TreeWalk walk = createTreeWalk(); try (TreeWalk walk = createTreeWalk()) {
try {
walk.addTree(commit.getParent(0).getTree()); walk.addTree(commit.getParent(0).getTree());
walk.addTree(commit.getTree()); walk.addTree(commit.getTree());
return DiffEntry.scan(walk); return DiffEntry.scan(walk);
} finally {
walk.release();
} }
} }
private List<DiffEntry> diffIndexAgainstHead(final RevCommit commit) private List<DiffEntry> diffIndexAgainstHead(final RevCommit commit)
throws IOException { throws IOException {
TreeWalk walk = createTreeWalk(); try (TreeWalk walk = createTreeWalk()) {
try {
walk.addTree(commit.getParent(0).getTree()); walk.addTree(commit.getParent(0).getTree());
walk.addTree(commit.getParent(1).getTree()); walk.addTree(commit.getParent(1).getTree());
return DiffEntry.scan(walk); return DiffEntry.scan(walk);
} finally {
walk.release();
} }
} }
private List<DiffEntry> diffIndexAgainstWorking(final RevCommit commit) private List<DiffEntry> diffIndexAgainstWorking(final RevCommit commit)
throws IOException { throws IOException {
TreeWalk walk = createTreeWalk(); try (TreeWalk walk = createTreeWalk()) {
try {
walk.addTree(commit.getParent(1).getTree()); walk.addTree(commit.getParent(1).getTree());
walk.addTree(commit.getTree()); walk.addTree(commit.getTree());
return DiffEntry.scan(walk); return DiffEntry.scan(walk);
} finally {
walk.release();
} }
} }
@ -224,11 +212,12 @@ public void newFileInIndexThenModifiedInWorkTree() throws Exception {
writeTrashFile("file", "content2"); writeTrashFile("file", "content2");
RevCommit stashedWorkTree = Git.wrap(db).stashCreate().call(); RevCommit stashedWorkTree = Git.wrap(db).stashCreate().call();
validateStashedCommit(stashedWorkTree); validateStashedCommit(stashedWorkTree);
RevWalk walk = new RevWalk(db); try (RevWalk walk = new RevWalk(db)) {
RevCommit stashedIndex = stashedWorkTree.getParent(1); RevCommit stashedIndex = stashedWorkTree.getParent(1);
walk.parseBody(stashedIndex); walk.parseBody(stashedIndex);
walk.parseBody(stashedIndex.getTree()); walk.parseBody(stashedIndex.getTree());
walk.parseBody(stashedIndex.getParent(0)); walk.parseBody(stashedIndex.getParent(0));
}
List<DiffEntry> workTreeStashAgainstWorkTree = diffWorkingAgainstHead(stashedWorkTree); List<DiffEntry> workTreeStashAgainstWorkTree = diffWorkingAgainstHead(stashedWorkTree);
assertEquals(1, workTreeStashAgainstWorkTree.size()); assertEquals(1, workTreeStashAgainstWorkTree.size());
List<DiffEntry> workIndexAgainstWorkTree = diffIndexAgainstHead(stashedWorkTree); List<DiffEntry> workIndexAgainstWorkTree = diffIndexAgainstHead(stashedWorkTree);

View File

@ -70,8 +70,7 @@ public void testBoundLineDelete() throws Exception {
git.add().addFilepattern("file.txt").call(); git.add().addFilepattern("file.txt").call();
RevCommit c2 = git.commit().setMessage("create file").call(); RevCommit c2 = git.commit().setMessage("create file").call();
BlameGenerator generator = new BlameGenerator(db, "file.txt"); try (BlameGenerator generator = new BlameGenerator(db, "file.txt")) {
try {
generator.push(null, db.resolve(Constants.HEAD)); generator.push(null, db.resolve(Constants.HEAD));
assertEquals(3, generator.getResultContents().size()); assertEquals(3, generator.getResultContents().size());
@ -94,8 +93,6 @@ public void testBoundLineDelete() throws Exception {
assertEquals("file.txt", generator.getSourcePath()); assertEquals("file.txt", generator.getSourcePath());
assertFalse(generator.next()); assertFalse(generator.next());
} finally {
generator.release();
} }
} }
@ -123,8 +120,7 @@ public void testRenamedBoundLineDelete() throws Exception {
git.add().addFilepattern(FILENAME_2).call(); git.add().addFilepattern(FILENAME_2).call();
RevCommit c2 = git.commit().setMessage("change file2").call(); RevCommit c2 = git.commit().setMessage("change file2").call();
BlameGenerator generator = new BlameGenerator(db, FILENAME_2); try (BlameGenerator generator = new BlameGenerator(db, FILENAME_2)) {
try {
generator.push(null, db.resolve(Constants.HEAD)); generator.push(null, db.resolve(Constants.HEAD));
assertEquals(3, generator.getResultContents().size()); assertEquals(3, generator.getResultContents().size());
@ -147,13 +143,10 @@ public void testRenamedBoundLineDelete() throws Exception {
assertEquals(FILENAME_1, generator.getSourcePath()); assertEquals(FILENAME_1, generator.getSourcePath());
assertFalse(generator.next()); assertFalse(generator.next());
} finally {
generator.release();
} }
// and test again with other BlameGenerator API: // and test again with other BlameGenerator API:
generator = new BlameGenerator(db, FILENAME_2); try (BlameGenerator generator = new BlameGenerator(db, FILENAME_2)) {
try {
generator.push(null, db.resolve(Constants.HEAD)); generator.push(null, db.resolve(Constants.HEAD));
BlameResult result = generator.computeBlameResult(); BlameResult result = generator.computeBlameResult();
@ -167,9 +160,6 @@ public void testRenamedBoundLineDelete() throws Exception {
assertEquals(c1, result.getSourceCommit(2)); assertEquals(c1, result.getSourceCommit(2));
assertEquals(FILENAME_1, result.getSourcePath(2)); assertEquals(FILENAME_1, result.getSourcePath(2));
} finally {
generator.release();
} }
} }
@ -193,8 +183,7 @@ public void testLinesAllDeletedShortenedWalk() throws Exception {
git.add().addFilepattern("file.txt").call(); git.add().addFilepattern("file.txt").call();
RevCommit c3 = git.commit().setMessage("create file").call(); RevCommit c3 = git.commit().setMessage("create file").call();
BlameGenerator generator = new BlameGenerator(db, "file.txt"); try (BlameGenerator generator = new BlameGenerator(db, "file.txt")) {
try {
generator.push(null, db.resolve(Constants.HEAD)); generator.push(null, db.resolve(Constants.HEAD));
assertEquals(3, generator.getResultContents().size()); assertEquals(3, generator.getResultContents().size());
@ -204,8 +193,6 @@ public void testLinesAllDeletedShortenedWalk() throws Exception {
assertEquals(3, generator.getResultEnd()); assertEquals(3, generator.getResultEnd());
assertFalse(generator.next()); assertFalse(generator.next());
} finally {
generator.release();
} }
} }

View File

@ -98,8 +98,9 @@ public void setUp() throws Exception {
@Override @Override
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
if (df != null) if (df != null) {
df.release(); df.close();
}
super.tearDown(); super.tearDown();
} }

View File

@ -0,0 +1,112 @@
/*
* Copyright (C) 2015, Google Inc.
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, Inc. nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.eclipse.jgit.gitrepo;
import static org.junit.Assert.assertTrue;
import java.io.StringBufferInputStream;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
public class ManifestParserTest {
@Test
public void testManifestParser() throws Exception {
String baseUrl = "https://git.google.com/";
StringBuilder xmlContent = new StringBuilder();
Set<String> results = new HashSet<String>();
xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
.append("<manifest>")
.append("<remote name=\"remote1\" fetch=\".\" />")
.append("<default revision=\"master\" remote=\"remote1\" />")
.append("<project path=\"foo\" name=\"")
.append("foo")
.append("\" groups=\"a,test\" />")
.append("<project path=\"bar\" name=\"")
.append("bar")
.append("\" groups=\"notdefault\" />")
.append("<project path=\"foo/a\" name=\"")
.append("a")
.append("\" groups=\"a\" />")
.append("<project path=\"b\" name=\"")
.append("b")
.append("\" groups=\"b\" />")
.append("</manifest>");
ManifestParser parser = new ManifestParser(
null, null, "master", baseUrl, null, null);
parser.read(new StringBufferInputStream(xmlContent.toString()));
// Unfiltered projects should have them all.
results.clear();
results.add("foo");
results.add("bar");
results.add("foo/a");
results.add("b");
for (RepoProject proj : parser.getProjects()) {
String msg = String.format(
"project \"%s\" should be included in unfiltered projects",
proj.path);
assertTrue(msg, results.contains(proj.path));
results.remove(proj.path);
}
assertTrue(
"Unfiltered projects shouldn't contain any unexpected results",
results.isEmpty());
// Filtered projects should have foo & b
results.clear();
results.add("foo");
results.add("b");
for (RepoProject proj : parser.getFilteredProjects()) {
String msg = String.format(
"project \"%s\" should be included in filtered projects",
proj.path);
assertTrue(msg, results.contains(proj.path));
results.remove(proj.path);
}
assertTrue(
"Filtered projects shouldn't contain any unexpected results",
results.isEmpty());
}
}

View File

@ -78,12 +78,11 @@ public void setUp() {
@Test @Test
public void testInserterDiscardsPack() throws IOException { public void testInserterDiscardsPack() throws IOException {
ObjectInserter ins = db.newObjectInserter(); try (ObjectInserter ins = db.newObjectInserter()) {
ins.insert(Constants.OBJ_BLOB, Constants.encode("foo")); ins.insert(Constants.OBJ_BLOB, Constants.encode("foo"));
ins.insert(Constants.OBJ_BLOB, Constants.encode("bar")); ins.insert(Constants.OBJ_BLOB, Constants.encode("bar"));
assertEquals(0, db.getObjectDatabase().listPacks().size()); assertEquals(0, db.getObjectDatabase().listPacks().size());
}
ins.release();
assertEquals(0, db.getObjectDatabase().listPacks().size()); assertEquals(0, db.getObjectDatabase().listPacks().size());
} }

View File

@ -94,8 +94,9 @@ public void setUp() throws Exception {
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
if (reader != null) if (reader != null) {
reader.release(); reader.close();
}
} }
@Test @Test

View File

@ -150,11 +150,11 @@ public void testObjectMovedWithinPack()
// within the pack has been modified. // within the pack has been modified.
// //
final RevObject o2 = writeBlob(eden, "o2"); final RevObject o2 = writeBlob(eden, "o2");
final PackWriter pw = new PackWriter(eden); try (PackWriter pw = new PackWriter(eden)) {
pw.addObject(o2); pw.addObject(o2);
pw.addObject(o1); pw.addObject(o1);
write(out1, pw); write(out1, pw);
pw.release(); }
// Try the old name, then the new name. The old name should cause the // Try the old name, then the new name. The old name should cause the
// pack to reload when it opens and the index and pack mismatch. // pack to reload when it opens and the index and pack mismatch.
@ -216,7 +216,7 @@ private RevObject parse(final AnyObjectId id)
private File[] pack(final Repository src, final RevObject... list) private File[] pack(final Repository src, final RevObject... list)
throws IOException { throws IOException {
final PackWriter pw = new PackWriter(src); try (PackWriter pw = new PackWriter(src)) {
for (final RevObject o : list) { for (final RevObject o : list) {
pw.addObject(o); pw.addObject(o);
} }
@ -226,9 +226,9 @@ private File[] pack(final Repository src, final RevObject... list)
final File idxFile = fullPackFileName(name, ".idx"); final File idxFile = fullPackFileName(name, ".idx");
final File[] files = new File[] { packFile, idxFile }; final File[] files = new File[] { packFile, idxFile };
write(files, pw); write(files, pw);
pw.release();
return files; return files;
} }
}
private static void write(final File[] files, final PackWriter pw) private static void write(final File[] files, final PackWriter pw)
throws IOException { throws IOException {
@ -282,13 +282,10 @@ private RevObject writeBlob(final Repository repo, final String data)
throws IOException { throws IOException {
final RevWalk revWalk = new RevWalk(repo); final RevWalk revWalk = new RevWalk(repo);
final byte[] bytes = Constants.encode(data); final byte[] bytes = Constants.encode(data);
final ObjectInserter inserter = repo.newObjectInserter();
final ObjectId id; final ObjectId id;
try { try (ObjectInserter inserter = repo.newObjectInserter()) {
id = inserter.insert(Constants.OBJ_BLOB, bytes); id = inserter.insert(Constants.OBJ_BLOB, bytes);
inserter.flush(); inserter.flush();
} finally {
inserter.release();
} }
try { try {
parse(id); parse(id);

View File

@ -373,8 +373,9 @@ private static byte[] digest(TemporaryBuffer.Heap buf)
@After @After
public void release() { public void release() {
if (inserter != null) if (inserter != null) {
inserter.release(); inserter.close();
}
} }
private PackParser index(byte[] raw) throws IOException { private PackParser index(byte[] raw) throws IOException {

View File

@ -120,11 +120,11 @@ public void setUp() throws Exception {
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
if (writer != null) { if (writer != null) {
writer.release(); writer.close();
writer = null; writer = null;
} }
if (inserter != null) { if (inserter != null) {
inserter.release(); inserter.close();
inserter = null; inserter = null;
} }
super.tearDown(); super.tearDown();
@ -514,7 +514,7 @@ private static void assertContent(PackIndex pi, List<ObjectId> expected) {
private static PackIndex writePack(FileRepository repo, private static PackIndex writePack(FileRepository repo,
Set<? extends ObjectId> want, Set<ObjectIdSet> excludeObjects) Set<? extends ObjectId> want, Set<ObjectIdSet> excludeObjects)
throws IOException { throws IOException {
PackWriter pw = new PackWriter(repo); try (PackWriter pw = new PackWriter(repo)) {
pw.setDeltaBaseAsOffset(true); pw.setDeltaBaseAsOffset(true);
pw.setReuseDeltaCommits(false); pw.setReuseDeltaCommits(false);
for (ObjectIdSet idx : excludeObjects) for (ObjectIdSet idx : excludeObjects)
@ -532,9 +532,9 @@ private static PackIndex writePack(FileRepository repo,
FileOutputStream idxOS = new FileOutputStream(idxFile); FileOutputStream idxOS = new FileOutputStream(idxFile);
pw.writeIndex(idxOS); pw.writeIndex(idxOS);
idxOS.close(); idxOS.close();
pw.release();
return PackIndex.open(idxFile); return PackIndex.open(idxFile);
} }
}
// TODO: testWritePackDeltasCycle() // TODO: testWritePackDeltasCycle()
// TODO: testWritePackDeltasDepth() // TODO: testWritePackDeltasDepth()
@ -639,7 +639,7 @@ private void createVerifyOpenPack(final Set<ObjectId> interestings,
writer.setIgnoreMissingUninteresting(ignoreMissingUninteresting); writer.setIgnoreMissingUninteresting(ignoreMissingUninteresting);
writer.preparePack(m, interestings, uninterestings); writer.preparePack(m, interestings, uninterestings);
writer.writePack(m, m, os); writer.writePack(m, m, os);
writer.release(); writer.close();
verifyOpenPack(thin); verifyOpenPack(thin);
} }
@ -650,7 +650,7 @@ private void createVerifyOpenPack(final List<RevObject> objectSource)
writer.preparePack(objectSource.iterator()); writer.preparePack(objectSource.iterator());
assertEquals(objectSource.size(), writer.getObjectCount()); assertEquals(objectSource.size(), writer.getObjectCount());
writer.writePack(m, m, os); writer.writePack(m, m, os);
writer.release(); writer.close();
verifyOpenPack(false); verifyOpenPack(false);
} }

View File

@ -304,11 +304,12 @@ public void test002_WriteEmptyTree() throws IOException {
// object (as it already exists in the pack). // object (as it already exists in the pack).
// //
final Repository newdb = createBareRepository(); final Repository newdb = createBareRepository();
final ObjectInserter oi = newdb.newObjectInserter(); try (final ObjectInserter oi = newdb.newObjectInserter()) {
final ObjectId treeId = oi.insert(new TreeFormatter()); final ObjectId treeId = oi.insert(new TreeFormatter());
oi.release(); assertEquals("4b825dc642cb6eb9a060e54bf8d69288fbee4904",
treeId.name());
}
assertEquals("4b825dc642cb6eb9a060e54bf8d69288fbee4904", treeId.name());
final File o = new File(new File(new File(newdb.getDirectory(), final File o = new File(new File(new File(newdb.getDirectory(),
"objects"), "4b"), "825dc642cb6eb9a060e54bf8d69288fbee4904"); "objects"), "4b"), "825dc642cb6eb9a060e54bf8d69288fbee4904");
assertTrue("Exists " + o, o.isFile()); assertTrue("Exists " + o, o.isFile());
@ -569,8 +570,7 @@ public void test025_computeSha1NoStore() throws IOException {
@Test @Test
public void test026_CreateCommitMultipleparents() throws IOException { public void test026_CreateCommitMultipleparents() throws IOException {
final ObjectId treeId; final ObjectId treeId;
final ObjectInserter oi = db.newObjectInserter(); try (final ObjectInserter oi = db.newObjectInserter()) {
try {
final ObjectId blobId = oi.insert(Constants.OBJ_BLOB, final ObjectId blobId = oi.insert(Constants.OBJ_BLOB,
"and this is the data in me\n".getBytes(Constants.CHARSET "and this is the data in me\n".getBytes(Constants.CHARSET
.name())); .name()));
@ -578,8 +578,6 @@ public void test026_CreateCommitMultipleparents() throws IOException {
fmt.append("i-am-a-file", FileMode.REGULAR_FILE, blobId); fmt.append("i-am-a-file", FileMode.REGULAR_FILE, blobId);
treeId = oi.insert(fmt); treeId = oi.insert(fmt);
oi.flush(); oi.flush();
} finally {
oi.release();
} }
assertEquals(ObjectId assertEquals(ObjectId
.fromString("00b1f73724f493096d1ffa0b0f1f1482dbb8c936"), treeId); .fromString("00b1f73724f493096d1ffa0b0f1f1482dbb8c936"), treeId);
@ -741,80 +739,59 @@ public void test30_stripWorkDir() {
private ObjectId insertEmptyBlob() throws IOException { private ObjectId insertEmptyBlob() throws IOException {
final ObjectId emptyId; final ObjectId emptyId;
ObjectInserter oi = db.newObjectInserter(); try (ObjectInserter oi = db.newObjectInserter()) {
try {
emptyId = oi.insert(Constants.OBJ_BLOB, new byte[] {}); emptyId = oi.insert(Constants.OBJ_BLOB, new byte[] {});
oi.flush(); oi.flush();
} finally {
oi.release();
} }
return emptyId; return emptyId;
} }
private ObjectId insertTree(Tree tree) throws IOException { private ObjectId insertTree(Tree tree) throws IOException {
ObjectInserter oi = db.newObjectInserter(); try (ObjectInserter oi = db.newObjectInserter()) {
try {
ObjectId id = oi.insert(Constants.OBJ_TREE, tree.format()); ObjectId id = oi.insert(Constants.OBJ_TREE, tree.format());
oi.flush(); oi.flush();
return id; return id;
} finally {
oi.release();
} }
} }
private ObjectId insertTree(TreeFormatter tree) throws IOException { private ObjectId insertTree(TreeFormatter tree) throws IOException {
ObjectInserter oi = db.newObjectInserter(); try (ObjectInserter oi = db.newObjectInserter()) {
try {
ObjectId id = oi.insert(tree); ObjectId id = oi.insert(tree);
oi.flush(); oi.flush();
return id; return id;
} finally {
oi.release();
} }
} }
private ObjectId insertCommit(final CommitBuilder builder) private ObjectId insertCommit(final CommitBuilder builder)
throws IOException, UnsupportedEncodingException { throws IOException, UnsupportedEncodingException {
ObjectInserter oi = db.newObjectInserter(); try (ObjectInserter oi = db.newObjectInserter()) {
try {
ObjectId id = oi.insert(builder); ObjectId id = oi.insert(builder);
oi.flush(); oi.flush();
return id; return id;
} finally {
oi.release();
} }
} }
private RevCommit parseCommit(AnyObjectId id) private RevCommit parseCommit(AnyObjectId id)
throws MissingObjectException, IncorrectObjectTypeException, throws MissingObjectException, IncorrectObjectTypeException,
IOException { IOException {
RevWalk rw = new RevWalk(db); try (RevWalk rw = new RevWalk(db)) {
try {
return rw.parseCommit(id); return rw.parseCommit(id);
} finally {
rw.release();
} }
} }
private ObjectId insertTag(final TagBuilder tag) throws IOException, private ObjectId insertTag(final TagBuilder tag) throws IOException,
UnsupportedEncodingException { UnsupportedEncodingException {
ObjectInserter oi = db.newObjectInserter(); try (ObjectInserter oi = db.newObjectInserter()) {
try {
ObjectId id = oi.insert(tag); ObjectId id = oi.insert(tag);
oi.flush(); oi.flush();
return id; return id;
} finally {
oi.release();
} }
} }
private RevTag parseTag(AnyObjectId id) throws MissingObjectException, private RevTag parseTag(AnyObjectId id) throws MissingObjectException,
IncorrectObjectTypeException, IOException { IncorrectObjectTypeException, IOException {
RevWalk rw = new RevWalk(db); try (RevWalk rw = new RevWalk(db)) {
try {
return rw.parseTag(id); return rw.parseTag(id);
} finally {
rw.release();
} }
} }

View File

@ -356,15 +356,12 @@ private ObjectId buildTree(HashMap<String, String> headEntries)
} }
ObjectId genSha1(String data) { ObjectId genSha1(String data) {
ObjectInserter w = db.newObjectInserter(); try (ObjectInserter w = db.newObjectInserter()) {
try {
ObjectId id = w.insert(Constants.OBJ_BLOB, data.getBytes()); ObjectId id = w.insert(Constants.OBJ_BLOB, data.getBytes());
w.flush(); w.flush();
return id; return id;
} catch (IOException e) { } catch (IOException e) {
fail(e.toString()); fail(e.toString());
} finally {
w.release();
} }
return null; return null;
} }

View File

@ -384,13 +384,10 @@ public void testUnchangedComplex() throws IOException, GitAPIException {
} }
private ObjectId insertTree(Tree tree) throws IOException { private ObjectId insertTree(Tree tree) throws IOException {
ObjectInserter oi = db.newObjectInserter(); try (ObjectInserter oi = db.newObjectInserter()) {
try {
ObjectId id = oi.insert(Constants.OBJ_TREE, tree.format()); ObjectId id = oi.insert(Constants.OBJ_TREE, tree.format());
oi.flush(); oi.flush();
return id; return id;
} finally {
oi.release();
} }
} }

View File

@ -109,14 +109,11 @@ private void commit(String commitMsg, PersonIdent author,
commit.setAuthor(author); commit.setAuthor(author);
commit.setCommitter(committer); commit.setCommitter(committer);
commit.setMessage(commitMsg); commit.setMessage(commitMsg);
ObjectInserter inserter = db.newObjectInserter();
ObjectId id; ObjectId id;
try { try (ObjectInserter inserter = db.newObjectInserter()) {
commit.setTreeId(inserter.insert(new TreeFormatter())); commit.setTreeId(inserter.insert(new TreeFormatter()));
id = inserter.insert(commit); id = inserter.insert(commit);
inserter.flush(); inserter.flush();
} finally {
inserter.release();
} }
int nl = commitMsg.indexOf('\n'); int nl = commitMsg.indexOf('\n');

View File

@ -86,8 +86,8 @@ public void setUp() throws Exception {
@Override @Override
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
reader.release(); reader.close();
inserter.release(); inserter.close();
super.tearDown(); super.tearDown();
} }

View File

@ -127,8 +127,8 @@ public void setUp() throws Exception {
@Override @Override
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
reader.release(); reader.close();
inserter.release(); inserter.close();
super.tearDown(); super.tearDown();
} }

View File

@ -91,8 +91,8 @@ public void setUp() throws Exception {
@Override @Override
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
reader.release(); reader.close();
inserter.release(); inserter.close();
super.tearDown(); super.tearDown();
} }

View File

@ -229,15 +229,12 @@ public void testEmptyTreeCorruption() throws Exception {
Tree A_A = A.addTree("A"); Tree A_A = A.addTree("A");
Tree A_B = A.addTree("B"); Tree A_B = A.addTree("B");
final ObjectInserter inserter = db.newObjectInserter(); try (final ObjectInserter inserter = db.newObjectInserter()) {
try {
A_A.setId(inserter.insert(Constants.OBJ_TREE, A_A.format())); A_A.setId(inserter.insert(Constants.OBJ_TREE, A_A.format()));
A_B.setId(inserter.insert(Constants.OBJ_TREE, A_B.format())); A_B.setId(inserter.insert(Constants.OBJ_TREE, A_B.format()));
A.setId(inserter.insert(Constants.OBJ_TREE, A.format())); A.setId(inserter.insert(Constants.OBJ_TREE, A.format()));
root.setId(inserter.insert(Constants.OBJ_TREE, root.format())); root.setId(inserter.insert(Constants.OBJ_TREE, root.format()));
inserter.flush(); inserter.flush();
} finally {
inserter.release();
} }
tree_root = rw.parseTree(root.getId()); tree_root = rw.parseTree(root.getId());

View File

@ -103,12 +103,9 @@ public void withCommitLoadedByDifferentRevWalk() throws Exception {
RevCommit a = commit(); RevCommit a = commit();
Ref branchA = branch("a", a); Ref branchA = branch("a", a);
RevWalk walk = new RevWalk(db); try (RevWalk walk = new RevWalk(db)) {
try {
RevCommit parsedCommit = walk.parseCommit(a.getId()); RevCommit parsedCommit = walk.parseCommit(a.getId());
assertContains(parsedCommit, asList(branchA)); assertContains(parsedCommit, asList(branchA));
} finally {
walk.release();
} }
} }

View File

@ -486,8 +486,9 @@ private static void digest(TemporaryBuffer.Heap buf) throws IOException {
@After @After
public void release() { public void release() {
if (inserter != null) if (inserter != null) {
inserter.release(); inserter.close();
}
} }
private PackParser index(InputStream in) throws IOException { private PackParser index(InputStream in) throws IOException {

View File

@ -543,8 +543,9 @@ private static void digest(TemporaryBuffer.Heap buf) throws IOException {
@After @After
public void release() { public void release() {
if (inserter != null) if (inserter != null) {
inserter.release(); inserter.close();
}
} }
private void openPack(TemporaryBuffer.Heap buf) throws IOException { private void openPack(TemporaryBuffer.Heap buf) throws IOException {

View File

@ -89,11 +89,9 @@ public void testSymlinkNotModifiedThoughNormalized() throws Exception {
DirCacheEditor dce = dc.editor(); DirCacheEditor dce = dc.editor();
final String UNNORMALIZED = "target/"; final String UNNORMALIZED = "target/";
final byte[] UNNORMALIZED_BYTES = Constants.encode(UNNORMALIZED); final byte[] UNNORMALIZED_BYTES = Constants.encode(UNNORMALIZED);
ObjectInserter oi = db.newObjectInserter(); try (ObjectInserter oi = db.newObjectInserter()) {
final ObjectId linkid = oi.insert(Constants.OBJ_BLOB, final ObjectId linkid = oi.insert(Constants.OBJ_BLOB,
UNNORMALIZED_BYTES, 0, UNNORMALIZED_BYTES, 0, UNNORMALIZED_BYTES.length);
UNNORMALIZED_BYTES.length);
oi.release();
dce.add(new DirCacheEditor.PathEdit("link") { dce.add(new DirCacheEditor.PathEdit("link") {
@Override @Override
public void apply(DirCacheEntry ent) { public void apply(DirCacheEntry ent) {
@ -103,6 +101,7 @@ public void apply(DirCacheEntry ent) {
} }
}); });
assertTrue(dce.commit()); assertTrue(dce.commit());
}
new Git(db).commit().setMessage("Adding link").call(); new Git(db).commit().setMessage("Adding link").call();
new Git(db).reset().setMode(ResetType.HARD).call(); new Git(db).reset().setMode(ResetType.HARD).call();
DirCacheIterator dci = new DirCacheIterator(db.readDirCache()); DirCacheIterator dci = new DirCacheIterator(db.readDirCache());
@ -129,10 +128,9 @@ public void testSymlinkModifiedNotNormalized() throws Exception {
DirCacheEditor dce = dc.editor(); DirCacheEditor dce = dc.editor();
final String NORMALIZED = "target"; final String NORMALIZED = "target";
final byte[] NORMALIZED_BYTES = Constants.encode(NORMALIZED); final byte[] NORMALIZED_BYTES = Constants.encode(NORMALIZED);
ObjectInserter oi = db.newObjectInserter(); try (ObjectInserter oi = db.newObjectInserter()) {
final ObjectId linkid = oi.insert(Constants.OBJ_BLOB, NORMALIZED_BYTES, final ObjectId linkid = oi.insert(Constants.OBJ_BLOB,
0, NORMALIZED_BYTES.length); NORMALIZED_BYTES, 0, NORMALIZED_BYTES.length);
oi.release();
dce.add(new DirCacheEditor.PathEdit("link") { dce.add(new DirCacheEditor.PathEdit("link") {
@Override @Override
public void apply(DirCacheEntry ent) { public void apply(DirCacheEntry ent) {
@ -142,6 +140,7 @@ public void apply(DirCacheEntry ent) {
} }
}); });
assertTrue(dce.commit()); assertTrue(dce.commit());
}
new Git(db).commit().setMessage("Adding link").call(); new Git(db).commit().setMessage("Adding link").call();
new Git(db).reset().setMode(ResetType.HARD).call(); new Git(db).reset().setMode(ResetType.HARD).call();
DirCacheIterator dci = new DirCacheIterator(db.readDirCache()); DirCacheIterator dci = new DirCacheIterator(db.readDirCache());
@ -166,10 +165,9 @@ public void apply(DirCacheEntry ent) {
public void testSymlinkActuallyModified() throws Exception { public void testSymlinkActuallyModified() throws Exception {
final String NORMALIZED = "target"; final String NORMALIZED = "target";
final byte[] NORMALIZED_BYTES = Constants.encode(NORMALIZED); final byte[] NORMALIZED_BYTES = Constants.encode(NORMALIZED);
ObjectInserter oi = db.newObjectInserter(); try (ObjectInserter oi = db.newObjectInserter()) {
final ObjectId linkid = oi.insert(Constants.OBJ_BLOB, NORMALIZED_BYTES, final ObjectId linkid = oi.insert(Constants.OBJ_BLOB,
0, NORMALIZED_BYTES.length); NORMALIZED_BYTES, 0, NORMALIZED_BYTES.length);
oi.release();
DirCache dc = db.lockDirCache(); DirCache dc = db.lockDirCache();
DirCacheEditor dce = dc.editor(); DirCacheEditor dce = dc.editor();
dce.add(new DirCacheEditor.PathEdit("link") { dce.add(new DirCacheEditor.PathEdit("link") {
@ -181,6 +179,7 @@ public void apply(DirCacheEntry ent) {
} }
}); });
assertTrue(dce.commit()); assertTrue(dce.commit());
}
new Git(db).commit().setMessage("Adding link").call(); new Git(db).commit().setMessage("Adding link").call();
new Git(db).reset().setMode(ResetType.HARD).call(); new Git(db).reset().setMode(ResetType.HARD).call();

View File

@ -274,9 +274,9 @@ public void testDirCacheMatchingId() throws Exception {
ObjectId fromRaw = ObjectId.fromRaw(fti.idBuffer(), fti.idOffset()); ObjectId fromRaw = ObjectId.fromRaw(fti.idBuffer(), fti.idOffset());
assertEquals("6b584e8ece562ebffc15d38808cd6b98fc3d97ea", assertEquals("6b584e8ece562ebffc15d38808cd6b98fc3d97ea",
fromRaw.getName()); fromRaw.getName());
ObjectReader objectReader = db.newObjectReader(); try (ObjectReader objectReader = db.newObjectReader()) {
assertFalse(fti.isModified(dce, false, objectReader)); assertFalse(fti.isModified(dce, false, objectReader));
objectReader.release(); }
} }
@Test @Test
@ -291,15 +291,15 @@ public void testIsModifiedSymlinkAsFile() throws Exception {
// Modify previously committed DirCacheEntry and write it back to disk // Modify previously committed DirCacheEntry and write it back to disk
DirCacheEntry dce = db.readDirCache().getEntry("symlink"); DirCacheEntry dce = db.readDirCache().getEntry("symlink");
dce.setFileMode(FileMode.SYMLINK); dce.setFileMode(FileMode.SYMLINK);
ObjectReader objectReader = db.newObjectReader(); try (ObjectReader objectReader = db.newObjectReader()) {
DirCacheCheckout.checkoutEntry(db, dce, objectReader); DirCacheCheckout.checkoutEntry(db, dce, objectReader);
FileTreeIterator fti = new FileTreeIterator(trash, db.getFS(), db FileTreeIterator fti = new FileTreeIterator(trash, db.getFS(),
.getConfig().get(WorkingTreeOptions.KEY)); db.getConfig().get(WorkingTreeOptions.KEY));
while (!fti.getEntryPathString().equals("symlink")) while (!fti.getEntryPathString().equals("symlink"))
fti.next(1); fti.next(1);
assertFalse(fti.isModified(dce, false, objectReader)); assertFalse(fti.isModified(dce, false, objectReader));
objectReader.release(); }
} }
@Test @Test
@ -327,9 +327,9 @@ public void testIsModifiedFileSmudged() throws Exception {
// If the rounding trick does not work we could skip the compareMetaData // If the rounding trick does not work we could skip the compareMetaData
// test and hope that we are usually testing the intended code path. // test and hope that we are usually testing the intended code path.
assertEquals(MetadataDiff.SMUDGED, fti.compareMetadata(dce)); assertEquals(MetadataDiff.SMUDGED, fti.compareMetadata(dce));
ObjectReader objectReader = db.newObjectReader(); try (ObjectReader objectReader = db.newObjectReader()) {
assertTrue(fti.isModified(dce, false, objectReader)); assertTrue(fti.isModified(dce, false, objectReader));
objectReader.release(); }
} }
@Test @Test

View File

@ -68,8 +68,8 @@ public class ForPathTest extends RepositoryTestCase {
public void testFindObjects() throws Exception { public void testFindObjects() throws Exception {
final DirCache tree0 = DirCache.newInCore(); final DirCache tree0 = DirCache.newInCore();
final DirCacheBuilder b0 = tree0.builder(); final DirCacheBuilder b0 = tree0.builder();
ObjectReader or = db.newObjectReader(); try (ObjectReader or = db.newObjectReader();
ObjectInserter oi = db.newObjectInserter(); ObjectInserter oi = db.newObjectInserter()) {
DirCacheEntry aDotB = createEntry("a.b", EXECUTABLE_FILE); DirCacheEntry aDotB = createEntry("a.b", EXECUTABLE_FILE);
b0.add(aDotB); b0.add(aDotB);
@ -107,31 +107,30 @@ public void testFindObjects() throws Exception {
assertEquals(null, TreeWalk.forPath(or, "/a", tree)); assertEquals(null, TreeWalk.forPath(or, "/a", tree));
assertEquals(null, TreeWalk.forPath(or, "/a/", tree)); assertEquals(null, TreeWalk.forPath(or, "/a/", tree));
assertEquals(aDotB.getObjectId(), TreeWalk.forPath(or, "a.b", tree) assertEquals(aDotB.getObjectId(),
.getObjectId(0)); TreeWalk.forPath(or, "a.b", tree).getObjectId(0));
assertEquals(null, TreeWalk.forPath(or, "/a.b", tree)); assertEquals(null, TreeWalk.forPath(or, "/a.b", tree));
assertEquals(null, TreeWalk.forPath(or, "/a.b/", tree)); assertEquals(null, TreeWalk.forPath(or, "/a.b/", tree));
assertEquals(aDotB.getObjectId(), TreeWalk.forPath(or, "a.b/", tree) assertEquals(aDotB.getObjectId(),
.getObjectId(0)); TreeWalk.forPath(or, "a.b/", tree).getObjectId(0));
assertEquals(aZeroB.getObjectId(), TreeWalk.forPath(or, "a0b", tree) assertEquals(aZeroB.getObjectId(),
.getObjectId(0)); TreeWalk.forPath(or, "a0b", tree).getObjectId(0));
assertEquals(aSlashB.getObjectId(), TreeWalk.forPath(or, "a/b", tree) assertEquals(aSlashB.getObjectId(),
.getObjectId(0)); TreeWalk.forPath(or, "a/b", tree).getObjectId(0));
assertEquals(aSlashB.getObjectId(), TreeWalk.forPath(or, "b", a) assertEquals(aSlashB.getObjectId(),
.getObjectId(0)); TreeWalk.forPath(or, "b", a).getObjectId(0));
assertEquals(aSlashC, TreeWalk.forPath(or, "a/c", tree).getObjectId(0)); assertEquals(aSlashC,
TreeWalk.forPath(or, "a/c", tree).getObjectId(0));
assertEquals(aSlashC, TreeWalk.forPath(or, "c", a).getObjectId(0)); assertEquals(aSlashC, TreeWalk.forPath(or, "c", a).getObjectId(0));
assertEquals(aSlashCSlashD.getObjectId(), assertEquals(aSlashCSlashD.getObjectId(),
TreeWalk.forPath(or, "a/c/d", tree).getObjectId(0)); TreeWalk.forPath(or, "a/c/d", tree).getObjectId(0));
assertEquals(aSlashCSlashD.getObjectId(), TreeWalk assertEquals(aSlashCSlashD.getObjectId(),
.forPath(or, "c/d", a).getObjectId(0)); TreeWalk.forPath(or, "c/d", a).getObjectId(0));
}
or.release();
oi.release();
} }
} }

View File

@ -63,14 +63,14 @@ public class TreeWalkBasicDiffTest extends RepositoryTestCase {
@Test @Test
public void testMissingSubtree_DetectFileAdded_FileModified() public void testMissingSubtree_DetectFileAdded_FileModified()
throws Exception { throws Exception {
final ObjectInserter inserter = db.newObjectInserter(); final ObjectId oldTree, newTree, bFileId, cFileId1, cFileId2;
try (ObjectInserter inserter = db.newObjectInserter()) {
final ObjectId aFileId = inserter.insert(OBJ_BLOB, encode("a")); final ObjectId aFileId = inserter.insert(OBJ_BLOB, encode("a"));
final ObjectId bFileId = inserter.insert(OBJ_BLOB, encode("b")); bFileId = inserter.insert(OBJ_BLOB, encode("b"));
final ObjectId cFileId1 = inserter.insert(OBJ_BLOB, encode("c-1")); cFileId1 = inserter.insert(OBJ_BLOB, encode("c-1"));
final ObjectId cFileId2 = inserter.insert(OBJ_BLOB, encode("c-2")); cFileId2 = inserter.insert(OBJ_BLOB, encode("c-2"));
// Create sub-a/empty, sub-c/empty = hello. // Create sub-a/empty, sub-c/empty = hello.
final ObjectId oldTree;
{ {
final Tree root = new Tree(db); final Tree root = new Tree(db);
{ {
@ -87,7 +87,6 @@ public void testMissingSubtree_DetectFileAdded_FileModified()
} }
// Create sub-a/empty, sub-b/empty, sub-c/empty. // Create sub-a/empty, sub-b/empty, sub-c/empty.
final ObjectId newTree;
{ {
final Tree root = new Tree(db); final Tree root = new Tree(db);
{ {
@ -108,7 +107,7 @@ public void testMissingSubtree_DetectFileAdded_FileModified()
newTree = inserter.insert(OBJ_TREE, root.format()); newTree = inserter.insert(OBJ_TREE, root.format());
} }
inserter.flush(); inserter.flush();
inserter.release(); }
final TreeWalk tw = new TreeWalk(db); final TreeWalk tw = new TreeWalk(db);
tw.reset(oldTree, newTree); tw.reset(oldTree, newTree);

View File

@ -27,6 +27,7 @@ badEntryName=Bad entry name: {0}
badEscape=Bad escape: {0} badEscape=Bad escape: {0}
badGroupHeader=Bad group header badGroupHeader=Bad group header
badObjectType=Bad object type: {0} badObjectType=Bad object type: {0}
badRef=Bad ref: {0}: {1}
badSectionEntry=Bad section entry: {0} badSectionEntry=Bad section entry: {0}
bareRepositoryNoWorkdirAndIndex=Bare Repository has neither a working tree, nor an index bareRepositoryNoWorkdirAndIndex=Bare Repository has neither a working tree, nor an index
base64InputNotProperlyPadded=Base64 input not properly padded. base64InputNotProperlyPadded=Base64 input not properly padded.
@ -58,16 +59,23 @@ cannotCreateIndexfile=Cannot create an index file with name {0}
cannotCreateTempDir=Cannot create a temp dir cannotCreateTempDir=Cannot create a temp dir
cannotDeleteCheckedOutBranch=Branch {0} is checked out and can not be deleted cannotDeleteCheckedOutBranch=Branch {0} is checked out and can not be deleted
cannotDeleteFile=Cannot delete file: {0} cannotDeleteFile=Cannot delete file: {0}
cannotDeleteObjectsPath="Can't delete {0}/{1}: {2}
cannotDeleteStaleTrackingRef=Cannot delete stale tracking ref {0} cannotDeleteStaleTrackingRef=Cannot delete stale tracking ref {0}
cannotDeleteStaleTrackingRef2=Cannot delete stale tracking ref {0}: {1} cannotDeleteStaleTrackingRef2=Cannot delete stale tracking ref {0}: {1}
cannotDetermineProxyFor=Cannot determine proxy for {0} cannotDetermineProxyFor=Cannot determine proxy for {0}
cannotDownload=Cannot download {0} cannotDownload=Cannot download {0}
cannotEnterObjectsPath=Can't enter {0}/objects: {1}
cannotEnterPathFromParent=Can't enter {0} from {1}: {2}
cannotExecute=cannot execute: {0} cannotExecute=cannot execute: {0}
cannotGet=Cannot get {0} cannotGet=Cannot get {0}
cannotGetObjectsPath=Can't get {0}/{1}: {2}
cannotListObjectsPath=Can't ls {0}/{1}: {2}
cannotListPackPath=Can't ls {0}/pack: {1}
cannotListRefs=cannot list refs cannotListRefs=cannot list refs
cannotLock=Cannot lock {0} cannotLock=Cannot lock {0}
cannotLockPackIn=Cannot lock pack in {0} cannotLockPackIn=Cannot lock pack in {0}
cannotMatchOnEmptyString=Cannot match on empty string. cannotMatchOnEmptyString=Cannot match on empty string.
cannotMkdirObjectPath=Can't mkdir {0}/{1}: {2}
cannotMoveIndexTo=Cannot move index to {0} cannotMoveIndexTo=Cannot move index to {0}
cannotMovePackTo=Cannot move pack to {0} cannotMovePackTo=Cannot move pack to {0}
cannotOpenService=cannot open {0} cannotOpenService=cannot open {0}
@ -80,13 +88,16 @@ cannotReadCommit=Cannot read commit {0}
cannotReadFile=Cannot read file {0} cannotReadFile=Cannot read file {0}
cannotReadHEAD=cannot read HEAD: {0} {1} cannotReadHEAD=cannot read HEAD: {0} {1}
cannotReadObject=Cannot read object cannotReadObject=Cannot read object
cannotReadObjectsPath=Cannot read {0}/{1}: {2}
cannotReadTree=Cannot read tree {0} cannotReadTree=Cannot read tree {0}
cannotRebaseWithoutCurrentHead=Can not rebase without a current HEAD cannotRebaseWithoutCurrentHead=Can not rebase without a current HEAD
cannotResolveLocalTrackingRefForUpdating=Cannot resolve local tracking ref {0} for updating. cannotResolveLocalTrackingRefForUpdating=Cannot resolve local tracking ref {0} for updating.
cannotSquashFixupWithoutPreviousCommit=Cannot {0} without previous commit. cannotSquashFixupWithoutPreviousCommit=Cannot {0} without previous commit.
cannotStoreObjects=cannot store objects cannotStoreObjects=cannot store objects
cannotResolveUniquelyAbbrevObjectId=Could not resolve uniquely the abbreviated object ID
cannotUnloadAModifiedTree=Cannot unload a modified tree. cannotUnloadAModifiedTree=Cannot unload a modified tree.
cannotWorkWithOtherStagesThanZeroRightNow=Cannot work with other stages than zero right now. Won't write corrupt index. cannotWorkWithOtherStagesThanZeroRightNow=Cannot work with other stages than zero right now. Won't write corrupt index.
cannotWriteObjectsPath="Can't write {0}/{1}: {2}
canOnlyCherryPickCommitsWithOneParent=Cannot cherry-pick commit ''{0}'' because it has {1} parents, only commits with exactly one parent are supported. canOnlyCherryPickCommitsWithOneParent=Cannot cherry-pick commit ''{0}'' because it has {1} parents, only commits with exactly one parent are supported.
canOnlyRevertCommitsWithOneParent=Cannot revert commit ''{0}'' because it has {1} parents, only commits with exactly one parent are supported canOnlyRevertCommitsWithOneParent=Cannot revert commit ''{0}'' because it has {1} parents, only commits with exactly one parent are supported
commitDoesNotHaveGivenParent=The commit ''{0}'' does not have a parent number {1}. commitDoesNotHaveGivenParent=The commit ''{0}'' does not have a parent number {1}.
@ -113,26 +124,60 @@ contextMustBeNonNegative=context must be >= 0
corruptionDetectedReReadingAt=Corruption detected re-reading at {0} corruptionDetectedReReadingAt=Corruption detected re-reading at {0}
corruptObjectBadStream=bad stream corruptObjectBadStream=bad stream
corruptObjectBadStreamCorruptHeader=bad stream, corrupt header corruptObjectBadStreamCorruptHeader=bad stream, corrupt header
corruptObjectDuplicateEntryNames=duplicate entry names
corruptObjectGarbageAfterSize=garbage after size corruptObjectGarbageAfterSize=garbage after size
corruptObjectIncorrectLength=incorrect length corruptObjectIncorrectLength=incorrect length
corruptObjectIncorrectSorting=incorrectly sorted
corruptObjectInvalidAuthor=invalid author
corruptObjectInvalidCommitter=invalid committer
corruptObjectInvalidEntryMode=invalid entry mode corruptObjectInvalidEntryMode=invalid entry mode
corruptObjectInvalidMode=invalid mode corruptObjectInvalidMode=invalid mode
corruptObjectInvalidMode2=invalid mode {0} corruptObjectInvalidModeChar=invalid mode character
corruptObjectInvalidModeStartsZero=mode starts with '0'
corruptObjectInvalidMode2=invalid mode {0,number,#}
corruptObjectInvalidMode3=invalid mode {0} for {1} ''{2}'' in {3}. corruptObjectInvalidMode3=invalid mode {0} for {1} ''{2}'' in {3}.
corruptObjectInvalidName=invalid name '%s'
corruptObjectInvalidNameAux=invalid name 'AUX'
corruptObjectInvalidNameCon=invalid name 'CON'
corruptObjectInvalidNameCom=invalid name 'COM%c'
corruptObjectInvalidNameEnd=invalid name ends with '%c'
corruptObjectInvalidNameIgnorableUnicode=invalid name '%s' contains ignorable Unicode characters
corruptObjectInvalidNameInvalidUtf8=invalid name contains byte sequence ''{0}'' which is not a valid UTF-8 character
corruptObjectInvalidNameLpt=invalid name 'LPT%c'
corruptObjectInvalidNameNul=invalid name 'NUL'
corruptObjectInvalidNamePrn=invalid name 'PRN'
corruptObjectInvalidObject=invalid object
corruptObjectInvalidParent=invalid parent
corruptObjectInvalidTagger=invalid tagger
corruptObjectInvalidTree=invalid tree
corruptObjectInvalidType=invalid type corruptObjectInvalidType=invalid type
corruptObjectInvalidType2=invalid type {0} corruptObjectInvalidType2=invalid type {0}
corruptObjectMalformedHeader=malformed header: {0} corruptObjectMalformedHeader=malformed header: {0}
corruptObjectNameContainsByte=name contains byte 0x%x
corruptObjectNameContainsChar=name contains '%c'
corruptObjectNameContainsNullByte=name contains byte 0x00
corruptObjectNameContainsSlash=name contains '/'
corruptObjectNameDot=invalid name '.'
corruptObjectNameDotDot=invalid name '..'
corruptObjectNameZeroLength=zero length name
corruptObjectNegativeSize=negative size corruptObjectNegativeSize=negative size
corruptObjectNoAuthor=no author corruptObjectNoAuthor=no author
corruptObjectNoCommitter=no committer corruptObjectNoCommitter=no committer
corruptObjectNoHeader=no header corruptObjectNoHeader=no header
corruptObjectNoObject=no object corruptObjectNoObject=no object
corruptObjectNoObjectHeader=no object header
corruptObjectNoTaggerBadHeader=no tagger/bad header corruptObjectNoTaggerBadHeader=no tagger/bad header
corruptObjectNoTaggerHeader=no tagger header corruptObjectNoTaggerHeader=no tagger header
corruptObjectNoTagHeader=no tag header
corruptObjectNoTagName=no tag name corruptObjectNoTagName=no tag name
corruptObjectNotree=no tree corruptObjectNotree=no tree
corruptObjectNotreeHeader=no tree header
corruptObjectNoType=no type corruptObjectNoType=no type
corruptObjectNoTypeHeader=no type header
corruptObjectPackfileChecksumIncorrect=Packfile checksum incorrect. corruptObjectPackfileChecksumIncorrect=Packfile checksum incorrect.
corruptObjectTruncatedInMode=truncated in mode
corruptObjectTruncatedInName=truncated in name
corruptObjectTruncatedInObjectId=truncated in object id
couldNotCheckOutBecauseOfConflicts=Could not check out because of conflicts couldNotCheckOutBecauseOfConflicts=Could not check out because of conflicts
couldNotDeleteLockFileShouldNotHappen=Could not delete lock file. Should not happen couldNotDeleteLockFileShouldNotHappen=Could not delete lock file. Should not happen
couldNotDeleteTemporaryIndexFileShouldNotHappen=Could not delete temporary index file. Should not happen couldNotDeleteTemporaryIndexFileShouldNotHappen=Could not delete temporary index file. Should not happen
@ -144,6 +189,7 @@ couldNotReadObjectWhileParsingCommit=Could not read an object while parsing comm
couldNotRenameDeleteOldIndex=Could not rename delete old index couldNotRenameDeleteOldIndex=Could not rename delete old index
couldNotRenameTemporaryFile=Could not rename temporary file {0} to new location {1} couldNotRenameTemporaryFile=Could not rename temporary file {0} to new location {1}
couldNotRenameTemporaryIndexFileToIndex=Could not rename temporary index file to index couldNotRenameTemporaryIndexFileToIndex=Could not rename temporary index file to index
couldNotRewindToUpstreamCommit=Could not rewind to upstream commit
couldNotURLEncodeToUTF8=Could not URL encode to UTF-8 couldNotURLEncodeToUTF8=Could not URL encode to UTF-8
couldNotWriteFile=Could not write file {0} couldNotWriteFile=Could not write file {0}
countingObjects=Counting objects countingObjects=Counting objects
@ -180,6 +226,7 @@ duplicateStagesNotAllowed=Duplicate stages not allowed
eitherGitDirOrWorkTreeRequired=One of setGitDir or setWorkTree must be called. eitherGitDirOrWorkTreeRequired=One of setGitDir or setWorkTree must be called.
emptyCommit=No changes emptyCommit=No changes
emptyPathNotPermitted=Empty path not permitted. emptyPathNotPermitted=Empty path not permitted.
emptyRef=Empty ref: {0}
encryptionError=Encryption error: {0} encryptionError=Encryption error: {0}
endOfFileInEscape=End of file in escape endOfFileInEscape=End of file in escape
entryNotFoundByPath=Entry not found by path: {0} entryNotFoundByPath=Entry not found by path: {0}
@ -240,6 +287,7 @@ funnyRefname=funny refname
gcFailed=Garbage collection failed. gcFailed=Garbage collection failed.
gitmodulesNotFound=.gitmodules not found in tree. gitmodulesNotFound=.gitmodules not found in tree.
headRequiredToStash=HEAD required to stash local changes headRequiredToStash=HEAD required to stash local changes
hiddenFilesStartWithDot=Hiding only allowed for names that start with a period
hoursAgo={0} hours ago hoursAgo={0} hours ago
hugeIndexesAreNotSupportedByJgitYet=Huge indexes are not supported by jgit, yet hugeIndexesAreNotSupportedByJgitYet=Huge indexes are not supported by jgit, yet
hunkBelongsToAnotherFile=Hunk belongs to another file hunkBelongsToAnotherFile=Hunk belongs to another file
@ -276,8 +324,9 @@ invalidCommitParentNumber=Invalid commit parent number
invalidEncryption=Invalid encryption invalidEncryption=Invalid encryption
invalidGitdirRef = Invalid .git reference in file ''{0}'' invalidGitdirRef = Invalid .git reference in file ''{0}''
invalidGitType=invalid git type: {0} invalidGitType=invalid git type: {0}
invalidId=Invalid id {0} invalidId=Invalid id: {0}
invalidIdLength=Invalid id length {0}; should be {1} invalidIdLength=Invalid id length {0}; should be {1}
invalidIgnoreParamSubmodule=Found invalid ignore param for submodule {0}.
invalidIntegerValue=Invalid integer value: {0}.{1}={2} invalidIntegerValue=Invalid integer value: {0}.{1}={2}
invalidKey=Invalid key: {0} invalidKey=Invalid key: {0}
invalidLineInConfigFile=Invalid line in config file invalidLineInConfigFile=Invalid line in config file
@ -310,8 +359,10 @@ largeObjectException={0} exceeds size limit
largeObjectOutOfMemory=Out of memory loading {0} largeObjectOutOfMemory=Out of memory loading {0}
lengthExceedsMaximumArraySize=Length exceeds maximum array size lengthExceedsMaximumArraySize=Length exceeds maximum array size
listingAlternates=Listing alternates listingAlternates=Listing alternates
listingPacks=Listing packs
localObjectsIncomplete=Local objects incomplete. localObjectsIncomplete=Local objects incomplete.
localRefIsMissingObjects=Local ref {0} is missing object(s). localRefIsMissingObjects=Local ref {0} is missing object(s).
localRepository=local repository
lockCountMustBeGreaterOrEqual1=lockCount must be >= 1 lockCountMustBeGreaterOrEqual1=lockCount must be >= 1
lockError=lock error: {0} lockError=lock error: {0}
lockOnNotClosed=Lock on {0} not closed. lockOnNotClosed=Lock on {0} not closed.
@ -410,6 +461,8 @@ pathIsNotInWorkingDir=Path is not in working dir
pathNotConfigured=Submodule path is not configured pathNotConfigured=Submodule path is not configured
peeledLineBeforeRef=Peeled line before ref. peeledLineBeforeRef=Peeled line before ref.
peerDidNotSupplyACompleteObjectGraph=peer did not supply a complete object graph peerDidNotSupplyACompleteObjectGraph=peer did not supply a complete object graph
personIdentEmailNonNull=E-mail address of PersonIdent must not be null.
personIdentNameNonNull=Name of PersonIdent must not be null.
prefixRemote=remote: prefixRemote=remote:
problemWithResolvingPushRefSpecsLocally=Problem with resolving push ref specs locally: {0} problemWithResolvingPushRefSpecsLocally=Problem with resolving push ref specs locally: {0}
progressMonUploading=Uploading {0} progressMonUploading=Uploading {0}
@ -453,6 +506,7 @@ repositoryConfigFileInvalid=Repository config file {0} invalid {1}
repositoryIsRequired=Repository is required. repositoryIsRequired=Repository is required.
repositoryNotFound=repository not found: {0} repositoryNotFound=repository not found: {0}
repositoryState_applyMailbox=Apply mailbox repositoryState_applyMailbox=Apply mailbox
repositoryState_bare=Bare
repositoryState_bisecting=Bisecting repositoryState_bisecting=Bisecting
repositoryState_conflicts=Conflicts repositoryState_conflicts=Conflicts
repositoryState_merged=Merged repositoryState_merged=Merged
@ -466,6 +520,9 @@ resettingHead=Resetting head to {0}
resolvingDeltas=Resolving deltas resolvingDeltas=Resolving deltas
resultLengthIncorrect=result length incorrect resultLengthIncorrect=result length incorrect
rewinding=Rewinding to commit {0} rewinding=Rewinding to commit {0}
s3ActionDeletion=Deletion
s3ActionReading=Reading
s3ActionWriting=Writing
searchForReuse=Finding sources searchForReuse=Finding sources
searchForSizes=Getting sizes searchForSizes=Getting sizes
secondsAgo={0} seconds ago secondsAgo={0} seconds ago
@ -547,6 +604,7 @@ unableToWrite=Unable to write {0}
unencodeableFile=Unencodable file: {0} unencodeableFile=Unencodable file: {0}
unexpectedCompareResult=Unexpected metadata comparison result: {0} unexpectedCompareResult=Unexpected metadata comparison result: {0}
unexpectedEndOfConfigFile=Unexpected end of config file unexpectedEndOfConfigFile=Unexpected end of config file
unexpectedEndOfInput=Unexpected end of input
unexpectedHunkTrailer=Unexpected hunk trailer unexpectedHunkTrailer=Unexpected hunk trailer
unexpectedOddResult=odd: {0} + {1} - {2} unexpectedOddResult=odd: {0} + {1} - {2}
unexpectedRefReport={0}: unexpected ref report: {1} unexpectedRefReport={0}: unexpected ref report: {1}
@ -558,6 +616,7 @@ unknownHost=unknown host
unknownIndexVersionOrCorruptIndex=Unknown index version (or corrupt index): {0} unknownIndexVersionOrCorruptIndex=Unknown index version (or corrupt index): {0}
unknownObject=unknown object unknownObject=unknown object
unknownObjectType=Unknown object type {0}. unknownObjectType=Unknown object type {0}.
unknownObjectType2=unknown
unknownRepositoryFormat=Unknown repository format unknownRepositoryFormat=Unknown repository format
unknownRepositoryFormat2=Unknown repository format "{0}"; expected "0". unknownRepositoryFormat2=Unknown repository format "{0}"; expected "0".
unknownZlibError=Unknown zlib error. unknownZlibError=Unknown zlib error.
@ -566,16 +625,21 @@ unmergedPaths=Repository contains unmerged paths
unpackException=Exception while parsing pack stream unpackException=Exception while parsing pack stream
unreadablePackIndex=Unreadable pack index: {0} unreadablePackIndex=Unreadable pack index: {0}
unrecognizedRef=Unrecognized ref: {0} unrecognizedRef=Unrecognized ref: {0}
unsetMark=Mark not set
unsupportedAlternates=Alternates not supported
unsupportedArchiveFormat=Unknown archive format ''{0}'' unsupportedArchiveFormat=Unknown archive format ''{0}''
unsupportedCommand0=unsupported command 0 unsupportedCommand0=unsupported command 0
unsupportedEncryptionAlgorithm=Unsupported encryption algorithm: {0} unsupportedEncryptionAlgorithm=Unsupported encryption algorithm: {0}
unsupportedEncryptionVersion=Unsupported encryption version: {0} unsupportedEncryptionVersion=Unsupported encryption version: {0}
unsupportedGC=Unsupported garbage collector for repository type: {0} unsupportedGC=Unsupported garbage collector for repository type: {0}
unsupportedMark=Mark not supported
unsupportedOperationNotAddAtEnd=Not add-at-end: {0} unsupportedOperationNotAddAtEnd=Not add-at-end: {0}
unsupportedPackIndexVersion=Unsupported pack index version {0} unsupportedPackIndexVersion=Unsupported pack index version {0}
unsupportedPackVersion=Unsupported pack version {0}. unsupportedPackVersion=Unsupported pack version {0}.
updatingHeadFailed=Updating HEAD failed
updatingReferences=Updating references updatingReferences=Updating references
updatingRefFailed=Updating the ref {0} to {1} failed. ReturnCode from RefUpdate.update() was {2} updatingRefFailed=Updating the ref {0} to {1} failed. ReturnCode from RefUpdate.update() was {2}
upstreamBranchName=branch ''{0}'' of {1}
uriNotConfigured=Submodule URI not configured uriNotConfigured=Submodule URI not configured
uriNotFound={0} not found uriNotFound={0} not found
URINotSupported=URI not supported: {0} URINotSupported=URI not supported: {0}

View File

@ -124,8 +124,7 @@ public Ref call() throws GitAPIException, RefAlreadyExistsException,
RefNotFoundException, InvalidRefNameException { RefNotFoundException, InvalidRefNameException {
checkCallable(); checkCallable();
processOptions(); processOptions();
RevWalk revWalk = new RevWalk(repo); try (RevWalk revWalk = new RevWalk(repo)) {
try {
Ref refToCheck = repo.getRef(name); Ref refToCheck = repo.getRef(name);
boolean exists = refToCheck != null boolean exists = refToCheck != null
&& refToCheck.getName().startsWith(Constants.R_HEADS); && refToCheck.getName().startsWith(Constants.R_HEADS);
@ -270,8 +269,6 @@ else if (upstreamMode == SetupUpstreamMode.NOTRACK)
return result; return result;
} catch (IOException ioe) { } catch (IOException ioe) {
throw new JGitInternalException(ioe.getMessage(), ioe); throw new JGitInternalException(ioe.getMessage(), ioe);
} finally {
revWalk.release();
} }
} }

View File

@ -108,8 +108,9 @@ public List<String> call() throws GitAPIException,
if (!force) { if (!force) {
// check if the branches to be deleted // check if the branches to be deleted
// are all merged into the current branch // are all merged into the current branch
RevWalk walk = new RevWalk(repo); try (RevWalk walk = new RevWalk(repo)) {
RevCommit tip = walk.parseCommit(repo.resolve(Constants.HEAD)); RevCommit tip = walk
.parseCommit(repo.resolve(Constants.HEAD));
for (String branchName : branchNames) { for (String branchName : branchNames) {
if (branchName == null) if (branchName == null)
continue; continue;
@ -117,12 +118,14 @@ public List<String> call() throws GitAPIException,
if (currentRef == null) if (currentRef == null)
continue; continue;
RevCommit base = walk.parseCommit(repo.resolve(branchName)); RevCommit base = walk
.parseCommit(repo.resolve(branchName));
if (!walk.isMergedInto(base, tip)) { if (!walk.isMergedInto(base, tip)) {
throw new NotMergedException(); throw new NotMergedException();
} }
} }
} }
}
setCallable(false); setCallable(false);
for (String branchName : branchNames) { for (String branchName : branchNames) {
if (branchName == null) if (branchName == null)

View File

@ -139,8 +139,7 @@ private Collection<Ref> filterRefs(Collection<Ref> refs)
if (containsCommitish == null) if (containsCommitish == null)
return refs; return refs;
RevWalk walk = new RevWalk(repo); try (RevWalk walk = new RevWalk(repo)) {
try {
ObjectId resolved = repo.resolve(containsCommitish); ObjectId resolved = repo.resolve(containsCommitish);
if (resolved == null) if (resolved == null)
throw new RefNotFoundException(MessageFormat.format( throw new RefNotFoundException(MessageFormat.format(
@ -149,8 +148,6 @@ private Collection<Ref> filterRefs(Collection<Ref> refs)
RevCommit containsCommit = walk.parseCommit(resolved); RevCommit containsCommit = walk.parseCommit(resolved);
return RevWalkUtils.findBranchesReachableFrom(containsCommit, walk, return RevWalkUtils.findBranchesReachableFrom(containsCommit, walk,
refs); refs);
} finally {
walk.release();
} }
} }

View File

@ -80,9 +80,8 @@ protected ListNotesCommand(Repository repo) {
public List<Note> call() throws GitAPIException { public List<Note> call() throws GitAPIException {
checkCallable(); checkCallable();
List<Note> notes = new ArrayList<Note>(); List<Note> notes = new ArrayList<Note>();
RevWalk walk = new RevWalk(repo);
NoteMap map = NoteMap.newEmptyMap(); NoteMap map = NoteMap.newEmptyMap();
try { try (RevWalk walk = new RevWalk(repo)) {
Ref ref = repo.getRef(notesRef); Ref ref = repo.getRef(notesRef);
// if we have a notes ref, use it // if we have a notes ref, use it
if (ref != null) { if (ref != null) {
@ -95,8 +94,6 @@ public List<Note> call() throws GitAPIException {
notes.add(i.next()); notes.add(i.next());
} catch (IOException e) { } catch (IOException e) {
throw new JGitInternalException(e.getMessage(), e); throw new JGitInternalException(e.getMessage(), e);
} finally {
walk.release();
} }
return notes; return notes;

View File

@ -78,16 +78,13 @@ public List<Ref> call() throws GitAPIException {
checkCallable(); checkCallable();
Map<String, Ref> refList; Map<String, Ref> refList;
List<Ref> tags = new ArrayList<Ref>(); List<Ref> tags = new ArrayList<Ref>();
RevWalk revWalk = new RevWalk(repo); try (RevWalk revWalk = new RevWalk(repo)) {
try {
refList = repo.getRefDatabase().getRefs(Constants.R_TAGS); refList = repo.getRefDatabase().getRefs(Constants.R_TAGS);
for (Ref ref : refList.values()) { for (Ref ref : refList.values()) {
tags.add(ref); tags.add(ref);
} }
} catch (IOException e) { } catch (IOException e) {
throw new JGitInternalException(e.getMessage(), e); throw new JGitInternalException(e.getMessage(), e);
} finally {
revWalk.release();
} }
Collections.sort(tags, new Comparator<Ref>() { Collections.sort(tags, new Comparator<Ref>() {
public int compare(Ref o1, Ref o2) { public int compare(Ref o1, Ref o2) {

View File

@ -369,9 +369,11 @@ public MergeResult call() throws GitAPIException, NoHeadException,
mergeStatus = MergeStatus.MERGED_NOT_COMMITTED; mergeStatus = MergeStatus.MERGED_NOT_COMMITTED;
} }
if (commit && !squash) { if (commit && !squash) {
newHeadId = new Git(getRepository()).commit() try (Git git = new Git(getRepository())) {
newHeadId = git.commit()
.setReflogComment(refLogMessage.toString()) .setReflogComment(refLogMessage.toString())
.call().getId(); .call().getId();
}
mergeStatus = MergeStatus.MERGED; mergeStatus = MergeStatus.MERGED;
} }
if (commit && squash) { if (commit && squash) {
@ -416,7 +418,7 @@ public MergeResult call() throws GitAPIException, NoHeadException,
e), e); e), e);
} finally { } finally {
if (revWalk != null) if (revWalk != null)
revWalk.release(); revWalk.close();
} }
} }

View File

@ -69,7 +69,7 @@ public enum MergeStatus {
FAST_FORWARD { FAST_FORWARD {
@Override @Override
public String toString() { public String toString() {
return "Fast-forward"; return "Fast-forward"; //$NON-NLS-1$
} }
@Override @Override
@ -83,7 +83,7 @@ public boolean isSuccessful() {
FAST_FORWARD_SQUASHED { FAST_FORWARD_SQUASHED {
@Override @Override
public String toString() { public String toString() {
return "Fast-forward-squashed"; return "Fast-forward-squashed"; //$NON-NLS-1$
} }
@Override @Override
@ -95,7 +95,7 @@ public boolean isSuccessful() {
ALREADY_UP_TO_DATE { ALREADY_UP_TO_DATE {
@Override @Override
public String toString() { public String toString() {
return "Already-up-to-date"; return "Already-up-to-date"; //$NON-NLS-1$
} }
@Override @Override
@ -107,7 +107,7 @@ public boolean isSuccessful() {
FAILED { FAILED {
@Override @Override
public String toString() { public String toString() {
return "Failed"; return "Failed"; //$NON-NLS-1$
} }
@Override @Override
@ -119,7 +119,7 @@ public boolean isSuccessful() {
MERGED { MERGED {
@Override @Override
public String toString() { public String toString() {
return "Merged"; return "Merged"; //$NON-NLS-1$
} }
@Override @Override
@ -133,7 +133,7 @@ public boolean isSuccessful() {
MERGED_SQUASHED { MERGED_SQUASHED {
@Override @Override
public String toString() { public String toString() {
return "Merged-squashed"; return "Merged-squashed"; //$NON-NLS-1$
} }
@Override @Override
@ -147,7 +147,7 @@ public boolean isSuccessful() {
MERGED_SQUASHED_NOT_COMMITTED { MERGED_SQUASHED_NOT_COMMITTED {
@Override @Override
public String toString() { public String toString() {
return "Merged-squashed-not-committed"; return "Merged-squashed-not-committed"; //$NON-NLS-1$
} }
@Override @Override
@ -159,7 +159,7 @@ public boolean isSuccessful() {
CONFLICTING { CONFLICTING {
@Override @Override
public String toString() { public String toString() {
return "Conflicting"; return "Conflicting"; //$NON-NLS-1$
} }
@Override @Override
@ -173,7 +173,7 @@ public boolean isSuccessful() {
ABORTED { ABORTED {
@Override @Override
public String toString() { public String toString() {
return "Aborted"; return "Aborted"; //$NON-NLS-1$
} }
@Override @Override
@ -186,7 +186,7 @@ public boolean isSuccessful() {
**/ **/
MERGED_NOT_COMMITTED { MERGED_NOT_COMMITTED {
public String toString() { public String toString() {
return "Merged-not-committed"; return "Merged-not-committed"; //$NON-NLS-1$
} }
@Override @Override
@ -198,7 +198,7 @@ public boolean isSuccessful() {
NOT_SUPPORTED { NOT_SUPPORTED {
@Override @Override
public String toString() { public String toString() {
return "Not-yet-supported"; return "Not-yet-supported"; //$NON-NLS-1$
} }
@Override @Override
@ -213,7 +213,7 @@ public boolean isSuccessful() {
*/ */
CHECKOUT_CONFLICT { CHECKOUT_CONFLICT {
public String toString() { public String toString() {
return "Checkout Conflict"; return "Checkout Conflict"; //$NON-NLS-1$
} }
@Override @Override

View File

@ -261,7 +261,7 @@ public PullResult call() throws GitAPIException,
fetchRes = fetch.call(); fetchRes = fetch.call();
} else { } else {
// we can skip the fetch altogether // we can skip the fetch altogether
remoteUri = "local repository"; remoteUri = JGitText.get().localRepository;
fetchRes = null; fetchRes = null;
} }
@ -302,9 +302,9 @@ public PullResult call() throws GitAPIException,
} }
} }
String upstreamName = "branch \'" String upstreamName = MessageFormat.format(
+ Repository.shortenRefName(remoteBranchName) + "\' of " JGitText.get().upstreamBranchName,
+ remoteUri; Repository.shortenRefName(remoteBranchName), remoteUri);
PullResult result; PullResult result;
if (pullRebaseMode.rebase) { if (pullRebaseMode.rebase) {

View File

@ -405,13 +405,14 @@ private boolean autoStashApply() throws IOException, GitAPIException {
.call(); .call();
} catch (StashApplyFailureException e) { } catch (StashApplyFailureException e) {
conflicts = true; conflicts = true;
RevWalk rw = new RevWalk(repo); try (RevWalk rw = new RevWalk(repo)) {
ObjectId stashId = repo.resolve(stash); ObjectId stashId = repo.resolve(stash);
RevCommit commit = rw.parseCommit(stashId); RevCommit commit = rw.parseCommit(stashId);
updateStashRef(commit, commit.getAuthorIdent(), updateStashRef(commit, commit.getAuthorIdent(),
commit.getShortMessage()); commit.getShortMessage());
} }
} }
}
return conflicts; return conflicts;
} }
@ -444,7 +445,7 @@ private RebaseResult processStep(RebaseTodoLine step, boolean shouldPick)
Collection<ObjectId> ids = or.resolve(step.getCommit()); Collection<ObjectId> ids = or.resolve(step.getCommit());
if (ids.size() != 1) if (ids.size() != 1)
throw new JGitInternalException( throw new JGitInternalException(
"Could not resolve uniquely the abbreviated object ID"); JGitText.get().cannotResolveUniquelyAbbrevObjectId);
RevCommit commitToPick = walk.parseCommit(ids.iterator().next()); RevCommit commitToPick = walk.parseCommit(ids.iterator().next());
if (shouldPick) { if (shouldPick) {
if (monitor.isCancelled()) if (monitor.isCancelled())
@ -518,15 +519,16 @@ private RebaseResult cherryPickCommitFlattening(RevCommit commitToPick)
// here we should skip this step in order to avoid // here we should skip this step in order to avoid
// confusing pseudo-changed // confusing pseudo-changed
String ourCommitName = getOurCommitName(); String ourCommitName = getOurCommitName();
CherryPickResult cherryPickResult = new Git(repo).cherryPick() try (Git git = new Git(repo)) {
CherryPickResult cherryPickResult = git.cherryPick()
.include(commitToPick).setOurCommitName(ourCommitName) .include(commitToPick).setOurCommitName(ourCommitName)
.setReflogPrefix(REFLOG_PREFIX).setStrategy(strategy) .setReflogPrefix(REFLOG_PREFIX).setStrategy(strategy)
.call(); .call();
switch (cherryPickResult.getStatus()) { switch (cherryPickResult.getStatus()) {
case FAILED: case FAILED:
if (operation == Operation.BEGIN) if (operation == Operation.BEGIN)
return abort(RebaseResult.failed(cherryPickResult return abort(RebaseResult
.getFailingPaths())); .failed(cherryPickResult.getFailingPaths()));
else else
return stop(commitToPick, Status.STOPPED); return stop(commitToPick, Status.STOPPED);
case CONFLICTING: case CONFLICTING:
@ -535,6 +537,7 @@ private RebaseResult cherryPickCommitFlattening(RevCommit commitToPick)
newHead = cherryPickResult.getNewHead(); newHead = cherryPickResult.getNewHead();
} }
} }
}
return null; return null;
} }
@ -563,12 +566,15 @@ private RebaseResult cherryPickCommitPreservingMerges(RevCommit commitToPick)
// Use the cherry-pick strategy if all non-first parents did not // Use the cherry-pick strategy if all non-first parents did not
// change. This is different from C Git, which always uses the merge // change. This is different from C Git, which always uses the merge
// strategy (see below). // strategy (see below).
try (Git git = new Git(repo)) {
if (otherParentsUnchanged) { if (otherParentsUnchanged) {
boolean isMerge = commitToPick.getParentCount() > 1; boolean isMerge = commitToPick.getParentCount() > 1;
String ourCommitName = getOurCommitName(); String ourCommitName = getOurCommitName();
CherryPickCommand pickCommand = new Git(repo).cherryPick() CherryPickCommand pickCommand = git.cherryPick()
.include(commitToPick).setOurCommitName(ourCommitName) .include(commitToPick)
.setReflogPrefix(REFLOG_PREFIX).setStrategy(strategy); .setOurCommitName(ourCommitName)
.setReflogPrefix(REFLOG_PREFIX)
.setStrategy(strategy);
if (isMerge) { if (isMerge) {
pickCommand.setMainlineParentNumber(1); pickCommand.setMainlineParentNumber(1);
// We write a MERGE_HEAD and later commit explicitly // We write a MERGE_HEAD and later commit explicitly
@ -579,16 +585,17 @@ private RebaseResult cherryPickCommitPreservingMerges(RevCommit commitToPick)
switch (cherryPickResult.getStatus()) { switch (cherryPickResult.getStatus()) {
case FAILED: case FAILED:
if (operation == Operation.BEGIN) if (operation == Operation.BEGIN)
return abort(RebaseResult.failed(cherryPickResult return abort(RebaseResult.failed(
.getFailingPaths())); cherryPickResult.getFailingPaths()));
else else
return stop(commitToPick, Status.STOPPED); return stop(commitToPick, Status.STOPPED);
case CONFLICTING: case CONFLICTING:
return stop(commitToPick, Status.STOPPED); return stop(commitToPick, Status.STOPPED);
case OK: case OK:
if (isMerge) { if (isMerge) {
// Commit the merge (setup above using writeMergeInfo()) // Commit the merge (setup above using
CommitCommand commit = new Git(repo).commit(); // writeMergeInfo())
CommitCommand commit = git.commit();
commit.setAuthor(commitToPick.getAuthorIdent()); commit.setAuthor(commitToPick.getAuthorIdent());
commit.setReflogComment(REFLOG_PREFIX + " " //$NON-NLS-1$ commit.setReflogComment(REFLOG_PREFIX + " " //$NON-NLS-1$
+ commitToPick.getShortMessage()); + commitToPick.getShortMessage());
@ -600,28 +607,29 @@ private RebaseResult cherryPickCommitPreservingMerges(RevCommit commitToPick)
} else { } else {
// Use the merge strategy to redo merges, which had some of // Use the merge strategy to redo merges, which had some of
// their non-first parents rewritten // their non-first parents rewritten
MergeCommand merge = new Git(repo).merge() MergeCommand merge = git.merge()
.setFastForward(MergeCommand.FastForwardMode.NO_FF) .setFastForward(MergeCommand.FastForwardMode.NO_FF)
.setCommit(false); .setCommit(false);
for (int i = 1; i < commitToPick.getParentCount(); i++) for (int i = 1; i < commitToPick.getParentCount(); i++)
merge.include(newParents.get(i)); merge.include(newParents.get(i));
MergeResult mergeResult = merge.call(); MergeResult mergeResult = merge.call();
if (mergeResult.getMergeStatus().isSuccessful()) { if (mergeResult.getMergeStatus().isSuccessful()) {
CommitCommand commit = new Git(repo).commit(); CommitCommand commit = git.commit();
commit.setAuthor(commitToPick.getAuthorIdent()); commit.setAuthor(commitToPick.getAuthorIdent());
commit.setMessage(commitToPick.getFullMessage()); commit.setMessage(commitToPick.getFullMessage());
commit.setReflogComment(REFLOG_PREFIX + " " //$NON-NLS-1$ commit.setReflogComment(REFLOG_PREFIX + " " //$NON-NLS-1$
+ commitToPick.getShortMessage()); + commitToPick.getShortMessage());
newHead = commit.call(); newHead = commit.call();
} else { } else {
if (operation == Operation.BEGIN if (operation == Operation.BEGIN && mergeResult
&& mergeResult.getMergeStatus() == MergeResult.MergeStatus.FAILED) .getMergeStatus() == MergeResult.MergeStatus.FAILED)
return abort(RebaseResult.failed(mergeResult return abort(RebaseResult
.getFailingPaths())); .failed(mergeResult.getFailingPaths()));
return stop(commitToPick, Status.STOPPED); return stop(commitToPick, Status.STOPPED);
} }
} }
} }
}
return null; return null;
} }
@ -758,15 +766,15 @@ private RevCommit squashIntoPrevious(boolean sequenceContainsSquash,
String commitMessage = rebaseState String commitMessage = rebaseState
.readFile(MESSAGE_SQUASH); .readFile(MESSAGE_SQUASH);
if (nextStep == null try (Git git = new Git(repo)) {
|| ((nextStep.getAction() != Action.FIXUP) && (nextStep if (nextStep == null || ((nextStep.getAction() != Action.FIXUP)
.getAction() != Action.SQUASH))) { && (nextStep.getAction() != Action.SQUASH))) {
// this is the last step in this sequence // this is the last step in this sequence
if (sequenceContainsSquash) { if (sequenceContainsSquash) {
commitMessage = interactiveHandler commitMessage = interactiveHandler
.modifyCommitMessage(commitMessage); .modifyCommitMessage(commitMessage);
} }
retNewHead = new Git(repo).commit() retNewHead = git.commit()
.setMessage(stripCommentLines(commitMessage)) .setMessage(stripCommentLines(commitMessage))
.setAmend(true).setNoVerify(true).call(); .setAmend(true).setNoVerify(true).call();
rebaseState.getFile(MESSAGE_SQUASH).delete(); rebaseState.getFile(MESSAGE_SQUASH).delete();
@ -774,9 +782,10 @@ private RevCommit squashIntoPrevious(boolean sequenceContainsSquash,
} else { } else {
// Next step is either Squash or Fixup // Next step is either Squash or Fixup
retNewHead = new Git(repo).commit().setMessage(commitMessage) retNewHead = git.commit().setMessage(commitMessage)
.setAmend(true).setNoVerify(true).call(); .setAmend(true).setNoVerify(true).call();
} }
}
return retNewHead; return retNewHead;
} }
@ -878,7 +887,8 @@ private void updateHead(String headName, RevCommit aNewHead, RevCommit onto)
case NO_CHANGE: case NO_CHANGE:
break; break;
default: default:
throw new JGitInternalException("Updating HEAD failed"); throw new JGitInternalException(
JGitText.get().updatingHeadFailed);
} }
rup = repo.updateRef(Constants.HEAD); rup = repo.updateRef(Constants.HEAD);
rup.setRefLogMessage("rebase finished: returning to " + headName, //$NON-NLS-1$ rup.setRefLogMessage("rebase finished: returning to " + headName, //$NON-NLS-1$
@ -890,7 +900,8 @@ private void updateHead(String headName, RevCommit aNewHead, RevCommit onto)
case NO_CHANGE: case NO_CHANGE:
break; break;
default: default:
throw new JGitInternalException("Updating HEAD failed"); throw new JGitInternalException(
JGitText.get().updatingHeadFailed);
} }
} }
} }
@ -917,11 +928,11 @@ private RevCommit checkoutCurrentHead() throws IOException, NoHeadException {
} finally { } finally {
dc.unlock(); dc.unlock();
} }
RevWalk rw = new RevWalk(repo); try (RevWalk rw = new RevWalk(repo)) {
RevCommit commit = rw.parseCommit(repo.resolve(Constants.HEAD)); RevCommit commit = rw.parseCommit(repo.resolve(Constants.HEAD));
rw.release();
return commit; return commit;
} }
}
/** /**
* @return the commit if we had to do a commit, otherwise null * @return the commit if we had to do a commit, otherwise null
@ -936,7 +947,8 @@ private RevCommit continueRebase() throws GitAPIException, IOException {
throw new UnmergedPathsException(); throw new UnmergedPathsException();
// determine whether we need to commit // determine whether we need to commit
TreeWalk treeWalk = new TreeWalk(repo); boolean needsCommit;
try (TreeWalk treeWalk = new TreeWalk(repo)) {
treeWalk.reset(); treeWalk.reset();
treeWalk.setRecursive(true); treeWalk.setRecursive(true);
treeWalk.addTree(new DirCacheIterator(dc)); treeWalk.addTree(new DirCacheIterator(dc));
@ -949,15 +961,16 @@ private RevCommit continueRebase() throws GitAPIException, IOException {
treeWalk.setFilter(TreeFilter.ANY_DIFF); treeWalk.setFilter(TreeFilter.ANY_DIFF);
boolean needsCommit = treeWalk.next(); needsCommit = treeWalk.next();
treeWalk.release(); }
if (needsCommit) { if (needsCommit) {
CommitCommand commit = new Git(repo).commit(); try (Git git = new Git(repo)) {
CommitCommand commit = git.commit();
commit.setMessage(rebaseState.readFile(MESSAGE)); commit.setMessage(rebaseState.readFile(MESSAGE));
commit.setAuthor(parseAuthor()); commit.setAuthor(parseAuthor());
return commit.call(); return commit.call();
} }
}
return null; return null;
} }
@ -979,9 +992,10 @@ private RebaseResult stop(RevCommit commitToPick, RebaseResult.Status status)
rebaseState.createFile(AUTHOR_SCRIPT, authorScript); rebaseState.createFile(AUTHOR_SCRIPT, authorScript);
rebaseState.createFile(MESSAGE, commitToPick.getFullMessage()); rebaseState.createFile(MESSAGE, commitToPick.getFullMessage());
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
DiffFormatter df = new DiffFormatter(bos); try (DiffFormatter df = new DiffFormatter(bos)) {
df.setRepository(repo); df.setRepository(repo);
df.format(commitToPick.getParent(0), commitToPick); df.format(commitToPick.getParent(0), commitToPick);
}
rebaseState.createFile(PATCH, new String(bos.toByteArray(), rebaseState.createFile(PATCH, new String(bos.toByteArray(),
Constants.CHARACTER_ENCODING)); Constants.CHARACTER_ENCODING));
rebaseState.createFile(STOPPED_SHA, rebaseState.createFile(STOPPED_SHA,
@ -1124,9 +1138,11 @@ else if (!isInteractive() && walk.isMergedInto(headCommit, upstream)) {
private List<RevCommit> calculatePickList(RevCommit headCommit) private List<RevCommit> calculatePickList(RevCommit headCommit)
throws GitAPIException, NoHeadException, IOException { throws GitAPIException, NoHeadException, IOException {
LogCommand cmd = new Git(repo).log().addRange(upstreamCommit, Iterable<RevCommit> commitsToUse;
headCommit); try (Git git = new Git(repo)) {
Iterable<RevCommit> commitsToUse = cmd.call(); LogCommand cmd = git.log().addRange(upstreamCommit, headCommit);
commitsToUse = cmd.call();
}
List<RevCommit> cherryPickList = new ArrayList<RevCommit>(); List<RevCommit> cherryPickList = new ArrayList<RevCommit>();
for (RevCommit commit : commitsToUse) { for (RevCommit commit : commitsToUse) {
if (preserveMerges || commit.getParentCount() == 1) if (preserveMerges || commit.getParentCount() == 1)
@ -1277,7 +1293,7 @@ private void checkParameters() throws WrongRepositoryStateException {
if (this.upstreamCommit == null) if (this.upstreamCommit == null)
throw new JGitInternalException(MessageFormat throw new JGitInternalException(MessageFormat
.format(JGitText.get().missingRequiredParameter, .format(JGitText.get().missingRequiredParameter,
"upstream")); "upstream")); //$NON-NLS-1$
return; return;
default: default:
throw new WrongRepositoryStateException(MessageFormat.format( throw new WrongRepositoryStateException(MessageFormat.format(
@ -1312,7 +1328,7 @@ private RebaseResult abort(RebaseResult result) throws IOException,
} }
dco.setFailOnConflict(false); dco.setFailOnConflict(false);
dco.checkout(); dco.checkout();
walk.release(); walk.close();
} finally { } finally {
monitor.endTask(); monitor.endTask();
} }
@ -1384,10 +1400,11 @@ private boolean checkoutCommit(String headName, RevCommit commit)
case FORCED: case FORCED:
break; break;
default: default:
throw new IOException("Could not rewind to upstream commit"); throw new IOException(
JGitText.get().couldNotRewindToUpstreamCommit);
} }
} finally { } finally {
walk.release(); walk.close();
monitor.endTask(); monitor.endTask();
} }
return true; return true;
@ -1454,7 +1471,7 @@ public RebaseCommand setUpstream(String upstream)
public RebaseCommand setUpstreamName(String upstreamName) { public RebaseCommand setUpstreamName(String upstreamName) {
if (upstreamCommit == null) { if (upstreamCommit == null) {
throw new IllegalStateException( throw new IllegalStateException(
"setUpstreamName must be called after setUpstream."); "setUpstreamName must be called after setUpstream."); //$NON-NLS-1$
} }
this.upstreamCommitName = upstreamName; this.upstreamCommitName = upstreamName;
return this; return this;

View File

@ -81,11 +81,10 @@ protected RemoveNoteCommand(Repository repo) {
public Note call() throws GitAPIException { public Note call() throws GitAPIException {
checkCallable(); checkCallable();
RevWalk walk = new RevWalk(repo); try (RevWalk walk = new RevWalk(repo);
ObjectInserter inserter = repo.newObjectInserter(); ObjectInserter inserter = repo.newObjectInserter()) {
NoteMap map = NoteMap.newEmptyMap(); NoteMap map = NoteMap.newEmptyMap();
RevCommit notesCommit = null; RevCommit notesCommit = null;
try {
Ref ref = repo.getRef(notesRef); Ref ref = repo.getRef(notesRef);
// if we have a notes ref, use it // if we have a notes ref, use it
if (ref != null) { if (ref != null) {
@ -94,13 +93,10 @@ public Note call() throws GitAPIException {
} }
map.set(id, null, inserter); map.set(id, null, inserter);
commitNoteMap(walk, map, notesCommit, inserter, commitNoteMap(walk, map, notesCommit, inserter,
"Notes removed by 'git notes remove'"); "Notes removed by 'git notes remove'"); //$NON-NLS-1$
return map.getNote(id); return map.getNote(id);
} catch (IOException e) { } catch (IOException e) {
throw new JGitInternalException(e.getMessage(), e); throw new JGitInternalException(e.getMessage(), e);
} finally {
inserter.release();
walk.release();
} }
} }

View File

@ -157,8 +157,8 @@ public Ref call() throws GitAPIException, CheckoutConflictException {
if (ref != null && commitId == null) { if (ref != null && commitId == null) {
// @TODO throw an InvalidRefNameException. We can't do that // @TODO throw an InvalidRefNameException. We can't do that
// now because this would break the API // now because this would break the API
throw new JGitInternalException("Invalid ref " + ref throw new JGitInternalException(MessageFormat
+ " specified"); .format(JGitText.get().invalidRefName, ref));
} }
final ObjectId commitTree; final ObjectId commitTree;
@ -234,17 +234,12 @@ else if (repo.readSquashCommitMsg() != null)
} }
private RevCommit parseCommit(final ObjectId commitId) { private RevCommit parseCommit(final ObjectId commitId) {
RevCommit commit; try (RevWalk rw = new RevWalk(repo)) {
RevWalk rw = new RevWalk(repo); return rw.parseCommit(commitId);
try {
commit = rw.parseCommit(commitId);
} catch (IOException e) { } catch (IOException e) {
throw new JGitInternalException(MessageFormat.format( throw new JGitInternalException(MessageFormat.format(
JGitText.get().cannotReadCommit, commitId.toString()), e); JGitText.get().cannotReadCommit, commitId.toString()), e);
} finally {
rw.release();
} }
return commit;
} }
private ObjectId resolveRefToCommitId() { private ObjectId resolveRefToCommitId() {
@ -276,7 +271,7 @@ public ResetCommand setMode(ResetType mode) {
if (!filepaths.isEmpty()) if (!filepaths.isEmpty())
throw new JGitInternalException(MessageFormat.format( throw new JGitInternalException(MessageFormat.format(
JGitText.get().illegalCombinationOfArguments, JGitText.get().illegalCombinationOfArguments,
"[--mixed | --soft | --hard]", "<paths>...")); //$NON-NLS-1$ "[--mixed | --soft | --hard]", "<paths>...")); //$NON-NLS-1$ //$NON-NLS-2$
this.mode = mode; this.mode = mode;
return this; return this;
} }
@ -290,7 +285,7 @@ public ResetCommand setMode(ResetType mode) {
public ResetCommand addPath(String path) { public ResetCommand addPath(String path) {
if (mode != null) if (mode != null)
throw new JGitInternalException(MessageFormat.format( throw new JGitInternalException(MessageFormat.format(
JGitText.get().illegalCombinationOfArguments, "<paths>...", JGitText.get().illegalCombinationOfArguments, "<paths>...", //$NON-NLS-1$
"[--mixed | --soft | --hard]")); //$NON-NLS-1$ "[--mixed | --soft | --hard]")); //$NON-NLS-1$
filepaths.add(path); filepaths.add(path);
return this; return this;
@ -305,11 +300,10 @@ private String getRefOrHEAD() {
private void resetIndexForPaths(ObjectId commitTree) { private void resetIndexForPaths(ObjectId commitTree) {
DirCache dc = null; DirCache dc = null;
try { try (final TreeWalk tw = new TreeWalk(repo)) {
dc = repo.lockDirCache(); dc = repo.lockDirCache();
DirCacheBuilder builder = dc.builder(); DirCacheBuilder builder = dc.builder();
final TreeWalk tw = new TreeWalk(repo);
tw.addTree(new DirCacheBuildIterator(builder)); tw.addTree(new DirCacheBuildIterator(builder));
if (commitTree != null) if (commitTree != null)
tw.addTree(commitTree); tw.addTree(commitTree);
@ -342,11 +336,9 @@ private void resetIndexForPaths(ObjectId commitTree) {
private void resetIndex(ObjectId commitTree) throws IOException { private void resetIndex(ObjectId commitTree) throws IOException {
DirCache dc = repo.lockDirCache(); DirCache dc = repo.lockDirCache();
TreeWalk walk = null; try (TreeWalk walk = new TreeWalk(repo)) {
try {
DirCacheBuilder builder = dc.builder(); DirCacheBuilder builder = dc.builder();
walk = new TreeWalk(repo);
if (commitTree != null) if (commitTree != null)
walk.addTree(commitTree); walk.addTree(commitTree);
else else
@ -380,8 +372,6 @@ private void resetIndex(ObjectId commitTree) throws IOException {
builder.commit(); builder.commit();
} finally { } finally {
dc.unlock(); dc.unlock();
if (walk != null)
walk.release();
} }
} }

View File

@ -126,8 +126,7 @@ public RevCommit call() throws NoMessageException, UnmergedPathsException,
RevCommit newHead = null; RevCommit newHead = null;
checkCallable(); checkCallable();
RevWalk revWalk = new RevWalk(repo); try (RevWalk revWalk = new RevWalk(repo)) {
try {
// get the head commit // get the head commit
Ref headRef = repo.getRef(Constants.HEAD); Ref headRef = repo.getRef(Constants.HEAD);
@ -182,9 +181,11 @@ public RevCommit call() throws NoMessageException, UnmergedPathsException,
merger.getResultTreeId()); merger.getResultTreeId());
dco.setFailOnConflict(true); dco.setFailOnConflict(true);
dco.checkout(); dco.checkout();
newHead = new Git(getRepository()).commit() try (Git git = new Git(getRepository())) {
.setMessage(newMessage) newHead = git.commit().setMessage(newMessage)
.setReflogComment("revert: " + shortMessage).call(); //$NON-NLS-1$ .setReflogComment("revert: " + shortMessage) //$NON-NLS-1$
.call();
}
revertedRefs.add(src); revertedRefs.add(src);
headCommit = newHead; headCommit = newHead;
} else { } else {
@ -220,8 +221,6 @@ public RevCommit call() throws NoMessageException, UnmergedPathsException,
MessageFormat.format( MessageFormat.format(
JGitText.get().exceptionCaughtDuringExecutionOfRevertCommand, JGitText.get().exceptionCaughtDuringExecutionOfRevertCommand,
e), e); e), e);
} finally {
revWalk.release();
} }
return newHead; return newHead;
} }

View File

@ -144,10 +144,9 @@ public DirCache call() throws GitAPIException,
checkCallable(); checkCallable();
DirCache dc = null; DirCache dc = null;
try { try (final TreeWalk tw = new TreeWalk(repo)) {
dc = repo.lockDirCache(); dc = repo.lockDirCache();
DirCacheBuilder builder = dc.builder(); DirCacheBuilder builder = dc.builder();
final TreeWalk tw = new TreeWalk(repo);
tw.reset(); // drop the first empty tree, which we do not need here tw.reset(); // drop the first empty tree, which we do not need here
tw.setRecursive(true); tw.setRecursive(true);
tw.setFilter(PathFilterGroup.createFromStrings(filepatterns)); tw.setFilter(PathFilterGroup.createFromStrings(filepatterns));

View File

@ -76,10 +76,9 @@ protected ShowNoteCommand(Repository repo) {
public Note call() throws GitAPIException { public Note call() throws GitAPIException {
checkCallable(); checkCallable();
RevWalk walk = new RevWalk(repo);
NoteMap map = NoteMap.newEmptyMap(); NoteMap map = NoteMap.newEmptyMap();
RevCommit notesCommit = null; RevCommit notesCommit = null;
try { try (RevWalk walk = new RevWalk(repo)) {
Ref ref = repo.getRef(notesRef); Ref ref = repo.getRef(notesRef);
// if we have a notes ref, use it // if we have a notes ref, use it
if (ref != null) { if (ref != null) {
@ -89,8 +88,6 @@ public Note call() throws GitAPIException {
return map.getNote(id); return map.getNote(id);
} catch (IOException e) { } catch (IOException e) {
throw new JGitInternalException(e.getMessage(), e); throw new JGitInternalException(e.getMessage(), e);
} finally {
walk.release();
} }
} }

View File

@ -166,9 +166,8 @@ public ObjectId call() throws GitAPIException,
JGitText.get().stashApplyOnUnsafeRepository, JGitText.get().stashApplyOnUnsafeRepository,
repo.getRepositoryState())); repo.getRepositoryState()));
ObjectReader reader = repo.newObjectReader(); try (ObjectReader reader = repo.newObjectReader();
try { RevWalk revWalk = new RevWalk(reader)) {
RevWalk revWalk = new RevWalk(reader);
ObjectId headCommit = repo.resolve(Constants.HEAD); ObjectId headCommit = repo.resolve(Constants.HEAD);
if (headCommit == null) if (headCommit == null)
@ -192,8 +191,8 @@ public ObjectId call() throws GitAPIException,
untrackedCommit = revWalk.parseCommit(stashCommit.getParent(2)); untrackedCommit = revWalk.parseCommit(stashCommit.getParent(2));
ResolveMerger merger = (ResolveMerger) strategy.newMerger(repo); ResolveMerger merger = (ResolveMerger) strategy.newMerger(repo);
merger.setCommitNames(new String[] { "stashed HEAD", "HEAD", merger.setCommitNames(new String[] { "stashed HEAD", "HEAD", //$NON-NLS-1$ //$NON-NLS-2$
"stash" }); "stash" }); //$NON-NLS-1$
merger.setBase(stashHeadCommit); merger.setBase(stashHeadCommit);
merger.setWorkingTreeIterator(new FileTreeIterator(repo)); merger.setWorkingTreeIterator(new FileTreeIterator(repo));
if (merger.merge(headCommit, stashCommit)) { if (merger.merge(headCommit, stashCommit)) {
@ -205,8 +204,8 @@ public ObjectId call() throws GitAPIException,
if (applyIndex) { if (applyIndex) {
ResolveMerger ixMerger = (ResolveMerger) strategy ResolveMerger ixMerger = (ResolveMerger) strategy
.newMerger(repo, true); .newMerger(repo, true);
ixMerger.setCommitNames(new String[] { "stashed HEAD", ixMerger.setCommitNames(new String[] { "stashed HEAD", //$NON-NLS-1$
"HEAD", "stashed index" }); "HEAD", "stashed index" }); //$NON-NLS-1$//$NON-NLS-2$
ixMerger.setBase(stashHeadCommit); ixMerger.setBase(stashHeadCommit);
boolean ok = ixMerger.merge(headCommit, stashIndexCommit); boolean ok = ixMerger.merge(headCommit, stashIndexCommit);
if (ok) { if (ok) {
@ -250,8 +249,6 @@ public ObjectId call() throws GitAPIException,
throw e; throw e;
} catch (IOException e) { } catch (IOException e) {
throw new JGitInternalException(JGitText.get().stashApplyFailed, e); throw new JGitInternalException(JGitText.get().stashApplyFailed, e);
} finally {
reader.release();
} }
} }
@ -286,11 +283,9 @@ public void setApplyUntracked(boolean applyUntracked) {
private void resetIndex(RevTree tree) throws IOException { private void resetIndex(RevTree tree) throws IOException {
DirCache dc = repo.lockDirCache(); DirCache dc = repo.lockDirCache();
TreeWalk walk = null; try (TreeWalk walk = new TreeWalk(repo)) {
try {
DirCacheBuilder builder = dc.builder(); DirCacheBuilder builder = dc.builder();
walk = new TreeWalk(repo);
walk.addTree(tree); walk.addTree(tree);
walk.addTree(new DirCacheIterator(dc)); walk.addTree(new DirCacheIterator(dc));
walk.setRecursive(true); walk.setRecursive(true);
@ -321,15 +316,13 @@ private void resetIndex(RevTree tree) throws IOException {
builder.commit(); builder.commit();
} finally { } finally {
dc.unlock(); dc.unlock();
if (walk != null)
walk.release();
} }
} }
private void resetUntracked(RevTree tree) throws CheckoutConflictException, private void resetUntracked(RevTree tree) throws CheckoutConflictException,
IOException { IOException {
TreeWalk walk = new TreeWalk(repo); // maybe NameConflictTreeWalk; // TODO maybe NameConflictTreeWalk ?
try { try (TreeWalk walk = new TreeWalk(repo)) {
walk.addTree(tree); walk.addTree(tree);
walk.addTree(new FileTreeIterator(repo)); walk.addTree(new FileTreeIterator(repo));
walk.setRecursive(true); walk.setRecursive(true);
@ -359,8 +352,6 @@ private void resetUntracked(RevTree tree) throws CheckoutConflictException,
checkoutPath(entry, reader); checkoutPath(entry, reader);
} }
} finally {
walk.release();
} }
} }

View File

@ -94,11 +94,11 @@
*/ */
public class StashCreateCommand extends GitCommand<RevCommit> { public class StashCreateCommand extends GitCommand<RevCommit> {
private static final String MSG_INDEX = "index on {0}: {1} {2}"; private static final String MSG_INDEX = "index on {0}: {1} {2}"; //$NON-NLS-1$
private static final String MSG_UNTRACKED = "untracked files on {0}: {1} {2}"; private static final String MSG_UNTRACKED = "untracked files on {0}: {1} {2}"; //$NON-NLS-1$
private static final String MSG_WORKING_DIR = "WIP on {0}: {1} {2}"; private static final String MSG_WORKING_DIR = "WIP on {0}: {1} {2}"; //$NON-NLS-1$
private String indexMessage = MSG_INDEX; private String indexMessage = MSG_INDEX;
@ -187,9 +187,10 @@ public StashCreateCommand setIncludeUntracked(boolean includeUntracked) {
private RevCommit parseCommit(final ObjectReader reader, private RevCommit parseCommit(final ObjectReader reader,
final ObjectId headId) throws IOException { final ObjectId headId) throws IOException {
final RevWalk walk = new RevWalk(reader); try (final RevWalk walk = new RevWalk(reader)) {
return walk.parseCommit(headId); return walk.parseCommit(headId);
} }
}
private CommitBuilder createBuilder() { private CommitBuilder createBuilder() {
CommitBuilder builder = new CommitBuilder(); CommitBuilder builder = new CommitBuilder();
@ -239,14 +240,13 @@ public RevCommit call() throws GitAPIException {
checkCallable(); checkCallable();
Ref head = getHead(); Ref head = getHead();
ObjectReader reader = repo.newObjectReader(); try (ObjectReader reader = repo.newObjectReader()) {
try {
RevCommit headCommit = parseCommit(reader, head.getObjectId()); RevCommit headCommit = parseCommit(reader, head.getObjectId());
DirCache cache = repo.lockDirCache(); DirCache cache = repo.lockDirCache();
ObjectInserter inserter = repo.newObjectInserter();
ObjectId commitId; ObjectId commitId;
try { try (ObjectInserter inserter = repo.newObjectInserter();
TreeWalk treeWalk = new TreeWalk(reader); TreeWalk treeWalk = new TreeWalk(reader)) {
treeWalk.setRecursive(true); treeWalk.setRecursive(true);
treeWalk.addTree(headCommit.getTree()); treeWalk.addTree(headCommit.getTree());
treeWalk.addTree(new DirCacheIterator(cache)); treeWalk.addTree(new DirCacheIterator(cache));
@ -380,7 +380,6 @@ public void apply(DirCacheEntry ent) {
} }
} finally { } finally {
inserter.release();
cache.unlock(); cache.unlock();
} }
@ -391,8 +390,6 @@ public void apply(DirCacheEntry ent) {
return parseCommit(reader, commitId); return parseCommit(reader, commitId);
} catch (IOException e) { } catch (IOException e) {
throw new JGitInternalException(JGitText.get().stashFailed, e); throw new JGitInternalException(JGitText.get().stashFailed, e);
} finally {
reader.release();
} }
} }
} }

View File

@ -52,6 +52,7 @@
import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRefNameException; import org.eclipse.jgit.api.errors.InvalidRefNameException;
import org.eclipse.jgit.api.errors.JGitInternalException; import org.eclipse.jgit.api.errors.JGitInternalException;
import org.eclipse.jgit.api.errors.RefNotFoundException;
import org.eclipse.jgit.errors.LockFailedException; import org.eclipse.jgit.errors.LockFailedException;
import org.eclipse.jgit.internal.JGitText; import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.internal.storage.file.ReflogWriter; import org.eclipse.jgit.internal.storage.file.ReflogWriter;
@ -184,6 +185,10 @@ public ObjectId call() throws GitAPIException {
List<ReflogEntry> entries; List<ReflogEntry> entries;
try { try {
ReflogReader reader = repo.getReflogReader(R_STASH); ReflogReader reader = repo.getReflogReader(R_STASH);
if (reader == null) {
throw new RefNotFoundException(MessageFormat
.format(JGitText.get().refNotResolved, stashRef));
}
entries = reader.getReverseEntries(); entries = reader.getReverseEntries();
} catch (IOException e) { } catch (IOException e) {
throw new JGitInternalException(JGitText.get().stashDropFailed, e); throw new JGitInternalException(JGitText.get().stashDropFailed, e);

View File

@ -143,8 +143,7 @@ public Collection<String> call() throws InvalidConfigurationException,
RefNotFoundException, GitAPIException { RefNotFoundException, GitAPIException {
checkCallable(); checkCallable();
try { try (SubmoduleWalk generator = SubmoduleWalk.forIndex(repo)) {
SubmoduleWalk generator = SubmoduleWalk.forIndex(repo);
if (!paths.isEmpty()) if (!paths.isEmpty())
generator.setFilter(PathFilterGroup.createFromStrings(paths)); generator.setFilter(PathFilterGroup.createFromStrings(paths));
List<String> updated = new ArrayList<String>(); List<String> updated = new ArrayList<String>();
@ -171,8 +170,7 @@ public Collection<String> call() throws InvalidConfigurationException,
submoduleRepo = clone.call().getRepository(); submoduleRepo = clone.call().getRepository();
} }
try { try (RevWalk walk = new RevWalk(submoduleRepo)) {
RevWalk walk = new RevWalk(submoduleRepo);
RevCommit commit = walk RevCommit commit = walk
.parseCommit(generator.getObjectId()); .parseCommit(generator.getObjectId());

View File

@ -128,8 +128,7 @@ public Ref call() throws GitAPIException, ConcurrentRefUpdateException,
RepositoryState state = repo.getRepositoryState(); RepositoryState state = repo.getRepositoryState();
processOptions(state); processOptions(state);
RevWalk revWalk = new RevWalk(repo); try (RevWalk revWalk = new RevWalk(repo)) {
try {
// if no id is set, we should attempt to use HEAD // if no id is set, we should attempt to use HEAD
if (id == null) { if (id == null) {
ObjectId objectId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$ ObjectId objectId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$
@ -157,24 +156,19 @@ public Ref call() throws GitAPIException, ConcurrentRefUpdateException,
newTag.setObjectId(id); newTag.setObjectId(id);
// write the tag object // write the tag object
ObjectInserter inserter = repo.newObjectInserter(); try (ObjectInserter inserter = repo.newObjectInserter()) {
try {
ObjectId tagId = inserter.insert(newTag); ObjectId tagId = inserter.insert(newTag);
inserter.flush(); inserter.flush();
String tag = newTag.getTag(); String tag = newTag.getTag();
return updateTagRef(tagId, revWalk, tag, newTag.toString()); return updateTagRef(tagId, revWalk, tag, newTag.toString());
} finally {
inserter.release();
} }
} catch (IOException e) { } catch (IOException e) {
throw new JGitInternalException( throw new JGitInternalException(
JGitText.get().exceptionCaughtDuringExecutionOfTagCommand, JGitText.get().exceptionCaughtDuringExecutionOfTagCommand,
e); e);
} finally {
revWalk.release();
} }
} }
@ -222,8 +216,9 @@ private void processOptions(RepositoryState state)
if (tagger == null && annotated) if (tagger == null && annotated)
tagger = new PersonIdent(repo); tagger = new PersonIdent(repo);
if (name == null || !Repository.isValidRefName(Constants.R_TAGS + name)) if (name == null || !Repository.isValidRefName(Constants.R_TAGS + name))
throw new InvalidTagNameException(MessageFormat.format(JGitText throw new InvalidTagNameException(
.get().tagNameInvalid, name == null ? "<null>" : name)); MessageFormat.format(JGitText.get().tagNameInvalid,
name == null ? "<null>" : name)); //$NON-NLS-1$
if (signed) if (signed)
throw new UnsupportedOperationException( throw new UnsupportedOperationException(
JGitText.get().signingNotSupportedOnTag); JGitText.get().signingNotSupportedOnTag);

View File

@ -172,7 +172,7 @@ private void initRevPool(boolean reverse) {
throw new IllegalStateException(); throw new IllegalStateException();
if (revPool != null) if (revPool != null)
revPool.release(); revPool.close();
if (reverse) if (reverse)
revPool = new ReverseWalk(getRepository()); revPool = new ReverseWalk(getRepository());
@ -450,7 +450,7 @@ public BlameResult computeBlameResult() throws IOException {
r.computeAll(); r.computeAll();
return r; return r;
} finally { } finally {
release(); close();
} }
} }
@ -513,7 +513,7 @@ public boolean next() throws IOException {
} }
private boolean done() { private boolean done() {
release(); close();
return false; return false;
} }
@ -936,14 +936,6 @@ public RawText getResultContents() throws IOException {
return queue != null ? queue.sourceText : null; return queue != null ? queue.sourceText : null;
} }
/**
* Release the current blame session. Use {@link #close()} instead.
*/
@Deprecated
public void release() {
close();
}
/** /**
* Release the current blame session. * Release the current blame session.
* *

View File

@ -380,14 +380,6 @@ public void flush() throws IOException {
out.flush(); out.flush();
} }
/**
* Release the internal ObjectReader state. Use {@link #close()} instead.
*/
@Deprecated
public void release() {
close();
}
/** /**
* Release the internal ObjectReader state. * Release the internal ObjectReader state.
* *

View File

@ -323,7 +323,7 @@ public List<DiffEntry> compute(ProgressMonitor pm) throws IOException {
try { try {
return compute(objectReader, pm); return compute(objectReader, pm);
} finally { } finally {
objectReader.release(); objectReader.close();
} }
} }
return Collections.unmodifiableList(entries); return Collections.unmodifiableList(entries);

View File

@ -403,8 +403,7 @@ private boolean doCheckout() throws CorruptObjectException, IOException,
MissingObjectException, IncorrectObjectTypeException, MissingObjectException, IncorrectObjectTypeException,
CheckoutConflictException, IndexWriteException { CheckoutConflictException, IndexWriteException {
toBeDeleted.clear(); toBeDeleted.clear();
ObjectReader objectReader = repo.getObjectDatabase().newReader(); try (ObjectReader objectReader = repo.getObjectDatabase().newReader()) {
try {
if (headCommitTree != null) if (headCommitTree != null)
preScanTwoTrees(); preScanTwoTrees();
else else
@ -454,8 +453,6 @@ private boolean doCheckout() throws CorruptObjectException, IOException,
// commit the index builder - a new index is persisted // commit the index builder - a new index is persisted
if (!builder.commit()) if (!builder.commit())
throw new IndexWriteException(); throw new IndexWriteException();
} finally {
objectReader.release();
} }
return toBeDeleted.size() == 0; return toBeDeleted.size() == 0;
} }
@ -1056,8 +1053,7 @@ private void cleanUpConflicts() throws CheckoutConflictException {
*/ */
private boolean isModifiedSubtree_IndexWorkingtree(String path) private boolean isModifiedSubtree_IndexWorkingtree(String path)
throws CorruptObjectException, IOException { throws CorruptObjectException, IOException {
NameConflictTreeWalk tw = new NameConflictTreeWalk(repo); try (NameConflictTreeWalk tw = new NameConflictTreeWalk(repo)) {
try {
tw.addTree(new DirCacheIterator(dc)); tw.addTree(new DirCacheIterator(dc));
tw.addTree(new FileTreeIterator(repo)); tw.addTree(new FileTreeIterator(repo));
tw.setRecursive(true); tw.setRecursive(true);
@ -1075,8 +1071,6 @@ private boolean isModifiedSubtree_IndexWorkingtree(String path)
} }
} }
return false; return false;
} finally {
tw.release();
} }
} }
@ -1105,8 +1099,7 @@ private boolean isModified_IndexTree(String path, ObjectId iId,
*/ */
private boolean isModifiedSubtree_IndexTree(String path, ObjectId tree) private boolean isModifiedSubtree_IndexTree(String path, ObjectId tree)
throws CorruptObjectException, IOException { throws CorruptObjectException, IOException {
NameConflictTreeWalk tw = new NameConflictTreeWalk(repo); try (NameConflictTreeWalk tw = new NameConflictTreeWalk(repo)) {
try {
tw.addTree(new DirCacheIterator(dc)); tw.addTree(new DirCacheIterator(dc));
tw.addTree(tree); tw.addTree(tree);
tw.setRecursive(true); tw.setRecursive(true);
@ -1124,8 +1117,6 @@ private boolean isModifiedSubtree_IndexTree(String path, ObjectId tree)
return true; return true;
} }
return false; return false;
} finally {
tw.release();
} }
} }

View File

@ -0,0 +1,357 @@
/*
* Copyright (C) 2015, Google Inc.
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, Inc. nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.eclipse.jgit.gitrepo;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.gitrepo.RepoProject.CopyFile;
import org.eclipse.jgit.gitrepo.internal.RepoText;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.lib.Repository;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* Repo XML manifest parser.
*
* @see <a href="https://code.google.com/p/git-repo/">git-repo project page</a>
* @since 4.0
*/
public class ManifestParser extends DefaultHandler {
private final String filename;
private final String baseUrl;
private final String defaultBranch;
private final Repository rootRepo;
private final Map<String, String> remotes;
private final Set<String> plusGroups;
private final Set<String> minusGroups;
private final List<RepoProject> projects;
private final List<RepoProject> filteredProjects;
private final IncludedFileReader includedReader;
private String defaultRemote;
private String defaultRevision;
private int xmlInRead;
private RepoProject currentProject;
/**
* A callback to read included xml files.
*/
public interface IncludedFileReader {
/**
* Read a file from the same base dir of the manifest xml file.
*
* @param path
* The relative path to the file to read
* @return the {@code InputStream} of the file.
* @throws GitAPIException
* @throws IOException
*/
public InputStream readIncludeFile(String path)
throws GitAPIException, IOException;
}
/**
* @param includedReader
* @param filename
* @param defaultBranch
* @param baseUrl
* @param groups
* @param rootRepo
*/
public ManifestParser(IncludedFileReader includedReader, String filename,
String defaultBranch, String baseUrl, String groups,
Repository rootRepo) {
this.includedReader = includedReader;
this.filename = filename;
this.defaultBranch = defaultBranch;
this.rootRepo = rootRepo;
// Strip trailing /s to match repo behavior.
int lastIndex = baseUrl.length() - 1;
while (lastIndex >= 0 && baseUrl.charAt(lastIndex) == '/')
lastIndex--;
this.baseUrl = baseUrl.substring(0, lastIndex + 1);
plusGroups = new HashSet<String>();
minusGroups = new HashSet<String>();
if (groups == null || groups.length() == 0
|| groups.equals("default")) { //$NON-NLS-1$
// default means "all,-notdefault"
minusGroups.add("notdefault"); //$NON-NLS-1$
} else {
for (String group : groups.split(",")) { //$NON-NLS-1$
if (group.startsWith("-")) //$NON-NLS-1$
minusGroups.add(group.substring(1));
else
plusGroups.add(group);
}
}
remotes = new HashMap<String, String>();
projects = new ArrayList<RepoProject>();
filteredProjects = new ArrayList<RepoProject>();
}
/**
* Read the xml file.
*
* @param inputStream
* @throws IOException
*/
public void read(InputStream inputStream) throws IOException {
xmlInRead++;
final XMLReader xr;
try {
xr = XMLReaderFactory.createXMLReader();
} catch (SAXException e) {
throw new IOException(JGitText.get().noXMLParserAvailable);
}
xr.setContentHandler(this);
try {
xr.parse(new InputSource(inputStream));
} catch (SAXException e) {
IOException error = new IOException(
RepoText.get().errorParsingManifestFile);
error.initCause(e);
throw error;
}
}
@Override
public void startElement(
String uri,
String localName,
String qName,
Attributes attributes) throws SAXException {
if ("project".equals(qName)) { //$NON-NLS-1$
currentProject = new RepoProject(
attributes.getValue("name"), //$NON-NLS-1$
attributes.getValue("path"), //$NON-NLS-1$
attributes.getValue("revision"), //$NON-NLS-1$
attributes.getValue("remote"), //$NON-NLS-1$
attributes.getValue("groups")); //$NON-NLS-1$
} else if ("remote".equals(qName)) { //$NON-NLS-1$
String alias = attributes.getValue("alias"); //$NON-NLS-1$
String fetch = attributes.getValue("fetch"); //$NON-NLS-1$
remotes.put(attributes.getValue("name"), fetch); //$NON-NLS-1$
if (alias != null)
remotes.put(alias, fetch);
} else if ("default".equals(qName)) { //$NON-NLS-1$
defaultRemote = attributes.getValue("remote"); //$NON-NLS-1$
defaultRevision = attributes.getValue("revision"); //$NON-NLS-1$
if (defaultRevision == null)
defaultRevision = defaultBranch;
} else if ("copyfile".equals(qName)) { //$NON-NLS-1$
if (currentProject == null)
throw new SAXException(RepoText.get().invalidManifest);
currentProject.addCopyFile(new CopyFile(
rootRepo,
currentProject.path,
attributes.getValue("src"), //$NON-NLS-1$
attributes.getValue("dest"))); //$NON-NLS-1$
} else if ("include".equals(qName)) { //$NON-NLS-1$
String name = attributes.getValue("name"); //$NON-NLS-1$
InputStream is = null;
if (includedReader != null) {
try {
is = includedReader.readIncludeFile(name);
} catch (Exception e) {
throw new SAXException(MessageFormat.format(
RepoText.get().errorIncludeFile, name), e);
}
} else if (filename != null) {
int index = filename.lastIndexOf('/');
String path = filename.substring(0, index + 1) + name;
try {
is = new FileInputStream(path);
} catch (IOException e) {
throw new SAXException(MessageFormat.format(
RepoText.get().errorIncludeFile, path), e);
}
}
if (is == null) {
throw new SAXException(
RepoText.get().errorIncludeNotImplemented);
}
try {
read(is);
} catch (IOException e) {
throw new SAXException(e);
}
}
}
@Override
public void endElement(
String uri,
String localName,
String qName) throws SAXException {
if ("project".equals(qName)) { //$NON-NLS-1$
projects.add(currentProject);
currentProject = null;
}
}
@Override
public void endDocument() throws SAXException {
xmlInRead--;
if (xmlInRead != 0)
return;
// Only do the following after we finished reading everything.
Map<String, String> remoteUrls = new HashMap<String, String>();
URI baseUri;
try {
baseUri = new URI(baseUrl);
} catch (URISyntaxException e) {
throw new SAXException(e);
}
for (RepoProject proj : projects) {
String remote = proj.remote;
if (remote == null) {
if (defaultRemote == null) {
if (filename != null)
throw new SAXException(MessageFormat.format(
RepoText.get().errorNoDefaultFilename,
filename));
else
throw new SAXException(
RepoText.get().errorNoDefault);
}
remote = defaultRemote;
}
String remoteUrl = remoteUrls.get(remote);
if (remoteUrl == null) {
remoteUrl = baseUri.resolve(remotes.get(remote)).toString();
if (!remoteUrl.endsWith("/")) //$NON-NLS-1$
remoteUrl = remoteUrl + "/"; //$NON-NLS-1$
remoteUrls.put(remote, remoteUrl);
}
proj.setUrl(remoteUrl + proj.name)
.setDefaultRevision(defaultRevision);
}
filteredProjects.addAll(projects);
removeNotInGroup();
removeOverlaps();
}
/**
* Getter for projects.
*
* @return projects list reference, never null
*/
public List<RepoProject> getProjects() {
return projects;
}
/**
* Getter for filterdProjects.
*
* @return filtered projects list reference, never null
*/
public List<RepoProject> getFilteredProjects() {
return filteredProjects;
}
/** Remove projects that are not in our desired groups. */
void removeNotInGroup() {
Iterator<RepoProject> iter = filteredProjects.iterator();
while (iter.hasNext())
if (!inGroups(iter.next()))
iter.remove();
}
/** Remove projects that sits in a subdirectory of any other project. */
void removeOverlaps() {
Collections.sort(filteredProjects);
Iterator<RepoProject> iter = filteredProjects.iterator();
if (!iter.hasNext())
return;
RepoProject last = iter.next();
while (iter.hasNext()) {
RepoProject p = iter.next();
if (last.isAncestorOf(p))
iter.remove();
else
last = p;
}
}
boolean inGroups(RepoProject proj) {
for (String group : minusGroups) {
if (proj.groups.contains(group)) {
// minus groups have highest priority.
return false;
}
}
if (plusGroups.isEmpty() || plusGroups.contains("all")) { //$NON-NLS-1$
// empty plus groups means "all"
return true;
}
for (String group : plusGroups) {
if (proj.groups.contains(group))
return true;
}
return false;
}
}

View File

@ -44,22 +44,12 @@
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.channels.FileChannel;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.GitCommand; import org.eclipse.jgit.api.GitCommand;
@ -70,6 +60,8 @@
import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheBuilder; import org.eclipse.jgit.dircache.DirCacheBuilder;
import org.eclipse.jgit.dircache.DirCacheEntry; import org.eclipse.jgit.dircache.DirCacheEntry;
import org.eclipse.jgit.gitrepo.ManifestParser.IncludedFileReader;
import org.eclipse.jgit.gitrepo.RepoProject.CopyFile;
import org.eclipse.jgit.gitrepo.internal.RepoText; import org.eclipse.jgit.gitrepo.internal.RepoText;
import org.eclipse.jgit.internal.JGitText; import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.lib.CommitBuilder; import org.eclipse.jgit.lib.CommitBuilder;
@ -89,12 +81,6 @@
import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.util.FileUtils; import org.eclipse.jgit.util.FileUtils;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
/** /**
* A class used to execute a repo command. * A class used to execute a repo command.
@ -124,7 +110,7 @@ public class RepoCommand extends GitCommand<RevCommit> {
private InputStream inputStream; private InputStream inputStream;
private IncludedFileReader includedReader; private IncludedFileReader includedReader;
private List<Project> bareProjects; private List<RepoProject> bareProjects;
private Git git; private Git git;
private ProgressMonitor monitor; private ProgressMonitor monitor;
@ -214,350 +200,10 @@ public byte[] readFile(String uri, String ref, String path)
*/ */
protected byte[] readFileFromRepo(Repository repo, protected byte[] readFileFromRepo(Repository repo,
String ref, String path) throws GitAPIException, IOException { String ref, String path) throws GitAPIException, IOException {
ObjectReader reader = repo.newObjectReader(); try (ObjectReader reader = repo.newObjectReader()) {
byte[] result;
try {
ObjectId oid = repo.resolve(ref + ":" + path); //$NON-NLS-1$ ObjectId oid = repo.resolve(ref + ":" + path); //$NON-NLS-1$
result = reader.open(oid).getBytes(Integer.MAX_VALUE); return reader.open(oid).getBytes(Integer.MAX_VALUE);
} finally {
reader.release();
} }
return result;
}
}
/**
* A callback to read included xml files.
*
* @since 3.5
*/
public interface IncludedFileReader {
/**
* Read a file from the same base dir of the manifest xml file.
*
* @param path
* The relative path to the file to read
* @return the {@code InputStream} of the file.
* @throws GitAPIException
* @throws IOException
*/
public InputStream readIncludeFile(String path)
throws GitAPIException, IOException;
}
private static class CopyFile {
final Repository repo;
final String path;
final String src;
final String dest;
CopyFile(Repository repo, String path, String src, String dest) {
this.repo = repo;
this.path = path;
this.src = src;
this.dest = dest;
}
void copy() throws IOException {
File srcFile = new File(repo.getWorkTree(),
path + "/" + src); //$NON-NLS-1$
File destFile = new File(repo.getWorkTree(), dest);
FileInputStream input = new FileInputStream(srcFile);
try {
FileOutputStream output = new FileOutputStream(destFile);
try {
FileChannel channel = input.getChannel();
output.getChannel().transferFrom(channel, 0, channel.size());
} finally {
output.close();
}
} finally {
input.close();
}
}
}
private static class Project implements Comparable<Project> {
final String name;
final String path;
final String revision;
final String remote;
final Set<String> groups;
final List<CopyFile> copyfiles;
Project(String name, String path, String revision,
String remote, String groups) {
this.name = name;
if (path != null)
this.path = path;
else
this.path = name;
this.revision = revision;
this.remote = remote;
this.groups = new HashSet<String>();
if (groups != null && groups.length() > 0)
this.groups.addAll(Arrays.asList(groups.split(","))); //$NON-NLS-1$
copyfiles = new ArrayList<CopyFile>();
}
void addCopyFile(CopyFile copyfile) {
copyfiles.add(copyfile);
}
String getPathWithSlash() {
if (path.endsWith("/")) //$NON-NLS-1$
return path;
else
return path + "/"; //$NON-NLS-1$
}
boolean isAncestorOf(Project that) {
return that.getPathWithSlash().startsWith(this.getPathWithSlash());
}
@Override
public boolean equals(Object o) {
if (o instanceof Project) {
Project that = (Project) o;
return this.getPathWithSlash().equals(that.getPathWithSlash());
}
return false;
}
@Override
public int hashCode() {
return this.getPathWithSlash().hashCode();
}
public int compareTo(Project that) {
return this.getPathWithSlash().compareTo(that.getPathWithSlash());
}
}
private static class XmlManifest extends DefaultHandler {
private final RepoCommand command;
private final String filename;
private final String baseUrl;
private final Map<String, String> remotes;
private final Set<String> plusGroups;
private final Set<String> minusGroups;
private List<Project> projects;
private String defaultRemote;
private String defaultRevision;
private IncludedFileReader includedReader;
private int xmlInRead;
private Project currentProject;
XmlManifest(RepoCommand command, IncludedFileReader includedReader,
String filename, String baseUrl, String groups) {
this.command = command;
this.includedReader = includedReader;
this.filename = filename;
// Strip trailing /s to match repo behavior.
int lastIndex = baseUrl.length() - 1;
while (lastIndex >= 0 && baseUrl.charAt(lastIndex) == '/')
lastIndex--;
this.baseUrl = baseUrl.substring(0, lastIndex + 1);
remotes = new HashMap<String, String>();
projects = new ArrayList<Project>();
plusGroups = new HashSet<String>();
minusGroups = new HashSet<String>();
if (groups == null || groups.length() == 0 || groups.equals("default")) { //$NON-NLS-1$
// default means "all,-notdefault"
minusGroups.add("notdefault"); //$NON-NLS-1$
} else {
for (String group : groups.split(",")) { //$NON-NLS-1$
if (group.startsWith("-")) //$NON-NLS-1$
minusGroups.add(group.substring(1));
else
plusGroups.add(group);
}
}
}
void read(InputStream inputStream) throws IOException {
xmlInRead++;
final XMLReader xr;
try {
xr = XMLReaderFactory.createXMLReader();
} catch (SAXException e) {
throw new IOException(JGitText.get().noXMLParserAvailable);
}
xr.setContentHandler(this);
try {
xr.parse(new InputSource(inputStream));
} catch (SAXException e) {
IOException error = new IOException(
RepoText.get().errorParsingManifestFile);
error.initCause(e);
throw error;
}
}
@Override
public void startElement(
String uri,
String localName,
String qName,
Attributes attributes) throws SAXException {
if ("project".equals(qName)) { //$NON-NLS-1$
currentProject = new Project(
attributes.getValue("name"), //$NON-NLS-1$
attributes.getValue("path"), //$NON-NLS-1$
attributes.getValue("revision"), //$NON-NLS-1$
attributes.getValue("remote"), //$NON-NLS-1$
attributes.getValue("groups")); //$NON-NLS-1$
} else if ("remote".equals(qName)) { //$NON-NLS-1$
String alias = attributes.getValue("alias"); //$NON-NLS-1$
String fetch = attributes.getValue("fetch"); //$NON-NLS-1$
remotes.put(attributes.getValue("name"), fetch); //$NON-NLS-1$
if (alias != null)
remotes.put(alias, fetch);
} else if ("default".equals(qName)) { //$NON-NLS-1$
defaultRemote = attributes.getValue("remote"); //$NON-NLS-1$
defaultRevision = attributes.getValue("revision"); //$NON-NLS-1$
if (defaultRevision == null)
defaultRevision = command.branch;
} else if ("copyfile".equals(qName)) { //$NON-NLS-1$
if (currentProject == null)
throw new SAXException(RepoText.get().invalidManifest);
currentProject.addCopyFile(new CopyFile(
command.repo,
currentProject.path,
attributes.getValue("src"), //$NON-NLS-1$
attributes.getValue("dest"))); //$NON-NLS-1$
} else if ("include".equals(qName)) { //$NON-NLS-1$
String name = attributes.getValue("name"); //$NON-NLS-1$
InputStream is = null;
if (includedReader != null) {
try {
is = includedReader.readIncludeFile(name);
} catch (Exception e) {
throw new SAXException(MessageFormat.format(
RepoText.get().errorIncludeFile, name), e);
}
} else if (filename != null) {
int index = filename.lastIndexOf('/');
String path = filename.substring(0, index + 1) + name;
try {
is = new FileInputStream(path);
} catch (IOException e) {
throw new SAXException(MessageFormat.format(
RepoText.get().errorIncludeFile, path), e);
}
}
if (is == null) {
throw new SAXException(
RepoText.get().errorIncludeNotImplemented);
}
try {
read(is);
} catch (IOException e) {
throw new SAXException(e);
}
}
}
@Override
public void endElement(
String uri,
String localName,
String qName) throws SAXException {
if ("project".equals(qName)) { //$NON-NLS-1$
projects.add(currentProject);
currentProject = null;
}
}
@Override
public void endDocument() throws SAXException {
xmlInRead--;
if (xmlInRead != 0)
return;
// Only do the following after we finished reading everything.
removeNotInGroup();
removeOverlaps();
Map<String, String> remoteUrls = new HashMap<String, String>();
URI baseUri;
try {
baseUri = new URI(baseUrl);
} catch (URISyntaxException e) {
throw new SAXException(e);
}
for (Project proj : projects) {
String remote = proj.remote;
if (remote == null) {
if (defaultRemote == null) {
if (filename != null)
throw new SAXException(MessageFormat.format(
RepoText.get().errorNoDefaultFilename,
filename));
else
throw new SAXException(
RepoText.get().errorNoDefault);
}
remote = defaultRemote;
}
String remoteUrl = remoteUrls.get(remote);
if (remoteUrl == null) {
remoteUrl = baseUri.resolve(remotes.get(remote)).toString();
if (!remoteUrl.endsWith("/")) //$NON-NLS-1$
remoteUrl = remoteUrl + "/"; //$NON-NLS-1$
remoteUrls.put(remote, remoteUrl);
}
command.addSubmodule(remoteUrl + proj.name,
proj.path,
proj.revision == null
? defaultRevision : proj.revision,
proj.copyfiles);
}
}
/** Remove projects that are not in our desired groups. */
void removeNotInGroup() {
Iterator<Project> iter = projects.iterator();
while (iter.hasNext())
if (!inGroups(iter.next()))
iter.remove();
}
/** Remove projects that sits in a subdirectory of any other project. */
void removeOverlaps() {
Collections.sort(projects);
Iterator<Project> iter = projects.iterator();
if (!iter.hasNext())
return;
Project last = iter.next();
while (iter.hasNext()) {
Project p = iter.next();
if (last.isAncestorOf(p))
iter.remove();
else
last = p;
}
}
boolean inGroups(Project proj) {
for (String group : minusGroups) {
if (proj.groups.contains(group)) {
// minus groups have highest priority.
return false;
}
}
if (plusGroups.isEmpty() || plusGroups.contains("all")) { //$NON-NLS-1$
// empty plus groups means "all"
return true;
}
for (String group : plusGroups) {
if (proj.groups.contains(group))
return true;
}
return false;
} }
} }
@ -693,7 +339,7 @@ public RepoCommand setRemoteReader(final RemoteReader callback) {
* *
* @param reader * @param reader
* @return this command * @return this command
* @since 3.5 * @since 4.0
*/ */
public RepoCommand setIncludedFileReader(IncludedFileReader reader) { public RepoCommand setIncludedFileReader(IncludedFileReader reader) {
this.includedReader = reader; this.includedReader = reader;
@ -720,7 +366,7 @@ public RevCommit call() throws GitAPIException {
} }
if (repo.isBare()) { if (repo.isBare()) {
bareProjects = new ArrayList<Project>(); bareProjects = new ArrayList<RepoProject>();
if (author == null) if (author == null)
author = new PersonIdent(repo); author = new PersonIdent(repo);
if (callback == null) if (callback == null)
@ -728,11 +374,17 @@ public RevCommit call() throws GitAPIException {
} else } else
git = new Git(repo); git = new Git(repo);
XmlManifest manifest = new XmlManifest( ManifestParser parser = new ManifestParser(
this, includedReader, path, uri, groups); includedReader, path, branch, uri, groups, repo);
try { try {
manifest.read(inputStream); parser.read(inputStream);
} catch (IOException e) { for (RepoProject proj : parser.getFilteredProjects()) {
addSubmodule(proj.url,
proj.path,
proj.getRevision(),
proj.copyfiles);
}
} catch (GitAPIException | IOException e) {
throw new ManifestErrorException(e); throw new ManifestErrorException(e);
} }
} finally { } finally {
@ -748,10 +400,9 @@ public RevCommit call() throws GitAPIException {
DirCache index = DirCache.newInCore(); DirCache index = DirCache.newInCore();
DirCacheBuilder builder = index.builder(); DirCacheBuilder builder = index.builder();
ObjectInserter inserter = repo.newObjectInserter(); ObjectInserter inserter = repo.newObjectInserter();
RevWalk rw = new RevWalk(repo); try (RevWalk rw = new RevWalk(repo)) {
try {
Config cfg = new Config(); Config cfg = new Config();
for (Project proj : bareProjects) { for (RepoProject proj : bareProjects) {
String name = proj.path; String name = proj.path;
String nameUri = proj.name; String nameUri = proj.name;
cfg.setString("submodule", name, "path", name); //$NON-NLS-1$ //$NON-NLS-2$ cfg.setString("submodule", name, "path", name); //$NON-NLS-1$ //$NON-NLS-2$
@ -831,8 +482,6 @@ public RevCommit call() throws GitAPIException {
return rw.parseCommit(commitId); return rw.parseCommit(commitId);
} catch (IOException e) { } catch (IOException e) {
throw new ManifestErrorException(e); throw new ManifestErrorException(e);
} finally {
rw.release();
} }
} else { } else {
return git return git
@ -843,9 +492,9 @@ public RevCommit call() throws GitAPIException {
} }
private void addSubmodule(String url, String name, String revision, private void addSubmodule(String url, String name, String revision,
List<CopyFile> copyfiles) throws SAXException { List<CopyFile> copyfiles) throws GitAPIException, IOException {
if (repo.isBare()) { if (repo.isBare()) {
Project proj = new Project(url, name, revision, null, null); RepoProject proj = new RepoProject(url, name, revision, null, null);
proj.copyfiles.addAll(copyfiles); proj.copyfiles.addAll(copyfiles);
bareProjects.add(proj); bareProjects.add(proj);
} else { } else {
@ -856,11 +505,12 @@ private void addSubmodule(String url, String name, String revision,
if (monitor != null) if (monitor != null)
add.setProgressMonitor(monitor); add.setProgressMonitor(monitor);
try {
Repository subRepo = add.call(); Repository subRepo = add.call();
if (revision != null) { if (revision != null) {
Git sub = new Git(subRepo); try (Git sub = new Git(subRepo)) {
sub.checkout().setName(findRef(revision, subRepo)).call(); sub.checkout().setName(findRef(revision, subRepo))
.call();
}
subRepo.close(); subRepo.close();
git.add().addFilepattern(name).call(); git.add().addFilepattern(name).call();
} }
@ -868,11 +518,6 @@ private void addSubmodule(String url, String name, String revision,
copyfile.copy(); copyfile.copy();
git.add().addFilepattern(copyfile.dest).call(); git.add().addFilepattern(copyfile.dest).call();
} }
} catch (GitAPIException e) {
throw new SAXException(e);
} catch (IOException e) {
throw new SAXException(e);
}
} }
} }

View File

@ -0,0 +1,220 @@
/*
* Copyright (C) 2015, Google Inc.
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, Inc. nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.eclipse.jgit.gitrepo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.jgit.lib.Repository;
/**
* The representation of a repo sub project.
*
* @see <a href="https://code.google.com/p/git-repo/">git-repo project page</a>
* @since 4.0
*/
public class RepoProject implements Comparable<RepoProject> {
final String name;
final String path;
final String revision;
final String remote;
final Set<String> groups;
final List<CopyFile> copyfiles;
String url;
String defaultRevision;
/**
* The representation of a copy file configuration.
*/
public static class CopyFile {
final Repository repo;
final String path;
final String src;
final String dest;
/**
* @param repo
* @param path
* the path of the project containing this copyfile config.
* @param src
* @param dest
*/
public CopyFile(Repository repo, String path, String src, String dest) {
this.repo = repo;
this.path = path;
this.src = src;
this.dest = dest;
}
/**
* Do the copy file action.
*
* @throws IOException
*/
public void copy() throws IOException {
File srcFile = new File(repo.getWorkTree(),
path + "/" + src); //$NON-NLS-1$
File destFile = new File(repo.getWorkTree(), dest);
FileInputStream input = new FileInputStream(srcFile);
try {
FileOutputStream output = new FileOutputStream(destFile);
try {
FileChannel channel = input.getChannel();
output.getChannel().transferFrom(channel, 0, channel.size());
} finally {
output.close();
}
} finally {
input.close();
}
}
}
/**
* @param name
* @param path
* @param revision
* @param remote
* @param groups
*/
public RepoProject(String name, String path, String revision,
String remote, String groups) {
this.name = name;
if (path != null)
this.path = path;
else
this.path = name;
this.revision = revision;
this.remote = remote;
this.groups = new HashSet<String>();
if (groups != null && groups.length() > 0)
this.groups.addAll(Arrays.asList(groups.split(","))); //$NON-NLS-1$
copyfiles = new ArrayList<CopyFile>();
}
/**
* Set the url of the sub repo.
*
* @param url
* @return this for chaining.
*/
public RepoProject setUrl(String url) {
this.url = url;
return this;
}
/**
* Set the default revision for the sub repo.
*
* @param defaultRevision
* @return this for chaining.
*/
public RepoProject setDefaultRevision(String defaultRevision) {
this.defaultRevision = defaultRevision;
return this;
}
/**
* Get the revision of the sub repo.
*
* @return revision if set, or default revision.
*/
public String getRevision() {
return revision == null ? defaultRevision : revision;
}
/**
* Add a copy file configuration.
*
* @param copyfile
*/
public void addCopyFile(CopyFile copyfile) {
copyfiles.add(copyfile);
}
String getPathWithSlash() {
if (path.endsWith("/")) //$NON-NLS-1$
return path;
else
return path + "/"; //$NON-NLS-1$
}
/**
* Check if this sub repo is the ancestor of given sub repo.
*
* @param that
* non null
* @return true if this sub repo is the ancestor of given sub repo.
*/
public boolean isAncestorOf(RepoProject that) {
return that.getPathWithSlash().startsWith(this.getPathWithSlash());
}
@Override
public boolean equals(Object o) {
if (o instanceof RepoProject) {
RepoProject that = (RepoProject) o;
return this.getPathWithSlash().equals(that.getPathWithSlash());
}
return false;
}
@Override
public int hashCode() {
return this.getPathWithSlash().hashCode();
}
@Override
public int compareTo(RepoProject that) {
return this.getPathWithSlash().compareTo(that.getPathWithSlash());
}
}

View File

@ -86,6 +86,7 @@ public static JGitText get() {
/***/ public String badEscape; /***/ public String badEscape;
/***/ public String badGroupHeader; /***/ public String badGroupHeader;
/***/ public String badObjectType; /***/ public String badObjectType;
/***/ public String badRef;
/***/ public String badSectionEntry; /***/ public String badSectionEntry;
/***/ public String bareRepositoryNoWorkdirAndIndex; /***/ public String bareRepositoryNoWorkdirAndIndex;
/***/ public String base64InputNotProperlyPadded; /***/ public String base64InputNotProperlyPadded;
@ -117,16 +118,23 @@ public static JGitText get() {
/***/ public String cannotCreateTempDir; /***/ public String cannotCreateTempDir;
/***/ public String cannotDeleteCheckedOutBranch; /***/ public String cannotDeleteCheckedOutBranch;
/***/ public String cannotDeleteFile; /***/ public String cannotDeleteFile;
/***/ public String cannotDeleteObjectsPath;
/***/ public String cannotDeleteStaleTrackingRef; /***/ public String cannotDeleteStaleTrackingRef;
/***/ public String cannotDeleteStaleTrackingRef2; /***/ public String cannotDeleteStaleTrackingRef2;
/***/ public String cannotDetermineProxyFor; /***/ public String cannotDetermineProxyFor;
/***/ public String cannotDownload; /***/ public String cannotDownload;
/***/ public String cannotEnterObjectsPath;
/***/ public String cannotEnterPathFromParent;
/***/ public String cannotExecute; /***/ public String cannotExecute;
/***/ public String cannotGet; /***/ public String cannotGet;
/***/ public String cannotGetObjectsPath;
/***/ public String cannotListObjectsPath;
/***/ public String cannotListPackPath;
/***/ public String cannotListRefs; /***/ public String cannotListRefs;
/***/ public String cannotLock; /***/ public String cannotLock;
/***/ public String cannotLockPackIn; /***/ public String cannotLockPackIn;
/***/ public String cannotMatchOnEmptyString; /***/ public String cannotMatchOnEmptyString;
/***/ public String cannotMkdirObjectPath;
/***/ public String cannotMoveIndexTo; /***/ public String cannotMoveIndexTo;
/***/ public String cannotMovePackTo; /***/ public String cannotMovePackTo;
/***/ public String cannotOpenService; /***/ public String cannotOpenService;
@ -139,13 +147,16 @@ public static JGitText get() {
/***/ public String cannotReadFile; /***/ public String cannotReadFile;
/***/ public String cannotReadHEAD; /***/ public String cannotReadHEAD;
/***/ public String cannotReadObject; /***/ public String cannotReadObject;
/***/ public String cannotReadObjectsPath;
/***/ public String cannotReadTree; /***/ public String cannotReadTree;
/***/ public String cannotRebaseWithoutCurrentHead; /***/ public String cannotRebaseWithoutCurrentHead;
/***/ public String cannotResolveLocalTrackingRefForUpdating; /***/ public String cannotResolveLocalTrackingRefForUpdating;
/***/ public String cannotSquashFixupWithoutPreviousCommit; /***/ public String cannotSquashFixupWithoutPreviousCommit;
/***/ public String cannotStoreObjects; /***/ public String cannotStoreObjects;
/***/ public String cannotResolveUniquelyAbbrevObjectId;
/***/ public String cannotUnloadAModifiedTree; /***/ public String cannotUnloadAModifiedTree;
/***/ public String cannotWorkWithOtherStagesThanZeroRightNow; /***/ public String cannotWorkWithOtherStagesThanZeroRightNow;
/***/ public String cannotWriteObjectsPath;
/***/ public String canOnlyCherryPickCommitsWithOneParent; /***/ public String canOnlyCherryPickCommitsWithOneParent;
/***/ public String canOnlyRevertCommitsWithOneParent; /***/ public String canOnlyRevertCommitsWithOneParent;
/***/ public String commitDoesNotHaveGivenParent; /***/ public String commitDoesNotHaveGivenParent;
@ -172,26 +183,60 @@ public static JGitText get() {
/***/ public String corruptionDetectedReReadingAt; /***/ public String corruptionDetectedReReadingAt;
/***/ public String corruptObjectBadStream; /***/ public String corruptObjectBadStream;
/***/ public String corruptObjectBadStreamCorruptHeader; /***/ public String corruptObjectBadStreamCorruptHeader;
/***/ public String corruptObjectDuplicateEntryNames;
/***/ public String corruptObjectGarbageAfterSize; /***/ public String corruptObjectGarbageAfterSize;
/***/ public String corruptObjectIncorrectLength; /***/ public String corruptObjectIncorrectLength;
/***/ public String corruptObjectIncorrectSorting;
/***/ public String corruptObjectInvalidAuthor;
/***/ public String corruptObjectInvalidCommitter;
/***/ public String corruptObjectInvalidEntryMode; /***/ public String corruptObjectInvalidEntryMode;
/***/ public String corruptObjectInvalidMode; /***/ public String corruptObjectInvalidMode;
/***/ public String corruptObjectInvalidModeChar;
/***/ public String corruptObjectInvalidModeStartsZero;
/***/ public String corruptObjectInvalidMode2; /***/ public String corruptObjectInvalidMode2;
/***/ public String corruptObjectInvalidMode3; /***/ public String corruptObjectInvalidMode3;
/***/ public String corruptObjectInvalidName;
/***/ public String corruptObjectInvalidNameAux;
/***/ public String corruptObjectInvalidNameCon;
/***/ public String corruptObjectInvalidNameCom;
/***/ public String corruptObjectInvalidNameEnd;
/***/ public String corruptObjectInvalidNameIgnorableUnicode;
/***/ public String corruptObjectInvalidNameInvalidUtf8;
/***/ public String corruptObjectInvalidNameLpt;
/***/ public String corruptObjectInvalidNameNul;
/***/ public String corruptObjectInvalidNamePrn;
/***/ public String corruptObjectInvalidObject;
/***/ public String corruptObjectInvalidParent;
/***/ public String corruptObjectInvalidTagger;
/***/ public String corruptObjectInvalidTree;
/***/ public String corruptObjectInvalidType; /***/ public String corruptObjectInvalidType;
/***/ public String corruptObjectInvalidType2; /***/ public String corruptObjectInvalidType2;
/***/ public String corruptObjectMalformedHeader; /***/ public String corruptObjectMalformedHeader;
/***/ public String corruptObjectNameContainsByte;
/***/ public String corruptObjectNameContainsChar;
/***/ public String corruptObjectNameContainsNullByte;
/***/ public String corruptObjectNameContainsSlash;
/***/ public String corruptObjectNameDot;
/***/ public String corruptObjectNameDotDot;
/***/ public String corruptObjectNameZeroLength;
/***/ public String corruptObjectNegativeSize; /***/ public String corruptObjectNegativeSize;
/***/ public String corruptObjectNoAuthor; /***/ public String corruptObjectNoAuthor;
/***/ public String corruptObjectNoCommitter; /***/ public String corruptObjectNoCommitter;
/***/ public String corruptObjectNoHeader; /***/ public String corruptObjectNoHeader;
/***/ public String corruptObjectNoObject; /***/ public String corruptObjectNoObject;
/***/ public String corruptObjectNoObjectHeader;
/***/ public String corruptObjectNoTaggerBadHeader; /***/ public String corruptObjectNoTaggerBadHeader;
/***/ public String corruptObjectNoTaggerHeader; /***/ public String corruptObjectNoTaggerHeader;
/***/ public String corruptObjectNoTagHeader;
/***/ public String corruptObjectNoTagName; /***/ public String corruptObjectNoTagName;
/***/ public String corruptObjectNotree; /***/ public String corruptObjectNotree;
/***/ public String corruptObjectNotreeHeader;
/***/ public String corruptObjectNoType; /***/ public String corruptObjectNoType;
/***/ public String corruptObjectNoTypeHeader;
/***/ public String corruptObjectPackfileChecksumIncorrect; /***/ public String corruptObjectPackfileChecksumIncorrect;
/***/ public String corruptObjectTruncatedInMode;
/***/ public String corruptObjectTruncatedInName;
/***/ public String corruptObjectTruncatedInObjectId;
/***/ public String corruptPack; /***/ public String corruptPack;
/***/ public String couldNotCheckOutBecauseOfConflicts; /***/ public String couldNotCheckOutBecauseOfConflicts;
/***/ public String couldNotDeleteLockFileShouldNotHappen; /***/ public String couldNotDeleteLockFileShouldNotHappen;
@ -204,6 +249,7 @@ public static JGitText get() {
/***/ public String couldNotRenameDeleteOldIndex; /***/ public String couldNotRenameDeleteOldIndex;
/***/ public String couldNotRenameTemporaryFile; /***/ public String couldNotRenameTemporaryFile;
/***/ public String couldNotRenameTemporaryIndexFileToIndex; /***/ public String couldNotRenameTemporaryIndexFileToIndex;
/***/ public String couldNotRewindToUpstreamCommit;
/***/ public String couldNotURLEncodeToUTF8; /***/ public String couldNotURLEncodeToUTF8;
/***/ public String couldNotWriteFile; /***/ public String couldNotWriteFile;
/***/ public String countingObjects; /***/ public String countingObjects;
@ -239,6 +285,7 @@ public static JGitText get() {
/***/ public String eitherGitDirOrWorkTreeRequired; /***/ public String eitherGitDirOrWorkTreeRequired;
/***/ public String emptyCommit; /***/ public String emptyCommit;
/***/ public String emptyPathNotPermitted; /***/ public String emptyPathNotPermitted;
/***/ public String emptyRef;
/***/ public String encryptionError; /***/ public String encryptionError;
/***/ public String endOfFileInEscape; /***/ public String endOfFileInEscape;
/***/ public String entryNotFoundByPath; /***/ public String entryNotFoundByPath;
@ -299,6 +346,7 @@ public static JGitText get() {
/***/ public String gcFailed; /***/ public String gcFailed;
/***/ public String gitmodulesNotFound; /***/ public String gitmodulesNotFound;
/***/ public String headRequiredToStash; /***/ public String headRequiredToStash;
/***/ public String hiddenFilesStartWithDot;
/***/ public String hoursAgo; /***/ public String hoursAgo;
/***/ public String hugeIndexesAreNotSupportedByJgitYet; /***/ public String hugeIndexesAreNotSupportedByJgitYet;
/***/ public String hunkBelongsToAnotherFile; /***/ public String hunkBelongsToAnotherFile;
@ -337,6 +385,7 @@ public static JGitText get() {
/***/ public String invalidGitType; /***/ public String invalidGitType;
/***/ public String invalidId; /***/ public String invalidId;
/***/ public String invalidIdLength; /***/ public String invalidIdLength;
/***/ public String invalidIgnoreParamSubmodule;
/***/ public String invalidIntegerValue; /***/ public String invalidIntegerValue;
/***/ public String invalidKey; /***/ public String invalidKey;
/***/ public String invalidLineInConfigFile; /***/ public String invalidLineInConfigFile;
@ -369,8 +418,10 @@ public static JGitText get() {
/***/ public String largeObjectOutOfMemory; /***/ public String largeObjectOutOfMemory;
/***/ public String lengthExceedsMaximumArraySize; /***/ public String lengthExceedsMaximumArraySize;
/***/ public String listingAlternates; /***/ public String listingAlternates;
/***/ public String listingPacks;
/***/ public String localObjectsIncomplete; /***/ public String localObjectsIncomplete;
/***/ public String localRefIsMissingObjects; /***/ public String localRefIsMissingObjects;
/***/ public String localRepository;
/***/ public String lockCountMustBeGreaterOrEqual1; /***/ public String lockCountMustBeGreaterOrEqual1;
/***/ public String lockError; /***/ public String lockError;
/***/ public String lockOnNotClosed; /***/ public String lockOnNotClosed;
@ -469,6 +520,8 @@ public static JGitText get() {
/***/ public String pathNotConfigured; /***/ public String pathNotConfigured;
/***/ public String peeledLineBeforeRef; /***/ public String peeledLineBeforeRef;
/***/ public String peerDidNotSupplyACompleteObjectGraph; /***/ public String peerDidNotSupplyACompleteObjectGraph;
/***/ public String personIdentEmailNonNull;
/***/ public String personIdentNameNonNull;
/***/ public String prefixRemote; /***/ public String prefixRemote;
/***/ public String problemWithResolvingPushRefSpecsLocally; /***/ public String problemWithResolvingPushRefSpecsLocally;
/***/ public String progressMonUploading; /***/ public String progressMonUploading;
@ -512,6 +565,7 @@ public static JGitText get() {
/***/ public String repositoryIsRequired; /***/ public String repositoryIsRequired;
/***/ public String repositoryNotFound; /***/ public String repositoryNotFound;
/***/ public String repositoryState_applyMailbox; /***/ public String repositoryState_applyMailbox;
/***/ public String repositoryState_bare;
/***/ public String repositoryState_bisecting; /***/ public String repositoryState_bisecting;
/***/ public String repositoryState_conflicts; /***/ public String repositoryState_conflicts;
/***/ public String repositoryState_merged; /***/ public String repositoryState_merged;
@ -525,6 +579,9 @@ public static JGitText get() {
/***/ public String resolvingDeltas; /***/ public String resolvingDeltas;
/***/ public String resultLengthIncorrect; /***/ public String resultLengthIncorrect;
/***/ public String rewinding; /***/ public String rewinding;
/***/ public String s3ActionDeletion;
/***/ public String s3ActionReading;
/***/ public String s3ActionWriting;
/***/ public String searchForReuse; /***/ public String searchForReuse;
/***/ public String searchForSizes; /***/ public String searchForSizes;
/***/ public String secondsAgo; /***/ public String secondsAgo;
@ -606,6 +663,7 @@ public static JGitText get() {
/***/ public String unencodeableFile; /***/ public String unencodeableFile;
/***/ public String unexpectedCompareResult; /***/ public String unexpectedCompareResult;
/***/ public String unexpectedEndOfConfigFile; /***/ public String unexpectedEndOfConfigFile;
/***/ public String unexpectedEndOfInput;
/***/ public String unexpectedHunkTrailer; /***/ public String unexpectedHunkTrailer;
/***/ public String unexpectedOddResult; /***/ public String unexpectedOddResult;
/***/ public String unexpectedRefReport; /***/ public String unexpectedRefReport;
@ -617,6 +675,7 @@ public static JGitText get() {
/***/ public String unknownIndexVersionOrCorruptIndex; /***/ public String unknownIndexVersionOrCorruptIndex;
/***/ public String unknownObject; /***/ public String unknownObject;
/***/ public String unknownObjectType; /***/ public String unknownObjectType;
/***/ public String unknownObjectType2;
/***/ public String unknownRepositoryFormat; /***/ public String unknownRepositoryFormat;
/***/ public String unknownRepositoryFormat2; /***/ public String unknownRepositoryFormat2;
/***/ public String unknownZlibError; /***/ public String unknownZlibError;
@ -625,16 +684,21 @@ public static JGitText get() {
/***/ public String unpackException; /***/ public String unpackException;
/***/ public String unreadablePackIndex; /***/ public String unreadablePackIndex;
/***/ public String unrecognizedRef; /***/ public String unrecognizedRef;
/***/ public String unsetMark;
/***/ public String unsupportedAlternates;
/***/ public String unsupportedArchiveFormat; /***/ public String unsupportedArchiveFormat;
/***/ public String unsupportedCommand0; /***/ public String unsupportedCommand0;
/***/ public String unsupportedEncryptionAlgorithm; /***/ public String unsupportedEncryptionAlgorithm;
/***/ public String unsupportedEncryptionVersion; /***/ public String unsupportedEncryptionVersion;
/***/ public String unsupportedGC; /***/ public String unsupportedGC;
/***/ public String unsupportedMark;
/***/ public String unsupportedOperationNotAddAtEnd; /***/ public String unsupportedOperationNotAddAtEnd;
/***/ public String unsupportedPackIndexVersion; /***/ public String unsupportedPackIndexVersion;
/***/ public String unsupportedPackVersion; /***/ public String unsupportedPackVersion;
/***/ public String updatingHeadFailed;
/***/ public String updatingReferences; /***/ public String updatingReferences;
/***/ public String updatingRefFailed; /***/ public String updatingRefFailed;
/***/ public String upstreamBranchName;
/***/ public String uriNotConfigured; /***/ public String uriNotConfigured;
/***/ public String uriNotFound; /***/ public String uriNotFound;
/***/ public String URINotSupported; /***/ public String URINotSupported;

View File

@ -230,7 +230,7 @@ public boolean pack(ProgressMonitor pm) throws IOException {
objdb.rollbackPack(newPackDesc); objdb.rollbackPack(newPackDesc);
} }
} finally { } finally {
ctx.release(); ctx.close();
} }
} }

View File

@ -216,7 +216,7 @@ public void flush() throws IOException {
} }
@Override @Override
public void release() { public void close() {
if (packOut != null) { if (packOut != null) {
try { try {
packOut.close(); packOut.close();
@ -600,8 +600,8 @@ public Set<ObjectId> getShallowCommits() throws IOException {
} }
@Override @Override
public void release() { public void close() {
ctx.release(); ctx.close();
} }
} }
@ -631,7 +631,7 @@ public ObjectStream openStream() throws IOException {
// The newly created pack is registered in the cache. // The newly created pack is registered in the cache.
return ctx.open(id, type).openStream(); return ctx.open(id, type).openStream();
} finally { } finally {
ctx.release(); ctx.close();
} }
} }
@ -642,7 +642,7 @@ size, new BufferedInputStream(new InflaterInputStream(
new ReadBackStream(pos), inf, bufsz), bufsz)) { new ReadBackStream(pos), inf, bufsz), bufsz)) {
@Override @Override
public void close() throws IOException { public void close() throws IOException {
ctx.release(); ctx.close();
super.close(); super.close();
} }
}; };

View File

@ -179,11 +179,8 @@ public DfsPackCompactor exclude(PackWriter.ObjectIdSet set) {
*/ */
public DfsPackCompactor exclude(DfsPackFile pack) throws IOException { public DfsPackCompactor exclude(DfsPackFile pack) throws IOException {
final PackIndex idx; final PackIndex idx;
DfsReader ctx = (DfsReader) repo.newObjectReader(); try (DfsReader ctx = (DfsReader) repo.newObjectReader()) {
try {
idx = pack.getPackIndex(ctx); idx = pack.getPackIndex(ctx);
} finally {
ctx.release();
} }
return exclude(new PackWriter.ObjectIdSet() { return exclude(new PackWriter.ObjectIdSet() {
public boolean contains(AnyObjectId id) { public boolean contains(AnyObjectId id) {
@ -206,8 +203,7 @@ public void compact(ProgressMonitor pm) throws IOException {
pm = NullProgressMonitor.INSTANCE; pm = NullProgressMonitor.INSTANCE;
DfsObjDatabase objdb = repo.getObjectDatabase(); DfsObjDatabase objdb = repo.getObjectDatabase();
DfsReader ctx = (DfsReader) objdb.newReader(); try (DfsReader ctx = (DfsReader) objdb.newReader()) {
try {
PackConfig pc = new PackConfig(repo); PackConfig pc = new PackConfig(repo);
pc.setIndexVersion(2); pc.setIndexVersion(2);
pc.setDeltaCompress(false); pc.setDeltaCompress(false);
@ -236,7 +232,7 @@ public void compact(ProgressMonitor pm) throws IOException {
writeIndex(objdb, pack, pw); writeIndex(objdb, pack, pw);
PackWriter.Statistics stats = pw.getStatistics(); PackWriter.Statistics stats = pw.getStatistics();
pw.release(); pw.close();
pw = null; pw = null;
pack.setPackStats(stats); pack.setPackStats(stats);
@ -250,11 +246,10 @@ public void compact(ProgressMonitor pm) throws IOException {
} }
} finally { } finally {
if (pw != null) if (pw != null)
pw.release(); pw.close();
} }
} finally { } finally {
rw = null; rw = null;
ctx.release();
} }
} }

View File

@ -61,6 +61,7 @@
import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.StoredObjectRepresentationNotAvailableException; import org.eclipse.jgit.errors.StoredObjectRepresentationNotAvailableException;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.internal.storage.file.BitmapIndexImpl; import org.eclipse.jgit.internal.storage.file.BitmapIndexImpl;
import org.eclipse.jgit.internal.storage.file.PackBitmapIndex; import org.eclipse.jgit.internal.storage.file.PackBitmapIndex;
import org.eclipse.jgit.internal.storage.file.PackIndex; import org.eclipse.jgit.internal.storage.file.PackIndex;
@ -210,7 +211,8 @@ public ObjectLoader open(AnyObjectId objectId, int typeHint)
} }
if (typeHint == OBJ_ANY) if (typeHint == OBJ_ANY)
throw new MissingObjectException(objectId.copy(), "unknown"); throw new MissingObjectException(objectId.copy(),
JGitText.get().unknownObjectType2);
throw new MissingObjectException(objectId.copy(), typeHint); throw new MissingObjectException(objectId.copy(), typeHint);
} }
@ -339,7 +341,8 @@ public ObjectId getObjectId() {
public ObjectLoader open() throws IOException { public ObjectLoader open() throws IOException {
if (cur.pack == null) if (cur.pack == null)
throw new MissingObjectException(cur.id, "unknown"); throw new MissingObjectException(cur.id,
JGitText.get().unknownObjectType2);
return cur.pack.load(DfsReader.this, cur.offset); return cur.pack.load(DfsReader.this, cur.offset);
} }
@ -376,7 +379,8 @@ public boolean next() throws MissingObjectException, IOException {
if (idItr.hasNext()) { if (idItr.hasNext()) {
cur = idItr.next(); cur = idItr.next();
if (cur.pack == null) if (cur.pack == null)
throw new MissingObjectException(cur.id, "unknown"); throw new MissingObjectException(cur.id,
JGitText.get().unknownObjectType2);
sz = cur.pack.getObjectSize(DfsReader.this, cur.offset); sz = cur.pack.getObjectSize(DfsReader.this, cur.offset);
return true; return true;
} else if (findAllError != null) { } else if (findAllError != null) {
@ -429,7 +433,8 @@ public long getObjectSize(AnyObjectId objectId, int typeHint)
} }
if (typeHint == OBJ_ANY) if (typeHint == OBJ_ANY)
throw new MissingObjectException(objectId.copy(), "unknown"); throw new MissingObjectException(objectId.copy(),
JGitText.get().unknownObjectType2);
throw new MissingObjectException(objectId.copy(), typeHint); throw new MissingObjectException(objectId.copy(), typeHint);
} }
@ -618,7 +623,7 @@ void unpin() {
/** Release the current window cursor. */ /** Release the current window cursor. */
@Override @Override
public void release() { public void close() {
last = null; last = null;
block = null; block = null;
baseCache = null; baseCache = null;

View File

@ -183,8 +183,7 @@ public Ref peel(Ref ref) throws IOException {
private Ref doPeel(final Ref leaf) throws MissingObjectException, private Ref doPeel(final Ref leaf) throws MissingObjectException,
IOException { IOException {
RevWalk rw = new RevWalk(repository); try (RevWalk rw = new RevWalk(repository)) {
try {
RevObject obj = rw.parseAny(leaf.getObjectId()); RevObject obj = rw.parseAny(leaf.getObjectId());
if (obj instanceof RevTag) { if (obj instanceof RevTag) {
return new ObjectIdRef.PeeledTag( return new ObjectIdRef.PeeledTag(
@ -198,8 +197,6 @@ private Ref doPeel(final Ref leaf) throws MissingObjectException,
leaf.getName(), leaf.getName(),
leaf.getObjectId()); leaf.getObjectId());
} }
} finally {
rw.release();
} }
} }

View File

@ -46,6 +46,7 @@
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.lib.BaseRepositoryBuilder; import org.eclipse.jgit.lib.BaseRepositoryBuilder;
/** /**
@ -141,7 +142,8 @@ public B setObjectDirectory(File objectDirectory) {
@Override @Override
public B addAlternateObjectDirectory(File other) { public B addAlternateObjectDirectory(File other) {
throw new UnsupportedOperationException("Alternates not supported"); throw new UnsupportedOperationException(
JGitText.get().unsupportedAlternates);
} }
@Override @Override

View File

@ -112,8 +112,10 @@ public ObjectStream openStream() throws MissingObjectException, IOException {
ObjectId obj = pack.getReverseIdx(ctx).findObject(objectOffset); ObjectId obj = pack.getReverseIdx(ctx).findObject(objectOffset);
return ctx.open(obj, type).openStream(); return ctx.open(obj, type).openStream();
} finally { } finally {
ctx.release(); ctx.close();
} }
} finally {
ctx.close();
} }
// Align buffer to inflater size, at a larger than default block. // Align buffer to inflater size, at a larger than default block.

View File

@ -80,6 +80,6 @@ public int read() throws IOException {
@Override @Override
public void close() { public void close() {
ctx.release(); ctx.close();
} }
} }

View File

@ -145,7 +145,7 @@ public void flush() throws IOException {
} }
@Override @Override
public void release() { public void close() {
if (deflate != null) { if (deflate != null) {
try { try {
deflate.end(); deflate.end();

View File

@ -51,6 +51,7 @@
import java.io.EOFException; import java.io.EOFException;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer; import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel.MapMode; import java.nio.channels.FileChannel.MapMode;
@ -177,6 +178,9 @@ private synchronized PackIndex idx() throws IOException {
packFile.getPath())); packFile.getPath()));
} }
loadedIdx = idx; loadedIdx = idx;
} catch (InterruptedIOException e) {
// don't invalidate the pack, we are interrupted from another thread
throw e;
} catch (IOException e) { } catch (IOException e) {
invalid = true; invalid = true;
throw e; throw e;
@ -605,22 +609,26 @@ private void doOpen() throws IOException {
length = fd.length(); length = fd.length();
onOpenPack(); onOpenPack();
} }
} catch (InterruptedIOException e) {
// don't invalidate the pack, we are interrupted from another thread
openFail(false);
throw e;
} catch (IOException ioe) { } catch (IOException ioe) {
openFail(); openFail(true);
throw ioe; throw ioe;
} catch (RuntimeException re) { } catch (RuntimeException re) {
openFail(); openFail(true);
throw re; throw re;
} catch (Error re) { } catch (Error re) {
openFail(); openFail(true);
throw re; throw re;
} }
} }
private void openFail() { private void openFail(boolean invalidate) {
activeWindows = 0; activeWindows = 0;
activeCopyRawData = 0; activeCopyRawData = 0;
invalid = true; invalid = invalidate;
doClose(); doClose();
} }

View File

@ -477,8 +477,7 @@ public Ref peel(final Ref ref) throws IOException {
private ObjectIdRef doPeel(final Ref leaf) throws MissingObjectException, private ObjectIdRef doPeel(final Ref leaf) throws MissingObjectException,
IOException { IOException {
RevWalk rw = new RevWalk(getRepository()); try (RevWalk rw = new RevWalk(getRepository())) {
try {
RevObject obj = rw.parseAny(leaf.getObjectId()); RevObject obj = rw.parseAny(leaf.getObjectId());
if (obj instanceof RevTag) { if (obj instanceof RevTag) {
return new ObjectIdRef.PeeledTag(leaf.getStorage(), leaf return new ObjectIdRef.PeeledTag(leaf.getStorage(), leaf
@ -487,8 +486,6 @@ private ObjectIdRef doPeel(final Ref leaf) throws MissingObjectException,
return new ObjectIdRef.PeeledNonTag(leaf.getStorage(), leaf return new ObjectIdRef.PeeledNonTag(leaf.getStorage(), leaf
.getName(), leaf.getObjectId()); .getName(), leaf.getObjectId());
} }
} finally {
rw.release();
} }
} }

View File

@ -96,8 +96,7 @@ protected Result doRename() throws IOException {
objId = source.getOldObjectId(); objId = source.getOldObjectId();
updateHEAD = needToUpdateHEAD(); updateHEAD = needToUpdateHEAD();
tmp = refdb.newTemporaryUpdate(); tmp = refdb.newTemporaryUpdate();
final RevWalk rw = new RevWalk(refdb.getRepository()); try (final RevWalk rw = new RevWalk(refdb.getRepository())) {
try {
// First backup the source so its never unreachable. // First backup the source so its never unreachable.
tmp.setNewObjectId(objId); tmp.setNewObjectId(objId);
tmp.setForceUpdate(true); tmp.setForceUpdate(true);
@ -178,7 +177,6 @@ protected Result doRename() throws IOException {
} catch (IOException err) { } catch (IOException err) {
FileUtils.delete(refdb.fileFor(tmp.getName())); FileUtils.delete(refdb.fileFor(tmp.getName()));
} }
rw.release();
} }
} }

View File

@ -128,11 +128,11 @@ protected Result doUpdate(final Result status) throws IOException {
private String toResultString(final Result status) { private String toResultString(final Result status) {
switch (status) { switch (status) {
case FORCED: case FORCED:
return "forced-update"; return "forced-update"; //$NON-NLS-1$
case FAST_FORWARD: case FAST_FORWARD:
return "fast forward"; return "fast forward"; //$NON-NLS-1$
case NEW: case NEW:
return "created"; return "created"; //$NON-NLS-1$
default: default:
return null; return null;
} }

View File

@ -56,6 +56,7 @@
import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.StoredObjectRepresentationNotAvailableException; import org.eclipse.jgit.errors.StoredObjectRepresentationNotAvailableException;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.internal.storage.pack.CachedPack; import org.eclipse.jgit.internal.storage.pack.CachedPack;
import org.eclipse.jgit.internal.storage.pack.ObjectReuseAsIs; import org.eclipse.jgit.internal.storage.pack.ObjectReuseAsIs;
import org.eclipse.jgit.internal.storage.pack.ObjectToPack; import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
@ -141,7 +142,8 @@ public ObjectLoader open(AnyObjectId objectId, int typeHint)
final ObjectLoader ldr = db.openObject(this, objectId); final ObjectLoader ldr = db.openObject(this, objectId);
if (ldr == null) { if (ldr == null) {
if (typeHint == OBJ_ANY) if (typeHint == OBJ_ANY)
throw new MissingObjectException(objectId.copy(), "unknown"); throw new MissingObjectException(objectId.copy(),
JGitText.get().unknownObjectType2);
throw new MissingObjectException(objectId.copy(), typeHint); throw new MissingObjectException(objectId.copy(), typeHint);
} }
if (typeHint != OBJ_ANY && ldr.getType() != typeHint) if (typeHint != OBJ_ANY && ldr.getType() != typeHint)
@ -160,7 +162,8 @@ public long getObjectSize(AnyObjectId objectId, int typeHint)
long sz = db.getObjectSize(this, objectId); long sz = db.getObjectSize(this, objectId);
if (sz < 0) { if (sz < 0) {
if (typeHint == OBJ_ANY) if (typeHint == OBJ_ANY)
throw new MissingObjectException(objectId.copy(), "unknown"); throw new MissingObjectException(objectId.copy(),
JGitText.get().unknownObjectType2);
throw new MissingObjectException(objectId.copy(), typeHint); throw new MissingObjectException(objectId.copy(), typeHint);
} }
return sz; return sz;

View File

@ -288,7 +288,7 @@ public Object call() throws Exception {
runWindow(w); runWindow(w);
} finally { } finally {
block.pm.endWorker(); block.pm.endWorker();
or.release(); or.close();
or = null; or = null;
} }
return null; return null;

View File

@ -987,7 +987,7 @@ public void writePack(ProgressMonitor compressMonitor,
} }
stats.totalBytes = out.length(); stats.totalBytes = out.length();
reader.release(); reader.close();
endPhase(writeMonitor); endPhase(writeMonitor);
} }
@ -1005,14 +1005,6 @@ public State getState() {
return state.snapshot(); return state.snapshot();
} }
/**
* Release all resources used by this writer. Use {@link #close()} instead.
*/
@Deprecated
public void release() {
close();
}
/** /**
* Release all resources used by this writer. * Release all resources used by this writer.
* *

View File

@ -48,6 +48,7 @@
package org.eclipse.jgit.lib; package org.eclipse.jgit.lib;
import java.io.IOException; import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
@ -63,6 +64,7 @@
import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.StopWalkException; import org.eclipse.jgit.errors.StopWalkException;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.submodule.SubmoduleWalk; import org.eclipse.jgit.submodule.SubmoduleWalk;
@ -400,7 +402,7 @@ public boolean diff(final ProgressMonitor monitor, int estWorkTreeSize,
throws IOException { throws IOException {
dirCache = repository.readDirCache(); dirCache = repository.readDirCache();
TreeWalk treeWalk = new TreeWalk(repository); try (TreeWalk treeWalk = new TreeWalk(repository)) {
treeWalk.setRecursive(true); treeWalk.setRecursive(true);
// add the trees (tree, dirchache, workdir) // add the trees (tree, dirchache, workdir)
if (tree != null) if (tree != null)
@ -434,8 +436,8 @@ public boolean diff(final ProgressMonitor monitor, int estWorkTreeSize,
AbstractTreeIterator.class); AbstractTreeIterator.class);
DirCacheIterator dirCacheIterator = treeWalk.getTree(INDEX, DirCacheIterator dirCacheIterator = treeWalk.getTree(INDEX,
DirCacheIterator.class); DirCacheIterator.class);
WorkingTreeIterator workingTreeIterator = treeWalk.getTree(WORKDIR, WorkingTreeIterator workingTreeIterator = treeWalk
WorkingTreeIterator.class); .getTree(WORKDIR, WorkingTreeIterator.class);
if (dirCacheIterator != null) { if (dirCacheIterator != null) {
final DirCacheEntry dirCacheEntry = dirCacheIterator final DirCacheEntry dirCacheEntry = dirCacheIterator
@ -453,8 +455,9 @@ public boolean diff(final ProgressMonitor monitor, int estWorkTreeSize,
if (treeIterator != null) { if (treeIterator != null) {
if (dirCacheIterator != null) { if (dirCacheIterator != null) {
if (!treeIterator.idEqual(dirCacheIterator) if (!treeIterator.idEqual(dirCacheIterator)
|| treeIterator.getEntryRawMode() || treeIterator
!= dirCacheIterator.getEntryRawMode()) { .getEntryRawMode() != dirCacheIterator
.getEntryRawMode()) {
// in repo, in index, content diff => changed // in repo, in index, content diff => changed
if (!isEntryGitLink(treeIterator) if (!isEntryGitLink(treeIterator)
|| !isEntryGitLink(dirCacheIterator) || !isEntryGitLink(dirCacheIterator)
@ -495,8 +498,10 @@ public boolean diff(final ProgressMonitor monitor, int estWorkTreeSize,
dirCacheIterator.getDirCacheEntry(), true, dirCacheIterator.getDirCacheEntry(), true,
treeWalk.getObjectReader())) { treeWalk.getObjectReader())) {
// in index, in workdir, content differs => modified // in index, in workdir, content differs => modified
if (!isEntryGitLink(dirCacheIterator) || !isEntryGitLink(workingTreeIterator) if (!isEntryGitLink(dirCacheIterator)
|| (ignoreSubmoduleMode != IgnoreSubmoduleMode.ALL && ignoreSubmoduleMode != IgnoreSubmoduleMode.DIRTY)) || !isEntryGitLink(workingTreeIterator)
|| (ignoreSubmoduleMode != IgnoreSubmoduleMode.ALL
&& ignoreSubmoduleMode != IgnoreSubmoduleMode.DIRTY))
modified.add(treeWalk.getPathString()); modified.add(treeWalk.getPathString());
} }
} }
@ -513,6 +518,7 @@ public boolean diff(final ProgressMonitor monitor, int estWorkTreeSize,
} }
} }
} }
}
if (ignoreSubmoduleMode != IgnoreSubmoduleMode.ALL) { if (ignoreSubmoduleMode != IgnoreSubmoduleMode.ALL) {
IgnoreSubmoduleMode localIgnoreSubmoduleMode = ignoreSubmoduleMode; IgnoreSubmoduleMode localIgnoreSubmoduleMode = ignoreSubmoduleMode;
@ -525,9 +531,9 @@ public boolean diff(final ProgressMonitor monitor, int estWorkTreeSize,
.equals(localIgnoreSubmoduleMode)) .equals(localIgnoreSubmoduleMode))
continue; continue;
} catch (ConfigInvalidException e) { } catch (ConfigInvalidException e) {
IOException e1 = new IOException( IOException e1 = new IOException(MessageFormat.format(
"Found invalid ignore param for submodule " JGitText.get().invalidIgnoreParamSubmodule,
+ smw.getPath()); smw.getPath()));
e1.initCause(e); e1.initCause(e);
throw e1; throw e1;
} }

View File

@ -254,25 +254,32 @@ public void checkCommit(final byte[] raw) throws CorruptObjectException {
int ptr = 0; int ptr = 0;
if ((ptr = match(raw, ptr, tree)) < 0) if ((ptr = match(raw, ptr, tree)) < 0)
throw new CorruptObjectException("no tree header"); throw new CorruptObjectException(
JGitText.get().corruptObjectNotreeHeader);
if ((ptr = id(raw, ptr)) < 0 || raw[ptr++] != '\n') if ((ptr = id(raw, ptr)) < 0 || raw[ptr++] != '\n')
throw new CorruptObjectException("invalid tree"); throw new CorruptObjectException(
JGitText.get().corruptObjectInvalidTree);
while (match(raw, ptr, parent) >= 0) { while (match(raw, ptr, parent) >= 0) {
ptr += parent.length; ptr += parent.length;
if ((ptr = id(raw, ptr)) < 0 || raw[ptr++] != '\n') if ((ptr = id(raw, ptr)) < 0 || raw[ptr++] != '\n')
throw new CorruptObjectException("invalid parent"); throw new CorruptObjectException(
JGitText.get().corruptObjectInvalidParent);
} }
if ((ptr = match(raw, ptr, author)) < 0) if ((ptr = match(raw, ptr, author)) < 0)
throw new CorruptObjectException("no author"); throw new CorruptObjectException(
JGitText.get().corruptObjectNoAuthor);
if ((ptr = personIdent(raw, ptr)) < 0 || raw[ptr++] != '\n') if ((ptr = personIdent(raw, ptr)) < 0 || raw[ptr++] != '\n')
throw new CorruptObjectException("invalid author"); throw new CorruptObjectException(
JGitText.get().corruptObjectInvalidAuthor);
if ((ptr = match(raw, ptr, committer)) < 0) if ((ptr = match(raw, ptr, committer)) < 0)
throw new CorruptObjectException("no committer"); throw new CorruptObjectException(
JGitText.get().corruptObjectNoCommitter);
if ((ptr = personIdent(raw, ptr)) < 0 || raw[ptr++] != '\n') if ((ptr = personIdent(raw, ptr)) < 0 || raw[ptr++] != '\n')
throw new CorruptObjectException("invalid committer"); throw new CorruptObjectException(
JGitText.get().corruptObjectInvalidCommitter);
} }
/** /**
@ -287,21 +294,26 @@ public void checkTag(final byte[] raw) throws CorruptObjectException {
int ptr = 0; int ptr = 0;
if ((ptr = match(raw, ptr, object)) < 0) if ((ptr = match(raw, ptr, object)) < 0)
throw new CorruptObjectException("no object header"); throw new CorruptObjectException(
JGitText.get().corruptObjectNoObjectHeader);
if ((ptr = id(raw, ptr)) < 0 || raw[ptr++] != '\n') if ((ptr = id(raw, ptr)) < 0 || raw[ptr++] != '\n')
throw new CorruptObjectException("invalid object"); throw new CorruptObjectException(
JGitText.get().corruptObjectInvalidObject);
if ((ptr = match(raw, ptr, type)) < 0) if ((ptr = match(raw, ptr, type)) < 0)
throw new CorruptObjectException("no type header"); throw new CorruptObjectException(
JGitText.get().corruptObjectNoTypeHeader);
ptr = nextLF(raw, ptr); ptr = nextLF(raw, ptr);
if ((ptr = match(raw, ptr, tag)) < 0) if ((ptr = match(raw, ptr, tag)) < 0)
throw new CorruptObjectException("no tag header"); throw new CorruptObjectException(
JGitText.get().corruptObjectNoTagHeader);
ptr = nextLF(raw, ptr); ptr = nextLF(raw, ptr);
if ((ptr = match(raw, ptr, tagger)) > 0) { if ((ptr = match(raw, ptr, tagger)) > 0) {
if ((ptr = personIdent(raw, ptr)) < 0 || raw[ptr++] != '\n') if ((ptr = personIdent(raw, ptr)) < 0 || raw[ptr++] != '\n')
throw new CorruptObjectException("invalid tagger"); throw new CorruptObjectException(
JGitText.get().corruptObjectInvalidTagger);
} }
} }
@ -382,37 +394,46 @@ public void checkTree(final byte[] raw) throws CorruptObjectException {
int thisMode = 0; int thisMode = 0;
for (;;) { for (;;) {
if (ptr == sz) if (ptr == sz)
throw new CorruptObjectException("truncated in mode"); throw new CorruptObjectException(
JGitText.get().corruptObjectTruncatedInMode);
final byte c = raw[ptr++]; final byte c = raw[ptr++];
if (' ' == c) if (' ' == c)
break; break;
if (c < '0' || c > '7') if (c < '0' || c > '7')
throw new CorruptObjectException("invalid mode character"); throw new CorruptObjectException(
JGitText.get().corruptObjectInvalidModeChar);
if (thisMode == 0 && c == '0' && !allowZeroMode) if (thisMode == 0 && c == '0' && !allowZeroMode)
throw new CorruptObjectException("mode starts with '0'"); throw new CorruptObjectException(
JGitText.get().corruptObjectInvalidModeStartsZero);
thisMode <<= 3; thisMode <<= 3;
thisMode += c - '0'; thisMode += c - '0';
} }
if (FileMode.fromBits(thisMode).getObjectType() == Constants.OBJ_BAD) if (FileMode.fromBits(thisMode).getObjectType() == Constants.OBJ_BAD)
throw new CorruptObjectException("invalid mode " + thisMode); throw new CorruptObjectException(MessageFormat.format(
JGitText.get().corruptObjectInvalidMode2,
Integer.valueOf(thisMode)));
final int thisNameB = ptr; final int thisNameB = ptr;
ptr = scanPathSegment(raw, ptr, sz); ptr = scanPathSegment(raw, ptr, sz);
if (ptr == sz || raw[ptr] != 0) if (ptr == sz || raw[ptr] != 0)
throw new CorruptObjectException("truncated in name"); throw new CorruptObjectException(
JGitText.get().corruptObjectTruncatedInName);
checkPathSegment2(raw, thisNameB, ptr); checkPathSegment2(raw, thisNameB, ptr);
if (normalized != null) { if (normalized != null) {
if (!normalized.add(normalize(raw, thisNameB, ptr))) if (!normalized.add(normalize(raw, thisNameB, ptr)))
throw new CorruptObjectException("duplicate entry names"); throw new CorruptObjectException(
JGitText.get().corruptObjectDuplicateEntryNames);
} else if (duplicateName(raw, thisNameB, ptr)) } else if (duplicateName(raw, thisNameB, ptr))
throw new CorruptObjectException("duplicate entry names"); throw new CorruptObjectException(
JGitText.get().corruptObjectDuplicateEntryNames);
if (lastNameB != 0) { if (lastNameB != 0) {
final int cmp = pathCompare(raw, lastNameB, lastNameE, final int cmp = pathCompare(raw, lastNameB, lastNameE,
lastMode, thisNameB, ptr, thisMode); lastMode, thisNameB, ptr, thisMode);
if (cmp > 0) if (cmp > 0)
throw new CorruptObjectException("incorrectly sorted"); throw new CorruptObjectException(
JGitText.get().corruptObjectIncorrectSorting);
} }
lastNameB = thisNameB; lastNameB = thisNameB;
@ -421,7 +442,8 @@ public void checkTree(final byte[] raw) throws CorruptObjectException {
ptr += 1 + Constants.OBJECT_ID_LENGTH; ptr += 1 + Constants.OBJECT_ID_LENGTH;
if (ptr > sz) if (ptr > sz)
throw new CorruptObjectException("truncated in object id"); throw new CorruptObjectException(
JGitText.get().corruptObjectTruncatedInObjectId);
} }
} }
@ -432,13 +454,16 @@ private int scanPathSegment(byte[] raw, int ptr, int end)
if (c == 0) if (c == 0)
return ptr; return ptr;
if (c == '/') if (c == '/')
throw new CorruptObjectException("name contains '/'"); throw new CorruptObjectException(
JGitText.get().corruptObjectNameContainsSlash);
if (windows && isInvalidOnWindows(c)) { if (windows && isInvalidOnWindows(c)) {
if (c > 31) if (c > 31)
throw new CorruptObjectException(String.format( throw new CorruptObjectException(String.format(
"name contains '%c'", c)); JGitText.get().corruptObjectNameContainsChar,
Byte.valueOf(c)));
throw new CorruptObjectException(String.format( throw new CorruptObjectException(String.format(
"name contains byte 0x%x", c & 0xff)); JGitText.get().corruptObjectNameContainsByte,
Integer.valueOf(c & 0xff)));
} }
} }
return ptr; return ptr;
@ -496,49 +521,55 @@ public void checkPathSegment(byte[] raw, int ptr, int end)
throws CorruptObjectException { throws CorruptObjectException {
int e = scanPathSegment(raw, ptr, end); int e = scanPathSegment(raw, ptr, end);
if (e < end && raw[e] == 0) if (e < end && raw[e] == 0)
throw new CorruptObjectException("name contains byte 0x00"); throw new CorruptObjectException(
JGitText.get().corruptObjectNameContainsNullByte);
checkPathSegment2(raw, ptr, end); checkPathSegment2(raw, ptr, end);
} }
private void checkPathSegment2(byte[] raw, int ptr, int end) private void checkPathSegment2(byte[] raw, int ptr, int end)
throws CorruptObjectException { throws CorruptObjectException {
if (ptr == end) if (ptr == end)
throw new CorruptObjectException("zero length name"); throw new CorruptObjectException(
JGitText.get().corruptObjectNameZeroLength);
if (raw[ptr] == '.') { if (raw[ptr] == '.') {
switch (end - ptr) { switch (end - ptr) {
case 1: case 1:
throw new CorruptObjectException("invalid name '.'"); throw new CorruptObjectException(
JGitText.get().corruptObjectNameDot);
case 2: case 2:
if (raw[ptr + 1] == '.') if (raw[ptr + 1] == '.')
throw new CorruptObjectException("invalid name '..'"); throw new CorruptObjectException(
JGitText.get().corruptObjectNameDotDot);
break; break;
case 4: case 4:
if (isGit(raw, ptr + 1)) if (isGit(raw, ptr + 1))
throw new CorruptObjectException(String.format( throw new CorruptObjectException(String.format(
"invalid name '%s'", JGitText.get().corruptObjectInvalidName,
RawParseUtils.decode(raw, ptr, end))); RawParseUtils.decode(raw, ptr, end)));
break; break;
default: default:
if (end - ptr > 4 && isNormalizedGit(raw, ptr + 1, end)) if (end - ptr > 4 && isNormalizedGit(raw, ptr + 1, end))
throw new CorruptObjectException(String.format( throw new CorruptObjectException(String.format(
"invalid name '%s'", JGitText.get().corruptObjectInvalidName,
RawParseUtils.decode(raw, ptr, end))); RawParseUtils.decode(raw, ptr, end)));
} }
} else if (isGitTilde1(raw, ptr, end)) { } else if (isGitTilde1(raw, ptr, end)) {
throw new CorruptObjectException(String.format("invalid name '%s'", throw new CorruptObjectException(String.format(
JGitText.get().corruptObjectInvalidName,
RawParseUtils.decode(raw, ptr, end))); RawParseUtils.decode(raw, ptr, end)));
} }
if (macosx && isMacHFSGit(raw, ptr, end)) if (macosx && isMacHFSGit(raw, ptr, end))
throw new CorruptObjectException(String.format( throw new CorruptObjectException(String.format(
"invalid name '%s' contains ignorable Unicode characters", JGitText.get().corruptObjectInvalidNameIgnorableUnicode,
RawParseUtils.decode(raw, ptr, end))); RawParseUtils.decode(raw, ptr, end)));
if (windows) { if (windows) {
// Windows ignores space and dot at end of file name. // Windows ignores space and dot at end of file name.
if (raw[end - 1] == ' ' || raw[end - 1] == '.') if (raw[end - 1] == ' ' || raw[end - 1] == '.')
throw new CorruptObjectException("invalid name ends with '" throw new CorruptObjectException(String.format(
+ ((char) raw[end - 1]) + "'"); JGitText.get().corruptObjectInvalidNameEnd,
Character.valueOf(((char) raw[end - 1]))));
if (end - ptr >= 3) if (end - ptr >= 3)
checkNotWindowsDevice(raw, ptr, end); checkNotWindowsDevice(raw, ptr, end);
} }
@ -615,7 +646,7 @@ private static void checkTruncatedIgnorableUTF8(byte[] raw, int ptr, int end)
throws CorruptObjectException { throws CorruptObjectException {
if ((ptr + 2) >= end) if ((ptr + 2) >= end)
throw new CorruptObjectException(MessageFormat.format( throw new CorruptObjectException(MessageFormat.format(
"invalid name contains byte sequence ''{0}'' which is not a valid UTF-8 character", JGitText.get().corruptObjectInvalidNameInvalidUtf8,
toHexString(raw, ptr, end))); toHexString(raw, ptr, end)));
} }
@ -634,7 +665,8 @@ private static void checkNotWindowsDevice(byte[] raw, int ptr, int end)
&& toLower(raw[ptr + 1]) == 'u' && toLower(raw[ptr + 1]) == 'u'
&& toLower(raw[ptr + 2]) == 'x' && toLower(raw[ptr + 2]) == 'x'
&& (end - ptr == 3 || raw[ptr + 3] == '.')) && (end - ptr == 3 || raw[ptr + 3] == '.'))
throw new CorruptObjectException("invalid name 'AUX'"); throw new CorruptObjectException(
JGitText.get().corruptObjectInvalidNameAux);
break; break;
case 'c': // CON, COM[1-9] case 'c': // CON, COM[1-9]
@ -642,14 +674,16 @@ && toLower(raw[ptr + 2]) == 'x'
&& toLower(raw[ptr + 2]) == 'n' && toLower(raw[ptr + 2]) == 'n'
&& toLower(raw[ptr + 1]) == 'o' && toLower(raw[ptr + 1]) == 'o'
&& (end - ptr == 3 || raw[ptr + 3] == '.')) && (end - ptr == 3 || raw[ptr + 3] == '.'))
throw new CorruptObjectException("invalid name 'CON'"); throw new CorruptObjectException(
JGitText.get().corruptObjectInvalidNameCon);
if (end - ptr >= 4 if (end - ptr >= 4
&& toLower(raw[ptr + 2]) == 'm' && toLower(raw[ptr + 2]) == 'm'
&& toLower(raw[ptr + 1]) == 'o' && toLower(raw[ptr + 1]) == 'o'
&& isPositiveDigit(raw[ptr + 3]) && isPositiveDigit(raw[ptr + 3])
&& (end - ptr == 4 || raw[ptr + 4] == '.')) && (end - ptr == 4 || raw[ptr + 4] == '.'))
throw new CorruptObjectException("invalid name 'COM" throw new CorruptObjectException(String.format(
+ ((char) raw[ptr + 3]) + "'"); JGitText.get().corruptObjectInvalidNameCom,
Character.valueOf(((char) raw[ptr + 3]))));
break; break;
case 'l': // LPT[1-9] case 'l': // LPT[1-9]
@ -658,8 +692,9 @@ && toLower(raw[ptr + 1]) == 'p'
&& toLower(raw[ptr + 2]) == 't' && toLower(raw[ptr + 2]) == 't'
&& isPositiveDigit(raw[ptr + 3]) && isPositiveDigit(raw[ptr + 3])
&& (end - ptr == 4 || raw[ptr + 4] == '.')) && (end - ptr == 4 || raw[ptr + 4] == '.'))
throw new CorruptObjectException("invalid name 'LPT" throw new CorruptObjectException(String.format(
+ ((char) raw[ptr + 3]) + "'"); JGitText.get().corruptObjectInvalidNameLpt,
Character.valueOf(((char) raw[ptr + 3]))));
break; break;
case 'n': // NUL case 'n': // NUL
@ -667,7 +702,8 @@ && isPositiveDigit(raw[ptr + 3])
&& toLower(raw[ptr + 1]) == 'u' && toLower(raw[ptr + 1]) == 'u'
&& toLower(raw[ptr + 2]) == 'l' && toLower(raw[ptr + 2]) == 'l'
&& (end - ptr == 3 || raw[ptr + 3] == '.')) && (end - ptr == 3 || raw[ptr + 3] == '.'))
throw new CorruptObjectException("invalid name 'NUL'"); throw new CorruptObjectException(
JGitText.get().corruptObjectInvalidNameNul);
break; break;
case 'p': // PRN case 'p': // PRN
@ -675,7 +711,8 @@ && toLower(raw[ptr + 2]) == 'l'
&& toLower(raw[ptr + 1]) == 'r' && toLower(raw[ptr + 1]) == 'r'
&& toLower(raw[ptr + 2]) == 'n' && toLower(raw[ptr + 2]) == 'n'
&& (end - ptr == 3 || raw[ptr + 3] == '.')) && (end - ptr == 3 || raw[ptr + 3] == '.'))
throw new CorruptObjectException("invalid name 'PRN'"); throw new CorruptObjectException(
JGitText.get().corruptObjectInvalidNamePrn);
break; break;
} }
} }

View File

@ -45,6 +45,7 @@
package org.eclipse.jgit.lib; package org.eclipse.jgit.lib;
import org.eclipse.jgit.errors.InvalidObjectIdException; import org.eclipse.jgit.errors.InvalidObjectIdException;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.util.NB; import org.eclipse.jgit.util.NB;
import org.eclipse.jgit.util.RawParseUtils; import org.eclipse.jgit.util.RawParseUtils;
@ -52,6 +53,7 @@
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.io.Serializable; import java.io.Serializable;
import java.text.MessageFormat;
/** /**
* A SHA-1 abstraction. * A SHA-1 abstraction.
@ -229,7 +231,8 @@ public static final ObjectId fromString(final byte[] buf, final int offset) {
*/ */
public static ObjectId fromString(final String str) { public static ObjectId fromString(final String str) {
if (str.length() != Constants.OBJECT_ID_STRING_LENGTH) if (str.length() != Constants.OBJECT_ID_STRING_LENGTH)
throw new IllegalArgumentException("Invalid id: " + str); throw new IllegalArgumentException(
MessageFormat.format(JGitText.get().invalidId, str));
return fromHexString(Constants.encodeASCII(str), 0); return fromHexString(Constants.encodeASCII(str), 0);
} }

View File

@ -52,6 +52,7 @@
import java.io.InputStream; import java.io.InputStream;
import java.security.MessageDigest; import java.security.MessageDigest;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.transport.PackParser; import org.eclipse.jgit.transport.PackParser;
/** /**
@ -63,7 +64,7 @@
* <p> * <p>
* Objects written by an inserter may not be immediately visible for reading * Objects written by an inserter may not be immediately visible for reading
* after the insert method completes. Callers must invoke either * after the insert method completes. Callers must invoke either
* {@link #release()} or {@link #flush()} prior to updating references or * {@link #close()} or {@link #flush()} prior to updating references or
* otherwise making the returned ObjectIds visible to other code. * otherwise making the returned ObjectIds visible to other code.
*/ */
public abstract class ObjectInserter implements AutoCloseable { public abstract class ObjectInserter implements AutoCloseable {
@ -91,7 +92,7 @@ public void flush() throws IOException {
} }
@Override @Override
public void release() { public void close() {
// Do nothing. // Do nothing.
} }
} }
@ -149,8 +150,8 @@ public void flush() throws IOException {
delegate().flush(); delegate().flush();
} }
public void release() { public void close() {
delegate().release(); delegate().close();
} }
} }
@ -263,7 +264,7 @@ public ObjectId idFor(int objectType, long length, InputStream in)
while (length > 0) { while (length > 0) {
int n = in.read(buf, 0, (int) Math.min(length, buf.length)); int n = in.read(buf, 0, (int) Math.min(length, buf.length));
if (n < 0) if (n < 0)
throw new EOFException("Unexpected end of input"); throw new EOFException(JGitText.get().unexpectedEndOfInput);
md.update(buf, 0, n); md.update(buf, 0, n);
length -= n; length -= n;
} }
@ -416,15 +417,6 @@ public abstract ObjectId insert(int objectType, long length, InputStream in)
*/ */
public abstract void flush() throws IOException; public abstract void flush() throws IOException;
/**
* Release any resources used by this inserter.
* <p>
* An inserter that has been released can be used again, but may need to be
* released after the subsequent usage. Use {@link #close()} instead
*/
@Deprecated
public abstract void release();
/** /**
* Release any resources used by this inserter. * Release any resources used by this inserter.
* <p> * <p>
@ -434,7 +426,5 @@ public abstract ObjectId insert(int objectType, long length, InputStream in)
* @since 4.0 * @since 4.0
*/ */
@Override @Override
public void close() { public abstract void close();
release();
}
} }

Some files were not shown because too many files have changed in this diff Show More