Java JGitを使用してGitコードを取得
7183 ワード
package com.sf.sgs.smp.manager.test;
import org.eclipse.jgit.api.*;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.JGitInternalException;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
/**
* JGit API
*/
public class gitTest {
public String remotePath = "http://[email protected]:8080/project.git";//
public String localPath = "D:\\project\\";//
public String initPath = "D:\\test\\";//
/**
*
* @throws IOException
* @throws GitAPIException
*/
@Test
public void testClone() throws IOException, GitAPIException {
//
UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider =new
UsernamePasswordCredentialsProvider("username","password");
//
CloneCommand cloneCommand = Git.cloneRepository();
Git git= cloneCommand.setURI(remotePath) // URI
.setBranch("master") // clone
.setDirectory(new File(localPath)) //
.setCredentialsProvider(usernamePasswordCredentialsProvider) //
.call();
System.out.print(git.tag());
}
/**
*
*/
@Test
public void testCreate() throws IOException {
//
Repository newRepo = FileRepositoryBuilder.create(new File(initPath + "/.git"));
newRepo.create();
}
/**
*
*/
@Test
public void testAdd() throws IOException, GitAPIException {
File myfile = new File(localPath + "/myfile.txt");
myfile.createNewFile();
//git
Git git = new Git(new FileRepository(localPath+"/.git"));
//
git.add().addFilepattern("myfile").call();
}
/**
*
*/
@Test
public void testCommit() throws IOException, GitAPIException,
JGitInternalException {
//git
Git git = new Git(new FileRepository(localPath+"/.git"));
//
git.commit().setMessage("test jGit").call();
}
/**
*
*/
@Test
public void testPull() throws IOException, GitAPIException {
UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider =new
UsernamePasswordCredentialsProvider("username","password");
//git
Git git = new Git(new FileRepository(localPath+"/.git"));
git.pull().setRemoteBranchName("master").
setCredentialsProvider(usernamePasswordCredentialsProvider).call();
}
/**
* push
*/
@Test
public void testPush() throws IOException, JGitInternalException,
GitAPIException {
UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider =new
UsernamePasswordCredentialsProvider("username","password");
//git
Git git = new Git(new FileRepository(localPath+"/.git"));
git.push().setRemote("origin"). setCredentialsProvider(usernamePasswordCredentialsProvider).call();
}
}