Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix clippy #1426

Merged
merged 2 commits into from
Jan 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion sea-orm-cli/src/commands/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ where
// Set search_path for Postgres, E.g. Some("public") by default
// MySQL & SQLite connection initialize with schema `None`
if let Some(schema) = schema {
let sql = format!("SET search_path = '{}'", schema);
let sql = format!("SET search_path = '{schema}'");
pool_options = pool_options.after_connect(move |conn, _| {
let sql = sql.clone();
Box::pin(async move {
Expand Down
22 changes: 11 additions & 11 deletions sea-orm-cli/src/commands/migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ pub fn run_migrate_command(

// Construct the `--manifest-path`
let manifest_path = if migration_dir.ends_with('/') {
format!("{}Cargo.toml", migration_dir)
format!("{migration_dir}Cargo.toml")
} else {
format!("{}/Cargo.toml", migration_dir)
format!("{migration_dir}/Cargo.toml")
};
// Construct the arguments that will be supplied to `cargo` command
let mut args = vec!["run", "--manifest-path", &manifest_path, "--", subcommand];
Expand Down Expand Up @@ -80,7 +80,7 @@ pub fn run_migrate_command(
pub fn run_migrate_init(migration_dir: &str) -> Result<(), Box<dyn Error>> {
let migration_dir = match migration_dir.ends_with('/') {
true => migration_dir.to_string(),
false => format!("{}/", migration_dir),
false => format!("{migration_dir}/"),
};
println!("Initializing migration directory...");
macro_rules! write_file {
Expand Down Expand Up @@ -139,7 +139,7 @@ pub fn run_migrate_generate(
} else {
Local::now().format(FMT)
};
let migration_name = format!("m{}_{}", formatted_now, migration_name);
let migration_name = format!("m{formatted_now}_{migration_name}");

create_new_migration(&migration_name, migration_dir)?;
update_migrator(&migration_name, migration_dir)?;
Expand Down Expand Up @@ -217,7 +217,7 @@ fn update_migrator(migration_name: &str, migration_dir: &str) -> Result<(), Box<
let mod_regex = Regex::new(r"mod\s+(?P<name>m\d{8}_\d{6}_\w+);")?;
let mods: Vec<_> = mod_regex.captures_iter(&migrator_content).collect();
let mods_end = mods.last().unwrap().get(0).unwrap().end() + 1;
updated_migrator_content.insert_str(mods_end, format!("mod {};\n", migration_name).as_str());
updated_migrator_content.insert_str(mods_end, format!("mod {migration_name};\n").as_str());

// build new vector from declared migration modules
let mut migrations: Vec<&str> = mods
Expand All @@ -227,11 +227,11 @@ fn update_migrator(migration_name: &str, migration_dir: &str) -> Result<(), Box<
migrations.push(migration_name);
let mut boxed_migrations = migrations
.iter()
.map(|migration| format!(" Box::new({}::Migration),", migration))
.map(|migration| format!(" Box::new({migration}::Migration),"))
.collect::<Vec<String>>()
.join("\n");
boxed_migrations.push('\n');
let boxed_migrations = format!("vec![\n{} ]\n", boxed_migrations);
let boxed_migrations = format!("vec![\n{boxed_migrations} ]\n");
let vec_regex = Regex::new(r"vec!\[[\s\S]+\]\n")?;
let updated_migrator_content = vec_regex.replace(&updated_migrator_content, &boxed_migrations);

Expand All @@ -249,7 +249,7 @@ impl Display for MigrationCommandError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MigrationCommandError::InvalidName(name) => {
write!(f, "Invalid migration name: {}", name)
write!(f, "Invalid migration name: {name}")
}
}
}
Expand All @@ -265,11 +265,11 @@ mod tests {
fn test_create_new_migration() {
let migration_name = "test_name";
let migration_dir = "/tmp/sea_orm_cli_test_new_migration/";
fs::create_dir_all(format!("{}src", migration_dir)).unwrap();
fs::create_dir_all(format!("{migration_dir}src")).unwrap();
create_new_migration(migration_name, migration_dir).unwrap();
let migration_filepath = Path::new(migration_dir)
.join("src")
.join(format!("{}.rs", migration_name));
.join(format!("{migration_name}.rs"));
assert!(migration_filepath.exists());
let migration_content = fs::read_to_string(migration_filepath).unwrap();
assert_eq!(
Expand All @@ -283,7 +283,7 @@ mod tests {
fn test_update_migrator() {
let migration_name = "test_name";
let migration_dir = "/tmp/sea_orm_cli_test_update_migrator/";
fs::create_dir_all(format!("{}src", migration_dir)).unwrap();
fs::create_dir_all(format!("{migration_dir}src")).unwrap();
let migrator_filepath = Path::new(migration_dir).join("src").join("lib.rs");
fs::copy("./template/migration/src/lib.rs", &migrator_filepath).unwrap();
update_migrator(migration_name, migration_dir).unwrap();
Expand Down
2 changes: 1 addition & 1 deletion sea-orm-cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ pub fn handle_error<E>(error: E)
where
E: Display,
{
eprintln!("{}", error);
eprintln!("{error}");
::std::process::exit(1);
}
4 changes: 2 additions & 2 deletions sea-orm-codegen/src/entity/column.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ impl Column {
let col_type = match &self.col_type {
ColumnType::Float => Some("Float".to_owned()),
ColumnType::Double => Some("Double".to_owned()),
ColumnType::Decimal(Some((p, s))) => Some(format!("Decimal(Some(({}, {})))", p, s)),
ColumnType::Money(Some((p, s))) => Some(format!("Money(Some({}, {}))", p, s)),
ColumnType::Decimal(Some((p, s))) => Some(format!("Decimal(Some(({p}, {s})))")),
ColumnType::Money(Some((p, s))) => Some(format!("Money(Some({p}, {s}))")),
ColumnType::Text => Some("Text".to_owned()),
ColumnType::JsonBinary => Some("JsonBinary".to_owned()),
ColumnType::Custom(iden) => {
Expand Down
8 changes: 4 additions & 4 deletions sea-orm-codegen/src/entity/relation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,11 @@ impl Relation {
pub fn get_attrs(&self) -> TokenStream {
let rel_type = self.get_rel_type();
let module_name = if let Some(module_name) = self.get_module_name() {
format!("super::{}::", module_name)
format!("super::{module_name}::")
} else {
String::new()
};
let ref_entity = format!("{}Entity", module_name);
let ref_entity = format!("{module_name}Entity");
match self.rel_type {
RelationType::HasOne | RelationType::HasMany => {
quote! {
Expand All @@ -100,8 +100,8 @@ impl Relation {
RelationType::BelongsTo => {
let column_camel_case = self.get_column_camel_case();
let ref_column_camel_case = self.get_ref_column_camel_case();
let from = format!("Column::{}", column_camel_case);
let to = format!("{}Column::{}", module_name, ref_column_camel_case);
let from = format!("Column::{column_camel_case}");
let to = format!("{module_name}Column::{ref_column_camel_case}");
let on_update = if let Some(action) = &self.on_update {
let action = Self::get_foreign_key_action(action);
quote! {
Expand Down
6 changes: 2 additions & 4 deletions sea-orm-codegen/src/entity/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,7 @@ impl FromStr for WithSerde {
"both" => Self::Both,
v => {
return Err(crate::Error::TransformError(format!(
"Unsupported enum variant '{}'",
v
"Unsupported enum variant '{v}'"
)))
}
})
Expand Down Expand Up @@ -308,8 +307,7 @@ impl EntityWriter {
pub fn write_doc_comment(lines: &mut Vec<String>) {
let ver = env!("CARGO_PKG_VERSION");
let comments = vec![format!(
"//! `SeaORM` Entity. Generated by sea-orm-codegen {}",
ver
"//! `SeaORM` Entity. Generated by sea-orm-codegen {ver}"
)];
lines.extend(comments);
lines.push("".to_owned());
Expand Down
4 changes: 2 additions & 2 deletions sea-orm-codegen/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ pub enum Error {
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::StdIoError(e) => write!(f, "{:?}", e),
Self::TransformError(e) => write!(f, "{:?}", e),
Self::StdIoError(e) => write!(f, "{e:?}"),
Self::TransformError(e) => write!(f, "{e:?}"),
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions sea-orm-codegen/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ where
{
let string = string.to_string();
if RUST_KEYWORDS.iter().any(|s| s.eq(&string)) {
format!("r#{}", string)
format!("r#{string}")
} else if RUST_SPECIAL_KEYWORDS.iter().any(|s| s.eq(&string)) {
format!("{}_", string)
format!("{string}_")
} else {
string
}
Expand Down
2 changes: 1 addition & 1 deletion sea-orm-macros/src/derives/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ impl DeriveModel {
.filter_map(ignore)
.collect();

let missing_field_msg = format!("field does not exist on {}", ident);
let missing_field_msg = format!("field does not exist on {ident}");

quote!(
#[automatically_derived]
Expand Down
2 changes: 1 addition & 1 deletion sea-orm-macros/src/derives/relation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl DeriveRelation {
fn impl_relation_trait(&self) -> syn::Result<TokenStream> {
let ident = &self.ident;
let entity_ident = &self.entity_ident;
let no_relation_def_msg = format!("No RelationDef for {}", ident);
let no_relation_def_msg = format!("No RelationDef for {ident}");

let variant_relation_defs: Vec<TokenStream> = self
.variants
Expand Down
4 changes: 2 additions & 2 deletions sea-orm-macros/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ where
{
let string = string.to_string();
if RUST_KEYWORDS.iter().any(|s| s.eq(&string)) {
format!("r#{}", string)
format!("r#{string}")
} else if RUST_SPECIAL_KEYWORDS.iter().any(|s| s.eq(&string)) {
format!("{}_", string)
format!("{string}_")
} else {
string
}
Expand Down
2 changes: 1 addition & 1 deletion sea-orm-migration/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,6 @@ fn handle_error<E>(error: E)
where
E: Display,
{
eprintln!("{}", error);
eprintln!("{error}");
exit(1);
}
4 changes: 2 additions & 2 deletions sea-orm-migration/src/migrator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl Display for MigrationStatus {
MigrationStatus::Pending => "Pending",
MigrationStatus::Applied => "Applied",
};
write!(f, "{}", status)
write!(f, "{status}")
}
}

Expand Down Expand Up @@ -91,7 +91,7 @@ pub trait MigratorTrait: Send {
let errors: Vec<String> = missing_migrations_in_fs
.iter()
.map(|missing_migration| {
format!("Migration file of version '{}' is missing, this migration has been applied but its file is missing", missing_migration)
format!("Migration file of version '{missing_migration}' is missing, this migration has been applied but its file is missing")
}).collect();

if !errors.is_empty() {
Expand Down
12 changes: 6 additions & 6 deletions sea-orm-migration/tests/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,31 +35,31 @@ async fn run_migration(url: &str, db_name: &str, schema: &str) -> Result<(), DbE
DbBackend::MySql => {
db.execute(Statement::from_string(
db.get_database_backend(),
format!("CREATE DATABASE IF NOT EXISTS `{}`;", db_name),
format!("CREATE DATABASE IF NOT EXISTS `{db_name}`;"),
))
.await?;

let url = format!("{}/{}", url, db_name);
let url = format!("{url}/{db_name}");
db_connect(url).await?
}
DbBackend::Postgres => {
db.execute(Statement::from_string(
db.get_database_backend(),
format!("DROP DATABASE IF EXISTS \"{}\";", db_name),
format!("DROP DATABASE IF EXISTS \"{db_name}\";"),
))
.await?;
db.execute(Statement::from_string(
db.get_database_backend(),
format!("CREATE DATABASE \"{}\";", db_name),
format!("CREATE DATABASE \"{db_name}\";"),
))
.await?;

let url = format!("{}/{}", url, db_name);
let url = format!("{url}/{db_name}");
let db = db_connect(url).await?;

db.execute(Statement::from_string(
db.get_database_backend(),
format!("CREATE SCHEMA IF NOT EXISTS \"{}\";", schema),
format!("CREATE SCHEMA IF NOT EXISTS \"{schema}\";"),
))
.await?;

Expand Down
2 changes: 1 addition & 1 deletion sea-orm-rocket/codegen/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ pub fn derive_database(input: TokenStream) -> TokenStream {
.map(|attr| attr.name)
.ok_or_else(|| s.span().error(ONE_DATABASE_ATTR))?;

let fairing_name = format!("'{}' Database Pool", db_name);
let fairing_name = format!("'{db_name}' Database Pool");

let pool_type = match &s.fields {
syn::Fields::Unnamed(f) => &f.unnamed[0].ty,
Expand Down
2 changes: 1 addition & 1 deletion sea-orm-rocket/lib/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ pub trait Database:
}

let dbtype = std::any::type_name::<Self>();
let fairing = Paint::default(format!("{}::init()", dbtype)).bold();
let fairing = Paint::default(format!("{dbtype}::init()")).bold();
error!(
"Attempted to fetch unattached database `{}`.",
Paint::default(dbtype).bold()
Expand Down
6 changes: 3 additions & 3 deletions sea-orm-rocket/lib/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ pub enum Error<A, B = A> {
impl<A: fmt::Display, B: fmt::Display> fmt::Display for Error<A, B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Init(e) => write!(f, "failed to initialize database: {}", e),
Error::Get(e) => write!(f, "failed to get db connection: {}", e),
Error::Config(e) => write!(f, "bad configuration: {}", e),
Error::Init(e) => write!(f, "failed to initialize database: {e}"),
Error::Get(e) => write!(f, "failed to get db connection: {e}"),
Error::Config(e) => write!(f, "bad configuration: {e}"),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion sea-orm-rocket/lib/src/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub struct MockPoolErr;

impl std::fmt::Display for MockPoolErr {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
write!(f, "{self:?}")
}
}

Expand Down
5 changes: 2 additions & 3 deletions src/database/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,15 +223,14 @@ impl MockRow {
T::try_from(
self.values
.get(index)
.unwrap_or_else(|| panic!("No column for ColIdx {:?}", index))
.unwrap_or_else(|| panic!("No column for ColIdx {index:?}"))
.clone(),
)
.map_err(|e| DbErr::Type(e.to_string()))
} else if let Some(index) = index.as_usize() {
let (_, value) = self.values.iter().nth(*index).ok_or_else(|| {
DbErr::Query(RuntimeErr::Internal(format!(
"Column at index {} not found",
index
"Column at index {index} not found"
)))
})?;
T::try_from(value.clone()).map_err(|e| DbErr::Type(e.to_string()))
Expand Down
3 changes: 1 addition & 2 deletions src/entity/active_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,7 @@ mod tests {
"B" => Ok(Self::Big),
"S" => Ok(Self::Small),
_ => Err(DbErr::Type(format!(
"unexpected value for Category enum: {}",
v
"unexpected value for Category enum: {v}"
))),
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/entity/base_entity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -952,7 +952,7 @@ mod tests {
);
}

delete_by_id(format!("UUID"));
delete_by_id("UUID".to_string());
delete_by_id("UUID".to_string());
delete_by_id("UUID");
delete_by_id(Cow::from("UUID"));
Expand Down
6 changes: 3 additions & 3 deletions src/entity/column.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ pub trait ColumnTrait: IdenStatic + Iterable + FromStr {
/// );
/// ```
fn starts_with(&self, s: &str) -> SimpleExpr {
let pattern = format!("{}%", s);
let pattern = format!("{s}%");
Expr::col((self.entity_name(), *self)).like(pattern)
}

Expand All @@ -295,7 +295,7 @@ pub trait ColumnTrait: IdenStatic + Iterable + FromStr {
/// );
/// ```
fn ends_with(&self, s: &str) -> SimpleExpr {
let pattern = format!("%{}", s);
let pattern = format!("%{s}");
Expr::col((self.entity_name(), *self)).like(pattern)
}

Expand All @@ -311,7 +311,7 @@ pub trait ColumnTrait: IdenStatic + Iterable + FromStr {
/// );
/// ```
fn contains(&self, s: &str) -> SimpleExpr {
let pattern = format!("%{}%", s);
let pattern = format!("%{s}%");
Expr::col((self.entity_name(), *self)).like(pattern)
}

Expand Down
2 changes: 1 addition & 1 deletion src/entity/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub trait Linked {
fn find_linked(&self) -> Select<Self::ToEntity> {
let mut select = Select::new();
for (i, mut rel) in self.link().into_iter().rev().enumerate() {
let from_tbl = Alias::new(&format!("r{}", i)).into_iden();
let from_tbl = Alias::new(&format!("r{i}")).into_iden();
let to_tbl = if i > 0 {
Alias::new(&format!("r{}", i - 1)).into_iden()
} else {
Expand Down
Loading