WordPress網(wǎng)站hym地圖百度一下電腦版首頁網(wǎng)址
Jgit的使用
文章目錄
- Jgit的使用
- 一,git操作的對應(yīng)代碼
- 1.1 查看操作
- 1.1.1 打開倉庫
- 1.1.3 獲取狀態(tài)信息
- 1.2 添加操作
- 1.2.1 初始化本地倉庫
- 1.2.2 創(chuàng)建一個新文件并寫入內(nèi)容
- 1.2.3 添加指定(所有)文件到暫存區(qū)
- 1.2.4 提交操作
- 1.2.5 連接并推送到遠(yuǎn)程倉庫
當(dāng)需要對系統(tǒng)中某些頁面管理的文件做版本管理時,使用git作為其基本組件。
此時需要在頁面上做一些按鈕,操作時會執(zhí)行g(shù)it指令。
使用java作為開發(fā)語言時,需要引用jgit依賴
例如
<dependency><groupId>org.eclipse.jgit</groupId><artifactId>org.eclipse.jgit</artifactId><version>6.5.0.202303070854-r</version>
</dependency>
一,git操作的對應(yīng)代碼
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 獲取狀態(tài)信息
Status status = git.status().call();
1.2 添加操作
1.2.1 初始化本地倉庫
// 執(zhí)行代碼前不存在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 創(chuàng)建一個新文件并寫入內(nèi)容
File file = new File(repositoryPath, "xxx.txt");
FileWriter writer = new FileWriter(file);
writer.write("Hello, JGit!\n");
writer.close();
1.2.3 添加指定(所有)文件到暫存區(qū)
// 不需要將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 連接并推送到遠(yuǎn)程倉庫
String remoteRepoUrl = "https://github.com/"
String userName = "git賬號";
String password = "git賬號密碼";
// 連接到遠(yuǎn)程倉庫
git.remoteAdd().setName("origin").setUri(new java.net.URI(remoteRepoUrl)).call();CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(userName, password);
git.push().setCredentialsProvider(credentialsProvider).call();
到這里,雖然jgit能夠做很多git操作,但如果需要直接在服務(wù)器創(chuàng)建遠(yuǎn)程倉庫,單靠jgit還是不夠的,此時就需要gitlab4j-api。
gitlab4j-api提供了更多的gitlab中API的調(diào)用方法。