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 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 {
// 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();
} 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
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)

View file

@ -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<String> {
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(())
}

View file

@ -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);

View file

@ -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<Value<
// Create and send the request
let mut request = client.request(method, url).headers(header_map);
if let Some(body) = body {
request = request.body(body)
request = request.body(body);
}
let response = request.send().await.map_err(Error::external)?;
// Extract status, headers, body
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)?;
// Construct and return a readonly lua table with results
let tab = lua.create_table()?;

View file

@ -10,24 +10,24 @@ use mlua::{
use os_str_bytes::RawOsString;
use tokio::process::Command;
pub struct LuneProcess {
pub struct Process {
args: Vec<String>,
}
impl LuneProcess {
impl Process {
pub fn new(args: Vec<String>) -> 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<Vec<String>>)
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)?;

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 mlua::Result;

View file

@ -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::<Value, Value>() {
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<String> {
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<String> {
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}"),
}