Fix clippy (#15489)

# Description
There are some clippy(version 0.1.86) errors on nushell repo. This pr is
trying to fix it.

# User-Facing Changes
Hopefully none.

# Tests + Formatting
NaN

# After Submitting
NaN
This commit is contained in:
Wind 2025-04-06 09:49:28 +08:00 committed by GitHub
parent 67ea25afca
commit 1c6c85d35d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
19 changed files with 30 additions and 35 deletions

View File

@ -135,7 +135,7 @@ where
(min, max) => (rhs, lhs, max, min),
};
let pad = iter::repeat(0).take(max_len - min_len);
let pad = iter::repeat_n(0, max_len - min_len);
let mut a;
let mut b;

View File

@ -249,7 +249,7 @@ fn shift_bytes_and_bits_left(data: &[u8], byte_shift: usize, bit_shift: usize) -
Last | Only => lhs << bit_shift,
_ => (lhs << bit_shift) | (rhs >> (8 - bit_shift)),
})
.chain(iter::repeat(0).take(byte_shift))
.chain(iter::repeat_n(0, byte_shift))
.collect::<Vec<u8>>()
}

View File

@ -118,7 +118,7 @@ fn increase_string_width(text: &mut String, total: usize) {
let rest = total - width;
if rest > 0 {
text.extend(std::iter::repeat(' ').take(rest));
text.extend(std::iter::repeat_n(' ', rest));
}
}

View File

@ -378,10 +378,7 @@ fn ls_for_one_pattern(
.par_bridge()
.filter_map(move |x| match x {
Ok(path) => {
let metadata = match std::fs::symlink_metadata(&path) {
Ok(metadata) => Some(metadata),
Err(_) => None,
};
let metadata = std::fs::symlink_metadata(&path).ok();
let hidden_dir_clone = Arc::clone(&hidden_dirs);
let mut hidden_dir_mutex = hidden_dir_clone
.lock()

View File

@ -243,7 +243,7 @@ mod test {
let chunks = chunk_read.map(|e| e.unwrap()).collect::<Vec<_>>();
assert_eq!(
chunks,
[s[..4].as_bytes(), s[4..8].as_bytes(), s[8..].as_bytes()]
[&s.as_bytes()[..4], &s.as_bytes()[4..8], &s.as_bytes()[8..]]
);
}
@ -260,7 +260,7 @@ mod test {
let chunks = chunk_read.map(|e| e.unwrap()).collect::<Vec<_>>();
assert_eq!(
chunks,
[s[..4].as_bytes(), s[4..8].as_bytes(), s[8..].as_bytes()]
[&s.as_bytes()[..4], &s.as_bytes()[4..8], &s.as_bytes()[8..]]
);
}

View File

@ -102,7 +102,7 @@ pub fn calculate(
mf(&new_vals?, span, name)
}
PipelineData::Value(val, ..) => mf(&[val], span, name),
PipelineData::Empty { .. } => Err(ShellError::PipelineEmpty { dst_span: name }),
PipelineData::Empty => Err(ShellError::PipelineEmpty { dst_span: name }),
val => Err(ShellError::UnsupportedInput {
msg: "Only ints, floats, lists, records, or ranges are supported".into(),
input: "value originates from here".into(),

View File

@ -723,7 +723,7 @@ fn transform_response_using_content_type(
)
})?
.path_segments()
.and_then(|segments| segments.last())
.and_then(|mut segments| segments.next_back())
.and_then(|name| if name.is_empty() { None } else { Some(name) })
.and_then(|name| {
PathBuf::from(name)

View File

@ -175,7 +175,7 @@ fn run(call: &Call, args: &Arguments, input: PipelineData) -> Result<PipelineDat
handle_value(stream.into_value(), args, head),
metadata,
)),
PipelineData::Empty { .. } => Err(ShellError::PipelineEmpty { dst_span: head }),
PipelineData::Empty => Err(ShellError::PipelineEmpty { dst_span: head }),
_ => Err(ShellError::UnsupportedInput {
msg: "Input value cannot be joined".to_string(),
input: "value originates from here".into(),

View File

@ -98,7 +98,7 @@ pub(crate) fn finish_redirection(
if !matches!(
modes.err,
Some(Spanned {
item: RedirectMode::Pipe { .. },
item: RedirectMode::Pipe,
..
})
) {

View File

@ -323,9 +323,7 @@ fn repeat_vertical(
c: char,
style: TextStyle,
) {
let text = std::iter::repeat(c)
.take(width as usize)
.collect::<String>();
let text = std::iter::repeat_n(c, width as usize).collect::<String>();
let style = text_style_to_tui_style(style);
let span = Span::styled(text, style);

View File

@ -2678,7 +2678,7 @@ pub fn parse_unit_value<'res>(
if let Some((unit, name, convert)) = unit_groups.iter().find(|x| value.ends_with(x.1)) {
let lhs_len = value.len() - name.len();
let lhs = strip_underscores(value[..lhs_len].as_bytes());
let lhs = strip_underscores(&value.as_bytes()[..lhs_len]);
let lhs_span = Span::new(span.start, span.start + lhs_len);
let unit_span = Span::new(span.start + lhs_len, span.end);
if lhs.ends_with('$') {

View File

@ -46,7 +46,7 @@ pub fn expand_ndots(path: impl AsRef<Path>) -> PathBuf {
pub fn expand_dots(path: impl AsRef<Path>) -> PathBuf {
// Check if the last component of the path is a normal component.
fn last_component_is_normal(path: &Path) -> bool {
matches!(path.components().last(), Some(Component::Normal(_)))
matches!(path.components().next_back(), Some(Component::Normal(_)))
}
let path = path.as_ref();
@ -61,7 +61,7 @@ pub fn expand_dots(path: impl AsRef<Path>) -> PathBuf {
// no-op
}
_ => {
let prev_component = result.components().last();
let prev_component = result.components().next_back();
if prev_component == Some(Component::RootDir) && component == Component::ParentDir {
continue;
}

View File

@ -29,7 +29,7 @@ fn expand_tilde_with_home(path: impl AsRef<Path>, home: Option<PathBuf>) -> Path
};
}
let path_last_char = path.as_os_str().to_string_lossy().chars().last();
let path_last_char = path.as_os_str().to_string_lossy().chars().next_back();
let need_trailing_slash = path_last_char == Some('/') || path_last_char == Some('\\');
match home {
@ -94,7 +94,7 @@ fn user_home_dir(username: &str) -> PathBuf {
if !cfg!(target_os = "android")
&& expected_path
.components()
.last()
.next_back()
.map(|last| last != Component::Normal(username.as_ref()))
.unwrap_or(false)
{

View File

@ -884,7 +884,7 @@ impl<'a> StateWorkingSet<'a> {
.active_overlay_names(&mut removed_overlays)
.iter()
.rev()
.last()
.next_back()
{
return last_name;
}
@ -900,7 +900,7 @@ impl<'a> StateWorkingSet<'a> {
if let Some(last_overlay) = scope_frame
.active_overlays(&mut removed_overlays)
.rev()
.last()
.next_back()
{
return last_overlay;
}

View File

@ -88,7 +88,7 @@ pub fn lev_distance_with_substrings(a: &str, b: &str, limit: usize) -> Option<us
1 // Exact substring match, but not a total word match so return non-zero
} else if !big_len_diff {
// Not a big difference in length, discount cost of length difference
score + (len_diff + 1) / 2
score + len_diff.div_ceil(2)
} else {
// A big difference in length, add back the difference in length to the score
score + len_diff

View File

@ -133,7 +133,7 @@ pub trait FromValue: Sized {
Type::Custom(
any::type_name::<Self>()
.split(':')
.last()
.next_back()
.expect("str::split returns an iterator with at least one element")
.to_string()
.into_boxed_str(),

View File

@ -119,7 +119,7 @@ fn build_vertical_map(record: Record, config: &Config) -> TableValue {
fn string_append_to_width(key: &mut String, max: usize) {
let width = string_width(key);
let rest = max - width;
key.extend(std::iter::repeat(' ').take(rest));
key.extend(std::iter::repeat_n(' ', rest));
}
fn build_vertical_array(vals: Vec<Value>, config: &Config) -> TableValue {

View File

@ -39,15 +39,15 @@
//! that dictate how the grid is formatted:
//!
//! - `filling`: what to put in between two columns — either a number of
//! spaces, or a text string;
//! spaces, or a text string;
//! - `direction`, which specifies whether the cells should go along
//! rows, or columns:
//! rows, or columns:
//! - `Direction::LeftToRight` starts them in the top left and
//! moves *rightwards*, going to the start of a new row after reaching the
//! final column;
//! moves *rightwards*, going to the start of a new row after reaching the
//! final column;
//! - `Direction::TopToBottom` starts them in the top left and moves
//! *downwards*, going to the top of a new column after reaching the final
//! row.
//! *downwards*, going to the top of a new column after reaching the final
//! row.
//!
//!
//! ## Displaying a grid
@ -93,7 +93,7 @@
use std::cmp::max;
use std::fmt;
use std::iter::repeat;
use std::iter::repeat_n;
use unicode_width::UnicodeWidthStr;
fn unicode_width_strip_ansi(astring: &str) -> usize {
@ -290,7 +290,7 @@ impl Grid {
}
fn column_widths(&self, num_lines: usize, num_columns: usize) -> Dimensions {
let mut widths: Vec<Width> = repeat(0).take(num_columns).collect();
let mut widths: Vec<Width> = repeat_n(0, num_columns).collect();
for (index, cell) in self.cells.iter().enumerate() {
let index = match self.options.direction {
Direction::LeftToRight => index % num_columns,

View File

@ -317,7 +317,7 @@ impl NuDataFrame {
let series = self.as_series(span)?;
let column = conversion::create_column_from_series(&series, row, row + 1, span)?;
if column.len() == 0 {
if column.is_empty() {
Err(ShellError::AccessEmptyContent { span })
} else {
let value = column