Skip to content

Commit

Permalink
Update Rust fmt config
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaspustina committed Feb 8, 2020
1 parent ebabee4 commit 049259d
Show file tree
Hide file tree
Showing 15 changed files with 229 additions and 310 deletions.
54 changes: 52 additions & 2 deletions .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,56 @@
comment_width = 100
# stable options
edition = "2018"
merge_imports = true
fn_args_layout = "Tall"
force_explicit_abi = true
format_code_in_doc_comments = true
hard_tabs = false
max_width = 120
merge_derives = false
newline_style = "Auto"
remove_nested_parens = true
reorder_imports = true
reorder_modules = true
tab_spaces = 4
use_field_init_shorthand = true
use_small_heuristics = "Default"
use_try_shorthand = true

# unstable options
binop_separator = "Front"
blank_lines_lower_bound = 0
blank_lines_upper_bound = 1
brace_style = "SameLineWhere"
combine_control_expr = false
comment_width = 100
condense_wildcard_suffixes = true
control_brace_style = "AlwaysSameLine"
empty_item_single_line = true
enum_discrim_align_threshold = 50
fn_single_line = true
force_multiline_blocks = true
format_macro_bodies = true
format_macro_matchers = true
format_strings = true
imports_indent = "Block"
imports_layout = "HorizontalVertical"
indent_style = "Block"
match_arm_blocks = true
match_block_trailing_comma = false
merge_imports = true
normalize_comments = true
normalize_doc_attributes = true
overflow_delimited_expr = false
reorder_impl_items = true
report_fixme = "Never"
report_todo = "Never"
space_after_colon = true
space_before_colon = false
spaces_around_ranges = false
struct_field_align_threshold = 20
struct_lit_single_line = true
trailing_comma = "Vertical"
trailing_semicolon = true
type_punctuation_density = "Wide"
where_single_line = false
wrap_comments = true

4 changes: 1 addition & 3 deletions examples/collections.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use centerdevice::{
client::collections::CollectionsQuery, CenterDevice, Client, ClientCredentials, Token,
};
use centerdevice::{client::collections::CollectionsQuery, CenterDevice, Client, ClientCredentials, Token};

use std::env;

Expand Down
16 changes: 6 additions & 10 deletions examples/download_with_progress.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use centerdevice::{
client::download::Download, CenterDevice, Client, ClientCredentials, Token, WithProgress,
};
use centerdevice::{client::download::Download, CenterDevice, Client, ClientCredentials, Token, WithProgress};

use std::{
env,
Expand All @@ -9,25 +7,23 @@ use std::{
};

pub struct Progress {
amount: usize,
interval: usize,
amount: usize,
interval: usize,
interval_counter: usize,
}

impl Progress {
fn new() -> Self {
Progress {
amount: 0,
interval: 0,
amount: 0,
interval: 0,
interval_counter: 0,
}
}
}

impl WithProgress for Progress {
fn setup(&mut self, size: usize) {
self.interval = size / 10;
}
fn setup(&mut self, size: usize) { self.interval = size / 10; }

fn progress(&mut self, amount: usize) {
self.amount += amount;
Expand Down
8 changes: 6 additions & 2 deletions examples/get_tokens.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use centerdevice::{
client::auth::{Code, CodeProvider},
errors::Result,
Client, ClientCredentials,
Client,
ClientCredentials,
};

use reqwest::IntoUrl;
Expand All @@ -16,7 +17,10 @@ impl CodeProvider for MyCodeProvider {
fn get_code<T: IntoUrl>(&self, auth_url: T) -> Result<Code> {
let auth_url = auth_url.into_url().expect("Failed to parse auth url");

println!("Please authenticate at the following URL, wait for the redirect, enter the code into the terminal, and then press return ...");
println!(
"Please authenticate at the following URL, wait for the redirect, enter the code into the terminal, and \
then press return ..."
);
println!("\n\t{}\n", auth_url);
print!("Authentication code: ");
let _ = std::io::stdout().flush();
Expand Down
80 changes: 28 additions & 52 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,18 @@ use crate::{
users::{UsersQuery, UsersResult},
},
errors::{Error, ErrorKind, Result},
CenterDevice, ClientCredentials, WithProgress,
CenterDevice,
ClientCredentials,
WithProgress,
};

use failure::Fail;
use reqwest::{self, IntoUrl, Response, StatusCode};

pub struct UnauthorizedClient<'a> {
pub(crate) base_url: &'a str,
pub(crate) base_url: &'a str,
pub(crate) client_credentials: ClientCredentials<'a>,
pub(crate) http_client: reqwest::Client,
pub(crate) http_client: reqwest::Client,
}

impl<'a, 'b: 'a> UnauthorizedClient<'b> {
Expand All @@ -35,18 +37,13 @@ impl<'a, 'b: 'a> UnauthorizedClient<'b> {
redirect_uri: T,
code_provider: &S,
) -> Result<AuthorizedClient<'a>> {
let redirect_url = redirect_uri.clone().into_url().map_err(|e| {
e.context(ErrorKind::FailedToPrepareHttpRequest(
redirect_uri.to_string(),
))
})?;
let redirect_url = redirect_uri
.clone()
.into_url()
.map_err(|e| e.context(ErrorKind::FailedToPrepareHttpRequest(redirect_uri.to_string())))?;

let token = auth::authorization_code_flow(
&self.client_credentials,
self.base_url,
&redirect_url,
code_provider,
)?;
let token =
auth::authorization_code_flow(&self.client_credentials, self.base_url, &redirect_url, code_provider)?;

let authorized_client = AuthorizedClient {
base_url: self.base_url,
Expand All @@ -60,50 +57,32 @@ impl<'a, 'b: 'a> UnauthorizedClient<'b> {
}

pub struct AuthorizedClient<'a> {
pub(crate) base_url: &'a str,
pub(crate) base_url: &'a str,
pub(crate) client_credentials: ClientCredentials<'a>,
pub(crate) token: Token,
pub(crate) http_client: reqwest::Client,
pub(crate) token: Token,
pub(crate) http_client: reqwest::Client,
}

impl<'a> AuthorizedClient<'a> {
pub fn token(&self) -> &Token {
&self.token
}
pub fn token(&self) -> &Token { &self.token }
}

impl<'a> CenterDevice for AuthorizedClient<'a> {
fn refresh_access_token(&self) -> Result<Token> {
auth::refresh_access_token(self)
}
fn refresh_access_token(&self) -> Result<Token> { auth::refresh_access_token(self) }

fn search_documents(&self, search: Search) -> Result<SearchResult> {
search::search_documents(self, search)
}
fn search_documents(&self, search: Search) -> Result<SearchResult> { search::search_documents(self, search) }

fn upload_file(&self, upload: Upload) -> Result<ID> {
upload::upload_file(&self, upload)
}
fn upload_file(&self, upload: Upload) -> Result<ID> { upload::upload_file(&self, upload) }

fn download_file(&self, download: Download) -> Result<u64> {
download::download_file(self, download)
}
fn download_file(&self, download: Download) -> Result<u64> { download::download_file(self, download) }

fn download_file_with_progress<T: WithProgress>(
&self,
download: Download,
progress: &mut T,
) -> Result<u64> {
fn download_file_with_progress<T: WithProgress>(&self, download: Download, progress: &mut T) -> Result<u64> {
download::download_file_with_progress(self, download, progress)
}

fn delete_documents(&self, document_ids: &[&str]) -> Result<()> {
delete::delete_documents(self, document_ids)
}
fn delete_documents(&self, document_ids: &[&str]) -> Result<()> { delete::delete_documents(self, document_ids) }

fn search_users(&self, users_query: UsersQuery) -> Result<UsersResult> {
users::search_users(self, users_query)
}
fn search_users(&self, users_query: UsersQuery) -> Result<UsersResult> { users::search_users(self, users_query) }

fn search_collections(&self, collections_query: CollectionsQuery) -> Result<CollectionsResult> {
collections::search_collections(self, collections_query)
Expand All @@ -124,12 +103,8 @@ impl GeneralErrHandler for Response {
fn general_err_handler(mut self, expected_states: &[StatusCode]) -> Result<Self> {
match self.status() {
code if expected_states.contains(&code) => Ok(self),
code @ StatusCode::UNAUTHORIZED => {
Err(Error::from(ErrorKind::ApiCallFailedInvalidToken(code)))
}
code @ StatusCode::TOO_MANY_REQUESTS => {
Err(Error::from(ErrorKind::ApiCallFailedTooManyRequests(code)))
}
code @ StatusCode::UNAUTHORIZED => Err(Error::from(ErrorKind::ApiCallFailedInvalidToken(code))),
code @ StatusCode::TOO_MANY_REQUESTS => Err(Error::from(ErrorKind::ApiCallFailedTooManyRequests(code))),
_ => Err(handle_error(&mut self)),
}
}
Expand All @@ -140,11 +115,12 @@ fn handle_error(response: &mut Response) -> Error {

match response.text() {
Ok(body) => Error::from(ErrorKind::ApiCallFailed(status_code, body)),
Err(e) => e
.context(ErrorKind::FailedToProcessHttpResponse(
Err(e) => {
e.context(ErrorKind::FailedToProcessHttpResponse(
status_code,
"reading body".to_string(),
))
.into(),
.into()
}
}
}
38 changes: 11 additions & 27 deletions src/client/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ pub use reqwest::IntoUrl;

#[derive(Debug, Clone, Deserialize)]
pub struct Token {
pub(crate) token_type: Option<String>,
pub(crate) access_token: String,
pub(crate) expires_in: Option<u32>,
pub(crate) token_type: Option<String>,
pub(crate) access_token: String,
pub(crate) expires_in: Option<u32>,
pub(crate) refresh_token: String,
}

Expand All @@ -30,21 +30,13 @@ impl Token {
}
}

pub fn token_type(&self) -> Option<&str> {
self.token_type.as_ref().map(String::as_ref)
}
pub fn token_type(&self) -> Option<&str> { self.token_type.as_ref().map(String::as_ref) }

pub fn access_token(&self) -> &str {
&self.access_token
}
pub fn access_token(&self) -> &str { &self.access_token }

pub fn expires_in(&self) -> Option<u32> {
self.expires_in
}
pub fn expires_in(&self) -> Option<u32> { self.expires_in }

pub fn refresh_token(&self) -> &str {
self.refresh_token.as_ref()
}
pub fn refresh_token(&self) -> &str { self.refresh_token.as_ref() }
}

pub trait CodeProvider {
Expand All @@ -57,9 +49,7 @@ pub struct Code {
}

impl Code {
pub fn new(code: String) -> Code {
Code { code }
}
pub fn new(code: String) -> Code { Code { code } }
}

pub fn authorization_code_flow<T: CodeProvider>(
Expand All @@ -86,11 +76,8 @@ fn get_code<T: CodeProvider>(
("redirect_uri", redirect_uri.as_str()),
("response_type", "code"),
];
let auth_url = Url::parse_with_params(&auth_endpoint, &params).map_err(|e| {
e.context(ErrorKind::FailedToPrepareHttpRequest(
redirect_uri.to_string(),
))
})?;
let auth_url = Url::parse_with_params(&auth_endpoint, &params)
.map_err(|e| e.context(ErrorKind::FailedToPrepareHttpRequest(redirect_uri.to_string())))?;

code_provider.get_code(auth_url)
}
Expand All @@ -112,10 +99,7 @@ pub fn exchange_code_for_token(

let request = http_client
.post(&token_endpoint)
.basic_auth(
&client_credentials.client_id,
Some(&client_credentials.client_secret),
)
.basic_auth(&client_credentials.client_id, Some(&client_credentials.client_secret))
.form(&params);
debug!("Request: '{:#?}'", request);

Expand Down
Loading

0 comments on commit 049259d

Please sign in to comment.