diff options
Diffstat (limited to 'org.eclipse.jgit.test/tst')
44 files changed, 1555 insertions, 484 deletions
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 aafda0171c..911f659149 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 @@ -63,8 +63,7 @@ import org.eclipse.jgit.dircache.DirCacheBuilder; import org.eclipse.jgit.dircache.DirCacheEntry; import org.eclipse.jgit.junit.JGitTestUtil; import org.eclipse.jgit.junit.RepositoryTestCase; -import org.eclipse.jgit.lfs.CleanFilter; -import org.eclipse.jgit.lfs.SmudgeFilter; +import org.eclipse.jgit.lfs.BuiltinLFS; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.FileMode; @@ -92,8 +91,7 @@ public class AddCommandTest extends RepositoryTestCase { @Override public void setUp() throws Exception { - CleanFilter.register(); - SmudgeFilter.register(); + BuiltinLFS.register(); super.setUp(); } @@ -120,9 +118,9 @@ public class AddCommandTest extends RepositoryTestCase { public void testAddExistingSingleFile() throws IOException, GitAPIException { File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } try (Git git = new Git(db)) { git.add().addFilepattern("a.txt").call(); @@ -491,9 +489,9 @@ public class AddCommandTest extends RepositoryTestCase { GitAPIException { File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("row1\r\nrow2"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("row1\r\nrow2"); + } try (Git git = new Git(db)) { db.getConfig().setString("core", null, "autocrlf", "false"); @@ -521,9 +519,9 @@ public class AddCommandTest extends RepositoryTestCase { data.append("row1\r\nrow2"); } String crData = data.toString(); - PrintWriter writer = new PrintWriter(file); - writer.print(crData); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print(crData); + } String lfData = data.toString().replaceAll("\r", ""); try (Git git = new Git(db)) { db.getConfig().setString("core", null, "autocrlf", "false"); @@ -546,9 +544,9 @@ public class AddCommandTest extends RepositoryTestCase { GitAPIException { File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("row1\r\nrow2\u0000"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("row1\r\nrow2\u0000"); + } try (Git git = new Git(db)) { db.getConfig().setString("core", null, "autocrlf", "false"); @@ -572,9 +570,9 @@ public class AddCommandTest extends RepositoryTestCase { FileUtils.mkdir(new File(db.getWorkTree(), "sub")); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } try (Git git = new Git(db)) { git.add().addFilepattern("sub/a.txt").call(); @@ -590,18 +588,18 @@ public class AddCommandTest extends RepositoryTestCase { GitAPIException { File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } try (Git git = new Git(db)) { DirCache dc = git.add().addFilepattern("a.txt").call(); dc.getEntry(0).getObjectId(); - writer = new PrintWriter(file); - writer.print("other content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("other content"); + } dc = git.add().addFilepattern("a.txt").call(); @@ -615,9 +613,9 @@ public class AddCommandTest extends RepositoryTestCase { public void testAddExistingSingleFileTwiceWithCommit() throws Exception { File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } try (Git git = new Git(db)) { DirCache dc = git.add().addFilepattern("a.txt").call(); @@ -626,9 +624,9 @@ public class AddCommandTest extends RepositoryTestCase { git.commit().setMessage("commit a.txt").call(); - writer = new PrintWriter(file); - writer.print("other content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("other content"); + } dc = git.add().addFilepattern("a.txt").call(); @@ -642,9 +640,9 @@ public class AddCommandTest extends RepositoryTestCase { public void testAddRemovedFile() throws Exception { File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } try (Git git = new Git(db)) { DirCache dc = git.add().addFilepattern("a.txt").call(); @@ -665,9 +663,9 @@ public class AddCommandTest extends RepositoryTestCase { public void testAddRemovedCommittedFile() throws Exception { File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } try (Git git = new Git(db)) { DirCache dc = git.add().addFilepattern("a.txt").call(); @@ -692,15 +690,15 @@ public class AddCommandTest extends RepositoryTestCase { File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } File file2 = new File(db.getWorkTree(), "b.txt"); FileUtils.createNewFile(file2); - writer = new PrintWriter(file2); - writer.print("content b"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file2)) { + writer.print("content b"); + } ObjectInserter newObjectInserter = db.newObjectInserter(); DirCache dc = db.lockDirCache(); @@ -709,14 +707,14 @@ public class AddCommandTest extends RepositoryTestCase { addEntryToBuilder("b.txt", file2, newObjectInserter, builder, 0); addEntryToBuilder("a.txt", file, newObjectInserter, builder, 1); - writer = new PrintWriter(file); - writer.print("other content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("other content"); + } addEntryToBuilder("a.txt", file, newObjectInserter, builder, 3); - writer = new PrintWriter(file); - writer.print("our content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("our content"); + } addEntryToBuilder("a.txt", file, newObjectInserter, builder, 2) .getObjectId(); @@ -745,15 +743,15 @@ public class AddCommandTest extends RepositoryTestCase { public void testAddTwoFiles() throws Exception { File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } File file2 = new File(db.getWorkTree(), "b.txt"); FileUtils.createNewFile(file2); - writer = new PrintWriter(file2); - writer.print("content b"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file2)) { + writer.print("content b"); + } try (Git git = new Git(db)) { git.add().addFilepattern("a.txt").addFilepattern("b.txt").call(); @@ -769,15 +767,15 @@ public class AddCommandTest extends RepositoryTestCase { FileUtils.mkdir(new File(db.getWorkTree(), "sub")); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); - writer = new PrintWriter(file2); - writer.print("content b"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file2)) { + writer.print("content b"); + } try (Git git = new Git(db)) { git.add().addFilepattern("sub").call(); @@ -793,21 +791,21 @@ public class AddCommandTest extends RepositoryTestCase { FileUtils.mkdir(new File(db.getWorkTree(), "sub")); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } File ignoreFile = new File(db.getWorkTree(), ".gitignore"); FileUtils.createNewFile(ignoreFile); - writer = new PrintWriter(ignoreFile); - writer.print("sub/b.txt"); - writer.close(); + try (PrintWriter writer = new PrintWriter(ignoreFile)) { + writer.print("sub/b.txt"); + } File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); - writer = new PrintWriter(file2); - writer.print("content b"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file2)) { + writer.print("content b"); + } try (Git git = new Git(db)) { git.add().addFilepattern("sub").call(); @@ -823,15 +821,15 @@ public class AddCommandTest extends RepositoryTestCase { FileUtils.mkdir(new File(db.getWorkTree(), "sub")); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); - writer = new PrintWriter(file2); - writer.print("content b"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file2)) { + writer.print("content b"); + } try (Git git = new Git(db)) { git.add().addFilepattern(".").call(); @@ -851,15 +849,15 @@ public class AddCommandTest extends RepositoryTestCase { FileUtils.mkdir(new File(db.getWorkTree(), "sub")); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); - writer = new PrintWriter(file2); - writer.print("content b"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file2)) { + writer.print("content b"); + } try (Git git = new Git(db)) { git.add().addFilepattern("sub").call(); @@ -874,14 +872,14 @@ public class AddCommandTest extends RepositoryTestCase { // new unstaged file sub/c.txt File file3 = new File(db.getWorkTree(), "sub/c.txt"); FileUtils.createNewFile(file3); - writer = new PrintWriter(file3); - writer.print("content c"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file3)) { + writer.print("content c"); + } // file sub/a.txt is modified - writer = new PrintWriter(file); - writer.print("modified content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("modified content"); + } // file sub/b.txt is deleted FileUtils.delete(file2); @@ -906,15 +904,15 @@ public class AddCommandTest extends RepositoryTestCase { FileUtils.mkdir(new File(db.getWorkTree(), "sub")); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); - writer = new PrintWriter(file2); - writer.print("content b"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file2)) { + writer.print("content b"); + } try (Git git = new Git(db)) { git.add().addFilepattern("sub").call(); @@ -929,14 +927,14 @@ public class AddCommandTest extends RepositoryTestCase { // new unstaged file sub/c.txt File file3 = new File(db.getWorkTree(), "sub/c.txt"); FileUtils.createNewFile(file3); - writer = new PrintWriter(file3); - writer.print("content c"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file3)) { + writer.print("content c"); + } // file sub/a.txt is modified - writer = new PrintWriter(file); - writer.print("modified content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("modified content"); + } FileUtils.delete(file2); @@ -1250,9 +1248,9 @@ public class AddCommandTest extends RepositoryTestCase { try (Git git = new Git(db)) { git.add().addFilepattern("nested-repo").call(); - + // with gitlinks ignored, we treat this as a normal directory assertEquals( - "[nested-repo, mode:160000]", + "[nested-repo/README1.md, mode:100644][nested-repo/README2.md, mode:100644]", indexState(0)); } } @@ -1260,10 +1258,11 @@ public class AddCommandTest extends RepositoryTestCase { private static DirCacheEntry addEntryToBuilder(String path, File file, ObjectInserter newObjectInserter, DirCacheBuilder builder, int stage) throws IOException { - FileInputStream inputStream = new FileInputStream(file); - ObjectId id = newObjectInserter.insert( + ObjectId id; + try (FileInputStream inputStream = new FileInputStream(file)) { + id = newObjectInserter.insert( Constants.OBJ_BLOB, file.length(), inputStream); - inputStream.close(); + } DirCacheEntry entry = new DirCacheEntry(path, stage); entry.setObjectId(id); entry.setFileMode(FileMode.REGULAR_FILE); 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 1201d9f391..71df59e1ff 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 @@ -74,8 +74,7 @@ import org.eclipse.jgit.dircache.DirCache; import org.eclipse.jgit.dircache.DirCacheEntry; import org.eclipse.jgit.junit.JGitTestUtil; import org.eclipse.jgit.junit.RepositoryTestCase; -import org.eclipse.jgit.lfs.CleanFilter; -import org.eclipse.jgit.lfs.SmudgeFilter; +import org.eclipse.jgit.lfs.BuiltinLFS; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Ref; @@ -102,8 +101,7 @@ public class CheckoutCommandTest extends RepositoryTestCase { @Override @Before public void setUp() throws Exception { - CleanFilter.register(); - SmudgeFilter.register(); + BuiltinLFS.register(); super.setUp(); git = new Git(db); // commit something @@ -172,15 +170,12 @@ public class CheckoutCommandTest extends RepositoryTestCase { @Test public void testCheckoutWithNonDeletedFiles() throws Exception { File testFile = writeTrashFile("temp", ""); - FileInputStream fis = new FileInputStream(testFile); - try { + try (FileInputStream fis = new FileInputStream(testFile)) { FileUtils.delete(testFile); return; } catch (IOException e) { // the test makes only sense if deletion of // a file with open stream fails - } finally { - fis.close(); } FileUtils.delete(testFile); CheckoutCommand co = git.checkout(); @@ -194,15 +189,12 @@ public class CheckoutCommandTest extends RepositoryTestCase { git.checkout().setName("master").call(); assertTrue(testFile.exists()); // lock the file so it can't be deleted (in Windows, that is) - fis = new FileInputStream(testFile); - try { + try (FileInputStream fis = new FileInputStream(testFile)) { assertEquals(Status.NOT_TRIED, co.getResult().getStatus()); co.setName("test").call(); assertTrue(testFile.exists()); assertEquals(Status.NONDELETED, co.getResult().getStatus()); assertTrue(co.getResult().getUndeletedList().contains("Test.txt")); - } finally { - fis.close(); } } @@ -824,7 +816,7 @@ public class CheckoutCommandTest extends RepositoryTestCase { } private File writeTempFile(String body) throws IOException { - File f = File.createTempFile("AddCommandTest_", ""); + File f = File.createTempFile("CheckoutCommandTest_", ""); JGitTestUtil.write(f, body); return f; } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CleanCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CleanCommandTest.java index 85436db472..065b5b4c3e 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CleanCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CleanCommandTest.java @@ -48,10 +48,12 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; +import java.io.IOException; import java.util.Set; import java.util.TreeSet; import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.api.errors.NoFilepatternException; import org.eclipse.jgit.errors.NoWorkTreeException; import org.eclipse.jgit.junit.RepositoryTestCase; import org.eclipse.jgit.lib.Repository; @@ -238,8 +240,9 @@ public class CleanCommandTest extends RepositoryTestCase { command.setPath(path); String uri = db.getDirectory().toURI().toString(); command.setURI(uri); - Repository repo = command.call(); - repo.close(); + try (Repository repo = command.call()) { + // Unused + } Status beforeCleanStatus = git.status().call(); assertTrue(beforeCleanStatus.getAdded().contains(DOT_GIT_MODULES)); @@ -296,4 +299,18 @@ public class CleanCommandTest extends RepositoryTestCase { // The inner repository should be cleaned this time assertTrue(forceCleanedFiles.contains(innerRepoName + "/")); } + + @Test + // To proof Bug 514434. No assertions, but before the bugfix + // this test was throwing Exceptions + public void testFilesShouldBeCleanedInSubSubFolders() + throws IOException, NoFilepatternException, GitAPIException { + writeTrashFile(".gitignore", + "/ignored-dir\n/sub-noclean/Ignored.txt\n/this_is_ok\n/this_is/not_ok\n"); + git.add().addFilepattern(".gitignore").call(); + git.commit().setMessage("adding .gitignore").call(); + writeTrashFile("this_is_ok/more/subdirs/file.txt", "1"); + writeTrashFile("this_is/not_ok/more/subdirs/file.txt", "2"); + git.clean().setCleanDirectories(true).setIgnore(false).call(); + } } 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 e687a6ca7f..0d7009dca4 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 @@ -601,17 +601,17 @@ public class CloneCommandTest extends RepositoryTestCase { SubmoduleWalk walk = SubmoduleWalk.forIndex(git2.getRepository()); assertTrue(walk.next()); - Repository clonedSub1 = walk.getRepository(); - assertNotNull(clonedSub1); - assertEquals( - new File(git2.getRepository().getWorkTree(), walk.getPath()), - clonedSub1.getWorkTree()); - assertEquals(new File(new File(git2.getRepository().getDirectory(), - "modules"), walk.getPath()), - clonedSub1.getDirectory()); - status = new SubmoduleStatusCommand(clonedSub1); - statuses = status.call(); - clonedSub1.close(); + try (Repository clonedSub1 = walk.getRepository()) { + assertNotNull(clonedSub1); + assertEquals(new File(git2.getRepository().getWorkTree(), + walk.getPath()), clonedSub1.getWorkTree()); + assertEquals( + new File(new File(git2.getRepository().getDirectory(), + "modules"), walk.getPath()), + clonedSub1.getDirectory()); + status = new SubmoduleStatusCommand(clonedSub1); + statuses = status.call(); + } pathStatus = statuses.get(path); assertNotNull(pathStatus); assertEquals(SubmoduleStatusType.INITIALIZED, pathStatus.getType()); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CommitAndLogCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CommitAndLogCommandTest.java index 1d5c6742c7..ca0630ea35 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CommitAndLogCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CommitAndLogCommandTest.java @@ -120,9 +120,9 @@ public class CommitAndLogCommandTest extends RepositoryTestCase { // create first file File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content1"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content1"); + } // First commit - a.txt file git.add().addFilepattern("a.txt").call(); @@ -131,9 +131,9 @@ public class CommitAndLogCommandTest extends RepositoryTestCase { // create second file file = new File(db.getWorkTree(), "b.txt"); FileUtils.createNewFile(file); - writer = new PrintWriter(file); - writer.print("content2"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content2"); + } // Second commit - b.txt file git.add().addFilepattern("b.txt").call(); @@ -231,9 +231,9 @@ public class CommitAndLogCommandTest extends RepositoryTestCase { JGitInternalException, GitAPIException { File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content"); + } try (Git git = new Git(db)) { git.add().addFilepattern("a.txt").call(); @@ -242,9 +242,9 @@ public class CommitAndLogCommandTest extends RepositoryTestCase { assertEquals("6b584e8ece562ebffc15d38808cd6b98fc3d97ea", tw.getObjectId(0).getName()); - writer = new PrintWriter(file); - writer.print("content2"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content2"); + } commit = git.commit().setMessage("second commit").call(); tw = TreeWalk.forPath(db, "a.txt", commit.getTree()); assertEquals("6b584e8ece562ebffc15d38808cd6b98fc3d97ea", @@ -265,9 +265,9 @@ public class CommitAndLogCommandTest extends RepositoryTestCase { // create file File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); - PrintWriter writer = new PrintWriter(file); - writer.print("content1"); - writer.close(); + try (PrintWriter writer = new PrintWriter(file)) { + writer.print("content1"); + } // First commit - a.txt file git.add().addFilepattern("a.txt").call(); 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 a0834e7e85..0dd3749337 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 @@ -223,9 +223,9 @@ public class CommitCommandTest extends RepositoryTestCase { assertEquals(uri, generator.getModulesUrl()); assertEquals(path, generator.getModulesPath()); assertEquals(uri, generator.getConfigUrl()); - Repository subModRepo = generator.getRepository(); - assertNotNull(subModRepo); - subModRepo.close(); + try (Repository subModRepo = generator.getRepository()) { + assertNotNull(subModRepo); + } assertEquals(commit, repo.resolve(Constants.HEAD)); RevCommit submoduleCommit = git.commit().setMessage("submodule add") @@ -273,9 +273,9 @@ public class CommitCommandTest extends RepositoryTestCase { assertEquals(uri, generator.getModulesUrl()); assertEquals(path, generator.getModulesPath()); assertEquals(uri, generator.getConfigUrl()); - Repository subModRepo = generator.getRepository(); - assertNotNull(subModRepo); - subModRepo.close(); + try (Repository subModRepo = generator.getRepository()) { + assertNotNull(subModRepo); + } assertEquals(commit2, repo.resolve(Constants.HEAD)); RevCommit submoduleAddCommit = git.commit().setMessage("submodule add") diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/DescribeCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/DescribeCommandTest.java index d78a328402..79da2da7ea 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/DescribeCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/DescribeCommandTest.java @@ -297,9 +297,9 @@ public class DescribeCommandTest extends RepositoryTestCase { } private static void touch(File f, String contents) throws Exception { - FileWriter w = new FileWriter(f); - w.write(contents); - w.close(); + try (FileWriter w = new FileWriter(f)) { + w.write(contents); + } } private String describe(ObjectId c1, boolean longDesc) diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/HugeFileTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/HugeFileTest.java index 4208f4d8e3..6c3504aa48 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/HugeFileTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/HugeFileTest.java @@ -87,9 +87,9 @@ public class HugeFileTest extends RepositoryTestCase { public void testAddHugeFile() throws Exception { measure("Commencing test"); File file = new File(db.getWorkTree(), "a.txt"); - RandomAccessFile rf = new RandomAccessFile(file, "rw"); - rf.setLength(4429185024L); - rf.close(); + try (RandomAccessFile rf = new RandomAccessFile(file, "rw")) { + rf.setLength(4429185024L); + } measure("Created file"); git.add().addFilepattern("a.txt").call(); @@ -109,9 +109,9 @@ public class HugeFileTest extends RepositoryTestCase { assertEquals(0, status.getUntracked().size()); // Does not change anything, but modified timestamp - rf = new RandomAccessFile(file, "rw"); - rf.write(0); - rf.close(); + try (RandomAccessFile rf = new RandomAccessFile(file, "rw")) { + rf.write(0); + } status = git.status().call(); measure("Status after non-modifying update"); @@ -125,9 +125,9 @@ public class HugeFileTest extends RepositoryTestCase { assertEquals(0, status.getUntracked().size()); // Change something - rf = new RandomAccessFile(file, "rw"); - rf.write('a'); - rf.close(); + try (RandomAccessFile rf = new RandomAccessFile(file, "rw")) { + rf.write('a'); + } status = git.status().call(); measure("Status after modifying update"); @@ -141,10 +141,10 @@ public class HugeFileTest extends RepositoryTestCase { assertEquals(0, status.getUntracked().size()); // Truncate mod 4G and re-establish equality - rf = new RandomAccessFile(file, "rw"); - rf.setLength(134217728L); - rf.write(0); - rf.close(); + try (RandomAccessFile rf = new RandomAccessFile(file, "rw")) { + rf.setLength(134217728L); + rf.write(0); + } status = git.status().call(); measure("Status after truncating update"); @@ -158,9 +158,9 @@ public class HugeFileTest extends RepositoryTestCase { assertEquals(0, status.getUntracked().size()); // Change something - rf = new RandomAccessFile(file, "rw"); - rf.write('a'); - rf.close(); + try (RandomAccessFile rf = new RandomAccessFile(file, "rw")) { + rf.write('a'); + } status = git.status().call(); measure("Status after modifying and truncating update"); @@ -174,10 +174,10 @@ public class HugeFileTest extends RepositoryTestCase { assertEquals(0, status.getUntracked().size()); // Truncate to entry length becomes negative int - rf = new RandomAccessFile(file, "rw"); - rf.setLength(3429185024L); - rf.write(0); - rf.close(); + try (RandomAccessFile rf = new RandomAccessFile(file, "rw")) { + rf.setLength(3429185024L); + rf.write(0); + } git.add().addFilepattern("a.txt").call(); measure("Added truncated file"); @@ -197,9 +197,9 @@ public class HugeFileTest extends RepositoryTestCase { assertEquals(0, status.getUntracked().size()); // Change something - rf = new RandomAccessFile(file, "rw"); - rf.write('a'); - rf.close(); + try (RandomAccessFile rf = new RandomAccessFile(file, "rw")) { + rf.write('a'); + } status = git.status().call(); measure("Status after modifying and truncating update"); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/InitCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/InitCommandTest.java index e850223762..9e3ee2c566 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/InitCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/InitCommandTest.java @@ -69,14 +69,14 @@ public class InitCommandTest extends RepositoryTestCase { } @Test - public void testInitRepository() throws IOException, JGitInternalException, - GitAPIException { + public void testInitRepository() + throws IOException, JGitInternalException, GitAPIException { File directory = createTempDirectory("testInitRepository"); InitCommand command = new InitCommand(); command.setDirectory(directory); - Repository repository = command.call().getRepository(); - addRepoToClose(repository); - assertNotNull(repository); + try (Git git = command.call()) { + assertNotNull(git.getRepository()); + } } @Test @@ -89,9 +89,9 @@ public class InitCommandTest extends RepositoryTestCase { assertTrue(directory.listFiles().length > 0); InitCommand command = new InitCommand(); command.setDirectory(directory); - Repository repository = command.call().getRepository(); - addRepoToClose(repository); - assertNotNull(repository); + try (Git git = command.call()) { + assertNotNull(git.getRepository()); + } } @Test @@ -101,10 +101,11 @@ public class InitCommandTest extends RepositoryTestCase { InitCommand command = new InitCommand(); command.setDirectory(directory); command.setBare(true); - Repository repository = command.call().getRepository(); - addRepoToClose(repository); - assertNotNull(repository); - assertTrue(repository.isBare()); + try (Git git = command.call()) { + Repository repository = git.getRepository(); + assertNotNull(repository); + assertTrue(repository.isBare()); + } } // non-bare repos where gitDir and directory is set. Same as @@ -117,11 +118,12 @@ public class InitCommandTest extends RepositoryTestCase { InitCommand command = new InitCommand(); command.setDirectory(wt); command.setGitDir(gitDir); - Repository repository = command.call().getRepository(); - addRepoToClose(repository); - assertNotNull(repository); - assertEqualsFile(wt, repository.getWorkTree()); - assertEqualsFile(gitDir, repository.getDirectory()); + try (Git git = command.call()) { + Repository repository = git.getRepository(); + assertNotNull(repository); + assertEqualsFile(wt, repository.getWorkTree()); + assertEqualsFile(gitDir, repository.getDirectory()); + } } // non-bare repos where only gitDir is set. Same as @@ -135,12 +137,13 @@ public class InitCommandTest extends RepositoryTestCase { File gitDir = createTempDirectory("testInitRepository/.git"); InitCommand command = new InitCommand(); command.setGitDir(gitDir); - Repository repository = command.call().getRepository(); - addRepoToClose(repository); - assertNotNull(repository); - assertEqualsFile(gitDir, repository.getDirectory()); - assertEqualsFile(new File(reader.getProperty("user.dir")), - repository.getWorkTree()); + try (Git git = command.call()) { + Repository repository = git.getRepository(); + assertNotNull(repository); + assertEqualsFile(gitDir, repository.getDirectory()); + assertEqualsFile(new File(reader.getProperty("user.dir")), + repository.getWorkTree()); + } } // Bare repos where gitDir and directory is set will only work if gitDir and @@ -169,13 +172,14 @@ public class InitCommandTest extends RepositoryTestCase { .getAbsolutePath()); InitCommand command = new InitCommand(); command.setBare(false); - Repository repository = command.call().getRepository(); - addRepoToClose(repository); - assertNotNull(repository); - assertEqualsFile(new File(reader.getProperty("user.dir"), ".git"), - repository.getDirectory()); - assertEqualsFile(new File(reader.getProperty("user.dir")), - repository.getWorkTree()); + try (Git git = command.call()) { + Repository repository = git.getRepository(); + assertNotNull(repository); + assertEqualsFile(new File(reader.getProperty("user.dir"), ".git"), + repository.getDirectory()); + assertEqualsFile(new File(reader.getProperty("user.dir")), + repository.getWorkTree()); + } } // If neither directory nor gitDir is set in a bare repo make sure @@ -189,12 +193,13 @@ public class InitCommandTest extends RepositoryTestCase { .getAbsolutePath()); InitCommand command = new InitCommand(); command.setBare(true); - Repository repository = command.call().getRepository(); - addRepoToClose(repository); - assertNotNull(repository); - assertEqualsFile(new File(reader.getProperty("user.dir")), - repository.getDirectory()); - assertNull(repository.getWorkTree()); + try (Git git = command.call()) { + Repository repository = git.getRepository(); + assertNotNull(repository); + assertEqualsFile(new File(reader.getProperty("user.dir")), + repository.getDirectory()); + assertNull(repository.getWorkTree()); + } } // In a non-bare repo when directory and gitDir is set then they shouldn't diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/NotesCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/NotesCommandTest.java index 9d15699963..6e06e9545a 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/NotesCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/NotesCommandTest.java @@ -42,6 +42,7 @@ */ package org.eclipse.jgit.api; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; import java.util.List; @@ -87,7 +88,7 @@ public class NotesCommandTest extends RepositoryTestCase { git.notesAdd().setObjectId(commit2).setMessage("data").call(); Note note = git.notesShow().setObjectId(commit2).call(); String content = new String(db.open(note.getData()).getCachedBytes(), - "UTF-8"); + UTF_8); assertEquals(content, "data"); git.notesRemove().setObjectId(commit2).call(); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandTest.java index cc5a0249cb..9461c42500 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandTest.java @@ -591,34 +591,23 @@ public class PullCommandTest extends RepositoryTestCase { private static void writeToFile(File actFile, String string) throws IOException { - FileOutputStream fos = null; - try { - fos = new FileOutputStream(actFile); + try (FileOutputStream fos = new FileOutputStream(actFile)) { fos.write(string.getBytes(UTF_8)); - fos.close(); - } finally { - if (fos != null) - fos.close(); } } private static void assertFileContentsEqual(File actFile, String string) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); - FileInputStream fis = null; byte[] buffer = new byte[100]; - try { - fis = new FileInputStream(actFile); + try (FileInputStream fis = new FileInputStream(actFile)) { int read = fis.read(buffer); while (read > 0) { bos.write(buffer, 0, read); read = fis.read(buffer); } - String content = new String(bos.toByteArray(), "UTF-8"); + String content = new String(bos.toByteArray(), UTF_8); assertEquals(string, content); - } finally { - if (fis != null) - fis.close(); } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandWithRebaseTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandWithRebaseTest.java index dfe05b808e..913b4ac434 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandWithRebaseTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/PullCommandWithRebaseTest.java @@ -395,34 +395,23 @@ public class PullCommandWithRebaseTest extends RepositoryTestCase { private static void writeToFile(File actFile, String string) throws IOException { - FileOutputStream fos = null; - try { - fos = new FileOutputStream(actFile); + try (FileOutputStream fos = new FileOutputStream(actFile)) { fos.write(string.getBytes(UTF_8)); - fos.close(); - } finally { - if (fos != null) - fos.close(); } } private static void assertFileContentsEqual(File actFile, String string) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); - FileInputStream fis = null; byte[] buffer = new byte[100]; - try { - fis = new FileInputStream(actFile); + try (FileInputStream fis = new FileInputStream(actFile)) { int read = fis.read(buffer); while (read > 0) { bos.write(buffer, 0, read); read = fis.read(buffer); } - String content = new String(bos.toByteArray(), "UTF-8"); + String content = new String(bos.toByteArray(), UTF_8); assertEquals(string, content); - } finally { - if (fis != null) - fis.close(); } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RebaseCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RebaseCommandTest.java index 3f43c6b1bb..2bf91aeed8 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RebaseCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RebaseCommandTest.java @@ -2103,9 +2103,8 @@ public class RebaseCommandTest extends RepositoryTestCase { private int countPicks() throws IOException { int count = 0; File todoFile = getTodoFile(); - BufferedReader br = new BufferedReader(new InputStreamReader( - new FileInputStream(todoFile), "UTF-8")); - try { + try (BufferedReader br = new BufferedReader(new InputStreamReader( + new FileInputStream(todoFile), UTF_8))) { String line = br.readLine(); while (line != null) { int firstBlank = line.indexOf(' '); @@ -2123,8 +2122,6 @@ public class RebaseCommandTest extends RepositoryTestCase { line = br.readLine(); } return count; - } finally { - br.close(); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/attributes/CGitAttributesTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/attributes/CGitAttributesTest.java index 34838138e3..344d1af6a0 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/attributes/CGitAttributesTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/attributes/CGitAttributesTest.java @@ -366,6 +366,34 @@ public class CGitAttributesTest extends RepositoryTestCase { } @Test + public void testDirectoryWildmatchDoesNotMatchFiles1() throws Exception { + createFiles("a", "dir/b", "dir/sub/c"); + writeTrashFile(".gitattributes", "**/ bar\n"); + assertSameAsCGit(); + } + + @Test + public void testDirectoryWildmatchDoesNotMatchFiles2() throws Exception { + createFiles("a", "dir/b", "dir/sub/c"); + writeTrashFile(".gitattributes", "**/**/ bar\n"); + assertSameAsCGit(); + } + + @Test + public void testDirectoryWildmatchDoesNotMatchFiles3() throws Exception { + createFiles("a", "x/b", "sub/x/c", "sub/x/d/e"); + writeTrashFile(".gitattributes", "x/**/ bar\n"); + assertSameAsCGit(); + } + + @Test + public void testDirectoryWildmatchDoesNotMatchFiles4() throws Exception { + createFiles("a", "dir/x", "dir/sub1/x", "dir/sub2/x/y"); + writeTrashFile(".gitattributes", "x/**/ bar\n"); + assertSameAsCGit(); + } + + @Test public void testDirectoryMatchSubComplex() throws Exception { createFiles("src/new/foo.txt", "foo/src/new/foo.txt", "sub/src/new"); writeTrashFile(".gitattributes", "s[rs]c/n*/ bar\n"); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/attributes/merge/MergeGitAttributeTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/attributes/merge/MergeGitAttributeTest.java index a4f3d18d1f..01ca88880f 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/attributes/merge/MergeGitAttributeTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/attributes/merge/MergeGitAttributeTest.java @@ -313,7 +313,6 @@ public class MergeGitAttributeTest extends RepositoryTestCase { WrongRepositoryStateException, NoMessageException, GitAPIException { RevCommit disableCheckedCommit; - FileInputStream mergeResultFile = null; // Set up a git with conflict commits on images try (Git git = new Git(db)) { // First commit @@ -352,15 +351,12 @@ public class MergeGitAttributeTest extends RepositoryTestCase { assertEquals(MergeStatus.CONFLICTING, mergeResult.getMergeStatus()); // Check that the image was not modified (no conflict marker added) - mergeResultFile = new FileInputStream( + try (FileInputStream mergeResultFile = new FileInputStream( db.getWorkTree().toPath().resolve(ENABLED_CHECKED_GIF) - .toFile()); - assertTrue(contentEquals( - getClass().getResourceAsStream(ENABLED_CHECKED_GIF), - mergeResultFile)); - } finally { - if (mergeResultFile != null) { - mergeResultFile.close(); + .toFile())) { + assertTrue(contentEquals( + getClass().getResourceAsStream(ENABLED_CHECKED_GIF), + mergeResultFile)); } } } @@ -373,7 +369,6 @@ public class MergeGitAttributeTest extends RepositoryTestCase { WrongRepositoryStateException, NoMessageException, GitAPIException { RevCommit disableCheckedCommit; - FileInputStream mergeResultFile = null; // Set up a git whith conflict commits on images try (Git git = new Git(db)) { // First commit @@ -412,14 +407,12 @@ public class MergeGitAttributeTest extends RepositoryTestCase { assertEquals(MergeStatus.CONFLICTING, mergeResult.getMergeStatus()); // Check that the image was not modified (not conflict marker added) - mergeResultFile = new FileInputStream(db.getWorkTree().toPath() - .resolve(ENABLED_CHECKED_GIF).toFile()); - assertTrue(contentEquals( - getClass().getResourceAsStream(ENABLED_CHECKED_GIF), - mergeResultFile)); - } finally { - if (mergeResultFile != null) { - mergeResultFile.close(); + try (FileInputStream mergeResultFile = new FileInputStream( + db.getWorkTree().toPath().resolve(ENABLED_CHECKED_GIF) + .toFile())) { + assertTrue(contentEquals( + getClass().getResourceAsStream(ENABLED_CHECKED_GIF), + mergeResultFile)); } } } @@ -432,7 +425,6 @@ public class MergeGitAttributeTest extends RepositoryTestCase { NoMessageException, GitAPIException { RevCommit disableCheckedCommit; - FileInputStream mergeResultFile = null; // Set up a git whith conflict commits on images try (Git git = new Git(db)) { // First commit @@ -471,14 +463,12 @@ public class MergeGitAttributeTest extends RepositoryTestCase { assertEquals(MergeStatus.CONFLICTING, mergeResult.getMergeStatus()); // Check that the image was not modified (not conflict marker added) - mergeResultFile = new FileInputStream(db.getWorkTree().toPath() - .resolve(ENABLED_CHECKED_GIF).toFile()); - assertFalse(contentEquals( - getClass().getResourceAsStream(ENABLED_CHECKED_GIF), - mergeResultFile)); - } finally { - if (mergeResultFile != null) { - mergeResultFile.close(); + try (FileInputStream mergeResultFile = new FileInputStream( + db.getWorkTree().toPath().resolve(ENABLED_CHECKED_GIF) + .toFile())) { + assertFalse(contentEquals( + getClass().getResourceAsStream(ENABLED_CHECKED_GIF), + mergeResultFile)); } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/DiffFormatterReflowTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/DiffFormatterReflowTest.java index 31f70cf28c..49e5d1b3d4 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/DiffFormatterReflowTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/DiffFormatterReflowTest.java @@ -181,17 +181,14 @@ public class DiffFormatterReflowTest { } private Patch parseTestPatchFile(final String patchFile) throws IOException { - final InputStream in = getClass().getResourceAsStream(patchFile); - if (in == null) { - fail("No " + patchFile + " test vector"); - return null; // Never happens - } - try { + try (InputStream in = getClass().getResourceAsStream(patchFile)) { + if (in == null) { + fail("No " + patchFile + " test vector"); + return null; // Never happens + } final Patch p = new Patch(); p.parse(in); return p; - } finally { - in.close(); } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/DiffFormatterTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/DiffFormatterTest.java index fabf03440a..45832f4958 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/DiffFormatterTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/DiffFormatterTest.java @@ -55,12 +55,14 @@ import org.eclipse.jgit.dircache.DirCacheIterator; import org.eclipse.jgit.junit.RepositoryTestCase; import org.eclipse.jgit.junit.TestRepository; import org.eclipse.jgit.lib.AnyObjectId; +import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.patch.FileHeader; import org.eclipse.jgit.patch.HunkHeader; import org.eclipse.jgit.revwalk.RevCommit; +import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.treewalk.FileTreeIterator; import org.eclipse.jgit.treewalk.filter.PathFilter; import org.eclipse.jgit.util.FileUtils; @@ -485,6 +487,102 @@ public class DiffFormatterTest extends RepositoryTestCase { } } + @Test + public void testDiffAutoCrlfSmallFile() throws Exception { + String content = "01234\r\n01234\r\n01234\r\n"; + String expectedDiff = "diff --git a/test.txt b/test.txt\n" + + "index fe25983..a44a032 100644\n" // + + "--- a/test.txt\n" // + + "+++ b/test.txt\n" // + + "@@ -1,3 +1,4 @@\n" // + + " 01234\n" // + + "+ABCD\n" // + + " 01234\n" // + + " 01234\n"; + doAutoCrLfTest(content, expectedDiff); + } + + @Test + public void testDiffAutoCrlfMediumFile() throws Exception { + String content = mediumCrLfString(); + String expectedDiff = "diff --git a/test.txt b/test.txt\n" + + "index 215c502..c10f08c 100644\n" // + + "--- a/test.txt\n" // + + "+++ b/test.txt\n" // + + "@@ -1,4 +1,5 @@\n" // + + " 01234567\n" // + + "+ABCD\n" // + + " 01234567\n" // + + " 01234567\n" // + + " 01234567\n"; + doAutoCrLfTest(content, expectedDiff); + } + + @Test + public void testDiffAutoCrlfLargeFile() throws Exception { + String content = largeCrLfString(); + String expectedDiff = "diff --git a/test.txt b/test.txt\n" + + "index 7014942..c0487a7 100644\n" // + + "--- a/test.txt\n" // + + "+++ b/test.txt\n" // + + "@@ -1,4 +1,5 @@\n" + + " 012345678901234567890123456789012345678901234567\n" + + "+ABCD\n" + + " 012345678901234567890123456789012345678901234567\n" + + " 012345678901234567890123456789012345678901234567\n" + + " 012345678901234567890123456789012345678901234567\n"; + doAutoCrLfTest(content, expectedDiff); + } + + private void doAutoCrLfTest(String content, String expectedDiff) + throws Exception { + FileBasedConfig config = db.getConfig(); + config.setString(ConfigConstants.CONFIG_CORE_SECTION, null, + ConfigConstants.CONFIG_KEY_AUTOCRLF, "true"); + config.save(); + commitFile("test.txt", content, "master"); + // Insert a line into content + int i = content.indexOf('\n'); + content = content.substring(0, i + 1) + "ABCD\r\n" + + content.substring(i + 1); + writeTrashFile("test.txt", content); + // Create the patch + try (ByteArrayOutputStream os = new ByteArrayOutputStream(); + DiffFormatter dfmt = new DiffFormatter( + new BufferedOutputStream(os))) { + dfmt.setRepository(db); + dfmt.format(new DirCacheIterator(db.readDirCache()), + new FileTreeIterator(db)); + dfmt.flush(); + + String actual = os.toString("UTF-8"); + + assertEquals(expectedDiff, actual); + } + } + + private static String largeCrLfString() { + String line = "012345678901234567890123456789012345678901234567\r\n"; + StringBuilder builder = new StringBuilder( + 2 * RawText.FIRST_FEW_BYTES); + while (builder.length() < 2 * RawText.FIRST_FEW_BYTES) { + builder.append(line); + } + return builder.toString(); + } + + private static String mediumCrLfString() { + // Create a CR-LF string longer than RawText.FIRST_FEW_BYTES whose + // canonical representation is shorter than RawText.FIRST_FEW_BYTES. + String line = "01234567\r\n"; // 10 characters + StringBuilder builder = new StringBuilder( + RawText.FIRST_FEW_BYTES + line.length()); + while (builder.length() <= RawText.FIRST_FEW_BYTES) { + builder.append(line); + } + return builder.toString(); + } + private static String makeDiffHeader(String pathA, String pathB, ObjectId aId, ObjectId bId) { diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/dircache/DirCacheCGitCompatabilityTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/dircache/DirCacheCGitCompatabilityTest.java index 92ce4e178b..dec17623fc 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/dircache/DirCacheCGitCompatabilityTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/dircache/DirCacheCGitCompatabilityTest.java @@ -43,6 +43,7 @@ package org.eclipse.jgit.dircache; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.eclipse.jgit.junit.Assert.assertEquals; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -234,32 +235,26 @@ public class DirCacheCGitCompatabilityTest extends LocalDiskRepositoryTestCase { private static Map<String, CGitIndexRecord> readLsFiles() throws Exception { final LinkedHashMap<String, CGitIndexRecord> r = new LinkedHashMap<>(); - final BufferedReader br = new BufferedReader(new InputStreamReader( - new FileInputStream(pathOf("gitgit.lsfiles")), "UTF-8")); - try { + try (BufferedReader br = new BufferedReader(new InputStreamReader( + new FileInputStream(pathOf("gitgit.lsfiles")), UTF_8))) { String line; while ((line = br.readLine()) != null) { final CGitIndexRecord cr = new CGitIndexRecord(line); r.put(cr.path, cr); } - } finally { - br.close(); } return r; } private static Map<String, CGitLsTreeRecord> readLsTree() throws Exception { final LinkedHashMap<String, CGitLsTreeRecord> r = new LinkedHashMap<>(); - final BufferedReader br = new BufferedReader(new InputStreamReader( - new FileInputStream(pathOf("gitgit.lstree")), "UTF-8")); - try { + try (BufferedReader br = new BufferedReader(new InputStreamReader( + new FileInputStream(pathOf("gitgit.lstree")), UTF_8))) { String line; while ((line = br.readLine()) != null) { final CGitLsTreeRecord cr = new CGitLsTreeRecord(line); r.put(cr.path, cr); } - } finally { - br.close(); } return r; } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/RepoCommandTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/RepoCommandTest.java index 9afb58ecfb..2253a0421f 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/RepoCommandTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/gitrepo/RepoCommandTest.java @@ -186,6 +186,59 @@ public class RepoCommandTest extends RepositoryTestCase { } @Test + public void runTwiceIsNOP() throws Exception { + Repository child = Git.cloneRepository() + .setURI(groupADb.getDirectory().toURI().toString()) + .setDirectory(createUniqueTestGitDir(true)).setBare(true).call() + .getRepository(); + + Repository dest = Git.cloneRepository() + .setURI(db.getDirectory().toURI().toString()) + .setDirectory(createUniqueTestGitDir(true)).setBare(true).call() + .getRepository(); + + assertTrue(dest.isBare()); + assertTrue(child.isBare()); + + StringBuilder xmlContent = new StringBuilder(); + xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") + .append("<manifest>") + .append("<remote name=\"remote1\" fetch=\"..\" />") + .append("<default revision=\"master\" remote=\"remote1\" />") + .append("<project path=\"base\" name=\"platform/base\" />") + .append("</manifest>"); + RepoCommand cmd = new RepoCommand(dest); + + IndexedRepos repos = new IndexedRepos(); + repos.put("platform/base", child); + + RevCommit commit = cmd + .setInputStream(new ByteArrayInputStream( + xmlContent.toString().getBytes(UTF_8))) + .setRemoteReader(repos) + .setURI("platform/") + .setTargetURI("platform/superproject") + .setRecordRemoteBranch(true) + .setRecordSubmoduleLabels(true) + .call(); + + String firstIdStr = commit.getId().name() + ":" + ".gitmodules"; + commit = new RepoCommand(dest) + .setInputStream(new ByteArrayInputStream( + xmlContent.toString().getBytes(UTF_8))) + .setRemoteReader(repos) + .setURI("platform/") + .setTargetURI("platform/superproject") + .setRecordRemoteBranch(true) + .setRecordSubmoduleLabels(true) + .call(); + String idStr = commit.getId().name() + ":" + ".gitmodules"; + assertEquals(firstIdStr, idStr); + child.close(); + dest.close(); + } + + @Test public void androidSetup() throws Exception { Repository child = Git.cloneRepository() .setURI(groupADb.getDirectory().toURI().toString()) @@ -213,8 +266,7 @@ public class RepoCommandTest extends RepositoryTestCase { repos.put("platform/base", child); RevCommit commit = cmd - .setInputStream(new ByteArrayInputStream( - xmlContent.toString().getBytes(UTF_8))) + .setInputStream(new ByteArrayInputStream(xmlContent.toString().getBytes(UTF_8))) .setRemoteReader(repos) .setURI("platform/") .setTargetURI("platform/superproject") @@ -238,6 +290,48 @@ public class RepoCommandTest extends RepositoryTestCase { } @Test + public void recordUnreachableRemotes() throws Exception { + StringBuilder xmlContent = new StringBuilder(); + xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") + .append("<manifest>") + .append("<remote name=\"remote1\" fetch=\"https://host.com/\" />") + .append("<default revision=\"master\" remote=\"remote1\" />") + .append("<project path=\"base\" name=\"platform/base\" />") + .append("</manifest>"); + + Repository dest = Git.cloneRepository() + .setURI(db.getDirectory().toURI().toString()) + .setDirectory(createUniqueTestGitDir(true)).setBare(true).call() + .getRepository(); + + assertTrue(dest.isBare()); + + RevCommit commit = new RepoCommand(dest) + .setInputStream(new ByteArrayInputStream( + xmlContent.toString().getBytes(UTF_8))) + .setRemoteReader(new IndexedRepos()) + .setURI("platform/") + .setTargetURI("platform/superproject") + .setRecordRemoteBranch(true) + .setIgnoreRemoteFailures(true) + .setRecordSubmoduleLabels(true) + .call(); + + String idStr = commit.getId().name() + ":" + ".gitmodules"; + ObjectId modId = dest.resolve(idStr); + + try (ObjectReader reader = dest.newObjectReader()) { + byte[] bytes = reader.open(modId).getCachedBytes(Integer.MAX_VALUE); + Config base = new Config(); + BlobBasedConfig cfg = new BlobBasedConfig(base, bytes); + String subUrl = cfg.getString("submodule", "base", "url"); + assertEquals(subUrl, "https://host.com/platform/base"); + } + + dest.close(); + } + + @Test public void gerritSetup() throws Exception { Repository child = Git.cloneRepository().setURI(groupADb.getDirectory().toURI().toString()) @@ -345,6 +439,63 @@ public class RepoCommandTest extends RepositoryTestCase { } @Test + public void absoluteRemoteURLAbsoluteTargetURL() throws Exception { + Repository child = + Git.cloneRepository().setURI(groupADb.getDirectory().toURI().toString()) + .setDirectory(createUniqueTestGitDir(true)) + .setBare(true).call().getRepository(); + Repository dest = Git.cloneRepository() + .setURI(db.getDirectory().toURI().toString()).setDirectory(createUniqueTestGitDir(true)) + .setBare(true).call().getRepository(); + String abs = "https://chromium.googlesource.com"; + String repoUrl = "https://chromium.googlesource.com/chromium/src"; + boolean fetchSlash = false; + boolean baseSlash = false; + do { + do { + String fetchUrl = fetchSlash ? abs + "/" : abs; + String baseUrl = baseSlash ? abs + "/" : abs; + + StringBuilder xmlContent = new StringBuilder(); + xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") + .append("<manifest>") + .append("<remote name=\"origin\" fetch=\"" + fetchUrl + "\" />") + .append("<default revision=\"master\" remote=\"origin\" />") + .append("<project path=\"src\" name=\"chromium/src\" />") + .append("</manifest>"); + RepoCommand cmd = new RepoCommand(dest); + + IndexedRepos repos = new IndexedRepos(); + repos.put(repoUrl, child); + + RevCommit commit = cmd + .setInputStream(new ByteArrayInputStream(xmlContent.toString().getBytes(UTF_8))) + .setRemoteReader(repos) + .setURI(baseUrl) + .setTargetURI(abs + "/superproject") + .setRecordRemoteBranch(true) + .setRecordSubmoduleLabels(true) + .call(); + + String idStr = commit.getId().name() + ":" + ".gitmodules"; + ObjectId modId = dest.resolve(idStr); + + try (ObjectReader reader = dest.newObjectReader()) { + byte[] bytes = reader.open(modId).getCachedBytes(Integer.MAX_VALUE); + Config base = new Config(); + BlobBasedConfig cfg = new BlobBasedConfig(base, bytes); + String subUrl = cfg.getString("submodule", "src", "url"); + assertEquals("../chromium/src", subUrl); + } + fetchSlash = !fetchSlash; + } while (fetchSlash); + baseSlash = !baseSlash; + } while (baseSlash); + child.close(); + dest.close(); + } + + @Test public void testAddRepoManifest() throws Exception { StringBuilder xmlContent = new StringBuilder(); xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") @@ -814,37 +965,6 @@ public class RepoCommandTest extends RepositoryTestCase { assertEquals("submodule content should be as expected", "master world", content); } - - @Test - public void testNonDefaultRemotes() throws Exception { - StringBuilder xmlContent = new StringBuilder(); - xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") - .append("<manifest>") - .append("<remote name=\"remote1\" fetch=\".\" />") - .append("<remote name=\"remote2\" fetch=\"") - .append(notDefaultUri) - .append("\" />") - .append("<default revision=\"master\" remote=\"remote1\" />") - .append("<project path=\"foo\" name=\"") - .append(defaultUri) - .append("\" />") - .append("<project path=\"bar\" name=\".\" remote=\"remote2\" />") - .append("</manifest>"); - - Repository localDb = createWorkRepository(); - JGitTestUtil.writeTrashFile( - localDb, "manifest.xml", xmlContent.toString()); - RepoCommand command = new RepoCommand(localDb); - command - .setPath(localDb.getWorkTree().getAbsolutePath() + "/manifest.xml") - .setURI(rootUri) - .call(); - File file = new File(localDb.getWorkTree(), "foo/hello.txt"); - assertTrue("We should have foo", file.exists()); - file = new File(localDb.getWorkTree(), "bar/world.txt"); - assertTrue("We should have bar", file.exists()); - } - @Test public void testRemoteAlias() throws Exception { StringBuilder xmlContent = new StringBuilder(); @@ -1125,5 +1245,6 @@ public class RepoCommandTest extends RepositoryTestCase { testRelative("abc", "/bcd", "/bcd"); testRelative("http://a", "a/b", "a/b"); testRelative("http://base.com/a/", "http://child.com/a/b", "http://child.com/a/b"); + testRelative("http://base.com/a/", "http://base.com/a/b", "b"); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/CGitIgnoreTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/CGitIgnoreTest.java index ee8191ffc5..3b11616fe6 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/CGitIgnoreTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/CGitIgnoreTest.java @@ -118,20 +118,41 @@ public class CGitIgnoreTest extends RepositoryTestCase { } } - private LinkedHashSet<String> jgitIgnored() throws IOException { + private String[] cgitUntracked() throws Exception { + FS fs = db.getFS(); + ProcessBuilder builder = fs.runInShell("git", + new String[] { "ls-files", "--exclude-standard", "-o" }); + builder.directory(db.getWorkTree()); + builder.environment().put("HOME", fs.userHome().getAbsolutePath()); + ExecutionResult result = fs.execute(builder, + new ByteArrayInputStream(new byte[0])); + String errorOut = toString(result.getStderr()); + assertEquals("External git failed", "exit 0\n", + "exit " + result.getRc() + '\n' + errorOut); + try (BufferedReader r = new BufferedReader(new InputStreamReader( + new BufferedInputStream(result.getStdout().openInputStream()), + Constants.CHARSET))) { + return r.lines().toArray(String[]::new); + } + } + + private void jgitIgnoredAndUntracked(LinkedHashSet<String> ignored, + LinkedHashSet<String> untracked) throws IOException { // Do a tree walk that does descend into ignored directories and return // a list of all ignored files - LinkedHashSet<String> result = new LinkedHashSet<>(); try (TreeWalk walk = new TreeWalk(db)) { walk.addTree(new FileTreeIterator(db)); walk.setRecursive(true); while (walk.next()) { if (walk.getTree(WorkingTreeIterator.class).isEntryIgnored()) { - result.add(walk.getPathString()); + ignored.add(walk.getPathString()); + } else { + // tests of this class won't add any files to the index, + // hence everything what is not ignored is untracked + untracked.add(walk.getPathString()); } } } - return result; } private void assertNoIgnoredVisited(Set<String> ignored) throws Exception { @@ -150,9 +171,13 @@ public class CGitIgnoreTest extends RepositoryTestCase { } private void assertSameAsCGit(String... notIgnored) throws Exception { - LinkedHashSet<String> ignored = jgitIgnored(); + LinkedHashSet<String> ignored = new LinkedHashSet<>(); + LinkedHashSet<String> untracked = new LinkedHashSet<>(); + jgitIgnoredAndUntracked(ignored, untracked); String[] cgit = cgitIgnored(); + String[] cgitUntracked = cgitUntracked(); assertArrayEquals(cgit, ignored.toArray()); + assertArrayEquals(cgitUntracked, untracked.toArray()); for (String notExcluded : notIgnored) { assertFalse("File " + notExcluded + " should not be ignored", ignored.contains(notExcluded)); @@ -242,6 +267,34 @@ public class CGitIgnoreTest extends RepositoryTestCase { } @Test + public void testDirectoryWildmatchDoesNotMatchFiles1() throws Exception { + createFiles("a", "dir/b", "dir/sub/c"); + writeTrashFile(".gitignore", "**/\n"); + assertSameAsCGit(); + } + + @Test + public void testDirectoryWildmatchDoesNotMatchFiles2() throws Exception { + createFiles("a", "dir/b", "dir/sub/c"); + writeTrashFile(".gitignore", "**/**/\n"); + assertSameAsCGit(); + } + + @Test + public void testDirectoryWildmatchDoesNotMatchFiles3() throws Exception { + createFiles("a", "x/b", "sub/x/c", "sub/x/d/e"); + writeTrashFile(".gitignore", "x/**/\n"); + assertSameAsCGit(); + } + + @Test + public void testDirectoryWildmatchDoesNotMatchFiles4() throws Exception { + createFiles("a", "dir/x", "dir/sub1/x", "dir/sub2/x/y"); + writeTrashFile(".gitignore", "**/x/\n"); + assertSameAsCGit(); + } + + @Test public void testUnescapedBracketsInGroup() throws Exception { createFiles("[", "]", "[]", "][", "[[]", "[]]", "[[]]"); writeTrashFile(".gitignore", "[[]]\n"); @@ -268,4 +321,68 @@ public class CGitIgnoreTest extends RepositoryTestCase { writeTrashFile(".gitignore", "[\\[\\]]\n"); assertSameAsCGit(); } + + @Test + public void testSimpleRootGitIgnoreGlobalNegation1() throws Exception { + // see IgnoreNodeTest.testSimpleRootGitIgnoreGlobalNegation1 + createFiles("x1", "a/x2", "x3/y"); + writeTrashFile(".gitignore", "*\n!x*"); + assertSameAsCGit(); + } + + @Test + public void testRepeatedNegationInDifferentFiles5() throws Exception { + // see IgnoreNodeTest.testRepeatedNegationInDifferentFiles5 + createFiles("a/b/e/nothere.o"); + writeTrashFile(".gitignore", "e"); + writeTrashFile("a/.gitignore", "e"); + writeTrashFile("a/b/.gitignore", "!e"); + assertSameAsCGit(); + } + + @Test + public void testRepeatedNegationInDifferentFilesWithWildmatcher1() + throws Exception { + createFiles("e", "x/e/f", "a/e/x1", "a/e/x2", "a/e/y", "a/e/sub/y"); + writeTrashFile(".gitignore", "a/e/**"); + writeTrashFile("a/.gitignore", "!e/x*"); + assertSameAsCGit(); + } + + @Test + public void testRepeatedNegationInDifferentFilesWithWildmatcher2() + throws Exception { + createFiles("e", "dir/f", "dir/g/h", "a/dir/i", "a/dir/j/k", + "a/b/dir/l", "a/b/dir/m/n", "a/b/dir/m/o/p", "a/q/dir/r", + "a/q/dir/dir/s", "c/d/dir/x", "c/d/dir/y"); + writeTrashFile(".gitignore", "**/dir/*"); + writeTrashFile("a/.gitignore", "!dir/*"); + writeTrashFile("a/b/.gitignore", "!**/dir/*"); + writeTrashFile("c/.gitignore", "!d/dir/x"); + assertSameAsCGit(); + } + + @Test + public void testNegationForSubDirectoryWithinIgnoredDirectoryHasNoEffect1() + throws Exception { + createFiles("e", "a/f", "a/b/g", "a/b/h/i"); + writeTrashFile(".gitignore", "a/b"); + writeTrashFile("a/.gitignore", "!b/*"); + assertSameAsCGit(); + } + + /* + * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=407475 + */ + @Test + public void testNegationAllExceptJavaInSrcAndExceptChildDirInSrc() + throws Exception { + // see + // IgnoreNodeTest.testNegationAllExceptJavaInSrcAndExceptChildDirInSrc + createFiles("nothere.o", "src/keep.java", "src/nothere.o", + "src/a/keep.java", "src/a/keep.o"); + writeTrashFile(".gitignore", "/*\n!/src/"); + writeTrashFile("src/.gitignore", "*\n!*.java\n!*/"); + assertSameAsCGit(); + } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/FastIgnoreRuleTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/FastIgnoreRuleTest.java index 06164c8a91..2a1721e66c 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/FastIgnoreRuleTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/FastIgnoreRuleTest.java @@ -48,10 +48,18 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import org.junit.Before; import org.junit.Test; public class FastIgnoreRuleTest { + private boolean pathMatch; + + @Before + public void setup() { + pathMatch = false; + } + @Test public void testSimpleCharClass() { assertMatched("][a]", "]a"); @@ -410,6 +418,19 @@ public class FastIgnoreRuleTest { assertMatched("a/**/b/**/c", "a/c/b/d/c"); assertMatched("a/**/**/b/**/**/c", "a/c/b/d/c"); + + assertMatched("**/", "a/"); + assertMatched("**/", "a/b"); + assertMatched("**/", "a/b/c"); + assertMatched("**/**/", "a/"); + assertMatched("**/**/", "a/b"); + assertMatched("**/**/", "a/b/"); + assertMatched("**/**/", "a/b/c"); + assertMatched("x/**/", "x/a/"); + assertMatched("x/**/", "x/a/b"); + assertMatched("x/**/", "x/a/b/"); + assertMatched("**/x/", "a/x/"); + assertMatched("**/x/", "a/b/x/"); } @Test @@ -424,6 +445,10 @@ public class FastIgnoreRuleTest { assertNotMatched("!/**/*.zip", "c/a/b.zip"); assertNotMatched("!**/*.zip", "c/a/b.zip"); assertNotMatched("a/**/b", "a/c/bb"); + + assertNotMatched("**/", "a"); + assertNotMatched("**/**/", "a"); + assertNotMatched("**/x/", "a/b/x"); } @SuppressWarnings("unused") @@ -465,6 +490,28 @@ public class FastIgnoreRuleTest { split("/a/b/c/", '/').toArray()); } + @Test + public void testPathMatch() { + pathMatch = true; + assertMatched("a", "a"); + assertMatched("a/", "a/"); + assertNotMatched("a/", "a/b"); + + assertMatched("**", "a"); + assertMatched("**", "a/"); + assertMatched("**", "a/b"); + + assertNotMatched("**/", "a"); + assertNotMatched("**/", "a/b"); + assertMatched("**/", "a/"); + assertMatched("**/", "a/b/"); + + assertNotMatched("x/**/", "x/a"); + assertNotMatched("x/**/", "x/a/b"); + assertMatched("x/**/", "x/a/"); + assertMatched("x/**/", "x/y/a/"); + } + private void assertMatched(String pattern, String path) { boolean match = match(pattern, path); String result = path + " is " + (match ? "ignored" : "not ignored") @@ -520,7 +567,7 @@ public class FastIgnoreRuleTest { FastIgnoreRule r = new FastIgnoreRule(pattern); // If speed of this test is ever an issue, we can use a presetRule field // to avoid recompiling a pattern each time. - boolean match = r.isMatch(target, isDirectory); + boolean match = r.isMatch(target, isDirectory, pathMatch); if (r.getNegation()) match = !match; return match; diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/IgnoreNodeTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/IgnoreNodeTest.java index 1178eb3e8a..ccc64fb468 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/IgnoreNodeTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/ignore/IgnoreNodeTest.java @@ -81,6 +81,141 @@ public class IgnoreNodeTest extends RepositoryTestCase { private TreeWalk walk; @Test + public void testSimpleRootGitIgnoreGlobalIgnore() throws IOException { + writeIgnoreFile(".gitignore", "x"); + + writeTrashFile("a/x/file", ""); + writeTrashFile("b/x", ""); + writeTrashFile("x/file", ""); + + beginWalk(); + assertEntry(F, tracked, ".gitignore"); + assertEntry(D, tracked, "a"); + assertEntry(D, ignored, "a/x"); + assertEntry(F, ignored, "a/x/file"); + assertEntry(D, tracked, "b"); + assertEntry(F, ignored, "b/x"); + assertEntry(D, ignored, "x"); + assertEntry(F, ignored, "x/file"); + endWalk(); + } + + @Test + public void testSimpleRootGitIgnoreGlobalDirIgnore() throws IOException { + writeIgnoreFile(".gitignore", "x/"); + + writeTrashFile("a/x/file", ""); + writeTrashFile("x/file", ""); + + beginWalk(); + assertEntry(F, tracked, ".gitignore"); + assertEntry(D, tracked, "a"); + assertEntry(D, ignored, "a/x"); + assertEntry(F, ignored, "a/x/file"); + assertEntry(D, ignored, "x"); + assertEntry(F, ignored, "x/file"); + endWalk(); + } + + @Test + public void testSimpleRootGitIgnoreWildMatcher() throws IOException { + writeIgnoreFile(".gitignore", "**"); + + writeTrashFile("a/x", ""); + writeTrashFile("y", ""); + + beginWalk(); + assertEntry(F, ignored, ".gitignore"); + assertEntry(D, ignored, "a"); + assertEntry(F, ignored, "a/x"); + assertEntry(F, ignored, "y"); + endWalk(); + } + + @Test + public void testSimpleRootGitIgnoreWildMatcherDirOnly() throws IOException { + writeIgnoreFile(".gitignore", "**/"); + + writeTrashFile("a/x", ""); + writeTrashFile("y", ""); + + beginWalk(); + assertEntry(F, tracked, ".gitignore"); + assertEntry(D, ignored, "a"); + assertEntry(F, ignored, "a/x"); + assertEntry(F, tracked, "y"); + endWalk(); + } + + @Test + public void testSimpleRootGitIgnoreGlobalNegation1() throws IOException { + writeIgnoreFile(".gitignore", "*", "!x*"); + writeTrashFile("x1", ""); + writeTrashFile("a/x2", ""); + writeTrashFile("x3/y", ""); + + beginWalk(); + assertEntry(F, ignored, ".gitignore"); + assertEntry(D, ignored, "a"); + assertEntry(F, ignored, "a/x2"); + assertEntry(F, tracked, "x1"); + assertEntry(D, tracked, "x3"); + assertEntry(F, ignored, "x3/y"); + endWalk(); + } + + @Test + public void testSimpleRootGitIgnoreGlobalNegation2() throws IOException { + writeIgnoreFile(".gitignore", "*", "!x*", "!/a"); + writeTrashFile("x1", ""); + writeTrashFile("a/x2", ""); + writeTrashFile("x3/y", ""); + + beginWalk(); + assertEntry(F, ignored, ".gitignore"); + assertEntry(D, tracked, "a"); + assertEntry(F, tracked, "a/x2"); + assertEntry(F, tracked, "x1"); + assertEntry(D, tracked, "x3"); + assertEntry(F, ignored, "x3/y"); + endWalk(); + } + + @Test + public void testSimpleRootGitIgnoreGlobalNegation3() throws IOException { + writeIgnoreFile(".gitignore", "*", "!x*", "!x*/**"); + writeTrashFile("x1", ""); + writeTrashFile("a/x2", ""); + writeTrashFile("x3/y", ""); + + beginWalk(); + assertEntry(F, ignored, ".gitignore"); + assertEntry(D, ignored, "a"); + assertEntry(F, ignored, "a/x2"); + assertEntry(F, tracked, "x1"); + assertEntry(D, tracked, "x3"); + assertEntry(F, tracked, "x3/y"); + endWalk(); + } + + @Test + public void testSimpleRootGitIgnoreGlobalNegation4() throws IOException { + writeIgnoreFile(".gitignore", "*", "!**/"); + writeTrashFile("x1", ""); + writeTrashFile("a/x2", ""); + writeTrashFile("x3/y", ""); + + beginWalk(); + assertEntry(F, ignored, ".gitignore"); + assertEntry(D, tracked, "a"); + assertEntry(F, ignored, "a/x2"); + assertEntry(F, ignored, "x1"); + assertEntry(D, tracked, "x3"); + assertEntry(F, ignored, "x3/y"); + endWalk(); + } + + @Test public void testRules() throws IOException { writeIgnoreFile(".git/info/exclude", "*~", "/out"); @@ -210,7 +345,7 @@ public class IgnoreNodeTest extends RepositoryTestCase { assertEntry(F, ignored, "src/.gitignore"); assertEntry(D, tracked, "src/a"); assertEntry(F, tracked, "src/a/keep.java"); - assertEntry(F, tracked, "src/a/keep.o"); + assertEntry(F, ignored, "src/a/keep.o"); assertEntry(F, tracked, "src/keep.java"); assertEntry(F, ignored, "src/nothere.o"); endWalk(); @@ -316,6 +451,103 @@ public class IgnoreNodeTest extends RepositoryTestCase { } @Test + public void testRepeatedNegationInDifferentFiles5() throws IOException { + writeIgnoreFile(".gitignore", "e"); + writeIgnoreFile("a/.gitignore", "e"); + writeIgnoreFile("a/b/.gitignore", "!e"); + writeTrashFile("a/b/e/nothere.o", ""); + + beginWalk(); + assertEntry(F, tracked, ".gitignore"); + assertEntry(D, tracked, "a"); + assertEntry(F, tracked, "a/.gitignore"); + assertEntry(D, tracked, "a/b"); + assertEntry(F, tracked, "a/b/.gitignore"); + assertEntry(D, tracked, "a/b/e"); + assertEntry(F, tracked, "a/b/e/nothere.o"); + endWalk(); + } + + @Test + public void testIneffectiveNegationDifferentLevels1() throws IOException { + writeIgnoreFile(".gitignore", "a/b/e/", "!a/b/e/*"); + writeTrashFile("a/b/e/nothere.o", ""); + + beginWalk(); + assertEntry(F, tracked, ".gitignore"); + assertEntry(D, tracked, "a"); + assertEntry(D, tracked, "a/b"); + assertEntry(D, ignored, "a/b/e"); + assertEntry(F, ignored, "a/b/e/nothere.o"); + endWalk(); + } + + @Test + public void testIneffectiveNegationDifferentLevels2() throws IOException { + writeIgnoreFile(".gitignore", "a/b/e/"); + writeIgnoreFile("a/.gitignore", "!b/e/*"); + writeTrashFile("a/b/e/nothere.o", ""); + + beginWalk(); + assertEntry(F, tracked, ".gitignore"); + assertEntry(D, tracked, "a"); + assertEntry(F, tracked, "a/.gitignore"); + assertEntry(D, tracked, "a/b"); + assertEntry(D, ignored, "a/b/e"); + assertEntry(F, ignored, "a/b/e/nothere.o"); + endWalk(); + } + + @Test + public void testIneffectiveNegationDifferentLevels3() throws IOException { + writeIgnoreFile(".gitignore", "a/b/e/"); + writeIgnoreFile("a/b/.gitignore", "!e/*"); + writeTrashFile("a/b/e/nothere.o", ""); + + beginWalk(); + assertEntry(F, tracked, ".gitignore"); + assertEntry(D, tracked, "a"); + assertEntry(D, tracked, "a/b"); + assertEntry(F, tracked, "a/b/.gitignore"); + assertEntry(D, ignored, "a/b/e"); + assertEntry(F, ignored, "a/b/e/nothere.o"); + endWalk(); + } + + @Test + public void testIneffectiveNegationDifferentLevels4() throws IOException { + writeIgnoreFile(".gitignore", "a/b/e/"); + writeIgnoreFile("a/b/e/.gitignore", "!*"); + writeTrashFile("a/b/e/nothere.o", ""); + + beginWalk(); + assertEntry(F, tracked, ".gitignore"); + assertEntry(D, tracked, "a"); + assertEntry(D, tracked, "a/b"); + assertEntry(D, ignored, "a/b/e"); + assertEntry(F, ignored, "a/b/e/.gitignore"); + assertEntry(F, ignored, "a/b/e/nothere.o"); + endWalk(); + } + + @Test + public void testIneffectiveNegationDifferentLevels5() throws IOException { + writeIgnoreFile("a/.gitignore", "b/e/"); + writeIgnoreFile("a/b/.gitignore", "!e/*"); + writeTrashFile("a/b/e/nothere.o", ""); + + beginWalk(); + assertEntry(D, tracked, "a"); + assertEntry(F, tracked, "a/.gitignore"); + assertEntry(D, tracked, "a/b"); + assertEntry(F, tracked, "a/b/.gitignore"); + assertEntry(D, ignored, "a/b/e"); + assertEntry(F, ignored, "a/b/e/nothere.o"); + endWalk(); + } + + @SuppressWarnings("deprecation") + @Test public void testEmptyIgnoreNode() { // Rules are never empty: WorkingTreeIterator optimizes empty files away // So we have to test it manually in case third party clients use diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/indexdiff/IndexDiffWithSymlinkTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/indexdiff/IndexDiffWithSymlinkTest.java index 3db27926c6..d5d3857ca4 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/indexdiff/IndexDiffWithSymlinkTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/indexdiff/IndexDiffWithSymlinkTest.java @@ -111,14 +111,12 @@ public class IndexDiffWithSymlinkTest extends LocalDiskRepositoryTestCase { && FS.DETECTED.supportsSymlinks()); super.setUp(); File testDir = createTempDirectory(this.getClass().getSimpleName()); - InputStream in = this.getClass().getClassLoader().getResourceAsStream( + try (InputStream in = this.getClass().getClassLoader() + .getResourceAsStream( this.getClass().getPackage().getName().replace('.', '/') + '/' - + FILEREPO + ".txt"); - assertNotNull("Test repo file not found", in); - try { + + FILEREPO + ".txt")) { + assertNotNull("Test repo file not found", in); testRepoDir = restoreGitRepo(in, testDir, FILEREPO); - } finally { - in.close(); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/AbbreviationTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/AbbreviationTest.java index a9edf73b85..14863488ca 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/AbbreviationTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/AbbreviationTest.java @@ -187,7 +187,10 @@ public class AbbreviationTest extends LocalDiskRepositoryTestCase { PackIndexWriter writer = new PackIndexWriterV2(dst); writer.write(objects, new byte[OBJECT_ID_LENGTH]); } - new FileOutputStream(packFile).close(); + + try (FileOutputStream unused = new FileOutputStream(packFile)) { + // unused + } assertEquals(id.abbreviate(20), reader.abbreviate(id, 2)); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/FileSnapshotTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/FileSnapshotTest.java index 9998666052..9ceaa345d9 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/FileSnapshotTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/FileSnapshotTest.java @@ -135,11 +135,8 @@ public class FileSnapshotTest { } private static void append(File f, byte b) throws IOException { - FileOutputStream os = new FileOutputStream(f, true); - try { + try (FileOutputStream os = new FileOutputStream(f, true)) { os.write(b); - } finally { - os.close(); } } 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 b37cd7ae05..3caae72fc6 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 @@ -129,4 +129,4 @@ public class GcDeleteEmptyRefsFoldersTest extends GcTestCase { assertTrue(ref01.toFile().exists()); assertTrue(ref02.toFile().exists()); } -} +}
\ No newline at end of file diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackInserterTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackInserterTest.java index b782ce87ff..8e438bc0e0 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackInserterTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/PackInserterTest.java @@ -95,6 +95,8 @@ import org.junit.Test; public class PackInserterTest extends RepositoryTestCase { private WindowCacheConfig origWindowCacheConfig; + private static final Random random = new Random(0); + @Before public void setWindowCacheConfig() { origWindowCacheConfig = new WindowCacheConfig(); @@ -518,7 +520,7 @@ public class PackInserterTest extends RepositoryTestCase { private static byte[] newLargeBlob() { byte[] blob = new byte[10240]; - new Random(0).nextBytes(blob); + random.nextBytes(blob); return blob; } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/ReflogReaderTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/ReflogReaderTest.java index 63bd7f4684..dc05eeabe1 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/ReflogReaderTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/ReflogReaderTest.java @@ -270,19 +270,16 @@ public class ReflogReaderTest extends SampleDataRepositoryTestCase { private void setupReflog(String logName, byte[] data) throws FileNotFoundException, IOException { - File logfile = new File(db.getDirectory(), logName); - if (!logfile.getParentFile().mkdirs() - && !logfile.getParentFile().isDirectory()) { - throw new IOException( - "oops, cannot create the directory for the test reflog file" - + logfile); - } - FileOutputStream fileOutputStream = new FileOutputStream(logfile); - try { - fileOutputStream.write(data); - } finally { - fileOutputStream.close(); - } - } + File logfile = new File(db.getDirectory(), logName); + if (!logfile.getParentFile().mkdirs() + && !logfile.getParentFile().isDirectory()) { + throw new IOException( + "oops, cannot create the directory for the test reflog file" + + logfile); + } + try (FileOutputStream fileOutputStream = new FileOutputStream(logfile)) { + fileOutputStream.write(data); + } + } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/ReflogWriterTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/ReflogWriterTest.java index 7f40bae556..1d188c3148 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/ReflogWriterTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/ReflogWriterTest.java @@ -87,11 +87,8 @@ public class ReflogWriterTest extends SampleDataRepositoryTestCase { "oops, cannot create the directory for the test reflog file" + logfile); } - FileInputStream fileInputStream = new FileInputStream(logfile); - try { + try (FileInputStream fileInputStream = new FileInputStream(logfile)) { fileInputStream.read(buffer); - } finally { - fileInputStream.close(); } } } 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 aa50697172..d7505af4cf 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 @@ -47,6 +47,7 @@ package org.eclipse.jgit.internal.storage.file; import static java.nio.charset.StandardCharsets.ISO_8859_1; +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.assertNotNull; @@ -521,7 +522,7 @@ public class T0003_BasicTest extends SampleDataRepositoryTestCase { 4294967295000L, 60)); commit.setCommitter(new PersonIdent("Joe Hacker", "joe2@example.com", 4294967295000L, 60)); - commit.setEncoding("UTF-8"); + commit.setEncoding(UTF_8); commit.setMessage("\u00dcbergeeks"); ObjectId cid = insertCommit(commit); assertEquals("4680908112778718f37e686cbebcc912730b3154", 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 adba048e65..ec60bd9137 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 @@ -218,6 +218,27 @@ public class MergedReftableTest { } @Test + public void scanDuplicates() throws IOException { + List<Ref> delta1 = Arrays.asList( + ref("refs/heads/apple", 1), + ref("refs/heads/banana", 2)); + List<Ref> delta2 = Arrays.asList( + ref("refs/heads/apple", 3), + ref("refs/heads/apple", 4)); + + MergedReftable mr = merge(write(delta1, 1000), write(delta2, 2000)); + try (RefCursor rc = mr.allRefs()) { + assertTrue(rc.next()); + assertEquals("refs/heads/apple", rc.getRef().getName()); + assertEquals(id(3), rc.getRef().getObjectId()); + assertTrue(rc.next()); + assertEquals("refs/heads/banana", rc.getRef().getName()); + assertEquals(id(2), rc.getRef().getObjectId()); + assertFalse(rc.next()); + } + } + + @Test public void scanIncludeDeletes() throws IOException { List<Ref> delta1 = Arrays.asList(ref("refs/heads/next", 4)); List<Ref> delta2 = Arrays.asList(delete("refs/heads/next")); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ConfigTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ConfigTest.java index fb1ee8cadb..7862005ebc 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ConfigTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ConfigTest.java @@ -808,8 +808,14 @@ public class ConfigTest { fbConfig.load(); fail(); } catch (ConfigInvalidException cie) { - assertEquals(JGitText.get().tooManyIncludeRecursions, - cie.getCause().getMessage()); + for (Throwable t = cie; t != null; t = t.getCause()) { + if (t.getMessage() + .equals(JGitText.get().tooManyIncludeRecursions)) { + return; + } + } + fail("Expected to find expected exception message: " + + JGitText.get().tooManyIncludeRecursions); } } @@ -824,6 +830,80 @@ public class ConfigTest { assertFalse(parsed.getBoolean("foo", "bar", false)); } + @Test + public void testIncludeCaseInsensitiveSection() + throws IOException, ConfigInvalidException { + File included = tmp.newFile("included"); + String content = "[foo]\nbar=true\n"; + Files.write(included.toPath(), content.getBytes()); + + File config = tmp.newFile("config"); + content = "[Include]\npath=" + pathToString(included) + "\n"; + Files.write(config.toPath(), content.getBytes()); + + FileBasedConfig fbConfig = new FileBasedConfig(null, config, + FS.DETECTED); + fbConfig.load(); + assertTrue(fbConfig.getBoolean("foo", "bar", false)); + } + + @Test + public void testIncludeCaseInsensitiveKey() + throws IOException, ConfigInvalidException { + File included = tmp.newFile("included"); + String content = "[foo]\nbar=true\n"; + Files.write(included.toPath(), content.getBytes()); + + File config = tmp.newFile("config"); + content = "[include]\nPath=" + pathToString(included) + "\n"; + Files.write(config.toPath(), content.getBytes()); + + FileBasedConfig fbConfig = new FileBasedConfig(null, config, + FS.DETECTED); + fbConfig.load(); + assertTrue(fbConfig.getBoolean("foo", "bar", false)); + } + + @Test + public void testIncludeExceptionContainsLine() { + try { + parse("[include]\npath=\n"); + fail("Expected ConfigInvalidException"); + } catch (ConfigInvalidException e) { + assertTrue( + "Expected to find the problem line in the exception message", + e.getMessage().contains("include.path")); + } + } + + @Test + public void testIncludeExceptionContainsFile() throws IOException { + File included = tmp.newFile("included"); + String includedPath = pathToString(included); + String content = "[include]\npath=\n"; + Files.write(included.toPath(), content.getBytes()); + + File config = tmp.newFile("config"); + String include = "[include]\npath=" + includedPath + "\n"; + Files.write(config.toPath(), include.getBytes()); + FileBasedConfig fbConfig = new FileBasedConfig(null, config, + FS.DETECTED); + try { + fbConfig.load(); + fail("Expected ConfigInvalidException"); + } catch (ConfigInvalidException e) { + // Check that there is some exception in the chain that contains + // includedPath + for (Throwable t = e; t != null; t = t.getCause()) { + if (t.getMessage().contains(includedPath)) { + return; + } + } + fail("Expected to find the path in the exception message: " + + includedPath); + } + } + private static void assertReadLong(long exp) throws ConfigInvalidException { assertReadLong(exp, String.valueOf(exp)); } 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 4d42bd19c5..0412242ebf 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 @@ -1923,18 +1923,20 @@ public class DirCacheCheckoutTest extends RepositoryTestCase { if (file.isFile()) { assertNotNull("found unexpected file for path " + path + " in workdir", expectedValue); - FileInputStream is = new FileInputStream(file); - byte[] buffer = new byte[(int) file.length()]; - int offset = 0; - int numRead = 0; - while (offset < buffer.length - && (numRead = is.read(buffer, offset, buffer.length - - offset)) >= 0) { - offset += numRead; + try (FileInputStream is = new FileInputStream(file)) { + byte[] buffer = new byte[(int) file.length()]; + int offset = 0; + int numRead = 0; + while (offset < buffer.length + && (numRead = is.read(buffer, offset, + buffer.length - offset)) >= 0) { + offset += numRead; + } + assertArrayEquals( + "unexpected content for path " + path + + " in workDir. ", + buffer, i.get(path).getBytes()); } - is.close(); - assertArrayEquals("unexpected content for path " + path - + " in workDir. ", buffer, i.get(path).getBytes()); nrFiles++; } else if (file.isDirectory()) { String[] files = file.list(); diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/MergeHeadMsgTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/MergeHeadMsgTest.java index 4f26a27ef6..347883f842 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/MergeHeadMsgTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/MergeHeadMsgTest.java @@ -68,13 +68,11 @@ public class MergeHeadMsgTest extends RepositoryTestCase { assertEquals(db.readMergeHeads().size(), 2); assertEquals(db.readMergeHeads().get(0), ObjectId.zeroId()); assertEquals(db.readMergeHeads().get(1), ObjectId.fromString(sampleId)); + // same test again, this time with lower-level io - FileOutputStream fos = new FileOutputStream(new File(db.getDirectory(), - "MERGE_HEAD")); - try { + try (FileOutputStream fos = new FileOutputStream( + new File(db.getDirectory(), "MERGE_HEAD"));) { fos.write("0000000000000000000000000000000000000000\n1c6db447abdbb291b25f07be38ea0b1bf94947c5\n".getBytes(Constants.CHARACTER_ENCODING)); - } finally { - fos.close(); } assertEquals(db.readMergeHeads().size(), 2); assertEquals(db.readMergeHeads().get(0), ObjectId.zeroId()); @@ -82,12 +80,9 @@ public class MergeHeadMsgTest extends RepositoryTestCase { db.writeMergeHeads(Collections.<ObjectId> emptyList()); assertEquals(read(new File(db.getDirectory(), "MERGE_HEAD")), ""); assertEquals(db.readMergeHeads(), null); - fos = new FileOutputStream(new File(db.getDirectory(), - "MERGE_HEAD")); - try { + try (FileOutputStream fos = new FileOutputStream( + new File(db.getDirectory(), "MERGE_HEAD"))) { fos.write(sampleId.getBytes(Constants.CHARACTER_ENCODING)); - } finally { - fos.close(); } assertEquals(db.readMergeHeads().size(), 1); assertEquals(db.readMergeHeads().get(0), ObjectId.fromString(sampleId)); @@ -103,12 +98,9 @@ public class MergeHeadMsgTest extends RepositoryTestCase { db.writeMergeCommitMsg(null); assertEquals(db.readMergeCommitMsg(), null); assertFalse(new File(db.getDirectory(), "MERGE_MSG").exists()); - FileOutputStream fos = new FileOutputStream(new File(db.getDirectory(), - Constants.MERGE_MSG)); - try { + try (FileOutputStream fos = new FileOutputStream( + new File(db.getDirectory(), Constants.MERGE_MSG))) { fos.write(mergeMsg.getBytes(Constants.CHARACTER_ENCODING)); - } finally { - fos.close(); } assertEquals(db.readMergeCommitMsg(), mergeMsg); } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ObjectIdSerializerTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ObjectIdSerializerTest.java new file mode 100644 index 0000000000..d98b792d75 --- /dev/null +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/ObjectIdSerializerTest.java @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2018, David Pursehouse <david.pursehouse@gmail.com> + * 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 org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; + +import org.junit.Test; + +public class ObjectIdSerializerTest { + @Test + public void serialize() throws Exception { + ObjectId original = new ObjectId(1, 2, 3, 4, 5); + ObjectId deserialized = writeAndReadBackFromTempFile(original); + assertEquals(original, deserialized); + } + + @Test + public void serializeZeroId() throws Exception { + ObjectId original = ObjectId.zeroId(); + ObjectId deserialized = writeAndReadBackFromTempFile(original); + assertEquals(original, deserialized); + } + + @Test + public void serializeNull() throws Exception { + ObjectId deserialized = writeAndReadBackFromTempFile(null); + assertNull(deserialized); + } + + private ObjectId writeAndReadBackFromTempFile(ObjectId objectId) + throws Exception { + File file = File.createTempFile("ObjectIdSerializerTest_", ""); + try (OutputStream out = new FileOutputStream(file)) { + if (objectId == null) { + ObjectIdSerializer.write(out, objectId); + } else { + ObjectIdSerializer.writeWithoutMarker(out, objectId); + } + } + try (InputStream in = new FileInputStream(file)) { + if (objectId == null) { + return ObjectIdSerializer.read(in); + } else { + return ObjectIdSerializer.readWithoutMarker(in); + } + } + } +} diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/RecursiveMergerTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/RecursiveMergerTest.java index 039a6e8cfc..190224a855 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/RecursiveMergerTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/RecursiveMergerTest.java @@ -817,40 +817,35 @@ public class RecursiveMergerTest extends RepositoryTestCase { void modifyWorktree(WorktreeState worktreeState, String path, String other) throws Exception { - FileOutputStream fos = null; - ObjectId bloblId; - - try { - switch (worktreeState) { - case Missing: - new File(db.getWorkTree(), path).delete(); - break; - case DifferentFromHeadAndOther: - write(new File(db.getWorkTree(), path), - Integer.toString(counter++)); - break; - case SameAsHead: - bloblId = contentId(Constants.HEAD, path); - fos = new FileOutputStream(new File(db.getWorkTree(), path)); - db.newObjectReader().open(bloblId).copyTo(fos); - break; - case SameAsOther: - bloblId = contentId(other, path); - fos = new FileOutputStream(new File(db.getWorkTree(), path)); - db.newObjectReader().open(bloblId).copyTo(fos); - break; - case Bare: - if (db.isBare()) - return; - File workTreeFile = db.getWorkTree(); - db.getConfig().setBoolean("core", null, "bare", true); - db.getDirectory().renameTo(new File(workTreeFile, "test.git")); - db = new FileRepository(new File(workTreeFile, "test.git")); - db_t = new TestRepository<>(db); + switch (worktreeState) { + case Missing: + new File(db.getWorkTree(), path).delete(); + break; + case DifferentFromHeadAndOther: + write(new File(db.getWorkTree(), path), + Integer.toString(counter++)); + break; + case SameAsHead: + try (FileOutputStream fos = new FileOutputStream( + new File(db.getWorkTree(), path))) { + db.newObjectReader().open(contentId(Constants.HEAD, path)) + .copyTo(fos); } - } finally { - if (fos != null) - fos.close(); + break; + case SameAsOther: + try (FileOutputStream fos = new FileOutputStream( + new File(db.getWorkTree(), path))) { + db.newObjectReader().open(contentId(other, path)).copyTo(fos); + } + break; + case Bare: + if (db.isBare()) + return; + File workTreeFile = db.getWorkTree(); + db.getConfig().setBoolean("core", null, "bare", true); + db.getDirectory().renameTo(new File(workTreeFile, "test.git")); + db = new FileRepository(new File(workTreeFile, "test.git")); + db_t = new TestRepository<>(db); } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/ResolveMergerTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/ResolveMergerTest.java index 3272d598bc..9322a4734e 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/ResolveMergerTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/merge/ResolveMergerTest.java @@ -46,6 +46,8 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.eclipse.jgit.lib.Constants.OBJ_BLOB; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; @@ -53,6 +55,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; +import java.util.Map; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.MergeResult; @@ -61,21 +64,29 @@ import org.eclipse.jgit.api.errors.CheckoutConflictException; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.JGitInternalException; import org.eclipse.jgit.dircache.DirCache; +import org.eclipse.jgit.dircache.DirCacheEditor; +import org.eclipse.jgit.dircache.DirCacheEntry; +import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.errors.NoMergeBaseException; import org.eclipse.jgit.errors.NoMergeBaseException.MergeBaseFailureReason; import org.eclipse.jgit.junit.RepositoryTestCase; import org.eclipse.jgit.junit.TestRepository; import org.eclipse.jgit.lib.AnyObjectId; +import org.eclipse.jgit.lib.ConfigConstants; +import org.eclipse.jgit.lib.Constants; +import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.ObjectStream; +import org.eclipse.jgit.lib.StoredConfig; import org.eclipse.jgit.merge.ResolveMerger.MergeFailureReason; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevObject; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; +import org.eclipse.jgit.storage.file.FileBasedConfig; import org.eclipse.jgit.treewalk.FileTreeIterator; import org.eclipse.jgit.util.FS; import org.eclipse.jgit.util.FileUtils; @@ -387,6 +398,38 @@ public class ResolveMergerTest extends RepositoryTestCase { mergeResult.getMergeStatus()); } + @Theory + public void mergeWithCrlfAutoCrlfTrue(MergeStrategy strategy) + throws IOException, GitAPIException { + Git git = Git.wrap(db); + db.getConfig().setString("core", null, "autocrlf", "true"); + db.getConfig().save(); + writeTrashFile("crlf.txt", "a crlf file\r\n"); + git.add().addFilepattern("crlf.txt").call(); + git.commit().setMessage("base").call(); + + git.branchCreate().setName("brancha").call(); + + writeTrashFile("crlf.txt", "a crlf file\r\na second line\r\n"); + git.add().addFilepattern("crlf.txt").call(); + git.commit().setMessage("on master").call(); + + git.checkout().setName("brancha").call(); + File testFile = writeTrashFile("crlf.txt", + "a first line\r\na crlf file\r\n"); + git.add().addFilepattern("crlf.txt").call(); + git.commit().setMessage("on brancha").call(); + + MergeResult mergeResult = git.merge().setStrategy(strategy) + .include(db.resolve("master")).call(); + assertEquals(MergeResult.MergeStatus.MERGED, + mergeResult.getMergeStatus()); + checkFile(testFile, "a first line\r\na crlf file\r\na second line\r\n"); + assertEquals( + "[crlf.txt, mode:100644, content:a first line\na crlf file\na second line\n]", + indexState(CONTENT)); + } + /** * Merging two equal subtrees when the index does not contain any file in * that subtree should lead to a merged state. @@ -1098,6 +1141,146 @@ public class ResolveMergerTest extends RepositoryTestCase { indexState(CONTENT)); } + /** + * Merging two conflicting submodules when the index does not contain any + * entry for that submodule. + * + * @param strategy + * @throws Exception + */ + @Theory + public void checkMergeConflictingSubmodulesWithoutIndex( + MergeStrategy strategy) throws Exception { + Git git = Git.wrap(db); + writeTrashFile("initial", "initial"); + git.add().addFilepattern("initial").call(); + RevCommit initial = git.commit().setMessage("initial").call(); + + writeSubmodule("one", ObjectId + .fromString("1000000000000000000000000000000000000000")); + git.add().addFilepattern(Constants.DOT_GIT_MODULES).call(); + RevCommit right = git.commit().setMessage("added one").call(); + + // a second commit in the submodule + + git.checkout().setStartPoint(initial).setName("left") + .setCreateBranch(true).call(); + writeSubmodule("one", ObjectId + .fromString("2000000000000000000000000000000000000000")); + + git.add().addFilepattern(Constants.DOT_GIT_MODULES).call(); + git.commit().setMessage("a different one").call(); + + MergeResult result = git.merge().setStrategy(strategy).include(right) + .call(); + + assertEquals(MergeStatus.CONFLICTING, result.getMergeStatus()); + Map<String, int[][]> conflicts = result.getConflicts(); + assertEquals(1, conflicts.size()); + assertNotNull(conflicts.get("one")); + } + + /** + * Merging two non-conflicting submodules when the index does not contain + * any entry for either submodule. + * + * @param strategy + * @throws Exception + */ + @Theory + public void checkMergeNonConflictingSubmodulesWithoutIndex( + MergeStrategy strategy) throws Exception { + Git git = Git.wrap(db); + writeTrashFile("initial", "initial"); + git.add().addFilepattern("initial").call(); + + writeSubmodule("one", ObjectId + .fromString("1000000000000000000000000000000000000000")); + + // Our initial commit should include a .gitmodules with a bunch of + // comment lines, so that + // we don't have a content merge issue when we add a new submodule at + // the top and a different + // one at the bottom. This is sort of a hack, but it should allow + // add/add submodule merges + String existing = read(Constants.DOT_GIT_MODULES); + String context = "\n# context\n# more context\n# yet more context\n"; + write(new File(db.getWorkTree(), Constants.DOT_GIT_MODULES), + existing + context + context + context); + + git.add().addFilepattern(Constants.DOT_GIT_MODULES).call(); + RevCommit initial = git.commit().setMessage("initial").call(); + + writeSubmodule("two", ObjectId + .fromString("1000000000000000000000000000000000000000")); + git.add().addFilepattern(Constants.DOT_GIT_MODULES).call(); + + RevCommit right = git.commit().setMessage("added two").call(); + + git.checkout().setStartPoint(initial).setName("left") + .setCreateBranch(true).call(); + + // we need to manually create the submodule for three for the + // .gitmodules hackery + addSubmoduleToIndex("three", ObjectId + .fromString("1000000000000000000000000000000000000000")); + new File(db.getWorkTree(), "three").mkdir(); + + existing = read(Constants.DOT_GIT_MODULES); + String three = "[submodule \"three\"]\n\tpath = three\n\turl = " + + db.getDirectory().toURI() + "\n"; + write(new File(db.getWorkTree(), Constants.DOT_GIT_MODULES), + three + existing); + + git.add().addFilepattern(Constants.DOT_GIT_MODULES).call(); + git.commit().setMessage("a different one").call(); + + MergeResult result = git.merge().setStrategy(strategy).include(right) + .call(); + + assertNull(result.getCheckoutConflicts()); + assertNull(result.getFailingPaths()); + for (String dir : Arrays.asList("one", "two", "three")) { + assertTrue(new File(db.getWorkTree(), dir).isDirectory()); + } + } + + private void writeSubmodule(String path, ObjectId commit) + throws IOException, ConfigInvalidException { + addSubmoduleToIndex(path, commit); + new File(db.getWorkTree(), path).mkdir(); + + StoredConfig config = db.getConfig(); + config.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, + ConfigConstants.CONFIG_KEY_URL, + db.getDirectory().toURI().toString()); + config.save(); + + FileBasedConfig modulesConfig = new FileBasedConfig( + new File(db.getWorkTree(), Constants.DOT_GIT_MODULES), + db.getFS()); + modulesConfig.load(); + modulesConfig.setString(ConfigConstants.CONFIG_SUBMODULE_SECTION, path, + ConfigConstants.CONFIG_KEY_PATH, path); + modulesConfig.save(); + + } + + private void addSubmoduleToIndex(String path, ObjectId commit) + throws IOException { + DirCache cache = db.lockDirCache(); + DirCacheEditor editor = cache.editor(); + editor.add(new DirCacheEditor.PathEdit(path) { + + @Override + public void apply(DirCacheEntry ent) { + ent.setFileMode(FileMode.GITLINK); + ent.setObjectId(commit); + } + }); + editor.commit(); + } + // Assert that every specified index entry has the same last modification // timestamp as the associated file private void checkConsistentLastModified(String... pathes) diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/EditListTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/EditListTest.java index 61bd8cf9c2..6027aff716 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/EditListTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/EditListTest.java @@ -90,17 +90,14 @@ public class EditListTest { } private Patch parseTestPatchFile(final String patchFile) throws IOException { - final InputStream in = getClass().getResourceAsStream(patchFile); - if (in == null) { - fail("No " + patchFile + " test vector"); - return null; // Never happens - } - try { + try (InputStream in = getClass().getResourceAsStream(patchFile)) { + if (in == null) { + fail("No " + patchFile + " test vector"); + return null; // Never happens + } final Patch p = new Patch(); p.parse(in); return p; - } finally { - in.close(); } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/GetTextTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/GetTextTest.java index 2aaf6afbe3..65375c7ae0 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/GetTextTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/patch/GetTextTest.java @@ -43,6 +43,8 @@ package org.eclipse.jgit.patch; +import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -58,7 +60,7 @@ import org.junit.Test; public class GetTextTest { @Test public void testGetText_BothISO88591() throws IOException { - final Charset cs = Charset.forName("ISO-8859-1"); + final Charset cs = ISO_8859_1; final Patch p = parseTestPatchFile(); assertTrue(p.getErrors().isEmpty()); assertEquals(1, p.getFiles().size()); @@ -69,7 +71,7 @@ public class GetTextTest { @Test public void testGetText_NoBinary() throws IOException { - final Charset cs = Charset.forName("ISO-8859-1"); + final Charset cs = ISO_8859_1; final Patch p = parseTestPatchFile(); assertTrue(p.getErrors().isEmpty()); assertEquals(1, p.getFiles().size()); @@ -80,8 +82,8 @@ public class GetTextTest { @Test public void testGetText_Convert() throws IOException { - final Charset csOld = Charset.forName("ISO-8859-1"); - final Charset csNew = Charset.forName("UTF-8"); + final Charset csOld = ISO_8859_1; + final Charset csNew = UTF_8; final Patch p = parseTestPatchFile(); assertTrue(p.getErrors().isEmpty()); assertEquals(1, p.getFiles().size()); @@ -100,8 +102,8 @@ public class GetTextTest { @Test public void testGetText_DiffCc() throws IOException { - final Charset csOld = Charset.forName("ISO-8859-1"); - final Charset csNew = Charset.forName("UTF-8"); + final Charset csOld = ISO_8859_1; + final Charset csNew = UTF_8; final Patch p = parseTestPatchFile(); assertTrue(p.getErrors().isEmpty()); assertEquals(1, p.getFiles().size()); @@ -121,28 +123,24 @@ public class GetTextTest { private Patch parseTestPatchFile() throws IOException { final String patchFile = JGitTestUtil.getName() + ".patch"; - final InputStream in = getClass().getResourceAsStream(patchFile); - if (in == null) { - fail("No " + patchFile + " test vector"); - return null; // Never happens - } - try { + try (InputStream in = getClass().getResourceAsStream(patchFile)) { + if (in == null) { + fail("No " + patchFile + " test vector"); + return null; // Never happens + } final Patch p = new Patch(); p.parse(in); return p; - } finally { - in.close(); } } private String readTestPatchFile(final Charset cs) throws IOException { final String patchFile = JGitTestUtil.getName() + ".patch"; - final InputStream in = getClass().getResourceAsStream(patchFile); - if (in == null) { - fail("No " + patchFile + " test vector"); - return null; // Never happens - } - try { + try (InputStream in = getClass().getResourceAsStream(patchFile)) { + if (in == null) { + fail("No " + patchFile + " test vector"); + return null; // Never happens + } final InputStreamReader r = new InputStreamReader(in, cs); char[] tmp = new char[2048]; final StringBuilder s = new StringBuilder(); @@ -150,8 +148,6 @@ public class GetTextTest { while ((n = r.read(tmp)) > 0) s.append(tmp, 0, n); return s.toString(); - } finally { - in.close(); } } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/storage/file/FileBasedConfigTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/storage/file/FileBasedConfigTest.java index 2a54dc6140..7f0d60295c 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/storage/file/FileBasedConfigTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/storage/file/FileBasedConfigTest.java @@ -242,11 +242,8 @@ public class FileBasedConfigTest { dir.mkdirs(); File f = File.createTempFile(getClass().getName(), null, dir); - FileOutputStream os = new FileOutputStream(f, true); - try { + try (FileOutputStream os = new FileOutputStream(f, true)) { os.write(content); - } finally { - os.close(); } return f; } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/TestProtocolTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/TestProtocolTest.java index b926e482f6..86c92bb528 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/TestProtocolTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/TestProtocolTest.java @@ -60,6 +60,9 @@ import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository; import org.eclipse.jgit.junit.TestRepository; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.revwalk.RevCommit; +import org.eclipse.jgit.storage.pack.PackStatistics; +import org.eclipse.jgit.transport.BasePackFetchConnection.FetchConfig; import org.eclipse.jgit.transport.resolver.ReceivePackFactory; import org.eclipse.jgit.transport.resolver.ServiceNotAuthorizedException; import org.eclipse.jgit.transport.resolver.UploadPackFactory; @@ -70,6 +73,11 @@ import org.junit.Test; public class TestProtocolTest { private static final RefSpec HEADS = new RefSpec("+refs/heads/*:refs/heads/*"); + private static final RefSpec MASTER = new RefSpec( + "+refs/heads/master:refs/heads/master"); + + private static final int HAVES_PER_ROUND = 32; + private static class User { private final String name; @@ -81,7 +89,14 @@ public class TestProtocolTest { private static class DefaultUpload implements UploadPackFactory<User> { @Override public UploadPack create(User req, Repository db) { - return new UploadPack(db); + UploadPack up = new UploadPack(db); + up.setPostUploadHook(new PostUploadHook() { + @Override + public void onPostUpload(PackStatistics stats) { + havesCount = stats.getHaves(); + } + }); + return up; } } @@ -92,6 +107,8 @@ public class TestProtocolTest { } } + private static long havesCount; + private List<TransportProtocol> protos; private TestRepository<InMemoryRepository> local; private TestRepository<InMemoryRepository> remote; @@ -147,6 +164,68 @@ public class TestProtocolTest { } @Test + public void testFullNegotiation() throws Exception { + TestProtocol<User> proto = registerDefault(); + URIish uri = proto.register(new User("user"), remote.getRepository()); + + // Enough local branches to cause 10 rounds of negotiation, + // and a unique remote master branch commit with a later timestamp. + for (int i = 0; i < 10 * HAVES_PER_ROUND; i++) { + local.branch("local-branch-" + i).commit().create(); + } + remote.tick(11 * HAVES_PER_ROUND); + RevCommit master = remote.branch("master").commit() + .add("readme.txt", "unique commit").create(); + + try (Git git = new Git(local.getRepository())) { + assertNull(local.getRepository().exactRef("refs/heads/master")); + git.fetch().setRemote(uri.toString()).setRefSpecs(MASTER).call(); + assertEquals(master, local.getRepository() + .exactRef("refs/heads/master").getObjectId()); + assertEquals(10 * HAVES_PER_ROUND, havesCount); + } + } + + @Test + public void testMinimalNegotiation() throws Exception { + TestProtocol<User> proto = registerDefault(); + URIish uri = proto.register(new User("user"), remote.getRepository()); + + // Enough local branches to cause 10 rounds of negotiation, + // and a unique remote master branch commit with a later timestamp. + for (int i = 0; i < 10 * HAVES_PER_ROUND; i++) { + local.branch("local-branch-" + i).commit().create(); + } + remote.tick(11 * HAVES_PER_ROUND); + RevCommit master = remote.branch("master").commit() + .add("readme.txt", "unique commit").create(); + + TestProtocol.setFetchConfig(new FetchConfig(true, true)); + try (Git git = new Git(local.getRepository())) { + assertNull(local.getRepository().exactRef("refs/heads/master")); + git.fetch().setRemote(uri.toString()).setRefSpecs(MASTER).call(); + assertEquals(master, local.getRepository() + .exactRef("refs/heads/master").getObjectId()); + assertTrue(havesCount <= 2 * HAVES_PER_ROUND); + + // Update the remote master and add local branches for 5 more rounds + // of negotiation, where the local branch commits have newer + // timestamps. Negotiation should send 5 rounds for those newer + // branches before getting to the round that sends its stale version + // of master. + master = remote.branch("master").commit().parent(master).create(); + local.tick(2 * HAVES_PER_ROUND); + for (int i = 0; i < 5 * HAVES_PER_ROUND; i++) { + local.branch("local-" + i).commit().create(); + } + git.fetch().setRemote(uri.toString()).setRefSpecs(MASTER).call(); + assertEquals(master, local.getRepository() + .exactRef("refs/heads/master").getObjectId()); + assertEquals(6 * HAVES_PER_ROUND, havesCount); + } + } + + @Test public void testUploadPackFactory() throws Exception { ObjectId master = remote.branch("master").commit().create(); @@ -171,7 +250,7 @@ public class TestProtocolTest { try { git.fetch() .setRemote(user1Uri.toString()) - .setRefSpecs(HEADS) + .setRefSpecs(MASTER) .call(); } catch (InvalidRemoteException expected) { // Expected. @@ -181,7 +260,7 @@ public class TestProtocolTest { git.fetch() .setRemote(user2Uri.toString()) - .setRefSpecs(HEADS) + .setRefSpecs(MASTER) .call(); assertEquals(1, rejected.get()); assertEquals(master, diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/URIishTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/URIishTest.java index 1eb218c865..39cd71947d 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/URIishTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/URIishTest.java @@ -1052,4 +1052,32 @@ public class URIishTest { assertEquals("", u.getPath()); assertEquals(str, u.toString()); } + + @Test + public void testEqualsHashcode() throws Exception + { + String[] urls = { "http://user:pass@example.com:8081/path", "../x", + "ssh://x.y:23/z", "ssh://example.com:/path", "D:\\m y", + "\\\\some\\place", "http://localhost:1234", + "user@example.com:some/p ath", "a", + "http://user:pwd@example.com:8081/path", + "http://user:pass@another.com:8081/path", + "http://user:pass@example.com:8083/path" }; + URIish w = new URIish("http://user:pass@example.com:8081/path/x"); + for (String s : urls) { + URIish u = new URIish(s); + URIish v = new URIish(s); + assertTrue(u.equals(v)); + assertTrue(v.equals(u)); + + assertFalse(u.equals(null)); + assertFalse(u.equals(new Object())); + assertFalse(new Object().equals(u)); + assertFalse(u.equals(w)); + assertFalse(w.equals(u)); + + assertTrue(u.hashCode() == v.hashCode()); + assertFalse(u.hashCode() == new Object().hashCode()); + } + } } diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/WalkEncryptionTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/WalkEncryptionTest.java index 1b434d3ddc..cb04f83fb5 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/WalkEncryptionTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/WalkEncryptionTest.java @@ -43,7 +43,7 @@ package org.eclipse.jgit.transport; -import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.UTF_8; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.cryptoCipherListPBE; import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.cryptoCipherListTrans; import static org.eclipse.jgit.transport.WalkEncryptionTest.Util.folderDelete; @@ -77,7 +77,6 @@ import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; -import java.nio.charset.Charset; import java.nio.file.Files; import java.security.GeneralSecurityException; import java.security.Provider; @@ -353,8 +352,6 @@ public class WalkEncryptionTest { */ static class Util { - static final Charset UTF_8 = Charset.forName("UTF-8"); - /** * Read UTF-8 encoded text file into string. * diff --git a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoCRLFInputStreamTest.java b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoCRLFInputStreamTest.java index 83a53b9a6d..1272e16173 100644 --- a/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoCRLFInputStreamTest.java +++ b/org.eclipse.jgit.test/tst/org/eclipse/jgit/util/io/AutoCRLFInputStreamTest.java @@ -93,25 +93,24 @@ public class AutoCRLFInputStreamTest { byte[] expectBytes = expect.getBytes(); for (int i = 0; i < 5; ++i) { byte[] buf = new byte[i]; - ByteArrayInputStream bis = new ByteArrayInputStream(inbytes); - InputStream in = new AutoCRLFInputStream(bis, true); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - if (i > 0) { - int n; - while ((n = in.read(buf)) >= 0) { - out.write(buf, 0, n); + try (ByteArrayInputStream bis = new ByteArrayInputStream(inbytes); + InputStream in = new AutoCRLFInputStream(bis, true); + ByteArrayOutputStream out = new ByteArrayOutputStream()) { + if (i > 0) { + int n; + while ((n = in.read(buf)) >= 0) { + out.write(buf, 0, n); + } + } else { + int c; + while ((c = in.read()) != -1) + out.write(c); } - } else { - int c; - while ((c = in.read()) != -1) - out.write(c); + out.flush(); + byte[] actualBytes = out.toByteArray(); + Assert.assertEquals("bufsize=" + i, encode(expectBytes), + encode(actualBytes)); } - out.flush(); - in.close(); - out.close(); - byte[] actualBytes = out.toByteArray(); - Assert.assertEquals("bufsize=" + i, encode(expectBytes), - encode(actualBytes)); } } |