1
0
mirror of https://github.com/jht5945/rust_util.git synced 2025-12-27 07:30:05 +08:00

fix: clippy

This commit is contained in:
2021-05-30 01:28:16 +08:00
parent c8a0f22425
commit 8d4b8aa1e0
10 changed files with 75 additions and 61 deletions

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "rust_util" name = "rust_util"
version = "0.6.36" version = "0.6.37"
authors = ["Hatter Jiang <jht5945@gmail.com>"] authors = ["Hatter Jiang <jht5945@gmail.com>"]
edition = "2018" edition = "2018"
description = "Hatter's Rust Util" description = "Hatter's Rust Util"

View File

@@ -4,7 +4,16 @@ pub fn is_env_on(var: &str) -> bool {
env::var(var).ok().map(|val| is_on(&val)).unwrap_or(false) env::var(var).ok().map(|val| is_on(&val)).unwrap_or(false)
} }
pub fn is_env_off(var: &str) -> bool {
env::var(var).ok().map(|val| is_off(&val)).unwrap_or(false)
}
pub fn is_on(val: &str) -> bool { pub fn is_on(val: &str) -> bool {
let lower_val = val.to_lowercase(); let lower_val = val.to_lowercase();
vec!["true", "yes", "1"].iter().any(|x| *x == lower_val) vec!["true", "yes", "1"].iter().any(|x| *x == lower_val)
} }
pub fn is_off(val: &str) -> bool {
let lower_val = val.to_lowercase();
vec!["false", "no", "0"].iter().any(|x| *x == lower_val)
}

View File

@@ -1,8 +1,7 @@
use std::env;
use std::fs::{self, File}; use std::fs::{self, File};
use std::io::{Lines, BufReader}; use std::io::{Lines, BufReader};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use crate::{iff, util_os, util_io, util_msg, new_box_ioerror, XResult}; use crate::{util_os, util_io, util_msg, new_box_ioerror, XResult};
pub struct JoinFilesReader { pub struct JoinFilesReader {
files: Vec<String>, files: Vec<String>,
@@ -18,7 +17,6 @@ fn open_file_as_lines(f: &str) -> XResult<Lines<BufReader<File>>> {
} }
impl JoinFilesReader { impl JoinFilesReader {
pub fn new(fns: &[&str]) -> XResult<Self> { pub fn new(fns: &[&str]) -> XResult<Self> {
let mut files: Vec<String> = vec![]; let mut files: Vec<String> = vec![];
for f in fns { for f in fns {
@@ -49,10 +47,11 @@ impl Iterator for JoinFilesReader {
} else { } else {
// if open file failed, will not continue read files // if open file failed, will not continue read files
self.file_lines = Some(Box::new(match open_file_as_lines(&self.files[self.file_ptr]) { self.file_lines = Some(Box::new(match open_file_as_lines(&self.files[self.file_ptr]) {
Ok(ln) => ln, Err(e) => return Some(Err(e)), Ok(ln) => ln,
Err(e) => return Some(Err(e)),
})); }));
} }
}, }
}, },
None => return None, None => return None,
} }
@@ -129,13 +128,15 @@ pub fn locate_file(files: &[String]) -> Option<PathBuf> {
None None
} }
#[deprecated]
pub fn get_home_str() -> Option<String> { pub fn get_home_str() -> Option<String> {
iff!(util_os::is_macos_or_linux(), env::var("HOME").ok(), None) util_os::get_user_home()
} }
pub fn resolve_file_path(path: &str) -> String { pub fn resolve_file_path(path: &str) -> String {
let home_path = match get_home_str() { let home_path = match util_os::get_user_home() {
Some(p) => p, None => return path.to_owned(), Some(p) => p,
None => return path.to_owned(),
}; };
match path { match path {
"~" => home_path, "~" => home_path,
@@ -145,13 +146,13 @@ pub fn resolve_file_path(path: &str) -> String {
} }
pub fn get_home_path() -> Option<PathBuf> { pub fn get_home_path() -> Option<PathBuf> {
Some(PathBuf::from(get_home_str()?)) Some(PathBuf::from(util_os::get_user_home()?))
} }
pub fn get_absolute_path(path: &str) -> Option<PathBuf> { pub fn get_absolute_path(path: &str) -> Option<PathBuf> {
match path { match path {
"~" => Some(PathBuf::from(get_home_str()?)), "~" => Some(PathBuf::from(util_os::get_user_home()?)),
path if path.starts_with("~/") => Some(PathBuf::from(&format!("{}/{}", get_home_str()?, &path[2..]))), path if path.starts_with("~/") => Some(PathBuf::from(&format!("{}/{}", util_os::get_user_home()?, &path[2..]))),
path => fs::canonicalize(path).ok(), path => fs::canonicalize(path).ok(),
} }
} }
@@ -168,37 +169,39 @@ pub fn is_symlink(path: &Path) -> bool {
} }
pub fn walk_dir<FError, FProcess, FFilter>(dir: &Path, pub fn walk_dir<FError, FProcess, FFilter>(dir: &Path,
func_walk_error: &FError, func_walk_error: &FError,
func_process_file: &FProcess, func_process_file: &FProcess,
func_filter_dir: &FFilter) -> XResult<()> func_filter_dir: &FFilter) -> XResult<()>
where FError: Fn(&Path, Box<dyn std::error::Error>), where FError: Fn(&Path, Box<dyn std::error::Error>),
FProcess: Fn(&Path), FProcess: Fn(&Path),
FFilter: Fn(&Path) -> bool { FFilter: Fn(&Path) -> bool {
walk_dir_with_depth_check(&mut 0u32, dir, func_walk_error, func_process_file, func_filter_dir) walk_dir_with_depth_check(&mut 0u32, dir, func_walk_error, func_process_file, func_filter_dir)
} }
fn walk_dir_with_depth_check<FError, FProcess, FFilter>(depth: &mut u32, dir: &Path, fn walk_dir_with_depth_check<FError, FProcess, FFilter>(depth: &mut u32, dir: &Path,
func_walk_error: &FError, func_walk_error: &FError,
func_process_file: &FProcess, func_process_file: &FProcess,
func_filter_dir: &FFilter) -> XResult<()> func_filter_dir: &FFilter) -> XResult<()>
where FError: Fn(&Path, Box<dyn std::error::Error>), where FError: Fn(&Path, Box<dyn std::error::Error>),
FProcess: Fn(&Path), FProcess: Fn(&Path),
FFilter: Fn(&Path) -> bool { FFilter: Fn(&Path) -> bool {
if *depth > 100u32 { if *depth > 100u32 {
return Err(new_box_ioerror(&format!("Depth exceed, depth: {}, path: {:?}", *depth, dir))); return Err(new_box_ioerror(&format!("Depth exceed, depth: {}, path: {:?}", *depth, dir)));
} }
let read_dir = match dir.read_dir() { let read_dir = match dir.read_dir() {
Ok(rd) => rd, Err(err) => { Ok(rd) => rd,
Err(err) => {
func_walk_error(&dir, Box::new(err)); func_walk_error(&dir, Box::new(err));
return Ok(()); return Ok(());
}, }
}; };
for dir_entry_item in read_dir { for dir_entry_item in read_dir {
let dir_entry = match dir_entry_item { let dir_entry = match dir_entry_item {
Ok(item) => item, Err(err) => { Ok(item) => item,
Err(err) => {
func_walk_error(&dir, Box::new(err)); func_walk_error(&dir, Box::new(err));
continue; // Ok? continue; // Ok?
}, }
}; };
let path_buf = dir_entry.path(); let path_buf = dir_entry.path();

View File

@@ -16,7 +16,7 @@ pub struct GitStatusChange {
impl GitStatusChange { impl GitStatusChange {
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
self.added.is_empty() && self.modified.is_empty() self.added.is_empty() && self.modified.is_empty()
&& self.deleted.is_empty() && self.untracked.is_empty() && self.deleted.is_empty() && self.untracked.is_empty()
} }
} }
@@ -58,7 +58,7 @@ pub fn git_branch(working_dir: Option<&str>) -> XResult<Option<String>> {
util_msg::print_info(&format!("Exec: {:?}", cmd)); util_msg::print_info(&format!("Exec: {:?}", cmd));
let output = cmd.output()?; let output = cmd.output()?;
let git_branch = String::from_utf8(output.stdout)?; let git_branch = String::from_utf8(output.stdout)?;
let current_branch = git_branch.lines().find(|ln| ln.trim().starts_with("*")); let current_branch = git_branch.lines().find(|ln| ln.trim().starts_with('*'));
Ok(current_branch.map(|ln| ln.trim()[1..].trim().into())) Ok(current_branch.map(|ln| ln.trim()[1..].trim().into()))
} }

View File

@@ -13,15 +13,13 @@ pub fn stdout_or_file_write(file: Option<&str>, overwrite: bool) -> XResult<Box<
match file { match file {
None => Ok(Box::new(io::stdout())), None => Ok(Box::new(io::stdout())),
Some(output) => { Some(output) => {
if let Ok(_) = File::open(output) { if File::open(output).is_ok() && !overwrite {
if !overwrite { return Err(SimpleError::new(format!("File exists: {}", output)).into());
return Err(SimpleError::new(format!("File exists: {}", output)).into());
}
} }
Ok(Box::new(File::create(output).map_err(|e| { Ok(Box::new(File::create(output).map_err(|e| {
SimpleError::new(format!("Create file: {}, failed: {}", output, e)) SimpleError::new(format!("Create file: {}, failed: {}", output, e))
})?)) })?))
}, }
} }
} }
@@ -59,10 +57,7 @@ impl PrintStatusContext {
if written > self.total_written_bytes && (written - self.total_written_bytes > self.print_interval_bytes) { if written > self.total_written_bytes && (written - self.total_written_bytes > self.print_interval_bytes) {
return true; return true;
} }
match last_print_cost.as_millis() { last_print_cost.as_millis() > self.print_interval_time.as_millis()
m if m > self.print_interval_time.as_millis() => true,
_ => false,
}
}; };
if should_update_status_line() { if should_update_status_line() {
self.last_print_time = now; self.last_print_time = now;
@@ -104,18 +99,18 @@ pub fn read_to_bytes(read: &mut dyn Read) -> XResult<Vec<u8>> {
} }
pub fn copy_io_default<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W, total: i64) -> io::Result<u64> pub fn copy_io_default<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W, total: i64) -> io::Result<u64>
where R: io::Read, W: io::Write { where R: io::Read, W: io::Write {
copy_io_with_head(reader, writer, total, "Downloading", &mut PrintStatusContext::default()) copy_io_with_head(reader, writer, total, "Downloading", &mut PrintStatusContext::default())
} }
pub fn copy_io<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W, total: i64, print_status_context: &mut PrintStatusContext) pub fn copy_io<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W, total: i64, print_status_context: &mut PrintStatusContext)
-> io::Result<u64> -> io::Result<u64>
where R: io::Read, W: io::Write { where R: io::Read, W: io::Write {
copy_io_with_head(reader, writer, total, "Downloading", print_status_context) copy_io_with_head(reader, writer, total, "Downloading", print_status_context)
} }
pub fn copy_io_with_head<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W, total: i64, head: &str, print_status_context: &mut PrintStatusContext) -> io::Result<u64> pub fn copy_io_with_head<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W, total: i64, head: &str, print_status_context: &mut PrintStatusContext) -> io::Result<u64>
where R: io::Read, W: io::Write { where R: io::Read, W: io::Write {
let written = copy_io_callback(reader, writer, total, print_status_context, &mut |total, written, _len, print_status_context| { let written = copy_io_callback(reader, writer, total, print_status_context, &mut |total, written, _len, print_status_context| {
print_status_last_line(head, total, written as i64, print_status_context); print_status_last_line(head, total, written as i64, print_status_context);
}); });
@@ -124,9 +119,9 @@ pub fn copy_io_with_head<R: ?Sized, W: ?Sized>(reader: &mut R, writer: &mut W, t
} }
pub fn copy_io_callback<R: ?Sized, W: ?Sized, FCallback>(reader: &mut R, writer: &mut W, total: i64, print_status_context: &mut PrintStatusContext, callback: &mut FCallback) -> io::Result<u64> pub fn copy_io_callback<R: ?Sized, W: ?Sized, FCallback>(reader: &mut R, writer: &mut W, total: i64, print_status_context: &mut PrintStatusContext, callback: &mut FCallback) -> io::Result<u64>
where R: io::Read, where R: io::Read,
W: io::Write, W: io::Write,
FCallback: Fn(i64, u64, usize, &mut PrintStatusContext) { FCallback: Fn(i64, u64, usize, &mut PrintStatusContext) {
let mut written = 0u64; let mut written = 0u64;
let mut buf: [u8; DEFAULT_BUF_SIZE] = [0u8; DEFAULT_BUF_SIZE]; let mut buf: [u8; DEFAULT_BUF_SIZE] = [0u8; DEFAULT_BUF_SIZE];
loop { loop {
@@ -154,14 +149,14 @@ pub fn print_status_last_line(head: &str, total: i64, written: i64, print_status
} }
if total > 0 { if total > 0 {
util_msg::print_lastline(&format!("{}, Total: {}, Finished: {}, Speed: {}", util_msg::print_lastline(&format!("{}, Total: {}, Finished: {}, Speed: {}",
head, head,
util_size::get_display_size(total), util_size::get_display_size(total),
util_size::get_display_size(written), util_size::get_display_size(written),
download_speed)); download_speed));
} else { } else {
util_msg::print_lastline(&format!("{}, Finished: {}, Speed: {}", util_msg::print_lastline(&format!("{}, Finished: {}, Speed: {}",
head, head,
util_size::get_display_size(written), util_size::get_display_size(written),
download_speed)); download_speed));
} }
} }

View File

@@ -8,6 +8,7 @@ lazy_static! {
static ref PRINT_MESSAGE_LOCK: Arc<Mutex<()>> = Arc::new(Mutex::new(())); static ref PRINT_MESSAGE_LOCK: Arc<Mutex<()>> = Arc::new(Mutex::new(()));
} }
#[allow(clippy::upper_case_acronyms)]
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub enum MessageType { DEBUG, INFO, OK, WARN, ERROR } pub enum MessageType { DEBUG, INFO, OK, WARN, ERROR }
@@ -92,7 +93,7 @@ pub fn is_logger_level_enabled(mt: MessageType) -> bool {
mt.get_u8_value() >= logger_level.get_u8_value() mt.get_u8_value() >= logger_level.get_u8_value()
} }
pub fn when<F>(mt: MessageType, f: F) where F: Fn() -> () { pub fn when<F>(mt: MessageType, f: F) where F: Fn() {
if is_logger_level_enabled(mt) { if is_logger_level_enabled(mt) {
f(); f();
} }

View File

@@ -79,7 +79,7 @@ impl IpAddress {
pub fn to_u32(&self) -> u32 { pub fn to_u32(&self) -> u32 {
match self { match self {
IpAddress::Ipv4(ipv4) => { IpAddress::Ipv4(ipv4) => {
u32::from_be_bytes(ipv4.clone()) u32::from_be_bytes(*ipv4)
} }
} }
} }

View File

@@ -1,4 +1,6 @@
use std::env;
use std::path::PathBuf; use std::path::PathBuf;
use crate::iff;
pub fn is_macos() -> bool { pub fn is_macos() -> bool {
cfg!(target_os = "macos") cfg!(target_os = "macos")
@@ -12,6 +14,10 @@ pub fn is_macos_or_linux() -> bool {
is_macos() || is_linux() is_macos() || is_linux()
} }
pub fn get_user_home() -> Option<String> {
iff!(is_macos_or_linux(), env::var("HOME").ok(), None)
}
pub fn get_full_work_dir() -> Option<String> { pub fn get_full_work_dir() -> Option<String> {
PathBuf::from(".").canonicalize().ok().map(|p| { PathBuf::from(".").canonicalize().ok().map(|p| {
p.to_str().map(ToString::to_string) p.to_str().map(ToString::to_string)

View File

@@ -2,10 +2,10 @@ use std::sync::Mutex;
use crate::util_msg::MessageType; use crate::util_msg::MessageType;
lazy_static! { lazy_static! {
static ref EXIT_CALLBACK: Mutex<Vec<Box<dyn Fn() -> () + Send + 'static>>> = Mutex::new(vec![]); static ref EXIT_CALLBACK: Mutex<Vec<Box<dyn Fn() + Send + 'static>>> = Mutex::new(vec![]);
} }
pub fn register_callback<F>(f: F) where F: Fn() -> () + Send + 'static { pub fn register_callback<F>(f: F) where F: Fn() + Send + 'static {
let mut exit_callbacks = EXIT_CALLBACK.lock().unwrap(); let mut exit_callbacks = EXIT_CALLBACK.lock().unwrap();
exit_callbacks.push(Box::new(f)); exit_callbacks.push(Box::new(f));
} }

View File

@@ -1,11 +1,11 @@
use std::time::{SystemTime, Duration}; use std::time::{SystemTime, Duration};
pub fn get_current_secs() -> u64 { pub fn get_current_secs() -> u64 {
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0 /* SHOULD NOT HAPPEN */ ) SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0 /* SHOULD NOT HAPPEN */)
} }
pub fn get_current_millis() -> u128 { pub fn get_current_millis() -> u128 {
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0 /* SHOULD NOT HAPPEN */ ) SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0 /* SHOULD NOT HAPPEN */)
} }
pub fn parse_duration(t: &str) -> Option<Duration> { pub fn parse_duration(t: &str) -> Option<Duration> {
@@ -20,7 +20,7 @@ pub fn parse_duration(t: &str) -> Option<Duration> {
Some('m') => parse_and_process_time(60 * 1000), Some('m') => parse_and_process_time(60 * 1000),
Some('h') => parse_and_process_time(60 * 60 * 1000), Some('h') => parse_and_process_time(60 * 60 * 1000),
Some('d') => parse_and_process_time(24 * 60 * 60 * 1000), Some('d') => parse_and_process_time(24 * 60 * 60 * 1000),
_ => t.parse::<u64>().map(|t| Duration::from_millis(t)).ok(), _ => t.parse::<u64>().map(Duration::from_millis).ok(),
} }
} }
@@ -47,5 +47,5 @@ fn test_parse_duration() {
assert_eq!(Duration::from_millis(60000), parse_duration("1m").unwrap()); assert_eq!(Duration::from_millis(60000), parse_duration("1m").unwrap());
assert_eq!(Duration::from_millis(3600000), parse_duration("1h").unwrap()); assert_eq!(Duration::from_millis(3600000), parse_duration("1h").unwrap());
assert_eq!(Duration::from_millis(1800000), parse_duration("0.5h").unwrap()); assert_eq!(Duration::from_millis(1800000), parse_duration("0.5h").unwrap());
assert_eq!(Duration::from_millis(24*3600000), parse_duration("1d").unwrap()); assert_eq!(Duration::from_millis(24 * 3600000), parse_duration("1d").unwrap());
} }