https://www.freesion.com/article/50181381474/
JGIT获取远程仓库、本地仓库提交版本号
- 一、环境搭建
- 二、项目结构
- 二、代码部分
-  
  - GitUtils.java
- GitInfoAtom.java
 
- 三、运行结果:
- 总结
一、环境搭建
Maven依赖导入
<dependency>
            <groupId>org.eclipse.jgit</groupId>
            <artifactId>org.eclipse.jgit</artifactId>
            <version>5.9.0.202009080501-r</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jgit</groupId>
            <artifactId>org.eclipse.jgit.archive</artifactId>
            <version>5.9.0.202009080501-r</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jgit</groupId>
            <artifactId>org.eclipse.jgit.ssh.jsch</artifactId>
            <version>5.9.0.202009080501-r</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.30</version>
        </dependency>
        <!-- optional dependency of commons-compress which is needed by JGit -->
        <dependency>
            <groupId>org.tukaani</groupId>
            <artifactId>xz</artifactId>
            <version>1.8</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
 
二、项目结构

二、代码部分
GITUTILS.JAVA
package Utils;
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.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GitUtils {
    /**
     * getMatcher 正则表达式方法
     * @param regex
     * @param source
     * @return
     */
    public static String getMatcher(String regex, String source) {
        String str = "";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(source);
        while (matcher.find()) {
            str = matcher.group(1); // 只取第一组
        }
        return str;
    }
    /**
     * TokenClone 通过**连接克隆
     * @param repositoryUrl
     * @param privateToken
     * @param repositoryDir
     * @return
     * @throws InvalidRemoteException
     * @throws TransportException
     * @throws GitAPIException
     */
    public static Git TokenClone(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;
    }
    /**
     * CredentialsProvider **认证
     * @param privateToken
     * @return
     * @throws InvalidRemoteException
     * @throws TransportException
     * @throws GitAPIException
     */
    public static CredentialsProvider Credentials(String privateToken)
            throws InvalidRemoteException, TransportException, GitAPIException {
        CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider("PRIVATE-TOKEN",
                privateToken);
        return credentialsProvider;
    }
    /**
     * LogRemote 获取Git远程仓库版本号
     * @param repositoryUrl
     * @param privateToken
     * @return
     * @throws IOException
     * @throws GitAPIException
     */
    public static String LogRemote(String repositoryUrl, String privateToken) throws IOException, GitAPIException {
        String temDir = "D:\\Test"; //临时文件夹
        if (new File(temDir).exists()) {
            temDir += "one";
        }
        Git git;
        String versionID = "";
        git = TokenClone(repositoryUrl, privateToken, temDir);
        Iterable<RevCommit> iterable = git.log().call();
        for (RevCommit u : iterable) {
            String ID = String.valueOf(u.getId());
            //正则表达式 截取需要的部分
            versionID = getMatcher("commit\\s(\\w+)\\s?", ID);
            break;
        }
        git.close();
        deleteFile(new File(temDir));
        return versionID;
    }
    /**
     * 获取Git本地仓库版本号
     *
     * @return versionID 版本号
     * @throws IOException
     * @throws GitAPIException
     */
    public static String Log(String repositoryDir) throws IOException, GitAPIException {
        String versionID = "";
        Repository localRepo;
        localRepo = new FileRepository(repositoryDir + "/.git");
        Git git = new Git(localRepo);
        System.out.println("获取本地");
        Iterable<RevCommit> iterable = git.log().all().call();
        for (RevCommit u : iterable) {
            //版本id
            String ID = String.valueOf(u.getId());
            versionID = getMatcher("commit\\s(\\w+)\\s?", ID);
            break;
        }
        git.close();
        return versionID;
    }
    /**
     * 删除目录以文件
     *
     * @param dirFile
     * @return
     */
    public static boolean deleteFile(File dirFile) {
        // 如果dir对应的文件不存在,则退出
        if (!dirFile.exists()) {
            return false;
        }
        if (dirFile.isFile()) {
            return dirFile.delete();
        } else {
            for (File file : dirFile.listFiles()) {
                deleteFile(file);
            }
        }
        return dirFile.delete();
    }
}
该类为工具类
GITINFOATOM.JAVA
import Utils.GitUtils;
import org.eclipse.jgit.api.errors.GitAPIException;
public class GitInfoAtom {
    public static void main(String[] args) throws IOException, GitAPIException, Exception {
        // 远程仓库地址
        String repositoryUrl = "http://gitlab.testplus.cn/weipei/GitTest.git";
        // **
        String privateToken = "rAtfgm7U4-WTYX61QLn9111";
        // 本地仓库地址
        String repositoryDir = "C:\\Test";
        // 输出远程仓库的最新版本号
        System.out.println(GitUtils.LogRemote(repositoryUrl, privateToken));
        // 输出本地仓库版本号
        //System.out.println(GitUtils.Log(repositoryDir));
    }
}
三、运行结果:




















