git筆記——jgit使用

有時需要通過Java代碼連接Git庫,開源的JGit是不錯選擇。JGit連接代碼倉庫通常需要鑑權,這裏介紹一種使用私有Token進行鑑權連接的方法。

首先在Git庫上生成私有Token,Github中生成路徑爲:Settings -> Developer settings -> Personal access tokens -> Generate new token,最終生成Token字符串,需要牢記,後面使用。

JGit連接Git倉庫時,使用CredentialsProvider進行鑑權,私有Token使用UsernamePasswordCredentialsProvider對象進行設置,進行數據庫連接即可,代碼如下:

package com.king.jgit.service;

import java.io.File;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

public class JGitService {

	public Git getGit(String repositoryUrl, String privateToken, String repositoryDir)
			throws InvalidRemoteException, TransportException, GitAPIException {
		CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider("PRIVATE-TOKEN",
				privateToken);
		Git git = Git.cloneRepository().setCredentialsProvider(credentialsProvider).setURI(repositoryUrl)
				.setDirectory(new File(repositoryDir)).call();
		return git;
	}

}

其中需要注意的是,UsernamePasswordCredentialsProvider構建方法,第一個參數爲用戶名,這個用戶名在使用私有Token 的時候,必須固定的設置爲“PRIVATE-TOKEN”,第二個參數即爲上面生成的Git庫私有Token。如果你用的是gitlab,那麼第一個參數仍然使用的是用戶名。

/**
 * JGit
 */
public class GitUtils {
    //遠程庫路徑
    public String remotePath = "git repo address";
    //下載已有倉庫到本地路徑
    public String localPath = "";
    //本地路徑新建
    public String initPath = localPath;
    public String gitlabUserName = "";
    public String gitlabPrivateToken = "";


    /**
     * 克隆遠程庫
     * @throws IOException
     * @throws GitAPIException
     */
    public void cloneFromRemote(String path) throws IOException, GitAPIException {
        //設置遠程服務器上的用戶名和密碼
        UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider =new
                UsernamePasswordCredentialsProvider(gitlabUserName,gitlabPrivateToken);

        //克隆代碼庫命令
        CloneCommand cloneCommand = Git.cloneRepository();

        Git git= cloneCommand.setURI(remotePath)
                .setBranch("master")
                .setDirectory(new File(path))
                .setCredentialsProvider(usernamePasswordCredentialsProvider)
                .call();

    }

    /**
     * 本地新建倉庫
     */
    public void createRepo(String path) throws IOException {
        //本地新建倉庫地址
        Repository newRepo = FileRepositoryBuilder.create(new File(path + "/.git"));
        newRepo.create();
    }

    /**
     * 本地倉庫新增文件
     */
    public void add(File file) throws IOException, GitAPIException {
        //git倉庫地址
        Git git = new Git(new FileRepository(localPath+"/.git"));

        //添加文件
        git.add().addFilepattern(file.getName()).call();
    }

    /**
     * 本地提交代碼
     */
    public void commit() throws IOException, GitAPIException,
            JGitInternalException {
        //git倉庫地址
        Git git = new Git(new FileRepository(localPath+"/.git"));
        //提交代碼
        git.commit().setMessage("test jGit").call();
    }


    /**
     * 拉取遠程倉庫內容到本地
     */
    public void pullFromRemoteMaster(String path) throws IOException, GitAPIException {

        UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider =new
                UsernamePasswordCredentialsProvider(gitlabUserName,gitlabPrivateToken);
        //git倉庫地址
        Git git = new Git(new FileRepository(path+"/.git"));
        git.pull().setRemoteBranchName("master").
                setCredentialsProvider(usernamePasswordCredentialsProvider).call();
    }

    /**
     * push本地代碼到遠程倉庫地址
     */
    public void push() throws IOException, JGitInternalException,
            GitAPIException {

        UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider =new
                UsernamePasswordCredentialsProvider(gitlabUserName,gitlabPrivateToken);
        //git倉庫地址
        Git git = new Git(new FileRepository(localPath+"/.git"));
        git.push().setRemote("origin").     setCredentialsProvider(usernamePasswordCredentialsProvider).call();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章