自学内容网 自学内容网

Jgit的使用

Jgit的使用


当需要对系统中某些页面管理的文件做版本管理时,使用git作为其基本组件。

此时需要在页面上做一些按钮,操作时会执行git指令。

使用java作为开发语言时,需要引用jgit依赖

例如

<dependency>
    <groupId>org.eclipse.jgit</groupId>
    <artifactId>org.eclipse.jgit</artifactId>
    <version>6.5.0.202303070854-r</version>
</dependency>

一,git操作的对应代码

1.1 查看操作

1.1.1 打开仓库

Git git = Git.open(new File(repoPath));

举例:

String repositoryPath = "E:\Workspace\GitHab\test-git-demo";
Repository repository = new FileRepositoryBuilder().setGitDir(new File(repositoryPath, ".git")).build();
Git git = new Git(repository);

// 或

Git git = Git.open(new File(repositoryPath));

1.1.3 获取状态信息

Status status = git.status().call();

1.2 添加操作

1.2.1 初始化本地仓库

// 执行代码前不存在new-git-repository-demo目录
String repositoryPath = "E:\Workspace\GitHab\new-git-repository-demo";
Git.init().setDirectory(repositoryPath).call();

Repository repository = Git.init().setGitDir(repoDir).call().getRepository()

1.2.2 创建一个新文件并写入内容

File file = new File(repositoryPath, "xxx.txt");
FileWriter writer = new FileWriter(file);
writer.write("Hello, JGit!\n");
writer.close();

1.2.3 添加指定(所有)文件到暂存区

// 不需要将repositoryPath目录写上,从该目录下开始即可
git.add().addFilepattern("xxx.txt").call();

// 指定所有文件
git.add().addFilepattern(".").call();

1.2.4 提交操作

// 提交更改
git.commit().setMessage("Commit message for add and modified file xxx.txt").call();

1.2.5 连接并推送到远程仓库

String remoteRepoUrl = "https://github.com/"
String userName = "git账号";
String password = "git账号密码";
// 连接到远程仓库
git.remoteAdd().setName("origin").setUri(new java.net.URI(remoteRepoUrl)).call();

CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(userName, password);
git.push().setCredentialsProvider(credentialsProvider).call();

到这里,虽然jgit能够做很多git操作,但如果需要直接在服务器创建远程仓库,单靠jgit还是不够的,此时就需要gitlab4j-api。

gitlab4j-api提供了更多的gitlab中API的调用方法。


原文地址:https://blog.csdn.net/lmchhh/article/details/142764095

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!