Fix a bunch of future clippy warnings (#3586)

* Fix a bunch of future clippy warnings

* Fix a bunch of future clippy warnings
This commit is contained in:
JT 2021-06-10 07:08:12 +12:00 committed by GitHub
parent e8a2250ef8
commit 383e874166
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
86 changed files with 237 additions and 258 deletions

View File

@ -320,7 +320,7 @@ impl fmt::Display for Infix {
let f: &mut dyn fmt::Write = f; let f: &mut dyn fmt::Write = f;
write!(f, "{}{}", RESET, self.1.prefix()) write!(f, "{}{}", RESET, self.1.prefix())
} }
Difference::NoDifference => { Difference::Empty => {
Ok(()) // nothing to write Ok(()) // nothing to write
} }
} }

View File

@ -14,7 +14,7 @@ pub enum Difference {
/// The before style is exactly the same as the after style, so no further /// The before style is exactly the same as the after style, so no further
/// control codes need to be printed. /// control codes need to be printed.
NoDifference, Empty,
} }
impl Difference { impl Difference {
@ -40,7 +40,7 @@ impl Difference {
// it commented out for now, and defaulting to Reset. // it commented out for now, and defaulting to Reset.
if first == next { if first == next {
return NoDifference; return Empty;
} }
// Cannot un-bold, so must Reset. // Cannot un-bold, so must Reset.
@ -153,10 +153,10 @@ mod test {
}; };
} }
test!(nothing: Green.normal(); Green.normal() => NoDifference); test!(nothing: Green.normal(); Green.normal() => Empty);
test!(uppercase: Green.normal(); Green.bold() => ExtraStyles(style().bold())); test!(uppercase: Green.normal(); Green.bold() => ExtraStyles(style().bold()));
test!(lowercase: Green.bold(); Green.normal() => Reset); test!(lowercase: Green.bold(); Green.normal() => Reset);
test!(nothing2: Green.bold(); Green.bold() => NoDifference); test!(nothing2: Green.bold(); Green.bold() => Empty);
test!(color_change: Red.normal(); Blue.normal() => ExtraStyles(Blue.normal())); test!(color_change: Red.normal(); Blue.normal() => ExtraStyles(Blue.normal()));

View File

@ -266,7 +266,7 @@ where
match Difference::between(&window[0].style, &window[1].style) { match Difference::between(&window[0].style, &window[1].style) {
ExtraStyles(style) => write!(w, "{}", style.prefix())?, ExtraStyles(style) => write!(w, "{}", style.prefix())?,
Reset => write!(w, "{}{}", RESET, window[1].style.prefix())?, Reset => write!(w, "{}{}", RESET, window[1].style.prefix())?,
NoDifference => { /* Do nothing! */ } Empty => { /* Do nothing! */ }
} }
w.write_str(&window[1].string)?; w.write_str(&window[1].string)?;

View File

@ -43,7 +43,7 @@ pub fn unstyle(strs: &AnsiStrings) -> String {
let mut s = String::new(); let mut s = String::new();
for i in strs.0.iter() { for i in strs.0.iter() {
s += &i.deref(); s += i.deref();
} }
s s

View File

@ -307,7 +307,7 @@ pub fn cli(context: EvaluationContext, options: Options) -> Result<(), Box<dyn E
let mut initial_command = Some(String::new()); let mut initial_command = Some(String::new());
let mut readline = Err(ReadlineError::Eof); let mut readline = Err(ReadlineError::Eof);
while let Some(ref cmd) = initial_command { while let Some(ref cmd) = initial_command {
readline = rl.readline_with_initial(&prompt, (&cmd, "")); readline = rl.readline_with_initial(&prompt, (cmd, ""));
initial_command = None; initial_command = None;
} }
@ -479,7 +479,7 @@ pub fn parse_and_eval(line: &str, ctx: &EvaluationContext) -> Result<String, She
// TODO ensure the command whose examples we're testing is actually in the pipeline // TODO ensure the command whose examples we're testing is actually in the pipeline
ctx.scope.enter_scope(); ctx.scope.enter_scope();
let (classified_block, err) = nu_parser::parse(&line, 0, &ctx.scope); let (classified_block, err) = nu_parser::parse(line, 0, &ctx.scope);
if let Some(err) = err { if let Some(err) = err {
ctx.scope.exit_scope(); ctx.scope.exit_scope();
return Err(err.into()); return Err(err.into());

View File

@ -270,12 +270,11 @@ pub fn completion_location(line: &str, block: &Block, pos: usize) -> Vec<Complet
} }
if line[start..pos].contains(BEFORE_COMMAND_CHARS) { if line[start..pos].contains(BEFORE_COMMAND_CHARS) {
locations.push(LocationType::Command.spanned(Span::new(pos, pos))); locations.push(LocationType::Command.spanned(Span::new(pos, pos)));
locations
} else { } else {
// TODO this should be able to be mapped to a command // TODO this should be able to be mapped to a command
locations.push(LocationType::Argument(command, None).spanned(Span::new(pos, pos))); locations.push(LocationType::Argument(command, None).spanned(Span::new(pos, pos)));
locations
} }
locations
} else { } else {
// Cursor is before any possible completion location, so must be a command // Cursor is before any possible completion location, so must be a command
vec![LocationType::Command.spanned(Span::unknown())] vec![LocationType::Command.spanned(Span::unknown())]

View File

@ -60,7 +60,7 @@ impl rustyline::completion::Completer for Helper {
impl rustyline::hint::Hinter for Helper { impl rustyline::hint::Hinter for Helper {
type Hint = String; type Hint = String;
fn hint(&self, line: &str, pos: usize, ctx: &rustyline::Context<'_>) -> Option<String> { fn hint(&self, line: &str, pos: usize, ctx: &rustyline::Context<'_>) -> Option<String> {
self.hinter.as_ref().and_then(|h| h.hint(line, pos, &ctx)) self.hinter.as_ref().and_then(|h| h.hint(line, pos, ctx))
} }
} }
@ -166,7 +166,7 @@ mod tests {
let helper = Helper::new(EvaluationContext::basic(), None); let helper = Helper::new(EvaluationContext::basic(), None);
helper.update(&mut buffer, "cd ".len(), &replacement); helper.update(&mut buffer, "cd ".len(), replacement);
assert_eq!( assert_eq!(
buffer.as_str(), buffer.as_str(),
@ -186,7 +186,7 @@ mod tests {
let helper = Helper::new(EvaluationContext::basic(), None); let helper = Helper::new(EvaluationContext::basic(), None);
helper.update(&mut buffer, "cd ".len(), &replacement); helper.update(&mut buffer, "cd ".len(), replacement);
assert_eq!( assert_eq!(
buffer.as_str(), buffer.as_str(),

View File

@ -326,7 +326,7 @@ fn get_result_shape_of_math_expr(
for expr in &[&bin.left, &bin.right] { for expr in &[&bin.left, &bin.right] {
let shape = match &expr.expr { let shape = match &expr.expr {
Expression::Binary(deep_binary) => { Expression::Binary(deep_binary) => {
get_result_shape_of_math_expr(&deep_binary, (pipeline_idx, pipeline), scope)? get_result_shape_of_math_expr(deep_binary, (pipeline_idx, pipeline), scope)?
} }
_ => get_shape_of_expr(expr), _ => get_shape_of_expr(expr),
}; };
@ -537,19 +537,19 @@ impl VarSyntaxShapeDeductor {
} }
Expression::Block(b) => { Expression::Block(b) => {
trace!("Inferring vars in block"); trace!("Inferring vars in block");
self.infer_shape(&b, scope)?; self.infer_shape(b, scope)?;
} }
Expression::FullColumnPath(path) => { Expression::FullColumnPath(path) => {
trace!("Inferring vars in path"); trace!("Inferring vars in path");
match &path.head.expr { match &path.head.expr {
//PathMember can't be var yet (?) //PathMember can't be var yet (?)
//TODO Iterate over path parts and find var when implemented //TODO Iterate over path parts and find var when implemented
Expression::Subexpression(b) => self.infer_shape(&b, scope)?, Expression::Subexpression(b) => self.infer_shape(b, scope)?,
Expression::Variable(var_name, span) => { Expression::Variable(var_name, span) => {
self.checked_insert( self.checked_insert(
&VarUsage::new(var_name, span), &VarUsage::new(var_name, span),
VarShapeDeduction::from_usage_with_alternatives( VarShapeDeduction::from_usage_with_alternatives(
&span, span,
&get_shapes_allowed_in_path(), &get_shapes_allowed_in_path(),
), ),
)?; )?;
@ -573,9 +573,9 @@ impl VarSyntaxShapeDeductor {
if let Some(range_right) = &range.right { if let Some(range_right) = &range.right {
if let Expression::Variable(var_name, span) = &range_right.expr { if let Expression::Variable(var_name, span) = &range_right.expr {
self.checked_insert( self.checked_insert(
&VarUsage::new(&var_name, &spanned_expr.span), &VarUsage::new(var_name, &spanned_expr.span),
VarShapeDeduction::from_usage_with_alternatives( VarShapeDeduction::from_usage_with_alternatives(
&span, span,
&get_shapes_allowed_in_range(), &get_shapes_allowed_in_range(),
), ),
)?; )?;
@ -745,7 +745,7 @@ impl VarSyntaxShapeDeductor {
let shapes = get_shapes_decay_able_to_bool(); let shapes = get_shapes_decay_able_to_bool();
// shapes.push(SyntaxShape::Math); // shapes.push(SyntaxShape::Math);
self.checked_insert( self.checked_insert(
&var, var,
VarShapeDeduction::from_usage_with_alternatives(&var.span, &shapes), VarShapeDeduction::from_usage_with_alternatives(&var.span, &shapes),
)?; )?;
} }
@ -765,7 +765,7 @@ impl VarSyntaxShapeDeductor {
let shapes_in_list = self.get_shapes_in_list_or_insert_dependency( let shapes_in_list = self.get_shapes_in_list_or_insert_dependency(
var, var,
bin_spanned, bin_spanned,
&list, list,
(pipeline_idx, pipeline), (pipeline_idx, pipeline),
); );
match shapes_in_list { match shapes_in_list {
@ -879,7 +879,7 @@ impl VarSyntaxShapeDeductor {
var, var,
VarShapeDeduction::from_usage_with_alternatives( VarShapeDeduction::from_usage_with_alternatives(
&var.span, &var.span,
&MULT_DIV_LOOKUP_TABLE MULT_DIV_LOOKUP_TABLE
.get(&(op, var_side, shape)) .get(&(op, var_side, shape))
.expect("shape is unit, number or int. Would have failed in parsing stage otherwise") .expect("shape is unit, number or int. Would have failed in parsing stage otherwise")
), ),
@ -971,7 +971,7 @@ impl VarSyntaxShapeDeductor {
let mut new_deductions = new_deductions; let mut new_deductions = new_deductions;
new_deductions.sort_unstable_by(|a, b| (a.deduction as i32).cmp(&(b.deduction as i32))); new_deductions.sort_unstable_by(|a, b| (a.deduction as i32).cmp(&(b.deduction as i32)));
let (insert_k, insert_v) = match self.inferences.get_key_value(&var_usage) { let (insert_k, insert_v) = match self.inferences.get_key_value(var_usage) {
Some((k, existing_deductions)) => { Some((k, existing_deductions)) => {
let Deduction::VarShapeDeduction(existing_deductions) = existing_deductions; let Deduction::VarShapeDeduction(existing_deductions) = existing_deductions;

View File

@ -183,9 +183,9 @@ fn add_months_of_year_to_table(
} }
let add_month_to_table_result = add_month_to_table( let add_month_to_table_result = add_month_to_table(
&args, args,
&mut calendar_vec_deque, &mut calendar_vec_deque,
&tag, tag,
selected_year, selected_year,
month_number, month_number,
new_current_day_option, new_current_day_option,

View File

@ -625,26 +625,26 @@ mod tests {
#[test] #[test]
fn checks_quotes_from_argument_to_be_passed_in() { fn checks_quotes_from_argument_to_be_passed_in() {
assert_eq!(argument_is_quoted(""), false); assert!(!argument_is_quoted(""));
assert_eq!(argument_is_quoted("'"), false); assert!(!argument_is_quoted("'"));
assert_eq!(argument_is_quoted("'a"), false); assert!(!argument_is_quoted("'a"));
assert_eq!(argument_is_quoted("a"), false); assert!(!argument_is_quoted("a"));
assert_eq!(argument_is_quoted("a'"), false); assert!(!argument_is_quoted("a'"));
assert_eq!(argument_is_quoted("''"), true); assert!(argument_is_quoted("''"));
assert_eq!(argument_is_quoted(r#"""#), false); assert!(!argument_is_quoted(r#"""#));
assert_eq!(argument_is_quoted(r#""a"#), false); assert!(!argument_is_quoted(r#""a"#));
assert_eq!(argument_is_quoted(r#"a"#), false); assert!(!argument_is_quoted(r#"a"#));
assert_eq!(argument_is_quoted(r#"a""#), false); assert!(!argument_is_quoted(r#"a""#));
assert_eq!(argument_is_quoted(r#""""#), true); assert!(argument_is_quoted(r#""""#));
assert_eq!(argument_is_quoted("'andrés"), false); assert!(!argument_is_quoted("'andrés"));
assert_eq!(argument_is_quoted("andrés'"), false); assert!(!argument_is_quoted("andrés'"));
assert_eq!(argument_is_quoted(r#""andrés"#), false); assert!(!argument_is_quoted(r#""andrés"#));
assert_eq!(argument_is_quoted(r#"andrés""#), false); assert!(!argument_is_quoted(r#"andrés""#));
assert_eq!(argument_is_quoted("'andrés'"), true); assert!(argument_is_quoted("'andrés'"));
assert_eq!(argument_is_quoted(r#""andrés""#), true); assert!(argument_is_quoted(r#""andrés""#));
} }
#[test] #[test]

View File

@ -73,7 +73,7 @@ impl Iterator for EachGroupIterator {
let mut group = vec![]; let mut group = vec![];
let mut current_count = 0; let mut current_count = 0;
while let Some(next) = self.input.next() { for next in &mut self.input {
group.push(next); group.push(next);
current_count += 1; current_count += 1;

View File

@ -85,7 +85,7 @@ fn flat_value(
} = value } = value
{ {
if column_requested.is_none() && !columns.is_empty() { if column_requested.is_none() && !columns.is_empty() {
if out.contains_key(&column) { if out.contains_key(column) {
out.insert_value(format!("{}_{}", column, column), value.clone()); out.insert_value(format!("{}_{}", column, column), value.clone());
} else { } else {
out.insert_value(column, value.clone()); out.insert_value(column, value.clone());
@ -141,7 +141,7 @@ fn flat_value(
} }
} else if a_table.is_none() { } else if a_table.is_none() {
a_table = Some(TableInside::Entries( a_table = Some(TableInside::Entries(
&column, column,
&value.tag, &value.tag,
value.table_entries().collect(), value.table_entries().collect(),
)) ))

View File

@ -56,7 +56,7 @@ fn format_command(args: CommandArgs) -> Result<OutputStream, ShellError> {
for command in &*commands { for command in &*commands {
match command { match command {
FormatCommand::Text(s) => { FormatCommand::Text(s) => {
output.push_str(&s); output.push_str(s);
} }
FormatCommand::Column(c) => { FormatCommand::Column(c) => {
// FIXME: use the correct spans // FIXME: use the correct spans
@ -97,7 +97,7 @@ fn format(input: &str) -> Vec<FormatCommand> {
loop { loop {
let mut before = String::new(); let mut before = String::new();
while let Some(c) = loop_input.next() { for c in &mut loop_input {
if c == '{' { if c == '{' {
break; break;
} }
@ -110,7 +110,7 @@ fn format(input: &str) -> Vec<FormatCommand> {
// Look for column as we're now at one // Look for column as we're now at one
let mut column = String::new(); let mut column = String::new();
while let Some(c) = loop_input.next() { for c in &mut loop_input {
if c == '}' { if c == '}' {
break; break;
} }

View File

@ -102,7 +102,7 @@ fn from_eml(args: CommandArgs) -> Result<OutputStream, ShellError> {
} }
for HeaderField { name, value } in eml.headers.iter() { for HeaderField { name, value } in eml.headers.iter() {
dict.insert_untagged(name, headerfieldvalue_to_value(&tag, &value)); dict.insert_untagged(name, headerfieldvalue_to_value(&tag, value));
} }
if let Some(body) = eml.body { if let Some(body) = eml.body {

View File

@ -60,7 +60,7 @@ fn from_node_to_value(n: &roxmltree::Node, tag: impl Into<Tag>) -> Value {
let mut collected = TaggedDictBuilder::new(&tag); let mut collected = TaggedDictBuilder::new(&tag);
let attribute_value: Value = from_attributes_to_value(&n.attributes(), &tag); let attribute_value: Value = from_attributes_to_value(n.attributes(), &tag);
let mut row = TaggedDictBuilder::new(&tag); let mut row = TaggedDictBuilder::new(&tag);
row.insert_untagged( row.insert_untagged(

View File

@ -99,7 +99,7 @@ fn convert_yaml_value_to_nu_value(
.first() .first()
.and_then(|e| match e { .and_then(|e| match e {
(serde_yaml::Value::String(s), serde_yaml::Value::Null) => Some( (serde_yaml::Value::String(s), serde_yaml::Value::Null) => Some(
UntaggedValue::string("{{ ".to_owned() + &s + " }}") UntaggedValue::string("{{ ".to_owned() + s + " }}")
.into_value(tag), .into_value(tag),
), ),
_ => None, _ => None,

View File

@ -120,7 +120,7 @@ pub fn get_column_path(path: &ColumnPath, obj: &Value) -> Result<Value, ShellErr
_ => {} _ => {}
} }
if let Some(suggestions) = did_you_mean(&obj_source, column_path_tried.as_string()) { if let Some(suggestions) = did_you_mean(obj_source, column_path_tried.as_string()) {
ShellError::labeled_error( ShellError::labeled_error(
"Unknown column", "Unknown column",
format!("did you mean '{}'?", suggestions[0]), format!("did you mean '{}'?", suggestions[0]),
@ -146,7 +146,7 @@ pub fn get_column_path_from_table_error(
let suggestions: IndexSet<_> = rows let suggestions: IndexSet<_> = rows
.iter() .iter()
.filter_map(|r| did_you_mean(&r, column_path_tried.as_string())) .filter_map(|r| did_you_mean(r, column_path_tried.as_string()))
.map(|s| s[0].to_owned()) .map(|s| s[0].to_owned())
.collect(); .collect();
let mut existing_columns: IndexSet<_> = IndexSet::default(); let mut existing_columns: IndexSet<_> = IndexSet::default();
@ -223,7 +223,7 @@ pub fn get_column_from_row_error(
} => { } => {
let primary_label = format!("There isn't a column named '{}'", &column); let primary_label = format!("There isn't a column named '{}'", &column);
did_you_mean(&obj_source, column_path_tried.as_string()).map(|suggestions| { did_you_mean(obj_source, column_path_tried.as_string()).map(|suggestions| {
ShellError::labeled_error_with_secondary( ShellError::labeled_error_with_secondary(
"Unknown column", "Unknown column",
primary_label, primary_label,

View File

@ -241,16 +241,16 @@ pub fn group(
let block = Box::new(move |_, row: &Value| { let block = Box::new(move |_, row: &Value| {
match row.get_data_by_key(column_name.borrow_spanned()) { match row.get_data_by_key(column_name.borrow_spanned()) {
Some(group_key) => Ok(as_string(&group_key)?), Some(group_key) => Ok(as_string(&group_key)?),
None => Err(suggestions(column_name.borrow_tagged(), &row)), None => Err(suggestions(column_name.borrow_tagged(), row)),
} }
}); });
nu_data::utils::group(&values, &Some(block), &name) nu_data::utils::group(values, &Some(block), &name)
} }
Grouper::ByColumn(None) => { Grouper::ByColumn(None) => {
let block = Box::new(move |_, row: &Value| as_string(row)); let block = Box::new(move |_, row: &Value| as_string(row));
nu_data::utils::group(&values, &Some(block), &name) nu_data::utils::group(values, &Some(block), &name)
} }
Grouper::ByBlock => Err(ShellError::unimplemented( Grouper::ByBlock => Err(ShellError::unimplemented(
"Block not implemented: This should never happen.", "Block not implemented: This should never happen.",

View File

@ -91,7 +91,7 @@ pub fn group_by_date(args: CommandArgs) -> Result<OutputStream, ShellError> {
let block = Box::new(move |_, row: &Value| { let block = Box::new(move |_, row: &Value| {
let group_key = row let group_key = row
.get_data_by_key(column_name.borrow_spanned()) .get_data_by_key(column_name.borrow_spanned())
.ok_or_else(|| suggestions(column_name.borrow_tagged(), &row)); .ok_or_else(|| suggestions(column_name.borrow_tagged(), row));
group_key?.format("%Y-%m-%d") group_key?.format("%Y-%m-%d")
}); });
@ -107,7 +107,7 @@ pub fn group_by_date(args: CommandArgs) -> Result<OutputStream, ShellError> {
let block = Box::new(move |_, row: &Value| { let block = Box::new(move |_, row: &Value| {
let group_key = row let group_key = row
.get_data_by_key(column_name.borrow_spanned()) .get_data_by_key(column_name.borrow_spanned())
.ok_or_else(|| suggestions(column_name.borrow_tagged(), &row)); .ok_or_else(|| suggestions(column_name.borrow_tagged(), row));
group_key?.format(&fmt) group_key?.format(&fmt)
}); });

View File

@ -48,7 +48,7 @@ fn help(args: CommandArgs) -> Result<ActionStream, ShellError> {
// Internal only commands shouldn't be displayed // Internal only commands shouldn't be displayed
.filter(|cmd_name| { .filter(|cmd_name| {
scope scope
.get_command(&cmd_name) .get_command(cmd_name)
.filter(|command| !command.is_internal()) .filter(|command| !command.is_internal())
.is_some() .is_some()
}) })
@ -63,7 +63,7 @@ fn help(args: CommandArgs) -> Result<ActionStream, ShellError> {
) -> Result<(), ShellError> { ) -> Result<(), ShellError> {
let document_tag = rest[0].tag.clone(); let document_tag = rest[0].tag.clone();
let value = command_dict( let value = command_dict(
scope.get_command(&cmd_name).ok_or_else(|| { scope.get_command(cmd_name).ok_or_else(|| {
ShellError::labeled_error( ShellError::labeled_error(
format!("Could not load {}", cmd_name), format!("Could not load {}", cmd_name),
"could not load command", "could not load command",

View File

@ -165,11 +165,9 @@ pub fn histogram(args: CommandArgs) -> Result<ActionStream, ShellError> {
); );
fact.insert_untagged("percentage", UntaggedValue::string(fmt_percentage)); fact.insert_untagged("percentage", UntaggedValue::string(fmt_percentage));
let string = std::iter::repeat("*") let string = "*".repeat(percentage.as_u64().map_err(|_| {
.take(percentage.as_u64().map_err(|_| { ShellError::labeled_error("expected a number", "expected a number", &name)
ShellError::labeled_error("expected a number", "expected a number", &name) })? as usize);
})? as usize)
.collect::<String>();
fact.insert_untagged(&frequency_column_name, UntaggedValue::string(string)); fact.insert_untagged(&frequency_column_name, UntaggedValue::string(string));
@ -209,7 +207,7 @@ fn splitter(
)), )),
} }
}), }),
None => Box::new(move |_, row: &Value| nu_value_ext::as_string(&row)), None => Box::new(move |_, row: &Value| nu_value_ext::as_string(row)),
} }
} }

View File

@ -101,7 +101,7 @@ fn if_command(raw_args: CommandArgs) -> Result<OutputStream, ShellError> {
context.scope.add_vars(&condition.captured.entries); context.scope.add_vars(&condition.captured.entries);
//FIXME: should we use the scope that's brought in as well? //FIXME: should we use the scope that's brought in as well?
let condition = evaluate_baseline_expr(&cond, &*context); let condition = evaluate_baseline_expr(cond, &*context);
match condition { match condition {
Ok(condition) => match condition.as_bool() { Ok(condition) => match condition.as_bool() {
Ok(b) => { Ok(b) => {

View File

@ -98,7 +98,7 @@ pub fn letcmd(args: CommandArgs) -> Result<ActionStream, ShellError> {
}; };
ctx.scope.enter_scope(); ctx.scope.enter_scope();
let value = evaluate_baseline_expr(&expr, &ctx); let value = evaluate_baseline_expr(expr, &ctx);
ctx.scope.exit_scope(); ctx.scope.exit_scope();
let value = value?; let value = value?;

View File

@ -46,7 +46,7 @@ pub fn mode(values: &[Value], name: &Tag) -> Result<Value, ShellError> {
let mut max_freq = -1; let mut max_freq = -1;
let mut modes = Vec::<Value>::new(); let mut modes = Vec::<Value>::new();
for (value, frequency) in frequency_map.iter() { for (value, frequency) in frequency_map.iter() {
match max_freq.cmp(&frequency) { match max_freq.cmp(frequency) {
Ordering::Less => { Ordering::Less => {
max_freq = *frequency; max_freq = *frequency;
modes.clear(); modes.clear();

View File

@ -60,7 +60,7 @@ pub fn run_with_numerical_functions_on_stream(
pub fn calculate(values: &[Value], name: &Tag, mf: MathFunction) -> Result<Value, ShellError> { pub fn calculate(values: &[Value], name: &Tag, mf: MathFunction) -> Result<Value, ShellError> {
if values.iter().all(|v| v.is_primitive()) { if values.iter().all(|v| v.is_primitive()) {
mf(&values, &name) mf(values, name)
} else { } else {
// If we are not dealing with Primitives, then perhaps we are dealing with a table // If we are not dealing with Primitives, then perhaps we are dealing with a table
// Create a key for each column name // Create a key for each column name
@ -78,7 +78,7 @@ pub fn calculate(values: &[Value], name: &Tag, mf: MathFunction) -> Result<Value
// The mathematical function operates over the columns of the table // The mathematical function operates over the columns of the table
let mut column_totals = IndexMap::new(); let mut column_totals = IndexMap::new();
for (col_name, col_vals) in column_values { for (col_name, col_vals) in column_values {
if let Ok(out) = mf(&col_vals, &name) { if let Ok(out) = mf(&col_vals, name) {
column_totals.insert(col_name, out); column_totals.insert(col_name, out);
} }
} }

View File

@ -181,7 +181,7 @@ where
let cloned_args = Arc::clone(&args); let cloned_args = Arc::clone(&args);
ret = match ret.swap_data_by_column_path( ret = match ret.swap_data_by_column_path(
path, path,
Box::new(move |old| handle_value(&action, &old, span, cloned_args)), Box::new(move |old| handle_value(&action, old, span, cloned_args)),
) { ) {
Ok(v) => v, Ok(v) => v,
Err(e) => Value::error(e), Err(e) => Value::error(e),

View File

@ -77,14 +77,12 @@ fn roll_by(value: Value, options: &Arguments) -> Option<Vec<Value>> {
let direction = options.direction(); let direction = options.direction();
if value.is_row() { if value.is_row() {
let columns = value.data_descriptors();
if options.move_headers() { if options.move_headers() {
let columns = value.data_descriptors();
if let Some(fields) = rotate(columns, &options.by, direction) { if let Some(fields) = rotate(columns, &options.by, direction) {
return Some(vec![select_fields(&value, &fields, &tag)]); return Some(vec![select_fields(&value, &fields, &tag)]);
} }
} else { } else {
let columns = value.data_descriptors();
let values_rotated = rotate( let values_rotated = rotate(
value value
.row_entries() .row_entries()

View File

@ -135,7 +135,7 @@ fn maybe_autocd_dir(cmd: &ExternalCommand, ctx: &mut EvaluationContext) -> Optio
|| (cmd.args.is_empty() || (cmd.args.is_empty()
&& PathBuf::from(name).is_dir() && PathBuf::from(name).is_dir()
&& dunce::canonicalize(name).is_ok() && dunce::canonicalize(name).is_ok()
&& !ctx.host.lock().is_external_cmd(&name)) && !ctx.host.lock().is_external_cmd(name))
{ {
Some(name) Some(name)
} else { } else {

View File

@ -65,7 +65,7 @@ fn select(args: CommandArgs) -> Result<OutputStream, ShellError> {
for path in &columns { for path in &columns {
let fetcher = get_data_by_column_path( let fetcher = get_data_by_column_path(
&value, &value,
&path, path,
move |obj_source, path_member_tried, error| { move |obj_source, path_member_tried, error| {
if let PathMember { if let PathMember {
unspanned: UnspannedPathMember::String(column), unspanned: UnspannedPathMember::String(column),

View File

@ -71,16 +71,16 @@ pub fn split(
let block = Box::new(move |_, row: &Value| { let block = Box::new(move |_, row: &Value| {
match row.get_data_by_key(column_name.borrow_spanned()) { match row.get_data_by_key(column_name.borrow_spanned()) {
Some(group_key) => Ok(as_string(&group_key)?), Some(group_key) => Ok(as_string(&group_key)?),
None => Err(suggestions(column_name.borrow_tagged(), &row)), None => Err(suggestions(column_name.borrow_tagged(), row)),
} }
}); });
nu_data::utils::split(&values, &Some(block), &name) nu_data::utils::split(values, &Some(block), &name)
} }
Grouper::ByColumn(None) => { Grouper::ByColumn(None) => {
let block = Box::new(move |_, row: &Value| as_string(row)); let block = Box::new(move |_, row: &Value| as_string(row));
nu_data::utils::split(&values, &Some(block), &name) nu_data::utils::split(values, &Some(block), &name)
} }
} }
} }

View File

@ -62,7 +62,7 @@ pub fn collect(args: CommandArgs) -> Result<ActionStream, ShellError> {
match strings { match strings {
Ok(strings) => { Ok(strings) => {
let output = strings.join(&separator); let output = strings.join(separator);
Ok(ActionStream::one(ReturnSuccess::value( Ok(ActionStream::one(ReturnSuccess::value(
UntaggedValue::string(output).into_value(tag), UntaggedValue::string(output).into_value(tag),

View File

@ -114,7 +114,7 @@ mod tests {
let pattern = ".toml"; let pattern = ".toml";
let expected = UntaggedValue::boolean(true).into_untagged_value(); let expected = UntaggedValue::boolean(true).into_untagged_value();
let actual = action(&word, &pattern, Tag::unknown()).unwrap(); let actual = action(&word, pattern, Tag::unknown()).unwrap();
assert_eq!(actual, expected); assert_eq!(actual, expected);
} }
@ -124,7 +124,7 @@ mod tests {
let pattern = "Car"; let pattern = "Car";
let expected = UntaggedValue::boolean(false).into_untagged_value(); let expected = UntaggedValue::boolean(false).into_untagged_value();
let actual = action(&word, &pattern, Tag::unknown()).unwrap(); let actual = action(&word, pattern, Tag::unknown()).unwrap();
assert_eq!(actual, expected); assert_eq!(actual, expected);
} }
} }

View File

@ -101,7 +101,7 @@ fn action(
) -> Result<Value, ShellError> { ) -> Result<Value, ShellError> {
match &input.value { match &input.value {
UntaggedValue::Primitive(Primitive::String(s)) => { UntaggedValue::Primitive(Primitive::String(s)) => {
let FindReplace(find, replacement) = FindReplace(&find, &replace); let FindReplace(find, replacement) = FindReplace(find, replace);
let regex = Regex::new(find); let regex = Regex::new(find);
Ok(match regex { Ok(match regex {

View File

@ -138,7 +138,7 @@ fn action(
None => UntaggedValue::string("").into_value(&tag), None => UntaggedValue::string("").into_value(&tag),
}; };
let r = process_range(&input, &range)?; let r = process_range(input, &range)?;
match &input.value { match &input.value {
UntaggedValue::Primitive(Primitive::String(s)) => { UntaggedValue::Primitive(Primitive::String(s)) => {

View File

@ -114,7 +114,7 @@ mod tests {
let pattern = "Car"; let pattern = "Car";
let expected = UntaggedValue::boolean(true).into_untagged_value(); let expected = UntaggedValue::boolean(true).into_untagged_value();
let actual = action(&word, &pattern, Tag::unknown()).unwrap(); let actual = action(&word, pattern, Tag::unknown()).unwrap();
assert_eq!(actual, expected); assert_eq!(actual, expected);
} }
@ -124,7 +124,7 @@ mod tests {
let pattern = ".toml"; let pattern = ".toml";
let expected = UntaggedValue::boolean(false).into_untagged_value(); let expected = UntaggedValue::boolean(false).into_untagged_value();
let actual = action(&word, &pattern, Tag::unknown()).unwrap(); let actual = action(&word, pattern, Tag::unknown()).unwrap();
assert_eq!(actual, expected); assert_eq!(actual, expected);
} }
} }

View File

@ -90,7 +90,7 @@ where
.map(|(k, v)| -> Result<_, ShellError> { .map(|(k, v)| -> Result<_, ShellError> {
Ok(( Ok((
k.clone(), k.clone(),
action(&v, tag.clone(), char_, trim_operation, mode)?, action(v, tag.clone(), char_, trim_operation, mode)?,
)) ))
}) })
.collect(); .collect();

View File

@ -57,13 +57,7 @@ pub fn from_list(
.into_iter() .into_iter()
.map(|x| StyledString::new(x, header_style)) .map(|x| StyledString::new(x, header_style))
.collect(); .collect();
let entries = values_to_entries( let entries = values_to_entries(values, &mut headers, configuration, starting_idx, color_hm);
values,
&mut headers,
&configuration,
starting_idx,
&color_hm,
);
nu_table::Table { nu_table::Table {
headers, headers,
data: entries, data: entries,
@ -96,11 +90,11 @@ fn values_to_entries(
.. ..
} => StyledString::new( } => StyledString::new(
format_leaf(&UntaggedValue::nothing()).plain_string(100_000), format_leaf(&UntaggedValue::nothing()).plain_string(100_000),
style_leaf(&UntaggedValue::nothing(), &color_hm), style_leaf(&UntaggedValue::nothing(), color_hm),
), ),
_ => StyledString::new( _ => StyledString::new(
format_leaf(value).plain_string(100_000), format_leaf(value).plain_string(100_000),
style_leaf(value, &color_hm), style_leaf(value, color_hm),
), ),
} }
} else { } else {
@ -113,12 +107,12 @@ fn values_to_entries(
StyledString::new( StyledString::new(
format_leaf(data.borrow()).plain_string(100_000), format_leaf(data.borrow()).plain_string(100_000),
style_leaf(data.borrow(), &color_hm), style_leaf(data.borrow(), color_hm),
) )
} }
_ => StyledString::new( _ => StyledString::new(
format_leaf(&UntaggedValue::nothing()).plain_string(100_000), format_leaf(&UntaggedValue::nothing()).plain_string(100_000),
style_leaf(&UntaggedValue::nothing(), &color_hm), style_leaf(&UntaggedValue::nothing(), color_hm),
), ),
} }
} }

View File

@ -23,7 +23,7 @@ fn from_value_to_delimited_string(
for (k, v) in o.entries.iter() { for (k, v) in o.entries.iter() {
fields.push_back(k.clone()); fields.push_back(k.clone());
values.push_back(to_string_tagged_value(&v)?); values.push_back(to_string_tagged_value(v)?);
} }
wtr.write_record(fields).expect("can not write."); wtr.write_record(fields).expect("can not write.");
@ -50,7 +50,7 @@ fn from_value_to_delimited_string(
.delimiter(separator as u8) .delimiter(separator as u8)
.from_writer(vec![]); .from_writer(vec![]);
let merged_descriptors = merge_descriptors(&list); let merged_descriptors = merge_descriptors(list);
if merged_descriptors.is_empty() { if merged_descriptors.is_empty() {
wtr.write_record( wtr.write_record(

View File

@ -285,18 +285,13 @@ fn to_html(args: CommandArgs) -> Result<OutputStream, ShellError> {
output_string.push_str("\nScreenshots of themes can be found here:\n"); output_string.push_str("\nScreenshots of themes can be found here:\n");
output_string.push_str("https://github.com/mbadolato/iTerm2-Color-Schemes\n"); output_string.push_str("https://github.com/mbadolato/iTerm2-Color-Schemes\n");
// Short circuit and return the output_string
Ok(OutputStream::one(
UntaggedValue::string(output_string).into_value(name_tag),
))
} else { } else {
let theme_tag = match &theme { let theme_tag = match &theme {
Some(v) => &v.tag, Some(v) => &v.tag,
None => &name_tag, None => &name_tag,
}; };
let color_hm = get_theme_from_asset_file(dark, &theme, &theme_tag); let color_hm = get_theme_from_asset_file(dark, &theme, theme_tag);
let color_hm = match color_hm { let color_hm = match color_hm {
Ok(c) => c, Ok(c) => c,
_ => { _ => {
@ -362,11 +357,10 @@ fn to_html(args: CommandArgs) -> Result<OutputStream, ShellError> {
setup_no_color_regexes(&mut regex_hm); setup_no_color_regexes(&mut regex_hm);
output_string = run_regexes(&regex_hm, &output_string); output_string = run_regexes(&regex_hm, &output_string);
} }
Ok(OutputStream::one(
UntaggedValue::string(output_string).into_value(name_tag),
))
} }
Ok(OutputStream::one(
UntaggedValue::string(output_string).into_value(name_tag),
))
} }
fn html_list(list: Vec<Value>) -> String { fn html_list(list: Vec<Value>) -> String {
@ -393,7 +387,7 @@ fn html_table(table: Vec<Value>, headers: Vec<String>) -> String {
output_string.push_str("<tr>"); output_string.push_str("<tr>");
for header in &headers { for header in &headers {
output_string.push_str("<th>"); output_string.push_str("<th>");
output_string.push_str(&htmlescape::encode_minimal(&header)); output_string.push_str(&htmlescape::encode_minimal(header));
output_string.push_str("</th>"); output_string.push_str("</th>");
} }
output_string.push_str("</tr>"); output_string.push_str("</tr>");

View File

@ -189,9 +189,7 @@ fn to_json(args: CommandArgs) -> Result<OutputStream, ShellError> {
serde_json_string.as_str(), serde_json_string.as_str(),
) )
{ {
let indentation_string = std::iter::repeat(" ") let indentation_string = " ".repeat(pretty_u64 as usize);
.take(pretty_u64 as usize)
.collect::<String>();
let serde_formatter = let serde_formatter =
serde_json::ser::PrettyFormatter::with_indent( serde_json::ser::PrettyFormatter::with_indent(
indentation_string.as_bytes(), indentation_string.as_bytes(),

View File

@ -117,7 +117,7 @@ fn process(
}) })
.collect::<String>() .collect::<String>()
} else { } else {
table(&input, pretty) table(input, pretty)
} }
} }
@ -158,7 +158,7 @@ fn collect_headers(headers: &[String]) -> (Vec<String>, Vec<usize>) {
if !headers.is_empty() && (headers.len() > 1 || !headers[0].is_empty()) { if !headers.is_empty() && (headers.len() > 1 || !headers[0].is_empty()) {
for header in headers { for header in headers {
let escaped_header_string = htmlescape::encode_minimal(&header); let escaped_header_string = htmlescape::encode_minimal(header);
column_widths.push(escaped_header_string.len()); column_widths.push(escaped_header_string.len());
escaped_headers.push(escaped_header_string); escaped_headers.push(escaped_header_string);
} }
@ -170,7 +170,7 @@ fn collect_headers(headers: &[String]) -> (Vec<String>, Vec<usize>) {
} }
fn table(input: &[Value], pretty: bool) -> String { fn table(input: &[Value], pretty: bool) -> String {
let headers = nu_protocol::merge_descriptors(&input); let headers = nu_protocol::merge_descriptors(input);
let (escaped_headers, mut column_widths) = collect_headers(&headers); let (escaped_headers, mut column_widths) = collect_headers(&headers);

View File

@ -51,7 +51,7 @@ where
for path in &paths { for path in &paths {
ret = ret.swap_data_by_column_path( ret = ret.swap_data_by_column_path(
path, path,
Box::new(move |old| handle_value(&action, &old)), Box::new(move |old| handle_value(&action, old)),
)?; )?;
} }

View File

@ -125,7 +125,7 @@ impl Iterator for WhereIterator {
type Item = Value; type Item = Value;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
while let Some(x) = self.input.next() { for x in &mut self.input {
self.context.scope.enter_scope(); self.context.scope.enter_scope();
self.context.scope.add_vars(&self.block.captured.entries); self.context.scope.add_vars(&self.block.captured.entries);

View File

@ -209,7 +209,7 @@ fn parse_line(line: &str, ctx: &EvaluationContext) -> Result<ClassifiedBlock, Sh
line line
}; };
let (lite_result, err) = nu_parser::lex(&line, 0); let (lite_result, err) = nu_parser::lex(line, 0);
if let Some(err) = err { if let Some(err) = err {
return Err(err.into()); return Err(err.into());
} }

View File

@ -20,7 +20,7 @@ impl Trusted {
} }
pub fn is_file_trusted(nu_env_file: &Path, content: &[u8]) -> Result<bool, ShellError> { pub fn is_file_trusted(nu_env_file: &Path, content: &[u8]) -> Result<bool, ShellError> {
let contentdigest = Sha256::digest(&content).as_slice().to_vec(); let contentdigest = Sha256::digest(content).as_slice().to_vec();
let nufile = std::fs::canonicalize(nu_env_file)?; let nufile = std::fs::canonicalize(nu_env_file)?;
let trusted = read_trusted()?; let trusted = read_trusted()?;

View File

@ -106,11 +106,11 @@ fn is_existent_local_cfg(cfg_file_path: &Path) -> Result<bool, ShellError> {
fn is_trusted_local_cfg_content(cfg_file_path: &Path, content: &[u8]) -> Result<bool, ShellError> { fn is_trusted_local_cfg_content(cfg_file_path: &Path, content: &[u8]) -> Result<bool, ShellError> {
//This checks whether user used `autoenv trust` to mark this cfg as secure //This checks whether user used `autoenv trust` to mark this cfg as secure
if !super::is_file_trusted(&cfg_file_path, &content)? { if !super::is_file_trusted(cfg_file_path, content)? {
//Notify user about present config, but not trusted //Notify user about present config, but not trusted
Err(ShellError::untagged_runtime_error( Err(ShellError::untagged_runtime_error(
format!("{:?} is untrusted. Run 'autoenv trust {:?}' to trust it.\nThis needs to be done after each change to the file.", format!("{:?} is untrusted. Run 'autoenv trust {:?}' to trust it.\nThis needs to be done after each change to the file.",
cfg_file_path, cfg_file_path.parent().unwrap_or_else(|| &Path::new(""))))) cfg_file_path, cfg_file_path.parent().unwrap_or_else(|| Path::new("")))))
} else { } else {
Ok(true) Ok(true)
} }

View File

@ -113,7 +113,7 @@ pub fn string_to_lookup_value(str_prim: &str) -> String {
fn update_hashmap(key: &str, val: &Value, hm: &mut HashMap<String, Style>) { fn update_hashmap(key: &str, val: &Value, hm: &mut HashMap<String, Style>) {
if let Ok(var) = val.as_string() { if let Ok(var) = val.as_string() {
let color = lookup_ansi_color_style(var); let color = lookup_ansi_color_style(var);
let prim = string_to_lookup_value(&key); let prim = string_to_lookup_value(key);
if let Some(v) = hm.get_mut(&prim) { if let Some(v) = hm.get_mut(&prim) {
*v = color; *v = color;
} else { } else {
@ -157,64 +157,64 @@ pub fn get_color_config(config: &NuConfig) -> HashMap<String, Style> {
for (key, value) in primitive_color_vars.row_entries() { for (key, value) in primitive_color_vars.row_entries() {
match key.as_ref() { match key.as_ref() {
"primitive_int" => { "primitive_int" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"primitive_decimal" => { "primitive_decimal" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"primitive_filesize" => { "primitive_filesize" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"primitive_string" => { "primitive_string" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"primitive_line" => { "primitive_line" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"primitive_columnpath" => { "primitive_columnpath" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"primitive_pattern" => { "primitive_pattern" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"primitive_boolean" => { "primitive_boolean" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"primitive_date" => { "primitive_date" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"primitive_duration" => { "primitive_duration" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"primitive_range" => { "primitive_range" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"primitive_path" => { "primitive_path" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"primitive_binary" => { "primitive_binary" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"separator_color" => { "separator_color" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"header_align" => { "header_align" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"header_color" => { "header_color" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"header_bold" => { "header_bold" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"header_style" => { "header_style" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"index_color" => { "index_color" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
"leading_trailing_space_bg" => { "leading_trailing_space_bg" => {
update_hashmap(&key, &value, &mut hm); update_hashmap(key, value, &mut hm);
} }
_ => (), _ => (),
} }

View File

@ -16,9 +16,9 @@ pub fn group(
for (idx, value) in values.table_entries().enumerate() { for (idx, value) in values.table_entries().enumerate() {
let group_key = if let Some(ref grouper) = grouper { let group_key = if let Some(ref grouper) = grouper {
grouper(idx, &value) grouper(idx, value)
} else { } else {
as_string(&value) as_string(value)
}; };
let group = groups.entry(group_key?).or_insert(vec![]); let group = groups.entry(group_key?).or_insert(vec![]);

View File

@ -51,7 +51,7 @@ fn formula(
calculator: Box<dyn Fn(Vec<&Value>) -> Result<Value, ShellError> + Send + Sync + 'static>, calculator: Box<dyn Fn(Vec<&Value>) -> Result<Value, ShellError> + Send + Sync + 'static>,
) -> Box<dyn Fn(&Value, Vec<&Value>) -> Result<Value, ShellError> + Send + Sync + 'static> { ) -> Box<dyn Fn(&Value, Vec<&Value>) -> Result<Value, ShellError> + Send + Sync + 'static> {
Box::new(move |acc, datax| -> Result<Value, ShellError> { Box::new(move |acc, datax| -> Result<Value, ShellError> {
let result = match unsafe_compute_values(Operator::Multiply, &acc, &acc_begin) { let result = match unsafe_compute_values(Operator::Multiply, acc, &acc_begin) {
Ok(v) => v.into_untagged_value(), Ok(v) => v.into_untagged_value(),
Err((left_type, right_type)) => { Err((left_type, right_type)) => {
return Err(ShellError::coerce_error( return Err(ShellError::coerce_error(
@ -164,7 +164,7 @@ pub fn sum(data: Vec<&Value>) -> Result<Value, ShellError> {
for value in data { for value in data {
match value.value { match value.value {
UntaggedValue::Primitive(_) => { UntaggedValue::Primitive(_) => {
acc = match unsafe_compute_values(Operator::Plus, &acc, &value) { acc = match unsafe_compute_values(Operator::Plus, &acc, value) {
Ok(v) => v, Ok(v) => v,
Err((left_type, right_type)) => { Err((left_type, right_type)) => {
return Err(ShellError::coerce_error( return Err(ShellError::coerce_error(
@ -314,8 +314,8 @@ pub fn percentages(
.filter_map(|s| { .filter_map(|s| {
let hundred = UntaggedValue::decimal_from_float(100.0, tag.span); let hundred = UntaggedValue::decimal_from_float(100.0, tag.span);
match unsafe_compute_values(Operator::Divide, &hundred, &maxima) { match unsafe_compute_values(Operator::Divide, &hundred, maxima) {
Ok(v) => match unsafe_compute_values(Operator::Multiply, &s, &v) { Ok(v) => match unsafe_compute_values(Operator::Multiply, s, &v) {
Ok(v) => Some(v.into_untagged_value()), Ok(v) => Some(v.into_untagged_value()),
Err(_) => None, Err(_) => None,
}, },

View File

@ -40,7 +40,7 @@ pub fn report(
) -> Result<Model, ShellError> { ) -> Result<Model, ShellError> {
let tag = tag.into(); let tag = tag.into();
let grouped = group(&values, &options.grouper, &tag)?; let grouped = group(values, &options.grouper, &tag)?;
let splitted = split(&grouped, &options.splitter, &tag)?; let splitted = split(&grouped, &options.splitter, &tag)?;
let x = grouped let x = grouped
@ -48,7 +48,7 @@ pub fn report(
.map(|(key, _)| key.clone()) .map(|(key, _)| key.clone())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let x = sort_columns(&x, &options.format)?; let x = sort_columns(&x, options.format)?;
let mut y = splitted let mut y = splitted
.row_entries() .row_entries()

View File

@ -28,7 +28,7 @@ pub fn split(
)); ));
} }
match group(&value, splitter, &tag) { match group(value, splitter, &tag) {
Ok(grouped) => { Ok(grouped) => {
for (split_label, subset) in grouped.row_entries() { for (split_label, subset) in grouped.row_entries() {
let s = splits let s = splits

View File

@ -590,7 +590,7 @@ pub fn style_leaf<'a>(
let str_len = str.len(); let str_len = str.len();
let paren_index = str.find('(').unwrap_or(str_len - 1); let paren_index = str.find('(').unwrap_or(str_len - 1);
let prim_type = str[0..paren_index].to_string(); let prim_type = str[0..paren_index].to_string();
style_primitive(&prim_type, &color_hash_map) style_primitive(&prim_type, color_hash_map)
} }
_ => TextStyle::basic_left(), _ => TextStyle::basic_left(),
} }

View File

@ -26,7 +26,7 @@ pub fn evaluate_baseline_expr(
}; };
let span = expr.span; let span = expr.span;
match &expr.expr { match &expr.expr {
Expression::Literal(literal) => Ok(evaluate_literal(&literal, span)), Expression::Literal(literal) => Ok(evaluate_literal(literal, span)),
Expression::ExternalWord => Err(ShellError::argument_error( Expression::ExternalWord => Err(ShellError::argument_error(
"Invalid external word".spanned(tag.span), "Invalid external word".spanned(tag.span),
ArgumentError::InvalidExternalWord, ArgumentError::InvalidExternalWord,
@ -35,7 +35,7 @@ pub fn evaluate_baseline_expr(
Expression::Synthetic(hir::Synthetic::String(s)) => { Expression::Synthetic(hir::Synthetic::String(s)) => {
Ok(UntaggedValue::string(s).into_untagged_value()) Ok(UntaggedValue::string(s).into_untagged_value())
} }
Expression::Variable(var, s) => evaluate_reference(&var, ctx, *s), Expression::Variable(var, s) => evaluate_reference(var, ctx, *s),
Expression::Command => unimplemented!(), Expression::Command => unimplemented!(),
Expression::Subexpression(block) => evaluate_subexpression(block, ctx), Expression::Subexpression(block) => evaluate_subexpression(block, ctx),
Expression::ExternalCommand(_) => unimplemented!(), Expression::ExternalCommand(_) => unimplemented!(),
@ -68,13 +68,13 @@ pub fn evaluate_baseline_expr(
} }
Expression::Range(range) => { Expression::Range(range) => {
let left = if let Some(left) = &range.left { let left = if let Some(left) = &range.left {
evaluate_baseline_expr(&left, ctx)? evaluate_baseline_expr(left, ctx)?
} else { } else {
Value::nothing() Value::nothing()
}; };
let right = if let Some(right) = &range.right { let right = if let Some(right) = &range.right {
evaluate_baseline_expr(&right, ctx)? evaluate_baseline_expr(right, ctx)?
} else { } else {
Value::nothing() Value::nothing()
}; };
@ -100,7 +100,7 @@ pub fn evaluate_baseline_expr(
let mut output_headers = vec![]; let mut output_headers = vec![];
for expr in headers { for expr in headers {
let val = evaluate_baseline_expr(&expr, ctx)?; let val = evaluate_baseline_expr(expr, ctx)?;
let header = val.as_string()?; let header = val.as_string()?;
output_headers.push(header); output_headers.push(header);
@ -128,7 +128,7 @@ pub fn evaluate_baseline_expr(
let mut row_output = IndexMap::new(); let mut row_output = IndexMap::new();
for cell in output_headers.iter().zip(row.iter()) { for cell in output_headers.iter().zip(row.iter()) {
let val = evaluate_baseline_expr(&cell.1, ctx)?; let val = evaluate_baseline_expr(cell.1, ctx)?;
row_output.insert(cell.0.clone(), val); row_output.insert(cell.0.clone(), val);
} }
output_table.push(UntaggedValue::row(row_output).into_value(tag.clone())); output_table.push(UntaggedValue::row(row_output).into_value(tag.clone()));
@ -140,7 +140,7 @@ pub fn evaluate_baseline_expr(
let mut exprs = vec![]; let mut exprs = vec![];
for expr in list { for expr in list {
let expr = evaluate_baseline_expr(&expr, ctx)?; let expr = evaluate_baseline_expr(expr, ctx)?;
exprs.push(expr); exprs.push(expr);
} }
@ -228,7 +228,7 @@ fn evaluate_literal(literal: &hir::Literal, span: Span) -> Value {
UntaggedValue::decimal(d.clone()).into_value(span) UntaggedValue::decimal(d.clone()).into_value(span)
} }
}, },
hir::Literal::Size(int, unit) => unit.compute(&int).into_value(span), hir::Literal::Size(int, unit) => unit.compute(int).into_value(span),
hir::Literal::String(string) => UntaggedValue::string(string).into_value(span), hir::Literal::String(string) => UntaggedValue::string(string).into_value(span),
hir::Literal::GlobPattern(pattern) => UntaggedValue::glob_pattern(pattern).into_value(span), hir::Literal::GlobPattern(pattern) => UntaggedValue::glob_pattern(pattern).into_value(span),
hir::Literal::Bare(bare) => UntaggedValue::string(bare.clone()).into_value(span), hir::Literal::Bare(bare) => UntaggedValue::string(bare.clone()).into_value(span),
@ -287,7 +287,7 @@ fn evaluate_subexpression(
None => InputStream::empty(), None => InputStream::empty(),
}; };
let result = run_block(&block, ctx, input, hir::ExternalRedirection::Stdout)?; let result = run_block(block, ctx, input, hir::ExternalRedirection::Stdout)?;
let output = result.into_vec(); let output = result.into_vec();

View File

@ -84,7 +84,7 @@ fn table_contains(
UntaggedValue::Table(values) => { UntaggedValue::Table(values) => {
Ok(values Ok(values
.iter() .iter()
.any(|x| match compare_values(Operator::Equal, &left, &x.value) { .any(|x| match compare_values(Operator::Equal, left, &x.value) {
Ok(coerced) => coerced, Ok(coerced) => coerced,
_ => false, _ => false,
})) }))

View File

@ -292,7 +292,7 @@ impl EvaluationContext {
} }
//Unload config //Unload config
self.configs.lock().remove_cfg(&cfg_path); self.configs.lock().remove_cfg(cfg_path);
self.scope.exit_scope_with_tag(&tag); self.scope.exit_scope_with_tag(&tag);
} }
@ -301,7 +301,7 @@ impl EvaluationContext {
pub fn run_scripts(&self, scripts: Vec<String>, dir: Option<&Path>) { pub fn run_scripts(&self, scripts: Vec<String>, dir: Option<&Path>) {
if let Some(dir) = dir { if let Some(dir) = dir {
for script in scripts { for script in scripts {
match script::run_script_in_dir(script.clone(), dir, &self) { match script::run_script_in_dir(script.clone(), dir, self) {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
let err = ShellError::untagged_runtime_error(format!( let err = ShellError::untagged_runtime_error(format!(

View File

@ -105,9 +105,9 @@ impl DirInfo {
match f { match f {
Ok(i) => match i.file_type() { Ok(i) => match i.file_type() {
Ok(t) if t.is_dir() => { Ok(t) if t.is_dir() => {
s = s.add_dir(i.path(), depth, &params, ctrl_c.clone()) s = s.add_dir(i.path(), depth, params, ctrl_c.clone())
} }
Ok(_t) => s = s.add_file(i.path(), &params), Ok(_t) => s = s.add_file(i.path(), params),
Err(e) => s = s.add_error(e.into()), Err(e) => s = s.add_error(e.into()),
}, },
Err(e) => s = s.add_error(e.into()), Err(e) => s = s.add_error(e.into()),
@ -134,7 +134,7 @@ impl DirInfo {
} }
} }
let d = DirInfo::new(path, &params, depth, ctrl_c); let d = DirInfo::new(path, params, depth, ctrl_c);
self.size += d.size; self.size += d.size;
self.blocks += d.blocks; self.blocks += d.blocks;
self.dirs.push(d); self.dirs.push(d);

View File

@ -931,7 +931,7 @@ fn move_file(from: TaggedPathBuf, to: TaggedPathBuf) -> Result<(), ShellError> {
to.push(from_file_name); to.push(from_file_name);
} }
move_item(&from, from_tag, &to) move_item(from, from_tag, &to)
} }
fn move_item(from: &Path, from_tag: &Tag, to: &Path) -> Result<(), ShellError> { fn move_item(from: &Path, from_tag: &Tag, to: &Path) -> Result<(), ShellError> {

View File

@ -185,7 +185,7 @@ mod tests {
let mut res = FileStructure::new(); let mut res = FileStructure::new();
res.walk_decorate(&dirs.test()) res.walk_decorate(dirs.test())
.expect("Can not decorate files traversal."); .expect("Can not decorate files traversal.");
assert_eq!( assert_eq!(

View File

@ -40,7 +40,7 @@ impl<R: Read> Iterator for BufCodecReader<R> {
let buffer = self.input.fill_buf(); let buffer = self.input.fill_buf();
match buffer { match buffer {
Ok(s) => { Ok(s) => {
let result = self.maybe_text_codec.decode(&s).transpose(); let result = self.maybe_text_codec.decode(s).transpose();
let buffer_len = s.len(); let buffer_len = s.len();
self.input.consume(buffer_len); self.input.consume(buffer_len);

View File

@ -158,7 +158,7 @@ pub fn scan(
if is_valid_name && is_executable { if is_valid_name && is_executable {
trace!(target: "nu::load", "plugin infrastructure -> Trying {:?}", path.display()); trace!(target: "nu::load", "plugin infrastructure -> Trying {:?}", path.display());
build_plugin_command(&path).unwrap_or(None) build_plugin_command(path).unwrap_or(None)
} else { } else {
None None
} }

View File

@ -416,7 +416,7 @@ fn run_sink(path: String, args: CommandArgs) -> Result<ActionStream, ShellError>
"Bypass", "Bypass",
"-File", "-File",
&real_path.to_string_lossy(), &real_path.to_string_lossy(),
&tmpfile tmpfile
.path() .path()
.to_str() .to_str()
.expect("Failed getting tmpfile path"), .expect("Failed getting tmpfile path"),

View File

@ -65,7 +65,7 @@ pub fn process_script(
} else { } else {
let line = chomp_newline(script_text); let line = chomp_newline(script_text);
let (block, err) = nu_parser::parse(&line, span_offset, &ctx.scope); let (block, err) = nu_parser::parse(line, span_offset, &ctx.scope);
debug!("{:#?}", block); debug!("{:#?}", block);
//println!("{:#?}", pipeline); //println!("{:#?}", pipeline);
@ -111,7 +111,7 @@ pub fn process_script(
&& args && args
.positional .positional
.as_ref() .as_ref()
.map(|ref v| v.len() == 1) .map(|v| v.len() == 1)
.unwrap_or(true) .unwrap_or(true)
&& args && args
.named .named
@ -120,7 +120,7 @@ pub fn process_script(
.unwrap_or(true) .unwrap_or(true)
&& canonicalize(ctx.shell_manager.path(), name).is_ok() && canonicalize(ctx.shell_manager.path(), name).is_ok()
&& Path::new(&name).is_dir() && Path::new(&name).is_dir()
&& !ctx.host.lock().is_external_cmd(&name) && !ctx.host.lock().is_external_cmd(name)
{ {
let tag = Tag { let tag = Tag {
anchor: Some(AnchorLocation::Source(line.into())), anchor: Some(AnchorLocation::Source(line.into())),
@ -285,7 +285,7 @@ pub fn run_script_standalone(
} }
}; };
maybe_print_errors(&context, Text::from(line)); maybe_print_errors(context, Text::from(line));
if error_code != 0 && exit_on_error { if error_code != 0 && exit_on_error {
std::process::exit(error_code); std::process::exit(error_code);
} }
@ -297,7 +297,7 @@ pub fn run_script_standalone(
.lock() .lock()
.print_err(err, &Text::from(line.clone())); .print_err(err, &Text::from(line.clone()));
maybe_print_errors(&context, Text::from(line)); maybe_print_errors(context, Text::from(line));
if exit_on_error { if exit_on_error {
std::process::exit(1); std::process::exit(1);
} }

View File

@ -72,10 +72,8 @@ impl Painter {
current_style = self.styles[idx_end]; current_style = self.styles[idx_end];
idx_start = idx_end; idx_start = idx_end;
idx_end += 1;
} else {
idx_end += 1;
} }
idx_end += 1;
} }
let intermediate = String::from_utf8_lossy(&self.original[idx_start..idx_end]); let intermediate = String::from_utf8_lossy(&self.original[idx_start..idx_end]);

View File

@ -94,7 +94,7 @@ mod tests {
#[test] #[test]
fn parses_longform_flag_containing_equal_sign() { fn parses_longform_flag_containing_equal_sign() {
let input = "bundle add rails --group=development"; let input = "bundle add rails --group=development";
let (tokens, _) = lex(&input, 0); let (tokens, _) = lex(input, 0);
let (root_node, _) = parse_block(tokens); let (root_node, _) = parse_block(tokens);
assert_eq!(root_node.block.len(), 1); assert_eq!(root_node.block.len(), 1);

View File

@ -537,7 +537,7 @@ fn parse_dollar_expr(
&& lite_arg.item.ends_with('\'')) && lite_arg.item.ends_with('\''))
{ {
// This is an interpolated string // This is an interpolated string
parse_interpolated_string(&lite_arg, scope) parse_interpolated_string(lite_arg, scope)
} else if let (expr, None) = parse_range(lite_arg, scope) { } else if let (expr, None) = parse_range(lite_arg, scope) {
(expr, None) (expr, None)
} else if let (expr, None) = parse_full_column_path(lite_arg, scope) { } else if let (expr, None) = parse_full_column_path(lite_arg, scope) {
@ -588,7 +588,7 @@ fn format(input: &str, start: usize) -> (Vec<FormatCommand>, Option<ParseError>)
let mut found_end = false; let mut found_end = false;
let mut delimiter_stack = vec![')']; let mut delimiter_stack = vec![')'];
while let Some(c) = loop_input.next() { for c in &mut loop_input {
end += 1; end += 1;
if let Some('\'') = delimiter_stack.last() { if let Some('\'') = delimiter_stack.last() {
if c == '\'' { if c == '\'' {
@ -726,9 +726,9 @@ fn parse_external_arg(
scope: &dyn ParserScope, scope: &dyn ParserScope,
) -> (SpannedExpression, Option<ParseError>) { ) -> (SpannedExpression, Option<ParseError>) {
if lite_arg.item.starts_with('$') { if lite_arg.item.starts_with('$') {
parse_dollar_expr(&lite_arg, scope) parse_dollar_expr(lite_arg, scope)
} else if lite_arg.item.starts_with('(') { } else if lite_arg.item.starts_with('(') {
parse_subexpression(&lite_arg, scope) parse_subexpression(lite_arg, scope)
} else { } else {
( (
SpannedExpression::new(Expression::string(lite_arg.item.clone()), lite_arg.span), SpannedExpression::new(Expression::string(lite_arg.item.clone()), lite_arg.span),
@ -809,7 +809,7 @@ fn parse_table(
let lite_cells = &lite_rows.commands[0]; let lite_cells = &lite_rows.commands[0];
for arg in &lite_cells.parts { for arg in &lite_cells.parts {
let (string, err) = verify_and_strip(&arg, '[', ']'); let (string, err) = verify_and_strip(arg, '[', ']');
if error.is_none() { if error.is_none() {
error = err; error = err;
} }
@ -891,12 +891,12 @@ fn parse_arg(
lite_arg: &Spanned<String>, lite_arg: &Spanned<String>,
) -> (SpannedExpression, Option<ParseError>) { ) -> (SpannedExpression, Option<ParseError>) {
if lite_arg.item.starts_with('$') { if lite_arg.item.starts_with('$') {
return parse_dollar_expr(&lite_arg, scope); return parse_dollar_expr(lite_arg, scope);
} }
// before anything else, try to see if this is a number in paranthesis // before anything else, try to see if this is a number in paranthesis
if lite_arg.item.starts_with('(') { if lite_arg.item.starts_with('(') {
return parse_full_column_path(&lite_arg, scope); return parse_full_column_path(lite_arg, scope);
} }
match expected_type { match expected_type {
@ -954,13 +954,13 @@ fn parse_arg(
) )
} }
SyntaxShape::Range => parse_range(&lite_arg, scope), SyntaxShape::Range => parse_range(lite_arg, scope),
SyntaxShape::Operator => ( SyntaxShape::Operator => (
garbage(lite_arg.span), garbage(lite_arg.span),
Some(ParseError::mismatch("operator", lite_arg.clone())), Some(ParseError::mismatch("operator", lite_arg.clone())),
), ),
SyntaxShape::Filesize => parse_filesize(&lite_arg), SyntaxShape::Filesize => parse_filesize(lite_arg),
SyntaxShape::Duration => parse_duration(&lite_arg), SyntaxShape::Duration => parse_duration(lite_arg),
SyntaxShape::FilePath => { SyntaxShape::FilePath => {
let trimmed = trim_quotes(&lite_arg.item); let trimmed = trim_quotes(&lite_arg.item);
let expanded = expand_path(&trimmed).to_string(); let expanded = expand_path(&trimmed).to_string();
@ -1084,7 +1084,7 @@ fn parse_arg(
// We've found a parameter list // We've found a parameter list
let mut param_tokens = vec![]; let mut param_tokens = vec![];
let mut token_iter = tokens.into_iter().skip(1); let mut token_iter = tokens.into_iter().skip(1);
while let Some(token) = token_iter.next() { for token in &mut token_iter {
if matches!( if matches!(
token, token,
Token { Token {
@ -1478,7 +1478,7 @@ fn parse_internal_command(
); );
let mut internal_command = InternalCommand::new(name, name_span, lite_cmd.span()); let mut internal_command = InternalCommand::new(name, name_span, lite_cmd.span());
internal_command.args.set_initial_flags(&signature); internal_command.args.set_initial_flags(signature);
let mut current_positional = 0; let mut current_positional = 0;
let mut named = NamedArguments::new(); let mut named = NamedArguments::new();
@ -1489,7 +1489,7 @@ fn parse_internal_command(
while idx < lite_cmd.parts.len() { while idx < lite_cmd.parts.len() {
if lite_cmd.parts[idx].item.starts_with('-') && lite_cmd.parts[idx].item.len() > 1 { if lite_cmd.parts[idx].item.starts_with('-') && lite_cmd.parts[idx].item.len() > 1 {
let (named_types, err) = super::flag::get_flag_signature_spec( let (named_types, err) = super::flag::get_flag_signature_spec(
&signature, signature,
&internal_command, &internal_command,
&lite_cmd.parts[idx], &lite_cmd.parts[idx],
); );

View File

@ -23,7 +23,7 @@ pub fn expression_to_flat_shape(e: &SpannedExpression) -> Vec<Spanned<FlatShape>
} }
for row in cells { for row in cells {
for cell in row { for cell in row {
output.append(&mut expression_to_flat_shape(&cell)); output.append(&mut expression_to_flat_shape(cell));
} }
} }
output output

View File

@ -112,7 +112,7 @@ impl CallStub {
} }
pub fn with_parameter(&mut self, name: &str) -> Result<&mut Self, ShellError> { pub fn with_parameter(&mut self, name: &str) -> Result<&mut Self, ShellError> {
let cp = column_path(&name) let cp = column_path(name)
.as_column_path() .as_column_path()
.expect("Failed! Expected valid column path."); .expect("Failed! Expected valid column path.");
let cp = UntaggedValue::Primitive(Primitive::ColumnPath(cp.item)).into_value(cp.tag); let cp = UntaggedValue::Primitive(Primitive::ColumnPath(cp.item)).into_value(cp.tag);

View File

@ -536,12 +536,12 @@ impl Value {
/// Returns an iterator of the values rows /// Returns an iterator of the values rows
pub fn table_entries(&self) -> TableValueIter<'_> { pub fn table_entries(&self) -> TableValueIter<'_> {
crate::value::iter::table_entries(&self) crate::value::iter::table_entries(self)
} }
/// Returns an iterator of the value's cells /// Returns an iterator of the value's cells
pub fn row_entries(&self) -> RowValueIter<'_> { pub fn row_entries(&self) -> RowValueIter<'_> {
crate::value::iter::row_entries(&self) crate::value::iter::row_entries(self)
} }
/// Returns true if the value is empty /// Returns true if the value is empty

View File

@ -78,7 +78,7 @@ impl ColumnPath {
span: _, span: _,
}, },
_, _,
) = parse(&text) ) = parse(text)
{ {
ColumnPath { ColumnPath {
members: path.iter().map(|member| member.to_path_member()).collect(), members: path.iter().map(|member| member.to_path_member()).collect(),

View File

@ -43,7 +43,7 @@ impl InputStream {
pub fn drain_vec(&mut self) -> Vec<Value> { pub fn drain_vec(&mut self) -> Vec<Value> {
let mut output = vec![]; let mut output = vec![];
while let Some(x) = self.values.next() { for x in &mut self.values {
output.push(x); output.push(x);
} }
output output

View File

@ -45,7 +45,7 @@ impl ActionStream {
pub fn drain_vec(&mut self) -> Vec<ReturnValue> { pub fn drain_vec(&mut self) -> Vec<ReturnValue> {
let mut output = vec![]; let mut output = vec![];
while let Some(x) = self.values.next() { for x in &mut self.values {
output.push(x); output.push(x);
} }

View File

@ -886,7 +886,7 @@ impl WrappedTable {
if self.theme.print_top_border { if self.theme.print_top_border {
output.push_str( output.push_str(
self.print_separator(SeparatorPosition::Top, &color_hm) self.print_separator(SeparatorPosition::Top, color_hm)
.as_str(), .as_str(),
); );
} }
@ -895,7 +895,7 @@ impl WrappedTable {
|| (self.headers.len() == 1 && self.headers[0].max_width == 0); || (self.headers.len() == 1 && self.headers[0].max_width == 0);
if !self.headers.is_empty() && !skip_headers { if !self.headers.is_empty() && !skip_headers {
output.push_str(self.print_cell_contents(&self.headers, &color_hm).as_str()); output.push_str(self.print_cell_contents(&self.headers, color_hm).as_str());
} }
let mut first_row = true; let mut first_row = true;
@ -904,7 +904,7 @@ impl WrappedTable {
if !first_row { if !first_row {
if self.theme.separate_rows { if self.theme.separate_rows {
output.push_str( output.push_str(
self.print_separator(SeparatorPosition::Middle, &color_hm) self.print_separator(SeparatorPosition::Middle, color_hm)
.as_str(), .as_str(),
) )
} }
@ -913,18 +913,18 @@ impl WrappedTable {
if self.theme.separate_header && !self.headers.is_empty() && !skip_headers { if self.theme.separate_header && !self.headers.is_empty() && !skip_headers {
output.push_str( output.push_str(
self.print_separator(SeparatorPosition::Middle, &color_hm) self.print_separator(SeparatorPosition::Middle, color_hm)
.as_str(), .as_str(),
); );
} }
} }
output.push_str(self.print_cell_contents(row, &color_hm).as_str()); output.push_str(self.print_cell_contents(row, color_hm).as_str());
} }
if self.theme.print_bottom_border { if self.theme.print_bottom_border {
output.push_str( output.push_str(
self.print_separator(SeparatorPosition::Bottom, &color_hm) self.print_separator(SeparatorPosition::Bottom, color_hm)
.as_str(), .as_str(),
); );
} }
@ -1073,12 +1073,12 @@ pub fn draw_table(table: &Table, termwidth: usize, color_hm: &HashMap<String, St
let wrapped_table = wrap_cells( let wrapped_table = wrap_cells(
processed_table, processed_table,
max_column_width, max_column_width,
&color_hm, color_hm,
&re_leading, &re_leading,
&re_trailing, &re_trailing,
); );
wrapped_table.print_table(&color_hm) wrapped_table.print_table(color_hm)
} }
fn wrap_cells( fn wrap_cells(
@ -1111,9 +1111,9 @@ fn wrap_cells(
let (mut lines, inner_max_width) = wrap( let (mut lines, inner_max_width) = wrap(
max_column_width, max_column_width,
contents.into_iter(), contents.into_iter(),
&color_hm, color_hm,
&re_leading, re_leading,
&re_trailing, re_trailing,
); );
wrapped.lines.append(&mut lines); wrapped.lines.append(&mut lines);
if inner_max_width > wrapped.max_width { if inner_max_width > wrapped.max_width {
@ -1139,9 +1139,9 @@ fn wrap_cells(
let (mut lines, inner_max_width) = wrap( let (mut lines, inner_max_width) = wrap(
max_column_width, max_column_width,
contents.into_iter(), contents.into_iter(),
&color_hm, color_hm,
&re_leading, re_leading,
&re_trailing, re_trailing,
); );
wrapped.lines.append(&mut lines); wrapped.lines.append(&mut lines);
if inner_max_width > wrapped.max_width { if inner_max_width > wrapped.max_width {

View File

@ -165,7 +165,7 @@ pub fn wrap<'a>(
// If this is a really long single word, we need to split the word // If this is a really long single word, we need to split the word
if current_line.len() == 1 && current_width > cell_width { if current_line.len() == 1 && current_width > cell_width {
max_width = cell_width; max_width = cell_width;
let sublines = split_word(cell_width, &current_line[0].subline); let sublines = split_word(cell_width, current_line[0].subline);
for subline in sublines { for subline in sublines {
let width = subline.width; let width = subline.width;
lines.push(Line { lines.push(Line {
@ -200,7 +200,7 @@ pub fn wrap<'a>(
None => { None => {
if current_width > cell_width { if current_width > cell_width {
// We need to break up the last word // We need to break up the last word
let sublines = split_word(cell_width, &current_line[0].subline); let sublines = split_word(cell_width, current_line[0].subline);
for subline in sublines { for subline in sublines {
let width = subline.width; let width = subline.width;
lines.push(Line { lines.push(Line {
@ -231,12 +231,11 @@ pub fn wrap<'a>(
if !first { if !first {
current_line_width += 1 + subline.width; current_line_width += 1 + subline.width;
current_line.push(' '); current_line.push(' ');
current_line.push_str(subline.subline);
} else { } else {
first = false; first = false;
current_line_width = subline.width; current_line_width = subline.width;
current_line.push_str(subline.subline);
} }
current_line.push_str(subline.subline);
} }
if current_line_width > current_max { if current_line_width > current_max {

View File

@ -30,7 +30,7 @@ fn current_working_directory_in_sandbox_directory_created() {
let original_cwd = dirs.test(); let original_cwd = dirs.test();
nu.within("some_directory_within"); nu.within("some_directory_within");
assert_eq!(path(&nu.cwd()), original_cwd.join("some_directory_within")); assert_eq!(path(nu.cwd()), original_cwd.join("some_directory_within"));
}) })
} }
@ -42,6 +42,6 @@ fn current_working_directory_back_to_root_from_anywhere() {
nu.within("some_directory_within"); nu.within("some_directory_within");
nu.back_to_playground(); nu.back_to_playground();
assert_eq!(path(&nu.cwd()), *original_cwd); assert_eq!(path(nu.cwd()), *original_cwd);
}) })
} }

View File

@ -242,7 +242,7 @@ where
match value { match value {
Ok(v) => current = v.clone(), Ok(v) => current = v.clone(),
Err(e) => return Err(get_error(&current, &p, e)), Err(e) => return Err(get_error(&current, p, e)),
} }
} }
@ -260,7 +260,7 @@ where
let fields = path.clone(); let fields = path.clone();
let to_replace = let to_replace =
get_data_by_column_path(&value, path, move |obj_source, column_path_tried, error| { get_data_by_column_path(value, path, move |obj_source, column_path_tried, error| {
let path_members_span = fields.maybe_span().unwrap_or_else(Span::unknown); let path_members_span = fields.maybe_span().unwrap_or_else(Span::unknown);
match &obj_source.value { match &obj_source.value {
@ -274,7 +274,7 @@ where
let suggestions: IndexSet<_> = rows let suggestions: IndexSet<_> = rows
.iter() .iter()
.filter_map(|r| { .filter_map(|r| {
nu_protocol::did_you_mean(&r, column_path_tried.as_string()) nu_protocol::did_you_mean(r, column_path_tried.as_string())
}) })
.map(|s| s[0].to_owned()) .map(|s| s[0].to_owned())
.collect(); .collect();
@ -345,7 +345,7 @@ where
let primary_label = format!("There isn't a column named '{}'", &column); let primary_label = format!("There isn't a column named '{}'", &column);
if let Some(suggestions) = if let Some(suggestions) =
nu_protocol::did_you_mean(&obj_source, column_path_tried.as_string()) nu_protocol::did_you_mean(obj_source, column_path_tried.as_string())
{ {
return ShellError::labeled_error_with_secondary( return ShellError::labeled_error_with_secondary(
"Unknown column", "Unknown column",
@ -380,7 +380,7 @@ where
} }
if let Some(suggestions) = if let Some(suggestions) =
nu_protocol::did_you_mean(&obj_source, column_path_tried.as_string()) nu_protocol::did_you_mean(obj_source, column_path_tried.as_string())
{ {
return ShellError::labeled_error( return ShellError::labeled_error(
"Unknown column", "Unknown column",
@ -396,7 +396,7 @@ where
let replacement = callback(&old_value)?; let replacement = callback(&old_value)?;
value value
.replace_data_at_column_path(&path, replacement) .replace_data_at_column_path(path, replacement)
.ok_or_else(|| { .ok_or_else(|| {
ShellError::labeled_error("missing column-path", "missing column-path", value.tag.span) ShellError::labeled_error("missing column-path", "missing column-path", value.tag.span)
}) })
@ -560,14 +560,14 @@ pub fn forgiving_insert_data_at_column_path(
.get_data_by_column_path(&cp, Box::new(move |_, _, err| err)) .get_data_by_column_path(&cp, Box::new(move |_, _, err| err))
.is_ok() .is_ok()
{ {
return insert_data_at_column_path(&value, &cp, candidate); return insert_data_at_column_path(value, &cp, candidate);
} else if let Some((last, front)) = cp.split_last() { } else if let Some((last, front)) = cp.split_last() {
let mut current: &mut Value = &mut original; let mut current: &mut Value = &mut original;
for member in front { for member in front {
let type_name = current.spanned_type_name(); let type_name = current.spanned_type_name();
current = get_mut_data_by_member(current, &member).ok_or_else(|| { current = get_mut_data_by_member(current, member).ok_or_else(|| {
ShellError::missing_property( ShellError::missing_property(
member.plain_string(std::usize::MAX).spanned(member.span), member.plain_string(std::usize::MAX).spanned(member.span),
type_name, type_name,
@ -575,7 +575,7 @@ pub fn forgiving_insert_data_at_column_path(
})? })?
} }
insert_data_at_member(current, &last, candidate)?; insert_data_at_member(current, last, candidate)?;
return Ok(original); return Ok(original);
} else { } else {
@ -585,7 +585,7 @@ pub fn forgiving_insert_data_at_column_path(
} }
} }
insert_data_at_column_path(&value, split_path, new_value) insert_data_at_column_path(value, split_path, new_value)
} }
pub fn insert_data_at_column_path( pub fn insert_data_at_column_path(
@ -601,7 +601,7 @@ pub fn insert_data_at_column_path(
for member in front { for member in front {
let type_name = current.spanned_type_name(); let type_name = current.spanned_type_name();
current = get_mut_data_by_member(current, &member).ok_or_else(|| { current = get_mut_data_by_member(current, member).ok_or_else(|| {
ShellError::missing_property( ShellError::missing_property(
member.plain_string(std::usize::MAX).spanned(member.span), member.plain_string(std::usize::MAX).spanned(member.span),
type_name, type_name,
@ -609,7 +609,7 @@ pub fn insert_data_at_column_path(
})? })?
} }
insert_data_at_member(current, &last, new_value)?; insert_data_at_member(current, last, new_value)?;
Ok(original) Ok(original)
} else { } else {
@ -801,7 +801,7 @@ pub(crate) fn get_mut_data_by_member<'value>(
) -> Option<&'value mut Value> { ) -> Option<&'value mut Value> {
match &mut value.value { match &mut value.value {
UntaggedValue::Row(o) => match &name.unspanned { UntaggedValue::Row(o) => match &name.unspanned {
UnspannedPathMember::String(string) => o.get_mut_data_by_key(&string), UnspannedPathMember::String(string) => o.get_mut_data_by_key(string),
UnspannedPathMember::Int(_) => None, UnspannedPathMember::Int(_) => None,
}, },
UntaggedValue::Table(l) => match &name.unspanned { UntaggedValue::Table(l) => match &name.unspanned {
@ -812,7 +812,7 @@ pub(crate) fn get_mut_data_by_member<'value>(
.. ..
} = item } = item
{ {
if let Some(v) = o.get_mut_data_by_key(&string) { if let Some(v) = o.get_mut_data_by_key(string) {
return Some(v); return Some(v);
} }
} }

View File

@ -328,7 +328,7 @@ pub fn view_contents_interactive(
let mut nes = neso::Nes::new(0.0); let mut nes = neso::Nes::new(0.0);
let rawkey = RawKey::new(); let rawkey = RawKey::new();
nes.load_rom(&buffer); nes.load_rom(buffer);
if let Some(ref sav_path) = sav_path { if let Some(ref sav_path) = sav_path {
if let Ok(contents) = std::fs::read(sav_path) { if let Ok(contents) = std::fs::read(sav_path) {

View File

@ -31,7 +31,7 @@ impl Plugin for BinaryView {
let low_res = call_info.args.has("lores"); let low_res = call_info.args.has("lores");
let skip = call_info.args.get("skip"); let skip = call_info.args.get("skip");
let length = call_info.args.get("bytes"); let length = call_info.args.get("bytes");
let _ = view_binary(&b, value_anchor.as_ref(), low_res, skip, length); let _ = view_binary(b, value_anchor.as_ref(), low_res, skip, length);
} }
} }
} }

View File

@ -60,7 +60,7 @@ impl SubCommand {
} }
fn display(model: &Model) -> Result<(), Box<dyn Error>> { fn display(model: &Model) -> Result<(), Box<dyn Error>> {
let mut app = Bar::from_model(&model)?; let mut app = Bar::from_model(model)?;
enable_raw_mode()?; enable_raw_mode()?;

View File

@ -60,7 +60,7 @@ impl SubCommand {
} }
fn display(model: &Model) -> Result<(), Box<dyn Error>> { fn display(model: &Model) -> Result<(), Box<dyn Error>> {
let mut app = Line::from_model(&model)?; let mut app = Line::from_model(model)?;
enable_raw_mode()?; enable_raw_mode()?;

View File

@ -31,7 +31,7 @@ impl Inc {
fn apply(&self, input: &str) -> UntaggedValue { fn apply(&self, input: &str) -> UntaggedValue {
match &self.action { match &self.action {
Some(Action::SemVerAction(act_on)) => { Some(Action::SemVerAction(act_on)) => {
let mut ver = match semver::Version::parse(&input) { let mut ver = match semver::Version::parse(input) {
Ok(parsed_ver) => parsed_ver, Ok(parsed_ver) => parsed_ver,
Err(_) => return UntaggedValue::string(input.to_string()), Err(_) => return UntaggedValue::string(input.to_string()),
}; };
@ -80,7 +80,7 @@ impl Inc {
Ok(UntaggedValue::filesize(b + 1_u64).into_value(value.tag())) Ok(UntaggedValue::filesize(b + 1_u64).into_value(value.tag()))
} }
UntaggedValue::Primitive(Primitive::String(ref s)) => { UntaggedValue::Primitive(Primitive::String(ref s)) => {
Ok(self.apply(&s).into_value(value.tag())) Ok(self.apply(s).into_value(value.tag()))
} }
UntaggedValue::Table(values) => { UntaggedValue::Table(values) => {
if values.len() == 1 { if values.len() == 1 {
@ -100,9 +100,9 @@ impl Inc {
let replace_for = get_data_by_column_path( let replace_for = get_data_by_column_path(
&value, &value,
&f, f,
move |obj_source, column_path_tried, _| match did_you_mean( move |obj_source, column_path_tried, _| match did_you_mean(
&obj_source, obj_source,
column_path_tried.as_string(), column_path_tried.as_string(),
) { ) {
Some(suggestions) => ShellError::labeled_error( Some(suggestions) => ShellError::labeled_error(
@ -122,7 +122,7 @@ impl Inc {
let replacement = self.inc(got)?; let replacement = self.inc(got)?;
value value
.replace_data_at_column_path(&f, replacement.value.into_untagged_value()) .replace_data_at_column_path(f, replacement.value.into_untagged_value())
.ok_or_else(|| { .ok_or_else(|| {
ShellError::labeled_error( ShellError::labeled_error(
"inc could not find field to replace", "inc could not find field to replace",

View File

@ -91,7 +91,7 @@ pub async fn post_helper(
let path_str = path.as_string()?; let path_str = path.as_string()?;
let (file_extension, contents, contents_tag) = let (file_extension, contents, contents_tag) =
post(&path_str, &body, user, password, &headers, path_tag.clone()).await?; post(&path_str, body, user, password, headers, path_tag.clone()).await?;
let file_extension = if has_raw { let file_extension = if has_raw {
None None
@ -456,7 +456,7 @@ fn json_list(input: &[Value]) -> Result<Vec<serde_json::Value>, ShellError> {
fn get_headers(call_info: &CallInfo) -> Result<Vec<HeaderKind>, ShellError> { fn get_headers(call_info: &CallInfo) -> Result<Vec<HeaderKind>, ShellError> {
let mut headers = vec![]; let mut headers = vec![];
match extract_header_value(&call_info, "content-type") { match extract_header_value(call_info, "content-type") {
Ok(h) => { Ok(h) => {
if let Some(ct) = h { if let Some(ct) = h {
headers.push(HeaderKind::ContentType(ct)) headers.push(HeaderKind::ContentType(ct))
@ -467,7 +467,7 @@ fn get_headers(call_info: &CallInfo) -> Result<Vec<HeaderKind>, ShellError> {
} }
}; };
match extract_header_value(&call_info, "content-length") { match extract_header_value(call_info, "content-length") {
Ok(h) => { Ok(h) => {
if let Some(cl) = h { if let Some(cl) = h {
headers.push(HeaderKind::ContentLength(cl)) headers.push(HeaderKind::ContentLength(cl))

View File

@ -137,7 +137,7 @@ mod tests {
fn validate_string() { fn validate_string() {
let json = r#"{ "name": { "first": "Tom", "last": "Anderson" }, "age": 37, "children": ["Sara", "Alex", "Jack"], "friends": [ { "first": "James", "last": "Murphy" }, { "first": "Roger", "last": "Craig" } ] }"#; let json = r#"{ "name": { "first": "Tom", "last": "Anderson" }, "age": 37, "children": ["Sara", "Alex", "Jack"], "friends": [ { "first": "James", "last": "Murphy" }, { "first": "Roger", "last": "Craig" } ] }"#;
let val = valid(json); let val = valid(json);
assert_eq!(val, true); assert!(val);
} }
#[test] #[test]

View File

@ -46,7 +46,7 @@ impl Plugin for Selector {
Value { Value {
value: UntaggedValue::Primitive(Primitive::String(s)), value: UntaggedValue::Primitive(Primitive::String(s)),
.. ..
} => Ok(begin_selector_query(s, &self) } => Ok(begin_selector_query(s, self)
.into_iter() .into_iter()
.map(ReturnSuccess::value) .map(ReturnSuccess::value)
.collect()), .collect()),

View File

@ -48,7 +48,7 @@ fn execute_selector_query_with_attribute(
) -> Vec<Value> { ) -> Vec<Value> {
let doc = Document::from(input_string); let doc = Document::from(input_string);
doc.select(&query_string) doc.select(query_string)
.iter() .iter()
.map(|selection| { .map(|selection| {
selection selection
@ -64,12 +64,12 @@ fn execute_selector_query(input_string: &str, query_string: &str, as_html: bool)
match as_html { match as_html {
true => doc true => doc
.select(&query_string) .select(query_string)
.iter() .iter()
.map(|selection| selection.html().to_string().to_string_value_create_tag()) .map(|selection| selection.html().to_string().to_string_value_create_tag())
.collect(), .collect(),
false => doc false => doc
.select(&query_string) .select(query_string)
.iter() .iter()
.map(|selection| selection.text().to_string().to_string_value_create_tag()) .map(|selection| selection.text().to_string().to_string_value_create_tag())
.collect(), .collect(),

View File

@ -16,6 +16,7 @@ pub struct Config {
pub pager: String, pub pager: String,
pub line_ranges: bat::line_range::LineRanges, pub line_ranges: bat::line_range::LineRanges,
// TODO: Not configurable // TODO: Not configurable
#[allow(unused)]
highlight_range: String, highlight_range: String,
// TODO: Not configurable // TODO: Not configurable
pub highlight_range_from: u64, pub highlight_range_from: u64,

View File

@ -13,7 +13,7 @@ impl Plugin for TreeViewer {
fn sink(&mut self, _call_info: CallInfo, input: Vec<Value>) { fn sink(&mut self, _call_info: CallInfo, input: Vec<Value>) {
if !input.is_empty() { if !input.is_empty() {
for i in input.iter() { for i in input.iter() {
let view = TreeView::from_value(&i); let view = TreeView::from_value(i);
let _ = view.render_view(); let _ = view.render_view();
} }
} }