From 3c3a798fbbd9971d27e6d06895f96f97e33ff959 Mon Sep 17 00:00:00 2001 From: Filip Tibell Date: Fri, 20 Jan 2023 21:05:51 -0500 Subject: [PATCH] Use pedantic clippy, fix lints --- src/cli.rs | 29 ++++++++++++++--------------- src/lune/console.rs | 14 +++++++------- src/lune/fs.rs | 6 +++--- src/lune/net.rs | 10 +++++----- src/lune/process.rs | 15 ++++++--------- src/main.rs | 5 ++++- src/utils.rs | 40 +++++++++++++++++++--------------------- 7 files changed, 58 insertions(+), 61 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 3d9f7be..b0e7ad2 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -7,7 +7,7 @@ use clap::{CommandFactory, Parser}; use mlua::{Lua, Result}; use crate::{ - lune::{console::LuneConsole, fs::LuneFs, net::LuneNet, process::LuneProcess}, + lune::{console::Console, fs::Fs, net::Net, process::Process}, utils::GithubClient, }; @@ -82,18 +82,17 @@ impl Cli { } } if self.script_path.is_none() { - if !download_types_requested { - // HACK: We know that we didn't get any arguments here but since - // script_path is optional clap will not error on its own, to fix - // we will duplicate the cli command and make arguments required, - // which will then fail and print out the normal help message - let cmd = Cli::command(); - cmd.arg_required_else_help(true).get_matches(); - } else { - // Only downloading types without running a script is completely - // fine, and we should just exit the program normally afterwards + // Only downloading types without running a script is completely + // fine, and we should just exit the program normally afterwards + if download_types_requested { return Ok(()); } + // HACK: We know that we didn't get any arguments here but since + // script_path is optional clap will not error on its own, to fix + // we will duplicate the cli command and make arguments required, + // which will then fail and print out the normal help message + let cmd = Cli::command(); + cmd.arg_required_else_help(true).get_matches(); } // Parse and read the wanted file let file_path = find_parse_file_path(&self.script_path.unwrap())?; @@ -101,10 +100,10 @@ impl Cli { // Create a new lua state and add in all lune globals let lua = Lua::new(); let globals = lua.globals(); - globals.set("console", LuneConsole::new())?; - globals.set("fs", LuneFs::new())?; - globals.set("net", LuneNet::new())?; - globals.set("process", LuneProcess::new(self.script_args))?; + globals.set("console", Console::new())?; + globals.set("fs", Fs::new())?; + globals.set("net", Net::new())?; + globals.set("process", Process::new(self.script_args))?; lua.sandbox(true)?; // Load & call the file with the given args lua.load(&file_contents) diff --git a/src/lune/console.rs b/src/lune/console.rs index 2daa803..91a3b74 100644 --- a/src/lune/console.rs +++ b/src/lune/console.rs @@ -4,15 +4,15 @@ use crate::utils::{ flush_stdout, pretty_format_multi_value, print_color, print_label, print_style, }; -pub struct LuneConsole(); +pub struct Console(); -impl LuneConsole { +impl Console { pub fn new() -> Self { Self() } } -impl UserData for LuneConsole { +impl UserData for Console { fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) { methods.add_function("resetColor", console_reset_color); methods.add_function("setColor", console_set_color); @@ -54,7 +54,7 @@ fn console_format(_: &Lua, args: MultiValue) -> Result { fn console_log(_: &Lua, args: MultiValue) -> Result<()> { let s = pretty_format_multi_value(&args)?; - println!("{}", s); + println!("{s}"); flush_stdout()?; Ok(()) } @@ -62,7 +62,7 @@ fn console_log(_: &Lua, args: MultiValue) -> Result<()> { fn console_info(_: &Lua, args: MultiValue) -> Result<()> { print_label("info")?; let s = pretty_format_multi_value(&args)?; - println!("{}", s); + println!("{s}"); flush_stdout()?; Ok(()) } @@ -70,7 +70,7 @@ fn console_info(_: &Lua, args: MultiValue) -> Result<()> { fn console_warn(_: &Lua, args: MultiValue) -> Result<()> { print_label("warn")?; let s = pretty_format_multi_value(&args)?; - println!("{}", s); + println!("{s}"); flush_stdout()?; Ok(()) } @@ -78,7 +78,7 @@ fn console_warn(_: &Lua, args: MultiValue) -> Result<()> { fn console_error(_: &Lua, args: MultiValue) -> Result<()> { print_label("error")?; let s = pretty_format_multi_value(&args)?; - eprintln!("{}", s); + eprintln!("{s}"); flush_stdout()?; Ok(()) } diff --git a/src/lune/fs.rs b/src/lune/fs.rs index 98ac777..0c33a3c 100644 --- a/src/lune/fs.rs +++ b/src/lune/fs.rs @@ -3,15 +3,15 @@ use std::path::{PathBuf, MAIN_SEPARATOR}; use mlua::{Lua, Result, UserData, UserDataMethods}; use tokio::fs; -pub struct LuneFs(); +pub struct Fs(); -impl LuneFs { +impl Fs { pub fn new() -> Self { Self() } } -impl UserData for LuneFs { +impl UserData for Fs { fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) { methods.add_async_function("readFile", fs_read_file); methods.add_async_function("readDir", fs_read_dir); diff --git a/src/lune/net.rs b/src/lune/net.rs index 5257b29..26c4c2f 100644 --- a/src/lune/net.rs +++ b/src/lune/net.rs @@ -8,15 +8,15 @@ use reqwest::{ use crate::utils::get_github_user_agent_header; -pub struct LuneNet(); +pub struct Net(); -impl LuneNet { +impl Net { pub fn new() -> Self { Self() } } -impl UserData for LuneNet { +impl UserData for Net { fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) { methods.add_function("jsonEncode", net_json_encode); methods.add_function("jsonDecode", net_json_decode); @@ -108,12 +108,12 @@ async fn net_request<'lua>(lua: &'lua Lua, config: Value<'lua>) -> Result, } -impl LuneProcess { +impl Process { pub fn new(args: Vec) -> Self { Self { args } } } -impl UserData for LuneProcess { +impl UserData for Process { fn add_fields<'lua, F: UserDataFields<'lua, Self>>(fields: &mut F) { fields.add_field_method_get("args", |lua, this| { // TODO: Use the same strategy as env uses below to avoid // copying each time args are accessed? is it worth it? let tab = lua.create_table()?; for arg in &this.args { - tab.push(arg.to_owned())?; + tab.push(arg.clone())?; } Ok(tab) }); @@ -49,7 +49,7 @@ impl UserData for LuneProcess { tab.set_metatable(Some(meta)); tab.set_readonly(true); Ok(tab) - }) + }); } fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) { @@ -137,10 +137,7 @@ async fn process_spawn(lua: &Lua, (program, args): (String, Option>) let code = output .status .code() - .unwrap_or(match output.stderr.is_empty() { - true => 0, - false => 1, - }); + .unwrap_or_else(|| i32::from(!output.stderr.is_empty())); // Construct and return a readonly lua table with results let table = lua.create_table()?; table.raw_set("ok", code == 0)?; diff --git a/src/main.rs b/src/main.rs index e8983f0..cc7f194 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,7 @@ -#![deny(clippy::all, clippy::cargo)] +#![deny(clippy::all, clippy::cargo, clippy::pedantic)] +// mlua does not implement userdata for &str +// so in some cases we have to use String +#![allow(clippy::needless_pass_by_value)] use clap::Parser; use mlua::Result; diff --git a/src/utils.rs b/src/utils.rs index 3bc3c05..4879fce 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -106,8 +106,8 @@ impl GithubClient { all_releases .iter() .find(|release| release.tag_name == release_version_tag) - .map(|release| release.to_owned()) - .with_context(|| format!("Failed to find release for version {}", release_version_tag)) + .map(ToOwned::to_owned) + .with_context(|| format!("Failed to find release for version {release_version_tag}")) } pub async fn fetch_release_asset( @@ -158,7 +158,7 @@ pub fn get_github_owner_and_repo() -> (String, String) { pub fn get_github_user_agent_header() -> String { let (github_owner, github_repo) = get_github_owner_and_repo(); - format!("{}-{}-cli", github_owner, github_repo) + format!("{github_owner}-{github_repo}-cli") } // TODO: Separate utils out into github & formatting @@ -245,10 +245,10 @@ fn pretty_format_value(buffer: &mut String, value: &Value, depth: usize) -> anyh // TODO: Handle other types like function, userdata, ... match &value { Value::Nil => write!(buffer, "nil")?, - Value::Boolean(true) => write!(buffer, "{}true{}", COLOR_YELLOW, COLOR_RESET)?, - Value::Boolean(false) => write!(buffer, "{}false{}", COLOR_YELLOW, COLOR_RESET)?, - Value::Number(n) => write!(buffer, "{}{}{}", COLOR_BLUE, n, COLOR_RESET)?, - Value::Integer(i) => write!(buffer, "{}{}{}", COLOR_BLUE, i, COLOR_RESET)?, + Value::Boolean(true) => write!(buffer, "{COLOR_YELLOW}true{COLOR_RESET}")?, + Value::Boolean(false) => write!(buffer, "{COLOR_YELLOW}false{COLOR_RESET}")?, + Value::Number(n) => write!(buffer, "{COLOR_BLUE}{n}{COLOR_RESET}")?, + Value::Integer(i) => write!(buffer, "{COLOR_BLUE}{i}{COLOR_RESET}")?, Value::String(s) => write!( buffer, "{}\"{}\"{}", @@ -260,10 +260,10 @@ fn pretty_format_value(buffer: &mut String, value: &Value, depth: usize) -> anyh )?, Value::Table(ref tab) => { if depth >= MAX_FORMAT_DEPTH { - write!(buffer, "{}{{ ... }}{}", STYLE_DIM, STYLE_RESET)?; + write!(buffer, "{STYLE_DIM}{{ ... }}{STYLE_RESET}")?; } else { let depth_indent = INDENT.repeat(depth); - write!(buffer, "{}{{{}", STYLE_DIM, STYLE_RESET)?; + write!(buffer, "{STYLE_DIM}{{{STYLE_RESET}")?; for pair in tab.clone().pairs::() { let (key, value) = pair?; match &key { @@ -277,15 +277,15 @@ fn pretty_format_value(buffer: &mut String, value: &Value, depth: usize) -> anyh STYLE_RESET )?, _ => { - write!(buffer, "\n{}{}[", depth_indent, INDENT)?; + write!(buffer, "\n{depth_indent}{INDENT}[")?; pretty_format_value(buffer, &key, depth)?; - write!(buffer, "] {}={} ", STYLE_DIM, STYLE_RESET)?; + write!(buffer, "] {STYLE_DIM}={STYLE_RESET} ")?; } } pretty_format_value(buffer, &value, depth + 1)?; - write!(buffer, "{},{}", STYLE_DIM, STYLE_RESET)?; + write!(buffer, "{STYLE_DIM},{STYLE_RESET}")?; } - write!(buffer, "\n{}{}}}{}", depth_indent, STYLE_DIM, STYLE_RESET)?; + write!(buffer, "\n{depth_indent}{STYLE_DIM}}}{STYLE_RESET}")?; } } _ => write!(buffer, "?")?, @@ -299,7 +299,7 @@ pub fn pretty_format_multi_value(multi: &MultiValue) -> mlua::Result { for value in multi { counter += 1; if let Value::String(s) = value { - write!(buffer, "{}", s.to_string_lossy()).map_err(mlua::Error::external)? + write!(buffer, "{}", s.to_string_lossy()).map_err(mlua::Error::external)?; } else { pretty_format_value(&mut buffer, value, 0).map_err(mlua::Error::external)?; } @@ -313,7 +313,7 @@ pub fn pretty_format_multi_value(multi: &MultiValue) -> mlua::Result { pub fn pretty_print_luau_error(e: &mlua::Error) { match e { mlua::Error::RuntimeError(e) => { - eprintln!("{}", e); + eprintln!("{e}"); } mlua::Error::CallbackError { cause, traceback } => { pretty_print_luau_error(cause.as_ref()); @@ -323,22 +323,20 @@ pub fn pretty_print_luau_error(e: &mlua::Error) { mlua::Error::ToLuaConversionError { from, to, message } => { let msg = message .clone() - .map(|m| format!("\nDetails:\n\t{m}")) - .unwrap_or_else(|| "".to_string()); + .map_or_else(String::new, |m| format!("\nDetails:\n\t{m}")); eprintln!( "Failed to convert Rust type '{}' into Luau type '{}'!{}", from, to, msg - ) + ); } mlua::Error::FromLuaConversionError { from, to, message } => { let msg = message .clone() - .map(|m| format!("\nDetails:\n\t{m}")) - .unwrap_or_else(|| "".to_string()); + .map_or_else(String::new, |m| format!("\nDetails:\n\t{m}")); eprintln!( "Failed to convert Luau type '{}' into Rust type '{}'!{}", from, to, msg - ) + ); } e => eprintln!("{e}"), }