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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
use super::prelude::*;
use crate::{
    methods::Pagination,
    model::gists::{Gist, SimpleGist},
};
use std::{collections::HashMap, fmt::Display};

user_and_pagination_methods!(
    /// * tags gists
    /// * get `/users/{username}/gists`
    /// * docs <https://docs.github.com/rest/reference/gists#list-gists-for-a-user>
    ///
    /// List gists for a user
    /// Lists public gists for the specified user:
    get_user_gists,
    EndPoints::GetUsersusernameGists,
    Vec<SimpleGist>
);

/// * tags gists
/// * delete `/gists/{gist_id}`
/// * docs <https://docs.github.com/rest/reference/gists#delete-a-gist>
///
/// Delete a gist
pub async fn delete_gist<T, A>(client: &T, gist_id: A) -> Result<(), GithubRestError>
where
    T: Requester,
    A: Into<String>,
{
    client
        .raw_req::<String, String>(EndPoints::DeleteGistsgistId(gist_id.into()), None, None)
        .await?;

    Ok(())
}

#[derive(Serialize, Deserialize, Default, Clone, Debug)]
pub struct CreateGistBody {
    /// Schema:
    /// ```json
    /// "files": {
    ///     "filename": {
    ///         "content": "file contents"
    ///     }
    /// }
    /// ```
    pub files: HashMap<String, FileContents>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub public: bool,
}

#[derive(Serialize, Deserialize, Default, Clone, Debug)]
pub struct FileContents {
    pub content: String,
}

impl<T: Display> From<T> for FileContents {
    fn from(val: T) -> Self {
        FileContents {
            content: format!("{val}"),
        }
    }
}

/// * tags gists
/// * post `/gists`
/// * docs <https://docs.github.com/rest/reference/gists#create-a-gist>
///
/// Create a gist
/// Allows you to add a new gist with one or more files.
///
/// **Note:** Don't name your files "gistfile" with a numerical suffix. This is
/// the format of the automatic naming scheme that Gist uses internally.
pub async fn create_gist<T>(client: &T, body: &CreateGistBody) -> Result<Gist, GithubRestError>
where
    T: Requester,
{
    client
        .req::<String, String, Gist>(EndPoints::PostGists(), None, Some(serde_json::to_string(body).unwrap()))
        .await
}

#[derive(Serialize, Deserialize, Default, Clone, Debug)]
pub struct PatchGistBody {
    /// Schema:
    /// ```json
    /// "files": {
    ///     "filename": {
    ///         "content": "file contents"
    ///     }
    /// }
    /// ```
    pub files: HashMap<String, FileContents>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// * tags gists
/// * patch `/gists/{gist_id}`
/// * docs <https://docs.github.com/rest/reference/gists/#update-a-gist>
///
/// Update a gist
/// Allows you to update or delete a gist file and rename gist files. Files from
/// the previous version of the gist that aren't explicitly changed during an
/// edit are unchanged.
pub async fn patch_gist<T, A>(client: &T, gist_id: A, body: &PatchGistBody) -> Result<Gist, GithubRestError>
where
    T: Requester,
    A: Into<String>,
{
    client
        .req::<String, String, Gist>(
            EndPoints::PatchGistsgistId(gist_id.into()),
            None,
            Some(serde_json::to_string(&body).unwrap()),
        )
        .await
}

#[cfg(feature = "client")]
#[cfg(test)]
mod tests {
    use crate::{client::DefaultRequester, methods::util};

    use super::*;

    const GIST_ID: &str = "c2196b06d002d4ee278175bb82454a95";

    #[tokio::test]
    async fn test_get_user_gists() {
        let requester = DefaultRequester::new_none();
        let res = get_user_gists(&requester, "tricked-dev", None).await.unwrap();
        dbg!(res);
    }

    #[tokio::test]
    async fn test_create_gist() {
        let mut files = HashMap::new();
        files.insert("1.rs".to_owned(), r#"fn main() { println!("testing")}"#.into());

        let body = CreateGistBody {
            files,
            ..Default::default()
        };

        let res = create_gist(&util::github_auth(), &body).await.unwrap();
        dbg!(res);
    }

    #[tokio::test]
    async fn test_delete_gist() {
        delete_gist(&util::github_auth(), GIST_ID).await.unwrap()
    }

    #[tokio::test]
    async fn test_patch_gist() {
        let body = PatchGistBody {
            description: Some("Something".to_owned()),
            ..Default::default()
        };

        let res = patch_gist(&util::github_auth(), GIST_ID, &body).await.unwrap();
        dbg!(res);
    }
}