Clean up code using Rustfmt

This commit is contained in:
James 2018-01-27 22:58:56 +11:00
parent cf41f552c4
commit 4ed50c885b
5 changed files with 58 additions and 62 deletions

View File

@ -12,14 +12,14 @@ include!(concat!(env!("OUT_DIR"), "/data.rs"));
/// Returns a static file based upon a given String as a Path. /// Returns a static file based upon a given String as a Path.
/// ///
/// file_path: String path, beginning with a / /// file_path: String path, beginning with a /
pub fn file_from_string(file_path : &str) -> Option<(ContentType, Cow<'static, [u8]>)> { pub fn file_from_string(file_path: &str) -> Option<(ContentType, Cow<'static, [u8]>)> {
let guessed_mime = match file_path.rfind(".") { let guessed_mime = match file_path.rfind(".") {
Some(ext_ptr) => { Some(ext_ptr) => {
let ext = &file_path[ext_ptr + 1 ..]; let ext = &file_path[ext_ptr + 1..];
get_mime_type(ext) get_mime_type(ext)
}, }
None => octet_stream() None => octet_stream(),
}; };
let string_mime = guessed_mime.to_string(); let string_mime = guessed_mime.to_string();
@ -30,6 +30,6 @@ pub fn file_from_string(file_path : &str) -> Option<(ContentType, Cow<'static, [
match FILES.get(&format!("static{}", file_path)) { match FILES.get(&format!("static{}", file_path)) {
Ok(val) => Some((content_type, val)), Ok(val) => Some((content_type, val)),
// Only error is a not found one // Only error is a not found one
Err(_) => None Err(_) => None,
} }
} }

View File

@ -10,22 +10,22 @@ use serde_json::{self, Error as SerdeError};
/// Describes a overview of a individual package. /// Describes a overview of a individual package.
#[derive(Deserialize, Serialize, Clone)] #[derive(Deserialize, Serialize, Clone)]
pub struct PackageDescription { pub struct PackageDescription {
pub name : String, pub name: String,
pub description : String, pub description: String,
pub default : Option<bool> pub default: Option<bool>,
} }
/// Describes the application itself. /// Describes the application itself.
#[derive(Deserialize, Serialize, Clone)] #[derive(Deserialize, Serialize, Clone)]
pub struct GeneralConfig { pub struct GeneralConfig {
pub name : String, pub name: String,
pub installing_message : String pub installing_message: String,
} }
#[derive(Deserialize, Serialize, Clone)] #[derive(Deserialize, Serialize, Clone)]
pub struct Config { pub struct Config {
pub general : GeneralConfig, pub general: GeneralConfig,
pub packages : Vec<PackageDescription> pub packages: Vec<PackageDescription>,
} }
impl Config { impl Config {
@ -35,7 +35,7 @@ impl Config {
} }
/// Builds a configuration from a specified TOML string. /// Builds a configuration from a specified TOML string.
pub fn from_toml_str(contents : &str) -> Result<Self, TomlError> { pub fn from_toml_str(contents: &str) -> Result<Self, TomlError> {
toml::from_str(contents) toml::from_str(contents)
} }
} }

View File

@ -12,7 +12,7 @@ use config::Config;
/// The installer framework contains metadata about packages, what is installable, what isn't, /// The installer framework contains metadata about packages, what is installable, what isn't,
/// etc. /// etc.
pub struct InstallerFramework { pub struct InstallerFramework {
config : Config config: Config,
} }
impl InstallerFramework { impl InstallerFramework {
@ -27,7 +27,7 @@ impl InstallerFramework {
let base_dir = match var("LOCALAPPDATA") { let base_dir = match var("LOCALAPPDATA") {
Ok(path) => PathBuf::from(path), Ok(path) => PathBuf::from(path),
Err(_) => home_dir()? Err(_) => home_dir()?,
}; };
println!("{:?}", base_dir); println!("{:?}", base_dir);
@ -39,9 +39,7 @@ impl InstallerFramework {
} }
/// Creates a new instance of the Installer Framework with a specified Config. /// Creates a new instance of the Installer Framework with a specified Config.
pub fn new(config : Config) -> Self { pub fn new(config: Config) -> Self {
InstallerFramework { InstallerFramework { config }
config
}
} }
} }

View File

@ -2,11 +2,11 @@
extern crate web_view; extern crate web_view;
extern crate futures;
extern crate hyper; extern crate hyper;
extern crate hyper_tls; extern crate hyper_tls;
extern crate tokio_core;
extern crate futures;
extern crate mime_guess; extern crate mime_guess;
extern crate tokio_core;
extern crate includedir; extern crate includedir;
extern crate phf; extern crate phf;
@ -33,7 +33,7 @@ use installer::InstallerFramework;
use rest::WebServer; use rest::WebServer;
// TODO: Fetch this over a HTTP request? // TODO: Fetch this over a HTTP request?
static RAW_CONFIG : &'static str = include_str!("../config.toml"); static RAW_CONFIG: &'static str = include_str!("../config.toml");
fn main() { fn main() {
let config = Config::from_toml_str(RAW_CONFIG).unwrap(); let config = Config::from_toml_str(RAW_CONFIG).unwrap();
@ -63,6 +63,6 @@ fn main() {
debug, debug,
init_cb, init_cb,
/* frontend_cb: */ |_, _, _| {}, /* frontend_cb: */ |_, _, _| {},
userdata userdata,
); );
} }

View File

@ -12,11 +12,11 @@ use futures::future;
use futures::future::FutureResult; use futures::future::FutureResult;
use hyper; use hyper;
use hyper::{Get, StatusCode, Error as HyperError}; use hyper::{Error as HyperError, Get, StatusCode};
use hyper::header::{ContentLength, ContentType}; use hyper::header::{ContentLength, ContentType};
use hyper::server::{Http, Service, Request, Response}; use hyper::server::{Http, Request, Response, Service};
use std::net::{SocketAddr, IpAddr, Ipv4Addr}; use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::thread::{self, JoinHandle}; use std::thread::{self, JoinHandle};
use std::process::exit; use std::process::exit;
use std::sync::Arc; use std::sync::Arc;
@ -28,13 +28,13 @@ use installer::InstallerFramework;
#[derive(Serialize)] #[derive(Serialize)]
struct FileSelection { struct FileSelection {
path : Option<String> path: Option<String>,
} }
/// Encapsulates Hyper's state. /// Encapsulates Hyper's state.
pub struct WebServer { pub struct WebServer {
handle : JoinHandle<()>, _handle: JoinHandle<()>,
addr : SocketAddr addr: SocketAddr,
} }
impl WebServer { impl WebServer {
@ -44,25 +44,27 @@ impl WebServer {
} }
/// Creates a new web server, bound to a random port on localhost. /// Creates a new web server, bound to a random port on localhost.
pub fn new(framework : InstallerFramework) -> Result<Self, HyperError> { pub fn new(framework: InstallerFramework) -> Result<Self, HyperError> {
WebServer::with_addr(framework, SocketAddr::new( WebServer::with_addr(
IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0)) framework,
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0),
)
} }
/// Creates a new web server with the specified address. /// Creates a new web server with the specified address.
pub fn with_addr(framework : InstallerFramework, addr : SocketAddr) pub fn with_addr(framework: InstallerFramework, addr: SocketAddr) -> Result<Self, HyperError> {
-> Result<Self, HyperError> {
let (sender, receiver) = channel(); let (sender, receiver) = channel();
let handle = thread::spawn(move || { let handle = thread::spawn(move || {
let shared_framework = Arc::new(framework); let shared_framework = Arc::new(framework);
let server = let server = Http::new()
Http::new().bind(&addr, move || .bind(&addr, move || {
Ok(WebService { Ok(WebService {
framework : shared_framework.clone() framework: shared_framework.clone(),
}) })
).unwrap(); })
.unwrap();
sender.send(server.local_addr().unwrap()).unwrap(); sender.send(server.local_addr().unwrap()).unwrap();
@ -72,44 +74,45 @@ impl WebServer {
let addr = receiver.recv().unwrap(); let addr = receiver.recv().unwrap();
Ok(WebServer { Ok(WebServer {
handle, addr _handle: handle,
addr,
}) })
} }
} }
struct WebService { struct WebService {
framework : Arc<InstallerFramework> framework: Arc<InstallerFramework>,
} }
impl Service for WebService { impl Service for WebService {
type Request = Request; type Request = Request;
type Response = Response; type Response = Response;
type Error = hyper::Error; type Error = hyper::Error;
type Future = FutureResult<Self::Response, Self::Error>; type Future = FutureResult<Self::Response, Self::Error>;
fn call(&self, req: Self::Request) -> Self::Future { fn call(&self, req: Self::Request) -> Self::Future {
future::ok(match (req.method(), req.path()) { future::ok(match (req.method(), req.path()) {
// This endpoint should be usable directly from a <script> tag during loading. // This endpoint should be usable directly from a <script> tag during loading.
// TODO: Handle errors // TODO: Handle errors
(&Get, "/api/config") => { (&Get, "/api/config") => {
let file = enscapsulate_json("config", let file = enscapsulate_json(
&self.framework.get_config().to_json_str().unwrap()); "config",
&self.framework.get_config().to_json_str().unwrap(),
);
Response::<hyper::Body>::new() Response::<hyper::Body>::new()
.with_header(ContentLength(file.len() as u64)) .with_header(ContentLength(file.len() as u64))
.with_header(ContentType::json()) .with_header(ContentType::json())
.with_body(file) .with_body(file)
}, }
(&Get, "/api/file-select") => { (&Get, "/api/file-select") => {
let file_dialog = nfd::open_pick_folder(None).unwrap(); let file_dialog = nfd::open_pick_folder(None).unwrap();
let file = match file_dialog { let file = match file_dialog {
NfdResponse::Okay(path) => Some(path), NfdResponse::Okay(path) => Some(path),
_ => None _ => None,
}; };
let response = FileSelection { let response = FileSelection { path: file };
path : file
};
let file = serde_json::to_string(&response).unwrap(); let file = serde_json::to_string(&response).unwrap();
@ -117,13 +120,11 @@ impl Service for WebService {
.with_header(ContentLength(file.len() as u64)) .with_header(ContentLength(file.len() as u64))
.with_header(ContentType::json()) .with_header(ContentType::json())
.with_body(file) .with_body(file)
}, }
(&Get, "/api/default-path") => { (&Get, "/api/default-path") => {
let path = self.framework.get_default_path(); let path = self.framework.get_default_path();
let response = FileSelection { let response = FileSelection { path };
path
};
let file = serde_json::to_string(&response).unwrap(); let file = serde_json::to_string(&response).unwrap();
@ -131,16 +132,16 @@ impl Service for WebService {
.with_header(ContentLength(file.len() as u64)) .with_header(ContentLength(file.len() as u64))
.with_header(ContentType::json()) .with_header(ContentType::json())
.with_body(file) .with_body(file)
}, }
(&Get, "/api/exit") => { (&Get, "/api/exit") => {
exit(0); exit(0);
}, }
// Static file handler // Static file handler
(&Get, _) => { (&Get, _) => {
// At this point, we have a web browser client. Search for a index page // At this point, we have a web browser client. Search for a index page
// if needed // if needed
let mut path : String = req.path().to_owned(); let mut path: String = req.path().to_owned();
if path.ends_with("/") { if path.ends_with("/") {
path += "index.html"; path += "index.html";
} }
@ -152,19 +153,16 @@ impl Service for WebService {
.with_header(ContentLength(file.len() as u64)) .with_header(ContentLength(file.len() as u64))
.with_header(content_type) .with_header(content_type)
.with_body(file), .with_body(file),
None => Response::new() None => Response::new().with_status(StatusCode::NotFound),
.with_status(StatusCode::NotFound)
} }
},
// Fallthrough for POST/PUT/CONNECT/...
_ => {
Response::new().with_status(StatusCode::NotFound)
} }
// Fallthrough for POST/PUT/CONNECT/...
_ => Response::new().with_status(StatusCode::NotFound),
}) })
} }
} }
/// Encapsulates JSON as a injectable Javascript script. /// Encapsulates JSON as a injectable Javascript script.
fn enscapsulate_json(field_name : &str, json : &str) -> String { fn enscapsulate_json(field_name: &str, json: &str) -> String {
format!("var {} = {};", field_name, json) format!("var {} = {};", field_name, json)
} }