前言:之前项目中有通过java读取gitlab中代码的需求,通过查资料和自己总结满足了需求,供大家参考。
- 引入依赖
<dependency>
<groupId>org.gitlab4j</groupId>
<artifactId>gitlab4j-api</artifactId>
<version>4.19.0</version>
</dependency>
- application.yml中增加
gitlab:
host: http://xxxx.xxxx.xxxx.xxxx:xxxx #gitlab地址
accessToken: xxxxxxx #在gitlab生成的accessToken
branch: master #分支名称
- 代码实现
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"
}