java代码调用git命令_JGIT 实现java代码的git client操作

JGIT 实现java代码的git client操作

pom依赖

org.eclipse.jgit

org.eclipse.jgit

4.4.1.201607150455-r

示例测试代码

package test;

import static org.junit.Assert.fail;

import java.io.File;

import java.io.IOException;

import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode;

import org.eclipse.jgit.api.Git;

import org.eclipse.jgit.api.errors.GitAPIException;

import org.eclipse.jgit.api.errors.JGitInternalException;

import org.eclipse.jgit.internal.storage.file.FileRepository;

import org.eclipse.jgit.lib.Repository;

import org.junit.After;

import org.junit.AfterClass;

import org.junit.Before;

import org.junit.BeforeClass;

import org.junit.Test;

public class TestJGit {

private String localPath, remotePath;

private Repository

localRepo;

private Git git;

@BeforeClass

public static void setUpBeforeClass()

throws Exception

{

}

@AfterClass

public static void tearDownAfterClass()

throws Exception

{

}

@Before

public void setUp() throws Exception {

localPath = "/Users/jack/gitcode/jgit";

remotePath = "git@gitlab.xxxx.com:esigngroup/lhotse_hsftest.git";

localRepo = new FileRepository(localPath + "/.git");

git = new Git(localRepo);

}

@Test

public void testCreate() throws IOException

{

Repository newRepo

= new

FileRepository(localPath + "/.git");

newRepo.create();

}

@Test

public void testClone() throws IOException, GitAPIException {

Git.cloneRepository().setURI(remotePath).setBranch("finance")

.setDirectory(new File(localPath)).call();

}

@Test

public void testPull() throws IOException, GitAPIException {

git.pull().setRemoteBranchName("finance").call();

}

@Test

public void testAdd() throws IOException, GitAPIException {

File myfile = new File(localPath + "/myfile");

myfile.createNewFile();

git.add().addFilepattern("myfile").call();

}

@Test

public void testCommit() throws IOException, GitAPIException,

JGitInternalException {

git.commit().setMessage("Added myfile").call();

}

@Test

public void testPush() throws IOException, JGitInternalException,

GitAPIException {

git.push().call();

}

@Test

public void testTrackMaster()

throws IOException, JGitInternalException,

GitAPIException {

git.branchCreate().setName("master")

.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)

.setStartPoint("origin/master").setForce(true).call();

}

@After

public void tearDown() throws Exception {

}

@Test

public void test() {

fail("Not

yet implemented");

}

}

完整代码

package com.steda.spider;

import org.eclipse.jgit.api.Git;

import org.eclipse.jgit.internal.storage.file.FileRepository;

import org.eclipse.jgit.lib.Repository;

import java.io.File;

public class CodeDownloaderGIT implements

CodeDownloader {

private String localPath, remotePath, branch;

private Repository

localRepo;

private Git git;

//

TODO git代码下载

public String download(String appName, String codeUrl) {

try {

//代码拷贝目录

localPath = System.getProperty("user.home") + "/" + appName;

localRepo = new FileRepository(localPath + "/.git");

git = new Git(localRepo);

String[] gitCodeUrl = codeUrl.split("::");

if (gitCodeUrl.length != 2) {

return "git代码地址请按照格式:

git@gitlab.[host].com:esigngroup/lhotse_hsftest.git::[branch]";

}

remotePath = gitCodeUrl[0]; //

git@gitlab.[host].com:esigngroup/lhotse_hsftest.git::[branch]

branch = gitCodeUrl[1];

File localPathFile

= new

File(localPath);

//

如果没有该代码目录,就执行git clone

if (!localPathFile.exists()) {

gitClone(remotePath, branch, localPath);

} else { // 如果有代码,git

pull

gitPull(branch);

}

} catch (Exception e) {

e.printStackTrace();

}

return localPath;

}

private void gitClone(String remotePath, String branch, String copyPath) {

try {

Git.cloneRepository().setURI(remotePath).setBranch(branch)

.setDirectory(new File(copyPath)).call();

} catch (Exception e) {

e.printStackTrace();

}

}

private void gitPull(String branch) {

try {

git.pull().setRemoteBranchName(branch).call();

} catch (Exception e) {

e.printStackTrace();

}

}

}

Porcelain

The plumbing APIs are rather complete, but it can be cumbersome

to string them together to achieve common goals, like adding a file

to the index, or making a new commit. JGit provides a higher-level

set of APIs to help out with this, and the entry point to these

APIs is the Git class:

Repository

repo;

// construct

repo...

Git git = new Git(repo);

The Git class has a nice set of high-level builder-style methods

that can be used to construct some pretty complex behavior. Let’s

take a look at an example – doing something like git ls-remote:

CredentialsProvider

cp = new UsernamePasswordCredentialsProvider("username", "p4ssw0rd");

Collection

remoteRefs =

git.lsRemote()

.setCredentialsProvider(cp)

.setRemote("origin")

.setTags(true)

.setHeads(false)

.call();

for (Ref ref : remoteRefs) {

System.out.println(ref.getName() + "

-> " + ref.getObjectId().name());

}

This is a common pattern with the Git class; the methods return

a command object that lets you chain method calls to set

parameters, which are executed when you call .call(). In this case,

we’re asking the origin remote for tags, but not heads. Also notice

the use of aCredentialsProvider object for authentication.

Many other commands are available through the Git class, including

but not limited to add,blame, commit, clean, push, rebase, revert,

and reset.

遇到的坑UnknownHostKey Exception in Accessing GitHub

Securely

加上一句:

SshSessionFactory.setInstance(new JschConfigSessionFactory()

{

@Override

protected

void configure(OpenSshConfig.Host hc, Session session) {

session.setConfig("StrictHostKeyChecking",

"no");

}

});

package com.steda.spider;

import com.jcraft.jsch.Session;

import org.eclipse.jgit.api.Git;

import org.eclipse.jgit.internal.storage.file.FileRepository;

import org.eclipse.jgit.lib.Repository;

import org.eclipse.jgit.transport.*;

import java.io.File;

public class CodeDownloaderGIT implements

CodeDownloader {

private String localPath, remotePath, branch;

private Repository

localRepo;

private Git git;

//

TODO git代码下载

public String download(String appName, String codeUrl) {

try {

//代码拷贝目录

localPath = System.getProperty("user.home") + "/" + appName;

localRepo = new FileRepository(localPath + "/.git");

git = new Git(localRepo);

SshSessionFactory.setInstance(new JschConfigSessionFactory()

{

@Override

protected void configure(OpenSshConfig.Host hc, Session session) {

session.setConfig("StrictHostKeyChecking",

"no");

}

});

String[] gitCodeUrl = codeUrl.split("::");

if (gitCodeUrl.length != 2) {

return "git代码地址请按照格式:

git@gitlab.[host].com:esigngroup/lhotse_hsftest.git::[branch]";

}

remotePath = gitCodeUrl[0]; //

git@gitlab.[host].com:esigngroup/lhotse_hsftest.git::[branch]

branch = gitCodeUrl[1];

File localPathFile

= new

File(localPath);

//

如果没有该代码目录,就执行git clone

if (!localPathFile.exists()) {

gitClone(remotePath, branch, localPath);

} else { // 如果有代码,git

pull

gitPull(branch);

}

} catch (Exception e) {

e.printStackTrace();

}

return localPath;

}

private void gitClone(String remotePath, String branch, String copyPath) {

try {

//.setCredentialsProvider(cp)

Git.cloneRepository().setURI(remotePath).setBranch(branch)

.setDirectory(new File(copyPath)).call();

} catch (Exception e) {

e.printStackTrace();

}

}

private void gitPull(String branch) {

try {

git.pull().setRemoteBranchName(branch).call();

} catch (Exception e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
执行Java代码操作git命令的步骤可以参考以下引用内容。首先,你可以使用开源库jgit操作git命令。\[1\]接下来,你需要根据你的环境进行相应的准备工作。如果你在Windows环境下使用Java IDE,你可以直接运行代码。如果没有Java环境,你需要先安装Java并配置好环境变量。\[1\]在准备好环境后,你可以使用jgit操作git命令。你可以使用jgit提供的API来进行git项目的创建、克隆以及其他基本操作。\[2\]如果你想在Idea中集成git,你可以参考相关文档进行配置。\[2\]最后,你可以根据需要执行相应的git命令,比如更新分支等。\[1\]在执行git命令时,你可以使用application.properties文件来配置相关参数,比如git仓库地址、分支名称、项目名称、登录名字、登录密码以及本地路径等。\[3\]通过以上步骤,你就可以使用Java代码执行git命令了。 #### 引用[.reference_title] - *1* *3* [[Java实战][仅需一步][org.eclipse.jgit]代码操作git命令的步骤...再也不用手写git命令了](https://blog.csdn.net/aaaadong/article/details/126730887)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [java学习之git的基本使用](https://blog.csdn.net/qq_28356977/article/details/125598096)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值