Merge branch 'stable-4.2'

* stable-4.2:
  DirCacheCheckoutTest: Open Git and TreeWalk in try-with-resource
  CommitCommand: Remove declaration of unthrown exception
  Branch: Fix variable hiding warning
  ApplyCommandTest: Open Git in try-with-resource
  PackFileTest: Open ObjectInserter.Formatter in try-with-resource

Change-Id: I8484b10fad5a4c35fcfaedc1cdf8ccf97471618e
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
This commit is contained in:
Matthias Sohn 2016-02-03 10:30:38 +01:00
commit b0facdc113
5 changed files with 220 additions and 213 deletions

View File

@ -310,24 +310,24 @@ private void delete(List<String> branches, boolean force)
throws IOException { throws IOException {
String current = db.getBranch(); String current = db.getBranch();
ObjectId head = db.resolve(Constants.HEAD); ObjectId head = db.resolve(Constants.HEAD);
for (String branch : branches) { for (String b : branches) {
if (branch.equals(current)) { if (b.equals(current)) {
throw die(MessageFormat.format(CLIText.get().cannotDeleteTheBranchWhichYouAreCurrentlyOn, branch)); throw die(MessageFormat.format(CLIText.get().cannotDeleteTheBranchWhichYouAreCurrentlyOn, b));
} }
RefUpdate update = db.updateRef((remote ? Constants.R_REMOTES RefUpdate update = db.updateRef((remote ? Constants.R_REMOTES
: Constants.R_HEADS) : Constants.R_HEADS)
+ branch); + b);
update.setNewObjectId(head); update.setNewObjectId(head);
update.setForceUpdate(force || remote); update.setForceUpdate(force || remote);
Result result = update.delete(); Result result = update.delete();
if (result == Result.REJECTED) { if (result == Result.REJECTED) {
throw die(MessageFormat.format(CLIText.get().branchIsNotAnAncestorOfYourCurrentHEAD, branch)); throw die(MessageFormat.format(CLIText.get().branchIsNotAnAncestorOfYourCurrentHEAD, b));
} else if (result == Result.NEW) } else if (result == Result.NEW)
throw die(MessageFormat.format(CLIText.get().branchNotFound, branch)); throw die(MessageFormat.format(CLIText.get().branchNotFound, b));
if (remote) if (remote)
outw.println(MessageFormat.format(CLIText.get().deletedRemoteBranch, branch)); outw.println(MessageFormat.format(CLIText.get().deletedRemoteBranch, b));
else if (verbose) else if (verbose)
outw.println(MessageFormat.format(CLIText.get().deletedBranch, branch)); outw.println(MessageFormat.format(CLIText.get().deletedBranch, b));
} }
} }
} }

View File

@ -69,23 +69,24 @@ private ApplyResult init(final String name) throws Exception {
private ApplyResult init(final String name, final boolean preExists, private ApplyResult init(final String name, final boolean preExists,
final boolean postExists) throws Exception { final boolean postExists) throws Exception {
Git git = new Git(db); try (Git git = new Git(db)) {
if (preExists) {
a = new RawText(readFile(name + "_PreImage"));
write(new File(db.getDirectory().getParent(), name),
a.getString(0, a.size(), false));
if (preExists) { git.add().addFilepattern(name).call();
a = new RawText(readFile(name + "_PreImage")); git.commit().setMessage("PreImage").call();
write(new File(db.getDirectory().getParent(), name), }
a.getString(0, a.size(), false));
git.add().addFilepattern(name).call(); if (postExists) {
git.commit().setMessage("PreImage").call(); b = new RawText(readFile(name + "_PostImage"));
}
return git
.apply()
.setPatch(getTestResource(name + ".patch")).call();
} }
if (postExists)
b = new RawText(readFile(name + "_PostImage"));
return git
.apply()
.setPatch(getTestResource(name + ".patch")).call();
} }
@Test @Test

View File

@ -191,119 +191,122 @@ public void testWhole_LargeObject() throws Exception {
@Test @Test
public void testDelta_SmallObjectChain() throws Exception { public void testDelta_SmallObjectChain() throws Exception {
ObjectInserter.Formatter fmt = new ObjectInserter.Formatter(); try (ObjectInserter.Formatter fmt = new ObjectInserter.Formatter()) {
byte[] data0 = new byte[512]; byte[] data0 = new byte[512];
Arrays.fill(data0, (byte) 0xf3); Arrays.fill(data0, (byte) 0xf3);
ObjectId id0 = fmt.idFor(Constants.OBJ_BLOB, data0); ObjectId id0 = fmt.idFor(Constants.OBJ_BLOB, data0);
TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(64 * 1024); TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(64 * 1024);
packHeader(pack, 4); packHeader(pack, 4);
objectHeader(pack, Constants.OBJ_BLOB, data0.length); objectHeader(pack, Constants.OBJ_BLOB, data0.length);
deflate(pack, data0); deflate(pack, data0);
byte[] data1 = clone(0x01, data0); byte[] data1 = clone(0x01, data0);
byte[] delta1 = delta(data0, data1); byte[] delta1 = delta(data0, data1);
ObjectId id1 = fmt.idFor(Constants.OBJ_BLOB, data1); ObjectId id1 = fmt.idFor(Constants.OBJ_BLOB, data1);
objectHeader(pack, Constants.OBJ_REF_DELTA, delta1.length); objectHeader(pack, Constants.OBJ_REF_DELTA, delta1.length);
id0.copyRawTo(pack); id0.copyRawTo(pack);
deflate(pack, delta1); deflate(pack, delta1);
byte[] data2 = clone(0x02, data1); byte[] data2 = clone(0x02, data1);
byte[] delta2 = delta(data1, data2); byte[] delta2 = delta(data1, data2);
ObjectId id2 = fmt.idFor(Constants.OBJ_BLOB, data2); ObjectId id2 = fmt.idFor(Constants.OBJ_BLOB, data2);
objectHeader(pack, Constants.OBJ_REF_DELTA, delta2.length); objectHeader(pack, Constants.OBJ_REF_DELTA, delta2.length);
id1.copyRawTo(pack); id1.copyRawTo(pack);
deflate(pack, delta2); deflate(pack, delta2);
byte[] data3 = clone(0x03, data2); byte[] data3 = clone(0x03, data2);
byte[] delta3 = delta(data2, data3); byte[] delta3 = delta(data2, data3);
ObjectId id3 = fmt.idFor(Constants.OBJ_BLOB, data3); ObjectId id3 = fmt.idFor(Constants.OBJ_BLOB, data3);
objectHeader(pack, Constants.OBJ_REF_DELTA, delta3.length); objectHeader(pack, Constants.OBJ_REF_DELTA, delta3.length);
id2.copyRawTo(pack); id2.copyRawTo(pack);
deflate(pack, delta3); deflate(pack, delta3);
digest(pack); digest(pack);
PackParser ip = index(pack.toByteArray()); PackParser ip = index(pack.toByteArray());
ip.setAllowThin(true); ip.setAllowThin(true);
ip.parse(NullProgressMonitor.INSTANCE); ip.parse(NullProgressMonitor.INSTANCE);
assertTrue("has blob", wc.has(id3)); assertTrue("has blob", wc.has(id3));
ObjectLoader ol = wc.open(id3); ObjectLoader ol = wc.open(id3);
assertNotNull("created loader", ol); assertNotNull("created loader", ol);
assertEquals(Constants.OBJ_BLOB, ol.getType()); assertEquals(Constants.OBJ_BLOB, ol.getType());
assertEquals(data3.length, ol.getSize()); assertEquals(data3.length, ol.getSize());
assertFalse("is large", ol.isLarge()); assertFalse("is large", ol.isLarge());
assertNotNull(ol.getCachedBytes()); assertNotNull(ol.getCachedBytes());
assertArrayEquals(data3, ol.getCachedBytes()); assertArrayEquals(data3, ol.getCachedBytes());
ObjectStream in = ol.openStream(); ObjectStream in = ol.openStream();
assertNotNull("have stream", in); assertNotNull("have stream", in);
assertEquals(Constants.OBJ_BLOB, in.getType()); assertEquals(Constants.OBJ_BLOB, in.getType());
assertEquals(data3.length, in.getSize()); assertEquals(data3.length, in.getSize());
byte[] act = new byte[data3.length]; byte[] act = new byte[data3.length];
IO.readFully(in, act, 0, data3.length); IO.readFully(in, act, 0, data3.length);
assertTrue("same content", Arrays.equals(act, data3)); assertTrue("same content", Arrays.equals(act, data3));
assertEquals("stream at EOF", -1, in.read()); assertEquals("stream at EOF", -1, in.read());
in.close(); in.close();
}
} }
@Test @Test
public void testDelta_FailsOver2GiB() throws Exception { public void testDelta_FailsOver2GiB() throws Exception {
ObjectInserter.Formatter fmt = new ObjectInserter.Formatter(); try (ObjectInserter.Formatter fmt = new ObjectInserter.Formatter()) {
byte[] base = new byte[] { 'a' }; byte[] base = new byte[] { 'a' };
ObjectId idA = fmt.idFor(Constants.OBJ_BLOB, base); ObjectId idA = fmt.idFor(Constants.OBJ_BLOB, base);
ObjectId idB = fmt.idFor(Constants.OBJ_BLOB, new byte[] { 'b' }); ObjectId idB = fmt.idFor(Constants.OBJ_BLOB, new byte[] { 'b' });
PackedObjectInfo a = new PackedObjectInfo(idA); PackedObjectInfo a = new PackedObjectInfo(idA);
PackedObjectInfo b = new PackedObjectInfo(idB); PackedObjectInfo b = new PackedObjectInfo(idB);
TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(64 * 1024); TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(64 * 1024);
packHeader(pack, 2); packHeader(pack, 2);
a.setOffset(pack.length()); a.setOffset(pack.length());
objectHeader(pack, Constants.OBJ_BLOB, base.length); objectHeader(pack, Constants.OBJ_BLOB, base.length);
deflate(pack, base); deflate(pack, base);
ByteArrayOutputStream tmp = new ByteArrayOutputStream(); ByteArrayOutputStream tmp = new ByteArrayOutputStream();
DeltaEncoder de = new DeltaEncoder(tmp, base.length, 3L << 30); DeltaEncoder de = new DeltaEncoder(tmp, base.length, 3L << 30);
de.copy(0, 1); de.copy(0, 1);
byte[] delta = tmp.toByteArray(); byte[] delta = tmp.toByteArray();
b.setOffset(pack.length()); b.setOffset(pack.length());
objectHeader(pack, Constants.OBJ_REF_DELTA, delta.length); objectHeader(pack, Constants.OBJ_REF_DELTA, delta.length);
idA.copyRawTo(pack); idA.copyRawTo(pack);
deflate(pack, delta); deflate(pack, delta);
byte[] footer = digest(pack); byte[] footer = digest(pack);
File dir = new File(repo.getObjectDatabase().getDirectory(), "pack"); File dir = new File(repo.getObjectDatabase().getDirectory(),
File packName = new File(dir, idA.name() + ".pack"); "pack");
File idxName = new File(dir, idA.name() + ".idx"); File packName = new File(dir, idA.name() + ".pack");
File idxName = new File(dir, idA.name() + ".idx");
FileOutputStream f = new FileOutputStream(packName); FileOutputStream f = new FileOutputStream(packName);
try { try {
f.write(pack.toByteArray()); f.write(pack.toByteArray());
} finally { } finally {
f.close(); f.close();
} }
f = new FileOutputStream(idxName); f = new FileOutputStream(idxName);
try { try {
List<PackedObjectInfo> list = new ArrayList<PackedObjectInfo>(); List<PackedObjectInfo> list = new ArrayList<PackedObjectInfo>();
list.add(a); list.add(a);
list.add(b); list.add(b);
Collections.sort(list); Collections.sort(list);
new PackIndexWriterV1(f).write(list, footer); new PackIndexWriterV1(f).write(list, footer);
} finally { } finally {
f.close(); f.close();
} }
PackFile packFile = new PackFile(packName, PackExt.INDEX.getBit()); PackFile packFile = new PackFile(packName, PackExt.INDEX.getBit());
try { try {
packFile.get(wc, b); packFile.get(wc, b);
fail("expected LargeObjectException.ExceedsByteArrayLimit"); fail("expected LargeObjectException.ExceedsByteArrayLimit");
} catch (LargeObjectException.ExceedsByteArrayLimit bad) { } catch (LargeObjectException.ExceedsByteArrayLimit bad) {
assertNull(bad.getObjectId()); assertNull(bad.getObjectId());
} finally { } finally {
packFile.close(); packFile.close();
}
} }
} }

View File

@ -140,52 +140,53 @@ private static HashMap<String, String> mkmap(String... args) {
@Test @Test
public void testResetHard() throws IOException, NoFilepatternException, public void testResetHard() throws IOException, NoFilepatternException,
GitAPIException { GitAPIException {
Git git = new Git(db); try (Git git = new Git(db)) {
writeTrashFile("f", "f()"); writeTrashFile("f", "f()");
writeTrashFile("D/g", "g()"); writeTrashFile("D/g", "g()");
git.add().addFilepattern(".").call(); git.add().addFilepattern(".").call();
git.commit().setMessage("inital").call(); git.commit().setMessage("inital").call();
assertIndex(mkmap("f", "f()", "D/g", "g()")); assertIndex(mkmap("f", "f()", "D/g", "g()"));
git.branchCreate().setName("topic").call(); git.branchCreate().setName("topic").call();
writeTrashFile("f", "f()\nmaster"); writeTrashFile("f", "f()\nmaster");
writeTrashFile("D/g", "g()\ng2()"); writeTrashFile("D/g", "g()\ng2()");
writeTrashFile("E/h", "h()"); writeTrashFile("E/h", "h()");
git.add().addFilepattern(".").call(); git.add().addFilepattern(".").call();
RevCommit master = git.commit().setMessage("master-1").call(); RevCommit master = git.commit().setMessage("master-1").call();
assertIndex(mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", "h()")); assertIndex(mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", "h()"));
checkoutBranch("refs/heads/topic"); checkoutBranch("refs/heads/topic");
assertIndex(mkmap("f", "f()", "D/g", "g()")); assertIndex(mkmap("f", "f()", "D/g", "g()"));
writeTrashFile("f", "f()\nside"); writeTrashFile("f", "f()\nside");
assertTrue(new File(db.getWorkTree(), "D/g").delete()); assertTrue(new File(db.getWorkTree(), "D/g").delete());
writeTrashFile("G/i", "i()"); writeTrashFile("G/i", "i()");
git.add().addFilepattern(".").call(); git.add().addFilepattern(".").call();
git.add().addFilepattern(".").setUpdate(true).call(); git.add().addFilepattern(".").setUpdate(true).call();
RevCommit topic = git.commit().setMessage("topic-1").call(); RevCommit topic = git.commit().setMessage("topic-1").call();
assertIndex(mkmap("f", "f()\nside", "G/i", "i()")); assertIndex(mkmap("f", "f()\nside", "G/i", "i()"));
writeTrashFile("untracked", "untracked"); writeTrashFile("untracked", "untracked");
resetHard(master); resetHard(master);
assertIndex(mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", "h()")); assertIndex(mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", "h()"));
resetHard(topic); resetHard(topic);
assertIndex(mkmap("f", "f()\nside", "G/i", "i()")); assertIndex(mkmap("f", "f()\nside", "G/i", "i()"));
assertWorkDir(mkmap("f", "f()\nside", "G/i", "i()", "untracked", assertWorkDir(mkmap("f", "f()\nside", "G/i", "i()", "untracked",
"untracked")); "untracked"));
assertEquals(MergeStatus.CONFLICTING, git.merge().include(master) assertEquals(MergeStatus.CONFLICTING, git.merge().include(master)
.call().getMergeStatus()); .call().getMergeStatus());
assertEquals( assertEquals(
"[D/g, mode:100644, stage:1][D/g, mode:100644, stage:3][E/h, mode:100644][G/i, mode:100644][f, mode:100644, stage:1][f, mode:100644, stage:2][f, mode:100644, stage:3]", "[D/g, mode:100644, stage:1][D/g, mode:100644, stage:3][E/h, mode:100644][G/i, mode:100644][f, mode:100644, stage:1][f, mode:100644, stage:2][f, mode:100644, stage:3]",
indexState(0)); indexState(0));
resetHard(master); resetHard(master);
assertIndex(mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", "h()")); assertIndex(mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", "h()"));
assertWorkDir(mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", assertWorkDir(mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h",
"h()", "untracked", "untracked")); "h()", "untracked", "untracked"));
}
} }
/** /**
@ -200,21 +201,22 @@ public void testResetHard() throws IOException, NoFilepatternException,
@Test @Test
public void testResetHardFromIndexEntryWithoutFileToTreeWithoutFile() public void testResetHardFromIndexEntryWithoutFileToTreeWithoutFile()
throws Exception { throws Exception {
Git git = new Git(db); try (Git git = new Git(db)) {
writeTrashFile("x", "x"); writeTrashFile("x", "x");
git.add().addFilepattern("x").call(); git.add().addFilepattern("x").call();
RevCommit id1 = git.commit().setMessage("c1").call(); RevCommit id1 = git.commit().setMessage("c1").call();
writeTrashFile("f/g", "f/g"); writeTrashFile("f/g", "f/g");
git.rm().addFilepattern("x").call(); git.rm().addFilepattern("x").call();
git.add().addFilepattern("f/g").call(); git.add().addFilepattern("f/g").call();
git.commit().setMessage("c2").call(); git.commit().setMessage("c2").call();
deleteTrashFile("f/g"); deleteTrashFile("f/g");
deleteTrashFile("f"); deleteTrashFile("f");
// The actual test // The actual test
git.reset().setMode(ResetType.HARD).setRef(id1.getName()).call(); git.reset().setMode(ResetType.HARD).setRef(id1.getName()).call();
assertIndex(mkmap("x", "x")); assertIndex(mkmap("x", "x"));
}
} }
/** /**
@ -224,14 +226,14 @@ public void testResetHardFromIndexEntryWithoutFileToTreeWithoutFile()
*/ */
@Test @Test
public void testInitialCheckout() throws Exception { public void testInitialCheckout() throws Exception {
Git git = new Git(db); try (Git git = new Git(db)) {
TestRepository<Repository> db_t = new TestRepository<Repository>(db);
TestRepository<Repository> db_t = new TestRepository<Repository>(db); BranchBuilder master = db_t.branch("master");
BranchBuilder master = db_t.branch("master"); master.commit().add("f", "1").message("m0").create();
master.commit().add("f", "1").message("m0").create(); assertFalse(new File(db.getWorkTree(), "f").exists());
assertFalse(new File(db.getWorkTree(), "f").exists()); git.checkout().setName("master").call();
git.checkout().setName("master").call(); assertTrue(new File(db.getWorkTree(), "f").exists());
assertTrue(new File(db.getWorkTree(), "f").exists()); }
} }
private DirCacheCheckout resetHard(RevCommit commit) private DirCacheCheckout resetHard(RevCommit commit)
@ -1612,46 +1614,47 @@ public void testFileModeChangeAndContentChangeNoConflict() throws Exception {
public void assertWorkDir(Map<String, String> i) public void assertWorkDir(Map<String, String> i)
throws CorruptObjectException, throws CorruptObjectException,
IOException { IOException {
TreeWalk walk = new TreeWalk(db); try (TreeWalk walk = new TreeWalk(db)) {
walk.setRecursive(false); walk.setRecursive(false);
walk.addTree(new FileTreeIterator(db)); walk.addTree(new FileTreeIterator(db));
String expectedValue; String expectedValue;
String path; String path;
int nrFiles = 0; int nrFiles = 0;
FileTreeIterator ft; FileTreeIterator ft;
while (walk.next()) { while (walk.next()) {
ft = walk.getTree(0, FileTreeIterator.class); ft = walk.getTree(0, FileTreeIterator.class);
path = ft.getEntryPathString(); path = ft.getEntryPathString();
expectedValue = i.get(path); expectedValue = i.get(path);
File file = new File(db.getWorkTree(), path); File file = new File(db.getWorkTree(), path);
assertTrue(file.exists()); assertTrue(file.exists());
if (file.isFile()) { if (file.isFile()) {
assertNotNull("found unexpected file for path " + path assertNotNull("found unexpected file for path " + path
+ " in workdir", expectedValue); + " in workdir", expectedValue);
FileInputStream is = new FileInputStream(file); FileInputStream is = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()]; byte[] buffer = new byte[(int) file.length()];
int offset = 0; int offset = 0;
int numRead = 0; int numRead = 0;
while (offset < buffer.length while (offset < buffer.length
&& (numRead = is.read(buffer, offset, buffer.length && (numRead = is.read(buffer, offset, buffer.length
- offset)) >= 0) { - offset)) >= 0) {
offset += numRead; offset += numRead;
} }
is.close(); is.close();
assertArrayEquals("unexpected content for path " + path assertArrayEquals("unexpected content for path " + path
+ " in workDir. ", buffer, i.get(path).getBytes()); + " in workDir. ", buffer, i.get(path).getBytes());
nrFiles++;
} else if (file.isDirectory()) {
if (file.list().length == 0) {
assertEquals("found unexpected empty folder for path "
+ path + " in workDir. ", "/", i.get(path));
nrFiles++; nrFiles++;
} else if (file.isDirectory()) {
if (file.list().length == 0) {
assertEquals("found unexpected empty folder for path "
+ path + " in workDir. ", "/", i.get(path));
nrFiles++;
}
}
if (walk.isSubtree()) {
walk.enterSubtree();
} }
} }
if (walk.isSubtree()) { assertEquals("WorkDir has not the right size.", i.size(), nrFiles);
walk.enterSubtree();
}
} }
assertEquals("WorkDir has not the right size.", i.size(), nrFiles);
} }
} }

View File

@ -312,7 +312,7 @@ public RevCommit call() throws GitAPIException, NoHeadException,
} }
} }
private void insertChangeId(ObjectId treeId) throws IOException { private void insertChangeId(ObjectId treeId) {
ObjectId firstParentId = null; ObjectId firstParentId = null;
if (!parents.isEmpty()) if (!parents.isEmpty())
firstParentId = parents.get(0); firstParentId = parents.get(0);