最近实在是懒得写周报以及一个个去询问同事的工作进度做汇总,故就产生了本项目。本人的思路是希望可以收集最近一周所有项目开发上传代码的Commit记录生成一个周报并且将周报信息发送至企业微信群中。

申请企业微信机器人

此步骤省略,直接手机企业微信群里面添加企业微信机器人即可,对于我们项目来说只需要拿到机器人对应的webhook。
注意: 你需要安全妥善保存好你的webhook不能被第三方所知晓。

了解私服的gitlab接口

对应的Commits类型的接口地址如下:https://{私服host地址}/help/api/commits.md

GET /projects/:id/repository/commits

PRIVATE-TOKEN

PRIVATE-TOKEN 可以在gitlab私服 https://{私服host地址}/profile/personal_access_tokens 这个页面中生成并配置相应的权限。

保存好你的PRIVATE-TOKEN 字符串

开始编码

下面是git Commits收集代码

@Service
public class GitlabService {

    @Value("${gitlab.pojects}")
    private String projects; //项目名称数组用;隔开

    @Value("${gitlab.refName}")
    private String refName;

    @Value("${gitlab.token}")
    private String gitlabToken; //上面的PRIVATE-TOKEN

    private final Logger logger = LoggerFactory.getLogger(GitlabService.class);

    public String doAction(String url, Map<String, String> params) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();

        Request.Builder reqBuild = new Request.Builder();
        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(url))
                .newBuilder();

        params.keySet().forEach(key -> urlBuilder.addQueryParameter(key, params.get(key)));

        reqBuild.url(urlBuilder.build());
        reqBuild.addHeader("PRIVATE-TOKEN", gitlabToken);
        reqBuild.addHeader("Cache-Control", "no-cache");
        reqBuild.method("GET", null);

        Request request = reqBuild.build();

        Response response = client.newCall(request).execute();
        return Objects.requireNonNull(response.body()).string();
    }


    public List<WxDto> getSimpleCommits(String since, String until) {
        Map<String, String> params = new HashMap<>();
        params.put("since", since);
        params.put("until", until);
        params.put("ref_name", refName);

        List<WxDto> result = new ArrayList<>();
        String[] ps = projects.split(";");
        for (String p : ps) {
            try {
                WxDto wxDto = new WxDto();
                List<SimpleCommit> simpleCommits = new ArrayList<>();

                String iid = URLEncoder.encode(p, "utf-8");
                String url =
                        "https://{gitlab私服地址}/api/v4/projects/" + iid + "/repository/commits";

                String responseBody = this.doAction(url, params);
                List<GitCommit> gitCommits = JSON.parseObject(responseBody,
                                                              new TypeReference<List<GitCommit>>() {
                                                              });
                assert gitCommits!=null;
                for (int i = gitCommits.size() - 1; i >= 0; i--) {
                    GitCommit temp = gitCommits.get(i);
                    if (temp.getParent_ids().size()==1) {
                        SimpleCommit simpleCommit = new SimpleCommit();
                        simpleCommit.setAuthor(temp.getCommitter_name());
                        simpleCommit.setContent(temp.getMessage());
                        simpleCommits.add(simpleCommit);
                    }
                }

                wxDto.setTitle(p);
                wxDto.setCommits(simpleCommits);
                if (simpleCommits.size() > 0) {
                    result.add(wxDto);
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }

        }
        return result;
    }
}
public class WxMarkdown {
    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
public class WxObj {

    private String msgtype = "markdown";

    private WxMarkdown markdown;

    public String getMsgtype() {
        return msgtype;
    }

    public void setMsgtype(String msgtype) {
        this.msgtype = msgtype;
    }

    public WxMarkdown getMarkdown() {
        return markdown;
    }

    public void setMarkdown(WxMarkdown markdown) {
        this.markdown = markdown;
    }
}
@Repository
public class WxReporter {//wx周报发送

    @Value("${wxHook}")
    private String wxHook;

    private final Logger logger = LoggerFactory.getLogger(WxReporter.class);


    public void doReport(List<WxDto> wxDto, String sinceTime, String endTime) {

        try {
            WxObj wxObj = new WxObj();
            WxMarkdown wxMarkdown = new WxMarkdown();

            StringBuilder content = new StringBuilder("# " + sinceTime + "-" + endTime + "周报\n");

            wxDto.forEach(item -> content.append(item.toString()));
            wxMarkdown.setContent(content.toString());
            wxObj.setMarkdown(wxMarkdown);

            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(wxObj));
            Request request = new Request.Builder()
                    .url(wxHook)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            client.newCall(request).execute();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

}