Skip to content

Instantly share code, notes, and snippets.

@rherrmann
Created September 23, 2017 02:55
Show Gist options
  • Save rherrmann/0c682ea327862cb6847704acf90b1d5d to your computer and use it in GitHub Desktop.
Save rherrmann/0c682ea327862cb6847704acf90b1d5d to your computer and use it in GitHub Desktop.
Learning test to read the contents of a file at a specific revision with JGit , emulates git show <branch>:<file>
package com.codeaffine.jgit.example;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class ObjectLoaderLearningTest {
@Rule
public final TemporaryFolder tempFolder = new TemporaryFolder();
private Git git;
private Repository repository;
@Before
public void setUp() throws GitAPIException {
git = Git.init().setDirectory( tempFolder.getRoot() ).call();
repository = git.getRepository();
}
@After
public void tearDown() {
repository.close();
}
@Test
public void testShow() throws Exception {
String helloWorld = "Hello World!";
writeFile( "readme", helloWorld );
commitAll( "Add readme file" );
ObjectId masterTreeId = git.getRepository().resolve( "refs/heads/master^{tree}" );
TreeWalk treeWalk = TreeWalk.forPath( git.getRepository(), "readme", masterTreeId );
ObjectId blobId = treeWalk.getObjectId( 0 );
ObjectLoader objectLoader = loadObject( blobId );
byte[] bytes = objectLoader.getBytes();
treeWalk.close();
assertEquals( helloWorld, new String( bytes, UTF_8 ) );
}
private void commitAll( String message ) throws Exception {
git.add().addFilepattern( "." ).call();
git.commit().setMessage( message ).call();
}
private ObjectLoader loadObject( ObjectId objectId ) throws IOException {
ObjectReader objectReader = repository.newObjectReader();
ObjectLoader result = objectReader.open( objectId );
objectReader.close();
return result;
}
private void writeFile( String name, String content ) throws IOException {
File file = new File( git.getRepository().getWorkTree(), name );
try( FileOutputStream outputStream = new FileOutputStream( file ) ) {
outputStream.write( content.getBytes( UTF_8 ) );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment