git4j is an attempt to learn how git works by implementing some parts of it.
Here we create an initial tree at root leve; with a file named pippo with the content "Hello World!\n\n"
private GitTreeEntry createInitialTree() {
List<GitTreeEntry> objects = new ArrayList<>();
objects.add(createFileEntry("pippo", "Hello World!\n\n"));
return new GitTreeEntry(objects);
}
@Test
public void testTreeWith1Item() {
assertThat(g.binaryToHex(g.getTreeSha(createInitialTree())))
.isEqualTo("132bfb311556de7c60c34ef3d450c9e8bcc6310b");
}
Here we create a commit with a reference to the tree created in the previous example.
/**
* tree 132bfb311556de7c60c34ef3d450c9e8bcc6310b
* author Montoya Edu <montoya.edu@gmail.com> 1496830486 +0200
* committer Montoya Edu <montoya.edu@gmail.com> 1496830486 +0200
*
* Add file.
*
*/
Git git = new Git();
GitCommit c = new GitCommit();
c.setMessage("Add file.");
c.setCommitter("Montoya Edu <montoya.edu@gmail.com>");
c.setAuthor("Montoya Edu <montoya.edu@gmail.com>");
Calendar calendar = g.getCalendar("Europe/Rome");
calendar.setTimeInMillis(1496830486);
c.setAuthoringDate(calendar.getTime());
c.setCommitDate(calendar.getTime());
c.setAuthoringTimezone("Europe/Rome");
c.setCommitTimezone("Europe/Rome");
c.setTree("132bfb311556de7c60c34ef3d450c9e8bcc6310b");
byte[] bytes = g.serialize(c);
byte[] compressed = g.compress(bytes);
String sha = g.binaryToHex(g.getSha(c));
// now that we have the SHA1 string, and the compressed bytes, we can store it:
// on the filesystem, as git normally does, or
// you can choose the kind persistence layer you want to use for your needs.
Look for file GitTest.java