Skip to content

Commit

Permalink
aw-server: Clippy fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
johan-bjareholt committed Mar 29, 2020
1 parent 718ebfd commit 4ceb9c2
Show file tree
Hide file tree
Showing 12 changed files with 71 additions and 83 deletions.
16 changes: 9 additions & 7 deletions aw-server/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,13 @@ impl Default for AWConfig {

impl AWConfig {
pub fn to_rocket_config(&self) -> rocket::Config {
let env = match self.testing {
true => Environment::Production,
false => Environment::Development,
let env = if self.testing {
Environment::Production
} else {
Environment::Development
};
// Needed for bucket imports
let limits = Limits::new().limit("json", 1 * 1000 * 1000 * 1000);
let limits = Limits::new().limit("json", 1_000_000_000);

Config::build(env)
.address(self.address.clone())
Expand All @@ -70,9 +71,10 @@ fn default_testing() -> bool {
}

fn default_port() -> u16 {
match is_testing() {
false => 5600,
true => 5666,
if is_testing() {
5666
} else {
5600
}
}

Expand Down
3 changes: 0 additions & 3 deletions aw-server/src/dirs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@ use std::path::PathBuf;
#[cfg(not(target_os = "android"))]
use std::fs;

#[cfg(not(target_os = "android"))]
use appdirs;

#[cfg(target_os = "android")]
use std::sync::Mutex;

Expand Down
15 changes: 6 additions & 9 deletions aw-server/src/endpoints/bucket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,10 @@ pub fn buckets_get(state: State<ServerState>) -> Result<Json<HashMap<String, Buc
let datastore = endpoints_get_lock!(state.datastore);
match datastore.get_buckets() {
Ok(bucketlist) => Ok(Json(bucketlist)),
Err(e) => match e {
_ => {
warn!("Unexpected error: {:?}", e);
Err(Status::InternalServerError)
}
},
Err(e) => {
warn!("Unexpected error: {:?}", e);
Err(Status::InternalServerError)
}
}
}

Expand Down Expand Up @@ -236,14 +234,13 @@ pub fn bucket_export(bucket_id: String, state: State<ServerState>) -> Result<Res
let filename = format!("aw-bucket-export_{}.json", bucket_id);

let header_content = format!("attachment; filename={}", filename);
let response = Response::build()
Ok(Response::build()
.status(Status::Ok)
.header(Header::new("Content-Disposition", header_content))
.sized_body(Cursor::new(
serde_json::to_string(&export).expect("Failed to serialize"),
))
.finalize();
return Ok(response);
.finalize())
}

#[delete("/<bucket_id>")]
Expand Down
5 changes: 2 additions & 3 deletions aw-server/src/endpoints/cors.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use rocket::http::Method;
use rocket_cors;
use rocket_cors::{AllowedHeaders, AllowedOrigins};

use crate::config::AWConfig;

pub fn cors(config: &AWConfig) -> rocket_cors::Cors {
let root_url = format!("http://127.0.0.1:{}", config.port).to_string();
let root_url_localhost = format!("http://localhost:{}", config.port).to_string();
let root_url = format!("http://127.0.0.1:{}", config.port);
let root_url_localhost = format!("http://localhost:{}", config.port);
let mut allowed_exact_origins = vec![root_url, root_url_localhost];
allowed_exact_origins.extend(config.cors.clone());

Expand Down
5 changes: 2 additions & 3 deletions aw-server/src/endpoints/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub fn buckets_export(state: State<ServerState>) -> Result<Response, Status> {
export.buckets.insert(bid, bucket);
}

let response = Response::build()
Ok(Response::build()
.status(Status::Ok)
.header(Header::new(
"Content-Disposition",
Expand All @@ -35,6 +35,5 @@ pub fn buckets_export(state: State<ServerState>) -> Result<Response, Status> {
.sized_body(Cursor::new(
serde_json::to_string(&export).expect("Failed to serialize"),
))
.finalize();
return Ok(response);
.finalize())
}
2 changes: 1 addition & 1 deletion aw-server/src/endpoints/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ pub fn bucket_import_form(
.find(|&(k, _)| k == "boundary")
.ok_or_else(|| {
warn!("`Content-Type: multipart/form-data` boundary param not provided");
return Status::BadRequest;
Status::BadRequest
})?;

let string = process_multipart_packets(boundary, data);
Expand Down
2 changes: 1 addition & 1 deletion aw-server/src/endpoints/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::path::PathBuf;
use std::sync::Mutex;

use gethostname::gethostname;
use rocket;
use rocket::response::NamedFile;
use rocket::State;
use rocket_contrib::json::JsonValue;
Expand Down Expand Up @@ -88,6 +87,7 @@ fn get_device_id() -> String {

#[get("/")]
fn server_info(config: State<AWConfig>) -> JsonValue {
#[allow(clippy::or_fun_call)]
let hostname = gethostname().into_string().unwrap_or("unknown".to_string());
const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");

Expand Down
1 change: 0 additions & 1 deletion aw-server/src/endpoints/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use rocket_contrib::json::{Json, JsonValue};
use aw_models::Query;

use crate::endpoints::ServerState;
use aw_query;
use aw_query::QueryError;

#[derive(Serialize)]
Expand Down
20 changes: 12 additions & 8 deletions aw-server/src/endpoints/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use aw_models::{Key, KeyValue};
fn parse_key(key: String) -> Result<String, Status> {
let namespace: String = "settings.".to_string();
if key.len() >= 128 {
return Err(Status::BadRequest);
Err(Status::BadRequest)
} else {
Ok(namespace + key.as_str())
}
Expand All @@ -24,13 +24,14 @@ pub fn setting_set(state: State<ServerState>, message: Json<KeyValue>) -> Result

let datastore: MutexGuard<'_, Datastore> = endpoints_get_lock!(state.datastore);
let result = datastore.insert_key_value(&setting_key, &data.value);
return match result {

match result {
Ok(_) => Ok(Status::Created),
Err(err) => {
warn!("Unexpected error when creating setting: {:?}", err);
Err(Status::InternalServerError)
}
};
}
}

#[get("/")]
Expand All @@ -49,22 +50,24 @@ pub fn settings_list_get(state: State<ServerState>) -> Result<Json<Vec<Key>>, St
for i in queryresults? {
output.push(Key { key: i });
}
return Ok(Json(output));

Ok(Json(output))
}

#[get("/<key>")]
pub fn setting_get(state: State<ServerState>, key: String) -> Result<Json<KeyValue>, Status> {
let setting_key = parse_key(key)?;

let datastore = endpoints_get_lock!(state.datastore);
return match datastore.get_key_value(&setting_key) {

match datastore.get_key_value(&setting_key) {
Ok(result) => Ok(Json(result)),
Err(DatastoreError::NoSuchKey) => Err(Status::NotFound),
Err(err) => {
warn!("Unexpected error when getting setting: {:?}", err);
Err(Status::InternalServerError)
}
};
}
}

#[delete("/<key>")]
Expand All @@ -73,11 +76,12 @@ pub fn setting_delete(state: State<ServerState>, key: String) -> Result<(), Stat

let datastore = endpoints_get_lock!(state.datastore);
let result = datastore.delete_key_value(&setting_key);
return match result {

match result {
Ok(_) => Ok(()),
Err(err) => {
warn!("Unexpected error when deleting setting: {:?}", err);
Err(Status::InternalServerError)
}
};
}
}
1 change: 1 addition & 0 deletions aw-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ extern crate serde_derive;

extern crate chrono;

#[cfg(not(target_os = "android"))]
extern crate appdirs;

#[cfg(target_os = "android")]
Expand Down
5 changes: 1 addition & 4 deletions aw-server/src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,7 @@ pub fn setup_logger(testing: bool) -> Result<(), fern::InitError> {
))
})
// Color and higher log levels to stdout
.chain(
fern::Dispatch::new()
.chain(std::io::stdout()),
)
.chain(fern::Dispatch::new().chain(std::io::stdout()))
// No color and lower log levels to logfile
.chain(
fern::Dispatch::new()
Expand Down
79 changes: 36 additions & 43 deletions aw-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ fn main() {
return;
}

let env = Environment::active().expect("Failed to get current environment");
let mut testing = match env {
Environment::Production => false,
Environment::Development => true,
Environment::Staging => panic!("Staging environment not supported"),
};
let mut testing = matches.opt_present("testing");
// Always override environment if --testing is specified
if matches.opt_present("testing") {
testing = true;
if !testing {
let env = Environment::active().expect("Failed to get current environment");
testing = match env {
Environment::Production => false,
Environment::Development => true,
Environment::Staging => panic!("Staging environment not supported"),
};
}

logging::setup_logger(testing).expect("Failed to setup logging");
Expand All @@ -56,7 +56,7 @@ fn main() {
// Even if legacy_import is set to true it is disabled on Android so
// it will not happen there
datastore: Mutex::new(aw_datastore::Datastore::new(db_path, true)),
asset_path: asset_path,
asset_path,
};

endpoints::build_rocket(server_state, config).launch();
Expand All @@ -73,30 +73,29 @@ use std::path::PathBuf;
// don't want this change?
fn site_data_dir(app: Option<&str>, _: Option<&str>) -> Result<PathBuf, ()> {
// Iterate over all XDG_DATA_DIRS and return first match that exists
match env::var_os("XDG_DATA_DIRS") {
Some(joined) => {
for mut data_dir in env::split_paths(&joined) {
if app.is_some() {
data_dir.push(app.unwrap());
}
if !data_dir.is_dir() {
continue;
}
return Ok(data_dir);
if let Some(joined) = env::var_os("XDG_DATA_DIRS") {
for mut data_dir in env::split_paths(&joined) {
if let Some(app) = app {
data_dir.push(app);
}
if !data_dir.is_dir() {
continue;
}
return Ok(data_dir);
}
None => {}
};
}
// If no dirs exists in XDG_DATA_DIRS, fallback to /usr/local/share
let default = "/usr/local/share";
let mut data_dir = PathBuf::new();
data_dir.push(default);
if app.is_some() {
data_dir.push(app.unwrap());
if let Some(app) = app {
data_dir.push(app);
}
match data_dir.is_dir() {
true => Ok(data_dir),
false => Err(()),

if data_dir.is_dir() {
Ok(data_dir)
} else {
Err(())
}
}

Expand All @@ -120,29 +119,23 @@ fn get_asset_path() -> PathBuf {

// current_exe_path
// (for self-contained deployed binaries)
match current_exe() {
Ok(mut current_exe_path) => {
current_exe_path.pop(); // remove name of executable
current_exe_path.push("./static/");
if current_exe_path.as_path().exists() {
return current_exe_path;
}
if let Ok(mut current_exe_path) = current_exe() {
current_exe_path.pop(); // remove name of executable
current_exe_path.push("./static/");
if current_exe_path.as_path().exists() {
return current_exe_path;
}
Err(_) => (),
};
}

// usr_path
// (for linux usr installs)
match site_data_dir(Some("aw-server"), None) {
Ok(mut usr_path) => {
usr_path.push("static");
if usr_path.as_path().exists() {
return usr_path;
}
if let Ok(mut usr_path) = site_data_dir(Some("aw-server"), None) {
usr_path.push("static");
if usr_path.as_path().exists() {
return usr_path;
}
Err(_) => {}
}

warn!("Unable to find an aw-webui asset path which exists, falling back to ./aw-webui/dist");
return cargo_dev_path;
cargo_dev_path
}

0 comments on commit 4ceb9c2

Please sign in to comment.