Fixed some Clippy lints

This commit is contained in:
Nathan Fisher 2023-01-14 02:34:27 -05:00
parent 3ffcdb54ed
commit b401aaad47
9 changed files with 80 additions and 68 deletions

View File

@ -200,6 +200,7 @@ impl Cmd for Bootstrap {
} }
} }
#[allow(clippy::module_name_repetitions)]
pub trait BootstrapCmd { pub trait BootstrapCmd {
fn completion(&self, outdir: &Path, gen: &str) -> Result<(), io::Error>; fn completion(&self, outdir: &Path, gen: &str) -> Result<(), io::Error>;
fn linkpath(&self, prefix: &str, usr: bool) -> Option<PathBuf>; fn linkpath(&self, prefix: &str, usr: bool) -> Option<PathBuf>;

View File

@ -123,57 +123,6 @@ fn get_ranges(raw_ranges: ValuesRef<String>) -> Result<Vec<ParsedRange>, Box<dyn
Ok(ranges) Ok(ranges)
} }
fn print_bytes(line: &str, ranges: &[ParsedRange]) -> Result<(), Box<dyn Error>> {
let combined_ranges = combine_ranges(ranges, line.len());
let mut writer = BufWriter::new(std::io::stdout());
for (idx, byte) in line.as_bytes().iter().enumerate() {
if combined_ranges.contains(&idx) {
write!(writer, "{}", *byte as char)?;
}
}
write!(writer, "\n")?;
Ok(())
}
fn print_chars(line: &str, ranges: &[ParsedRange]) -> Result<(), Box<dyn Error>> {
let combined_ranges = combine_ranges(ranges, line.len());
let mut writer = BufWriter::new(std::io::stdout());
for (idx, ch) in line.chars().enumerate() {
if combined_ranges.contains(&idx) {
write!(writer, "{}", &ch)?;
}
}
write!(writer, "\n")?;
Ok(())
}
fn print_fields(
line: &str,
ranges: &[ParsedRange],
suppress: bool,
delimiter: Option<&String>,
) -> Result<(), Box<dyn Error>> {
let combined_ranges = combine_ranges(ranges, line.len());
let mut writer = BufWriter::new(std::io::stdout());
let delimiter = match delimiter {
Some(d) => d,
None => "\t",
};
if suppress {
if !line.contains(delimiter) {
return Ok(());
}
}
let fields = line.split(delimiter);
for (idx, field) in fields.enumerate() {
if combined_ranges.contains(&idx) {
write!(writer, "{field}")?;
}
}
write!(writer, "\n")?;
Ok(())
}
enum ParsedRange { enum ParsedRange {
Bounded(Range<usize>), Bounded(Range<usize>),
LowerBounded(RangeFrom<usize>), LowerBounded(RangeFrom<usize>),
@ -233,9 +182,9 @@ fn combine_ranges(ranges: &[ParsedRange], max: usize) -> Vec<usize> {
} }
fn parse_range(range: &str) -> Result<ParsedRange, Box<dyn Error>> { fn parse_range(range: &str) -> Result<ParsedRange, Box<dyn Error>> {
if range.starts_with('-') { if let Some(stripped) = range.strip_prefix('-') {
if range.len() > 1 { if range.len() > 1 {
let end: usize = range[1..].parse()?; let end: usize = stripped.parse()?;
if end >= 1 { if end >= 1 {
Ok((..end - 1).into()) Ok((..end - 1).into())
} else { } else {
@ -283,3 +232,52 @@ fn parse_range(range: &str) -> Result<ParsedRange, Box<dyn Error>> {
Ok(range.into()) Ok(range.into())
} }
} }
fn print_bytes(line: &str, ranges: &[ParsedRange]) -> Result<(), Box<dyn Error>> {
let combined_ranges = combine_ranges(ranges, line.len());
let mut writer = BufWriter::new(std::io::stdout());
for (idx, byte) in line.as_bytes().iter().enumerate() {
if combined_ranges.contains(&idx) {
write!(writer, "{}", *byte as char)?;
}
}
writeln!(writer)?;
Ok(())
}
fn print_chars(line: &str, ranges: &[ParsedRange]) -> Result<(), Box<dyn Error>> {
let combined_ranges = combine_ranges(ranges, line.len());
let mut writer = BufWriter::new(std::io::stdout());
for (idx, ch) in line.chars().enumerate() {
if combined_ranges.contains(&idx) {
write!(writer, "{}", &ch)?;
}
}
writeln!(writer)?;
Ok(())
}
fn print_fields(
line: &str,
ranges: &[ParsedRange],
suppress: bool,
delimiter: Option<&String>,
) -> Result<(), Box<dyn Error>> {
let combined_ranges = combine_ranges(ranges, line.len());
let mut writer = BufWriter::new(std::io::stdout());
let delimiter = match delimiter {
Some(d) => d,
None => "\t",
};
if suppress && !line.contains(delimiter) {
return Ok(());
}
let fields = line.split(delimiter);
for (idx, field) in fields.enumerate() {
if combined_ranges.contains(&idx) {
write!(writer, "{field}")?;
}
}
writeln!(writer)?;
Ok(())
}

View File

@ -97,7 +97,7 @@ fn wrap_line(line: &str, args: &ArgMatches) {
.map(|c| c.iter().collect::<String>()) .map(|c| c.iter().collect::<String>())
.collect::<Vec<String>>(); .collect::<Vec<String>>();
for line in &line { for line in &line {
println!("{}", line); println!("{line}");
} }
} }
} }

View File

@ -26,7 +26,7 @@ impl Cmd for Groups {
return Err(Box::new(io::Error::new(io::ErrorKind::Other, "no input"))) return Err(Box::new(io::Error::new(io::ErrorKind::Other, "no input")))
}; };
let groups = match matches.get_one::<String>("user") { let groups = match matches.get_one::<String>("user") {
Some(u) => pw::get_group_names_for_name(&u)?, Some(u) => pw::get_group_names_for_name(u)?,
None => pw::get_group_names()?, None => pw::get_group_names()?,
}; };
let len = groups.len(); let len = groups.len();

View File

@ -68,9 +68,9 @@ impl Cmd for Head {
}; };
let mut lines = 10; let mut lines = 10;
if args.len() > idx { if args.len() > idx {
let arg1 = &args[idx]; let one = &args[idx];
if arg1.starts_with('-') && arg1.len() > 1 { if one.starts_with('-') && one.len() > 1 {
if let Ok(lines) = arg1[1..].parse::<usize>() { if let Ok(lines) = one[1..].parse::<usize>() {
let files: Vec<_> = if args.len() > idx + 1 { let files: Vec<_> = if args.len() > idx + 1 {
args[idx + 1..].iter().map(String::as_str).collect() args[idx + 1..].iter().map(String::as_str).collect()
} else { } else {

View File

@ -40,6 +40,7 @@ pub mod which;
pub mod whoami; pub mod whoami;
pub mod yes; pub mod yes;
#[allow(clippy::module_name_repetitions)]
pub use { pub use {
self::hostname::Hostname, base32::Base32, base64::Base64, basename::Basename, self::hostname::Hostname, base32::Base32, base64::Base64, basename::Basename,
bootstrap::Bootstrap, clear::Clear, cut::Cut, dirname::Dirname, echo::Echo, factor::Factor, bootstrap::Bootstrap, clear::Clear, cut::Cut, dirname::Dirname, echo::Echo, factor::Factor,
@ -55,6 +56,7 @@ pub trait Cmd: fmt::Debug + Sync {
} }
#[must_use] #[must_use]
#[allow(clippy::box_default)]
pub fn get(name: &str) -> Option<Box<dyn Cmd>> { pub fn get(name: &str) -> Option<Box<dyn Cmd>> {
match name { match name {
"base64" => Some(Box::new(Base64::default())), "base64" => Some(Box::new(Base64::default())),
@ -86,7 +88,7 @@ pub fn get(name: &str) -> Option<Box<dyn Cmd>> {
} }
} }
pub static COMMANDS: [&'static str; 26] = [ pub static COMMANDS: [&str; 26] = [
"base32", "base32",
"base64", "base64",
"basename", "basename",

View File

@ -1,5 +1,5 @@
#![warn(clippy::all, clippy::pedantic)] #![warn(clippy::all, clippy::pedantic)]
use std::{env, error::Error, path::PathBuf, process, string::ToString}; use std::{env, path::PathBuf, process, string::ToString};
pub mod cmd; pub mod cmd;
pub use cmd::Cmd; pub use cmd::Cmd;
@ -47,7 +47,7 @@ pub fn progpath() -> Option<PathBuf> {
} }
} }
pub fn run() -> Result<(), Box<dyn Error>> { pub fn run() {
if let Some(progname) = progname() { if let Some(progname) = progname() {
if let Some(command) = cmd::get(&progname) { if let Some(command) = cmd::get(&progname) {
let cli = command.cli(); let cli = command.cli();
@ -60,5 +60,4 @@ pub fn run() -> Result<(), Box<dyn Error>> {
process::exit(1); process::exit(1);
} }
} }
Ok(())
} }

View File

@ -1,8 +1,3 @@
use std::process;
fn main() { fn main() {
if let Err(e) = shitbox::run() { shitbox::run();
eprintln!("{e}");
process::exit(1);
}
} }

View File

@ -24,6 +24,7 @@ pub fn get_eusername<'a>() -> Result<&'a str, std::str::Utf8Error> {
user.to_str() user.to_str()
} }
#[must_use]
pub fn get_uid_for_name(name: &str) -> Option<u32> { pub fn get_uid_for_name(name: &str) -> Option<u32> {
let Ok(user) = CString::new(name.as_bytes()) else { return None }; let Ok(user) = CString::new(name.as_bytes()) else { return None };
unsafe { unsafe {
@ -69,6 +70,10 @@ pub fn get_egrpname<'a>() -> Result<&'a str, std::str::Utf8Error> {
group.to_str() group.to_str()
} }
/// Gets the group ids for all groups the current effective user belongs to
/// # Errors
/// Can only error if unable to make a valid usize from the number
/// of groups returned via `libc::getgroups`
pub fn get_gids() -> Result<Vec<u32>, num::TryFromIntError> { pub fn get_gids() -> Result<Vec<u32>, num::TryFromIntError> {
let mut buf: Vec<libc::gid_t>; let mut buf: Vec<libc::gid_t>;
unsafe { unsafe {
@ -82,6 +87,10 @@ pub fn get_gids() -> Result<Vec<u32>, num::TryFromIntError> {
Ok(buf) Ok(buf)
} }
/// Gets the group ids for all groups the named user belongs to
/// # Errors
/// Errors if a valid `CString` cannot be made
/// Errors if a user belongs to more than 1024 groups
#[allow(clippy::cast_sign_loss)] #[allow(clippy::cast_sign_loss)]
pub fn get_gids_for_name(name: &str) -> Result<Vec<u32>, Box<dyn Error>> { pub fn get_gids_for_name(name: &str) -> Result<Vec<u32>, Box<dyn Error>> {
let gid = match get_pgid_for_name(name) { let gid = match get_pgid_for_name(name) {
@ -108,6 +117,10 @@ pub fn get_gids_for_name(name: &str) -> Result<Vec<u32>, Box<dyn Error>> {
Ok(buf[0..ct as usize].to_vec()) Ok(buf[0..ct as usize].to_vec())
} }
/// Gets a list of group names for the current effective user
/// # Errors
/// Bubbles up errors from `get_gids`
/// Can error if a group name is not valid utf8
pub fn get_group_names() -> Result<Vec<String>, Box<dyn Error>> { pub fn get_group_names() -> Result<Vec<String>, Box<dyn Error>> {
let gids = get_gids()?; let gids = get_gids()?;
let mut names = vec![]; let mut names = vec![];
@ -128,6 +141,10 @@ pub fn get_group_names() -> Result<Vec<String>, Box<dyn Error>> {
Ok(names) Ok(names)
} }
/// Gets a list of group names for the given user name
/// # Errors
/// Bubbles up errors from `get_gids_for_name`
/// Can error if a group name is not valid utf8
pub fn get_group_names_for_name(name: &str) -> Result<Vec<String>, Box<dyn Error>> { pub fn get_group_names_for_name(name: &str) -> Result<Vec<String>, Box<dyn Error>> {
let gids = get_gids_for_name(name)?; let gids = get_gids_for_name(name)?;
let mut names = vec![]; let mut names = vec![];