java操作Git工具-----Jgit使用

Jgit

官网地址

http://www.eclipse.org/jgit/

仓库地址

https://gitee.com/mirrors/jgit

用途

可以通过代码调用git对象对不同git Repository,所以可以通过它去实现一些多项目代码管理小工具,比如某个项目中的固定流程或者不同项目之间的交互,通过代码减少人工操作。

使用

依赖

<dependency>
  <groupId>org.eclipse.jgit</groupId>
  <artifactId>org.eclipse.jgit-parent</artifactId>
  <version>6.1.0.202203080745-r</version>
  <type>pom</type>
</dependency>

获取Repository对象

代码示例:https://wiki.eclipse.org/JGit/User_Guide#git-add
官方文档非常旧并且很久没更新了,上次是2010年。。。。

//官方代码
 Repository repository = new FileRepositoryBuilder()
                .setGitDir(new File("C:\\..\\.git"))
                .readEnvironment() 
                .findGitDir() // scan up the file system tree
                .build();
// 一般选择封装成方法
/*
     * @Author Larry Luo
     * @Date 9:55 2022/4/12
     * @Description 获取git的repository

     * @param: dir 项目中.git文件本地路径

     * @Return org.eclipse.jgit.lib.Repository
     * @Exception
     */
    public static Repository getRepository(String dir) {
        try {
            Repository repository = new FileRepositoryBuilder()
                    	.setGitDir(new File("C:\\..\\.git"))
			.readEnvironment() 
                	.findGitDir()		
                    	.build();
            return repository;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

获取GIT对象

拿到git对象后就可以去执行git操作了

public static Git getGitObj(Repository repository) {
        Git git = null;

        git = new Git(repository);

        return git;
    }

image.png
这里面最常用的比如切换分支,新建分支,删除分支,revet,reset,commit,add。
先附上官方操作代码:

Git git = new Git(db);
AddCommand add = git.add();
add.addFilepattern("需要add的文件名或者文件目录").call();

Git git = new Git(db);
CommitCommand commit = git.commit();
commit.setMessage("initial commit").call();

Git git = new Git(db);
RevCommit commit = git.commit().setMessage("initial commit").call();
RevTag tag = git.tag().setName("tag").call();

Git git = new Git(db);
Iterable<RevCommit> log = git.log().call();

实际使用过程不会这么简单,一般操作如下:

1.new branch from …

你需要先checkout base的分支然后create。

 git.checkout().setName(baseBranch).call();
 git.branchCreate().setName(新分支名).call();
//切换到新分支
 git.checkout().setName(新分支名).call();

2.add&commit

实际使用时不可能就简单的commit就完事了。

git.add().addFilepattern(".").call();
git.rm().addFilepattern(".").call()
//setall()对应 -a 命令
git.commit().setMessage(commit msg).setAll(false).call();

// 一般的在add之前还会需要查看文件status,然后决定add哪些或者rm哪些
Status status = git.status().call();
Map<String,String> map = new HashMap<String,String>();
map.put("Added", status.getAdded().toString());
map.put("Changed", status.getChanged().toString());
map.put("Conflicting", status.getConflicting().toString());
map.put("ConflictingStageState", status.getConflictingStageState().toString());
map.put("IgnoredNotInIndex", status.getIgnoredNotInIndex().toString());
map.put("Missing", status.getMissing().toString());
map.put("Modified", status.getModified().toString());
map.put("Removed", status.getRemoved().toString());
map.put("UntrackedFiles", status.getUntracked().toString());
map.put("UntrackedFolders", status.getUntrackedFolders().toString());
System.out.println(map);

3.revert

使用git对象revert时需要拿到你当初commit的commitid或者其他操作的objectid。

git.revert().include(ObjectId.fromString(commitId)).setOurCommitName("OURS").call();

看了几个例子,代码就一行,要求输入commitid然后操作。。。。。但是不可能谁能记住哪次commit的commitid,所以我这里选择通过log去获取Revcommit对象,目前没找到别的途径。

List<String> commitIdList = new LinkedList<>();
gitObj.log().call().forEach(e -> finalPluginCommitLogList.add(e.getName()));

一般是根据特殊的commit msg去筛选需要使用的commit对象,然后获取到id操作。

PS

以上主要是对本地git仓库操作,一般可以用来做一些本地小工具去简化一些固定的人工操作流程,仅供参考。

其他参考

https://blog.csdn.net/qq_44299928/article/details/109577937


版权声明:本文为weixin_54106626原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。