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;
write!(f, "{}{}", RESET, self.1.prefix())
}
Difference::NoDifference => {
Difference::Empty => {
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
/// control codes need to be printed.
NoDifference,
Empty,
}
impl Difference {
@ -40,7 +40,7 @@ impl Difference {
// it commented out for now, and defaulting to Reset.
if first == next {
return NoDifference;
return Empty;
}
// 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!(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()));

View File

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

View File

@ -43,7 +43,7 @@ pub fn unstyle(strs: &AnsiStrings) -> String {
let mut s = String::new();
for i in strs.0.iter() {
s += &i.deref();
s += i.deref();
}
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 readline = Err(ReadlineError::Eof);
while let Some(ref cmd) = initial_command {
readline = rl.readline_with_initial(&prompt, (&cmd, ""));
readline = rl.readline_with_initial(&prompt, (cmd, ""));
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
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 {
ctx.scope.exit_scope();
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) {
locations.push(LocationType::Command.spanned(Span::new(pos, pos)));
locations
} else {
// TODO this should be able to be mapped to a command
locations.push(LocationType::Argument(command, None).spanned(Span::new(pos, pos)));
locations
}
locations
} else {
// Cursor is before any possible completion location, so must be a command
vec![LocationType::Command.spanned(Span::unknown())]

View File

@ -60,7 +60,7 @@ impl rustyline::completion::Completer for Helper {
impl rustyline::hint::Hinter for Helper {
type Hint = 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);
helper.update(&mut buffer, "cd ".len(), &replacement);
helper.update(&mut buffer, "cd ".len(), replacement);
assert_eq!(
buffer.as_str(),
@ -186,7 +186,7 @@ mod tests {
let helper = Helper::new(EvaluationContext::basic(), None);
helper.update(&mut buffer, "cd ".len(), &replacement);
helper.update(&mut buffer, "cd ".len(), replacement);
assert_eq!(
buffer.as_str(),

View File

@ -326,7 +326,7 @@ fn get_result_shape_of_math_expr(
for expr in &[&bin.left, &bin.right] {
let shape = match &expr.expr {
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),
};
@ -537,19 +537,19 @@ impl VarSyntaxShapeDeductor {
}
Expression::Block(b) => {
trace!("Inferring vars in block");
self.infer_shape(&b, scope)?;
self.infer_shape(b, scope)?;
}
Expression::FullColumnPath(path) => {
trace!("Inferring vars in path");
match &path.head.expr {
//PathMember can't be var yet (?)
//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) => {
self.checked_insert(
&VarUsage::new(var_name, span),
VarShapeDeduction::from_usage_with_alternatives(
&span,
span,
&get_shapes_allowed_in_path(),
),
)?;
@ -573,9 +573,9 @@ impl VarSyntaxShapeDeductor {
if let Some(range_right) = &range.right {
if let Expression::Variable(var_name, span) = &range_right.expr {
self.checked_insert(
&VarUsage::new(&var_name, &spanned_expr.span),
&VarUsage::new(var_name, &spanned_expr.span),
VarShapeDeduction::from_usage_with_alternatives(
&span,
span,
&get_shapes_allowed_in_range(),
),
)?;
@ -745,7 +745,7 @@ impl VarSyntaxShapeDeductor {
let shapes = get_shapes_decay_able_to_bool();
// shapes.push(SyntaxShape::Math);
self.checked_insert(
&var,
var,
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(
var,
bin_spanned,
&list,
list,
(pipeline_idx, pipeline),
);
match shapes_in_list {
@ -879,7 +879,7 @@ impl VarSyntaxShapeDeductor {
var,
VarShapeDeduction::from_usage_with_alternatives(
&var.span,
&MULT_DIV_LOOKUP_TABLE
MULT_DIV_LOOKUP_TABLE
.get(&(op, var_side, shape))
.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;
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)) => {
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(
&args,
args,
&mut calendar_vec_deque,
&tag,
tag,
selected_year,
month_number,
new_current_day_option,

View File

@ -625,26 +625,26 @@ mod tests {
#[test]
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_eq!(argument_is_quoted("'a"), false);
assert_eq!(argument_is_quoted("a"), false);
assert_eq!(argument_is_quoted("a'"), false);
assert_eq!(argument_is_quoted("''"), true);
assert!(!argument_is_quoted("'"));
assert!(!argument_is_quoted("'a"));
assert!(!argument_is_quoted("a"));
assert!(!argument_is_quoted("a'"));
assert!(argument_is_quoted("''"));
assert_eq!(argument_is_quoted(r#"""#), false);
assert_eq!(argument_is_quoted(r#""a"#), false);
assert_eq!(argument_is_quoted(r#"a"#), false);
assert_eq!(argument_is_quoted(r#"a""#), false);
assert_eq!(argument_is_quoted(r#""""#), true);
assert!(!argument_is_quoted(r#"""#));
assert!(!argument_is_quoted(r#""a"#));
assert!(!argument_is_quoted(r#"a"#));
assert!(!argument_is_quoted(r#"a""#));
assert!(argument_is_quoted(r#""""#));
assert_eq!(argument_is_quoted("'andrés"), false);
assert_eq!(argument_is_quoted("andrés'"), false);
assert_eq!(argument_is_quoted(r#""andrés"#), false);
assert_eq!(argument_is_quoted(r#"andrés""#), false);
assert_eq!(argument_is_quoted("'andrés'"), true);
assert_eq!(argument_is_quoted(r#""andrés""#), true);
assert!(!argument_is_quoted("'andrés"));
assert!(!argument_is_quoted("andrés'"));
assert!(!argument_is_quoted(r#""andrés"#));
assert!(!argument_is_quoted(r#"andrés""#));
assert!(argument_is_quoted("'andrés'"));
assert!(argument_is_quoted(r#""andrés""#));
}
#[test]

View File

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

View File

@ -85,7 +85,7 @@ fn flat_value(
} = value
{
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());
} else {
out.insert_value(column, value.clone());
@ -141,7 +141,7 @@ fn flat_value(
}
} else if a_table.is_none() {
a_table = Some(TableInside::Entries(
&column,
column,
&value.tag,
value.table_entries().collect(),
))

View File

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

View File

@ -102,7 +102,7 @@ fn from_eml(args: CommandArgs) -> Result<OutputStream, ShellError> {
}
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 {

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 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);
row.insert_untagged(

View File

@ -99,7 +99,7 @@ fn convert_yaml_value_to_nu_value(
.first()
.and_then(|e| match e {
(serde_yaml::Value::String(s), serde_yaml::Value::Null) => Some(
UntaggedValue::string("{{ ".to_owned() + &s + " }}")
UntaggedValue::string("{{ ".to_owned() + s + " }}")
.into_value(tag),
),
_ => 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(
"Unknown column",
format!("did you mean '{}'?", suggestions[0]),
@ -146,7 +146,7 @@ pub fn get_column_path_from_table_error(
let suggestions: IndexSet<_> = rows
.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())
.collect();
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);
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(
"Unknown column",
primary_label,

View File

@ -241,16 +241,16 @@ pub fn group(
let block = Box::new(move |_, row: &Value| {
match row.get_data_by_key(column_name.borrow_spanned()) {
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) => {
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(
"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 group_key = row
.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")
});
@ -107,7 +107,7 @@ pub fn group_by_date(args: CommandArgs) -> Result<OutputStream, ShellError> {
let block = Box::new(move |_, row: &Value| {
let group_key = row
.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)
});

View File

@ -48,7 +48,7 @@ fn help(args: CommandArgs) -> Result<ActionStream, ShellError> {
// Internal only commands shouldn't be displayed
.filter(|cmd_name| {
scope
.get_command(&cmd_name)
.get_command(cmd_name)
.filter(|command| !command.is_internal())
.is_some()
})
@ -63,7 +63,7 @@ fn help(args: CommandArgs) -> Result<ActionStream, ShellError> {
) -> Result<(), ShellError> {
let document_tag = rest[0].tag.clone();
let value = command_dict(
scope.get_command(&cmd_name).ok_or_else(|| {
scope.get_command(cmd_name).ok_or_else(|| {
ShellError::labeled_error(
format!("Could not load {}", cmd_name),
"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));
let string = std::iter::repeat("*")
.take(percentage.as_u64().map_err(|_| {
ShellError::labeled_error("expected a number", "expected a number", &name)
})? as usize)
.collect::<String>();
let string = "*".repeat(percentage.as_u64().map_err(|_| {
ShellError::labeled_error("expected a number", "expected a number", &name)
})? as usize);
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);
//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 {
Ok(condition) => match condition.as_bool() {
Ok(b) => {

View File

@ -98,7 +98,7 @@ pub fn letcmd(args: CommandArgs) -> Result<ActionStream, ShellError> {
};
ctx.scope.enter_scope();
let value = evaluate_baseline_expr(&expr, &ctx);
let value = evaluate_baseline_expr(expr, &ctx);
ctx.scope.exit_scope();
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 modes = Vec::<Value>::new();
for (value, frequency) in frequency_map.iter() {
match max_freq.cmp(&frequency) {
match max_freq.cmp(frequency) {
Ordering::Less => {
max_freq = *frequency;
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> {
if values.iter().all(|v| v.is_primitive()) {
mf(&values, &name)
mf(values, name)
} else {
// If we are not dealing with Primitives, then perhaps we are dealing with a table
// 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
let mut column_totals = IndexMap::new();
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);
}
}

View File

@ -181,7 +181,7 @@ where
let cloned_args = Arc::clone(&args);
ret = match ret.swap_data_by_column_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,
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();
if value.is_row() {
let columns = value.data_descriptors();
if options.move_headers() {
let columns = value.data_descriptors();
if let Some(fields) = rotate(columns, &options.by, direction) {
return Some(vec![select_fields(&value, &fields, &tag)]);
}
} else {
let columns = value.data_descriptors();
let values_rotated = rotate(
value
.row_entries()

View File

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

View File

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

View File

@ -71,16 +71,16 @@ pub fn split(
let block = Box::new(move |_, row: &Value| {
match row.get_data_by_key(column_name.borrow_spanned()) {
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) => {
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 {
Ok(strings) => {
let output = strings.join(&separator);
let output = strings.join(separator);
Ok(ActionStream::one(ReturnSuccess::value(
UntaggedValue::string(output).into_value(tag),

View File

@ -114,7 +114,7 @@ mod tests {
let pattern = ".toml";
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);
}
@ -124,7 +124,7 @@ mod tests {
let pattern = "Car";
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);
}
}

View File

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

View File

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

View File

@ -114,7 +114,7 @@ mod tests {
let pattern = "Car";
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);
}
@ -124,7 +124,7 @@ mod tests {
let pattern = ".toml";
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);
}
}

View File

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

View File

@ -57,13 +57,7 @@ pub fn from_list(
.into_iter()
.map(|x| StyledString::new(x, header_style))
.collect();
let entries = values_to_entries(
values,
&mut headers,
&configuration,
starting_idx,
&color_hm,
);
let entries = values_to_entries(values, &mut headers, configuration, starting_idx, color_hm);
nu_table::Table {
headers,
data: entries,
@ -96,11 +90,11 @@ fn values_to_entries(
..
} => StyledString::new(
format_leaf(&UntaggedValue::nothing()).plain_string(100_000),
style_leaf(&UntaggedValue::nothing(), &color_hm),
style_leaf(&UntaggedValue::nothing(), color_hm),
),
_ => StyledString::new(
format_leaf(value).plain_string(100_000),
style_leaf(value, &color_hm),
style_leaf(value, color_hm),
),
}
} else {
@ -113,12 +107,12 @@ fn values_to_entries(
StyledString::new(
format_leaf(data.borrow()).plain_string(100_000),
style_leaf(data.borrow(), &color_hm),
style_leaf(data.borrow(), color_hm),
)
}
_ => StyledString::new(
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() {
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.");
@ -50,7 +50,7 @@ fn from_value_to_delimited_string(
.delimiter(separator as u8)
.from_writer(vec![]);
let merged_descriptors = merge_descriptors(&list);
let merged_descriptors = merge_descriptors(list);
if merged_descriptors.is_empty() {
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("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 {
let theme_tag = match &theme {
Some(v) => &v.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 {
Ok(c) => c,
_ => {
@ -362,11 +357,10 @@ fn to_html(args: CommandArgs) -> Result<OutputStream, ShellError> {
setup_no_color_regexes(&mut regex_hm);
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 {
@ -393,7 +387,7 @@ fn html_table(table: Vec<Value>, headers: Vec<String>) -> String {
output_string.push_str("<tr>");
for header in &headers {
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("</tr>");

View File

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

View File

@ -117,7 +117,7 @@ fn process(
})
.collect::<String>()
} 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()) {
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());
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 {
let headers = nu_protocol::merge_descriptors(&input);
let headers = nu_protocol::merge_descriptors(input);
let (escaped_headers, mut column_widths) = collect_headers(&headers);

View File

@ -51,7 +51,7 @@ where
for path in &paths {
ret = ret.swap_data_by_column_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;
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.add_vars(&self.block.captured.entries);

View File

@ -209,7 +209,7 @@ fn parse_line(line: &str, ctx: &EvaluationContext) -> Result<ClassifiedBlock, Sh
line
};
let (lite_result, err) = nu_parser::lex(&line, 0);
let (lite_result, err) = nu_parser::lex(line, 0);
if let Some(err) = err {
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> {
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 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> {
//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
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.",
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 {
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>) {
if let Ok(var) = val.as_string() {
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) {
*v = color;
} else {
@ -157,64 +157,64 @@ pub fn get_color_config(config: &NuConfig) -> HashMap<String, Style> {
for (key, value) in primitive_color_vars.row_entries() {
match key.as_ref() {
"primitive_int" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"primitive_decimal" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"primitive_filesize" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"primitive_string" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"primitive_line" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"primitive_columnpath" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"primitive_pattern" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"primitive_boolean" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"primitive_date" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"primitive_duration" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"primitive_range" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"primitive_path" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"primitive_binary" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"separator_color" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"header_align" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"header_color" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"header_bold" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"header_style" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"index_color" => {
update_hashmap(&key, &value, &mut hm);
update_hashmap(key, value, &mut hm);
}
"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() {
let group_key = if let Some(ref grouper) = grouper {
grouper(idx, &value)
grouper(idx, value)
} else {
as_string(&value)
as_string(value)
};
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>,
) -> Box<dyn Fn(&Value, Vec<&Value>) -> Result<Value, ShellError> + Send + Sync + 'static> {
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(),
Err((left_type, right_type)) => {
return Err(ShellError::coerce_error(
@ -164,7 +164,7 @@ pub fn sum(data: Vec<&Value>) -> Result<Value, ShellError> {
for value in data {
match value.value {
UntaggedValue::Primitive(_) => {
acc = match unsafe_compute_values(Operator::Plus, &acc, &value) {
acc = match unsafe_compute_values(Operator::Plus, &acc, value) {
Ok(v) => v,
Err((left_type, right_type)) => {
return Err(ShellError::coerce_error(
@ -314,8 +314,8 @@ pub fn percentages(
.filter_map(|s| {
let hundred = UntaggedValue::decimal_from_float(100.0, tag.span);
match unsafe_compute_values(Operator::Divide, &hundred, &maxima) {
Ok(v) => match unsafe_compute_values(Operator::Multiply, &s, &v) {
match unsafe_compute_values(Operator::Divide, &hundred, maxima) {
Ok(v) => match unsafe_compute_values(Operator::Multiply, s, &v) {
Ok(v) => Some(v.into_untagged_value()),
Err(_) => None,
},

View File

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

View File

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

View File

@ -590,7 +590,7 @@ pub fn style_leaf<'a>(
let str_len = str.len();
let paren_index = str.find('(').unwrap_or(str_len - 1);
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(),
}

View File

@ -26,7 +26,7 @@ pub fn evaluate_baseline_expr(
};
let span = expr.span;
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(
"Invalid external word".spanned(tag.span),
ArgumentError::InvalidExternalWord,
@ -35,7 +35,7 @@ pub fn evaluate_baseline_expr(
Expression::Synthetic(hir::Synthetic::String(s)) => {
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::Subexpression(block) => evaluate_subexpression(block, ctx),
Expression::ExternalCommand(_) => unimplemented!(),
@ -68,13 +68,13 @@ pub fn evaluate_baseline_expr(
}
Expression::Range(range) => {
let left = if let Some(left) = &range.left {
evaluate_baseline_expr(&left, ctx)?
evaluate_baseline_expr(left, ctx)?
} else {
Value::nothing()
};
let right = if let Some(right) = &range.right {
evaluate_baseline_expr(&right, ctx)?
evaluate_baseline_expr(right, ctx)?
} else {
Value::nothing()
};
@ -100,7 +100,7 @@ pub fn evaluate_baseline_expr(
let mut output_headers = vec![];
for expr in headers {
let val = evaluate_baseline_expr(&expr, ctx)?;
let val = evaluate_baseline_expr(expr, ctx)?;
let header = val.as_string()?;
output_headers.push(header);
@ -128,7 +128,7 @@ pub fn evaluate_baseline_expr(
let mut row_output = IndexMap::new();
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);
}
output_table.push(UntaggedValue::row(row_output).into_value(tag.clone()));
@ -140,7 +140,7 @@ pub fn evaluate_baseline_expr(
let mut exprs = vec![];
for expr in list {
let expr = evaluate_baseline_expr(&expr, ctx)?;
let expr = evaluate_baseline_expr(expr, ctx)?;
exprs.push(expr);
}
@ -228,7 +228,7 @@ fn evaluate_literal(literal: &hir::Literal, span: Span) -> Value {
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::GlobPattern(pattern) => UntaggedValue::glob_pattern(pattern).into_value(span),
hir::Literal::Bare(bare) => UntaggedValue::string(bare.clone()).into_value(span),
@ -287,7 +287,7 @@ fn evaluate_subexpression(
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();

View File

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

View File

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

View File

@ -105,9 +105,9 @@ impl DirInfo {
match f {
Ok(i) => match i.file_type() {
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()),
@ -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.blocks += d.blocks;
self.dirs.push(d);

View File

@ -931,7 +931,7 @@ fn move_file(from: TaggedPathBuf, to: TaggedPathBuf) -> Result<(), ShellError> {
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> {

View File

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

View File

@ -40,7 +40,7 @@ impl<R: Read> Iterator for BufCodecReader<R> {
let buffer = self.input.fill_buf();
match buffer {
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();
self.input.consume(buffer_len);

View File

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

View File

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

View File

@ -65,7 +65,7 @@ pub fn process_script(
} else {
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);
//println!("{:#?}", pipeline);
@ -111,7 +111,7 @@ pub fn process_script(
&& args
.positional
.as_ref()
.map(|ref v| v.len() == 1)
.map(|v| v.len() == 1)
.unwrap_or(true)
&& args
.named
@ -120,7 +120,7 @@ pub fn process_script(
.unwrap_or(true)
&& canonicalize(ctx.shell_manager.path(), name).is_ok()
&& Path::new(&name).is_dir()
&& !ctx.host.lock().is_external_cmd(&name)
&& !ctx.host.lock().is_external_cmd(name)
{
let tag = Tag {
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 {
std::process::exit(error_code);
}
@ -297,7 +297,7 @@ pub fn run_script_standalone(
.lock()
.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 {
std::process::exit(1);
}

View File

@ -72,10 +72,8 @@ impl Painter {
current_style = self.styles[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]);

View File

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

View File

@ -537,7 +537,7 @@ fn parse_dollar_expr(
&& lite_arg.item.ends_with('\''))
{
// 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) {
(expr, None)
} 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 delimiter_stack = vec![')'];
while let Some(c) = loop_input.next() {
for c in &mut loop_input {
end += 1;
if let Some('\'') = delimiter_stack.last() {
if c == '\'' {
@ -726,9 +726,9 @@ fn parse_external_arg(
scope: &dyn ParserScope,
) -> (SpannedExpression, Option<ParseError>) {
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('(') {
parse_subexpression(&lite_arg, scope)
parse_subexpression(lite_arg, scope)
} else {
(
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];
for arg in &lite_cells.parts {
let (string, err) = verify_and_strip(&arg, '[', ']');
let (string, err) = verify_and_strip(arg, '[', ']');
if error.is_none() {
error = err;
}
@ -891,12 +891,12 @@ fn parse_arg(
lite_arg: &Spanned<String>,
) -> (SpannedExpression, Option<ParseError>) {
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
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 {
@ -954,13 +954,13 @@ fn parse_arg(
)
}
SyntaxShape::Range => parse_range(&lite_arg, scope),
SyntaxShape::Range => parse_range(lite_arg, scope),
SyntaxShape::Operator => (
garbage(lite_arg.span),
Some(ParseError::mismatch("operator", lite_arg.clone())),
),
SyntaxShape::Filesize => parse_filesize(&lite_arg),
SyntaxShape::Duration => parse_duration(&lite_arg),
SyntaxShape::Filesize => parse_filesize(lite_arg),
SyntaxShape::Duration => parse_duration(lite_arg),
SyntaxShape::FilePath => {
let trimmed = trim_quotes(&lite_arg.item);
let expanded = expand_path(&trimmed).to_string();
@ -1084,7 +1084,7 @@ fn parse_arg(
// We've found a parameter list
let mut param_tokens = vec![];
let mut token_iter = tokens.into_iter().skip(1);
while let Some(token) = token_iter.next() {
for token in &mut token_iter {
if matches!(
token,
Token {
@ -1478,7 +1478,7 @@ fn parse_internal_command(
);
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 named = NamedArguments::new();
@ -1489,7 +1489,7 @@ fn parse_internal_command(
while idx < lite_cmd.parts.len() {
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(
&signature,
signature,
&internal_command,
&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 cell in row {
output.append(&mut expression_to_flat_shape(&cell));
output.append(&mut expression_to_flat_shape(cell));
}
}
output

View File

@ -112,7 +112,7 @@ impl CallStub {
}
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()
.expect("Failed! Expected valid column path.");
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
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
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

View File

@ -78,7 +78,7 @@ impl ColumnPath {
span: _,
},
_,
) = parse(&text)
) = parse(text)
{
ColumnPath {
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> {
let mut output = vec![];
while let Some(x) = self.values.next() {
for x in &mut self.values {
output.push(x);
}
output

View File

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

View File

@ -886,7 +886,7 @@ impl WrappedTable {
if self.theme.print_top_border {
output.push_str(
self.print_separator(SeparatorPosition::Top, &color_hm)
self.print_separator(SeparatorPosition::Top, color_hm)
.as_str(),
);
}
@ -895,7 +895,7 @@ impl WrappedTable {
|| (self.headers.len() == 1 && self.headers[0].max_width == 0);
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;
@ -904,7 +904,7 @@ impl WrappedTable {
if !first_row {
if self.theme.separate_rows {
output.push_str(
self.print_separator(SeparatorPosition::Middle, &color_hm)
self.print_separator(SeparatorPosition::Middle, color_hm)
.as_str(),
)
}
@ -913,18 +913,18 @@ impl WrappedTable {
if self.theme.separate_header && !self.headers.is_empty() && !skip_headers {
output.push_str(
self.print_separator(SeparatorPosition::Middle, &color_hm)
self.print_separator(SeparatorPosition::Middle, color_hm)
.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 {
output.push_str(
self.print_separator(SeparatorPosition::Bottom, &color_hm)
self.print_separator(SeparatorPosition::Bottom, color_hm)
.as_str(),
);
}
@ -1073,12 +1073,12 @@ pub fn draw_table(table: &Table, termwidth: usize, color_hm: &HashMap<String, St
let wrapped_table = wrap_cells(
processed_table,
max_column_width,
&color_hm,
color_hm,
&re_leading,
&re_trailing,
);
wrapped_table.print_table(&color_hm)
wrapped_table.print_table(color_hm)
}
fn wrap_cells(
@ -1111,9 +1111,9 @@ fn wrap_cells(
let (mut lines, inner_max_width) = wrap(
max_column_width,
contents.into_iter(),
&color_hm,
&re_leading,
&re_trailing,
color_hm,
re_leading,
re_trailing,
);
wrapped.lines.append(&mut lines);
if inner_max_width > wrapped.max_width {
@ -1139,9 +1139,9 @@ fn wrap_cells(
let (mut lines, inner_max_width) = wrap(
max_column_width,
contents.into_iter(),
&color_hm,
&re_leading,
&re_trailing,
color_hm,
re_leading,
re_trailing,
);
wrapped.lines.append(&mut lines);
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 current_line.len() == 1 && current_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 {
let width = subline.width;
lines.push(Line {
@ -200,7 +200,7 @@ pub fn wrap<'a>(
None => {
if current_width > cell_width {
// 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 {
let width = subline.width;
lines.push(Line {
@ -231,12 +231,11 @@ pub fn wrap<'a>(
if !first {
current_line_width += 1 + subline.width;
current_line.push(' ');
current_line.push_str(subline.subline);
} else {
first = false;
current_line_width = subline.width;
current_line.push_str(subline.subline);
}
current_line.push_str(subline.subline);
}
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();
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.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 {
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 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);
match &obj_source.value {
@ -274,7 +274,7 @@ where
let suggestions: IndexSet<_> = rows
.iter()
.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())
.collect();
@ -345,7 +345,7 @@ where
let primary_label = format!("There isn't a column named '{}'", &column);
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(
"Unknown column",
@ -380,7 +380,7 @@ where
}
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(
"Unknown column",
@ -396,7 +396,7 @@ where
let replacement = callback(&old_value)?;
value
.replace_data_at_column_path(&path, replacement)
.replace_data_at_column_path(path, replacement)
.ok_or_else(|| {
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))
.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() {
let mut current: &mut Value = &mut original;
for member in front {
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(
member.plain_string(std::usize::MAX).spanned(member.span),
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);
} 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(
@ -601,7 +601,7 @@ pub fn insert_data_at_column_path(
for member in front {
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(
member.plain_string(std::usize::MAX).spanned(member.span),
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)
} else {
@ -801,7 +801,7 @@ pub(crate) fn get_mut_data_by_member<'value>(
) -> Option<&'value mut Value> {
match &mut value.value {
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,
},
UntaggedValue::Table(l) => match &name.unspanned {
@ -812,7 +812,7 @@ pub(crate) fn get_mut_data_by_member<'value>(
..
} = 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);
}
}

View File

@ -328,7 +328,7 @@ pub fn view_contents_interactive(
let mut nes = neso::Nes::new(0.0);
let rawkey = RawKey::new();
nes.load_rom(&buffer);
nes.load_rom(buffer);
if let Some(ref sav_path) = 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 skip = call_info.args.get("skip");
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>> {
let mut app = Bar::from_model(&model)?;
let mut app = Bar::from_model(model)?;
enable_raw_mode()?;

View File

@ -60,7 +60,7 @@ impl SubCommand {
}
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()?;

View File

@ -31,7 +31,7 @@ impl Inc {
fn apply(&self, input: &str) -> UntaggedValue {
match &self.action {
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,
Err(_) => return UntaggedValue::string(input.to_string()),
};
@ -80,7 +80,7 @@ impl Inc {
Ok(UntaggedValue::filesize(b + 1_u64).into_value(value.tag()))
}
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) => {
if values.len() == 1 {
@ -100,9 +100,9 @@ impl Inc {
let replace_for = get_data_by_column_path(
&value,
&f,
f,
move |obj_source, column_path_tried, _| match did_you_mean(
&obj_source,
obj_source,
column_path_tried.as_string(),
) {
Some(suggestions) => ShellError::labeled_error(
@ -122,7 +122,7 @@ impl Inc {
let replacement = self.inc(got)?;
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(|| {
ShellError::labeled_error(
"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 (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 {
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> {
let mut headers = vec![];
match extract_header_value(&call_info, "content-type") {
match extract_header_value(call_info, "content-type") {
Ok(h) => {
if let Some(ct) = h {
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) => {
if let Some(cl) = h {
headers.push(HeaderKind::ContentLength(cl))

View File

@ -137,7 +137,7 @@ mod tests {
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 val = valid(json);
assert_eq!(val, true);
assert!(val);
}
#[test]

View File

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

View File

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

View File

@ -16,6 +16,7 @@ pub struct Config {
pub pager: String,
pub line_ranges: bat::line_range::LineRanges,
// TODO: Not configurable
#[allow(unused)]
highlight_range: String,
// TODO: Not configurable
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>) {
if !input.is_empty() {
for i in input.iter() {
let view = TreeView::from_value(&i);
let view = TreeView::from_value(i);
let _ = view.render_view();
}
}