mirror of
https://github.com/nushell/nushell
synced 2024-11-10 15:14:14 +00:00
Add general refactorings (#3996)
This commit is contained in:
parent
ae9f4135c0
commit
51c74eebd0
165 changed files with 540 additions and 615 deletions
|
@ -93,7 +93,7 @@ pub static RESET: &str = "\x1B[0m";
|
|||
|
||||
impl Color {
|
||||
fn write_foreground_code<W: AnyWrite + ?Sized>(&self, f: &mut W) -> Result<(), W::Error> {
|
||||
match *self {
|
||||
match self {
|
||||
Color::Black => write!(f, "30"),
|
||||
Color::Red => write!(f, "31"),
|
||||
Color::Green => write!(f, "32"),
|
||||
|
@ -103,8 +103,8 @@ impl Color {
|
|||
Color::Magenta => write!(f, "35"),
|
||||
Color::Cyan => write!(f, "36"),
|
||||
Color::White => write!(f, "37"),
|
||||
Color::Fixed(num) => write!(f, "38;5;{}", &num),
|
||||
Color::Rgb(r, g, b) => write!(f, "38;2;{};{};{}", &r, &g, &b),
|
||||
Color::Fixed(num) => write!(f, "38;5;{}", num),
|
||||
Color::Rgb(r, g, b) => write!(f, "38;2;{};{};{}", r, g, b),
|
||||
Color::DarkGray => write!(f, "90"),
|
||||
Color::LightRed => write!(f, "91"),
|
||||
Color::LightGreen => write!(f, "92"),
|
||||
|
@ -118,7 +118,7 @@ impl Color {
|
|||
}
|
||||
|
||||
fn write_background_code<W: AnyWrite + ?Sized>(&self, f: &mut W) -> Result<(), W::Error> {
|
||||
match *self {
|
||||
match self {
|
||||
Color::Black => write!(f, "40"),
|
||||
Color::Red => write!(f, "41"),
|
||||
Color::Green => write!(f, "42"),
|
||||
|
@ -128,8 +128,8 @@ impl Color {
|
|||
Color::Magenta => write!(f, "45"),
|
||||
Color::Cyan => write!(f, "46"),
|
||||
Color::White => write!(f, "47"),
|
||||
Color::Fixed(num) => write!(f, "48;5;{}", &num),
|
||||
Color::Rgb(r, g, b) => write!(f, "48;2;{};{};{}", &r, &g, &b),
|
||||
Color::Fixed(num) => write!(f, "48;5;{}", num),
|
||||
Color::Rgb(r, g, b) => write!(f, "48;2;{};{};{}", r, g, b),
|
||||
Color::DarkGray => write!(f, "100"),
|
||||
Color::LightRed => write!(f, "101"),
|
||||
Color::LightGreen => write!(f, "102"),
|
||||
|
|
|
@ -297,7 +297,7 @@ mod tests {
|
|||
fn no_control_codes_for_plain() {
|
||||
let one = Style::default().paint("one");
|
||||
let two = Style::default().paint("two");
|
||||
let output = format!("{}", AnsiStrings(&[one, two]));
|
||||
assert_eq!(&*output, "onetwo");
|
||||
let output = AnsiStrings(&[one, two]).to_string();
|
||||
assert_eq!(output, "onetwo");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -602,14 +602,14 @@ mod serde_json_tests {
|
|||
|
||||
#[test]
|
||||
fn color_deserialization() {
|
||||
let colors = &[
|
||||
let colors = [
|
||||
Color::Red,
|
||||
Color::Blue,
|
||||
Color::Rgb(123, 123, 123),
|
||||
Color::Fixed(255),
|
||||
];
|
||||
|
||||
for color in colors.iter() {
|
||||
for color in colors {
|
||||
let serialized = serde_json::to_string(&color).unwrap();
|
||||
let deserialized: Color = serde_json::from_str(&serialized).unwrap();
|
||||
|
||||
|
|
|
@ -75,6 +75,6 @@ mod test {
|
|||
assert_eq!(unstyled_len(&a), 18);
|
||||
|
||||
let l2 = [Black.paint("st"), Red.paint("-second"), White.paint("-t")];
|
||||
assert_eq!(sub_string(3, 11, &a).as_slice(), &l2);
|
||||
assert_eq!(sub_string(3, 11, &a), l2);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -508,14 +508,14 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn can_use_loglevels() -> Result<(), ShellError> {
|
||||
for level in &["error", "warn", "info", "debug", "trace"] {
|
||||
for level in ["error", "warn", "info", "debug", "trace"] {
|
||||
let ui = cli_app();
|
||||
let args = format!("nu --loglevel={}", *level);
|
||||
let args = format!("nu --loglevel={}", level);
|
||||
ui.parse(&args)?;
|
||||
assert_eq!(ui.loglevel().unwrap(), Ok(level.to_string()));
|
||||
|
||||
let ui = cli_app();
|
||||
let args = format!("nu -l {}", *level);
|
||||
let args = format!("nu -l {}", level);
|
||||
ui.parse(&args)?;
|
||||
assert_eq!(ui.loglevel().unwrap(), Ok(level.to_string()));
|
||||
}
|
||||
|
@ -541,11 +541,11 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn can_use_test_binaries() -> Result<(), ShellError> {
|
||||
for binarie_name in &[
|
||||
for binarie_name in [
|
||||
"echo_env", "cococo", "iecho", "fail", "nonu", "chop", "repeater", "meow",
|
||||
] {
|
||||
let ui = cli_app();
|
||||
let args = format!("nu --testbin={}", *binarie_name);
|
||||
let args = format!("nu --testbin={}", binarie_name);
|
||||
ui.parse(&args)?;
|
||||
assert_eq!(ui.testbin().unwrap(), Ok(binarie_name.to_string()));
|
||||
}
|
||||
|
|
|
@ -44,7 +44,7 @@ impl Options {
|
|||
}
|
||||
|
||||
pub fn get(&self, key: &str) -> Option<Value> {
|
||||
self.inner.borrow().get(key).map(Clone::clone)
|
||||
self.inner.borrow().get(key).cloned()
|
||||
}
|
||||
|
||||
pub fn put(&self, key: &str, value: Value) {
|
||||
|
|
|
@ -67,48 +67,37 @@ impl OptionsParser for NuParser {
|
|||
}
|
||||
};
|
||||
|
||||
let value =
|
||||
value
|
||||
.map(|v| match k.as_ref() {
|
||||
"testbin" => {
|
||||
if let Ok(name) = v.as_string() {
|
||||
if testbins().iter().any(|n| name == *n) {
|
||||
Some(v)
|
||||
} else {
|
||||
Some(
|
||||
UntaggedValue::Error(
|
||||
ShellError::untagged_runtime_error(
|
||||
format!("{} is not supported.", name),
|
||||
),
|
||||
)
|
||||
.into_value(v.tag),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Some(v)
|
||||
}
|
||||
let value = value.map(|v| match k.as_ref() {
|
||||
"testbin" => {
|
||||
if let Ok(name) = v.as_string() {
|
||||
if testbins().iter().any(|n| name == *n) {
|
||||
v
|
||||
} else {
|
||||
UntaggedValue::Error(ShellError::untagged_runtime_error(
|
||||
format!("{} is not supported.", name),
|
||||
))
|
||||
.into_value(v.tag)
|
||||
}
|
||||
"loglevel" => {
|
||||
if let Ok(name) = v.as_string() {
|
||||
if loglevels().iter().any(|n| name == *n) {
|
||||
Some(v)
|
||||
} else {
|
||||
Some(
|
||||
UntaggedValue::Error(
|
||||
ShellError::untagged_runtime_error(
|
||||
format!("{} is not supported.", name),
|
||||
),
|
||||
)
|
||||
.into_value(v.tag),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Some(v)
|
||||
}
|
||||
} else {
|
||||
v
|
||||
}
|
||||
}
|
||||
"loglevel" => {
|
||||
if let Ok(name) = v.as_string() {
|
||||
if loglevels().iter().any(|n| name == *n) {
|
||||
v
|
||||
} else {
|
||||
UntaggedValue::Error(ShellError::untagged_runtime_error(
|
||||
format!("{} is not supported.", name),
|
||||
))
|
||||
.into_value(v.tag)
|
||||
}
|
||||
_ => Some(v),
|
||||
})
|
||||
.flatten();
|
||||
} else {
|
||||
v
|
||||
}
|
||||
}
|
||||
_ => v,
|
||||
});
|
||||
|
||||
if let Some(value) = value {
|
||||
options.put(k, value);
|
||||
|
|
|
@ -165,7 +165,10 @@ pub fn cli(
|
|||
// Store cmd duration in an env var
|
||||
context.scope.add_env_var(
|
||||
"CMD_DURATION_MS",
|
||||
format!("{}", startup_commands_start_time.elapsed().as_millis()),
|
||||
startup_commands_start_time
|
||||
.elapsed()
|
||||
.as_millis()
|
||||
.to_string(),
|
||||
);
|
||||
|
||||
if options.perf {
|
||||
|
@ -353,7 +356,7 @@ pub fn cli(
|
|||
// Store cmd duration in an env var
|
||||
context.scope.add_env_var(
|
||||
"CMD_DURATION_MS",
|
||||
format!("{}", cmd_start_time.elapsed().as_millis()),
|
||||
cmd_start_time.elapsed().as_millis().to_string(),
|
||||
);
|
||||
|
||||
match line {
|
||||
|
@ -397,8 +400,7 @@ pub fn cli(
|
|||
.lock()
|
||||
.global_config
|
||||
.as_ref()
|
||||
.map(|cfg| cfg.var("ctrlc_exit"))
|
||||
.flatten()
|
||||
.and_then(|cfg| cfg.var("ctrlc_exit"))
|
||||
.map(|ctrl_c| ctrl_c.is_true())
|
||||
.unwrap_or(false); // default behavior is to allow CTRL-C spamming similar to other shells
|
||||
|
||||
|
|
|
@ -461,7 +461,7 @@ pub(crate) fn load_keybindings(
|
|||
if let Ok(contents) = contents {
|
||||
let keybindings: Keybindings = serde_yaml::from_str(&contents)?;
|
||||
// eprintln!("{:#?}", keybindings);
|
||||
for keybinding in keybindings.into_iter() {
|
||||
for keybinding in keybindings {
|
||||
let (k, b) = convert_keybinding(keybinding);
|
||||
// eprintln!("{:?} {:?}", k, b);
|
||||
|
||||
|
|
|
@ -509,7 +509,7 @@ fn spawn(
|
|||
Ok(stream.into_input_stream())
|
||||
}
|
||||
Err(e) => Err(ShellError::labeled_error(
|
||||
format!("{}", e),
|
||||
e.to_string(),
|
||||
"failed to spawn",
|
||||
&command.name_tag,
|
||||
)),
|
||||
|
|
|
@ -159,7 +159,7 @@ pub fn action(
|
|||
}
|
||||
|
||||
fn format_int(int: i64) -> String {
|
||||
format!("{}", int)
|
||||
int.to_string()
|
||||
|
||||
// TODO once platform-specific dependencies are stable (see Cargo.toml)
|
||||
// #[cfg(windows)]
|
||||
|
@ -176,7 +176,7 @@ fn format_int(int: i64) -> String {
|
|||
}
|
||||
|
||||
fn format_bigint(int: &BigInt) -> String {
|
||||
format!("{}", int)
|
||||
int.to_string()
|
||||
|
||||
// TODO once platform-specific dependencies are stable (see Cargo.toml)
|
||||
// #[cfg(windows)]
|
||||
|
@ -230,7 +230,7 @@ fn format_decimal(mut decimal: BigDecimal, digits: Option<u64>, group_digits: bo
|
|||
let format_default_loc = |int_part: BigInt| {
|
||||
let loc = Locale::en;
|
||||
//TODO: when num_format is available for recent bigint, replace this with the locale-based format
|
||||
let (int_str, sep) = (format!("{}", int_part), String::from(loc.decimal()));
|
||||
let (int_str, sep) = (int_part.to_string(), String::from(loc.decimal()));
|
||||
|
||||
format!("{}{}{}", int_str, sep, dec_str)
|
||||
};
|
||||
|
|
|
@ -55,17 +55,18 @@ fn make_error(value: &Value) -> Option<ShellError> {
|
|||
{
|
||||
let msg = dict.get_data_by_key("msg".spanned_unknown());
|
||||
|
||||
let labels = dict
|
||||
.get_data_by_key("labels".spanned_unknown())
|
||||
.map(|table| match &table.value {
|
||||
UntaggedValue::Table(_) => table
|
||||
.table_entries()
|
||||
.map(|value| value.as_string().ok())
|
||||
.collect(),
|
||||
UntaggedValue::Primitive(Primitive::String(label)) => Some(vec![label.to_string()]),
|
||||
_ => None,
|
||||
})
|
||||
.flatten();
|
||||
let labels =
|
||||
dict.get_data_by_key("labels".spanned_unknown())
|
||||
.and_then(|table| match &table.value {
|
||||
UntaggedValue::Table(_) => table
|
||||
.table_entries()
|
||||
.map(|value| value.as_string().ok())
|
||||
.collect(),
|
||||
UntaggedValue::Primitive(Primitive::String(label)) => {
|
||||
Some(vec![label.to_string()])
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
|
||||
let _anchor = dict.get_data_by_key("tag".spanned_unknown());
|
||||
let span = dict.get_data_by_key("span".spanned_unknown());
|
||||
|
@ -74,7 +75,7 @@ fn make_error(value: &Value) -> Option<ShellError> {
|
|||
return None;
|
||||
}
|
||||
|
||||
let msg = msg.map(|msg| msg.as_string().ok()).flatten();
|
||||
let msg = msg.and_then(|msg| msg.as_string().ok());
|
||||
|
||||
if let Some(labels) = labels {
|
||||
if labels.is_empty() {
|
||||
|
|
|
@ -50,7 +50,7 @@ impl WholeStreamCommand for Find {
|
|||
|
||||
fn row_contains(row: &Dictionary, search_terms: Vec<String>) -> bool {
|
||||
for term in search_terms {
|
||||
for (k, v) in row.entries.iter() {
|
||||
for (k, v) in &row.entries {
|
||||
let key = k.to_string().trim().to_lowercase();
|
||||
let value = v.convert_to_string().trim().to_lowercase();
|
||||
if key.contains(&term) || value.contains(&term) {
|
||||
|
|
|
@ -302,7 +302,7 @@ pub fn signature_dict(signature: Signature, tag: impl Into<Tag>) -> Value {
|
|||
let tag = tag.into();
|
||||
let mut sig = TaggedListBuilder::new(&tag);
|
||||
|
||||
for arg in signature.positional.iter() {
|
||||
for arg in &signature.positional {
|
||||
let is_required = matches!(arg.0, PositionalType::Mandatory(_, _));
|
||||
|
||||
sig.push_value(for_spec(arg.0.name(), "argument", is_required, &tag));
|
||||
|
@ -313,7 +313,7 @@ pub fn signature_dict(signature: Signature, tag: impl Into<Tag>) -> Value {
|
|||
sig.push_value(for_spec("rest", "argument", is_required, &tag));
|
||||
}
|
||||
|
||||
for (name, ty) in signature.named.iter() {
|
||||
for (name, ty) in &signature.named {
|
||||
match ty.0 {
|
||||
NamedType::Mandatory(_, _) => sig.push_value(for_spec(name, "flag", true, &tag)),
|
||||
NamedType::Optional(_, _) => sig.push_value(for_spec(name, "flag", false, &tag)),
|
||||
|
|
|
@ -100,14 +100,14 @@ fn if_command(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) => {
|
||||
let result = if b {
|
||||
run_block(&then_case.block, &*context, input, external_redirection)
|
||||
run_block(&then_case.block, &context, input, external_redirection)
|
||||
} else {
|
||||
run_block(&else_case.block, &*context, input, external_redirection)
|
||||
run_block(&else_case.block, &context, input, external_redirection)
|
||||
};
|
||||
context.scope.exit_scope();
|
||||
|
||||
|
|
|
@ -56,7 +56,7 @@ fn tutor(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
let search: Option<String> = args.opt(0).unwrap_or(None);
|
||||
let find: Option<String> = args.get_flag("find")?;
|
||||
|
||||
let search_space = vec![
|
||||
let search_space = [
|
||||
(vec!["begin"], begin_tutor()),
|
||||
(
|
||||
vec!["table", "tables", "row", "rows", "column", "columns"],
|
||||
|
@ -88,7 +88,7 @@ fn tutor(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
if let Some(find) = find {
|
||||
let mut results = vec![];
|
||||
for search_group in search_space {
|
||||
if search_group.1.contains(&find.as_str()) {
|
||||
if search_group.1.contains(&find) {
|
||||
results.push(search_group.0[0].to_string())
|
||||
}
|
||||
}
|
||||
|
@ -383,7 +383,7 @@ fn display(tag: Tag, scope: &Scope, help: &str) -> OutputStream {
|
|||
|
||||
//TODO: support no-color mode
|
||||
let colored_example = nu_engine::Painter::paint_string(item, scope, &palette);
|
||||
build.push_str(&format!("{}", colored_example));
|
||||
build.push_str(&colored_example);
|
||||
} else {
|
||||
code_mode = true;
|
||||
build.push_str(item);
|
||||
|
|
|
@ -245,7 +245,7 @@ fn perform_groupby_aggregation(
|
|||
None => &col[..],
|
||||
};
|
||||
|
||||
res.rename(col.as_str(), new_col)
|
||||
res.rename(&col, new_col)
|
||||
.expect("Column is always there. Looping with known names");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -107,7 +107,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
let other: Value = args.req_named("other")?;
|
||||
let axis: Tagged<String> = args.req_named("axis")?;
|
||||
|
||||
let axis = Axis::try_from_str(axis.item.as_str(), &axis.tag.span)?;
|
||||
let axis = Axis::try_from_str(&axis.item, &axis.tag.span)?;
|
||||
|
||||
let df_other = match other.value {
|
||||
UntaggedValue::DataFrame(df) => Ok(df),
|
||||
|
|
|
@ -53,7 +53,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
|
||||
let res = df
|
||||
.as_ref()
|
||||
.column(column.item.as_ref())
|
||||
.column(&column.item)
|
||||
.map_err(|e| parse_polars_error::<&str>(&e, &column.tag.span, None))?;
|
||||
|
||||
let df = NuDataFrame::try_from_series(vec![res.clone()], &tag.span)?;
|
||||
|
|
|
@ -195,7 +195,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
|
||||
let name = format!("{} ({})", col.name(), col.dtype());
|
||||
ChunkedArray::<Float64Type>::new_from_opt_slice(
|
||||
name.as_str(),
|
||||
&name,
|
||||
&[
|
||||
Some(count),
|
||||
sum,
|
||||
|
|
|
@ -72,7 +72,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
.expect("using name from list of names from dataframe")
|
||||
.dtype();
|
||||
|
||||
let dtype_str = format!("{}", dtype);
|
||||
let dtype_str = dtype.to_string();
|
||||
dtypes.push(Value {
|
||||
value: dtype_str.into(),
|
||||
tag: Tag::default(),
|
||||
|
|
|
@ -177,7 +177,7 @@ fn check_column_datatypes<T: AsRef<str>>(
|
|||
));
|
||||
}
|
||||
|
||||
for (l, r) in l_cols.iter().zip(r_cols.iter()) {
|
||||
for (l, r) in l_cols.iter().zip(r_cols) {
|
||||
let l_series = df_l
|
||||
.column(l.as_ref())
|
||||
.map_err(|e| parse_polars_error::<&str>(&e, l_col_span, None))?;
|
||||
|
|
|
@ -135,12 +135,12 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
.map_err(|e| parse_polars_error::<&str>(&e, &tag.span, None))?;
|
||||
|
||||
if let Some(name) = &variable_name {
|
||||
res.rename("variable", name.item.as_str())
|
||||
res.rename("variable", &name.item)
|
||||
.map_err(|e| parse_polars_error::<&str>(&e, &name.tag.span, None))?;
|
||||
}
|
||||
|
||||
if let Some(name) = &value_name {
|
||||
res.rename("value", name.item.as_str())
|
||||
res.rename("value", &name.item)
|
||||
.map_err(|e| parse_polars_error::<&str>(&e, &name.tag.span, None))?;
|
||||
}
|
||||
|
||||
|
|
|
@ -100,7 +100,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
|
||||
let mut groupby = nu_groupby.to_groupby()?;
|
||||
|
||||
let pivot = groupby.pivot(pivot_col.item.as_ref(), value_col.item.as_ref());
|
||||
let pivot = groupby.pivot(&pivot_col.item, &value_col.item);
|
||||
|
||||
let res = match op {
|
||||
Operation::Mean => pivot.mean(),
|
||||
|
@ -120,7 +120,7 @@ fn check_pivot_column(
|
|||
col: &Tagged<String>,
|
||||
) -> Result<(), ShellError> {
|
||||
let series = df
|
||||
.column(col.item.as_ref())
|
||||
.column(&col.item)
|
||||
.map_err(|e| parse_polars_error::<&str>(&e, &col.tag.span, None))?;
|
||||
|
||||
match series.dtype() {
|
||||
|
@ -146,7 +146,7 @@ fn check_value_column(
|
|||
col: &Tagged<String>,
|
||||
) -> Result<(), ShellError> {
|
||||
let series = df
|
||||
.column(col.item.as_ref())
|
||||
.column(&col.item)
|
||||
.map_err(|e| parse_polars_error::<&str>(&e, &col.tag.span, None))?;
|
||||
|
||||
match series.dtype() {
|
||||
|
|
|
@ -61,7 +61,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
let (mut df, df_tag) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
||||
|
||||
df.as_mut()
|
||||
.rename(from.item.as_str(), to.item.as_str())
|
||||
.rename(&from.item, &to.item)
|
||||
.map_err(|e| parse_polars_error::<&str>(&e, &df_tag.span, None))?;
|
||||
|
||||
Ok(OutputStream::one(df.into_value(tag)))
|
||||
|
|
|
@ -68,7 +68,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
})?;
|
||||
|
||||
let res = chunked
|
||||
.contains(pattern.as_str())
|
||||
.contains(&pattern.item)
|
||||
.map_err(|e| parse_polars_error::<&str>(&e, &tag.span, None))?;
|
||||
|
||||
let df = NuDataFrame::try_from_series(vec![res.into_series()], &tag.span)?;
|
||||
|
|
|
@ -99,7 +99,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
));
|
||||
}
|
||||
|
||||
let cum_type = CumType::from_str(cum_type.item.as_str(), &cum_type.tag.span)?;
|
||||
let cum_type = CumType::from_str(&cum_type.item, &cum_type.tag.span)?;
|
||||
let mut res = match cum_type {
|
||||
CumType::Max => series.cum_max(reverse),
|
||||
CumType::Min => series.cum_min(reverse),
|
||||
|
|
|
@ -60,7 +60,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
|
||||
let mut series = df.as_series(&df_tag.span)?;
|
||||
|
||||
series.rename(name.item.as_ref());
|
||||
series.rename(&name.item);
|
||||
|
||||
let df = NuDataFrame::try_from_series(vec![series], &tag.span)?;
|
||||
Ok(OutputStream::one(df.into_value(df_tag)))
|
||||
|
|
|
@ -77,7 +77,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
})?;
|
||||
|
||||
let mut res = chunked
|
||||
.replace(pattern.as_str(), replace.as_str())
|
||||
.replace(&pattern.item, &replace.item)
|
||||
.map_err(|e| parse_polars_error::<&str>(&e, &tag.span, None))?;
|
||||
|
||||
res.rename(series.name());
|
||||
|
|
|
@ -77,7 +77,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
})?;
|
||||
|
||||
let mut res = chunked
|
||||
.replace_all(pattern.as_str(), replace.as_str())
|
||||
.replace_all(&pattern.item, &replace.item)
|
||||
.map_err(|e| parse_polars_error::<&str>(&e, &tag.span, None))?;
|
||||
|
||||
res.rename(series.name());
|
||||
|
|
|
@ -125,7 +125,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
));
|
||||
}
|
||||
|
||||
let roll_type = RollType::from_str(roll_type.item.as_str(), &roll_type.tag.span)?;
|
||||
let roll_type = RollType::from_str(&roll_type.item, &roll_type.tag.span)?;
|
||||
let res = match roll_type {
|
||||
RollType::Max => series.rolling_max(
|
||||
window_size.item as u32,
|
||||
|
|
|
@ -61,7 +61,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
.date64()
|
||||
.map_err(|e| parse_polars_error::<&str>(&e, &df_tag.span, None))?;
|
||||
|
||||
let res = casted.strftime(fmt.item.as_str()).into_series();
|
||||
let res = casted.strftime(&fmt.item).into_series();
|
||||
let df = NuDataFrame::try_from_series(vec![res], &tag.span)?;
|
||||
Ok(OutputStream::one(df.into_value(df_tag)))
|
||||
}
|
||||
|
|
|
@ -64,14 +64,10 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
let delimiter: Option<Tagged<String>> = args.get_flag("delimiter")?;
|
||||
let no_header: bool = args.has_flag("no_header");
|
||||
|
||||
let (mut df, _) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
||||
let (df, _) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
||||
|
||||
let mut file = File::create(&file_name.item).map_err(|e| {
|
||||
ShellError::labeled_error(
|
||||
"Error with file name",
|
||||
format!("{}", e),
|
||||
&file_name.tag.span,
|
||||
)
|
||||
ShellError::labeled_error("Error with file name", e.to_string(), &file_name.tag.span)
|
||||
})?;
|
||||
|
||||
let writer = CsvWriter::new(&mut file);
|
||||
|
@ -103,7 +99,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
};
|
||||
|
||||
writer
|
||||
.finish(df.as_mut())
|
||||
.finish(df.as_ref())
|
||||
.map_err(|e| parse_polars_error::<&str>(&e, &file_name.tag.span, None))?;
|
||||
|
||||
let tagged_value = Value {
|
||||
|
|
|
@ -48,18 +48,14 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
let tag = args.call_info.name_tag.clone();
|
||||
let file_name: Tagged<PathBuf> = args.req(0)?;
|
||||
|
||||
let (mut df, _) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
||||
let (df, _) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
||||
|
||||
let file = File::create(&file_name.item).map_err(|e| {
|
||||
ShellError::labeled_error(
|
||||
"Error with file name",
|
||||
format!("{}", e),
|
||||
&file_name.tag.span,
|
||||
)
|
||||
ShellError::labeled_error("Error with file name", e.to_string(), &file_name.tag.span)
|
||||
})?;
|
||||
|
||||
ParquetWriter::new(file)
|
||||
.finish(df.as_mut())
|
||||
.finish(df.as_ref())
|
||||
.map_err(|e| parse_polars_error::<&str>(&e, &file_name.tag.span, None))?;
|
||||
|
||||
let tagged_value = Value {
|
||||
|
|
|
@ -46,30 +46,32 @@ pub(crate) fn parse_polars_error<T: AsRef<str>>(
|
|||
span: &Span,
|
||||
secondary: Option<T>,
|
||||
) -> ShellError {
|
||||
let (msg, label) = match e {
|
||||
PolarsError::PolarsArrowError(_) => ("PolarsArrow Error", format!("{}", e)),
|
||||
PolarsError::ArrowError(_) => ("Arrow Error", format!("{}", e)),
|
||||
PolarsError::InvalidOperation(_) => ("Invalid Operation", format!("{}", e)),
|
||||
PolarsError::DataTypeMisMatch(_) => ("Data Type Mismatch", format!("{}", e)),
|
||||
PolarsError::NotFound(_) => ("Not Found", format!("{}", e)),
|
||||
PolarsError::ShapeMisMatch(_) => ("Shape Mismatch", format!("{}", e)),
|
||||
PolarsError::Other(_) => ("Other", format!("{}", e)),
|
||||
PolarsError::OutOfBounds(_) => ("Out Of Bounds", format!("{}", e)),
|
||||
PolarsError::NoSlice => ("No Slice", format!("{}", e)),
|
||||
PolarsError::NoData(_) => ("No Data", format!("{}", e)),
|
||||
PolarsError::ValueError(_) => ("Value Error", format!("{}", e)),
|
||||
PolarsError::MemoryNotAligned => ("Memory Not Aligned", format!("{}", e)),
|
||||
PolarsError::ParquetError(_) => ("Parquet Error", format!("{}", e)),
|
||||
PolarsError::RandError(_) => ("Rand Error", format!("{}", e)),
|
||||
PolarsError::HasNullValues(_) => ("Has Null Values", format!("{}", e)),
|
||||
PolarsError::UnknownSchema(_) => ("Unknown Schema", format!("{}", e)),
|
||||
PolarsError::Various(_) => ("Various", format!("{}", e)),
|
||||
PolarsError::Io(_) => ("Io Error", format!("{}", e)),
|
||||
PolarsError::Regex(_) => ("Regex Error", format!("{}", e)),
|
||||
PolarsError::Duplicate(_) => ("Duplicate Error", format!("{}", e)),
|
||||
PolarsError::ImplementationError => ("Implementation Error", format!("{}", e)),
|
||||
let msg = match e {
|
||||
PolarsError::PolarsArrowError(_) => "PolarsArrow Error",
|
||||
PolarsError::ArrowError(_) => "Arrow Error",
|
||||
PolarsError::InvalidOperation(_) => "Invalid Operation",
|
||||
PolarsError::DataTypeMisMatch(_) => "Data Type Mismatch",
|
||||
PolarsError::NotFound(_) => "Not Found",
|
||||
PolarsError::ShapeMisMatch(_) => "Shape Mismatch",
|
||||
PolarsError::Other(_) => "Other",
|
||||
PolarsError::OutOfBounds(_) => "Out Of Bounds",
|
||||
PolarsError::NoSlice => "No Slice",
|
||||
PolarsError::NoData(_) => "No Data",
|
||||
PolarsError::ValueError(_) => "Value Error",
|
||||
PolarsError::MemoryNotAligned => "Memory Not Aligned",
|
||||
PolarsError::ParquetError(_) => "Parquet Error",
|
||||
PolarsError::RandError(_) => "Rand Error",
|
||||
PolarsError::HasNullValues(_) => "Has Null Values",
|
||||
PolarsError::UnknownSchema(_) => "Unknown Schema",
|
||||
PolarsError::Various(_) => "Various",
|
||||
PolarsError::Io(_) => "Io Error",
|
||||
PolarsError::Regex(_) => "Regex Error",
|
||||
PolarsError::Duplicate(_) => "Duplicate Error",
|
||||
PolarsError::ImplementationError => "Implementation Error",
|
||||
};
|
||||
|
||||
let label = e.to_string();
|
||||
|
||||
match secondary {
|
||||
None => ShellError::labeled_error(msg, label, span),
|
||||
Some(s) => ShellError::labeled_error_with_secondary(msg, label, span, s.as_ref(), span),
|
||||
|
|
|
@ -82,7 +82,7 @@ fn command(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
|
||||
let mut series = df.as_series(&value.tag.span)?;
|
||||
|
||||
let series = series.rename(name.item.as_ref()).clone();
|
||||
let series = series.rename(&name.item).clone();
|
||||
|
||||
let (mut df, _) = NuDataFrame::try_from_stream(&mut args.input, &tag.span)?;
|
||||
|
||||
|
|
|
@ -61,7 +61,7 @@ impl WholeStreamCommand for AutoenvUntrust {
|
|||
let mut doc = String::new();
|
||||
file.read_to_string(&mut doc)?;
|
||||
|
||||
let mut allowed: Trusted = toml::from_str(doc.as_str()).unwrap_or_else(|_| Trusted::new());
|
||||
let mut allowed: Trusted = toml::from_str(&doc).unwrap_or_else(|_| Trusted::new());
|
||||
|
||||
let file_to_untrust = file_to_untrust.to_string_lossy().to_string();
|
||||
|
||||
|
|
|
@ -173,9 +173,9 @@ fn open(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
Ok(StringOrBinary::String(s)) => {
|
||||
ReturnSuccess::value(UntaggedValue::string(s).into_value(file_tag))
|
||||
}
|
||||
Ok(StringOrBinary::Binary(b)) => ReturnSuccess::value(
|
||||
UntaggedValue::binary(b.into_iter().collect()).into_value(file_tag),
|
||||
),
|
||||
Ok(StringOrBinary::Binary(b)) => {
|
||||
ReturnSuccess::value(UntaggedValue::binary(b).into_value(file_tag))
|
||||
}
|
||||
Err(se) => Err(se),
|
||||
}
|
||||
});
|
||||
|
|
|
@ -241,7 +241,7 @@ fn string_from(input: &[Value]) -> String {
|
|||
|
||||
if !input.is_empty() {
|
||||
let mut first = true;
|
||||
for i in input.iter() {
|
||||
for i in input {
|
||||
if !first {
|
||||
save_data.push('\n');
|
||||
} else {
|
||||
|
|
|
@ -48,7 +48,7 @@ fn touch(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
let target: Tagged<PathBuf> = args.req(0)?;
|
||||
let rest: Vec<Tagged<PathBuf>> = args.rest(1)?;
|
||||
|
||||
for item in vec![target].into_iter().chain(rest.into_iter()) {
|
||||
for item in vec![target].into_iter().chain(rest) {
|
||||
match OpenOptions::new().write(true).create(true).open(&item) {
|
||||
Ok(_) => continue,
|
||||
Err(err) => {
|
||||
|
|
|
@ -45,7 +45,7 @@ impl WholeStreamCommand for Command {
|
|||
|
||||
Ok(prepend
|
||||
.into_iter()
|
||||
.chain(args.input.into_iter().chain(vec![value]))
|
||||
.chain(args.input.into_iter().chain([value]))
|
||||
.into_output_stream())
|
||||
}
|
||||
|
||||
|
|
|
@ -96,7 +96,7 @@ pub fn process_row(
|
|||
|
||||
let result = run_block(
|
||||
&captured_block.block,
|
||||
&*context,
|
||||
&context,
|
||||
input_stream,
|
||||
external_redirection,
|
||||
);
|
||||
|
@ -127,7 +127,7 @@ fn each(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
Ok(args
|
||||
.input
|
||||
.enumerate()
|
||||
.map(move |input| {
|
||||
.flat_map(move |input| {
|
||||
let block = block.clone();
|
||||
let context = context.clone();
|
||||
let row = make_indexed_item(input.0, input.1);
|
||||
|
@ -137,12 +137,11 @@ fn each(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
Err(e) => OutputStream::one(Value::error(e)),
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
.into_output_stream())
|
||||
} else {
|
||||
Ok(args
|
||||
.input
|
||||
.map(move |input| {
|
||||
.flat_map(move |input| {
|
||||
let block = block.clone();
|
||||
let context = context.clone();
|
||||
|
||||
|
@ -151,7 +150,6 @@ fn each(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
Err(e) => OutputStream::one(Value::error(e)),
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
.into_output_stream())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -64,7 +64,7 @@ impl WholeStreamCommand for EachWindow {
|
|||
Ok(args
|
||||
.input
|
||||
.enumerate()
|
||||
.map(move |(i, input)| {
|
||||
.flat_map(move |(i, input)| {
|
||||
// This would probably be more efficient if `last` was a VecDeque
|
||||
// But we can't have that because it needs to be put into a Table
|
||||
window.remove(0);
|
||||
|
@ -86,7 +86,6 @@ impl WholeStreamCommand for EachWindow {
|
|||
}
|
||||
})
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(Ok)
|
||||
.into_input_stream())
|
||||
}
|
||||
|
|
|
@ -140,7 +140,7 @@ fn process_row(
|
|||
|
||||
let stream = run_block(
|
||||
&default_block.block,
|
||||
&*context,
|
||||
context,
|
||||
input_stream,
|
||||
ExternalRedirection::Stdout,
|
||||
);
|
||||
|
|
|
@ -56,8 +56,7 @@ fn flatten(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
let input = args.input;
|
||||
|
||||
Ok(input
|
||||
.map(move |item| flat_value(&columns, &item, &tag).into_iter())
|
||||
.flatten()
|
||||
.flat_map(move |item| flat_value(&columns, &item, &tag))
|
||||
.into_action_stream())
|
||||
}
|
||||
|
||||
|
@ -96,7 +95,7 @@ fn flat_value(
|
|||
continue;
|
||||
}
|
||||
|
||||
for (k, v) in mapa.into_iter() {
|
||||
for (k, v) in mapa {
|
||||
if out.contains_key(k) {
|
||||
out.insert_value(format!("{}_{}", column, k), v.clone());
|
||||
} else {
|
||||
|
@ -159,7 +158,7 @@ fn flat_value(
|
|||
let mut expanded = vec![];
|
||||
|
||||
if let Some(TableInside::Entries(column, _, entries)) = a_table {
|
||||
for entry in entries.into_iter() {
|
||||
for entry in entries {
|
||||
let mut base = out.clone();
|
||||
base.insert_value(column, entry.clone());
|
||||
expanded.push(base.into_value());
|
||||
|
@ -170,7 +169,7 @@ fn flat_value(
|
|||
|
||||
expanded
|
||||
} else if item.is_table() {
|
||||
item.table_entries().map(Clone::clone).collect()
|
||||
item.table_entries().cloned().collect()
|
||||
} else {
|
||||
vec![item.clone()]
|
||||
}
|
||||
|
|
|
@ -65,14 +65,12 @@ pub fn get(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
} else {
|
||||
trace!("get {:?}", column_paths);
|
||||
let output_stream = input
|
||||
.map(move |item| {
|
||||
.flat_map(move |item| {
|
||||
column_paths
|
||||
.iter()
|
||||
.map(move |path| get_output(&item, path))
|
||||
.flatten()
|
||||
.flat_map(move |path| get_output(&item, path))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.flatten()
|
||||
.into_action_stream();
|
||||
Ok(output_stream)
|
||||
}
|
||||
|
|
|
@ -140,7 +140,7 @@ pub fn group_by(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
let block = Arc::new(block_given);
|
||||
let error_key = "error";
|
||||
|
||||
for value in values.iter() {
|
||||
for value in &values {
|
||||
let run = block.clone();
|
||||
let context = context.clone();
|
||||
|
||||
|
|
|
@ -80,7 +80,7 @@ fn process_row(
|
|||
|
||||
let result = run_block(
|
||||
&block.block,
|
||||
&*context,
|
||||
&context,
|
||||
input_stream,
|
||||
ExternalRedirection::Stdout,
|
||||
);
|
||||
|
@ -162,7 +162,7 @@ fn insert(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
let column = Arc::new(column);
|
||||
|
||||
Ok(input
|
||||
.map(move |input| {
|
||||
.flat_map(move |input| {
|
||||
let context = context.clone();
|
||||
let value = value.clone();
|
||||
let column = column.clone();
|
||||
|
@ -172,6 +172,5 @@ fn insert(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
Err(e) => ActionStream::one(Err(e)),
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
.into_action_stream())
|
||||
}
|
||||
|
|
|
@ -74,7 +74,7 @@ impl WholeStreamCommand for SubCommand {
|
|||
ctx.scope.add_var(arg.name(), item.clone());
|
||||
}
|
||||
|
||||
let result = evaluate_baseline_expr(&*condition, &*ctx);
|
||||
let result = evaluate_baseline_expr(&condition, &ctx);
|
||||
ctx.scope.exit_scope();
|
||||
|
||||
!matches!(result, Ok(ref v) if v.is_true())
|
||||
|
|
|
@ -76,7 +76,7 @@ impl WholeStreamCommand for SubCommand {
|
|||
}
|
||||
trace!("ITEM = {:?}", item);
|
||||
|
||||
let result = evaluate_baseline_expr(&*condition, &*ctx);
|
||||
let result = evaluate_baseline_expr(&condition, &ctx);
|
||||
ctx.scope.exit_scope();
|
||||
trace!("RESULT = {:?}", result);
|
||||
|
||||
|
|
|
@ -242,7 +242,7 @@ fn move_after(table: &Value, columns: &[String], from: &ColumnPath) -> Result<Va
|
|||
let mut insert = false;
|
||||
let mut inserted = false;
|
||||
|
||||
for name in columns_moved.into_iter() {
|
||||
for name in columns_moved {
|
||||
if let Some(name) = name {
|
||||
reordered_columns.push(Some(name.clone()));
|
||||
|
||||
|
@ -291,7 +291,7 @@ fn move_before(table: &Value, columns: &[String], from: &ColumnPath) -> Result<V
|
|||
let mut reordered_columns = vec![];
|
||||
let mut inserted = false;
|
||||
|
||||
for name in columns_moved.into_iter() {
|
||||
for name in columns_moved {
|
||||
if let Some(name) = name {
|
||||
if !inserted && name == from {
|
||||
for column in columns {
|
||||
|
|
|
@ -163,7 +163,7 @@ fn reduce(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
|
||||
context.scope.enter_scope();
|
||||
context.scope.add_var("$acc", f);
|
||||
let result = process_row(block, &*context, row);
|
||||
let result = process_row(block, &context, row);
|
||||
context.scope.exit_scope();
|
||||
|
||||
// we make sure that result is an indexed item
|
||||
|
@ -201,7 +201,7 @@ fn reduce(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
|
||||
context.scope.enter_scope();
|
||||
context.scope.add_var("$acc", f);
|
||||
let result = process_row(block, &*context, row);
|
||||
let result = process_row(block, &context, row);
|
||||
context.scope.exit_scope();
|
||||
result
|
||||
})?
|
||||
|
|
|
@ -59,14 +59,12 @@ pub fn roll(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
|
||||
Ok(args
|
||||
.input
|
||||
.map(move |value| {
|
||||
.flat_map(move |value| {
|
||||
let tag = value.tag();
|
||||
|
||||
roll_by(value, &options)
|
||||
.unwrap_or_else(|| vec![UntaggedValue::nothing().into_value(tag)])
|
||||
.into_iter()
|
||||
})
|
||||
.flatten()
|
||||
.into_output_stream())
|
||||
}
|
||||
|
||||
|
@ -84,8 +82,7 @@ fn roll_by(value: Value, options: &Arguments) -> Option<Vec<Value>> {
|
|||
let values_rotated = rotate(
|
||||
value
|
||||
.row_entries()
|
||||
.map(|(_, value)| value)
|
||||
.map(Clone::clone)
|
||||
.map(|(_, value)| value.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
&options.by,
|
||||
direction,
|
||||
|
@ -94,7 +91,7 @@ fn roll_by(value: Value, options: &Arguments) -> Option<Vec<Value>> {
|
|||
if let Some(ref values) = values_rotated {
|
||||
let mut out = TaggedDictBuilder::new(&tag);
|
||||
|
||||
for (k, v) in columns.iter().zip(values.iter()) {
|
||||
for (k, v) in columns.iter().zip(values) {
|
||||
out.insert_value(k, v.clone());
|
||||
}
|
||||
|
||||
|
@ -104,7 +101,7 @@ fn roll_by(value: Value, options: &Arguments) -> Option<Vec<Value>> {
|
|||
None
|
||||
} else if value.is_table() {
|
||||
rotate(
|
||||
value.table_entries().map(Clone::clone).collect(),
|
||||
value.table_entries().cloned().collect(),
|
||||
&options.by,
|
||||
direction,
|
||||
)
|
||||
|
|
|
@ -76,7 +76,7 @@ impl WholeStreamCommand for SubCommand {
|
|||
}
|
||||
trace!("ITEM = {:?}", item);
|
||||
|
||||
let result = evaluate_baseline_expr(&*condition, &*ctx);
|
||||
let result = evaluate_baseline_expr(&condition, &ctx);
|
||||
ctx.scope.exit_scope();
|
||||
trace!("RESULT = {:?}", result);
|
||||
|
||||
|
|
|
@ -77,7 +77,7 @@ impl WholeStreamCommand for SubCommand {
|
|||
}
|
||||
trace!("ITEM = {:?}", item);
|
||||
|
||||
let result = evaluate_baseline_expr(&*condition, &*ctx);
|
||||
let result = evaluate_baseline_expr(&condition, &ctx);
|
||||
ctx.scope.exit_scope();
|
||||
trace!("RESULT = {:?}", result);
|
||||
|
||||
|
|
|
@ -118,7 +118,7 @@ fn sort_by(mut args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
vec.reverse()
|
||||
}
|
||||
|
||||
Ok((vec.into_iter()).into_output_stream())
|
||||
Ok(vec.into_iter().into_output_stream())
|
||||
}
|
||||
|
||||
pub fn sort(
|
||||
|
@ -137,7 +137,7 @@ pub fn sort(
|
|||
));
|
||||
}
|
||||
|
||||
for sort_arg in keys.iter() {
|
||||
for sort_arg in keys {
|
||||
let match_test = &vec[0].get_data_by_key(sort_arg.borrow_spanned());
|
||||
if match_test.is_none() {
|
||||
return Err(ShellError::labeled_error(
|
||||
|
|
|
@ -66,7 +66,6 @@ fn process_row(
|
|||
field: Arc<ColumnPath>,
|
||||
tag: Arc<Tag>,
|
||||
) -> Result<ActionStream, ShellError> {
|
||||
let tag = &*tag;
|
||||
let replacement = Arc::make_mut(&mut replacement);
|
||||
|
||||
Ok(match replacement {
|
||||
|
@ -86,7 +85,7 @@ fn process_row(
|
|||
|
||||
let result = run_block(
|
||||
&captured_block.block,
|
||||
&*context,
|
||||
&context,
|
||||
input_stream,
|
||||
ExternalRedirection::Stdout,
|
||||
);
|
||||
|
@ -184,7 +183,7 @@ fn update(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
let field = Arc::new(field);
|
||||
|
||||
Ok(input
|
||||
.map(move |input| {
|
||||
.flat_map(move |input| {
|
||||
let tag = name_tag.clone();
|
||||
let context = context.clone();
|
||||
let replacement = replacement.clone();
|
||||
|
@ -195,6 +194,5 @@ fn update(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
Err(e) => ActionStream::one(Err(e)),
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
.into_action_stream())
|
||||
}
|
||||
|
|
|
@ -27,7 +27,7 @@ fn from_delimited_string_to_value(
|
|||
let mut rows = vec![];
|
||||
for row in reader.records() {
|
||||
let mut tagged_row = TaggedDictBuilder::new(&tag);
|
||||
for (value, header) in row?.iter().zip(headers.iter()) {
|
||||
for (value, header) in row?.iter().zip(&headers) {
|
||||
if let Ok(i) = value.parse::<i64>() {
|
||||
tagged_row.insert_value(header, UntaggedValue::int(i).into_value(&tag))
|
||||
} else if let Ok(f) = value.parse::<f64>() {
|
||||
|
|
|
@ -100,7 +100,7 @@ fn from_eml(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
dict.insert_untagged("To", headerfieldvalue_to_value(&tag, &to));
|
||||
}
|
||||
|
||||
for HeaderField { name, value } in eml.headers.iter() {
|
||||
for HeaderField { name, value } in &eml.headers {
|
||||
dict.insert_untagged(name, headerfieldvalue_to_value(&tag, value));
|
||||
}
|
||||
|
||||
|
|
|
@ -75,7 +75,7 @@ fn convert_yaml_value_to_nu_value(
|
|||
serde_yaml::Value::Mapping(t) => {
|
||||
let mut collected = TaggedDictBuilder::new(&tag);
|
||||
|
||||
for (k, v) in t.iter() {
|
||||
for (k, v) in t {
|
||||
// A ShellError that we re-use multiple times in the Mapping scenario
|
||||
let err_unexpected_map = ShellError::labeled_error(
|
||||
format!("Unexpected YAML:\nKey: {:?}\nValue: {:?}", k, v),
|
||||
|
@ -202,7 +202,7 @@ mod tests {
|
|||
expected: Ok(row!["value".to_owned() => string("{{ something }}")]),
|
||||
},
|
||||
];
|
||||
for tc in tt.into_iter() {
|
||||
for tc in tt {
|
||||
let actual = from_yaml_string_to_value(tc.input.to_owned(), Tag::default());
|
||||
if actual.is_err() {
|
||||
assert!(
|
||||
|
|
|
@ -20,7 +20,7 @@ fn from_value_to_delimited_string(
|
|||
let mut fields: VecDeque<String> = VecDeque::new();
|
||||
let mut values: VecDeque<String> = VecDeque::new();
|
||||
|
||||
for (k, v) in o.entries.iter() {
|
||||
for (k, v) in &o.entries {
|
||||
fields.push_back(k.clone());
|
||||
|
||||
values.push_back(to_string_tagged_value(v)?);
|
||||
|
@ -130,12 +130,14 @@ pub fn clone_tagged_value(v: &Value) -> Value {
|
|||
// NOTE: could this be useful more widely and implemented on Value ?
|
||||
fn to_string_tagged_value(v: &Value) -> Result<String, ShellError> {
|
||||
match &v.value {
|
||||
UntaggedValue::Primitive(Primitive::String(_))
|
||||
| UntaggedValue::Primitive(Primitive::Filesize(_))
|
||||
| UntaggedValue::Primitive(Primitive::Boolean(_))
|
||||
| UntaggedValue::Primitive(Primitive::Decimal(_))
|
||||
| UntaggedValue::Primitive(Primitive::FilePath(_))
|
||||
| UntaggedValue::Primitive(Primitive::Int(_)) => as_string(v),
|
||||
UntaggedValue::Primitive(
|
||||
Primitive::String(_)
|
||||
| Primitive::Filesize(_)
|
||||
| Primitive::Boolean(_)
|
||||
| Primitive::Decimal(_)
|
||||
| Primitive::FilePath(_)
|
||||
| Primitive::Int(_),
|
||||
) => as_string(v),
|
||||
UntaggedValue::Primitive(Primitive::Date(d)) => Ok(d.to_string()),
|
||||
UntaggedValue::Primitive(Primitive::Nothing) => Ok(String::new()),
|
||||
UntaggedValue::Table(_) => Ok(String::from("[Table]")),
|
||||
|
@ -153,7 +155,7 @@ fn merge_descriptors(values: &[Value]) -> Vec<Spanned<String>> {
|
|||
let mut seen: IndexSet<String> = indexset! {};
|
||||
for value in values {
|
||||
for desc in value.data_descriptors() {
|
||||
if !seen.contains(&desc[..]) {
|
||||
if !seen.contains(&desc) {
|
||||
seen.insert(desc.clone());
|
||||
ret.push(desc.spanned(value.tag.span));
|
||||
}
|
||||
|
|
|
@ -11,6 +11,7 @@ use serde::{Deserialize, Serialize};
|
|||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::fmt::Write;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct HtmlThemes {
|
||||
|
@ -124,8 +125,8 @@ fn get_theme_from_asset_file(
|
|||
theme_tag: &Tag,
|
||||
) -> Result<HashMap<&'static str, String>, ShellError> {
|
||||
let theme_name = match theme {
|
||||
Some(s) => s.to_string(),
|
||||
None => "default".to_string(), // There is no theme named "default" so this will be HtmlTheme::default(), which is "nu_default".
|
||||
Some(s) => s.as_str(),
|
||||
None => "default", // There is no theme named "default" so this will be HtmlTheme::default(), which is "nu_default".
|
||||
};
|
||||
|
||||
// 228 themes come from
|
||||
|
@ -143,7 +144,7 @@ fn get_theme_from_asset_file(
|
|||
let th = asset
|
||||
.themes
|
||||
.iter()
|
||||
.find(|&n| n.name.to_lowercase() == *theme_name.to_lowercase().as_str()); // case insensitive search
|
||||
.find(|&n| n.name.to_lowercase() == theme_name.to_lowercase()); // case insensitive search
|
||||
|
||||
// If no theme is found by the name provided, ensure we return the default theme
|
||||
let default_theme = HtmlTheme::default();
|
||||
|
@ -248,11 +249,7 @@ fn get_list_of_theme_names() -> Vec<String> {
|
|||
_ => HtmlThemes::default(),
|
||||
};
|
||||
|
||||
let theme_names: Vec<String> = html_themes
|
||||
.themes
|
||||
.iter()
|
||||
.map(|n| n.name[..].to_string())
|
||||
.collect();
|
||||
let theme_names: Vec<String> = html_themes.themes.iter().map(|n| n.name.clone()).collect();
|
||||
|
||||
theme_names
|
||||
}
|
||||
|
@ -278,8 +275,8 @@ fn to_html(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
let theme_names = get_list_of_theme_names();
|
||||
|
||||
// Put that list into the output string
|
||||
for s in theme_names.iter() {
|
||||
output_string.push_str(&format!("{}\n", s));
|
||||
for s in &theme_names {
|
||||
writeln!(&mut output_string, "{}", s).unwrap();
|
||||
}
|
||||
|
||||
output_string.push_str("\nScreenshots of themes can be found here:\n");
|
||||
|
@ -304,7 +301,8 @@ fn to_html(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
|
||||
// change the color of the page
|
||||
if !partial {
|
||||
output_string.push_str(&format!(
|
||||
write!(
|
||||
&mut output_string,
|
||||
r"<html><style>body {{ background-color:{};color:{}; }}</style><body>",
|
||||
color_hm
|
||||
.get("background")
|
||||
|
@ -312,9 +310,11 @@ fn to_html(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
color_hm
|
||||
.get("foreground")
|
||||
.expect("Error getting foreground color")
|
||||
));
|
||||
)
|
||||
.unwrap();
|
||||
} else {
|
||||
output_string.push_str(&format!(
|
||||
write!(
|
||||
&mut output_string,
|
||||
"<div style=\"background-color:{};color:{};\">",
|
||||
color_hm
|
||||
.get("background")
|
||||
|
@ -322,7 +322,8 @@ fn to_html(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
color_hm
|
||||
.get("foreground")
|
||||
.expect("Error getting foreground color")
|
||||
));
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let inner_value = match input.len() {
|
||||
|
|
|
@ -134,7 +134,7 @@ pub fn value_to_json_value(v: &Value) -> Result<serde_json::Value, ShellError> {
|
|||
),
|
||||
UntaggedValue::Row(o) => {
|
||||
let mut m = serde_json::Map::new();
|
||||
for (k, v) in o.entries.iter() {
|
||||
for (k, v) in &o.entries {
|
||||
m.insert(k.clone(), value_to_json_value(v)?);
|
||||
}
|
||||
serde_json::Value::Object(m)
|
||||
|
@ -184,9 +184,7 @@ fn to_json(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
|
||||
if let Ok(pretty_u64) = pretty_value.as_u64() {
|
||||
if let Ok(serde_json_value) =
|
||||
serde_json::from_str::<serde_json::Value>(
|
||||
serde_json_string.as_str(),
|
||||
)
|
||||
serde_json::from_str::<serde_json::Value>(&serde_json_string)
|
||||
{
|
||||
let indentation_string = " ".repeat(pretty_u64 as usize);
|
||||
let serde_formatter =
|
||||
|
|
|
@ -236,7 +236,7 @@ fn get_output_string(
|
|||
));
|
||||
output_string.push(' ');
|
||||
} else {
|
||||
output_string.push_str(headers[i].as_str());
|
||||
output_string.push_str(&headers[i]);
|
||||
}
|
||||
|
||||
output_string.push('|');
|
||||
|
@ -275,7 +275,7 @@ fn get_output_string(
|
|||
output_string.push_str(&get_padded_string(row[i].clone(), column_widths[i], ' '));
|
||||
output_string.push(' ');
|
||||
} else {
|
||||
output_string.push_str(row[i].as_str());
|
||||
output_string.push_str(&row[i]);
|
||||
}
|
||||
|
||||
if !headers.is_empty() {
|
||||
|
|
|
@ -83,7 +83,7 @@ fn helper(v: &Value) -> Result<toml::Value, ShellError> {
|
|||
}
|
||||
UntaggedValue::Row(o) => {
|
||||
let mut m = toml::map::Map::new();
|
||||
for (k, v) in o.entries.iter() {
|
||||
for (k, v) in &o.entries {
|
||||
m.insert(k.clone(), helper(v)?);
|
||||
}
|
||||
toml::Value::Table(m)
|
||||
|
@ -97,7 +97,7 @@ pub fn value_to_toml_value(v: &Value) -> Result<toml::Value, ShellError> {
|
|||
match &v.value {
|
||||
UntaggedValue::Row(o) => {
|
||||
let mut m = toml::map::Map::new();
|
||||
for (k, v) in o.entries.iter() {
|
||||
for (k, v) in &o.entries {
|
||||
m.insert(k.clone(), helper(v)?);
|
||||
}
|
||||
Ok(toml::Value::Table(m))
|
||||
|
|
|
@ -37,7 +37,7 @@ pub fn add_attributes<'a>(
|
|||
element: &mut quick_xml::events::BytesStart<'a>,
|
||||
attributes: &'a IndexMap<String, String>,
|
||||
) {
|
||||
for (k, v) in attributes.iter() {
|
||||
for (k, v) in attributes {
|
||||
element.push_attribute((k.as_str(), v.as_str()));
|
||||
}
|
||||
}
|
||||
|
@ -47,7 +47,7 @@ pub fn get_attributes(row: &Value) -> Option<IndexMap<String, String>> {
|
|||
if let Some(v) = r.entries.get("attributes") {
|
||||
if let UntaggedValue::Row(a) = &v.value {
|
||||
let mut h = IndexMap::new();
|
||||
for (k, v) in a.entries.iter() {
|
||||
for (k, v) in &a.entries {
|
||||
h.insert(k.clone(), v.convert_to_string());
|
||||
}
|
||||
return Some(h);
|
||||
|
@ -84,7 +84,7 @@ pub fn write_xml_events<W: Write>(
|
|||
) -> Result<(), ShellError> {
|
||||
match ¤t.value {
|
||||
UntaggedValue::Row(o) => {
|
||||
for (k, v) in o.entries.iter() {
|
||||
for (k, v) in &o.entries {
|
||||
let mut e = BytesStart::owned(k.as_bytes(), k.len());
|
||||
if !is_xml_row(v) {
|
||||
return Err(ShellError::labeled_error(
|
||||
|
|
|
@ -65,7 +65,7 @@ pub fn value_to_yaml_value(v: &Value) -> Result<serde_yaml::Value, ShellError> {
|
|||
UntaggedValue::Primitive(Primitive::ColumnPath(path)) => {
|
||||
let mut out = vec![];
|
||||
|
||||
for member in path.iter() {
|
||||
for member in path {
|
||||
match &member.unspanned {
|
||||
UnspannedPathMember::String(string) => {
|
||||
out.push(serde_yaml::Value::String(string.clone()))
|
||||
|
@ -104,7 +104,7 @@ pub fn value_to_yaml_value(v: &Value) -> Result<serde_yaml::Value, ShellError> {
|
|||
),
|
||||
UntaggedValue::Row(o) => {
|
||||
let mut m = serde_yaml::Mapping::new();
|
||||
for (k, v) in o.entries.iter() {
|
||||
for (k, v) in &o.entries {
|
||||
m.insert(
|
||||
serde_yaml::Value::String(k.clone()),
|
||||
value_to_yaml_value(v)?,
|
||||
|
|
|
@ -77,7 +77,7 @@ fn to_table(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
let tz = dt.offset();
|
||||
indexmap.insert(
|
||||
"timezone".to_string(),
|
||||
UntaggedValue::string(format!("{}", tz)).into_value(&tag),
|
||||
UntaggedValue::string(tz.to_string()).into_value(&tag),
|
||||
);
|
||||
|
||||
let value = UntaggedValue::Row(Dictionary::from(indexmap)).into_value(&tag);
|
||||
|
|
|
@ -90,7 +90,7 @@ pub fn process_row(
|
|||
|
||||
let result = run_block(
|
||||
&captured_block.block,
|
||||
&*context,
|
||||
context,
|
||||
input_stream,
|
||||
external_redirection,
|
||||
);
|
||||
|
@ -130,7 +130,7 @@ fn for_in(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
if numbered {
|
||||
Ok(input
|
||||
.enumerate()
|
||||
.map(move |input| {
|
||||
.flat_map(move |input| {
|
||||
let row = make_indexed_item(input.0, input.1);
|
||||
|
||||
match process_row(&block, &context, row, &var_name, external_redirection) {
|
||||
|
@ -138,11 +138,10 @@ fn for_in(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
Err(e) => OutputStream::one(Value::error(e)),
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
.into_output_stream())
|
||||
} else {
|
||||
Ok(input
|
||||
.map(move |input| {
|
||||
.flat_map(move |input| {
|
||||
let block = block.clone();
|
||||
|
||||
match process_row(&block, &context, input, &var_name, external_redirection) {
|
||||
|
@ -150,7 +149,6 @@ fn for_in(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
Err(e) => OutputStream::one(Value::error(e)),
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
.into_output_stream())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -321,7 +321,7 @@ pub fn run_seq_dates(
|
|||
|
||||
let mut ret_str = String::from("");
|
||||
loop {
|
||||
ret_str.push_str(&format!("{}", next.format(&out_format)));
|
||||
ret_str.push_str(&next.format(&out_format).to_string());
|
||||
// TODO: check this value is good
|
||||
next += Duration::days(step_size);
|
||||
|
||||
|
|
|
@ -169,7 +169,7 @@ mod tests {
|
|||
// },
|
||||
];
|
||||
let test_tag = Tag::unknown();
|
||||
for tc in tt.iter() {
|
||||
for tc in &tt {
|
||||
let tc: &TestCase = tc; // Just for type annotations
|
||||
let math_functions: Vec<MathFunction> = vec![
|
||||
average, minimum, maximum, median, mode, stddev, summation, variance,
|
||||
|
|
|
@ -45,7 +45,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() {
|
||||
for (value, frequency) in &frequency_map {
|
||||
match max_freq.cmp(frequency) {
|
||||
Ordering::Less => {
|
||||
max_freq = *frequency;
|
||||
|
|
|
@ -108,7 +108,7 @@ pub fn max(data: Vec<Value>) -> Result<Value, ShellError> {
|
|||
.value
|
||||
.clone();
|
||||
|
||||
for value in data.iter() {
|
||||
for value in &data {
|
||||
if let Ok(greater_than) = compare_values(Operator::GreaterThan, &value.value, &biggest) {
|
||||
if greater_than {
|
||||
biggest = value.value.clone();
|
||||
|
@ -133,7 +133,7 @@ pub fn min(data: Vec<Value>) -> Result<Value, ShellError> {
|
|||
.value
|
||||
.clone();
|
||||
|
||||
for value in data.iter() {
|
||||
for value in &data {
|
||||
if let Ok(greater_than) = compare_values(Operator::LessThan, &value.value, &smallest) {
|
||||
if greater_than {
|
||||
smallest = value.value.clone();
|
||||
|
|
|
@ -43,7 +43,7 @@ impl WholeStreamCommand for SubCommand {
|
|||
let mut column_values = IndexMap::new();
|
||||
for value in values {
|
||||
if let UntaggedValue::Row(row_dict) = &value.value {
|
||||
for (key, value) in row_dict.entries.iter() {
|
||||
for (key, value) in &row_dict.entries {
|
||||
column_values
|
||||
.entry(key.clone())
|
||||
.and_modify(|v: &mut Vec<Value>| v.push(value.clone()))
|
||||
|
|
|
@ -67,7 +67,7 @@ pub fn calculate(values: &[Value], name: &Tag, mf: MathFunction) -> Result<Value
|
|||
let mut column_values = IndexMap::new();
|
||||
for value in values {
|
||||
if let UntaggedValue::Row(row_dict) = &value.value {
|
||||
for (key, value) in row_dict.entries.iter() {
|
||||
for (key, value) in &row_dict.entries {
|
||||
column_values
|
||||
.entry(key.clone())
|
||||
.and_modify(|v: &mut Vec<Value>| v.push(value.clone()))
|
||||
|
|
|
@ -39,7 +39,7 @@ impl WholeStreamCommand for SubCommand {
|
|||
let mut column_values = IndexMap::new();
|
||||
for value in values {
|
||||
if let UntaggedValue::Row(row_dict) = &value.value {
|
||||
for (key, value) in row_dict.entries.iter() {
|
||||
for (key, value) in &row_dict.entries {
|
||||
column_values
|
||||
.entry(key.clone())
|
||||
.and_modify(|v: &mut Vec<Value>| v.push(value.clone()))
|
||||
|
|
|
@ -112,10 +112,7 @@ mod tests {
|
|||
|
||||
fn only_examples() -> Vec<Command> {
|
||||
let mut commands = full_tests();
|
||||
commands.extend(vec![
|
||||
whole_stream_command(Zip),
|
||||
whole_stream_command(Flatten),
|
||||
]);
|
||||
commands.extend([whole_stream_command(Zip), whole_stream_command(Flatten)]);
|
||||
commands
|
||||
}
|
||||
|
||||
|
|
|
@ -519,7 +519,7 @@ pub fn value_to_json_value(v: &Value) -> Result<serde_json::Value, ShellError> {
|
|||
UntaggedValue::Primitive(Primitive::Binary(b)) => {
|
||||
let mut output = vec![];
|
||||
|
||||
for item in b.iter() {
|
||||
for item in b {
|
||||
output.push(serde_json::Value::Number(
|
||||
serde_json::Number::from_f64(*item as f64).ok_or_else(|| {
|
||||
ShellError::labeled_error(
|
||||
|
@ -534,7 +534,7 @@ pub fn value_to_json_value(v: &Value) -> Result<serde_json::Value, ShellError> {
|
|||
}
|
||||
UntaggedValue::Row(o) => {
|
||||
let mut m = serde_json::Map::new();
|
||||
for (k, v) in o.entries.iter() {
|
||||
for (k, v) in &o.entries {
|
||||
m.insert(k.clone(), value_to_json_value(v)?);
|
||||
}
|
||||
serde_json::Value::Object(m)
|
||||
|
|
|
@ -22,12 +22,12 @@ impl WholeStreamCommand for Clear {
|
|||
fn run(&self, _: CommandArgs) -> Result<InputStream, ShellError> {
|
||||
if cfg!(windows) {
|
||||
Command::new("cmd")
|
||||
.args(&["/C", "cls"])
|
||||
.args(["/C", "cls"])
|
||||
.status()
|
||||
.expect("failed to execute process");
|
||||
} else if cfg!(unix) {
|
||||
Command::new("/bin/sh")
|
||||
.args(&["-c", "clear"])
|
||||
.args(["-c", "clear"])
|
||||
.status()
|
||||
.expect("failed to execute process");
|
||||
}
|
||||
|
|
|
@ -51,7 +51,7 @@ pub fn clip(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
|
||||
if !values.is_empty() {
|
||||
let mut first = true;
|
||||
for i in values.iter() {
|
||||
for i in &values {
|
||||
if !first {
|
||||
new_copy_data.push('\n');
|
||||
} else {
|
||||
|
|
|
@ -99,7 +99,7 @@ fn du(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
|
||||
let exclude = args.exclude.map_or(Ok(None), move |x| {
|
||||
Pattern::new(&x.item)
|
||||
.map(Option::Some)
|
||||
.map(Some)
|
||||
.map_err(|e| ShellError::labeled_error(e.msg, "glob error", x.tag.clone()))
|
||||
})?;
|
||||
|
||||
|
@ -148,11 +148,10 @@ fn du(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
output.push(Ok(ReturnSuccess::Value(
|
||||
DirInfo::new(p, ¶ms, max_depth, ctrl_c.clone()).into(),
|
||||
)));
|
||||
} else {
|
||||
for v in FileInfo::new(p, deref, tag.clone()).into_iter() {
|
||||
output.push(Ok(ReturnSuccess::Value(v.into())));
|
||||
}
|
||||
} else if let Ok(v) = FileInfo::new(p, deref, tag.clone()) {
|
||||
output.push(Ok(ReturnSuccess::Value(v.into())));
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
Err(e) => vec![Err(e)],
|
||||
|
|
|
@ -80,7 +80,7 @@ fn exec(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
|
||||
Err(ShellError::labeled_error(
|
||||
"Error on exec",
|
||||
format!("{}", err),
|
||||
err.to_string(),
|
||||
&name,
|
||||
))
|
||||
}
|
||||
|
|
|
@ -82,7 +82,7 @@ pub fn dice(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
UntaggedValue::int(thread_rng.gen_range(1..sides + 1)).into_value(tag.clone())
|
||||
});
|
||||
|
||||
Ok((iter).into_output_stream())
|
||||
Ok(iter.into_output_stream())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
@ -66,7 +66,7 @@ fn format_command(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
|
||||
ctx.scope.enter_scope();
|
||||
ctx.scope.add_var("$it", value.clone());
|
||||
let result = evaluate_baseline_expr(&full_column_path.0, &*ctx);
|
||||
let result = evaluate_baseline_expr(&full_column_path.0, &ctx);
|
||||
ctx.scope.exit_scope();
|
||||
|
||||
if let Ok(c) = result {
|
||||
|
|
|
@ -90,7 +90,7 @@ fn filesize(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
|
||||
Ok(args
|
||||
.input
|
||||
.map(move |input| {
|
||||
.flat_map(move |input| {
|
||||
let format = format.clone();
|
||||
let field = field.clone();
|
||||
|
||||
|
@ -99,7 +99,6 @@ fn filesize(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
Err(e) => Err(e),
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
.map(Ok)
|
||||
.into_input_stream())
|
||||
}
|
||||
|
|
|
@ -91,7 +91,7 @@ fn lines(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
value: UntaggedValue::Primitive(Primitive::EndOfStream),
|
||||
..
|
||||
} => {
|
||||
let st = (&*leftover_string).lock().clone();
|
||||
let st = leftover_string.lock().clone();
|
||||
if !st.is_empty() {
|
||||
Some(vec![ReturnSuccess::value(
|
||||
UntaggedValue::string(st).into_untagged_value(),
|
||||
|
|
|
@ -176,15 +176,14 @@ fn parse_regex_error(e: regex::Error, base_span: Span) -> ShellError {
|
|||
.map(|l| l.replace(':', ""))
|
||||
.expect("invalid regex pattern");
|
||||
|
||||
let span = lines.nth(1).map(|l| l.find('^')).flatten().map(|space| {
|
||||
let span = lines.nth(1).and_then(|l| l.find('^')).map(|space| {
|
||||
let start = base_span.start() + space - 3;
|
||||
Span::for_char(start)
|
||||
});
|
||||
|
||||
let msg = lines
|
||||
.next()
|
||||
.map(|l| l.split(':').nth(1))
|
||||
.flatten()
|
||||
.and_then(|l| l.split(':').nth(1))
|
||||
.map(|s| s.trim().to_string());
|
||||
|
||||
match (msg, span) {
|
||||
|
|
|
@ -69,14 +69,14 @@ fn split_column(args: CommandArgs) -> Result<ActionStream, ShellError> {
|
|||
}
|
||||
|
||||
let mut dict = TaggedDictBuilder::new(&v.tag);
|
||||
for (&k, v) in split_result.iter().zip(gen_columns.iter()) {
|
||||
for (&k, v) in split_result.iter().zip(&gen_columns) {
|
||||
dict.insert_untagged(v.clone(), Primitive::String(k.into()));
|
||||
}
|
||||
|
||||
ReturnSuccess::value(dict.into_value())
|
||||
} else {
|
||||
let mut dict = TaggedDictBuilder::new(&v.tag);
|
||||
for (&k, v) in split_result.iter().zip(positional.iter()) {
|
||||
for (&k, v) in split_result.iter().zip(&positional) {
|
||||
dict.insert_untagged(
|
||||
v,
|
||||
UntaggedValue::Primitive(Primitive::String(k.into())),
|
||||
|
|
|
@ -125,7 +125,7 @@ fn action(
|
|||
)
|
||||
} else {
|
||||
let mut res = character.repeat(**length - s.chars().count());
|
||||
res += s.as_ref();
|
||||
res += s;
|
||||
Ok(UntaggedValue::string(res).into_value(tag))
|
||||
}
|
||||
}
|
||||
|
|
|
@ -125,7 +125,7 @@ fn action(
|
|||
)
|
||||
} else {
|
||||
let mut res = s.to_string();
|
||||
res += character.repeat(**length - s.chars().count()).as_str();
|
||||
res += &character.repeat(**length - s.chars().count());
|
||||
Ok(UntaggedValue::string(res).into_value(tag))
|
||||
}
|
||||
}
|
||||
|
|
|
@ -343,7 +343,7 @@ mod tests {
|
|||
expectation("", (6, -6)),
|
||||
];
|
||||
|
||||
for expectation in cases.iter() {
|
||||
for expectation in &cases {
|
||||
let expected = expectation.expected;
|
||||
let actual = action(&word, &expectation.options(), Tag::unknown()).unwrap();
|
||||
|
||||
|
|
|
@ -47,7 +47,7 @@ fn run_ps(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
|
||||
let result: Vec<_> = sys.processes().iter().map(|x| *x.0).collect();
|
||||
|
||||
for pid in result.into_iter() {
|
||||
for pid in result {
|
||||
if let Some(result) = sys.process(pid) {
|
||||
let mut dict = TaggedDictBuilder::new(args.name_tag());
|
||||
dict.insert_untagged("pid", UntaggedValue::int(pid as i64));
|
||||
|
|
|
@ -206,7 +206,7 @@ pub fn autoview(args: CommandArgs) -> Result<OutputStream, ShellError> {
|
|||
> term_width)
|
||||
{
|
||||
let mut entries = vec![];
|
||||
for (key, value) in row.entries.iter() {
|
||||
for (key, value) in &row.entries {
|
||||
entries.push(vec![
|
||||
nu_table::StyledString::new(
|
||||
key.to_string(),
|
||||
|
|
|
@ -61,7 +61,7 @@ pub fn test_examples(cmd: Command) -> Result<(), ShellError> {
|
|||
if let Some(expected) = &sample_pipeline.result {
|
||||
let result = evaluate_block(block, &mut ctx)?;
|
||||
|
||||
ctx.with_errors(|reasons| reasons.iter().cloned().take(1).next())
|
||||
ctx.with_errors(|reasons| reasons.iter().cloned().next())
|
||||
.map_or(Ok(()), Err)?;
|
||||
|
||||
if expected.len() != result.len() {
|
||||
|
@ -75,7 +75,7 @@ pub fn test_examples(cmd: Command) -> Result<(), ShellError> {
|
|||
);
|
||||
}
|
||||
|
||||
for (e, a) in expected.iter().zip(result.iter()) {
|
||||
for (e, a) in expected.iter().zip(&result) {
|
||||
if !values_equal(e, a) {
|
||||
let row_errored = format!("expected: {:#?}\nactual: {:#?}", e, a);
|
||||
let failed_call = format!("command: {}\n", sample_pipeline.example);
|
||||
|
@ -140,7 +140,7 @@ pub fn test(cmd: impl WholeStreamCommand + 'static) -> Result<(), ShellError> {
|
|||
);
|
||||
}
|
||||
|
||||
for (e, a) in expected.iter().zip(result.iter()) {
|
||||
for (e, a) in expected.iter().zip(&result) {
|
||||
if !values_equal(e, a) {
|
||||
let row_errored = format!("expected: {:#?}\nactual: {:#?}", e, a);
|
||||
let failed_call = format!("command: {}\n", sample_pipeline.example);
|
||||
|
@ -275,10 +275,10 @@ pub fn test_anchors(cmd: Command) -> Result<(), ShellError> {
|
|||
if sample_pipeline.result.is_some() {
|
||||
let result = evaluate_block(block, &mut ctx)?;
|
||||
|
||||
ctx.with_errors(|reasons| reasons.iter().cloned().take(1).next())
|
||||
ctx.with_errors(|reasons| reasons.iter().cloned().next())
|
||||
.map_or(Ok(()), Err)?;
|
||||
|
||||
for actual in result.iter() {
|
||||
for actual in &result {
|
||||
if !is_anchor_carried(actual, mock_path()) {
|
||||
let failed_call = format!("command: {}\n", pipeline_with_anchor);
|
||||
|
||||
|
@ -351,10 +351,10 @@ fn values_equal(expected: &Value, actual: &Value) -> bool {
|
|||
|
||||
e.entries
|
||||
.iter()
|
||||
.zip(a.entries.iter())
|
||||
.zip(&a.entries)
|
||||
.all(|((ek, ev), (ak, av))| ek == ak && values_equal(ev, av))
|
||||
}
|
||||
(Table(e), Table(a)) => e.iter().zip(a.iter()).all(|(e, a)| values_equal(e, a)),
|
||||
(Table(e), Table(a)) => e.iter().zip(a).all(|(e, a)| values_equal(e, a)),
|
||||
(e, a) => unimplemented!("{} {}", e.type_name(), a.type_name()),
|
||||
}
|
||||
}
|
||||
|
|
|
@ -38,7 +38,7 @@ impl WholeStreamCommand for Command {
|
|||
base_value = first.clone()
|
||||
}
|
||||
|
||||
let stream = rest.into_iter().map(move |i| {
|
||||
let stream = rest.into_iter().flat_map(move |i| {
|
||||
let base_value = base_value.clone();
|
||||
match i.as_string() {
|
||||
Ok(s) => ActionStream::one(Ok(ReturnSuccess::Value(Value {
|
||||
|
@ -52,9 +52,9 @@ impl WholeStreamCommand for Command {
|
|||
} => {
|
||||
if table.len() == 1 && table[0].is_table() {
|
||||
let mut values: Vec<Value> =
|
||||
table[0].table_entries().map(Clone::clone).collect();
|
||||
table[0].table_entries().cloned().collect();
|
||||
|
||||
for v in values.iter_mut() {
|
||||
for v in &mut values {
|
||||
v.tag = base_value.tag();
|
||||
}
|
||||
|
||||
|
@ -81,6 +81,6 @@ impl WholeStreamCommand for Command {
|
|||
}
|
||||
});
|
||||
|
||||
Ok((stream).flatten().into_action_stream())
|
||||
Ok(stream.into_action_stream())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -42,14 +42,14 @@ fn compute_sum_of_individual_row() -> Result<(), String> {
|
|||
("mem", 3032375296.),
|
||||
("virtual", 102579965952.),
|
||||
];
|
||||
for (column_name, expected_value) in answers_for_columns.iter() {
|
||||
for (column_name, expected_value) in answers_for_columns {
|
||||
let actual = nu!(
|
||||
cwd: "tests/fixtures/formats/",
|
||||
format!("open sample-ps-output.json | select {} | math sum | get {}", column_name, column_name)
|
||||
);
|
||||
let result =
|
||||
f64::from_str(&actual.out).map_err(|_| String::from("Failed to parse float."))?;
|
||||
assert_eq!(result, *expected_value);
|
||||
assert_eq!(result, expected_value);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
@ -63,14 +63,14 @@ fn compute_sum_of_table() -> Result<(), String> {
|
|||
("mem", 3032375296.),
|
||||
("virtual", 102579965952.),
|
||||
];
|
||||
for (column_name, expected_value) in answers_for_columns.iter() {
|
||||
for (column_name, expected_value) in answers_for_columns {
|
||||
let actual = nu!(
|
||||
cwd: "tests/fixtures/formats/",
|
||||
format!("open sample-ps-output.json | select cpu mem virtual | math sum | get {}", column_name)
|
||||
);
|
||||
let result =
|
||||
f64::from_str(&actual.out).map_err(|_| String::from("Failed to parse float."))?;
|
||||
assert_eq!(result, *expected_value);
|
||||
assert_eq!(result, expected_value);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
@ -25,7 +25,7 @@ where
|
|||
let path_executables = find_path_executables().unwrap_or_default();
|
||||
|
||||
// TODO quote these, if necessary
|
||||
commands.extend(path_executables.into_iter());
|
||||
commands.extend(path_executables);
|
||||
|
||||
let mut suggestions: Vec<_> = commands
|
||||
.into_iter()
|
||||
|
|
|
@ -37,7 +37,7 @@ impl NuCompleter {
|
|||
.and_then(|cfg| cfg.get("line_editor").cloned())
|
||||
.and_then(|le| {
|
||||
le.row_entries()
|
||||
.find(|(idx, _value)| idx.as_str() == "completion_match_method")
|
||||
.find(|&(idx, _value)| idx == "completion_match_method")
|
||||
.and_then(|(_idx, value)| value.as_string().ok())
|
||||
})
|
||||
.unwrap_or_else(String::new);
|
||||
|
|
|
@ -306,7 +306,7 @@ mod tests {
|
|||
}
|
||||
|
||||
fn get_signature(&self, name: &str) -> Option<nu_protocol::Signature> {
|
||||
self.0.iter().find(|v| v.name == name).map(Clone::clone)
|
||||
self.0.iter().find(|v| v.name == name).cloned()
|
||||
}
|
||||
|
||||
fn get_alias(&self, _name: &str) -> Option<Vec<Spanned<String>>> {
|
||||
|
|
|
@ -12,7 +12,7 @@ where
|
|||
fn complete(&self, ctx: &Context, partial: &str, matcher: &dyn Matcher) -> Vec<Suggestion> {
|
||||
if let Some(sig) = ctx.signature_registry().get(&self.cmd) {
|
||||
let mut suggestions = Vec::new();
|
||||
for (name, (named_type, _desc)) in sig.named.iter() {
|
||||
for (name, (named_type, _desc)) in &sig.named {
|
||||
suggestions.push(format!("--{}", name));
|
||||
|
||||
if let Some(c) = named_type.get_short() {
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue