【Git】使用程序控制Git(20230515更新)

Java - JGit

依赖

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

ps:版本号随时可能更新,频率很高,注意版本之间兼容性

JGit官网

基本操作

打开git仓库
File file = new File("C:\aa\bb\cc");		//本地仓库目录
Git git = Git.open(file);
登录git账号
String account = "账号";
String password = "密码";
UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(account, password);

UsernamePasswordCredentialsProvider 对象实现git仓库对用户操作的鉴权。

clone
git = Git.cloneRepository()
            .setURI("http://127.0.0.1:8080/xxx.git")	//远程git地址
            .setBranch("branchName")					//分支名字
            .setDirectory(file)							//本地git仓库对象
            .setCredentialsProvider(provider)			//操作用户对象
            .call();									//所有JGit命令都有一个call()方法,设置该命令后,该方法将用于实际执行它。
checkout
git.checkout().setCreateBranch(true).setName("branchName").call();			//切换分支,并创建目标分支
git.checkout().setCreateBranch(false).setName("branchName").call();			//切换分支,不创建目标分支
pull
git.pull()
        .setRemoteBranchName("branchName")				//要拉取的远程分支名
        .setCredentialsProvider(provider)				//操作用户对象
        .call();
add
git.add().addFilepattern(".").call();		//add仓库目录下所有文件

git.add().addFilepattern("aaa.txt").call();	//添加仓库目录下的aaa.txt文件

addFilepattern()中的参数用于筛选出要add的文件路径
addFilePattern()提供的路径必须相对于工作目录根目录。
传递“.” 将以递归方式添加工作目录中的所有文件。 但是尚不支持本地Git中可用的fileglob(例如* .java)。
注意:必须设定addFilepattern()内容,否则会报异常。

commit
git.commit()
    .setAuthor("account", "email")		//设置commit用户,若不设置,则commit用户跟随分支创建者
    .setMessage("msg")					//必需,否则报错
    .call();		
push
git.push()
        .setCredentialsProvider(provider)
        .call();
获取分支
git.getRepository()			//获取当前分支
    .getBranch();			//获取当前分支名
List<Ref> refs = git.branchList().call();	//获取所有分支

其他操作

JGit入门

业务事项

分支切换

当上传位置与代码实际位置不一样时,checkout方法执行后并不会切换分支所对应的代码,注意先清空原有代码,然后远程拉取,再执行后续操作。

不同仓库鉴权方式

包含github与gitlab

JGit Authentication Explained (codeaffine.com)

其他

日期使用时造成的Bug

Git中AuthorDate和CommitDate的区别以及由此引起的JGit使用时造成的Bug

jgit 访问tfs(Azure DevOps Service)支持不佳

来源 :Eclipse Community Forums: EGit / JGit » Can you and how to connect to azure devops git supported?

tfs out of the box is configured only for NTLM authentication over HTTP. jgit does not do NTLM, and we have no plans to add support for it. We’re not going to invest time to support a broken protocol of which even Microsoft says new applications shouldn’t use it. (They say so in their very own NTLM specification.)

Possible solutions I know of are:

  • Use SSH. Users will probably have to upload an SSH public key to the server first. (Once.) Don’t know if the server needs special configuration to enable SSH access.
  • Use Kerberos (SPNEGO), either with HTTP(S) or SSH. Difficult to configure on server and client side.
  • Make sure your server is accessible only over HTTPS and enable basic authentication in the server.
  • Use a proxy like cntlm on the client side. Don’t know if that works reliably.

Please see the tfs/Azure Devops manuals for how exactly to do any of these. Once the server (or the cntlm proxy) is configured, jgit can clone/fetch from it, or push to it.

简而言之,jgit仅支持basic and digest authentication,对于tfs(现Azure devops services)使用的ntlm authentication是不兼容的。

推荐使用微软的git api来访问tfs:用于Azure DevOps Services - Azure DevOps Services REST API | Microsoft Learn

命令行操作git

使用ProcessBuilder 调用cmd通过命令行来操控git,有一定的风险,因为操作是完全的命令行,对本地环境的修改有直接影响。

	String cmd = "git push ";
	ProcessBuilder pb = new ProcessBuilder()
    	.command("cmd.exe", "/c", cmd)
    	.directory(new File(dir))
    	.inheritIO();

	pb.redirectErrorStream(true);

	//File file = new File(url);

	pb.redirectOutput(file);//start()后把执行结果输出到目标文件。
	pb.start().waitFor();

    //List<String> line = FileUtils.readLines(file, StandardCharsets.UTF_8);
    //for (String s : line) {
    //    logger.info("--- {}",s);
    //    if (s.startsWith(FATAL) || s.startsWith(ERROR)) {
    //        throw new RuntimeException("Checkout failure");
    //    }
    //}
	//Files.delete(file.toPath());

使用命令行操作时应严格遵循git操作规范进行!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值