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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
//! Gists interface

use std::collections::HashMap;
use std::hash::Hash;

use futures::future;
use hyper::client::connect::Connect;
use url::form_urlencoded;

use users::User;
use {serde_json, Future, Github};

/// reference to gists associated with a github user
pub struct UserGists<C>
where
    C: Clone + Connect + 'static,
{
    github: Github<C>,
    owner: String,
}

impl<C: Clone + Connect + 'static> UserGists<C> {
    #[doc(hidden)]
    pub fn new<O>(github: Github<C>, owner: O) -> Self
    where
        O: Into<String>,
    {
        UserGists {
            github,
            owner: owner.into(),
        }
    }

    pub fn list(&self, options: &GistListOptions) -> Future<Vec<Gist>> {
        let mut uri = vec![format!("/users/{}/gists", self.owner)];
        if let Some(query) = options.serialize() {
            uri.push(query);
        }
        self.github.get(&uri.join("?"))
    }
}

pub struct Gists<C>
where
    C: Clone + Connect + 'static,
{
    github: Github<C>,
}

impl<C: Clone + Connect + 'static> Gists<C> {
    #[doc(hidden)]
    pub fn new(github: Github<C>) -> Self {
        Self { github }
    }

    fn path(&self, more: &str) -> String {
        format!("/gists{}", more)
    }

    pub fn star(&self, id: &str) -> Future<()> {
        self.github
            .put_no_response(&self.path(&format!("/{}/star", id)), Vec::new())
    }

    pub fn unstar(&self, id: &str) -> Future<()> {
        self.github.delete(&self.path(&format!("/{}/star", id)))
    }

    pub fn fork(&self, id: &str) -> Future<Gist> {
        self.github
            .post(&self.path(&format!("/{}/forks", id)), Vec::new())
    }

    pub fn forks(&self, id: &str) -> Future<Vec<GistFork>> {
        self.github.get(&self.path(&format!("/{}/forks", id)))
    }

    pub fn delete(&self, id: &str) -> Future<()> {
        self.github.delete(&self.path(&format!("/{}", id)))
    }

    pub fn get(&self, id: &str) -> Future<Gist> {
        self.github.get(&self.path(&format!("/{}", id)))
    }

    pub fn getrev(&self, id: &str, sha: &str) -> Future<Gist> {
        self.github.get(&self.path(&format!("/{}/{}", id, sha)))
    }

    pub fn list(&self, options: &GistListOptions) -> Future<Vec<Gist>> {
        let mut uri = vec![self.path("")];
        if let Some(query) = options.serialize() {
            uri.push(query);
        }
        self.github.get::<Vec<Gist>>(&uri.join("?"))
    }

    pub fn public(&self) -> Future<Vec<Gist>> {
        self.github.get(&self.path("/public"))
    }

    pub fn starred(&self) -> Future<Vec<Gist>> {
        self.github.get(&self.path("/starred"))
    }

    pub fn create(&self, gist: &GistOptions) -> Future<Gist> {
        self.github.post(&self.path(""), json!(gist))
    }

    pub fn edit(&self, id: &str, gist: &GistOptions) -> Future<Gist> {
        self.github
            .patch(&self.path(&format!("/{}", id)), json!(gist))
    }
}

// representations

#[derive(Default)]
pub struct GistListOptions {
    params: HashMap<&'static str, String>,
}

impl GistListOptions {
    pub fn since<T>(timestamp: T) -> GistListOptions
    where
        T: Into<String>,
    {
        let mut params = HashMap::new();
        params.insert("since", timestamp.into());
        GistListOptions { params }
    }

    /// serialize options as a string. returns None if no options are defined
    pub fn serialize(&self) -> Option<String> {
        if self.params.is_empty() {
            None
        } else {
            let encoded: String = form_urlencoded::Serializer::new(String::new())
                .extend_pairs(&self.params)
                .finish();
            Some(encoded)
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct GistFile {
    pub size: u64,
    pub raw_url: String,
    pub content: Option<String>,
    #[serde(rename = "type")]
    pub content_type: String,
    pub truncated: Option<bool>,
    pub language: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct Gist {
    pub url: String,
    pub forks_url: String,
    pub commits_url: String,
    pub id: String,
    pub description: Option<String>,
    pub public: bool,
    pub owner: Option<User>,
    pub user: Option<User>,
    pub files: HashMap<String, GistFile>,
    pub truncated: bool,
    pub comments: u64,
    pub comments_url: String,
    pub html_url: String,
    pub git_pull_url: String,
    pub git_push_url: String,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Debug, Deserialize)]
pub struct GistFork {
    pub user: User,
    pub url: String,
    pub id: String,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct Content {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,
    pub content: String,
}

impl Content {
    pub fn new<F, C>(filename: Option<F>, content: C) -> Content
    where
        F: Into<String>,
        C: Into<String>,
    {
        Content {
            filename: filename.map(|f| f.into()),
            content: content.into(),
        }
    }
}

pub struct GistOptionsBuilder(GistOptions);

impl GistOptionsBuilder {
    pub(crate) fn new<K, V>(files: HashMap<K, V>) -> Self
    where
        K: Clone + Hash + Eq + Into<String>,
        V: Into<String>,
    {
        let mut contents = HashMap::new();
        for (k, v) in files {
            contents.insert(k.into(), Content::new(None as Option<String>, v.into()));
        }
        GistOptionsBuilder(GistOptions {
            files: contents,
            ..Default::default()
        })
    }

    pub fn description<D>(&mut self, desc: D) -> &mut Self
    where
        D: Into<String>,
    {
        self.0.description = Some(desc.into());
        self
    }

    pub fn public(&mut self, p: bool) -> &mut Self {
        self.0.public = Some(p);
        self
    }

    pub fn build(&self) -> GistOptions {
        GistOptions {
            files: self.0.files.clone(),
            description: self.0.description.clone(),
            public: self.0.public,
        }
    }
}

#[derive(Debug, Default, Serialize)]
pub struct GistOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub public: Option<bool>,
    pub files: HashMap<String, Content>,
}

impl GistOptions {
    pub fn new<D, K, V>(desc: Option<D>, public: bool, files: HashMap<K, V>) -> GistOptions
    where
        D: Into<String>,
        K: Hash + Eq + Into<String>,
        V: Into<String>,
    {
        let mut contents = HashMap::new();
        for (k, v) in files {
            contents.insert(k.into(), Content::new(None as Option<String>, v.into()));
        }
        GistOptions {
            description: desc.map(|d| d.into()),
            public: Some(public),
            files: contents,
        }
    }

    pub fn builder<K, V>(files: HashMap<K, V>) -> GistOptionsBuilder
    where
        K: Clone + Hash + Eq + Into<String>,
        V: Into<String>,
    {
        GistOptionsBuilder::new(files)
    }
}

#[cfg(test)]
mod tests {
    use super::GistOptions;
    use serde::ser::Serialize;
    use serde_json;
    use std::collections::HashMap;

    fn test_encoding<E: Serialize>(tests: Vec<(E, &str)>) {
        for test in tests {
            match test {
                (k, v) => assert_eq!(serde_json::to_string(&k).unwrap(), v),
            }
        }
    }
    #[test]
    fn gist_reqs() {
        let mut files = HashMap::new();
        files.insert("foo", "bar");
        let tests = vec![
            (
                GistOptions::new(None as Option<String>, true, files.clone()),
                r#"{"public":true,"files":{"foo":{"content":"bar"}}}"#,
            ),
            (
                GistOptions::new(Some("desc"), true, files.clone()),
                r#"{"description":"desc","public":true,"files":{"foo":{"content":"bar"}}}"#,
            ),
        ];
        test_encoding(tests);
    }

    #[test]
    fn gist_req() {
        let mut files = HashMap::new();
        files.insert("test", "foo");
        let tests = vec![
            (
                GistOptions::builder(files.clone()).build(),
                r#"{"files":{"test":{"content":"foo"}}}"#,
            ),
            (
                GistOptions::builder(files.clone())
                    .description("desc")
                    .build(),
                r#"{"description":"desc","files":{"test":{"content":"foo"}}}"#,
            ),
            (
                GistOptions::builder(files.clone())
                    .description("desc")
                    .public(false)
                    .build(),
                r#"{"description":"desc","public":false,"files":{"test":{"content":"foo"}}}"#,
            ),
        ];
        test_encoding(tests)
    }
}