1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

#![forbid(unsafe_code)]

use anyhow::{anyhow, format_err, Result};
use reqwest::{header::USER_AGENT, Url};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct CommitInfo {
    pub sha: String,
    pub commit: GitCommitInfo,
}

#[derive(Debug, Deserialize)]
pub struct GitCommitInfo {
    pub author: Author,
    pub message: String,
}

#[derive(Debug, Deserialize)]
pub struct Author {
    pub name: String,
    pub email: String,
}

pub struct GitHub {
    client: reqwest::blocking::Client,
}

impl GitHub {
    pub fn new() -> GitHub {
        let client = reqwest::blocking::Client::new();
        GitHub { client }
    }

    /// repo in format owner/repo_name
    /// sha can be long or short hash, or branch name
    /// Paging is not implemented yet
    pub fn get_commits(&self, repo: &str, sha: &str) -> Result<Vec<CommitInfo>> {
        let url = format!("https://api.github.com/repos/{}/commits?sha={}", repo, sha);
        let url: Url = url.parse().map_err(|e| {
            anyhow!(
                "Failed to parse github url: {:?}\n, resulted in Error:{}",
                url,
                e
            )
        })?;
        let request = self.client.get(url);
        let response = request
            .header(USER_AGENT, "diem-cluster-test")
            .send()
            .map_err(|e| format_err!("Failed to query github: {:?}", e))?;
        let response: Vec<CommitInfo> = response
            .json()
            .map_err(|e| format_err!("Failed to parse github response: {:?}", e))?;
        Ok(response)
    }
}

impl Default for GitHub {
    fn default() -> Self {
        Self::new()
    }
}