工作中难免需要使用gitlab api来完成某些任务,现在写点这几天对gitlab api的一点使用心得。
公司有实时计算平台,上面的文件是保存git中,但是平台需要进行版本控制,也就是需要回滚、对比等操作,单纯的使用git命令,底层调用Linux命令太麻烦,比如需要回滚到某文件的某个commitID,需要使用git log filename拿到commitid,然后git reset 也好,其余git命令也好,完成后也只是在本地完成,还需要push上去,当然,每次操作前也需要先pull到最新的文件。这样会导致平台再版本控制模块很浪费时间资源,因此需要使用gitlab api来完成。
在使用gitlab api中也发现了官网的某个api的不完整性,以及v3 v4版本的差异,具体每个api的含义不做解释,真正需要用到gitlab api的当然知道怎么使用,下面就放上我的gitlabUtils方法,仅供参考。
package com.utils; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import okhttp3.*; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.TimeUnit; public class GitlabUtils { public static final Integer PROJECT_ID=xxxxx; private static final String PRIVATE_TOKEN = "xxxxx";//使用gitlab的应该知道这里是什么吧 private static final String CONTENT_URL = "https://code.xxx.com.cn/api/v3/projects/%d/repository/blobs/%s"; private static final String URL = "https://code.xxx.com.cn/api/v3/projects/%d/repository/files"; private static final String CURRENT_VERSION = "https://code.xxx.com.cn/api/v3/projects/%d/repository/files"; private static final String DIFF_URL = "https://code.xxxp.com.cn/api/v4/projects/%d/repository/commits/%s/diff"; private static final String HISTORY_URL = "https://code.xxx.com.cn/api/v4/projects/%d/repository/commits"; private static final String VIEW_URL = "https://code.xxx.com.cn/api/v3/projects/%d/repository/files"; public static final String BRANCH = "master"; /** * * @param projectId * @param branch * @param path * @return 查看文件内容 * @throws UnsupportedEncodingException */ public static String getViewFileContent(Integer projectId, String branch, String path) throws UnsupportedEncodingException { Request request = new Request.Builder() .url(String.format(VIEW_URL + "?file_path=%s&ref=%s", projectId, path, branch)) .header("PRIVATE-TOKEN", PRIVATE_TOKEN) .get() .build(); OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .build(); try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { String row = Objects.requireNonNull(response.body()).string(); // log.info("get catalogue files {}: {}", path, row); return row; } } catch (Exception e) { // log.error("get catalogue files " + path + " error.", e); } retur