diff options
Diffstat (limited to 'org.eclipse.jgit.test')
49 files changed, 2027 insertions, 979 deletions
diff --git a/org.eclipse.jgit.test/BUILD b/org.eclipse.jgit.test/BUILD index 95586e246e..2d2f760c26 100644 --- a/org.eclipse.jgit.test/BUILD +++ b/org.eclipse.jgit.test/BUILD @@ -1,8 +1,8 @@ -load(":tests.bzl", "tests") load( "@com_googlesource_gerrit_bazlets//tools:genrule2.bzl", "genrule2", ) +load(":tests.bzl", "tests") PKG = "tst/org/eclipse/jgit/" diff --git a/org.eclipse.jgit.test/META-INF/MANIFEST.MF b/org.eclipse.jgit.test/META-INF/MANIFEST.MF index e0d4ddaa5b..5533304913 100644 --- a/org.eclipse.jgit.test/META-INF/MANIFEST.MF +++ b/org.eclipse.jgit.test/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Bundle-ManifestVersion: 2 Bundle-Name: %plugin_name Automatic-Module-Name: org.eclipse.jgit.test Bundle-SymbolicName: org.eclipse.jgit.test -Bundle-Version: 5.2.3.qualifier +Bundle-Version: 5.3.3.qualifier Bundle-Localization: plugin Bundle-Vendor: %provider_name Bundle-ActivationPolicy: lazy @@ -17,56 +17,57 @@ Import-Package: com.googlecode.javaewah;version="[1.1.6,2.0.0)", org.apache.commons.compress.compressors.bzip2;version="[1.15.0,2.0)", org.apache.commons.compress.compressors.gzip;version="[1.15.0,2.0)", org.apache.commons.compress.compressors.xz;version="[1.15.0,2.0)", - org.eclipse.jgit.annotations;version="[5.2.3,5.3.0)", - org.eclipse.jgit.api;version="[5.2.3,5.3.0)", - org.eclipse.jgit.api.errors;version="[5.2.3,5.3.0)", - org.eclipse.jgit.archive;version="[5.2.3,5.3.0)", - org.eclipse.jgit.attributes;version="[5.2.3,5.3.0)", - org.eclipse.jgit.awtui;version="[5.2.3,5.3.0)", - org.eclipse.jgit.blame;version="[5.2.3,5.3.0)", - org.eclipse.jgit.diff;version="[5.2.3,5.3.0)", - org.eclipse.jgit.dircache;version="[5.2.3,5.3.0)", - org.eclipse.jgit.errors;version="[5.2.3,5.3.0)", - org.eclipse.jgit.events;version="[5.2.3,5.3.0)", - org.eclipse.jgit.fnmatch;version="[5.2.3,5.3.0)", - org.eclipse.jgit.gitrepo;version="[5.2.3,5.3.0)", - org.eclipse.jgit.hooks;version="[5.2.3,5.3.0)", - org.eclipse.jgit.ignore;version="[5.2.3,5.3.0)", - org.eclipse.jgit.ignore.internal;version="[5.2.3,5.3.0)", - org.eclipse.jgit.internal;version="[5.2.3,5.3.0)", - org.eclipse.jgit.internal.fsck;version="[5.2.3,5.3.0)", - org.eclipse.jgit.internal.storage.dfs;version="[5.2.3,5.3.0)", - org.eclipse.jgit.internal.storage.file;version="[5.2.3,5.3.0)", - org.eclipse.jgit.internal.storage.io;version="[5.2.3,5.3.0)", - org.eclipse.jgit.internal.storage.pack;version="[5.2.3,5.3.0)", - org.eclipse.jgit.internal.storage.reftable;version="[5.2.3,5.3.0)", - org.eclipse.jgit.internal.storage.reftree;version="[5.2.3,5.3.0)", - org.eclipse.jgit.internal.transport.parser;version="[5.2.3,5.3.0)", - org.eclipse.jgit.junit;version="[5.2.3,5.3.0)", - org.eclipse.jgit.junit.ssh;version="[5.2.3,5.3.0)", - org.eclipse.jgit.junit.time;version="[5.2.3,5.3.0)", - org.eclipse.jgit.lfs;version="[5.2.3,5.3.0)", - org.eclipse.jgit.lib;version="[5.2.3,5.3.0)", - org.eclipse.jgit.merge;version="[5.2.3,5.3.0)", - org.eclipse.jgit.nls;version="[5.2.3,5.3.0)", - org.eclipse.jgit.notes;version="[5.2.3,5.3.0)", - org.eclipse.jgit.patch;version="[5.2.3,5.3.0)", - org.eclipse.jgit.pgm;version="[5.2.3,5.3.0)", - org.eclipse.jgit.pgm.internal;version="[5.2.3,5.3.0)", - org.eclipse.jgit.revplot;version="[5.2.3,5.3.0)", - org.eclipse.jgit.revwalk;version="[5.2.3,5.3.0)", - org.eclipse.jgit.revwalk.filter;version="[5.2.3,5.3.0)", - org.eclipse.jgit.storage.file;version="[5.2.3,5.3.0)", - org.eclipse.jgit.storage.pack;version="[5.2.3,5.3.0)", - org.eclipse.jgit.submodule;version="[5.2.3,5.3.0)", - org.eclipse.jgit.transport;version="[5.2.3,5.3.0)", - org.eclipse.jgit.transport.http;version="[5.2.3,5.3.0)", - org.eclipse.jgit.transport.resolver;version="[5.2.3,5.3.0)", - org.eclipse.jgit.treewalk;version="[5.2.3,5.3.0)", - org.eclipse.jgit.treewalk.filter;version="[5.2.3,5.3.0)", - org.eclipse.jgit.util;version="[5.2.3,5.3.0)", - org.eclipse.jgit.util.io;version="[5.2.3,5.3.0)", - org.eclipse.jgit.util.sha1;version="[5.2.3,5.3.0)", + org.bouncycastle.util.encoders;version="[1.60.0,2.0.0)", + org.eclipse.jgit.annotations;version="[5.3.3,5.4.0)", + org.eclipse.jgit.api;version="[5.3.3,5.4.0)", + org.eclipse.jgit.api.errors;version="[5.3.3,5.4.0)", + org.eclipse.jgit.archive;version="[5.3.3,5.4.0)", + org.eclipse.jgit.attributes;version="[5.3.3,5.4.0)", + org.eclipse.jgit.awtui;version="[5.3.3,5.4.0)", + org.eclipse.jgit.blame;version="[5.3.3,5.4.0)", + org.eclipse.jgit.diff;version="[5.3.3,5.4.0)", + org.eclipse.jgit.dircache;version="[5.3.3,5.4.0)", + org.eclipse.jgit.errors;version="[5.3.3,5.4.0)", + org.eclipse.jgit.events;version="[5.3.3,5.4.0)", + org.eclipse.jgit.fnmatch;version="[5.3.3,5.4.0)", + org.eclipse.jgit.gitrepo;version="[5.3.3,5.4.0)", + org.eclipse.jgit.hooks;version="[5.3.3,5.4.0)", + org.eclipse.jgit.ignore;version="[5.3.3,5.4.0)", + org.eclipse.jgit.ignore.internal;version="[5.3.3,5.4.0)", + org.eclipse.jgit.internal;version="[5.3.3,5.4.0)", + org.eclipse.jgit.internal.fsck;version="[5.3.3,5.4.0)", + org.eclipse.jgit.internal.storage.dfs;version="[5.3.3,5.4.0)", + org.eclipse.jgit.internal.storage.file;version="[5.3.3,5.4.0)", + org.eclipse.jgit.internal.storage.io;version="[5.3.3,5.4.0)", + org.eclipse.jgit.internal.storage.pack;version="[5.3.3,5.4.0)", + org.eclipse.jgit.internal.storage.reftable;version="[5.3.3,5.4.0)", + org.eclipse.jgit.internal.storage.reftree;version="[5.3.3,5.4.0)", + org.eclipse.jgit.internal.transport.parser;version="[5.3.3,5.4.0)", + org.eclipse.jgit.junit;version="[5.3.3,5.4.0)", + org.eclipse.jgit.junit.ssh;version="[5.3.3,5.4.0)", + org.eclipse.jgit.junit.time;version="[5.3.3,5.4.0)", + org.eclipse.jgit.lfs;version="[5.3.3,5.4.0)", + org.eclipse.jgit.lib;version="[5.3.3,5.4.0)", + org.eclipse.jgit.merge;version="[5.3.3,5.4.0)", + org.eclipse.jgit.nls;version="[5.3.3,5.4.0)", + org.eclipse.jgit.notes;version="[5.3.3,5.4.0)", + org.eclipse.jgit.patch;version="[5.3.3,5.4.0)", + org.eclipse.jgit.pgm;version="[5.3.3,5.4.0)", + org.eclipse.jgit.pgm.internal;version="[5.3.3,5.4.0)", + org.eclipse.jgit.revplot;version="[5.3.3,5.4.0)", + org.eclipse.jgit.revwalk;version="[5.3.3,5.4.0)", + org.eclipse.jgit.revwalk.filter;version="[5.3.3,5.4.0)", + org.eclipse.jgit.storage.file;version="[5.3.3,5.4.0)", + org.eclipse.jgit.storage.pack;version="[5.3.3,5.4.0)", + org.eclipse.jgit.submodule;version="[5.3.3,5.4.0)", + org.eclipse.jgit.transport;version="[5.3.3,5.4.0)", + org.eclipse.jgit.transport.http;version="[5.3.3,5.4.0)", + org.eclipse.jgit.transport.resolver;version="[5.3.3,5.4.0)", + org.eclipse.jgit.treewalk;version="[5.3.3,5.4.0)", + org.eclipse.jgit.treewalk.filter;version="[5.3.3,5.4.0)", + org.eclipse.jgit.util;version="[5.3.3,5.4.0)", + org.eclipse.jgit.util.io;version="[5.3.3,5.4.0)", + org.eclipse.jgit.util.sha1;version="[5.3.3,5.4.0)", org.junit;version="[4.12,5.0.0)", org.junit.experimental.theories;version="[4.12,5.0.0)", org.junit.rules;version="[4.12,5.0.0)", @@ -81,4 +82,4 @@ Import-Package: com.googlecode.javaewah;version="[1.1.6,2.0.0)", org.tukaani.xz;version="[1.6.0,2.0)" Require-Bundle: org.hamcrest.core;bundle-version="[1.1.0,2.0.0)", org.hamcrest.library;bundle-version="[1.1.0,2.0.0)" -Export-Package: org.eclipse.jgit.transport.ssh;version="5.2.3";x-friends:="org.eclipse.jgit.ssh.apache.test" +Export-Package: org.eclipse.jgit.transport.ssh;version="5.3.3";x-friends:="org.eclipse.jgit.ssh.apache.test" diff --git a/org.eclipse.jgit.test/pom.xml b/org.eclipse.jgit.test/pom.xml index 149663f64e..9f66d7ed73 100644 --- a/org.eclipse.jgit.test/pom.xml +++ b/org.eclipse.jgit.test/pom.xml @@ -52,7 +52,7 @@ <parent> <groupId>org.eclipse.jgit</groupId> <artifactId>org.eclipse.jgit-parent</artifactId> - <version>5.2.3-SNAPSHOT</version> + <version>5.3.3-SNAPSHOT</version> </parent> <artifactId>org.eclipse.jgit.test</artifactId> @@ -76,11 +76,22 @@ <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> - <version>1.59</version> <scope>test</scope> </dependency> <dependency> + <groupId>org.bouncycastle</groupId> + <artifactId>bcpg-jdk15on</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.bouncycastle</groupId> + <artifactId>bcpkix-jdk15on</artifactId> + <scope>test</scope> + </dependency> + + <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <scope>test</scope> @@ -141,7 +152,7 @@ <artifactId>maven-surefire-plugin</artifactId> <version>${maven-surefire-plugin-version}</version> <configuration> - <argLine>-Djgit.test.long=true</argLine> + <argLine>@{argLine} -Djgit.test.long=true</argLine> </configuration> </plugin> </plugins> @@ -186,7 +197,7 @@ <plugin> <artifactId>maven-surefire-plugin</artifactId> <configuration> - <argLine>-Xmx1024m -Dfile.encoding=UTF-8 -Djava.io.tmpdir=${project.build.directory}</argLine> + <argLine>@{argLine} -Xmx1024m -Dfile.encoding=UTF-8 -Djava.io.tmpdir=${project.build.directory}</argLine> <includes> <include>**/*Test.java</include> <include>**/*Tests.java</include> diff --git a/org.eclipse.jgit.test/src/org/eclipse/jgit/transport/ssh/SshTestBase.java b/org.eclipse.jgit.test/src/org/eclipse/jgit/transport/ssh/SshTestBase.java index dde55b6d79..2f367ba51f 100644 --- a/org.eclipse.jgit.test/src/org/eclipse/jgit/transport/ssh/SshTestBase.java +++ b/org.eclipse.jgit.test/src/org/eclipse/jgit/transport/ssh/SshTestBase.java @@ -42,6 +42,7 @@ */ package org.eclipse.jgit.transport.ssh; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -51,7 +52,6 @@ import static org.junit.Assume.assumeTrue; import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.List; import java.util.Locale; @@ -409,8 +409,7 @@ public abstract class SshTestBase extends SshTestHarness { private void checkKnownHostsModifiedHostKey(File backup, File newFile, String wrongKey) throws IOException { - List<String> oldLines = Files.readAllLines(backup.toPath(), - StandardCharsets.UTF_8); + List<String> oldLines = Files.readAllLines(backup.toPath(), UTF_8); // Find the original entry. We should have that again in known_hosts. String oldKeyPart = null; for (String oldLine : oldLines) { @@ -424,8 +423,7 @@ public abstract class SshTestBase extends SshTestHarness { } } assertNotNull("Old key not found", oldKeyPart); - List<String> newLines = Files.readAllLines(newFile.toPath(), - StandardCharsets.UTF_8); + List<String> newLines = Files.readAllLines(newFile.toPath(), UTF_8); assertFalse("Old host key still found in known_hosts file" + newFile, hasHostKey("localhost", testPort, wrongKey, newLines)); assertTrue("New host key not found in known_hosts file" + newFile, @@ -448,10 +446,10 @@ public abstract class SshTestBase extends SshTestHarness { "IdentityFile " + privateKey1.getAbsolutePath()); // File should not have been updated! String[] oldLines = Files - .readAllLines(backup.toPath(), StandardCharsets.UTF_8) + .readAllLines(backup.toPath(), UTF_8) .toArray(new String[0]); String[] newLines = Files - .readAllLines(knownHosts.toPath(), StandardCharsets.UTF_8) + .readAllLines(knownHosts.toPath(), UTF_8) .toArray(new String[0]); assertArrayEquals("Known hosts file should not be modified", oldLines, newLines); diff --git a/org.eclipse.jgit.test/src/org/eclipse/jgit/transport/ssh/SshTestHarness.java b/org.eclipse.jgit.test/src/org/eclipse/jgit/transport/ssh/SshTestHarness.java index 59925a5a16..ada16b75eb 100644 --- a/org.eclipse.jgit.test/src/org/eclipse/jgit/transport/ssh/SshTestHarness.java +++ b/org.eclipse.jgit.test/src/org/eclipse/jgit/transport/ssh/SshTestHarness.java @@ -42,6 +42,8 @@ */ package org.eclipse.jgit.transport.ssh; +import static java.nio.charset.StandardCharsets.US_ASCII; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -54,7 +56,6 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; @@ -150,7 +151,7 @@ public abstract class SshTestHarness extends RepositoryTestCase { knownHosts = new File(sshDir, "known_hosts"); Files.write(knownHosts.toPath(), Collections.singleton("[localhost]:" + testPort + ' ' - + publicHostKey.toString(StandardCharsets.US_ASCII.name()))); + + publicHostKey.toString(US_ASCII.name()))); factory = createSessionFactory(); SshSessionFactory.setInstance(factory); } @@ -200,8 +201,7 @@ public abstract class SshTestHarness extends RepositoryTestCase { */ protected static String createKnownHostsFile(File file, String host, int port, File publicKey) throws IOException { - List<String> lines = Files.readAllLines(publicKey.toPath(), - StandardCharsets.UTF_8); + List<String> lines = Files.readAllLines(publicKey.toPath(), UTF_8); assertEquals("Public key has too many lines", 1, lines.size()); String pubKey = lines.get(0); // Strip off the comment. diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/AddCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/AddCommandTest.java index 687926bd8d..b28e26a639 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/AddCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/AddCommandTest.java @@ -501,11 +501,11 @@ public class AddCommandTest extends RepositoryTestCase { indexState(CONTENT)); db.getConfig().setString("core", null, "autocrlf", "true"); git.add().addFilepattern("a.txt").call(); - assertEquals("[a.txt, mode:100644, content:row1\nrow2]", + assertEquals("[a.txt, mode:100644, content:row1\r\nrow2]", indexState(CONTENT)); db.getConfig().setString("core", null, "autocrlf", "input"); git.add().addFilepattern("a.txt").call(); - assertEquals("[a.txt, mode:100644, content:row1\nrow2]", + assertEquals("[a.txt, mode:100644, content:row1\r\nrow2]", indexState(CONTENT)); } } @@ -523,19 +523,18 @@ public class AddCommandTest extends RepositoryTestCase { try (PrintWriter writer = new PrintWriter(file, UTF_8.name())) { writer.print(crData); } - String lfData = data.toString().replaceAll("\r", ""); try (Git git = new Git(db)) { db.getConfig().setString("core", null, "autocrlf", "false"); git.add().addFilepattern("a.txt").call(); - assertEquals("[a.txt, mode:100644, content:" + data + "]", + assertEquals("[a.txt, mode:100644, content:" + crData + "]", indexState(CONTENT)); db.getConfig().setString("core", null, "autocrlf", "true"); git.add().addFilepattern("a.txt").call(); - assertEquals("[a.txt, mode:100644, content:" + lfData + "]", + assertEquals("[a.txt, mode:100644, content:" + crData + "]", indexState(CONTENT)); db.getConfig().setString("core", null, "autocrlf", "input"); git.add().addFilepattern("a.txt").call(); - assertEquals("[a.txt, mode:100644, content:" + lfData + "]", + assertEquals("[a.txt, mode:100644, content:" + crData + "]", indexState(CONTENT)); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CheckoutCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CheckoutCommandTest.java index 65c20aa9ab..1f3527f479 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CheckoutCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CheckoutCommandTest.java @@ -67,6 +67,7 @@ import java.time.Instant; import org.eclipse.jgit.api.CheckoutResult.Status; import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode; +import org.eclipse.jgit.api.errors.CheckoutConflictException; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.InvalidRefNameException; import org.eclipse.jgit.api.errors.InvalidRemoteException; @@ -115,7 +116,7 @@ public class CheckoutCommandTest extends RepositoryTestCase { git.add().addFilepattern("Test.txt").call(); initialCommit = git.commit().setMessage("Initial commit").call(); - // create a master branch and switch to it + // create a test branch and switch to it git.branchCreate().setName("test").call(); RefUpdate rup = db.updateRef(Constants.HEAD); rup.link("refs/heads/test"); @@ -144,6 +145,19 @@ public class CheckoutCommandTest extends RepositoryTestCase { } @Test + public void testCheckoutForced() throws Exception { + writeTrashFile("Test.txt", "Garbage"); + try { + git.checkout().setName("master").call().getObjectId(); + fail("Expected CheckoutConflictException didn't occur"); + } catch (CheckoutConflictException e) { + // Expected + } + assertEquals(initialCommit.getId(), git.checkout().setName("master") + .setForced(true).call().getObjectId()); + } + + @Test public void testCreateBranchOnCheckout() throws Exception { git.checkout().setCreateBranch(true).setName("test2").call(); assertNotNull(db.exactRef("refs/heads/test2")); @@ -171,7 +185,7 @@ public class CheckoutCommandTest extends RepositoryTestCase { assertEquals(Status.CONFLICTS, co.getResult().getStatus()); assertTrue(co.getResult().getConflictList().contains("Test.txt")); } - git.checkout().setName("master").setForce(true).call(); + git.checkout().setName("master").setForced(true).call(); assertThat(read("Test.txt"), is("Hello world")); } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CloneCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CloneCommandTest.java index 6b5fe502b7..1523b49ecc 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CloneCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CloneCommandTest.java @@ -424,6 +424,32 @@ public class CloneCommandTest extends RepositoryTestCase { specs.get(0)); } + @Test + public void testCloneRepositoryOnlyOneTag() throws Exception { + File directory = createTempDirectory("testCloneRepositoryWithBranch"); + CloneCommand command = Git.cloneRepository(); + command.setBranch("tag-initial"); + command.setBranchesToClone( + Collections.singletonList("refs/tags/tag-initial")); + command.setDirectory(directory); + command.setURI(fileUri()); + Git git2 = command.call(); + addRepoToClose(git2.getRepository()); + assertNotNull(git2); + assertNull(git2.getRepository().resolve("tag-for-blob")); + assertNull(git2.getRepository().resolve("refs/heads/master")); + assertNotNull(git2.getRepository().resolve("tag-initial")); + ObjectId taggedCommit = db.resolve("tag-initial^{commit}"); + assertEquals(taggedCommit.name(), git2.getRepository().getFullBranch()); + RemoteConfig cfg = new RemoteConfig(git2.getRepository().getConfig(), + Constants.DEFAULT_REMOTE_NAME); + List<RefSpec> specs = cfg.getFetchRefSpecs(); + assertEquals(1, specs.size()); + assertEquals( + new RefSpec("+refs/tags/tag-initial:refs/tags/tag-initial"), + specs.get(0)); + } + public static String allRefNames(List<Ref> refs) { StringBuilder sb = new StringBuilder(); for (Ref f : refs) { diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CommitCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CommitCommandTest.java index a6072a0f5f..e4b7ed7ba7 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CommitCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CommitCommandTest.java @@ -46,6 +46,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -53,7 +54,10 @@ import java.io.File; import java.util.Date; import java.util.List; import java.util.TimeZone; +import java.util.concurrent.atomic.AtomicInteger; +import org.eclipse.jgit.api.CherryPickResult.CherryPickStatus; +import org.eclipse.jgit.api.errors.CanceledException; import org.eclipse.jgit.api.errors.EmptyCommitException; import org.eclipse.jgit.api.errors.WrongRepositoryStateException; import org.eclipse.jgit.diff.DiffEntry; @@ -62,9 +66,11 @@ import org.eclipse.jgit.dircache.DirCacheBuilder; import org.eclipse.jgit.dircache.DirCacheEntry; import org.eclipse.jgit.junit.RepositoryTestCase; import org.eclipse.jgit.junit.time.TimeUtil; +import org.eclipse.jgit.lib.CommitBuilder; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.FileMode; +import org.eclipse.jgit.lib.GpgSigner; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.RefUpdate; @@ -73,7 +79,9 @@ import org.eclipse.jgit.lib.ReflogEntry; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.StoredConfig; import org.eclipse.jgit.revwalk.RevCommit; +import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.submodule.SubmoduleWalk; +import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.eclipse.jgit.util.FS; @@ -616,9 +624,100 @@ public class CommitCommandTest extends RepositoryTestCase { writeTrashFile(".gitignore", "bar"); git.add().addFilepattern("subdir").call(); git.commit().setOnly("subdir").setMessage("first commit").call(); + assertEquals("[subdir/foo, mode:100644, content:Hello World]", + indexState(CONTENT)); } } + @Test + public void commitWithAutoCrlfAndNonNormalizedIndex() throws Exception { + try (Git git = new Git(db)) { + // Commit a file with CR/LF into the index + FileBasedConfig config = db.getConfig(); + config.setString("core", null, "autocrlf", "false"); + config.save(); + writeTrashFile("file.txt", "line 1\r\nline 2\r\n"); + git.add().addFilepattern("file.txt").call(); + git.commit().setMessage("Initial").call(); + assertEquals( + "[file.txt, mode:100644, content:line 1\r\nline 2\r\n]", + indexState(CONTENT)); + config.setString("core", null, "autocrlf", "true"); + config.save(); + writeTrashFile("file.txt", "line 1\r\nline 1.5\r\nline 2\r\n"); + writeTrashFile("file2.txt", "new\r\nfile\r\n"); + git.add().addFilepattern("file.txt").addFilepattern("file2.txt") + .call(); + git.commit().setMessage("Second").call(); + assertEquals( + "[file.txt, mode:100644, content:line 1\r\nline 1.5\r\nline 2\r\n]" + + "[file2.txt, mode:100644, content:new\nfile\n]", + indexState(CONTENT)); + writeTrashFile("file2.txt", "new\r\nfile\r\ncontent\r\n"); + git.add().addFilepattern("file2.txt").call(); + git.commit().setMessage("Third").call(); + assertEquals( + "[file.txt, mode:100644, content:line 1\r\nline 1.5\r\nline 2\r\n]" + + "[file2.txt, mode:100644, content:new\nfile\ncontent\n]", + indexState(CONTENT)); + } + } + + private void testConflictWithAutoCrlf(String baseLf, String lf) + throws Exception { + try (Git git = new Git(db)) { + // Commit a file with CR/LF into the index + FileBasedConfig config = db.getConfig(); + config.setString("core", null, "autocrlf", "false"); + config.save(); + writeTrashFile("file.txt", "foo" + baseLf); + git.add().addFilepattern("file.txt").call(); + git.commit().setMessage("Initial").call(); + // Switch to side branch + git.checkout().setCreateBranch(true).setName("side").call(); + writeTrashFile("file.txt", "bar\r\n"); + git.add().addFilepattern("file.txt").call(); + RevCommit side = git.commit().setMessage("Side").call(); + // Switch back to master and commit a conflict with the given lf + git.checkout().setName("master"); + writeTrashFile("file.txt", "foob" + lf); + git.add().addFilepattern("file.txt").call(); + git.commit().setMessage("Second").call(); + // Switch on autocrlf=true + config.setString("core", null, "autocrlf", "true"); + config.save(); + // Cherry pick side: conflict. Resolve with CR-LF and commit. + CherryPickResult pick = git.cherryPick().include(side).call(); + assertEquals("Expected a cherry-pick conflict", + CherryPickStatus.CONFLICTING, pick.getStatus()); + writeTrashFile("file.txt", "foobar\r\n"); + git.add().addFilepattern("file.txt").call(); + git.commit().setMessage("Second").call(); + assertEquals("[file.txt, mode:100644, content:foobar" + lf + "]", + indexState(CONTENT)); + } + } + + @Test + public void commitConflictWithAutoCrlfBaseCrLfOursLf() throws Exception { + testConflictWithAutoCrlf("\r\n", "\n"); + } + + @Test + public void commitConflictWithAutoCrlfBaseLfOursLf() throws Exception { + testConflictWithAutoCrlf("\n", "\n"); + } + + @Test + public void commitConflictWithAutoCrlfBasCrLfOursCrLf() throws Exception { + testConflictWithAutoCrlf("\r\n", "\r\n"); + } + + @Test + public void commitConflictWithAutoCrlfBaseLfOursCrLf() throws Exception { + testConflictWithAutoCrlf("\n", "\r\n"); + } + private static void addUnmergedEntry(String file, DirCacheBuilder builder) { DirCacheEntry stage1 = new DirCacheEntry(file, DirCacheEntry.STAGE_1); DirCacheEntry stage2 = new DirCacheEntry(file, DirCacheEntry.STAGE_2); @@ -630,4 +729,126 @@ public class CommitCommandTest extends RepositoryTestCase { builder.add(stage2); builder.add(stage3); } + + @Test + public void callSignerWithProperSigningKey() throws Exception { + try (Git git = new Git(db)) { + writeTrashFile("file1", "file1"); + git.add().addFilepattern("file1").call(); + + String[] signingKey = new String[1]; + PersonIdent[] signingCommitters = new PersonIdent[1]; + AtomicInteger callCount = new AtomicInteger(); + GpgSigner.setDefault(new GpgSigner() { + @Override + public void sign(CommitBuilder commit, String gpgSigningKey, + PersonIdent signingCommitter, CredentialsProvider credentialsProvider) { + signingKey[0] = gpgSigningKey; + signingCommitters[0] = signingCommitter; + callCount.incrementAndGet(); + } + + @Override + public boolean canLocateSigningKey(String gpgSigningKey, + PersonIdent signingCommitter, + CredentialsProvider credentialsProvider) + throws CanceledException { + return false; + } + }); + + // first call should use config, which is expected to be null at + // this time + git.commit().setCommitter(committer).setSign(Boolean.TRUE) + .setMessage("initial commit") + .call(); + assertNull(signingKey[0]); + assertEquals(1, callCount.get()); + assertSame(committer, signingCommitters[0]); + + writeTrashFile("file2", "file2"); + git.add().addFilepattern("file2").call(); + + // second commit applies config value + String expectedConfigSigningKey = "config-" + System.nanoTime(); + StoredConfig config = git.getRepository().getConfig(); + config.setString("user", null, "signingKey", + expectedConfigSigningKey); + config.save(); + + git.commit().setCommitter(committer).setSign(Boolean.TRUE) + .setMessage("initial commit") + .call(); + assertEquals(expectedConfigSigningKey, signingKey[0]); + assertEquals(2, callCount.get()); + assertSame(committer, signingCommitters[0]); + + writeTrashFile("file3", "file3"); + git.add().addFilepattern("file3").call(); + + // now use specific on api + String expectedSigningKey = "my-" + System.nanoTime(); + git.commit().setCommitter(committer).setSign(Boolean.TRUE) + .setSigningKey(expectedSigningKey) + .setMessage("initial commit").call(); + assertEquals(expectedSigningKey, signingKey[0]); + assertEquals(3, callCount.get()); + assertSame(committer, signingCommitters[0]); + } + } + + @Test + public void callSignerOnlyWhenSigning() throws Exception { + try (Git git = new Git(db)) { + writeTrashFile("file1", "file1"); + git.add().addFilepattern("file1").call(); + + AtomicInteger callCount = new AtomicInteger(); + GpgSigner.setDefault(new GpgSigner() { + @Override + public void sign(CommitBuilder commit, String gpgSigningKey, + PersonIdent signingCommitter, CredentialsProvider credentialsProvider) { + callCount.incrementAndGet(); + } + + @Override + public boolean canLocateSigningKey(String gpgSigningKey, + PersonIdent signingCommitter, + CredentialsProvider credentialsProvider) + throws CanceledException { + return false; + } + }); + + // first call should use config, which is expected to be null at + // this time + git.commit().setMessage("initial commit").call(); + assertEquals(0, callCount.get()); + + writeTrashFile("file2", "file2"); + git.add().addFilepattern("file2").call(); + + // now force signing + git.commit().setSign(Boolean.TRUE).setMessage("commit").call(); + assertEquals(1, callCount.get()); + + writeTrashFile("file3", "file3"); + git.add().addFilepattern("file3").call(); + + // now rely on config + StoredConfig config = git.getRepository().getConfig(); + config.setBoolean("commit", null, "gpgSign", true); + config.save(); + + git.commit().setMessage("commit").call(); + assertEquals(2, callCount.get()); + + writeTrashFile("file4", "file4"); + git.add().addFilepattern("file4").call(); + + // now force "no-sign" (even though config is true) + git.commit().setSign(Boolean.FALSE).setMessage("commit").call(); + assertEquals(2, callCount.get()); + } + } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/MergeCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/MergeCommandTest.java index 9af003d424..5a15838029 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/MergeCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/MergeCommandTest.java @@ -1557,32 +1557,37 @@ public class MergeCommandTest extends RepositoryTestCase { @Test public void testRecursiveMergeWithConflict() throws Exception { - TestRepository<Repository> db_t = new TestRepository<>(db); - BranchBuilder master = db_t.branch("master"); - RevCommit m0 = master.commit().add("f", "1\n2\n3\n4\n5\n6\n7\n8\n9\n") - .message("m0").create(); - RevCommit m1 = master.commit() - .add("f", "1-master\n2\n3\n4\n5\n6\n7\n8\n9\n").message("m1") - .create(); - db_t.getRevWalk().parseCommit(m1); - - BranchBuilder side = db_t.branch("side"); - RevCommit s1 = side.commit().parent(m0) - .add("f", "1\n2\n3\n4\n5\n6\n7\n8\n9-side\n").message("s1") - .create(); - RevCommit s2 = side.commit().parent(m1) - .add("f", "1-master\n2\n3\n4\n5\n6\n7-res(side)\n8\n9-side\n") - .message("s2(merge)").create(); - master.commit().parent(s1) - .add("f", "1-master\n2\n3\n4\n5\n6\n7-conflict\n8\n9-side\n") - .message("m2(merge)").create(); - - Git git = Git.wrap(db); - git.checkout().setName("master").call(); - - MergeResult result = git.merge().setStrategy(MergeStrategy.RECURSIVE) - .include("side", s2).call(); - assertEquals(MergeStatus.CONFLICTING, result.getMergeStatus()); + try (TestRepository<Repository> db_t = new TestRepository<>(db)) { + BranchBuilder master = db_t.branch("master"); + RevCommit m0 = master.commit() + .add("f", "1\n2\n3\n4\n5\n6\n7\n8\n9\n").message("m0") + .create(); + RevCommit m1 = master.commit() + .add("f", "1-master\n2\n3\n4\n5\n6\n7\n8\n9\n") + .message("m1").create(); + db_t.getRevWalk().parseCommit(m1); + + BranchBuilder side = db_t.branch("side"); + RevCommit s1 = side.commit().parent(m0) + .add("f", "1\n2\n3\n4\n5\n6\n7\n8\n9-side\n").message("s1") + .create(); + RevCommit s2 = side.commit().parent(m1) + .add("f", + "1-master\n2\n3\n4\n5\n6\n7-res(side)\n8\n9-side\n") + .message("s2(merge)").create(); + master.commit().parent(s1) + .add("f", + "1-master\n2\n3\n4\n5\n6\n7-conflict\n8\n9-side\n") + .message("m2(merge)").create(); + + Git git = Git.wrap(db); + git.checkout().setName("master").call(); + + MergeResult result = git.merge() + .setStrategy(MergeStrategy.RECURSIVE).include("side", s2) + .call(); + assertEquals(MergeStatus.CONFLICTING, result.getMergeStatus()); + } } private Ref prepareSuccessfulMerge(Git git) throws Exception { diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RemoteDeleteCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RemoteDeleteCommandTest.java index 7055daff9a..50e7095792 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RemoteDeleteCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RemoteDeleteCommandTest.java @@ -56,7 +56,7 @@ public class RemoteDeleteCommandTest extends AbstractRemoteCommandTest { // execute the command to remove the remote RemoteRemoveCommand cmd = Git.wrap(db).remoteRemove(); - cmd.setName(REMOTE_NAME); + cmd.setRemoteName(REMOTE_NAME); RemoteConfig remote = cmd.call(); // assert that the removed remote is the initial remote diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RemoteSetUrlCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RemoteSetUrlCommandTest.java index 6969c3df6c..d3265fee70 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RemoteSetUrlCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RemoteSetUrlCommandTest.java @@ -45,6 +45,7 @@ package org.eclipse.jgit.api; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import org.eclipse.jgit.api.RemoteSetUrlCommand.UriType; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; import org.junit.Test; @@ -58,9 +59,9 @@ public class RemoteSetUrlCommandTest extends AbstractRemoteCommandTest { // execute the command to change the fetch url RemoteSetUrlCommand cmd = Git.wrap(db).remoteSetUrl(); - cmd.setName(REMOTE_NAME); + cmd.setRemoteName(REMOTE_NAME); URIish newUri = new URIish("git://test.com/test"); - cmd.setUri(newUri); + cmd.setRemoteUri(newUri); RemoteConfig remote = cmd.call(); // assert that the changed remote has the new fetch url @@ -79,10 +80,10 @@ public class RemoteSetUrlCommandTest extends AbstractRemoteCommandTest { // execute the command to change the push url RemoteSetUrlCommand cmd = Git.wrap(db).remoteSetUrl(); - cmd.setName(REMOTE_NAME); + cmd.setRemoteName(REMOTE_NAME); URIish newUri = new URIish("git://test.com/test"); - cmd.setUri(newUri); - cmd.setPush(true); + cmd.setRemoteUri(newUri); + cmd.setUriType(UriType.PUSH); RemoteConfig remote = cmd.call(); // assert that the changed remote has the old fetch url and the new push diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RenameBranchCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RenameBranchCommandTest.java index 5c437ac5a1..9facce9ac6 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RenameBranchCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RenameBranchCommandTest.java @@ -49,14 +49,18 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import org.eclipse.jgit.api.errors.RefAlreadyExistsException; import org.eclipse.jgit.junit.RepositoryTestCase; import org.eclipse.jgit.lib.BranchConfig.BranchRebaseMode; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.Constants; +import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.StoredConfig; import org.eclipse.jgit.revwalk.RevCommit; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; /** * Unit tests of {@link RenameBranchCommand} @@ -69,6 +73,9 @@ public class RenameBranchCommandTest extends RepositoryTestCase { private Git git; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @Override @Before public void setUp() throws Exception { @@ -81,6 +88,45 @@ public class RenameBranchCommandTest extends RepositoryTestCase { } @Test + public void renameToExisting() throws Exception { + assertNotNull(git.branchCreate().setName("foo").call()); + thrown.expect(RefAlreadyExistsException.class); + git.branchRename().setOldName("master").setNewName("foo").call(); + } + + @Test + public void renameToTag() throws Exception { + Ref ref = git.tag().setName("foo").call(); + assertNotNull(ref); + assertEquals("Unexpected tag name", Constants.R_TAGS + "foo", + ref.getName()); + ref = git.branchRename().setNewName("foo").call(); + assertNotNull(ref); + assertEquals("Unexpected ref name", Constants.R_HEADS + "foo", + ref.getName()); + // Check that we can rename it back + ref = git.branchRename().setOldName("foo").setNewName(Constants.MASTER) + .call(); + assertNotNull(ref); + assertEquals("Unexpected ref name", + Constants.R_HEADS + Constants.MASTER, ref.getName()); + } + + @Test + public void renameToStupidName() throws Exception { + Ref ref = git.branchRename().setNewName(Constants.R_HEADS + "foo") + .call(); + assertEquals("Unexpected ref name", + Constants.R_HEADS + Constants.R_HEADS + "foo", + ref.getName()); + // And check that we can rename it back to a sane name + ref = git.branchRename().setNewName("foo").call(); + assertNotNull(ref); + assertEquals("Unexpected ref name", Constants.R_HEADS + "foo", + ref.getName()); + } + + @Test public void renameBranchNoConfigValues() throws Exception { StoredConfig config = git.getRepository().getConfig(); config.unsetSection(ConfigConstants.CONFIG_BRANCH_SECTION, diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/attributes/AttributesNodeDirCacheIteratorTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/attributes/AttributesNodeDirCacheIteratorTest.java index 7421e907dc..837de74818 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/attributes/AttributesNodeDirCacheIteratorTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/attributes/AttributesNodeDirCacheIteratorTest.java @@ -64,7 +64,7 @@ import org.junit.Before; import org.junit.Test; /** - * Tests attributes node behavior on the the index. + * Tests attributes node behavior on the index. */ public class AttributesNodeDirCacheIteratorTest extends RepositoryTestCase { diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/RawTextTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/RawTextTest.java index 178d62072d..5333451a96 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/RawTextTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/RawTextTest.java @@ -79,6 +79,36 @@ public class RawTextTest { } @Test + public void testCrLfTextYes() { + assertTrue(RawText + .isCrLfText(Constants.encodeASCII("line 1\r\nline 2\r\n"))); + } + + @Test + public void testCrLfTextNo() { + assertFalse( + RawText.isCrLfText(Constants.encodeASCII("line 1\nline 2\n"))); + } + + @Test + public void testCrLfTextBinary() { + assertFalse(RawText + .isCrLfText(Constants.encodeASCII("line 1\r\nline\0 2\r\n"))); + } + + @Test + public void testCrLfTextMixed() { + assertTrue(RawText + .isCrLfText(Constants.encodeASCII("line 1\nline 2\r\n"))); + } + + @Test + public void testCrLfTextCutShort() { + assertFalse( + RawText.isCrLfText(Constants.encodeASCII("line 1\nline 2\r"))); + } + + @Test public void testEquals() { final RawText a = new RawText(Constants.encodeASCII("foo-a\nfoo-b\n")); final RawText b = new RawText(Constants.encodeASCII("foo-b\nfoo-c\n")); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/dfs/DfsPackFileTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/dfs/DfsPackFileTest.java new file mode 100644 index 0000000000..dd41b6fca6 --- /dev/null +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/dfs/DfsPackFileTest.java @@ -0,0 +1,165 @@ +/* + * Copyright (C) 2019, Google LLC. + * 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.internal.storage.dfs; + +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.zip.Deflater; + +import org.eclipse.jgit.internal.storage.pack.PackExt; +import org.eclipse.jgit.internal.storage.pack.PackOutputStream; +import org.eclipse.jgit.internal.storage.pack.PackWriter; +import org.eclipse.jgit.junit.JGitTestUtil; +import org.eclipse.jgit.junit.TestRng; +import org.eclipse.jgit.lib.Constants; +import org.eclipse.jgit.lib.NullProgressMonitor; +import org.junit.Before; +import org.junit.Test; + +public class DfsPackFileTest { + InMemoryRepository db; + boolean bypassCache; + boolean clearCache; + + @Before + public void setUp() { + db = new InMemoryRepository(new DfsRepositoryDescription("test")); + } + + @Test + public void testCopyPackBypassCachesSmallCached() throws IOException { + bypassCache = true; + clearCache = false; + setupPack(512, 256); + assertPackSize(); + } + + @Test + public void testCopyPackBypassCacheSmallNoCache() throws IOException { + bypassCache = true; + clearCache = true; + setupPack(512, 256); + assertPackSize(); + } + + @Test + public void testCopyPackBypassCacheLargeCached() throws IOException { + bypassCache = true; + clearCache = false; + setupPack(512, 8000); + assertPackSize(); + } + + @Test + public void testCopyPackBypassCacheLargeNoCache() throws IOException { + bypassCache = true; + clearCache = true; + setupPack(512, 8000); + assertPackSize(); + } + + @Test + public void testCopyPackThroughCacheSmallCached() throws IOException { + bypassCache = false; + clearCache = false; + setupPack(512, 256); + assertPackSize(); + } + + @Test + public void testCopyPackThroughCacheSmallNoCache() throws IOException { + bypassCache = false; + clearCache = true; + setupPack(512, 256); + assertPackSize(); + } + + @Test + public void testCopyPackThroughCacheLargeCached() throws IOException { + bypassCache = false; + clearCache = false; + setupPack(512, 8000); + assertPackSize(); + } + + @Test + public void testCopyPackThroughCacheLargeNoCache() throws IOException { + bypassCache = false; + clearCache = true; + setupPack(512, 8000); + assertPackSize(); + } + + private void setupPack(int bs, int ps) throws IOException { + DfsBlockCacheConfig cfg = new DfsBlockCacheConfig().setBlockSize(bs) + .setBlockLimit(bs * 100).setStreamRatio(bypassCache ? 0F : 1F); + DfsBlockCache.reconfigure(cfg); + + byte[] data = new TestRng(JGitTestUtil.getName()).nextBytes(ps); + DfsInserter ins = (DfsInserter) db.newObjectInserter(); + ins.setCompressionLevel(Deflater.NO_COMPRESSION); + ins.insert(Constants.OBJ_BLOB, data); + ins.flush(); + + if (clearCache) { + DfsBlockCache.reconfigure(cfg); + db.getObjectDatabase().clearCache(); + } + } + + private void assertPackSize() throws IOException { + try (DfsReader ctx = db.getObjectDatabase().newReader(); + PackWriter pw = new PackWriter(ctx); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PackOutputStream out = new PackOutputStream( + NullProgressMonitor.INSTANCE, os, pw)) { + DfsPackFile pack = db.getObjectDatabase().getPacks()[0]; + long packSize = pack.getPackDescription().getFileSize(PackExt.PACK); + pack.copyPackAsIs(out, ctx); + assertEquals(packSize - (12 + 20), os.size()); + } + } +} diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcBranchPrunedTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcBranchPrunedTest.java index c7ee9256d7..8f29b3b9d6 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcBranchPrunedTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcBranchPrunedTest.java @@ -66,11 +66,11 @@ public class GcBranchPrunedTest extends GcTestCase { fsTick(); gc.prune(Collections.<ObjectId> emptySet()); do { - assertTrue(repo.hasObject(tip)); + assertTrue(repo.getObjectDatabase().has(tip)); tr.parseBody(tip); RevTree t = tip.getTree(); - assertTrue(repo.hasObject(t)); - assertTrue(repo.hasObject(tr.get(t, "a"))); + assertTrue(repo.getObjectDatabase().has(t)); + assertTrue(repo.getObjectDatabase().has(tr.get(t, "a"))); tip = tip.getParentCount() > 0 ? tip.getParent(0) : null; } while (tip != null); } @@ -114,6 +114,6 @@ public class GcBranchPrunedTest extends GcTestCase { gc.setExpireAgeMillis(0); fsTick(); gc.prune(Collections.<ObjectId> emptySet()); - assertTrue(repo.hasObject(b2Tip)); + assertTrue(repo.getObjectDatabase().has(b2Tip)); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcConcurrentTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcConcurrentTest.java index c60c357da3..05f7c65fa8 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcConcurrentTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcConcurrentTest.java @@ -177,7 +177,7 @@ public class GcConcurrentTest extends GcTestCase { gc2.gc(); // Simulate parts of an UploadPack. This is the situation on - // server side (e.g. gerrit) when when clients are + // server side (e.g. gerrit) when clients are // cloning/fetching while the server side repo's // are gc'ed by an external process (e.g. scheduled // native git gc) diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcDeleteEmptyRefsFoldersTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcDeleteEmptyRefsFoldersTest.java index 3caae72fc6..d450f94941 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcDeleteEmptyRefsFoldersTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcDeleteEmptyRefsFoldersTest.java @@ -91,6 +91,20 @@ public class GcDeleteEmptyRefsFoldersTest extends GcTestCase { assertFalse(refDir02.getParent().getParent().toFile().exists()); } + @Test + public void emptyRefFoldersSkipFiles() throws Exception { + FileTime fileTime = FileTime.from(Instant.now().minusSeconds(31)); + Path refFile = Files.createFile(refsDir.resolve(".DS_Store")); + Path refDir01 = Files.createDirectories(heads.resolve(REF_FOLDER_01)); + Path refDir02 = Files.createDirectories(heads.resolve(REF_FOLDER_02)); + setLastModifiedTime(fileTime, heads, REF_FOLDER_01); + setLastModifiedTime(fileTime, heads, REF_FOLDER_02); + assertTrue(refDir01.toFile().exists()); + assertTrue(refDir02.toFile().exists()); + gc.gc(); + assertTrue(Files.exists(refFile)); + } + private void setLastModifiedTime(FileTime fileTime, Path path, String folder) throws IOException { long numParents = folder.chars().filter(c -> c == '/').count(); Path folderPath = path.resolve(folder); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcPruneNonReferencedTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcPruneNonReferencedTest.java index 345207089f..878dc860ce 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcPruneNonReferencedTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcPruneNonReferencedTest.java @@ -64,7 +64,7 @@ public class GcPruneNonReferencedTest extends GcTestCase { RevBlob a = tr.blob("a"); gc.setExpire(new Date(lastModified(a))); gc.prune(Collections.<ObjectId> emptySet()); - assertTrue(repo.hasObject(a)); + assertTrue(repo.getObjectDatabase().has(a)); } @Test @@ -73,7 +73,7 @@ public class GcPruneNonReferencedTest extends GcTestCase { gc.setExpireAgeMillis(0); fsTick(); gc.prune(Collections.<ObjectId> emptySet()); - assertFalse(repo.hasObject(a)); + assertFalse(repo.getObjectDatabase().has(a)); } @Test @@ -83,8 +83,8 @@ public class GcPruneNonReferencedTest extends GcTestCase { gc.setExpireAgeMillis(0); fsTick(); gc.prune(Collections.<ObjectId> emptySet()); - assertFalse(repo.hasObject(t)); - assertFalse(repo.hasObject(a)); + assertFalse(repo.getObjectDatabase().has(t)); + assertFalse(repo.getObjectDatabase().has(a)); } @Test @@ -96,8 +96,8 @@ public class GcPruneNonReferencedTest extends GcTestCase { RevBlob b = tr.blob("b"); gc.prune(Collections.<ObjectId> emptySet()); - assertFalse(repo.hasObject(a)); - assertTrue(repo.hasObject(b)); + assertFalse(repo.getObjectDatabase().has(a)); + assertTrue(repo.getObjectDatabase().has(b)); } @Test diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcTagTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcTagTest.java index 4afbeff3ec..cf7a4319cd 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcTagTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/GcTagTest.java @@ -60,7 +60,7 @@ public class GcTagTest extends GcTestCase { gc.setExpireAgeMillis(0); fsTick(); gc.prune(Collections.<ObjectId> emptySet()); - assertTrue(repo.hasObject(a)); + assertTrue(repo.getObjectDatabase().has(a)); } @Test @@ -72,7 +72,7 @@ public class GcTagTest extends GcTestCase { gc.setExpireAgeMillis(0); fsTick(); gc.prune(Collections.<ObjectId> emptySet()); - assertTrue(repo.hasObject(t)); - assertTrue(repo.hasObject(a)); + assertTrue(repo.getObjectDatabase().has(t)); + assertTrue(repo.getObjectDatabase().has(a)); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/ObjectDirectoryTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/ObjectDirectoryTest.java index 1d3ca03178..9d47c7e3bc 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/ObjectDirectoryTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/ObjectDirectoryTest.java @@ -127,7 +127,7 @@ public class ObjectDirectoryTest extends RepositoryTestCase { // scanning of the packs directory ObjectId id = commitFile("file.txt", "test", "master").getId(); gc.gc(); - assertFalse(receivingDB.hasObject(unknownID)); + assertFalse(receivingDB.getObjectDatabase().has(unknownID)); assertTrue(receivingDB.getObjectDatabase().hasPackedObject(id)); // preparations @@ -151,7 +151,7 @@ public class ObjectDirectoryTest extends RepositoryTestCase { // JGit will not rescan the packs folder later on and fails to see // the pack file created during gc. assertTrue(tmpFile.createNewFile()); - assertFalse(receivingDB.hasObject(unknownID)); + assertFalse(receivingDB.getObjectDatabase().has(unknownID)); // trigger a gc. This will create packfiles which have likely the // same mtime than the packfolder @@ -181,8 +181,8 @@ public class ObjectDirectoryTest extends RepositoryTestCase { .equals(fs.lastModifiedInstant(ret[0]))); // all objects are in a new packfile but we will not detect it - assertFalse(receivingDB.hasObject(unknownID)); - assertTrue(receivingDB.hasObject(id2)); + assertFalse(receivingDB.getObjectDatabase().has(unknownID)); + assertTrue(receivingDB.getObjectDatabase().has(id2)); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java index 04bed09af3..ca4486256b 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackWriterTest.java @@ -469,10 +469,12 @@ public class PackWriterTest extends SampleDataRepositoryTestCase { public void testDeltaStatistics() throws Exception { config.setDeltaCompress(true); FileRepository repo = createBareRepository(); - TestRepository<FileRepository> testRepo = new TestRepository<>(repo); ArrayList<RevObject> blobs = new ArrayList<>(); - blobs.add(testRepo.blob(genDeltableData(1000))); - blobs.add(testRepo.blob(genDeltableData(1005))); + try (TestRepository<FileRepository> testRepo = new TestRepository<>( + repo)) { + blobs.add(testRepo.blob(genDeltableData(1000))); + blobs.add(testRepo.blob(genDeltableData(1005))); + } try (PackWriter pw = new PackWriter(repo)) { NullProgressMonitor m = NullProgressMonitor.INSTANCE; @@ -535,25 +537,23 @@ public class PackWriterTest extends SampleDataRepositoryTestCase { public void testExclude() throws Exception { FileRepository repo = createBareRepository(); - TestRepository<FileRepository> testRepo = new TestRepository<>( - repo); - BranchBuilder bb = testRepo.branch("refs/heads/master"); - contentA = testRepo.blob("A"); - c1 = bb.commit().add("f", contentA).create(); - testRepo.getRevWalk().parseHeaders(c1); - PackIndex pf1 = writePack(repo, wants(c1), EMPTY_ID_SET); - assertContent( - pf1, - Arrays.asList(c1.getId(), c1.getTree().getId(), - contentA.getId())); - contentB = testRepo.blob("B"); - c2 = bb.commit().add("f", contentB).create(); - testRepo.getRevWalk().parseHeaders(c2); - PackIndex pf2 = writePack(repo, wants(c2), Sets.of((ObjectIdSet) pf1)); - assertContent( - pf2, - Arrays.asList(c2.getId(), c2.getTree().getId(), - contentB.getId())); + try (TestRepository<FileRepository> testRepo = new TestRepository<>( + repo)) { + BranchBuilder bb = testRepo.branch("refs/heads/master"); + contentA = testRepo.blob("A"); + c1 = bb.commit().add("f", contentA).create(); + testRepo.getRevWalk().parseHeaders(c1); + PackIndex pf1 = writePack(repo, wants(c1), EMPTY_ID_SET); + assertContent(pf1, Arrays.asList(c1.getId(), c1.getTree().getId(), + contentA.getId())); + contentB = testRepo.blob("B"); + c2 = bb.commit().add("f", contentB).create(); + testRepo.getRevWalk().parseHeaders(c2); + PackIndex pf2 = writePack(repo, wants(c2), + Sets.of((ObjectIdSet) pf1)); + assertContent(pf2, Arrays.asList(c2.getId(), c2.getTree().getId(), + contentB.getId())); + } } private static void assertContent(PackIndex pi, List<ObjectId> expected) { @@ -660,20 +660,21 @@ public class PackWriterTest extends SampleDataRepositoryTestCase { private FileRepository setupRepoForShallowFetch() throws Exception { FileRepository repo = createBareRepository(); - TestRepository<Repository> r = new TestRepository<>(repo); - BranchBuilder bb = r.branch("refs/heads/master"); - contentA = r.blob("A"); - contentB = r.blob("B"); - contentC = r.blob("C"); - contentD = r.blob("D"); - contentE = r.blob("E"); - c1 = bb.commit().add("a", contentA).create(); - c2 = bb.commit().add("b", contentB).create(); - c3 = bb.commit().add("c", contentC).create(); - c4 = bb.commit().add("d", contentD).create(); - c5 = bb.commit().add("e", contentE).create(); - r.getRevWalk().parseHeaders(c5); // fully initialize the tip RevCommit - return repo; + try (TestRepository<Repository> r = new TestRepository<>(repo)) { + BranchBuilder bb = r.branch("refs/heads/master"); + contentA = r.blob("A"); + contentB = r.blob("B"); + contentC = r.blob("C"); + contentD = r.blob("D"); + contentE = r.blob("E"); + c1 = bb.commit().add("a", contentA).create(); + c2 = bb.commit().add("b", contentB).create(); + c3 = bb.commit().add("c", contentC).create(); + c4 = bb.commit().add("d", contentD).create(); + c5 = bb.commit().add("e", contentE).create(); + r.getRevWalk().parseHeaders(c5); // fully initialize the tip RevCommit + return repo; + } } private static PackIndex writePack(FileRepository repo, diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/RefDirectoryTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/RefDirectoryTest.java index 24e3bc0773..2357edf6cb 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/RefDirectoryTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/RefDirectoryTest.java @@ -48,6 +48,7 @@ import static org.eclipse.jgit.lib.Constants.R_HEADS; import static org.eclipse.jgit.lib.Constants.R_TAGS; import static org.eclipse.jgit.lib.Ref.Storage.LOOSE; import static org.eclipse.jgit.lib.Ref.Storage.NEW; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -62,6 +63,7 @@ import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -137,6 +139,33 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { assertEquals("ref: refs/heads/master\n", read(new File(d, HEAD))); } + @Test(expected = UnsupportedOperationException.class) + public void testVersioningNotImplemented_exactRef() throws IOException { + assertFalse(refdir.hasVersioning()); + + Ref ref = refdir.exactRef(HEAD); + assertNotNull(ref); + ref.getUpdateIndex(); // Not implemented on FS + } + + @Test + public void testVersioningNotImplemented_getRefs() throws Exception { + assertFalse(refdir.hasVersioning()); + + RevCommit C = repo.commit().parent(B).create(); + repo.update("master", C); + List<Ref> refs = refdir.getRefs(); + + for (Ref ref : refs) { + try { + ref.getUpdateIndex(); + fail("FS doesn't implement ref versioning"); + } catch (UnsupportedOperationException e) { + // ok + } + } + } + @Test public void testGetRefs_EmptyDatabase() throws IOException { Map<String, Ref> all; @@ -395,15 +424,15 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { @Test public void testReadNotExistingBranchConfig() throws IOException { - assertNull("find branch config", refdir.getRef("config")); - assertNull("find branch config", refdir.getRef("refs/heads/config")); + assertNull("find branch config", refdir.findRef("config")); + assertNull("find branch config", refdir.findRef("refs/heads/config")); } @Test public void testReadBranchConfig() throws IOException { writeLooseRef("refs/heads/config", A); - assertNotNull("find branch config", refdir.getRef("config")); + assertNotNull("find branch config", refdir.findRef("config")); } @Test @@ -647,7 +676,7 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { @Repeat(n = 100, abortOnFailure = false) @Test - public void testGetRef_DiscoversModifiedLoose() throws IOException { + public void testFindRef_DiscoversModifiedLoose() throws IOException { Map<String, Ref> all; writeLooseRef("refs/heads/master", A); @@ -656,7 +685,7 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { writeLooseRef("refs/heads/master", B); - Ref master = refdir.getRef("refs/heads/master"); + Ref master = refdir.findRef("refs/heads/master"); assertEquals(B, master.getObjectId()); } @@ -691,7 +720,7 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { } @Test - public void testGetRef_DiscoversDeletedLoose() throws IOException { + public void testFindRef_DiscoversDeletedLoose() throws IOException { Map<String, Ref> all; writeLooseRef("refs/heads/master", A); @@ -699,7 +728,7 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { assertEquals(A, all.get(HEAD).getObjectId()); deleteLooseRef("refs/heads/master"); - assertNull(refdir.getRef("refs/heads/master")); + assertNull(refdir.findRef("refs/heads/master")); assertTrue(refdir.getRefs(RefDatabase.ALL).isEmpty()); } @@ -859,7 +888,7 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { } @Test - public void testGetRef_CycleInSymbolicRef() throws IOException { + public void testFindRef_CycleInSymbolicRef() throws IOException { Ref r; writeLooseRef("refs/1", "ref: refs/2\n"); @@ -869,7 +898,7 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { writeLooseRef("refs/5", "ref: refs/end\n"); writeLooseRef("refs/end", A); - r = refdir.getRef("1"); + r = refdir.findRef("1"); assertEquals("refs/1", r.getName()); assertEquals(A, r.getObjectId()); assertTrue(r.isSymbolic()); @@ -877,12 +906,12 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { writeLooseRef("refs/5", "ref: refs/6\n"); writeLooseRef("refs/6", "ref: refs/end\n"); - r = refdir.getRef("1"); + r = refdir.findRef("1"); assertNull("missing 1 due to cycle", r); writeLooseRef("refs/heads/1", B); - r = refdir.getRef("1"); + r = refdir.findRef("1"); assertEquals("refs/heads/1", r.getName()); assertEquals(B, r.getObjectId()); assertFalse(r.isSymbolic()); @@ -923,16 +952,16 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { } @Test - public void testGetRef_PackedNotPeeled_WrongSort() throws IOException { + public void testFindRef_PackedNotPeeled_WrongSort() throws IOException { writePackedRefs("" + // v1_0.name() + " refs/tags/v1.0\n" + // B.name() + " refs/heads/other\n" + // A.name() + " refs/heads/master\n"); - final Ref head = refdir.getRef(HEAD); - final Ref master = refdir.getRef("refs/heads/master"); - final Ref other = refdir.getRef("refs/heads/other"); - final Ref tag = refdir.getRef("refs/tags/v1.0"); + final Ref head = refdir.findRef(HEAD); + final Ref master = refdir.findRef("refs/heads/master"); + final Ref other = refdir.findRef("refs/heads/other"); + final Ref tag = refdir.findRef("refs/tags/v1.0"); assertEquals(A, master.getObjectId()); assertFalse(master.isPeeled()); @@ -1037,22 +1066,22 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { } @Test - public void testGetRef_EmptyDatabase() throws IOException { + public void testFindRef_EmptyDatabase() throws IOException { Ref r; - r = refdir.getRef(HEAD); + r = refdir.findRef(HEAD); assertTrue(r.isSymbolic()); assertSame(LOOSE, r.getStorage()); assertEquals("refs/heads/master", r.getTarget().getName()); assertSame(NEW, r.getTarget().getStorage()); assertNull(r.getTarget().getObjectId()); - assertNull(refdir.getRef("refs/heads/master")); - assertNull(refdir.getRef("refs/tags/v1.0")); - assertNull(refdir.getRef("FETCH_HEAD")); - assertNull(refdir.getRef("NOT.A.REF.NAME")); - assertNull(refdir.getRef("master")); - assertNull(refdir.getRef("v1.0")); + assertNull(refdir.findRef("refs/heads/master")); + assertNull(refdir.findRef("refs/tags/v1.0")); + assertNull(refdir.findRef("FETCH_HEAD")); + assertNull(refdir.findRef("NOT.A.REF.NAME")); + assertNull(refdir.findRef("master")); + assertNull(refdir.findRef("v1.0")); } @Test @@ -1075,7 +1104,29 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { } @Test - public void testGetRef_FetchHead() throws IOException { + public void testGetAdditionalRefs_OrigHead() throws IOException { + writeLooseRef("ORIG_HEAD", A); + + List<Ref> refs = refdir.getAdditionalRefs(); + assertEquals(1, refs.size()); + + Ref r = refs.get(0); + assertFalse(r.isSymbolic()); + assertEquals(A, r.getObjectId()); + assertEquals("ORIG_HEAD", r.getName()); + assertFalse(r.isPeeled()); + assertNull(r.getPeeledObjectId()); + } + + @Test + public void testGetAdditionalRefs_OrigHeadBranch() throws IOException { + writeLooseRef("refs/heads/ORIG_HEAD", A); + List<Ref> refs = refdir.getAdditionalRefs(); + assertArrayEquals(new Ref[0], refs.toArray()); + } + + @Test + public void testFindRef_FetchHead() throws IOException { // This is an odd special case where we need to make sure we read // exactly the first 40 bytes of the file and nothing further on // that line, or the remainder of the file. @@ -1083,7 +1134,7 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { + "\tnot-for-merge" + "\tbranch 'master' of git://egit.eclipse.org/jgit\n"); - Ref r = refdir.getRef("FETCH_HEAD"); + Ref r = refdir.findRef("FETCH_HEAD"); assertFalse(r.isSymbolic()); assertEquals(A, r.getObjectId()); assertEquals("FETCH_HEAD", r.getName()); @@ -1109,12 +1160,12 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { } @Test - public void testGetRef_AnyHeadWithGarbage() throws IOException { + public void testFindRef_AnyHeadWithGarbage() throws IOException { write(new File(diskRepo.getDirectory(), "refs/heads/A"), A.name() + "012345 . this is not a standard reference\n" + "#and even more junk\n"); - Ref r = refdir.getRef("refs/heads/A"); + Ref r = refdir.findRef("refs/heads/A"); assertFalse(r.isSymbolic()); assertEquals(A, r.getObjectId()); assertEquals("refs/heads/A", r.getName()); @@ -1130,11 +1181,11 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { } @Test - public void testGetRef_CorruptSymbolicReference() throws IOException { + public void testFindRef_CorruptSymbolicReference() throws IOException { String name = "refs/heads/A"; writeLooseRef(name, "ref: \n"); try { - refdir.getRef(name); + refdir.findRef(name); fail("read an invalid reference"); } catch (IOException err) { String msg = err.getMessage(); @@ -1151,12 +1202,12 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { } @Test - public void testGetRef_CorruptObjectIdReference() throws IOException { + public void testFindRef_CorruptObjectIdReference() throws IOException { String name = "refs/heads/A"; String content = "zoo" + A.name(); writeLooseRef(name, content + "\n"); try { - refdir.getRef(name); + refdir.findRef(name); fail("read an invalid reference"); } catch (IOException err) { String msg = err.getMessage(); @@ -1191,8 +1242,8 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { writeLooseRef("refs/tags/v1_0", v1_0); writeLooseRef("refs/tags/current", "ref: refs/tags/v1_0\n"); - final Ref tag = refdir.getRef("refs/tags/v1_0"); - final Ref cur = refdir.getRef("refs/tags/current"); + final Ref tag = refdir.findRef("refs/tags/v1_0"); + final Ref cur = refdir.findRef("refs/tags/current"); assertEquals(v1_0, tag.getObjectId()); assertFalse(tag.isSymbolic()); @@ -1224,14 +1275,14 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { // reuses cached peeling later, but not immediately due to // the implementation so we have to fetch it once. - final Ref tag_p2 = refdir.getRef("refs/tags/v1_0"); + final Ref tag_p2 = refdir.findRef("refs/tags/v1_0"); assertFalse(tag_p2.isSymbolic()); assertTrue(tag_p2.isPeeled()); assertEquals(v1_0, tag_p2.getObjectId()); assertEquals(v1_0.getObject(), tag_p2.getPeeledObjectId()); - assertSame(tag_p2, refdir.getRef("refs/tags/v1_0")); - assertSame(tag_p2, refdir.getRef("refs/tags/current").getTarget()); + assertSame(tag_p2, refdir.findRef("refs/tags/v1_0")); + assertSame(tag_p2, refdir.findRef("refs/tags/current").getTarget()); assertSame(tag_p2, refdir.peel(tag_p2)); } @@ -1239,7 +1290,7 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { public void testPeelCommit() throws IOException { writeLooseRef("refs/heads/master", A); - Ref master = refdir.getRef("refs/heads/master"); + Ref master = refdir.findRef("refs/heads/master"); assertEquals(A, master.getObjectId()); assertFalse(master.isPeeled()); assertNull(master.getPeeledObjectId()); @@ -1252,7 +1303,7 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { // reuses cached peeling later, but not immediately due to // the implementation so we have to fetch it once. - Ref master_p2 = refdir.getRef("refs/heads/master"); + Ref master_p2 = refdir.findRef("refs/heads/master"); assertNotSame(master, master_p2); assertEquals(A, master_p2.getObjectId()); assertTrue(master_p2.isPeeled()); @@ -1304,7 +1355,7 @@ public class RefDirectoryTest extends LocalDiskRepositoryTestCase { } finally { myLock.unlock(); } - Ref ref = refdir.getRef("refs/heads/master"); + Ref ref = refdir.findRef("refs/heads/master"); assertEquals(Storage.LOOSE, ref.getStorage()); } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/T0003_BasicTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/T0003_BasicTest.java index 9eb181635f..e2887d9053 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/T0003_BasicTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/T0003_BasicTest.java @@ -540,7 +540,7 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase { 4294967295000L, 60)); commit.setCommitter(new PersonIdent("Joe Hacker", "joe2@example.com", 4294967295000L, 60)); - commit.setEncoding("ISO-8859-1"); + commit.setEncoding(ISO_8859_1); commit.setMessage("\u00dcbergeeks"); ObjectId cid = insertCommit(commit); assertEquals("2979b39d385014b33287054b87f77bcb3ecb5ebf", cid.name()); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftable/MergedReftableTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftable/MergedReftableTest.java index 1d11573b99..11d6439931 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftable/MergedReftableTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftable/MergedReftableTest.java @@ -44,6 +44,7 @@ package org.eclipse.jgit.internal.storage.reftable; import static org.eclipse.jgit.lib.Constants.HEAD; +import static org.eclipse.jgit.lib.Constants.MASTER; import static org.eclipse.jgit.lib.Constants.OBJECT_ID_LENGTH; import static org.eclipse.jgit.lib.Constants.R_HEADS; import static org.eclipse.jgit.lib.Ref.Storage.NEW; @@ -68,6 +69,7 @@ import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectIdRef; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.RefComparator; +import org.eclipse.jgit.lib.SymbolicRef; import org.junit.Test; public class MergedReftableTest { @@ -128,6 +130,7 @@ public class MergedReftableTest { Ref act = rc.getRef(); assertEquals(exp.getName(), act.getName()); assertEquals(exp.getObjectId(), act.getObjectId()); + assertEquals(1, act.getUpdateIndex()); } assertFalse(rc.next()); } @@ -145,6 +148,7 @@ public class MergedReftableTest { assertTrue(rc.next()); assertEquals("refs/heads/master", rc.getRef().getName()); assertEquals(id(2), rc.getRef().getObjectId()); + assertEquals(1, rc.getRef().getUpdateIndex()); assertFalse(rc.next()); } } @@ -162,6 +166,7 @@ public class MergedReftableTest { assertEquals("refs/heads/master", rc.getRef().getName()); assertEquals(id(2), rc.getRef().getObjectId()); assertFalse(rc.next()); + assertEquals(1, rc.getRef().getUpdateIndex()); } } @@ -177,6 +182,7 @@ public class MergedReftableTest { assertTrue(rc.next()); assertEquals("refs/heads/master", rc.getRef().getName()); assertEquals(id(2), rc.getRef().getObjectId()); + assertEquals(1, rc.getRef().getUpdateIndex()); assertFalse(rc.next()); } } @@ -212,6 +218,7 @@ public class MergedReftableTest { Ref act = rc.getRef(); assertEquals(exp.getName(), act.getName()); assertEquals(exp.getObjectId(), act.getObjectId()); + assertEquals(1, rc.getRef().getUpdateIndex()); } assertFalse(rc.next()); } @@ -231,9 +238,11 @@ public class MergedReftableTest { assertTrue(rc.next()); assertEquals("refs/heads/apple", rc.getRef().getName()); assertEquals(id(3), rc.getRef().getObjectId()); + assertEquals(2000, rc.getRef().getUpdateIndex()); assertTrue(rc.next()); assertEquals("refs/heads/banana", rc.getRef().getName()); assertEquals(id(2), rc.getRef().getObjectId()); + assertEquals(1000, rc.getRef().getUpdateIndex()); assertFalse(rc.next()); } } @@ -251,12 +260,14 @@ public class MergedReftableTest { Ref r = rc.getRef(); assertEquals("refs/heads/master", r.getName()); assertEquals(id(8), r.getObjectId()); + assertEquals(1, rc.getRef().getUpdateIndex()); assertTrue(rc.next()); r = rc.getRef(); assertEquals("refs/heads/next", r.getName()); assertEquals(NEW, r.getStorage()); assertNull(r.getObjectId()); + assertEquals(1, rc.getRef().getUpdateIndex()); assertFalse(rc.next()); } @@ -277,6 +288,7 @@ public class MergedReftableTest { Ref act = rc.getRef(); assertEquals(exp.getName(), act.getName()); assertEquals(exp.getObjectId(), act.getObjectId()); + assertEquals(1, act.getUpdateIndex()); assertFalse(rc.next()); } } @@ -303,17 +315,17 @@ public class MergedReftableTest { assertTrue(rc.next()); assertEquals("refs/heads/a", rc.getRef().getName()); assertEquals(id(1), rc.getRef().getObjectId()); - assertEquals(1, rc.getUpdateIndex()); + assertEquals(1, rc.getRef().getUpdateIndex()); assertTrue(rc.next()); assertEquals("refs/heads/b", rc.getRef().getName()); assertEquals(id(2), rc.getRef().getObjectId()); - assertEquals(2, rc.getUpdateIndex()); + assertEquals(2, rc.getRef().getUpdateIndex()); assertTrue(rc.next()); assertEquals("refs/heads/c", rc.getRef().getName()); assertEquals(id(3), rc.getRef().getObjectId()); - assertEquals(3, rc.getUpdateIndex()); + assertEquals(3, rc.getRef().getUpdateIndex()); } } @@ -344,6 +356,63 @@ public class MergedReftableTest { } } + @Test + public void versioningSymbolicReftargetMoves() throws IOException { + Ref master = ref(MASTER, 100); + + List<Ref> delta1 = Arrays.asList(master, sym(HEAD, MASTER)); + List<Ref> delta2 = Arrays.asList(ref(MASTER, 200)); + + MergedReftable mr = merge(write(delta1, 1), write(delta2, 2)); + Ref head = mr.exactRef(HEAD); + assertEquals(head.getUpdateIndex(), 1); + + Ref masterRef = mr.exactRef(MASTER); + assertEquals(masterRef.getUpdateIndex(), 2); + } + + @Test + public void versioningSymbolicRefMoves() throws IOException { + Ref branchX = ref("refs/heads/branchX", 200); + + List<Ref> delta1 = Arrays.asList(ref(MASTER, 100), branchX, + sym(HEAD, MASTER)); + List<Ref> delta2 = Arrays.asList(sym(HEAD, "refs/heads/branchX")); + List<Ref> delta3 = Arrays.asList(sym(HEAD, MASTER)); + + MergedReftable mr = merge(write(delta1, 1), write(delta2, 2), + write(delta3, 3)); + Ref head = mr.exactRef(HEAD); + assertEquals(head.getUpdateIndex(), 3); + + Ref masterRef = mr.exactRef(MASTER); + assertEquals(masterRef.getUpdateIndex(), 1); + + Ref branchRef = mr.exactRef(MASTER); + assertEquals(branchRef.getUpdateIndex(), 1); + } + + @Test + public void versioningResolveRef() throws IOException { + List<Ref> delta1 = Arrays.asList(sym(HEAD, "refs/heads/tmp"), + sym("refs/heads/tmp", MASTER), ref(MASTER, 100)); + List<Ref> delta2 = Arrays.asList(ref(MASTER, 200)); + List<Ref> delta3 = Arrays.asList(ref(MASTER, 300)); + + MergedReftable mr = merge(write(delta1, 1), write(delta2, 2), + write(delta3, 3)); + Ref head = mr.exactRef(HEAD); + Ref resolvedHead = mr.resolve(head); + assertEquals(resolvedHead.getObjectId(), id(300)); + assertEquals("HEAD has not moved", resolvedHead.getUpdateIndex(), 1); + + Ref master = mr.exactRef(MASTER); + Ref resolvedMaster = mr.resolve(master); + assertEquals(resolvedMaster.getObjectId(), id(300)); + assertEquals("master also has update index", + resolvedMaster.getUpdateIndex(), 3); + } + private static MergedReftable merge(byte[]... table) { List<Reftable> stack = new ArrayList<>(table.length); for (byte[] b : table) { @@ -360,6 +429,14 @@ public class MergedReftableTest { return new ObjectIdRef.PeeledNonTag(PACKED, name, id(id)); } + private static Ref sym(String name, String target) { + return new SymbolicRef(name, newRef(target)); + } + + private static Ref newRef(String name) { + return new ObjectIdRef.Unpeeled(NEW, name, null); + } + private static Ref delete(String name) { return new ObjectIdRef.Unpeeled(NEW, name, null); } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftable/ReftableCompactorTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftable/ReftableCompactorTest.java index 46a37ff603..1ea73097fe 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftable/ReftableCompactorTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftable/ReftableCompactorTest.java @@ -108,7 +108,7 @@ public class ReftableCompactorTest { assertTrue(rc.next()); assertEquals(MASTER, rc.getRef().getName()); assertEquals(id(1), rc.getRef().getObjectId()); - assertEquals(0, rc.getUpdateIndex()); + assertEquals(0, rc.getRef().getUpdateIndex()); } } @@ -155,7 +155,7 @@ public class ReftableCompactorTest { assertTrue(rc.next()); assertEquals(MASTER, rc.getRef().getName()); assertEquals(id(2), rc.getRef().getObjectId()); - assertEquals(1, rc.getUpdateIndex()); + assertEquals(1, rc.getRef().getUpdateIndex()); } } @@ -203,12 +203,12 @@ public class ReftableCompactorTest { assertTrue(rc.next()); assertEquals(MASTER, rc.getRef().getName()); assertEquals(id(3), rc.getRef().getObjectId()); - assertEquals(1, rc.getUpdateIndex()); + assertEquals(1, rc.getRef().getUpdateIndex()); assertTrue(rc.next()); assertEquals(NEXT, rc.getRef().getName()); assertEquals(id(2), rc.getRef().getObjectId()); - assertEquals(0, rc.getUpdateIndex()); + assertEquals(0, rc.getRef().getUpdateIndex()); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftable/ReftableTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftable/ReftableTest.java index 0ee785c60c..a142166983 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftable/ReftableTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftable/ReftableTest.java @@ -186,6 +186,7 @@ public class ReftableTest { assertFalse(act.isSymbolic()); assertEquals(exp.getName(), act.getName()); assertEquals(exp.getObjectId(), act.getObjectId()); + assertEquals(0, act.getUpdateIndex()); assertNull(act.getPeeledObjectId()); assertFalse(rc.wasDeleted()); assertFalse(rc.next()); @@ -195,6 +196,7 @@ public class ReftableTest { Ref act = rc.getRef(); assertNotNull(act); assertEquals(exp.getName(), act.getName()); + assertEquals(0, act.getUpdateIndex()); assertFalse(rc.next()); } } @@ -216,6 +218,7 @@ public class ReftableTest { assertEquals(exp.getName(), act.getName()); assertEquals(exp.getObjectId(), act.getObjectId()); assertEquals(exp.getPeeledObjectId(), act.getPeeledObjectId()); + assertEquals(0, act.getUpdateIndex()); } } @@ -237,6 +240,7 @@ public class ReftableTest { assertNotNull(act.getLeaf()); assertEquals(MASTER, act.getTarget().getName()); assertNull(act.getObjectId()); + assertEquals(0, act.getUpdateIndex()); } } @@ -250,14 +254,17 @@ public class ReftableTest { Ref head = t.exactRef(HEAD); assertNull(head.getObjectId()); assertEquals("refs/heads/tmp", head.getTarget().getName()); + assertEquals(0, head.getUpdateIndex()); head = t.resolve(head); assertNotNull(head); assertEquals(id(1), head.getObjectId()); + assertEquals(0, head.getUpdateIndex()); Ref master = t.exactRef(MASTER); assertNotNull(master); assertSame(master, t.resolve(master)); + assertEquals(0, master.getUpdateIndex()); } @Test @@ -335,14 +342,17 @@ public class ReftableTest { try (RefCursor rc = t.seekRefsWithPrefix("refs/tags/")) { assertTrue(rc.next()); assertEquals(V1_0, rc.getRef().getName()); + assertEquals(0, rc.getRef().getUpdateIndex()); assertFalse(rc.next()); } try (RefCursor rc = t.seekRefsWithPrefix("refs/heads/")) { assertTrue(rc.next()); assertEquals(MASTER, rc.getRef().getName()); + assertEquals(0, rc.getRef().getUpdateIndex()); assertTrue(rc.next()); assertEquals(NEXT, rc.getRef().getName()); + assertEquals(0, rc.getRef().getUpdateIndex()); assertFalse(rc.next()); } @@ -432,11 +442,12 @@ public class ReftableTest { assertTrue(rc.next()); assertEquals(MASTER, rc.getRef().getName()); assertEquals(id(1), rc.getRef().getObjectId()); - assertEquals(1, rc.getUpdateIndex()); + assertEquals(1, rc.getRef().getUpdateIndex()); assertTrue(rc.next()); assertEquals(NEXT, rc.getRef().getName()); assertEquals(id(2), rc.getRef().getObjectId()); + assertEquals(1, rc.getRef().getUpdateIndex()); assertFalse(rc.next()); } try (LogCursor lc = t.allLogs()) { @@ -569,6 +580,7 @@ public class ReftableTest { assertTrue("has 42", rc.next()); assertEquals("refs/heads/42", rc.getRef().getName()); assertEquals(id(42), rc.getRef().getObjectId()); + assertEquals(0, rc.getRef().getUpdateIndex()); assertFalse(rc.next()); } try (RefCursor rc = t.byObjectId(id(100))) { @@ -579,6 +591,7 @@ public class ReftableTest { assertTrue("has master", rc.next()); assertEquals("refs/heads/master", rc.getRef().getName()); assertEquals(id(100), rc.getRef().getObjectId()); + assertEquals(0, rc.getRef().getUpdateIndex()); assertFalse(rc.next()); } @@ -600,6 +613,7 @@ public class ReftableTest { assertTrue("has 42", rc.next()); assertEquals("refs/heads/42", rc.getRef().getName()); assertEquals(id(42), rc.getRef().getObjectId()); + assertEquals(0, rc.getRef().getUpdateIndex()); assertFalse(rc.next()); } try (RefCursor rc = t.byObjectId(id(100))) { @@ -610,6 +624,7 @@ public class ReftableTest { assertTrue("has master", rc.next()); assertEquals("refs/heads/master", rc.getRef().getName()); assertEquals(id(100), rc.getRef().getObjectId()); + assertEquals(0, rc.getRef().getUpdateIndex()); assertFalse(rc.next()); } @@ -654,7 +669,6 @@ public class ReftableTest { } } - private static void assertScan(List<Ref> refs, Reftable t) throws IOException { try (RefCursor rc = t.allRefs()) { @@ -663,6 +677,7 @@ public class ReftableTest { Ref act = rc.getRef(); assertEquals(exp.getName(), act.getName()); assertEquals(exp.getObjectId(), act.getObjectId()); + assertEquals(0, rc.getRef().getUpdateIndex()); } assertFalse(rc.next()); } @@ -676,6 +691,7 @@ public class ReftableTest { Ref act = rc.getRef(); assertEquals(exp.getName(), act.getName()); assertEquals(exp.getObjectId(), act.getObjectId()); + assertEquals(0, rc.getRef().getUpdateIndex()); assertFalse(rc.next()); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftree/RefTreeDatabaseTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftree/RefTreeDatabaseTest.java index ae52ad5917..8ef21e6da7 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftree/RefTreeDatabaseTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/reftree/RefTreeDatabaseTest.java @@ -362,8 +362,8 @@ public class RefTreeDatabaseTest { @Test public void testGetRef_NonExistingBranchConfig() throws IOException { - assertNull("find branch config", refdb.getRef("config")); - assertNull("find branch config", refdb.getRef("refs/heads/config")); + assertNull("find branch config", refdb.findRef("config")); + assertNull("find branch config", refdb.findRef("refs/heads/config")); } @Test @@ -371,7 +371,7 @@ public class RefTreeDatabaseTest { update("refs/heads/config", A); for (String t : new String[] { "config", "refs/heads/config" }) { - Ref r = refdb.getRef(t); + Ref r = refdb.findRef(t); assertNotNull("find branch config (" + t + ")", r); assertEquals("for " + t, "refs/heads/config", r.getName()); assertEquals("for " + t, A, r.getObjectId()); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/CommitBuilderTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/CommitBuilderTest.java new file mode 100644 index 0000000000..27ea505618 --- /dev/null +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/CommitBuilderTest.java @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2018, Salesforce. + * 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.lib; + +import static java.nio.charset.StandardCharsets.US_ASCII; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.text.MessageFormat; + +import org.eclipse.jgit.internal.JGitText; +import org.junit.Test; + +public class CommitBuilderTest { + + private void assertGpgSignatureStringOutcome(String signature, + String expectedOutcome) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + CommitBuilder.writeGpgSignatureString(signature, out); + String formatted_signature = new String(out.toByteArray(), US_ASCII); + assertEquals(expectedOutcome, formatted_signature); + } + + @Test + public void writeGpgSignatureString_1() throws Exception { + // @formatter:off + String signature = "-----BEGIN PGP SIGNATURE-----\n" + + "Version: BCPG v1.60\n" + + "\n" + + "iQEcBAABCAAGBQJb9cVhAAoJEKX+6Axg/6TZeFsH/0CY0WX/z7U8+7S5giFX4wH4\n" + + "opvBwqyt6OX8lgNwTwBGHFNt8LdmDCCmKoq/XwkNi3ARVjLhe3gBcKXNoavvPk2Z\n" + + "gIg5ChevGkU4afWCOMLVEYnkCBGw2+86XhrK1P7gTHEk1Rd+Yv1ZRDJBY+fFO7yz\n" + + "uSBuF5RpEY2sJiIvp27Gub/rY3B5NTR/feO/z+b9oiP/fMUhpRwG5KuWUsn9NPjw\n" + + "3tvbgawYpU/2UnS+xnavMY4t2fjRYjsoxndPLb2MUX8X7vC7FgWLBlmI/rquLZVM\n" + + "IQEKkjnA+lhejjK1rv+ulq4kGZJFKGYWYYhRDwFg5PTkzhudhN2SGUq5Wxq1Eg4=\n" + + "=b9OI\n" + + "-----END PGP SIGNATURE-----"; + String expectedOutcome = "-----BEGIN PGP SIGNATURE-----\n" + + " Version: BCPG v1.60\n" + + " \n" + + " iQEcBAABCAAGBQJb9cVhAAoJEKX+6Axg/6TZeFsH/0CY0WX/z7U8+7S5giFX4wH4\n" + + " opvBwqyt6OX8lgNwTwBGHFNt8LdmDCCmKoq/XwkNi3ARVjLhe3gBcKXNoavvPk2Z\n" + + " gIg5ChevGkU4afWCOMLVEYnkCBGw2+86XhrK1P7gTHEk1Rd+Yv1ZRDJBY+fFO7yz\n" + + " uSBuF5RpEY2sJiIvp27Gub/rY3B5NTR/feO/z+b9oiP/fMUhpRwG5KuWUsn9NPjw\n" + + " 3tvbgawYpU/2UnS+xnavMY4t2fjRYjsoxndPLb2MUX8X7vC7FgWLBlmI/rquLZVM\n" + + " IQEKkjnA+lhejjK1rv+ulq4kGZJFKGYWYYhRDwFg5PTkzhudhN2SGUq5Wxq1Eg4=\n" + + " =b9OI\n" + + " -----END PGP SIGNATURE-----"; + // @formatter:on + assertGpgSignatureStringOutcome(signature, expectedOutcome); + } + + @Test + public void writeGpgSignatureString_failsForNonAscii() throws Exception { + String signature = "Ü Ä"; + try { + CommitBuilder.writeGpgSignatureString(signature, + new ByteArrayOutputStream()); + fail("Exception expected"); + } catch (IllegalArgumentException e) { + // good + String message = MessageFormat.format(JGitText.get().notASCIIString, + signature); + assertEquals(message, e.getMessage()); + } + } + + @Test + public void writeGpgSignatureString_oneLineNotModified() throws Exception { + String signature = " A string "; + String expectedOutcome = signature; + assertGpgSignatureStringOutcome(signature, expectedOutcome); + } + + @Test + public void writeGpgSignatureString_preservesRandomWhitespace() + throws Exception { + // @formatter:off + String signature = " String with \n" + + "Line 2\n" + + " Line 3\n" + + "Line 4 \n" + + " Line 5 "; + String expectedOutcome = " String with \n" + + " Line 2\n" + + " Line 3\n" + + " Line 4 \n" + + " Line 5 "; + // @formatter:on + assertGpgSignatureStringOutcome(signature, expectedOutcome); + } + + @Test + public void writeGpgSignatureString_replaceCR() throws Exception { + // @formatter:off + String signature = "String with \r" + + "Line 2\r" + + "Line 3\r" + + "Line 4\r" + + "Line 5"; + String expectedOutcome = "String with \n" + + " Line 2\n" + + " Line 3\n" + + " Line 4\n" + + " Line 5"; + // @formatter:on + assertGpgSignatureStringOutcome(signature, expectedOutcome); + } + + @Test + public void writeGpgSignatureString_replaceCRLF() throws Exception { + // @formatter:off + String signature = "String with \r\n" + + "Line 2\r\n" + + "Line 3\r\n" + + "Line 4\r\n" + + "Line 5"; + String expectedOutcome = "String with \n" + + " Line 2\n" + + " Line 3\n" + + " Line 4\n" + + " Line 5"; + // @formatter:on + assertGpgSignatureStringOutcome(signature, expectedOutcome); + } + + @Test + public void writeGpgSignatureString_replaceCRLFMixed() throws Exception { + // @formatter:off + String signature = "String with \r" + + "Line 2\r\n" + + "Line 3\r" + + "Line 4\r\n" + + "Line 5"; + String expectedOutcome = "String with \n" + + " Line 2\n" + + " Line 3\n" + + " Line 4\n" + + " Line 5"; + // @formatter:on + assertGpgSignatureStringOutcome(signature, expectedOutcome); + } + + @Test + public void setGpgSignature() throws Exception { + GpgSignature dummy = new GpgSignature(new byte[0]); + + CommitBuilder builder = new CommitBuilder(); + assertNull(builder.getGpgSignature()); + + builder.setGpgSignature(dummy); + assertSame(dummy, builder.getGpgSignature()); + + builder.setGpgSignature(null); + assertNull(builder.getGpgSignature()); + } +} diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/DirCacheCheckoutTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/DirCacheCheckoutTest.java index 534b323fe6..483051ceeb 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/DirCacheCheckoutTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/DirCacheCheckoutTest.java @@ -267,10 +267,10 @@ public class DirCacheCheckoutTest extends RepositoryTestCase { public void testInitialCheckout() throws Exception { ChangeRecorder recorder = new ChangeRecorder(); ListenerHandle handle = null; - try (Git git = new Git(db)) { + try (Git git = new Git(db); + TestRepository<Repository> db_t = new TestRepository<>(db)) { handle = db.getListenerList() .addWorkingTreeModifiedListener(recorder); - TestRepository<Repository> db_t = new TestRepository<>(db); BranchBuilder master = db_t.branch("master"); master.commit().add("f", "1").message("m0").create(); assertFalse(new File(db.getWorkTree(), "f").exists()); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ObjectIdRefTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ObjectIdRefTest.java index fb16c6baca..6553bfa830 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ObjectIdRefTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ObjectIdRefTest.java @@ -48,6 +48,10 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.Arrays; +import java.util.List; import org.junit.Test; @@ -115,10 +119,43 @@ public class ObjectIdRefTest { } @Test + public void testUpdateIndex() { + ObjectIdRef r; + + r = new ObjectIdRef.Unpeeled(Ref.Storage.LOOSE, name, ID_A, 3); + assertTrue(r.getUpdateIndex() == 3); + + r = new ObjectIdRef.PeeledTag(Ref.Storage.LOOSE, name, ID_A, ID_B, 4); + assertTrue(r.getUpdateIndex() == 4); + + r = new ObjectIdRef.PeeledNonTag(Ref.Storage.LOOSE, name, ID_A, 5); + assertTrue(r.getUpdateIndex() == 5); + } + + @Test + public void testUpdateIndexNotSet() { + List<ObjectIdRef> r = Arrays.asList( + new ObjectIdRef.Unpeeled(Ref.Storage.LOOSE, name, ID_A), + new ObjectIdRef.PeeledTag(Ref.Storage.LOOSE, name, ID_A, ID_B), + new ObjectIdRef.PeeledNonTag(Ref.Storage.LOOSE, name, ID_A)); + + for (ObjectIdRef ref : r) { + try { + ref.getUpdateIndex(); + fail("Update index wasn't set. It must throw"); + } catch (UnsupportedOperationException u) { + // Ok + } + } + } + + + @Test public void testToString() { ObjectIdRef r; r = new ObjectIdRef.Unpeeled(Ref.Storage.LOOSE, name, ID_A); - assertEquals("Ref[" + name + "=" + ID_A.name() + "]", r.toString()); + assertEquals("Ref[" + name + "=" + ID_A.name() + "(-1)]", + r.toString()); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RefDatabaseConflictingNamesTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RefDatabaseConflictingNamesTest.java index 1c21194248..cbb47fa829 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RefDatabaseConflictingNamesTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RefDatabaseConflictingNamesTest.java @@ -95,7 +95,7 @@ public class RefDatabaseConflictingNamesTest { } @Override - public Ref getRef(String name) throws IOException { + public Ref exactRef(String name) throws IOException { return null; } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RepositoryCacheTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RepositoryCacheTest.java index 58b005c282..15c4e4a029 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RepositoryCacheTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/RepositoryCacheTest.java @@ -110,7 +110,7 @@ public class RepositoryCacheTest extends RepositoryTestCase { @Test public void testFileKeyOpenNew() throws IOException { File gitdir; - try (Repository n = createRepository(true, false)) { + try (Repository n = createRepository(true)) { gitdir = n.getDirectory(); } recursiveDelete(gitdir); @@ -192,7 +192,7 @@ public class RepositoryCacheTest extends RepositoryTestCase { @Test public void testRepositoryUsageCountWithRegisteredRepository() throws IOException { - @SuppressWarnings("resource") // We are testing the close() method + @SuppressWarnings({"resource", "deprecation"}) // We are testing the close() method Repository repo = createRepository(false, false); assertEquals(1, repo.useCnt.get()); RepositoryCache.register(repo); @@ -240,9 +240,9 @@ public class RepositoryCacheTest extends RepositoryTestCase { @Test public void testRepositoryUnregisteringWhenExpired() throws Exception { - @SuppressWarnings("resource") // We are testing the close() method + @SuppressWarnings({"resource", "deprecation"}) // We are testing the close() method Repository repoA = createRepository(true, false); - @SuppressWarnings("resource") // We are testing the close() method + @SuppressWarnings({"resource", "deprecation"}) // We are testing the close() method Repository repoB = createRepository(true, false); Repository repoC = createBareRepository(); RepositoryCache.register(repoA); @@ -276,7 +276,7 @@ public class RepositoryCacheTest extends RepositoryTestCase { @Test public void testReconfigure() throws InterruptedException, IOException { - @SuppressWarnings("resource") // We are testing the close() method + @SuppressWarnings({"resource", "deprecation"}) // We are testing the close() method Repository repo = createRepository(false, false); RepositoryCache.register(repo); assertTrue(RepositoryCache.isCached(repo)); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/SymbolicRefTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/SymbolicRefTest.java index 1342253c05..99b2211e69 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/SymbolicRefTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/SymbolicRefTest.java @@ -68,7 +68,7 @@ public class SymbolicRefTest { SymbolicRef r; t = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, targetName, null); - r = new SymbolicRef(name, t); + r = new SymbolicRef(name, t, 1); assertSame(Ref.Storage.LOOSE, r.getStorage()); assertSame(name, r.getName()); assertNull("no id on new ref", r.getObjectId()); @@ -77,9 +77,10 @@ public class SymbolicRefTest { assertSame("leaf is t", t, r.getLeaf()); assertSame("target is t", t, r.getTarget()); assertTrue("is symbolic", r.isSymbolic()); + assertTrue("holds update index", r.getUpdateIndex() == 1); t = new ObjectIdRef.Unpeeled(Ref.Storage.PACKED, targetName, ID_A); - r = new SymbolicRef(name, t); + r = new SymbolicRef(name, t, 2); assertSame(Ref.Storage.LOOSE, r.getStorage()); assertSame(name, r.getName()); assertSame(ID_A, r.getObjectId()); @@ -88,6 +89,7 @@ public class SymbolicRefTest { assertSame("leaf is t", t, r.getLeaf()); assertSame("target is t", t, r.getTarget()); assertTrue("is symbolic", r.isSymbolic()); + assertTrue("holds update index", r.getUpdateIndex() == 2); } @Test @@ -133,6 +135,6 @@ public class SymbolicRefTest { d = new SymbolicRef("D", c); assertEquals("SymbolicRef[D -> C -> B -> " + targetName + "=" - + ID_A.name() + "]", d.toString()); + + ID_A.name() + "(-1)]", d.toString()); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/MergerTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/MergerTest.java index fa02227a58..2ae9c11a7d 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/MergerTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/MergerTest.java @@ -1071,7 +1071,7 @@ public class MergerTest extends RepositoryTestCase { git.add().addFilepattern("c.txt").call(); git.commit().setMessage("added c.txt").call(); - // Get a handle to the the file so on windows it can't be deleted. + // Get a handle to the file so on windows it can't be deleted. try (FileInputStream fis = new FileInputStream( new File(db.getWorkTree(), "b.txt"))) { MergeResult mergeRes = git.merge().setStrategy(strategy) @@ -1365,14 +1365,15 @@ public class MergerTest extends RepositoryTestCase { } private String readBlob(ObjectId treeish, String path) throws Exception { - TestRepository<?> tr = new TestRepository<>(db); - RevWalk rw = tr.getRevWalk(); - RevTree tree = rw.parseTree(treeish); - RevObject obj = tr.get(tree, path); - if (obj == null) { - return null; + try (TestRepository<?> tr = new TestRepository<>(db)) { + RevWalk rw = tr.getRevWalk(); + RevTree tree = rw.parseTree(treeish); + RevObject obj = tr.get(tree, path); + if (obj == null) { + return null; + } + return new String( + rw.getObjectReader().open(obj, OBJ_BLOB).getBytes(), UTF_8); } - return new String(rw.getObjectReader().open(obj, OBJ_BLOB).getBytes(), - UTF_8); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleStatusTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleStatusTest.java index 5832518f81..9151b0407f 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleStatusTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleStatusTest.java @@ -263,8 +263,10 @@ public class SubmoduleStatusTest extends RepositoryTestCase { .getRepository(); assertNotNull(subRepo); - TestRepository<?> subTr = new TestRepository<>(subRepo); - ObjectId id = subTr.branch(Constants.HEAD).commit().create().copy(); + ObjectId id; + try (TestRepository<?> subTr = new TestRepository<>(subRepo)) { + id = subTr.branch(Constants.HEAD).commit().create().copy(); + } DirCache cache = db.lockDirCache(); DirCacheEditor editor = cache.editor(); @@ -315,50 +317,52 @@ public class SubmoduleStatusTest extends RepositoryTestCase { .getRepository(); assertNotNull(subRepo); - TestRepository<?> subTr = new TestRepository<>(subRepo); - ObjectId id = subTr.branch(Constants.HEAD).commit().create().copy(); - - DirCache cache = db.lockDirCache(); - DirCacheEditor editor = cache.editor(); - editor.add(new PathEdit(path) { - - @Override - public void apply(DirCacheEntry ent) { - ent.setFileMode(FileMode.GITLINK); - ent.setObjectId(id); - } - }); - editor.commit(); - - String url = "git://server/repo.git"; - StoredConfig config = db.getConfig(); - config.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, - ConfigConstants.CONFIG_KEY_URL, url); - config.save(); - - FileBasedConfig modulesConfig = new FileBasedConfig(new File( - db.getWorkTree(), Constants.DOT_GIT_MODULES), db.getFS()); - modulesConfig.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, - ConfigConstants.CONFIG_KEY_PATH, path); - modulesConfig.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, - ConfigConstants.CONFIG_KEY_URL, url); - modulesConfig.save(); - - ObjectId newId = subTr.branch(Constants.HEAD).commit().create().copy(); - - SubmoduleStatusCommand command = new SubmoduleStatusCommand(db); - Map<String, SubmoduleStatus> statuses = command.call(); - assertNotNull(statuses); - assertEquals(1, statuses.size()); - Entry<String, SubmoduleStatus> module = statuses.entrySet().iterator() - .next(); - assertNotNull(module); - assertEquals(path, module.getKey()); - SubmoduleStatus status = module.getValue(); - assertNotNull(status); - assertEquals(path, status.getPath()); - assertEquals(id, status.getIndexId()); - assertEquals(newId, status.getHeadId()); - assertEquals(SubmoduleStatusType.REV_CHECKED_OUT, status.getType()); + try (TestRepository<?> subTr = new TestRepository<>(subRepo)) { + ObjectId id = subTr.branch(Constants.HEAD).commit().create().copy(); + DirCache cache = db.lockDirCache(); + DirCacheEditor editor = cache.editor(); + editor.add(new PathEdit(path) { + + @Override + public void apply(DirCacheEntry ent) { + ent.setFileMode(FileMode.GITLINK); + ent.setObjectId(id); + } + }); + editor.commit(); + + String url = "git://server/repo.git"; + StoredConfig config = db.getConfig(); + config.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, + ConfigConstants.CONFIG_KEY_URL, url); + config.save(); + + FileBasedConfig modulesConfig = new FileBasedConfig( + new File(db.getWorkTree(), Constants.DOT_GIT_MODULES), + db.getFS()); + modulesConfig.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, + path, ConfigConstants.CONFIG_KEY_PATH, path); + modulesConfig.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, + path, ConfigConstants.CONFIG_KEY_URL, url); + modulesConfig.save(); + + ObjectId newId = subTr.branch(Constants.HEAD).commit().create() + .copy(); + + SubmoduleStatusCommand command = new SubmoduleStatusCommand(db); + Map<String, SubmoduleStatus> statuses = command.call(); + assertNotNull(statuses); + assertEquals(1, statuses.size()); + Entry<String, SubmoduleStatus> module = statuses.entrySet() + .iterator().next(); + assertNotNull(module); + assertEquals(path, module.getKey()); + SubmoduleStatus status = module.getValue(); + assertNotNull(status); + assertEquals(path, status.getPath()); + assertEquals(id, status.getIndexId()); + assertEquals(newId, status.getHeadId()); + assertEquals(SubmoduleStatusType.REV_CHECKED_OUT, status.getType()); + } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleWalkTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleWalkTest.java index a0cd37ee5f..ea1ace364e 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleWalkTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/submodule/SubmoduleWalkTest.java @@ -145,7 +145,6 @@ public class SubmoduleWalkTest extends RepositoryTestCase { assertFalse(gen.next()); } - @SuppressWarnings("resource" /* java 7 */) @Test public void repositoryWithRootLevelSubmoduleAbsoluteRef() throws IOException, ConfigInvalidException { @@ -189,17 +188,16 @@ public class SubmoduleWalkTest extends RepositoryTestCase { assertNull(gen.getModulesPath()); assertNull(gen.getModulesUpdate()); assertNull(gen.getModulesUrl()); - Repository subRepo = gen.getRepository(); - assertNotNull(subRepo); - assertEquals(modulesGitDir.getAbsolutePath(), - subRepo.getDirectory().getAbsolutePath()); - assertEquals(new File(db.getWorkTree(), path).getAbsolutePath(), - subRepo.getWorkTree().getAbsolutePath()); - subRepo.close(); + try (Repository subRepo = gen.getRepository()) { + assertNotNull(subRepo); + assertEquals(modulesGitDir.getAbsolutePath(), + subRepo.getDirectory().getAbsolutePath()); + assertEquals(new File(db.getWorkTree(), path).getAbsolutePath(), + subRepo.getWorkTree().getAbsolutePath()); + } assertFalse(gen.next()); } - @SuppressWarnings("resource" /* java 7 */) @Test public void repositoryWithRootLevelSubmoduleRelativeRef() throws IOException, ConfigInvalidException { @@ -244,13 +242,14 @@ public class SubmoduleWalkTest extends RepositoryTestCase { assertNull(gen.getModulesPath()); assertNull(gen.getModulesUpdate()); assertNull(gen.getModulesUrl()); - Repository subRepo = gen.getRepository(); - assertNotNull(subRepo); - assertEqualsFile(modulesGitDir, subRepo.getDirectory()); - assertEqualsFile(new File(db.getWorkTree(), path), - subRepo.getWorkTree()); - subRepo.close(); - assertFalse(gen.next()); + try (Repository subRepo = gen.getRepository()) { + assertNotNull(subRepo); + assertEqualsFile(modulesGitDir, subRepo.getDirectory()); + assertEqualsFile(new File(db.getWorkTree(), path), + subRepo.getWorkTree()); + subRepo.close(); + assertFalse(gen.next()); + } } @Test diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/BundleWriterTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/BundleWriterTest.java index 7b31bfa3ad..dce9db572e 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/BundleWriterTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/BundleWriterTest.java @@ -77,10 +77,38 @@ import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.test.resources.SampleDataRepositoryTestCase; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; public class BundleWriterTest extends SampleDataRepositoryTestCase { + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testEmptyBundleFails() throws Exception { + Repository newRepo = createBareRepository(); + thrown.expect(TransportException.class); + fetchFromBundle(newRepo, new byte[0]); + } + + @Test + public void testNonBundleFails() throws Exception { + Repository newRepo = createBareRepository(); + thrown.expect(TransportException.class); + fetchFromBundle(newRepo, "Not a bundle file".getBytes(UTF_8)); + } + + @Test + public void testGarbageBundleFails() throws Exception { + Repository newRepo = createBareRepository(); + thrown.expect(TransportException.class); + fetchFromBundle(newRepo, + (TransportBundle.V2_BUNDLE_SIGNATURE + '\n' + "Garbage") + .getBytes(UTF_8)); + } + @Test public void testWriteSingleRef() throws Exception { // Create a tiny bundle, (well one of) the first commits only diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/JschConfigSessionFactoryTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/JschConfigSessionFactoryTest.java index 1e65a20d7f..3de4210baa 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/JschConfigSessionFactoryTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/JschConfigSessionFactoryTest.java @@ -49,8 +49,11 @@ import java.nio.file.Files; import java.util.Arrays; import java.util.concurrent.TimeUnit; +import org.eclipse.jgit.junit.MockSystemReader; import org.eclipse.jgit.util.FS; +import org.eclipse.jgit.util.SystemReader; import org.junit.After; +import org.junit.Before; import org.junit.Test; import com.jcraft.jsch.Session; @@ -67,8 +70,14 @@ public class JschConfigSessionFactoryTest { DefaultSshSessionFactory factory = new DefaultSshSessionFactory(); + @Before + public void setup() { + SystemReader.setInstance(new MockSystemReader()); + } + @After public void removeTmpConfig() { + SystemReader.setInstance(null); if (tmpConfigFile == null) { return; } @@ -87,7 +96,8 @@ public class JschConfigSessionFactoryTest { Session session = createSession("ssh://egit/egit/egit"); assertEquals("egit", session.getHost()); // No user in URI, none in ssh config: default is OS user name - assertEquals(System.getProperty("user.name"), session.getUserName()); + assertEquals(SystemReader.getInstance().getProperty("user.name"), + session.getUserName()); assertEquals(22, session.getPort()); } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PackParserTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PackParserTest.java index b6d0611437..fd952f328f 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PackParserTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PackParserTest.java @@ -141,8 +141,10 @@ public class PackParserTest extends RepositoryTestCase { @Test public void testTinyThinPack() throws Exception { - TestRepository d = new TestRepository<Repository>(db); - RevBlob a = d.blob("a"); + RevBlob a; + try (TestRepository d = new TestRepository<Repository>(db)) { + a = d.blob("a"); + } TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); @@ -162,8 +164,9 @@ public class PackParserTest extends RepositoryTestCase { @Test public void testPackWithDuplicateBlob() throws Exception { final byte[] data = Constants.encode("0123456789abcdefg"); - TestRepository<Repository> d = new TestRepository<>(db); - assertTrue(db.hasObject(d.blob(data))); + try (TestRepository<Repository> d = new TestRepository<>(db)) { + assertTrue(db.getObjectDatabase().has(d.blob(data))); + } TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); packHeader(pack, 1); @@ -179,8 +182,10 @@ public class PackParserTest extends RepositoryTestCase { @Test public void testPackWithTrailingGarbage() throws Exception { - TestRepository d = new TestRepository<Repository>(db); - RevBlob a = d.blob("a"); + RevBlob a; + try (TestRepository d = new TestRepository<Repository>(db)) { + a = d.blob("a"); + } TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); packHeader(pack, 1); @@ -206,9 +211,10 @@ public class PackParserTest extends RepositoryTestCase { @Test public void testMaxObjectSizeFullBlob() throws Exception { - TestRepository d = new TestRepository<Repository>(db); final byte[] data = Constants.encode("0123456789"); - d.blob(data); + try (TestRepository d = new TestRepository<Repository>(db)) { + d.blob(data); + } TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); @@ -238,8 +244,10 @@ public class PackParserTest extends RepositoryTestCase { @Test public void testMaxObjectSizeDeltaBlock() throws Exception { - TestRepository d = new TestRepository<Repository>(db); - RevBlob a = d.blob("a"); + RevBlob a; + try (TestRepository d = new TestRepository<Repository>(db)) { + a = d.blob("a"); + } TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); @@ -269,8 +277,10 @@ public class PackParserTest extends RepositoryTestCase { @Test public void testMaxObjectSizeDeltaResultSize() throws Exception { - TestRepository d = new TestRepository<Repository>(db); - RevBlob a = d.blob("0123456789"); + RevBlob a; + try (TestRepository d = new TestRepository<Repository>(db)) { + a = d.blob("0123456789"); + } TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); @@ -299,8 +309,10 @@ public class PackParserTest extends RepositoryTestCase { @Test public void testNonMarkingInputStream() throws Exception { - TestRepository d = new TestRepository<Repository>(db); - RevBlob a = d.blob("a"); + RevBlob a; + try (TestRepository d = new TestRepository<Repository>(db)) { + a = d.blob("a"); + } TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); packHeader(pack, 1); @@ -337,8 +349,10 @@ public class PackParserTest extends RepositoryTestCase { @Test public void testDataAfterPackFooterSingleRead() throws Exception { - TestRepository d = new TestRepository<Repository>(db); - RevBlob a = d.blob("a"); + RevBlob a; + try (TestRepository d = new TestRepository<Repository>(db)) { + a = d.blob("a"); + } TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(32*1024); packHeader(pack, 1); @@ -395,9 +409,11 @@ public class PackParserTest extends RepositoryTestCase { @Test public void testDataAfterPackFooterSplitHeaderRead() throws Exception { - TestRepository d = new TestRepository<Repository>(db); final byte[] data = Constants.encode("a"); - RevBlob b = d.blob(data); + RevBlob b; + try (TestRepository d = new TestRepository<Repository>(db)) { + b = d.blob(data); + } int objects = 248; TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(32 * 1024); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PushConnectionTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PushConnectionTest.java index 63478f6f92..cea432e34c 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PushConnectionTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/PushConnectionTest.java @@ -216,15 +216,16 @@ public class PushConnectionTest { @Test public void commandOrder() throws Exception { - TestRepository<?> tr = new TestRepository<>(client); List<RemoteRefUpdate> updates = new ArrayList<>(); - // Arbitrary non-sorted order. - for (int i = 9; i >= 0; i--) { - String name = "refs/heads/b" + i; - tr.branch(name).commit().create(); - RemoteRefUpdate rru = new RemoteRefUpdate(client, name, name, false, null, - ObjectId.zeroId()); - updates.add(rru); + try (TestRepository<?> tr = new TestRepository<>(client)) { + // Arbitrary non-sorted order. + for (int i = 9; i >= 0; i--) { + String name = "refs/heads/b" + i; + tr.branch(name).commit().create(); + RemoteRefUpdate rru = new RemoteRefUpdate(client, name, name, + false, null, ObjectId.zeroId()); + updates.add(rru); + } } PushResult result; diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ReceivePackAdvertiseRefsHookTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ReceivePackAdvertiseRefsHookTest.java index dfa50b6bb6..50c8a29543 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ReceivePackAdvertiseRefsHookTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/ReceivePackAdvertiseRefsHookTest.java @@ -110,24 +110,26 @@ public class ReceivePackAdvertiseRefsHookTest extends LocalDiskRepositoryTestCas // Fill dst with a some common history. // - TestRepository<Repository> d = new TestRepository<>(dst); - a = d.blob("a"); - A = d.commit(d.tree(d.file("a", a))); - B = d.commit().parent(A).create(); - d.update(R_MASTER, B); + try (TestRepository<Repository> d = new TestRepository<>(dst)) { + a = d.blob("a"); + A = d.commit(d.tree(d.file("a", a))); + B = d.commit().parent(A).create(); + d.update(R_MASTER, B); + + // Clone from dst into src + // + try (Transport t = Transport.open(src, uriOf(dst))) { + t.fetch(PM, + Collections.singleton(new RefSpec("+refs/*:refs/*"))); + assertEquals(B, src.resolve(R_MASTER)); + } - // Clone from dst into src - // - try (Transport t = Transport.open(src, uriOf(dst))) { - t.fetch(PM, Collections.singleton(new RefSpec("+refs/*:refs/*"))); - assertEquals(B, src.resolve(R_MASTER)); + // Now put private stuff into dst. + // + b = d.blob("b"); + P = d.commit(d.tree(d.file("b", b)), A); + d.update(R_PRIVATE, P); } - - // Now put private stuff into dst. - // - b = d.blob("b"); - P = d.commit(d.tree(d.file("b", b)), A); - d.update(R_PRIVATE, P); } @Test @@ -236,36 +238,38 @@ public class ReceivePackAdvertiseRefsHookTest extends LocalDiskRepositoryTestCas // Verify the only storage of b is our packed delta above. // ObjectDirectory od = (ObjectDirectory) src.getObjectDatabase(); - assertTrue("has b", src.hasObject(b)); + assertTrue("has b", od.has(b)); assertFalse("b not loose", od.fileFor(b).exists()); // Now use b but in a different commit than what is hidden. // - TestRepository<Repository> s = new TestRepository<>(src); - RevCommit N = s.commit().parent(B).add("q", b).create(); - s.update(R_MASTER, N); + try (TestRepository<Repository> s = new TestRepository<>(src)) { + RevCommit N = s.commit().parent(B).add("q", b).create(); + s.update(R_MASTER, N); + + // Push this new content to the remote, doing strict validation. + // + PushResult r; + RemoteRefUpdate u = new RemoteRefUpdate( // + src, // + R_MASTER, // src name + R_MASTER, // dst name + false, // do not force update + null, // local tracking branch + null // expected id + ); + try (TransportLocal t = newTransportLocalWithStrictValidation()) { + t.setPushThin(true); + r = t.push(PM, Collections.singleton(u)); + dst.close(); + } - // Push this new content to the remote, doing strict validation. - // - PushResult r; - RemoteRefUpdate u = new RemoteRefUpdate( // - src, // - R_MASTER, // src name - R_MASTER, // dst name - false, // do not force update - null, // local tracking branch - null // expected id - ); - try (TransportLocal t = newTransportLocalWithStrictValidation()) { - t.setPushThin(true); - r = t.push(PM, Collections.singleton(u)); - dst.close(); + assertNotNull("have result", r); + assertNull("private not advertised", r.getAdvertisedRef(R_PRIVATE)); + assertSame("master updated", RemoteRefUpdate.Status.OK, + u.getStatus()); + assertEquals(N, dst.resolve(R_MASTER)); } - - assertNotNull("have result", r); - assertNull("private not advertised", r.getAdvertisedRef(R_PRIVATE)); - assertSame("master updated", RemoteRefUpdate.Status.OK, u.getStatus()); - assertEquals(N, dst.resolve(R_MASTER)); } @Test @@ -318,154 +322,165 @@ public class ReceivePackAdvertiseRefsHookTest extends LocalDiskRepositoryTestCas @Test public void testUsingHiddenDeltaBaseFails() throws Exception { byte[] delta = { 0x1, 0x1, 0x1, 'c' }; - TestRepository<Repository> s = new TestRepository<>(src); - RevCommit N = s.commit().parent(B).add("q", - s.blob(BinaryDelta.apply(dst.open(b).getCachedBytes(), delta))) - .create(); - - final TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); - packHeader(pack, 3); - copy(pack, src.open(N)); - copy(pack, src.open(s.parseBody(N).getTree())); - pack.write((Constants.OBJ_REF_DELTA) << 4 | 4); - b.copyRawTo(pack); - deflate(pack, delta); - digest(pack); - - final TemporaryBuffer.Heap inBuf = new TemporaryBuffer.Heap(1024); - final PacketLineOut inPckLine = new PacketLineOut(inBuf); - inPckLine.writeString(ObjectId.zeroId().name() + ' ' + N.name() + ' ' - + "refs/heads/s" + '\0' - + BasePackPushConnection.CAPABILITY_REPORT_STATUS); - inPckLine.end(); - pack.writeTo(inBuf, PM); + try (TestRepository<Repository> s = new TestRepository<>(src)) { + RevCommit N = s.commit().parent(B) + .add("q", + s.blob(BinaryDelta.apply( + dst.open(b).getCachedBytes(), delta))) + .create(); + + final TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); + packHeader(pack, 3); + copy(pack, src.open(N)); + copy(pack, src.open(s.parseBody(N).getTree())); + pack.write((Constants.OBJ_REF_DELTA) << 4 | 4); + b.copyRawTo(pack); + deflate(pack, delta); + digest(pack); + + final TemporaryBuffer.Heap inBuf = new TemporaryBuffer.Heap(1024); + final PacketLineOut inPckLine = new PacketLineOut(inBuf); + inPckLine.writeString(ObjectId.zeroId().name() + ' ' + N.name() + + ' ' + "refs/heads/s" + '\0' + + BasePackPushConnection.CAPABILITY_REPORT_STATUS); + inPckLine.end(); + pack.writeTo(inBuf, PM); + + final TemporaryBuffer.Heap outBuf = new TemporaryBuffer.Heap(1024); + final ReceivePack rp = new ReceivePack(dst); + rp.setCheckReceivedObjects(true); + rp.setCheckReferencedObjectsAreReachable(true); + rp.setAdvertiseRefsHook(new HidePrivateHook()); + try { + receive(rp, inBuf, outBuf); + fail("Expected UnpackException"); + } catch (UnpackException failed) { + Throwable err = failed.getCause(); + assertTrue(err instanceof MissingObjectException); + MissingObjectException moe = (MissingObjectException) err; + assertEquals(b, moe.getObjectId()); + } - final TemporaryBuffer.Heap outBuf = new TemporaryBuffer.Heap(1024); - final ReceivePack rp = new ReceivePack(dst); - rp.setCheckReceivedObjects(true); - rp.setCheckReferencedObjectsAreReachable(true); - rp.setAdvertiseRefsHook(new HidePrivateHook()); - try { - receive(rp, inBuf, outBuf); - fail("Expected UnpackException"); - } catch (UnpackException failed) { - Throwable err = failed.getCause(); - assertTrue(err instanceof MissingObjectException); - MissingObjectException moe = (MissingObjectException) err; - assertEquals(b, moe.getObjectId()); + final PacketLineIn r = asPacketLineIn(outBuf); + String master = r.readString(); + int nul = master.indexOf('\0'); + assertTrue("has capability list", nul > 0); + assertEquals(B.name() + ' ' + R_MASTER, master.substring(0, nul)); + assertSame(PacketLineIn.END, r.readString()); + + assertEquals("unpack error Missing blob " + b.name(), + r.readString()); + assertEquals("ng refs/heads/s n/a (unpacker error)", + r.readString()); + assertSame(PacketLineIn.END, r.readString()); } - - final PacketLineIn r = asPacketLineIn(outBuf); - String master = r.readString(); - int nul = master.indexOf('\0'); - assertTrue("has capability list", nul > 0); - assertEquals(B.name() + ' ' + R_MASTER, master.substring(0, nul)); - assertSame(PacketLineIn.END, r.readString()); - - assertEquals("unpack error Missing blob " + b.name(), r.readString()); - assertEquals("ng refs/heads/s n/a (unpacker error)", r.readString()); - assertSame(PacketLineIn.END, r.readString()); } @Test public void testUsingHiddenCommonBlobFails() throws Exception { // Try to use the 'b' blob that is hidden. // - TestRepository<Repository> s = new TestRepository<>(src); - RevCommit N = s.commit().parent(B).add("q", s.blob("b")).create(); - - // But don't include it in the pack. - // - final TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); - packHeader(pack, 2); - copy(pack, src.open(N)); - copy(pack,src.open(s.parseBody(N).getTree())); - digest(pack); - - final TemporaryBuffer.Heap inBuf = new TemporaryBuffer.Heap(1024); - final PacketLineOut inPckLine = new PacketLineOut(inBuf); - inPckLine.writeString(ObjectId.zeroId().name() + ' ' + N.name() + ' ' - + "refs/heads/s" + '\0' - + BasePackPushConnection.CAPABILITY_REPORT_STATUS); - inPckLine.end(); - pack.writeTo(inBuf, PM); + try (TestRepository<Repository> s = new TestRepository<>(src)) { + RevCommit N = s.commit().parent(B).add("q", s.blob("b")).create(); + + // But don't include it in the pack. + // + final TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); + packHeader(pack, 2); + copy(pack, src.open(N)); + copy(pack, src.open(s.parseBody(N).getTree())); + digest(pack); + + final TemporaryBuffer.Heap inBuf = new TemporaryBuffer.Heap(1024); + final PacketLineOut inPckLine = new PacketLineOut(inBuf); + inPckLine.writeString(ObjectId.zeroId().name() + ' ' + N.name() + + ' ' + "refs/heads/s" + '\0' + + BasePackPushConnection.CAPABILITY_REPORT_STATUS); + inPckLine.end(); + pack.writeTo(inBuf, PM); + + final TemporaryBuffer.Heap outBuf = new TemporaryBuffer.Heap(1024); + final ReceivePack rp = new ReceivePack(dst); + rp.setCheckReceivedObjects(true); + rp.setCheckReferencedObjectsAreReachable(true); + rp.setAdvertiseRefsHook(new HidePrivateHook()); + try { + receive(rp, inBuf, outBuf); + fail("Expected UnpackException"); + } catch (UnpackException failed) { + Throwable err = failed.getCause(); + assertTrue(err instanceof MissingObjectException); + MissingObjectException moe = (MissingObjectException) err; + assertEquals(b, moe.getObjectId()); + } - final TemporaryBuffer.Heap outBuf = new TemporaryBuffer.Heap(1024); - final ReceivePack rp = new ReceivePack(dst); - rp.setCheckReceivedObjects(true); - rp.setCheckReferencedObjectsAreReachable(true); - rp.setAdvertiseRefsHook(new HidePrivateHook()); - try { - receive(rp, inBuf, outBuf); - fail("Expected UnpackException"); - } catch (UnpackException failed) { - Throwable err = failed.getCause(); - assertTrue(err instanceof MissingObjectException); - MissingObjectException moe = (MissingObjectException) err; - assertEquals(b, moe.getObjectId()); + final PacketLineIn r = asPacketLineIn(outBuf); + String master = r.readString(); + int nul = master.indexOf('\0'); + assertTrue("has capability list", nul > 0); + assertEquals(B.name() + ' ' + R_MASTER, master.substring(0, nul)); + assertSame(PacketLineIn.END, r.readString()); + + assertEquals("unpack error Missing blob " + b.name(), + r.readString()); + assertEquals("ng refs/heads/s n/a (unpacker error)", + r.readString()); + assertSame(PacketLineIn.END, r.readString()); } - - final PacketLineIn r = asPacketLineIn(outBuf); - String master = r.readString(); - int nul = master.indexOf('\0'); - assertTrue("has capability list", nul > 0); - assertEquals(B.name() + ' ' + R_MASTER, master.substring(0, nul)); - assertSame(PacketLineIn.END, r.readString()); - - assertEquals("unpack error Missing blob " + b.name(), r.readString()); - assertEquals("ng refs/heads/s n/a (unpacker error)", r.readString()); - assertSame(PacketLineIn.END, r.readString()); } @Test public void testUsingUnknownBlobFails() throws Exception { // Try to use the 'n' blob that is not on the server. // - TestRepository<Repository> s = new TestRepository<>(src); - RevBlob n = s.blob("n"); - RevCommit N = s.commit().parent(B).add("q", n).create(); - - // But don't include it in the pack. - // - final TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); - packHeader(pack, 2); - copy(pack, src.open(N)); - copy(pack,src.open(s.parseBody(N).getTree())); - digest(pack); - - final TemporaryBuffer.Heap inBuf = new TemporaryBuffer.Heap(1024); - final PacketLineOut inPckLine = new PacketLineOut(inBuf); - inPckLine.writeString(ObjectId.zeroId().name() + ' ' + N.name() + ' ' - + "refs/heads/s" + '\0' - + BasePackPushConnection.CAPABILITY_REPORT_STATUS); - inPckLine.end(); - pack.writeTo(inBuf, PM); + try (TestRepository<Repository> s = new TestRepository<>(src)) { + RevBlob n = s.blob("n"); + RevCommit N = s.commit().parent(B).add("q", n).create(); + + // But don't include it in the pack. + // + final TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); + packHeader(pack, 2); + copy(pack, src.open(N)); + copy(pack, src.open(s.parseBody(N).getTree())); + digest(pack); + + final TemporaryBuffer.Heap inBuf = new TemporaryBuffer.Heap(1024); + final PacketLineOut inPckLine = new PacketLineOut(inBuf); + inPckLine.writeString(ObjectId.zeroId().name() + ' ' + N.name() + + ' ' + "refs/heads/s" + '\0' + + BasePackPushConnection.CAPABILITY_REPORT_STATUS); + inPckLine.end(); + pack.writeTo(inBuf, PM); + + final TemporaryBuffer.Heap outBuf = new TemporaryBuffer.Heap(1024); + final ReceivePack rp = new ReceivePack(dst); + rp.setCheckReceivedObjects(true); + rp.setCheckReferencedObjectsAreReachable(true); + rp.setAdvertiseRefsHook(new HidePrivateHook()); + try { + receive(rp, inBuf, outBuf); + fail("Expected UnpackException"); + } catch (UnpackException failed) { + Throwable err = failed.getCause(); + assertTrue(err instanceof MissingObjectException); + MissingObjectException moe = (MissingObjectException) err; + assertEquals(n, moe.getObjectId()); + } - final TemporaryBuffer.Heap outBuf = new TemporaryBuffer.Heap(1024); - final ReceivePack rp = new ReceivePack(dst); - rp.setCheckReceivedObjects(true); - rp.setCheckReferencedObjectsAreReachable(true); - rp.setAdvertiseRefsHook(new HidePrivateHook()); - try { - receive(rp, inBuf, outBuf); - fail("Expected UnpackException"); - } catch (UnpackException failed) { - Throwable err = failed.getCause(); - assertTrue(err instanceof MissingObjectException); - MissingObjectException moe = (MissingObjectException) err; - assertEquals(n, moe.getObjectId()); + final PacketLineIn r = asPacketLineIn(outBuf); + String master = r.readString(); + int nul = master.indexOf('\0'); + assertTrue("has capability list", nul > 0); + assertEquals(B.name() + ' ' + R_MASTER, master.substring(0, nul)); + assertSame(PacketLineIn.END, r.readString()); + + assertEquals("unpack error Missing blob " + n.name(), + r.readString()); + assertEquals("ng refs/heads/s n/a (unpacker error)", + r.readString()); + assertSame(PacketLineIn.END, r.readString()); } - - final PacketLineIn r = asPacketLineIn(outBuf); - String master = r.readString(); - int nul = master.indexOf('\0'); - assertTrue("has capability list", nul > 0); - assertEquals(B.name() + ' ' + R_MASTER, master.substring(0, nul)); - assertSame(PacketLineIn.END, r.readString()); - - assertEquals("unpack error Missing blob " + n.name(), r.readString()); - assertEquals("ng refs/heads/s n/a (unpacker error)", r.readString()); - assertSame(PacketLineIn.END, r.readString()); } @Test @@ -509,75 +524,79 @@ public class ReceivePackAdvertiseRefsHookTest extends LocalDiskRepositoryTestCas .append(" url = -upayload.sh\n") .toString(); - TestRepository<Repository> s = new TestRepository<>(src); - RevBlob blob = s.blob(fakeGitmodules); - RevCommit N = s.commit().parent(B) - .add(".gitmodules", blob).create(); - RevTree t = s.parseBody(N).getTree(); - - final TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); - packHeader(pack, 3); - copy(pack, src.open(N)); - copy(pack, src.open(t)); - copy(pack, src.open(blob)); - digest(pack); - - final TemporaryBuffer.Heap inBuf = new TemporaryBuffer.Heap(1024); - final PacketLineOut inPckLine = new PacketLineOut(inBuf); - inPckLine.writeString(ObjectId.zeroId().name() + ' ' + N.name() + ' ' - + "refs/heads/s" + '\0' - + BasePackPushConnection.CAPABILITY_REPORT_STATUS); - inPckLine.end(); - pack.writeTo(inBuf, PM); - return inBuf; + try (TestRepository<Repository> s = new TestRepository<>(src)) { + RevBlob blob = s.blob(fakeGitmodules); + RevCommit N = s.commit().parent(B).add(".gitmodules", blob) + .create(); + RevTree t = s.parseBody(N).getTree(); + + final TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); + packHeader(pack, 3); + copy(pack, src.open(N)); + copy(pack, src.open(t)); + copy(pack, src.open(blob)); + digest(pack); + + final TemporaryBuffer.Heap inBuf = new TemporaryBuffer.Heap(1024); + final PacketLineOut inPckLine = new PacketLineOut(inBuf); + inPckLine.writeString(ObjectId.zeroId().name() + ' ' + N.name() + + ' ' + "refs/heads/s" + '\0' + + BasePackPushConnection.CAPABILITY_REPORT_STATUS); + inPckLine.end(); + pack.writeTo(inBuf, PM); + return inBuf; + } } @Test public void testUsingUnknownTreeFails() throws Exception { - TestRepository<Repository> s = new TestRepository<>(src); - RevCommit N = s.commit().parent(B).add("q", s.blob("a")).create(); - RevTree t = s.parseBody(N).getTree(); - - // Don't include the tree in the pack. - // - final TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); - packHeader(pack, 1); - copy(pack, src.open(N)); - digest(pack); - - final TemporaryBuffer.Heap inBuf = new TemporaryBuffer.Heap(1024); - final PacketLineOut inPckLine = new PacketLineOut(inBuf); - inPckLine.writeString(ObjectId.zeroId().name() + ' ' + N.name() + ' ' - + "refs/heads/s" + '\0' - + BasePackPushConnection.CAPABILITY_REPORT_STATUS); - inPckLine.end(); - pack.writeTo(inBuf, PM); + try (TestRepository<Repository> s = new TestRepository<>(src)) { + RevCommit N = s.commit().parent(B).add("q", s.blob("a")).create(); + RevTree t = s.parseBody(N).getTree(); + + // Don't include the tree in the pack. + // + final TemporaryBuffer.Heap pack = new TemporaryBuffer.Heap(1024); + packHeader(pack, 1); + copy(pack, src.open(N)); + digest(pack); + + final TemporaryBuffer.Heap inBuf = new TemporaryBuffer.Heap(1024); + final PacketLineOut inPckLine = new PacketLineOut(inBuf); + inPckLine.writeString(ObjectId.zeroId().name() + ' ' + N.name() + + ' ' + "refs/heads/s" + '\0' + + BasePackPushConnection.CAPABILITY_REPORT_STATUS); + inPckLine.end(); + pack.writeTo(inBuf, PM); + + final TemporaryBuffer.Heap outBuf = new TemporaryBuffer.Heap(1024); + final ReceivePack rp = new ReceivePack(dst); + rp.setCheckReceivedObjects(true); + rp.setCheckReferencedObjectsAreReachable(true); + rp.setAdvertiseRefsHook(new HidePrivateHook()); + try { + receive(rp, inBuf, outBuf); + fail("Expected UnpackException"); + } catch (UnpackException failed) { + Throwable err = failed.getCause(); + assertTrue(err instanceof MissingObjectException); + MissingObjectException moe = (MissingObjectException) err; + assertEquals(t, moe.getObjectId()); + } - final TemporaryBuffer.Heap outBuf = new TemporaryBuffer.Heap(1024); - final ReceivePack rp = new ReceivePack(dst); - rp.setCheckReceivedObjects(true); - rp.setCheckReferencedObjectsAreReachable(true); - rp.setAdvertiseRefsHook(new HidePrivateHook()); - try { - receive(rp, inBuf, outBuf); - fail("Expected UnpackException"); - } catch (UnpackException failed) { - Throwable err = failed.getCause(); - assertTrue(err instanceof MissingObjectException); - MissingObjectException moe = (MissingObjectException) err; - assertEquals(t, moe.getObjectId()); + final PacketLineIn r = asPacketLineIn(outBuf); + String master = r.readString(); + int nul = master.indexOf('\0'); + assertTrue("has capability list", nul > 0); + assertEquals(B.name() + ' ' + R_MASTER, master.substring(0, nul)); + assertSame(PacketLineIn.END, r.readString()); + + assertEquals("unpack error Missing tree " + t.name(), + r.readString()); + assertEquals("ng refs/heads/s n/a (unpacker error)", + r.readString()); + assertSame(PacketLineIn.END, r.readString()); } - - final PacketLineIn r = asPacketLineIn(outBuf); - String master = r.readString(); - int nul = master.indexOf('\0'); - assertTrue("has capability list", nul > 0); - assertEquals(B.name() + ' ' + R_MASTER, master.substring(0, nul)); - assertSame(PacketLineIn.END, r.readString()); - - assertEquals("unpack error Missing tree " + t.name(), r.readString()); - assertEquals("ng refs/heads/s n/a (unpacker error)", r.readString()); - assertSame(PacketLineIn.END, r.readString()); } private static void packHeader(TemporaryBuffer.Heap tinyPack, int cnt) diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/SideBandOutputStreamTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/SideBandOutputStreamTest.java index b6cf3564c1..0bf9a8026e 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/SideBandOutputStreamTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/SideBandOutputStreamTest.java @@ -77,76 +77,76 @@ public class SideBandOutputStreamTest { @Test public void testWrite_CH_DATA() throws IOException { - @SuppressWarnings("resource" /* java 7 */) - final SideBandOutputStream out = new SideBandOutputStream(CH_DATA, - SMALL_BUF, rawOut); - out.write(new byte[] { 'a', 'b', 'c' }); - out.flush(); + try (SideBandOutputStream out = new SideBandOutputStream(CH_DATA, + SMALL_BUF, rawOut)) { + out.write(new byte[] { 'a', 'b', 'c' }); + out.flush(); + } assertBuffer("0008\001abc"); } @Test public void testWrite_CH_PROGRESS() throws IOException { - @SuppressWarnings("resource" /* java 7 */) - final SideBandOutputStream out = new SideBandOutputStream(CH_PROGRESS, - SMALL_BUF, rawOut); - out.write(new byte[] { 'a', 'b', 'c' }); - out.flush(); + try (SideBandOutputStream out = new SideBandOutputStream(CH_PROGRESS, + SMALL_BUF, rawOut)) { + out.write(new byte[] { 'a', 'b', 'c' }); + out.flush(); + } assertBuffer("0008\002abc"); } @Test public void testWrite_CH_ERROR() throws IOException { - @SuppressWarnings("resource" /* java 7 */) - final SideBandOutputStream out = new SideBandOutputStream(CH_ERROR, - SMALL_BUF, rawOut); - out.write(new byte[] { 'a', 'b', 'c' }); - out.flush(); + try (SideBandOutputStream out = new SideBandOutputStream(CH_ERROR, + SMALL_BUF, rawOut)) { + out.write(new byte[] { 'a', 'b', 'c' }); + out.flush(); + } assertBuffer("0008\003abc"); } @Test public void testWrite_Small() throws IOException { - @SuppressWarnings("resource" /* java 7 */) - final SideBandOutputStream out = new SideBandOutputStream(CH_DATA, - SMALL_BUF, rawOut); - out.write('a'); - out.write('b'); - out.write('c'); - out.flush(); + try (SideBandOutputStream out = new SideBandOutputStream(CH_DATA, + SMALL_BUF, rawOut)) { + out.write('a'); + out.write('b'); + out.write('c'); + out.flush(); + } assertBuffer("0008\001abc"); } @Test public void testWrite_SmallBlocks1() throws IOException { - @SuppressWarnings("resource" /* java 7 */) - final SideBandOutputStream out = new SideBandOutputStream(CH_DATA, 6, - rawOut); - out.write('a'); - out.write('b'); - out.write('c'); - out.flush(); + try (SideBandOutputStream out = new SideBandOutputStream(CH_DATA, 6, + rawOut)) { + out.write('a'); + out.write('b'); + out.write('c'); + out.flush(); + } assertBuffer("0006\001a0006\001b0006\001c"); } @Test public void testWrite_SmallBlocks2() throws IOException { - @SuppressWarnings("resource" /* java 7 */) - final SideBandOutputStream out = new SideBandOutputStream(CH_DATA, 6, - rawOut); - out.write(new byte[] { 'a', 'b', 'c' }); - out.flush(); + try (SideBandOutputStream out = new SideBandOutputStream(CH_DATA, 6, + rawOut)) { + out.write(new byte[] { 'a', 'b', 'c' }); + out.flush(); + } assertBuffer("0006\001a0006\001b0006\001c"); } @Test public void testWrite_SmallBlocks3() throws IOException { - @SuppressWarnings("resource" /* java 7 */) - final SideBandOutputStream out = new SideBandOutputStream(CH_DATA, 7, - rawOut); - out.write('a'); - out.write(new byte[] { 'b', 'c' }); - out.flush(); + try (SideBandOutputStream out = new SideBandOutputStream(CH_DATA, 7, + rawOut)) { + out.write('a'); + out.write(new byte[] { 'b', 'c' }); + out.flush(); + } assertBuffer("0007\001ab0006\001c"); } @@ -158,11 +158,11 @@ public class SideBandOutputStreamTest { buf[i] = (byte) i; } - @SuppressWarnings("resource" /* java 7 */) - final SideBandOutputStream out = new SideBandOutputStream(CH_DATA, - MAX_BUF, rawOut); - out.write(buf); - out.flush(); + try (SideBandOutputStream out = new SideBandOutputStream(CH_DATA, + MAX_BUF, rawOut)) { + out.write(buf); + out.flush(); + } final byte[] act = rawOut.toByteArray(); final String explen = Integer.toString(buf.length + HDR_SIZE, 16); @@ -174,7 +174,6 @@ public class SideBandOutputStreamTest { } } - @SuppressWarnings("resource" /* java 7 */) @Test public void testFlush() throws IOException { final int[] flushCnt = new int[1]; @@ -190,7 +189,10 @@ public class SideBandOutputStreamTest { } }; - new SideBandOutputStream(CH_DATA, SMALL_BUF, mockout).flush(); + try (SideBandOutputStream out = new SideBandOutputStream(CH_DATA, + SMALL_BUF, mockout)) { + out.flush(); + } assertEquals(1, flushCnt[0]); } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/UploadPackTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/UploadPackTest.java index 8acbcce36d..1cbe8a4312 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/UploadPackTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/UploadPackTest.java @@ -128,13 +128,13 @@ public class UploadPackTest { }, null); uri = testProtocol.register(ctx, server); - assertFalse(client.hasObject(commit0.toObjectId())); + assertFalse(client.getObjectDatabase().has(commit0.toObjectId())); // Fetch of the parent of the shallow commit try (Transport tn = testProtocol.open(uri, client, "server")) { tn.fetch(NullProgressMonitor.INSTANCE, Collections.singletonList(new RefSpec(commit0.name()))); - assertTrue(client.hasObject(commit0.toObjectId())); + assertTrue(client.getObjectDatabase().has(commit0.toObjectId())); } } @@ -147,7 +147,7 @@ public class UploadPackTest { testProtocol = generateReachableCommitUploadPackProtocol(); uri = testProtocol.register(ctx, server); - assertFalse(client.hasObject(blob.toObjectId())); + assertFalse(client.getObjectDatabase().has(blob.toObjectId())); try (Transport tn = testProtocol.open(uri, client, "server")) { thrown.expect(TransportException.class); @@ -168,12 +168,12 @@ public class UploadPackTest { testProtocol = generateReachableCommitUploadPackProtocol(); uri = testProtocol.register(ctx, server); - assertFalse(client.hasObject(blob.toObjectId())); + assertFalse(client.getObjectDatabase().has(blob.toObjectId())); try (Transport tn = testProtocol.open(uri, client, "server")) { tn.fetch(NullProgressMonitor.INSTANCE, Collections.singletonList(new RefSpec(blob.name()))); - assertTrue(client.hasObject(blob.toObjectId())); + assertTrue(client.getObjectDatabase().has(blob.toObjectId())); } } @@ -186,7 +186,7 @@ public class UploadPackTest { testProtocol = generateReachableCommitUploadPackProtocol(); uri = testProtocol.register(ctx, server); - assertFalse(client.hasObject(blob.toObjectId())); + assertFalse(client.getObjectDatabase().has(blob.toObjectId())); try (Transport tn = testProtocol.open(uri, client, "server")) { thrown.expect(TransportException.class); @@ -200,224 +200,233 @@ public class UploadPackTest { @Test public void testFetchWithBlobNoneFilter() throws Exception { InMemoryRepository server2 = newRepo("server2"); - TestRepository<InMemoryRepository> remote2 = - new TestRepository<>(server2); - RevBlob blob1 = remote2.blob("foobar"); - RevBlob blob2 = remote2.blob("fooba"); - RevTree tree = remote2.tree(remote2.file("1", blob1), - remote2.file("2", blob2)); - RevCommit commit = remote2.commit(tree); - remote2.update("master", commit); - - server2.getConfig().setBoolean("uploadpack", null, "allowfilter", true); - - testProtocol = new TestProtocol<>( - new UploadPackFactory<Object>() { - @Override - public UploadPack create(Object req, Repository db) - throws ServiceNotEnabledException, - ServiceNotAuthorizedException { - UploadPack up = new UploadPack(db); - return up; - } - }, null); - uri = testProtocol.register(ctx, server2); - - try (Transport tn = testProtocol.open(uri, client, "server2")) { - tn.setFilterBlobLimit(0); - tn.fetch(NullProgressMonitor.INSTANCE, - Collections.singletonList(new RefSpec(commit.name()))); - assertTrue(client.hasObject(tree.toObjectId())); - assertFalse(client.hasObject(blob1.toObjectId())); - assertFalse(client.hasObject(blob2.toObjectId())); + try (TestRepository<InMemoryRepository> remote2 = new TestRepository<>( + server2)) { + RevBlob blob1 = remote2.blob("foobar"); + RevBlob blob2 = remote2.blob("fooba"); + RevTree tree = remote2.tree(remote2.file("1", blob1), + remote2.file("2", blob2)); + RevCommit commit = remote2.commit(tree); + remote2.update("master", commit); + + server2.getConfig().setBoolean("uploadpack", null, "allowfilter", + true); + + testProtocol = new TestProtocol<>(new UploadPackFactory<Object>() { + @Override + public UploadPack create(Object req, Repository db) + throws ServiceNotEnabledException, + ServiceNotAuthorizedException { + UploadPack up = new UploadPack(db); + return up; + } + }, null); + uri = testProtocol.register(ctx, server2); + + try (Transport tn = testProtocol.open(uri, client, "server2")) { + tn.setFilterBlobLimit(0); + tn.fetch(NullProgressMonitor.INSTANCE, + Collections.singletonList(new RefSpec(commit.name()))); + assertTrue(client.getObjectDatabase().has(tree.toObjectId())); + assertFalse(client.getObjectDatabase().has(blob1.toObjectId())); + assertFalse(client.getObjectDatabase().has(blob2.toObjectId())); + } } } @Test public void testFetchExplicitBlobWithFilter() throws Exception { InMemoryRepository server2 = newRepo("server2"); - TestRepository<InMemoryRepository> remote2 = - new TestRepository<>(server2); - RevBlob blob1 = remote2.blob("foobar"); - RevBlob blob2 = remote2.blob("fooba"); - RevTree tree = remote2.tree(remote2.file("1", blob1), - remote2.file("2", blob2)); - RevCommit commit = remote2.commit(tree); - remote2.update("master", commit); - remote2.update("a_blob", blob1); - - server2.getConfig().setBoolean("uploadpack", null, "allowfilter", true); - - testProtocol = new TestProtocol<>( - new UploadPackFactory<Object>() { - @Override - public UploadPack create(Object req, Repository db) - throws ServiceNotEnabledException, - ServiceNotAuthorizedException { - UploadPack up = new UploadPack(db); - return up; - } - }, null); - uri = testProtocol.register(ctx, server2); - - try (Transport tn = testProtocol.open(uri, client, "server2")) { - tn.setFilterBlobLimit(0); - tn.fetch(NullProgressMonitor.INSTANCE, Arrays.asList( - new RefSpec(commit.name()), - new RefSpec(blob1.name()))); - assertTrue(client.hasObject(tree.toObjectId())); - assertTrue(client.hasObject(blob1.toObjectId())); - assertFalse(client.hasObject(blob2.toObjectId())); + try (TestRepository<InMemoryRepository> remote2 = new TestRepository<>( + server2)) { + RevBlob blob1 = remote2.blob("foobar"); + RevBlob blob2 = remote2.blob("fooba"); + RevTree tree = remote2.tree(remote2.file("1", blob1), + remote2.file("2", blob2)); + RevCommit commit = remote2.commit(tree); + remote2.update("master", commit); + remote2.update("a_blob", blob1); + + server2.getConfig().setBoolean("uploadpack", null, "allowfilter", + true); + + testProtocol = new TestProtocol<>(new UploadPackFactory<Object>() { + @Override + public UploadPack create(Object req, Repository db) + throws ServiceNotEnabledException, + ServiceNotAuthorizedException { + UploadPack up = new UploadPack(db); + return up; + } + }, null); + uri = testProtocol.register(ctx, server2); + + try (Transport tn = testProtocol.open(uri, client, "server2")) { + tn.setFilterBlobLimit(0); + tn.fetch(NullProgressMonitor.INSTANCE, Arrays.asList( + new RefSpec(commit.name()), new RefSpec(blob1.name()))); + assertTrue(client.getObjectDatabase().has(tree.toObjectId())); + assertTrue(client.getObjectDatabase().has(blob1.toObjectId())); + assertFalse(client.getObjectDatabase().has(blob2.toObjectId())); + } } } @Test public void testFetchWithBlobLimitFilter() throws Exception { InMemoryRepository server2 = newRepo("server2"); - TestRepository<InMemoryRepository> remote2 = - new TestRepository<>(server2); - RevBlob longBlob = remote2.blob("foobar"); - RevBlob shortBlob = remote2.blob("fooba"); - RevTree tree = remote2.tree(remote2.file("1", longBlob), - remote2.file("2", shortBlob)); - RevCommit commit = remote2.commit(tree); - remote2.update("master", commit); - - server2.getConfig().setBoolean("uploadpack", null, "allowfilter", true); - - testProtocol = new TestProtocol<>( - new UploadPackFactory<Object>() { - @Override - public UploadPack create(Object req, Repository db) - throws ServiceNotEnabledException, - ServiceNotAuthorizedException { - UploadPack up = new UploadPack(db); - return up; - } - }, null); - uri = testProtocol.register(ctx, server2); - - try (Transport tn = testProtocol.open(uri, client, "server2")) { - tn.setFilterBlobLimit(5); - tn.fetch(NullProgressMonitor.INSTANCE, - Collections.singletonList(new RefSpec(commit.name()))); - assertFalse(client.hasObject(longBlob.toObjectId())); - assertTrue(client.hasObject(shortBlob.toObjectId())); + try (TestRepository<InMemoryRepository> remote2 = new TestRepository<>( + server2)) { + RevBlob longBlob = remote2.blob("foobar"); + RevBlob shortBlob = remote2.blob("fooba"); + RevTree tree = remote2.tree(remote2.file("1", longBlob), + remote2.file("2", shortBlob)); + RevCommit commit = remote2.commit(tree); + remote2.update("master", commit); + + server2.getConfig().setBoolean("uploadpack", null, "allowfilter", + true); + + testProtocol = new TestProtocol<>(new UploadPackFactory<Object>() { + @Override + public UploadPack create(Object req, Repository db) + throws ServiceNotEnabledException, + ServiceNotAuthorizedException { + UploadPack up = new UploadPack(db); + return up; + } + }, null); + uri = testProtocol.register(ctx, server2); + + try (Transport tn = testProtocol.open(uri, client, "server2")) { + tn.setFilterBlobLimit(5); + tn.fetch(NullProgressMonitor.INSTANCE, + Collections.singletonList(new RefSpec(commit.name()))); + assertFalse( + client.getObjectDatabase().has(longBlob.toObjectId())); + assertTrue( + client.getObjectDatabase().has(shortBlob.toObjectId())); + } } } @Test public void testFetchExplicitBlobWithFilterAndBitmaps() throws Exception { InMemoryRepository server2 = newRepo("server2"); - TestRepository<InMemoryRepository> remote2 = - new TestRepository<>(server2); - RevBlob blob1 = remote2.blob("foobar"); - RevBlob blob2 = remote2.blob("fooba"); - RevTree tree = remote2.tree(remote2.file("1", blob1), - remote2.file("2", blob2)); - RevCommit commit = remote2.commit(tree); - remote2.update("master", commit); - remote2.update("a_blob", blob1); - - server2.getConfig().setBoolean("uploadpack", null, "allowfilter", true); - - // generate bitmaps - new DfsGarbageCollector(server2).pack(null); - server2.scanForRepoChanges(); - - testProtocol = new TestProtocol<>( - new UploadPackFactory<Object>() { - @Override - public UploadPack create(Object req, Repository db) - throws ServiceNotEnabledException, - ServiceNotAuthorizedException { - UploadPack up = new UploadPack(db); - return up; - } - }, null); - uri = testProtocol.register(ctx, server2); - - try (Transport tn = testProtocol.open(uri, client, "server2")) { - tn.setFilterBlobLimit(0); - tn.fetch(NullProgressMonitor.INSTANCE, Arrays.asList( - new RefSpec(commit.name()), - new RefSpec(blob1.name()))); - assertTrue(client.hasObject(blob1.toObjectId())); - assertFalse(client.hasObject(blob2.toObjectId())); + try (TestRepository<InMemoryRepository> remote2 = new TestRepository<>( + server2)) { + RevBlob blob1 = remote2.blob("foobar"); + RevBlob blob2 = remote2.blob("fooba"); + RevTree tree = remote2.tree(remote2.file("1", blob1), + remote2.file("2", blob2)); + RevCommit commit = remote2.commit(tree); + remote2.update("master", commit); + remote2.update("a_blob", blob1); + + server2.getConfig().setBoolean("uploadpack", null, "allowfilter", + true); + + // generate bitmaps + new DfsGarbageCollector(server2).pack(null); + server2.scanForRepoChanges(); + + testProtocol = new TestProtocol<>(new UploadPackFactory<Object>() { + @Override + public UploadPack create(Object req, Repository db) + throws ServiceNotEnabledException, + ServiceNotAuthorizedException { + UploadPack up = new UploadPack(db); + return up; + } + }, null); + uri = testProtocol.register(ctx, server2); + + try (Transport tn = testProtocol.open(uri, client, "server2")) { + tn.setFilterBlobLimit(0); + tn.fetch(NullProgressMonitor.INSTANCE, Arrays.asList( + new RefSpec(commit.name()), new RefSpec(blob1.name()))); + assertTrue(client.getObjectDatabase().has(blob1.toObjectId())); + assertFalse(client.getObjectDatabase().has(blob2.toObjectId())); + } } } @Test public void testFetchWithBlobLimitFilterAndBitmaps() throws Exception { InMemoryRepository server2 = newRepo("server2"); - TestRepository<InMemoryRepository> remote2 = - new TestRepository<>(server2); - RevBlob longBlob = remote2.blob("foobar"); - RevBlob shortBlob = remote2.blob("fooba"); - RevTree tree = remote2.tree(remote2.file("1", longBlob), - remote2.file("2", shortBlob)); - RevCommit commit = remote2.commit(tree); - remote2.update("master", commit); - - server2.getConfig().setBoolean("uploadpack", null, "allowfilter", true); - - // generate bitmaps - new DfsGarbageCollector(server2).pack(null); - server2.scanForRepoChanges(); - - testProtocol = new TestProtocol<>( - new UploadPackFactory<Object>() { - @Override - public UploadPack create(Object req, Repository db) - throws ServiceNotEnabledException, - ServiceNotAuthorizedException { - UploadPack up = new UploadPack(db); - return up; - } - }, null); - uri = testProtocol.register(ctx, server2); - - try (Transport tn = testProtocol.open(uri, client, "server2")) { - tn.setFilterBlobLimit(5); - tn.fetch(NullProgressMonitor.INSTANCE, - Collections.singletonList(new RefSpec(commit.name()))); - assertFalse(client.hasObject(longBlob.toObjectId())); - assertTrue(client.hasObject(shortBlob.toObjectId())); + try (TestRepository<InMemoryRepository> remote2 = new TestRepository<>( + server2)) { + RevBlob longBlob = remote2.blob("foobar"); + RevBlob shortBlob = remote2.blob("fooba"); + RevTree tree = remote2.tree(remote2.file("1", longBlob), + remote2.file("2", shortBlob)); + RevCommit commit = remote2.commit(tree); + remote2.update("master", commit); + + server2.getConfig().setBoolean("uploadpack", null, "allowfilter", + true); + + // generate bitmaps + new DfsGarbageCollector(server2).pack(null); + server2.scanForRepoChanges(); + + testProtocol = new TestProtocol<>(new UploadPackFactory<Object>() { + @Override + public UploadPack create(Object req, Repository db) + throws ServiceNotEnabledException, + ServiceNotAuthorizedException { + UploadPack up = new UploadPack(db); + return up; + } + }, null); + uri = testProtocol.register(ctx, server2); + + try (Transport tn = testProtocol.open(uri, client, "server2")) { + tn.setFilterBlobLimit(5); + tn.fetch(NullProgressMonitor.INSTANCE, + Collections.singletonList(new RefSpec(commit.name()))); + assertFalse( + client.getObjectDatabase().has(longBlob.toObjectId())); + assertTrue( + client.getObjectDatabase().has(shortBlob.toObjectId())); + } } } @Test public void testFetchWithNonSupportingServer() throws Exception { InMemoryRepository server2 = newRepo("server2"); - TestRepository<InMemoryRepository> remote2 = - new TestRepository<>(server2); - RevBlob blob = remote2.blob("foo"); - RevTree tree = remote2.tree(remote2.file("1", blob)); - RevCommit commit = remote2.commit(tree); - remote2.update("master", commit); - - server2.getConfig().setBoolean("uploadpack", null, "allowfilter", false); - - testProtocol = new TestProtocol<>( - new UploadPackFactory<Object>() { - @Override - public UploadPack create(Object req, Repository db) - throws ServiceNotEnabledException, - ServiceNotAuthorizedException { - UploadPack up = new UploadPack(db); - return up; - } - }, null); - uri = testProtocol.register(ctx, server2); + try (TestRepository<InMemoryRepository> remote2 = new TestRepository<>( + server2)) { + RevBlob blob = remote2.blob("foo"); + RevTree tree = remote2.tree(remote2.file("1", blob)); + RevCommit commit = remote2.commit(tree); + remote2.update("master", commit); + + server2.getConfig().setBoolean("uploadpack", null, "allowfilter", + false); + + testProtocol = new TestProtocol<>(new UploadPackFactory<Object>() { + @Override + public UploadPack create(Object req, Repository db) + throws ServiceNotEnabledException, + ServiceNotAuthorizedException { + UploadPack up = new UploadPack(db); + return up; + } + }, null); + uri = testProtocol.register(ctx, server2); - try (Transport tn = testProtocol.open(uri, client, "server2")) { - tn.setFilterBlobLimit(0); + try (Transport tn = testProtocol.open(uri, client, "server2")) { + tn.setFilterBlobLimit(0); - thrown.expect(TransportException.class); - thrown.expectMessage("filter requires server to advertise that capability"); + thrown.expect(TransportException.class); + thrown.expectMessage( + "filter requires server to advertise that capability"); - tn.fetch(NullProgressMonitor.INSTANCE, - Collections.singletonList(new RefSpec(commit.name()))); + tn.fetch(NullProgressMonitor.INSTANCE, + Collections.singletonList(new RefSpec(commit.name()))); + } } } @@ -965,10 +974,10 @@ public class UploadPackTest { assertThat(pckIn.readString(), theInstance(PacketLineIn.DELIM)); assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertFalse(client.hasObject(fooParent.toObjectId())); - assertTrue(client.hasObject(fooChild.toObjectId())); - assertFalse(client.hasObject(barParent.toObjectId())); - assertTrue(client.hasObject(barChild.toObjectId())); + assertFalse(client.getObjectDatabase().has(fooParent.toObjectId())); + assertTrue(client.getObjectDatabase().has(fooChild.toObjectId())); + assertFalse(client.getObjectDatabase().has(barParent.toObjectId())); + assertTrue(client.getObjectDatabase().has(barChild.toObjectId())); } @Test @@ -992,10 +1001,10 @@ public class UploadPackTest { assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertFalse(client.hasObject(fooParent.toObjectId())); - assertTrue(client.hasObject(fooChild.toObjectId())); - assertTrue(client.hasObject(barParent.toObjectId())); - assertTrue(client.hasObject(barChild.toObjectId())); + assertFalse(client.getObjectDatabase().has(fooParent.toObjectId())); + assertTrue(client.getObjectDatabase().has(fooChild.toObjectId())); + assertTrue(client.getObjectDatabase().has(barParent.toObjectId())); + assertTrue(client.getObjectDatabase().has(barChild.toObjectId())); } @Test @@ -1078,7 +1087,7 @@ public class UploadPackTest { PacketLineIn pckIn = new PacketLineIn(recvStream); assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertFalse(client.hasObject(tag.toObjectId())); + assertFalse(client.getObjectDatabase().has(tag.toObjectId())); // With tag. recvStream = uploadPackV2( @@ -1091,7 +1100,7 @@ public class UploadPackTest { pckIn = new PacketLineIn(recvStream); assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertTrue(client.hasObject(tag.toObjectId())); + assertTrue(client.getObjectDatabase().has(tag.toObjectId())); } @Test @@ -1149,8 +1158,8 @@ public class UploadPackTest { PacketLineIn pckIn = new PacketLineIn(recvStream); assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertTrue(client.hasObject(barChild.toObjectId())); - assertFalse(client.hasObject(commonParent.toObjectId())); + assertTrue(client.getObjectDatabase().has(barChild.toObjectId())); + assertFalse(client.getObjectDatabase().has(commonParent.toObjectId())); // With shallow, the server knows that we don't have // commonParent, so it sends it. @@ -1165,7 +1174,7 @@ public class UploadPackTest { pckIn = new PacketLineIn(recvStream); assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertTrue(client.hasObject(commonParent.toObjectId())); + assertTrue(client.getObjectDatabase().has(commonParent.toObjectId())); } @Test @@ -1188,8 +1197,8 @@ public class UploadPackTest { assertThat(pckIn.readString(), theInstance(PacketLineIn.DELIM)); assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertTrue(client.hasObject(child.toObjectId())); - assertFalse(client.hasObject(parent.toObjectId())); + assertTrue(client.getObjectDatabase().has(child.toObjectId())); + assertFalse(client.getObjectDatabase().has(parent.toObjectId())); // Without that, the parent is sent too. recvStream = uploadPackV2( @@ -1201,7 +1210,7 @@ public class UploadPackTest { pckIn = new PacketLineIn(recvStream); assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertTrue(client.hasObject(parent.toObjectId())); + assertTrue(client.getObjectDatabase().has(parent.toObjectId())); } @Test @@ -1268,15 +1277,15 @@ public class UploadPackTest { // The server does not send this because it is committed // earlier than the given deepen-since time. - assertFalse(client.hasObject(tooOld.toObjectId())); + assertFalse(client.getObjectDatabase().has(tooOld.toObjectId())); // The server does not send this because the client claims to // have it. - assertFalse(client.hasObject(boundary.toObjectId())); + assertFalse(client.getObjectDatabase().has(boundary.toObjectId())); // The server sends both these commits. - assertTrue(client.hasObject(beyondBoundary.toObjectId())); - assertTrue(client.hasObject(merge.toObjectId())); + assertTrue(client.getObjectDatabase().has(beyondBoundary.toObjectId())); + assertTrue(client.getObjectDatabase().has(merge.toObjectId())); } @Test @@ -1316,9 +1325,9 @@ public class UploadPackTest { parsePack(recvStream); // Only the children are sent. - assertFalse(client.hasObject(base.toObjectId())); - assertTrue(client.hasObject(child1.toObjectId())); - assertTrue(client.hasObject(child2.toObjectId())); + assertFalse(client.getObjectDatabase().has(base.toObjectId())); + assertTrue(client.getObjectDatabase().has(child1.toObjectId())); + assertTrue(client.getObjectDatabase().has(child2.toObjectId())); } @Test @@ -1384,16 +1393,16 @@ public class UploadPackTest { // The server does not send these because they are excluded by // deepen-not. - assertFalse(client.hasObject(side.toObjectId())); - assertFalse(client.hasObject(one.toObjectId())); + assertFalse(client.getObjectDatabase().has(side.toObjectId())); + assertFalse(client.getObjectDatabase().has(one.toObjectId())); // The server does not send this because the client claims to // have it. - assertFalse(client.hasObject(three.toObjectId())); + assertFalse(client.getObjectDatabase().has(three.toObjectId())); // The server sends both these commits. - assertTrue(client.hasObject(merge.toObjectId())); - assertTrue(client.hasObject(two.toObjectId())); + assertTrue(client.getObjectDatabase().has(merge.toObjectId())); + assertTrue(client.getObjectDatabase().has(two.toObjectId())); } @Test @@ -1441,10 +1450,10 @@ public class UploadPackTest { assertThat(pckIn.readString(), theInstance(PacketLineIn.DELIM)); assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertFalse(client.hasObject(one.toObjectId())); - assertFalse(client.hasObject(two.toObjectId())); - assertTrue(client.hasObject(three.toObjectId())); - assertTrue(client.hasObject(four.toObjectId())); + assertFalse(client.getObjectDatabase().has(one.toObjectId())); + assertFalse(client.getObjectDatabase().has(two.toObjectId())); + assertTrue(client.getObjectDatabase().has(three.toObjectId())); + assertTrue(client.getObjectDatabase().has(four.toObjectId())); } @Test @@ -1485,9 +1494,9 @@ public class UploadPackTest { parsePack(recvStream); // Only the children are sent. - assertFalse(client.hasObject(base.toObjectId())); - assertTrue(client.hasObject(child1.toObjectId())); - assertTrue(client.hasObject(child2.toObjectId())); + assertFalse(client.getObjectDatabase().has(base.toObjectId())); + assertTrue(client.getObjectDatabase().has(child1.toObjectId())); + assertTrue(client.getObjectDatabase().has(child2.toObjectId())); } @Test @@ -1538,8 +1547,8 @@ public class UploadPackTest { assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertFalse(client.hasObject(big.toObjectId())); - assertTrue(client.hasObject(small.toObjectId())); + assertFalse(client.getObjectDatabase().has(big.toObjectId())); + assertTrue(client.getObjectDatabase().has(small.toObjectId())); } @Test @@ -1610,9 +1619,9 @@ public class UploadPackTest { assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertTrue(client.hasObject(one.toObjectId())); - assertTrue(client.hasObject(two.toObjectId())); - assertFalse(client.hasObject(three.toObjectId())); + assertTrue(client.getObjectDatabase().has(one.toObjectId())); + assertTrue(client.getObjectDatabase().has(two.toObjectId())); + assertFalse(client.getObjectDatabase().has(three.toObjectId())); } @Test @@ -1666,9 +1675,9 @@ public class UploadPackTest { assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertTrue(client.hasObject(one.toObjectId())); - assertTrue(client.hasObject(two.toObjectId())); - assertFalse(client.hasObject(three.toObjectId())); + assertTrue(client.getObjectDatabase().has(one.toObjectId())); + assertTrue(client.getObjectDatabase().has(two.toObjectId())); + assertFalse(client.getObjectDatabase().has(three.toObjectId())); } @Test @@ -1699,7 +1708,7 @@ public class UploadPackTest { // ... but the client does not need the object itself. assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertFalse(client.hasObject(one.toObjectId())); + assertFalse(client.getObjectDatabase().has(one.toObjectId())); } @Test @@ -1728,8 +1737,8 @@ public class UploadPackTest { assertThat(pckIn.readString(), theInstance(PacketLineIn.DELIM)); assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertTrue(client.hasObject(child.toObjectId())); - assertFalse(client.hasObject(parent.toObjectId())); + assertTrue(client.getObjectDatabase().has(child.toObjectId())); + assertFalse(client.getObjectDatabase().has(parent.toObjectId())); } @Test @@ -1765,9 +1774,9 @@ public class UploadPackTest { assertThat(pckIn.readString(), is("packfile")); parsePack(recvStream); - assertTrue(client.hasObject(one.toObjectId())); - assertTrue(client.hasObject(two.toObjectId())); - assertTrue(client.hasObject(three.toObjectId())); + assertTrue(client.getObjectDatabase().has(one.toObjectId())); + assertTrue(client.getObjectDatabase().has(two.toObjectId())); + assertTrue(client.getObjectDatabase().has(three.toObjectId())); } @Test diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/treewalk/FileTreeIteratorTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/treewalk/FileTreeIteratorTest.java index 9a0e7d2eac..754341dfea 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/treewalk/FileTreeIteratorTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/treewalk/FileTreeIteratorTest.java @@ -48,9 +48,11 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeNoException; import java.io.File; import java.io.IOException; +import java.nio.file.InvalidPathException; import java.security.MessageDigest; import java.time.Instant; @@ -668,9 +670,23 @@ public class FileTreeIteratorTest extends RepositoryTestCase { public void testFileModeSymLinkIsNotATree() throws IOException { org.junit.Assume.assumeTrue(FS.DETECTED.supportsSymlinks()); FS fs = db.getFS(); - // mål = target in swedish, just to get som unicode in here + // mål = target in swedish, just to get some unicode in here writeTrashFile("mål/data", "targetdata"); - fs.createSymLink(new File(trash, "länk"), "mål"); + File file = new File(trash, "länk"); + + try { + file.toPath(); + } catch (InvalidPathException e) { + // When executing a test with LANG environment variable set to non + // UTF-8 encoding, it seems that JRE cannot handle Unicode file + // paths. This happens when this test is executed in Bazel as it + // unsets LANG + // (https://docs.bazel.build/versions/master/test-encyclopedia.html#initial-conditions). + // Skip the test if the runtime cannot handle Unicode characters. + assumeNoException(e); + } + + fs.createSymLink(file, "mål"); FileTreeIterator fti = new FileTreeIterator(db); assertFalse(fti.eof()); while (!fti.getEntryPathString().equals("länk")) { diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/FSTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/FSTest.java index 2054e1efa8..99d435100b 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/FSTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/FSTest.java @@ -47,12 +47,14 @@ import static java.time.Instant.EPOCH; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeNoException; import static org.junit.Assume.assumeTrue; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; +import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.attribute.FileTime; import java.nio.file.attribute.PosixFileAttributeView; @@ -101,16 +103,17 @@ public class FSTest { public void testSymlinkAttributes() throws IOException, InterruptedException { Assume.assumeTrue(FS.DETECTED.supportsSymlinks()); FS fs = FS.DETECTED; - File link = new File(trash, "ä"); - File target = new File(trash, "å"); - fs.createSymLink(link, "å"); + File link = new File(trash, "a"); + File target = new File(trash, "b"); + fs.createSymLink(link, "b"); assertTrue(fs.exists(link)); String targetName = fs.readSymLink(link); - assertEquals("å", targetName); + assertEquals("b", targetName); assertTrue(fs.lastModifiedInstant(link).compareTo(EPOCH) > 0); assertTrue(fs.exists(link)); assertFalse(fs.canExecute(link)); - assertEquals(2, fs.length(link)); + // The length of a symbolic link is a length of the target file path. + assertEquals(1, fs.length(link)); assertFalse(fs.exists(target)); assertFalse(fs.isFile(target)); assertFalse(fs.isDirectory(target)); @@ -131,6 +134,32 @@ public class FSTest { } @Test + public void testUnicodeFilePath() throws IOException { + Assume.assumeTrue(FS.DETECTED.supportsSymlinks()); + FS fs = FS.DETECTED; + File link = new File(trash, "ä"); + File target = new File(trash, "å"); + + try { + // Check if the runtime can support Unicode file paths. + link.toPath(); + target.toPath(); + } catch (InvalidPathException e) { + // When executing a test with LANG environment variable set to non + // UTF-8 encoding, it seems that JRE cannot handle Unicode file + // paths. This happens when this test is executed in Bazel as it + // unsets LANG + // (https://docs.bazel.build/versions/master/test-encyclopedia.html#initial-conditions). + // Skip the test if the runtime cannot handle Unicode characters. + assumeNoException(e); + } + + fs.createSymLink(link, "å"); + assertTrue(fs.exists(link)); + assertEquals("å", fs.readSymLink(link)); + } + + @Test public void testExecutableAttributes() throws Exception { FS fs = FS.DETECTED.newInstance(); // If this assumption fails the test is halted and ignored. diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/TemporaryBufferTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/TemporaryBufferTest.java index edcce126bb..9f1395b58a 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/TemporaryBufferTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/TemporaryBufferTest.java @@ -404,16 +404,16 @@ public class TemporaryBufferTest { @Test public void testHeap() throws IOException { - @SuppressWarnings("resource" /* java 7 */) - final TemporaryBuffer b = new TemporaryBuffer.Heap(2 * 8 * 1024); - final byte[] r = new byte[8 * 1024]; - b.write(r); - b.write(r); - try { - b.write(1); - fail("accepted too many bytes of data"); - } catch (IOException e) { - assertEquals("In-memory buffer limit exceeded", e.getMessage()); + try (TemporaryBuffer b = new TemporaryBuffer.Heap(2 * 8 * 1024)) { + final byte[] r = new byte[8 * 1024]; + b.write(r); + b.write(r); + try { + b.write(1); + fail("accepted too many bytes of data"); + } catch (IOException e) { + assertEquals("In-memory buffer limit exceeded", e.getMessage()); + } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/UnionInputStreamTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/UnionInputStreamTest.java index a6e0eedfbc..e38bbfef58 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/UnionInputStreamTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/UnionInputStreamTest.java @@ -69,53 +69,52 @@ public class UnionInputStreamTest { @Test public void testReadSingleBytes() throws IOException { - @SuppressWarnings("resource" /* java 7 */) - final UnionInputStream u = new UnionInputStream(); - - assertTrue(u.isEmpty()); - u.add(new ByteArrayInputStream(new byte[] { 1, 0, 2 })); - u.add(new ByteArrayInputStream(new byte[] { 3 })); - u.add(new ByteArrayInputStream(new byte[] { 4, 5 })); + try (UnionInputStream u = new UnionInputStream()) { + assertTrue(u.isEmpty()); + u.add(new ByteArrayInputStream(new byte[] { 1, 0, 2 })); + u.add(new ByteArrayInputStream(new byte[] { 3 })); + u.add(new ByteArrayInputStream(new byte[] { 4, 5 })); - assertFalse(u.isEmpty()); - assertEquals(3, u.available()); - assertEquals(1, u.read()); - assertEquals(0, u.read()); - assertEquals(2, u.read()); - assertEquals(0, u.available()); + assertFalse(u.isEmpty()); + assertEquals(3, u.available()); + assertEquals(1, u.read()); + assertEquals(0, u.read()); + assertEquals(2, u.read()); + assertEquals(0, u.available()); - assertEquals(3, u.read()); - assertEquals(0, u.available()); + assertEquals(3, u.read()); + assertEquals(0, u.available()); - assertEquals(4, u.read()); - assertEquals(1, u.available()); - assertEquals(5, u.read()); - assertEquals(0, u.available()); - assertEquals(-1, u.read()); + assertEquals(4, u.read()); + assertEquals(1, u.available()); + assertEquals(5, u.read()); + assertEquals(0, u.available()); + assertEquals(-1, u.read()); - assertTrue(u.isEmpty()); - u.add(new ByteArrayInputStream(new byte[] { (byte) 255 })); - assertEquals(255, u.read()); - assertEquals(-1, u.read()); - assertTrue(u.isEmpty()); + assertTrue(u.isEmpty()); + u.add(new ByteArrayInputStream(new byte[] { (byte) 255 })); + assertEquals(255, u.read()); + assertEquals(-1, u.read()); + assertTrue(u.isEmpty()); + } } @Test public void testReadByteBlocks() throws IOException { - @SuppressWarnings("resource" /* java 7 */) - final UnionInputStream u = new UnionInputStream(); - u.add(new ByteArrayInputStream(new byte[] { 1, 0, 2 })); - u.add(new ByteArrayInputStream(new byte[] { 3 })); - u.add(new ByteArrayInputStream(new byte[] { 4, 5 })); + try (UnionInputStream u = new UnionInputStream()) { + u.add(new ByteArrayInputStream(new byte[] { 1, 0, 2 })); + u.add(new ByteArrayInputStream(new byte[] { 3 })); + u.add(new ByteArrayInputStream(new byte[] { 4, 5 })); - final byte[] r = new byte[5]; - assertEquals(3, u.read(r, 0, 5)); - assertTrue(Arrays.equals(new byte[] { 1, 0, 2, }, slice(r, 3))); - assertEquals(1, u.read(r, 0, 5)); - assertEquals(3, r[0]); - assertEquals(2, u.read(r, 0, 5)); - assertTrue(Arrays.equals(new byte[] { 4, 5, }, slice(r, 2))); - assertEquals(-1, u.read(r, 0, 5)); + final byte[] r = new byte[5]; + assertEquals(3, u.read(r, 0, 5)); + assertTrue(Arrays.equals(new byte[] { 1, 0, 2, }, slice(r, 3))); + assertEquals(1, u.read(r, 0, 5)); + assertEquals(3, r[0]); + assertEquals(2, u.read(r, 0, 5)); + assertTrue(Arrays.equals(new byte[] { 4, 5, }, slice(r, 2))); + assertEquals(-1, u.read(r, 0, 5)); + } } private static byte[] slice(byte[] in, int len) { @@ -126,89 +125,88 @@ public class UnionInputStreamTest { @Test public void testArrayConstructor() throws IOException { - @SuppressWarnings("resource" /* java 7 */) - final UnionInputStream u = new UnionInputStream( + try (UnionInputStream u = new UnionInputStream( new ByteArrayInputStream(new byte[] { 1, 0, 2 }), new ByteArrayInputStream(new byte[] { 3 }), - new ByteArrayInputStream(new byte[] { 4, 5 })); - - final byte[] r = new byte[5]; - assertEquals(3, u.read(r, 0, 5)); - assertTrue(Arrays.equals(new byte[] { 1, 0, 2, }, slice(r, 3))); - assertEquals(1, u.read(r, 0, 5)); - assertEquals(3, r[0]); - assertEquals(2, u.read(r, 0, 5)); - assertTrue(Arrays.equals(new byte[] { 4, 5, }, slice(r, 2))); - assertEquals(-1, u.read(r, 0, 5)); + new ByteArrayInputStream(new byte[] { 4, 5 }))) { + final byte[] r = new byte[5]; + assertEquals(3, u.read(r, 0, 5)); + assertTrue(Arrays.equals(new byte[] { 1, 0, 2, }, slice(r, 3))); + assertEquals(1, u.read(r, 0, 5)); + assertEquals(3, r[0]); + assertEquals(2, u.read(r, 0, 5)); + assertTrue(Arrays.equals(new byte[] { 4, 5, }, slice(r, 2))); + assertEquals(-1, u.read(r, 0, 5)); + } } @Test - public void testMarkSupported() { - @SuppressWarnings("resource" /* java 7 */) - final UnionInputStream u = new UnionInputStream(); - assertFalse(u.markSupported()); - u.add(new ByteArrayInputStream(new byte[] { 1, 0, 2 })); - assertFalse(u.markSupported()); + public void testMarkSupported() throws IOException { + try (UnionInputStream u = new UnionInputStream()) { + assertFalse(u.markSupported()); + u.add(new ByteArrayInputStream(new byte[] { 1, 0, 2 })); + assertFalse(u.markSupported()); + } } @Test public void testSkip() throws IOException { - @SuppressWarnings("resource" /* java 7 */) - final UnionInputStream u = new UnionInputStream(); - u.add(new ByteArrayInputStream(new byte[] { 1, 0, 2 })); - u.add(new ByteArrayInputStream(new byte[] { 3 })); - u.add(new ByteArrayInputStream(new byte[] { 4, 5 })); - assertEquals(0, u.skip(0)); - assertEquals(3, u.skip(3)); - assertEquals(3, u.read()); - assertEquals(2, u.skip(5)); - assertEquals(0, u.skip(5)); - assertEquals(-1, u.read()); + try (UnionInputStream u = new UnionInputStream()) { + u.add(new ByteArrayInputStream(new byte[] { 1, 0, 2 })); + u.add(new ByteArrayInputStream(new byte[] { 3 })); + u.add(new ByteArrayInputStream(new byte[] { 4, 5 })); + assertEquals(0, u.skip(0)); + assertEquals(3, u.skip(3)); + assertEquals(3, u.read()); + assertEquals(2, u.skip(5)); + assertEquals(0, u.skip(5)); + assertEquals(-1, u.read()); - u.add(new ByteArrayInputStream(new byte[] { 20, 30 }) { - @Override - @SuppressWarnings("UnsynchronizedOverridesSynchronized") - // This is only used in tests and is thread-safe - public long skip(long n) { - return 0; - } - }); - assertEquals(2, u.skip(8)); - assertEquals(-1, u.read()); + u.add(new ByteArrayInputStream(new byte[] { 20, 30 }) { + @Override + @SuppressWarnings("UnsynchronizedOverridesSynchronized") + // This is only used in tests and is thread-safe + public long skip(long n) { + return 0; + } + }); + assertEquals(2, u.skip(8)); + assertEquals(-1, u.read()); + } } @Test public void testAutoCloseDuringRead() throws IOException { - @SuppressWarnings("resource" /* java 7 */) - final UnionInputStream u = new UnionInputStream(); - final boolean closed[] = new boolean[2]; - u.add(new ByteArrayInputStream(new byte[] { 1 }) { - @Override - public void close() { - closed[0] = true; - } - }); - u.add(new ByteArrayInputStream(new byte[] { 2 }) { - @Override - public void close() { - closed[1] = true; - } - }); + try (UnionInputStream u = new UnionInputStream()) { + final boolean closed[] = new boolean[2]; + u.add(new ByteArrayInputStream(new byte[] { 1 }) { + @Override + public void close() { + closed[0] = true; + } + }); + u.add(new ByteArrayInputStream(new byte[] { 2 }) { + @Override + public void close() { + closed[1] = true; + } + }); - assertFalse(closed[0]); - assertFalse(closed[1]); + assertFalse(closed[0]); + assertFalse(closed[1]); - assertEquals(1, u.read()); - assertFalse(closed[0]); - assertFalse(closed[1]); + assertEquals(1, u.read()); + assertFalse(closed[0]); + assertFalse(closed[1]); - assertEquals(2, u.read()); - assertTrue(closed[0]); - assertFalse(closed[1]); + assertEquals(2, u.read()); + assertTrue(closed[0]); + assertFalse(closed[1]); - assertEquals(-1, u.read()); - assertTrue(closed[0]); - assertTrue(closed[1]); + assertEquals(-1, u.read()); + assertTrue(closed[0]); + assertTrue(closed[1]); + } } @Test @@ -267,18 +265,18 @@ public class UnionInputStreamTest { throw new IOException("Expected"); } }; - @SuppressWarnings("resource" /* java 7 */) - final UnionInputStream u = new UnionInputStream( - new ByteArrayInputStream(new byte[]{1,2,3}), - errorReadStream); - byte buf[] = new byte[10]; - assertEquals(3, u.read(buf, 0, 10)); - assertTrue(Arrays.equals(new byte[] {1,2,3}, slice(buf, 3))); - try { - u.read(buf, 0, 1); - fail("Expected exception from errorReadStream"); - } catch (IOException e) { - assertEquals("Expected", e.getMessage()); + try (UnionInputStream u = new UnionInputStream( + new ByteArrayInputStream(new byte[] { 1, 2, 3 }), + errorReadStream)) { + byte buf[] = new byte[10]; + assertEquals(3, u.read(buf, 0, 10)); + assertTrue(Arrays.equals(new byte[] { 1, 2, 3 }, slice(buf, 3))); + try { + u.read(buf, 0, 1); + fail("Expected exception from errorReadStream"); + } catch (IOException e) { + assertEquals("Expected", e.getMessage()); + } } } } |