Use pedantic clippy, fix lints

This commit is contained in:
Filip Tibell 2023-01-20 21:05:51 -05:00
parent bce6958c46
commit 3c3a798fbb
No known key found for this signature in database
7 changed files with 58 additions and 61 deletions

View file

@ -7,7 +7,7 @@ use clap::{CommandFactory, Parser};
use mlua::{Lua, Result}; use mlua::{Lua, Result};
use crate::{ use crate::{
lune::{console::LuneConsole, fs::LuneFs, net::LuneNet, process::LuneProcess}, lune::{console::Console, fs::Fs, net::Net, process::Process},
utils::GithubClient, utils::GithubClient,
}; };
@ -82,18 +82,17 @@ impl Cli {
} }
} }
if self.script_path.is_none() { if self.script_path.is_none() {
if !download_types_requested { // 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 // 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 // script_path is optional clap will not error on its own, to fix
// we will duplicate the cli command and make arguments required, // we will duplicate the cli command and make arguments required,
// which will then fail and print out the normal help message // which will then fail and print out the normal help message
let cmd = Cli::command(); let cmd = Cli::command();
cmd.arg_required_else_help(true).get_matches(); 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
return Ok(());
}
} }
// Parse and read the wanted file // Parse and read the wanted file
let file_path = find_parse_file_path(&self.script_path.unwrap())?; 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 // Create a new lua state and add in all lune globals
let lua = Lua::new(); let lua = Lua::new();
let globals = lua.globals(); let globals = lua.globals();
globals.set("console", LuneConsole::new())?; globals.set("console", Console::new())?;
globals.set("fs", LuneFs::new())?; globals.set("fs", Fs::new())?;
globals.set("net", LuneNet::new())?; globals.set("net", Net::new())?;
globals.set("process", LuneProcess::new(self.script_args))?; globals.set("process", Process::new(self.script_args))?;
lua.sandbox(true)?; lua.sandbox(true)?;
// Load & call the file with the given args // Load & call the file with the given args
lua.load(&file_contents) lua.load(&file_contents)

View file

@ -4,15 +4,15 @@ use crate::utils::{
flush_stdout, pretty_format_multi_value, print_color, print_label, print_style, 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 { pub fn new() -> Self {
Self() Self()
} }
} }
impl UserData for LuneConsole { impl UserData for Console {
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) { fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_function("resetColor", console_reset_color); methods.add_function("resetColor", console_reset_color);
methods.add_function("setColor", console_set_color); methods.add_function("setColor", console_set_color);
@ -54,7 +54,7 @@ fn console_format(_: &Lua, args: MultiValue) -> Result<String> {
fn console_log(_: &Lua, args: MultiValue) -> Result<()> { fn console_log(_: &Lua, args: MultiValue) -> Result<()> {
let s = pretty_format_multi_value(&args)?; let s = pretty_format_multi_value(&args)?;
println!("{}", s); println!("{s}");
flush_stdout()?; flush_stdout()?;
Ok(()) Ok(())
} }
@ -62,7 +62,7 @@ fn console_log(_: &Lua, args: MultiValue) -> Result<()> {
fn console_info(_: &Lua, args: MultiValue) -> Result<()> { fn console_info(_: &Lua, args: MultiValue) -> Result<()> {
print_label("info")?; print_label("info")?;
let s = pretty_format_multi_value(&args)?; let s = pretty_format_multi_value(&args)?;
println!("{}", s); println!("{s}");
flush_stdout()?; flush_stdout()?;
Ok(()) Ok(())
} }
@ -70,7 +70,7 @@ fn console_info(_: &Lua, args: MultiValue) -> Result<()> {
fn console_warn(_: &Lua, args: MultiValue) -> Result<()> { fn console_warn(_: &Lua, args: MultiValue) -> Result<()> {
print_label("warn")?; print_label("warn")?;
let s = pretty_format_multi_value(&args)?; let s = pretty_format_multi_value(&args)?;
println!("{}", s); println!("{s}");
flush_stdout()?; flush_stdout()?;
Ok(()) Ok(())
} }
@ -78,7 +78,7 @@ fn console_warn(_: &Lua, args: MultiValue) -> Result<()> {
fn console_error(_: &Lua, args: MultiValue) -> Result<()> { fn console_error(_: &Lua, args: MultiValue) -> Result<()> {
print_label("error")?; print_label("error")?;
let s = pretty_format_multi_value(&args)?; let s = pretty_format_multi_value(&args)?;
eprintln!("{}", s); eprintln!("{s}");
flush_stdout()?; flush_stdout()?;
Ok(()) Ok(())
} }

View file

@ -3,15 +3,15 @@ use std::path::{PathBuf, MAIN_SEPARATOR};
use mlua::{Lua, Result, UserData, UserDataMethods}; use mlua::{Lua, Result, UserData, UserDataMethods};
use tokio::fs; use tokio::fs;
pub struct LuneFs(); pub struct Fs();
impl LuneFs { impl Fs {
pub fn new() -> Self { pub fn new() -> Self {
Self() Self()
} }
} }
impl UserData for LuneFs { impl UserData for Fs {
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) { fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_async_function("readFile", fs_read_file); methods.add_async_function("readFile", fs_read_file);
methods.add_async_function("readDir", fs_read_dir); methods.add_async_function("readDir", fs_read_dir);

View file

@ -8,15 +8,15 @@ use reqwest::{
use crate::utils::get_github_user_agent_header; use crate::utils::get_github_user_agent_header;
pub struct LuneNet(); pub struct Net();
impl LuneNet { impl Net {
pub fn new() -> Self { pub fn new() -> Self {
Self() Self()
} }
} }
impl UserData for LuneNet { impl UserData for Net {
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) { fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_function("jsonEncode", net_json_encode); methods.add_function("jsonEncode", net_json_encode);
methods.add_function("jsonDecode", net_json_decode); methods.add_function("jsonDecode", net_json_decode);
@ -108,12 +108,12 @@ async fn net_request<'lua>(lua: &'lua Lua, config: Value<'lua>) -> Result<Value<
// Create and send the request // Create and send the request
let mut request = client.request(method, url).headers(header_map); let mut request = client.request(method, url).headers(header_map);
if let Some(body) = body { if let Some(body) = body {
request = request.body(body) request = request.body(body);
} }
let response = request.send().await.map_err(Error::external)?; let response = request.send().await.map_err(Error::external)?;
// Extract status, headers, body // Extract status, headers, body
let res_status = response.status(); let res_status = response.status();
let res_headers = response.headers().to_owned(); let res_headers = response.headers().clone();
let res_bytes = response.bytes().await.map_err(Error::external)?; let res_bytes = response.bytes().await.map_err(Error::external)?;
// Construct and return a readonly lua table with results // Construct and return a readonly lua table with results
let tab = lua.create_table()?; let tab = lua.create_table()?;

View file

@ -10,24 +10,24 @@ use mlua::{
use os_str_bytes::RawOsString; use os_str_bytes::RawOsString;
use tokio::process::Command; use tokio::process::Command;
pub struct LuneProcess { pub struct Process {
args: Vec<String>, args: Vec<String>,
} }
impl LuneProcess { impl Process {
pub fn new(args: Vec<String>) -> Self { pub fn new(args: Vec<String>) -> Self {
Self { args } Self { args }
} }
} }
impl UserData for LuneProcess { impl UserData for Process {
fn add_fields<'lua, F: UserDataFields<'lua, Self>>(fields: &mut F) { fn add_fields<'lua, F: UserDataFields<'lua, Self>>(fields: &mut F) {
fields.add_field_method_get("args", |lua, this| { fields.add_field_method_get("args", |lua, this| {
// TODO: Use the same strategy as env uses below to avoid // TODO: Use the same strategy as env uses below to avoid
// copying each time args are accessed? is it worth it? // copying each time args are accessed? is it worth it?
let tab = lua.create_table()?; let tab = lua.create_table()?;
for arg in &this.args { for arg in &this.args {
tab.push(arg.to_owned())?; tab.push(arg.clone())?;
} }
Ok(tab) Ok(tab)
}); });
@ -49,7 +49,7 @@ impl UserData for LuneProcess {
tab.set_metatable(Some(meta)); tab.set_metatable(Some(meta));
tab.set_readonly(true); tab.set_readonly(true);
Ok(tab) Ok(tab)
}) });
} }
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) { 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<Vec<String>>)
let code = output let code = output
.status .status
.code() .code()
.unwrap_or(match output.stderr.is_empty() { .unwrap_or_else(|| i32::from(!output.stderr.is_empty()));
true => 0,
false => 1,
});
// Construct and return a readonly lua table with results // Construct and return a readonly lua table with results
let table = lua.create_table()?; let table = lua.create_table()?;
table.raw_set("ok", code == 0)?; table.raw_set("ok", code == 0)?;

View file

@ -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 clap::Parser;
use mlua::Result; use mlua::Result;

View file

@ -106,8 +106,8 @@ impl GithubClient {
all_releases all_releases
.iter() .iter()
.find(|release| release.tag_name == release_version_tag) .find(|release| release.tag_name == release_version_tag)
.map(|release| release.to_owned()) .map(ToOwned::to_owned)
.with_context(|| format!("Failed to find release for version {}", release_version_tag)) .with_context(|| format!("Failed to find release for version {release_version_tag}"))
} }
pub async fn fetch_release_asset( 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 { pub fn get_github_user_agent_header() -> String {
let (github_owner, github_repo) = get_github_owner_and_repo(); 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 // 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, ... // TODO: Handle other types like function, userdata, ...
match &value { match &value {
Value::Nil => write!(buffer, "nil")?, Value::Nil => write!(buffer, "nil")?,
Value::Boolean(true) => write!(buffer, "{}true{}", COLOR_YELLOW, COLOR_RESET)?, Value::Boolean(true) => write!(buffer, "{COLOR_YELLOW}true{COLOR_RESET}")?,
Value::Boolean(false) => write!(buffer, "{}false{}", COLOR_YELLOW, COLOR_RESET)?, Value::Boolean(false) => write!(buffer, "{COLOR_YELLOW}false{COLOR_RESET}")?,
Value::Number(n) => write!(buffer, "{}{}{}", COLOR_BLUE, n, COLOR_RESET)?, Value::Number(n) => write!(buffer, "{COLOR_BLUE}{n}{COLOR_RESET}")?,
Value::Integer(i) => write!(buffer, "{}{}{}", COLOR_BLUE, i, COLOR_RESET)?, Value::Integer(i) => write!(buffer, "{COLOR_BLUE}{i}{COLOR_RESET}")?,
Value::String(s) => write!( Value::String(s) => write!(
buffer, buffer,
"{}\"{}\"{}", "{}\"{}\"{}",
@ -260,10 +260,10 @@ fn pretty_format_value(buffer: &mut String, value: &Value, depth: usize) -> anyh
)?, )?,
Value::Table(ref tab) => { Value::Table(ref tab) => {
if depth >= MAX_FORMAT_DEPTH { if depth >= MAX_FORMAT_DEPTH {
write!(buffer, "{}{{ ... }}{}", STYLE_DIM, STYLE_RESET)?; write!(buffer, "{STYLE_DIM}{{ ... }}{STYLE_RESET}")?;
} else { } else {
let depth_indent = INDENT.repeat(depth); let depth_indent = INDENT.repeat(depth);
write!(buffer, "{}{{{}", STYLE_DIM, STYLE_RESET)?; write!(buffer, "{STYLE_DIM}{{{STYLE_RESET}")?;
for pair in tab.clone().pairs::<Value, Value>() { for pair in tab.clone().pairs::<Value, Value>() {
let (key, value) = pair?; let (key, value) = pair?;
match &key { match &key {
@ -277,15 +277,15 @@ fn pretty_format_value(buffer: &mut String, value: &Value, depth: usize) -> anyh
STYLE_RESET STYLE_RESET
)?, )?,
_ => { _ => {
write!(buffer, "\n{}{}[", depth_indent, INDENT)?; write!(buffer, "\n{depth_indent}{INDENT}[")?;
pretty_format_value(buffer, &key, depth)?; 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)?; 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, "?")?, _ => write!(buffer, "?")?,
@ -299,7 +299,7 @@ pub fn pretty_format_multi_value(multi: &MultiValue) -> mlua::Result<String> {
for value in multi { for value in multi {
counter += 1; counter += 1;
if let Value::String(s) = value { 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 { } else {
pretty_format_value(&mut buffer, value, 0).map_err(mlua::Error::external)?; 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<String> {
pub fn pretty_print_luau_error(e: &mlua::Error) { pub fn pretty_print_luau_error(e: &mlua::Error) {
match e { match e {
mlua::Error::RuntimeError(e) => { mlua::Error::RuntimeError(e) => {
eprintln!("{}", e); eprintln!("{e}");
} }
mlua::Error::CallbackError { cause, traceback } => { mlua::Error::CallbackError { cause, traceback } => {
pretty_print_luau_error(cause.as_ref()); 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 } => { mlua::Error::ToLuaConversionError { from, to, message } => {
let msg = message let msg = message
.clone() .clone()
.map(|m| format!("\nDetails:\n\t{m}")) .map_or_else(String::new, |m| format!("\nDetails:\n\t{m}"));
.unwrap_or_else(|| "".to_string());
eprintln!( eprintln!(
"Failed to convert Rust type '{}' into Luau type '{}'!{}", "Failed to convert Rust type '{}' into Luau type '{}'!{}",
from, to, msg from, to, msg
) );
} }
mlua::Error::FromLuaConversionError { from, to, message } => { mlua::Error::FromLuaConversionError { from, to, message } => {
let msg = message let msg = message
.clone() .clone()
.map(|m| format!("\nDetails:\n\t{m}")) .map_or_else(String::new, |m| format!("\nDetails:\n\t{m}"));
.unwrap_or_else(|| "".to_string());
eprintln!( eprintln!(
"Failed to convert Luau type '{}' into Rust type '{}'!{}", "Failed to convert Luau type '{}' into Rust type '{}'!{}",
from, to, msg from, to, msg
) );
} }
e => eprintln!("{e}"), e => eprintln!("{e}"),
} }