关于gitlab api的一点使用,以及简单的gitlab工具类

工作中问题 专栏收录该内容
6 篇文章 0 订阅

    工作中难免需要使用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);
        }
        return null;

    }


    public static String getContentUrl(Integer projectId,
                                            String commitid ,
                                            String path) throws UnsupportedEncodingException {

        Request request = new Request.Builder()
                .url(String.format(CONTENT_URL + "?filepath=%s", projectId, commitid, path))
                .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);
        }
        return null;

    }

    /**
     *
     * @param projectId
     * @param branch
     * @param path
     * @param page
     * @param size
     * @return  获取历史版本信息
     * @throws UnsupportedEncodingException
     */
    public static String getHistoryUrl(Integer projectId,
                                       String branch,
                                       String path,
                                       int page,
                                       int size) throws UnsupportedEncodingException {
        if(path.startsWith("/")) {
            path = path.substring(1);
        }
        path = URLEncoder.encode(path, "UTF-8");

//        String url =String.format(HISTORY_URL + "?path=%s&ref=%s&per_page=%s&page=%s", projectId, path, branch, size, page);
//        System.out.println(url);

        Request request = new Request.Builder()
                .url(String.format(HISTORY_URL + "?path=%s&ref=%s&per_page=%s&page=%s", projectId, path, branch, size, page))
                .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);
        }
        return null;
    }
    /**
     *
     * @param projectId
     * @param commitId
     * @return 获取某个commit_id下的历史版本文件与最新文件之间的diff
     */
    public static String getDiffFile(Integer projectId, String commitId) {


        String url = String.format(DIFF_URL, projectId, commitId);
        System.out.println(url);
        Request request = new Request.Builder()
                .url(String.format(DIFF_URL, projectId, commitId))
                .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()) {
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (Exception e) {
            //log.error("view file " + path + " error.", e);
        }
        return null;
    }

    /**
     *
     * @param projectId
     * @param path
     * @param branch
     * @return 获取当前版本文件信息
     */
    public static String getCurrentVersionFile(Integer projectId, String path, String branch) {

        Request request = new Request.Builder()
                .url(String.format(CURRENT_VERSION + "?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()) {
                return Objects.requireNonNull(response.body()).string();
            }
        } catch (Exception e) {
            //log.error("view file " + path + " error.", e);
        }
        return null;
    }

    /**
     *
     * @param projectId
     * @param branch
     * @param path
     * @param page
     * @param size
     * @return 获取到对应文件下,按照路径条件(页数和页大小)的commit_id 创建人 创建时间
     * @throws UnsupportedEncodingException
     */
    public static List<String> getCommitId(Integer projectId,
                                     String branch,
                                     String path,
                                     int page,
                                     int size ) throws UnsupportedEncodingException {

        gitlabBean gb = new gitlabBean();
        List<String> list = new ArrayList<>();

        String historyUrl = getHistoryUrl(projectId, branch, path, page, size);

        JSONArray jsonArray = JSONArray.parseArray(historyUrl);

        JSONObject jsonObject = new JSONObject();

        for (int i = 0; i < jsonArray.size(); i++) {
            jsonObject = jsonArray.getJSONObject(i);
            String id = jsonObject.getString("short_id");
            String authorName = jsonObject.getString("author_name");
            Date committedDate = jsonObject.getDate("committed_date");

            SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateTime = dateFm.format(committedDate);

            gb.setId(id);
            gb.setAuthorName(authorName);
            gb.setCommittedDate(dateTime);

            list.add(id);
            list.add(authorName);
            list.add(dateTime);
        }

        return list;
    }

    public static void updateFile(Integer projectId,
                                  String branch,
                                  String path,
                                  String fileContent,
                                  String commitMsg,
                                  boolean isText,
                                  String userName) throws UnsupportedEncodingException {

        RequestBody body;
        if (isText) {
            body = new FormBody.Builder()
                    .add("branch", branch)
                    .add("content", fileContent)
                    .add("author_email", userName)
                    .add("author_name", userName.substring(0, userName.indexOf("@")))
                    .add("commit_message", commitMsg)
                    .build();
        } else {
            body = new FormBody.Builder()
                    .add("branch", branch)
                    .add("encoding", "base64")
                    .add("content", fileContent)
                    .add("author_email", userName)
                    .add("author_name", userName.substring(0, userName.indexOf("@")))
                    .add("commit_message", commitMsg)
                    .build();
        }

        path = URLEncoder.encode(path, "UTF-8");

        Request request = new Request.Builder()
                .url(String.format(CURRENT_VERSION + "?file_path=%s&ref=%s", projectId, path, branch))
                //.url(String.format(URL, + "?file_path=%s&ref=%s", projectId, path, branch))
                .header("PRIVATE-TOKEN", PRIVATE_TOKEN)
                .put(body)
                .build();

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .build();

        try (Response response = client.newCall(request).execute()) {
            //log.info("update git file: {}", Objects.requireNonNull(response.body()).string());
        } catch (Exception e) {
           // log.error("update file " + path + " error!!", e);
        }
    }

    /**
     *
     * @param commidId
     * @param path
     * @param project_id
     * @param branch
     * @return  回滚版本,使用api得到当前content,使用api得到某个commit对应的content,替换
     * @throws UnsupportedEncodingException
     */
    public static void rollBach2Version(String commidId,
                                           String path,
                                           Integer project_id,
                                           String branch
                                            ) throws UnsupportedEncodingException {

        if (path.startsWith("/")) {
            path = path.substring(1);
        }

        String contentUrl = getContentUrl(project_id, commidId, path);

        String viewFileContent = getViewFileContent(project_id, branch, path);

        JSONObject jsonObject = JSONObject.parseObject(viewFileContent);
        String content = jsonObject.getString("content");

        content = contentUrl;
        System.out.println(content);
        //替换完成以后还需要重新上传上线
        updateFile(PROJECT_ID, BRANCH, path, content, "test", true, "xx");
      //  return content;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {

        //回滚某个文件到某个commit历史版本
      //  rollBach2Version("831c9dd3763758ca5658832ec7d94564f90d5a97", "/src/main/java/test.java", PROJECT_ID, BRANCH);
//        String currentVersionFile = getCurrentVersionFile(PROJECT_ID, "/src/main/java/test.java", BRANCH);
//        System.out.println(currentVersionFile);
        //获取某个文件当前版本和历史某个commitid的diff
      //  String t = getDiffFile(PROJECT_ID, "085e074f6a0ca8e20e09b30557376bf627ab48f2");
       // System.out.println(t);
        //获取某个历史版本的文件信息
//        String t = getHistoryUrl(PROJECT_ID,BRANCH,"/src/main/java/test.java",1,10);
//        System.out.println(t);
        //获取某个文件历史版本的内容
        String contentUrl = getContentUrl(PROJECT_ID, "2613ed7f72f65fad8bc6770064b9bb4ce283d662", "src/main/java/test.java");
        System.out.println(contentUrl);

        //获取某个文件的所有的历史版本以及获取里面的字段信息
      // List commitId = getCommitId(PROJECT_ID, BRANCH, "src/main/java/test.java", 1, 1);
//        for (int i = 0; i < commitId.size(); i++) {
//            System.out.println(commitId.get(i));
//        }
        //获取当前版本的某个文件的全部信息
//        String master = getCurrentVersionFile(PROJECT_ID, "/src/main/java/test.java", "master");
//        System.out.println(master);
        //获取某历史版本的文件内容
    //获取某个文件历史版本的内容
//        String historyVersionContent = getHistoryVersionContent("01ac89", "src/main/java/test.java");
//        System.out.println(historyVersionContent);
    }
} 

 

在官网上找怎样获取某个文件,某个历史版本的内容,终于找到这个,

GET /projects/:id/repository/blobs/:sha
  • id (required) - The ID of a project
  • sha (required) - The commit or branch name

结果我写了后,发现一直有问题,至于什么问题试试就知道,我大概说下解决方法,首先一定得是V3版本,再就是官方没说还有一个必须项目filepath ,完整的url如下:

https://xxx/api/v3/projects/projectid/repository/blobs/commitid?filepath=filepath

 

具体可以参考代码里面的getConentUrl方法即可。 

 

  • 1
    点赞
  • 1
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 黑客帝国 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值