[snowpatch] [PATCH 3/4] Style changes from rustfmt
Russell Currey
ruscur at russell.cc
Thu Jul 12 19:49:44 AEST 2018
Signed-off-by: Russell Currey <ruscur at russell.cc>
---
src/git.rs | 53 ++++++++------
src/jenkins.rs | 75 +++++++++++--------
src/main.rs | 182 +++++++++++++++++++++++++++++------------------
src/patchwork.rs | 149 ++++++++++++++++++++++----------------
src/settings.rs | 20 +++---
src/utils.rs | 19 +++--
6 files changed, 303 insertions(+), 195 deletions(-)
diff --git a/src/git.rs b/src/git.rs
index ccf8bdf..bc93009 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -14,12 +14,12 @@
// git.rs - snowpatch git functionality
//
-use git2::{Repository, Commit, Remote, Error, PushOptions, Cred};
use git2::build::CheckoutBuilder;
+use git2::{Commit, Cred, Error, PushOptions, Remote, Repository};
-use std::result::Result;
use std::path::Path;
use std::process::{Command, Output};
+use std::result::Result;
use settings::Git;
@@ -31,9 +31,11 @@ pub fn get_latest_commit(repo: &Repository) -> Commit {
repo.find_commit(oid).unwrap()
}
-pub fn push_to_remote(remote: &mut Remote, branch: &str,
- mut opts: &mut PushOptions)
- -> Result<(), Error> {
+pub fn push_to_remote(
+ remote: &mut Remote,
+ branch: &str,
+ mut opts: &mut PushOptions,
+) -> Result<(), Error> {
let refspecs: &[&str] = &[&format!("+{}/{}", GIT_REF_BASE, branch)];
remote.push(refspecs, Some(&mut opts))
}
@@ -49,12 +51,14 @@ pub fn pull(repo: &Repository) -> Result<Output, &'static str> {
.unwrap(); // TODO
if output.status.success() {
- debug!("Pull: {}", String::from_utf8(output.clone().stdout).unwrap());
+ debug!(
+ "Pull: {}",
+ String::from_utf8(output.clone().stdout).unwrap()
+ );
Ok(output)
} else {
Err("Error: couldn't pull changes")
}
-
}
pub fn checkout_branch(repo: &Repository, branch: &str) -> () {
@@ -99,8 +103,7 @@ pub fn checkout_branch(repo: &Repository, branch: &str) -> () {
()
}
-pub fn apply_patch(repo: &Repository, path: &Path)
- -> Result<Output, &'static str> {
+pub fn apply_patch(repo: &Repository, path: &Path) -> Result<Output, &'static str> {
let workdir = repo.workdir().unwrap(); // TODO: support bare repositories
// We call out to "git am" since libgit2 doesn't implement "am"
@@ -113,15 +116,23 @@ pub fn apply_patch(repo: &Repository, path: &Path)
.unwrap(); // TODO
if output.status.success() {
- debug!("Patch applied with text {}",
- String::from_utf8(output.clone().stdout).unwrap());
+ debug!(
+ "Patch applied with text {}",
+ String::from_utf8(output.clone().stdout).unwrap()
+ );
Ok(output)
} else {
- info!("Patch failed to apply with text {} {}",
- String::from_utf8(output.clone().stdout).unwrap(),
- String::from_utf8(output.clone().stderr).unwrap());
- Command::new("git").arg("am").arg("--abort")
- .current_dir(&workdir).output().unwrap();
+ info!(
+ "Patch failed to apply with text {} {}",
+ String::from_utf8(output.clone().stdout).unwrap(),
+ String::from_utf8(output.clone().stderr).unwrap()
+ );
+ Command::new("git")
+ .arg("am")
+ .arg("--abort")
+ .current_dir(&workdir)
+ .output()
+ .unwrap();
Err("Patch did not apply successfully")
}
}
@@ -131,8 +142,10 @@ pub fn cred_from_settings(settings: &Git) -> Result<Cred, Error> {
let public_key = settings.public_key.as_ref().map(String::as_ref);
let passphrase = settings.passphrase.as_ref().map(String::as_ref);
- Cred::ssh_key(&settings.user,
- public_key,
- Path::new(&settings.private_key),
- passphrase)
+ Cred::ssh_key(
+ &settings.user,
+ public_key,
+ Path::new(&settings.private_key),
+ passphrase,
+ )
}
diff --git a/src/jenkins.rs b/src/jenkins.rs
index d8a2068..3d6ffb1 100644
--- a/src/jenkins.rs
+++ b/src/jenkins.rs
@@ -23,15 +23,15 @@
extern crate hyper;
extern crate url;
+use std::collections::BTreeMap;
use std::io::Read;
-use std::time::Duration;
-use std::thread::sleep;
use std::sync::Arc;
-use std::collections::BTreeMap;
+use std::thread::sleep;
+use std::time::Duration;
-use hyper::Client;
use hyper::client::{IntoUrl, RequestBuilder};
-use hyper::header::{Headers, Basic, Authorization, Location};
+use hyper::header::{Authorization, Basic, Headers, Location};
+use hyper::Client;
use serde_json::{self, Value};
use patchwork::TestState;
@@ -41,8 +41,10 @@ const JENKINS_POLLING_INTERVAL: u64 = 5000; // Polling interval in milliseconds
// Jenkins API definitions
-pub trait CIBackend { // TODO: Separate out
- fn start_test(&self, job_name: &str, params: Vec<(&str, &str)>) -> Result<String, &'static str>;
+pub trait CIBackend {
+ // TODO: Separate out
+ fn start_test(&self, job_name: &str, params: Vec<(&str, &str)>)
+ -> Result<String, &'static str>;
}
pub struct JenkinsBackend {
@@ -58,15 +60,20 @@ impl CIBackend for JenkinsBackend {
/// # Failures
///
/// Returns Err when HTTP request fails or when no Location: header is returned
- fn start_test(&self, job_name: &str, params: Vec<(&str, &str)>)
- -> Result<String, &'static str> {
+ fn start_test(
+ &self,
+ job_name: &str,
+ params: Vec<(&str, &str)>,
+ ) -> Result<String, &'static str> {
let params = url::form_urlencoded::Serializer::new(String::new())
.extend_pairs(params)
.finish();
- let res = self.post(&format!("{}/job/{}/buildWithParameters?{}",
- self.base_url, job_name, params))
- .send().expect("HTTP request error"); // TODO don't panic here
+ let res = self.post(&format!(
+ "{}/job/{}/buildWithParameters?{}",
+ self.base_url, job_name, params
+ )).send()
+ .expect("HTTP request error"); // TODO don't panic here
match res.headers.get::<Location>() {
Some(loc) => Ok(loc.to_string()),
@@ -85,14 +92,10 @@ impl JenkinsBackend {
fn headers(&self) -> Headers {
let mut headers = Headers::new();
if let Some(ref username) = self.username {
- headers.set(
- Authorization(
- Basic {
- username: username.clone(),
- password: self.token.clone(),
- }
- )
- );
+ headers.set(Authorization(Basic {
+ username: username.clone(),
+ password: self.token.clone(),
+ }));
}
headers
}
@@ -119,31 +122,37 @@ impl JenkinsBackend {
resp.read_to_string(&mut result_str)
.unwrap_or_else(|err| panic!("Couldn't read from server: {}", err));
break;
- }
- serde_json::from_str(&result_str).unwrap_or_else(
- |err| panic!("Couldn't parse JSON from Jenkins: {}", err)
- )
+ }
+ serde_json::from_str(&result_str)
+ .unwrap_or_else(|err| panic!("Couldn't parse JSON from Jenkins: {}", err))
}
pub fn get_build_url(&self, build_queue_entry: &str) -> Option<String> {
loop {
let entry = self.get_api_json_object(build_queue_entry);
match entry.get("executable") {
- Some(exec) => return Some(exec
+ Some(exec) => {
+ return Some(
+ exec
.as_object() // Option<BTreeMap>
.unwrap() // BTreeMap
.get("url") // Option<&str>
.unwrap() // &str ?
.as_str()
.unwrap()
- .to_string()),
+ .to_string(),
+ );
+ }
None => sleep(Duration::from_millis(JENKINS_POLLING_INTERVAL)),
}
}
}
pub fn get_build_status(&self, build_url: &str) -> JenkinsBuildStatus {
- if self.get_api_json_object(build_url)["building"].as_bool().unwrap() {
+ if self.get_api_json_object(build_url)["building"]
+ .as_bool()
+ .unwrap()
+ {
JenkinsBuildStatus::Running
} else {
JenkinsBuildStatus::Done
@@ -151,10 +160,14 @@ impl JenkinsBackend {
}
pub fn get_build_result(&self, build_url: &str) -> Option<TestState> {
- match self.get_api_json_object(build_url).get("result").unwrap()
- .as_str() {
+ match self.get_api_json_object(build_url)
+ .get("result")
+ .unwrap()
+ .as_str()
+ {
None => None,
- Some(result) => match result { // TODO: Improve this...
+ Some(result) => match result {
+ // TODO: Improve this...
"SUCCESS" => Some(TestState::Success),
"FAILURE" => Some(TestState::Fail),
"UNSTABLE" => Some(TestState::Warning),
@@ -166,7 +179,7 @@ impl JenkinsBackend {
pub fn get_results_url(&self, build_url: &str, job: &BTreeMap<String, String>) -> String {
match job.get("artifact") {
Some(artifact) => format!("{}/artifact/{}", build_url, artifact),
- None => format!("{}/consoleText/", build_url)
+ None => format!("{}/consoleText/", build_url),
}
}
diff --git a/src/main.rs b/src/main.rs
index aaa3ac9..c5a9ebf 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -19,11 +19,11 @@
// Equivalent of -Werror
#![deny(warnings)]
+extern crate docopt;
+extern crate git2;
extern crate hyper;
extern crate hyper_openssl;
-extern crate git2;
extern crate tempdir;
-extern crate docopt;
extern crate url;
#[macro_use]
extern crate log;
@@ -34,34 +34,34 @@ extern crate serde_derive;
extern crate serde_json;
extern crate toml;
-use git2::{BranchType, RemoteCallbacks, PushOptions};
+use git2::{BranchType, PushOptions, RemoteCallbacks};
-use hyper::Client;
use hyper::client::ProxyConfig;
+use hyper::client::RedirectPolicy;
use hyper::net::HttpsConnector;
+use hyper::Client;
use hyper_openssl::OpensslClient;
-use hyper::client::RedirectPolicy;
use docopt::Docopt;
use url::Url;
-use log::LevelFilter;
use env_logger::Builder;
+use log::LevelFilter;
+use std::env;
use std::fs;
+use std::path::Path;
use std::string::String;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
-use std::path::Path;
-use std::env;
mod patchwork;
-use patchwork::{PatchworkServer, TestState, TestResult};
+use patchwork::{PatchworkServer, TestResult, TestState};
mod jenkins;
-use jenkins::{JenkinsBackend, CIBackend};
+use jenkins::{CIBackend, JenkinsBackend};
mod settings;
use settings::{Config, Project};
@@ -101,8 +101,14 @@ struct Args {
flag_project: String,
}
-fn run_tests(settings: &Config, client: Arc<Client>, project: &Project, tag: &str,
- branch_name: &str, hefty_tests: bool) -> Vec<TestResult> {
+fn run_tests(
+ settings: &Config,
+ client: Arc<Client>,
+ project: &Project,
+ tag: &str,
+ branch_name: &str,
+ hefty_tests: bool,
+) -> Vec<TestResult> {
let mut results: Vec<TestResult> = Vec::new();
let jenkins = JenkinsBackend {
base_url: settings.jenkins.url.clone(),
@@ -126,7 +132,8 @@ fn run_tests(settings: &Config, client: Arc<Client>, project: &Project, tag: &st
jenkins_params.push((&job.branch, tag));
info!("Starting job: {}", &job.title);
- let res = jenkins.start_test(&job.job, jenkins_params)
+ let res = jenkins
+ .start_test(&job.job, jenkins_params)
.unwrap_or_else(|err| panic!("Starting Jenkins test failed: {}", err));
debug!("{:?}", &res);
let build_url_real;
@@ -145,8 +152,9 @@ fn run_tests(settings: &Config, client: Arc<Client>, project: &Project, tag: &st
test_result = TestState::Warning;
}
results.push(TestResult {
- description: Some(format!("Test {} on branch {}", job.title,
- branch_name.to_string()).to_string()),
+ description: Some(
+ format!("Test {} on branch {}", job.title, branch_name.to_string()).to_string(),
+ ),
state: test_result,
context: Some(format!("{}-{}", "snowpatch", job.title.replace("/", "_")).to_string()),
target_url: Some(jenkins.get_results_url(&build_url_real, &job.parameters)),
@@ -155,21 +163,23 @@ fn run_tests(settings: &Config, client: Arc<Client>, project: &Project, tag: &st
results
}
-fn test_patch(settings: &Config, client: &Arc<Client>, project: &Project,
- path: &Path, hefty_tests: bool) -> Vec<TestResult> {
+fn test_patch(
+ settings: &Config,
+ client: &Arc<Client>,
+ project: &Project,
+ path: &Path,
+ hefty_tests: bool,
+) -> Vec<TestResult> {
let repo = project.get_repo().unwrap();
let mut results: Vec<TestResult> = Vec::new();
if !path.is_file() {
return results;
}
- let tag = utils::sanitise_path(
- path.file_name().unwrap().to_str().unwrap().to_string());
+ let tag = utils::sanitise_path(path.file_name().unwrap().to_str().unwrap().to_string());
let mut remote = repo.find_remote(&project.remote_name).unwrap();
let mut push_callbacks = RemoteCallbacks::new();
- push_callbacks.credentials(|_, _, _| {
- git::cred_from_settings(&settings.git)
- });
+ push_callbacks.credentials(|_, _, _| git::cred_from_settings(&settings.git));
let mut push_opts = PushOptions::new();
push_opts.remote_callbacks(push_callbacks);
@@ -192,7 +202,10 @@ fn test_patch(settings: &Config, client: &Arc<Client>, project: &Project,
.unwrap_or_else(|err| panic!("Couldn't set HEAD: {}", err));
repo.checkout_head(None)
.unwrap_or_else(|err| panic!("Couldn't checkout HEAD: {}", err));
- debug!("Repo is now at head {}", repo.head().unwrap().name().unwrap());
+ debug!(
+ "Repo is now at head {}",
+ repo.head().unwrap().name().unwrap()
+ );
let output = git::apply_patch(&repo, path);
@@ -211,24 +224,30 @@ fn test_patch(settings: &Config, client: &Arc<Client>, project: &Project,
successfully_applied = true;
results.push(TestResult {
state: TestState::Success,
- description: Some(format!("{}/{}\n\n{}",
- branch_name.to_string(),
- "apply_patch".to_string(),
- "Successfully applied".to_string())
- .to_string()),
- .. Default::default()
+ description: Some(
+ format!(
+ "{}/{}\n\n{}",
+ branch_name.to_string(),
+ "apply_patch".to_string(),
+ "Successfully applied".to_string()
+ ).to_string(),
+ ),
+ ..Default::default()
});
- },
+ }
Err(_) => {
// It didn't apply. No need to bother testing.
results.push(TestResult {
state: TestState::Warning,
- description: Some(format!("{}/{}\n\n{}",
- branch_name.to_string(),
- "apply_patch".to_string(),
- "Patch failed to apply".to_string())
- .to_string()),
- .. Default::default()
+ description: Some(
+ format!(
+ "{}/{}\n\n{}",
+ branch_name.to_string(),
+ "apply_patch".to_string(),
+ "Patch failed to apply".to_string()
+ ).to_string(),
+ ),
+ ..Default::default()
});
continue;
}
@@ -241,26 +260,37 @@ fn test_patch(settings: &Config, client: &Arc<Client>, project: &Project,
let test_all_branches = project.test_all_branches.unwrap_or(true);
// We've set up a remote branch, time to kick off tests
- let test = thread::Builder::new().name(tag.to_string()).spawn(move || {
- run_tests(&settings_clone, client, &project, &tag, &branch_name,
- hefty_tests)
- }).unwrap();
+ let test = thread::Builder::new()
+ .name(tag.to_string())
+ .spawn(move || {
+ run_tests(
+ &settings_clone,
+ client,
+ &project,
+ &tag,
+ &branch_name,
+ hefty_tests,
+ )
+ })
+ .unwrap();
results.append(&mut test.join().unwrap());
- if !test_all_branches { break; }
+ if !test_all_branches {
+ break;
+ }
}
if !successfully_applied {
results.push(TestResult {
state: TestState::Fail,
description: Some("Failed to apply to any branch".to_string()),
- .. Default::default()
+ ..Default::default()
});
}
results
}
-#[cfg_attr(feature="cargo-clippy", allow(cyclomatic_complexity))]
+#[cfg_attr(feature = "cargo-clippy", allow(cyclomatic_complexity))]
fn main() {
let mut log_builder = Builder::new();
// By default, log at the "info" level for every module
@@ -270,8 +300,11 @@ fn main() {
}
log_builder.init();
- let version = format!("{} version {}",
- env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
+ let version = format!(
+ "{} version {}",
+ env!("CARGO_PKG_NAME"),
+ env!("CARGO_PKG_VERSION")
+ );
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.version(Some(version)).deserialize())
@@ -293,14 +326,17 @@ fn main() {
assert_eq!(proxy.scheme(), "http");
// This should pass even if no trailing slash is in http_proxy
assert_eq!(proxy.path(), "/");
- let proxy_config = ProxyConfig::new(proxy.scheme(),
- proxy.host_str().unwrap().to_string(),
- proxy.port().unwrap_or(80),
- connector, ssl);
+ let proxy_config = ProxyConfig::new(
+ proxy.scheme(),
+ proxy.host_str().unwrap().to_string(),
+ proxy.port().unwrap_or(80),
+ connector,
+ ssl,
+ );
let mut c = Client::with_proxy_config(proxy_config);
c.set_redirect_policy(RedirectPolicy::FollowAll);
c
- },
+ }
_ => {
debug!("snowpatch starting without a HTTP proxy");
let mut c = Client::with_connector(connector);
@@ -310,9 +346,11 @@ fn main() {
});
let mut patchwork = PatchworkServer::new(&settings.patchwork.url, &client);
- patchwork.set_authentication(&settings.patchwork.user,
- &settings.patchwork.pass,
- &settings.patchwork.token);
+ patchwork.set_authentication(
+ &settings.patchwork.user,
+ &settings.patchwork.pass,
+ &settings.patchwork.token,
+ );
let patchwork = patchwork;
if args.flag_series > 0 && args.flag_patch > 0 {
@@ -354,7 +392,9 @@ fn main() {
info!("snowpatch is testing a series from Patchwork.");
let series = patchwork.get_series(&(args.flag_series as u64)).unwrap();
// The last patch in the series, so its dependencies are the whole series
- let patch = patchwork.get_patch_by_url(&series.patches.last().unwrap().url).unwrap();
+ let patch = patchwork
+ .get_patch_by_url(&series.patches.last().unwrap().url)
+ .unwrap();
// We have to do it this way since there's no project field on Series
let project = patchwork.get_project(&patch.project.name).unwrap();
match settings.projects.get(&project.link_name) {
@@ -378,8 +418,9 @@ fn main() {
* Spawn tests.
*/
'daemon: loop {
- let patch_list = patchwork.get_patch_query().unwrap_or_else(
- |err| panic!("Failed to obtain patch list: {}", err));
+ let patch_list = patchwork
+ .get_patch_query()
+ .unwrap_or_else(|err| panic!("Failed to obtain patch list: {}", err));
info!("snowpatch is ready to test new revisions from Patchwork.");
for patch in patch_list {
// If it's already been tested, we can skip it
@@ -396,22 +437,29 @@ fn main() {
//let project = patchwork.get_project(&patch.project).unwrap();
// Skip if we're using -p and it's the wrong project
if args.flag_project != "" && patch.project.link_name != args.flag_project {
- debug!("Skipping patch {} ({}) (wrong project: {})",
- patch.name, patch.id, patch.project.link_name);
+ debug!(
+ "Skipping patch {} ({}) (wrong project: {})",
+ patch.name, patch.id, patch.project.link_name
+ );
continue;
}
match settings.projects.get(&patch.project.link_name) {
None => {
- debug!("Project {} not configured for patch {}",
- &patch.project.link_name, patch.name);
+ debug!(
+ "Project {} not configured for patch {}",
+ &patch.project.link_name, patch.name
+ );
continue;
- },
+ }
Some(project) => {
// TODO(ajd): Refactor this.
let hefty_tests;
let mbox = if patch.has_series() {
- debug!("Patch {} has a series at {}!", &patch.name, &patch.series[0].url);
+ debug!(
+ "Patch {} has a series at {}!",
+ &patch.name, &patch.series[0].url
+ );
let series = patchwork.get_series_by_url(&patch.series[0].url);
match series {
Ok(series) => {
@@ -422,8 +470,7 @@ fn main() {
let dependencies = patchwork.get_patch_dependencies(&patch);
hefty_tests = dependencies.len() == series.patches.len();
patchwork.get_patches_mbox(dependencies)
-
- },
+ }
Err(e) => {
debug!("Series is not OK: {}", e);
hefty_tests = true;
@@ -438,8 +485,8 @@ fn main() {
let results = test_patch(&settings, &client, project, &mbox, hefty_tests);
// Delete the temporary directory with the patch in it
- fs::remove_dir_all(mbox.parent().unwrap()).unwrap_or_else(
- |err| error!("Couldn't delete temp directory: {}", err));
+ fs::remove_dir_all(mbox.parent().unwrap())
+ .unwrap_or_else(|err| error!("Couldn't delete temp directory: {}", err));
if project.push_results {
for result in results {
patchwork.post_test_result(result, &patch.checks).unwrap();
@@ -447,8 +494,7 @@ fn main() {
}
if args.flag_count > 0 {
patch_count += 1;
- debug!("Tested {} patches out of {}",
- patch_count, args.flag_count);
+ debug!("Tested {} patches out of {}", patch_count, args.flag_count);
if patch_count >= args.flag_count {
break 'daemon;
}
diff --git a/src/patchwork.rs b/src/patchwork.rs
index c3c6286..3aecb58 100644
--- a/src/patchwork.rs
+++ b/src/patchwork.rs
@@ -15,22 +15,21 @@
//
use std;
-use std::io::{self};
+use std::collections::BTreeMap;
+use std::fs::{File, OpenOptions};
+use std::io;
use std::option::Option;
use std::path::PathBuf;
-use std::fs::{File, OpenOptions};
use std::result::Result;
-use std::collections::BTreeMap;
use tempdir::TempDir;
use hyper;
-use hyper::Client;
-use hyper::header::{Connection, Headers, Accept, ContentType, qitem,
- Authorization, Basic};
-use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
-use hyper::status::StatusCode;
use hyper::client::response::Response;
+use hyper::header::{qitem, Accept, Authorization, Basic, Connection, ContentType, Headers};
+use hyper::mime::{Attr, Mime, SubLevel, TopLevel, Value};
+use hyper::status::StatusCode;
+use hyper::Client;
use serde::{self, Serializer};
use serde_json;
@@ -46,7 +45,7 @@ pub struct SubmitterSummary {
pub id: u64,
pub url: String,
pub name: String,
- pub email: String
+ pub email: String,
}
#[derive(Deserialize, Clone)]
@@ -55,7 +54,7 @@ pub struct DelegateSummary {
pub url: String,
pub first_name: String,
pub last_name: String,
- pub email: String
+ pub email: String,
}
// /api/1.0/projects/{id}
@@ -94,7 +93,7 @@ pub struct Patch {
pub series: Vec<SeriesSummary>,
pub check: String, // TODO enum of possible states
pub checks: String,
- pub tags: BTreeMap<String, u64>
+ pub tags: BTreeMap<String, u64>,
}
impl Patch {
@@ -114,7 +113,7 @@ pub struct PatchSummary {
pub mbox: String,
pub msgid: String,
pub name: String,
- pub url: String
+ pub url: String,
}
#[derive(Deserialize, Clone)]
@@ -123,7 +122,7 @@ pub struct CoverLetter {
pub id: u64,
pub msgid: String,
pub name: String,
- pub url: String
+ pub url: String,
}
// /api/1.0/series/
@@ -142,7 +141,7 @@ pub struct Series {
pub submitter: SubmitterSummary,
pub total: u64,
pub url: String,
- pub version: u64
+ pub version: u64,
}
#[derive(Deserialize, Clone)]
@@ -184,15 +183,19 @@ pub struct TestResult {
}
impl TestResult {
- fn serialize_context<S>(context: &Option<String>, ser: S)
- -> Result<S::Ok, S::Error> where S: Serializer {
+ 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)
+ &Some(
+ format!("{}-{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"))
+ .to_string()
+ .replace(".", "_"),
+ ),
+ ser,
+ )
} else {
serde::Serialize::serialize(context, ser)
}
@@ -206,17 +209,19 @@ pub struct PatchworkServer {
}
impl PatchworkServer {
- #[cfg_attr(feature="cargo-clippy", allow(ptr_arg))]
+ #[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(Mime(TopLevel::Application,
- SubLevel::Json,
- vec![(Attr::Charset, Value::Utf8)]))])
- );
- headers.set(ContentType(Mime(TopLevel::Application,
- SubLevel::Json,
- vec![(Attr::Charset, Value::Utf8)]))
- );
+ headers.set(Accept(vec![qitem(Mime(
+ TopLevel::Application,
+ SubLevel::Json,
+ vec![(Attr::Charset, Value::Utf8)],
+ ))]));
+ headers.set(ContentType(Mime(
+ TopLevel::Application,
+ SubLevel::Json,
+ vec![(Attr::Charset, Value::Utf8)],
+ )));
PatchworkServer {
url: url.clone(),
client: client.clone(),
@@ -224,46 +229,63 @@ impl PatchworkServer {
}
}
- #[cfg_attr(feature="cargo-clippy", allow(ptr_arg))]
- pub fn set_authentication(&mut self, username: &Option<String>,
- password: &Option<String>,
- token: &Option<String>) {
+ #[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)));
- },
+ 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, hyper::error::Error> {
- self.client.get(&*url).headers(self.headers.clone())
- .header(Connection::close()).send()
+ pub fn get_url(&self, url: &str) -> std::result::Result<Response, hyper::error::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, hyper::error::Error> {
- let mut resp = try!(self.client.get(&*url).headers(self.headers.clone())
- .header(Connection::close()).send());
+ 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, hyper::error::Error> {
+ pub fn post_test_result(
+ &self,
+ result: TestResult,
+ checks_url: &str,
+ ) -> Result<StatusCode, hyper::error::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 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());
@@ -276,8 +298,10 @@ impl PatchworkServer {
}
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);
+ let url = format!(
+ "{}{}/patches/{}{}",
+ &self.url, PATCHWORK_API, patch_id, PATCHWORK_QUERY
+ );
serde_json::from_str(&self.get_url_string(&url).unwrap())
}
@@ -287,13 +311,13 @@ impl PatchworkServer {
pub fn get_patch_query(&self) -> Result<Vec<Patch>, serde_json::Error> {
let url = format!("{}{}/patches/{}", &self.url, PATCHWORK_API, PATCHWORK_QUERY);
- serde_json::from_str(&self.get_url_string(&url).unwrap_or_else(
- |err| panic!("Failed to connect to Patchwork: {}", err)))
+ serde_json::from_str(&self.get_url_string(&url)
+ .unwrap_or_else(|err| panic!("Failed to connect to Patchwork: {}", err)))
}
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 mut dependencies: Vec<Patch> = vec![];
let series = self.get_series_by_url(&patch.series[0].url);
if series.is_err() {
return dependencies;
@@ -316,10 +340,10 @@ impl PatchworkServer {
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));
+ 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
}
@@ -339,20 +363,21 @@ impl PatchworkServer {
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));
+ 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);
+ 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())
}
-
}
diff --git a/src/settings.rs b/src/settings.rs
index 0ce7031..2d39354 100644
--- a/src/settings.rs
+++ b/src/settings.rs
@@ -16,14 +16,14 @@
use toml;
-use serde::de::{self, Visitor, Deserializer, Deserialize, MapAccess};
+use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor};
-use git2::{Repository, Error};
+use git2::{Error, Repository};
+use std::collections::BTreeMap;
use std::fmt;
use std::fs::File;
use std::io::Read;
-use std::collections::BTreeMap;
// TODO: Give more informative error messages when we fail to parse.
@@ -32,7 +32,7 @@ pub struct Git {
pub user: String,
pub public_key: Option<String>,
pub private_key: String,
- pub passphrase: Option<String>
+ pub passphrase: Option<String>,
}
#[derive(Deserialize, Clone)]
@@ -53,7 +53,7 @@ pub struct Jenkins {
pub port: Option<u16>,
// TODO: fail if we only get one of username or token
pub username: Option<String>,
- pub token: Option<String>
+ pub token: Option<String>,
}
#[derive(Deserialize, Clone)]
@@ -87,7 +87,8 @@ pub struct Job {
impl<'de> Deserialize<'de> for Job {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
- where D: Deserializer<'de>
+ where
+ D: Deserializer<'de>,
{
struct JobVisitor;
@@ -99,7 +100,8 @@ impl<'de> Deserialize<'de> for Job {
}
fn visit_map<A>(self, mut map: A) -> Result<Job, A::Error>
- where A: MapAccess<'de>
+ where
+ A: MapAccess<'de>,
{
let mut job = None;
let mut title = None;
@@ -180,7 +182,7 @@ pub struct Config {
pub git: Git,
pub patchwork: Patchwork,
pub jenkins: Jenkins,
- pub projects: BTreeMap<String, Project>
+ pub projects: BTreeMap<String, Project>,
}
pub fn parse(path: &str) -> Config {
@@ -188,7 +190,7 @@ pub fn parse(path: &str) -> Config {
let mut file = match File::open(&path) {
Ok(file) => file,
- Err(_) => panic!("Couldn't open config file, exiting.")
+ Err(_) => panic!("Couldn't open config file, exiting."),
};
file.read_to_string(&mut toml_config)
diff --git a/src/utils.rs b/src/utils.rs
index aca373a..10ffd95 100644
--- a/src/utils.rs
+++ b/src/utils.rs
@@ -14,9 +14,18 @@
//
pub fn sanitise_path(path: String) -> String {
- path.replace("/", "_").replace("\\", "_").replace(".", "_")
- .replace("~", "_").replace(" ", "_").replace(":", "")
- .replace("[", "_").replace("]", "_").replace("'", "")
- .replace("\"", "").replace("(", "_").replace(")", "_")
- .replace("*", "_").replace("?", "_")
+ path.replace("/", "_")
+ .replace("\\", "_")
+ .replace(".", "_")
+ .replace("~", "_")
+ .replace(" ", "_")
+ .replace(":", "")
+ .replace("[", "_")
+ .replace("]", "_")
+ .replace("'", "")
+ .replace("\"", "")
+ .replace("(", "_")
+ .replace(")", "_")
+ .replace("*", "_")
+ .replace("?", "_")
}
--
2.17.1
More information about the snowpatch
mailing list