Ver código fonte

Merge branch 'stable-4.2'

* stable-4.2:
  BundleWriterTest: Open RevWalk in try-with-resource
  DiffFormatterTest: Remove accidentally added trailing whitespace
  CherryPickCommandTest: Create Git instances in try-with-resource
  DiffFormatterTest: Create auto-closeable instances in try-with-resource
  ConfigTest: Create Git instance in try-with-resource
  CommitAndLogCommandTest: Use assumeFalse to skip test on Windows
  CommitAndLogCommandTest: Create Git instances in try-with-resource
  AddCommandTest: Create Git instances in try-with-resource
  ArchiveCommandTest: Create Git instances in try-with-resource
  TagCommandTest: Instantiate Git and RevWalk objects in try-with-resource
  BlameCommandTest: Instantiate Git objects in try-with-resource
  SideBandOutputStreamTest: Use try-with-resource
  FileTreeIteratorJava7Test: Create Git instances in try-with-resource

Change-Id: Ib572e98e6117b70442aee9cd7e7b8c3cf65562a7
Signed-off-by: Matthias Sohn <matthias.sohn@sap.com>
tags/v4.3.0.201603230630-rc1
Matthias Sohn 8 anos atrás
pai
commit
34b4a564ea

+ 3
- 1
org.eclipse.jgit.pgm.test/tst/org/eclipse/jgit/pgm/ConfigTest.java Ver arquivo

@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
super.setUp(); super.setUp();
new Git(db).commit().setMessage("initial commit").call();
try (Git git = new Git(db)) {
git.commit().setMessage("initial commit").call();
}
} }


@Test @Test

+ 320
- 299
org.eclipse.jgit.test/tst/org/eclipse/jgit/api/AddCommandTest.java Ver arquivo



@Test @Test
public void testAddNothing() throws GitAPIException { public void testAddNothing() throws GitAPIException {
Git git = new Git(db);

try {
try (Git git = new Git(db)) {
git.add().call(); git.add().call();
fail("Expected IllegalArgumentException"); fail("Expected IllegalArgumentException");
} catch (NoFilepatternException e) { } catch (NoFilepatternException e) {


@Test @Test
public void testAddNonExistingSingleFile() throws GitAPIException { public void testAddNonExistingSingleFile() throws GitAPIException {
Git git = new Git(db);

DirCache dc = git.add().addFilepattern("a.txt").call();
assertEquals(0, dc.getEntryCount());

try (Git git = new Git(db)) {
DirCache dc = git.add().addFilepattern("a.txt").call();
assertEquals(0, dc.getEntryCount());
}
} }


@Test @Test
writer.print("content"); writer.print("content");
writer.close(); writer.close();


Git git = new Git(db);

git.add().addFilepattern("a.txt").call();
try (Git git = new Git(db)) {
git.add().addFilepattern("a.txt").call();


assertEquals(
"[a.txt, mode:100644, content:content]",
indexState(CONTENT));
assertEquals(
"[a.txt, mode:100644, content:content]",
indexState(CONTENT));
}
} }


@Test @Test
writeTrashFile("src/a.txt", "foo\n"); writeTrashFile("src/a.txt", "foo\n");
File script = writeTempFile("sed s/o/e/g"); File script = writeTempFile("sed s/o/e/g");


Git git = new Git(db);
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"sh " + slashify(script.getPath()));
config.save();
try (Git git = new Git(db)) {
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"sh " + slashify(script.getPath()));
config.save();


git.add().addFilepattern("src/a.txt").addFilepattern("src/a.tmp")
.call();
git.add().addFilepattern("src/a.txt").addFilepattern("src/a.tmp")
.call();


assertEquals(
"[src/a.tmp, mode:100644, content:foo][src/a.txt, mode:100644, content:fee\n]",
indexState(CONTENT));
assertEquals(
"[src/a.tmp, mode:100644, content:foo][src/a.txt, mode:100644, content:fee\n]",
indexState(CONTENT));
}
} }


@Test @Test
writeTrashFile("src/a.txt", "foo"); writeTrashFile("src/a.txt", "foo");
File script = writeTempFile("echo $GIT_DIR; echo 1 >xyz"); File script = writeTempFile("echo $GIT_DIR; echo 1 >xyz");


Git git = new Git(db);
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"sh " + slashify(script.getPath()));
config.save();
git.add().addFilepattern("src/a.txt").call();

String gitDir = db.getDirectory().getAbsolutePath();
assertEquals("[src/a.txt, mode:100644, content:" + gitDir
+ "\n]", indexState(CONTENT));
assertTrue(new File(db.getWorkTree(), "xyz").exists());
try (Git git = new Git(db)) {
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"sh " + slashify(script.getPath()));
config.save();
git.add().addFilepattern("src/a.txt").call();

String gitDir = db.getDirectory().getAbsolutePath();
assertEquals("[src/a.txt, mode:100644, content:" + gitDir
+ "\n]", indexState(CONTENT));
assertTrue(new File(db.getWorkTree(), "xyz").exists());
}
} }


@Test @Test
File script = writeTempFile("sed s/o/e/g"); File script = writeTempFile("sed s/o/e/g");
File script2 = writeTempFile("sed s/f/x/g"); File script2 = writeTempFile("sed s/f/x/g");


Git git = new Git(db);
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"sh " + slashify(script.getPath()));
config.setString("filter", "tstFilter2", "clean",
"sh " + slashify(script2.getPath()));
config.save();
try (Git git = new Git(db)) {
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"sh " + slashify(script.getPath()));
config.setString("filter", "tstFilter2", "clean",
"sh " + slashify(script2.getPath()));
config.save();


git.add().addFilepattern("src/a.txt").addFilepattern("src/a.tmp")
.call();
git.add().addFilepattern("src/a.txt").addFilepattern("src/a.tmp")
.call();


assertEquals(
"[src/a.tmp, mode:100644, content:xoo\n][src/a.txt, mode:100644, content:fee\n]",
indexState(CONTENT));
assertEquals(
"[src/a.tmp, mode:100644, content:xoo\n][src/a.txt, mode:100644, content:fee\n]",
indexState(CONTENT));


// TODO: multiple clean filters for one file???
// TODO: multiple clean filters for one file???
}
} }


/** /**
writeTrashFile("; echo virus", "foo\n"); writeTrashFile("; echo virus", "foo\n");
File script = writeTempFile("sed s/o/e/g"); File script = writeTempFile("sed s/o/e/g");


Git git = new Git(db);
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"sh " + slashify(script.getPath()) + " %f");
writeTrashFile(".gitattributes", "* filter=tstFilter");

git.add().addFilepattern("; echo virus").call();
// Without proper escaping the content would be "feovirus". The sed
// command and the "echo virus" would contribute to the content
assertEquals("[; echo virus, mode:100644, content:fee\n]",
indexState(CONTENT));
try (Git git = new Git(db)) {
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"sh " + slashify(script.getPath()) + " %f");
writeTrashFile(".gitattributes", "* filter=tstFilter");

git.add().addFilepattern("; echo virus").call();
// Without proper escaping the content would be "feovirus". The sed
// command and the "echo virus" would contribute to the content
assertEquals("[; echo virus, mode:100644, content:fee\n]",
indexState(CONTENT));
}
} }


@Test @Test
writeTrashFile("a.txt", "foo"); writeTrashFile("a.txt", "foo");
File script = writeTempFile("sedfoo s/o/e/g"); File script = writeTempFile("sedfoo s/o/e/g");


Git git = new Git(db);
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"sh " + script.getPath());
config.save();
writeTrashFile(".gitattributes", "*.txt filter=tstFilter");

try {
git.add().addFilepattern("a.txt").call();
fail("Didn't received the expected exception");
} catch (FilterFailedException e) {
assertEquals(127, e.getReturnCode());
try (Git git = new Git(db)) {
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"sh " + script.getPath());
config.save();
writeTrashFile(".gitattributes", "*.txt filter=tstFilter");

try {
git.add().addFilepattern("a.txt").call();
fail("Didn't received the expected exception");
} catch (FilterFailedException e) {
assertEquals(127, e.getReturnCode());
}
} }
} }


writeTrashFile("a.txt", "foo"); writeTrashFile("a.txt", "foo");
File script = writeTempFile("sed s/o/e/g"); File script = writeTempFile("sed s/o/e/g");


Git git = new Git(db);
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"shfoo " + script.getPath());
config.save();
writeTrashFile(".gitattributes", "*.txt filter=tstFilter");

try {
git.add().addFilepattern("a.txt").call();
fail("Didn't received the expected exception");
} catch (FilterFailedException e) {
assertEquals(127, e.getReturnCode());
try (Git git = new Git(db)) {
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"shfoo " + script.getPath());
config.save();
writeTrashFile(".gitattributes", "*.txt filter=tstFilter");

try {
git.add().addFilepattern("a.txt").call();
fail("Didn't received the expected exception");
} catch (FilterFailedException e) {
assertEquals(127, e.getReturnCode());
}
} }
} }


writeTrashFile("a.txt", "foo"); writeTrashFile("a.txt", "foo");
File script = writeTempFile("exit 12"); File script = writeTempFile("exit 12");


Git git = new Git(db);
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"sh " + slashify(script.getPath()));
config.save();
writeTrashFile(".gitattributes", "*.txt filter=tstFilter");

try {
git.add().addFilepattern("a.txt").call();
fail("Didn't received the expected exception");
} catch (FilterFailedException e) {
assertEquals(12, e.getReturnCode());
try (Git git = new Git(db)) {
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "clean",
"sh " + slashify(script.getPath()));
config.save();
writeTrashFile(".gitattributes", "*.txt filter=tstFilter");

try {
git.add().addFilepattern("a.txt").call();
fail("Didn't received the expected exception");
} catch (FilterFailedException e) {
assertEquals(12, e.getReturnCode());
}
} }
} }


writeTrashFile("a.txt", "foo"); writeTrashFile("a.txt", "foo");
File script = writeTempFile("sed s/o/e/g"); File script = writeTempFile("sed s/o/e/g");


Git git = new Git(db);
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "something",
"sh " + script.getPath());
config.save();
writeTrashFile(".gitattributes", "*.txt filter=tstFilter");
try (Git git = new Git(db)) {
StoredConfig config = git.getRepository().getConfig();
config.setString("filter", "tstFilter", "something",
"sh " + script.getPath());
config.save();
writeTrashFile(".gitattributes", "*.txt filter=tstFilter");


git.add().addFilepattern("a.txt").call();
git.add().addFilepattern("a.txt").call();


assertEquals("[a.txt, mode:100644, content:foo]", indexState(CONTENT));
assertEquals("[a.txt, mode:100644, content:foo]",
indexState(CONTENT));
}
} }


private File writeTempFile(String body) throws IOException { private File writeTempFile(String body) throws IOException {
writer.print("row1\r\nrow2"); writer.print("row1\r\nrow2");
writer.close(); writer.close();


Git git = new Git(db);
db.getConfig().setString("core", null, "autocrlf", "false");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:row1\r\nrow2]",
indexState(CONTENT));
db.getConfig().setString("core", null, "autocrlf", "true");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:row1\nrow2]",
indexState(CONTENT));
db.getConfig().setString("core", null, "autocrlf", "input");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:row1\nrow2]",
indexState(CONTENT));
try (Git git = new Git(db)) {
db.getConfig().setString("core", null, "autocrlf", "false");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:row1\r\nrow2]",
indexState(CONTENT));
db.getConfig().setString("core", null, "autocrlf", "true");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:row1\nrow2]",
indexState(CONTENT));
db.getConfig().setString("core", null, "autocrlf", "input");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:row1\nrow2]",
indexState(CONTENT));
}
} }


@Test @Test
writer.print(crData); writer.print(crData);
writer.close(); writer.close();
String lfData = data.toString().replaceAll("\r", ""); String lfData = data.toString().replaceAll("\r", "");
Git git = new Git(db);
db.getConfig().setString("core", null, "autocrlf", "false");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:" + data + "]",
indexState(CONTENT));
db.getConfig().setString("core", null, "autocrlf", "true");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:" + lfData + "]",
indexState(CONTENT));
db.getConfig().setString("core", null, "autocrlf", "input");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:" + lfData + "]",
indexState(CONTENT));
try (Git git = new Git(db)) {
db.getConfig().setString("core", null, "autocrlf", "false");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:" + data + "]",
indexState(CONTENT));
db.getConfig().setString("core", null, "autocrlf", "true");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:" + lfData + "]",
indexState(CONTENT));
db.getConfig().setString("core", null, "autocrlf", "input");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:" + lfData + "]",
indexState(CONTENT));
}
} }


@Test @Test
writer.print("row1\r\nrow2\u0000"); writer.print("row1\r\nrow2\u0000");
writer.close(); writer.close();


Git git = new Git(db);
db.getConfig().setString("core", null, "autocrlf", "false");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:row1\r\nrow2\u0000]",
indexState(CONTENT));
db.getConfig().setString("core", null, "autocrlf", "true");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:row1\r\nrow2\u0000]",
indexState(CONTENT));
db.getConfig().setString("core", null, "autocrlf", "input");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:row1\r\nrow2\u0000]",
indexState(CONTENT));
try (Git git = new Git(db)) {
db.getConfig().setString("core", null, "autocrlf", "false");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:row1\r\nrow2\u0000]",
indexState(CONTENT));
db.getConfig().setString("core", null, "autocrlf", "true");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:row1\r\nrow2\u0000]",
indexState(CONTENT));
db.getConfig().setString("core", null, "autocrlf", "input");
git.add().addFilepattern("a.txt").call();
assertEquals("[a.txt, mode:100644, content:row1\r\nrow2\u0000]",
indexState(CONTENT));
}
} }


@Test @Test
writer.print("content"); writer.print("content");
writer.close(); writer.close();


Git git = new Git(db);

git.add().addFilepattern("sub/a.txt").call();
try (Git git = new Git(db)) {
git.add().addFilepattern("sub/a.txt").call();


assertEquals(
"[sub/a.txt, mode:100644, content:content]",
indexState(CONTENT));
assertEquals(
"[sub/a.txt, mode:100644, content:content]",
indexState(CONTENT));
}
} }


@Test @Test
writer.print("content"); writer.print("content");
writer.close(); writer.close();


Git git = new Git(db);
DirCache dc = git.add().addFilepattern("a.txt").call();
try (Git git = new Git(db)) {
DirCache dc = git.add().addFilepattern("a.txt").call();


dc.getEntry(0).getObjectId();
dc.getEntry(0).getObjectId();


writer = new PrintWriter(file);
writer.print("other content");
writer.close();
writer = new PrintWriter(file);
writer.print("other content");
writer.close();


dc = git.add().addFilepattern("a.txt").call();
dc = git.add().addFilepattern("a.txt").call();


assertEquals(
"[a.txt, mode:100644, content:other content]",
indexState(CONTENT));
assertEquals(
"[a.txt, mode:100644, content:other content]",
indexState(CONTENT));
}
} }


@Test @Test
writer.print("content"); writer.print("content");
writer.close(); writer.close();


Git git = new Git(db);
DirCache dc = git.add().addFilepattern("a.txt").call();
try (Git git = new Git(db)) {
DirCache dc = git.add().addFilepattern("a.txt").call();


dc.getEntry(0).getObjectId();
dc.getEntry(0).getObjectId();


git.commit().setMessage("commit a.txt").call();
git.commit().setMessage("commit a.txt").call();


writer = new PrintWriter(file);
writer.print("other content");
writer.close();
writer = new PrintWriter(file);
writer.print("other content");
writer.close();


dc = git.add().addFilepattern("a.txt").call();
dc = git.add().addFilepattern("a.txt").call();


assertEquals(
"[a.txt, mode:100644, content:other content]",
indexState(CONTENT));
assertEquals(
"[a.txt, mode:100644, content:other content]",
indexState(CONTENT));
}
} }


@Test @Test
writer.print("content"); writer.print("content");
writer.close(); writer.close();


Git git = new Git(db);
DirCache dc = git.add().addFilepattern("a.txt").call();
try (Git git = new Git(db)) {
DirCache dc = git.add().addFilepattern("a.txt").call();


dc.getEntry(0).getObjectId();
FileUtils.delete(file);
dc.getEntry(0).getObjectId();
FileUtils.delete(file);


// is supposed to do nothing
dc = git.add().addFilepattern("a.txt").call();
// is supposed to do nothing
dc = git.add().addFilepattern("a.txt").call();


assertEquals(
"[a.txt, mode:100644, content:content]",
indexState(CONTENT));
assertEquals(
"[a.txt, mode:100644, content:content]",
indexState(CONTENT));
}
} }


@Test @Test
writer.print("content"); writer.print("content");
writer.close(); writer.close();


Git git = new Git(db);
DirCache dc = git.add().addFilepattern("a.txt").call();
try (Git git = new Git(db)) {
DirCache dc = git.add().addFilepattern("a.txt").call();


git.commit().setMessage("commit a.txt").call();
git.commit().setMessage("commit a.txt").call();


dc.getEntry(0).getObjectId();
FileUtils.delete(file);
dc.getEntry(0).getObjectId();
FileUtils.delete(file);


// is supposed to do nothing
dc = git.add().addFilepattern("a.txt").call();
// is supposed to do nothing
dc = git.add().addFilepattern("a.txt").call();


assertEquals(
"[a.txt, mode:100644, content:content]",
indexState(CONTENT));
assertEquals(
"[a.txt, mode:100644, content:content]",
indexState(CONTENT));
}
} }


@Test @Test


// now the test begins // now the test begins


Git git = new Git(db);
dc = git.add().addFilepattern("a.txt").call();
try (Git git = new Git(db)) {
dc = git.add().addFilepattern("a.txt").call();


assertEquals(
"[a.txt, mode:100644, content:our content]" +
"[b.txt, mode:100644, content:content b]",
indexState(CONTENT));
assertEquals(
"[a.txt, mode:100644, content:our content]" +
"[b.txt, mode:100644, content:content b]",
indexState(CONTENT));
}
} }


@Test @Test
writer.print("content b"); writer.print("content b");
writer.close(); writer.close();


Git git = new Git(db);
git.add().addFilepattern("a.txt").addFilepattern("b.txt").call();
assertEquals(
"[a.txt, mode:100644, content:content]" +
"[b.txt, mode:100644, content:content b]",
indexState(CONTENT));
try (Git git = new Git(db)) {
git.add().addFilepattern("a.txt").addFilepattern("b.txt").call();
assertEquals(
"[a.txt, mode:100644, content:content]" +
"[b.txt, mode:100644, content:content b]",
indexState(CONTENT));
}
} }


@Test @Test
writer.print("content b"); writer.print("content b");
writer.close(); writer.close();


Git git = new Git(db);
git.add().addFilepattern("sub").call();
assertEquals(
"[sub/a.txt, mode:100644, content:content]" +
"[sub/b.txt, mode:100644, content:content b]",
indexState(CONTENT));
try (Git git = new Git(db)) {
git.add().addFilepattern("sub").call();
assertEquals(
"[sub/a.txt, mode:100644, content:content]" +
"[sub/b.txt, mode:100644, content:content b]",
indexState(CONTENT));
}
} }


@Test @Test
writer.print("content b"); writer.print("content b");
writer.close(); writer.close();


Git git = new Git(db);
git.add().addFilepattern("sub").call();
try (Git git = new Git(db)) {
git.add().addFilepattern("sub").call();


assertEquals(
"[sub/a.txt, mode:100644, content:content]",
indexState(CONTENT));
assertEquals(
"[sub/a.txt, mode:100644, content:content]",
indexState(CONTENT));
}
} }


@Test @Test
writer.print("content b"); writer.print("content b");
writer.close(); writer.close();


Git git = new Git(db);
git.add().addFilepattern(".").call();
assertEquals(
"[sub/a.txt, mode:100644, content:content]" +
"[sub/b.txt, mode:100644, content:content b]",
indexState(CONTENT));
try (Git git = new Git(db)) {
git.add().addFilepattern(".").call();
assertEquals(
"[sub/a.txt, mode:100644, content:content]" +
"[sub/b.txt, mode:100644, content:content b]",
indexState(CONTENT));
}
} }


// the same three cases as in testAddWithParameterUpdate // the same three cases as in testAddWithParameterUpdate
writer.print("content b"); writer.print("content b");
writer.close(); writer.close();


Git git = new Git(db);
git.add().addFilepattern("sub").call();
try (Git git = new Git(db)) {
git.add().addFilepattern("sub").call();


assertEquals(
"[sub/a.txt, mode:100644, content:content]" +
"[sub/b.txt, mode:100644, content:content b]",
indexState(CONTENT));
assertEquals(
"[sub/a.txt, mode:100644, content:content]" +
"[sub/b.txt, mode:100644, content:content b]",
indexState(CONTENT));


git.commit().setMessage("commit").call();
git.commit().setMessage("commit").call();


// 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();
// 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();


// file sub/a.txt is modified
writer = new PrintWriter(file);
writer.print("modified content");
writer.close();
// file sub/a.txt is modified
writer = new PrintWriter(file);
writer.print("modified content");
writer.close();


// file sub/b.txt is deleted
FileUtils.delete(file2);
// file sub/b.txt is deleted
FileUtils.delete(file2);


git.add().addFilepattern("sub").call();
// change in sub/a.txt is staged
// deletion of sub/b.txt is not staged
// sub/c.txt is staged
assertEquals(
"[sub/a.txt, mode:100644, content:modified content]" +
"[sub/b.txt, mode:100644, content:content b]" +
"[sub/c.txt, mode:100644, content:content c]",
indexState(CONTENT));
git.add().addFilepattern("sub").call();
// change in sub/a.txt is staged
// deletion of sub/b.txt is not staged
// sub/c.txt is staged
assertEquals(
"[sub/a.txt, mode:100644, content:modified content]" +
"[sub/b.txt, mode:100644, content:content b]" +
"[sub/c.txt, mode:100644, content:content c]",
indexState(CONTENT));
}
} }


// file a exists in workdir and in index -> added // file a exists in workdir and in index -> added
writer.print("content b"); writer.print("content b");
writer.close(); writer.close();


Git git = new Git(db);
git.add().addFilepattern("sub").call();
try (Git git = new Git(db)) {
git.add().addFilepattern("sub").call();


assertEquals(
"[sub/a.txt, mode:100644, content:content]" +
"[sub/b.txt, mode:100644, content:content b]",
indexState(CONTENT));
assertEquals(
"[sub/a.txt, mode:100644, content:content]" +
"[sub/b.txt, mode:100644, content:content b]",
indexState(CONTENT));


git.commit().setMessage("commit").call();
git.commit().setMessage("commit").call();


// 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();
// 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();


// file sub/a.txt is modified
writer = new PrintWriter(file);
writer.print("modified content");
writer.close();
// file sub/a.txt is modified
writer = new PrintWriter(file);
writer.print("modified content");
writer.close();


FileUtils.delete(file2);
FileUtils.delete(file2);


// change in sub/a.txt is staged
// deletion of sub/b.txt is staged
// sub/c.txt is not staged
git.add().addFilepattern("sub").setUpdate(true).call();
// change in sub/a.txt is staged
assertEquals(
"[sub/a.txt, mode:100644, content:modified content]",
indexState(CONTENT));
// change in sub/a.txt is staged
// deletion of sub/b.txt is staged
// sub/c.txt is not staged
git.add().addFilepattern("sub").setUpdate(true).call();
// change in sub/a.txt is staged
assertEquals(
"[sub/a.txt, mode:100644, content:modified content]",
indexState(CONTENT));
}
} }


@Test @Test
public void testAssumeUnchanged() throws Exception { public void testAssumeUnchanged() throws Exception {
Git git = new Git(db);
String path = "a.txt";
writeTrashFile(path, "content");
git.add().addFilepattern(path).call();
String path2 = "b.txt";
writeTrashFile(path2, "content");
git.add().addFilepattern(path2).call();
git.commit().setMessage("commit").call();
assertEquals("[a.txt, mode:100644, content:"
+ "content, assume-unchanged:false]"
+ "[b.txt, mode:100644, content:content, "
+ "assume-unchanged:false]", indexState(CONTENT
| ASSUME_UNCHANGED));
assumeUnchanged(path2);
assertEquals("[a.txt, mode:100644, content:content, "
+ "assume-unchanged:false][b.txt, mode:100644, "
+ "content:content, assume-unchanged:true]", indexState(CONTENT
| ASSUME_UNCHANGED));
writeTrashFile(path, "more content");
writeTrashFile(path2, "more content");

git.add().addFilepattern(".").call();

assertEquals("[a.txt, mode:100644, content:more content,"
+ " assume-unchanged:false][b.txt, mode:100644,"
+ " content:content, assume-unchanged:true]",
indexState(CONTENT
| ASSUME_UNCHANGED));
try (Git git = new Git(db)) {
String path = "a.txt";
writeTrashFile(path, "content");
git.add().addFilepattern(path).call();
String path2 = "b.txt";
writeTrashFile(path2, "content");
git.add().addFilepattern(path2).call();
git.commit().setMessage("commit").call();
assertEquals("[a.txt, mode:100644, content:"
+ "content, assume-unchanged:false]"
+ "[b.txt, mode:100644, content:content, "
+ "assume-unchanged:false]", indexState(CONTENT
| ASSUME_UNCHANGED));
assumeUnchanged(path2);
assertEquals("[a.txt, mode:100644, content:content, "
+ "assume-unchanged:false][b.txt, mode:100644, "
+ "content:content, assume-unchanged:true]", indexState(CONTENT
| ASSUME_UNCHANGED));
writeTrashFile(path, "more content");
writeTrashFile(path2, "more content");

git.add().addFilepattern(".").call();

assertEquals("[a.txt, mode:100644, content:more content,"
+ " assume-unchanged:false][b.txt, mode:100644,"
+ " content:content, assume-unchanged:true]",
indexState(CONTENT
| ASSUME_UNCHANGED));
}
} }


@Test @Test

+ 89
- 85
org.eclipse.jgit.test/tst/org/eclipse/jgit/api/ArchiveCommandTest.java Ver arquivo



@Test @Test
public void archiveHeadAllFiles() throws IOException, GitAPIException { public void archiveHeadAllFiles() throws IOException, GitAPIException {
Git git = new Git(db);
writeTrashFile("file_1.txt", "content_1_1");
git.add().addFilepattern("file_1.txt").call();
git.commit().setMessage("create file").call();

writeTrashFile("file_1.txt", "content_1_2");
writeTrashFile("file_2.txt", "content_2_2");
git.add().addFilepattern(".").call();
git.commit().setMessage("updated file").call();

git.archive().setOutputStream(new MockOutputStream())
.setFormat(format.SUFFIXES.get(0))
.setTree(git.getRepository().resolve("HEAD")).call();

assertEquals(UNEXPECTED_ARCHIVE_SIZE, 2, format.size());
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_1_2", format.getByPath("file_1.txt"));
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_2_2", format.getByPath("file_2.txt"));
try (Git git = new Git(db)) {
writeTrashFile("file_1.txt", "content_1_1");
git.add().addFilepattern("file_1.txt").call();
git.commit().setMessage("create file").call();

writeTrashFile("file_1.txt", "content_1_2");
writeTrashFile("file_2.txt", "content_2_2");
git.add().addFilepattern(".").call();
git.commit().setMessage("updated file").call();

git.archive().setOutputStream(new MockOutputStream())
.setFormat(format.SUFFIXES.get(0))
.setTree(git.getRepository().resolve("HEAD")).call();

assertEquals(UNEXPECTED_ARCHIVE_SIZE, 2, format.size());
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_1_2", format.getByPath("file_1.txt"));
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_2_2", format.getByPath("file_2.txt"));
}
} }


@Test @Test
public void archiveHeadSpecificPath() throws IOException, GitAPIException { public void archiveHeadSpecificPath() throws IOException, GitAPIException {
Git git = new Git(db);
writeTrashFile("file_1.txt", "content_1_1");
git.add().addFilepattern("file_1.txt").call();
git.commit().setMessage("create file").call();

writeTrashFile("file_1.txt", "content_1_2");
String expectedFilePath = "some_directory/file_2.txt";
writeTrashFile(expectedFilePath, "content_2_2");
git.add().addFilepattern(".").call();
git.commit().setMessage("updated file").call();

git.archive().setOutputStream(new MockOutputStream())
.setFormat(format.SUFFIXES.get(0))
.setTree(git.getRepository().resolve("HEAD"))
.setPaths(expectedFilePath).call();

assertEquals(UNEXPECTED_ARCHIVE_SIZE, 2, format.size());
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_2_2", format.getByPath(expectedFilePath));
assertNull(UNEXPECTED_TREE_CONTENTS, format.getByPath("some_directory"));
try (Git git = new Git(db)) {
writeTrashFile("file_1.txt", "content_1_1");
git.add().addFilepattern("file_1.txt").call();
git.commit().setMessage("create file").call();

writeTrashFile("file_1.txt", "content_1_2");
String expectedFilePath = "some_directory/file_2.txt";
writeTrashFile(expectedFilePath, "content_2_2");
git.add().addFilepattern(".").call();
git.commit().setMessage("updated file").call();

git.archive().setOutputStream(new MockOutputStream())
.setFormat(format.SUFFIXES.get(0))
.setTree(git.getRepository().resolve("HEAD"))
.setPaths(expectedFilePath).call();

assertEquals(UNEXPECTED_ARCHIVE_SIZE, 2, format.size());
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_2_2", format.getByPath(expectedFilePath));
assertNull(UNEXPECTED_TREE_CONTENTS, format.getByPath("some_directory"));
}
} }


@Test @Test
public void archiveByIdSpecificFile() throws IOException, GitAPIException { public void archiveByIdSpecificFile() throws IOException, GitAPIException {
Git git = new Git(db);
writeTrashFile("file_1.txt", "content_1_1");
git.add().addFilepattern("file_1.txt").call();
RevCommit first = git.commit().setMessage("create file").call();

writeTrashFile("file_1.txt", "content_1_2");
String expectedFilePath = "some_directory/file_2.txt";
writeTrashFile(expectedFilePath, "content_2_2");
git.add().addFilepattern(".").call();
git.commit().setMessage("updated file").call();

Map<String, Object> options = new HashMap<>();
Integer opt = Integer.valueOf(42);
options.put("foo", opt);
MockOutputStream out = new MockOutputStream();
git.archive().setOutputStream(out)
.setFormat(format.SUFFIXES.get(0))
.setFormatOptions(options)
.setTree(first)
.setPaths("file_1.txt").call();

assertEquals(opt.intValue(), out.getFoo());
assertEquals(UNEXPECTED_ARCHIVE_SIZE, 1, format.size());
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_1_1", format.getByPath("file_1.txt"));
try (Git git = new Git(db)) {
writeTrashFile("file_1.txt", "content_1_1");
git.add().addFilepattern("file_1.txt").call();
RevCommit first = git.commit().setMessage("create file").call();

writeTrashFile("file_1.txt", "content_1_2");
String expectedFilePath = "some_directory/file_2.txt";
writeTrashFile(expectedFilePath, "content_2_2");
git.add().addFilepattern(".").call();
git.commit().setMessage("updated file").call();

Map<String, Object> options = new HashMap<>();
Integer opt = Integer.valueOf(42);
options.put("foo", opt);
MockOutputStream out = new MockOutputStream();
git.archive().setOutputStream(out)
.setFormat(format.SUFFIXES.get(0))
.setFormatOptions(options)
.setTree(first)
.setPaths("file_1.txt").call();

assertEquals(opt.intValue(), out.getFoo());
assertEquals(UNEXPECTED_ARCHIVE_SIZE, 1, format.size());
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_1_1", format.getByPath("file_1.txt"));
}
} }


@Test @Test
public void archiveByDirectoryPath() throws GitAPIException, IOException { public void archiveByDirectoryPath() throws GitAPIException, IOException {
Git git = new Git(db);
writeTrashFile("file_0.txt", "content_0_1");
git.add().addFilepattern("file_0.txt").call();
git.commit().setMessage("commit_1").call();

writeTrashFile("file_0.txt", "content_0_2");
String expectedFilePath1 = "some_directory/file_1.txt";
writeTrashFile(expectedFilePath1, "content_1_2");
String expectedFilePath2 = "some_directory/file_2.txt";
writeTrashFile(expectedFilePath2, "content_2_2");
String expectedFilePath3 = "some_directory/nested_directory/file_3.txt";
writeTrashFile(expectedFilePath3, "content_3_2");
git.add().addFilepattern(".").call();
git.commit().setMessage("commit_2").call();
git.archive().setOutputStream(new MockOutputStream())
.setFormat(format.SUFFIXES.get(0))
.setTree(git.getRepository().resolve("HEAD"))
.setPaths("some_directory/").call();

assertEquals(UNEXPECTED_ARCHIVE_SIZE, 5, format.size());
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_1_2", format.getByPath(expectedFilePath1));
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_2_2", format.getByPath(expectedFilePath2));
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_3_2", format.getByPath(expectedFilePath3));
assertNull(UNEXPECTED_TREE_CONTENTS, format.getByPath("some_directory"));
assertNull(UNEXPECTED_TREE_CONTENTS, format.getByPath("some_directory/nested_directory"));
try (Git git = new Git(db)) {
writeTrashFile("file_0.txt", "content_0_1");
git.add().addFilepattern("file_0.txt").call();
git.commit().setMessage("commit_1").call();

writeTrashFile("file_0.txt", "content_0_2");
String expectedFilePath1 = "some_directory/file_1.txt";
writeTrashFile(expectedFilePath1, "content_1_2");
String expectedFilePath2 = "some_directory/file_2.txt";
writeTrashFile(expectedFilePath2, "content_2_2");
String expectedFilePath3 = "some_directory/nested_directory/file_3.txt";
writeTrashFile(expectedFilePath3, "content_3_2");
git.add().addFilepattern(".").call();
git.commit().setMessage("commit_2").call();
git.archive().setOutputStream(new MockOutputStream())
.setFormat(format.SUFFIXES.get(0))
.setTree(git.getRepository().resolve("HEAD"))
.setPaths("some_directory/").call();

assertEquals(UNEXPECTED_ARCHIVE_SIZE, 5, format.size());
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_1_2", format.getByPath(expectedFilePath1));
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_2_2", format.getByPath(expectedFilePath2));
assertEquals(UNEXPECTED_FILE_CONTENTS, "content_3_2", format.getByPath(expectedFilePath3));
assertNull(UNEXPECTED_TREE_CONTENTS, format.getByPath("some_directory"));
assertNull(UNEXPECTED_TREE_CONTENTS, format.getByPath("some_directory/nested_directory"));
}
} }


private class MockFormat implements ArchiveCommand.Format<MockOutputStream> { private class MockFormat implements ArchiveCommand.Format<MockOutputStream> {

+ 305
- 303
org.eclipse.jgit.test/tst/org/eclipse/jgit/api/BlameCommandTest.java Ver arquivo



@Test @Test
public void testSingleRevision() throws Exception { public void testSingleRevision() throws Exception {
Git git = new Git(db);
String[] content = new String[] { "first", "second", "third" };
writeTrashFile("file.txt", join(content));
git.add().addFilepattern("file.txt").call();
RevCommit commit = git.commit().setMessage("create file").call();
BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt");
BlameResult lines = command.call();
assertNotNull(lines);
assertEquals(3, lines.getResultContents().size());
for (int i = 0; i < 3; i++) {
assertEquals(commit, lines.getSourceCommit(i));
assertEquals(i, lines.getSourceLine(i));
try (Git git = new Git(db)) {
String[] content = new String[] { "first", "second", "third" };
writeTrashFile("file.txt", join(content));
git.add().addFilepattern("file.txt").call();
RevCommit commit = git.commit().setMessage("create file").call();
BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt");
BlameResult lines = command.call();
assertNotNull(lines);
assertEquals(3, lines.getResultContents().size());
for (int i = 0; i < 3; i++) {
assertEquals(commit, lines.getSourceCommit(i));
assertEquals(i, lines.getSourceLine(i));
}
} }
} }


@Test @Test
public void testTwoRevisions() throws Exception { public void testTwoRevisions() throws Exception {
Git git = new Git(db);
String[] content1 = new String[] { "first", "second" };
writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
RevCommit commit1 = git.commit().setMessage("create file").call();
String[] content2 = new String[] { "first", "second", "third" };
writeTrashFile("file.txt", join(content2));
git.add().addFilepattern("file.txt").call();
RevCommit commit2 = git.commit().setMessage("create file").call();
BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(3, lines.getResultContents().size());
assertEquals(commit1, lines.getSourceCommit(0));
assertEquals(0, lines.getSourceLine(0));
assertEquals(commit1, lines.getSourceCommit(1));
assertEquals(1, lines.getSourceLine(1));
assertEquals(commit2, lines.getSourceCommit(2));
assertEquals(2, lines.getSourceLine(2));
try (Git git = new Git(db)) {
String[] content1 = new String[] { "first", "second" };
writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
RevCommit commit1 = git.commit().setMessage("create file").call();
String[] content2 = new String[] { "first", "second", "third" };
writeTrashFile("file.txt", join(content2));
git.add().addFilepattern("file.txt").call();
RevCommit commit2 = git.commit().setMessage("create file").call();
BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(3, lines.getResultContents().size());
assertEquals(commit1, lines.getSourceCommit(0));
assertEquals(0, lines.getSourceLine(0));
assertEquals(commit1, lines.getSourceCommit(1));
assertEquals(1, lines.getSourceLine(1));
assertEquals(commit2, lines.getSourceCommit(2));
assertEquals(2, lines.getSourceLine(2));
}
} }


@Test @Test


private void testRename(final String sourcePath, final String destPath) private void testRename(final String sourcePath, final String destPath)
throws Exception { throws Exception {
Git git = new Git(db);
String[] content1 = new String[] { "a", "b", "c" };
writeTrashFile(sourcePath, join(content1));
git.add().addFilepattern(sourcePath).call();
RevCommit commit1 = git.commit().setMessage("create file").call();
writeTrashFile(destPath, join(content1));
git.add().addFilepattern(destPath).call();
git.rm().addFilepattern(sourcePath).call();
git.commit().setMessage("moving file").call();
String[] content2 = new String[] { "a", "b", "c2" };
writeTrashFile(destPath, join(content2));
git.add().addFilepattern(destPath).call();
RevCommit commit3 = git.commit().setMessage("editing file").call();
BlameCommand command = new BlameCommand(db);
command.setFollowFileRenames(true);
command.setFilePath(destPath);
BlameResult lines = command.call();
assertEquals(commit1, lines.getSourceCommit(0));
assertEquals(0, lines.getSourceLine(0));
assertEquals(sourcePath, lines.getSourcePath(0));
assertEquals(commit1, lines.getSourceCommit(1));
assertEquals(1, lines.getSourceLine(1));
assertEquals(sourcePath, lines.getSourcePath(1));
assertEquals(commit3, lines.getSourceCommit(2));
assertEquals(2, lines.getSourceLine(2));
assertEquals(destPath, lines.getSourcePath(2));
try (Git git = new Git(db)) {
String[] content1 = new String[] { "a", "b", "c" };
writeTrashFile(sourcePath, join(content1));
git.add().addFilepattern(sourcePath).call();
RevCommit commit1 = git.commit().setMessage("create file").call();
writeTrashFile(destPath, join(content1));
git.add().addFilepattern(destPath).call();
git.rm().addFilepattern(sourcePath).call();
git.commit().setMessage("moving file").call();
String[] content2 = new String[] { "a", "b", "c2" };
writeTrashFile(destPath, join(content2));
git.add().addFilepattern(destPath).call();
RevCommit commit3 = git.commit().setMessage("editing file").call();
BlameCommand command = new BlameCommand(db);
command.setFollowFileRenames(true);
command.setFilePath(destPath);
BlameResult lines = command.call();
assertEquals(commit1, lines.getSourceCommit(0));
assertEquals(0, lines.getSourceLine(0));
assertEquals(sourcePath, lines.getSourcePath(0));
assertEquals(commit1, lines.getSourceCommit(1));
assertEquals(1, lines.getSourceLine(1));
assertEquals(sourcePath, lines.getSourcePath(1));
assertEquals(commit3, lines.getSourceCommit(2));
assertEquals(2, lines.getSourceLine(2));
assertEquals(destPath, lines.getSourcePath(2));
}
} }


@Test @Test
public void testTwoRenames() throws Exception { public void testTwoRenames() throws Exception {
Git git = new Git(db);
// Commit 1: Add file.txt
String[] content1 = new String[] { "a" };
writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
RevCommit commit1 = git.commit().setMessage("create file").call();
// Commit 2: Rename to file1.txt
writeTrashFile("file1.txt", join(content1));
git.add().addFilepattern("file1.txt").call();
git.rm().addFilepattern("file.txt").call();
git.commit().setMessage("moving file").call();
// Commit 3: Edit file1.txt
String[] content2 = new String[] { "a", "b" };
writeTrashFile("file1.txt", join(content2));
git.add().addFilepattern("file1.txt").call();
RevCommit commit3 = git.commit().setMessage("editing file").call();
// Commit 4: Rename to file2.txt
writeTrashFile("file2.txt", join(content2));
git.add().addFilepattern("file2.txt").call();
git.rm().addFilepattern("file1.txt").call();
git.commit().setMessage("moving file again").call();
BlameCommand command = new BlameCommand(db);
command.setFollowFileRenames(true);
command.setFilePath("file2.txt");
BlameResult lines = command.call();
assertEquals(commit1, lines.getSourceCommit(0));
assertEquals(0, lines.getSourceLine(0));
assertEquals("file.txt", lines.getSourcePath(0));
assertEquals(commit3, lines.getSourceCommit(1));
assertEquals(1, lines.getSourceLine(1));
assertEquals("file1.txt", lines.getSourcePath(1));
try (Git git = new Git(db)) {
// Commit 1: Add file.txt
String[] content1 = new String[] { "a" };
writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
RevCommit commit1 = git.commit().setMessage("create file").call();
// Commit 2: Rename to file1.txt
writeTrashFile("file1.txt", join(content1));
git.add().addFilepattern("file1.txt").call();
git.rm().addFilepattern("file.txt").call();
git.commit().setMessage("moving file").call();
// Commit 3: Edit file1.txt
String[] content2 = new String[] { "a", "b" };
writeTrashFile("file1.txt", join(content2));
git.add().addFilepattern("file1.txt").call();
RevCommit commit3 = git.commit().setMessage("editing file").call();
// Commit 4: Rename to file2.txt
writeTrashFile("file2.txt", join(content2));
git.add().addFilepattern("file2.txt").call();
git.rm().addFilepattern("file1.txt").call();
git.commit().setMessage("moving file again").call();
BlameCommand command = new BlameCommand(db);
command.setFollowFileRenames(true);
command.setFilePath("file2.txt");
BlameResult lines = command.call();
assertEquals(commit1, lines.getSourceCommit(0));
assertEquals(0, lines.getSourceLine(0));
assertEquals("file.txt", lines.getSourcePath(0));
assertEquals(commit3, lines.getSourceCommit(1));
assertEquals(1, lines.getSourceLine(1));
assertEquals("file1.txt", lines.getSourcePath(1));
}
} }


@Test @Test
public void testDeleteTrailingLines() throws Exception { public void testDeleteTrailingLines() throws Exception {
Git git = new Git(db);
try (Git git = new Git(db)) {
String[] content1 = new String[] { "a", "b", "c", "d" };
String[] content2 = new String[] { "a", "b" };


String[] content1 = new String[] { "a", "b", "c", "d" };
String[] content2 = new String[] { "a", "b" };
writeTrashFile("file.txt", join(content2));
git.add().addFilepattern("file.txt").call();
RevCommit commit1 = git.commit().setMessage("create file").call();


writeTrashFile("file.txt", join(content2));
git.add().addFilepattern("file.txt").call();
RevCommit commit1 = git.commit().setMessage("create file").call();
writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("edit file").call();


writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("edit file").call();
writeTrashFile("file.txt", join(content2));
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("edit file").call();


writeTrashFile("file.txt", join(content2));
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("edit file").call();
BlameCommand command = new BlameCommand(db);


BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(content2.length, lines.getResultContents().size());


command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(content2.length, lines.getResultContents().size());
assertEquals(commit1, lines.getSourceCommit(0));
assertEquals(commit1, lines.getSourceCommit(1));


assertEquals(commit1, lines.getSourceCommit(0));
assertEquals(commit1, lines.getSourceCommit(1));

assertEquals(0, lines.getSourceLine(0));
assertEquals(1, lines.getSourceLine(1));
assertEquals(0, lines.getSourceLine(0));
assertEquals(1, lines.getSourceLine(1));
}
} }


@Test @Test
public void testDeleteMiddleLines() throws Exception { public void testDeleteMiddleLines() throws Exception {
Git git = new Git(db);
try (Git git = new Git(db)) {
String[] content1 = new String[] { "a", "b", "c", "d", "e" };
String[] content2 = new String[] { "a", "c", "e" };


String[] content1 = new String[] { "a", "b", "c", "d", "e" };
String[] content2 = new String[] { "a", "c", "e" };
writeTrashFile("file.txt", join(content2));
git.add().addFilepattern("file.txt").call();
RevCommit commit1 = git.commit().setMessage("edit file").call();


writeTrashFile("file.txt", join(content2));
git.add().addFilepattern("file.txt").call();
RevCommit commit1 = git.commit().setMessage("edit file").call();
writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("edit file").call();


writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("edit file").call();
writeTrashFile("file.txt", join(content2));
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("edit file").call();


writeTrashFile("file.txt", join(content2));
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("edit file").call();
BlameCommand command = new BlameCommand(db);


BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(content2.length, lines.getResultContents().size());


command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(content2.length, lines.getResultContents().size());
assertEquals(commit1, lines.getSourceCommit(0));
assertEquals(0, lines.getSourceLine(0));


assertEquals(commit1, lines.getSourceCommit(0));
assertEquals(0, lines.getSourceLine(0));
assertEquals(commit1, lines.getSourceCommit(1));
assertEquals(1, lines.getSourceLine(1));


assertEquals(commit1, lines.getSourceCommit(1));
assertEquals(1, lines.getSourceLine(1));

assertEquals(commit1, lines.getSourceCommit(2));
assertEquals(2, lines.getSourceLine(2));
assertEquals(commit1, lines.getSourceCommit(2));
assertEquals(2, lines.getSourceLine(2));
}
} }


@Test @Test
public void testEditAllLines() throws Exception { public void testEditAllLines() throws Exception {
Git git = new Git(db);

String[] content1 = new String[] { "a", "1" };
String[] content2 = new String[] { "b", "2" };
try (Git git = new Git(db)) {
String[] content1 = new String[] { "a", "1" };
String[] content2 = new String[] { "b", "2" };


writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("edit file").call();
writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("edit file").call();


writeTrashFile("file.txt", join(content2));
git.add().addFilepattern("file.txt").call();
RevCommit commit2 = git.commit().setMessage("create file").call();
writeTrashFile("file.txt", join(content2));
git.add().addFilepattern("file.txt").call();
RevCommit commit2 = git.commit().setMessage("create file").call();


BlameCommand command = new BlameCommand(db);
BlameCommand command = new BlameCommand(db);


command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(content2.length, lines.getResultContents().size());
assertEquals(commit2, lines.getSourceCommit(0));
assertEquals(commit2, lines.getSourceCommit(1));
command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(content2.length, lines.getResultContents().size());
assertEquals(commit2, lines.getSourceCommit(0));
assertEquals(commit2, lines.getSourceCommit(1));
}
} }


@Test @Test
public void testMiddleClearAllLines() throws Exception { public void testMiddleClearAllLines() throws Exception {
Git git = new Git(db);

String[] content1 = new String[] { "a", "b", "c" };
try (Git git = new Git(db)) {
String[] content1 = new String[] { "a", "b", "c" };


writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("edit file").call();
writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("edit file").call();


writeTrashFile("file.txt", "");
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("create file").call();
writeTrashFile("file.txt", "");
git.add().addFilepattern("file.txt").call();
git.commit().setMessage("create file").call();


writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
RevCommit commit3 = git.commit().setMessage("edit file").call();
writeTrashFile("file.txt", join(content1));
git.add().addFilepattern("file.txt").call();
RevCommit commit3 = git.commit().setMessage("edit file").call();


BlameCommand command = new BlameCommand(db);
BlameCommand command = new BlameCommand(db);


command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(content1.length, lines.getResultContents().size());
assertEquals(commit3, lines.getSourceCommit(0));
assertEquals(commit3, lines.getSourceCommit(1));
assertEquals(commit3, lines.getSourceCommit(2));
command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(content1.length, lines.getResultContents().size());
assertEquals(commit3, lines.getSourceCommit(0));
assertEquals(commit3, lines.getSourceCommit(1));
assertEquals(commit3, lines.getSourceCommit(2));
}
} }


@Test @Test


private void testCoreAutoCrlf(AutoCRLF modeForCommitting, private void testCoreAutoCrlf(AutoCRLF modeForCommitting,
AutoCRLF modeForReset) throws Exception { AutoCRLF modeForReset) throws Exception {
Git git = new Git(db);
FileBasedConfig config = db.getConfig();
config.setEnum(ConfigConstants.CONFIG_CORE_SECTION, null,
ConfigConstants.CONFIG_KEY_AUTOCRLF, modeForCommitting);
config.save();

String joinedCrlf = "a\r\nb\r\nc\r\n";
File trashFile = writeTrashFile("file.txt", joinedCrlf);
git.add().addFilepattern("file.txt").call();
RevCommit commit = git.commit().setMessage("create file").call();

// re-create file from the repo
trashFile.delete();
config.setEnum(ConfigConstants.CONFIG_CORE_SECTION, null,
ConfigConstants.CONFIG_KEY_AUTOCRLF, modeForReset);
config.save();
git.reset().setMode(ResetType.HARD).call();

BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt");
BlameResult lines = command.call();

assertEquals(3, lines.getResultContents().size());
assertEquals(commit, lines.getSourceCommit(0));
assertEquals(commit, lines.getSourceCommit(1));
assertEquals(commit, lines.getSourceCommit(2));
try (Git git = new Git(db)) {
FileBasedConfig config = db.getConfig();
config.setEnum(ConfigConstants.CONFIG_CORE_SECTION, null,
ConfigConstants.CONFIG_KEY_AUTOCRLF, modeForCommitting);
config.save();

String joinedCrlf = "a\r\nb\r\nc\r\n";
File trashFile = writeTrashFile("file.txt", joinedCrlf);
git.add().addFilepattern("file.txt").call();
RevCommit commit = git.commit().setMessage("create file").call();

// re-create file from the repo
trashFile.delete();
config.setEnum(ConfigConstants.CONFIG_CORE_SECTION, null,
ConfigConstants.CONFIG_KEY_AUTOCRLF, modeForReset);
config.save();
git.reset().setMode(ResetType.HARD).call();

BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt");
BlameResult lines = command.call();

assertEquals(3, lines.getResultContents().size());
assertEquals(commit, lines.getSourceCommit(0));
assertEquals(commit, lines.getSourceCommit(1));
assertEquals(commit, lines.getSourceCommit(2));
}
} }


@Test @Test
public void testConflictingMerge1() throws Exception { public void testConflictingMerge1() throws Exception {
Git git = new Git(db);
RevCommit base = commitFile("file.txt", join("0", "1", "2", "3", "4"),
"master");
git.checkout().setName("side").setCreateBranch(true)
.setStartPoint(base).call();
RevCommit side = commitFile("file.txt",
join("0", "1 side", "2", "3 on side", "4"), "side");
commitFile("file.txt", join("0", "1", "2"), "master");
checkoutBranch("refs/heads/master");
git.merge().include(side).call();
// The merge results in a conflict, which we resolve using mostly the
// side branch contents. Especially the "4" survives.
RevCommit merge = commitFile("file.txt",
join("0", "1 side", "2", "3 resolved", "4"), "master");
BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(5, lines.getResultContents().size());
assertEquals(base, lines.getSourceCommit(0));
assertEquals(side, lines.getSourceCommit(1));
assertEquals(base, lines.getSourceCommit(2));
assertEquals(merge, lines.getSourceCommit(3));
assertEquals(base, lines.getSourceCommit(4));
try (Git git = new Git(db)) {
RevCommit base = commitFile("file.txt", join("0", "1", "2", "3", "4"),
"master");
git.checkout().setName("side").setCreateBranch(true)
.setStartPoint(base).call();
RevCommit side = commitFile("file.txt",
join("0", "1 side", "2", "3 on side", "4"), "side");
commitFile("file.txt", join("0", "1", "2"), "master");
checkoutBranch("refs/heads/master");
git.merge().include(side).call();
// The merge results in a conflict, which we resolve using mostly the
// side branch contents. Especially the "4" survives.
RevCommit merge = commitFile("file.txt",
join("0", "1 side", "2", "3 resolved", "4"), "master");
BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(5, lines.getResultContents().size());
assertEquals(base, lines.getSourceCommit(0));
assertEquals(side, lines.getSourceCommit(1));
assertEquals(base, lines.getSourceCommit(2));
assertEquals(merge, lines.getSourceCommit(3));
assertEquals(base, lines.getSourceCommit(4));
}
} }


// this test inverts the order of the master and side commit and is // this test inverts the order of the master and side commit and is
// otherwise identical to testConflictingMerge1 // otherwise identical to testConflictingMerge1
@Test @Test
public void testConflictingMerge2() throws Exception { public void testConflictingMerge2() throws Exception {
Git git = new Git(db);
RevCommit base = commitFile("file.txt", join("0", "1", "2", "3", "4"),
"master");
commitFile("file.txt", join("0", "1", "2"), "master");
git.checkout().setName("side").setCreateBranch(true)
.setStartPoint(base).call();
RevCommit side = commitFile("file.txt",
join("0", "1 side", "2", "3 on side", "4"), "side");
checkoutBranch("refs/heads/master");
git.merge().include(side).call();
// The merge results in a conflict, which we resolve using mostly the
// side branch contents. Especially the "4" survives.
RevCommit merge = commitFile("file.txt",
join("0", "1 side", "2", "3 resolved", "4"), "master");
BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(5, lines.getResultContents().size());
assertEquals(base, lines.getSourceCommit(0));
assertEquals(side, lines.getSourceCommit(1));
assertEquals(base, lines.getSourceCommit(2));
assertEquals(merge, lines.getSourceCommit(3));
assertEquals(base, lines.getSourceCommit(4));
try (Git git = new Git(db)) {
RevCommit base = commitFile("file.txt", join("0", "1", "2", "3", "4"),
"master");
commitFile("file.txt", join("0", "1", "2"), "master");
git.checkout().setName("side").setCreateBranch(true)
.setStartPoint(base).call();
RevCommit side = commitFile("file.txt",
join("0", "1 side", "2", "3 on side", "4"), "side");
checkoutBranch("refs/heads/master");
git.merge().include(side).call();
// The merge results in a conflict, which we resolve using mostly the
// side branch contents. Especially the "4" survives.
RevCommit merge = commitFile("file.txt",
join("0", "1 side", "2", "3 resolved", "4"), "master");
BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt");
BlameResult lines = command.call();
assertEquals(5, lines.getResultContents().size());
assertEquals(base, lines.getSourceCommit(0));
assertEquals(side, lines.getSourceCommit(1));
assertEquals(base, lines.getSourceCommit(2));
assertEquals(merge, lines.getSourceCommit(3));
assertEquals(base, lines.getSourceCommit(4));
}
} }


@Test @Test
public void testWhitespaceMerge() throws Exception { public void testWhitespaceMerge() throws Exception {
Git git = new Git(db);
RevCommit base = commitFile("file.txt", join("0", "1", "2"), "master");
RevCommit side = commitFile("file.txt", join("0", "1", " 2 side "),
"side");

checkoutBranch("refs/heads/master");
git.merge().setFastForward(FastForwardMode.NO_FF).include(side).call();

// change whitespace, so the merge content is not identical to side, but
// is the same when ignoring whitespace
writeTrashFile("file.txt", join("0", "1", "2 side"));
RevCommit merge = git.commit().setAll(true).setMessage("merge")
.setAmend(true)
.call();

BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt")
.setTextComparator(RawTextComparator.WS_IGNORE_ALL)
.setStartCommit(merge.getId());
BlameResult lines = command.call();

assertEquals(3, lines.getResultContents().size());
assertEquals(base, lines.getSourceCommit(0));
assertEquals(base, lines.getSourceCommit(1));
assertEquals(side, lines.getSourceCommit(2));
try (Git git = new Git(db)) {
RevCommit base = commitFile("file.txt", join("0", "1", "2"), "master");
RevCommit side = commitFile("file.txt", join("0", "1", " 2 side "),
"side");

checkoutBranch("refs/heads/master");
git.merge().setFastForward(FastForwardMode.NO_FF).include(side).call();

// change whitespace, so the merge content is not identical to side, but
// is the same when ignoring whitespace
writeTrashFile("file.txt", join("0", "1", "2 side"));
RevCommit merge = git.commit().setAll(true).setMessage("merge")
.setAmend(true)
.call();

BlameCommand command = new BlameCommand(db);
command.setFilePath("file.txt")
.setTextComparator(RawTextComparator.WS_IGNORE_ALL)
.setStartCommit(merge.getId());
BlameResult lines = command.call();

assertEquals(3, lines.getResultContents().size());
assertEquals(base, lines.getSourceCommit(0));
assertEquals(base, lines.getSourceCommit(1));
assertEquals(side, lines.getSourceCommit(2));
}
} }
} }

+ 197
- 191
org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CherryPickCommandTest.java Ver arquivo

private void doTestCherryPick(boolean noCommit) throws IOException, private void doTestCherryPick(boolean noCommit) throws IOException,
JGitInternalException, JGitInternalException,
GitAPIException { GitAPIException {
Git git = new Git(db);
writeTrashFile("a", "first line\nsec. line\nthird line\n");
git.add().addFilepattern("a").call();
RevCommit firstCommit = git.commit().setMessage("create a").call();
writeTrashFile("b", "content\n");
git.add().addFilepattern("b").call();
git.commit().setMessage("create b").call();
writeTrashFile("a", "first line\nsec. line\nthird line\nfourth line\n");
git.add().addFilepattern("a").call();
git.commit().setMessage("enlarged a").call();
writeTrashFile("a",
"first line\nsecond line\nthird line\nfourth line\n");
git.add().addFilepattern("a").call();
RevCommit fixingA = git.commit().setMessage("fixed a").call();
git.branchCreate().setName("side").setStartPoint(firstCommit).call();
checkoutBranch("refs/heads/side");
writeTrashFile("a", "first line\nsec. line\nthird line\nfeature++\n");
git.add().addFilepattern("a").call();
git.commit().setMessage("enhanced a").call();
CherryPickResult pickResult = git.cherryPick().include(fixingA)
.setNoCommit(noCommit).call();
assertEquals(CherryPickStatus.OK, pickResult.getStatus());
assertFalse(new File(db.getWorkTree(), "b").exists());
checkFile(new File(db.getWorkTree(), "a"),
"first line\nsecond line\nthird line\nfeature++\n");
Iterator<RevCommit> history = git.log().call().iterator();
if (!noCommit)
assertEquals("fixed a", history.next().getFullMessage());
assertEquals("enhanced a", history.next().getFullMessage());
assertEquals("create a", history.next().getFullMessage());
assertFalse(history.hasNext());
try (Git git = new Git(db)) {
writeTrashFile("a", "first line\nsec. line\nthird line\n");
git.add().addFilepattern("a").call();
RevCommit firstCommit = git.commit().setMessage("create a").call();
writeTrashFile("b", "content\n");
git.add().addFilepattern("b").call();
git.commit().setMessage("create b").call();
writeTrashFile("a", "first line\nsec. line\nthird line\nfourth line\n");
git.add().addFilepattern("a").call();
git.commit().setMessage("enlarged a").call();
writeTrashFile("a",
"first line\nsecond line\nthird line\nfourth line\n");
git.add().addFilepattern("a").call();
RevCommit fixingA = git.commit().setMessage("fixed a").call();
git.branchCreate().setName("side").setStartPoint(firstCommit).call();
checkoutBranch("refs/heads/side");
writeTrashFile("a", "first line\nsec. line\nthird line\nfeature++\n");
git.add().addFilepattern("a").call();
git.commit().setMessage("enhanced a").call();
CherryPickResult pickResult = git.cherryPick().include(fixingA)
.setNoCommit(noCommit).call();
assertEquals(CherryPickStatus.OK, pickResult.getStatus());
assertFalse(new File(db.getWorkTree(), "b").exists());
checkFile(new File(db.getWorkTree(), "a"),
"first line\nsecond line\nthird line\nfeature++\n");
Iterator<RevCommit> history = git.log().call().iterator();
if (!noCommit)
assertEquals("fixed a", history.next().getFullMessage());
assertEquals("enhanced a", history.next().getFullMessage());
assertEquals("create a", history.next().getFullMessage());
assertFalse(history.hasNext());
}
} }


@Test @Test
public void testSequentialCherryPick() throws IOException, JGitInternalException, public void testSequentialCherryPick() throws IOException, JGitInternalException,
GitAPIException { GitAPIException {
Git git = new Git(db);
writeTrashFile("a", "first line\nsec. line\nthird line\n");
git.add().addFilepattern("a").call();
RevCommit firstCommit = git.commit().setMessage("create a").call();
writeTrashFile("a", "first line\nsec. line\nthird line\nfourth line\n");
git.add().addFilepattern("a").call();
RevCommit enlargingA = git.commit().setMessage("enlarged a").call();
writeTrashFile("a",
"first line\nsecond line\nthird line\nfourth line\n");
git.add().addFilepattern("a").call();
RevCommit fixingA = git.commit().setMessage("fixed a").call();
git.branchCreate().setName("side").setStartPoint(firstCommit).call();
checkoutBranch("refs/heads/side");
writeTrashFile("b", "nothing to do with a");
git.add().addFilepattern("b").call();
git.commit().setMessage("create b").call();
CherryPickResult result = git.cherryPick().include(enlargingA).include(fixingA).call();
assertEquals(CherryPickResult.CherryPickStatus.OK, result.getStatus());
Iterator<RevCommit> history = git.log().call().iterator();
assertEquals("fixed a", history.next().getFullMessage());
assertEquals("enlarged a", history.next().getFullMessage());
assertEquals("create b", history.next().getFullMessage());
assertEquals("create a", history.next().getFullMessage());
assertFalse(history.hasNext());
try (Git git = new Git(db)) {
writeTrashFile("a", "first line\nsec. line\nthird line\n");
git.add().addFilepattern("a").call();
RevCommit firstCommit = git.commit().setMessage("create a").call();
writeTrashFile("a", "first line\nsec. line\nthird line\nfourth line\n");
git.add().addFilepattern("a").call();
RevCommit enlargingA = git.commit().setMessage("enlarged a").call();
writeTrashFile("a",
"first line\nsecond line\nthird line\nfourth line\n");
git.add().addFilepattern("a").call();
RevCommit fixingA = git.commit().setMessage("fixed a").call();
git.branchCreate().setName("side").setStartPoint(firstCommit).call();
checkoutBranch("refs/heads/side");
writeTrashFile("b", "nothing to do with a");
git.add().addFilepattern("b").call();
git.commit().setMessage("create b").call();
CherryPickResult result = git.cherryPick().include(enlargingA).include(fixingA).call();
assertEquals(CherryPickResult.CherryPickStatus.OK, result.getStatus());
Iterator<RevCommit> history = git.log().call().iterator();
assertEquals("fixed a", history.next().getFullMessage());
assertEquals("enlarged a", history.next().getFullMessage());
assertEquals("create b", history.next().getFullMessage());
assertEquals("create a", history.next().getFullMessage());
assertFalse(history.hasNext());
}
} }


@Test @Test
public void testCherryPickDirtyIndex() throws Exception { public void testCherryPickDirtyIndex() throws Exception {
Git git = new Git(db);
RevCommit sideCommit = prepareCherryPick(git);
try (Git git = new Git(db)) {
RevCommit sideCommit = prepareCherryPick(git);


// modify and add file a
writeTrashFile("a", "a(modified)");
git.add().addFilepattern("a").call();
// do not commit
// modify and add file a
writeTrashFile("a", "a(modified)");
git.add().addFilepattern("a").call();
// do not commit


doCherryPickAndCheckResult(git, sideCommit,
MergeFailureReason.DIRTY_INDEX);
doCherryPickAndCheckResult(git, sideCommit,
MergeFailureReason.DIRTY_INDEX);
}
} }


@Test @Test
public void testCherryPickDirtyWorktree() throws Exception { public void testCherryPickDirtyWorktree() throws Exception {
Git git = new Git(db);
RevCommit sideCommit = prepareCherryPick(git);
try (Git git = new Git(db)) {
RevCommit sideCommit = prepareCherryPick(git);


// modify file a
writeTrashFile("a", "a(modified)");
// do not add and commit
// modify file a
writeTrashFile("a", "a(modified)");
// do not add and commit


doCherryPickAndCheckResult(git, sideCommit,
MergeFailureReason.DIRTY_WORKTREE);
doCherryPickAndCheckResult(git, sideCommit,
MergeFailureReason.DIRTY_WORKTREE);
}
} }


@Test @Test
public void testCherryPickConflictResolution() throws Exception { public void testCherryPickConflictResolution() throws Exception {
Git git = new Git(db);
RevCommit sideCommit = prepareCherryPick(git);
try (Git git = new Git(db)) {
RevCommit sideCommit = prepareCherryPick(git);


CherryPickResult result = git.cherryPick().include(sideCommit.getId())
.call();
CherryPickResult result = git.cherryPick().include(sideCommit.getId())
.call();


assertEquals(CherryPickStatus.CONFLICTING, result.getStatus());
assertTrue(new File(db.getDirectory(), Constants.MERGE_MSG).exists());
assertEquals("side\n\nConflicts:\n\ta\n", db.readMergeCommitMsg());
assertTrue(new File(db.getDirectory(), Constants.CHERRY_PICK_HEAD)
.exists());
assertEquals(sideCommit.getId(), db.readCherryPickHead());
assertEquals(RepositoryState.CHERRY_PICKING, db.getRepositoryState());
assertEquals(CherryPickStatus.CONFLICTING, result.getStatus());
assertTrue(new File(db.getDirectory(), Constants.MERGE_MSG).exists());
assertEquals("side\n\nConflicts:\n\ta\n", db.readMergeCommitMsg());
assertTrue(new File(db.getDirectory(), Constants.CHERRY_PICK_HEAD)
.exists());
assertEquals(sideCommit.getId(), db.readCherryPickHead());
assertEquals(RepositoryState.CHERRY_PICKING, db.getRepositoryState());


// Resolve
writeTrashFile("a", "a");
git.add().addFilepattern("a").call();
// Resolve
writeTrashFile("a", "a");
git.add().addFilepattern("a").call();


assertEquals(RepositoryState.CHERRY_PICKING_RESOLVED,
db.getRepositoryState());
assertEquals(RepositoryState.CHERRY_PICKING_RESOLVED,
db.getRepositoryState());


git.commit().setOnly("a").setMessage("resolve").call();
git.commit().setOnly("a").setMessage("resolve").call();


assertEquals(RepositoryState.SAFE, db.getRepositoryState());
assertEquals(RepositoryState.SAFE, db.getRepositoryState());
}
} }


@Test @Test


@Test @Test
public void testCherryPickConflictReset() throws Exception { public void testCherryPickConflictReset() throws Exception {
Git git = new Git(db);

RevCommit sideCommit = prepareCherryPick(git);
try (Git git = new Git(db)) {
RevCommit sideCommit = prepareCherryPick(git);


CherryPickResult result = git.cherryPick().include(sideCommit.getId())
.call();
CherryPickResult result = git.cherryPick().include(sideCommit.getId())
.call();


assertEquals(CherryPickStatus.CONFLICTING, result.getStatus());
assertEquals(RepositoryState.CHERRY_PICKING, db.getRepositoryState());
assertTrue(new File(db.getDirectory(), Constants.CHERRY_PICK_HEAD)
.exists());
assertEquals(CherryPickStatus.CONFLICTING, result.getStatus());
assertEquals(RepositoryState.CHERRY_PICKING, db.getRepositoryState());
assertTrue(new File(db.getDirectory(), Constants.CHERRY_PICK_HEAD)
.exists());


git.reset().setMode(ResetType.MIXED).setRef("HEAD").call();
git.reset().setMode(ResetType.MIXED).setRef("HEAD").call();


assertEquals(RepositoryState.SAFE, db.getRepositoryState());
assertFalse(new File(db.getDirectory(), Constants.CHERRY_PICK_HEAD)
.exists());
assertEquals(RepositoryState.SAFE, db.getRepositoryState());
assertFalse(new File(db.getDirectory(), Constants.CHERRY_PICK_HEAD)
.exists());
}
} }


@Test @Test
public void testCherryPickOverExecutableChangeOnNonExectuableFileSystem() public void testCherryPickOverExecutableChangeOnNonExectuableFileSystem()
throws Exception { throws Exception {
Git git = new Git(db);
File file = writeTrashFile("test.txt", "a");
assertNotNull(git.add().addFilepattern("test.txt").call());
assertNotNull(git.commit().setMessage("commit1").call());
try (Git git = new Git(db)) {
File file = writeTrashFile("test.txt", "a");
assertNotNull(git.add().addFilepattern("test.txt").call());
assertNotNull(git.commit().setMessage("commit1").call());


assertNotNull(git.checkout().setCreateBranch(true).setName("a").call());
assertNotNull(git.checkout().setCreateBranch(true).setName("a").call());


writeTrashFile("test.txt", "b");
assertNotNull(git.add().addFilepattern("test.txt").call());
RevCommit commit2 = git.commit().setMessage("commit2").call();
assertNotNull(commit2);
writeTrashFile("test.txt", "b");
assertNotNull(git.add().addFilepattern("test.txt").call());
RevCommit commit2 = git.commit().setMessage("commit2").call();
assertNotNull(commit2);


assertNotNull(git.checkout().setName(Constants.MASTER).call());
assertNotNull(git.checkout().setName(Constants.MASTER).call());


DirCache cache = db.lockDirCache();
cache.getEntry("test.txt").setFileMode(FileMode.EXECUTABLE_FILE);
cache.write();
assertTrue(cache.commit());
cache.unlock();
DirCache cache = db.lockDirCache();
cache.getEntry("test.txt").setFileMode(FileMode.EXECUTABLE_FILE);
cache.write();
assertTrue(cache.commit());
cache.unlock();


assertNotNull(git.commit().setMessage("commit3").call());
assertNotNull(git.commit().setMessage("commit3").call());


db.getFS().setExecute(file, false);
git.getRepository()
.getConfig()
.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
ConfigConstants.CONFIG_KEY_FILEMODE, false);
db.getFS().setExecute(file, false);
git.getRepository()
.getConfig()
.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
ConfigConstants.CONFIG_KEY_FILEMODE, false);


CherryPickResult result = git.cherryPick().include(commit2).call();
assertNotNull(result);
assertEquals(CherryPickStatus.OK, result.getStatus());
CherryPickResult result = git.cherryPick().include(commit2).call();
assertNotNull(result);
assertEquals(CherryPickStatus.OK, result.getStatus());
}
} }


@Test @Test
public void testCherryPickConflictMarkers() throws Exception { public void testCherryPickConflictMarkers() throws Exception {
Git git = new Git(db);
RevCommit sideCommit = prepareCherryPick(git);
try (Git git = new Git(db)) {
RevCommit sideCommit = prepareCherryPick(git);


CherryPickResult result = git.cherryPick().include(sideCommit.getId())
.call();
assertEquals(CherryPickStatus.CONFLICTING, result.getStatus());
CherryPickResult result = git.cherryPick().include(sideCommit.getId())
.call();
assertEquals(CherryPickStatus.CONFLICTING, result.getStatus());


String expected = "<<<<<<< master\na(master)\n=======\na(side)\n>>>>>>> 527460a side\n";
checkFile(new File(db.getWorkTree(), "a"), expected);
String expected = "<<<<<<< master\na(master)\n=======\na(side)\n>>>>>>> 527460a side\n";
checkFile(new File(db.getWorkTree(), "a"), expected);
}
} }


@Test @Test
public void testCherryPickOurCommitName() throws Exception { public void testCherryPickOurCommitName() throws Exception {
Git git = new Git(db);
RevCommit sideCommit = prepareCherryPick(git);
try (Git git = new Git(db)) {
RevCommit sideCommit = prepareCherryPick(git);


CherryPickResult result = git.cherryPick().include(sideCommit.getId())
.setOurCommitName("custom name").call();
assertEquals(CherryPickStatus.CONFLICTING, result.getStatus());
CherryPickResult result = git.cherryPick().include(sideCommit.getId())
.setOurCommitName("custom name").call();
assertEquals(CherryPickStatus.CONFLICTING, result.getStatus());


String expected = "<<<<<<< custom name\na(master)\n=======\na(side)\n>>>>>>> 527460a side\n";
checkFile(new File(db.getWorkTree(), "a"), expected);
String expected = "<<<<<<< custom name\na(master)\n=======\na(side)\n>>>>>>> 527460a side\n";
checkFile(new File(db.getWorkTree(), "a"), expected);
}
} }


private RevCommit prepareCherryPick(final Git git) throws Exception { private RevCommit prepareCherryPick(final Git git) throws Exception {
*/ */
@Test @Test
public void testCherryPickMerge() throws Exception { public void testCherryPickMerge() throws Exception {
Git git = new Git(db);

commitFile("file", "1\n2\n3\n", "master");
commitFile("file", "1\n2\n3\n", "side");
checkoutBranch("refs/heads/side");
RevCommit commitD = commitFile("file", "1\n2\n3\n4\n5\n", "side2");
commitFile("file", "a\n2\n3\n", "side");
MergeResult mergeResult = git.merge().include(commitD).call();
ObjectId commitM = mergeResult.getNewHead();
checkoutBranch("refs/heads/master");
RevCommit commitT = commitFile("another", "t", "master");

try {
git.cherryPick().include(commitM).call();
fail("merges should not be cherry-picked by default");
} catch (MultipleParentsNotAllowedException e) {
// expected
try (Git git = new Git(db)) {
commitFile("file", "1\n2\n3\n", "master");
commitFile("file", "1\n2\n3\n", "side");
checkoutBranch("refs/heads/side");
RevCommit commitD = commitFile("file", "1\n2\n3\n4\n5\n", "side2");
commitFile("file", "a\n2\n3\n", "side");
MergeResult mergeResult = git.merge().include(commitD).call();
ObjectId commitM = mergeResult.getNewHead();
checkoutBranch("refs/heads/master");
RevCommit commitT = commitFile("another", "t", "master");

try {
git.cherryPick().include(commitM).call();
fail("merges should not be cherry-picked by default");
} catch (MultipleParentsNotAllowedException e) {
// expected
}
try {
git.cherryPick().include(commitM).setMainlineParentNumber(3).call();
fail("specifying a non-existent parent should fail");
} catch (JGitInternalException e) {
// expected
assertTrue(e.getMessage().endsWith(
"does not have a parent number 3."));
}

CherryPickResult result = git.cherryPick().include(commitM)
.setMainlineParentNumber(1).call();
assertEquals(CherryPickStatus.OK, result.getStatus());
checkFile(new File(db.getWorkTree(), "file"), "1\n2\n3\n4\n5\n");

git.reset().setMode(ResetType.HARD).setRef(commitT.getName()).call();

CherryPickResult result2 = git.cherryPick().include(commitM)
.setMainlineParentNumber(2).call();
assertEquals(CherryPickStatus.OK, result2.getStatus());
checkFile(new File(db.getWorkTree(), "file"), "a\n2\n3\n");
} }
try {
git.cherryPick().include(commitM).setMainlineParentNumber(3).call();
fail("specifying a non-existent parent should fail");
} catch (JGitInternalException e) {
// expected
assertTrue(e.getMessage().endsWith(
"does not have a parent number 3."));
}

CherryPickResult result = git.cherryPick().include(commitM)
.setMainlineParentNumber(1).call();
assertEquals(CherryPickStatus.OK, result.getStatus());
checkFile(new File(db.getWorkTree(), "file"), "1\n2\n3\n4\n5\n");

git.reset().setMode(ResetType.HARD).setRef(commitT.getName()).call();

CherryPickResult result2 = git.cherryPick().include(commitM)
.setMainlineParentNumber(2).call();
assertEquals(CherryPickStatus.OK, result2.getStatus());
checkFile(new File(db.getWorkTree(), "file"), "a\n2\n3\n");
} }
} }

+ 258
- 252
org.eclipse.jgit.test/tst/org/eclipse/jgit/api/CommitAndLogCommandTest.java Ver arquivo

import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse;


import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
GitAPIException { GitAPIException {


// do 4 commits // do 4 commits
Git git = new Git(db);
git.commit().setMessage("initial commit").call();
git.commit().setMessage("second commit").setCommitter(committer).call();
git.commit().setMessage("third commit").setAuthor(author).call();
git.commit().setMessage("fourth commit").setAuthor(author)
.setCommitter(committer).call();
Iterable<RevCommit> commits = git.log().call();

// check that all commits came in correctly
PersonIdent defaultCommitter = new PersonIdent(db);
PersonIdent expectedAuthors[] = new PersonIdent[] { defaultCommitter,
committer, author, author };
PersonIdent expectedCommitters[] = new PersonIdent[] {
defaultCommitter, committer, defaultCommitter, committer };
String expectedMessages[] = new String[] { "initial commit",
"second commit", "third commit", "fourth commit" };
int l = expectedAuthors.length - 1;
for (RevCommit c : commits) {
assertEquals(expectedAuthors[l].getName(), c.getAuthorIdent()
.getName());
assertEquals(expectedCommitters[l].getName(), c.getCommitterIdent()
.getName());
assertEquals(c.getFullMessage(), expectedMessages[l]);
l--;
try (Git git = new Git(db)) {
git.commit().setMessage("initial commit").call();
git.commit().setMessage("second commit").setCommitter(committer).call();
git.commit().setMessage("third commit").setAuthor(author).call();
git.commit().setMessage("fourth commit").setAuthor(author)
.setCommitter(committer).call();
Iterable<RevCommit> commits = git.log().call();

// check that all commits came in correctly
PersonIdent defaultCommitter = new PersonIdent(db);
PersonIdent expectedAuthors[] = new PersonIdent[] { defaultCommitter,
committer, author, author };
PersonIdent expectedCommitters[] = new PersonIdent[] {
defaultCommitter, committer, defaultCommitter, committer };
String expectedMessages[] = new String[] { "initial commit",
"second commit", "third commit", "fourth commit" };
int l = expectedAuthors.length - 1;
for (RevCommit c : commits) {
assertEquals(expectedAuthors[l].getName(), c.getAuthorIdent()
.getName());
assertEquals(expectedCommitters[l].getName(), c.getCommitterIdent()
.getName());
assertEquals(c.getFullMessage(), expectedMessages[l]);
l--;
}
assertEquals(l, -1);
ReflogReader reader = db.getReflogReader(Constants.HEAD);
assertTrue(reader.getLastEntry().getComment().startsWith("commit:"));
reader = db.getReflogReader(db.getBranch());
assertTrue(reader.getLastEntry().getComment().startsWith("commit:"));
} }
assertEquals(l, -1);
ReflogReader reader = db.getReflogReader(Constants.HEAD);
assertTrue(reader.getLastEntry().getComment().startsWith("commit:"));
reader = db.getReflogReader(db.getBranch());
assertTrue(reader.getLastEntry().getComment().startsWith("commit:"));
} }


@Test @Test
public void testLogWithFilter() throws IOException, JGitInternalException, public void testLogWithFilter() throws IOException, JGitInternalException,
GitAPIException { GitAPIException {


Git git = new Git(db);

// create first file
File file = new File(db.getWorkTree(), "a.txt");
FileUtils.createNewFile(file);
PrintWriter writer = new PrintWriter(file);
writer.print("content1");
writer.close();

// First commit - a.txt file
git.add().addFilepattern("a.txt").call();
git.commit().setMessage("commit1").setCommitter(committer).call();

// create second file
file = new File(db.getWorkTree(), "b.txt");
FileUtils.createNewFile(file);
writer = new PrintWriter(file);
writer.print("content2");
writer.close();

// Second commit - b.txt file
git.add().addFilepattern("b.txt").call();
git.commit().setMessage("commit2").setCommitter(committer).call();

// First log - a.txt filter
int count = 0;
for (RevCommit c : git.log().addPath("a.txt").call()) {
assertEquals("commit1", c.getFullMessage());
count++;
}
assertEquals(1, count);

// Second log - b.txt filter
count = 0;
for (RevCommit c : git.log().addPath("b.txt").call()) {
assertEquals("commit2", c.getFullMessage());
count++;
}
assertEquals(1, count);

// Third log - without filter
count = 0;
for (RevCommit c : git.log().call()) {
assertEquals(committer, c.getCommitterIdent());
count++;
try (Git git = new Git(db)) {
// create first file
File file = new File(db.getWorkTree(), "a.txt");
FileUtils.createNewFile(file);
PrintWriter writer = new PrintWriter(file);
writer.print("content1");
writer.close();

// First commit - a.txt file
git.add().addFilepattern("a.txt").call();
git.commit().setMessage("commit1").setCommitter(committer).call();

// create second file
file = new File(db.getWorkTree(), "b.txt");
FileUtils.createNewFile(file);
writer = new PrintWriter(file);
writer.print("content2");
writer.close();

// Second commit - b.txt file
git.add().addFilepattern("b.txt").call();
git.commit().setMessage("commit2").setCommitter(committer).call();

// First log - a.txt filter
int count = 0;
for (RevCommit c : git.log().addPath("a.txt").call()) {
assertEquals("commit1", c.getFullMessage());
count++;
}
assertEquals(1, count);

// Second log - b.txt filter
count = 0;
for (RevCommit c : git.log().addPath("b.txt").call()) {
assertEquals("commit2", c.getFullMessage());
count++;
}
assertEquals(1, count);

// Third log - without filter
count = 0;
for (RevCommit c : git.log().call()) {
assertEquals(committer, c.getCommitterIdent());
count++;
}
assertEquals(2, count);
} }
assertEquals(2, count);
} }


// try to do a commit without specifying a message. Should fail! // try to do a commit without specifying a message. Should fail!
@Test @Test
public void testWrongParams() throws GitAPIException { public void testWrongParams() throws GitAPIException {
Git git = new Git(db);
try {
try (Git git = new Git(db)) {
git.commit().setAuthor(author).call(); git.commit().setAuthor(author).call();
fail("Didn't get the expected exception"); fail("Didn't get the expected exception");
} catch (NoMessageException e) { } catch (NoMessageException e) {
// exceptions // exceptions
@Test @Test
public void testMultipleInvocations() throws GitAPIException { public void testMultipleInvocations() throws GitAPIException {
Git git = new Git(db);
CommitCommand commitCmd = git.commit();
commitCmd.setMessage("initial commit").call();
try {
// check that setters can't be called after invocation
commitCmd.setAuthor(author);
fail("didn't catch the expected exception");
} catch (IllegalStateException e) {
// expected
}
LogCommand logCmd = git.log();
logCmd.call();
try {
// check that call can't be called twice
try (Git git = new Git(db)) {
CommitCommand commitCmd = git.commit();
commitCmd.setMessage("initial commit").call();
try {
// check that setters can't be called after invocation
commitCmd.setAuthor(author);
fail("didn't catch the expected exception");
} catch (IllegalStateException e) {
// expected
}
LogCommand logCmd = git.log();
logCmd.call(); logCmd.call();
fail("didn't catch the expected exception");
} catch (IllegalStateException e) {
// expected
try {
// check that call can't be called twice
logCmd.call();
fail("didn't catch the expected exception");
} catch (IllegalStateException e) {
// expected
}
} }
} }


@Test @Test
public void testMergeEmptyBranches() throws IOException, public void testMergeEmptyBranches() throws IOException,
JGitInternalException, GitAPIException { JGitInternalException, GitAPIException {
Git git = new Git(db);
git.commit().setMessage("initial commit").call();
RefUpdate r = db.updateRef("refs/heads/side");
r.setNewObjectId(db.resolve(Constants.HEAD));
assertEquals(r.forceUpdate(), RefUpdate.Result.NEW);
RevCommit second = git.commit().setMessage("second commit").setCommitter(committer).call();
db.updateRef(Constants.HEAD).link("refs/heads/side");
RevCommit firstSide = git.commit().setMessage("first side commit").setAuthor(author).call();

write(new File(db.getDirectory(), Constants.MERGE_HEAD), ObjectId
.toString(db.resolve("refs/heads/master")));
write(new File(db.getDirectory(), Constants.MERGE_MSG), "merging");

RevCommit commit = git.commit().call();
RevCommit[] parents = commit.getParents();
assertEquals(parents[0], firstSide);
assertEquals(parents[1], second);
assertEquals(2, parents.length);
try (Git git = new Git(db)) {
git.commit().setMessage("initial commit").call();
RefUpdate r = db.updateRef("refs/heads/side");
r.setNewObjectId(db.resolve(Constants.HEAD));
assertEquals(r.forceUpdate(), RefUpdate.Result.NEW);
RevCommit second = git.commit().setMessage("second commit").setCommitter(committer).call();
db.updateRef(Constants.HEAD).link("refs/heads/side");
RevCommit firstSide = git.commit().setMessage("first side commit").setAuthor(author).call();

write(new File(db.getDirectory(), Constants.MERGE_HEAD), ObjectId
.toString(db.resolve("refs/heads/master")));
write(new File(db.getDirectory(), Constants.MERGE_MSG), "merging");

RevCommit commit = git.commit().call();
RevCommit[] parents = commit.getParents();
assertEquals(parents[0], firstSide);
assertEquals(parents[1], second);
assertEquals(2, parents.length);
}
} }


@Test @Test
writer.print("content"); writer.print("content");
writer.close(); writer.close();


Git git = new Git(db);
git.add().addFilepattern("a.txt").call();
RevCommit commit = git.commit().setMessage("initial commit").call();
TreeWalk tw = TreeWalk.forPath(db, "a.txt", commit.getTree());
assertEquals("6b584e8ece562ebffc15d38808cd6b98fc3d97ea",
tw.getObjectId(0).getName());

writer = new PrintWriter(file);
writer.print("content2");
writer.close();
commit = git.commit().setMessage("second commit").call();
tw = TreeWalk.forPath(db, "a.txt", commit.getTree());
assertEquals("6b584e8ece562ebffc15d38808cd6b98fc3d97ea",
tw.getObjectId(0).getName());

commit = git.commit().setAll(true).setMessage("third commit")
.setAll(true).call();
tw = TreeWalk.forPath(db, "a.txt", commit.getTree());
assertEquals("db00fd65b218578127ea51f3dffac701f12f486a",
tw.getObjectId(0).getName());
try (Git git = new Git(db)) {
git.add().addFilepattern("a.txt").call();
RevCommit commit = git.commit().setMessage("initial commit").call();
TreeWalk tw = TreeWalk.forPath(db, "a.txt", commit.getTree());
assertEquals("6b584e8ece562ebffc15d38808cd6b98fc3d97ea",
tw.getObjectId(0).getName());

writer = new PrintWriter(file);
writer.print("content2");
writer.close();
commit = git.commit().setMessage("second commit").call();
tw = TreeWalk.forPath(db, "a.txt", commit.getTree());
assertEquals("6b584e8ece562ebffc15d38808cd6b98fc3d97ea",
tw.getObjectId(0).getName());

commit = git.commit().setAll(true).setMessage("third commit")
.setAll(true).call();
tw = TreeWalk.forPath(db, "a.txt", commit.getTree());
assertEquals("db00fd65b218578127ea51f3dffac701f12f486a",
tw.getObjectId(0).getName());
}
} }


@Test @Test
public void testModeChange() throws IOException, GitAPIException { public void testModeChange() throws IOException, GitAPIException {
if (System.getProperty("os.name").startsWith("Windows"))
return; // SKIP
Git git = new Git(db);

// create file
File file = new File(db.getWorkTree(), "a.txt");
FileUtils.createNewFile(file);
PrintWriter writer = new PrintWriter(file);
writer.print("content1");
writer.close();

// First commit - a.txt file
git.add().addFilepattern("a.txt").call();
git.commit().setMessage("commit1").setCommitter(committer).call();

// pure mode change should be committable
FS fs = db.getFS();
fs.setExecute(file, true);
git.add().addFilepattern("a.txt").call();
git.commit().setMessage("mode change").setCommitter(committer).call();

// pure mode change should be committable with -o option
fs.setExecute(file, false);
git.add().addFilepattern("a.txt").call();
git.commit().setMessage("mode change").setCommitter(committer)
.setOnly("a.txt").call();
assumeFalse(System.getProperty("os.name").startsWith("Windows"));// SKIP
try (Git git = new Git(db)) {
// create file
File file = new File(db.getWorkTree(), "a.txt");
FileUtils.createNewFile(file);
PrintWriter writer = new PrintWriter(file);
writer.print("content1");
writer.close();

// First commit - a.txt file
git.add().addFilepattern("a.txt").call();
git.commit().setMessage("commit1").setCommitter(committer).call();

// pure mode change should be committable
FS fs = db.getFS();
fs.setExecute(file, true);
git.add().addFilepattern("a.txt").call();
git.commit().setMessage("mode change").setCommitter(committer).call();

// pure mode change should be committable with -o option
fs.setExecute(file, false);
git.add().addFilepattern("a.txt").call();
git.commit().setMessage("mode change").setCommitter(committer)
.setOnly("a.txt").call();
}
} }


@Test @Test
JGitInternalException, MissingObjectException, JGitInternalException, MissingObjectException,
IncorrectObjectTypeException { IncorrectObjectTypeException {
// do 4 commits and set the range to the second and fourth one // do 4 commits and set the range to the second and fourth one
Git git = new Git(db);
git.commit().setMessage("first commit").call();
RevCommit second = git.commit().setMessage("second commit")
.setCommitter(committer).call();
git.commit().setMessage("third commit").setAuthor(author).call();
RevCommit last = git.commit().setMessage("fourth commit").setAuthor(
author)
.setCommitter(committer).call();
Iterable<RevCommit> commits = git.log().addRange(second.getId(),
last.getId()).call();

// check that we have the third and fourth commit
PersonIdent defaultCommitter = new PersonIdent(db);
PersonIdent expectedAuthors[] = new PersonIdent[] { author, author };
PersonIdent expectedCommitters[] = new PersonIdent[] {
defaultCommitter, committer };
String expectedMessages[] = new String[] { "third commit",
"fourth commit" };
int l = expectedAuthors.length - 1;
for (RevCommit c : commits) {
assertEquals(expectedAuthors[l].getName(), c.getAuthorIdent()
.getName());
assertEquals(expectedCommitters[l].getName(), c.getCommitterIdent()
.getName());
assertEquals(c.getFullMessage(), expectedMessages[l]);
l--;
try (Git git = new Git(db)) {
git.commit().setMessage("first commit").call();
RevCommit second = git.commit().setMessage("second commit")
.setCommitter(committer).call();
git.commit().setMessage("third commit").setAuthor(author).call();
RevCommit last = git.commit().setMessage("fourth commit").setAuthor(
author)
.setCommitter(committer).call();
Iterable<RevCommit> commits = git.log().addRange(second.getId(),
last.getId()).call();

// check that we have the third and fourth commit
PersonIdent defaultCommitter = new PersonIdent(db);
PersonIdent expectedAuthors[] = new PersonIdent[] { author, author };
PersonIdent expectedCommitters[] = new PersonIdent[] {
defaultCommitter, committer };
String expectedMessages[] = new String[] { "third commit",
"fourth commit" };
int l = expectedAuthors.length - 1;
for (RevCommit c : commits) {
assertEquals(expectedAuthors[l].getName(), c.getAuthorIdent()
.getName());
assertEquals(expectedCommitters[l].getName(), c.getCommitterIdent()
.getName());
assertEquals(c.getFullMessage(), expectedMessages[l]);
l--;
}
assertEquals(l, -1);
} }
assertEquals(l, -1);
} }


@Test @Test
public void testCommitAmend() throws JGitInternalException, IOException, public void testCommitAmend() throws JGitInternalException, IOException,
GitAPIException { GitAPIException {
Git git = new Git(db);
git.commit().setMessage("first comit").call(); // typo
git.commit().setAmend(true).setMessage("first commit").call();

Iterable<RevCommit> commits = git.log().call();
int c = 0;
for (RevCommit commit : commits) {
assertEquals("first commit", commit.getFullMessage());
c++;
try (Git git = new Git(db)) {
git.commit().setMessage("first comit").call(); // typo
git.commit().setAmend(true).setMessage("first commit").call();

Iterable<RevCommit> commits = git.log().call();
int c = 0;
for (RevCommit commit : commits) {
assertEquals("first commit", commit.getFullMessage());
c++;
}
assertEquals(1, c);
ReflogReader reader = db.getReflogReader(Constants.HEAD);
assertTrue(reader.getLastEntry().getComment()
.startsWith("commit (amend):"));
reader = db.getReflogReader(db.getBranch());
assertTrue(reader.getLastEntry().getComment()
.startsWith("commit (amend):"));
} }
assertEquals(1, c);
ReflogReader reader = db.getReflogReader(Constants.HEAD);
assertTrue(reader.getLastEntry().getComment()
.startsWith("commit (amend):"));
reader = db.getReflogReader(db.getBranch());
assertTrue(reader.getLastEntry().getComment()
.startsWith("commit (amend):"));
} }


@Test @Test
public void testInsertChangeId() throws JGitInternalException, public void testInsertChangeId() throws JGitInternalException,
GitAPIException { GitAPIException {
Git git = new Git(db);
String messageHeader = "Some header line\n\nSome detail explanation\n";
String changeIdTemplate = "\nChange-Id: I"
+ ObjectId.zeroId().getName() + "\n";
String messageFooter = "Some foooter lines\nAnother footer line\n";
RevCommit commit = git.commit().setMessage(
messageHeader + messageFooter)
.setInsertChangeId(true).call();
// we should find a real change id (at the end of the file)
byte[] chars = commit.getFullMessage().getBytes();
int lastLineBegin = RawParseUtils.prevLF(chars, chars.length - 2);
String lastLine = RawParseUtils.decode(chars, lastLineBegin + 1,
chars.length);
assertTrue(lastLine.contains("Change-Id:"));
assertFalse(lastLine.contains(
"Change-Id: I" + ObjectId.zeroId().getName()));

commit = git.commit().setMessage(
messageHeader + changeIdTemplate + messageFooter)
.setInsertChangeId(true).call();
// we should find a real change id (in the line as dictated by the
// template)
chars = commit.getFullMessage().getBytes();
int lineStart = 0;
int lineEnd = 0;
for (int i = 0; i < 4; i++) {
lineStart = RawParseUtils.nextLF(chars, lineStart);
}
lineEnd = RawParseUtils.nextLF(chars, lineStart);

String line = RawParseUtils.decode(chars, lineStart, lineEnd);

assertTrue(line.contains("Change-Id:"));
assertFalse(line.contains(
"Change-Id: I" + ObjectId.zeroId().getName()));

commit = git.commit().setMessage(
messageHeader + changeIdTemplate + messageFooter)
.setInsertChangeId(false).call();
// we should find the untouched template
chars = commit.getFullMessage().getBytes();
lineStart = 0;
lineEnd = 0;
for (int i = 0; i < 4; i++) {
lineStart = RawParseUtils.nextLF(chars, lineStart);
try (Git git = new Git(db)) {
String messageHeader = "Some header line\n\nSome detail explanation\n";
String changeIdTemplate = "\nChange-Id: I"
+ ObjectId.zeroId().getName() + "\n";
String messageFooter = "Some foooter lines\nAnother footer line\n";
RevCommit commit = git.commit().setMessage(
messageHeader + messageFooter)
.setInsertChangeId(true).call();
// we should find a real change id (at the end of the file)
byte[] chars = commit.getFullMessage().getBytes();
int lastLineBegin = RawParseUtils.prevLF(chars, chars.length - 2);
String lastLine = RawParseUtils.decode(chars, lastLineBegin + 1,
chars.length);
assertTrue(lastLine.contains("Change-Id:"));
assertFalse(lastLine.contains(
"Change-Id: I" + ObjectId.zeroId().getName()));

commit = git.commit().setMessage(
messageHeader + changeIdTemplate + messageFooter)
.setInsertChangeId(true).call();
// we should find a real change id (in the line as dictated by the
// template)
chars = commit.getFullMessage().getBytes();
int lineStart = 0;
int lineEnd = 0;
for (int i = 0; i < 4; i++) {
lineStart = RawParseUtils.nextLF(chars, lineStart);
}
lineEnd = RawParseUtils.nextLF(chars, lineStart);

String line = RawParseUtils.decode(chars, lineStart, lineEnd);

assertTrue(line.contains("Change-Id:"));
assertFalse(line.contains(
"Change-Id: I" + ObjectId.zeroId().getName()));

commit = git.commit().setMessage(
messageHeader + changeIdTemplate + messageFooter)
.setInsertChangeId(false).call();
// we should find the untouched template
chars = commit.getFullMessage().getBytes();
lineStart = 0;
lineEnd = 0;
for (int i = 0; i < 4; i++) {
lineStart = RawParseUtils.nextLF(chars, lineStart);
}
lineEnd = RawParseUtils.nextLF(chars, lineStart);

line = RawParseUtils.decode(chars, lineStart, lineEnd);

assertTrue(commit.getFullMessage().contains(
"Change-Id: I" + ObjectId.zeroId().getName()));
} }
lineEnd = RawParseUtils.nextLF(chars, lineStart);

line = RawParseUtils.decode(chars, lineStart, lineEnd);

assertTrue(commit.getFullMessage().contains(
"Change-Id: I" + ObjectId.zeroId().getName()));
} }
} }

+ 115
- 101
org.eclipse.jgit.test/tst/org/eclipse/jgit/api/TagCommandTest.java Ver arquivo



@Test @Test
public void testTaggingOnHead() throws GitAPIException, IOException { public void testTaggingOnHead() throws GitAPIException, IOException {
Git git = new Git(db);
RevCommit commit = git.commit().setMessage("initial commit").call();
Ref tagRef = git.tag().setName("tag").call();
assertEquals(commit.getId(), db.peel(tagRef).getPeeledObjectId());
RevWalk walk = new RevWalk(db);
assertEquals("tag", walk.parseTag(tagRef.getObjectId()).getTagName());
try (Git git = new Git(db);
RevWalk walk = new RevWalk(db)) {
RevCommit commit = git.commit().setMessage("initial commit").call();
Ref tagRef = git.tag().setName("tag").call();
assertEquals(commit.getId(), db.peel(tagRef).getPeeledObjectId());
assertEquals("tag", walk.parseTag(tagRef.getObjectId()).getTagName());
}
} }


@Test @Test
public void testTagging() throws GitAPIException, JGitInternalException { public void testTagging() throws GitAPIException, JGitInternalException {
Git git = new Git(db);
git.commit().setMessage("initial commit").call();
RevCommit commit = git.commit().setMessage("second commit").call();
git.commit().setMessage("third commit").call();
Ref tagRef = git.tag().setObjectId(commit).setName("tag").call();
assertEquals(commit.getId(), db.peel(tagRef).getPeeledObjectId());
try (Git git = new Git(db)) {
git.commit().setMessage("initial commit").call();
RevCommit commit = git.commit().setMessage("second commit").call();
git.commit().setMessage("third commit").call();
Ref tagRef = git.tag().setObjectId(commit).setName("tag").call();
assertEquals(commit.getId(), db.peel(tagRef).getPeeledObjectId());
}
} }


@Test @Test
public void testUnannotatedTagging() throws GitAPIException, public void testUnannotatedTagging() throws GitAPIException,
JGitInternalException { JGitInternalException {
Git git = new Git(db);
git.commit().setMessage("initial commit").call();
RevCommit commit = git.commit().setMessage("second commit").call();
git.commit().setMessage("third commit").call();
Ref tagRef = git.tag().setObjectId(commit).setName("tag")
.setAnnotated(false).call();
assertEquals(commit.getId(), tagRef.getObjectId());
try (Git git = new Git(db)) {
git.commit().setMessage("initial commit").call();
RevCommit commit = git.commit().setMessage("second commit").call();
git.commit().setMessage("third commit").call();
Ref tagRef = git.tag().setObjectId(commit).setName("tag")
.setAnnotated(false).call();
assertEquals(commit.getId(), tagRef.getObjectId());
}
} }


@Test @Test
public void testEmptyTagName() throws GitAPIException { public void testEmptyTagName() throws GitAPIException {
Git git = new Git(db);
git.commit().setMessage("initial commit").call();
try {
// forget to tag name
git.tag().setMessage("some message").call();
fail("We should have failed without a tag name");
} catch (InvalidTagNameException e) {
// should hit here
try (Git git = new Git(db)) {
git.commit().setMessage("initial commit").call();
try {
// forget to tag name
git.tag().setMessage("some message").call();
fail("We should have failed without a tag name");
} catch (InvalidTagNameException e) {
// should hit here
}
} }
} }


@Test @Test
public void testInvalidTagName() throws GitAPIException { public void testInvalidTagName() throws GitAPIException {
Git git = new Git(db);
git.commit().setMessage("initial commit").call();
try {
git.tag().setName("bad~tag~name").setMessage("some message").call();
fail("We should have failed due to a bad tag name");
} catch (InvalidTagNameException e) {
// should hit here
try (Git git = new Git(db)) {
git.commit().setMessage("initial commit").call();
try {
git.tag().setName("bad~tag~name").setMessage("some message").call();
fail("We should have failed due to a bad tag name");
} catch (InvalidTagNameException e) {
// should hit here
}
} }
} }


@Test @Test
public void testFailureOnSignedTags() throws GitAPIException { public void testFailureOnSignedTags() throws GitAPIException {
Git git = new Git(db);
git.commit().setMessage("initial commit").call();
try {
git.tag().setSigned(true).setName("tag").call();
fail("We should have failed with an UnsupportedOperationException due to signed tag");
} catch (UnsupportedOperationException e) {
// should hit here
try (Git git = new Git(db)) {
git.commit().setMessage("initial commit").call();
try {
git.tag().setSigned(true).setName("tag").call();
fail("We should have failed with an UnsupportedOperationException due to signed tag");
} catch (UnsupportedOperationException e) {
// should hit here
}
} }
} }


@Test @Test
public void testDelete() throws Exception { public void testDelete() throws Exception {
Git git = new Git(db);
git.commit().setMessage("initial commit").call();
Ref tagRef = git.tag().setName("tag").call();
assertEquals(1, db.getTags().size());

List<String> deleted = git.tagDelete().setTags(tagRef.getName())
.call();
assertEquals(1, deleted.size());
assertEquals(tagRef.getName(), deleted.get(0));
assertEquals(0, db.getTags().size());

Ref tagRef1 = git.tag().setName("tag1").call();
Ref tagRef2 = git.tag().setName("tag2").call();
assertEquals(2, db.getTags().size());
deleted = git.tagDelete().setTags(tagRef1.getName(), tagRef2.getName())
.call();
assertEquals(2, deleted.size());
assertEquals(0, db.getTags().size());
try (Git git = new Git(db)) {
git.commit().setMessage("initial commit").call();
Ref tagRef = git.tag().setName("tag").call();
assertEquals(1, db.getTags().size());

List<String> deleted = git.tagDelete().setTags(tagRef.getName())
.call();
assertEquals(1, deleted.size());
assertEquals(tagRef.getName(), deleted.get(0));
assertEquals(0, db.getTags().size());

Ref tagRef1 = git.tag().setName("tag1").call();
Ref tagRef2 = git.tag().setName("tag2").call();
assertEquals(2, db.getTags().size());
deleted = git.tagDelete().setTags(tagRef1.getName(), tagRef2.getName())
.call();
assertEquals(2, deleted.size());
assertEquals(0, db.getTags().size());
}
} }


@Test @Test
public void testDeleteFullName() throws Exception { public void testDeleteFullName() throws Exception {
Git git = new Git(db);
git.commit().setMessage("initial commit").call();
Ref tagRef = git.tag().setName("tag").call();
assertEquals(1, db.getTags().size());

List<String> deleted = git.tagDelete()
.setTags(Repository.shortenRefName(tagRef.getName())).call();
assertEquals(1, deleted.size());
assertEquals(tagRef.getName(), deleted.get(0));
assertEquals(0, db.getTags().size());
try (Git git = new Git(db)) {
git.commit().setMessage("initial commit").call();
Ref tagRef = git.tag().setName("tag").call();
assertEquals(1, db.getTags().size());

List<String> deleted = git.tagDelete()
.setTags(Repository.shortenRefName(tagRef.getName())).call();
assertEquals(1, deleted.size());
assertEquals(tagRef.getName(), deleted.get(0));
assertEquals(0, db.getTags().size());
}
} }


@Test @Test
public void testDeleteEmptyTagNames() throws Exception { public void testDeleteEmptyTagNames() throws Exception {
Git git = new Git(db);
git.commit().setMessage("initial commit").call();
try (Git git = new Git(db)) {
git.commit().setMessage("initial commit").call();


List<String> deleted = git.tagDelete().setTags().call();
assertEquals(0, deleted.size());
List<String> deleted = git.tagDelete().setTags().call();
assertEquals(0, deleted.size());
}
} }


@Test @Test
public void testDeleteNonExisting() throws Exception { public void testDeleteNonExisting() throws Exception {
Git git = new Git(db);
git.commit().setMessage("initial commit").call();
try (Git git = new Git(db)) {
git.commit().setMessage("initial commit").call();


List<String> deleted = git.tagDelete().setTags("tag").call();
assertEquals(0, deleted.size());
List<String> deleted = git.tagDelete().setTags("tag").call();
assertEquals(0, deleted.size());
}
} }


@Test @Test
public void testDeleteBadName() throws Exception { public void testDeleteBadName() throws Exception {
Git git = new Git(db);
git.commit().setMessage("initial commit").call();
try (Git git = new Git(db)) {
git.commit().setMessage("initial commit").call();


List<String> deleted = git.tagDelete().setTags("bad~tag~name")
.call();
assertEquals(0, deleted.size());
List<String> deleted = git.tagDelete().setTags("bad~tag~name")
.call();
assertEquals(0, deleted.size());
}
} }


@Test @Test
public void testShouldNotBlowUpIfThereAreNoTagsInRepository() public void testShouldNotBlowUpIfThereAreNoTagsInRepository()
throws Exception { throws Exception {
Git git = new Git(db);
git.add().addFilepattern("*").call();
git.commit().setMessage("initial commit").call();
List<Ref> list = git.tagList().call();
assertEquals(0, list.size());
try (Git git = new Git(db)) {
git.add().addFilepattern("*").call();
git.commit().setMessage("initial commit").call();
List<Ref> list = git.tagList().call();
assertEquals(0, list.size());
}
} }


@Test @Test
public void testShouldNotBlowUpIfThereAreNoCommitsInRepository() public void testShouldNotBlowUpIfThereAreNoCommitsInRepository()
throws Exception { throws Exception {
Git git = new Git(db);
List<Ref> list = git.tagList().call();
assertEquals(0, list.size());
try (Git git = new Git(db)) {
List<Ref> list = git.tagList().call();
assertEquals(0, list.size());
}
} }


@Test @Test
public void testListAllTagsInRepositoryInOrder() throws Exception { public void testListAllTagsInRepositoryInOrder() throws Exception {
Git git = new Git(db);
git.add().addFilepattern("*").call();
git.commit().setMessage("initial commit").call();
try (Git git = new Git(db)) {
git.add().addFilepattern("*").call();
git.commit().setMessage("initial commit").call();


git.tag().setName("v3").call();
git.tag().setName("v2").call();
git.tag().setName("v10").call();
git.tag().setName("v3").call();
git.tag().setName("v2").call();
git.tag().setName("v10").call();


List<Ref> list = git.tagList().call();
List<Ref> list = git.tagList().call();


assertEquals(3, list.size());
assertEquals("refs/tags/v10", list.get(0).getName());
assertEquals("refs/tags/v2", list.get(1).getName());
assertEquals("refs/tags/v3", list.get(2).getName());
assertEquals(3, list.size());
assertEquals("refs/tags/v10", list.get(0).getName());
assertEquals("refs/tags/v2", list.get(1).getName());
assertEquals("refs/tags/v3", list.get(2).getName());
}
} }


} }

+ 82
- 78
org.eclipse.jgit.test/tst/org/eclipse/jgit/diff/DiffFormatterTest.java Ver arquivo

File folder = new File(db.getDirectory().getParent(), "folder"); File folder = new File(db.getDirectory().getParent(), "folder");
FileUtils.mkdir(folder); FileUtils.mkdir(folder);
write(new File(folder, "folder.txt"), "folder"); write(new File(folder, "folder.txt"), "folder");
Git git = new Git(db);
git.add().addFilepattern(".").call();
git.commit().setMessage("Initial commit").call();
write(new File(folder, "folder.txt"), "folder change");

ByteArrayOutputStream os = new ByteArrayOutputStream();
DiffFormatter dfmt = new DiffFormatter(new SafeBufferedOutputStream(os));
dfmt.setRepository(db);
dfmt.setPathFilter(PathFilter.create("folder"));
DirCacheIterator oldTree = new DirCacheIterator(db.readDirCache());
FileTreeIterator newTree = new FileTreeIterator(db);
dfmt.format(oldTree, newTree);
dfmt.flush();

String actual = os.toString("UTF-8");
String expected =
"diff --git a/folder/folder.txt b/folder/folder.txt\n"
+ "index 0119635..95c4c65 100644\n"
+ "--- a/folder/folder.txt\n" + "+++ b/folder/folder.txt\n"
+ "@@ -1 +1 @@\n" + "-folder\n"
+ "\\ No newline at end of file\n" + "+folder change\n"
+ "\\ No newline at end of file\n";

assertEquals(expected, actual);
try (Git git = new Git(db);
ByteArrayOutputStream os = new ByteArrayOutputStream();
DiffFormatter dfmt = new DiffFormatter(new SafeBufferedOutputStream(os))) {
git.add().addFilepattern(".").call();
git.commit().setMessage("Initial commit").call();
write(new File(folder, "folder.txt"), "folder change");
dfmt.setRepository(db);
dfmt.setPathFilter(PathFilter.create("folder"));
DirCacheIterator oldTree = new DirCacheIterator(db.readDirCache());
FileTreeIterator newTree = new FileTreeIterator(db);

dfmt.format(oldTree, newTree);
dfmt.flush();

String actual = os.toString("UTF-8");
String expected =
"diff --git a/folder/folder.txt b/folder/folder.txt\n"
+ "index 0119635..95c4c65 100644\n"
+ "--- a/folder/folder.txt\n" + "+++ b/folder/folder.txt\n"
+ "@@ -1 +1 @@\n" + "-folder\n"
+ "\\ No newline at end of file\n" + "+folder change\n"
+ "\\ No newline at end of file\n";

assertEquals(expected, actual);
}
} }


@Test @Test
File folder = new File(db.getDirectory().getParent(), "folder"); File folder = new File(db.getDirectory().getParent(), "folder");
FileUtils.mkdir(folder); FileUtils.mkdir(folder);
write(new File(folder, "folder.txt"), "folder"); write(new File(folder, "folder.txt"), "folder");
Git git = new Git(db);
git.add().addFilepattern(".").call();
RevCommit commit = git.commit().setMessage("Initial commit").call();
write(new File(folder, "folder.txt"), "folder change");

ByteArrayOutputStream os = new ByteArrayOutputStream();
DiffFormatter dfmt = new DiffFormatter(new SafeBufferedOutputStream(os));
dfmt.setRepository(db);
dfmt.setPathFilter(PathFilter.create("folder"));
dfmt.format(null, commit.getTree().getId());
dfmt.flush();

String actual = os.toString("UTF-8");
String expected = "diff --git a/folder/folder.txt b/folder/folder.txt\n"
+ "new file mode 100644\n"
+ "index 0000000..0119635\n"
+ "--- /dev/null\n"
+ "+++ b/folder/folder.txt\n"
+ "@@ -0,0 +1 @@\n"
+ "+folder\n"
+ "\\ No newline at end of file\n";

assertEquals(expected, actual);
try (Git git = new Git(db);
ByteArrayOutputStream os = new ByteArrayOutputStream();
DiffFormatter dfmt = new DiffFormatter(new SafeBufferedOutputStream(os))) {
git.add().addFilepattern(".").call();
RevCommit commit = git.commit().setMessage("Initial commit").call();
write(new File(folder, "folder.txt"), "folder change");

dfmt.setRepository(db);
dfmt.setPathFilter(PathFilter.create("folder"));
dfmt.format(null, commit.getTree().getId());
dfmt.flush();

String actual = os.toString("UTF-8");
String expected = "diff --git a/folder/folder.txt b/folder/folder.txt\n"
+ "new file mode 100644\n"
+ "index 0000000..0119635\n"
+ "--- /dev/null\n"
+ "+++ b/folder/folder.txt\n"
+ "@@ -0,0 +1 @@\n"
+ "+folder\n"
+ "\\ No newline at end of file\n";

assertEquals(expected, actual);
}
} }


@Test @Test
File folder = new File(db.getDirectory().getParent(), "folder"); File folder = new File(db.getDirectory().getParent(), "folder");
FileUtils.mkdir(folder); FileUtils.mkdir(folder);
write(new File(folder, "folder.txt"), "folder"); write(new File(folder, "folder.txt"), "folder");
Git git = new Git(db);
git.add().addFilepattern(".").call();
RevCommit commit = git.commit().setMessage("Initial commit").call();
write(new File(folder, "folder.txt"), "folder change");

ByteArrayOutputStream os = new ByteArrayOutputStream();
DiffFormatter dfmt = new DiffFormatter(new SafeBufferedOutputStream(os));
dfmt.setRepository(db);
dfmt.setPathFilter(PathFilter.create("folder"));
dfmt.format(commit.getTree().getId(), null);
dfmt.flush();

String actual = os.toString("UTF-8");
String expected = "diff --git a/folder/folder.txt b/folder/folder.txt\n"
+ "deleted file mode 100644\n"
+ "index 0119635..0000000\n"
+ "--- a/folder/folder.txt\n"
+ "+++ /dev/null\n"
+ "@@ -1 +0,0 @@\n"
+ "-folder\n"
+ "\\ No newline at end of file\n";

assertEquals(expected, actual);
try (Git git = new Git(db);
ByteArrayOutputStream os = new ByteArrayOutputStream();
DiffFormatter dfmt = new DiffFormatter(new SafeBufferedOutputStream(os));) {
git.add().addFilepattern(".").call();
RevCommit commit = git.commit().setMessage("Initial commit").call();
write(new File(folder, "folder.txt"), "folder change");

dfmt.setRepository(db);
dfmt.setPathFilter(PathFilter.create("folder"));
dfmt.format(commit.getTree().getId(), null);
dfmt.flush();

String actual = os.toString("UTF-8");
String expected = "diff --git a/folder/folder.txt b/folder/folder.txt\n"
+ "deleted file mode 100644\n"
+ "index 0119635..0000000\n"
+ "--- a/folder/folder.txt\n"
+ "+++ /dev/null\n"
+ "@@ -1 +0,0 @@\n"
+ "-folder\n"
+ "\\ No newline at end of file\n";

assertEquals(expected, actual);
}
} }


@Test @Test
public void testDiffNullToNull() throws Exception { public void testDiffNullToNull() throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
DiffFormatter dfmt = new DiffFormatter(new SafeBufferedOutputStream(os));
dfmt.setRepository(db);
dfmt.format((AnyObjectId) null, null);
dfmt.flush();
try (ByteArrayOutputStream os = new ByteArrayOutputStream();
DiffFormatter dfmt = new DiffFormatter(new SafeBufferedOutputStream(os))) {
dfmt.setRepository(db);
dfmt.format((AnyObjectId) null, null);
dfmt.flush();


String actual = os.toString("UTF-8");
String expected = "";
String actual = os.toString("UTF-8");
String expected = "";


assertEquals(expected, actual);
assertEquals(expected, actual);
}
} }


private static String makeDiffHeader(String pathA, String pathB, private static String makeDiffHeader(String pathA, String pathB,

+ 20
- 18
org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/BundleWriterTest.java Ver arquivo

assertNull(newRepo.resolve("refs/heads/a")); assertNull(newRepo.resolve("refs/heads/a"));


// Next an incremental bundle // Next an incremental bundle
bundle = makeBundle("refs/heads/cc", db.resolve("c").name(),
new RevWalk(db).parseCommit(db.resolve("a").toObjectId()));
fetchResult = fetchFromBundle(newRepo, bundle);
advertisedRef = fetchResult.getAdvertisedRef("refs/heads/cc");
assertEquals(db.resolve("c").name(), advertisedRef.getObjectId().name());
assertEquals(db.resolve("c").name(), newRepo.resolve("refs/heads/cc")
.name());
assertNull(newRepo.resolve("refs/heads/c"));
assertNull(newRepo.resolve("refs/heads/a")); // still unknown

try {
// Check that we actually needed the first bundle
Repository newRepo2 = createBareRepository();
fetchResult = fetchFromBundle(newRepo2, bundle);
fail("We should not be able to fetch from bundle with prerequisites that are not fulfilled");
} catch (MissingBundlePrerequisiteException e) {
assertTrue(e.getMessage()
.indexOf(db.resolve("refs/heads/a").name()) >= 0);
try (RevWalk rw = new RevWalk(db)) {
bundle = makeBundle("refs/heads/cc", db.resolve("c").name(),
rw.parseCommit(db.resolve("a").toObjectId()));
fetchResult = fetchFromBundle(newRepo, bundle);
advertisedRef = fetchResult.getAdvertisedRef("refs/heads/cc");
assertEquals(db.resolve("c").name(), advertisedRef.getObjectId().name());
assertEquals(db.resolve("c").name(), newRepo.resolve("refs/heads/cc")
.name());
assertNull(newRepo.resolve("refs/heads/c"));
assertNull(newRepo.resolve("refs/heads/a")); // still unknown

try {
// Check that we actually needed the first bundle
Repository newRepo2 = createBareRepository();
fetchResult = fetchFromBundle(newRepo2, bundle);
fail("We should not be able to fetch from bundle with prerequisites that are not fulfilled");
} catch (MissingBundlePrerequisiteException e) {
assertTrue(e.getMessage()
.indexOf(db.resolve("refs/heads/a").name()) >= 0);
}
} }
} }



+ 16
- 11
org.eclipse.jgit.test/tst/org/eclipse/jgit/transport/SideBandOutputStreamTest.java Ver arquivo

assertEquals(1, flushCnt[0]); assertEquals(1, flushCnt[0]);
} }


@SuppressWarnings("unused")
private void createSideBandOutputStream(int chan, int sz, OutputStream os)
throws Exception {
try (SideBandOutputStream s = new SideBandOutputStream(chan, sz, os)) {
// Unused
}
}

@Test @Test
public void testConstructor_RejectsBadChannel() {
public void testConstructor_RejectsBadChannel() throws Exception {
try { try {
new SideBandOutputStream(-1, MAX_BUF, rawOut);
createSideBandOutputStream(-1, MAX_BUF, rawOut);
fail("Accepted -1 channel number"); fail("Accepted -1 channel number");
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("channel -1 must be in range [1, 255]", e.getMessage()); assertEquals("channel -1 must be in range [1, 255]", e.getMessage());
} }


try { try {
new SideBandOutputStream(0, MAX_BUF, rawOut);
createSideBandOutputStream(0, MAX_BUF, rawOut);
fail("Accepted 0 channel number"); fail("Accepted 0 channel number");
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("channel 0 must be in range [1, 255]", e.getMessage()); assertEquals("channel 0 must be in range [1, 255]", e.getMessage());
} }


try { try {
new SideBandOutputStream(256, MAX_BUF, rawOut);
createSideBandOutputStream(256, MAX_BUF, rawOut);
fail("Accepted 256 channel number"); fail("Accepted 256 channel number");
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("channel 256 must be in range [1, 255]", e assertEquals("channel 256 must be in range [1, 255]", e
} }
} }


@SuppressWarnings("unused")
@Test @Test
public void testConstructor_RejectsBadBufferSize() {
public void testConstructor_RejectsBadBufferSize() throws Exception {
try { try {
new SideBandOutputStream(CH_DATA, -1, rawOut);
createSideBandOutputStream(CH_DATA, -1, rawOut);
fail("Accepted -1 for buffer size"); fail("Accepted -1 for buffer size");
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("packet size -1 must be >= 5", e.getMessage()); assertEquals("packet size -1 must be >= 5", e.getMessage());
} }


try { try {
new SideBandOutputStream(CH_DATA, 0, rawOut);
createSideBandOutputStream(CH_DATA, 0, rawOut);
fail("Accepted 0 for buffer size"); fail("Accepted 0 for buffer size");
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("packet size 0 must be >= 5", e.getMessage()); assertEquals("packet size 0 must be >= 5", e.getMessage());
} }


try { try {
new SideBandOutputStream(CH_DATA, 1, rawOut);
createSideBandOutputStream(CH_DATA, 1, rawOut);
fail("Accepted 1 for buffer size"); fail("Accepted 1 for buffer size");
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals("packet size 1 must be >= 5", e.getMessage()); assertEquals("packet size 1 must be >= 5", e.getMessage());
} }


try { try {
new SideBandOutputStream(CH_DATA, Integer.MAX_VALUE, rawOut);
createSideBandOutputStream(CH_DATA, Integer.MAX_VALUE, rawOut);
fail("Accepted " + Integer.MAX_VALUE + " for buffer size"); fail("Accepted " + Integer.MAX_VALUE + " for buffer size");
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
assertEquals(MessageFormat.format( assertEquals(MessageFormat.format(

+ 38
- 32
org.eclipse.jgit.test/tst/org/eclipse/jgit/treewalk/FileTreeIteratorJava7Test.java Ver arquivo

}); });
assertTrue(dce.commit()); assertTrue(dce.commit());
} }
new Git(db).commit().setMessage("Adding link").call();
new Git(db).reset().setMode(ResetType.HARD).call();
DirCacheIterator dci = new DirCacheIterator(db.readDirCache());
FileTreeIterator fti = new FileTreeIterator(db);
try (Git git = new Git(db)) {
git.commit().setMessage("Adding link").call();
git.reset().setMode(ResetType.HARD).call();
DirCacheIterator dci = new DirCacheIterator(db.readDirCache());
FileTreeIterator fti = new FileTreeIterator(db);


// self-check
assertEquals("link", fti.getEntryPathString());
assertEquals("link", dci.getEntryPathString());
// self-check
assertEquals("link", fti.getEntryPathString());
assertEquals("link", dci.getEntryPathString());


// test
assertFalse(fti.isModified(dci.getDirCacheEntry(), true,
db.newObjectReader()));
// test
assertFalse(fti.isModified(dci.getDirCacheEntry(), true,
db.newObjectReader()));
}
} }


/** /**
}); });
assertTrue(dce.commit()); assertTrue(dce.commit());
} }
new Git(db).commit().setMessage("Adding link").call();
new Git(db).reset().setMode(ResetType.HARD).call();
DirCacheIterator dci = new DirCacheIterator(db.readDirCache());
FileTreeIterator fti = new FileTreeIterator(db);
try (Git git = new Git(db)) {
git.commit().setMessage("Adding link").call();
git.reset().setMode(ResetType.HARD).call();
DirCacheIterator dci = new DirCacheIterator(db.readDirCache());
FileTreeIterator fti = new FileTreeIterator(db);


// self-check
assertEquals("link", fti.getEntryPathString());
assertEquals("link", dci.getEntryPathString());
// self-check
assertEquals("link", fti.getEntryPathString());
assertEquals("link", dci.getEntryPathString());


// test
assertFalse(fti.isModified(dci.getDirCacheEntry(), true,
db.newObjectReader()));
// test
assertFalse(fti.isModified(dci.getDirCacheEntry(), true,
db.newObjectReader()));
}
} }


/** /**
}); });
assertTrue(dce.commit()); assertTrue(dce.commit());
} }
new Git(db).commit().setMessage("Adding link").call();
new Git(db).reset().setMode(ResetType.HARD).call();
try (Git git = new Git(db)) {
git.commit().setMessage("Adding link").call();
git.reset().setMode(ResetType.HARD).call();


FileUtils.delete(new File(trash, "link"), FileUtils.NONE);
FS.DETECTED.createSymLink(new File(trash, "link"), "newtarget");
DirCacheIterator dci = new DirCacheIterator(db.readDirCache());
FileTreeIterator fti = new FileTreeIterator(db);
FileUtils.delete(new File(trash, "link"), FileUtils.NONE);
FS.DETECTED.createSymLink(new File(trash, "link"), "newtarget");
DirCacheIterator dci = new DirCacheIterator(db.readDirCache());
FileTreeIterator fti = new FileTreeIterator(db);


// self-check
assertEquals("link", fti.getEntryPathString());
assertEquals("link", dci.getEntryPathString());
// self-check
assertEquals("link", fti.getEntryPathString());
assertEquals("link", dci.getEntryPathString());


// test
assertTrue(fti.isModified(dci.getDirCacheEntry(), true,
db.newObjectReader()));
// test
assertTrue(fti.isModified(dci.getDirCacheEntry(), true,
db.newObjectReader()));
}
} }
} }

Carregando…
Cancelar
Salvar