在做一個項目中需要用到遠程倉庫,本來想使用svn的,但是svn的java api網上的資料很少,而且與git相比,svn顯得笨重且不方便,因此放棄了svn轉而使用git。java git api - jgit的資料還是比較多的,而且git的操作比svn更容易理解,所以毅然決然的在git的道路上越走越遠。
如果你想在一個 Java 程序中使用 Git ,有一個功能齊全的 Git 庫,那就是 JGit 。 JGit 是一個用 Java 寫成的功能相對健全的 Git 的實現,它在 Java 社區中被廣泛使用。 JGit 項目由 Eclipse 維護,它的主頁在 http://www.eclipse.org/jgit 。
非常好的例子:https://github.com/centic9/jgit-cookbook
下面是我實現的代碼,分別包含了如下的功能:
1、在本地文件夾建立起與遠程倉庫的連接
2、根據主干master新建分支並同步到遠程
3、提交commit文件到遠程
4、從遠程拉去代碼到本地文件夾
public class GitUtilClass { public static String localRepoPath = "D:/repo"; public static String localRepoGitConfig = "D:/repo/.git"; public static String remoteRepoURI = "git@gitlab.com:wilson/test.git"; public static String localCodeDir = "D:/platplat"; /** * 新建一個分支並同步到遠程倉庫 * @param branchName * @throws IOException * @throws GitAPIException */ public static String newBranch(String branchName){ String newBranchIndex = "refs/heads/"+branchName; String gitPathURI = ""; Git git; try { //檢查新建的分支是否已經存在,如果存在則將已存在的分支強制刪除並新建一個分支 List<Ref> refs = git.branchList().call(); for (Ref ref : refs) { if (ref.getName().equals(newBranchIndex)) { System.out.println("Removing branch before"); git.branchDelete().setBranchNames(branchName).setForce(true) .call(); break; } } //新建分支 Ref ref = git.branchCreate().setName(branchName).call(); //推送到遠程 git.push().add(ref).call(); gitPathURI = remoteRepoURI + " " + "feature/" + branchName; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (GitAPIException e) { // TODO Auto-generated catch block e.printStackTrace(); } return gitPathURI; } public static void commitFiles() throws IOException, GitAPIException{ String filePath = ""; Git git = Git.open( new File(localRepoGitConfig) ); //創建用戶文件的過程 File myfile = new File(filePath); myfile.createNewFile(); git.add().addFilepattern("pets").call(); //提交 git.commit().setMessage("Added pets").call(); //推送到遠程 git.push().call(); } public static boolean pullBranchToLocal(String cloneURL){ boolean resultFlag = false; String[] splitURL = cloneURL.split(" "); String branchName = splitURL[1]; String fileDir = localCodeDir+"/"+branchName; //檢查目標文件夾是否存在 File file = new File(fileDir); if(file.exists()){ deleteFolder(file); } Git git; try { git = Git.open( new File(localRepoGitConfig) ); git.cloneRepository().setURI(cloneURL).setDirectory(file).call(); resultFlag = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (GitAPIException e) { // TODO Auto-generated catch block e.printStackTrace(); } return resultFlag; } public static void deleteFolder(File file){ if(file.isFile() || file.list().length==0){ file.delete(); }else{ File[] files = file.listFiles(); for(int i=0;i<files.length;i++){ deleteFolder(files[i]); files[i].delete(); } } } public static void setupRepo() throws GitAPIException{ //建立與遠程倉庫的聯系,僅需要執行一次 Git git = Git.cloneRepository().setURI(remoteRepoURI).setDirectory(new File(localRepoPath)).call(); } }