使用gitlab java api 读取gitlab代码

前言:之前项目中有通过java读取gitlab中代码的需求,通过查资料和自己总结满足了需求,供大家参考。

  1. 引入依赖
<dependency>
    <groupId>org.gitlab4j</groupId>
    <artifactId>gitlab4j-api</artifactId>
    <version>4.19.0</version>
</dependency>
  1. application.yml中增加
gitlab:
  host: http://xxxx.xxxx.xxxx.xxxx:xxxx #gitlab地址
  accessToken: xxxxxxx #在gitlab生成的accessToken
  branch: master #分支名称
  1. 代码实现

controller

@RestController
@RequestMapping("gitLab")
public class GitLabController extends ApiController {
    @Autowired
    private GitlabService gitlabService;
    @PostMapping("getFile")
    public Result<Object> pullFileFromGitlab(@RequestBody GitLabConfig gitLabConfig){
        try {
            String file = gitlabService.readFile(gitLabConfig);
            return Result.success(file);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }
}

service

public interface GitlabService {
    /**
     * 读取gitlab
     * @param gitLabConfig
     * @return
     */
    String readFile(GitLabConfig gitLabConfig);
}

serviceImpl

@Slf4j
@Service
public class GitlabServiceImpl implements GitlabService {
    @Value("${gitlab.host}")
    private String gitUrl;
    @Value("${gitlab.accessToken}")
    private String accessToken;
    @Value("${gitlab.branch}")
    private String branch;
    @Override
    public String readFile(GitLabConfig gitLabConfig) {
        GitLabApi gitLabApi = new GitLabApi(gitUrl,accessToken);
        Project project = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            project = gitLabApi.getProjectApi().getProject(gitLabConfig.getNamespace, gitLabConfig.getProjectName());
        } catch (GitLabApiException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        try {
            InputStream inputStream = gitLabApi.getRepositoryFileApi().getRawFile(project.getId(), branch, gitLabConfig.getFilePath);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            bufferedReader.readLine();
            while ((line = bufferedReader.readLine())!=null){
                stringBuilder.append(line).append("\n");
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}

gitLabConfig请求参数

{
    "namespace": "xxxxx",
    "projectName": "xxxxxx",
    "filePath": "xxxxxxx"
}
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值