Browse Source

add new rustfmt.toml and reformat code

master
Ondřej Hruška 9 months ago
parent
commit
bc70389346
Signed by: MightyPork GPG Key ID: 2C5FD5035250423D
  1. 4
      rustfmt.toml
  2. 14
      src/apps.rs
  3. 10
      src/entities/account.rs
  4. 7
      src/entities/status.rs
  5. 6
      src/helpers/json.rs
  6. 6
      src/helpers/toml.rs
  7. 105
      src/lib.rs
  8. 15
      src/mastodon_client.rs
  9. 11
      src/media_builder.rs
  10. 16
      src/registration.rs
  11. 22
      src/requests/push.rs
  12. 11
      src/requests/update_credentials.rs
  13. 35
      src/scopes.rs
  14. 15
      src/status_builder.rs

4
rustfmt.toml

@ -0,0 +1,4 @@
max_width=120
newline_style="Unix"
use_field_init_shorthand=true
chain_width=80

14
src/apps.rs

@ -118,14 +118,8 @@ impl<'a> AppBuilder<'a> {
/// Will fail if no `client_name` was provided
pub fn build(self) -> Result<App> {
Ok(App {
client_name: self
.client_name
.ok_or(Error::MissingField("client_name"))?
.into(),
redirect_uris: self
.redirect_uris
.unwrap_or_else(|| "urn:ietf:wg:oauth:2.0:oob".into())
.into(),
client_name: self.client_name.ok_or(Error::MissingField("client_name"))?.into(),
redirect_uris: self.redirect_uris.unwrap_or_else(|| "urn:ietf:wg:oauth:2.0:oob".into()).into(),
scopes: self.scopes.unwrap_or_else(Scopes::read_all),
website: self.website.map(|s| s.into()),
})
@ -220,9 +214,7 @@ mod tests {
scopes: Scopes::all(),
website: None,
};
let result = builder
.try_into()
.expect("Couldn't make AppBuilder into App");
let result = builder.try_into().expect("Couldn't make AppBuilder into App");
assert_eq!(expected, result);
}
}

10
src/entities/account.rs

@ -4,8 +4,7 @@ use crate::status_builder;
use chrono::prelude::*;
use serde::{
de::{self, Unexpected},
Deserialize,
Serialize,
Deserialize, Serialize,
};
use std::path::PathBuf;
@ -99,12 +98,9 @@ fn string_or_bool<'de, D: de::Deserializer<'de>>(val: D) -> ::std::result::Resul
} else if s == "false" {
false
} else {
return Err(de::Error::invalid_value(
Unexpected::Str(s),
&"true or false",
));
return Err(de::Error::invalid_value(Unexpected::Str(s), &"true or false"));
}
},
}
})
}

7
src/entities/status.rs

@ -2,11 +2,8 @@
use super::prelude::*;
use crate::{
entities::{
card::Card,
poll::Poll,
},
status_builder::Visibility
entities::{card::Card, poll::Poll},
status_builder::Visibility,
};
use chrono::prelude::*;
use serde::{Deserialize, Serialize};

6
src/helpers/json.rs

@ -63,11 +63,7 @@ pub fn to_file<P: AsRef<Path>>(data: &Data, path: P) -> Result<()> {
}
/// Attempts to serialize a Data struct to a file
pub fn to_file_with_options<P: AsRef<Path>>(
data: &Data,
path: P,
options: OpenOptions,
) -> Result<()> {
pub fn to_file_with_options<P: AsRef<Path>>(data: &Data, path: P, options: OpenOptions) -> Result<()> {
let path = path.as_ref();
let file = options.open(path)?;
to_writer(data, file)?;

6
src/helpers/toml.rs

@ -63,11 +63,7 @@ pub fn to_file<P: AsRef<Path>>(data: &Data, path: P) -> Result<()> {
}
/// Attempts to serialize a Data struct to a file
pub fn to_file_with_options<P: AsRef<Path>>(
data: &Data,
path: P,
options: OpenOptions,
) -> Result<()> {
pub fn to_file_with_options<P: AsRef<Path>>(data: &Data, path: P, options: OpenOptions) -> Result<()> {
let path = path.as_ref();
let file = options.open(path)?;
to_writer(data, file)?;

105
src/lib.rs

@ -86,13 +86,7 @@ pub use crate::{
mastodon_client::{MastodonClient, MastodonUnauthenticated},
media_builder::MediaBuilder,
registration::Registration,
requests::{
AddFilterRequest,
AddPushRequest,
StatusesRequest,
UpdateCredsRequest,
UpdatePushRequest,
},
requests::{AddFilterRequest, AddPushRequest, StatusesRequest, UpdateCredsRequest, UpdatePushRequest},
status_builder::{NewStatus, StatusBuilder},
};
pub use isolang::Language;
@ -125,14 +119,7 @@ mod macros;
/// Automatically import the things you need
pub mod prelude {
pub use crate::{
scopes::Scopes,
Data,
Mastodon,
MastodonClient,
NewStatus,
Registration,
StatusBuilder,
StatusesRequest,
scopes::Scopes, Data, Mastodon, MastodonClient, NewStatus, Registration, StatusBuilder, StatusesRequest,
};
}
@ -162,9 +149,7 @@ impl From<Data> for Mastodon {
fn from(data: Data) -> Mastodon {
let mut builder = MastodonBuilder::new();
builder.data(data);
builder
.build()
.expect("We know `data` is present, so this should be fine")
builder.build().expect("We know `data` is present, so this should be fine")
}
}
@ -289,11 +274,7 @@ impl MastodonClient for Mastodon {
/// Post a new status to the account.
fn new_status(&self, status: NewStatus) -> Result<Status> {
let response = self.send(
self.client
.post(&self.route("/api/v1/statuses"))
.json(&status),
)?;
let response = self.send(self.client.post(&self.route("/api/v1/statuses")).json(&status))?;
deserialise(response)
}
@ -393,11 +374,7 @@ impl MastodonClient for Mastodon {
/// Add a push notifications subscription
fn add_push_subscription(&self, request: &AddPushRequest) -> Result<Subscription> {
let request = request.build()?;
let response = self.send(
self.client
.post(&self.route("/api/v1/push/subscription"))
.json(&request),
)?;
let response = self.send(self.client.post(&self.route("/api/v1/push/subscription")).json(&request))?;
deserialise(response)
}
@ -406,11 +383,7 @@ impl MastodonClient for Mastodon {
/// access token
fn update_push_data(&self, request: &UpdatePushRequest) -> Result<Subscription> {
let request = request.build();
let response = self.send(
self.client
.put(&self.route("/api/v1/push/subscription"))
.json(&request),
)?;
let response = self.send(self.client.put(&self.route("/api/v1/push/subscription")).json(&request))?;
deserialise(response)
}
@ -462,10 +435,7 @@ impl MastodonClient for Mastodon {
url.query_pairs_mut()
.append_pair("access_token", &self.token)
.append_pair("stream", "user");
let mut url: url::Url = reqwest::blocking::get(url.as_str())?
.url()
.as_str()
.parse()?;
let mut url: url::Url = reqwest::blocking::get(url.as_str())?.url().as_str().parse()?;
let new_scheme = match url.scheme() {
"http" => "ws",
"https" => "wss",
@ -485,10 +455,7 @@ impl MastodonClient for Mastodon {
url.query_pairs_mut()
.append_pair("access_token", &self.token)
.append_pair("stream", "public");
let mut url: url::Url = reqwest::blocking::get(url.as_str())?
.url()
.as_str()
.parse()?;
let mut url: url::Url = reqwest::blocking::get(url.as_str())?.url().as_str().parse()?;
let new_scheme = match url.scheme() {
"http" => "ws",
"https" => "wss",
@ -508,10 +475,7 @@ impl MastodonClient for Mastodon {
url.query_pairs_mut()
.append_pair("access_token", &self.token)
.append_pair("stream", "public:local");
let mut url: url::Url = reqwest::blocking::get(url.as_str())?
.url()
.as_str()
.parse()?;
let mut url: url::Url = reqwest::blocking::get(url.as_str())?.url().as_str().parse()?;
let new_scheme = match url.scheme() {
"http" => "ws",
"https" => "wss",
@ -532,10 +496,7 @@ impl MastodonClient for Mastodon {
.append_pair("access_token", &self.token)
.append_pair("stream", "hashtag")
.append_pair("tag", hashtag);
let mut url: url::Url = reqwest::blocking::get(url.as_str())?
.url()
.as_str()
.parse()?;
let mut url: url::Url = reqwest::blocking::get(url.as_str())?.url().as_str().parse()?;
let new_scheme = match url.scheme() {
"http" => "ws",
"https" => "wss",
@ -556,10 +517,7 @@ impl MastodonClient for Mastodon {
.append_pair("access_token", &self.token)
.append_pair("stream", "hashtag:local")
.append_pair("tag", hashtag);
let mut url: url::Url = reqwest::blocking::get(url.as_str())?
.url()
.as_str()
.parse()?;
let mut url: url::Url = reqwest::blocking::get(url.as_str())?.url().as_str().parse()?;
let new_scheme = match url.scheme() {
"http" => "ws",
"https" => "wss",
@ -580,10 +538,7 @@ impl MastodonClient for Mastodon {
.append_pair("access_token", &self.token)
.append_pair("stream", "list")
.append_pair("list", list_id);
let mut url: url::Url = reqwest::blocking::get(url.as_str())?
.url()
.as_str()
.parse()?;
let mut url: url::Url = reqwest::blocking::get(url.as_str())?.url().as_str().parse()?;
let new_scheme = match url.scheme() {
"http" => "ws",
"https" => "wss",
@ -603,10 +558,7 @@ impl MastodonClient for Mastodon {
url.query_pairs_mut()
.append_pair("access_token", &self.token)
.append_pair("stream", "direct");
let mut url: url::Url = reqwest::blocking::get(url.as_str())?
.url()
.as_str()
.parse()?;
let mut url: url::Url = reqwest::blocking::get(url.as_str())?.url().as_str().parse()?;
let new_scheme = match url.scheme() {
"http" => "ws",
"https" => "wss",
@ -689,11 +641,7 @@ impl MastodonClient for Mastodon {
form = form.text("focus", format!("{},{}", x, y));
}
let response = self.send(
self.client
.post(&self.route("/api/v1/media"))
.multipart(form),
)?;
let response = self.send(self.client.post(&self.route("/api/v1/media")).multipart(form))?;
deserialise(response)
}
@ -774,23 +722,19 @@ impl<R: EventStream> EventReader<R> {
let event: &str = &event;
Ok(match event {
"notification" => {
let data = data.ok_or_else(|| {
Error::Other("Missing `data` line for notification".to_string())
})?;
let data = data.ok_or_else(|| Error::Other("Missing `data` line for notification".to_string()))?;
let notification = serde_json::from_str::<Notification>(&data)?;
Event::Notification(notification)
},
}
"update" => {
let data =
data.ok_or_else(|| Error::Other("Missing `data` line for update".to_string()))?;
let data = data.ok_or_else(|| Error::Other("Missing `data` line for update".to_string()))?;
let status = serde_json::from_str::<Status>(&data)?;
Event::Update(status)
},
}
"delete" => {
let data =
data.ok_or_else(|| Error::Other("Missing `data` line for delete".to_string()))?;
let data = data.ok_or_else(|| Error::Other("Missing `data` line for delete".to_string()))?;
Event::Delete(data)
},
}
"filters_changed" => Event::FiltersChanged,
_ => return Err(Error::Other(format!("Unknown event `{}`", event))),
})
@ -876,10 +820,7 @@ impl MastodonUnauth {
pub fn streaming_public(&self) -> Result<EventReader<WebSocket>> {
let mut url: url::Url = self.route("/api/v1/streaming/public/local")?;
url.query_pairs_mut().append_pair("stream", "public");
let mut url: url::Url = reqwest::blocking::get(url.as_str())?
.url()
.as_str()
.parse()?;
let mut url: url::Url = reqwest::blocking::get(url.as_str())?.url().as_str().parse()?;
let new_scheme = match url.scheme() {
"http" => "ws",
"https" => "wss",
@ -931,7 +872,7 @@ fn deserialise<T: for<'de> serde::Deserialize<'de>>(response: Response) -> Resul
Ok(t) => {
log::debug!("{}", String::from_utf8_lossy(&reader.bytes));
Ok(t)
},
}
// If deserializing into the desired type fails try again to
// see if this is an error response.
Err(e) => {
@ -940,6 +881,6 @@ fn deserialise<T: for<'de> serde::Deserialize<'de>>(response: Response) -> Resul
return Err(Error::Api(error));
}
Err(e.into())
},
}
}
}

15
src/mastodon_client.rs

@ -5,13 +5,7 @@ use crate::{
errors::Result,
media_builder::MediaBuilder,
page::Page,
requests::{
AddFilterRequest,
AddPushRequest,
StatusesRequest,
UpdateCredsRequest,
UpdatePushRequest,
},
requests::{AddFilterRequest, AddPushRequest, StatusesRequest, UpdateCredsRequest, UpdatePushRequest},
status_builder::NewStatus,
};
@ -222,12 +216,7 @@ pub trait MastodonClient {
unimplemented!("This method was not implemented");
}
/// GET /api/v1/accounts/search?q=:query&limit=:limit&following=:following
fn search_accounts(
&self,
query: &str,
limit: Option<u64>,
following: bool,
) -> Result<Page<Account>> {
fn search_accounts(&self, query: &str, limit: Option<u64>, following: bool) -> Result<Page<Account>> {
unimplemented!("This method was not implemented");
}
/// POST /api/v1/push/subscription

11
src/media_builder.rs

@ -38,10 +38,7 @@ impl fmt::Debug for MediaBuilderData {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
MediaBuilderData::File(f) => fmt.debug_tuple("File").field(&f).finish(),
MediaBuilderData::Reader(_) => fmt
.debug_tuple("Reader")
.field(&format_args!("..."))
.finish(),
MediaBuilderData::Reader(_) => fmt.debug_tuple("Reader").field(&format_args!("...")).finish(),
}
}
}
@ -64,11 +61,7 @@ impl MediaBuilder {
/// not valid, [`add_media()`](trait.MastodonClient.html#method.add_media) will return an error when called with the `MediaBuilder`.
pub fn from_file(path: impl AsRef<Path>) -> MediaBuilder {
let pb = path.as_ref().to_owned();
let filename = pb
.file_name()
.expect("file name")
.to_string_lossy()
.to_string();
let filename = pb.file_name().expect("file name").to_string_lossy().to_string();
let mimetype = match pb.extension().map(|s| s.to_str()).flatten() {
Some("jpg") | Some("jpeg") => Some("image/jpeg".to_string()),
Some("png") => Some("image/png".to_string()),

16
src/registration.rs

@ -7,11 +7,7 @@ use std::convert::TryInto;
use crate::{
apps::{App, AppBuilder},
scopes::Scopes,
Data,
Error,
Mastodon,
MastodonBuilder,
Result,
Data, Error, Mastodon, MastodonBuilder, Result,
};
const DEFAULT_REDIRECT_URI: &str = "urn:ietf:wg:oauth:2.0:oob";
@ -362,10 +358,7 @@ mod tests {
r.client_name("foo-test");
assert_eq!(r.base, "https://example.com".to_string());
assert_eq!(
&mut r.app_builder,
AppBuilder::new().client_name("foo-test")
);
assert_eq!(&mut r.app_builder, AppBuilder::new().client_name("foo-test"));
}
#[test]
@ -374,10 +367,7 @@ mod tests {
r.redirect_uris("https://foo.com");
assert_eq!(r.base, "https://example.com".to_string());
assert_eq!(
&mut r.app_builder,
AppBuilder::new().redirect_uris("https://foo.com")
);
assert_eq!(&mut r.app_builder, AppBuilder::new().redirect_uris("https://foo.com"));
}
#[test]

22
src/requests/push.rs

@ -165,10 +165,7 @@ impl AddPushRequest {
}
fn flags_present(&self) -> bool {
self.follow.is_some()
|| self.favourite.is_some()
|| self.reblog.is_some()
|| self.mention.is_some()
self.follow.is_some() || self.favourite.is_some() || self.reblog.is_some() || self.mention.is_some()
}
pub(crate) fn build(&self) -> Result<add_subscription::Form> {
@ -205,9 +202,7 @@ impl AddPushRequest {
alerts.mention = Some(mention);
}
form.data = Some(Data {
alerts: Some(alerts),
});
form.data = Some(Data { alerts: Some(alerts) });
}
Ok(form)
}
@ -322,10 +317,7 @@ impl UpdatePushRequest {
}
fn flags_present(&self) -> bool {
self.follow.is_some()
|| self.favourite.is_some()
|| self.reblog.is_some()
|| self.mention.is_some()
self.follow.is_some() || self.favourite.is_some() || self.reblog.is_some() || self.mention.is_some()
}
pub(crate) fn build(&self) -> update_data::Form {
@ -353,9 +345,7 @@ impl UpdatePushRequest {
if let Some(mention) = self.mention {
alerts.mention = Some(mention);
}
form.data = Data {
alerts: Some(alerts),
};
form.data = Data { alerts: Some(alerts) };
}
form
}
@ -606,9 +596,7 @@ mod tests {
form,
update_data::Form {
id: "some-id".to_string(),
data: update_data::Data {
alerts: None
},
data: update_data::Data { alerts: None },
}
);
}

11
src/requests/update_credentials.rs

@ -212,12 +212,7 @@ mod tests {
#[test]
fn test_update_creds_request_new() {
let builder = UpdateCredsRequest::new();
assert_eq!(
builder,
UpdateCredsRequest {
..Default::default()
}
);
assert_eq!(builder, UpdateCredsRequest { ..Default::default() });
}
#[test]
@ -321,9 +316,7 @@ mod tests {
Credentials {
display_name: Some("test".into()),
note: Some("a note".into()),
source: Some(UpdateSource {
..Default::default()
}),
source: Some(UpdateSource { ..Default::default() }),
..Default::default()
}
);

35
src/scopes.rs

@ -9,9 +9,7 @@ use std::{
use crate::errors::Error;
use serde::{
de::{self, Visitor},
Deserialize,
Deserializer,
Serialize,
Deserialize, Deserializer, Serialize,
};
/// Represents a set of OAuth scopes
@ -40,9 +38,7 @@ impl FromStr for Scopes {
let scope = Scope::from_str(&scope)?;
set.insert(scope);
}
Ok(Scopes {
scopes: set,
})
Ok(Scopes { scopes: set })
}
}
@ -215,9 +211,7 @@ impl Scopes {
/// ```
pub fn and(self, other: Scopes) -> Scopes {
let newset: HashSet<_> = self.scopes.union(&other.scopes).copied().collect();
Scopes {
scopes: newset,
}
Scopes { scopes: newset }
}
fn _write(subscope: Option<Write>) -> Scopes {
@ -231,9 +225,7 @@ impl Scopes {
fn new(scope: Scope) -> Scopes {
let mut set = HashSet::new();
set.insert(scope);
Scopes {
scopes: set,
}
Scopes { scopes: set }
}
}
@ -247,10 +239,7 @@ impl BitOr for Scopes {
impl PartialEq for Scopes {
fn eq(&self, other: &Scopes) -> bool {
self.scopes
.symmetric_difference(&other.scopes)
.next()
.is_none()
self.scopes.symmetric_difference(&other.scopes).next().is_none()
}
}
@ -321,11 +310,11 @@ impl FromStr for Scope {
read if read.starts_with("read:") => {
let r: Read = Read::from_str(&read[5..])?;
Scope::Read(Some(r))
},
}
write if write.starts_with("write:") => {
let w: Write = Write::from_str(&write[6..])?;
Scope::Write(Some(w))
},
}
_ => return Err(Error::Other("Unknown scope".to_string())),
})
}
@ -740,10 +729,7 @@ mod tests {
#[test]
fn test_scopes_display() {
let tests = [
(
Scopes::read(Read::Accounts) | Scopes::follow(),
"read:accounts follow",
),
(Scopes::read(Read::Accounts) | Scopes::follow(), "read:accounts follow"),
(
Scopes::read(Read::Follows) | Scopes::read(Read::Accounts) | Scopes::write_all(),
"read:accounts read:follows write",
@ -799,10 +785,7 @@ mod tests {
("write:lists", Scope::Write(Some(Write::Lists))),
("write:media", Scope::Write(Some(Write::Media))),
("write:mutes", Scope::Write(Some(Write::Mutes))),
(
"write:notifications",
Scope::Write(Some(Write::Notifications)),
),
("write:notifications", Scope::Write(Some(Write::Notifications))),
("write:reports", Scope::Write(Some(Write::Reports))),
("write:statuses", Scope::Write(Some(Write::Statuses))),
("follow", Scope::Follow),

15
src/status_builder.rs

@ -106,10 +106,7 @@ impl StatusBuilder {
/// # Ok(())
/// # }
/// ```
pub fn media_ids<S: std::fmt::Display, I: IntoIterator<Item = S>>(
&mut self,
ids: I,
) -> &mut Self {
pub fn media_ids<S: std::fmt::Display, I: IntoIterator<Item = S>>(&mut self, ids: I) -> &mut Self {
self.media_ids = Some(ids.into_iter().map(|s| s.to_string()).collect::<Vec<_>>());
self
}
@ -300,10 +297,7 @@ mod tests {
#[test]
fn test_new() {
let s = StatusBuilder::new()
.status("a status")
.build()
.expect("Couldn't build status");
let s = StatusBuilder::new().status("a status").build().expect("Couldn't build status");
let expected = NewStatus {
status: Some("a status".to_string()),
in_reply_to_id: None,
@ -345,10 +339,7 @@ mod tests {
#[test]
fn test_serialize_status() {
let status = StatusBuilder::new()
.status("a status")
.build()
.expect("Couldn't build status");
let status = StatusBuilder::new().status("a status").build().expect("Couldn't build status");
assert_eq!(
serde_json::to_string(&status).expect("Couldn't serialize status"),
"{\"status\":\"a status\"}".to_string()

Loading…
Cancel
Save