snowpatch 0.2.0

continuous integration for patch-based workflows
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//
// snowpatch - continuous integration for patch-based workflows
//
// Copyright (C) 2016 IBM Corporation
// Authors:
//     Russell Currey <ruscur@russell.cc>
//     Andrew Donnellan <andrew.donnellan@au1.ibm.com>
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version.
//
// patchwork.rs - patchwork API
//

use std;
use std::collections::BTreeMap;
use std::fs::{File, OpenOptions};
use std::io;
use std::option::Option;
use std::path::PathBuf;
use std::result::Result;

use tempdir::TempDir;

use reqwest;
use reqwest::header::{
    qitem, Accept, Authorization, Basic, Connection, ContentType, Headers, Link, RelationType,
};
use reqwest::Client;
use reqwest::Response;
use reqwest::StatusCode;

use serde::{self, Serializer};
use serde_json;

use utils;

// TODO: more constants.  constants for format strings of URLs and such.
pub static PATCHWORK_API: &'static str = "/api/1.0";
pub static PATCHWORK_QUERY: &'static str = "?order=-id";

#[derive(Deserialize, Clone)]
pub struct SubmitterSummary {
    pub id: u64,
    pub url: String,
    pub name: String,
    pub email: String,
}

#[derive(Deserialize, Clone)]
pub struct DelegateSummary {
    pub id: u64,
    pub url: String,
    pub first_name: String,
    pub last_name: String,
    pub email: String,
}

// /api/1.0/projects/{id}
#[derive(Deserialize, Clone)]
pub struct Project {
    pub id: u64,
    pub url: String,
    pub name: String,
    pub link_name: String,
    pub list_email: String,
    pub list_id: String,
    pub web_url: Option<String>,
    pub scm_url: Option<String>,
    pub webscm_url: Option<String>,
}

// /api/1.0/patches/
// This omits fields from /patches/{id}, deal with it for now.

#[derive(Deserialize, Clone)]
pub struct Patch {
    pub id: u64,
    pub url: String,
    pub project: Project,
    pub msgid: String,
    pub date: String,
    pub name: String,
    pub commit_ref: Option<String>,
    pub pull_url: Option<String>,
    pub state: String, // TODO enum of possible states
    pub archived: bool,
    pub hash: Option<String>,
    pub submitter: SubmitterSummary,
    pub delegate: Option<DelegateSummary>,
    pub mbox: String,
    pub series: Vec<SeriesSummary>,
    pub check: String, // TODO enum of possible states
    pub checks: String,
    pub tags: BTreeMap<String, u64>,
}

impl Patch {
    pub fn has_series(&self) -> bool {
        !&self.series.is_empty()
    }

    pub fn action_required(&self) -> bool {
        &self.state == "new" || &self.state == "under-review"
    }
}

#[derive(Deserialize, Clone)]
pub struct PatchSummary {
    pub date: String,
    pub id: u64,
    pub mbox: String,
    pub msgid: String,
    pub name: String,
    pub url: String,
}

#[derive(Deserialize, Clone)]
pub struct CoverLetter {
    pub date: String,
    pub id: u64,
    pub msgid: String,
    pub name: String,
    pub url: String,
}

// /api/1.0/series/
// The series list and /series/{id} are the same, luckily
#[derive(Deserialize, Clone)]
pub struct Series {
    pub cover_letter: Option<CoverLetter>,
    pub date: String,
    pub id: u64,
    pub mbox: String,
    pub name: Option<String>,
    pub patches: Vec<PatchSummary>,
    pub project: Project,
    pub received_all: bool,
    pub received_total: u64,
    pub submitter: SubmitterSummary,
    pub total: u64,
    pub url: String,
    pub version: u64,
}

#[derive(Deserialize, Clone)]
pub struct SeriesSummary {
    pub id: u64,
    pub url: String,
    pub date: String,
    pub name: Option<String>,
    pub version: u64,
    pub mbox: String,
}

#[derive(Serialize, Clone, PartialEq)]
pub enum TestState {
    #[serde(rename = "pending")]
    Pending,
    #[serde(rename = "success")]
    Success,
    #[serde(rename = "warning")]
    Warning,
    #[serde(rename = "fail")]
    Fail,
}

impl Default for TestState {
    fn default() -> TestState {
        TestState::Pending
    }
}

// /api/1.0/series/*/revisions/*/test-results/
#[derive(Serialize, Default, Clone)]
pub struct TestResult {
    pub state: TestState,
    pub target_url: Option<String>,
    pub description: Option<String>,
    #[serde(serialize_with = "TestResult::serialize_context")]
    pub context: Option<String>,
}

impl TestResult {
    fn serialize_context<S>(context: &Option<String>, ser: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if context.is_none() {
            serde::Serialize::serialize(
                &Some(
                    format!("{}-{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"))
                        .to_string()
                        .replace(".", "_"),
                ),
                ser,
            )
        } else {
            serde::Serialize::serialize(context, ser)
        }
    }
}

pub struct PatchworkServer {
    pub url: String,
    headers: Headers,
    pub client: std::sync::Arc<Client>,
}

impl PatchworkServer {
    #[cfg_attr(feature = "cargo-clippy", allow(ptr_arg))]
    pub fn new(url: &String, client: &std::sync::Arc<Client>) -> PatchworkServer {
        let mut headers = Headers::new();
        headers.set(Accept(vec![qitem(reqwest::mime::APPLICATION_JSON)]));
        headers.set(ContentType(reqwest::mime::APPLICATION_JSON));
        PatchworkServer {
            url: url.clone(),
            client: client.clone(),
            headers,
        }
    }

    #[cfg_attr(feature = "cargo-clippy", allow(ptr_arg))]
    pub fn set_authentication(
        &mut self,
        username: &Option<String>,
        password: &Option<String>,
        token: &Option<String>,
    ) {
        match (username, password, token) {
            (&None, &None, &Some(ref token)) => {
                self.headers.set(Authorization(format!("Token {}", token)));
            }
            (&Some(ref username), &Some(ref password), &None) => {
                self.headers.set(Authorization(Basic {
                    username: username.clone(),
                    password: Some(password.clone()),
                }));
            }
            _ => panic!("Invalid patchwork authentication details"),
        }
    }

    pub fn get_url(&self, url: &str) -> std::result::Result<Response, reqwest::Error> {
        self.client
            .get(&*url)
            .headers(self.headers.clone())
            .header(Connection::close())
            .send()
    }

    pub fn get_url_string(&self, url: &str) -> std::result::Result<String, reqwest::Error> {
        let mut resp = try!(
            self.client
                .get(&*url)
                .headers(self.headers.clone())
                .header(Connection::close())
                .send()
        );
        let mut body: Vec<u8> = vec![];
        io::copy(&mut resp, &mut body).unwrap();
        Ok(String::from_utf8(body).unwrap())
    }

    pub fn post_test_result(
        &self,
        result: &TestResult,
        checks_url: &str,
    ) -> Result<StatusCode, reqwest::Error> {
        let encoded = serde_json::to_string(&result).unwrap();
        let headers = self.headers.clone();
        debug!("JSON Encoded: {}", encoded);
        let mut resp = try!(
            self.client
                .post(checks_url)
                .headers(headers)
                .body(encoded)
                .send()
        );
        let mut body: Vec<u8> = vec![];
        io::copy(&mut resp, &mut body).unwrap();
        trace!("{}", String::from_utf8(body).unwrap());
        assert_eq!(resp.status(), StatusCode::Created);
        Ok(resp.status())
    }

    pub fn get_patch(&self, patch_id: u64) -> Result<Patch, serde_json::Error> {
        let url = format!(
            "{}{}/patches/{}{}",
            &self.url, PATCHWORK_API, patch_id, PATCHWORK_QUERY
        );
        serde_json::from_str(&self.get_url_string(&url).unwrap())
    }

    pub fn get_patch_by_url(&self, url: &str) -> Result<Patch, serde_json::Error> {
        serde_json::from_str(&self.get_url_string(url).unwrap())
    }

    pub fn get_patch_query(&self, project: &str) -> Result<Vec<Patch>, serde_json::Error> {
        let url = format!(
            "{}{}/patches/{}&project={}",
            &self.url, PATCHWORK_API, PATCHWORK_QUERY, project
        );

        serde_json::from_str(
            &self
                .get_url_string(&url)
                .unwrap_or_else(|err| panic!("Failed to connect to Patchwork: {}", err)),
        )
    }

    fn get_next_link(&self, resp: &Response) -> Option<String> {
        let next = resp.headers().get::<Link>()?;
        for val in next.values() {
            if let Some(rel) = val.rel() {
                if rel.iter().any(|reltype| reltype == &RelationType::Next) {
                    return Some(val.link().to_string());
                }
            }
        }
        None
    }

    pub fn get_patch_query_num(
        &self,
        project: &str,
        num_patches: usize,
    ) -> Result<Vec<Patch>, serde_json::Error> {
        let mut list: Vec<Patch> = vec![];
        let mut url = Some(format!(
            "{}{}/patches/{}&project={}",
            &self.url, PATCHWORK_API, PATCHWORK_QUERY, project
        ));

        while let Some(real_url) = url {
            let resp = self
                .get_url(&real_url)
                .unwrap_or_else(|err| panic!("Failed to connect to Patchwork: {}", err));
            url = self.get_next_link(&resp);
            let new_patches: Vec<Patch> = serde_json::from_reader(resp)?;
            list.extend(new_patches);
            if list.len() >= num_patches {
                break;
            }
        }
        list.truncate(num_patches);
        Ok(list)
    }

    pub fn get_patch_dependencies(&self, patch: &Patch) -> Vec<Patch> {
        // We assume the list of patches in a series are in order.
        let mut dependencies: Vec<Patch> = vec![];
        let series = self.get_series_by_url(&patch.series[0].url);
        if series.is_err() {
            return dependencies;
        }
        for dependency in series.unwrap().patches {
            dependencies.push(self.get_patch_by_url(&dependency.url).unwrap());
            if dependency.url == patch.url {
                break;
            }
        }
        dependencies
    }

    pub fn get_patch_mbox(&self, patch: &Patch) -> PathBuf {
        let dir = TempDir::new("snowpatch").unwrap().into_path();
        let mut path = dir.clone();
        let tag = utils::sanitise_path(&patch.name);
        path.push(format!("{}.mbox", tag));

        let mut mbox_resp = self.get_url(&patch.mbox).unwrap();

        debug!("Saving patch to file {}", path.display());
        let mut mbox =
            File::create(&path).unwrap_or_else(|err| panic!("Couldn't create mbox file: {}", err));
        io::copy(&mut mbox_resp, &mut mbox)
            .unwrap_or_else(|err| panic!("Couldn't save mbox from Patchwork: {}", err));
        path
    }

    pub fn get_patches_mbox(&self, patches: Vec<Patch>) -> PathBuf {
        let dir = TempDir::new("snowpatch").unwrap().into_path();
        let mut path = dir.clone();
        let tag = utils::sanitise_path(&patches.last().unwrap().name);
        path.push(format!("{}.mbox", tag));

        let mut mbox = OpenOptions::new()
            .create(true)
            .write(true)
            .append(true)
            .open(&path)
            .unwrap_or_else(|err| panic!("Couldn't make file: {}", err));

        for patch in patches {
            let mut mbox_resp = self.get_url(&patch.mbox).unwrap();
            debug!("Appending patch {} to file {}", patch.name, path.display());
            io::copy(&mut mbox_resp, &mut mbox)
                .unwrap_or_else(|err| panic!("Couldn't save mbox from Patchwork: {}", err));
        }
        path
    }

    pub fn get_series(&self, series_id: u64) -> Result<Series, serde_json::Error> {
        let url = format!(
            "{}{}/series/{}{}",
            &self.url, PATCHWORK_API, series_id, PATCHWORK_QUERY
        );
        serde_json::from_str(&self.get_url_string(&url).unwrap())
    }

    pub fn get_series_by_url(&self, url: &str) -> Result<Series, serde_json::Error> {
        serde_json::from_str(&self.get_url_string(url).unwrap())
    }
}