Clippy fixes from stable and nightly (#13455)

- **Doccomment style fixes**
- **Forgotten stuff in `nu-pretty-hex`**
- **Don't `for` around an `Option`**
- and more

I think the suggestions here are a net positive, some of the suggestions
moved into #13498 feel somewhat arbitrary, I also raised
https://github.com/rust-lang/rust-clippy/issues/13188 as the nightly
`byte_char_slices` would require either a global allow or otherwise a
ton of granular allows or possibly confusing bytestring literals.
This commit is contained in:
Stefan Holderbach 2024-07-31 20:37:40 +02:00 committed by GitHub
parent 928c57db41
commit 42531e017c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 185 additions and 240 deletions

View File

@ -156,58 +156,34 @@ fn create_history_record(idx: usize, entry: HistoryItem, long: bool, head: Span)
//2. Create a record of either short or long columns and values //2. Create a record of either short or long columns and values
let item_id_value = Value::int( let item_id_value = Value::int(
match entry.id { entry
Some(id) => { .id
let ids = id.to_string(); .and_then(|id| id.to_string().parse::<i64>().ok())
match ids.parse::<i64>() { .unwrap_or_default(),
Ok(i) => i,
_ => 0i64,
}
}
None => 0i64,
},
head, head,
); );
let start_timestamp_value = Value::string( let start_timestamp_value = Value::string(
match entry.start_timestamp { entry
Some(time) => time.to_string(), .start_timestamp
None => "".into(), .map(|time| time.to_string())
}, .unwrap_or_default(),
head, head,
); );
let command_value = Value::string(entry.command_line, head); let command_value = Value::string(entry.command_line, head);
let session_id_value = Value::int( let session_id_value = Value::int(
match entry.session_id { entry
Some(sid) => { .session_id
let sids = sid.to_string(); .and_then(|id| id.to_string().parse::<i64>().ok())
match sids.parse::<i64>() { .unwrap_or_default(),
Ok(i) => i,
_ => 0i64,
}
}
None => 0i64,
},
head,
);
let hostname_value = Value::string(
match entry.hostname {
Some(host) => host,
None => "".into(),
},
head,
);
let cwd_value = Value::string(
match entry.cwd {
Some(cwd) => cwd,
None => "".into(),
},
head, head,
); );
let hostname_value = Value::string(entry.hostname.unwrap_or_default(), head);
let cwd_value = Value::string(entry.cwd.unwrap_or_default(), head);
let duration_value = Value::duration( let duration_value = Value::duration(
match entry.duration { entry
Some(d) => d.as_nanos().try_into().unwrap_or(0), .duration
None => 0, .and_then(|d| d.as_nanos().try_into().ok())
}, .unwrap_or(0),
head, head,
); );
let exit_status_value = Value::int(entry.exit_status.unwrap_or(0), head); let exit_status_value = Value::int(entry.exit_status.unwrap_or(0), head);

View File

@ -150,13 +150,9 @@ fn fill(
FillAlignment::Left FillAlignment::Left
}; };
let width = if let Some(arg) = width_arg { arg } else { 1 }; let width = width_arg.unwrap_or(1);
let character = if let Some(arg) = character_arg { let character = character_arg.unwrap_or_else(|| " ".to_string());
arg
} else {
" ".to_string()
};
let arg = Arguments { let arg = Arguments {
width, width,

View File

@ -141,17 +141,17 @@ pub fn request_add_authorization_header(
let login = match (user, password) { let login = match (user, password) {
(Some(user), Some(password)) => { (Some(user), Some(password)) => {
let mut enc_str = String::new(); let mut enc_str = String::new();
base64_engine.encode_string(&format!("{user}:{password}"), &mut enc_str); base64_engine.encode_string(format!("{user}:{password}"), &mut enc_str);
Some(enc_str) Some(enc_str)
} }
(Some(user), _) => { (Some(user), _) => {
let mut enc_str = String::new(); let mut enc_str = String::new();
base64_engine.encode_string(&format!("{user}:"), &mut enc_str); base64_engine.encode_string(format!("{user}:"), &mut enc_str);
Some(enc_str) Some(enc_str)
} }
(_, Some(password)) => { (_, Some(password)) => {
let mut enc_str = String::new(); let mut enc_str = String::new();
base64_engine.encode_string(&format!(":{password}"), &mut enc_str); base64_engine.encode_string(format!(":{password}"), &mut enc_str);
Some(enc_str) Some(enc_str)
} }
_ => None, _ => None,

View File

@ -3,5 +3,4 @@ mod chars;
mod dice; mod dice;
mod float; mod float;
mod int; mod int;
#[cfg(feature = "uuid_crate")]
mod uuid; mod uuid;

View File

@ -1,5 +1,5 @@
use nu_test_support::nu; use nu_test_support::nu;
use uuid_crate::Uuid; use uuid::Uuid;
#[test] #[test]
fn generates_valid_uuid4() { fn generates_valid_uuid4() {

View File

@ -169,11 +169,7 @@ pub fn parse_def_predecl(working_set: &mut StateWorkingSet, spans: &[Span]) {
// Now, pos should point at the next span after the def-like call. // Now, pos should point at the next span after the def-like call.
// Skip all potential flags, like --env, --wrapped or --help: // Skip all potential flags, like --env, --wrapped or --help:
while pos < spans.len() while pos < spans.len() && working_set.get_span_contents(spans[pos]).starts_with(b"-") {
&& working_set
.get_span_contents(spans[pos])
.starts_with(&[b'-'])
{
pos += 1; pos += 1;
} }
@ -202,12 +198,8 @@ pub fn parse_def_predecl(working_set: &mut StateWorkingSet, spans: &[Span]) {
let mut signature_pos = None; let mut signature_pos = None;
while pos < spans.len() { while pos < spans.len() {
if working_set if working_set.get_span_contents(spans[pos]).starts_with(b"[")
.get_span_contents(spans[pos]) || working_set.get_span_contents(spans[pos]).starts_with(b"(")
.starts_with(&[b'['])
|| working_set
.get_span_contents(spans[pos])
.starts_with(&[b'('])
{ {
signature_pos = Some(pos); signature_pos = Some(pos);
break; break;
@ -424,7 +416,7 @@ pub fn parse_def(
let mut decl_name_span = None; let mut decl_name_span = None;
for span in rest_spans { for span in rest_spans {
if !working_set.get_span_contents(*span).starts_with(&[b'-']) { if !working_set.get_span_contents(*span).starts_with(b"-") {
decl_name_span = Some(*span); decl_name_span = Some(*span);
break; break;
} }
@ -554,7 +546,7 @@ pub fn parse_def(
for arg_name in &signature.optional_positional { for arg_name in &signature.optional_positional {
verify_not_reserved_variable_name(working_set, &arg_name.name, sig.span); verify_not_reserved_variable_name(working_set, &arg_name.name, sig.span);
} }
for arg_name in &signature.rest_positional { if let Some(arg_name) = &signature.rest_positional {
verify_not_reserved_variable_name(working_set, &arg_name.name, sig.span); verify_not_reserved_variable_name(working_set, &arg_name.name, sig.span);
} }
for flag_name in &signature.get_names() { for flag_name in &signature.get_names() {

View File

@ -5926,7 +5926,7 @@ pub fn discover_captures_in_closure(
seen.push(var_id); seen.push(var_id);
} }
} }
for positional in &block.signature.rest_positional { if let Some(positional) = &block.signature.rest_positional {
if let Some(var_id) = positional.var_id { if let Some(var_id) = positional.var_id {
seen.push(var_id); seen.push(var_id);
} }

View File

@ -660,10 +660,10 @@ impl Path {
/// the current directory. /// the current directory.
/// ///
/// * On Unix, a path is absolute if it starts with the root, /// * On Unix, a path is absolute if it starts with the root,
/// so [`is_absolute`](Path::is_absolute) and [`has_root`](Path::has_root) are equivalent. /// so [`is_absolute`](Path::is_absolute) and [`has_root`](Path::has_root) are equivalent.
/// ///
/// * On Windows, a path is absolute if it has a prefix and starts with the root: /// * On Windows, a path is absolute if it has a prefix and starts with the root:
/// `c:\windows` is absolute, while `c:temp` and `\temp` are not. /// `c:\windows` is absolute, while `c:temp` and `\temp` are not.
/// ///
/// # Examples /// # Examples
/// ///

View File

@ -121,7 +121,7 @@ fn expand_tilde_with_another_user_home(path: &Path) -> PathBuf {
return match path.to_str() { return match path.to_str() {
Some(file_path) => { Some(file_path) => {
let mut file = file_path.to_string(); let mut file = file_path.to_string();
match file_path.find(|c| c == '/' || c == '\\') { match file_path.find(['/', '\\']) {
None => { None => {
file.remove(0); file.remove(0);
user_home_dir(&file) user_home_dir(&file)

View File

@ -1,5 +1,3 @@
// #![no_std]
//! A Rust library providing pretty hex dump. //! A Rust library providing pretty hex dump.
//! //!
//! A `simple_hex()` way renders one-line hex dump, and a `pretty_hex()` way renders //! A `simple_hex()` way renders one-line hex dump, and a `pretty_hex()` way renders
@ -59,8 +57,5 @@
//! 0018: db b1 bc 35 bf ee ...5.. //! 0018: db b1 bc 35 bf ee ...5..
//! ``` //! ```
#[cfg(feature = "alloc")]
extern crate alloc;
mod pretty_hex; mod pretty_hex;
pub use pretty_hex::*; pub use pretty_hex::*;

View File

@ -1,158 +1,147 @@
// #![no_std]
#[cfg(feature = "alloc")]
extern crate alloc;
extern crate nu_pretty_hex;
#[cfg(feature = "alloc")]
use alloc::{format, string::String, vec, vec::Vec};
use nu_pretty_hex::*; use nu_pretty_hex::*;
#[cfg(feature = "alloc")] // #[test]
#[test] // fn test_simple() {
fn test_simple() { // let bytes: Vec<u8> = (0..16).collect();
let bytes: Vec<u8> = (0..16).collect(); // let expected = "00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f";
let expected = "00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f"; // assert_eq!(expected, simple_hex(&bytes));
assert_eq!(expected, simple_hex(&bytes)); // assert_eq!(expected, bytes.hex_dump().to_string());
assert_eq!(expected, bytes.hex_dump().to_string()); // assert_eq!(simple_hex(&bytes), config_hex(&bytes, HexConfig::simple()));
assert_eq!(simple_hex(&bytes), config_hex(&bytes, HexConfig::simple())); //
// let mut have = String::new();
let mut have = String::new(); // simple_hex_write(&mut have, &bytes).unwrap();
simple_hex_write(&mut have, &bytes).unwrap(); // assert_eq!(expected, have);
assert_eq!(expected, have); //
// let str = "string";
let str = "string"; // let string: String = String::from("string");
let string: String = String::from("string"); // let slice: &[u8] = &[0x73, 0x74, 0x72, 0x69, 0x6e, 0x67];
let slice: &[u8] = &[0x73, 0x74, 0x72, 0x69, 0x6e, 0x67]; // assert_eq!(simple_hex(&str), "73 74 72 69 6e 67");
assert_eq!(simple_hex(&str), "73 74 72 69 6e 67"); // assert_eq!(simple_hex(&str), simple_hex(&string));
assert_eq!(simple_hex(&str), simple_hex(&string)); // assert_eq!(simple_hex(&str), simple_hex(&slice));
assert_eq!(simple_hex(&str), simple_hex(&slice)); //
// assert!(simple_hex(&vec![]).is_empty());
assert!(simple_hex(&vec![]).is_empty()); // }
} //
// #[test]
#[cfg(feature = "alloc")] // fn test_pretty() {
#[test] // let bytes: Vec<u8> = (0..256).map(|x| x as u8).collect();
fn test_pretty() { // let want = include_str!("256.txt");
let bytes: Vec<u8> = (0..256).map(|x| x as u8).collect(); //
let want = include_str!("256.txt"); // let mut hex = String::new();
// pretty_hex_write(&mut hex, &bytes).unwrap();
let mut hex = String::new(); // assert_eq!(want, hex);
pretty_hex_write(&mut hex, &bytes).unwrap(); // assert_eq!(want, format!("{:?}", bytes.hex_dump()));
assert_eq!(want, hex); // assert_eq!(want, pretty_hex(&bytes));
assert_eq!(want, format!("{:?}", bytes.hex_dump())); // assert_eq!(want, config_hex(&bytes, HexConfig::default()));
assert_eq!(want, pretty_hex(&bytes)); //
assert_eq!(want, config_hex(&bytes, HexConfig::default())); // assert_eq!("Length: 0 (0x0) bytes\n", pretty_hex(&vec![]));
// }
assert_eq!("Length: 0 (0x0) bytes\n", pretty_hex(&vec![])); //
} // #[test]
// fn test_config() {
#[cfg(feature = "alloc")] // let cfg = HexConfig {
#[test] // title: false,
fn test_config() { // ascii: false,
let cfg = HexConfig { // width: 0,
title: false, // group: 0,
ascii: false, // chunk: 0,
width: 0, // };
group: 0, // assert!(config_hex(&vec![], cfg).is_empty());
chunk: 0, // assert_eq!("2425262728", config_hex(&"$%&'(", cfg));
}; //
assert!(config_hex(&vec![], cfg).is_empty()); // let v = include_bytes!("data");
assert_eq!("2425262728", config_hex(&"$%&'(", cfg)); // let cfg = HexConfig {
// title: false,
let v = include_bytes!("data"); // group: 8,
let cfg = HexConfig { // ..HexConfig::default()
title: false, // };
group: 8, // let hex = "0000: 6b 4e 1a c3 af 03 d2 1e 7e 73 ba c8 bd 84 0f 83 kN......~s......\n\
..HexConfig::default() // 0010: 89 d5 cf 90 23 67 4b 48 db b1 bc 35 bf ee ....#gKH...5..";
}; // assert_eq!(hex, config_hex(&v, cfg));
let hex = "0000: 6b 4e 1a c3 af 03 d2 1e 7e 73 ba c8 bd 84 0f 83 kN......~s......\n\ // assert_eq!(hex, format!("{:?}", v.hex_conf(cfg)));
0010: 89 d5 cf 90 23 67 4b 48 db b1 bc 35 bf ee ....#gKH...5.."; // let mut str = String::new();
assert_eq!(hex, config_hex(&v, cfg)); // hex_write(&mut str, v, cfg).unwrap();
assert_eq!(hex, format!("{:?}", v.hex_conf(cfg))); // assert_eq!(hex, str);
let mut str = String::new(); //
hex_write(&mut str, v, cfg).unwrap(); // assert_eq!(
assert_eq!(hex, str); // config_hex(
// &v,
assert_eq!( // HexConfig {
config_hex( // ascii: false,
&v, // ..cfg
HexConfig { // }
ascii: false, // ),
..cfg // "0000: 6b 4e 1a c3 af 03 d2 1e 7e 73 ba c8 bd 84 0f 83\n\
} // 0010: 89 d5 cf 90 23 67 4b 48 db b1 bc 35 bf ee"
), // );
"0000: 6b 4e 1a c3 af 03 d2 1e 7e 73 ba c8 bd 84 0f 83\n\ //
0010: 89 d5 cf 90 23 67 4b 48 db b1 bc 35 bf ee" // assert_eq!(
); // config_hex(
// &v,
assert_eq!( // HexConfig {
config_hex( // ascii: false,
&v, // group: 4,
HexConfig { // chunk: 2,
ascii: false, // ..cfg
group: 4, // }
chunk: 2, // ),
..cfg // "0000: 6b4e 1ac3 af03 d21e 7e73 bac8 bd84 0f83\n\
} // 0010: 89d5 cf90 2367 4b48 dbb1 bc35 bfee"
), // );
"0000: 6b4e 1ac3 af03 d21e 7e73 bac8 bd84 0f83\n\ //
0010: 89d5 cf90 2367 4b48 dbb1 bc35 bfee" // let v: Vec<u8> = (0..21).collect();
); // let want = r##"Length: 21 (0x15) bytes
// 0000: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ................
let v: Vec<u8> = (0..21).collect(); // 0010: 10 11 12 13 14 ....."##;
let want = r##"Length: 21 (0x15) bytes // assert_eq!(want, pretty_hex(&v));
0000: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ................ //
0010: 10 11 12 13 14 ....."##; // let v: Vec<u8> = (0..13).collect();
assert_eq!(want, pretty_hex(&v)); // assert_eq!(
// config_hex(
let v: Vec<u8> = (0..13).collect(); // &v,
assert_eq!( // HexConfig {
config_hex( // title: false,
&v, // ascii: true,
HexConfig { // width: 11,
title: false, // group: 2,
ascii: true, // chunk: 3
width: 11, // }
group: 2, // ),
chunk: 3 // "0000: 000102 030405 060708 090a ...........\n\
} // 000b: 0b0c .."
), // );
"0000: 000102 030405 060708 090a ...........\n\ //
000b: 0b0c .." // let v: Vec<u8> = (0..19).collect();
); // assert_eq!(
// config_hex(
let v: Vec<u8> = (0..19).collect(); // &v,
assert_eq!( // HexConfig {
config_hex( // title: false,
&v, // ascii: true,
HexConfig { // width: 16,
title: false, // group: 3,
ascii: true, // chunk: 3
width: 16, // }
group: 3, // ),
chunk: 3 // "0000: 000102 030405 060708 090a0b 0c0d0e 0f ................\n\
} // 0010: 101112 ..."
), // );
"0000: 000102 030405 060708 090a0b 0c0d0e 0f ................\n\ //
0010: 101112 ..." // let cfg = HexConfig {
); // title: false,
// group: 0,
let cfg = HexConfig { // ..HexConfig::default()
title: false, // };
group: 0, // assert_eq!(
..HexConfig::default() // format!("{:?}", v.hex_conf(cfg)),
}; // "0000: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ................\n\
assert_eq!( // 0010: 10 11 12 ..."
format!("{:?}", v.hex_conf(cfg)), // );
"0000: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ................\n\ // assert_eq!(
0010: 10 11 12 ..." // v.hex_conf(cfg).to_string(),
); // "00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12"
assert_eq!( // );
v.hex_conf(cfg).to_string(), // }
"00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12"
);
}
// This test case checks that hex_write works even without the alloc crate. // This test case checks that hex_write works even without the alloc crate.
// Decorators to this function like simple_hex_write or PrettyHex::hex_dump() // Decorators to this function like simple_hex_write or PrettyHex::hex_dump()

View File

@ -19,12 +19,12 @@ const LINE_ENDING_PATTERN: &[char] = &['\r', '\n'];
/// We've tried a few variations of this structure. Listing these below so we have a record. /// We've tried a few variations of this structure. Listing these below so we have a record.
/// ///
/// * We tried always assuming a stream in Nushell. This was a great 80% solution, but it had some rough edges. /// * We tried always assuming a stream in Nushell. This was a great 80% solution, but it had some rough edges.
/// Namely, how do you know the difference between a single string and a list of one string. How do you know /// Namely, how do you know the difference between a single string and a list of one string. How do you know
/// when to flatten the data given to you from a data source into the stream or to keep it as an unflattened /// when to flatten the data given to you from a data source into the stream or to keep it as an unflattened
/// list? /// list?
/// ///
/// * We tried putting the stream into Value. This had some interesting properties as now commands "just worked /// * We tried putting the stream into Value. This had some interesting properties as now commands "just worked
/// on values", but lead to a few unfortunate issues. /// on values", but lead to a few unfortunate issues.
/// ///
/// The first is that you can't easily clone Values in a way that felt largely immutable. For example, if /// The first is that you can't easily clone Values in a way that felt largely immutable. For example, if
/// you cloned a Value which contained a stream, and in one variable drained some part of it, then the second /// you cloned a Value which contained a stream, and in one variable drained some part of it, then the second
@ -37,8 +37,8 @@ const LINE_ENDING_PATTERN: &[char] = &['\r', '\n'];
/// concrete list values rather than streams, and be able to view them without non-local effects. /// concrete list values rather than streams, and be able to view them without non-local effects.
/// ///
/// * A balance of the two approaches is what we've landed on: Values are thread-safe to pass, and we can stream /// * A balance of the two approaches is what we've landed on: Values are thread-safe to pass, and we can stream
/// them into any sources. Streams are still available to model the infinite streams approach of original /// them into any sources. Streams are still available to model the infinite streams approach of original
/// Nushell. /// Nushell.
#[derive(Debug)] #[derive(Debug)]
pub enum PipelineData { pub enum PipelineData {
Empty, Empty,

View File

@ -467,13 +467,12 @@ impl Signature {
/// Checks if short or long are already present /// Checks if short or long are already present
/// Panics if one of them is found /// Panics if one of them is found
fn check_names(&self, name: impl Into<String>, short: Option<char>) -> (String, Option<char>) { fn check_names(&self, name: impl Into<String>, short: Option<char>) -> (String, Option<char>) {
let s = short.map(|c| { let s = short.inspect(|c| {
assert!( assert!(
!self.get_shorts().contains(&c), !self.get_shorts().contains(c),
"There may be duplicate short flags for '-{}'", "There may be duplicate short flags for '-{}'",
c c
); );
c
}); });
let name = { let name = {

View File

@ -61,9 +61,8 @@ impl ForegroundChild {
pipeline_state: Some(pipeline_state.clone()), pipeline_state: Some(pipeline_state.clone()),
} }
}) })
.map_err(|e| { .inspect_err(|_e| {
foreground_pgroup::reset(); foreground_pgroup::reset();
e
}) })
} else { } else {
command.spawn().map(|child| Self { command.spawn().map(|child| Self {

View File

@ -12,7 +12,7 @@ use std::sync::Arc;
/// > **Note** /// > **Note**
/// > [`Span`] can be passed to [`from_nuon`] if there is context available to the caller, e.g. when /// > [`Span`] can be passed to [`from_nuon`] if there is context available to the caller, e.g. when
/// > using this function in a command implementation such as /// > using this function in a command implementation such as
/// [`from nuon`](https://www.nushell.sh/commands/docs/from_nuon.html). /// > [`from nuon`](https://www.nushell.sh/commands/docs/from_nuon.html).
/// ///
/// also see [`super::to_nuon`] for the inverse operation /// also see [`super::to_nuon`] for the inverse operation
pub fn from_nuon(input: &str, span: Option<Span>) -> Result<Value, ShellError> { pub fn from_nuon(input: &str, span: Option<Span>) -> Result<Value, ShellError> {