DevOps系统文章之 JGit--将 Git 嵌入你的应用

如果你想在一个 Java 程序中使用 Git ,有一个功能齐全的 Git 库,那就是 JGit 。 JGit 是一个用 Java 写成的功能相对健全的 Git 的实现,它在 Java 社区中被广泛使用。 JGit 项目由 Eclipse 维护,它的主页。

依赖添加
有很多种方式可以将 JGit 依赖加入到你的项目,并依靠它去写代码。 最简单的方式也许就是使用 Maven 。你可以通过在你的 pom.xml 文件里的 标签中增加像下面这样的片段来完成这个整合。

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

在你读到这段文字时 version 很可能已经更新了,所以请浏览 http://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit 以获取最新的仓库信息。 当这一步完成之后, Maven 就会自动获取并使用你所需要的 JGit 库。

项目实践
在搭建我的博客的过程中,因为该博客是部署在自己的服务器上,需要在ci自动编译完成后,实现自动部署到我的服务器上(该步实现的方式很多,通过开放git接口,有编译部署的时候自动拉取到我的服务器就是其中的一个方法)

以下主要使用了pull拉取方法

package com.easy.jGit.controller;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.jgit.api.*;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

@RestController
@Slf4j
public class JGitController {

/**
 * git仓路径
 */
final String patch = "/opt/webapps/blog/.git";

/**
 * 代码分支
 */
final String branch = "origin/gh-pages";

/**
 * 拉取
 *
 * @return
 */
@RequestMapping("/pull")
public String pull() {
    String result;
    Repository repo = null;
    try {
        repo = new FileRepository(new File(patch));
        Git git = new Git(repo);

        log.info("开始重置");
        //重置
        git.reset()
                .setMode(ResetCommand.ResetType.HARD)
                .setRef(branch).call();

        log.info("开始拉取");

        //拉取
        git.pull()
                .setRemote("origin")
                .setRemoteBranchName("gh-pages")
                .call();
        result = "拉取成功!";
        log.info(result);
    } catch (Exception e) {
        result = e.getMessage();
    } finally {
        if (repo != null) {
            repo.close();
        }
    }
    return result;
}

/**
 * 重置
 *
 * @return
 */
@RequestMapping("/reset")
public String reset() {
    String result;

    Repository repo = null;
    try {
        repo = new FileRepository(new File(patch));
        Git git = new Git(repo);
        git.reset().setMode(ResetCommand.ResetType.HARD).setRef(branch).call();
        result = "重置成功!";

    } catch (Exception e) {
        re
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coder_Boy_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值